Project

General

Profile

Download (32.3 KB) Statistics
| Branch: | Tag: | Revision:

magiccube / src / main / java / org / distorted / objects / TwistyObject.java @ a38fe4b2

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2020 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Magic Cube.                                                              //
5
//                                                                                               //
6
// Magic Cube is free software: you can redistribute it and/or modify                            //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Magic Cube is distributed in the hope that it will be useful,                                 //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Magic Cube.  If not, see <http://www.gnu.org/licenses/>.                           //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.objects;
21

    
22
import android.content.SharedPreferences;
23
import android.content.res.Resources;
24
import android.graphics.Bitmap;
25
import android.graphics.Canvas;
26
import android.graphics.Paint;
27

    
28
import com.google.firebase.crashlytics.FirebaseCrashlytics;
29

    
30
import org.distorted.helpers.FactoryCubit;
31
import org.distorted.helpers.FactorySticker;
32
import org.distorted.helpers.ObjectSticker;
33
import org.distorted.helpers.QuatHelper;
34
import org.distorted.library.effect.Effect;
35
import org.distorted.library.effect.MatrixEffectMove;
36
import org.distorted.library.effect.MatrixEffectQuaternion;
37
import org.distorted.library.effect.MatrixEffectScale;
38
import org.distorted.library.effect.VertexEffectQuaternion;
39
import org.distorted.library.effect.VertexEffectRotate;
40
import org.distorted.library.main.DistortedEffects;
41
import org.distorted.library.main.DistortedLibrary;
42
import org.distorted.library.main.DistortedNode;
43
import org.distorted.library.main.DistortedTexture;
44
import org.distorted.library.mesh.MeshBase;
45
import org.distorted.library.mesh.MeshFile;
46
import org.distorted.library.mesh.MeshJoined;
47
import org.distorted.library.mesh.MeshSquare;
48
import org.distorted.library.message.EffectListener;
49
import org.distorted.library.type.Dynamic1D;
50
import org.distorted.library.type.Static1D;
51
import org.distorted.library.type.Static3D;
52
import org.distorted.library.type.Static4D;
53
import org.distorted.main.BuildConfig;
54

    
55
import java.io.DataInputStream;
56
import java.io.IOException;
57
import java.io.InputStream;
58
import java.util.Random;
59

    
60
///////////////////////////////////////////////////////////////////////////////////////////////////
61

    
62
public abstract class TwistyObject extends DistortedNode
63
  {
64
  public static final int COLOR_YELLOW = 0xffffff00;
65
  public static final int COLOR_WHITE  = 0xffffffff;
66
  public static final int COLOR_BLUE   = 0xff0000ff;
67
  public static final int COLOR_GREEN  = 0xff00bb00;
68
  public static final int COLOR_RED    = 0xff990000;
69
  public static final int COLOR_ORANGE = 0xffff6200;
70
  public static final int COLOR_GREY   = 0xff727c7b;
71
  public static final int COLOR_VIOLET = 0xff7700bb;
72
  public static final int COLOR_BLACK  = 0xff000000;
73

    
74
  public static final int TEXTURE_HEIGHT = 256;
75
  static final int NUM_STICKERS_IN_ROW = 4;
76

    
77
  static final float SQ2 = (float)Math.sqrt(2);
78
  static final float SQ3 = (float)Math.sqrt(3);
79
  static final float SQ5 = (float)Math.sqrt(5);
80
  static final float SQ6 = (float)Math.sqrt(6);
81

    
82
  private static final float NODE_RATIO = 1.40f;
83
  private static final float MAX_SIZE_CHANGE = 1.35f;
84
  private static final float MIN_SIZE_CHANGE = 0.75f;
85

    
86
  private static final Static3D CENTER = new Static3D(0,0,0);
87
  private static final int POST_ROTATION_MILLISEC = 500;
88

    
89
  MeshBase[] mMeshes;
90
  final Static4D[] QUATS;
91
  final Cubit[] CUBITS;
92
  final int NUM_FACES;
93
  final int NUM_TEXTURES;
94
  final int NUM_CUBITS;
95
  final int NUM_AXIS;
96

    
97
  private static final float[] mTmp1 = new float[4];
98
  private static final float[] mTmp2 = new float[4];
99

    
100
  private final int mNumCubitFaces;
101
  private final Static3D[] mAxis;
102
  private final float[][] mCuts;
103
  private final int[] mNumCuts;
104
  private final int mNodeSize;
105
  private final float[][] mOrigPos;
106
  private final Static3D mNodeScale;
107
  private final Static4D mQuat;
108
  private final int mNumLayers, mRealSize;
109
  private final ObjectList mList;
110
  private final DistortedEffects mEffects;
111
  private final VertexEffectRotate mRotateEffect;
112
  private final Dynamic1D mRotationAngle;
113
  private final Static3D mRotationAxis;
114
  private final Static3D mObjectScale;
115
  private final int[] mQuatDebug;
116
  private final float mCameraDist;
117
  private final Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
118
  private final DistortedTexture mTexture;
119
  private final float mInitScreenRatio;
120
  private float mObjectScreenRatio;
121
  private int mNumTexRows, mNumTexCols;
122
  private int mRotRowBitmap;
123
  private int mRotAxis;
124
  private MeshBase mMesh;
125

    
126
///////////////////////////////////////////////////////////////////////////////////////////////////
127

    
128
  TwistyObject(int numLayers, int realSize, Static4D quat, DistortedTexture nodeTexture, MeshSquare nodeMesh,
129
               DistortedEffects nodeEffects, int[][] moves, ObjectList list, Resources res, int screenWidth)
130
    {
131
    super(nodeTexture,nodeEffects,nodeMesh);
132

    
133
    mNodeSize = screenWidth;
134

    
135
    resizeFBO(mNodeSize, (int)(NODE_RATIO*mNodeSize));
136

    
137
    mNumLayers = numLayers;
138
    mRealSize = realSize;
139
    mList = list;
140
    mOrigPos = getCubitPositions(mNumLayers);
141
    mAxis = getRotationAxis();
142
    mInitScreenRatio = getScreenRatio();
143
    mObjectScreenRatio = 1.0f;
144
    mNumCubitFaces = getNumCubitFaces();
145

    
146
    mCuts = getCuts(mNumLayers);
147
    mNumCuts = new int[mAxis.length];
148
    if( mCuts==null ) for(int i=0; i<mAxis.length; i++) mNumCuts[i] = 0;
149
    else              for(int i=0; i<mAxis.length; i++) mNumCuts[i] = mCuts[i].length;
150

    
151
    QUATS = getQuats();
152
    NUM_CUBITS  = mOrigPos.length;
153
    NUM_FACES = getNumFaces();
154
    NUM_TEXTURES = getNumStickerTypes(mNumLayers)*NUM_FACES;
155
    NUM_AXIS = mAxis.length;
156

    
157
    mQuatDebug = new int[NUM_CUBITS];
158

    
159
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
160
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
161

    
162
    mNodeScale= new Static3D(1,NODE_RATIO,1);
163
    mQuat = quat;
164

    
165
    mRotationAngle= new Dynamic1D();
166
    mRotationAxis = new Static3D(1,0,0);
167
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
168

    
169
    mRotationAngleStatic = new Static1D(0);
170
    mRotationAngleMiddle = new Static1D(0);
171
    mRotationAngleFinal  = new Static1D(0);
172

    
173
    float scale  = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
174
    mObjectScale = new Static3D(scale,scale,scale);
175
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
176
    MatrixEffectQuaternion quatEffect  = new MatrixEffectQuaternion(quat, CENTER);
177

    
178
    MatrixEffectScale nodeScaleEffect = new MatrixEffectScale(mNodeScale);
179
    nodeEffects.apply(nodeScaleEffect);
180

    
181
    mNumTexCols = NUM_STICKERS_IN_ROW;
182
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
183

    
184
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
185

    
186
    CUBITS = new Cubit[NUM_CUBITS];
187
    createMeshAndCubits(list,res);
188

    
189
    mTexture = new DistortedTexture();
190
    mEffects = new DistortedEffects();
191

    
192
    int num_quats = QUATS.length;
193
    for(int q=0; q<num_quats; q++)
194
      {
195
      VertexEffectQuaternion vq = new VertexEffectQuaternion(QUATS[q],CENTER);
196
      vq.setMeshAssociation(0,q);
197
      mEffects.apply(vq);
198
      }
199

    
200
    mEffects.apply(mRotateEffect);
201
    mEffects.apply(quatEffect);
202
    mEffects.apply(scaleEffect);
203

    
204
    // Now postprocessed effects (the glow when you solve an object) require component centers. In
205
    // order for the effect to be in front of the object, we need to set the center to be behind it.
206
    getMesh().setComponentCenter(0,0,0,-0.1f);
207

    
208
    attach( new DistortedNode(mTexture,mEffects,mMesh) );
209

    
210
    setupPosition(moves);
211

    
212
    float fov = list.getFOV();
213
    double halfFOV = fov * (Math.PI/360);
214
    mCameraDist = 0.5f*NODE_RATIO / (float)Math.tan(halfFOV);
215

    
216
    setProjection( fov, 0.1f);
217
    }
218

    
219
///////////////////////////////////////////////////////////////////////////////////////////////////
220

    
221
  private Static3D getPos(float[] origPos)
222
    {
223
    int len = origPos.length/3;
224
    float sumX = 0.0f;
225
    float sumY = 0.0f;
226
    float sumZ = 0.0f;
227

    
228
    for(int i=0; i<len; i++)
229
      {
230
      sumX += origPos[3*i  ];
231
      sumY += origPos[3*i+1];
232
      sumZ += origPos[3*i+2];
233
      }
234

    
235
    sumX /= len;
236
    sumY /= len;
237
    sumZ /= len;
238

    
239
    return new Static3D(sumX,sumY,sumZ);
240
    }
241

    
242
///////////////////////////////////////////////////////////////////////////////////////////////////
243

    
244
  private void createMeshAndCubits(ObjectList list, Resources res)
245
    {
246
    int sizeIndex = ObjectList.getSizeIndex(list.ordinal(),mNumLayers);
247
    int resourceID= list.getResourceIDs()[sizeIndex];
248

    
249
    if( false)//resourceID!=0 )
250
      {
251
      InputStream is = res.openRawResource(resourceID);
252
      DataInputStream dos = new DataInputStream(is);
253
      mMesh = new MeshFile(dos);
254

    
255
      try
256
        {
257
        is.close();
258
        }
259
      catch(IOException e)
260
        {
261
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
262
        }
263

    
264
      for(int i=0; i<NUM_CUBITS; i++)
265
        {
266
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
267
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
268
        }
269

    
270
      if( shouldResetTextureMaps() ) resetAllTextureMaps();
271
      }
272
    else
273
      {
274
      MeshBase[] cubitMesh = new MeshBase[NUM_CUBITS];
275

    
276
      for(int i=0; i<NUM_CUBITS; i++)
277
        {
278
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
279
        cubitMesh[i] = createCubitMesh(i,mNumLayers);
280
        Static3D pos = getPos(mOrigPos[i]);
281
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
282
        cubitMesh[i].setEffectAssociation(0, CUBITS[i].computeAssociation(), 0);
283
        }
284

    
285
      mMesh = new MeshJoined(cubitMesh);
286
      resetAllTextureMaps();
287
      }
288
    }
289

    
290
///////////////////////////////////////////////////////////////////////////////////////////////////
291

    
292
  public void setObjectRatio(float sizeChange)
293
    {
294
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
295

    
296
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
297
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
298

    
299
    float scale = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
300
    mObjectScale.set(scale,scale,scale);
301
    }
302

    
303
///////////////////////////////////////////////////////////////////////////////////////////////////
304

    
305
  public float getObjectRatio()
306
    {
307
    return mObjectScreenRatio*mInitScreenRatio;
308
    }
309

    
310
///////////////////////////////////////////////////////////////////////////////////////////////////
311

    
312
  int computeRow(float[] pos, int axisIndex)
313
    {
314
    int ret=0;
315
    int len = pos.length / 3;
316
    Static3D axis = mAxis[axisIndex];
317
    float axisX = axis.get0();
318
    float axisY = axis.get1();
319
    float axisZ = axis.get2();
320
    float casted;
321

    
322
    for(int i=0; i<len; i++)
323
      {
324
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
325
      ret |= computeSingleRow(axisIndex,casted);
326
      }
327

    
328
    return ret;
329
    }
330

    
331
///////////////////////////////////////////////////////////////////////////////////////////////////
332

    
333
  private int computeSingleRow(int axisIndex,float casted)
334
    {
335
    int num = mNumCuts[axisIndex];
336

    
337
    for(int i=0; i<num; i++)
338
      {
339
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
340
      }
341

    
342
    return (1<<num);
343
    }
344

    
345
///////////////////////////////////////////////////////////////////////////////////////////////////
346

    
347
  private boolean wasRotateApplied()
348
    {
349
    return mEffects.exists(mRotateEffect.getID());
350
    }
351

    
352
///////////////////////////////////////////////////////////////////////////////////////////////////
353

    
354
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
355
    {
356
    return (CUBITS[cubit].mRotationRow[axis] & rowBitmap) != 0;
357
    }
358

    
359
///////////////////////////////////////////////////////////////////////////////////////////////////
360
// note the minus in front of the sin() - we rotate counterclockwise
361
// when looking towards the direction where the axis increases in values.
362

    
363
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
364
    {
365
    Static3D axis = mAxis[axisIndex];
366

    
367
    while( angleInDegrees<0 ) angleInDegrees += 360;
368
    angleInDegrees %= 360;
369
    
370
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
371
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
372

    
373
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
374
    }
375

    
376
///////////////////////////////////////////////////////////////////////////////////////////////////
377

    
378
  private synchronized void setupPosition(int[][] moves)
379
    {
380
    if( moves!=null )
381
      {
382
      Static4D quat;
383
      int index, axis, rowBitmap, angle;
384
      int[] basic = getBasicAngle();
385

    
386
      for(int[] move: moves)
387
        {
388
        axis     = move[0];
389
        rowBitmap= move[1];
390
        angle    = move[2]*(360/basic[axis]);
391
        quat     = makeQuaternion(axis,angle);
392

    
393
        for(int j=0; j<NUM_CUBITS; j++)
394
          if( belongsToRotation(j,axis,rowBitmap) )
395
            {
396
            index = CUBITS[j].removeRotationNow(quat);
397
            mMesh.setEffectAssociation(j, CUBITS[j].computeAssociation(),index);
398
            }
399
        }
400
      }
401
    }
402

    
403
///////////////////////////////////////////////////////////////////////////////////////////////////
404
// normal, not bandaged, object.
405

    
406
  int computeBitmapFromRow(int rowBitmap, int axis)
407
    {
408
    return rowBitmap;
409
    }
410

    
411
///////////////////////////////////////////////////////////////////////////////////////////////////
412
// Clamp all rotated positions to one of those original ones to avoid accumulating errors.
413
// Do so only if minimal Error is appropriately low (shape-shifting puzzles - Square-1)
414

    
415
  void clampPos(float[] pos, int offset)
416
    {
417
    float currError, minError = Float.MAX_VALUE;
418
    int minErrorIndex1 = -1;
419
    int minErrorIndex2 = -1;
420

    
421
    float x = pos[offset  ];
422
    float y = pos[offset+1];
423
    float z = pos[offset+2];
424

    
425
    float xo,yo,zo;
426

    
427
    for(int i=0; i<NUM_CUBITS; i++)
428
      {
429
      int len = mOrigPos[i].length / 3;
430

    
431
      for(int j=0; j<len; j++)
432
        {
433
        xo = mOrigPos[i][3*j  ];
434
        yo = mOrigPos[i][3*j+1];
435
        zo = mOrigPos[i][3*j+2];
436

    
437
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
438

    
439
        if( currError<minError )
440
          {
441
          minError = currError;
442
          minErrorIndex1 = i;
443
          minErrorIndex2 = j;
444
          }
445
        }
446
      }
447

    
448
    if( minError< 0.1f ) // TODO: 0.1 ?
449
      {
450
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
451
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
452
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
453
      }
454
    }
455

    
456
///////////////////////////////////////////////////////////////////////////////////////////////////
457
// remember about the double cover or unit quaternions!
458

    
459
  int mulQuat(int q1, int q2)
460
    {
461
    Static4D result = QuatHelper.quatMultiply(QUATS[q1],QUATS[q2]);
462

    
463
    float rX = result.get0();
464
    float rY = result.get1();
465
    float rZ = result.get2();
466
    float rW = result.get3();
467

    
468
    final float MAX_ERROR = 0.1f;
469
    float dX,dY,dZ,dW;
470

    
471
    for(int i=0; i<QUATS.length; i++)
472
      {
473
      dX = QUATS[i].get0() - rX;
474
      dY = QUATS[i].get1() - rY;
475
      dZ = QUATS[i].get2() - rZ;
476
      dW = QUATS[i].get3() - rW;
477

    
478
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
479
          dY<MAX_ERROR && dY>-MAX_ERROR &&
480
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
481
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
482

    
483
      dX = QUATS[i].get0() + rX;
484
      dY = QUATS[i].get1() + rY;
485
      dZ = QUATS[i].get2() + rZ;
486
      dW = QUATS[i].get3() + rW;
487

    
488
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
489
          dY<MAX_ERROR && dY>-MAX_ERROR &&
490
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
491
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
492
      }
493

    
494
    return -1;
495
    }
496

    
497
///////////////////////////////////////////////////////////////////////////////////////////////////
498
// return if the Cubit, when rotated with its own mQuatScramble, would have looked any different
499
// then if it were rotated by quaternion 'quat'.
500
// No it is not so simple as the quats need to be the same - imagine a 4x4x4 cube where the two
501
// middle squares get interchanged. No visible difference!
502
//
503
// So: this is true iff the cubit
504
// a) is a corner or edge and the quaternions are the same
505
// b) is inside one of the faces and after rotations by both quats it ends up on the same face.
506

    
507
  boolean thereIsVisibleDifference(Cubit cubit, int quatIndex)
508
    {
509
    if ( cubit.mQuatIndex == quatIndex ) return false;
510

    
511
    int belongsToHowManyFaces = 0;
512
    int bitmap = (1<<(getNumLayers()-1)) + 1;
513

    
514
    for(int i = 0; i< NUM_AXIS; i++)
515
      {
516
      if( (cubit.mRotationRow[i] & bitmap) != 0 ) belongsToHowManyFaces++;
517
      }
518

    
519
    switch(belongsToHowManyFaces)
520
      {
521
      case 0 : return false;  // 'inside' cubit that does not lie on any face
522
      case 1 :                // cubit that lies inside one of the faces
523
               float[] orig   = cubit.getOrigPosition();
524
               Static4D quat1 = QUATS[quatIndex];
525
               Static4D quat2 = QUATS[cubit.mQuatIndex];
526

    
527
               Static4D cubitCenter = new Static4D( orig[0], orig[1], orig[2], 0);              // not used for bandaged objects,
528
               Static4D rotated1 = QuatHelper.rotateVectorByQuat( cubitCenter, quat1 );   // only check the first position
529
               Static4D rotated2 = QuatHelper.rotateVectorByQuat( cubitCenter, quat2 );
530

    
531
               rotated1.get(mTmp1, 0, 0, 0);
532
               rotated2.get(mTmp2, 0, 0, 0);
533

    
534
               for(int i = 0; i< NUM_AXIS; i++)
535
                 {
536
                 if( (computeRow(mTmp1,i) & computeRow(mTmp2,i) & bitmap) != 0 ) return false;
537
                 }
538
               return true;
539

    
540
      default: return true;  // edge or corner
541
      }
542
    }
543

    
544
///////////////////////////////////////////////////////////////////////////////////////////////////
545
// create StickerCoord and FaceTransform data structures
546

    
547
  void createFaceDataStructures(double[][][] verts, int[][][] indices)
548
    {
549
    int numCubitTypes = verts.length;
550
    FactoryCubit factory = FactoryCubit.getInstance();
551
    factory.clear();
552

    
553
    for(int cubit=0; cubit<numCubitTypes; cubit++)
554
      {
555
      double[][] vertices = verts[cubit];
556
      int[][] vertIndices = indices[cubit];
557
      factory.createNewFaceTransform(vertices,vertIndices);
558
      }
559

    
560
    factory.printFaceTransform();
561
    factory.printStickerCoords();
562
    }
563

    
564
///////////////////////////////////////////////////////////////////////////////////////////////////
565

    
566
  public int getCubitFaceColorIndex(int cubit, int face)
567
    {
568
    Static4D texMap = mMesh.getTextureMap(NUM_FACES*cubit + face);
569

    
570
    int x = (int)(texMap.get0()/texMap.get2());
571
    int y = (int)(texMap.get1()/texMap.get3());
572

    
573
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
574
    }
575

    
576
///////////////////////////////////////////////////////////////////////////////////////////////////
577
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
578

    
579
  public void createTexture()
580
    {
581
    Bitmap bitmap;
582

    
583
    Paint paint = new Paint();
584
    bitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
585
    Canvas canvas = new Canvas(bitmap);
586

    
587
    paint.setAntiAlias(true);
588
    paint.setTextAlign(Paint.Align.CENTER);
589
    paint.setStyle(Paint.Style.FILL);
590

    
591
    paint.setColor(COLOR_BLACK);
592
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
593

    
594
    int face = 0;
595
    FactorySticker factory = FactorySticker.getInstance();
596

    
597
    for(int row=0; row<mNumTexRows; row++)
598
      for(int col=0; col<mNumTexCols; col++)
599
        {
600
        if( face>=NUM_TEXTURES ) break;
601
        ObjectSticker sticker = retSticker(face);
602
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, getColor(face%NUM_FACES), sticker);
603
        face++;
604
        }
605

    
606
    if( !mTexture.setTexture(bitmap) )
607
      {
608
      int max = DistortedLibrary.getMaxTextureSize();
609
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
610
      crashlytics.log("failed to set texture of size "+bitmap.getWidth()+"x"+bitmap.getHeight()+" max is "+max);
611
      }
612
    }
613

    
614
///////////////////////////////////////////////////////////////////////////////////////////////////
615

    
616
  public int getNumLayers()
617
    {
618
    return mNumLayers;
619
    }
620

    
621
///////////////////////////////////////////////////////////////////////////////////////////////////
622

    
623
  public void continueRotation(float angleInDegrees)
624
    {
625
    mRotationAngleStatic.set0(angleInDegrees);
626
    }
627

    
628
///////////////////////////////////////////////////////////////////////////////////////////////////
629

    
630
  public Static4D getRotationQuat()
631
      {
632
      return mQuat;
633
      }
634

    
635
///////////////////////////////////////////////////////////////////////////////////////////////////
636

    
637
  public void recomputeScaleFactor(int scrWidth)
638
    {
639
    mNodeScale.set(scrWidth,NODE_RATIO*scrWidth,scrWidth);
640
    }
641

    
642
///////////////////////////////////////////////////////////////////////////////////////////////////
643

    
644
  public void savePreferences(SharedPreferences.Editor editor)
645
    {
646
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
647
    }
648

    
649
///////////////////////////////////////////////////////////////////////////////////////////////////
650

    
651
  public synchronized void restorePreferences(SharedPreferences preferences)
652
    {
653
    boolean error = false;
654

    
655
    for(int i=0; i<NUM_CUBITS; i++)
656
      {
657
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
658

    
659
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<QUATS.length)
660
        {
661
        CUBITS[i].modifyCurrentPosition(QUATS[mQuatDebug[i]]);
662
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
663
        }
664
      else
665
        {
666
        error = true;
667
        }
668
      }
669

    
670
    if( error )
671
      {
672
      for(int i=0; i<NUM_CUBITS; i++)
673
        {
674
        CUBITS[i].solve();
675
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
676
        }
677
      recordQuatsState("Failed to restorePreferences");
678
      }
679
    }
680

    
681
///////////////////////////////////////////////////////////////////////////////////////////////////
682

    
683
  public void recordQuatsState(String message)
684
    {
685
    StringBuilder quats = new StringBuilder();
686

    
687
    for(int j=0; j<NUM_CUBITS; j++)
688
      {
689
      quats.append(mQuatDebug[j]);
690
      quats.append(" ");
691
      }
692

    
693
    if( BuildConfig.DEBUG )
694
      {
695
      android.util.Log.e("quats" , quats.toString());
696
      android.util.Log.e("object", mList.name()+"_"+mNumLayers);
697
      }
698
    else
699
      {
700
      Exception ex = new Exception(message);
701
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
702
      crashlytics.setCustomKey("quats" , quats.toString());
703
      crashlytics.setCustomKey("object", mList.name()+"_"+mNumLayers );
704
      crashlytics.recordException(ex);
705
      }
706
    }
707

    
708
///////////////////////////////////////////////////////////////////////////////////////////////////
709

    
710
  public void releaseResources()
711
    {
712
    mTexture.markForDeletion();
713
    mMesh.markForDeletion();
714
    mEffects.markForDeletion();
715

    
716
    for(int j=0; j<NUM_CUBITS; j++)
717
      {
718
      CUBITS[j].releaseResources();
719
      }
720
    }
721

    
722
///////////////////////////////////////////////////////////////////////////////////////////////////
723

    
724
  public void apply(Effect effect, int position)
725
    {
726
    mEffects.apply(effect, position);
727
    }
728

    
729
///////////////////////////////////////////////////////////////////////////////////////////////////
730

    
731
  public void remove(long effectID)
732
    {
733
    mEffects.abortById(effectID);
734
    }
735

    
736
///////////////////////////////////////////////////////////////////////////////////////////////////
737

    
738
  public synchronized void solve()
739
    {
740
    for(int i=0; i<NUM_CUBITS; i++)
741
      {
742
      CUBITS[i].solve();
743
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
744
      }
745
    }
746

    
747
///////////////////////////////////////////////////////////////////////////////////////////////////
748

    
749
  public void resetAllTextureMaps()
750
    {
751
    final float ratioW = 1.0f/mNumTexCols;
752
    final float ratioH = 1.0f/mNumTexRows;
753
    int color, row, col;
754

    
755
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
756
      {
757
      final Static4D[] maps = new Static4D[mNumCubitFaces];
758

    
759
      for(int cubitface=0; cubitface<mNumCubitFaces; cubitface++)
760
        {
761
        color = getFaceColor(cubit,cubitface,mNumLayers);
762
        row = (mNumTexRows-1) - color/mNumTexCols;
763
        col = color%mNumTexCols;
764
        maps[cubitface] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
765
        }
766

    
767
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
768
      }
769
    }
770

    
771
///////////////////////////////////////////////////////////////////////////////////////////////////
772

    
773
  public void setTextureMap(int cubit, int face, int newColor)
774
    {
775
    final float ratioW = 1.0f/mNumTexCols;
776
    final float ratioH = 1.0f/mNumTexRows;
777
    final Static4D[] maps = new Static4D[mNumCubitFaces];
778
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
779
    int col = newColor%mNumTexCols;
780

    
781
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
782
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
783
    }
784

    
785
///////////////////////////////////////////////////////////////////////////////////////////////////
786

    
787
  public synchronized void beginNewRotation(int axis, int row )
788
    {
789
    if( axis<0 || axis>=NUM_AXIS )
790
      {
791
      android.util.Log.e("object", "invalid rotation axis: "+axis);
792
      return;
793
      }
794
    if( row<0 || row>=mNumLayers )
795
      {
796
      android.util.Log.e("object", "invalid rotation row: "+row);
797
      return;
798
      }
799

    
800
    mRotAxis     = axis;
801
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
802
    mRotationAngleStatic.set0(0.0f);
803
    mRotationAxis.set( mAxis[axis] );
804
    mRotationAngle.add(mRotationAngleStatic);
805
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
806
    }
807

    
808
///////////////////////////////////////////////////////////////////////////////////////////////////
809

    
810
  public synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
811
    {
812
    if( wasRotateApplied() )
813
      {
814
      mRotAxis     = axis;
815
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
816

    
817
      mRotationAngleStatic.set0(0.0f);
818
      mRotationAxis.set( mAxis[axis] );
819
      mRotationAngle.setDuration(durationMillis);
820
      mRotationAngle.resetToBeginning();
821
      mRotationAngle.add(new Static1D(0));
822
      mRotationAngle.add(new Static1D(angle));
823
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
824
      mRotateEffect.notifyWhenFinished(listener);
825

    
826
      return mRotateEffect.getID();
827
      }
828

    
829
    return 0;
830
    }
831

    
832
///////////////////////////////////////////////////////////////////////////////////////////////////
833

    
834
  public long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
835
    {
836
    if( wasRotateApplied() )
837
      {
838
      float angle = getAngle();
839
      mRotationAngleStatic.set0(angle);
840
      mRotationAngleFinal.set0(nearestAngleInDegrees);
841
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
842

    
843
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
844
      mRotationAngle.resetToBeginning();
845
      mRotationAngle.removeAll();
846
      mRotationAngle.add(mRotationAngleStatic);
847
      mRotationAngle.add(mRotationAngleMiddle);
848
      mRotationAngle.add(mRotationAngleFinal);
849
      mRotateEffect.notifyWhenFinished(listener);
850

    
851
      return mRotateEffect.getID();
852
      }
853

    
854
    return 0;
855
    }
856

    
857
///////////////////////////////////////////////////////////////////////////////////////////////////
858

    
859
  private float getAngle()
860
    {
861
    int pointNum = mRotationAngle.getNumPoints();
862

    
863
    if( pointNum>=1 )
864
      {
865
      return mRotationAngle.getPoint(pointNum-1).get0();
866
      }
867
    else
868
      {
869
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
870
      crashlytics.log("points in RotationAngle: "+pointNum);
871
      return 0;
872
      }
873
    }
874

    
875
///////////////////////////////////////////////////////////////////////////////////////////////////
876

    
877
  public synchronized void removeRotationNow()
878
    {
879
    float angle = getAngle();
880
    double nearestAngleInRadians = angle*Math.PI/180;
881
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
882
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
883
    float axisX = mAxis[mRotAxis].get0();
884
    float axisY = mAxis[mRotAxis].get1();
885
    float axisZ = mAxis[mRotAxis].get2();
886
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
887

    
888
    mRotationAngle.removeAll();
889
    mRotationAngleStatic.set0(0);
890

    
891
    for(int i=0; i<NUM_CUBITS; i++)
892
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
893
        {
894
        int index = CUBITS[i].removeRotationNow(quat);
895
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
896
        }
897
    }
898

    
899
///////////////////////////////////////////////////////////////////////////////////////////////////
900

    
901
  public void initializeObject(int[][] moves)
902
    {
903
    solve();
904
    setupPosition(moves);
905
    }
906

    
907
///////////////////////////////////////////////////////////////////////////////////////////////////
908

    
909
  public int getCubit(float[] point3D)
910
    {
911
    float dist, minDist = Float.MAX_VALUE;
912
    int currentBest=-1;
913
    float multiplier = returnMultiplier();
914

    
915
    point3D[0] *= multiplier;
916
    point3D[1] *= multiplier;
917
    point3D[2] *= multiplier;
918

    
919
    for(int i=0; i<NUM_CUBITS; i++)
920
      {
921
      dist = CUBITS[i].getDistSquared(point3D);
922
      if( dist<minDist )
923
        {
924
        minDist = dist;
925
        currentBest = i;
926
        }
927
      }
928

    
929
    return currentBest;
930
    }
931

    
932
///////////////////////////////////////////////////////////////////////////////////////////////////
933

    
934
  public int computeNearestAngle(int axis, float angle, float speed)
935
    {
936
    int[] basicArray = getBasicAngle();
937
    int basicAngle   = basicArray[axis>=basicArray.length ? 0 : axis];
938
    int nearestAngle = 360/basicAngle;
939

    
940
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
941
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
942

    
943
    if( tmp!=0 ) return nearestAngle*tmp;
944

    
945
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
946
    }
947

    
948
///////////////////////////////////////////////////////////////////////////////////////////////////
949

    
950
  public float getCameraDist()
951
    {
952
    return mCameraDist;
953
    }
954

    
955
///////////////////////////////////////////////////////////////////////////////////////////////////
956

    
957
  public int getNodeSize()
958
    {
959
    return mNodeSize;
960
    }
961

    
962
///////////////////////////////////////////////////////////////////////////////////////////////////
963

    
964
  public ObjectList getObjectList()
965
    {
966
    return mList;
967
    }
968

    
969
///////////////////////////////////////////////////////////////////////////////////////////////////
970

    
971
  abstract float getScreenRatio();
972
  abstract float[][] getCubitPositions(int numLayers);
973
  abstract Static4D[] getQuats();
974
  abstract int getNumFaces();
975
  abstract int getNumStickerTypes(int numLayers);
976
  abstract int getNumCubitFaces();
977
  abstract MeshBase createCubitMesh(int cubit, int numLayers);
978
  abstract ObjectSticker retSticker(int face);
979
  abstract int getColor(int face);
980
  abstract int getFaceColor(int cubit, int cubitface, int numLayers);
981
  abstract float returnMultiplier();
982
  abstract float[][] getCuts(int numLayers);
983
  abstract boolean shouldResetTextureMaps();
984

    
985
  public abstract Static3D[] getRotationAxis();
986
  public abstract boolean isSolved();
987
  public abstract int[] getBasicAngle();
988
  public abstract void randomizeNewScramble(int[][] scramble, Random rnd, int curScramble, int totScrambles);
989
  public abstract int getObjectName(int numLayers);
990
  public abstract int getInventor(int numLayers);
991
  public abstract int getComplexity(int numLayers);
992
  }
(33-33/41)