Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ 3c48fab9

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_INTERNAL= 0xff000000;
81

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

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

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

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

    
96
  protected float[][] mStickerCoords;
97
  protected Static4D[] mObjectQuats;
98
  int mNumAxis, mMaxNumLayers;
99

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

    
145
  //////////////////// SOLVED1 ////////////////////////
146

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

    
151
///////////////////////////////////////////////////////////////////////////////////////////////////
152

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

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

    
164
///////////////////////////////////////////////////////////////////////////////////////////////////
165

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

    
173
///////////////////////////////////////////////////////////////////////////////////////////////////
174

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

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

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

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

    
204
    boolean bandaged=false;
205

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

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

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

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

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

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

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

    
239
    mEffects = new DistortedEffects();
240

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

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

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

    
256
///////////////////////////////////////////////////////////////////////////////////////////////////
257

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

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

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

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

    
279
///////////////////////////////////////////////////////////////////////////////////////////////////
280

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

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

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

    
304
///////////////////////////////////////////////////////////////////////////////////////////////////
305

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

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

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

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

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

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

    
336
///////////////////////////////////////////////////////////////////////////////////////////////////
337

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

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

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

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

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

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

    
379
///////////////////////////////////////////////////////////////////////////////////////////////////
380

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

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

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

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

    
399
    return mesh;
400
    }
401

    
402
///////////////////////////////////////////////////////////////////////////////////////////////////
403

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

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

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

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

    
432
///////////////////////////////////////////////////////////////////////////////////////////////////
433

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

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

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

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

    
452
///////////////////////////////////////////////////////////////////////////////////////////////////
453

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

    
459
///////////////////////////////////////////////////////////////////////////////////////////////////
460

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

    
466
///////////////////////////////////////////////////////////////////////////////////////////////////
467

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

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

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

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

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

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

    
502
    return nonBlackIndex;
503
    }
504

    
505
///////////////////////////////////////////////////////////////////////////////////////////////////
506

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

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

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

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

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

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

    
545
    return null;
546
    }
547

    
548
///////////////////////////////////////////////////////////////////////////////////////////////////
549

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

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

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

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

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

    
593
    for(int g=0; g<numGroups; g++)
594
      {
595
      int len = solvedQuats[g].length;
596

    
597
      for(int i=0; i<len; i++)
598
        {
599
        dbg += (" "+solvedQuats[g][i]);
600
        }
601

    
602
      dbg+="\n";
603
      }
604

    
605
    android.util.Log.e("D", dbg);
606
*/
607

    
608
    return solvedQuats;
609
    }
610

    
611
///////////////////////////////////////////////////////////////////////////////////////////////////
612

    
613
  public int getSolvedFunctionIndex()
614
    {
615
    return 0;
616
    }
617

    
618
///////////////////////////////////////////////////////////////////////////////////////////////////
619

    
620
  private boolean isSolved0()
621
    {
622
    for( int[] solvedQuat : mSolvedQuats )
623
      {
624
      int numCubits = solvedQuat[0];
625
      int firstCubit= solvedQuat[1];
626
      int quat = mCubits[firstCubit].mQuatIndex;
627

    
628
      for( int cubit=2; cubit<=numCubits; cubit++ )
629
        {
630
        int c = solvedQuat[cubit];
631
        if( quat != mCubits[c].mQuatIndex ) return false;
632
        }
633
      }
634

    
635
    int cubit= mSolvedQuats[0][1];
636
    int quat0= mCubits[cubit].mQuatIndex;
637
    int numGroups = mSolvedQuats.length;
638

    
639
    for(int group=1; group<numGroups; group++)
640
      {
641
      int firstCubit= mSolvedQuats[group][1];
642
      int currQuat  = mCubits[firstCubit].mQuatIndex;
643

    
644
      if( quat0==currQuat ) continue;
645

    
646
      boolean isGood= false;
647
      int numEntries= mSolvedQuats[group].length;
648
      int numCubits = mSolvedQuats[group][0];
649

    
650
      for(int q=numCubits+1; q<numEntries; q++)
651
        {
652
        int quat = mSolvedQuats[group][q];
653

    
654
        if( quat0 == getMultQuat(currQuat,quat) )
655
          {
656
          isGood = true;
657
          break;
658
          }
659
        }
660

    
661
      if( !isGood ) return false;
662
      }
663

    
664
    return true;
665
    }
666

    
667
///////////////////////////////////////////////////////////////////////////////////////////////////
668

    
669
  private int computeScramble(int quatNum, int centerNum)
670
    {
671
    float MAXDIFF = 0.01f;
672
    float[] center= mOrigPos[centerNum];
673
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
674
    Static4D result = QuatHelper.rotateVectorByQuat(sc,mObjectQuats[quatNum]);
675

    
676
    float x = result.get0();
677
    float y = result.get1();
678
    float z = result.get2();
679

    
680
    for(int c=0; c<mNumCubits; c++)
681
      {
682
      float[] cent = mOrigPos[c];
683

    
684
      float qx = cent[0] - x;
685
      float qy = cent[1] - y;
686
      float qz = cent[2] - z;
687

    
688
      if( qx>-MAXDIFF && qx<MAXDIFF &&
689
          qy>-MAXDIFF && qy<MAXDIFF &&
690
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
691
      }
692

    
693
    return -1;
694
    }
695

    
696
///////////////////////////////////////////////////////////////////////////////////////////////////
697
// Dino4 uses this. It is solved if and only if groups of cubits
698
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
699
// or
700
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
701
// are all the same color.
702

    
703
  private boolean isSolved1()
704
    {
705
    if( mScramble==null )
706
      {
707
      mScramble = new int[mNumQuats][mNumCubits];
708
      mColors   = new int[mNumCubits];
709

    
710
      for(int q=0; q<mNumQuats; q++)
711
        for(int c=0; c<mNumCubits; c++) mScramble[q][c] = computeScramble(q,c);
712
      }
713

    
714
    if( mFaceMap==null )
715
      {
716
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
717
      }
718

    
719
    for(int c=0; c<mNumCubits; c++)
720
      {
721
      int index = mScramble[mCubits[c].mQuatIndex][c];
722
      mColors[index] = mFaceMap[c];
723
      }
724

    
725
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
726
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
727
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
728

    
729
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
730
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
731
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
732

    
733
    return false;
734
    }
735

    
736
///////////////////////////////////////////////////////////////////////////////////////////////////
737

    
738
  int computeRow(float[] pos, int axisIndex)
739
    {
740
    int ret=0;
741
    int len = pos.length / 3;
742
    Static3D axis = mAxis[axisIndex];
743
    float axisX = axis.get0();
744
    float axisY = axis.get1();
745
    float axisZ = axis.get2();
746
    float casted;
747

    
748
    for(int i=0; i<len; i++)
749
      {
750
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
751
      ret |= computeSingleRow(axisIndex,casted);
752
      }
753

    
754
    return ret;
755
    }
756

    
757
///////////////////////////////////////////////////////////////////////////////////////////////////
758

    
759
  private int computeSingleRow(int axisIndex,float casted)
760
    {
761
    int num = mNumCuts[axisIndex];
762

    
763
    for(int i=0; i<num; i++)
764
      {
765
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
766
      }
767

    
768
    return (1<<num);
769
    }
770

    
771
///////////////////////////////////////////////////////////////////////////////////////////////////
772

    
773
  private boolean wasRotateApplied()
774
    {
775
    return mEffects.exists(mRotateEffect.getID());
776
    }
777

    
778
///////////////////////////////////////////////////////////////////////////////////////////////////
779

    
780
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
781
    {
782
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
783
    }
784

    
785
///////////////////////////////////////////////////////////////////////////////////////////////////
786
// note the minus in front of the sin() - we rotate counterclockwise
787
// when looking towards the direction where the axis increases in values.
788

    
789
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
790
    {
791
    Static3D axis = mAxis[axisIndex];
792

    
793
    while( angleInDegrees<0 ) angleInDegrees += 360;
794
    angleInDegrees %= 360;
795
    
796
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
797
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
798

    
799
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
800
    }
801

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

    
804
  private synchronized void setupPosition(int[][] moves)
805
    {
806
    if( moves!=null )
807
      {
808
      Static4D quat;
809
      int index, axis, rowBitmap, angle;
810

    
811
      for(int[] move: moves)
812
        {
813
        axis     = move[0];
814
        rowBitmap= move[1];
815
        angle    = move[2]*(360/mBasicAngles[axis]);
816
        quat     = makeQuaternion(axis,angle);
817

    
818
        for(int j=0; j<mNumCubits; j++)
819
          if( belongsToRotation(j,axis,rowBitmap) )
820
            {
821
            index = mCubits[j].removeRotationNow(quat);
822
            mMesh.setEffectAssociation(j, mCubits[j].computeAssociation(),index);
823
            }
824
        }
825
      }
826
    }
827

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

    
830
  public int getScrambleType()
831
    {
832
    return 0;
833
    }
834

    
835
///////////////////////////////////////////////////////////////////////////////////////////////////
836

    
837
  int computeBitmapFromRow(int rowBitmap, int axis)
838
    {
839
    if( mIsBandaged )
840
      {
841
      int bitmap, initBitmap=0;
842

    
843
      while( initBitmap!=rowBitmap )
844
        {
845
        initBitmap = rowBitmap;
846

    
847
        for(int cubit=0; cubit<mNumCubits; cubit++)
848
          {
849
          bitmap = mCubits[cubit].getRotRow(axis);
850
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
851
          }
852
        }
853
      }
854

    
855
    return rowBitmap;
856
    }
857

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

    
862
  void clampPos(float[] pos, int offset)
863
    {
864
    float currError, minError = Float.MAX_VALUE;
865
    int minErrorIndex1 = -1;
866
    int minErrorIndex2 = -1;
867

    
868
    float x = pos[offset  ];
869
    float y = pos[offset+1];
870
    float z = pos[offset+2];
871

    
872
    float xo,yo,zo;
873

    
874
    for(int i=0; i<mNumCubits; i++)
875
      {
876
      int len = mOrigPos[i].length / 3;
877

    
878
      for(int j=0; j<len; j++)
879
        {
880
        xo = mOrigPos[i][3*j  ];
881
        yo = mOrigPos[i][3*j+1];
882
        zo = mOrigPos[i][3*j+2];
883

    
884
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
885

    
886
        if( currError<minError )
887
          {
888
          minError = currError;
889
          minErrorIndex1 = i;
890
          minErrorIndex2 = j;
891
          }
892
        }
893
      }
894

    
895
    if( minError< 0.1f ) // TODO: 0.1 ?
896
      {
897
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
898
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
899
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
900
      }
901
    }
902

    
903
///////////////////////////////////////////////////////////////////////////////////////////////////
904
// remember about the double cover or unit quaternions!
905

    
906
  int mulQuat(int q1, int q2)
907
    {
908
    Static4D result = QuatHelper.quatMultiply(mObjectQuats[q1],mObjectQuats[q2]);
909

    
910
    float rX = result.get0();
911
    float rY = result.get1();
912
    float rZ = result.get2();
913
    float rW = result.get3();
914

    
915
    final float MAX_ERROR = 0.1f;
916
    float dX,dY,dZ,dW;
917

    
918
    for(int i=0; i<mNumQuats; i++)
919
      {
920
      dX = mObjectQuats[i].get0() - rX;
921
      dY = mObjectQuats[i].get1() - rY;
922
      dZ = mObjectQuats[i].get2() - rZ;
923
      dW = mObjectQuats[i].get3() - rW;
924

    
925
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
926
          dY<MAX_ERROR && dY>-MAX_ERROR &&
927
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
928
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
929

    
930
      dX = mObjectQuats[i].get0() + rX;
931
      dY = mObjectQuats[i].get1() + rY;
932
      dZ = mObjectQuats[i].get2() + rZ;
933
      dW = mObjectQuats[i].get3() + rW;
934

    
935
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
936
          dY<MAX_ERROR && dY>-MAX_ERROR &&
937
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
938
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
939
      }
940

    
941
    return -1;
942
    }
943

    
944
///////////////////////////////////////////////////////////////////////////////////////////////////
945

    
946
  private float getAngle()
947
    {
948
    int pointNum = mRotationAngle.getNumPoints();
949

    
950
    if( pointNum>=1 )
951
      {
952
      return mRotationAngle.getPoint(pointNum-1).get0();
953
      }
954
    else
955
      {
956
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
957
      return 0;
958
      }
959
    }
960

    
961
///////////////////////////////////////////////////////////////////////////////////////////////////
962

    
963
  void setLibInterface(ObjectLibInterface inter)
964
    {
965
    mInterface = inter;
966
    }
967

    
968
///////////////////////////////////////////////////////////////////////////////////////////////////
969

    
970
  void initializeObject(int[][] moves)
971
    {
972
    solve();
973
    setupPosition(moves);
974
    }
975

    
976
///////////////////////////////////////////////////////////////////////////////////////////////////
977

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

    
989
    mRotationAngle.removeAll();
990
    mRotationAngleStatic.set0(0);
991

    
992
    for(int i=0; i<mNumCubits; i++)
993
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
994
        {
995
        int index = mCubits[i].removeRotationNow(quat);
996
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),index);
997
        }
998
    }
999

    
1000
///////////////////////////////////////////////////////////////////////////////////////////////////
1001

    
1002
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
1003
    {
1004
    if( wasRotateApplied() )
1005
      {
1006
      float angle = getAngle();
1007
      mRotationAngleStatic.set0(angle);
1008
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1009
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1010

    
1011
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1012
      mRotationAngle.resetToBeginning();
1013
      mRotationAngle.removeAll();
1014
      mRotationAngle.add(mRotationAngleStatic);
1015
      mRotationAngle.add(mRotationAngleMiddle);
1016
      mRotationAngle.add(mRotationAngleFinal);
1017
      mRotateEffect.notifyWhenFinished(listener);
1018

    
1019
      return mRotateEffect.getID();
1020
      }
1021

    
1022
    return 0;
1023
    }
1024

    
1025
///////////////////////////////////////////////////////////////////////////////////////////////////
1026

    
1027
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1028
    {
1029
    if( wasRotateApplied() )
1030
      {
1031
      mCurrentRotAxis = axis;
1032
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1033

    
1034
      mRotationAngleStatic.set0(0.0f);
1035
      mRotationAxis.set( mAxis[axis] );
1036
      mRotationAngle.setDuration(durationMillis);
1037
      mRotationAngle.resetToBeginning();
1038
      mRotationAngle.add(new Static1D(0));
1039
      mRotationAngle.add(new Static1D(angle));
1040
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1041
      mRotateEffect.notifyWhenFinished(listener);
1042

    
1043
      return mRotateEffect.getID();
1044
      }
1045

    
1046
    return 0;
1047
    }
1048

    
1049
///////////////////////////////////////////////////////////////////////////////////////////////////
1050

    
1051
  void continueRotation(float angleInDegrees)
1052
    {
1053
    mRotationAngleStatic.set0(angleInDegrees);
1054
    }
1055

    
1056
///////////////////////////////////////////////////////////////////////////////////////////////////
1057

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

    
1071
    mCurrentRotAxis = axis;
1072
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1073
    mRotationAngleStatic.set0(0.0f);
1074
    mRotationAxis.set( mAxis[axis] );
1075
    mRotationAngle.add(mRotationAngleStatic);
1076
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1077
    }
1078

    
1079
///////////////////////////////////////////////////////////////////////////////////////////////////
1080

    
1081
  void setTextureMap(int cubit, int face, int newColor)
1082
    {
1083
    final float ratioW = 1.0f/mNumTexCols;
1084
    final float ratioH = 1.0f/mNumTexRows;
1085
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1086
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1087
    int col = newColor%mNumTexCols;
1088

    
1089
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1090
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1091
    }
1092

    
1093
///////////////////////////////////////////////////////////////////////////////////////////////////
1094

    
1095
  private int getCubitFaceColor(int cubit, int face)
1096
    {
1097
    int puzzleFace = getCubitFaceMap(cubit,face);
1098
    if( puzzleFace>=0 ) puzzleFace %= mNumFaceColors;
1099
    return puzzleFace;
1100
    }
1101

    
1102
///////////////////////////////////////////////////////////////////////////////////////////////////
1103

    
1104
  public int getCubitFaceMap(int cubit, int face)
1105
    {
1106
    int numFaces = mCubitFaceColors[cubit].length;
1107
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1108
    return puzzleFace<0 ? -1 : puzzleFace;
1109
    }
1110

    
1111
///////////////////////////////////////////////////////////////////////////////////////////////////
1112

    
1113
  void resetAllTextureMaps()
1114
    {
1115
    final float ratioW = 1.0f/mNumTexCols;
1116
    final float ratioH = 1.0f/mNumTexRows;
1117
    int cubColor, varColor, color, variant, row, col;
1118

    
1119
    for(int cubit=0; cubit<mNumCubits; cubit++)
1120
      {
1121
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1122
      variant = getCubitVariant(cubit,mNumLayers);
1123

    
1124
      for(int face=0; face<mNumCubitFaces; face++)
1125
        {
1126
        cubColor = getCubitFaceColor(cubit,face);
1127
        varColor = getVariantFaceColor(variant,face);
1128
        color    = cubColor<0 || varColor<0 ? mNumTextures : varColor*mNumFaceColors + cubColor;
1129
        row      = (mNumTexRows-1) - color/mNumTexCols;
1130
        col      = color%mNumTexCols;
1131

    
1132
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1133
        }
1134

    
1135
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1136
      }
1137
    }
1138

    
1139
///////////////////////////////////////////////////////////////////////////////////////////////////
1140

    
1141
  void releaseResources()
1142
    {
1143
    mTexture.markForDeletion();
1144
    mMesh.markForDeletion();
1145
    mEffects.markForDeletion();
1146

    
1147
    for(int j=0; j<mNumCubits; j++)
1148
      {
1149
      mCubits[j].releaseResources();
1150
      }
1151
    }
1152

    
1153
///////////////////////////////////////////////////////////////////////////////////////////////////
1154

    
1155
  synchronized void restorePreferences(SharedPreferences preferences)
1156
    {
1157
    boolean error = false;
1158

    
1159
    for(int i=0; i<mNumCubits; i++)
1160
      {
1161
      mQuatDebug[i] = mCubits[i].restorePreferences(preferences);
1162

    
1163
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1164
        {
1165
        mCubits[i].modifyCurrentPosition(mObjectQuats[mQuatDebug[i]]);
1166
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),mQuatDebug[i]);
1167
        }
1168
      else
1169
        {
1170
        error = true;
1171
        }
1172
      }
1173

    
1174
    if( error )
1175
      {
1176
      for(int i=0; i<mNumCubits; i++)
1177
        {
1178
        mCubits[i].solve();
1179
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),0);
1180
        }
1181
      }
1182
    }
1183

    
1184
///////////////////////////////////////////////////////////////////////////////////////////////////
1185

    
1186
  void savePreferences(SharedPreferences.Editor editor)
1187
    {
1188
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(editor);
1189
    }
1190

    
1191
///////////////////////////////////////////////////////////////////////////////////////////////////
1192

    
1193
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1194
    {
1195
    final float A = 0.8f;  // 0<A<1
1196

    
1197
    int prev = curr>0 ? curr-1 : len-1;
1198
    int next = curr<len-1 ? curr+1 : 0;
1199

    
1200
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1201
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1202
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1203
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1204

    
1205
    float len1= v1x*v1x+v1y*v1y;
1206
    float len2= v2x*v2x+v2y*v2y;
1207

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

    
1210
    return 1-A*cos;
1211
    }
1212

    
1213
///////////////////////////////////////////////////////////////////////////////////////////////////
1214

    
1215
  public ObjectSticker retSticker(int sticker)
1216
    {
1217
    if( mStickers==null )
1218
      {
1219
      float rad = getStickerRadius();
1220
      float str = getStickerStroke();
1221
      float[][] angles = getStickerAngles();
1222
      int numStickers = mStickerCoords.length;
1223
      mStickers = new ObjectSticker[numStickers];
1224

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

    
1237
    return mStickers[sticker];
1238
    }
1239

    
1240
///////////////////////////////////////////////////////////////////////////////////////////////////
1241
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1242

    
1243
  public void adjustStickerCoords()
1244
    {
1245

    
1246
    }
1247

    
1248
///////////////////////////////////////////////////////////////////////////////////////////////////
1249

    
1250
  public Static4D[] getQuats()
1251
    {
1252
    if( mObjectQuats==null )
1253
      {
1254
      mObjectQuats = QuatGroupGenerator.computeGroup(mAxis,mBasicAngles);
1255
      }
1256

    
1257
    return mObjectQuats;
1258
    }
1259

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

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

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

    
1273
    paint.setColor(COLOR_INTERNAL);
1274
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1275

    
1276
    int texture = 0;
1277
    FactorySticker factory = FactorySticker.getInstance();
1278

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

    
1290
///////////////////////////////////////////////////////////////////////////////////////////////////
1291

    
1292
  void setTexture()
1293
    {
1294
    if( mBitmap==null ) createTexture();
1295

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

    
1303
///////////////////////////////////////////////////////////////////////////////////////////////////
1304

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

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

    
1315
///////////////////////////////////////////////////////////////////////////////////////////////////
1316

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

    
1321
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1322
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1323

    
1324
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1325
    }
1326

    
1327
///////////////////////////////////////////////////////////////////////////////////////////////////
1328

    
1329
  void setNodeSize(int nodeSize)
1330
    {
1331
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1332
    }
1333

    
1334
///////////////////////////////////////////////////////////////////////////////////////////////////
1335

    
1336
  public float getRatio()
1337
    {
1338
    return mObjectScreenRatio;
1339
    }
1340

    
1341
///////////////////////////////////////////////////////////////////////////////////////////////////
1342

    
1343
  public float getObjectRatio()
1344
    {
1345
    return mObjectScreenRatio*mInitScreenRatio;
1346
    }
1347

    
1348
///////////////////////////////////////////////////////////////////////////////////////////////////
1349

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

    
1355
    return false;
1356
    }
1357

    
1358
///////////////////////////////////////////////////////////////////////////////////////////////////
1359

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

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

    
1368
    if( tmp!=0 ) return nearestAngle*tmp;
1369

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

    
1373
///////////////////////////////////////////////////////////////////////////////////////////////////
1374
// INTERNAL API - those are called from 'effects' package
1375
///////////////////////////////////////////////////////////////////////////////////////////////////
1376

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

    
1382
///////////////////////////////////////////////////////////////////////////////////////////////////
1383

    
1384
  public Static4D getRotationQuat()
1385
    {
1386
    return mQuat;
1387
    }
1388

    
1389
///////////////////////////////////////////////////////////////////////////////////////////////////
1390

    
1391
  public float getSize()
1392
    {
1393
    return mSize;
1394
    }
1395

    
1396
///////////////////////////////////////////////////////////////////////////////////////////////////
1397

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

    
1403
///////////////////////////////////////////////////////////////////////////////////////////////////
1404

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

    
1410
///////////////////////////////////////////////////////////////////////////////////////////////////
1411

    
1412
  public MeshBase getObjectMesh()
1413
    {
1414
    return mMesh;
1415
    }
1416

    
1417
///////////////////////////////////////////////////////////////////////////////////////////////////
1418

    
1419
  public DistortedEffects getObjectEffects()
1420
    {
1421
    return mEffects;
1422
    }
1423

    
1424
///////////////////////////////////////////////////////////////////////////////////////////////////
1425
// PUBLIC API
1426
///////////////////////////////////////////////////////////////////////////////////////////////////
1427

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

    
1432
    int x = (int)(texMap.get0()/texMap.get2());
1433
    int y = (int)(texMap.get1()/texMap.get3());
1434

    
1435
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1436
    }
1437

    
1438
///////////////////////////////////////////////////////////////////////////////////////////////////
1439

    
1440
  public int[] getNumLayers()
1441
    {
1442
    return mNumLayers;
1443
    }
1444

    
1445
///////////////////////////////////////////////////////////////////////////////////////////////////
1446

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

    
1456
///////////////////////////////////////////////////////////////////////////////////////////////////
1457

    
1458
  public int getCubitQuatIndex(int cubit)
1459
    {
1460
    return mCubits[cubit].mQuatIndex;
1461
    }
1462

    
1463
///////////////////////////////////////////////////////////////////////////////////////////////////
1464

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

    
1470
///////////////////////////////////////////////////////////////////////////////////////////////////
1471

    
1472
  public Bitmap getStickerBitmap()
1473
    {
1474
    return mBitmap;
1475
    }
1476

    
1477
///////////////////////////////////////////////////////////////////////////////////////////////////
1478

    
1479
  public DistortedNode getNode()
1480
    {
1481
    return mNode;
1482
    }
1483

    
1484
///////////////////////////////////////////////////////////////////////////////////////////////////
1485

    
1486
  public ObjectType getObjectType()
1487
    {
1488
    return intGetObjectType(mNumLayers);
1489
    }
1490

    
1491
///////////////////////////////////////////////////////////////////////////////////////////////////
1492

    
1493
  public int getNumStickerTypes()
1494
    {
1495
    return mNumStickerTypes;
1496
    }
1497

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

    
1501
  public int getNumCubitFaces()
1502
    {
1503
    return 0;
1504
    }
1505

    
1506
///////////////////////////////////////////////////////////////////////////////////////////////////
1507

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

    
1534
///////////////////////////////////////////////////////////////////////////////////////////////////
1535

    
1536
  public String getShortName()
1537
    {
1538
    return getObjectType().name();
1539
    }
1540

    
1541
///////////////////////////////////////////////////////////////////////////////////////////////////
1542

    
1543
  protected void setReader(JsonReader reader)
1544
    {
1545
    // empty
1546
    }
1547

    
1548
///////////////////////////////////////////////////////////////////////////////////////////////////
1549

    
1550
  protected abstract ObjectType intGetObjectType(int[] numLayers);
1551

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

    
1574
  // not only for JSON
1575
  public abstract Static3D[] getRotationAxis();
1576
  public abstract int[] getBasicAngles();
1577
  public abstract int getNumFaces();
1578
  public abstract String getObjectName();
1579
  public abstract String getInventor();
1580
  public abstract int getYearOfInvention();
1581
  public abstract int getComplexity();
1582
  public abstract int getFOV();
1583
  }
(11-11/13)