Project

General

Profile

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

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

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.QuatHelper;
32
import org.distorted.library.effect.Effect;
33
import org.distorted.library.effect.MatrixEffectMove;
34
import org.distorted.library.effect.MatrixEffectQuaternion;
35
import org.distorted.library.effect.MatrixEffectScale;
36
import org.distorted.library.effect.VertexEffectQuaternion;
37
import org.distorted.library.effect.VertexEffectRotate;
38
import org.distorted.library.main.DistortedEffects;
39
import org.distorted.library.main.DistortedLibrary;
40
import org.distorted.library.main.DistortedNode;
41
import org.distorted.library.main.DistortedTexture;
42
import org.distorted.library.mesh.MeshBase;
43
import org.distorted.library.mesh.MeshFile;
44
import org.distorted.library.mesh.MeshJoined;
45
import org.distorted.library.mesh.MeshSquare;
46
import org.distorted.library.message.EffectListener;
47
import org.distorted.library.type.Dynamic1D;
48
import org.distorted.library.type.Static1D;
49
import org.distorted.library.type.Static3D;
50
import org.distorted.library.type.Static4D;
51
import org.distorted.main.BuildConfig;
52

    
53
import java.io.DataInputStream;
54
import java.io.IOException;
55
import java.io.InputStream;
56
import java.util.Random;
57

    
58
///////////////////////////////////////////////////////////////////////////////////////////////////
59

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

    
72
  public static final int TEXTURE_HEIGHT = 256;
73
  static final int NUM_STICKERS_IN_ROW = 4;
74

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

    
80
  private static final float NODE_RATIO = 1.40f;
81
  private static final float MAX_SIZE_CHANGE = 1.35f;
82
  private static final float MIN_SIZE_CHANGE = 0.75f;
83

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

    
87
  final Static4D[] QUATS;
88
  final Cubit[] CUBITS;
89
  final int NUM_FACES;
90
  final int NUM_TEXTURES;
91
  final int NUM_CUBITS;
92
  final int NUM_AXIS;
93

    
94
  private static float mInitScreenRatio;
95
  private static float mObjectScreenRatio = 1.0f;
96
  private static final float[] mTmp1 = new float[4];
97
  private static final float[] mTmp2 = new float[4];
98

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

    
123
///////////////////////////////////////////////////////////////////////////////////////////////////
124

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

    
130
    mNodeSize = screenWidth;
131

    
132
    resizeFBO(mNodeSize, (int)(NODE_RATIO*mNodeSize));
133

    
134
    mNumLayers = numLayers;
135
    mRealSize = realSize;
136
    mList = list;
137
    mOrigPos = getCubitPositions(mNumLayers);
138
    mAxis = getRotationAxis();
139
    mInitScreenRatio = getScreenRatio();
140
    mNumCubitFaces = getNumCubitFaces();
141

    
142
    mCuts = getCuts(mNumLayers);
143
    mNumCuts = new int[mAxis.length];
144
    if( mCuts==null ) for(int i=0; i<mAxis.length; i++) mNumCuts[i] = 0;
145
    else              for(int i=0; i<mAxis.length; i++) mNumCuts[i] = mCuts[i].length;
146

    
147
    QUATS = getQuats();
148
    NUM_CUBITS  = mOrigPos.length;
149
    NUM_FACES = getNumFaces();
150
    NUM_TEXTURES = getNumStickerTypes(mNumLayers)*NUM_FACES;
151
    NUM_AXIS = mAxis.length;
152

    
153
    mQuatDebug = new int[NUM_CUBITS];
154

    
155
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
156
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
157

    
158
    mNodeScale= new Static3D(1,NODE_RATIO,1);
159
    mQuat = quat;
160

    
161
    mRotationAngle= new Dynamic1D();
162
    mRotationAxis = new Static3D(1,0,0);
163
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
164

    
165
    mRotationAngleStatic = new Static1D(0);
166
    mRotationAngleMiddle = new Static1D(0);
167
    mRotationAngleFinal  = new Static1D(0);
168

    
169
    float scale  = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
170
    mObjectScale = new Static3D(scale,scale,scale);
171
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
172
    MatrixEffectQuaternion quatEffect  = new MatrixEffectQuaternion(quat, CENTER);
173

    
174
    MatrixEffectScale nodeScaleEffect = new MatrixEffectScale(mNodeScale);
175
    nodeEffects.apply(nodeScaleEffect);
176

    
177
    mNumTexCols = NUM_STICKERS_IN_ROW;
178
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
179

    
180
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
181

    
182
    CUBITS = new Cubit[NUM_CUBITS];
183
    createMeshAndCubits(list,res);
184

    
185
    mTexture = new DistortedTexture();
186
    mEffects = new DistortedEffects();
187

    
188
    int num_quats = QUATS.length;
189
    for(int q=0; q<num_quats; q++)
190
      {
191
      VertexEffectQuaternion vq = new VertexEffectQuaternion(QUATS[q],CENTER);
192
      vq.setMeshAssociation(0,q);
193
      mEffects.apply(vq);
194
      }
195

    
196
    mEffects.apply(mRotateEffect);
197
    mEffects.apply(quatEffect);
198
    mEffects.apply(scaleEffect);
199

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

    
204
    attach( new DistortedNode(mTexture,mEffects,mMesh) );
205

    
206
    setupPosition(moves);
207

    
208
    float fov = list.getFOV();
209
    double halfFOV = fov * (Math.PI/360);
210
    mCameraDist = 0.5f*NODE_RATIO / (float)Math.tan(halfFOV);
211

    
212
    setProjection( fov, 0.1f);
213
    }
214

    
215
///////////////////////////////////////////////////////////////////////////////////////////////////
216

    
217
  private Static3D getPos(float[] origPos)
218
    {
219
    int len = origPos.length/3;
220
    float sumX = 0.0f;
221
    float sumY = 0.0f;
222
    float sumZ = 0.0f;
223

    
224
    for(int i=0; i<len; i++)
225
      {
226
      sumX += origPos[3*i  ];
227
      sumY += origPos[3*i+1];
228
      sumZ += origPos[3*i+2];
229
      }
230

    
231
    sumX /= len;
232
    sumY /= len;
233
    sumZ /= len;
234

    
235
    return new Static3D(sumX,sumY,sumZ);
236
    }
237

    
238
///////////////////////////////////////////////////////////////////////////////////////////////////
239

    
240
  private void createMeshAndCubits(ObjectList list, Resources res)
241
    {
242
    int sizeIndex = ObjectList.getSizeIndex(list.ordinal(),mNumLayers);
243
    int resourceID= list.getResourceIDs()[sizeIndex];
244

    
245
    if( resourceID!=0 )
246
      {
247
      InputStream is = res.openRawResource(resourceID);
248
      DataInputStream dos = new DataInputStream(is);
249
      mMesh = new MeshFile(dos);
250

    
251
      try
252
        {
253
        is.close();
254
        }
255
      catch(IOException e)
256
        {
257
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
258
        }
259

    
260
      for(int i=0; i<NUM_CUBITS; i++)
261
        {
262
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
263
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
264
        }
265

    
266
      if( shouldResetTextureMaps() ) resetAllTextureMaps();
267
      }
268
    else
269
      {
270
      MeshBase[] cubitMesh = new MeshBase[NUM_CUBITS];
271

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

    
281
      mMesh = new MeshJoined(cubitMesh);
282
      resetAllTextureMaps();
283
      }
284
    }
285

    
286
///////////////////////////////////////////////////////////////////////////////////////////////////
287

    
288
  public void setObjectRatio(float sizeChange)
289
    {
290
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
291

    
292
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
293
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
294

    
295
    float scale = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
296
    mObjectScale.set(scale,scale,scale);
297
    }
298

    
299
///////////////////////////////////////////////////////////////////////////////////////////////////
300

    
301
  static float getObjectRatio()
302
    {
303
    return mObjectScreenRatio*mInitScreenRatio;
304
    }
305

    
306
///////////////////////////////////////////////////////////////////////////////////////////////////
307

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

    
318
    for(int i=0; i<len; i++)
319
      {
320
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
321
      ret |= computeSingleRow(axisIndex,casted);
322
      }
323

    
324
    return ret;
325
    }
326

    
327
///////////////////////////////////////////////////////////////////////////////////////////////////
328

    
329
  private int computeSingleRow(int axisIndex,float casted)
330
    {
331
    int num = mNumCuts[axisIndex];
332

    
333
    for(int i=0; i<num; i++)
334
      {
335
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
336
      }
337

    
338
    return (1<<num);
339
    }
340

    
341
///////////////////////////////////////////////////////////////////////////////////////////////////
342

    
343
  private boolean wasRotateApplied()
344
    {
345
    return mEffects.exists(mRotateEffect.getID());
346
    }
347

    
348
///////////////////////////////////////////////////////////////////////////////////////////////////
349

    
350
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
351
    {
352
    return (CUBITS[cubit].mRotationRow[axis] & rowBitmap) != 0;
353
    }
354

    
355
///////////////////////////////////////////////////////////////////////////////////////////////////
356
// note the minus in front of the sin() - we rotate counterclockwise
357
// when looking towards the direction where the axis increases in values.
358

    
359
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
360
    {
361
    Static3D axis = mAxis[axisIndex];
362

    
363
    while( angleInDegrees<0 ) angleInDegrees += 360;
364
    angleInDegrees %= 360;
365
    
366
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
367
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
368

    
369
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
370
    }
371

    
372
///////////////////////////////////////////////////////////////////////////////////////////////////
373

    
374
  private synchronized void setupPosition(int[][] moves)
375
    {
376
    if( moves!=null )
377
      {
378
      Static4D quat;
379
      int index, axis, rowBitmap, angle;
380
      int[] basic = getBasicAngle();
381

    
382
      for(int[] move: moves)
383
        {
384
        axis     = move[0];
385
        rowBitmap= move[1];
386
        angle    = move[2]*(360/basic[axis]);
387
        quat     = makeQuaternion(axis,angle);
388

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

    
399
///////////////////////////////////////////////////////////////////////////////////////////////////
400

    
401
  int getCubitFaceColorIndex(int cubit, int face)
402
    {
403
    Static4D texMap = mMesh.getTextureMap(NUM_FACES*cubit + face);
404

    
405
    int x = (int)(texMap.get0()/texMap.get2());
406
    int y = (int)(texMap.get1()/texMap.get3());
407

    
408
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
409
    }
410

    
411
///////////////////////////////////////////////////////////////////////////////////////////////////
412
// normal, not bandaged, object.
413

    
414
  int computeBitmapFromRow(int rowBitmap, int axis)
415
    {
416
    return rowBitmap;
417
    }
418

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

    
423
  void clampPos(float[] pos, int offset)
424
    {
425
    float currError, minError = Float.MAX_VALUE;
426
    int minErrorIndex1 = -1;
427
    int minErrorIndex2 = -1;
428

    
429
    float x = pos[offset  ];
430
    float y = pos[offset+1];
431
    float z = pos[offset+2];
432

    
433
    float xo,yo,zo;
434

    
435
    for(int i=0; i<NUM_CUBITS; i++)
436
      {
437
      int len = mOrigPos[i].length / 3;
438

    
439
      for(int j=0; j<len; j++)
440
        {
441
        xo = mOrigPos[i][3*j  ];
442
        yo = mOrigPos[i][3*j+1];
443
        zo = mOrigPos[i][3*j+2];
444

    
445
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
446

    
447
        if( currError<minError )
448
          {
449
          minError = currError;
450
          minErrorIndex1 = i;
451
          minErrorIndex2 = j;
452
          }
453
        }
454
      }
455

    
456
    if( minError< 0.1f ) // TODO: 0.1 ?
457
      {
458
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
459
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
460
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
461
      }
462
    }
463

    
464
///////////////////////////////////////////////////////////////////////////////////////////////////
465
// remember about the double cover or unit quaternions!
466

    
467
  int mulQuat(int q1, int q2)
468
    {
469
    Static4D result = QuatHelper.quatMultiply(QUATS[q1],QUATS[q2]);
470

    
471
    float rX = result.get0();
472
    float rY = result.get1();
473
    float rZ = result.get2();
474
    float rW = result.get3();
475

    
476
    final float MAX_ERROR = 0.1f;
477
    float dX,dY,dZ,dW;
478

    
479
    for(int i=0; i<QUATS.length; i++)
480
      {
481
      dX = QUATS[i].get0() - rX;
482
      dY = QUATS[i].get1() - rY;
483
      dZ = QUATS[i].get2() - rZ;
484
      dW = QUATS[i].get3() - rW;
485

    
486
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
487
          dY<MAX_ERROR && dY>-MAX_ERROR &&
488
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
489
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
490

    
491
      dX = QUATS[i].get0() + rX;
492
      dY = QUATS[i].get1() + rY;
493
      dZ = QUATS[i].get2() + rZ;
494
      dW = QUATS[i].get3() + rW;
495

    
496
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
497
          dY<MAX_ERROR && dY>-MAX_ERROR &&
498
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
499
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
500
      }
501

    
502
    return -1;
503
    }
504

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

    
515
  boolean thereIsVisibleDifference(Cubit cubit, int quatIndex)
516
    {
517
    if ( cubit.mQuatIndex == quatIndex ) return false;
518

    
519
    int belongsToHowManyFaces = 0;
520
    int bitmap = (1<<(getNumLayers()-1)) + 1;
521

    
522
    for(int i = 0; i< NUM_AXIS; i++)
523
      {
524
      if( (cubit.mRotationRow[i] & bitmap) != 0 ) belongsToHowManyFaces++;
525
      }
526

    
527
    switch(belongsToHowManyFaces)
528
      {
529
      case 0 : return false;  // 'inside' cubit that does not lie on any face
530
      case 1 :                // cubit that lies inside one of the faces
531
               float[] orig   = cubit.getOrigPosition();
532
               Static4D quat1 = QUATS[quatIndex];
533
               Static4D quat2 = QUATS[cubit.mQuatIndex];
534

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

    
539
               rotated1.get(mTmp1, 0, 0, 0);
540
               rotated2.get(mTmp2, 0, 0, 0);
541

    
542
               for(int i = 0; i< NUM_AXIS; i++)
543
                 {
544
                 if( (computeRow(mTmp1,i) & computeRow(mTmp2,i) & bitmap) != 0 ) return false;
545
                 }
546
               return true;
547

    
548
      default: return true;  // edge or corner
549
      }
550
    }
551

    
552
///////////////////////////////////////////////////////////////////////////////////////////////////
553
// create StickerCoord and FaceTransform data structures
554

    
555
  void createFaceDataStructures(double[][][] verts, int[][][] indices)
556
    {
557
    int numCubitTypes = verts.length;
558
    FactoryCubit factory = FactoryCubit.getInstance();
559
    factory.clear();
560

    
561
    for(int cubit=0; cubit<numCubitTypes; cubit++)
562
      {
563
      double[][] vertices = verts[cubit];
564
      int[][] vertIndices = indices[cubit];
565
      factory.createNewFaceTransform(vertices,vertIndices);
566
      }
567

    
568
    factory.printFaceTransform();
569
    factory.printStickerCoords();
570
    }
571

    
572
///////////////////////////////////////////////////////////////////////////////////////////////////
573
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
574

    
575
  public void createTexture()
576
    {
577
    Bitmap bitmap;
578

    
579
    Paint paint = new Paint();
580
    bitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
581
    Canvas canvas = new Canvas(bitmap);
582

    
583
    paint.setAntiAlias(true);
584
    paint.setTextAlign(Paint.Align.CENTER);
585
    paint.setStyle(Paint.Style.FILL);
586

    
587
    paint.setColor(COLOR_BLACK);
588
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
589

    
590
    int tex = 0;
591

    
592
    for(int row=0; row<mNumTexRows; row++)
593
      for(int col=0; col<mNumTexCols; col++)
594
        {
595
        if( tex>=NUM_TEXTURES ) break;
596
        createFaceTexture(canvas, paint, tex, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT);
597
        tex++;
598
        }
599

    
600
    if( !mTexture.setTexture(bitmap) )
601
      {
602
      int max = DistortedLibrary.getMaxTextureSize();
603
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
604
      crashlytics.log("failed to set texture of size "+bitmap.getWidth()+"x"+bitmap.getHeight()+" max is "+max);
605
      }
606
    }
607

    
608
///////////////////////////////////////////////////////////////////////////////////////////////////
609

    
610
  public int getNumLayers()
611
    {
612
    return mNumLayers;
613
    }
614

    
615
///////////////////////////////////////////////////////////////////////////////////////////////////
616

    
617
  public void continueRotation(float angleInDegrees)
618
    {
619
    mRotationAngleStatic.set0(angleInDegrees);
620
    }
621

    
622
///////////////////////////////////////////////////////////////////////////////////////////////////
623

    
624
  public Static4D getRotationQuat()
625
      {
626
      return mQuat;
627
      }
628

    
629
///////////////////////////////////////////////////////////////////////////////////////////////////
630

    
631
  public void recomputeScaleFactor(int scrWidth)
632
    {
633
    mNodeScale.set(scrWidth,NODE_RATIO*scrWidth,scrWidth);
634
    }
635

    
636
///////////////////////////////////////////////////////////////////////////////////////////////////
637

    
638
  public void savePreferences(SharedPreferences.Editor editor)
639
    {
640
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
641
    }
642

    
643
///////////////////////////////////////////////////////////////////////////////////////////////////
644

    
645
  public synchronized void restorePreferences(SharedPreferences preferences)
646
    {
647
    boolean error = false;
648

    
649
    for(int i=0; i<NUM_CUBITS; i++)
650
      {
651
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
652

    
653
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<QUATS.length)
654
        {
655
        CUBITS[i].modifyCurrentPosition(QUATS[mQuatDebug[i]]);
656
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
657
        }
658
      else
659
        {
660
        error = true;
661
        }
662
      }
663

    
664
    if( error )
665
      {
666
      for(int i=0; i<NUM_CUBITS; i++)
667
        {
668
        CUBITS[i].solve();
669
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
670
        }
671
      recordQuatsState("Failed to restorePreferences");
672
      }
673
    }
674

    
675
///////////////////////////////////////////////////////////////////////////////////////////////////
676

    
677
  public void recordQuatsState(String message)
678
    {
679
    StringBuilder quats = new StringBuilder();
680

    
681
    for(int j=0; j<NUM_CUBITS; j++)
682
      {
683
      quats.append(mQuatDebug[j]);
684
      quats.append(" ");
685
      }
686

    
687
    if( BuildConfig.DEBUG )
688
      {
689
      android.util.Log.e("quats" , quats.toString());
690
      android.util.Log.e("object", mList.name()+"_"+mNumLayers);
691
      }
692
    else
693
      {
694
      Exception ex = new Exception(message);
695
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
696
      crashlytics.setCustomKey("quats" , quats.toString());
697
      crashlytics.setCustomKey("object", mList.name()+"_"+mNumLayers );
698
      crashlytics.recordException(ex);
699
      }
700
    }
701

    
702
///////////////////////////////////////////////////////////////////////////////////////////////////
703

    
704
  public void releaseResources()
705
    {
706
    mTexture.markForDeletion();
707
    mMesh.markForDeletion();
708
    mEffects.markForDeletion();
709

    
710
    for(int j=0; j<NUM_CUBITS; j++)
711
      {
712
      CUBITS[j].releaseResources();
713
      }
714
    }
715

    
716
///////////////////////////////////////////////////////////////////////////////////////////////////
717

    
718
  public void apply(Effect effect, int position)
719
    {
720
    mEffects.apply(effect, position);
721
    }
722

    
723
///////////////////////////////////////////////////////////////////////////////////////////////////
724

    
725
  public void remove(long effectID)
726
    {
727
    mEffects.abortById(effectID);
728
    }
729

    
730
///////////////////////////////////////////////////////////////////////////////////////////////////
731

    
732
  public synchronized void solve()
733
    {
734
    for(int i=0; i<NUM_CUBITS; i++)
735
      {
736
      CUBITS[i].solve();
737
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
738
      }
739
    }
740

    
741
///////////////////////////////////////////////////////////////////////////////////////////////////
742

    
743
  public void resetAllTextureMaps()
744
    {
745
    final float ratioW = 1.0f/mNumTexCols;
746
    final float ratioH = 1.0f/mNumTexRows;
747
    int color, row, col;
748

    
749
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
750
      {
751
      final Static4D[] maps = new Static4D[mNumCubitFaces];
752

    
753
      for(int cubitface=0; cubitface<mNumCubitFaces; cubitface++)
754
        {
755
        color = getFaceColor(cubit,cubitface,mNumLayers);
756
        row = (mNumTexRows-1) - color/mNumTexCols;
757
        col = color%mNumTexCols;
758
        maps[cubitface] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
759
        }
760

    
761
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
762
      }
763
    }
764

    
765
///////////////////////////////////////////////////////////////////////////////////////////////////
766

    
767
  public void setTextureMap(int cubit, int face, int newColor)
768
    {
769
    final float ratioW = 1.0f/mNumTexCols;
770
    final float ratioH = 1.0f/mNumTexRows;
771
    final Static4D[] maps = new Static4D[mNumCubitFaces];
772
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
773
    int col = newColor%mNumTexCols;
774

    
775
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
776
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
777
    }
778

    
779
///////////////////////////////////////////////////////////////////////////////////////////////////
780

    
781
  public synchronized void beginNewRotation(int axis, int row )
782
    {
783
    if( axis<0 || axis>=NUM_AXIS )
784
      {
785
      android.util.Log.e("object", "invalid rotation axis: "+axis);
786
      return;
787
      }
788
    if( row<0 || row>=mNumLayers )
789
      {
790
      android.util.Log.e("object", "invalid rotation row: "+row);
791
      return;
792
      }
793

    
794
    mRotAxis     = axis;
795
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
796
    mRotationAngleStatic.set0(0.0f);
797
    mRotationAxis.set( mAxis[axis] );
798
    mRotationAngle.add(mRotationAngleStatic);
799
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
800
    }
801

    
802
///////////////////////////////////////////////////////////////////////////////////////////////////
803

    
804
  public synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
805
    {
806
    if( wasRotateApplied() )
807
      {
808
      mRotAxis     = axis;
809
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
810

    
811
      mRotationAngleStatic.set0(0.0f);
812
      mRotationAxis.set( mAxis[axis] );
813
      mRotationAngle.setDuration(durationMillis);
814
      mRotationAngle.resetToBeginning();
815
      mRotationAngle.add(new Static1D(0));
816
      mRotationAngle.add(new Static1D(angle));
817
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
818
      mRotateEffect.notifyWhenFinished(listener);
819

    
820
      return mRotateEffect.getID();
821
      }
822

    
823
    return 0;
824
    }
825

    
826
///////////////////////////////////////////////////////////////////////////////////////////////////
827

    
828
  public long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
829
    {
830
    if( wasRotateApplied() )
831
      {
832
      float angle = getAngle();
833
      mRotationAngleStatic.set0(angle);
834
      mRotationAngleFinal.set0(nearestAngleInDegrees);
835
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
836

    
837
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
838
      mRotationAngle.resetToBeginning();
839
      mRotationAngle.removeAll();
840
      mRotationAngle.add(mRotationAngleStatic);
841
      mRotationAngle.add(mRotationAngleMiddle);
842
      mRotationAngle.add(mRotationAngleFinal);
843
      mRotateEffect.notifyWhenFinished(listener);
844

    
845
      return mRotateEffect.getID();
846
      }
847

    
848
    return 0;
849
    }
850

    
851
///////////////////////////////////////////////////////////////////////////////////////////////////
852

    
853
  private float getAngle()
854
    {
855
    int pointNum = mRotationAngle.getNumPoints();
856

    
857
    if( pointNum>=1 )
858
      {
859
      return mRotationAngle.getPoint(pointNum-1).get0();
860
      }
861
    else
862
      {
863
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
864
      crashlytics.log("points in RotationAngle: "+pointNum);
865
      return 0;
866
      }
867
    }
868

    
869
///////////////////////////////////////////////////////////////////////////////////////////////////
870

    
871
  public synchronized void removeRotationNow()
872
    {
873
    float angle = getAngle();
874
    double nearestAngleInRadians = angle*Math.PI/180;
875
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
876
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
877
    float axisX = mAxis[mRotAxis].get0();
878
    float axisY = mAxis[mRotAxis].get1();
879
    float axisZ = mAxis[mRotAxis].get2();
880
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
881

    
882
    mRotationAngle.removeAll();
883
    mRotationAngleStatic.set0(0);
884

    
885
    for(int i=0; i<NUM_CUBITS; i++)
886
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
887
        {
888
        int index = CUBITS[i].removeRotationNow(quat);
889
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
890
        }
891
    }
892

    
893
///////////////////////////////////////////////////////////////////////////////////////////////////
894

    
895
  public void initializeObject(int[][] moves)
896
    {
897
    solve();
898
    setupPosition(moves);
899
    }
900

    
901
///////////////////////////////////////////////////////////////////////////////////////////////////
902

    
903
  public int getCubit(float[] point3D)
904
    {
905
    float dist, minDist = Float.MAX_VALUE;
906
    int currentBest=-1;
907
    float multiplier = returnMultiplier();
908

    
909
    point3D[0] *= multiplier;
910
    point3D[1] *= multiplier;
911
    point3D[2] *= multiplier;
912

    
913
    for(int i=0; i<NUM_CUBITS; i++)
914
      {
915
      dist = CUBITS[i].getDistSquared(point3D);
916
      if( dist<minDist )
917
        {
918
        minDist = dist;
919
        currentBest = i;
920
        }
921
      }
922

    
923
    return currentBest;
924
    }
925

    
926
///////////////////////////////////////////////////////////////////////////////////////////////////
927

    
928
  public int computeNearestAngle(int axis, float angle, float speed)
929
    {
930
    int[] basicArray = getBasicAngle();
931
    int basicAngle   = basicArray[axis>=basicArray.length ? 0 : axis];
932
    int nearestAngle = 360/basicAngle;
933

    
934
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
935
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
936

    
937
    if( tmp!=0 ) return nearestAngle*tmp;
938

    
939
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
940
    }
941

    
942
///////////////////////////////////////////////////////////////////////////////////////////////////
943

    
944
  public float getCameraDist()
945
    {
946
    return mCameraDist;
947
    }
948

    
949
///////////////////////////////////////////////////////////////////////////////////////////////////
950

    
951
  public int getNodeSize()
952
    {
953
    return mNodeSize;
954
    }
955

    
956
///////////////////////////////////////////////////////////////////////////////////////////////////
957

    
958
  public ObjectList getObjectList()
959
    {
960
    return mList;
961
    }
962

    
963
///////////////////////////////////////////////////////////////////////////////////////////////////
964

    
965
  abstract float getScreenRatio();
966
  abstract float[][] getCubitPositions(int numLayers);
967
  abstract Static4D[] getQuats();
968
  abstract int getNumFaces();
969
  abstract int getNumStickerTypes(int numLayers);
970
  abstract int getNumCubitFaces();
971
  abstract MeshBase createCubitMesh(int cubit, int numLayers);
972
  abstract void createFaceTexture(Canvas canvas, Paint paint, int face, int left, int top);
973
  abstract int getFaceColor(int cubit, int cubitface, int numLayers);
974
  abstract float returnMultiplier();
975
  abstract float[][] getCuts(int numLayers);
976
  abstract boolean shouldResetTextureMaps();
977

    
978
  public abstract Static3D[] getRotationAxis();
979
  public abstract boolean isSolved();
980
  public abstract int[] getBasicAngle();
981
  public abstract String retObjectString();
982
  public abstract void randomizeNewScramble(int[][] scramble, Random rnd, int curScramble, int totScrambles);
983
  public abstract int getObjectName(int numLayers);
984
  public abstract int getInventor(int numLayers);
985
  public abstract int getComplexity(int numLayers);
986
  }
(31-31/39)