Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ 05b0a7dd

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.helpers.ScrambleState;
60
import org.distorted.objectlib.json.JsonReader;
61
import org.distorted.objectlib.touchcontrol.*;
62

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

    
65
///////////////////////////////////////////////////////////////////////////////////////////////////
66

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

    
72
  public static final int COLOR_YELLOW  = 0xffffff00;
73
  public static final int COLOR_WHITE   = 0xffffffff;
74
  public static final int COLOR_BLUE    = 0xff0000ff;
75
  public static final int COLOR_GREEN   = 0xff00bb00;
76
  public static final int COLOR_RED     = 0xff990000;
77
  public static final int COLOR_ORANGE  = 0xffff6200;
78
  public static final int COLOR_GREY    = 0xff727c7b;
79
  public static final int COLOR_VIOLET  = 0xff7700bb;
80
  public static final int COLOR_STROKE  = 0xff000000;
81
  private static final int COLOR_INTERNAL= 0xff222222;
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 float[][] mStickerCoords;
98
  protected Static4D[] mObjectQuats;
99
  int mNumAxis, mMaxNumLayers;
100

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

    
146
  //////////////////// SOLVED1 ////////////////////////
147

    
148
  private int[] mFaceMap;
149
  private int[][] mScramble;
150
  private int[] mColors;
151

    
152
///////////////////////////////////////////////////////////////////////////////////////////////////
153

    
154
  TwistyObject(InputStream jsonStream, int meshState, Static4D quat, Static3D move, float scale, InputStream meshStream)
155
    {
156
    JsonReader reader = JsonReader.getInstance();
157
    reader.parseJsonFile(jsonStream);
158
    setReader(reader);
159

    
160
    mNumLayers = reader.getNumLayers();
161
    mSize      = reader.getSize();
162
    initialize(meshState,quat,move,scale,meshStream,true);
163
    }
164

    
165
///////////////////////////////////////////////////////////////////////////////////////////////////
166

    
167
  TwistyObject(int[] numLayers, int meshState, float size, Static4D quat, Static3D move, float scale, InputStream meshStream)
168
    {
169
    mNumLayers = numLayers;
170
    mSize      = size;
171
    initialize(meshState,quat,move,scale,meshStream,false);
172
    }
173

    
174
///////////////////////////////////////////////////////////////////////////////////////////////////
175

    
176
  private void initialize(int meshState,Static4D quat, Static3D move, float scale, InputStream stream, boolean fromJSON)
177
    {
178
    mQuat = quat;
179
    mAxis = getRotationAxis();
180
    mInitScreenRatio = getScreenRatio();
181
    mSolvedFunctionIndex = getSolvedFunctionIndex();
182
    mBasicAngles = getBasicAngles();
183
    mObjectQuats = getQuats();
184
    mNumQuats = mObjectQuats.length;
185
    mOrigPos = getCubitPositions(mNumLayers);
186

    
187
    int numAxis = mAxis.length;
188
    mMaxNumLayers = -1;
189
    mCuts = getCuts(mNumLayers);
190
    mNumCuts = new int[numAxis];
191
    for(int i=0; i<numAxis; i++)
192
      {
193
      if( mMaxNumLayers<mNumLayers[i] ) mMaxNumLayers = mNumLayers[i];
194
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
195
      }
196

    
197
    mNumCubits = mOrigPos.length;
198
    mNumFaceColors = getNumFaceColors();
199
    mNumAxis = mAxis.length;
200

    
201
    int scramblingType = getScrambleType();
202
    ScrambleState[] states = getScrambleStates();
203
    mScrambler = new TwistyObjectScrambler(scramblingType, mNumAxis,mNumLayers,states);
204

    
205
    boolean bandaged=false;
206

    
207
    for( int c=0; c<mNumCubits; c++)
208
      {
209
      if( mOrigPos[c].length>3 )
210
        {
211
        bandaged=true;
212
        break;
213
        }
214
      }
215

    
216
    mIsBandaged = bandaged;
217
    mQuatDebug = new int[mNumCubits];
218

    
219
    mRotationAngle= new Dynamic1D();
220
    mRotationAxis = new Static3D(1,0,0);
221
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
222

    
223
    mRotationAngleStatic = new Static1D(0);
224
    mRotationAngleMiddle = new Static1D(0);
225
    mRotationAngleFinal  = new Static1D(0);
226

    
227
    mObjectScale = new Static3D(scale,scale,scale);
228
    setObjectRatioNow(scale,720);
229

    
230
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
231
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
232
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
233

    
234
    boolean fromDMESH = (stream!=null && meshState==MESH_NICE);
235
    getQuatsAndShapes(fromDMESH,fromJSON);
236
    createMeshAndCubits(stream,meshState,fromDMESH);
237
    setUpTextures(fromDMESH,fromJSON);
238
    createDataStructuresForSolved();
239

    
240
    mEffects = new DistortedEffects();
241

    
242
    for( int q=0; q<mNumQuats; q++)
243
      {
244
      VertexEffectQuaternion vq = new VertexEffectQuaternion(mObjectQuats[q],CENTER);
245
      vq.setMeshAssociation(0,q);
246
      mEffects.apply(vq);
247
      }
248

    
249
    mEffects.apply(mRotateEffect);
250
    mEffects.apply(quatEffect);
251
    mEffects.apply(scaleEffect);
252
    mEffects.apply(moveEffect);
253

    
254
    mNode = new DistortedNode(mTexture,mEffects,mMesh);
255
    }
256

    
257
///////////////////////////////////////////////////////////////////////////////////////////////////
258

    
259
  private Static3D getPos(float[] origPos)
260
    {
261
    int len = origPos.length/3;
262
    float sumX = 0.0f;
263
    float sumY = 0.0f;
264
    float sumZ = 0.0f;
265

    
266
    for(int i=0; i<len; i++)
267
      {
268
      sumX += origPos[3*i  ];
269
      sumY += origPos[3*i+1];
270
      sumZ += origPos[3*i+2];
271
      }
272

    
273
    sumX /= len;
274
    sumY /= len;
275
    sumZ /= len;
276

    
277
    return new Static3D(sumX,sumY,sumZ);
278
    }
279

    
280
///////////////////////////////////////////////////////////////////////////////////////////////////
281

    
282
  private void createOuterFaces()
283
    {
284
    for(int v=0; v<mNumCubitVariants; v++)
285
      {
286
      int[][] indices = mShapes[v].getVertIndices();
287
      int faces = indices.length;
288
      mVariantFaceIsOuter[v] = new int[faces];
289
      }
290

    
291
    for( int cubit=0; cubit<mNumCubits; cubit++)
292
      {
293
      int variant = getCubitVariant(cubit,mNumLayers);
294
      int[][] indices = mShapes[variant].getVertIndices();
295
      int numFaces = indices.length;
296

    
297
      for(int face=0; face<numFaces; face++)
298
        if( getCubitFaceColor(cubit,face)>=0 )
299
          {
300
          mVariantFaceIsOuter[variant][face] = 1;
301
          }
302
      }
303
    }
304

    
305
///////////////////////////////////////////////////////////////////////////////////////////////////
306

    
307
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
308
    {
309
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
310

    
311
    if( !fromDMESH || !fromJSON )
312
      {
313
      FactoryCubit factory = FactoryCubit.getInstance();
314
      factory.clear();
315

    
316
      mOrigQuat = new Static4D[mNumCubits];
317
      for(int i=0; i<mNumCubits; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
318

    
319
      mShapes = new ObjectShape[mNumCubitVariants];
320
      for(int i=0; i<mNumCubitVariants; i++) mShapes[i] = getObjectShape(i);
321
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
322
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
323

    
324
      if( !fromJSON )
325
        {
326
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
327
        createOuterFaces();
328
        }
329

    
330
      if( fromDMESH )
331
        {
332
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
333
        }
334
      }
335
    }
336

    
337
///////////////////////////////////////////////////////////////////////////////////////////////////
338

    
339
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH)
340
    {
341
    mCubits = new Cubit[mNumCubits];
342

    
343
    if( fromDMESH )
344
      {
345
      DataInputStream dos = new DataInputStream(stream);
346
      mMesh = new MeshFile(dos);
347

    
348
      try
349
        {
350
        stream.close();
351
        }
352
      catch(IOException e)
353
        {
354
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
355
        }
356

    
357
      for(int i=0; i<mNumCubits; i++)
358
        {
359
        mCubits[i] = new Cubit(this,mOrigPos[i], mNumAxis);
360
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(), 0);
361
        }
362
      }
363
    else
364
      {
365
      MeshBase[] cubitMesh = new MeshBase[mNumCubits];
366

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

    
376
      mMesh = new MeshJoined(cubitMesh);
377
      }
378
    }
379

    
380
///////////////////////////////////////////////////////////////////////////////////////////////////
381

    
382
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState, int numComponents)
383
    {
384
    int variant = getCubitVariant(cubit,numLayers);
385

    
386
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
387

    
388
    if( mMeshes[variant]==null )
389
      {
390
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
391
      FactoryCubit factory = FactoryCubit.getInstance();
392
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
393
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,meshState, numComponents);
394
      }
395

    
396
    MeshBase mesh = mMeshes[variant].copy(true);
397
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
398
    mesh.apply(quat,0xffffffff,0);
399

    
400
    return mesh;
401
    }
402

    
403
///////////////////////////////////////////////////////////////////////////////////////////////////
404

    
405
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
406
    {
407
    mTexture = new DistortedTexture();
408

    
409
    if( fromJSON )
410
      {
411
      mNumStickerTypes = getNumStickerTypes();
412
      mNumCubitFaces = getNumCubitFaces();
413
      }
414
    else
415
      {
416
      FactoryCubit factory = FactoryCubit.getInstance();
417
      mStickerCoords   = factory.getOuterStickerCoords();
418
      mStickerVariants = factory.getStickerVariants();
419
      mStickerScales   = factory.getOuterStickerScales();
420
      mNumStickerTypes = mStickerCoords.length;
421
      adjustStickerCoords();
422
      }
423

    
424
    mNumTextures= mNumFaceColors *mNumStickerTypes;
425
    mNumTexCols = NUM_STICKERS_IN_ROW;
426
    mNumTexRows = (mNumTextures+1)/NUM_STICKERS_IN_ROW;
427
    if( mNumTexCols*mNumTexRows < mNumTextures+1 ) mNumTexRows++;
428

    
429
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
430
    setTexture();
431
    }
432

    
433
///////////////////////////////////////////////////////////////////////////////////////////////////
434

    
435
  private int getMultQuat(int index1, int index2)
436
    {
437
    if( mQuatMult==null )
438
      {
439
      mQuatMult = new int[mNumQuats][mNumQuats];
440

    
441
      for(int i=0; i<mNumQuats; i++)
442
        for(int j=0; j<mNumQuats; j++) mQuatMult[i][j] = -1;
443
      }
444

    
445
    if( mQuatMult[index1][index2]==-1 )
446
      {
447
      mQuatMult[index1][index2] = mulQuat(index1,index2);
448
      }
449

    
450
    return mQuatMult[index1][index2];
451
    }
452

    
453
///////////////////////////////////////////////////////////////////////////////////////////////////
454

    
455
  public int getVariantFaceColor(int variant, int face)
456
    {
457
    return face>=mStickerVariants[variant].length ? -1 : mStickerVariants[variant][face];
458
    }
459

    
460
///////////////////////////////////////////////////////////////////////////////////////////////////
461

    
462
  public boolean shouldResetTextureMaps()
463
    {
464
    return false;
465
    }
466

    
467
///////////////////////////////////////////////////////////////////////////////////////////////////
468

    
469
  private void createDataStructuresForSolved()
470
    {
471
    mTmpQuats = new int[mNumQuats];
472
    mSolvedQuats = getSolvedQuats();
473
    }
474

    
475
///////////////////////////////////////////////////////////////////////////////////////////////////
476
// This is used to build internal data structures for the generic 'isSolved()'
477
//
478
// if this is an internal cubit (all faces black): return -1
479
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
480
// Color index, i.e. the index into the 'FACE_COLORS' table.
481
// else (edge or corner cubit, more than one non-black face): return -2.
482

    
483
  protected int retCubitSolvedStatus(int cubit)
484
    {
485
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
486
    int variant = getCubitVariant(cubit,mNumLayers);
487

    
488
    for(int face=0; face<mNumCubitFaces; face++)
489
      {
490
      varColor = getVariantFaceColor(variant,face);
491
      cubColor = getCubitFaceMap(cubit,face);
492

    
493
      if( varColor>=0 && cubColor>=0 )
494
        {
495
        numNonBlack++;
496
        nonBlackIndex = cubColor;
497
        }
498
      }
499

    
500
    if( numNonBlack==0 ) return -1;
501
    if( numNonBlack>=2 ) return -2;
502

    
503
    return nonBlackIndex;
504
    }
505

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

    
508
  protected int[] buildSolvedQuats(Static3D faceAx)
509
    {
510
    final float MAXD = 0.0001f;
511
    float x = faceAx.get0();
512
    float y = faceAx.get1();
513
    float z = faceAx.get2();
514
    float a,dx,dy,dz,qx,qy,qz;
515
    Static4D quat;
516
    int place = 0;
517

    
518
    for(int q=1; q<mNumQuats; q++)
519
      {
520
      quat = mObjectQuats[q];
521
      qx = quat.get0();
522
      qy = quat.get1();
523
      qz = quat.get2();
524

    
525
           if( x!=0.0f ) { a = qx/x; }
526
      else if( y!=0.0f ) { a = qy/y; }
527
      else               { a = qz/z; }
528

    
529
      dx = a*x-qx;
530
      dy = a*y-qy;
531
      dz = a*z-qz;
532

    
533
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
534
        {
535
        mTmpQuats[place++] = q;
536
        }
537
      }
538

    
539
    if( place!=0 )
540
      {
541
      int[] ret = new int[place];
542
      System.arraycopy(mTmpQuats,0,ret,0,place);
543
      return ret;
544
      }
545

    
546
    return null;
547
    }
548

    
549
///////////////////////////////////////////////////////////////////////////////////////////////////
550

    
551
  public int[][] getSolvedQuats()
552
    {
553
    int[] groups = new int[mNumCubits];
554
    int numGroups = 1;
555
    int numFirst  = 0;
556

    
557
    for(int cubit=0; cubit<mNumCubits; cubit++)
558
      {
559
      groups[cubit] = retCubitSolvedStatus(cubit);
560
      if( groups[cubit]>=0 ) numGroups++;
561
      else                   numFirst++;
562
      }
563

    
564
    int firstIndex = 1;
565
    int groupIndex = 1;
566
    int[][] solvedQuats = new int[numGroups][];
567
    solvedQuats[0] = new int[1+numFirst];
568
    solvedQuats[0][0] = numFirst;
569
    Static3D[] axis = getFaceAxis();
570

    
571
    for(int cubit=0; cubit<mNumCubits; cubit++)
572
      {
573
      int group = groups[cubit];
574

    
575
      if( group<0 )
576
        {
577
        solvedQuats[0][firstIndex] = cubit;
578
        firstIndex++;
579
        }
580
      else
581
        {
582
        int[] quats = buildSolvedQuats(axis[group]);
583
        int len = quats==null ? 0 : quats.length;
584
        solvedQuats[groupIndex] = new int[2+len];
585
        solvedQuats[groupIndex][0] = 1;
586
        solvedQuats[groupIndex][1] = cubit;
587
        for(int i=0; i<len; i++) solvedQuats[groupIndex][i+2] = quats[i];
588
        groupIndex++;
589
        }
590
      }
591
/*
592
    String dbg = "SOLVED GROUPS:\n";
593

    
594
    for(int g=0; g<numGroups; g++)
595
      {
596
      int len = solvedQuats[g].length;
597
      for(int i=0; i<len; i++) dbg += (" "+solvedQuats[g][i]);
598
      dbg+="\n";
599
      }
600

    
601
    android.util.Log.e("D", dbg);
602
*/
603
    return solvedQuats;
604
    }
605

    
606
///////////////////////////////////////////////////////////////////////////////////////////////////
607

    
608
  public int getSolvedFunctionIndex()
609
    {
610
    return 0;
611
    }
612

    
613
///////////////////////////////////////////////////////////////////////////////////////////////////
614

    
615
  private boolean isSolved0()
616
    {
617
    for( int[] solvedQuat : mSolvedQuats )
618
      {
619
      int numCubits = solvedQuat[0];
620
      int firstCubit= solvedQuat[1];
621
      int quat = mCubits[firstCubit].mQuatIndex;
622

    
623
      for( int cubit=2; cubit<=numCubits; cubit++ )
624
        {
625
        int c = solvedQuat[cubit];
626
        if( quat != mCubits[c].mQuatIndex ) return false;
627
        }
628
      }
629

    
630
    int cubit= mSolvedQuats[0][1];
631
    int quat0= mCubits[cubit].mQuatIndex;
632
    int numGroups = mSolvedQuats.length;
633

    
634
    for(int group=1; group<numGroups; group++)
635
      {
636
      int firstCubit= mSolvedQuats[group][1];
637
      int currQuat  = mCubits[firstCubit].mQuatIndex;
638

    
639
      if( quat0==currQuat ) continue;
640

    
641
      boolean isGood= false;
642
      int numEntries= mSolvedQuats[group].length;
643
      int numCubits = mSolvedQuats[group][0];
644

    
645
      for(int q=numCubits+1; q<numEntries; q++)
646
        {
647
        int quat = mSolvedQuats[group][q];
648

    
649
        if( quat0 == getMultQuat(currQuat,quat) )
650
          {
651
          isGood = true;
652
          break;
653
          }
654
        }
655

    
656
      if( !isGood ) return false;
657
      }
658

    
659
    return true;
660
    }
661

    
662
///////////////////////////////////////////////////////////////////////////////////////////////////
663

    
664
  private int computeScramble(int quatNum, int centerNum)
665
    {
666
    float MAXDIFF = 0.01f;
667
    float[] center= mOrigPos[centerNum];
668
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
669
    Static4D result = QuatHelper.rotateVectorByQuat(sc,mObjectQuats[quatNum]);
670

    
671
    float x = result.get0();
672
    float y = result.get1();
673
    float z = result.get2();
674

    
675
    for(int c=0; c<mNumCubits; c++)
676
      {
677
      float[] cent = mOrigPos[c];
678

    
679
      float qx = cent[0] - x;
680
      float qy = cent[1] - y;
681
      float qz = cent[2] - z;
682

    
683
      if( qx>-MAXDIFF && qx<MAXDIFF &&
684
          qy>-MAXDIFF && qy<MAXDIFF &&
685
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
686
      }
687

    
688
    return -1;
689
    }
690

    
691
///////////////////////////////////////////////////////////////////////////////////////////////////
692
// Dino4 uses this. It is solved if and only if groups of cubits
693
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
694
// or
695
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
696
// are all the same color.
697

    
698
  private boolean isSolved1()
699
    {
700
    if( mScramble==null )
701
      {
702
      mScramble = new int[mNumQuats][mNumCubits];
703
      mColors   = new int[mNumCubits];
704

    
705
      for(int q=0; q<mNumQuats; q++)
706
        for(int c=0; c<mNumCubits; c++) mScramble[q][c] = computeScramble(q,c);
707
      }
708

    
709
    if( mFaceMap==null )
710
      {
711
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
712
      }
713

    
714
    for(int c=0; c<mNumCubits; c++)
715
      {
716
      int index = mScramble[mCubits[c].mQuatIndex][c];
717
      mColors[index] = mFaceMap[c];
718
      }
719

    
720
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
721
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
722
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
723

    
724
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
725
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
726
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
727

    
728
    return false;
729
    }
730

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

    
733
  int computeRow(float[] pos, int axisIndex)
734
    {
735
    int ret=0;
736
    int len = pos.length / 3;
737
    Static3D axis = mAxis[axisIndex];
738
    float axisX = axis.get0();
739
    float axisY = axis.get1();
740
    float axisZ = axis.get2();
741
    float casted;
742

    
743
    for(int i=0; i<len; i++)
744
      {
745
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
746
      ret |= computeSingleRow(axisIndex,casted);
747
      }
748

    
749
    return ret;
750
    }
751

    
752
///////////////////////////////////////////////////////////////////////////////////////////////////
753

    
754
  private int computeSingleRow(int axisIndex,float casted)
755
    {
756
    int num = mNumCuts[axisIndex];
757

    
758
    for(int i=0; i<num; i++)
759
      {
760
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
761
      }
762

    
763
    return (1<<num);
764
    }
765

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

    
768
  private boolean wasRotateApplied()
769
    {
770
    return mEffects.exists(mRotateEffect.getID());
771
    }
772

    
773
///////////////////////////////////////////////////////////////////////////////////////////////////
774

    
775
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
776
    {
777
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
778
    }
779

    
780
///////////////////////////////////////////////////////////////////////////////////////////////////
781
// note the minus in front of the sin() - we rotate counterclockwise
782
// when looking towards the direction where the axis increases in values.
783

    
784
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
785
    {
786
    Static3D axis = mAxis[axisIndex];
787

    
788
    while( angleInDegrees<0 ) angleInDegrees += 360;
789
    angleInDegrees %= 360;
790
    
791
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
792
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
793

    
794
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
795
    }
796

    
797
///////////////////////////////////////////////////////////////////////////////////////////////////
798

    
799
  private synchronized void setupPosition(int[][] moves)
800
    {
801
    if( moves!=null )
802
      {
803
      Static4D quat;
804
      int index, axis, rowBitmap, angle;
805

    
806
      for(int[] move: moves)
807
        {
808
        axis     = move[0];
809
        rowBitmap= move[1];
810
        angle    = move[2]*(360/mBasicAngles[axis]);
811
        quat     = makeQuaternion(axis,angle);
812

    
813
        for(int j=0; j<mNumCubits; j++)
814
          if( belongsToRotation(j,axis,rowBitmap) )
815
            {
816
            index = mCubits[j].removeRotationNow(quat);
817
            mMesh.setEffectAssociation(j, mCubits[j].computeAssociation(),index);
818
            }
819
        }
820
      }
821
    }
822

    
823
///////////////////////////////////////////////////////////////////////////////////////////////////
824

    
825
  public int getScrambleType()
826
    {
827
    return 0;
828
    }
829

    
830
///////////////////////////////////////////////////////////////////////////////////////////////////
831

    
832
  int computeBitmapFromRow(int rowBitmap, int axis)
833
    {
834
    if( mIsBandaged )
835
      {
836
      int bitmap, initBitmap=0;
837

    
838
      while( initBitmap!=rowBitmap )
839
        {
840
        initBitmap = rowBitmap;
841

    
842
        for(int cubit=0; cubit<mNumCubits; cubit++)
843
          {
844
          bitmap = mCubits[cubit].getRotRow(axis);
845
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
846
          }
847
        }
848
      }
849

    
850
    return rowBitmap;
851
    }
852

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

    
857
  void clampPos(float[] pos, int offset)
858
    {
859
    float currError, minError = Float.MAX_VALUE;
860
    int minErrorIndex1 = -1;
861
    int minErrorIndex2 = -1;
862

    
863
    float x = pos[offset  ];
864
    float y = pos[offset+1];
865
    float z = pos[offset+2];
866

    
867
    float xo,yo,zo;
868

    
869
    for(int i=0; i<mNumCubits; i++)
870
      {
871
      int len = mOrigPos[i].length / 3;
872

    
873
      for(int j=0; j<len; j++)
874
        {
875
        xo = mOrigPos[i][3*j  ];
876
        yo = mOrigPos[i][3*j+1];
877
        zo = mOrigPos[i][3*j+2];
878

    
879
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
880

    
881
        if( currError<minError )
882
          {
883
          minError = currError;
884
          minErrorIndex1 = i;
885
          minErrorIndex2 = j;
886
          }
887
        }
888
      }
889

    
890
    if( minError< 0.1f ) // TODO: 0.1 ?
891
      {
892
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
893
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
894
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
895
      }
896
    }
897

    
898
///////////////////////////////////////////////////////////////////////////////////////////////////
899
// remember about the double cover or unit quaternions!
900

    
901
  int mulQuat(int q1, int q2)
902
    {
903
    Static4D result = QuatHelper.quatMultiply(mObjectQuats[q1],mObjectQuats[q2]);
904

    
905
    float rX = result.get0();
906
    float rY = result.get1();
907
    float rZ = result.get2();
908
    float rW = result.get3();
909

    
910
    final float MAX_ERROR = 0.1f;
911
    float dX,dY,dZ,dW;
912

    
913
    for(int i=0; i<mNumQuats; i++)
914
      {
915
      dX = mObjectQuats[i].get0() - rX;
916
      dY = mObjectQuats[i].get1() - rY;
917
      dZ = mObjectQuats[i].get2() - rZ;
918
      dW = mObjectQuats[i].get3() - rW;
919

    
920
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
921
          dY<MAX_ERROR && dY>-MAX_ERROR &&
922
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
923
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
924

    
925
      dX = mObjectQuats[i].get0() + rX;
926
      dY = mObjectQuats[i].get1() + rY;
927
      dZ = mObjectQuats[i].get2() + rZ;
928
      dW = mObjectQuats[i].get3() + rW;
929

    
930
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
931
          dY<MAX_ERROR && dY>-MAX_ERROR &&
932
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
933
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
934
      }
935

    
936
    return -1;
937
    }
938

    
939
///////////////////////////////////////////////////////////////////////////////////////////////////
940

    
941
  private float getAngle()
942
    {
943
    int pointNum = mRotationAngle.getNumPoints();
944

    
945
    if( pointNum>=1 )
946
      {
947
      return mRotationAngle.getPoint(pointNum-1).get0();
948
      }
949
    else
950
      {
951
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
952
      return 0;
953
      }
954
    }
955

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

    
958
  void setLibInterface(ObjectLibInterface inter)
959
    {
960
    mInterface = inter;
961
    }
962

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

    
965
  void initializeObject(int[][] moves)
966
    {
967
    solve();
968
    setupPosition(moves);
969
    }
970

    
971
///////////////////////////////////////////////////////////////////////////////////////////////////
972

    
973
  synchronized void removeRotationNow()
974
    {
975
    float angle = getAngle();
976
    double nearestAngleInRadians = angle*Math.PI/180;
977
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
978
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
979
    float axisX = mAxis[mCurrentRotAxis].get0();
980
    float axisY = mAxis[mCurrentRotAxis].get1();
981
    float axisZ = mAxis[mCurrentRotAxis].get2();
982
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
983

    
984
    mRotationAngle.removeAll();
985
    mRotationAngleStatic.set0(0);
986

    
987
    for(int i=0; i<mNumCubits; i++)
988
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
989
        {
990
        int index = mCubits[i].removeRotationNow(quat);
991
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),index);
992
        }
993
    }
994

    
995
///////////////////////////////////////////////////////////////////////////////////////////////////
996

    
997
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
998
    {
999
    if( wasRotateApplied() )
1000
      {
1001
      float angle = getAngle();
1002
      mRotationAngleStatic.set0(angle);
1003
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1004
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1005

    
1006
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1007
      mRotationAngle.resetToBeginning();
1008
      mRotationAngle.removeAll();
1009
      mRotationAngle.add(mRotationAngleStatic);
1010
      mRotationAngle.add(mRotationAngleMiddle);
1011
      mRotationAngle.add(mRotationAngleFinal);
1012
      mRotateEffect.notifyWhenFinished(listener);
1013

    
1014
      return mRotateEffect.getID();
1015
      }
1016

    
1017
    return 0;
1018
    }
1019

    
1020
///////////////////////////////////////////////////////////////////////////////////////////////////
1021

    
1022
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1023
    {
1024
    if( wasRotateApplied() )
1025
      {
1026
      mCurrentRotAxis = axis;
1027
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1028

    
1029
      mRotationAngleStatic.set0(0.0f);
1030
      mRotationAxis.set( mAxis[axis] );
1031
      mRotationAngle.setDuration(durationMillis);
1032
      mRotationAngle.resetToBeginning();
1033
      mRotationAngle.add(new Static1D(0));
1034
      mRotationAngle.add(new Static1D(angle));
1035
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1036
      mRotateEffect.notifyWhenFinished(listener);
1037

    
1038
      return mRotateEffect.getID();
1039
      }
1040

    
1041
    return 0;
1042
    }
1043

    
1044
///////////////////////////////////////////////////////////////////////////////////////////////////
1045

    
1046
  void continueRotation(float angleInDegrees)
1047
    {
1048
    mRotationAngleStatic.set0(angleInDegrees);
1049
    }
1050

    
1051
///////////////////////////////////////////////////////////////////////////////////////////////////
1052

    
1053
  synchronized void beginNewRotation(int axis, int row )
1054
    {
1055
    if( axis<0 || axis>=mNumAxis )
1056
      {
1057
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1058
      return;
1059
      }
1060
    if( row<0 || row>=mNumLayers[axis] )
1061
      {
1062
      android.util.Log.e("object", "invalid rotation row: "+row);
1063
      return;
1064
      }
1065

    
1066
    mCurrentRotAxis = axis;
1067
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1068
    mRotationAngleStatic.set0(0.0f);
1069
    mRotationAxis.set( mAxis[axis] );
1070
    mRotationAngle.add(mRotationAngleStatic);
1071
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1072
    }
1073

    
1074
///////////////////////////////////////////////////////////////////////////////////////////////////
1075

    
1076
  void setTextureMap(int cubit, int face, int newColor)
1077
    {
1078
    final float ratioW = 1.0f/mNumTexCols;
1079
    final float ratioH = 1.0f/mNumTexRows;
1080
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1081
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1082
    int col = newColor%mNumTexCols;
1083

    
1084
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1085
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1086
    }
1087

    
1088
///////////////////////////////////////////////////////////////////////////////////////////////////
1089

    
1090
  private int getCubitFaceColor(int cubit, int face)
1091
    {
1092
    int puzzleFace = getCubitFaceMap(cubit,face);
1093
    if( puzzleFace>=0 ) puzzleFace %= mNumFaceColors;
1094
    return puzzleFace;
1095
    }
1096

    
1097
///////////////////////////////////////////////////////////////////////////////////////////////////
1098

    
1099
  public int getCubitFaceMap(int cubit, int face)
1100
    {
1101
    int numFaces = mCubitFaceColors[cubit].length;
1102
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1103
    return puzzleFace<0 ? -1 : puzzleFace;
1104
    }
1105

    
1106
///////////////////////////////////////////////////////////////////////////////////////////////////
1107

    
1108
  void resetAllTextureMaps()
1109
    {
1110
    final float ratioW = 1.0f/mNumTexCols;
1111
    final float ratioH = 1.0f/mNumTexRows;
1112
    int cubColor, varColor, color, variant, row, col;
1113

    
1114
    for(int cubit=0; cubit<mNumCubits; cubit++)
1115
      {
1116
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1117
      variant = getCubitVariant(cubit,mNumLayers);
1118

    
1119
      for(int face=0; face<mNumCubitFaces; face++)
1120
        {
1121
        cubColor = getCubitFaceColor(cubit,face);
1122
        varColor = getVariantFaceColor(variant,face);
1123
        color    = cubColor<0 || varColor<0 ? mNumTextures : varColor*mNumFaceColors + cubColor;
1124
        row      = (mNumTexRows-1) - color/mNumTexCols;
1125
        col      = color%mNumTexCols;
1126

    
1127
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1128
        }
1129

    
1130
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1131
      }
1132
    }
1133

    
1134
///////////////////////////////////////////////////////////////////////////////////////////////////
1135

    
1136
  void releaseResources()
1137
    {
1138
    mTexture.markForDeletion();
1139
    mMesh.markForDeletion();
1140
    mEffects.markForDeletion();
1141

    
1142
    for(int j=0; j<mNumCubits; j++)
1143
      {
1144
      mCubits[j].releaseResources();
1145
      }
1146
    }
1147

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

    
1150
  synchronized void restorePreferences(SharedPreferences preferences)
1151
    {
1152
    boolean error = false;
1153

    
1154
    for(int i=0; i<mNumCubits; i++)
1155
      {
1156
      mQuatDebug[i] = mCubits[i].restorePreferences(preferences);
1157

    
1158
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1159
        {
1160
        mCubits[i].modifyCurrentPosition(mObjectQuats[mQuatDebug[i]]);
1161
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),mQuatDebug[i]);
1162
        }
1163
      else
1164
        {
1165
        error = true;
1166
        }
1167
      }
1168

    
1169
    if( error )
1170
      {
1171
      for(int i=0; i<mNumCubits; i++)
1172
        {
1173
        mCubits[i].solve();
1174
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),0);
1175
        }
1176
      }
1177
    }
1178

    
1179
///////////////////////////////////////////////////////////////////////////////////////////////////
1180

    
1181
  void savePreferences(SharedPreferences.Editor editor)
1182
    {
1183
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(editor);
1184
    }
1185

    
1186
///////////////////////////////////////////////////////////////////////////////////////////////////
1187

    
1188
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1189
    {
1190
    final float A = 0.8f;  // 0<A<1
1191

    
1192
    int prev = curr>0 ? curr-1 : len-1;
1193
    int next = curr<len-1 ? curr+1 : 0;
1194

    
1195
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1196
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1197
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1198
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1199

    
1200
    float len1= v1x*v1x+v1y*v1y;
1201
    float len2= v2x*v2x+v2y*v2y;
1202

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

    
1205
    return 1-A*cos;
1206
    }
1207

    
1208
///////////////////////////////////////////////////////////////////////////////////////////////////
1209

    
1210
  public ObjectSticker retSticker(int sticker)
1211
    {
1212
    if( mStickers==null )
1213
      {
1214
      float rad = getStickerRadius();
1215
      float str = getStickerStroke();
1216
      float[][] angles = getStickerAngles();
1217
      int numStickers = mStickerCoords.length;
1218
      mStickers = new ObjectSticker[numStickers];
1219

    
1220
      for(int s=0; s<numStickers; s++)
1221
        {
1222
        float scale = mStickerScales[s];
1223
        float radius = rad / scale;
1224
        float stroke = str / scale;
1225
        int len = mStickerCoords[s].length/2;
1226
        float[] radii = new float[len];
1227
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1228
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1229
        }
1230
      }
1231

    
1232
    return mStickers[sticker];
1233
    }
1234

    
1235
///////////////////////////////////////////////////////////////////////////////////////////////////
1236
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1237

    
1238
  public void adjustStickerCoords()
1239
    {
1240

    
1241
    }
1242

    
1243
///////////////////////////////////////////////////////////////////////////////////////////////////
1244

    
1245
  public Static4D[] getQuats()
1246
    {
1247
    if( mObjectQuats==null )
1248
      {
1249
      mObjectQuats = QuatGroupGenerator.computeGroup(mAxis,mBasicAngles);
1250
      }
1251

    
1252
    return mObjectQuats;
1253
    }
1254

    
1255
///////////////////////////////////////////////////////////////////////////////////////////////////
1256

    
1257
  public int getInternalColor()
1258
    {
1259
    return COLOR_INTERNAL;
1260
    }
1261

    
1262
///////////////////////////////////////////////////////////////////////////////////////////////////
1263
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1264

    
1265
  private void createTexture()
1266
    {
1267
    Paint paint = new Paint();
1268
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_4444);
1269
    Canvas canvas = new Canvas(mBitmap);
1270

    
1271
    paint.setAntiAlias(true);
1272
    paint.setTextAlign(Paint.Align.CENTER);
1273
    paint.setStyle(Paint.Style.FILL);
1274

    
1275
    paint.setColor(getInternalColor());
1276
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1277

    
1278
    int texture = 0;
1279
    FactorySticker factory = FactorySticker.getInstance();
1280

    
1281
    for(int row=0; row<mNumTexRows; row++)
1282
      for(int col=0; col<mNumTexCols; col++)
1283
        {
1284
        if( texture>=mNumTextures ) break;
1285
        ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1286
        int color = getColor(texture% mNumFaceColors);
1287
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, color, sticker);
1288
        texture++;
1289
        }
1290
    }
1291

    
1292
///////////////////////////////////////////////////////////////////////////////////////////////////
1293

    
1294
  void setTexture()
1295
    {
1296
    if( mBitmap==null ) createTexture();
1297

    
1298
    if( !mTexture.setTexture(mBitmap) )
1299
      {
1300
      int max = DistortedLibrary.getMaxTextureSize();
1301
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1302
      }
1303
    }
1304

    
1305
///////////////////////////////////////////////////////////////////////////////////////////////////
1306

    
1307
  void setObjectRatioNow(float sc, int nodeSize)
1308
    {
1309
    mObjectScreenRatio = sc;
1310
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1311
    mObjectScale.set(scale,scale,scale);
1312

    
1313
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1314
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1315
    }
1316

    
1317
///////////////////////////////////////////////////////////////////////////////////////////////////
1318

    
1319
  void setObjectRatio(float sizeChange, int nodeSize)
1320
    {
1321
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1322

    
1323
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1324
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1325

    
1326
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1327
    }
1328

    
1329
///////////////////////////////////////////////////////////////////////////////////////////////////
1330

    
1331
  void setNodeSize(int nodeSize)
1332
    {
1333
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1334
    }
1335

    
1336
///////////////////////////////////////////////////////////////////////////////////////////////////
1337

    
1338
  public float getRatio()
1339
    {
1340
    return mObjectScreenRatio;
1341
    }
1342

    
1343
///////////////////////////////////////////////////////////////////////////////////////////////////
1344

    
1345
  public float getObjectRatio()
1346
    {
1347
    return mObjectScreenRatio*mInitScreenRatio;
1348
    }
1349

    
1350
///////////////////////////////////////////////////////////////////////////////////////////////////
1351

    
1352
  boolean isSolved()
1353
    {
1354
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1355
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1356

    
1357
    return false;
1358
    }
1359

    
1360
///////////////////////////////////////////////////////////////////////////////////////////////////
1361

    
1362
  int computeNearestAngle(int axis, float angle, float speed)
1363
    {
1364
    int basicAngle   = mBasicAngles[axis>=mBasicAngles.length ? 0 : axis];
1365
    int nearestAngle = 360/basicAngle;
1366

    
1367
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1368
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1369

    
1370
    if( tmp!=0 ) return nearestAngle*tmp;
1371

    
1372
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1373
    }
1374

    
1375
///////////////////////////////////////////////////////////////////////////////////////////////////
1376
// INTERNAL API - those are called from 'effects' package
1377
///////////////////////////////////////////////////////////////////////////////////////////////////
1378

    
1379
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1380
    {
1381
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1382
    }
1383

    
1384
///////////////////////////////////////////////////////////////////////////////////////////////////
1385

    
1386
  public Static4D getRotationQuat()
1387
    {
1388
    return mQuat;
1389
    }
1390

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

    
1393
  public float getSize()
1394
    {
1395
    return mSize;
1396
    }
1397

    
1398
///////////////////////////////////////////////////////////////////////////////////////////////////
1399

    
1400
  public void apply(Effect effect, int position)
1401
    {
1402
    mEffects.apply(effect, position);
1403
    }
1404

    
1405
///////////////////////////////////////////////////////////////////////////////////////////////////
1406

    
1407
  public void remove(long effectID)
1408
    {
1409
    mEffects.abortById(effectID);
1410
    }
1411

    
1412
///////////////////////////////////////////////////////////////////////////////////////////////////
1413

    
1414
  public MeshBase getObjectMesh()
1415
    {
1416
    return mMesh;
1417
    }
1418

    
1419
///////////////////////////////////////////////////////////////////////////////////////////////////
1420

    
1421
  public DistortedEffects getObjectEffects()
1422
    {
1423
    return mEffects;
1424
    }
1425

    
1426
///////////////////////////////////////////////////////////////////////////////////////////////////
1427
// PUBLIC API
1428
///////////////////////////////////////////////////////////////////////////////////////////////////
1429

    
1430
  public int getCubitFaceColorIndex(int cubit, int face)
1431
    {
1432
    Static4D texMap = mMesh.getTextureMap(mNumFaceColors *cubit + face);
1433

    
1434
    int x = (int)(texMap.get0()/texMap.get2());
1435
    int y = (int)(texMap.get1()/texMap.get3());
1436

    
1437
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1438
    }
1439

    
1440
///////////////////////////////////////////////////////////////////////////////////////////////////
1441

    
1442
  public int[] getNumLayers()
1443
    {
1444
    return mNumLayers;
1445
    }
1446

    
1447
///////////////////////////////////////////////////////////////////////////////////////////////////
1448

    
1449
  public synchronized void solve()
1450
    {
1451
    for(int i=0; i<mNumCubits; i++)
1452
      {
1453
      mCubits[i].solve();
1454
      mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(), 0);
1455
      }
1456
    }
1457

    
1458
///////////////////////////////////////////////////////////////////////////////////////////////////
1459

    
1460
  public int getCubitQuatIndex(int cubit)
1461
    {
1462
    return (cubit>=0 && cubit<mNumCubits) ? mCubits[cubit].mQuatIndex : 0;
1463
    }
1464

    
1465
///////////////////////////////////////////////////////////////////////////////////////////////////
1466

    
1467
  public int getCubitRotRow(int cubit, int axis)
1468
    {
1469
    return mCubits[cubit].getRotRow(axis);
1470
    }
1471

    
1472
///////////////////////////////////////////////////////////////////////////////////////////////////
1473

    
1474
  public Bitmap getStickerBitmap()
1475
    {
1476
    return mBitmap;
1477
    }
1478

    
1479
///////////////////////////////////////////////////////////////////////////////////////////////////
1480

    
1481
  public DistortedNode getNode()
1482
    {
1483
    return mNode;
1484
    }
1485

    
1486
///////////////////////////////////////////////////////////////////////////////////////////////////
1487

    
1488
  public ObjectType getObjectType()
1489
    {
1490
    return intGetObjectType(mNumLayers);
1491
    }
1492

    
1493
///////////////////////////////////////////////////////////////////////////////////////////////////
1494

    
1495
  public int getNumStickerTypes()
1496
    {
1497
    return mNumStickerTypes;
1498
    }
1499

    
1500
///////////////////////////////////////////////////////////////////////////////////////////////////
1501
// this is here only so it can be overridden in TwistyJSON soo that we can get this from JSON.
1502

    
1503
  public int getNumCubitFaces()
1504
    {
1505
    return 0;
1506
    }
1507

    
1508
///////////////////////////////////////////////////////////////////////////////////////////////////
1509

    
1510
  public TouchControl getTouchControl()
1511
    {
1512
    if( mTouchControl==null )
1513
      {
1514
      switch(getTouchControlType())
1515
        {
1516
        case TC_TETRAHEDRON      : mTouchControl = new TouchControlTetrahedron(this);
1517
                                   break;
1518
        case TC_HEXAHEDRON       : mTouchControl = new TouchControlHexahedron(this);
1519
                                   break;
1520
        case TC_OCTAHEDRON       : mTouchControl = new TouchControlOctahedron(this);
1521
                                   break;
1522
        case TC_DODECAHEDRON     : mTouchControl = new TouchControlDodecahedron(this);
1523
                                   break;
1524
        case TC_CUBOID           : int[] numLayers = getNumLayers();
1525
                                   mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1526
                                   break;
1527
        case TC_CHANGING_MIRROR  : mTouchControl = new TouchControlMirror(this);
1528
                                   break;
1529
        case TC_CHANGING_SQUARE  : mTouchControl = new TouchControlSquare(this);
1530
                                   break;
1531
        case TC_CHANGING_SHAPEMOD: mTouchControl = new TouchControlShapemod(this);
1532
                                   break;
1533
        }
1534
      }
1535
    return mTouchControl;
1536
    }
1537

    
1538
///////////////////////////////////////////////////////////////////////////////////////////////////
1539

    
1540
  public String getShortName()
1541
    {
1542
    return getObjectType().name();
1543
    }
1544

    
1545
///////////////////////////////////////////////////////////////////////////////////////////////////
1546

    
1547
  protected void setReader(JsonReader reader)
1548
    {
1549
    // empty
1550
    }
1551

    
1552
///////////////////////////////////////////////////////////////////////////////////////////////////
1553

    
1554
  protected abstract ObjectType intGetObjectType(int[] numLayers);
1555

    
1556
  // for JSON only
1557
  public abstract int getTouchControlType();
1558
  public abstract int getTouchControlSplit();
1559
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1560
  public abstract int[][][] getEnabled();
1561
  public abstract float[] getDist3D(int[] numLayers);
1562
  public abstract Static3D[] getFaceAxis();
1563
  public abstract ScrambleState[] getScrambleStates();
1564
  public abstract float[][] getCuts(int[] numLayers);
1565
  public abstract float getStickerRadius();
1566
  public abstract float getStickerStroke();
1567
  public abstract float[][] getStickerAngles();
1568
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1569
  public abstract ObjectShape getObjectShape(int variant);
1570
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
1571
  public abstract int getNumCubitVariants(int[] numLayers);
1572
  public abstract float[][] getCubitPositions(int[] numLayers);
1573
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
1574
  public abstract int getNumFaceColors();
1575
  public abstract float getScreenRatio();
1576
  public abstract int getColor(int face);
1577

    
1578
  // not only for JSON
1579
  public abstract Static3D[] getRotationAxis();
1580
  public abstract int[] getBasicAngles();
1581
  public abstract int getNumFaces();
1582
  public abstract String getObjectName();
1583
  public abstract String getInventor();
1584
  public abstract int getYearOfInvention();
1585
  public abstract int getComplexity();
1586
  public abstract int getFOV();
1587
  public abstract String[][] getTutorials();
1588
  }
(11-11/13)