Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ 605f319b

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2020 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Magic Cube.                                                              //
5
//                                                                                               //
6
// Magic Cube is proprietary software licensed under an EULA which you should have received      //
7
// along with the code. If not, check https://distorted.org/magic/License-Magic-Cube.html        //
8
///////////////////////////////////////////////////////////////////////////////////////////////////
9

    
10
package org.distorted.objectlib.main;
11

    
12
import java.io.DataInputStream;
13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.util.Random;
16

    
17
import android.content.SharedPreferences;
18
import android.graphics.Bitmap;
19
import android.graphics.Canvas;
20
import android.graphics.Paint;
21

    
22
import org.distorted.library.effect.Effect;
23
import org.distorted.library.effect.MatrixEffectMove;
24
import org.distorted.library.effect.MatrixEffectQuaternion;
25
import org.distorted.library.effect.MatrixEffectScale;
26
import org.distorted.library.effect.VertexEffectQuaternion;
27
import org.distorted.library.effect.VertexEffectRotate;
28
import org.distorted.library.effect.VertexEffectSink;
29
import org.distorted.library.main.DistortedEffects;
30
import org.distorted.library.main.DistortedLibrary;
31
import org.distorted.library.main.DistortedNode;
32
import org.distorted.library.main.DistortedTexture;
33
import org.distorted.library.main.QuatHelper;
34
import org.distorted.library.mesh.MeshBase;
35
import org.distorted.library.mesh.MeshFile;
36
import org.distorted.library.mesh.MeshJoined;
37
import org.distorted.library.message.EffectListener;
38
import org.distorted.library.type.Dynamic1D;
39
import org.distorted.library.type.Static1D;
40
import org.distorted.library.type.Static3D;
41
import org.distorted.library.type.Static4D;
42

    
43
import org.distorted.objectlib.helpers.FactoryCubit;
44
import org.distorted.objectlib.helpers.FactorySticker;
45
import org.distorted.objectlib.helpers.ObjectFaceShape;
46
import org.distorted.objectlib.helpers.ObjectLibInterface;
47
import org.distorted.objectlib.helpers.ObjectShape;
48
import org.distorted.objectlib.helpers.ObjectSignature;
49
import org.distorted.objectlib.helpers.ObjectSticker;
50
import org.distorted.objectlib.helpers.ObjectStickerOverride;
51
import org.distorted.objectlib.helpers.ObjectVertexEffects;
52
import org.distorted.objectlib.helpers.QuatGroupGenerator;
53
import org.distorted.objectlib.scrambling.ObjectScrambler;
54
import org.distorted.objectlib.json.JsonReader;
55
import org.distorted.objectlib.scrambling.ScrambleEdgeGenerator;
56
import org.distorted.objectlib.touchcontrol.*;
57

    
58
import static org.distorted.objectlib.touchcontrol.TouchControl.*;
59

    
60
///////////////////////////////////////////////////////////////////////////////////////////////////
61

    
62
public abstract class TwistyObject
63
  {
64
  public static final int MESH_NICE = 0;
65
  public static final int MESH_FAST = 1;
66

    
67
  public static final int MODE_ICON = 0;
68
  public static final int MODE_NORM = 1;
69

    
70
  public static final int COLOR_YELLOW   = 0xffffff00;
71
  public static final int COLOR_WHITE    = 0xffffffff;
72
  public static final int COLOR_BLUE     = 0xff0000ff;
73
  public static final int COLOR_GREEN    = 0xff00bb00;
74
  public static final int COLOR_RED      = 0xff990000;
75
  public static final int COLOR_ORANGE   = 0xffff6200;
76
  public static final int COLOR_GREY     = 0xff727c7b;
77
  public static final int COLOR_VIOLET   = 0xff7700bb;
78
  public static final int COLOR_STROKE   = 0xff000000;
79
  public static final int COLOR_INTERNAL = 0xff000000;
80

    
81
  private static final int STATE_NOTHING = 0;
82
  private static final int STATE_ROTATE  = 1;
83
  private static final int STATE_FINISH  = 2;
84

    
85
  public static final int TEXTURE_HEIGHT = 256;
86
  static final int NUM_STICKERS_IN_ROW = 4;
87

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

    
93
  private static final float MAX_SIZE_CHANGE = 1.35f;
94
  private static final float MIN_SIZE_CHANGE = 0.75f;
95

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

    
99
  protected float[][] mStickerCoords;
100
  protected Static4D[] mObjectQuats;
101

    
102
  private int[][] mStickerVariants;
103
  private float[] mStickerScales;
104
  private Cubit[] mCubits;
105
  private MeshBase[] mMeshes;
106
  private int mNumCubits, mNumQuats, mNumFaceColors, mNumTextures, mNumOverrides;
107
  private int mNumCubitFaces, mNumStickerTypes;
108
  private Static3D[] mAxis;
109
  private float[][] mCuts;
110
  private int[] mNumCuts;
111
  private float[][] mOrigPos;
112
  private Static4D[] mOrigQuat;
113
  private Static4D[] mMixupModeQuats;
114
  private boolean mIsInMixupMode;
115
  private Static4D mQuat;
116
  private int[] mNumLayers;
117
  private float mSize;
118
  private DistortedEffects mEffects;
119
  private VertexEffectRotate mRotateEffect;
120
  private Dynamic1D mRotationAngle;
121
  private Static3D mRotationAxis;
122
  private Static3D mObjectScale;
123
  private int[] mQuatDebug;
124
  private Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
125
  private DistortedTexture mTexture;
126
  private float mInitScreenRatio;
127
  private int mSolvedFunctionIndex;
128
  private boolean mIsBandaged;
129
  private float mObjectScreenRatio;
130
  private int[][] mSolvedQuats;
131
  private int[][] mQuatMult;
132
  private int[] mTmpQuats;
133
  private int mNumTexRows, mNumTexCols;
134
  private int mRotRowBitmap;
135
  private int mCurrentRotAxis;
136
  private MeshBase mMesh;
137
  private ObjectScrambler mScrambler;
138
  private TouchControl mTouchControl;
139
  private DistortedNode mNode;
140
  private ObjectLibInterface mInterface;
141
  private Bitmap mBitmap;
142
  private ObjectSticker[] mStickers;
143
  private ObjectShape[] mShapes;
144
  private int mNumCubitVariants;
145
  private int[][] mCubitFaceColors;
146
  private int[][] mVariantFaceIsOuter;
147
  private int[][] mBasicAngles;
148
  private int mIconMode;
149
  private InitData mInitData;
150
  private float[][] mRowOffsets;
151
  private boolean[] mBelongs;
152
  private float[] mTmp;
153
  private int mNumPuzzleFaces;
154
  private ObjectStickerOverride[] mStickerOverrides;
155
  private boolean mError;
156
  private String mErrorString;
157
  private int mMaxNumLayers;
158
  private int mNumAxis;
159
  private int mPointNum;
160
  private int mRotationState;
161

    
162
  //////////////////// SOLVED1 ////////////////////////
163

    
164
  private int[] mFaceMap;
165
  private int[][] mScramble;
166
  private int[] mColors;
167

    
168
///////////////////////////////////////////////////////////////////////////////////////////////////
169

    
170
  TwistyObject(InputStream jsonStream, int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream meshStream)
171
    {
172
    try
173
      {
174
      JsonReader reader = new JsonReader();
175
      reader.parseJsonFile(jsonStream);
176
      setReader(reader);
177
      mNumLayers = reader.getNumLayers();
178
      mSize      = reader.getSize();
179
      mInitData  = null;
180
      initialize(meshState,iconMode,quat,move,scale,meshStream,true);
181
      mError = false;
182
      mErrorString=null;
183
      }
184
    catch(Exception ex)
185
      {
186
      mError = true;
187
      mErrorString = ex.getMessage();
188
      }
189
    }
190

    
191
///////////////////////////////////////////////////////////////////////////////////////////////////
192

    
193
  public TwistyObject(InitData data, int meshState, int iconMode, float size, Static4D quat, Static3D move, float scale, InputStream meshStream)
194
    {
195
    mNumLayers = data.getNumLayers();
196
    mSize      = size;
197
    mInitData  = data;
198
    initialize(meshState,iconMode,quat,move,scale,meshStream,false);
199
    mError = false;
200
    mErrorString = null;
201
    }
202

    
203
///////////////////////////////////////////////////////////////////////////////////////////////////
204

    
205
  private void debugQuat(Static4D quat, int cubitIndex, float axisX, float axisY, float axisZ, float angle, int place)
206
    {
207
    float[] tracking = mCubits[cubitIndex].getTrackingPoint();
208

    
209
    String problem = (getShortName()+" "+cubitIndex+" "+quat.get0()+" "+quat.get1()+" "+quat.get2()+" "+quat.get3());
210
    problem += (" "+angle+" "+place+" "+tracking[0]+" "+tracking[1]+" "+tracking[2]);
211
    problem += (" "+axisX+" "+axisY+" "+axisZ)+" "+mPointNum;
212

    
213
    mInterface.reportProblem(problem,true);
214
    }
215

    
216
///////////////////////////////////////////////////////////////////////////////////////////////////
217

    
218
  private void initialize(int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream meshStream, boolean fromJSON)
219
    {
220
    mRotationState = STATE_NOTHING;
221
    mIconMode = iconMode;
222
    mQuat = quat;
223
    mAxis = getRotationAxis();
224
    mInitScreenRatio = getScreenRatio();
225
    mSolvedFunctionIndex = getSolvedFunctionIndex();
226
    mBasicAngles = getBasicAngles();
227
    mObjectQuats = getQuats();
228
    mNumQuats = mObjectQuats.length;
229
    mOrigPos = getCubitPositions(mNumLayers);
230
    mNumPuzzleFaces = getNumFaces();
231
    mRowOffsets = new float[mNumPuzzleFaces][3];
232
    mTmp = new float[4];
233

    
234
    mNumAxis = mAxis.length;
235
    mCuts = getCuts(mNumLayers);
236
    mNumCuts = new int[mNumAxis];
237
    mMaxNumLayers = -1;
238
    for(int i=0; i<mNumAxis; i++)
239
      {
240
      if( mMaxNumLayers<mNumLayers[i] ) mMaxNumLayers = mNumLayers[i];
241
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
242
      }
243

    
244
    mNumCubits = mOrigPos.length;
245
    mNumFaceColors = getNumFaceColors();
246
    mBelongs = new boolean[mNumCubits];
247

    
248
    int scramblingType = getScrambleType();
249
    int[][] edges = getScrambleEdges();
250
    int[][] algorithms = getScrambleAlgorithms();
251

    
252
    // if( edges!=null )      print_table("EDGES", edges);
253
    // if( algorithms!=null ) print_table("ALGOS", algorithms);
254

    
255
    mScrambler = new ObjectScrambler(scramblingType,mNumAxis,mNumLayers,algorithms,edges);
256

    
257
    boolean bandaged=false;
258

    
259
    for( int c=0; c<mNumCubits; c++)
260
      {
261
      if( mOrigPos[c].length>3 )
262
        {
263
        bandaged=true;
264
        break;
265
        }
266
      }
267
    mIsBandaged = bandaged;
268
    mQuatDebug = new int[mNumCubits];
269

    
270
    mRotationAngle= new Dynamic1D();
271
    mRotationAxis = new Static3D(1,0,0);
272
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
273

    
274
    mRotationAngleStatic = new Static1D(0);
275
    mRotationAngleMiddle = new Static1D(0);
276
    mRotationAngleFinal  = new Static1D(0);
277

    
278
    mObjectScale = new Static3D(scale,scale,scale);
279
    setObjectRatioNow(scale,720);
280

    
281
    mEffects = new DistortedEffects();
282
    createQuaternionEffects();
283

    
284
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
285
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
286
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
287

    
288
    boolean fromDMESH = (meshStream!=null && meshState==MESH_NICE);
289
    getQuatsAndShapes(fromDMESH,fromJSON);
290
    createMeshAndCubits(meshStream,meshState,fromDMESH);
291
    setUpTextures(fromDMESH,fromJSON);
292
    createDataStructuresForSolved();
293

    
294
    mEffects.apply(mRotateEffect);
295
    mEffects.apply(quatEffect);
296
    mEffects.apply(scaleEffect);
297
    mEffects.apply(moveEffect);
298

    
299
    mNode = new DistortedNode(mTexture,mEffects,mMesh);
300
    }
301

    
302
///////////////////////////////////////////////////////////////////////////////////////////////////
303

    
304
  private static void print_table(String mess, int[][] table)
305
    {
306
    android.util.Log.e("D", mess);
307

    
308
    int len = table.length;
309

    
310
    for(int i=0; i<len; i++)
311
      {
312
      String m = "";
313
      int l = table[i].length;
314
      for(int j=0; j<l; j++) m += (" "+table[i][j]);
315
      android.util.Log.e("D", m);
316
      }
317
    }
318

    
319
///////////////////////////////////////////////////////////////////////////////////////////////////
320

    
321
  private void createQuaternionEffects()
322
    {
323
    if( mNumQuats<=ObjectControl.MAX_QUATS )
324
      {
325
      mIsInMixupMode = false;
326

    
327
      for( int q=0; q<mNumQuats; q++)
328
        {
329
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mObjectQuats[q],CENTER);
330
        vq.setMeshAssociation(0,q);
331
        mEffects.apply(vq);
332
        }
333
      }
334
    else if( mNumCubits<=ObjectControl.MAX_QUATS )
335
      {
336
      mIsInMixupMode = true;
337
      mMixupModeQuats = new Static4D[mNumCubits];
338

    
339
      for( int q=0; q<mNumCubits; q++)
340
        {
341
        mMixupModeQuats[q] = new Static4D(mObjectQuats[0]);
342
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mMixupModeQuats[q],CENTER);
343
        vq.setMeshAssociation(0,q);
344
        mEffects.apply(vq);
345
        }
346
      }
347
    else
348
      {
349
      android.util.Log.e("D", "object has too many quaternions ("+mNumQuats+") or too many cubits ("+mNumCubits+")");
350
      }
351
    }
352

    
353
///////////////////////////////////////////////////////////////////////////////////////////////////
354

    
355
  private Static3D getPos(float[] origPos)
356
    {
357
    int len = origPos.length/3;
358
    float sumX = 0.0f;
359
    float sumY = 0.0f;
360
    float sumZ = 0.0f;
361

    
362
    for(int i=0; i<len; i++)
363
      {
364
      sumX += origPos[3*i  ];
365
      sumY += origPos[3*i+1];
366
      sumZ += origPos[3*i+2];
367
      }
368

    
369
    sumX /= len;
370
    sumY /= len;
371
    sumZ /= len;
372

    
373
    return new Static3D(sumX,sumY,sumZ);
374
    }
375

    
376
///////////////////////////////////////////////////////////////////////////////////////////////////
377

    
378
  private void createOuterFaces()
379
    {
380
    for(int v=0; v<mNumCubitVariants; v++)
381
      {
382
      int[][] indices = mShapes[v].getVertIndices();
383
      int faces = indices.length;
384
      mVariantFaceIsOuter[v] = new int[faces];
385
      }
386

    
387
    for( int cubit=0; cubit<mNumCubits; cubit++)
388
      {
389
      int variant = getCubitVariant(cubit,mNumLayers);
390
      int[][] indices = mShapes[variant].getVertIndices();
391
      int numFaces = indices.length;
392

    
393
      for(int face=0; face<numFaces; face++)
394
        if( getCubitFaceColor(cubit,face)>=0 )
395
          {
396
          mVariantFaceIsOuter[variant][face] = 1;
397
          }
398
      }
399
    }
400

    
401
///////////////////////////////////////////////////////////////////////////////////////////////////
402

    
403
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
404
    {
405
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
406

    
407
    if( !fromDMESH || !fromJSON )
408
      {
409
      FactoryCubit factory = FactoryCubit.getInstance();
410
      factory.clear();
411

    
412
      mOrigQuat = new Static4D[mNumCubits];
413
      for(int i=0; i<mNumCubits; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
414

    
415
      mShapes = new ObjectShape[mNumCubitVariants];
416
      for(int i=0; i<mNumCubitVariants; i++) mShapes[i] = getObjectShape(i);
417
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
418
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
419

    
420
      if( !fromJSON )
421
        {
422
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
423
        createOuterFaces();
424
        }
425

    
426
      if( fromDMESH )
427
        {
428
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
429
        }
430
      }
431
    }
432

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

    
435
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH)
436
    {
437
    mCubits = new Cubit[mNumCubits];
438

    
439
    if( fromDMESH )
440
      {
441
      DataInputStream dos = new DataInputStream(stream);
442
      mMesh = new MeshFile(dos);
443

    
444
      try
445
        {
446
        stream.close();
447
        }
448
      catch(IOException e)
449
        {
450
        android.util.Log.e("meshFile", "Error closing InputStream: "+e);
451
        }
452
      }
453
    else
454
      {
455
      MeshBase[] cubitMesh = new MeshBase[mNumCubits];
456

    
457
      for(int i=0; i<mNumCubits; i++)
458
        {
459
        cubitMesh[i] = createCubitMesh(i,mNumLayers,meshState,mNumCubitFaces);
460
        Static3D pos = getPos(mOrigPos[i]);
461
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
462
        }
463

    
464
      mMesh = new MeshJoined(cubitMesh);
465

    
466
      float pillowCoeff = getPillowCoeff();
467

    
468
      if( pillowCoeff!=1.0f )
469
        {
470
        float radius = getCircumscribedRadius();
471
        Static1D coeff = new Static1D(pillowCoeff);
472
        Static4D region= new Static4D(0,0,0,radius);
473
        VertexEffectSink sink = new VertexEffectSink(coeff,CENTER,region);
474
        mMesh.apply(sink);
475
        }
476
      }
477

    
478
    for(int i=0; i<mNumCubits; i++)
479
      {
480
      mCubits[i] = new Cubit(this,mOrigPos[i],mNumAxis,mMaxNumLayers,i);
481
      setCubitQuat(i,mCubits[i].computeAssociation(),0);
482
      }
483
    }
484

    
485
///////////////////////////////////////////////////////////////////////////////////////////////////
486

    
487
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState, int numComponents)
488
    {
489
    int variant = getCubitVariant(cubit,numLayers);
490

    
491
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
492

    
493
    if( mMeshes[variant]==null )
494
      {
495
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
496
      ObjectVertexEffects effects = getVertexEffects(variant);
497
      FactoryCubit factory = FactoryCubit.getInstance();
498
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
499
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,effects, meshState, numComponents);
500
      }
501

    
502
    MeshBase mesh = mMeshes[variant].copy(true);
503
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
504
    mesh.apply(quat,0xffffffff,0);
505

    
506
    return mesh;
507
    }
508

    
509
///////////////////////////////////////////////////////////////////////////////////////////////////
510

    
511
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
512
    {
513
    mTexture = new DistortedTexture();
514

    
515
    if( fromJSON )
516
      {
517
      mNumStickerTypes = getNumStickerTypes();
518
      mNumCubitFaces = getNumCubitFaces();
519
      }
520
    else
521
      {
522
      FactoryCubit factory = FactoryCubit.getInstance();
523
      mStickerCoords   = factory.getStickerCoords();
524
      mStickerVariants = factory.getStickerVariants();
525
      mStickerScales   = factory.getStickerScales();
526
      adjustStickerCoords();
527
      mNumStickerTypes = (mStickerCoords==null ? 0 : mStickerCoords.length);
528
      }
529

    
530
    mStickerOverrides = getStickerOverrides();
531
    mNumOverrides = mStickerOverrides==null ? 0 : mStickerOverrides.length;
532

    
533
    mNumTextures= mNumFaceColors*mNumStickerTypes + mNumOverrides;
534
    mNumTexCols = NUM_STICKERS_IN_ROW;
535
    mNumTexRows = (mNumTextures+1)/NUM_STICKERS_IN_ROW;
536
    if( mNumTexCols*mNumTexRows < mNumTextures+1 ) mNumTexRows++;
537

    
538
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
539
    else overrideCubitFaceColor();
540

    
541
    setTexture();
542
    }
543

    
544
///////////////////////////////////////////////////////////////////////////////////////////////////
545

    
546
  private int getMultQuat(int index1, int index2)
547
    {
548
    if( mQuatMult==null )
549
      {
550
      mQuatMult = new int[mNumQuats][mNumQuats];
551

    
552
      for(int i=0; i<mNumQuats; i++)
553
        for(int j=0; j<mNumQuats; j++) mQuatMult[i][j] = -1;
554
      }
555

    
556
    if( index1<mNumQuats && index2<mNumQuats )
557
      {
558
      if( mQuatMult[index1][index2]==-1 ) mQuatMult[index1][index2] = mulQuat(index1,index2);
559
      return mQuatMult[index1][index2];
560
      }
561

    
562
    return -1;
563
    }
564

    
565
///////////////////////////////////////////////////////////////////////////////////////////////////
566

    
567
  public InitData getInitData()
568
    {
569
    return mInitData;
570
    }
571

    
572
///////////////////////////////////////////////////////////////////////////////////////////////////
573

    
574
  public boolean isInIconMode()
575
    {
576
    return mIconMode==MODE_ICON;
577
    }
578

    
579
///////////////////////////////////////////////////////////////////////////////////////////////////
580

    
581
  public int getVariantStickerShape(int variant, int face)
582
    {
583
    return face>=mStickerVariants[variant].length ? -1 : mStickerVariants[variant][face];
584
    }
585

    
586
///////////////////////////////////////////////////////////////////////////////////////////////////
587

    
588
  public boolean shouldResetTextureMaps()
589
    {
590
    return false;
591
    }
592

    
593
///////////////////////////////////////////////////////////////////////////////////////////////////
594

    
595
  public int[][] getScrambleAlgorithms()
596
    {
597
    return ScrambleEdgeGenerator.getScramblingAlgorithms(mBasicAngles);
598
    }
599

    
600
///////////////////////////////////////////////////////////////////////////////////////////////////
601

    
602
  private void createDataStructuresForSolved()
603
    {
604
    mTmpQuats = new int[mNumQuats];
605
    mSolvedQuats = getSolvedQuats();
606
    }
607

    
608
///////////////////////////////////////////////////////////////////////////////////////////////////
609
// This is used to build internal data structures for the generic 'isSolved()'
610
//
611
// if this is an internal cubit (all faces black): return -1
612
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
613
// Color index, i.e. the index into the 'FACE_COLORS' table.
614
// else (edge or corner cubit, more than one non-black face): return -2.
615

    
616
  protected int retCubitSolvedStatus(int cubit)
617
    {
618
    int numNonBlack=0, nonBlackIndex=-1, stiShape, cubColor;
619
    int variant = getCubitVariant(cubit,mNumLayers);
620

    
621
    for(int face=0; face<mNumCubitFaces; face++)
622
      {
623
      stiShape = getVariantStickerShape(variant,face);
624
      int numFaces = mCubitFaceColors[cubit].length;
625
      cubColor = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
626

    
627
      if( stiShape>=0 && cubColor>=0 )
628
        {
629
        numNonBlack++;
630
        nonBlackIndex = cubColor;
631
        }
632
      }
633

    
634
    if( numNonBlack==0 ) return -1;
635
    if( numNonBlack>=2 ) return -2;
636

    
637
    return nonBlackIndex;
638
    }
639

    
640
///////////////////////////////////////////////////////////////////////////////////////////////////
641

    
642
  private boolean sticksOut(Static3D[] faceAxis, float[] dist, float x, float y, float z )
643
    {
644
    final float MAXERR = 0.05f;
645
    int numAxis = dist.length;
646

    
647
    for(int i=0; i<numAxis; i++)
648
      {
649
      Static3D ax = faceAxis[i];
650
      float len = ax.get0()*x + ax.get1()*y + ax.get2()*z;
651
      if( len>mSize*dist[i]+MAXERR ) return true;
652
      }
653

    
654
    return false;
655
    }
656

    
657
///////////////////////////////////////////////////////////////////////////////////////////////////
658

    
659
  private boolean doesNotStickOut(int variant, float px, float py, float pz, float[] tmp, Static4D quat)
660
    {
661
    float[][] vertices = mShapes[variant].getVertices();
662
    Static3D[] axis = getFaceAxis();
663
    float[] dist3D = getDist3D(mNumLayers);
664

    
665
    for( float[] vertex : vertices)
666
      {
667
      float x = vertex[0];
668
      float y = vertex[1];
669
      float z = vertex[2];
670

    
671
      QuatHelper.rotateVectorByQuat(tmp, x, y, z, 1, quat);
672

    
673
      float mx = tmp[0] + px;
674
      float my = tmp[1] + py;
675
      float mz = tmp[2] + pz;
676

    
677
      if( sticksOut(axis, dist3D, mx,my,mz) ) return false;
678
      }
679

    
680
    return true;
681
    }
682

    
683
///////////////////////////////////////////////////////////////////////////////////////////////////
684

    
685
  private float computeAvg(float[] pos, int offset)
686
    {
687
    int len = pos.length/3;
688
    float ret=0.0f;
689
    for(int i=0; i<len; i++) ret += pos[3*i+offset];
690
    ret /= len;
691

    
692
    return ret;
693
    }
694

    
695
///////////////////////////////////////////////////////////////////////////////////////////////////
696

    
697
  protected void displayCubitQuats()
698
    {
699
    StringBuilder builder = new StringBuilder();
700
    float[] tmp = new float[4];
701
    float ERR = 0.01f;
702

    
703
    for(int cubit=0; cubit<mNumCubits; cubit++)
704
      {
705
      builder.append(cubit);
706
      builder.append(" : ");
707

    
708
      int refCubit,variant = getCubitVariant(cubit,mNumLayers);
709

    
710
      for(refCubit=0; refCubit<mNumCubits; refCubit++)
711
        {
712
        if( getCubitVariant(refCubit,mNumLayers)==variant ) break;
713
        }
714

    
715
      float[] curpos = mOrigPos[cubit];
716
      float[] refpos = mOrigPos[refCubit];
717
      float refX = computeAvg(refpos,0);
718
      float refY = computeAvg(refpos,1);
719
      float refZ = computeAvg(refpos,2);
720
      float curX = computeAvg(curpos,0);
721
      float curY = computeAvg(curpos,1);
722
      float curZ = computeAvg(curpos,2);
723

    
724
      for(int quat=0; quat<mNumQuats; quat++)
725
        {
726
        QuatHelper.rotateVectorByQuat(tmp,refX,refY,refZ,0,mObjectQuats[quat]);
727

    
728
        float dx = tmp[0]-curX;
729
        float dy = tmp[1]-curY;
730
        float dz = tmp[2]-curZ;
731

    
732
        if( dx>-ERR && dx<ERR && dy>-ERR && dy<ERR && dz>-ERR && dz<ERR )
733
          {
734
          if( doesNotStickOut(variant,curX,curY,curZ,tmp,mObjectQuats[quat]) )
735
            {
736
            builder.append(quat);
737
            builder.append(',');
738
            }
739
          else
740
            {
741
            android.util.Log.e("D", "cubit: "+cubit+" quat: "+quat+" : center correct, but shape sticks out");
742
            }
743
          }
744
        }
745

    
746
      builder.append('\n');
747
      }
748

    
749
    android.util.Log.e("D", "cubitQuats: \n"+builder );
750
    }
751

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

    
754
  protected int[] buildSolvedQuats(Static3D faceAx)
755
    {
756
    final float MAXD = 0.0001f;
757
    float x = faceAx.get0();
758
    float y = faceAx.get1();
759
    float z = faceAx.get2();
760
    float a,dx,dy,dz,qx,qy,qz;
761
    Static4D quat;
762
    int place = 0;
763

    
764
    for(int q=1; q<mNumQuats; q++)
765
      {
766
      quat = mObjectQuats[q];
767
      qx = quat.get0();
768
      qy = quat.get1();
769
      qz = quat.get2();
770

    
771
           if( x!=0.0f ) { a = qx/x; }
772
      else if( y!=0.0f ) { a = qy/y; }
773
      else               { a = qz/z; }
774

    
775
      dx = a*x-qx;
776
      dy = a*y-qy;
777
      dz = a*z-qz;
778

    
779
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
780
        {
781
        mTmpQuats[place++] = q;
782
        }
783
      }
784

    
785
    if( place!=0 )
786
      {
787
      int[] ret = new int[place];
788
      System.arraycopy(mTmpQuats,0,ret,0,place);
789
      return ret;
790
      }
791

    
792
    return null;
793
    }
794

    
795
///////////////////////////////////////////////////////////////////////////////////////////////////
796

    
797
  public int getCubitRotationType(int cubit)
798
    {
799
    return Cubit.TYPE_NORMAL;
800
    }
801

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

    
804
  float[] getTrackingPoint(int cubitIndex, int cubitType)
805
    {
806
    if( cubitType!=Cubit.TYPE_NORMAL )
807
      {
808
      int variant = getCubitVariant(cubitIndex,mNumLayers);
809

    
810
      // object must have been created from JSON
811
      if( mVariantFaceIsOuter==null || mVariantFaceIsOuter[variant]==null )
812
        {
813
        mVariantFaceIsOuter = getVariantFaceIsOuter();
814
        }
815
      if( mShapes==null )
816
        {
817
        mShapes = new ObjectShape[mNumCubitVariants];
818
        }
819
      if( mShapes[variant]==null )
820
        {
821
        mShapes[variant] = getObjectShape(variant);
822
        }
823
      if( mOrigQuat==null )
824
        {
825
        mOrigQuat = new Static4D[mNumCubits];
826
        }
827
      if( mOrigQuat[cubitIndex]==null )
828
        {
829
        mOrigQuat[cubitIndex] = getCubitQuats(cubitIndex,mNumLayers);
830
        }
831

    
832
      int[][] indices = mShapes[variant].getVertIndices();
833
      int outer=-1, faces = indices.length;
834

    
835
      for(int i=0; i<faces; i++)
836
        {
837
        if( mVariantFaceIsOuter[variant][i]==1 )
838
          {
839
          outer=i;
840
          break;
841
          }
842
        }
843

    
844
      if( outer>=0 )
845
        {
846
        int vertIndex = indices[outer][0];
847
        float[] vertices = mShapes[variant].getVertices()[vertIndex];
848
        float[] ret = new float[3];
849
        float[] curpos = mOrigPos[cubitIndex];
850
        Static4D quat = mOrigQuat[cubitIndex];
851
        QuatHelper.rotateVectorByQuat(mTmp, vertices[0], vertices[1], vertices[2], 1, quat);
852

    
853
        ret[0] = mTmp[0]+computeAvg(curpos,0);
854
        ret[1] = mTmp[1]+computeAvg(curpos,1);
855
        ret[2] = mTmp[2]+computeAvg(curpos,2);
856

    
857
        return ret;
858
        }
859
      else
860
        {
861
        android.util.Log.e("D", "Error in getTrackingPoint: no outer face??");
862
        }
863
      }
864

    
865
    return null;
866
    }
867

    
868
///////////////////////////////////////////////////////////////////////////////////////////////////
869

    
870
  public int computeCurrentPuzzleFace(int type, float[] vertex)
871
    {
872
    if( type!=Cubit.TYPE_NORMAL )
873
      {
874
      Static3D[] axis = getFaceAxis();
875
      float[] dist3D = getDist3D(mNumLayers);
876
      final float MAXERR = 0.98f;
877
      int numAxis = axis.length;
878
      float x = vertex[0];
879
      float y = vertex[1];
880
      float z = vertex[2];
881

    
882
      for(int i=0; i<numAxis; i++)
883
        {
884
        Static3D ax = axis[i];
885
        float len = ax.get0()*x + ax.get1()*y + ax.get2()*z;
886
        if( len>mSize*dist3D[i]*MAXERR ) return i;
887
        }
888

    
889
      return -2;
890
      }
891

    
892
    return -1;
893
    }
894

    
895
///////////////////////////////////////////////////////////////////////////////////////////////////
896

    
897
  public float[] getCubitRowOffset(int cubitIndex)
898
    {
899
    return null;
900
    }
901

    
902
///////////////////////////////////////////////////////////////////////////////////////////////////
903

    
904
  void setRotationRowOffset(int puzzleFace, float[] offset)
905
    {
906
    mRowOffsets[puzzleFace][0] = offset[0];
907
    mRowOffsets[puzzleFace][1] = offset[1];
908
    mRowOffsets[puzzleFace][2] = offset[2];
909
    }
910

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

    
913
  int getNumAxis()
914
    {
915
    return mNumAxis;
916
    }
917

    
918
///////////////////////////////////////////////////////////////////////////////////////////////////
919

    
920
  public int[][] getSolvedQuats()
921
    {
922
    int[] groups = new int[mNumCubits];
923
    int numGroups = 1;
924
    int numFirst  = 0;
925

    
926
    for(int cubit=0; cubit<mNumCubits; cubit++)
927
      {
928
      groups[cubit] = retCubitSolvedStatus(cubit);
929
      if( groups[cubit]>=0 ) numGroups++;
930
      else                   numFirst++;
931
      }
932

    
933
    int firstIndex = 1;
934
    int groupIndex = 1;
935
    int[][] solvedQuats = new int[numGroups][];
936
    solvedQuats[0] = new int[1+numFirst];
937
    solvedQuats[0][0] = numFirst;
938
    Static3D[] axis = getFaceAxis();
939

    
940
    for(int cubit=0; cubit<mNumCubits; cubit++)
941
      {
942
      int group = groups[cubit];
943

    
944
      if( group<0 )
945
        {
946
        solvedQuats[0][firstIndex] = cubit;
947
        firstIndex++;
948
        }
949
      else
950
        {
951
        int[] quats = buildSolvedQuats(axis[group]);
952
        int len = quats==null ? 0 : quats.length;
953
        solvedQuats[groupIndex] = new int[2+len];
954
        solvedQuats[groupIndex][0] = 1;
955
        solvedQuats[groupIndex][1] = cubit;
956
        for(int i=0; i<len; i++) solvedQuats[groupIndex][i+2] = quats[i];
957
        groupIndex++;
958
        }
959
      }
960
/*
961
    String dbg = "SOLVED GROUPS:\n";
962

    
963
    for(int g=0; g<numGroups; g++)
964
      {
965
      int len = solvedQuats[g].length;
966
      for(int i=0; i<len; i++) dbg += (" "+solvedQuats[g][i]);
967
      dbg+="\n";
968
      }
969

    
970
    android.util.Log.e("D", dbg);
971
*/
972
    return solvedQuats;
973
    }
974

    
975
///////////////////////////////////////////////////////////////////////////////////////////////////
976

    
977
  public int getSolvedFunctionIndex()
978
    {
979
    return 0;
980
    }
981

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

    
987
  private boolean isSolvedCentersOnly()
988
    {
989
    int numGroups = mSolvedQuats.length;
990

    
991
    for(int group=1; group<numGroups; group++)
992
      {
993
      int numEntries= mSolvedQuats[group].length;
994
      int numCubits = mSolvedQuats[group][0];
995
      int firstCubit= mSolvedQuats[group][1];
996
      int firstQuat = mCubits[firstCubit].mQuatIndex;
997

    
998
      for(int cubit=2; cubit<=numCubits; cubit++)
999
        {
1000
        int currCubit= mSolvedQuats[group][cubit];
1001
        int currQuat = mCubits[currCubit].mQuatIndex;
1002
        boolean isGood= (firstQuat==currQuat);
1003

    
1004
        for(int q=numCubits+1; !isGood && q<numEntries; q++)
1005
          {
1006
          int quat = mSolvedQuats[group][q];
1007
          if( firstQuat == getMultQuat(currQuat,quat) ) isGood = true;
1008
          }
1009

    
1010
        if( !isGood ) return false;
1011
        }
1012
      }
1013

    
1014
    return true;
1015
    }
1016

    
1017
///////////////////////////////////////////////////////////////////////////////////////////////////
1018

    
1019
  private boolean isSolved0()
1020
    {
1021
    if( mSolvedQuats[0][0]==0 ) return isSolvedCentersOnly();
1022

    
1023
    for( int[] solvedQuat : mSolvedQuats )
1024
      {
1025
      int numCubits = solvedQuat[0];
1026
      int firstCubit= solvedQuat[1];
1027
      int quat = mCubits[firstCubit].mQuatIndex;
1028

    
1029
      for( int cubit=2; cubit<=numCubits; cubit++ )
1030
        {
1031
        int c = solvedQuat[cubit];
1032
        if( quat != mCubits[c].mQuatIndex ) return false;
1033
        }
1034
      }
1035

    
1036
    int cubit= mSolvedQuats[0][1];
1037
    int quat0= mCubits[cubit].mQuatIndex;
1038
    int numGroups = mSolvedQuats.length;
1039

    
1040
    for(int group=1; group<numGroups; group++)
1041
      {
1042
      int firstCubit= mSolvedQuats[group][1];
1043
      int currQuat  = mCubits[firstCubit].mQuatIndex;
1044

    
1045
      if( quat0==currQuat ) continue;
1046

    
1047
      boolean isGood= false;
1048
      int numEntries= mSolvedQuats[group].length;
1049
      int numCubits = mSolvedQuats[group][0];
1050

    
1051
      for(int q=numCubits+1; q<numEntries; q++)
1052
        {
1053
        int quat = mSolvedQuats[group][q];
1054

    
1055
        if( quat0 == getMultQuat(currQuat,quat) )
1056
          {
1057
          isGood = true;
1058
          break;
1059
          }
1060
        }
1061

    
1062
      if( !isGood ) return false;
1063
      }
1064

    
1065
    return true;
1066
    }
1067

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

    
1070
  private int computeScramble(int quatNum, int centerNum)
1071
    {
1072
    float MAXDIFF = 0.01f;
1073
    float[] center= mOrigPos[centerNum];
1074
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
1075
    Static4D result = QuatHelper.rotateVectorByQuat(sc,mObjectQuats[quatNum]);
1076

    
1077
    float x = result.get0();
1078
    float y = result.get1();
1079
    float z = result.get2();
1080

    
1081
    for(int c=0; c<mNumCubits; c++)
1082
      {
1083
      float[] cent = mOrigPos[c];
1084

    
1085
      float qx = cent[0] - x;
1086
      float qy = cent[1] - y;
1087
      float qz = cent[2] - z;
1088

    
1089
      if( qx>-MAXDIFF && qx<MAXDIFF &&
1090
          qy>-MAXDIFF && qy<MAXDIFF &&
1091
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
1092
      }
1093

    
1094
    return -1;
1095
    }
1096

    
1097
///////////////////////////////////////////////////////////////////////////////////////////////////
1098
// Dino4 uses this. It is solved if and only if groups of cubits
1099
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
1100
// or
1101
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
1102
// are all the same color.
1103

    
1104
  private boolean isSolved1()
1105
    {
1106
    if( mScramble==null )
1107
      {
1108
      mScramble = new int[mNumQuats][mNumCubits];
1109
      mColors   = new int[mNumCubits];
1110

    
1111
      for(int q=0; q<mNumQuats; q++)
1112
        for(int c=0; c<mNumCubits; c++) mScramble[q][c] = computeScramble(q,c);
1113
      }
1114

    
1115
    if( mFaceMap==null )
1116
      {
1117
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
1118
      }
1119

    
1120
    for(int c=0; c<mNumCubits; c++)
1121
      {
1122
      int index = mScramble[mCubits[c].mQuatIndex][c];
1123
      mColors[index] = mFaceMap[c];
1124
      }
1125

    
1126
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
1127
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
1128
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
1129

    
1130
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
1131
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
1132
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
1133

    
1134
    return false;
1135
    }
1136

    
1137
///////////////////////////////////////////////////////////////////////////////////////////////////
1138

    
1139
  int computeRow(float[] pos, int axisIndex, int cubitType, int puzzleFace)
1140
    {
1141
    int ret=0;
1142
    int len = pos.length / 3;
1143
    Static3D axis = mAxis[axisIndex];
1144
    float axisX = axis.get0();
1145
    float axisY = axis.get1();
1146
    float axisZ = axis.get2();
1147
    float casted, xoff=0, yoff=0, zoff=0;
1148

    
1149
    if( cubitType!=Cubit.TYPE_NORMAL )
1150
      {
1151
      xoff = mRowOffsets[puzzleFace][0];
1152
      yoff = mRowOffsets[puzzleFace][1];
1153
      zoff = mRowOffsets[puzzleFace][2];
1154
      }
1155

    
1156
    for(int i=0; i<len; i++)
1157
      {
1158
      casted = (pos[3*i]+xoff)*axisX + (pos[3*i+1]+yoff)*axisY + (pos[3*i+2]+zoff)*axisZ;
1159
      ret |= computeSingleRow(axisIndex,casted);
1160
      }
1161

    
1162
    return ret;
1163
    }
1164

    
1165
///////////////////////////////////////////////////////////////////////////////////////////////////
1166

    
1167
  private int computeSingleRow(int axisIndex,float casted)
1168
    {
1169
    int num = mNumCuts[axisIndex];
1170

    
1171
    for(int i=0; i<num; i++)
1172
      {
1173
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
1174
      }
1175

    
1176
    return (1<<num);
1177
    }
1178

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

    
1181
  private boolean wasRotateApplied()
1182
    {
1183
    return mEffects.exists(mRotateEffect.getID());
1184
    }
1185

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

    
1188
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
1189
    {
1190
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
1191
    }
1192

    
1193
///////////////////////////////////////////////////////////////////////////////////////////////////
1194
// note the minus in front of the sin() - we rotate counterclockwise
1195
// when looking towards the direction where the axis increases in values.
1196

    
1197
  private Static4D makeQuaternion(float axisX, float axisY, float axisZ, int angleInDegrees)
1198
    {
1199
    while( angleInDegrees<0 ) angleInDegrees += 360;
1200
    angleInDegrees %= 360;
1201
    
1202
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
1203
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
1204

    
1205
    return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
1206
    }
1207

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

    
1210
  private synchronized void setupPosition(int[][] moves)
1211
    {
1212
    if( moves!=null )
1213
      {
1214
      Static4D quat;
1215
      int index, axisIndex, row, rowBitmap, basic, angle;
1216

    
1217
      for(int[] move: moves)
1218
        {
1219
        axisIndex= move[0];
1220
        rowBitmap= computeBitmapFromRow( move[1],axisIndex);
1221
        row      = computeRowFromBitmap( move[1] );
1222
        basic    = mBasicAngles[axisIndex][row];
1223
        angle    = move[2]*(360/basic);   // this assumes that all layers from
1224
                                          // the bitmap have the same BasicAngle.
1225
                                          // at the moment this is always true as
1226
                                          // there are no bandaged objects with
1227
                                          // different per-layer BasicAngles.
1228
        Static3D axis = mAxis[axisIndex];
1229
        float axisX = axis.get0();
1230
        float axisY = axis.get1();
1231
        float axisZ = axis.get2();
1232
        quat = makeQuaternion(axisX,axisY,axisZ,angle);
1233

    
1234
        for(int i=0; i<mNumCubits; i++)
1235
          {
1236
          mBelongs[i] = belongsToRotation(i,axisIndex,rowBitmap);
1237
          if( mBelongs[i] )
1238
            {
1239
            boolean result = mCubits[i].rotateCubit(quat);
1240
            if( !result ) debugQuat(quat,i,axisX,axisY,axisZ,angle,1);
1241
            }
1242
          }
1243

    
1244
        recomputeFaceOffsets();
1245

    
1246
        for(int i=0; i<mNumCubits; i++)
1247
          {
1248
          if( mBelongs[i] )
1249
            {
1250
            index = mCubits[i].postRotateCubit(quat);
1251
            setCubitQuat(i,mCubits[i].computeAssociation(),index);
1252
            }
1253
          else if( mCubits[i].getType()==Cubit.TYPE_FOLLOWER )
1254
            {
1255
            mCubits[i].computeRotationRow();
1256
            setCubitQuat(i,mCubits[i].computeAssociation(),mCubits[i].mQuatIndex);
1257
            }
1258
          }
1259
        }
1260
      }
1261
    }
1262

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

    
1265
  public int getScrambleType()
1266
    {
1267
    return 0;
1268
    }
1269

    
1270
///////////////////////////////////////////////////////////////////////////////////////////////////
1271

    
1272
  int computeBitmapFromRow(int rowBitmap, int axis)
1273
    {
1274
    if( mIsBandaged )
1275
      {
1276
      int bitmap, initBitmap=0;
1277

    
1278
      while( initBitmap!=rowBitmap )
1279
        {
1280
        initBitmap = rowBitmap;
1281

    
1282
        for(int cubit=0; cubit<mNumCubits; cubit++)
1283
          {
1284
          bitmap = mCubits[cubit].getRotRow(axis);
1285
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
1286
          }
1287
        }
1288
      }
1289

    
1290
    return rowBitmap;
1291
    }
1292

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

    
1295
  private int computeRowFromBitmap(int rowBitmap)
1296
    {
1297
    int index = 0;
1298

    
1299
    while(index<32)
1300
      {
1301
      if( (rowBitmap&0x1) != 0 ) return index;
1302
      rowBitmap>>=1;
1303
      index++;
1304
      }
1305
    return 0;
1306
    }
1307

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

    
1312
  void clampPos(float[] pos, int offset)
1313
    {
1314
    float currError, minError = Float.MAX_VALUE;
1315
    int minErrorIndex1 = -1;
1316
    int minErrorIndex2 = -1;
1317

    
1318
    float x = pos[offset  ];
1319
    float y = pos[offset+1];
1320
    float z = pos[offset+2];
1321

    
1322
    float xo,yo,zo;
1323

    
1324
    for(int i=0; i<mNumCubits; i++)
1325
      {
1326
      int len = mOrigPos[i].length / 3;
1327

    
1328
      for(int j=0; j<len; j++)
1329
        {
1330
        xo = mOrigPos[i][3*j  ];
1331
        yo = mOrigPos[i][3*j+1];
1332
        zo = mOrigPos[i][3*j+2];
1333

    
1334
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
1335

    
1336
        if( currError<minError )
1337
          {
1338
          minError = currError;
1339
          minErrorIndex1 = i;
1340
          minErrorIndex2 = j;
1341
          }
1342
        }
1343
      }
1344

    
1345
    if( minError< 0.05f ) // TODO: 0.05 ?
1346
      {
1347
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
1348
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
1349
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
1350
      }
1351
    }
1352

    
1353
///////////////////////////////////////////////////////////////////////////////////////////////////
1354
// remember about the double cover or unit quaternions!
1355

    
1356
  int mulQuat(int q1, int q2)
1357
    {
1358
    Static4D result = QuatHelper.quatMultiply(mObjectQuats[q1],mObjectQuats[q2]);
1359

    
1360
    float rX = result.get0();
1361
    float rY = result.get1();
1362
    float rZ = result.get2();
1363
    float rW = result.get3();
1364

    
1365
    final float MAX_ERROR = 0.1f;
1366
    float dX,dY,dZ,dW;
1367

    
1368
    for(int i=0; i<mNumQuats; i++)
1369
      {
1370
      dX = mObjectQuats[i].get0() - rX;
1371
      dY = mObjectQuats[i].get1() - rY;
1372
      dZ = mObjectQuats[i].get2() - rZ;
1373
      dW = mObjectQuats[i].get3() - rW;
1374

    
1375
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1376
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1377
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1378
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1379

    
1380
      dX = mObjectQuats[i].get0() + rX;
1381
      dY = mObjectQuats[i].get1() + rY;
1382
      dZ = mObjectQuats[i].get2() + rZ;
1383
      dW = mObjectQuats[i].get3() + rW;
1384

    
1385
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1386
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1387
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1388
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1389
      }
1390

    
1391
    return -1;
1392
    }
1393

    
1394
///////////////////////////////////////////////////////////////////////////////////////////////////
1395

    
1396
  private float getAngle()
1397
    {
1398
    mPointNum = mRotationAngle.getNumPoints();
1399
    return mPointNum>=1 ? mRotationAngle.getPoint(mPointNum-1).get0() : 0;
1400
    }
1401

    
1402
///////////////////////////////////////////////////////////////////////////////////////////////////
1403

    
1404
  void setLibInterface(ObjectLibInterface inter)
1405
    {
1406
    mInterface = inter;
1407
    }
1408

    
1409
///////////////////////////////////////////////////////////////////////////////////////////////////
1410

    
1411
  void applyScrambles(int[][] moves)
1412
    {
1413
    setupPosition(moves);
1414
    }
1415

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

    
1418
  void initializeObject(int[][] moves)
1419
    {
1420
    solve();
1421
    setupPosition(moves);
1422
    }
1423

    
1424
///////////////////////////////////////////////////////////////////////////////////////////////////
1425

    
1426
  synchronized void removeRotationNow()
1427
    {
1428
    float angle = getAngle();
1429
    double nearestAngleInRadians = angle*Math.PI/180;
1430
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
1431
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
1432
    float axisX = mAxis[mCurrentRotAxis].get0();
1433
    float axisY = mAxis[mCurrentRotAxis].get1();
1434
    float axisZ = mAxis[mCurrentRotAxis].get2();
1435
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
1436

    
1437
    mRotationAngleStatic.set0(0);
1438
    mRotationAngle.removeAll();
1439

    
1440
    for(int i=0; i<mNumCubits; i++)
1441
      {
1442
      mBelongs[i] = belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap);
1443
      if( mBelongs[i] )
1444
        {
1445
        boolean result = mCubits[i].rotateCubit(quat);
1446
        if( !result ) debugQuat(quat,i,axisX,axisY,axisZ,angle,2);
1447
        }
1448
      }
1449

    
1450
    recomputeFaceOffsets();
1451

    
1452
    for(int i=0; i<mNumCubits; i++)
1453
      {
1454
      if( mBelongs[i] )
1455
        {
1456
        int index = mCubits[i].postRotateCubit(quat);
1457
        setCubitQuat(i,mCubits[i].computeAssociation(),index);
1458
        }
1459
      else if( mCubits[i].getType()==Cubit.TYPE_FOLLOWER )
1460
        {
1461
        mCubits[i].computeRotationRow();
1462
        setCubitQuat(i,mCubits[i].computeAssociation(),mCubits[i].mQuatIndex);
1463
        }
1464
      }
1465

    
1466
    mRotationState = STATE_NOTHING;
1467
    }
1468

    
1469
///////////////////////////////////////////////////////////////////////////////////////////////////
1470

    
1471
  private void recomputeFaceOffsets()
1472
    {
1473
    for(int i=0; i<mNumPuzzleFaces; i++)
1474
      {
1475
      mRowOffsets[i][0] =0;
1476
      mRowOffsets[i][1] =0;
1477
      mRowOffsets[i][2] =0;
1478
      }
1479

    
1480
    for(int i=0; i<mNumCubits; i++)
1481
      if( mCubits[i].getType()==Cubit.TYPE_DECIDER )
1482
        {
1483
        float[] offset = mCubits[i].getOffset();
1484
        int face = mCubits[i].getPuzzleFace();
1485
        mRowOffsets[face][0] = offset[0];
1486
        mRowOffsets[face][1] = offset[1];
1487
        mRowOffsets[face][2] = offset[2];
1488
        }
1489
    }
1490

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

    
1493
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
1494
    {
1495
    if( wasRotateApplied() )
1496
      {
1497
      mRotationState = STATE_FINISH;
1498
      float angle = getAngle();
1499
      mRotationAngleStatic.set0(angle);
1500
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1501
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1502

    
1503
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1504
      mRotationAngle.resetToBeginning();
1505
      mRotationAngle.removeAll();
1506
      mRotationAngle.add(mRotationAngleStatic);
1507
      mRotationAngle.add(mRotationAngleMiddle);
1508
      mRotationAngle.add(mRotationAngleFinal);
1509
      mRotateEffect.notifyWhenFinished(listener);
1510

    
1511
      return mRotateEffect.getID();
1512
      }
1513

    
1514
    return 0;
1515
    }
1516

    
1517
///////////////////////////////////////////////////////////////////////////////////////////////////
1518

    
1519
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1520
    {
1521
    int mult = 1;
1522

    
1523
    if( wasRotateApplied() )
1524
      {
1525
      if( mRotationState==STATE_ROTATE )
1526
        {
1527
        return 0;
1528
        }
1529
      if( mRotationState==STATE_FINISH )
1530
        {
1531
        removeRotationNow();
1532
        mult = -1;
1533
        }
1534

    
1535
      mRotationState = STATE_ROTATE;
1536
      mCurrentRotAxis = axis;
1537
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1538
      mRotationAngleStatic.set0(0.0f);
1539
      mRotationAxis.set( mAxis[axis] );
1540
      mRotationAngle.setDuration(durationMillis);
1541
      mRotationAngle.resetToBeginning();
1542
      mRotationAngle.add(new Static1D(0));
1543
      mRotationAngle.add(new Static1D(angle));
1544
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1545
      mRotateEffect.notifyWhenFinished(listener);
1546
      return mult*mRotateEffect.getID();
1547
      }
1548

    
1549
    return 0;
1550
    }
1551

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

    
1554
  void continueRotation(float angleInDegrees)
1555
    {
1556
    mRotationAngleStatic.set0(angleInDegrees);
1557
    }
1558

    
1559
///////////////////////////////////////////////////////////////////////////////////////////////////
1560

    
1561
  synchronized boolean beginNewRotation(int axis, int row )
1562
    {
1563
    if( mRotationState==STATE_ROTATE )
1564
      {
1565
      return false;
1566
      }
1567
    if( mRotationState==STATE_FINISH )
1568
      {
1569
      removeRotationNow();
1570
      }
1571

    
1572
    if( axis<0 || axis>=mNumAxis )
1573
      {
1574
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1575
      return false;
1576
      }
1577
    if( row<0 || row>=mNumLayers[axis] )
1578
      {
1579
      android.util.Log.e("object", "invalid rotation row: "+row);
1580
      return false;
1581
      }
1582

    
1583
    mRotationState = STATE_ROTATE;
1584
    mCurrentRotAxis = axis;
1585
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1586
    mRotationAngleStatic.set0(0.0f);
1587
    mRotationAxis.set( mAxis[axis] );
1588
    mRotationAngle.add(mRotationAngleStatic);
1589
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1590

    
1591
    return true;
1592
    }
1593

    
1594
///////////////////////////////////////////////////////////////////////////////////////////////////
1595

    
1596
  void setTextureMap(int cubit, int face, int color)
1597
    {
1598
    int variant  = getCubitVariant(cubit,mNumLayers);
1599
    int shape    = getVariantStickerShape(variant,face);
1600
    int texIndex = color<0 || shape<0 ? mNumTextures-mNumOverrides : shape*mNumFaceColors + color;
1601
    int row      = (mNumTexRows-1) - texIndex/mNumTexCols;
1602
    int col      = texIndex%mNumTexCols;
1603

    
1604
    final float ratioW = 1.0f/mNumTexCols;
1605
    final float ratioH = 1.0f/mNumTexRows;
1606
    final Static4D[] maps = new Static4D[1];
1607
    maps[0] = new Static4D(col*ratioW, row*ratioH, ratioW, ratioH);
1608
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit+face);
1609
    }
1610

    
1611
///////////////////////////////////////////////////////////////////////////////////////////////////
1612

    
1613
  private int getCubitFaceColor(int cubit, int face)
1614
    {
1615
    int puzzleFace = getCubitFaceMap(cubit,face);
1616
    if( puzzleFace>=0 ) puzzleFace %= mNumFaceColors;
1617
    return puzzleFace;
1618
    }
1619

    
1620
///////////////////////////////////////////////////////////////////////////////////////////////////
1621

    
1622
  public int getCubitFaceMap(int cubit, int face)
1623
    {
1624
    int numFaces = mCubitFaceColors[cubit].length;
1625
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1626
    return puzzleFace<0 ? -1 : puzzleFace;
1627
    }
1628

    
1629
///////////////////////////////////////////////////////////////////////////////////////////////////
1630

    
1631
  void resetAllTextureMaps()
1632
    {
1633
    final float ratioW = 1.0f/mNumTexCols;
1634
    final float ratioH = 1.0f/mNumTexRows;
1635
    int cubColor, stiShape, texIndex, variant, row, col;
1636

    
1637
    for(int cubit=0; cubit<mNumCubits; cubit++)
1638
      {
1639
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1640
      variant = getCubitVariant(cubit,mNumLayers);
1641

    
1642
      for(int face=0; face<mNumCubitFaces; face++)
1643
        {
1644
        cubColor = getCubitFaceColor(cubit,face);
1645
        stiShape = getVariantStickerShape(variant,face);
1646
        texIndex = cubColor<0 || stiShape<0 ? mNumTextures-mNumOverrides : stiShape*mNumFaceColors + cubColor;
1647
        row      = (mNumTexRows-1) - texIndex/mNumTexCols;
1648
        col      = texIndex%mNumTexCols;
1649

    
1650
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1651
        }
1652

    
1653
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1654
      }
1655

    
1656
    overrideCubitFaceColor();
1657
    }
1658

    
1659
///////////////////////////////////////////////////////////////////////////////////////////////////
1660

    
1661
  private void overrideCubitFaceColor()
1662
    {
1663
    final float ratioW = 1.0f/mNumTexCols;
1664
    final float ratioH = 1.0f/mNumTexRows;
1665

    
1666
    for(int i=0; i<mNumOverrides; i++)
1667
      {
1668
      int[] cubitFaces = mStickerOverrides[i].getCubitFaces();
1669
      int length = cubitFaces.length/2;
1670

    
1671
      for(int j=0; j<length; j++)
1672
        {
1673
        final Static4D[] maps = new Static4D[1];
1674
        int color = mNumTextures-mNumOverrides+1+i;
1675
        int row   = (mNumTexRows-1) - color/mNumTexCols;
1676
        int col   = color%mNumTexCols;
1677
        int cubit = cubitFaces[2*j];
1678
        int face  = cubitFaces[2*j+1];
1679
        maps[0] = new Static4D(col*ratioW, row*ratioH, ratioW, ratioH);
1680
        mMesh.setTextureMap(maps,mNumCubitFaces*cubit+face);
1681
        }
1682
      }
1683
    }
1684

    
1685
///////////////////////////////////////////////////////////////////////////////////////////////////
1686

    
1687
  void releaseResources()
1688
    {
1689
    mTexture.markForDeletion();
1690
    mMesh.markForDeletion();
1691
    mEffects.markForDeletion();
1692

    
1693
    for(int j=0; j<mNumCubits; j++)
1694
      {
1695
      mCubits[j].releaseResources();
1696
      }
1697
    }
1698

    
1699
///////////////////////////////////////////////////////////////////////////////////////////////////
1700

    
1701
  private void setCubitQuat(int cubit, int andAssociation, int equAssociation)
1702
    {
1703
    if( !mIsInMixupMode )
1704
      {
1705
      mMesh.setEffectAssociation(cubit,andAssociation,equAssociation);
1706
      }
1707
    else
1708
      {
1709
      mMesh.setEffectAssociation(cubit,andAssociation,cubit);
1710
      Static4D tmp = mObjectQuats[equAssociation];
1711
      mMixupModeQuats[cubit].set(tmp);
1712
      }
1713
    }
1714

    
1715
///////////////////////////////////////////////////////////////////////////////////////////////////
1716

    
1717
  synchronized void restorePreferences(SharedPreferences preferences)
1718
    {
1719
    boolean error = false;
1720
    String key = getShortName();
1721

    
1722
    for(int i=0; i<mNumCubits; i++)
1723
      {
1724
      mQuatDebug[i] = mCubits[i].restorePreferences(key,preferences);
1725

    
1726
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1727
        {
1728
        boolean result = mCubits[i].rotateCubit(mObjectQuats[mQuatDebug[i]]);
1729
        if( !result ) debugQuat(mObjectQuats[mQuatDebug[i]],i,0,0,0,mQuatDebug[i],3);
1730
        }
1731
      else { error = true; break; }
1732
      }
1733

    
1734
    if( !error )
1735
      {
1736
      recomputeFaceOffsets();
1737

    
1738
      for(int i=0; i<mNumCubits; i++)
1739
        {
1740
        if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1741
          {
1742
          mCubits[i].computeRotationRow();
1743
          setCubitQuat(i,mCubits[i].computeAssociation(),mQuatDebug[i]);
1744
          }
1745
        else { error = true; break; }
1746
        }
1747
      }
1748

    
1749
    if( error )
1750
      {
1751
      for(int i=0; i<mNumCubits; i++)
1752
        {
1753
        mCubits[i].solve();
1754
        setCubitQuat(i,mCubits[i].computeAssociation(),0);
1755
        }
1756
      }
1757
    }
1758

    
1759
///////////////////////////////////////////////////////////////////////////////////////////////////
1760

    
1761
  void savePreferences(SharedPreferences.Editor editor)
1762
    {
1763
    String key = getShortName();
1764
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(key,editor);
1765
    }
1766

    
1767
///////////////////////////////////////////////////////////////////////////////////////////////////
1768

    
1769
  public void removePreferences(SharedPreferences.Editor editor)
1770
    {
1771
    String key = getShortName();
1772
    for(int i=0; i<mNumCubits; i++) mCubits[i].removePreferences(key,editor);
1773
    }
1774

    
1775
///////////////////////////////////////////////////////////////////////////////////////////////////
1776

    
1777
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1778
    {
1779
    final float A = 0.8f;  // 0<A<1
1780

    
1781
    int prev = curr>0 ? curr-1 : len-1;
1782
    int next = curr<len-1 ? curr+1 : 0;
1783

    
1784
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1785
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1786
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1787
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1788

    
1789
    float len1= v1x*v1x+v1y*v1y;
1790
    float len2= v2x*v2x+v2y*v2y;
1791

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

    
1794
    return 1-A*cos;
1795
    }
1796

    
1797
///////////////////////////////////////////////////////////////////////////////////////////////////
1798
// Radius of the sphere circumscribed on the puzzle. Needed for pillowing.
1799
//
1800
// This won't work correctly for pillowing off-center puzzles (e.g. mirrors) - for those we'd need
1801
// to introduce the concept of a 'sink center' as well.
1802
//
1803
// public because needed in TouchControlShapemod
1804

    
1805
  public float getCircumscribedRadius()
1806
    {
1807
    switch(mNumPuzzleFaces)
1808
      {
1809
      case  4: return (SQ6/4)*mSize;
1810
      case  6: return (SQ3/2)*mSize;
1811
      case  8: return (SQ2/2)*mSize;
1812
      case 12: return (SQ3/2)*((SQ5+1)/2)*mSize;
1813
      case 16: return 0.50f*mSize;
1814
      }
1815

    
1816
    return 0.0f;
1817
    }
1818

    
1819
///////////////////////////////////////////////////////////////////////////////////////////////////
1820

    
1821
  public ObjectSticker retSticker(int sticker)
1822
    {
1823
    if( mStickers==null )
1824
      {
1825
      float rad = getStickerRadius();
1826
      float str = getStickerStroke();
1827
      float[][] angles = getStickerAngles();
1828
      int numStickers = mStickerCoords.length;
1829
      mStickers = new ObjectSticker[numStickers];
1830

    
1831
      for(int s=0; s<numStickers; s++)
1832
        {
1833
        float scale = mStickerScales.length>s ? mStickerScales[s] : 1.0f;
1834
        float radius = rad / scale;
1835
        float stroke = str / scale;
1836
        int len = mStickerCoords[s].length/2;
1837
        float[] radii = new float[len];
1838
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1839
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1840
        }
1841
      }
1842

    
1843
    return mStickers[sticker];
1844
    }
1845

    
1846
///////////////////////////////////////////////////////////////////////////////////////////////////
1847
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1848

    
1849
  public void adjustStickerCoords()
1850
    {
1851

    
1852
    }
1853

    
1854
///////////////////////////////////////////////////////////////////////////////////////////////////
1855

    
1856
  public Static4D[] getQuats()
1857
    {
1858
    if( mObjectQuats==null )
1859
      {
1860
      mObjectQuats = QuatGroupGenerator.computeGroup(mAxis,mBasicAngles);
1861
      }
1862

    
1863
    return mObjectQuats;
1864
    }
1865

    
1866
///////////////////////////////////////////////////////////////////////////////////////////////////
1867

    
1868
  public int[][] getVariantFaceIsOuter()
1869
    {
1870
    return mVariantFaceIsOuter;
1871
    }
1872

    
1873
///////////////////////////////////////////////////////////////////////////////////////////////////
1874

    
1875
  public int getInternalColor()
1876
    {
1877
    return COLOR_INTERNAL;
1878
    }
1879

    
1880
///////////////////////////////////////////////////////////////////////////////////////////////////
1881
// the getFaceColors + final INTERNAL_COLOR in a grid (so that we do not exceed the maximum texture size)
1882

    
1883
  private void createTexture()
1884
    {
1885
    Paint paint = new Paint();
1886
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_4444);
1887
    Canvas canvas = new Canvas(mBitmap);
1888

    
1889
    paint.setAntiAlias(true);
1890
    paint.setTextAlign(Paint.Align.CENTER);
1891
    paint.setStyle(Paint.Style.FILL);
1892
    paint.setColor(getInternalColor());
1893
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1894

    
1895
    int texture = 0;
1896
    FactorySticker factory = FactorySticker.getInstance();
1897

    
1898
    for(int row=0; row<mNumTexRows; row++)
1899
      for(int col=0; col<mNumTexCols; col++)
1900
        {
1901
        if( texture<mNumTextures-mNumOverrides )
1902
          {
1903
          ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1904
          int color = getColor(texture%mNumFaceColors);
1905
          factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, (mNumTexRows-row)*TEXTURE_HEIGHT, color, sticker);
1906
          }
1907
        else if( texture>mNumTextures-mNumOverrides && texture<=mNumTextures )
1908
          {
1909
          int color = mStickerOverrides[mNumTextures-texture].getColor();
1910
          factory.drawSolidColor(canvas, paint, col*TEXTURE_HEIGHT, (mNumTexRows-row)*TEXTURE_HEIGHT, color);
1911
          }
1912

    
1913
        texture++;
1914
        }
1915
    }
1916

    
1917
///////////////////////////////////////////////////////////////////////////////////////////////////
1918

    
1919
  void setTexture()
1920
    {
1921
    if( mBitmap==null ) createTexture();
1922

    
1923
    if( !mTexture.setTextureAlreadyInverted(mBitmap) )
1924
      {
1925
      int max = DistortedLibrary.getMaxTextureSize();
1926
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1927
      }
1928
    }
1929

    
1930
///////////////////////////////////////////////////////////////////////////////////////////////////
1931

    
1932
  void setObjectRatioNow(float sc, int nodeSize)
1933
    {
1934
    mObjectScreenRatio = sc;
1935
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1936
    mObjectScale.set(scale,scale,scale);
1937

    
1938
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1939
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1940
    }
1941

    
1942
///////////////////////////////////////////////////////////////////////////////////////////////////
1943

    
1944
  void setObjectRatio(float sizeChange, int nodeSize)
1945
    {
1946
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1947

    
1948
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1949
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1950

    
1951
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1952
    }
1953

    
1954
///////////////////////////////////////////////////////////////////////////////////////////////////
1955

    
1956
  void setNodeSize(int nodeSize)
1957
    {
1958
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1959
    }
1960

    
1961
///////////////////////////////////////////////////////////////////////////////////////////////////
1962

    
1963
  public float getRatio()
1964
    {
1965
    return mObjectScreenRatio;
1966
    }
1967

    
1968
///////////////////////////////////////////////////////////////////////////////////////////////////
1969

    
1970
  public float getObjectRatio()
1971
    {
1972
    return mObjectScreenRatio*mInitScreenRatio;
1973
    }
1974

    
1975
///////////////////////////////////////////////////////////////////////////////////////////////////
1976

    
1977
  boolean isSolved()
1978
    {
1979
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1980
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1981

    
1982
    return false;
1983
    }
1984

    
1985
///////////////////////////////////////////////////////////////////////////////////////////////////
1986

    
1987
  int computeNearestAngle(int basicAngle, float angle, float speed)
1988
    {
1989
    int nearestAngle = 360/basicAngle;
1990
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1991
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1992

    
1993
    if( tmp!=0 ) return nearestAngle*tmp;
1994

    
1995
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1996
    }
1997

    
1998
///////////////////////////////////////////////////////////////////////////////////////////////////
1999
// INTERNAL API - those are called from 'effects' package
2000
///////////////////////////////////////////////////////////////////////////////////////////////////
2001

    
2002
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
2003
    {
2004
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total, getSignature() );
2005
    }
2006

    
2007
///////////////////////////////////////////////////////////////////////////////////////////////////
2008

    
2009
  public Static4D getRotationQuat()
2010
    {
2011
    return mQuat;
2012
    }
2013

    
2014
///////////////////////////////////////////////////////////////////////////////////////////////////
2015

    
2016
  public float getSize()
2017
    {
2018
    return mSize;
2019
    }
2020

    
2021
///////////////////////////////////////////////////////////////////////////////////////////////////
2022

    
2023
  public void applyEffect(Effect effect, int position)
2024
    {
2025
    mEffects.apply(effect, position);
2026
    }
2027

    
2028
///////////////////////////////////////////////////////////////////////////////////////////////////
2029

    
2030
  public void removeEffect(long effectID)
2031
    {
2032
    mEffects.abortById(effectID);
2033
    }
2034

    
2035
///////////////////////////////////////////////////////////////////////////////////////////////////
2036

    
2037
  public MeshBase getObjectMesh()
2038
    {
2039
    return mMesh;
2040
    }
2041

    
2042
///////////////////////////////////////////////////////////////////////////////////////////////////
2043

    
2044
  public DistortedEffects getObjectEffects()
2045
    {
2046
    return mEffects;
2047
    }
2048

    
2049
///////////////////////////////////////////////////////////////////////////////////////////////////
2050

    
2051
  public int getCubitType(int cubit)
2052
    {
2053
    return mCubits[cubit].getType();
2054
    }
2055

    
2056
///////////////////////////////////////////////////////////////////////////////////////////////////
2057

    
2058
  public float[] getCubitOffset(int cubit)
2059
    {
2060
    return mCubits[cubit].getOffset();
2061
    }
2062

    
2063
///////////////////////////////////////////////////////////////////////////////////////////////////
2064

    
2065
  public ObjectStickerOverride[] getStickerOverrides()
2066
    {
2067
    return null;
2068
    }
2069

    
2070
///////////////////////////////////////////////////////////////////////////////////////////////////
2071

    
2072
  public boolean getError()
2073
    {
2074
    return mError;
2075
    }
2076

    
2077
///////////////////////////////////////////////////////////////////////////////////////////////////
2078

    
2079
  public String getErrorString()
2080
    {
2081
    return mErrorString;
2082
    }
2083

    
2084
///////////////////////////////////////////////////////////////////////////////////////////////////
2085
// PUBLIC API
2086
///////////////////////////////////////////////////////////////////////////////////////////////////
2087

    
2088
  public int getCubitFaceColorIndex(int cubit, int face)
2089
    {
2090
    Static4D texMap = mMesh.getTextureMap(mNumFaceColors *cubit + face);
2091

    
2092
    int x = (int)(texMap.get0()/texMap.get2());
2093
    int y = (int)(texMap.get1()/texMap.get3());
2094

    
2095
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
2096
    }
2097

    
2098
///////////////////////////////////////////////////////////////////////////////////////////////////
2099

    
2100
  public int[] getNumLayers()
2101
    {
2102
    return mNumLayers;
2103
    }
2104

    
2105
///////////////////////////////////////////////////////////////////////////////////////////////////
2106

    
2107
  public synchronized void solve()
2108
    {
2109
    for(int i=0; i<mNumCubits; i++)
2110
      {
2111
      mCubits[i].solve();
2112
      }
2113

    
2114
    recomputeFaceOffsets();
2115

    
2116
    for(int i=0; i<mNumCubits; i++)
2117
      {
2118
      mCubits[i].computeRotationRow();
2119
      setCubitQuat(i,mCubits[i].computeAssociation(),0);
2120
      }
2121
    }
2122

    
2123
///////////////////////////////////////////////////////////////////////////////////////////////////
2124

    
2125
  public int getCubitQuatIndex(int cubit)
2126
    {
2127
    return (cubit>=0 && cubit<mNumCubits) ? mCubits[cubit].mQuatIndex : 0;
2128
    }
2129

    
2130
///////////////////////////////////////////////////////////////////////////////////////////////////
2131

    
2132
  public int getCubitRotRow(int cubit, int axis)
2133
    {
2134
    return mCubits[cubit].getRotRow(axis);
2135
    }
2136

    
2137
///////////////////////////////////////////////////////////////////////////////////////////////////
2138

    
2139
  public Bitmap getStickerBitmap()
2140
    {
2141
    return mBitmap;
2142
    }
2143

    
2144
///////////////////////////////////////////////////////////////////////////////////////////////////
2145

    
2146
  public DistortedNode getNode()
2147
    {
2148
    return mNode;
2149
    }
2150

    
2151
///////////////////////////////////////////////////////////////////////////////////////////////////
2152

    
2153
  public int getNumStickerTypes()
2154
    {
2155
    return mNumStickerTypes;
2156
    }
2157

    
2158
///////////////////////////////////////////////////////////////////////////////////////////////////
2159

    
2160
  public String reportState()
2161
    {
2162
    StringBuilder builder = new StringBuilder();
2163

    
2164
    for(int i=0; i<mNumCubits; i++ )
2165
      {
2166
      if( i>0 ) builder.append('.');
2167
      builder.append(mCubits[i].mQuatIndex);
2168
      }
2169

    
2170
    return builder.toString();
2171
    }
2172

    
2173
///////////////////////////////////////////////////////////////////////////////////////////////////
2174
// this is here only so it can be overridden in TwistyJSON so that we can get this from JSON.
2175

    
2176
  public int getNumCubitFaces()
2177
    {
2178
    return 0;
2179
    }
2180

    
2181
///////////////////////////////////////////////////////////////////////////////////////////////////
2182
// 1.0 - i.e. no pillowing - by default.
2183
// The coeff is really param of the 'sink' vertex effect - if it is not equal to 1.0, we apply the
2184
// sink effect [centered at (0,0,0)] to the whole mesh as the last step of composing it.
2185

    
2186
  public float getPillowCoeff()
2187
    {
2188
    return 1.0f;
2189
    }
2190

    
2191
///////////////////////////////////////////////////////////////////////////////////////////////////
2192

    
2193
  public TouchControl getTouchControl()
2194
    {
2195
    if( mTouchControl==null )
2196
      {
2197
      switch(getTouchControlType())
2198
        {
2199
        case TC_TETRAHEDRON      : mTouchControl = new TouchControlTetrahedron(this);
2200
                                   break;
2201
        case TC_HEXAHEDRON       : mTouchControl = new TouchControlHexahedron(this);
2202
                                   break;
2203
        case TC_OCTAHEDRON       : mTouchControl = new TouchControlOctahedron(this);
2204
                                   break;
2205
        case TC_DODECAHEDRON     : mTouchControl = new TouchControlDodecahedron(this);
2206
                                   break;
2207
        case TC_ICOSAHEDRON      : mTouchControl = new TouchControlIcosahedron(this);
2208
                                   break;
2209
        case TC_CUBOID           : int[] numLayers = getNumLayers();
2210
                                   mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
2211
                                   break;
2212
        case TC_BALL             : mTouchControl = new TouchControlBall(this);
2213
                                   break;
2214
        case TC_CHANGING_MIRROR  : mTouchControl = new TouchControlMirror(this);
2215
                                   break;
2216
        case TC_CHANGING_SQUARE  : mTouchControl = new TouchControlSquare(this);
2217
                                   break;
2218
        case TC_CHANGING_SHAPEMOD: mTouchControl = new TouchControlShapemod(this);
2219
                                   break;
2220
        }
2221
      }
2222
    return mTouchControl;
2223
    }
2224

    
2225
///////////////////////////////////////////////////////////////////////////////////////////////////
2226

    
2227
  protected void setReader(JsonReader reader)
2228
    {
2229
    // empty
2230
    }
2231

    
2232
///////////////////////////////////////////////////////////////////////////////////////////////////
2233
  // for JSON only
2234
  public abstract int getTouchControlType();
2235
  public abstract int getTouchControlSplit();
2236
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
2237
  public abstract int[][][] getEnabled();
2238
  public abstract float[] getDist3D(int[] numLayers);
2239
  public abstract Static3D[] getFaceAxis();
2240
  public abstract int[][] getScrambleEdges();
2241
  public abstract float[][] getCuts(int[] numLayers);
2242
  public abstract float getStickerRadius();
2243
  public abstract float getStickerStroke();
2244
  public abstract float[][] getStickerAngles();
2245
  public abstract int getCubitVariant(int cubit, int[] numLayers);
2246
  public abstract ObjectShape getObjectShape(int variant);
2247
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
2248
  public abstract ObjectVertexEffects getVertexEffects(int variant);
2249
  public abstract int getNumCubitVariants(int[] numLayers);
2250
  public abstract float[][] getCubitPositions(int[] numLayers);
2251
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
2252
  public abstract int getNumFaceColors();
2253
  public abstract float getScreenRatio();
2254
  public abstract int getColor(int face);
2255
  public abstract String getShortName();
2256
  public abstract ObjectSignature getSignature();
2257

    
2258
  // not only for JSON
2259
  public abstract Static3D[] getRotationAxis();
2260
  public abstract int[][] getBasicAngles();
2261
  public abstract int getNumFaces();
2262
  public abstract String getObjectName();
2263
  public abstract String getInventor();
2264
  public abstract int getYearOfInvention();
2265
  public abstract int getComplexity();
2266
  public abstract int getFOV();
2267
  public abstract String[][] getTutorials();
2268
  }
(8-8/9)