Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ 6db8fe2e

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.QuatGroupGenerator;
52
import org.distorted.objectlib.scrambling.ScrambleState;
53
import org.distorted.objectlib.scrambling.ObjectScrambler;
54
import org.distorted.objectlib.json.JsonReader;
55
import org.distorted.objectlib.touchcontrol.*;
56

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

    
59
///////////////////////////////////////////////////////////////////////////////////////////////////
60

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

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

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

    
80
  public static final int TEXTURE_HEIGHT = 256;
81
  static final int NUM_STICKERS_IN_ROW = 4;
82

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

    
88
  private static final float MAX_SIZE_CHANGE = 1.35f;
89
  private static final float MIN_SIZE_CHANGE = 0.75f;
90

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

    
94
  protected float[][] mStickerCoords;
95
  protected Static4D[] mObjectQuats;
96
  int mNumAxis, mMaxNumLayers;
97

    
98
  private int[][] mStickerVariants;
99
  private float[] mStickerScales;
100
  private Cubit[] mCubits;
101
  private MeshBase[] mMeshes;
102
  private int mNumCubits, mNumQuats, mNumFaceColors, mNumTextures, mNumOverrides;
103
  private int mNumCubitFaces, mNumStickerTypes;
104
  private Static3D[] mAxis;
105
  private float[][] mCuts;
106
  private int[] mNumCuts;
107
  private float[][] mOrigPos;
108
  private Static4D[] mOrigQuat;
109
  private Static4D[] mMixupModeQuats;
110
  private boolean mIsInMixupMode;
111
  private Static4D mQuat;
112
  private int[] mNumLayers;
113
  private 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 ObjectScrambler 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
  private int mIconMode;
145
  private InitData mInitData;
146
  private float[][] mRowOffsets;
147
  private boolean[] mBelongs;
148
  private float[] mTmp;
149
  private int mNumPuzzleFaces;
150
  private ObjectStickerOverride[] mStickerOverrides;
151
  private boolean mError;
152
  private String mErrorString;
153

    
154
  //////////////////// SOLVED1 ////////////////////////
155

    
156
  private int[] mFaceMap;
157
  private int[][] mScramble;
158
  private int[] mColors;
159

    
160
///////////////////////////////////////////////////////////////////////////////////////////////////
161

    
162
  TwistyObject(InputStream jsonStream, int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream meshStream)
163
    {
164
    try
165
      {
166
      JsonReader reader = JsonReader.getInstance();
167
      reader.parseJsonFile(jsonStream);
168
      setReader(reader);
169
      mNumLayers = reader.getNumLayers();
170
      mSize      = reader.getSize();
171
      mInitData  = null;
172
      initialize(meshState,iconMode,quat,move,scale,meshStream,true);
173
      mError = false;
174
      mErrorString=null;
175
      }
176
    catch(Exception ex)
177
      {
178
      mError = true;
179
      mErrorString = ex.getMessage();
180
      }
181
    }
182

    
183
///////////////////////////////////////////////////////////////////////////////////////////////////
184

    
185
  TwistyObject(InitData data, int meshState, int iconMode, float size, Static4D quat, Static3D move, float scale, InputStream meshStream)
186
    {
187
    mNumLayers = data.getNumLayers();
188
    mSize      = size;
189
    mInitData  = data;
190
    initialize(meshState,iconMode,quat,move,scale,meshStream,false);
191
    mError = false;
192
    mErrorString = null;
193
    }
194

    
195
///////////////////////////////////////////////////////////////////////////////////////////////////
196

    
197
  private void initialize(int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream meshStream, boolean fromJSON)
198
    {
199
    mIconMode = iconMode;
200
    mQuat = quat;
201
    mAxis = getRotationAxis();
202
    mInitScreenRatio = getScreenRatio();
203
    mSolvedFunctionIndex = getSolvedFunctionIndex();
204
    mBasicAngles = getBasicAngles();
205
    mObjectQuats = getQuats();
206
    mNumQuats = mObjectQuats.length;
207
    mOrigPos = getCubitPositions(mNumLayers);
208
    mNumPuzzleFaces = getNumFaces();
209
    mRowOffsets = new float[mNumPuzzleFaces][3];
210
    mTmp = new float[4];
211

    
212
    int numAxis = mAxis.length;
213
    mMaxNumLayers = -1;
214
    mCuts = getCuts(mNumLayers);
215
    mNumCuts = new int[numAxis];
216
    for(int i=0; i<numAxis; i++)
217
      {
218
      if( mMaxNumLayers<mNumLayers[i] ) mMaxNumLayers = mNumLayers[i];
219
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
220
      }
221

    
222
    mNumCubits = mOrigPos.length;
223
    mNumFaceColors = getNumFaceColors();
224
    mNumAxis = mAxis.length;
225
    mBelongs = new boolean[mNumCubits];
226

    
227
    int scramblingType = getScrambleType();
228
    ScrambleState[] states = getScrambleStates();
229
    mScrambler = new ObjectScrambler(scramblingType, mNumAxis,mNumLayers,states);
230

    
231
    boolean bandaged=false;
232

    
233
    for( int c=0; c<mNumCubits; c++)
234
      {
235
      if( mOrigPos[c].length>3 )
236
        {
237
        bandaged=true;
238
        break;
239
        }
240
      }
241
    mIsBandaged = bandaged;
242
    mQuatDebug = new int[mNumCubits];
243

    
244
    mRotationAngle= new Dynamic1D();
245
    mRotationAxis = new Static3D(1,0,0);
246
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
247

    
248
    mRotationAngleStatic = new Static1D(0);
249
    mRotationAngleMiddle = new Static1D(0);
250
    mRotationAngleFinal  = new Static1D(0);
251

    
252
    mObjectScale = new Static3D(scale,scale,scale);
253
    setObjectRatioNow(scale,720);
254

    
255
    mEffects = new DistortedEffects();
256
    createQuaternionEffects();
257

    
258
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
259
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
260
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
261

    
262
    boolean fromDMESH = (meshStream!=null && meshState==MESH_NICE);
263
    getQuatsAndShapes(fromDMESH,fromJSON);
264
    createMeshAndCubits(meshStream,meshState,fromDMESH);
265
    setUpTextures(fromDMESH,fromJSON);
266
    createDataStructuresForSolved();
267

    
268
    mEffects.apply(mRotateEffect);
269
    mEffects.apply(quatEffect);
270
    mEffects.apply(scaleEffect);
271
    mEffects.apply(moveEffect);
272

    
273
    mNode = new DistortedNode(mTexture,mEffects,mMesh);
274
    }
275

    
276
///////////////////////////////////////////////////////////////////////////////////////////////////
277

    
278
  private void createQuaternionEffects()
279
    {
280
    if( mNumQuats<=ObjectControl.MAX_QUATS )
281
      {
282
      mIsInMixupMode = false;
283

    
284
      for( int q=0; q<mNumQuats; q++)
285
        {
286
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mObjectQuats[q],CENTER);
287
        vq.setMeshAssociation(0,q);
288
        mEffects.apply(vq);
289
        }
290
      }
291
    else if( mNumCubits<=ObjectControl.MAX_QUATS )
292
      {
293
      mIsInMixupMode = true;
294
      mMixupModeQuats = new Static4D[mNumCubits];
295

    
296
      for( int q=0; q<mNumCubits; q++)
297
        {
298
        mMixupModeQuats[q] = new Static4D(mObjectQuats[0]);
299
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mMixupModeQuats[q],CENTER);
300
        vq.setMeshAssociation(0,q);
301
        mEffects.apply(vq);
302
        }
303
      }
304
    else
305
      {
306
      android.util.Log.e("D", "object has too many quaternions ("+mNumQuats+") or too many cubits ("+mNumCubits+")");
307
      }
308
    }
309

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

    
312
  private Static3D getPos(float[] origPos)
313
    {
314
    int len = origPos.length/3;
315
    float sumX = 0.0f;
316
    float sumY = 0.0f;
317
    float sumZ = 0.0f;
318

    
319
    for(int i=0; i<len; i++)
320
      {
321
      sumX += origPos[3*i  ];
322
      sumY += origPos[3*i+1];
323
      sumZ += origPos[3*i+2];
324
      }
325

    
326
    sumX /= len;
327
    sumY /= len;
328
    sumZ /= len;
329

    
330
    return new Static3D(sumX,sumY,sumZ);
331
    }
332

    
333
///////////////////////////////////////////////////////////////////////////////////////////////////
334

    
335
  private void createOuterFaces()
336
    {
337
    for(int v=0; v<mNumCubitVariants; v++)
338
      {
339
      int[][] indices = mShapes[v].getVertIndices();
340
      int faces = indices.length;
341
      mVariantFaceIsOuter[v] = new int[faces];
342
      }
343

    
344
    for( int cubit=0; cubit<mNumCubits; cubit++)
345
      {
346
      int variant = getCubitVariant(cubit,mNumLayers);
347
      int[][] indices = mShapes[variant].getVertIndices();
348
      int numFaces = indices.length;
349

    
350
      for(int face=0; face<numFaces; face++)
351
        if( getCubitFaceColor(cubit,face)>=0 )
352
          {
353
          mVariantFaceIsOuter[variant][face] = 1;
354
          }
355
      }
356
    }
357

    
358
///////////////////////////////////////////////////////////////////////////////////////////////////
359

    
360
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
361
    {
362
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
363

    
364
    if( !fromDMESH || !fromJSON )
365
      {
366
      FactoryCubit factory = FactoryCubit.getInstance();
367
      factory.clear();
368

    
369
      mOrigQuat = new Static4D[mNumCubits];
370
      for(int i=0; i<mNumCubits; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
371

    
372
      mShapes = new ObjectShape[mNumCubitVariants];
373
      for(int i=0; i<mNumCubitVariants; i++) mShapes[i] = getObjectShape(i);
374
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
375
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
376

    
377
      if( !fromJSON )
378
        {
379
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
380
        createOuterFaces();
381
        }
382

    
383
      if( fromDMESH )
384
        {
385
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
386
        }
387
      }
388
    }
389

    
390
///////////////////////////////////////////////////////////////////////////////////////////////////
391
// Radius of the sphere circumscribed on the puzzle. Needed for pillowing.
392
//
393
// This won't work correctly for pillowing off-center puzzles (e.g. mirrors) - for those we'd need
394
// to introduce the concept of a 'sink center' as well.
395

    
396
  private float getCircumscribedRadius()
397
    {
398
    switch(mNumPuzzleFaces)
399
      {
400
      case  4: return (SQ6/4)*mSize;
401
      case  6: return (SQ3/2)*mSize;
402
      case  8: return (SQ2/2)*mSize;
403
      case 12: return (SQ3/2)*((SQ5+1)/2)*mSize;
404
      }
405

    
406
    return 0.0f;
407
    }
408

    
409
///////////////////////////////////////////////////////////////////////////////////////////////////
410

    
411
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH)
412
    {
413
    mCubits = new Cubit[mNumCubits];
414

    
415
    if( fromDMESH )
416
      {
417
      DataInputStream dos = new DataInputStream(stream);
418
      mMesh = new MeshFile(dos);
419

    
420
      try
421
        {
422
        stream.close();
423
        }
424
      catch(IOException e)
425
        {
426
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
427
        }
428
      }
429
    else
430
      {
431
      MeshBase[] cubitMesh = new MeshBase[mNumCubits];
432

    
433
      for(int i=0; i<mNumCubits; i++)
434
        {
435
        cubitMesh[i] = createCubitMesh(i,mNumLayers,meshState,mNumCubitFaces);
436
        Static3D pos = getPos(mOrigPos[i]);
437
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
438
        }
439

    
440
      mMesh = new MeshJoined(cubitMesh);
441

    
442
      float pillowCoeff = getPillowCoeff();
443

    
444
      if( pillowCoeff!=1.0f )
445
        {
446
        float radius = getCircumscribedRadius();
447
        Static1D coeff = new Static1D(pillowCoeff);
448
        Static4D region= new Static4D(0,0,0,radius);
449
        VertexEffectSink sink = new VertexEffectSink(coeff,CENTER,region);
450
        mMesh.apply(sink);
451
        }
452
      }
453

    
454
    for(int i=0; i<mNumCubits; i++)
455
      {
456
      mCubits[i] = new Cubit(this,mOrigPos[i],mNumAxis,i);
457
      setCubitQuat(i,mCubits[i].computeAssociation(),0);
458
      }
459
    }
460

    
461
///////////////////////////////////////////////////////////////////////////////////////////////////
462

    
463
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState, int numComponents)
464
    {
465
    int variant = getCubitVariant(cubit,numLayers);
466

    
467
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
468

    
469
    if( mMeshes[variant]==null )
470
      {
471
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
472
      FactoryCubit factory = FactoryCubit.getInstance();
473
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
474
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,meshState, numComponents);
475
      }
476

    
477
    MeshBase mesh = mMeshes[variant].copy(true);
478
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
479
    mesh.apply(quat,0xffffffff,0);
480

    
481
    return mesh;
482
    }
483

    
484
///////////////////////////////////////////////////////////////////////////////////////////////////
485

    
486
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
487
    {
488
    mTexture = new DistortedTexture();
489

    
490
    if( fromJSON )
491
      {
492
      mNumStickerTypes = getNumStickerTypes();
493
      mNumCubitFaces = getNumCubitFaces();
494
      }
495
    else
496
      {
497
      FactoryCubit factory = FactoryCubit.getInstance();
498
      mStickerCoords   = factory.getStickerCoords();
499
      mStickerVariants = factory.getStickerVariants();
500
      mStickerScales   = factory.getStickerScales();
501
      adjustStickerCoords();
502
      mNumStickerTypes = (mStickerCoords==null ? 0 : mStickerCoords.length);
503
      }
504

    
505
    mStickerOverrides = getStickerOverrides();
506
    mNumOverrides = mStickerOverrides==null ? 0 : mStickerOverrides.length;
507

    
508
    mNumTextures= mNumFaceColors*mNumStickerTypes + mNumOverrides;
509
    mNumTexCols = NUM_STICKERS_IN_ROW;
510
    mNumTexRows = (mNumTextures+1)/NUM_STICKERS_IN_ROW;
511
    if( mNumTexCols*mNumTexRows < mNumTextures+1 ) mNumTexRows++;
512

    
513
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
514
    else overrideCubitFaceColor();
515

    
516
    setTexture();
517
    }
518

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

    
521
  private int getMultQuat(int index1, int index2)
522
    {
523
    if( mQuatMult==null )
524
      {
525
      mQuatMult = new int[mNumQuats][mNumQuats];
526

    
527
      for(int i=0; i<mNumQuats; i++)
528
        for(int j=0; j<mNumQuats; j++) mQuatMult[i][j] = -1;
529
      }
530

    
531
    if( index1<mNumQuats && index2<mNumQuats )
532
      {
533
      if( mQuatMult[index1][index2]==-1 ) mQuatMult[index1][index2] = mulQuat(index1,index2);
534
      return mQuatMult[index1][index2];
535
      }
536

    
537
    return -1;
538
    }
539

    
540
///////////////////////////////////////////////////////////////////////////////////////////////////
541

    
542
  public InitData getInitData()
543
    {
544
    return mInitData;
545
    }
546

    
547
///////////////////////////////////////////////////////////////////////////////////////////////////
548

    
549
  public boolean isInIconMode()
550
    {
551
    return mIconMode==MODE_ICON;
552
    }
553

    
554
///////////////////////////////////////////////////////////////////////////////////////////////////
555

    
556
  public int getVariantFaceColor(int variant, int face)
557
    {
558
    return face>=mStickerVariants[variant].length ? -1 : mStickerVariants[variant][face];
559
    }
560

    
561
///////////////////////////////////////////////////////////////////////////////////////////////////
562

    
563
  public boolean shouldResetTextureMaps()
564
    {
565
    return false;
566
    }
567

    
568
///////////////////////////////////////////////////////////////////////////////////////////////////
569

    
570
  private void createDataStructuresForSolved()
571
    {
572
    mTmpQuats = new int[mNumQuats];
573
    mSolvedQuats = getSolvedQuats();
574
    }
575

    
576
///////////////////////////////////////////////////////////////////////////////////////////////////
577
// This is used to build internal data structures for the generic 'isSolved()'
578
//
579
// if this is an internal cubit (all faces black): return -1
580
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
581
// Color index, i.e. the index into the 'FACE_COLORS' table.
582
// else (edge or corner cubit, more than one non-black face): return -2.
583

    
584
  protected int retCubitSolvedStatus(int cubit)
585
    {
586
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
587
    int variant = getCubitVariant(cubit,mNumLayers);
588

    
589
    for(int face=0; face<mNumCubitFaces; face++)
590
      {
591
      varColor = getVariantFaceColor(variant,face);
592
      int numFaces = mCubitFaceColors[cubit].length;
593
      cubColor = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
594

    
595
      if( varColor>=0 && cubColor>=0 )
596
        {
597
        numNonBlack++;
598
        nonBlackIndex = cubColor;
599
        }
600
      }
601

    
602
    if( numNonBlack==0 ) return -1;
603
    if( numNonBlack>=2 ) return -2;
604

    
605
    return nonBlackIndex;
606
    }
607

    
608
///////////////////////////////////////////////////////////////////////////////////////////////////
609

    
610
  private boolean sticksOut(Static3D[] faceAxis, float[] dist, float x, float y, float z )
611
    {
612
    final float MAXERR = 0.05f;
613
    int numAxis = dist.length;
614

    
615
    for(int i=0; i<numAxis; i++)
616
      {
617
      Static3D ax = faceAxis[i];
618
      float len = ax.get0()*x + ax.get1()*y + ax.get2()*z;
619
      if( len>mSize*dist[i]+MAXERR ) return true;
620
      }
621

    
622
    return false;
623
    }
624

    
625
///////////////////////////////////////////////////////////////////////////////////////////////////
626

    
627
  private boolean doesNotStickOut(int variant, float px, float py, float pz, float[] tmp, Static4D quat)
628
    {
629
    float[][] vertices = mShapes[variant].getVertices();
630
    Static3D[] axis = getFaceAxis();
631
    float[] dist3D = getDist3D(mNumLayers);
632

    
633
    for( float[] vertex : vertices)
634
      {
635
      float x = vertex[0];
636
      float y = vertex[1];
637
      float z = vertex[2];
638

    
639
      QuatHelper.rotateVectorByQuat(tmp, x, y, z, 1, quat);
640

    
641
      float mx = tmp[0] + px;
642
      float my = tmp[1] + py;
643
      float mz = tmp[2] + pz;
644

    
645
      if( sticksOut(axis, dist3D, mx,my,mz) ) return false;
646
      }
647

    
648
    return true;
649
    }
650

    
651
///////////////////////////////////////////////////////////////////////////////////////////////////
652

    
653
  private float computeAvg(float[] pos, int offset)
654
    {
655
    int len = pos.length/3;
656
    float ret=0.0f;
657
    for(int i=0; i<len; i++) ret += pos[3*i+offset];
658
    ret /= len;
659

    
660
    return ret;
661
    }
662

    
663
///////////////////////////////////////////////////////////////////////////////////////////////////
664

    
665
  protected void displayCubitQuats()
666
    {
667
    StringBuilder builder = new StringBuilder();
668
    float[] tmp = new float[4];
669
    float ERR = 0.01f;
670

    
671
    for(int cubit=0; cubit<mNumCubits; cubit++)
672
      {
673
      builder.append(cubit);
674
      builder.append(" : ");
675

    
676
      int refCubit,variant = getCubitVariant(cubit,mNumLayers);
677

    
678
      for(refCubit=0; refCubit<mNumCubits; refCubit++)
679
        {
680
        if( getCubitVariant(refCubit,mNumLayers)==variant ) break;
681
        }
682

    
683
      float[] curpos = mOrigPos[cubit];
684
      float[] refpos = mOrigPos[refCubit];
685
      float refX = computeAvg(refpos,0);
686
      float refY = computeAvg(refpos,1);
687
      float refZ = computeAvg(refpos,2);
688
      float curX = computeAvg(curpos,0);
689
      float curY = computeAvg(curpos,1);
690
      float curZ = computeAvg(curpos,2);
691

    
692
      for(int quat=0; quat<mNumQuats; quat++)
693
        {
694
        QuatHelper.rotateVectorByQuat(tmp,refX,refY,refZ,0,mObjectQuats[quat]);
695

    
696
        float dx = tmp[0]-curX;
697
        float dy = tmp[1]-curY;
698
        float dz = tmp[2]-curZ;
699

    
700
        if( dx>-ERR && dx<ERR && dy>-ERR && dy<ERR && dz>-ERR && dz<ERR )
701
          {
702
          if( doesNotStickOut(variant,curX,curY,curZ,tmp,mObjectQuats[quat]) )
703
            {
704
            builder.append(quat);
705
            builder.append(',');
706
            }
707
          else
708
            {
709
            android.util.Log.e("D", "cubit: "+cubit+" quat: "+quat+" : center correct, but shape sticks out");
710
            }
711
          }
712
        }
713

    
714
      builder.append('\n');
715
      }
716

    
717
    android.util.Log.e("D", "cubitQuats: \n"+builder.toString() );
718
    }
719

    
720
///////////////////////////////////////////////////////////////////////////////////////////////////
721

    
722
  protected int[] buildSolvedQuats(Static3D faceAx)
723
    {
724
    final float MAXD = 0.0001f;
725
    float x = faceAx.get0();
726
    float y = faceAx.get1();
727
    float z = faceAx.get2();
728
    float a,dx,dy,dz,qx,qy,qz;
729
    Static4D quat;
730
    int place = 0;
731

    
732
    for(int q=1; q<mNumQuats; q++)
733
      {
734
      quat = mObjectQuats[q];
735
      qx = quat.get0();
736
      qy = quat.get1();
737
      qz = quat.get2();
738

    
739
           if( x!=0.0f ) { a = qx/x; }
740
      else if( y!=0.0f ) { a = qy/y; }
741
      else               { a = qz/z; }
742

    
743
      dx = a*x-qx;
744
      dy = a*y-qy;
745
      dz = a*z-qz;
746

    
747
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
748
        {
749
        mTmpQuats[place++] = q;
750
        }
751
      }
752

    
753
    if( place!=0 )
754
      {
755
      int[] ret = new int[place];
756
      System.arraycopy(mTmpQuats,0,ret,0,place);
757
      return ret;
758
      }
759

    
760
    return null;
761
    }
762

    
763
///////////////////////////////////////////////////////////////////////////////////////////////////
764

    
765
  public int getCubitRotationType(int cubit)
766
    {
767
    return Cubit.TYPE_NORMAL;
768
    }
769

    
770
///////////////////////////////////////////////////////////////////////////////////////////////////
771

    
772
  float[] getTrackingPoint(int cubitIndex, int cubitType)
773
    {
774
    if( cubitType!=Cubit.TYPE_NORMAL )
775
      {
776
      int variant = getCubitVariant(cubitIndex,mNumLayers);
777

    
778
      // object must have been created from JSON
779
      if( mVariantFaceIsOuter==null || mVariantFaceIsOuter[variant]==null )
780
        {
781
        mVariantFaceIsOuter = getVariantFaceIsOuter();
782
        }
783
      if( mShapes==null )
784
        {
785
        mShapes = new ObjectShape[mNumCubitVariants];
786
        }
787
      if( mShapes[variant]==null )
788
        {
789
        mShapes[variant] = getObjectShape(variant);
790
        }
791
      if( mOrigQuat==null )
792
        {
793
        mOrigQuat = new Static4D[mNumCubits];
794
        }
795
      if( mOrigQuat[cubitIndex]==null )
796
        {
797
        mOrigQuat[cubitIndex] = getCubitQuats(cubitIndex,mNumLayers);
798
        }
799

    
800
      int[][] indices = mShapes[variant].getVertIndices();
801
      int outer=-1, faces = indices.length;
802

    
803
      for(int i=0; i<faces; i++)
804
        {
805
        if( mVariantFaceIsOuter[variant][i]==1 )
806
          {
807
          outer=i;
808
          break;
809
          }
810
        }
811

    
812
      if( outer>=0 )
813
        {
814
        int vertIndex = indices[outer][0];
815
        float[] vertices = mShapes[variant].getVertices()[vertIndex];
816
        float[] ret = new float[3];
817
        float[] curpos = mOrigPos[cubitIndex];
818
        Static4D quat = mOrigQuat[cubitIndex];
819
        QuatHelper.rotateVectorByQuat(mTmp, vertices[0], vertices[1], vertices[2], 1, quat);
820

    
821
        ret[0] = mTmp[0]+computeAvg(curpos,0);
822
        ret[1] = mTmp[1]+computeAvg(curpos,1);
823
        ret[2] = mTmp[2]+computeAvg(curpos,2);
824

    
825
        return ret;
826
        }
827
      else
828
        {
829
        android.util.Log.e("D", "Error in getTrackingPoint: no outer face??");
830
        }
831
      }
832

    
833
    return null;
834
    }
835

    
836
///////////////////////////////////////////////////////////////////////////////////////////////////
837

    
838
  public int computeCurrentPuzzleFace(int type, float[] vertex)
839
    {
840
    if( type!=Cubit.TYPE_NORMAL )
841
      {
842
      Static3D[] axis = getFaceAxis();
843
      float[] dist3D = getDist3D(mNumLayers);
844
      final float MAXERR = 0.98f;
845
      int numAxis = axis.length;
846
      float x = vertex[0];
847
      float y = vertex[1];
848
      float z = vertex[2];
849

    
850
      for(int i=0; i<numAxis; i++)
851
        {
852
        Static3D ax = axis[i];
853
        float len = ax.get0()*x + ax.get1()*y + ax.get2()*z;
854
        if( len>mSize*dist3D[i]*MAXERR ) return i;
855
        }
856
      }
857

    
858
    return -1;
859
    }
860

    
861
///////////////////////////////////////////////////////////////////////////////////////////////////
862

    
863
  public float[] getCubitRowOffset(int cubitIndex)
864
    {
865
    return null;
866
    }
867

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

    
870
  void setRotationRowOffset(int puzzleFace, float[] offset)
871
    {
872
    mRowOffsets[puzzleFace][0] = offset[0];
873
    mRowOffsets[puzzleFace][1] = offset[1];
874
    mRowOffsets[puzzleFace][2] = offset[2];
875
    }
876

    
877
///////////////////////////////////////////////////////////////////////////////////////////////////
878

    
879
  public int[][] getSolvedQuats()
880
    {
881
    int[] groups = new int[mNumCubits];
882
    int numGroups = 1;
883
    int numFirst  = 0;
884

    
885
    for(int cubit=0; cubit<mNumCubits; cubit++)
886
      {
887
      groups[cubit] = retCubitSolvedStatus(cubit);
888
      if( groups[cubit]>=0 ) numGroups++;
889
      else                   numFirst++;
890
      }
891

    
892
    int firstIndex = 1;
893
    int groupIndex = 1;
894
    int[][] solvedQuats = new int[numGroups][];
895
    solvedQuats[0] = new int[1+numFirst];
896
    solvedQuats[0][0] = numFirst;
897
    Static3D[] axis = getFaceAxis();
898

    
899
    for(int cubit=0; cubit<mNumCubits; cubit++)
900
      {
901
      int group = groups[cubit];
902

    
903
      if( group<0 )
904
        {
905
        solvedQuats[0][firstIndex] = cubit;
906
        firstIndex++;
907
        }
908
      else
909
        {
910
        int[] quats = buildSolvedQuats(axis[group]);
911
        int len = quats==null ? 0 : quats.length;
912
        solvedQuats[groupIndex] = new int[2+len];
913
        solvedQuats[groupIndex][0] = 1;
914
        solvedQuats[groupIndex][1] = cubit;
915
        for(int i=0; i<len; i++) solvedQuats[groupIndex][i+2] = quats[i];
916
        groupIndex++;
917
        }
918
      }
919
/*
920
    String dbg = "SOLVED GROUPS:\n";
921

    
922
    for(int g=0; g<numGroups; g++)
923
      {
924
      int len = solvedQuats[g].length;
925
      for(int i=0; i<len; i++) dbg += (" "+solvedQuats[g][i]);
926
      dbg+="\n";
927
      }
928

    
929
    android.util.Log.e("D", dbg);
930
*/
931
    return solvedQuats;
932
    }
933

    
934
///////////////////////////////////////////////////////////////////////////////////////////////////
935

    
936
  public int getSolvedFunctionIndex()
937
    {
938
    return 0;
939
    }
940

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

    
946
  private boolean isSolvedCentersOnly()
947
    {
948
    int numGroups = mSolvedQuats.length;
949

    
950
    for(int group=1; group<numGroups; group++)
951
      {
952
      int numEntries= mSolvedQuats[group].length;
953
      int numCubits = mSolvedQuats[group][0];
954
      int firstCubit= mSolvedQuats[group][1];
955
      int firstQuat = mCubits[firstCubit].mQuatIndex;
956

    
957
      for(int cubit=2; cubit<=numCubits; cubit++)
958
        {
959
        int currCubit= mSolvedQuats[group][cubit];
960
        int currQuat = mCubits[currCubit].mQuatIndex;
961
        boolean isGood= (firstQuat==currQuat);
962

    
963
        for(int q=numCubits+1; !isGood && q<numEntries; q++)
964
          {
965
          int quat = mSolvedQuats[group][q];
966
          if( firstQuat == getMultQuat(currQuat,quat) ) isGood = true;
967
          }
968

    
969
        if( !isGood ) return false;
970
        }
971
      }
972

    
973
    return true;
974
    }
975

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

    
978
  private boolean isSolved0()
979
    {
980
    if( mSolvedQuats[0][0]==0 ) return isSolvedCentersOnly();
981

    
982
    for( int[] solvedQuat : mSolvedQuats )
983
      {
984
      int numCubits = solvedQuat[0];
985
      int firstCubit= solvedQuat[1];
986
      int quat = mCubits[firstCubit].mQuatIndex;
987

    
988
      for( int cubit=2; cubit<=numCubits; cubit++ )
989
        {
990
        int c = solvedQuat[cubit];
991
        if( quat != mCubits[c].mQuatIndex ) return false;
992
        }
993
      }
994

    
995
    int cubit= mSolvedQuats[0][1];
996
    int quat0= mCubits[cubit].mQuatIndex;
997
    int numGroups = mSolvedQuats.length;
998

    
999
    for(int group=1; group<numGroups; group++)
1000
      {
1001
      int firstCubit= mSolvedQuats[group][1];
1002
      int currQuat  = mCubits[firstCubit].mQuatIndex;
1003

    
1004
      if( quat0==currQuat ) continue;
1005

    
1006
      boolean isGood= false;
1007
      int numEntries= mSolvedQuats[group].length;
1008
      int numCubits = mSolvedQuats[group][0];
1009

    
1010
      for(int q=numCubits+1; q<numEntries; q++)
1011
        {
1012
        int quat = mSolvedQuats[group][q];
1013

    
1014
        if( quat0 == getMultQuat(currQuat,quat) )
1015
          {
1016
          isGood = true;
1017
          break;
1018
          }
1019
        }
1020

    
1021
      if( !isGood ) return false;
1022
      }
1023

    
1024
    return true;
1025
    }
1026

    
1027
///////////////////////////////////////////////////////////////////////////////////////////////////
1028

    
1029
  private int computeScramble(int quatNum, int centerNum)
1030
    {
1031
    float MAXDIFF = 0.01f;
1032
    float[] center= mOrigPos[centerNum];
1033
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
1034
    Static4D result = QuatHelper.rotateVectorByQuat(sc,mObjectQuats[quatNum]);
1035

    
1036
    float x = result.get0();
1037
    float y = result.get1();
1038
    float z = result.get2();
1039

    
1040
    for(int c=0; c<mNumCubits; c++)
1041
      {
1042
      float[] cent = mOrigPos[c];
1043

    
1044
      float qx = cent[0] - x;
1045
      float qy = cent[1] - y;
1046
      float qz = cent[2] - z;
1047

    
1048
      if( qx>-MAXDIFF && qx<MAXDIFF &&
1049
          qy>-MAXDIFF && qy<MAXDIFF &&
1050
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
1051
      }
1052

    
1053
    return -1;
1054
    }
1055

    
1056
///////////////////////////////////////////////////////////////////////////////////////////////////
1057
// Dino4 uses this. It is solved if and only if groups of cubits
1058
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
1059
// or
1060
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
1061
// are all the same color.
1062

    
1063
  private boolean isSolved1()
1064
    {
1065
    if( mScramble==null )
1066
      {
1067
      mScramble = new int[mNumQuats][mNumCubits];
1068
      mColors   = new int[mNumCubits];
1069

    
1070
      for(int q=0; q<mNumQuats; q++)
1071
        for(int c=0; c<mNumCubits; c++) mScramble[q][c] = computeScramble(q,c);
1072
      }
1073

    
1074
    if( mFaceMap==null )
1075
      {
1076
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
1077
      }
1078

    
1079
    for(int c=0; c<mNumCubits; c++)
1080
      {
1081
      int index = mScramble[mCubits[c].mQuatIndex][c];
1082
      mColors[index] = mFaceMap[c];
1083
      }
1084

    
1085
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
1086
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
1087
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
1088

    
1089
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
1090
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
1091
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
1092

    
1093
    return false;
1094
    }
1095

    
1096
///////////////////////////////////////////////////////////////////////////////////////////////////
1097

    
1098
  int computeRow(float[] pos, int axisIndex, int cubitType, int puzzleFace)
1099
    {
1100
    int ret=0;
1101
    int len = pos.length / 3;
1102
    Static3D axis = mAxis[axisIndex];
1103
    float axisX = axis.get0();
1104
    float axisY = axis.get1();
1105
    float axisZ = axis.get2();
1106
    float casted, xoff=0, yoff=0, zoff=0;
1107

    
1108
    if( cubitType!=Cubit.TYPE_NORMAL )
1109
      {
1110
      xoff = mRowOffsets[puzzleFace][0];
1111
      yoff = mRowOffsets[puzzleFace][1];
1112
      zoff = mRowOffsets[puzzleFace][2];
1113
      }
1114

    
1115
    for(int i=0; i<len; i++)
1116
      {
1117
      casted = (pos[3*i]+xoff)*axisX + (pos[3*i+1]+yoff)*axisY + (pos[3*i+2]+zoff)*axisZ;
1118
      ret |= computeSingleRow(axisIndex,casted);
1119
      }
1120

    
1121
    return ret;
1122
    }
1123

    
1124
///////////////////////////////////////////////////////////////////////////////////////////////////
1125

    
1126
  private int computeSingleRow(int axisIndex,float casted)
1127
    {
1128
    int num = mNumCuts[axisIndex];
1129

    
1130
    for(int i=0; i<num; i++)
1131
      {
1132
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
1133
      }
1134

    
1135
    return (1<<num);
1136
    }
1137

    
1138
///////////////////////////////////////////////////////////////////////////////////////////////////
1139

    
1140
  private boolean wasRotateApplied()
1141
    {
1142
    return mEffects.exists(mRotateEffect.getID());
1143
    }
1144

    
1145
///////////////////////////////////////////////////////////////////////////////////////////////////
1146

    
1147
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
1148
    {
1149
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
1150
    }
1151

    
1152
///////////////////////////////////////////////////////////////////////////////////////////////////
1153
// note the minus in front of the sin() - we rotate counterclockwise
1154
// when looking towards the direction where the axis increases in values.
1155

    
1156
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
1157
    {
1158
    Static3D axis = mAxis[axisIndex];
1159

    
1160
    while( angleInDegrees<0 ) angleInDegrees += 360;
1161
    angleInDegrees %= 360;
1162
    
1163
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
1164
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
1165

    
1166
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
1167
    }
1168

    
1169
///////////////////////////////////////////////////////////////////////////////////////////////////
1170

    
1171
  private synchronized void setupPosition(int[][] moves)
1172
    {
1173
    if( moves!=null )
1174
      {
1175
      Static4D quat;
1176
      int index, axis, row, rowBitmap, basic, angle;
1177

    
1178
      for(int[] move: moves)
1179
        {
1180
        axis     = move[0];
1181
        rowBitmap= computeBitmapFromRow( move[1],axis );
1182
        row      = computeRowFromBitmap( move[1] );
1183
        basic    = mBasicAngles[axis][row];
1184
        angle    = move[2]*(360/basic);   // this assumes that all layers from
1185
                                          // the bitmap have the same BasicAngle.
1186
                                          // at the moment this is always true as
1187
                                          // there are no bandaged objects with
1188
                                          // different per-layer BasicAngles.
1189
        quat = makeQuaternion(axis,angle);
1190

    
1191
        for(int i=0; i<mNumCubits; i++)
1192
          {
1193
          mBelongs[i] = belongsToRotation(i,axis,rowBitmap);
1194
          if( mBelongs[i] ) mCubits[i].rotateCubit(quat);
1195
          }
1196

    
1197
        recomputeFaceOffsets();
1198

    
1199
        for(int i=0; i<mNumCubits; i++)
1200
          {
1201
          if( mBelongs[i] )
1202
            {
1203
            index = mCubits[i].postRotateCubit(quat);
1204
            setCubitQuat(i,mCubits[i].computeAssociation(),index);
1205
            }
1206
          else if( mCubits[i].getType()==Cubit.TYPE_FOLLOWER )
1207
            {
1208
            mCubits[i].computeRotationRow();
1209
            setCubitQuat(i,mCubits[i].computeAssociation(),mCubits[i].mQuatIndex);
1210
            }
1211
          }
1212
        }
1213
      }
1214
    }
1215

    
1216
///////////////////////////////////////////////////////////////////////////////////////////////////
1217

    
1218
  public int getScrambleType()
1219
    {
1220
    return 0;
1221
    }
1222

    
1223
///////////////////////////////////////////////////////////////////////////////////////////////////
1224

    
1225
  int computeBitmapFromRow(int rowBitmap, int axis)
1226
    {
1227
    if( mIsBandaged )
1228
      {
1229
      int bitmap, initBitmap=0;
1230

    
1231
      while( initBitmap!=rowBitmap )
1232
        {
1233
        initBitmap = rowBitmap;
1234

    
1235
        for(int cubit=0; cubit<mNumCubits; cubit++)
1236
          {
1237
          bitmap = mCubits[cubit].getRotRow(axis);
1238
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
1239
          }
1240
        }
1241
      }
1242

    
1243
    return rowBitmap;
1244
    }
1245

    
1246
///////////////////////////////////////////////////////////////////////////////////////////////////
1247

    
1248
  private int computeRowFromBitmap(int rowBitmap)
1249
    {
1250
    int index = 0;
1251

    
1252
    while(index<32)
1253
      {
1254
      if( (rowBitmap&0x1) != 0 ) return index;
1255
      rowBitmap>>=1;
1256
      index++;
1257
      }
1258
    return 0;
1259
    }
1260

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

    
1265
  void clampPos(float[] pos, int offset)
1266
    {
1267
    float currError, minError = Float.MAX_VALUE;
1268
    int minErrorIndex1 = -1;
1269
    int minErrorIndex2 = -1;
1270

    
1271
    float x = pos[offset  ];
1272
    float y = pos[offset+1];
1273
    float z = pos[offset+2];
1274

    
1275
    float xo,yo,zo;
1276

    
1277
    for(int i=0; i<mNumCubits; i++)
1278
      {
1279
      int len = mOrigPos[i].length / 3;
1280

    
1281
      for(int j=0; j<len; j++)
1282
        {
1283
        xo = mOrigPos[i][3*j  ];
1284
        yo = mOrigPos[i][3*j+1];
1285
        zo = mOrigPos[i][3*j+2];
1286

    
1287
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
1288

    
1289
        if( currError<minError )
1290
          {
1291
          minError = currError;
1292
          minErrorIndex1 = i;
1293
          minErrorIndex2 = j;
1294
          }
1295
        }
1296
      }
1297

    
1298
    if( minError< 0.1f ) // TODO: 0.1 ?
1299
      {
1300
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
1301
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
1302
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
1303
      }
1304
    }
1305

    
1306
///////////////////////////////////////////////////////////////////////////////////////////////////
1307
// remember about the double cover or unit quaternions!
1308

    
1309
  int mulQuat(int q1, int q2)
1310
    {
1311
    Static4D result = QuatHelper.quatMultiply(mObjectQuats[q1],mObjectQuats[q2]);
1312

    
1313
    float rX = result.get0();
1314
    float rY = result.get1();
1315
    float rZ = result.get2();
1316
    float rW = result.get3();
1317

    
1318
    final float MAX_ERROR = 0.1f;
1319
    float dX,dY,dZ,dW;
1320

    
1321
    for(int i=0; i<mNumQuats; i++)
1322
      {
1323
      dX = mObjectQuats[i].get0() - rX;
1324
      dY = mObjectQuats[i].get1() - rY;
1325
      dZ = mObjectQuats[i].get2() - rZ;
1326
      dW = mObjectQuats[i].get3() - rW;
1327

    
1328
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1329
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1330
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1331
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1332

    
1333
      dX = mObjectQuats[i].get0() + rX;
1334
      dY = mObjectQuats[i].get1() + rY;
1335
      dZ = mObjectQuats[i].get2() + rZ;
1336
      dW = mObjectQuats[i].get3() + rW;
1337

    
1338
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1339
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1340
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1341
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1342
      }
1343

    
1344
    return -1;
1345
    }
1346

    
1347
///////////////////////////////////////////////////////////////////////////////////////////////////
1348

    
1349
  private float getAngle()
1350
    {
1351
    int pointNum = mRotationAngle.getNumPoints();
1352

    
1353
    if( pointNum>=1 )
1354
      {
1355
      return mRotationAngle.getPoint(pointNum-1).get0();
1356
      }
1357
    else
1358
      {
1359
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
1360
      return 0;
1361
      }
1362
    }
1363

    
1364
///////////////////////////////////////////////////////////////////////////////////////////////////
1365

    
1366
  void setLibInterface(ObjectLibInterface inter)
1367
    {
1368
    mInterface = inter;
1369
    }
1370

    
1371
///////////////////////////////////////////////////////////////////////////////////////////////////
1372

    
1373
  void applyScrambles(int[][] moves)
1374
    {
1375
    setupPosition(moves);
1376
    }
1377

    
1378
///////////////////////////////////////////////////////////////////////////////////////////////////
1379

    
1380
  void initializeObject(int[][] moves)
1381
    {
1382
    solve();
1383
    setupPosition(moves);
1384
    }
1385

    
1386
///////////////////////////////////////////////////////////////////////////////////////////////////
1387

    
1388
  synchronized void removeRotationNow()
1389
    {
1390
    float angle = getAngle();
1391
    double nearestAngleInRadians = angle*Math.PI/180;
1392
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
1393
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
1394
    float axisX = mAxis[mCurrentRotAxis].get0();
1395
    float axisY = mAxis[mCurrentRotAxis].get1();
1396
    float axisZ = mAxis[mCurrentRotAxis].get2();
1397
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
1398

    
1399
    mRotationAngle.removeAll();
1400
    mRotationAngleStatic.set0(0);
1401

    
1402
    for(int i=0; i<mNumCubits; i++)
1403
      {
1404
      mBelongs[i] = belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap);
1405
      if( mBelongs[i] ) mCubits[i].rotateCubit(quat);
1406
      }
1407

    
1408
    recomputeFaceOffsets();
1409

    
1410
    for(int i=0; i<mNumCubits; i++)
1411
      {
1412
      if( mBelongs[i] )
1413
        {
1414
        int index = mCubits[i].postRotateCubit(quat);
1415
        setCubitQuat(i,mCubits[i].computeAssociation(),index);
1416
        }
1417
      else if( mCubits[i].getType()==Cubit.TYPE_FOLLOWER )
1418
        {
1419
        mCubits[i].computeRotationRow();
1420
        setCubitQuat(i,mCubits[i].computeAssociation(),mCubits[i].mQuatIndex);
1421
        }
1422
      }
1423
    }
1424

    
1425
///////////////////////////////////////////////////////////////////////////////////////////////////
1426

    
1427
  private void recomputeFaceOffsets()
1428
    {
1429
    for(int i=0; i<mNumPuzzleFaces; i++)
1430
      {
1431
      mRowOffsets[i][0] =0;
1432
      mRowOffsets[i][1] =0;
1433
      mRowOffsets[i][2] =0;
1434
      }
1435

    
1436
    for(int i=0; i<mNumCubits; i++)
1437
      if( mCubits[i].getType()==Cubit.TYPE_DECIDER )
1438
        {
1439
        float[] offset = mCubits[i].getOffset();
1440
        int face = mCubits[i].getPuzzleFace();
1441
        mRowOffsets[face][0] = offset[0];
1442
        mRowOffsets[face][1] = offset[1];
1443
        mRowOffsets[face][2] = offset[2];
1444
        }
1445
    }
1446

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

    
1449
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
1450
    {
1451
    if( wasRotateApplied() )
1452
      {
1453
      float angle = getAngle();
1454
      mRotationAngleStatic.set0(angle);
1455
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1456
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1457

    
1458
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1459
      mRotationAngle.resetToBeginning();
1460
      mRotationAngle.removeAll();
1461
      mRotationAngle.add(mRotationAngleStatic);
1462
      mRotationAngle.add(mRotationAngleMiddle);
1463
      mRotationAngle.add(mRotationAngleFinal);
1464
      mRotateEffect.notifyWhenFinished(listener);
1465

    
1466
      return mRotateEffect.getID();
1467
      }
1468

    
1469
    return 0;
1470
    }
1471

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

    
1474
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1475
    {
1476
    if( wasRotateApplied() )
1477
      {
1478
      mCurrentRotAxis = axis;
1479
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1480

    
1481
      mRotationAngleStatic.set0(0.0f);
1482
      mRotationAxis.set( mAxis[axis] );
1483
      mRotationAngle.setDuration(durationMillis);
1484
      mRotationAngle.resetToBeginning();
1485
      mRotationAngle.add(new Static1D(0));
1486
      mRotationAngle.add(new Static1D(angle));
1487
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1488
      mRotateEffect.notifyWhenFinished(listener);
1489

    
1490
      return mRotateEffect.getID();
1491
      }
1492

    
1493
    return 0;
1494
    }
1495

    
1496
///////////////////////////////////////////////////////////////////////////////////////////////////
1497

    
1498
  void continueRotation(float angleInDegrees)
1499
    {
1500
    mRotationAngleStatic.set0(angleInDegrees);
1501
    }
1502

    
1503
///////////////////////////////////////////////////////////////////////////////////////////////////
1504

    
1505
  synchronized void beginNewRotation(int axis, int row )
1506
    {
1507
    if( axis<0 || axis>=mNumAxis )
1508
      {
1509
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1510
      return;
1511
      }
1512
    if( row<0 || row>=mNumLayers[axis] )
1513
      {
1514
      android.util.Log.e("object", "invalid rotation row: "+row);
1515
      return;
1516
      }
1517

    
1518
    mCurrentRotAxis = axis;
1519
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1520
    mRotationAngleStatic.set0(0.0f);
1521
    mRotationAxis.set( mAxis[axis] );
1522
    mRotationAngle.add(mRotationAngleStatic);
1523
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1524
    }
1525

    
1526
///////////////////////////////////////////////////////////////////////////////////////////////////
1527

    
1528
  void setTextureMap(int cubit, int face, int newColor)
1529
    {
1530
    final float ratioW = 1.0f/mNumTexCols;
1531
    final float ratioH = 1.0f/mNumTexRows;
1532
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1533
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1534
    int col = newColor%mNumTexCols;
1535

    
1536
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1537
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1538
    }
1539

    
1540
///////////////////////////////////////////////////////////////////////////////////////////////////
1541

    
1542
  private int getCubitFaceColor(int cubit, int face)
1543
    {
1544
    int puzzleFace = getCubitFaceMap(cubit,face);
1545
    if( puzzleFace>=0 ) puzzleFace %= mNumFaceColors;
1546
    return puzzleFace;
1547
    }
1548

    
1549
///////////////////////////////////////////////////////////////////////////////////////////////////
1550

    
1551
  public int getCubitFaceMap(int cubit, int face)
1552
    {
1553
    int numFaces = mCubitFaceColors[cubit].length;
1554
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1555
    return puzzleFace<0 ? -1 : puzzleFace;
1556
    }
1557

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

    
1560
  void resetAllTextureMaps()
1561
    {
1562
    final float ratioW = 1.0f/mNumTexCols;
1563
    final float ratioH = 1.0f/mNumTexRows;
1564
    int cubColor, varColor, color, variant, row, col;
1565

    
1566
    for(int cubit=0; cubit<mNumCubits; cubit++)
1567
      {
1568
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1569
      variant = getCubitVariant(cubit,mNumLayers);
1570

    
1571
      for(int face=0; face<mNumCubitFaces; face++)
1572
        {
1573
        cubColor = getCubitFaceColor(cubit,face);
1574
        varColor = getVariantFaceColor(variant,face);
1575
        color    = cubColor<0 || varColor<0 ? mNumTextures-mNumOverrides : varColor*mNumFaceColors + cubColor;
1576
        row      = (mNumTexRows-1) - color/mNumTexCols;
1577
        col      = color%mNumTexCols;
1578

    
1579
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1580
        }
1581

    
1582
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1583
      }
1584

    
1585
    overrideCubitFaceColor();
1586
    }
1587

    
1588
///////////////////////////////////////////////////////////////////////////////////////////////////
1589

    
1590
  private void overrideCubitFaceColor()
1591
    {
1592
    final float ratioW = 1.0f/mNumTexCols;
1593
    final float ratioH = 1.0f/mNumTexRows;
1594

    
1595
    for(int i=0; i<mNumOverrides; i++)
1596
      {
1597
      int[] cubitFaces = mStickerOverrides[i].getCubitFaces();
1598
      int length = cubitFaces.length/2;
1599

    
1600
      for(int j=0; j<length; j++)
1601
        {
1602
        final Static4D[] maps = new Static4D[1];
1603
        int color = mNumTextures-mNumOverrides+1+i;
1604
        int row   = (mNumTexRows-1) - color/mNumTexCols;
1605
        int col   = color%mNumTexCols;
1606
        int cubit = cubitFaces[2*j];
1607
        int face  = cubitFaces[2*j+1];
1608
        maps[0] = new Static4D(col*ratioW, row*ratioH, ratioW, ratioH);
1609
        mMesh.setTextureMap(maps,mNumCubitFaces*cubit+face);
1610
        }
1611
      }
1612
    }
1613

    
1614
///////////////////////////////////////////////////////////////////////////////////////////////////
1615

    
1616
  void releaseResources()
1617
    {
1618
    mTexture.markForDeletion();
1619
    mMesh.markForDeletion();
1620
    mEffects.markForDeletion();
1621

    
1622
    for(int j=0; j<mNumCubits; j++)
1623
      {
1624
      mCubits[j].releaseResources();
1625
      }
1626
    }
1627

    
1628
///////////////////////////////////////////////////////////////////////////////////////////////////
1629

    
1630
  private void setCubitQuat(int cubit, int andAssociation, int equAssociation)
1631
    {
1632
    if( !mIsInMixupMode )
1633
      {
1634
      mMesh.setEffectAssociation(cubit,andAssociation,equAssociation);
1635
      }
1636
    else
1637
      {
1638
      mMesh.setEffectAssociation(cubit,andAssociation,cubit);
1639
      Static4D tmp = mObjectQuats[equAssociation];
1640
      mMixupModeQuats[cubit].set(tmp);
1641
      }
1642
    }
1643

    
1644
///////////////////////////////////////////////////////////////////////////////////////////////////
1645

    
1646
  synchronized void restorePreferences(SharedPreferences preferences)
1647
    {
1648
    boolean error = false;
1649
    String key = getShortName();
1650

    
1651
    for(int i=0; i<mNumCubits; i++)
1652
      {
1653
      mQuatDebug[i] = mCubits[i].restorePreferences(key,preferences);
1654

    
1655
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1656
        {
1657
        mCubits[i].rotateCubit(mObjectQuats[mQuatDebug[i]]);
1658
        }
1659
      else { error = true; break; }
1660
      }
1661

    
1662
    if( !error )
1663
      {
1664
      recomputeFaceOffsets();
1665

    
1666
      for(int i=0; i<mNumCubits; i++)
1667
        {
1668
        if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1669
          {
1670
          mCubits[i].computeRotationRow();
1671
          setCubitQuat(i,mCubits[i].computeAssociation(),mQuatDebug[i]);
1672
          }
1673
        else { error = true; break; }
1674
        }
1675
      }
1676

    
1677
    if( error )
1678
      {
1679
      for(int i=0; i<mNumCubits; i++)
1680
        {
1681
        mCubits[i].solve();
1682
        setCubitQuat(i,mCubits[i].computeAssociation(),0);
1683
        }
1684
      }
1685
    }
1686

    
1687
///////////////////////////////////////////////////////////////////////////////////////////////////
1688

    
1689
  void savePreferences(SharedPreferences.Editor editor)
1690
    {
1691
    String key = getShortName();
1692
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(key,editor);
1693
    }
1694

    
1695
///////////////////////////////////////////////////////////////////////////////////////////////////
1696

    
1697
  public void removePreferences(SharedPreferences.Editor editor)
1698
    {
1699
    String key = getShortName();
1700
    for(int i=0; i<mNumCubits; i++) mCubits[i].removePreferences(key,editor);
1701
    }
1702

    
1703
///////////////////////////////////////////////////////////////////////////////////////////////////
1704

    
1705
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1706
    {
1707
    final float A = 0.8f;  // 0<A<1
1708

    
1709
    int prev = curr>0 ? curr-1 : len-1;
1710
    int next = curr<len-1 ? curr+1 : 0;
1711

    
1712
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1713
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1714
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1715
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1716

    
1717
    float len1= v1x*v1x+v1y*v1y;
1718
    float len2= v2x*v2x+v2y*v2y;
1719

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

    
1722
    return 1-A*cos;
1723
    }
1724

    
1725
///////////////////////////////////////////////////////////////////////////////////////////////////
1726

    
1727
  public ObjectSticker retSticker(int sticker)
1728
    {
1729
    if( mStickers==null )
1730
      {
1731
      float rad = getStickerRadius();
1732
      float str = getStickerStroke();
1733
      float[][] angles = getStickerAngles();
1734
      int numStickers = mStickerCoords.length;
1735
      mStickers = new ObjectSticker[numStickers];
1736

    
1737
      for(int s=0; s<numStickers; s++)
1738
        {
1739
        float scale = mStickerScales.length>s ? mStickerScales[s] : 1.0f;
1740
        float radius = rad / scale;
1741
        float stroke = str / scale;
1742
        int len = mStickerCoords[s].length/2;
1743
        float[] radii = new float[len];
1744
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1745
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1746
        }
1747
      }
1748

    
1749
    return mStickers[sticker];
1750
    }
1751

    
1752
///////////////////////////////////////////////////////////////////////////////////////////////////
1753
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1754

    
1755
  public void adjustStickerCoords()
1756
    {
1757

    
1758
    }
1759

    
1760
///////////////////////////////////////////////////////////////////////////////////////////////////
1761

    
1762
  public Static4D[] getQuats()
1763
    {
1764
    if( mObjectQuats==null )
1765
      {
1766
      mObjectQuats = QuatGroupGenerator.computeGroup(mAxis,mBasicAngles);
1767
      }
1768

    
1769
    return mObjectQuats;
1770
    }
1771

    
1772
///////////////////////////////////////////////////////////////////////////////////////////////////
1773

    
1774
  public int[][] getVariantFaceIsOuter()
1775
    {
1776
    return mVariantFaceIsOuter;
1777
    }
1778

    
1779
///////////////////////////////////////////////////////////////////////////////////////////////////
1780

    
1781
  public int getInternalColor()
1782
    {
1783
    return COLOR_INTERNAL;
1784
    }
1785

    
1786
///////////////////////////////////////////////////////////////////////////////////////////////////
1787
// the getFaceColors + final INTERNAL_COLOR in a grid (so that we do not exceed the maximum texture size)
1788

    
1789
  private void createTexture()
1790
    {
1791
    Paint paint = new Paint();
1792
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_4444);
1793
    Canvas canvas = new Canvas(mBitmap);
1794

    
1795
    paint.setAntiAlias(true);
1796
    paint.setTextAlign(Paint.Align.CENTER);
1797
    paint.setStyle(Paint.Style.FILL);
1798
    paint.setColor(getInternalColor());
1799
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1800

    
1801
    int texture = 0;
1802
    FactorySticker factory = FactorySticker.getInstance();
1803

    
1804
    for(int row=0; row<mNumTexRows; row++)
1805
      for(int col=0; col<mNumTexCols; col++)
1806
        {
1807
        if( texture<mNumTextures-mNumOverrides )
1808
          {
1809
          ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1810
          int color = getColor(texture%mNumFaceColors);
1811
          factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, (mNumTexRows-row)*TEXTURE_HEIGHT, color, sticker);
1812
          }
1813
        else if( texture>mNumTextures-mNumOverrides && texture<=mNumTextures )
1814
          {
1815
          int color = mStickerOverrides[mNumTextures-texture].getColor();
1816
          factory.drawSolidColor(canvas, paint, col*TEXTURE_HEIGHT, (mNumTexRows-row)*TEXTURE_HEIGHT, color);
1817
          }
1818

    
1819
        texture++;
1820
        }
1821
    }
1822

    
1823
///////////////////////////////////////////////////////////////////////////////////////////////////
1824

    
1825
  void setTexture()
1826
    {
1827
    if( mBitmap==null ) createTexture();
1828

    
1829
    if( !mTexture.setTextureAlreadyInverted(mBitmap) )
1830
      {
1831
      int max = DistortedLibrary.getMaxTextureSize();
1832
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1833
      }
1834
    }
1835

    
1836
///////////////////////////////////////////////////////////////////////////////////////////////////
1837

    
1838
  void setObjectRatioNow(float sc, int nodeSize)
1839
    {
1840
    mObjectScreenRatio = sc;
1841
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1842
    mObjectScale.set(scale,scale,scale);
1843

    
1844
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1845
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1846
    }
1847

    
1848
///////////////////////////////////////////////////////////////////////////////////////////////////
1849

    
1850
  void setObjectRatio(float sizeChange, int nodeSize)
1851
    {
1852
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1853

    
1854
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1855
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1856

    
1857
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1858
    }
1859

    
1860
///////////////////////////////////////////////////////////////////////////////////////////////////
1861

    
1862
  void setNodeSize(int nodeSize)
1863
    {
1864
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1865
    }
1866

    
1867
///////////////////////////////////////////////////////////////////////////////////////////////////
1868

    
1869
  public float getRatio()
1870
    {
1871
    return mObjectScreenRatio;
1872
    }
1873

    
1874
///////////////////////////////////////////////////////////////////////////////////////////////////
1875

    
1876
  public float getObjectRatio()
1877
    {
1878
    return mObjectScreenRatio*mInitScreenRatio;
1879
    }
1880

    
1881
///////////////////////////////////////////////////////////////////////////////////////////////////
1882

    
1883
  boolean isSolved()
1884
    {
1885
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1886
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1887

    
1888
    return false;
1889
    }
1890

    
1891
///////////////////////////////////////////////////////////////////////////////////////////////////
1892

    
1893
  int computeNearestAngle(int basicAngle, float angle, float speed)
1894
    {
1895
    int nearestAngle = 360/basicAngle;
1896
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1897
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1898

    
1899
    if( tmp!=0 ) return nearestAngle*tmp;
1900

    
1901
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1902
    }
1903

    
1904
///////////////////////////////////////////////////////////////////////////////////////////////////
1905
// INTERNAL API - those are called from 'effects' package
1906
///////////////////////////////////////////////////////////////////////////////////////////////////
1907

    
1908
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1909
    {
1910
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total, getSignature() );
1911
    }
1912

    
1913
///////////////////////////////////////////////////////////////////////////////////////////////////
1914

    
1915
  public Static4D getRotationQuat()
1916
    {
1917
    return mQuat;
1918
    }
1919

    
1920
///////////////////////////////////////////////////////////////////////////////////////////////////
1921

    
1922
  public float getSize()
1923
    {
1924
    return mSize;
1925
    }
1926

    
1927
///////////////////////////////////////////////////////////////////////////////////////////////////
1928

    
1929
  public void applyEffect(Effect effect, int position)
1930
    {
1931
    mEffects.apply(effect, position);
1932
    }
1933

    
1934
///////////////////////////////////////////////////////////////////////////////////////////////////
1935

    
1936
  public void removeEffect(long effectID)
1937
    {
1938
    mEffects.abortById(effectID);
1939
    }
1940

    
1941
///////////////////////////////////////////////////////////////////////////////////////////////////
1942

    
1943
  public MeshBase getObjectMesh()
1944
    {
1945
    return mMesh;
1946
    }
1947

    
1948
///////////////////////////////////////////////////////////////////////////////////////////////////
1949

    
1950
  public DistortedEffects getObjectEffects()
1951
    {
1952
    return mEffects;
1953
    }
1954

    
1955
///////////////////////////////////////////////////////////////////////////////////////////////////
1956

    
1957
  public int getCubitType(int cubit)
1958
    {
1959
    return mCubits[cubit].getType();
1960
    }
1961

    
1962
///////////////////////////////////////////////////////////////////////////////////////////////////
1963

    
1964
  public float[] getCubitOffset(int cubit)
1965
    {
1966
    return mCubits[cubit].getOffset();
1967
    }
1968

    
1969
///////////////////////////////////////////////////////////////////////////////////////////////////
1970

    
1971
  public ObjectStickerOverride[] getStickerOverrides()
1972
    {
1973
    return null;
1974
    }
1975

    
1976
///////////////////////////////////////////////////////////////////////////////////////////////////
1977

    
1978
  public boolean getError()
1979
    {
1980
    return mError;
1981
    }
1982

    
1983
///////////////////////////////////////////////////////////////////////////////////////////////////
1984

    
1985
  public String getErrorString()
1986
    {
1987
    return mErrorString;
1988
    }
1989

    
1990
///////////////////////////////////////////////////////////////////////////////////////////////////
1991
// PUBLIC API
1992
///////////////////////////////////////////////////////////////////////////////////////////////////
1993

    
1994
  public int getCubitFaceColorIndex(int cubit, int face)
1995
    {
1996
    Static4D texMap = mMesh.getTextureMap(mNumFaceColors *cubit + face);
1997

    
1998
    int x = (int)(texMap.get0()/texMap.get2());
1999
    int y = (int)(texMap.get1()/texMap.get3());
2000

    
2001
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
2002
    }
2003

    
2004
///////////////////////////////////////////////////////////////////////////////////////////////////
2005

    
2006
  public int[] getNumLayers()
2007
    {
2008
    return mNumLayers;
2009
    }
2010

    
2011
///////////////////////////////////////////////////////////////////////////////////////////////////
2012

    
2013
  public synchronized void solve()
2014
    {
2015
    for(int i=0; i<mNumCubits; i++)
2016
      {
2017
      mCubits[i].solve();
2018
      }
2019

    
2020
    recomputeFaceOffsets();
2021

    
2022
    for(int i=0; i<mNumCubits; i++)
2023
      {
2024
      mCubits[i].computeRotationRow();
2025
      setCubitQuat(i,mCubits[i].computeAssociation(),0);
2026
      }
2027
    }
2028

    
2029
///////////////////////////////////////////////////////////////////////////////////////////////////
2030

    
2031
  public int getCubitQuatIndex(int cubit)
2032
    {
2033
    return (cubit>=0 && cubit<mNumCubits) ? mCubits[cubit].mQuatIndex : 0;
2034
    }
2035

    
2036
///////////////////////////////////////////////////////////////////////////////////////////////////
2037

    
2038
  public int getCubitRotRow(int cubit, int axis)
2039
    {
2040
    return mCubits[cubit].getRotRow(axis);
2041
    }
2042

    
2043
///////////////////////////////////////////////////////////////////////////////////////////////////
2044

    
2045
  public Bitmap getStickerBitmap()
2046
    {
2047
    return mBitmap;
2048
    }
2049

    
2050
///////////////////////////////////////////////////////////////////////////////////////////////////
2051

    
2052
  public DistortedNode getNode()
2053
    {
2054
    return mNode;
2055
    }
2056

    
2057
///////////////////////////////////////////////////////////////////////////////////////////////////
2058

    
2059
  public int getNumStickerTypes()
2060
    {
2061
    return mNumStickerTypes;
2062
    }
2063

    
2064
///////////////////////////////////////////////////////////////////////////////////////////////////
2065

    
2066
  public String reportState()
2067
    {
2068
    StringBuilder builder = new StringBuilder();
2069

    
2070
    for(int i=0; i<mNumCubits; i++ )
2071
      {
2072
      if( i>0 ) builder.append('.');
2073
      builder.append(mCubits[i].mQuatIndex);
2074
      }
2075

    
2076
    return builder.toString();
2077
    }
2078

    
2079
///////////////////////////////////////////////////////////////////////////////////////////////////
2080
// this is here only so it can be overridden in TwistyJSON so that we can get this from JSON.
2081

    
2082
  public int getNumCubitFaces()
2083
    {
2084
    return 0;
2085
    }
2086

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

    
2092
  public float getPillowCoeff()
2093
    {
2094
    return 1.0f;
2095
    }
2096

    
2097
///////////////////////////////////////////////////////////////////////////////////////////////////
2098

    
2099
  public TouchControl getTouchControl()
2100
    {
2101
    if( mTouchControl==null )
2102
      {
2103
      switch(getTouchControlType())
2104
        {
2105
        case TC_TETRAHEDRON      : mTouchControl = new TouchControlTetrahedron(this);
2106
                                   break;
2107
        case TC_HEXAHEDRON       : mTouchControl = new TouchControlHexahedron(this);
2108
                                   break;
2109
        case TC_OCTAHEDRON       : mTouchControl = new TouchControlOctahedron(this);
2110
                                   break;
2111
        case TC_DODECAHEDRON     : mTouchControl = new TouchControlDodecahedron(this);
2112
                                   break;
2113
        case TC_CUBOID           : int[] numLayers = getNumLayers();
2114
                                   mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
2115
                                   break;
2116
        case TC_CHANGING_MIRROR  : mTouchControl = new TouchControlMirror(this);
2117
                                   break;
2118
        case TC_CHANGING_SQUARE  : mTouchControl = new TouchControlSquare(this);
2119
                                   break;
2120
        case TC_CHANGING_SHAPEMOD: mTouchControl = new TouchControlShapemod(this);
2121
                                   break;
2122
        }
2123
      }
2124
    return mTouchControl;
2125
    }
2126

    
2127
///////////////////////////////////////////////////////////////////////////////////////////////////
2128

    
2129
  protected void setReader(JsonReader reader)
2130
    {
2131
    // empty
2132
    }
2133

    
2134
///////////////////////////////////////////////////////////////////////////////////////////////////
2135
  // for JSON only
2136
  public abstract int getTouchControlType();
2137
  public abstract int getTouchControlSplit();
2138
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
2139
  public abstract int[][][] getEnabled();
2140
  public abstract float[] getDist3D(int[] numLayers);
2141
  public abstract Static3D[] getFaceAxis();
2142
  public abstract ScrambleState[] getScrambleStates();
2143
  public abstract float[][] getCuts(int[] numLayers);
2144
  public abstract float getStickerRadius();
2145
  public abstract float getStickerStroke();
2146
  public abstract float[][] getStickerAngles();
2147
  public abstract int getCubitVariant(int cubit, int[] numLayers);
2148
  public abstract ObjectShape getObjectShape(int variant);
2149
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
2150
  public abstract int getNumCubitVariants(int[] numLayers);
2151
  public abstract float[][] getCubitPositions(int[] numLayers);
2152
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
2153
  public abstract int getNumFaceColors();
2154
  public abstract float getScreenRatio();
2155
  public abstract int getColor(int face);
2156
  public abstract String getShortName();
2157
  public abstract ObjectSignature getSignature();
2158

    
2159
  // not only for JSON
2160
  public abstract Static3D[] getRotationAxis();
2161
  public abstract int[][] getBasicAngles();
2162
  public abstract int getNumFaces();
2163
  public abstract String getObjectName();
2164
  public abstract String getInventor();
2165
  public abstract int getYearOfInvention();
2166
  public abstract int getComplexity();
2167
  public abstract int getFOV();
2168
  public abstract String[][] getTutorials();
2169
  }
(12-12/13)