Project

General

Profile

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

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

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 final float[] mTmp1 = new float[4];
95
  private static final float[] mTmp2 = new float[4];
96

    
97
  private final int mNumCubitFaces;
98
  private final Static3D[] mAxis;
99
  private final float[][] mCuts;
100
  private final int[] mNumCuts;
101
  private final int mNodeSize;
102
  private final float[][] mOrigPos;
103
  private final Static3D mNodeScale;
104
  private final Static4D mQuat;
105
  private final int mNumLayers, mRealSize;
106
  private final ObjectList mList;
107
  private final DistortedEffects mEffects;
108
  private final VertexEffectRotate mRotateEffect;
109
  private final Dynamic1D mRotationAngle;
110
  private final Static3D mRotationAxis;
111
  private final Static3D mObjectScale;
112
  private final int[] mQuatDebug;
113
  private final float mCameraDist;
114
  private final Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
115
  private final DistortedTexture mTexture;
116
  private final float mInitScreenRatio;
117
  private float mObjectScreenRatio;
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
    mObjectScreenRatio = 1.0f;
141
    mNumCubitFaces = getNumCubitFaces();
142

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

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

    
154
    mQuatDebug = new int[NUM_CUBITS];
155

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
207
    setupPosition(moves);
208

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

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

    
216
///////////////////////////////////////////////////////////////////////////////////////////////////
217

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

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

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

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

    
239
///////////////////////////////////////////////////////////////////////////////////////////////////
240

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

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

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

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

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

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

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

    
287
///////////////////////////////////////////////////////////////////////////////////////////////////
288

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

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

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

    
300
///////////////////////////////////////////////////////////////////////////////////////////////////
301

    
302
  public float getObjectRatio()
303
    {
304
    return mObjectScreenRatio*mInitScreenRatio;
305
    }
306

    
307
///////////////////////////////////////////////////////////////////////////////////////////////////
308

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

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

    
325
    return ret;
326
    }
327

    
328
///////////////////////////////////////////////////////////////////////////////////////////////////
329

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

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

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

    
342
///////////////////////////////////////////////////////////////////////////////////////////////////
343

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

    
349
///////////////////////////////////////////////////////////////////////////////////////////////////
350

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

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

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

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

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

    
373
///////////////////////////////////////////////////////////////////////////////////////////////////
374

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

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

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

    
400
///////////////////////////////////////////////////////////////////////////////////////////////////
401

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

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

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

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

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

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

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

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

    
434
    float xo,yo,zo;
435

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

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

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

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

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

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

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

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

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

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

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

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

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

    
503
    return -1;
504
    }
505

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
591
    int tex = 0;
592

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

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

    
609
///////////////////////////////////////////////////////////////////////////////////////////////////
610

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

    
616
///////////////////////////////////////////////////////////////////////////////////////////////////
617

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

    
623
///////////////////////////////////////////////////////////////////////////////////////////////////
624

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

    
630
///////////////////////////////////////////////////////////////////////////////////////////////////
631

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

    
637
///////////////////////////////////////////////////////////////////////////////////////////////////
638

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

    
644
///////////////////////////////////////////////////////////////////////////////////////////////////
645

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

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

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

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

    
676
///////////////////////////////////////////////////////////////////////////////////////////////////
677

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

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

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

    
703
///////////////////////////////////////////////////////////////////////////////////////////////////
704

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

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

    
717
///////////////////////////////////////////////////////////////////////////////////////////////////
718

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

    
724
///////////////////////////////////////////////////////////////////////////////////////////////////
725

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

    
731
///////////////////////////////////////////////////////////////////////////////////////////////////
732

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

    
742
///////////////////////////////////////////////////////////////////////////////////////////////////
743

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

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

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

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

    
766
///////////////////////////////////////////////////////////////////////////////////////////////////
767

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

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

    
780
///////////////////////////////////////////////////////////////////////////////////////////////////
781

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

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

    
803
///////////////////////////////////////////////////////////////////////////////////////////////////
804

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

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

    
821
      return mRotateEffect.getID();
822
      }
823

    
824
    return 0;
825
    }
826

    
827
///////////////////////////////////////////////////////////////////////////////////////////////////
828

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

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

    
846
      return mRotateEffect.getID();
847
      }
848

    
849
    return 0;
850
    }
851

    
852
///////////////////////////////////////////////////////////////////////////////////////////////////
853

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

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

    
870
///////////////////////////////////////////////////////////////////////////////////////////////////
871

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

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

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

    
894
///////////////////////////////////////////////////////////////////////////////////////////////////
895

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

    
902
///////////////////////////////////////////////////////////////////////////////////////////////////
903

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

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

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

    
924
    return currentBest;
925
    }
926

    
927
///////////////////////////////////////////////////////////////////////////////////////////////////
928

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

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

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

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

    
943
///////////////////////////////////////////////////////////////////////////////////////////////////
944

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

    
950
///////////////////////////////////////////////////////////////////////////////////////////////////
951

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

    
957
///////////////////////////////////////////////////////////////////////////////////////////////////
958

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

    
964
///////////////////////////////////////////////////////////////////////////////////////////////////
965

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

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