Project

General

Profile

Download (44.6 KB) Statistics
| Branch: | Revision:

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ 1bb09f88

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

    
51
import org.distorted.objectlib.BuildConfig;
52
import org.distorted.objectlib.helpers.FactoryCubit;
53
import org.distorted.objectlib.helpers.FactorySticker;
54
import org.distorted.objectlib.helpers.ObjectShape;
55
import org.distorted.objectlib.helpers.ObjectSticker;
56
import org.distorted.objectlib.helpers.ScrambleState;
57

    
58
import java.io.DataInputStream;
59
import java.io.IOException;
60
import java.io.InputStream;
61
import java.util.Random;
62

    
63
import static org.distorted.objectlib.main.Movement.MOVEMENT_TETRAHEDRON;
64
import static org.distorted.objectlib.main.Movement.MOVEMENT_HEXAHEDRON;
65
import static org.distorted.objectlib.main.Movement.MOVEMENT_OCTAHEDRON;
66
import static org.distorted.objectlib.main.Movement.MOVEMENT_DODECAHEDRON;
67
import static org.distorted.objectlib.main.Movement.MOVEMENT_SHAPECHANGE;
68

    
69
///////////////////////////////////////////////////////////////////////////////////////////////////
70

    
71
public abstract class TwistyObject extends DistortedNode
72
  {
73
  public static final int COLOR_YELLOW = 0xffffff00;
74
  public static final int COLOR_WHITE  = 0xffffffff;
75
  public static final int COLOR_BLUE   = 0xff0000ff;
76
  public static final int COLOR_GREEN  = 0xff00bb00;
77
  public static final int COLOR_RED    = 0xff990000;
78
  public static final int COLOR_ORANGE = 0xffff6200;
79
  public static final int COLOR_GREY   = 0xff727c7b;
80
  public static final int COLOR_VIOLET = 0xff7700bb;
81
  public static final int COLOR_BLACK  = 0xff000000;
82

    
83
  public static final int TEXTURE_HEIGHT = 256;
84
  static final int NUM_STICKERS_IN_ROW = 4;
85

    
86
  public static final float SQ2 = (float)Math.sqrt(2);
87
  public static final float SQ3 = (float)Math.sqrt(3);
88
  public static final float SQ5 = (float)Math.sqrt(5);
89
  public static final float SQ6 = (float)Math.sqrt(6);
90

    
91
  private static final float MAX_SIZE_CHANGE = 1.35f;
92
  private static final float MIN_SIZE_CHANGE = 0.75f;
93

    
94
  private static final Static3D CENTER = new Static3D(0,0,0);
95
  private static final int POST_ROTATION_MILLISEC = 500;
96

    
97
  protected final int NUM_FACE_COLORS;
98
  protected final int NUM_TEXTURES;
99
  protected final Cubit[] CUBITS;
100

    
101
  MeshBase[] mMeshes;
102
  final Static4D[] OBJECT_QUATS;
103
  final int NUM_CUBITS;
104
  final int NUM_AXIS;
105
  final int NUM_QUATS;
106

    
107
  private final int mNumCubitFaces;
108
  private final Static3D[] mAxis;
109
  private final float[][] mCuts;
110
  private final int[] mNumCuts;
111
  private final int mNodeW, mNodeH;
112
  private final float[][] mOrigPos;
113
  private final Static3D mNodeScale;
114
  private final Static4D mQuat;
115
  private final int[] mNumLayers;
116
  private final float mSize;
117
  private final DistortedEffects mEffects;
118
  private final VertexEffectRotate mRotateEffect;
119
  private final Dynamic1D mRotationAngle;
120
  private final Static3D mRotationAxis;
121
  private final Static3D mObjectScale;
122
  private final int[] mQuatDebug;
123
  private final float mCameraDist;
124
  private final Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
125
  private final DistortedTexture mTexture;
126
  private final float mInitScreenRatio;
127
  private final int mSolvedFunctionIndex;
128
  private final boolean mIsBandaged;
129
  private float mObjectScreenRatio;
130
  private int[][] mSolvedQuats;
131
  private int[][] mQuatMult;
132
  private int[] mTmpQuats;
133
  private int mNumTexRows, mNumTexCols;
134
  private int mRotRowBitmap;
135
  private int mCurrentRotAxis;
136
  private MeshBase mMesh;
137
  private final TwistyObjectScrambler mScrambler;
138
  private Movement mMovement;
139
  private boolean[][] mLayerRotatable;
140
  private int[][][] mEnabled;
141

    
142
  //////////////////// SOLVED1 ////////////////////////
143

    
144
  private int[] mFaceMap;
145
  private int[][] mScramble;
146
  private int[] mColors;
147

    
148
///////////////////////////////////////////////////////////////////////////////////////////////////
149

    
150
  TwistyObject(int[] numLayers, float size, Static4D quat, Static3D move, DistortedTexture nodeTexture,
151
               MeshSquare nodeMesh, DistortedEffects nodeEffects, Resources res, int surfaceW, int surfaceH)
152
    {
153
    super(nodeTexture,nodeEffects,nodeMesh);
154

    
155
    mNodeW = surfaceW;
156
    mNodeH = surfaceH;
157

    
158
    resizeFBO(mNodeW,mNodeH);
159

    
160
    mNumLayers = numLayers;
161
    mSize = size;
162
    mOrigPos = getCubitPositions(mNumLayers);
163
    mAxis = getRotationAxis();
164
    mInitScreenRatio = getScreenRatio();
165
    mNumCubitFaces = getNumCubitFaces();
166
    mSolvedFunctionIndex = getSolvedFunctionIndex();
167

    
168
    mCuts = getCuts(mNumLayers);
169
    mNumCuts = new int[mAxis.length];
170
    for(int i=0; i<mAxis.length; i++)
171
      {
172
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
173
      }
174

    
175
    OBJECT_QUATS = getQuats();
176
    NUM_CUBITS  = mOrigPos.length;
177
    NUM_FACE_COLORS = getNumFaceColors();
178
    NUM_TEXTURES = getNumStickerTypes(mNumLayers)*NUM_FACE_COLORS;
179
    NUM_AXIS = mAxis.length;
180
    NUM_QUATS = OBJECT_QUATS.length;
181

    
182
    int scramblingType = getScrambleType();
183
    ScrambleState[] states = getScrambleStates();
184
    mScrambler = new TwistyObjectScrambler(scramblingType,NUM_AXIS,numLayers,states);
185

    
186
    boolean bandaged=false;
187

    
188
    for(int c=0; c<NUM_CUBITS; c++)
189
      {
190
      if( mOrigPos[c].length>3 )
191
        {
192
        bandaged=true;
193
        break;
194
        }
195
      }
196

    
197
    mIsBandaged = bandaged;
198

    
199
    mQuatDebug = new int[NUM_CUBITS];
200

    
201
    mNodeScale= new Static3D(surfaceW,surfaceH,surfaceW);
202
    mQuat = quat;
203

    
204
    mRotationAngle= new Dynamic1D();
205
    mRotationAxis = new Static3D(1,0,0);
206
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
207

    
208
    mRotationAngleStatic = new Static1D(0);
209
    mRotationAngleMiddle = new Static1D(0);
210
    mRotationAngleFinal  = new Static1D(0);
211

    
212
    mObjectScale = new Static3D(1,1,1);
213
    setObjectRatioNow(1.0f);
214

    
215
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
216
    MatrixEffectQuaternion quatEffect  = new MatrixEffectQuaternion(quat, CENTER);
217
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
218

    
219
    MatrixEffectScale nodeScaleEffect = new MatrixEffectScale(mNodeScale);
220
    nodeEffects.apply(nodeScaleEffect);
221

    
222
    mNumTexCols = NUM_STICKERS_IN_ROW;
223
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
224

    
225
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
226

    
227
    CUBITS = new Cubit[NUM_CUBITS];
228
    createMeshAndCubits(res);
229
    createDataStructuresForSolved(numLayers);
230

    
231
    mTexture = new DistortedTexture();
232
    mEffects = new DistortedEffects();
233

    
234
    createTexture();
235

    
236
    for(int q=0; q<NUM_QUATS; q++)
237
      {
238
      VertexEffectQuaternion vq = new VertexEffectQuaternion(OBJECT_QUATS[q],CENTER);
239
      vq.setMeshAssociation(0,q);
240
      mEffects.apply(vq);
241
      }
242

    
243
    mEffects.apply(mRotateEffect);
244
    mEffects.apply(quatEffect);
245
    mEffects.apply(scaleEffect);
246
    mEffects.apply(moveEffect);
247

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

    
252
    attach( new DistortedNode(mTexture,mEffects,mMesh) );
253

    
254
    float fov = getFOV();
255
    double halfFOV = fov * (Math.PI/360);
256
    mCameraDist = (0.5f*mNodeH) / ((float)Math.tan(halfFOV)*mNodeW);
257

    
258
    setProjection( fov, 0.1f);
259
    }
260

    
261
///////////////////////////////////////////////////////////////////////////////////////////////////
262

    
263
  private Static3D getPos(float[] origPos)
264
    {
265
    int len = origPos.length/3;
266
    float sumX = 0.0f;
267
    float sumY = 0.0f;
268
    float sumZ = 0.0f;
269

    
270
    for(int i=0; i<len; i++)
271
      {
272
      sumX += origPos[3*i  ];
273
      sumY += origPos[3*i+1];
274
      sumZ += origPos[3*i+2];
275
      }
276

    
277
    sumX /= len;
278
    sumY /= len;
279
    sumZ /= len;
280

    
281
    return new Static3D(sumX,sumY,sumZ);
282
    }
283

    
284
///////////////////////////////////////////////////////////////////////////////////////////////////
285

    
286
  private void createMeshAndCubits(Resources res)
287
    {
288
    int resourceID= getResource(mNumLayers);
289

    
290
    if( resourceID!=0 && !ObjectControl.isInCreateMesh() )
291
      {
292
      InputStream is = res.openRawResource(resourceID);
293
      DataInputStream dos = new DataInputStream(is);
294
      mMesh = new MeshFile(dos);
295

    
296
      try
297
        {
298
        is.close();
299
        }
300
      catch(IOException e)
301
        {
302
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
303
        }
304

    
305
      for(int i=0; i<NUM_CUBITS; i++)
306
        {
307
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
308
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
309
        }
310

    
311
      if( shouldResetTextureMaps() ) resetAllTextureMaps();
312
      }
313
    else
314
      {
315
      MeshBase[] cubitMesh = new MeshBase[NUM_CUBITS];
316

    
317
      for(int i=0; i<NUM_CUBITS; i++)
318
        {
319
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
320
        cubitMesh[i] = createCubitMesh(i,mNumLayers);
321
        Static3D pos = getPos(mOrigPos[i]);
322
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
323
        cubitMesh[i].setEffectAssociation(0, CUBITS[i].computeAssociation(), 0);
324
        }
325

    
326
      mMesh = new MeshJoined(cubitMesh);
327
      resetAllTextureMaps();
328
      }
329
    }
330

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

    
333
  private MeshBase createCubitMesh(int cubit, int[] numLayers)
334
    {
335
    int variant = getCubitVariant(cubit,numLayers);
336

    
337
    if( mMeshes==null )
338
      {
339
      FactoryCubit factory = FactoryCubit.getInstance();
340
      factory.clear();
341
      mMeshes = new MeshBase[getNumCubitVariants(numLayers)];
342
      }
343

    
344
    if( mMeshes[variant]==null )
345
      {
346
      ObjectShape shape = getObjectShape(cubit,numLayers);
347
      FactoryCubit factory = FactoryCubit.getInstance();
348
      factory.createNewFaceTransform(shape);
349
      mMeshes[variant] = factory.createRoundedSolid(shape);
350
      }
351

    
352
    MeshBase mesh = mMeshes[variant].copy(true);
353
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( getQuat(cubit,numLayers), new Static3D(0,0,0) );
354
    mesh.apply(quat,0xffffffff,0);
355

    
356
    return mesh;
357
    }
358

    
359
///////////////////////////////////////////////////////////////////////////////////////////////////
360

    
361
  private void createDataStructuresForSolved(int[] numLayers)
362
    {
363
    mTmpQuats = new int[NUM_QUATS];
364
    mSolvedQuats = new int[NUM_CUBITS][];
365

    
366
    for(int c=0; c<NUM_CUBITS; c++)
367
      {
368
      mSolvedQuats[c] = getSolvedQuats(c,numLayers);
369
      }
370
    }
371

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

    
374
  private int getMultQuat(int index1, int index2)
375
    {
376
    if( mQuatMult==null )
377
      {
378
      mQuatMult = new int[NUM_QUATS][NUM_QUATS];
379

    
380
      for(int i=0; i<NUM_QUATS; i++)
381
        for(int j=0; j<NUM_QUATS; j++) mQuatMult[i][j] = -1;
382
      }
383

    
384
    if( mQuatMult[index1][index2]==-1 )
385
      {
386
      mQuatMult[index1][index2] = mulQuat(index1,index2);
387
      }
388

    
389
    return mQuatMult[index1][index2];
390
    }
391

    
392
///////////////////////////////////////////////////////////////////////////////////////////////////
393
// This is used to build internal data structures for the generic 'isSolved()'
394
//
395
// if this is an internal cubit (all faces black): return -1
396
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
397
// Color index, i.e. the index into the 'FACE_COLORS' table.
398
// else (edge or corner cubit, more than one non-black face): return -2.
399

    
400
  protected int retCubitSolvedStatus(int cubit, int[] numLayers)
401
    {
402
    int numNonBlack=0, nonBlackIndex=-1, color;
403

    
404
    for(int face=0; face<mNumCubitFaces; face++)
405
      {
406
      color = getFaceColor(cubit,face,numLayers);
407

    
408
      if( color<NUM_TEXTURES )
409
        {
410
        numNonBlack++;
411
        nonBlackIndex = color%NUM_FACE_COLORS;
412
        }
413
      }
414

    
415
    if( numNonBlack==0 ) return -1;
416
    if( numNonBlack>=2 ) return -2;
417

    
418
    return nonBlackIndex;
419
    }
420

    
421
///////////////////////////////////////////////////////////////////////////////////////////////////
422

    
423
  protected boolean shouldResetTextureMaps()
424
    {
425
    return false;
426
    }
427

    
428
///////////////////////////////////////////////////////////////////////////////////////////////////
429

    
430
  protected int[] buildSolvedQuats(Static3D faceAx, Static4D[] quats)
431
    {
432
    final float MAXD = 0.0001f;
433
    float x = faceAx.get0();
434
    float y = faceAx.get1();
435
    float z = faceAx.get2();
436
    float a,dx,dy,dz,qx,qy,qz;
437
    Static4D quat;
438

    
439
    int len = quats.length;
440
    int place = 0;
441

    
442
    for(int q=1; q<len; q++)
443
      {
444
      quat = quats[q];
445
      qx = quat.get0();
446
      qy = quat.get1();
447
      qz = quat.get2();
448

    
449
           if( x!=0.0f ) { a = qx/x; }
450
      else if( y!=0.0f ) { a = qy/y; }
451
      else               { a = qz/z; }
452

    
453
      dx = a*x-qx;
454
      dy = a*y-qy;
455
      dz = a*z-qz;
456

    
457
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
458
        {
459
        mTmpQuats[place++] = q;
460
        }
461
      }
462

    
463
    if( place!=0 )
464
      {
465
      int[] ret = new int[place];
466
      System.arraycopy(mTmpQuats,0,ret,0,place);
467
      return ret;
468
      }
469

    
470
    return null;
471
    }
472

    
473
///////////////////////////////////////////////////////////////////////////////////////////////////
474

    
475
  private boolean isSolved0()
476
    {
477
    int len, q1,q = CUBITS[0].mQuatIndex;
478
    int[] solved;
479
    boolean skip;
480

    
481
    for(int c=1; c<NUM_CUBITS; c++)
482
      {
483
      q1 = CUBITS[c].mQuatIndex;
484

    
485
      if( q1==q ) continue;
486

    
487
      skip = false;
488
      solved = mSolvedQuats[c];
489
      len = solved==null ? 0:solved.length;
490

    
491
      for(int i=0; i<len; i++)
492
        {
493
        if( q1==getMultQuat(q,solved[i]) )
494
          {
495
          skip = true;
496
          break;
497
          }
498
        }
499

    
500
      if( !skip ) return false;
501
      }
502

    
503
    return true;
504
    }
505

    
506
///////////////////////////////////////////////////////////////////////////////////////////////////
507

    
508
  private int computeScramble(int quatNum, int centerNum)
509
    {
510
    float MAXDIFF = 0.01f;
511
    float[] center= mOrigPos[centerNum];
512
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
513
    Static4D result = QuatHelper.rotateVectorByQuat(sc,OBJECT_QUATS[quatNum]);
514

    
515
    float x = result.get0();
516
    float y = result.get1();
517
    float z = result.get2();
518

    
519
    for(int c=0; c<NUM_CUBITS; c++)
520
      {
521
      float[] cent = mOrigPos[c];
522

    
523
      float qx = cent[0] - x;
524
      float qy = cent[1] - y;
525
      float qz = cent[2] - z;
526

    
527
      if( qx>-MAXDIFF && qx<MAXDIFF &&
528
          qy>-MAXDIFF && qy<MAXDIFF &&
529
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
530
      }
531

    
532
    return -1;
533
    }
534

    
535
///////////////////////////////////////////////////////////////////////////////////////////////////
536
// Dino4 uses this. It is solved if and only if groups of cubits
537
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
538
// or
539
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
540
// are all the same color.
541

    
542
  private boolean isSolved1()
543
    {
544
    if( mScramble==null )
545
      {
546
      mScramble = new int[NUM_QUATS][NUM_CUBITS];
547
      mColors   = new int[NUM_CUBITS];
548

    
549
      for(int q=0; q<NUM_QUATS; q++)
550
        for(int c=0; c<NUM_CUBITS; c++) mScramble[q][c] = computeScramble(q,c);
551
      }
552

    
553
    if( mFaceMap==null )
554
      {
555
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
556
      }
557

    
558
    for(int c=0; c<NUM_CUBITS; c++)
559
      {
560
      int index = mScramble[CUBITS[c].mQuatIndex][c];
561
      mColors[index] = mFaceMap[c];
562
      }
563

    
564
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
565
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
566
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
567

    
568
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
569
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
570
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
571

    
572
    return false;
573
    }
574

    
575
///////////////////////////////////////////////////////////////////////////////////////////////////
576
// Dino6 uses this. It is solved if and only if:
577
//
578
// All four 'X' cubits (i.e. those whose longest edge goes along the X axis) are rotated
579
// by the same quaternion qX, similarly all four 'Y' cubits by the same qY and all four 'Z'
580
// by the same qZ, and then either:
581
//
582
// a) qX = qY = qZ
583
// b) qY = qX*Q2 and qZ = qX*Q8  (i.e. swap of WHITE and YELLOW faces)
584
// c) qX = qY*Q2 and qZ = qY*Q10 (i.e. swap of BLUE and GREEN faces)
585
// d) qX = qZ*Q8 and qY = qZ*Q10 (i.e. swap of RED and BROWN faces)
586
//
587
// BUT: cases b), c) and d) are really the same - it's all just a mirror image of the original.
588
//
589
// X cubits: 0, 2, 8, 10
590
// Y cubits: 1, 3, 9, 11
591
// Z cubits: 4, 5, 6, 7
592

    
593
  private boolean isSolved2()
594
    {
595
    int qX = CUBITS[0].mQuatIndex;
596
    int qY = CUBITS[1].mQuatIndex;
597
    int qZ = CUBITS[4].mQuatIndex;
598

    
599
    if( CUBITS[2].mQuatIndex != qX || CUBITS[8].mQuatIndex != qX || CUBITS[10].mQuatIndex != qX ||
600
        CUBITS[3].mQuatIndex != qY || CUBITS[9].mQuatIndex != qY || CUBITS[11].mQuatIndex != qY ||
601
        CUBITS[5].mQuatIndex != qZ || CUBITS[6].mQuatIndex != qZ || CUBITS[ 7].mQuatIndex != qZ  )
602
      {
603
      return false;
604
      }
605

    
606
    return ( qX==qY && qX==qZ ) || ( qY==mulQuat(qX,2) && qZ==mulQuat(qX,8) );
607
    }
608

    
609
///////////////////////////////////////////////////////////////////////////////////////////////////
610
// Square-2 is solved iff
611
// a) all of its cubits are rotated with the same quat
612
// b) its two 'middle' cubits are rotated with the same quat, the 6 'front' and 6 'back'
613
// edges and corners with this quat multiplied by QUATS[18] (i.e. those are upside down)
614
// and all the 12 left and right edges and corners also with the same quat multiplied by
615
// QUATS[12] - i.e. also upside down.
616

    
617
  private boolean isSolved3()
618
    {
619
    int index = CUBITS[0].mQuatIndex;
620

    
621
    if( CUBITS[1].mQuatIndex!=index ) return false;
622

    
623
    boolean solved = true;
624

    
625
    for(int i=2; i<NUM_CUBITS; i++)
626
      {
627
      if( CUBITS[i].mQuatIndex!=index )
628
        {
629
        solved = false;
630
        break;
631
        }
632
      }
633

    
634
    if( solved ) return true;
635

    
636
    int indexX = mulQuat(index,12);  // QUATS[12] = 180deg (1,0,0)
637
    int indexZ = mulQuat(index,18);  // QUATS[18] = 180deg (0,0,1)
638

    
639
    for(int i= 2; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
640
    for(int i= 3; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
641
    for(int i=18; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
642
    for(int i=19; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
643

    
644
    return true;
645
    }
646

    
647
///////////////////////////////////////////////////////////////////////////////////////////////////
648

    
649
  int computeRow(float[] pos, int axisIndex)
650
    {
651
    int ret=0;
652
    int len = pos.length / 3;
653
    Static3D axis = mAxis[axisIndex];
654
    float axisX = axis.get0();
655
    float axisY = axis.get1();
656
    float axisZ = axis.get2();
657
    float casted;
658

    
659
    for(int i=0; i<len; i++)
660
      {
661
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
662
      ret |= computeSingleRow(axisIndex,casted);
663
      }
664

    
665
    return ret;
666
    }
667

    
668
///////////////////////////////////////////////////////////////////////////////////////////////////
669

    
670
  private int computeSingleRow(int axisIndex,float casted)
671
    {
672
    int num = mNumCuts[axisIndex];
673

    
674
    for(int i=0; i<num; i++)
675
      {
676
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
677
      }
678

    
679
    return (1<<num);
680
    }
681

    
682
///////////////////////////////////////////////////////////////////////////////////////////////////
683

    
684
  private boolean wasRotateApplied()
685
    {
686
    return mEffects.exists(mRotateEffect.getID());
687
    }
688

    
689
///////////////////////////////////////////////////////////////////////////////////////////////////
690

    
691
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
692
    {
693
    return (CUBITS[cubit].getRotRow(axis) & rowBitmap) != 0;
694
    }
695

    
696
///////////////////////////////////////////////////////////////////////////////////////////////////
697
// note the minus in front of the sin() - we rotate counterclockwise
698
// when looking towards the direction where the axis increases in values.
699

    
700
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
701
    {
702
    Static3D axis = mAxis[axisIndex];
703

    
704
    while( angleInDegrees<0 ) angleInDegrees += 360;
705
    angleInDegrees %= 360;
706
    
707
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
708
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
709

    
710
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
711
    }
712

    
713
///////////////////////////////////////////////////////////////////////////////////////////////////
714

    
715
  private synchronized void setupPosition(int[][] moves)
716
    {
717
    if( moves!=null )
718
      {
719
      Static4D quat;
720
      int index, axis, rowBitmap, angle;
721
      int[] basic = getBasicAngle();
722

    
723
      for(int[] move: moves)
724
        {
725
        axis     = move[0];
726
        rowBitmap= move[1];
727
        angle    = move[2]*(360/basic[axis]);
728
        quat     = makeQuaternion(axis,angle);
729

    
730
        for(int j=0; j<NUM_CUBITS; j++)
731
          if( belongsToRotation(j,axis,rowBitmap) )
732
            {
733
            index = CUBITS[j].removeRotationNow(quat);
734
            mMesh.setEffectAssociation(j, CUBITS[j].computeAssociation(),index);
735
            }
736
        }
737
      }
738
    }
739

    
740
///////////////////////////////////////////////////////////////////////////////////////////////////
741

    
742
  public int getScrambleType()
743
    {
744
    return 0;
745
    }
746

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

    
749
  int computeBitmapFromRow(int rowBitmap, int axis)
750
    {
751
    if( mIsBandaged )
752
      {
753
      int bitmap, initBitmap=0;
754

    
755
      while( initBitmap!=rowBitmap )
756
        {
757
        initBitmap = rowBitmap;
758

    
759
        for(int cubit=0; cubit<NUM_CUBITS; cubit++)
760
          {
761
          bitmap = CUBITS[cubit].getRotRow(axis);
762
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
763
          }
764
        }
765
      }
766

    
767
    return rowBitmap;
768
    }
769

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

    
774
  void clampPos(float[] pos, int offset)
775
    {
776
    float currError, minError = Float.MAX_VALUE;
777
    int minErrorIndex1 = -1;
778
    int minErrorIndex2 = -1;
779

    
780
    float x = pos[offset  ];
781
    float y = pos[offset+1];
782
    float z = pos[offset+2];
783

    
784
    float xo,yo,zo;
785

    
786
    for(int i=0; i<NUM_CUBITS; i++)
787
      {
788
      int len = mOrigPos[i].length / 3;
789

    
790
      for(int j=0; j<len; j++)
791
        {
792
        xo = mOrigPos[i][3*j  ];
793
        yo = mOrigPos[i][3*j+1];
794
        zo = mOrigPos[i][3*j+2];
795

    
796
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
797

    
798
        if( currError<minError )
799
          {
800
          minError = currError;
801
          minErrorIndex1 = i;
802
          minErrorIndex2 = j;
803
          }
804
        }
805
      }
806

    
807
    if( minError< 0.1f ) // TODO: 0.1 ?
808
      {
809
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
810
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
811
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
812
      }
813
    }
814

    
815
///////////////////////////////////////////////////////////////////////////////////////////////////
816
// remember about the double cover or unit quaternions!
817

    
818
  int mulQuat(int q1, int q2)
819
    {
820
    Static4D result = QuatHelper.quatMultiply(OBJECT_QUATS[q1],OBJECT_QUATS[q2]);
821

    
822
    float rX = result.get0();
823
    float rY = result.get1();
824
    float rZ = result.get2();
825
    float rW = result.get3();
826

    
827
    final float MAX_ERROR = 0.1f;
828
    float dX,dY,dZ,dW;
829

    
830
    for(int i=0; i<NUM_QUATS; i++)
831
      {
832
      dX = OBJECT_QUATS[i].get0() - rX;
833
      dY = OBJECT_QUATS[i].get1() - rY;
834
      dZ = OBJECT_QUATS[i].get2() - rZ;
835
      dW = OBJECT_QUATS[i].get3() - rW;
836

    
837
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
838
          dY<MAX_ERROR && dY>-MAX_ERROR &&
839
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
840
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
841

    
842
      dX = OBJECT_QUATS[i].get0() + rX;
843
      dY = OBJECT_QUATS[i].get1() + rY;
844
      dZ = OBJECT_QUATS[i].get2() + rZ;
845
      dW = OBJECT_QUATS[i].get3() + rW;
846

    
847
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
848
          dY<MAX_ERROR && dY>-MAX_ERROR &&
849
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
850
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
851
      }
852

    
853
    return -1;
854
    }
855

    
856
///////////////////////////////////////////////////////////////////////////////////////////////////
857

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

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

    
874
///////////////////////////////////////////////////////////////////////////////////////////////////
875

    
876
  private void recordQuatsState(String message)
877
    {
878
    StringBuilder quats = new StringBuilder();
879

    
880
    for(int j=0; j<NUM_CUBITS; j++)
881
      {
882
      quats.append(mQuatDebug[j]);
883
      quats.append(" ");
884
      }
885

    
886
    String name = intGetObjectType(mNumLayers).name();
887

    
888
    if( BuildConfig.DEBUG )
889
      {
890
      android.util.Log.e("quats" , quats.toString());
891
      android.util.Log.e("object", name);
892
      }
893
    else
894
      {
895
      Exception ex = new Exception(message);
896
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
897
      crashlytics.setCustomKey("quats" , quats.toString());
898
      crashlytics.setCustomKey("object", name);
899
      crashlytics.recordException(ex);
900
      }
901
    }
902

    
903
///////////////////////////////////////////////////////////////////////////////////////////////////
904

    
905
  void initializeObject(int[][] moves)
906
    {
907
    solve();
908
    setupPosition(moves);
909
    }
910

    
911
///////////////////////////////////////////////////////////////////////////////////////////////////
912

    
913
  synchronized void removeRotationNow()
914
    {
915
    float angle = getAngle();
916
    double nearestAngleInRadians = angle*Math.PI/180;
917
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
918
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
919
    float axisX = mAxis[mCurrentRotAxis].get0();
920
    float axisY = mAxis[mCurrentRotAxis].get1();
921
    float axisZ = mAxis[mCurrentRotAxis].get2();
922
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
923

    
924
    mRotationAngle.removeAll();
925
    mRotationAngleStatic.set0(0);
926

    
927
    for(int i=0; i<NUM_CUBITS; i++)
928
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
929
        {
930
        int index = CUBITS[i].removeRotationNow(quat);
931
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
932
        }
933
    }
934

    
935
///////////////////////////////////////////////////////////////////////////////////////////////////
936

    
937
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
938
    {
939
    if( wasRotateApplied() )
940
      {
941
      float angle = getAngle();
942
      mRotationAngleStatic.set0(angle);
943
      mRotationAngleFinal.set0(nearestAngleInDegrees);
944
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
945

    
946
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
947
      mRotationAngle.resetToBeginning();
948
      mRotationAngle.removeAll();
949
      mRotationAngle.add(mRotationAngleStatic);
950
      mRotationAngle.add(mRotationAngleMiddle);
951
      mRotationAngle.add(mRotationAngleFinal);
952
      mRotateEffect.notifyWhenFinished(listener);
953

    
954
      return mRotateEffect.getID();
955
      }
956

    
957
    return 0;
958
    }
959

    
960
///////////////////////////////////////////////////////////////////////////////////////////////////
961

    
962
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
963
    {
964
    if( wasRotateApplied() )
965
      {
966
      mCurrentRotAxis = axis;
967
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
968

    
969
      mRotationAngleStatic.set0(0.0f);
970
      mRotationAxis.set( mAxis[axis] );
971
      mRotationAngle.setDuration(durationMillis);
972
      mRotationAngle.resetToBeginning();
973
      mRotationAngle.add(new Static1D(0));
974
      mRotationAngle.add(new Static1D(angle));
975
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*ObjectType.MAX_OBJECT_SIZE) , -1);
976
      mRotateEffect.notifyWhenFinished(listener);
977

    
978
      return mRotateEffect.getID();
979
      }
980

    
981
    return 0;
982
    }
983

    
984
///////////////////////////////////////////////////////////////////////////////////////////////////
985

    
986
  void continueRotation(float angleInDegrees)
987
    {
988
    mRotationAngleStatic.set0(angleInDegrees);
989
    }
990

    
991
///////////////////////////////////////////////////////////////////////////////////////////////////
992

    
993
  synchronized void beginNewRotation(int axis, int row )
994
    {
995
    if( axis<0 || axis>=NUM_AXIS )
996
      {
997
      android.util.Log.e("object", "invalid rotation axis: "+axis);
998
      return;
999
      }
1000
    if( row<0 || row>=mNumLayers[axis] )
1001
      {
1002
      android.util.Log.e("object", "invalid rotation row: "+row);
1003
      return;
1004
      }
1005

    
1006
    mCurrentRotAxis = axis;
1007
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1008
    mRotationAngleStatic.set0(0.0f);
1009
    mRotationAxis.set( mAxis[axis] );
1010
    mRotationAngle.add(mRotationAngleStatic);
1011
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*ObjectType.MAX_OBJECT_SIZE) , -1);
1012
    }
1013

    
1014
///////////////////////////////////////////////////////////////////////////////////////////////////
1015

    
1016
  void setTextureMap(int cubit, int face, int newColor)
1017
    {
1018
    final float ratioW = 1.0f/mNumTexCols;
1019
    final float ratioH = 1.0f/mNumTexRows;
1020
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1021
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1022
    int col = newColor%mNumTexCols;
1023

    
1024
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1025
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1026
    }
1027

    
1028
///////////////////////////////////////////////////////////////////////////////////////////////////
1029

    
1030
  void resetAllTextureMaps()
1031
    {
1032
    final float ratioW = 1.0f/mNumTexCols;
1033
    final float ratioH = 1.0f/mNumTexRows;
1034
    int color, row, col;
1035

    
1036
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
1037
      {
1038
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1039

    
1040
      for(int cubitface=0; cubitface<mNumCubitFaces; cubitface++)
1041
        {
1042
        color = getFaceColor(cubit,cubitface,mNumLayers);
1043
        row = (mNumTexRows-1) - color/mNumTexCols;
1044
        col = color%mNumTexCols;
1045
        maps[cubitface] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1046
        }
1047

    
1048
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1049
      }
1050
    }
1051

    
1052
///////////////////////////////////////////////////////////////////////////////////////////////////
1053

    
1054
  void releaseResources()
1055
    {
1056
    mTexture.markForDeletion();
1057
    mMesh.markForDeletion();
1058
    mEffects.markForDeletion();
1059

    
1060
    for(int j=0; j<NUM_CUBITS; j++)
1061
      {
1062
      CUBITS[j].releaseResources();
1063
      }
1064
    }
1065

    
1066
///////////////////////////////////////////////////////////////////////////////////////////////////
1067

    
1068
  synchronized void restorePreferences(SharedPreferences preferences)
1069
    {
1070
    boolean error = false;
1071

    
1072
    for(int i=0; i<NUM_CUBITS; i++)
1073
      {
1074
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
1075

    
1076
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<NUM_QUATS)
1077
        {
1078
        CUBITS[i].modifyCurrentPosition(OBJECT_QUATS[mQuatDebug[i]]);
1079
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
1080
        }
1081
      else
1082
        {
1083
        error = true;
1084
        }
1085
      }
1086

    
1087
    if( error )
1088
      {
1089
      for(int i=0; i<NUM_CUBITS; i++)
1090
        {
1091
        CUBITS[i].solve();
1092
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
1093
        }
1094
      recordQuatsState("Failed to restorePreferences");
1095
      }
1096
    }
1097

    
1098
///////////////////////////////////////////////////////////////////////////////////////////////////
1099

    
1100
  void savePreferences(SharedPreferences.Editor editor)
1101
    {
1102
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
1103
    }
1104

    
1105
///////////////////////////////////////////////////////////////////////////////////////////////////
1106

    
1107
  void recomputeScaleFactor(int surfaceW, int surfaceH)
1108
    {
1109
    mNodeScale.set(surfaceW,surfaceH,surfaceW);
1110
    }
1111

    
1112
///////////////////////////////////////////////////////////////////////////////////////////////////
1113
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1114

    
1115
  void createTexture()
1116
    {
1117
    Bitmap bitmap;
1118

    
1119
    Paint paint = new Paint();
1120
    bitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
1121
    Canvas canvas = new Canvas(bitmap);
1122

    
1123
    paint.setAntiAlias(true);
1124
    paint.setTextAlign(Paint.Align.CENTER);
1125
    paint.setStyle(Paint.Style.FILL);
1126

    
1127
    paint.setColor(COLOR_BLACK);
1128
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1129

    
1130
    int face = 0;
1131
    FactorySticker factory = FactorySticker.getInstance();
1132

    
1133
    for(int row=0; row<mNumTexRows; row++)
1134
      for(int col=0; col<mNumTexCols; col++)
1135
        {
1136
        if( face>=NUM_TEXTURES ) break;
1137
        int sIndex = getStickerIndex(face);
1138
        ObjectSticker sticker = retSticker(sIndex);
1139
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, getColor(face%NUM_FACE_COLORS), sticker);
1140
        face++;
1141
        }
1142

    
1143
    if( !mTexture.setTexture(bitmap) )
1144
      {
1145
      int max = DistortedLibrary.getMaxTextureSize();
1146
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
1147
      crashlytics.log("failed to set texture of size "+bitmap.getWidth()+"x"+bitmap.getHeight()+" max is "+max);
1148
      }
1149
    }
1150

    
1151
///////////////////////////////////////////////////////////////////////////////////////////////////
1152

    
1153
  void setObjectRatioNow(float sc)
1154
    {
1155
    mObjectScreenRatio = sc;
1156
    int nodeMinSize = Math.min(mNodeW,mNodeH);
1157
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeMinSize/mSize;
1158
    mObjectScale.set(scale,scale,scale);
1159
    }
1160

    
1161
///////////////////////////////////////////////////////////////////////////////////////////////////
1162

    
1163
  void setObjectRatio(float sizeChange)
1164
    {
1165
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1166

    
1167
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1168
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1169

    
1170
    setObjectRatioNow(mObjectScreenRatio);
1171
    }
1172

    
1173
///////////////////////////////////////////////////////////////////////////////////////////////////
1174

    
1175
  float getObjectRatio()
1176
    {
1177
    return mObjectScreenRatio*mInitScreenRatio;
1178
    }
1179

    
1180
///////////////////////////////////////////////////////////////////////////////////////////////////
1181

    
1182
  public float getRatio()
1183
    {
1184
    return mObjectScreenRatio;
1185
    }
1186

    
1187
///////////////////////////////////////////////////////////////////////////////////////////////////
1188

    
1189
  boolean isSolved()
1190
    {
1191
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1192
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1193
    if( mSolvedFunctionIndex==2 ) return isSolved2();
1194
    if( mSolvedFunctionIndex==3 ) return isSolved3();
1195

    
1196
    return false;
1197
    }
1198

    
1199
///////////////////////////////////////////////////////////////////////////////////////////////////
1200
// only called with figuring out which cubit was touched in MODE_REPLACE, which is only used in
1201
// during setting up the initial position in the solver.
1202

    
1203
  int getCubit(float[] point3D)
1204
    {
1205
    float dist, minDist = Float.MAX_VALUE;
1206
    int currentBest=-1;
1207
    float multiplier = mNumLayers[0];
1208

    
1209
    point3D[0] *= multiplier;
1210
    point3D[1] *= multiplier;
1211
    point3D[2] *= multiplier;
1212

    
1213
    for(int i=0; i<NUM_CUBITS; i++)
1214
      {
1215
      dist = CUBITS[i].getDistSquared(point3D);
1216
      if( dist<minDist )
1217
        {
1218
        minDist = dist;
1219
        currentBest = i;
1220
        }
1221
      }
1222

    
1223
    return currentBest;
1224
    }
1225

    
1226
///////////////////////////////////////////////////////////////////////////////////////////////////
1227

    
1228
  int computeNearestAngle(int axis, float angle, float speed)
1229
    {
1230
    int[] basicArray = getBasicAngle();
1231
    int basicAngle   = basicArray[axis>=basicArray.length ? 0 : axis];
1232
    int nearestAngle = 360/basicAngle;
1233

    
1234
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1235
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1236

    
1237
    if( tmp!=0 ) return nearestAngle*tmp;
1238

    
1239
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1240
    }
1241

    
1242
///////////////////////////////////////////////////////////////////////////////////////////////////
1243

    
1244
  float getCameraDist()
1245
    {
1246
    return mCameraDist;
1247
    }
1248

    
1249
///////////////////////////////////////////////////////////////////////////////////////////////////
1250
// INTERNAL API - those are called from 'effects' package
1251
///////////////////////////////////////////////////////////////////////////////////////////////////
1252

    
1253
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1254
    {
1255
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1256
    }
1257

    
1258
///////////////////////////////////////////////////////////////////////////////////////////////////
1259

    
1260
  public int getNodeWidth()
1261
    {
1262
    return mNodeW;
1263
    }
1264

    
1265
///////////////////////////////////////////////////////////////////////////////////////////////////
1266

    
1267
  public Static4D getRotationQuat()
1268
    {
1269
    return mQuat;
1270
    }
1271

    
1272
///////////////////////////////////////////////////////////////////////////////////////////////////
1273

    
1274
  public float getSize()
1275
    {
1276
    return mSize;
1277
    }
1278

    
1279
///////////////////////////////////////////////////////////////////////////////////////////////////
1280

    
1281
  public void apply(Effect effect, int position)
1282
    {
1283
    mEffects.apply(effect, position);
1284
    }
1285

    
1286
///////////////////////////////////////////////////////////////////////////////////////////////////
1287

    
1288
  public void remove(long effectID)
1289
    {
1290
    mEffects.abortById(effectID);
1291
    }
1292

    
1293
///////////////////////////////////////////////////////////////////////////////////////////////////
1294

    
1295
  public MeshBase getObjectMesh()
1296
    {
1297
    return mMesh;
1298
    }
1299

    
1300
///////////////////////////////////////////////////////////////////////////////////////////////////
1301

    
1302
  public DistortedEffects getObjectEffects()
1303
    {
1304
    return mEffects;
1305
    }
1306

    
1307
///////////////////////////////////////////////////////////////////////////////////////////////////
1308
// PUBLIC API
1309
///////////////////////////////////////////////////////////////////////////////////////////////////
1310

    
1311
  public int getCubitFaceColorIndex(int cubit, int face)
1312
    {
1313
    Static4D texMap = mMesh.getTextureMap(NUM_FACE_COLORS*cubit + face);
1314

    
1315
    int x = (int)(texMap.get0()/texMap.get2());
1316
    int y = (int)(texMap.get1()/texMap.get3());
1317

    
1318
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1319
    }
1320

    
1321
///////////////////////////////////////////////////////////////////////////////////////////////////
1322

    
1323
  public int[] getNumLayers()
1324
    {
1325
    return mNumLayers;
1326
    }
1327

    
1328
///////////////////////////////////////////////////////////////////////////////////////////////////
1329

    
1330
  public synchronized void solve()
1331
    {
1332
    for(int i=0; i<NUM_CUBITS; i++)
1333
      {
1334
      CUBITS[i].solve();
1335
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
1336
      }
1337
    }
1338

    
1339
///////////////////////////////////////////////////////////////////////////////////////////////////
1340

    
1341
  public ObjectType getObjectType()
1342
    {
1343
    return intGetObjectType(mNumLayers);
1344
    }
1345

    
1346
///////////////////////////////////////////////////////////////////////////////////////////////////
1347

    
1348
  public Movement getMovement()
1349
    {
1350
    if( mMovement==null )
1351
      {
1352
      int[] numLayers = getNumLayers();
1353
      if( mCuts==null ) getCuts(numLayers);
1354
      if( mLayerRotatable==null ) mLayerRotatable = getLayerRotatable(numLayers);
1355
      if( mEnabled==null ) mEnabled = getEnabled();
1356

    
1357
      int movementType = getMovementType();
1358
      int movementSplit= getMovementSplit();
1359

    
1360
      switch(movementType)
1361
        {
1362
        case MOVEMENT_TETRAHEDRON : mMovement = new Movement4(mAxis,mCuts,mLayerRotatable,mSize,movementSplit,mEnabled);
1363
                                    break;
1364
        case MOVEMENT_HEXAHEDRON  : mMovement = new Movement6(mAxis,mCuts,mLayerRotatable,mSize,movementSplit,mEnabled);
1365
                                    break;
1366
        case MOVEMENT_OCTAHEDRON  : mMovement = new Movement8(mAxis,mCuts,mLayerRotatable,mSize,movementSplit,mEnabled);
1367
                                    break;
1368
        case MOVEMENT_DODECAHEDRON: mMovement = new Movement12(mAxis,mCuts,mLayerRotatable,mSize,movementSplit,mEnabled);
1369
                                    break;
1370
        case MOVEMENT_SHAPECHANGE : float[] dist3D = getDist3D(numLayers);
1371
                                    mMovement = new MovementC(mAxis,mCuts,mLayerRotatable,mSize,movementSplit,mEnabled,dist3D);
1372
                                    break;
1373
        }
1374
      }
1375
    return mMovement;
1376
    }
1377

    
1378
///////////////////////////////////////////////////////////////////////////////////////////////////
1379

    
1380
  protected abstract int getFOV();
1381
  protected abstract float getScreenRatio();
1382
  protected abstract int getNumFaceColors();
1383
  protected abstract int getColor(int face);
1384
  protected abstract int getNumCubitFaces();
1385
  protected abstract float[][] getCubitPositions(int[] numLayers);
1386
  protected abstract int getCubitVariant(int cubit, int[] numLayers);
1387
  protected abstract int getNumCubitVariants(int[] numLayers);
1388
  protected abstract Static4D getQuat(int cubit, int[] numLayers);
1389
  protected abstract ObjectShape getObjectShape(int cubit, int[] numLayers);
1390
  protected abstract int[] getSolvedQuats(int cubit, int[] numLayers);
1391
  protected abstract int getFaceColor(int cubit, int cubitface, int[] numLayers);
1392
  protected abstract int getResource(int[] numLayers);
1393
  protected abstract ObjectType intGetObjectType(int[] numLayers);
1394
  protected abstract int getStickerIndex(int face);
1395

    
1396
  // for JSON only
1397
  public abstract int getSolvedFunctionIndex();
1398
  public abstract int getMovementType();
1399
  public abstract int getMovementSplit();
1400
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1401
  public abstract int[][][] getEnabled();
1402
  public abstract float[] getDist3D(int[] numLayers);
1403
  public abstract ScrambleState[] getScrambleStates();
1404
  public abstract float[][] getCuts(int[] numLayers);
1405
  public abstract Static4D[] getQuats();
1406
  public abstract int getNumStickerTypes(int[] numLayers);
1407
  public abstract ObjectSticker retSticker(int sticker);
1408

    
1409
  public abstract Static3D[] getRotationAxis();
1410
  public abstract int[] getBasicAngle();
1411
  public abstract int getNumFaces();
1412
  public abstract int getObjectName(int[] numLayers);
1413
  public abstract int getInventor(int[] numLayers);
1414
  public abstract int getYearOfInvention(int[] numLayers);
1415
  public abstract int getComplexity(int[] numLayers);
1416
  }
(15-15/16)