Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ 97a6aa87

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 java.io.DataInputStream;
23
import java.io.IOException;
24
import java.io.InputStream;
25
import java.util.Random;
26

    
27
import android.content.SharedPreferences;
28
import android.graphics.Bitmap;
29
import android.graphics.Canvas;
30
import android.graphics.Paint;
31

    
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.main.QuatHelper;
43
import org.distorted.library.mesh.MeshBase;
44
import org.distorted.library.mesh.MeshFile;
45
import org.distorted.library.mesh.MeshJoined;
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

    
52
import org.distorted.objectlib.helpers.FactoryCubit;
53
import org.distorted.objectlib.helpers.FactorySticker;
54
import org.distorted.objectlib.helpers.ObjectFaceShape;
55
import org.distorted.objectlib.helpers.ObjectLibInterface;
56
import org.distorted.objectlib.helpers.ObjectShape;
57
import org.distorted.objectlib.helpers.ObjectSticker;
58
import org.distorted.objectlib.helpers.QuatGroupGenerator;
59
import org.distorted.objectlib.scrambling.ScrambleState;
60
import org.distorted.objectlib.scrambling.ObjectScrambler;
61
import org.distorted.objectlib.json.JsonReader;
62
import org.distorted.objectlib.touchcontrol.*;
63

    
64
import static org.distorted.objectlib.touchcontrol.TouchControl.*;
65

    
66
///////////////////////////////////////////////////////////////////////////////////////////////////
67

    
68
public abstract class TwistyObject
69
  {
70
  public static final int MESH_NICE = 0;
71
  public static final int MESH_FAST = 1;
72

    
73
  public static final int MODE_ICON = 0;
74
  public static final int MODE_NORM = 1;
75

    
76
  public static final int COLOR_YELLOW   = 0xffffff00;
77
  public static final int COLOR_WHITE    = 0xffffffff;
78
  public static final int COLOR_BLUE     = 0xff0000ff;
79
  public static final int COLOR_GREEN    = 0xff00bb00;
80
  public static final int COLOR_RED      = 0xff990000;
81
  public static final int COLOR_ORANGE   = 0xffff6200;
82
  public static final int COLOR_GREY     = 0xff727c7b;
83
  public static final int COLOR_VIOLET   = 0xff7700bb;
84
  public static final int COLOR_STROKE   = 0xff000000;
85
  private static final int COLOR_INTERNAL= 0xff000000;
86

    
87
  public static final int TEXTURE_HEIGHT = 256;
88
  static final int NUM_STICKERS_IN_ROW = 4;
89

    
90
  public static final float SQ2 = (float)Math.sqrt(2);
91
  public static final float SQ3 = (float)Math.sqrt(3);
92
  public static final float SQ5 = (float)Math.sqrt(5);
93
  public static final float SQ6 = (float)Math.sqrt(6);
94

    
95
  private static final float MAX_SIZE_CHANGE = 1.35f;
96
  private static final float MIN_SIZE_CHANGE = 0.75f;
97

    
98
  private static final Static3D CENTER = new Static3D(0,0,0);
99
  private static final int POST_ROTATION_MILLISEC = 500;
100

    
101
  protected float[][] mStickerCoords;
102
  protected Static4D[] mObjectQuats;
103
  int mNumAxis, mMaxNumLayers;
104

    
105
  private int[][] mStickerVariants;
106
  private float[] mStickerScales;
107
  private Cubit[] mCubits;
108
  private MeshBase[] mMeshes;
109
  private int mNumCubits, mNumQuats, mNumFaceColors, mNumTextures;
110
  private int mNumCubitFaces, mNumStickerTypes;
111
  private Static3D[] mAxis;
112
  private float[][] mCuts;
113
  private int[] mNumCuts;
114
  private float[][] mOrigPos;
115
  private Static4D[] mOrigQuat;
116
  private Static4D mQuat;
117
  private final int[] mNumLayers;
118
  private final float mSize;
119
  private DistortedEffects mEffects;
120
  private VertexEffectRotate mRotateEffect;
121
  private Dynamic1D mRotationAngle;
122
  private Static3D mRotationAxis;
123
  private Static3D mObjectScale;
124
  private int[] mQuatDebug;
125
  private Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
126
  private DistortedTexture mTexture;
127
  private float mInitScreenRatio;
128
  private int mSolvedFunctionIndex;
129
  private boolean mIsBandaged;
130
  private float mObjectScreenRatio;
131
  private int[][] mSolvedQuats;
132
  private int[][] mQuatMult;
133
  private int[] mTmpQuats;
134
  private int mNumTexRows, mNumTexCols;
135
  private int mRotRowBitmap;
136
  private int mCurrentRotAxis;
137
  private MeshBase mMesh;
138
  private ObjectScrambler mScrambler;
139
  private TouchControl mTouchControl;
140
  private DistortedNode mNode;
141
  private ObjectLibInterface mInterface;
142
  private Bitmap mBitmap;
143
  private ObjectSticker[] mStickers;
144
  private ObjectShape[] mShapes;
145
  private int mNumCubitVariants;
146
  private int[][] mCubitFaceColors;
147
  private int[][] mVariantFaceIsOuter;
148
  private int[] mBasicAngles;
149
  private int mIconMode;
150

    
151
  //////////////////// SOLVED1 ////////////////////////
152

    
153
  private int[] mFaceMap;
154
  private int[][] mScramble;
155
  private int[] mColors;
156

    
157
///////////////////////////////////////////////////////////////////////////////////////////////////
158

    
159
  TwistyObject(InputStream jsonStream, int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream meshStream)
160
    {
161
    JsonReader reader = JsonReader.getInstance();
162
    reader.parseJsonFile(jsonStream);
163
    setReader(reader);
164

    
165
    mNumLayers = reader.getNumLayers();
166
    mSize      = reader.getSize();
167
    initialize(meshState,iconMode,quat,move,scale,meshStream,true);
168
    }
169

    
170
///////////////////////////////////////////////////////////////////////////////////////////////////
171

    
172
  TwistyObject(int[] numLayers, int meshState, int iconMode, float size, Static4D quat, Static3D move, float scale, InputStream meshStream)
173
    {
174
    mNumLayers = numLayers;
175
    mSize      = size;
176
    initialize(meshState,iconMode,quat,move,scale,meshStream,false);
177
    }
178

    
179
///////////////////////////////////////////////////////////////////////////////////////////////////
180

    
181
  private void initialize(int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream stream, boolean fromJSON)
182
    {
183
    mIconMode = iconMode;
184
    mQuat = quat;
185
    mAxis = getRotationAxis();
186
    mInitScreenRatio = getScreenRatio();
187
    mSolvedFunctionIndex = getSolvedFunctionIndex();
188
    mBasicAngles = getBasicAngles();
189
    mObjectQuats = getQuats();
190
    mNumQuats = mObjectQuats.length;
191
    mOrigPos = getCubitPositions(mNumLayers);
192

    
193
    int numAxis = mAxis.length;
194
    mMaxNumLayers = -1;
195
    mCuts = getCuts(mNumLayers);
196
    mNumCuts = new int[numAxis];
197
    for(int i=0; i<numAxis; i++)
198
      {
199
      if( mMaxNumLayers<mNumLayers[i] ) mMaxNumLayers = mNumLayers[i];
200
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
201
      }
202

    
203
    mNumCubits = mOrigPos.length;
204
    mNumFaceColors = getNumFaceColors();
205
    mNumAxis = mAxis.length;
206

    
207
    int scramblingType = getScrambleType();
208
    ScrambleState[] states = getScrambleStates();
209
    mScrambler = new ObjectScrambler(scramblingType, mNumAxis,mNumLayers,states);
210

    
211
    boolean bandaged=false;
212

    
213
    for( int c=0; c<mNumCubits; c++)
214
      {
215
      if( mOrigPos[c].length>3 )
216
        {
217
        bandaged=true;
218
        break;
219
        }
220
      }
221
    mIsBandaged = bandaged;
222
    mQuatDebug = new int[mNumCubits];
223

    
224
    mRotationAngle= new Dynamic1D();
225
    mRotationAxis = new Static3D(1,0,0);
226
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
227

    
228
    mRotationAngleStatic = new Static1D(0);
229
    mRotationAngleMiddle = new Static1D(0);
230
    mRotationAngleFinal  = new Static1D(0);
231

    
232
    mObjectScale = new Static3D(scale,scale,scale);
233
    setObjectRatioNow(scale,720);
234

    
235
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
236
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
237
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
238

    
239
    boolean fromDMESH = (stream!=null && meshState==MESH_NICE);
240
    getQuatsAndShapes(fromDMESH,fromJSON);
241
    createMeshAndCubits(stream,meshState,fromDMESH);
242
    setUpTextures(fromDMESH,fromJSON);
243
    createDataStructuresForSolved();
244

    
245
    mEffects = new DistortedEffects();
246

    
247
    for( int q=0; q<mNumQuats; q++)
248
      {
249
      VertexEffectQuaternion vq = new VertexEffectQuaternion(mObjectQuats[q],CENTER);
250
      vq.setMeshAssociation(0,q);
251
      mEffects.apply(vq);
252
      }
253

    
254
    mEffects.apply(mRotateEffect);
255
    mEffects.apply(quatEffect);
256
    mEffects.apply(scaleEffect);
257
    mEffects.apply(moveEffect);
258

    
259
    mNode = new DistortedNode(mTexture,mEffects,mMesh);
260
    }
261

    
262
///////////////////////////////////////////////////////////////////////////////////////////////////
263

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

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

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

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

    
285
///////////////////////////////////////////////////////////////////////////////////////////////////
286

    
287
  private void createOuterFaces()
288
    {
289
    for(int v=0; v<mNumCubitVariants; v++)
290
      {
291
      int[][] indices = mShapes[v].getVertIndices();
292
      int faces = indices.length;
293
      mVariantFaceIsOuter[v] = new int[faces];
294
      }
295

    
296
    for( int cubit=0; cubit<mNumCubits; cubit++)
297
      {
298
      int variant = getCubitVariant(cubit,mNumLayers);
299
      int[][] indices = mShapes[variant].getVertIndices();
300
      int numFaces = indices.length;
301

    
302
      for(int face=0; face<numFaces; face++)
303
        if( getCubitFaceColor(cubit,face)>=0 )
304
          {
305
          mVariantFaceIsOuter[variant][face] = 1;
306
          }
307
      }
308
    }
309

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

    
312
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
313
    {
314
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
315

    
316
    if( !fromDMESH || !fromJSON )
317
      {
318
      FactoryCubit factory = FactoryCubit.getInstance();
319
      factory.clear();
320

    
321
      mOrigQuat = new Static4D[mNumCubits];
322
      for(int i=0; i<mNumCubits; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
323

    
324
      mShapes = new ObjectShape[mNumCubitVariants];
325
      for(int i=0; i<mNumCubitVariants; i++) mShapes[i] = getObjectShape(i);
326
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
327
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
328

    
329
      if( !fromJSON )
330
        {
331
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
332
        createOuterFaces();
333
        }
334

    
335
      if( fromDMESH )
336
        {
337
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
338
        }
339
      }
340
    }
341

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

    
344
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH)
345
    {
346
    mCubits = new Cubit[mNumCubits];
347

    
348
    if( fromDMESH )
349
      {
350
      DataInputStream dos = new DataInputStream(stream);
351
      mMesh = new MeshFile(dos);
352

    
353
      try
354
        {
355
        stream.close();
356
        }
357
      catch(IOException e)
358
        {
359
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
360
        }
361

    
362
      for(int i=0; i<mNumCubits; i++)
363
        {
364
        mCubits[i] = new Cubit(this,mOrigPos[i], mNumAxis);
365
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(), 0);
366
        }
367
      }
368
    else
369
      {
370
      MeshBase[] cubitMesh = new MeshBase[mNumCubits];
371

    
372
      for(int i=0; i<mNumCubits; i++)
373
        {
374
        mCubits[i] = new Cubit(this,mOrigPos[i], mNumAxis);
375
        cubitMesh[i] = createCubitMesh(i,mNumLayers,meshState,mNumCubitFaces);
376
        Static3D pos = getPos(mOrigPos[i]);
377
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
378
        cubitMesh[i].setEffectAssociation(0, mCubits[i].computeAssociation(), 0);
379
        }
380

    
381
      mMesh = new MeshJoined(cubitMesh);
382
      }
383
    }
384

    
385
///////////////////////////////////////////////////////////////////////////////////////////////////
386

    
387
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState, int numComponents)
388
    {
389
    int variant = getCubitVariant(cubit,numLayers);
390

    
391
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
392

    
393
    if( mMeshes[variant]==null )
394
      {
395
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
396
      FactoryCubit factory = FactoryCubit.getInstance();
397
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
398
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,meshState, numComponents);
399
      }
400

    
401
    MeshBase mesh = mMeshes[variant].copy(true);
402
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
403
    mesh.apply(quat,0xffffffff,0);
404

    
405
    return mesh;
406
    }
407

    
408
///////////////////////////////////////////////////////////////////////////////////////////////////
409

    
410
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
411
    {
412
    mTexture = new DistortedTexture();
413

    
414
    if( fromJSON )
415
      {
416
      mNumStickerTypes = getNumStickerTypes();
417
      mNumCubitFaces = getNumCubitFaces();
418
      }
419
    else
420
      {
421
      FactoryCubit factory = FactoryCubit.getInstance();
422
      mStickerCoords   = factory.getStickerCoords();
423
      mStickerVariants = factory.getStickerVariants();
424
      mStickerScales   = factory.getStickerScales();
425
      adjustStickerCoords();
426
      mNumStickerTypes = (mStickerCoords==null ? 0 : mStickerCoords.length);
427
      }
428

    
429
    mNumTextures= mNumFaceColors *mNumStickerTypes;
430
    mNumTexCols = NUM_STICKERS_IN_ROW;
431
    mNumTexRows = (mNumTextures+1)/NUM_STICKERS_IN_ROW;
432
    if( mNumTexCols*mNumTexRows < mNumTextures+1 ) mNumTexRows++;
433

    
434
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
435
    setTexture();
436
    }
437

    
438
///////////////////////////////////////////////////////////////////////////////////////////////////
439

    
440
  private int getMultQuat(int index1, int index2)
441
    {
442
    if( mQuatMult==null )
443
      {
444
      mQuatMult = new int[mNumQuats][mNumQuats];
445

    
446
      for(int i=0; i<mNumQuats; i++)
447
        for(int j=0; j<mNumQuats; j++) mQuatMult[i][j] = -1;
448
      }
449

    
450
    if( mQuatMult[index1][index2]==-1 )
451
      {
452
      mQuatMult[index1][index2] = mulQuat(index1,index2);
453
      }
454

    
455
    return mQuatMult[index1][index2];
456
    }
457

    
458
///////////////////////////////////////////////////////////////////////////////////////////////////
459

    
460
  public boolean isInIconMode()
461
    {
462
    return mIconMode==MODE_ICON;
463
    }
464

    
465
///////////////////////////////////////////////////////////////////////////////////////////////////
466

    
467
  public int getVariantFaceColor(int variant, int face)
468
    {
469
    return face>=mStickerVariants[variant].length ? -1 : mStickerVariants[variant][face];
470
    }
471

    
472
///////////////////////////////////////////////////////////////////////////////////////////////////
473

    
474
  public boolean shouldResetTextureMaps()
475
    {
476
    return false;
477
    }
478

    
479
///////////////////////////////////////////////////////////////////////////////////////////////////
480

    
481
  private void createDataStructuresForSolved()
482
    {
483
    mTmpQuats = new int[mNumQuats];
484
    mSolvedQuats = getSolvedQuats();
485
    }
486

    
487
///////////////////////////////////////////////////////////////////////////////////////////////////
488
// This is used to build internal data structures for the generic 'isSolved()'
489
//
490
// if this is an internal cubit (all faces black): return -1
491
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
492
// Color index, i.e. the index into the 'FACE_COLORS' table.
493
// else (edge or corner cubit, more than one non-black face): return -2.
494

    
495
  protected int retCubitSolvedStatus(int cubit)
496
    {
497
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
498
    int variant = getCubitVariant(cubit,mNumLayers);
499

    
500
    for(int face=0; face<mNumCubitFaces; face++)
501
      {
502
      varColor = getVariantFaceColor(variant,face);
503
      int numFaces = mCubitFaceColors[cubit].length;
504
      cubColor = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
505

    
506
      if( varColor>=0 && cubColor>=0 )
507
        {
508
        numNonBlack++;
509
        nonBlackIndex = cubColor;
510
        }
511
      }
512

    
513
    if( numNonBlack==0 ) return -1;
514
    if( numNonBlack>=2 ) return -2;
515

    
516
    return nonBlackIndex;
517
    }
518

    
519
///////////////////////////////////////////////////////////////////////////////////////////////////
520

    
521
  protected void displayCubitQuats()
522
    {
523
    StringBuilder builder = new StringBuilder();
524
    float[] tmp = new float[4];
525
    float MAXERR = 0.01f;
526

    
527
    for(int cubit=0; cubit<mNumCubits; cubit++)
528
      {
529
      int refCubit,variant = getCubitVariant(cubit,mNumLayers);
530

    
531
      for(refCubit=0; refCubit<mNumCubits; refCubit++)
532
        {
533
        if( getCubitVariant(refCubit,mNumLayers)==variant ) break;
534
        }
535

    
536
      float[] curpos = mOrigPos[cubit];
537
      float[] refpos = mOrigPos[refCubit];
538
      float refX = refpos[0];
539
      float refY = refpos[1];
540
      float refZ = refpos[2];
541
      float curX = curpos[0];
542
      float curY = curpos[1];
543
      float curZ = curpos[2];
544

    
545
      for(int quat=0; quat<mNumQuats; quat++)
546
        {
547
        QuatHelper.rotateVectorByQuat(tmp,refX,refY,refZ,0,mObjectQuats[quat]);
548

    
549
        float dx = tmp[0]-curX;
550
        float dy = tmp[1]-curY;
551
        float dz = tmp[2]-curZ;
552

    
553
        if( dx>-MAXERR && dx<MAXERR && dy>-MAXERR && dy<MAXERR && dz>-MAXERR && dz<MAXERR )
554
          {
555
          builder.append(quat);
556
          builder.append(',');
557
          }
558
        }
559

    
560
      builder.append('\n');
561
      }
562

    
563
    android.util.Log.e("D", "cubitQuats: \n"+builder.toString() );
564
    }
565

    
566
///////////////////////////////////////////////////////////////////////////////////////////////////
567

    
568
  protected int[] buildSolvedQuats(Static3D faceAx)
569
    {
570
    final float MAXD = 0.0001f;
571
    float x = faceAx.get0();
572
    float y = faceAx.get1();
573
    float z = faceAx.get2();
574
    float a,dx,dy,dz,qx,qy,qz;
575
    Static4D quat;
576
    int place = 0;
577

    
578
    for(int q=1; q<mNumQuats; q++)
579
      {
580
      quat = mObjectQuats[q];
581
      qx = quat.get0();
582
      qy = quat.get1();
583
      qz = quat.get2();
584

    
585
           if( x!=0.0f ) { a = qx/x; }
586
      else if( y!=0.0f ) { a = qy/y; }
587
      else               { a = qz/z; }
588

    
589
      dx = a*x-qx;
590
      dy = a*y-qy;
591
      dz = a*z-qz;
592

    
593
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
594
        {
595
        mTmpQuats[place++] = q;
596
        }
597
      }
598

    
599
    if( place!=0 )
600
      {
601
      int[] ret = new int[place];
602
      System.arraycopy(mTmpQuats,0,ret,0,place);
603
      return ret;
604
      }
605

    
606
    return null;
607
    }
608

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

    
611
  public int[][] getSolvedQuats()
612
    {
613
    int[] groups = new int[mNumCubits];
614
    int numGroups = 1;
615
    int numFirst  = 0;
616

    
617
    for(int cubit=0; cubit<mNumCubits; cubit++)
618
      {
619
      groups[cubit] = retCubitSolvedStatus(cubit);
620
      if( groups[cubit]>=0 ) numGroups++;
621
      else                   numFirst++;
622
      }
623

    
624
    int firstIndex = 1;
625
    int groupIndex = 1;
626
    int[][] solvedQuats = new int[numGroups][];
627
    solvedQuats[0] = new int[1+numFirst];
628
    solvedQuats[0][0] = numFirst;
629
    Static3D[] axis = getFaceAxis();
630

    
631
    for(int cubit=0; cubit<mNumCubits; cubit++)
632
      {
633
      int group = groups[cubit];
634

    
635
      if( group<0 )
636
        {
637
        solvedQuats[0][firstIndex] = cubit;
638
        firstIndex++;
639
        }
640
      else
641
        {
642
        int[] quats = buildSolvedQuats(axis[group]);
643
        int len = quats==null ? 0 : quats.length;
644
        solvedQuats[groupIndex] = new int[2+len];
645
        solvedQuats[groupIndex][0] = 1;
646
        solvedQuats[groupIndex][1] = cubit;
647
        for(int i=0; i<len; i++) solvedQuats[groupIndex][i+2] = quats[i];
648
        groupIndex++;
649
        }
650
      }
651
/*
652
    String dbg = "SOLVED GROUPS:\n";
653

    
654
    for(int g=0; g<numGroups; g++)
655
      {
656
      int len = solvedQuats[g].length;
657
      for(int i=0; i<len; i++) dbg += (" "+solvedQuats[g][i]);
658
      dbg+="\n";
659
      }
660

    
661
    android.util.Log.e("D", dbg);
662
*/
663
    return solvedQuats;
664
    }
665

    
666
///////////////////////////////////////////////////////////////////////////////////////////////////
667

    
668
  public int getSolvedFunctionIndex()
669
    {
670
    return 0;
671
    }
672

    
673
///////////////////////////////////////////////////////////////////////////////////////////////////
674
// special SolvedQuats for the case where there are no corner of edge cubits.
675
// first row {0} - means there are no corners or edges.
676
// each next defines all cubits of a singe face (numCubits, firstCubit, cubit1,..,cubitN-1, quat0,..., quatM
677

    
678
  private boolean isSolvedCentersOnly()
679
    {
680
    int numGroups = mSolvedQuats.length;
681

    
682
    for(int group=1; group<numGroups; group++)
683
      {
684
      int numEntries= mSolvedQuats[group].length;
685
      int numCubits = mSolvedQuats[group][0];
686
      int firstCubit= mSolvedQuats[group][1];
687
      int firstQuat = mCubits[firstCubit].mQuatIndex;
688

    
689
      for(int cubit=2; cubit<=numCubits; cubit++)
690
        {
691
        int currCubit= mSolvedQuats[group][cubit];
692
        int currQuat = mCubits[currCubit].mQuatIndex;
693
        boolean isGood= (firstQuat==currQuat);
694

    
695
        for(int q=numCubits+1; !isGood && q<numEntries; q++)
696
          {
697
          int quat = mSolvedQuats[group][q];
698
          if( firstQuat == getMultQuat(currQuat,quat) ) isGood = true;
699
          }
700

    
701
        if( !isGood ) return false;
702
        }
703
      }
704

    
705
    return true;
706
    }
707

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

    
710
  private boolean isSolved0()
711
    {
712
    if( mSolvedQuats[0][0]==0 ) return isSolvedCentersOnly();
713

    
714
    for( int[] solvedQuat : mSolvedQuats )
715
      {
716
      int numCubits = solvedQuat[0];
717
      int firstCubit= solvedQuat[1];
718
      int quat = mCubits[firstCubit].mQuatIndex;
719

    
720
      for( int cubit=2; cubit<=numCubits; cubit++ )
721
        {
722
        int c = solvedQuat[cubit];
723
        if( quat != mCubits[c].mQuatIndex ) return false;
724
        }
725
      }
726

    
727
    int cubit= mSolvedQuats[0][1];
728
    int quat0= mCubits[cubit].mQuatIndex;
729
    int numGroups = mSolvedQuats.length;
730

    
731
    for(int group=1; group<numGroups; group++)
732
      {
733
      int firstCubit= mSolvedQuats[group][1];
734
      int currQuat  = mCubits[firstCubit].mQuatIndex;
735

    
736
      if( quat0==currQuat ) continue;
737

    
738
      boolean isGood= false;
739
      int numEntries= mSolvedQuats[group].length;
740
      int numCubits = mSolvedQuats[group][0];
741

    
742
      for(int q=numCubits+1; q<numEntries; q++)
743
        {
744
        int quat = mSolvedQuats[group][q];
745

    
746
        if( quat0 == getMultQuat(currQuat,quat) )
747
          {
748
          isGood = true;
749
          break;
750
          }
751
        }
752

    
753
      if( !isGood ) return false;
754
      }
755

    
756
    return true;
757
    }
758

    
759
///////////////////////////////////////////////////////////////////////////////////////////////////
760

    
761
  private int computeScramble(int quatNum, int centerNum)
762
    {
763
    float MAXDIFF = 0.01f;
764
    float[] center= mOrigPos[centerNum];
765
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
766
    Static4D result = QuatHelper.rotateVectorByQuat(sc,mObjectQuats[quatNum]);
767

    
768
    float x = result.get0();
769
    float y = result.get1();
770
    float z = result.get2();
771

    
772
    for(int c=0; c<mNumCubits; c++)
773
      {
774
      float[] cent = mOrigPos[c];
775

    
776
      float qx = cent[0] - x;
777
      float qy = cent[1] - y;
778
      float qz = cent[2] - z;
779

    
780
      if( qx>-MAXDIFF && qx<MAXDIFF &&
781
          qy>-MAXDIFF && qy<MAXDIFF &&
782
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
783
      }
784

    
785
    return -1;
786
    }
787

    
788
///////////////////////////////////////////////////////////////////////////////////////////////////
789
// Dino4 uses this. It is solved if and only if groups of cubits
790
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
791
// or
792
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
793
// are all the same color.
794

    
795
  private boolean isSolved1()
796
    {
797
    if( mScramble==null )
798
      {
799
      mScramble = new int[mNumQuats][mNumCubits];
800
      mColors   = new int[mNumCubits];
801

    
802
      for(int q=0; q<mNumQuats; q++)
803
        for(int c=0; c<mNumCubits; c++) mScramble[q][c] = computeScramble(q,c);
804
      }
805

    
806
    if( mFaceMap==null )
807
      {
808
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
809
      }
810

    
811
    for(int c=0; c<mNumCubits; c++)
812
      {
813
      int index = mScramble[mCubits[c].mQuatIndex][c];
814
      mColors[index] = mFaceMap[c];
815
      }
816

    
817
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
818
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
819
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
820

    
821
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
822
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
823
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
824

    
825
    return false;
826
    }
827

    
828
///////////////////////////////////////////////////////////////////////////////////////////////////
829

    
830
  int computeRow(float[] pos, int axisIndex)
831
    {
832
    int ret=0;
833
    int len = pos.length / 3;
834
    Static3D axis = mAxis[axisIndex];
835
    float axisX = axis.get0();
836
    float axisY = axis.get1();
837
    float axisZ = axis.get2();
838
    float casted;
839

    
840
    for(int i=0; i<len; i++)
841
      {
842
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
843
      ret |= computeSingleRow(axisIndex,casted);
844
      }
845

    
846
    return ret;
847
    }
848

    
849
///////////////////////////////////////////////////////////////////////////////////////////////////
850

    
851
  private int computeSingleRow(int axisIndex,float casted)
852
    {
853
    int num = mNumCuts[axisIndex];
854

    
855
    for(int i=0; i<num; i++)
856
      {
857
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
858
      }
859

    
860
    return (1<<num);
861
    }
862

    
863
///////////////////////////////////////////////////////////////////////////////////////////////////
864

    
865
  private boolean wasRotateApplied()
866
    {
867
    return mEffects.exists(mRotateEffect.getID());
868
    }
869

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

    
872
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
873
    {
874
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
875
    }
876

    
877
///////////////////////////////////////////////////////////////////////////////////////////////////
878
// note the minus in front of the sin() - we rotate counterclockwise
879
// when looking towards the direction where the axis increases in values.
880

    
881
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
882
    {
883
    Static3D axis = mAxis[axisIndex];
884

    
885
    while( angleInDegrees<0 ) angleInDegrees += 360;
886
    angleInDegrees %= 360;
887
    
888
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
889
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
890

    
891
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
892
    }
893

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

    
896
  private synchronized void setupPosition(int[][] moves)
897
    {
898
    if( moves!=null )
899
      {
900
      Static4D quat;
901
      int index, axis, rowBitmap, angle;
902

    
903
      for(int[] move: moves)
904
        {
905
        axis     = move[0];
906
        rowBitmap= computeBitmapFromRow( move[1],axis );
907
        angle    = move[2]*(360/mBasicAngles[axis]);
908
        quat     = makeQuaternion(axis,angle);
909

    
910
        for(int j=0; j<mNumCubits; j++)
911
          if( belongsToRotation(j,axis,rowBitmap) )
912
            {
913
            index = mCubits[j].removeRotationNow(quat);
914
            mMesh.setEffectAssociation(j, mCubits[j].computeAssociation(),index);
915
            }
916
        }
917
      }
918
    }
919

    
920
///////////////////////////////////////////////////////////////////////////////////////////////////
921

    
922
  public int getScrambleType()
923
    {
924
    return 0;
925
    }
926

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

    
929
  int computeBitmapFromRow(int rowBitmap, int axis)
930
    {
931
    if( mIsBandaged )
932
      {
933
      int bitmap, initBitmap=0;
934

    
935
      while( initBitmap!=rowBitmap )
936
        {
937
        initBitmap = rowBitmap;
938

    
939
        for(int cubit=0; cubit<mNumCubits; cubit++)
940
          {
941
          bitmap = mCubits[cubit].getRotRow(axis);
942
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
943
          }
944
        }
945
      }
946

    
947
    return rowBitmap;
948
    }
949

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

    
954
  void clampPos(float[] pos, int offset)
955
    {
956
    float currError, minError = Float.MAX_VALUE;
957
    int minErrorIndex1 = -1;
958
    int minErrorIndex2 = -1;
959

    
960
    float x = pos[offset  ];
961
    float y = pos[offset+1];
962
    float z = pos[offset+2];
963

    
964
    float xo,yo,zo;
965

    
966
    for(int i=0; i<mNumCubits; i++)
967
      {
968
      int len = mOrigPos[i].length / 3;
969

    
970
      for(int j=0; j<len; j++)
971
        {
972
        xo = mOrigPos[i][3*j  ];
973
        yo = mOrigPos[i][3*j+1];
974
        zo = mOrigPos[i][3*j+2];
975

    
976
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
977

    
978
        if( currError<minError )
979
          {
980
          minError = currError;
981
          minErrorIndex1 = i;
982
          minErrorIndex2 = j;
983
          }
984
        }
985
      }
986

    
987
    if( minError< 0.1f ) // TODO: 0.1 ?
988
      {
989
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
990
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
991
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
992
      }
993
    }
994

    
995
///////////////////////////////////////////////////////////////////////////////////////////////////
996
// remember about the double cover or unit quaternions!
997

    
998
  int mulQuat(int q1, int q2)
999
    {
1000
    Static4D result = QuatHelper.quatMultiply(mObjectQuats[q1],mObjectQuats[q2]);
1001

    
1002
    float rX = result.get0();
1003
    float rY = result.get1();
1004
    float rZ = result.get2();
1005
    float rW = result.get3();
1006

    
1007
    final float MAX_ERROR = 0.1f;
1008
    float dX,dY,dZ,dW;
1009

    
1010
    for(int i=0; i<mNumQuats; i++)
1011
      {
1012
      dX = mObjectQuats[i].get0() - rX;
1013
      dY = mObjectQuats[i].get1() - rY;
1014
      dZ = mObjectQuats[i].get2() - rZ;
1015
      dW = mObjectQuats[i].get3() - rW;
1016

    
1017
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1018
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1019
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1020
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1021

    
1022
      dX = mObjectQuats[i].get0() + rX;
1023
      dY = mObjectQuats[i].get1() + rY;
1024
      dZ = mObjectQuats[i].get2() + rZ;
1025
      dW = mObjectQuats[i].get3() + rW;
1026

    
1027
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1028
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1029
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1030
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1031
      }
1032

    
1033
    return -1;
1034
    }
1035

    
1036
///////////////////////////////////////////////////////////////////////////////////////////////////
1037

    
1038
  private float getAngle()
1039
    {
1040
    int pointNum = mRotationAngle.getNumPoints();
1041

    
1042
    if( pointNum>=1 )
1043
      {
1044
      return mRotationAngle.getPoint(pointNum-1).get0();
1045
      }
1046
    else
1047
      {
1048
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
1049
      return 0;
1050
      }
1051
    }
1052

    
1053
///////////////////////////////////////////////////////////////////////////////////////////////////
1054

    
1055
  void setLibInterface(ObjectLibInterface inter)
1056
    {
1057
    mInterface = inter;
1058
    }
1059

    
1060
///////////////////////////////////////////////////////////////////////////////////////////////////
1061

    
1062
  void initializeObject(int[][] moves)
1063
    {
1064
    solve();
1065
    setupPosition(moves);
1066
    }
1067

    
1068
///////////////////////////////////////////////////////////////////////////////////////////////////
1069

    
1070
  synchronized void removeRotationNow()
1071
    {
1072
    float angle = getAngle();
1073
    double nearestAngleInRadians = angle*Math.PI/180;
1074
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
1075
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
1076
    float axisX = mAxis[mCurrentRotAxis].get0();
1077
    float axisY = mAxis[mCurrentRotAxis].get1();
1078
    float axisZ = mAxis[mCurrentRotAxis].get2();
1079
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
1080

    
1081
    mRotationAngle.removeAll();
1082
    mRotationAngleStatic.set0(0);
1083

    
1084
    for(int i=0; i<mNumCubits; i++)
1085
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
1086
        {
1087
        int index = mCubits[i].removeRotationNow(quat);
1088
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),index);
1089
        }
1090
    }
1091

    
1092
///////////////////////////////////////////////////////////////////////////////////////////////////
1093

    
1094
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
1095
    {
1096
    if( wasRotateApplied() )
1097
      {
1098
      float angle = getAngle();
1099
      mRotationAngleStatic.set0(angle);
1100
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1101
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1102

    
1103
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1104
      mRotationAngle.resetToBeginning();
1105
      mRotationAngle.removeAll();
1106
      mRotationAngle.add(mRotationAngleStatic);
1107
      mRotationAngle.add(mRotationAngleMiddle);
1108
      mRotationAngle.add(mRotationAngleFinal);
1109
      mRotateEffect.notifyWhenFinished(listener);
1110

    
1111
      return mRotateEffect.getID();
1112
      }
1113

    
1114
    return 0;
1115
    }
1116

    
1117
///////////////////////////////////////////////////////////////////////////////////////////////////
1118

    
1119
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1120
    {
1121
    if( wasRotateApplied() )
1122
      {
1123
      mCurrentRotAxis = axis;
1124
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1125

    
1126
      mRotationAngleStatic.set0(0.0f);
1127
      mRotationAxis.set( mAxis[axis] );
1128
      mRotationAngle.setDuration(durationMillis);
1129
      mRotationAngle.resetToBeginning();
1130
      mRotationAngle.add(new Static1D(0));
1131
      mRotationAngle.add(new Static1D(angle));
1132
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1133
      mRotateEffect.notifyWhenFinished(listener);
1134

    
1135
      return mRotateEffect.getID();
1136
      }
1137

    
1138
    return 0;
1139
    }
1140

    
1141
///////////////////////////////////////////////////////////////////////////////////////////////////
1142

    
1143
  void continueRotation(float angleInDegrees)
1144
    {
1145
    mRotationAngleStatic.set0(angleInDegrees);
1146
    }
1147

    
1148
///////////////////////////////////////////////////////////////////////////////////////////////////
1149

    
1150
  synchronized void beginNewRotation(int axis, int row )
1151
    {
1152
    if( axis<0 || axis>=mNumAxis )
1153
      {
1154
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1155
      return;
1156
      }
1157
    if( row<0 || row>=mNumLayers[axis] )
1158
      {
1159
      android.util.Log.e("object", "invalid rotation row: "+row);
1160
      return;
1161
      }
1162

    
1163
    mCurrentRotAxis = axis;
1164
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1165
    mRotationAngleStatic.set0(0.0f);
1166
    mRotationAxis.set( mAxis[axis] );
1167
    mRotationAngle.add(mRotationAngleStatic);
1168
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1169
    }
1170

    
1171
///////////////////////////////////////////////////////////////////////////////////////////////////
1172

    
1173
  void setTextureMap(int cubit, int face, int newColor)
1174
    {
1175
    final float ratioW = 1.0f/mNumTexCols;
1176
    final float ratioH = 1.0f/mNumTexRows;
1177
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1178
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1179
    int col = newColor%mNumTexCols;
1180

    
1181
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1182
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1183
    }
1184

    
1185
///////////////////////////////////////////////////////////////////////////////////////////////////
1186

    
1187
  private int getCubitFaceColor(int cubit, int face)
1188
    {
1189
    int puzzleFace = getCubitFaceMap(cubit,face);
1190
    if( puzzleFace>=0 ) puzzleFace %= mNumFaceColors;
1191
    return puzzleFace;
1192
    }
1193

    
1194
///////////////////////////////////////////////////////////////////////////////////////////////////
1195

    
1196
  public int getCubitFaceMap(int cubit, int face)
1197
    {
1198
    int numFaces = mCubitFaceColors[cubit].length;
1199
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1200
    return puzzleFace<0 ? -1 : puzzleFace;
1201
    }
1202

    
1203
///////////////////////////////////////////////////////////////////////////////////////////////////
1204

    
1205
  void resetAllTextureMaps()
1206
    {
1207
    final float ratioW = 1.0f/mNumTexCols;
1208
    final float ratioH = 1.0f/mNumTexRows;
1209
    int cubColor, varColor, color, variant, row, col;
1210

    
1211
    for(int cubit=0; cubit<mNumCubits; cubit++)
1212
      {
1213
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1214
      variant = getCubitVariant(cubit,mNumLayers);
1215

    
1216
      for(int face=0; face<mNumCubitFaces; face++)
1217
        {
1218
        cubColor = getCubitFaceColor(cubit,face);
1219
        varColor = getVariantFaceColor(variant,face);
1220
        color    = cubColor<0 || varColor<0 ? mNumTextures : varColor*mNumFaceColors + cubColor;
1221
        row      = (mNumTexRows-1) - color/mNumTexCols;
1222
        col      = color%mNumTexCols;
1223

    
1224
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1225
        }
1226

    
1227
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1228
      }
1229
    }
1230

    
1231
///////////////////////////////////////////////////////////////////////////////////////////////////
1232

    
1233
  void releaseResources()
1234
    {
1235
    mTexture.markForDeletion();
1236
    mMesh.markForDeletion();
1237
    mEffects.markForDeletion();
1238

    
1239
    for(int j=0; j<mNumCubits; j++)
1240
      {
1241
      mCubits[j].releaseResources();
1242
      }
1243
    }
1244

    
1245
///////////////////////////////////////////////////////////////////////////////////////////////////
1246

    
1247
  synchronized void restorePreferences(SharedPreferences preferences)
1248
    {
1249
    boolean error = false;
1250
    String key = getShortName();
1251

    
1252
    for(int i=0; i<mNumCubits; i++)
1253
      {
1254
      mQuatDebug[i] = mCubits[i].restorePreferences(key,i,preferences);
1255

    
1256
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1257
        {
1258
        mCubits[i].modifyCurrentPosition(mObjectQuats[mQuatDebug[i]]);
1259
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),mQuatDebug[i]);
1260
        }
1261
      else
1262
        {
1263
        error = true;
1264
        }
1265
      }
1266

    
1267
    if( error )
1268
      {
1269
      for(int i=0; i<mNumCubits; i++)
1270
        {
1271
        mCubits[i].solve();
1272
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),0);
1273
        }
1274
      }
1275
    }
1276

    
1277
///////////////////////////////////////////////////////////////////////////////////////////////////
1278

    
1279
  void savePreferences(SharedPreferences.Editor editor)
1280
    {
1281
    String key = getShortName();
1282
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(key,i,editor);
1283
    }
1284

    
1285
///////////////////////////////////////////////////////////////////////////////////////////////////
1286

    
1287
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1288
    {
1289
    final float A = 0.8f;  // 0<A<1
1290

    
1291
    int prev = curr>0 ? curr-1 : len-1;
1292
    int next = curr<len-1 ? curr+1 : 0;
1293

    
1294
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1295
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1296
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1297
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1298

    
1299
    float len1= v1x*v1x+v1y*v1y;
1300
    float len2= v2x*v2x+v2y*v2y;
1301

    
1302
    float cos = (v1x*v2x+v1y*v2y) / ( (float)Math.sqrt(len1*len2) );
1303

    
1304
    return 1-A*cos;
1305
    }
1306

    
1307
///////////////////////////////////////////////////////////////////////////////////////////////////
1308

    
1309
  public ObjectSticker retSticker(int sticker)
1310
    {
1311
    if( mStickers==null )
1312
      {
1313
      float rad = getStickerRadius();
1314
      float str = getStickerStroke();
1315
      float[][] angles = getStickerAngles();
1316
      int numStickers = mStickerCoords.length;
1317
      mStickers = new ObjectSticker[numStickers];
1318

    
1319
      for(int s=0; s<numStickers; s++)
1320
        {
1321
        float scale = mStickerScales[s];
1322
        float radius = rad / scale;
1323
        float stroke = str / scale;
1324
        int len = mStickerCoords[s].length/2;
1325
        float[] radii = new float[len];
1326
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1327
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1328
        }
1329
      }
1330

    
1331
    return mStickers[sticker];
1332
    }
1333

    
1334
///////////////////////////////////////////////////////////////////////////////////////////////////
1335
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1336

    
1337
  public void adjustStickerCoords()
1338
    {
1339

    
1340
    }
1341

    
1342
///////////////////////////////////////////////////////////////////////////////////////////////////
1343

    
1344
  public Static4D[] getQuats()
1345
    {
1346
    if( mObjectQuats==null )
1347
      {
1348
      mObjectQuats = QuatGroupGenerator.computeGroup(mAxis,mBasicAngles);
1349
      }
1350

    
1351
    return mObjectQuats;
1352
    }
1353

    
1354
///////////////////////////////////////////////////////////////////////////////////////////////////
1355

    
1356
  public int getInternalColor()
1357
    {
1358
    return COLOR_INTERNAL;
1359
    }
1360

    
1361
///////////////////////////////////////////////////////////////////////////////////////////////////
1362
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1363

    
1364
  private void createTexture()
1365
    {
1366
    Paint paint = new Paint();
1367
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_4444);
1368
    Canvas canvas = new Canvas(mBitmap);
1369

    
1370
    paint.setAntiAlias(true);
1371
    paint.setTextAlign(Paint.Align.CENTER);
1372
    paint.setStyle(Paint.Style.FILL);
1373

    
1374
    paint.setColor(getInternalColor());
1375
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1376

    
1377
    int texture = 0;
1378
    FactorySticker factory = FactorySticker.getInstance();
1379

    
1380
    for(int row=0; row<mNumTexRows; row++)
1381
      for(int col=0; col<mNumTexCols; col++)
1382
        {
1383
        if( texture>=mNumTextures ) break;
1384
        ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1385
        int color = getColor(texture% mNumFaceColors);
1386
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, (mNumTexRows-row)*TEXTURE_HEIGHT, color, sticker);
1387
        texture++;
1388
        }
1389
    }
1390

    
1391
///////////////////////////////////////////////////////////////////////////////////////////////////
1392

    
1393
  void setTexture()
1394
    {
1395
    if( mBitmap==null ) createTexture();
1396

    
1397
    if( !mTexture.setTextureAlreadyInverted(mBitmap) )
1398
      {
1399
      int max = DistortedLibrary.getMaxTextureSize();
1400
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1401
      }
1402
    }
1403

    
1404
///////////////////////////////////////////////////////////////////////////////////////////////////
1405

    
1406
  void setObjectRatioNow(float sc, int nodeSize)
1407
    {
1408
    mObjectScreenRatio = sc;
1409
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1410
    mObjectScale.set(scale,scale,scale);
1411

    
1412
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1413
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1414
    }
1415

    
1416
///////////////////////////////////////////////////////////////////////////////////////////////////
1417

    
1418
  void setObjectRatio(float sizeChange, int nodeSize)
1419
    {
1420
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1421

    
1422
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1423
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1424

    
1425
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1426
    }
1427

    
1428
///////////////////////////////////////////////////////////////////////////////////////////////////
1429

    
1430
  void setNodeSize(int nodeSize)
1431
    {
1432
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1433
    }
1434

    
1435
///////////////////////////////////////////////////////////////////////////////////////////////////
1436

    
1437
  public float getRatio()
1438
    {
1439
    return mObjectScreenRatio;
1440
    }
1441

    
1442
///////////////////////////////////////////////////////////////////////////////////////////////////
1443

    
1444
  public float getObjectRatio()
1445
    {
1446
    return mObjectScreenRatio*mInitScreenRatio;
1447
    }
1448

    
1449
///////////////////////////////////////////////////////////////////////////////////////////////////
1450

    
1451
  boolean isSolved()
1452
    {
1453
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1454
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1455

    
1456
    return false;
1457
    }
1458

    
1459
///////////////////////////////////////////////////////////////////////////////////////////////////
1460

    
1461
  int computeNearestAngle(int axis, float angle, float speed)
1462
    {
1463
    int basicAngle   = mBasicAngles[axis>=mBasicAngles.length ? 0 : axis];
1464
    int nearestAngle = 360/basicAngle;
1465

    
1466
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1467
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1468

    
1469
    if( tmp!=0 ) return nearestAngle*tmp;
1470

    
1471
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1472
    }
1473

    
1474
///////////////////////////////////////////////////////////////////////////////////////////////////
1475
// INTERNAL API - those are called from 'effects' package
1476
///////////////////////////////////////////////////////////////////////////////////////////////////
1477

    
1478
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1479
    {
1480
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1481
    }
1482

    
1483
///////////////////////////////////////////////////////////////////////////////////////////////////
1484

    
1485
  public Static4D getRotationQuat()
1486
    {
1487
    return mQuat;
1488
    }
1489

    
1490
///////////////////////////////////////////////////////////////////////////////////////////////////
1491

    
1492
  public float getSize()
1493
    {
1494
    return mSize;
1495
    }
1496

    
1497
///////////////////////////////////////////////////////////////////////////////////////////////////
1498

    
1499
  public void apply(Effect effect, int position)
1500
    {
1501
    mEffects.apply(effect, position);
1502
    }
1503

    
1504
///////////////////////////////////////////////////////////////////////////////////////////////////
1505

    
1506
  public void remove(long effectID)
1507
    {
1508
    mEffects.abortById(effectID);
1509
    }
1510

    
1511
///////////////////////////////////////////////////////////////////////////////////////////////////
1512

    
1513
  public MeshBase getObjectMesh()
1514
    {
1515
    return mMesh;
1516
    }
1517

    
1518
///////////////////////////////////////////////////////////////////////////////////////////////////
1519

    
1520
  public DistortedEffects getObjectEffects()
1521
    {
1522
    return mEffects;
1523
    }
1524

    
1525
///////////////////////////////////////////////////////////////////////////////////////////////////
1526
// PUBLIC API
1527
///////////////////////////////////////////////////////////////////////////////////////////////////
1528

    
1529
  public int getCubitFaceColorIndex(int cubit, int face)
1530
    {
1531
    Static4D texMap = mMesh.getTextureMap(mNumFaceColors *cubit + face);
1532

    
1533
    int x = (int)(texMap.get0()/texMap.get2());
1534
    int y = (int)(texMap.get1()/texMap.get3());
1535

    
1536
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1537
    }
1538

    
1539
///////////////////////////////////////////////////////////////////////////////////////////////////
1540

    
1541
  public int[] getNumLayers()
1542
    {
1543
    return mNumLayers;
1544
    }
1545

    
1546
///////////////////////////////////////////////////////////////////////////////////////////////////
1547

    
1548
  public synchronized void solve()
1549
    {
1550
    for(int i=0; i<mNumCubits; i++)
1551
      {
1552
      mCubits[i].solve();
1553
      mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(), 0);
1554
      }
1555
    }
1556

    
1557
///////////////////////////////////////////////////////////////////////////////////////////////////
1558

    
1559
  public int getCubitQuatIndex(int cubit)
1560
    {
1561
    return (cubit>=0 && cubit<mNumCubits) ? mCubits[cubit].mQuatIndex : 0;
1562
    }
1563

    
1564
///////////////////////////////////////////////////////////////////////////////////////////////////
1565

    
1566
  public int getCubitRotRow(int cubit, int axis)
1567
    {
1568
    return mCubits[cubit].getRotRow(axis);
1569
    }
1570

    
1571
///////////////////////////////////////////////////////////////////////////////////////////////////
1572

    
1573
  public Bitmap getStickerBitmap()
1574
    {
1575
    return mBitmap;
1576
    }
1577

    
1578
///////////////////////////////////////////////////////////////////////////////////////////////////
1579

    
1580
  public DistortedNode getNode()
1581
    {
1582
    return mNode;
1583
    }
1584

    
1585
///////////////////////////////////////////////////////////////////////////////////////////////////
1586

    
1587
  public int getNumStickerTypes()
1588
    {
1589
    return mNumStickerTypes;
1590
    }
1591

    
1592
///////////////////////////////////////////////////////////////////////////////////////////////////
1593
// this is here only so it can be overridden in TwistyJSON soo that we can get this from JSON.
1594

    
1595
  public int getNumCubitFaces()
1596
    {
1597
    return 0;
1598
    }
1599

    
1600
///////////////////////////////////////////////////////////////////////////////////////////////////
1601

    
1602
  public TouchControl getTouchControl()
1603
    {
1604
    if( mTouchControl==null )
1605
      {
1606
      switch(getTouchControlType())
1607
        {
1608
        case TC_TETRAHEDRON      : mTouchControl = new TouchControlTetrahedron(this);
1609
                                   break;
1610
        case TC_HEXAHEDRON       : mTouchControl = new TouchControlHexahedron(this);
1611
                                   break;
1612
        case TC_OCTAHEDRON       : mTouchControl = new TouchControlOctahedron(this);
1613
                                   break;
1614
        case TC_DODECAHEDRON     : mTouchControl = new TouchControlDodecahedron(this);
1615
                                   break;
1616
        case TC_CUBOID           : int[] numLayers = getNumLayers();
1617
                                   mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1618
                                   break;
1619
        case TC_CHANGING_MIRROR  : mTouchControl = new TouchControlMirror(this);
1620
                                   break;
1621
        case TC_CHANGING_SQUARE  : mTouchControl = new TouchControlSquare(this);
1622
                                   break;
1623
        case TC_CHANGING_SHAPEMOD: mTouchControl = new TouchControlShapemod(this);
1624
                                   break;
1625
        }
1626
      }
1627
    return mTouchControl;
1628
    }
1629

    
1630
///////////////////////////////////////////////////////////////////////////////////////////////////
1631

    
1632
  protected void setReader(JsonReader reader)
1633
    {
1634
    // empty
1635
    }
1636

    
1637
///////////////////////////////////////////////////////////////////////////////////////////////////
1638
  // for JSON only
1639
  public abstract int getTouchControlType();
1640
  public abstract int getTouchControlSplit();
1641
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1642
  public abstract int[][][] getEnabled();
1643
  public abstract float[] getDist3D(int[] numLayers);
1644
  public abstract Static3D[] getFaceAxis();
1645
  public abstract ScrambleState[] getScrambleStates();
1646
  public abstract float[][] getCuts(int[] numLayers);
1647
  public abstract float getStickerRadius();
1648
  public abstract float getStickerStroke();
1649
  public abstract float[][] getStickerAngles();
1650
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1651
  public abstract ObjectShape getObjectShape(int variant);
1652
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
1653
  public abstract int getNumCubitVariants(int[] numLayers);
1654
  public abstract float[][] getCubitPositions(int[] numLayers);
1655
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
1656
  public abstract int getNumFaceColors();
1657
  public abstract float getScreenRatio();
1658
  public abstract int getColor(int face);
1659
  public abstract String getShortName();
1660
  public abstract long getSignature();
1661

    
1662
  // not only for JSON
1663
  public abstract Static3D[] getRotationAxis();
1664
  public abstract int[] getBasicAngles();
1665
  public abstract int getNumFaces();
1666
  public abstract String getObjectName();
1667
  public abstract String getInventor();
1668
  public abstract int getYearOfInvention();
1669
  public abstract int getComplexity();
1670
  public abstract int getFOV();
1671
  public abstract String[][] getTutorials();
1672
  }
(11-11/12)