Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ f5426a4c

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(mNumLayers);
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 void createDataStructuresForSolved(int[] numLayers)
435
    {
436
    mTmpQuats = new int[mNumQuats];
437
    mSolvedQuats = new int[mNumCubits][];
438

    
439
    for(int c=0; c<mNumCubits; c++)
440
      {
441
      mSolvedQuats[c] = getSolvedQuats(c,numLayers);
442
      }
443
    }
444

    
445
///////////////////////////////////////////////////////////////////////////////////////////////////
446

    
447
  private int getMultQuat(int index1, int index2)
448
    {
449
    if( mQuatMult==null )
450
      {
451
      mQuatMult = new int[mNumQuats][mNumQuats];
452

    
453
      for(int i=0; i<mNumQuats; i++)
454
        for(int j=0; j<mNumQuats; j++) mQuatMult[i][j] = -1;
455
      }
456

    
457
    if( mQuatMult[index1][index2]==-1 )
458
      {
459
      mQuatMult[index1][index2] = mulQuat(index1,index2);
460
      }
461

    
462
    return mQuatMult[index1][index2];
463
    }
464

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

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

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

    
480
  protected int retCubitSolvedStatus(int cubit, int[] numLayers)
481
    {
482
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
483
    int variant = getCubitVariant(cubit,numLayers);
484

    
485
    for(int face=0; face<mNumCubitFaces; face++)
486
      {
487
      varColor = getVariantFaceColor(variant,face);
488
      cubColor = getCubitFaceFace(cubit,face);
489

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

    
497
    if( numNonBlack==0 ) return -1;
498
    if( numNonBlack>=2 ) return -2;
499

    
500
    return nonBlackIndex;
501
    }
502

    
503
///////////////////////////////////////////////////////////////////////////////////////////////////
504

    
505
  public boolean shouldResetTextureMaps()
506
    {
507
    return false;
508
    }
509

    
510
///////////////////////////////////////////////////////////////////////////////////////////////////
511

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

    
521
    int len = quats.length;
522
    int place = 0;
523

    
524
    for(int q=1; q<len; q++)
525
      {
526
      quat = quats[q];
527
      qx = quat.get0();
528
      qy = quat.get1();
529
      qz = quat.get2();
530

    
531
           if( x!=0.0f ) { a = qx/x; }
532
      else if( y!=0.0f ) { a = qy/y; }
533
      else               { a = qz/z; }
534

    
535
      dx = a*x-qx;
536
      dy = a*y-qy;
537
      dz = a*z-qz;
538

    
539
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
540
        {
541
        mTmpQuats[place++] = q;
542
        }
543
      }
544

    
545
    if( place!=0 )
546
      {
547
      int[] ret = new int[place];
548
      System.arraycopy(mTmpQuats,0,ret,0,place);
549
      return ret;
550
      }
551

    
552
    return null;
553
    }
554

    
555
///////////////////////////////////////////////////////////////////////////////////////////////////
556

    
557
  public int[] getSolvedQuats(int cubit, int[] numLayers)
558
    {
559
    int status = retCubitSolvedStatus(cubit,numLayers);
560

    
561
    if( status>=0 )
562
      {
563
      Static3D[] axis = getFaceAxis();
564
      return buildSolvedQuats(axis[status],mObjectQuats);
565
      }
566

    
567
    return null;
568
    }
569

    
570
///////////////////////////////////////////////////////////////////////////////////////////////////
571

    
572
  public int getSolvedFunctionIndex()
573
    {
574
    return 0;
575
    }
576

    
577
///////////////////////////////////////////////////////////////////////////////////////////////////
578

    
579
  private boolean isSolved0()
580
    {
581
    int len, q1,q = mCubits[0].mQuatIndex;
582
    int[] solved;
583
    boolean skip;
584

    
585
    for(int c=1; c<mNumCubits; c++)
586
      {
587
      q1 = mCubits[c].mQuatIndex;
588

    
589
      if( q1==q ) continue;
590

    
591
      skip = false;
592
      solved = mSolvedQuats[c];
593
      len = solved==null ? 0:solved.length;
594

    
595
      for(int i=0; i<len; i++)
596
        {
597
        if( q1==getMultQuat(q,solved[i]) )
598
          {
599
          skip = true;
600
          break;
601
          }
602
        }
603

    
604
      if( !skip ) return false;
605
      }
606

    
607
    return true;
608
    }
609

    
610
///////////////////////////////////////////////////////////////////////////////////////////////////
611

    
612
  private int computeScramble(int quatNum, int centerNum)
613
    {
614
    float MAXDIFF = 0.01f;
615
    float[] center= mOrigPos[centerNum];
616
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
617
    Static4D result = QuatHelper.rotateVectorByQuat(sc,mObjectQuats[quatNum]);
618

    
619
    float x = result.get0();
620
    float y = result.get1();
621
    float z = result.get2();
622

    
623
    for(int c=0; c<mNumCubits; c++)
624
      {
625
      float[] cent = mOrigPos[c];
626

    
627
      float qx = cent[0] - x;
628
      float qy = cent[1] - y;
629
      float qz = cent[2] - z;
630

    
631
      if( qx>-MAXDIFF && qx<MAXDIFF &&
632
          qy>-MAXDIFF && qy<MAXDIFF &&
633
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
634
      }
635

    
636
    return -1;
637
    }
638

    
639
///////////////////////////////////////////////////////////////////////////////////////////////////
640
// Dino4 uses this. It is solved if and only if groups of cubits
641
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
642
// or
643
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
644
// are all the same color.
645

    
646
  private boolean isSolved1()
647
    {
648
    if( mScramble==null )
649
      {
650
      mScramble = new int[mNumQuats][mNumCubits];
651
      mColors   = new int[mNumCubits];
652

    
653
      for(int q=0; q<mNumQuats; q++)
654
        for(int c=0; c<mNumCubits; c++) mScramble[q][c] = computeScramble(q,c);
655
      }
656

    
657
    if( mFaceMap==null )
658
      {
659
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
660
      }
661

    
662
    for(int c=0; c<mNumCubits; c++)
663
      {
664
      int index = mScramble[mCubits[c].mQuatIndex][c];
665
      mColors[index] = mFaceMap[c];
666
      }
667

    
668
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
669
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
670
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
671

    
672
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
673
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
674
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
675

    
676
    return false;
677
    }
678

    
679
///////////////////////////////////////////////////////////////////////////////////////////////////
680
// Dino6 uses this. It is solved if and only if:
681
//
682
// All four 'X' cubits (i.e. those whose longest edge goes along the X axis) are rotated
683
// by the same quaternion qX, similarly all four 'Y' cubits by the same qY and all four 'Z'
684
// by the same qZ, and then either:
685
//
686
// a) qX = qY = qZ
687
// b) qY = qX*Q10 and qZ = qX*Q11 (i.e. swap of WHITE and YELLOW faces)
688
// c) qX = qY*Q10 and qZ = qY*Q9  (i.e. swap of BLUE and GREEN faces)
689
// d) qX = qZ*Q11 and qY = qZ*Q9  (i.e. swap of RED and BROWN faces)
690
//
691
// BUT: cases b), c) and d) are really the same - it's all just a mirror image of the original.
692
//
693
// X cubits: 0, 2, 8, 10
694
// Y cubits: 1, 3, 9, 11
695
// Z cubits: 4, 5, 6, 7
696

    
697
  private boolean isSolved2()
698
    {
699
    int qX = mCubits[0].mQuatIndex;
700
    int qY = mCubits[1].mQuatIndex;
701
    int qZ = mCubits[4].mQuatIndex;
702

    
703
    if( mCubits[2].mQuatIndex != qX || mCubits[8].mQuatIndex != qX || mCubits[10].mQuatIndex != qX ||
704
        mCubits[3].mQuatIndex != qY || mCubits[9].mQuatIndex != qY || mCubits[11].mQuatIndex != qY ||
705
        mCubits[5].mQuatIndex != qZ || mCubits[6].mQuatIndex != qZ || mCubits[ 7].mQuatIndex != qZ  )
706
      {
707
      return false;
708
      }
709

    
710
    return ( qX==qY && qX==qZ ) || ( qY==mulQuat(qX,10) && qZ==mulQuat(qX,11) );
711
    }
712

    
713
///////////////////////////////////////////////////////////////////////////////////////////////////
714
// Square-2 is solved iff
715
// a) all of its cubits are rotated with the same quat
716
// b) its two 'middle' cubits are rotated with the same quat, the 6 'front' and 6 'back'
717
// edges and corners with this quat multiplied by QUATS[17] (i.e. those are upside down)
718
// and all the 12 left and right edges and corners also with the same quat multiplied by
719
// QUATS[23] - i.e. also upside down.
720

    
721
  private boolean isSolved3()
722
    {
723
    int index = mCubits[0].mQuatIndex;
724

    
725
    if( mCubits[1].mQuatIndex!=index ) return false;
726

    
727
    boolean solved = true;
728

    
729
    for(int i=2; i<mNumCubits; i++)
730
      {
731
      if( mCubits[i].mQuatIndex!=index )
732
        {
733
        solved = false;
734
        break;
735
        }
736
      }
737

    
738
    if( solved ) return true;
739

    
740
    int indexX = mulQuat(index,23);  // QUATS[23] = 180deg (1,0,0)
741
    int indexZ = mulQuat(index,17);  // QUATS[17] = 180deg (0,0,1)
742

    
743
    for(int i= 2; i<         18; i+=2) if( mCubits[i].mQuatIndex != indexZ ) return false;
744
    for(int i= 3; i<         18; i+=2) if( mCubits[i].mQuatIndex != indexX ) return false;
745
    for(int i=18; i< mNumCubits; i+=2) if( mCubits[i].mQuatIndex != indexX ) return false;
746
    for(int i=19; i< mNumCubits; i+=2) if( mCubits[i].mQuatIndex != indexZ ) return false;
747

    
748
    return true;
749
    }
750

    
751
///////////////////////////////////////////////////////////////////////////////////////////////////
752

    
753
  int computeRow(float[] pos, int axisIndex)
754
    {
755
    int ret=0;
756
    int len = pos.length / 3;
757
    Static3D axis = mAxis[axisIndex];
758
    float axisX = axis.get0();
759
    float axisY = axis.get1();
760
    float axisZ = axis.get2();
761
    float casted;
762

    
763
    for(int i=0; i<len; i++)
764
      {
765
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
766
      ret |= computeSingleRow(axisIndex,casted);
767
      }
768

    
769
    return ret;
770
    }
771

    
772
///////////////////////////////////////////////////////////////////////////////////////////////////
773

    
774
  private int computeSingleRow(int axisIndex,float casted)
775
    {
776
    int num = mNumCuts[axisIndex];
777

    
778
    for(int i=0; i<num; i++)
779
      {
780
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
781
      }
782

    
783
    return (1<<num);
784
    }
785

    
786
///////////////////////////////////////////////////////////////////////////////////////////////////
787

    
788
  private boolean wasRotateApplied()
789
    {
790
    return mEffects.exists(mRotateEffect.getID());
791
    }
792

    
793
///////////////////////////////////////////////////////////////////////////////////////////////////
794

    
795
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
796
    {
797
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
798
    }
799

    
800
///////////////////////////////////////////////////////////////////////////////////////////////////
801
// note the minus in front of the sin() - we rotate counterclockwise
802
// when looking towards the direction where the axis increases in values.
803

    
804
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
805
    {
806
    Static3D axis = mAxis[axisIndex];
807

    
808
    while( angleInDegrees<0 ) angleInDegrees += 360;
809
    angleInDegrees %= 360;
810
    
811
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
812
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
813

    
814
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
815
    }
816

    
817
///////////////////////////////////////////////////////////////////////////////////////////////////
818

    
819
  private synchronized void setupPosition(int[][] moves)
820
    {
821
    if( moves!=null )
822
      {
823
      Static4D quat;
824
      int index, axis, rowBitmap, angle;
825

    
826
      for(int[] move: moves)
827
        {
828
        axis     = move[0];
829
        rowBitmap= move[1];
830
        angle    = move[2]*(360/mBasicAngles[axis]);
831
        quat     = makeQuaternion(axis,angle);
832

    
833
        for(int j=0; j<mNumCubits; j++)
834
          if( belongsToRotation(j,axis,rowBitmap) )
835
            {
836
            index = mCubits[j].removeRotationNow(quat);
837
            mMesh.setEffectAssociation(j, mCubits[j].computeAssociation(),index);
838
            }
839
        }
840
      }
841
    }
842

    
843
///////////////////////////////////////////////////////////////////////////////////////////////////
844

    
845
  public int getScrambleType()
846
    {
847
    return 0;
848
    }
849

    
850
///////////////////////////////////////////////////////////////////////////////////////////////////
851

    
852
  int computeBitmapFromRow(int rowBitmap, int axis)
853
    {
854
    if( mIsBandaged )
855
      {
856
      int bitmap, initBitmap=0;
857

    
858
      while( initBitmap!=rowBitmap )
859
        {
860
        initBitmap = rowBitmap;
861

    
862
        for(int cubit=0; cubit<mNumCubits; cubit++)
863
          {
864
          bitmap = mCubits[cubit].getRotRow(axis);
865
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
866
          }
867
        }
868
      }
869

    
870
    return rowBitmap;
871
    }
872

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

    
877
  void clampPos(float[] pos, int offset)
878
    {
879
    float currError, minError = Float.MAX_VALUE;
880
    int minErrorIndex1 = -1;
881
    int minErrorIndex2 = -1;
882

    
883
    float x = pos[offset  ];
884
    float y = pos[offset+1];
885
    float z = pos[offset+2];
886

    
887
    float xo,yo,zo;
888

    
889
    for(int i=0; i<mNumCubits; i++)
890
      {
891
      int len = mOrigPos[i].length / 3;
892

    
893
      for(int j=0; j<len; j++)
894
        {
895
        xo = mOrigPos[i][3*j  ];
896
        yo = mOrigPos[i][3*j+1];
897
        zo = mOrigPos[i][3*j+2];
898

    
899
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
900

    
901
        if( currError<minError )
902
          {
903
          minError = currError;
904
          minErrorIndex1 = i;
905
          minErrorIndex2 = j;
906
          }
907
        }
908
      }
909

    
910
    if( minError< 0.1f ) // TODO: 0.1 ?
911
      {
912
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
913
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
914
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
915
      }
916
    }
917

    
918
///////////////////////////////////////////////////////////////////////////////////////////////////
919
// remember about the double cover or unit quaternions!
920

    
921
  int mulQuat(int q1, int q2)
922
    {
923
    Static4D result = QuatHelper.quatMultiply(mObjectQuats[q1],mObjectQuats[q2]);
924

    
925
    float rX = result.get0();
926
    float rY = result.get1();
927
    float rZ = result.get2();
928
    float rW = result.get3();
929

    
930
    final float MAX_ERROR = 0.1f;
931
    float dX,dY,dZ,dW;
932

    
933
    for(int i=0; i<mNumQuats; i++)
934
      {
935
      dX = mObjectQuats[i].get0() - rX;
936
      dY = mObjectQuats[i].get1() - rY;
937
      dZ = mObjectQuats[i].get2() - rZ;
938
      dW = mObjectQuats[i].get3() - rW;
939

    
940
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
941
          dY<MAX_ERROR && dY>-MAX_ERROR &&
942
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
943
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
944

    
945
      dX = mObjectQuats[i].get0() + rX;
946
      dY = mObjectQuats[i].get1() + rY;
947
      dZ = mObjectQuats[i].get2() + rZ;
948
      dW = mObjectQuats[i].get3() + rW;
949

    
950
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
951
          dY<MAX_ERROR && dY>-MAX_ERROR &&
952
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
953
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
954
      }
955

    
956
    return -1;
957
    }
958

    
959
///////////////////////////////////////////////////////////////////////////////////////////////////
960

    
961
  private float getAngle()
962
    {
963
    int pointNum = mRotationAngle.getNumPoints();
964

    
965
    if( pointNum>=1 )
966
      {
967
      return mRotationAngle.getPoint(pointNum-1).get0();
968
      }
969
    else
970
      {
971
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
972
      return 0;
973
      }
974
    }
975

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

    
978
  void setLibInterface(ObjectLibInterface inter)
979
    {
980
    mInterface = inter;
981
    }
982

    
983
///////////////////////////////////////////////////////////////////////////////////////////////////
984

    
985
  void initializeObject(int[][] moves)
986
    {
987
    solve();
988
    setupPosition(moves);
989
    }
990

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

    
993
  synchronized void removeRotationNow()
994
    {
995
    float angle = getAngle();
996
    double nearestAngleInRadians = angle*Math.PI/180;
997
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
998
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
999
    float axisX = mAxis[mCurrentRotAxis].get0();
1000
    float axisY = mAxis[mCurrentRotAxis].get1();
1001
    float axisZ = mAxis[mCurrentRotAxis].get2();
1002
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
1003

    
1004
    mRotationAngle.removeAll();
1005
    mRotationAngleStatic.set0(0);
1006

    
1007
    for(int i=0; i<mNumCubits; i++)
1008
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
1009
        {
1010
        int index = mCubits[i].removeRotationNow(quat);
1011
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),index);
1012
        }
1013
    }
1014

    
1015
///////////////////////////////////////////////////////////////////////////////////////////////////
1016

    
1017
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
1018
    {
1019
    if( wasRotateApplied() )
1020
      {
1021
      float angle = getAngle();
1022
      mRotationAngleStatic.set0(angle);
1023
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1024
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1025

    
1026
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1027
      mRotationAngle.resetToBeginning();
1028
      mRotationAngle.removeAll();
1029
      mRotationAngle.add(mRotationAngleStatic);
1030
      mRotationAngle.add(mRotationAngleMiddle);
1031
      mRotationAngle.add(mRotationAngleFinal);
1032
      mRotateEffect.notifyWhenFinished(listener);
1033

    
1034
      return mRotateEffect.getID();
1035
      }
1036

    
1037
    return 0;
1038
    }
1039

    
1040
///////////////////////////////////////////////////////////////////////////////////////////////////
1041

    
1042
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1043
    {
1044
    if( wasRotateApplied() )
1045
      {
1046
      mCurrentRotAxis = axis;
1047
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1048

    
1049
      mRotationAngleStatic.set0(0.0f);
1050
      mRotationAxis.set( mAxis[axis] );
1051
      mRotationAngle.setDuration(durationMillis);
1052
      mRotationAngle.resetToBeginning();
1053
      mRotationAngle.add(new Static1D(0));
1054
      mRotationAngle.add(new Static1D(angle));
1055
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1056
      mRotateEffect.notifyWhenFinished(listener);
1057

    
1058
      return mRotateEffect.getID();
1059
      }
1060

    
1061
    return 0;
1062
    }
1063

    
1064
///////////////////////////////////////////////////////////////////////////////////////////////////
1065

    
1066
  void continueRotation(float angleInDegrees)
1067
    {
1068
    mRotationAngleStatic.set0(angleInDegrees);
1069
    }
1070

    
1071
///////////////////////////////////////////////////////////////////////////////////////////////////
1072

    
1073
  synchronized void beginNewRotation(int axis, int row )
1074
    {
1075
    if( axis<0 || axis>=mNumAxis )
1076
      {
1077
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1078
      return;
1079
      }
1080
    if( row<0 || row>=mNumLayers[axis] )
1081
      {
1082
      android.util.Log.e("object", "invalid rotation row: "+row);
1083
      return;
1084
      }
1085

    
1086
    mCurrentRotAxis = axis;
1087
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1088
    mRotationAngleStatic.set0(0.0f);
1089
    mRotationAxis.set( mAxis[axis] );
1090
    mRotationAngle.add(mRotationAngleStatic);
1091
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1092
    }
1093

    
1094
///////////////////////////////////////////////////////////////////////////////////////////////////
1095

    
1096
  void setTextureMap(int cubit, int face, int newColor)
1097
    {
1098
    final float ratioW = 1.0f/mNumTexCols;
1099
    final float ratioH = 1.0f/mNumTexRows;
1100
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1101
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1102
    int col = newColor%mNumTexCols;
1103

    
1104
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1105
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1106
    }
1107

    
1108
///////////////////////////////////////////////////////////////////////////////////////////////////
1109

    
1110
  public int getCubitFaceColor(int cubit, int face)
1111
    {
1112
    int numFaces = mCubitFaceColors[cubit].length;
1113
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1114
    return puzzleFace<0 ? -1 : puzzleFace%mNumFaceColors;
1115
    }
1116

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

    
1119
  private int getCubitFaceFace(int cubit, int face)
1120
    {
1121
    int numFaces = mCubitFaceColors[cubit].length;
1122
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1123
    return puzzleFace<0 ? -1 : puzzleFace;
1124
    }
1125

    
1126
///////////////////////////////////////////////////////////////////////////////////////////////////
1127

    
1128
  void resetAllTextureMaps()
1129
    {
1130
    final float ratioW = 1.0f/mNumTexCols;
1131
    final float ratioH = 1.0f/mNumTexRows;
1132
    int cubColor, varColor, color, variant, row, col;
1133

    
1134
    for(int cubit=0; cubit<mNumCubits; cubit++)
1135
      {
1136
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1137
      variant = getCubitVariant(cubit,mNumLayers);
1138

    
1139
      for(int face=0; face<mNumCubitFaces; face++)
1140
        {
1141
        cubColor = getCubitFaceColor(cubit,face);
1142
        varColor = getVariantFaceColor(variant,face);
1143
        color    = cubColor<0 || varColor<0 ? mNumTextures : varColor*mNumFaceColors + cubColor;
1144
        row      = (mNumTexRows-1) - color/mNumTexCols;
1145
        col      = color%mNumTexCols;
1146

    
1147
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1148
        }
1149

    
1150
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1151
      }
1152
    }
1153

    
1154
///////////////////////////////////////////////////////////////////////////////////////////////////
1155

    
1156
  void releaseResources()
1157
    {
1158
    mTexture.markForDeletion();
1159
    mMesh.markForDeletion();
1160
    mEffects.markForDeletion();
1161

    
1162
    for(int j=0; j<mNumCubits; j++)
1163
      {
1164
      mCubits[j].releaseResources();
1165
      }
1166
    }
1167

    
1168
///////////////////////////////////////////////////////////////////////////////////////////////////
1169

    
1170
  synchronized void restorePreferences(SharedPreferences preferences)
1171
    {
1172
    boolean error = false;
1173

    
1174
    for(int i=0; i<mNumCubits; i++)
1175
      {
1176
      mQuatDebug[i] = mCubits[i].restorePreferences(preferences);
1177

    
1178
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1179
        {
1180
        mCubits[i].modifyCurrentPosition(mObjectQuats[mQuatDebug[i]]);
1181
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),mQuatDebug[i]);
1182
        }
1183
      else
1184
        {
1185
        error = true;
1186
        }
1187
      }
1188

    
1189
    if( error )
1190
      {
1191
      for(int i=0; i<mNumCubits; i++)
1192
        {
1193
        mCubits[i].solve();
1194
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),0);
1195
        }
1196
      }
1197
    }
1198

    
1199
///////////////////////////////////////////////////////////////////////////////////////////////////
1200

    
1201
  void savePreferences(SharedPreferences.Editor editor)
1202
    {
1203
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(editor);
1204
    }
1205

    
1206
///////////////////////////////////////////////////////////////////////////////////////////////////
1207

    
1208
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1209
    {
1210
    final float A = 0.8f;  // 0<A<1
1211

    
1212
    int prev = curr>0 ? curr-1 : len-1;
1213
    int next = curr<len-1 ? curr+1 : 0;
1214

    
1215
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1216
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1217
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1218
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1219

    
1220
    float len1= v1x*v1x+v1y*v1y;
1221
    float len2= v2x*v2x+v2y*v2y;
1222

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

    
1225
    return 1-A*cos;
1226
    }
1227

    
1228
///////////////////////////////////////////////////////////////////////////////////////////////////
1229

    
1230
  public ObjectSticker retSticker(int sticker)
1231
    {
1232
    if( mStickers==null )
1233
      {
1234
      float rad = getStickerRadius();
1235
      float str = getStickerStroke();
1236
      float[][] angles = getStickerAngles();
1237
      int numStickers = mStickerCoords.length;
1238
      mStickers = new ObjectSticker[numStickers];
1239

    
1240
      for(int s=0; s<numStickers; s++)
1241
        {
1242
        float scale = mStickerScales[s];
1243
        float radius = rad / scale;
1244
        float stroke = str / scale;
1245
        int len = mStickerCoords[s].length/2;
1246
        float[] radii = new float[len];
1247
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1248
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1249
        }
1250
      }
1251

    
1252
    return mStickers[sticker];
1253
    }
1254

    
1255
///////////////////////////////////////////////////////////////////////////////////////////////////
1256
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1257

    
1258
  public void adjustStickerCoords()
1259
    {
1260

    
1261
    }
1262

    
1263
///////////////////////////////////////////////////////////////////////////////////////////////////
1264

    
1265
  public Static4D[] getQuats()
1266
    {
1267
    if( mObjectQuats==null )
1268
      {
1269
      mObjectQuats = QuatGroupGenerator.computeGroup(mAxis,mBasicAngles);
1270
      }
1271

    
1272
    return mObjectQuats;
1273
    }
1274

    
1275
///////////////////////////////////////////////////////////////////////////////////////////////////
1276
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1277

    
1278
  private void createTexture()
1279
    {
1280
    Paint paint = new Paint();
1281
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_4444);
1282
    Canvas canvas = new Canvas(mBitmap);
1283

    
1284
    paint.setAntiAlias(true);
1285
    paint.setTextAlign(Paint.Align.CENTER);
1286
    paint.setStyle(Paint.Style.FILL);
1287

    
1288
    paint.setColor(COLOR_INTERNAL);
1289
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1290

    
1291
    int texture = 0;
1292
    FactorySticker factory = FactorySticker.getInstance();
1293

    
1294
    for(int row=0; row<mNumTexRows; row++)
1295
      for(int col=0; col<mNumTexCols; col++)
1296
        {
1297
        if( texture>=mNumTextures ) break;
1298
        ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1299
        int color = getColor(texture% mNumFaceColors);
1300
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, color, sticker);
1301
        texture++;
1302
        }
1303
    }
1304

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

    
1307
  void setTexture()
1308
    {
1309
    if( mBitmap==null ) createTexture();
1310

    
1311
    if( !mTexture.setTexture(mBitmap) )
1312
      {
1313
      int max = DistortedLibrary.getMaxTextureSize();
1314
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1315
      }
1316
    }
1317

    
1318
///////////////////////////////////////////////////////////////////////////////////////////////////
1319

    
1320
  void setObjectRatioNow(float sc, int nodeSize)
1321
    {
1322
    mObjectScreenRatio = sc;
1323
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1324
    mObjectScale.set(scale,scale,scale);
1325

    
1326
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1327
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1328
    }
1329

    
1330
///////////////////////////////////////////////////////////////////////////////////////////////////
1331

    
1332
  void setObjectRatio(float sizeChange, int nodeSize)
1333
    {
1334
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1335

    
1336
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1337
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1338

    
1339
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1340
    }
1341

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

    
1344
  void setNodeSize(int nodeSize)
1345
    {
1346
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1347
    }
1348

    
1349
///////////////////////////////////////////////////////////////////////////////////////////////////
1350

    
1351
  public float getRatio()
1352
    {
1353
    return mObjectScreenRatio;
1354
    }
1355

    
1356
///////////////////////////////////////////////////////////////////////////////////////////////////
1357

    
1358
  public float getObjectRatio()
1359
    {
1360
    return mObjectScreenRatio*mInitScreenRatio;
1361
    }
1362

    
1363
///////////////////////////////////////////////////////////////////////////////////////////////////
1364

    
1365
  boolean isSolved()
1366
    {
1367
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1368
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1369
    if( mSolvedFunctionIndex==2 ) return isSolved2();
1370
    if( mSolvedFunctionIndex==3 ) return isSolved3();
1371

    
1372
    return false;
1373
    }
1374

    
1375
///////////////////////////////////////////////////////////////////////////////////////////////////
1376

    
1377
  int computeNearestAngle(int axis, float angle, float speed)
1378
    {
1379
    int basicAngle   = mBasicAngles[axis>=mBasicAngles.length ? 0 : axis];
1380
    int nearestAngle = 360/basicAngle;
1381

    
1382
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1383
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1384

    
1385
    if( tmp!=0 ) return nearestAngle*tmp;
1386

    
1387
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1388
    }
1389

    
1390
///////////////////////////////////////////////////////////////////////////////////////////////////
1391
// INTERNAL API - those are called from 'effects' package
1392
///////////////////////////////////////////////////////////////////////////////////////////////////
1393

    
1394
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1395
    {
1396
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1397
    }
1398

    
1399
///////////////////////////////////////////////////////////////////////////////////////////////////
1400

    
1401
  public Static4D getRotationQuat()
1402
    {
1403
    return mQuat;
1404
    }
1405

    
1406
///////////////////////////////////////////////////////////////////////////////////////////////////
1407

    
1408
  public float getSize()
1409
    {
1410
    return mSize;
1411
    }
1412

    
1413
///////////////////////////////////////////////////////////////////////////////////////////////////
1414

    
1415
  public void apply(Effect effect, int position)
1416
    {
1417
    mEffects.apply(effect, position);
1418
    }
1419

    
1420
///////////////////////////////////////////////////////////////////////////////////////////////////
1421

    
1422
  public void remove(long effectID)
1423
    {
1424
    mEffects.abortById(effectID);
1425
    }
1426

    
1427
///////////////////////////////////////////////////////////////////////////////////////////////////
1428

    
1429
  public MeshBase getObjectMesh()
1430
    {
1431
    return mMesh;
1432
    }
1433

    
1434
///////////////////////////////////////////////////////////////////////////////////////////////////
1435

    
1436
  public DistortedEffects getObjectEffects()
1437
    {
1438
    return mEffects;
1439
    }
1440

    
1441
///////////////////////////////////////////////////////////////////////////////////////////////////
1442
// PUBLIC API
1443
///////////////////////////////////////////////////////////////////////////////////////////////////
1444

    
1445
  public int getCubitFaceColorIndex(int cubit, int face)
1446
    {
1447
    Static4D texMap = mMesh.getTextureMap(mNumFaceColors *cubit + face);
1448

    
1449
    int x = (int)(texMap.get0()/texMap.get2());
1450
    int y = (int)(texMap.get1()/texMap.get3());
1451

    
1452
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1453
    }
1454

    
1455
///////////////////////////////////////////////////////////////////////////////////////////////////
1456

    
1457
  public int[] getNumLayers()
1458
    {
1459
    return mNumLayers;
1460
    }
1461

    
1462
///////////////////////////////////////////////////////////////////////////////////////////////////
1463

    
1464
  public synchronized void solve()
1465
    {
1466
    for(int i=0; i<mNumCubits; i++)
1467
      {
1468
      mCubits[i].solve();
1469
      mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(), 0);
1470
      }
1471
    }
1472

    
1473
///////////////////////////////////////////////////////////////////////////////////////////////////
1474

    
1475
  public int getCubitQuatIndex(int cubit)
1476
    {
1477
    return mCubits[cubit].mQuatIndex;
1478
    }
1479

    
1480
///////////////////////////////////////////////////////////////////////////////////////////////////
1481

    
1482
  public int getCubitRotRow(int cubit, int axis)
1483
    {
1484
    return mCubits[cubit].getRotRow(axis);
1485
    }
1486

    
1487
///////////////////////////////////////////////////////////////////////////////////////////////////
1488

    
1489
  public Bitmap getStickerBitmap()
1490
    {
1491
    return mBitmap;
1492
    }
1493

    
1494
///////////////////////////////////////////////////////////////////////////////////////////////////
1495

    
1496
  public DistortedNode getNode()
1497
    {
1498
    return mNode;
1499
    }
1500

    
1501
///////////////////////////////////////////////////////////////////////////////////////////////////
1502

    
1503
  public ObjectType getObjectType()
1504
    {
1505
    return intGetObjectType(mNumLayers);
1506
    }
1507

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

    
1510
  public int getNumStickerTypes()
1511
    {
1512
    return mNumStickerTypes;
1513
    }
1514

    
1515
///////////////////////////////////////////////////////////////////////////////////////////////////
1516
// this is here only so it can be overridden in TwistyJSON soo that we can get this from JSON.
1517

    
1518
  public int getNumCubitFaces()
1519
    {
1520
    return 0;
1521
    }
1522

    
1523
///////////////////////////////////////////////////////////////////////////////////////////////////
1524

    
1525
  public TouchControl getTouchControl()
1526
    {
1527
    if( mTouchControl==null )
1528
      {
1529
      switch(getTouchControlType())
1530
        {
1531
        case TC_TETRAHEDRON    : mTouchControl = new TouchControlTetrahedron(this);
1532
                                 break;
1533
        case TC_HEXAHEDRON     : mTouchControl = new TouchControlHexahedron(this);
1534
                                 break;
1535
        case TC_OCTAHEDRON     : mTouchControl = new TouchControlOctahedron(this);
1536
                                 break;
1537
        case TC_DODECAHEDRON   : mTouchControl = new TouchControlDodecahedron(this);
1538
                                 break;
1539
        case TC_CUBOID         : int[] numLayers = getNumLayers();
1540
                                 mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1541
                                 break;
1542
        case TC_CHANGING_MIRROR: mTouchControl = new TouchControlMirror(this);
1543
                                 break;
1544
        case TC_CHANGING_SQUARE: mTouchControl = new TouchControlSquare(this);
1545
                                 break;
1546
        }
1547
      }
1548
    return mTouchControl;
1549
    }
1550

    
1551
///////////////////////////////////////////////////////////////////////////////////////////////////
1552

    
1553
  public String getShortName()
1554
    {
1555
    return getObjectType().name();
1556
    }
1557

    
1558
///////////////////////////////////////////////////////////////////////////////////////////////////
1559

    
1560
  protected void setReader(JsonReader reader)
1561
    {
1562
    // empty
1563
    }
1564

    
1565
///////////////////////////////////////////////////////////////////////////////////////////////////
1566

    
1567
  protected abstract ObjectType intGetObjectType(int[] numLayers);
1568

    
1569
  // for JSON only
1570
  public abstract int getTouchControlType();
1571
  public abstract int getTouchControlSplit();
1572
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1573
  public abstract int[][][] getEnabled();
1574
  public abstract float[] getDist3D(int[] numLayers);
1575
  public abstract Static3D[] getFaceAxis();
1576
  public abstract ScrambleState[] getScrambleStates();
1577
  public abstract float[][] getCuts(int[] numLayers);
1578
  public abstract float getStickerRadius();
1579
  public abstract float getStickerStroke();
1580
  public abstract float[][] getStickerAngles();
1581
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1582
  public abstract ObjectShape getObjectShape(int variant);
1583
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
1584
  public abstract int getNumCubitVariants(int[] numLayers);
1585
  public abstract float[][] getCubitPositions(int[] numLayers);
1586
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
1587
  public abstract int getNumFaceColors();
1588
  public abstract float getScreenRatio();
1589
  public abstract int getColor(int face);
1590

    
1591
  // not only for JSON
1592
  public abstract Static3D[] getRotationAxis();
1593
  public abstract int[] getBasicAngles();
1594
  public abstract int getNumFaces();
1595
  public abstract String getObjectName();
1596
  public abstract String getInventor();
1597
  public abstract int getYearOfInvention();
1598
  public abstract int getComplexity();
1599
  public abstract int getFOV();
1600
  }
(11-11/13)