Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ 224c0ff1

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.graphics.Bitmap;
18
import android.graphics.Canvas;
19
import android.graphics.Paint;
20

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

    
40
import org.distorted.objectlib.helpers.FactoryCubit;
41
import org.distorted.objectlib.helpers.FactorySticker;
42
import org.distorted.objectlib.helpers.ObjectFaceShape;
43
import org.distorted.objectlib.helpers.ObjectLibInterface;
44
import org.distorted.objectlib.helpers.ObjectShape;
45
import org.distorted.objectlib.metadata.Metadata;
46
import org.distorted.objectlib.signature.ObjectSignature;
47
import org.distorted.objectlib.helpers.ObjectSticker;
48
import org.distorted.objectlib.helpers.ObjectStickerOverride;
49
import org.distorted.objectlib.helpers.ObjectVertexEffects;
50
import org.distorted.objectlib.helpers.OperatingSystemInterface;
51
import org.distorted.objectlib.helpers.QuatGroupGenerator;
52
import org.distorted.objectlib.scrambling.ObjectScrambler;
53
import org.distorted.objectlib.json.JsonReader;
54
import org.distorted.objectlib.scrambling.ScrambleEdgeGenerator;
55
import org.distorted.objectlib.tablebases.ImplementedTablebasesList;
56
import org.distorted.objectlib.tablebases.TablebasesAbstract;
57
import org.distorted.objectlib.touchcontrol.*;
58

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

    
61
///////////////////////////////////////////////////////////////////////////////////////////////////
62

    
63
public abstract class TwistyObject
64
  {
65
  public static final int MODE_ICON = 0;
66
  public static final int MODE_NORM = 1;
67

    
68
  public static final int COLOR_STROKE   = 0xff000000;
69
  public static final int COLOR_INTERNAL = 0xff000000;
70

    
71
  private static final int DEFAULT_TEXTURE_HEIGHT = 256;
72
  private static final int DEFAULT_TEXTURE_ROWS   = 8;
73

    
74
  public static final float SQ2 = (float)Math.sqrt(2);
75
  public static final float SQ3 = (float)Math.sqrt(3);
76
  public static final float SQ5 = (float)Math.sqrt(5);
77
  public static final float SQ6 = (float)Math.sqrt(6);
78

    
79
  private static final float MAX_SIZE_CHANGE = 1.35f;
80
  private static final float MIN_SIZE_CHANGE = 0.75f;
81

    
82
  private static final Static3D CENTER = new Static3D(0,0,0);
83

    
84
  protected float[][][][] mStickerCoords;
85
  protected Static4D[] mObjectQuats;
86

    
87
  private int[][] mStickerVariants;
88
  private float[] mStickerScales;
89
  private TwistyObjectCubit[] mCubits;
90
  private TwistyObjectSolved mSolved;
91
  private MeshBase[] mMeshes;
92
  private int mNumCubits, mNumQuats, mNumFaceColors, mNumTextures, mNumOverrides;
93
  private int mNumCubitFaces, mNumStickerTypes;
94
  private Static3D[] mAxis;
95
  private float[][] mCuts;
96
  private int[][] mMinimalCubiesInRow;
97
  private int[] mNumCuts;
98
  private float[][] mOrigPos;
99
  private Static4D[] mOrigQuat;
100
  private Static4D[] mMixupModeQuats;
101
  private boolean mIsInMixupMode;
102
  private Static4D mQuat;
103
  private int[] mNumLayers;
104
  private float mSize;
105
  private DistortedEffects mEffects;
106
  private Static3D mObjectScale;
107
  private int[] mQuatDebug;
108
  private DistortedTexture mTexture;
109
  private float mInitScreenRatio;
110
  private boolean mIsBandaged;
111
  private float mObjectScreenRatio;
112
  private int mNumTexRows, mNumTexCols, mTexHeight;
113
  private MeshBase mMesh;
114
  private ObjectScrambler mScrambler;
115
  private TouchControl mTouchControl;
116
  private DistortedNode mNode;
117
  private ObjectLibInterface mInterface;
118
  private Bitmap mBitmap;
119
  private ObjectSticker[] mStickers;
120
  private ObjectShape[] mShapes;
121
  private int mNumCubitVariants;
122
  private int[][] mCubitFaceColors;
123
  private int[][] mVariantFaceIsOuter;
124
  private int[][] mBasicAngles;
125
  private int mIconMode;
126
  private Metadata mMetadata;
127
  private float[][] mRowOffsets;
128
  private boolean[] mBelongs;
129
  private float[] mTmp;
130
  private int mNumPuzzleFaces;
131
  private ObjectStickerOverride[] mStickerOverrides;
132
  private boolean mError;
133
  private String mErrorString;
134
  private int mMaxNumLayers;
135
  private int mNumAxis;
136
  private boolean mThereAreDeciders;
137
  private TwistyLayerRotations mRotation;
138
  private int[] mColorTable;
139
  private int[] mOriginalColorTable;
140
  private float mTextureBorderMultiplier, mTextureCornerMultiplier;
141

    
142
///////////////////////////////////////////////////////////////////////////////////////////////////
143

    
144
  TwistyObject(int iconMode, Static4D quat, Static3D move, float scale, InitAssets asset)
145
    {
146
    try
147
      {
148
      InputStream jsonStream = asset!=null ? asset.getJsonStream(): null;
149
      JsonReader reader = new JsonReader();
150
      reader.parseJsonFile(jsonStream);
151
      setReader(reader);
152
      mNumLayers = reader.getNumLayers();
153
      mSize      = reader.getSize();
154
      mMetadata  = null;
155
      initialize(iconMode,quat,move,scale,asset,true);
156
      if( asset!=null ) asset.close();
157
      mError = false;
158
      mErrorString=null;
159
      }
160
    catch(Exception ex)
161
      {
162
      mError = true;
163
      mErrorString = ex.getMessage();
164
      }
165
    }
166

    
167
///////////////////////////////////////////////////////////////////////////////////////////////////
168

    
169
  public TwistyObject(int iconMode, float size, Static4D quat, Static3D move, float scale, Metadata meta, InitAssets asset)
170
    {
171
    mNumLayers = meta.getNumLayers();
172
    mSize      = size;
173
    mMetadata  = meta;
174
    initialize(iconMode,quat,move,scale,asset,false);
175
    if( asset!=null ) asset.close();
176
    mError = false;
177
    mErrorString = null;
178
    }
179

    
180
///////////////////////////////////////////////////////////////////////////////////////////////////
181

    
182
  private void debugQuat(Static4D quat, int cubitIndex, float axisX, float axisY, float axisZ, float angle, int place)
183
    {
184
    float[] tracking = mCubits[cubitIndex].getTrackingPoint();
185

    
186
    if( tracking!=null )
187
      {
188
      String problem = (getShortName()+" "+cubitIndex+" "+quat.get0()+" "+quat.get1()+" "+quat.get2()+" "+quat.get3());
189
      problem += (" "+angle+" "+place+" "+tracking[0]+" "+tracking[1]+" "+tracking[2]);
190
      problem += (" "+axisX+" "+axisY+" "+axisZ);
191

    
192
      mInterface.reportProblem(problem, true);
193
      }
194
    }
195

    
196
///////////////////////////////////////////////////////////////////////////////////////////////////
197

    
198
  private void initialize(int iconMode, Static4D quat, Static3D move, float scale, InitAssets asset, boolean fromJSON)
199
    {
200
    mIconMode = iconMode;
201
    mQuat = quat;
202
    mAxis = getRotationAxis();
203
    mInitScreenRatio = getScreenRatio();
204
    mBasicAngles = getBasicAngles();
205
    mObjectQuats = getQuats();
206
    mNumQuats = mObjectQuats.length;
207
    mOrigPos = getCubitPositions(mNumLayers);
208
    mNumPuzzleFaces = getNumPuzzleFaces();
209
    mRowOffsets = new float[mNumPuzzleFaces][3];
210
    mTmp = new float[4];
211
    mNumAxis = mAxis.length;
212
    mCuts = getCuts(mNumLayers);
213
    mNumCuts = new int[mNumAxis];
214
    mMaxNumLayers = -1;
215
    for(int i=0; i<mNumAxis; i++)
216
      {
217
      if( mMaxNumLayers<mNumLayers[i] ) mMaxNumLayers = mNumLayers[i];
218
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
219
      }
220

    
221
    mOriginalColorTable = getColorTable();
222
    mNumFaceColors = mOriginalColorTable.length;
223
    mColorTable = new int[mNumFaceColors];
224
    recreateFaceColors();
225
    mTextureBorderMultiplier = 1.0f;
226
    mTextureCornerMultiplier = 1.0f;
227

    
228
    mMinimalCubiesInRow = getMinimalCubiesInRow();
229
    mNumCubits = mOrigPos.length;
230

    
231
    mBelongs = new boolean[mNumCubits];
232

    
233
    int scramblingType = getScrambleType();
234
    int[][] edges = getScrambleEdges();
235
    int[][] algorithms = getScrambleAlgorithms();
236

    
237
    OperatingSystemInterface os = asset==null ? null : asset.getOS();
238
    TablebasesAbstract tablebase = os!=null ? getTablebase(os) : null;
239
    mScrambler = new ObjectScrambler(scramblingType,mNumAxis,mNumLayers,algorithms,edges,tablebase);
240

    
241
    boolean bandaged=false;
242

    
243
    for( int c=0; c<mNumCubits; c++)
244
      {
245
      if( mOrigPos[c].length>3 )
246
        {
247
        bandaged=true;
248
        break;
249
        }
250
      }
251
    mIsBandaged = bandaged;
252
    mQuatDebug = new int[mNumCubits];
253

    
254
    mObjectScale = new Static3D(scale,scale,scale);
255
    setObjectRatioNow(scale,720);
256

    
257
    mEffects = new DistortedEffects();
258
    createQuaternionEffects();
259

    
260
    mRotation = new TwistyLayerRotations(this,mAxis,mNumLayers,getGhostAngle(),mEffects);
261

    
262
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
263
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
264
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
265

    
266
    InputStream meshStream = asset!=null ? asset.getMeshStream(): null;
267
    boolean fromDMESH = (meshStream!=null);
268
    getQuatsAndShapes(fromDMESH,fromJSON);
269
    createMeshAndCubits(meshStream,fromDMESH);
270
    setUpTextures(fromDMESH,fromJSON);
271

    
272
    int index = getSolvedFunctionIndex();
273
    mSolved = new TwistyObjectSolved(this,mOrigPos,index);
274
    mSolved.setupSolvedQuats(getSolvedQuats());
275
    mSolved.setPuzzleFaceColor(mColorTable);
276

    
277
    mEffects.apply(quatEffect);
278
    mEffects.apply(scaleEffect);
279
    mEffects.apply(moveEffect);
280

    
281
    mNode = new DistortedNode(mTexture,mEffects,mMesh);
282
    }
283

    
284
///////////////////////////////////////////////////////////////////////////////////////////////////
285

    
286
  public void recreateFaceColors()
287
    {
288
    for(int i=0; i<mNumFaceColors; i++) mColorTable[i] = mOriginalColorTable[i];
289
    }
290

    
291
///////////////////////////////////////////////////////////////////////////////////////////////////
292
// in degrees so that everything can be treated modulo 360
293

    
294
  public int getGhostAngle()
295
    {
296
    return 0;
297
    }
298

    
299
///////////////////////////////////////////////////////////////////////////////////////////////////
300

    
301
  private TablebasesAbstract getTablebase(OperatingSystemInterface os)
302
    {
303
    String shortName = getShortName();
304
    return ImplementedTablebasesList.createPacked(os,shortName);
305
    }
306

    
307
///////////////////////////////////////////////////////////////////////////////////////////////////
308

    
309
  private void createQuaternionEffects()
310
    {
311
    if( mNumQuats<=ObjectControl.MAX_QUATS )
312
      {
313
      mIsInMixupMode = false;
314

    
315
      for( int q=0; q<mNumQuats; q++)
316
        {
317
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mObjectQuats[q],CENTER);
318
        vq.setMeshAssociation(0,q);
319
        mEffects.apply(vq);
320
        }
321
      }
322
    else if( mNumCubits<=ObjectControl.MAX_QUATS )
323
      {
324
      mIsInMixupMode = true;
325
      mMixupModeQuats = new Static4D[mNumCubits];
326

    
327
      for( int q=0; q<mNumCubits; q++)
328
        {
329
        mMixupModeQuats[q] = new Static4D(mObjectQuats[0]);
330
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mMixupModeQuats[q],CENTER);
331
        vq.setMeshAssociation(0,q);
332
        mEffects.apply(vq);
333
        }
334
      }
335
    else
336
      {
337
      android.util.Log.e("D", "object has too many quaternions ("+mNumQuats+") or too many cubits ("+mNumCubits+")");
338
      }
339
    }
340

    
341
///////////////////////////////////////////////////////////////////////////////////////////////////
342

    
343
  private Static3D getPos(float[] origPos)
344
    {
345
    int len = origPos.length/3;
346
    float sumX = 0.0f;
347
    float sumY = 0.0f;
348
    float sumZ = 0.0f;
349

    
350
    for(int i=0; i<len; i++)
351
      {
352
      sumX += origPos[3*i  ];
353
      sumY += origPos[3*i+1];
354
      sumZ += origPos[3*i+2];
355
      }
356

    
357
    sumX /= len;
358
    sumY /= len;
359
    sumZ /= len;
360

    
361
    return new Static3D(sumX,sumY,sumZ);
362
    }
363

    
364
///////////////////////////////////////////////////////////////////////////////////////////////////
365

    
366
  private void createOuterFaces()
367
    {
368
    for(int v=0; v<mNumCubitVariants; v++)
369
      {
370
      int numFaces = mShapes[v].getNumFaces();
371
      mVariantFaceIsOuter[v] = new int[numFaces];
372
      }
373

    
374
    for( int cubit=0; cubit<mNumCubits; cubit++)
375
      {
376
      int variant = getCubitVariant(cubit,mNumLayers);
377
      int numFaces = mShapes[variant].getNumFaces();
378

    
379
      for(int face=0; face<numFaces; face++)
380
        if( getCubitFaceColor(cubit,face)>=0 )
381
          {
382
          mVariantFaceIsOuter[variant][face] = 1;
383
          }
384
      }
385
    }
386

    
387
///////////////////////////////////////////////////////////////////////////////////////////////////
388

    
389
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
390
    {
391
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
392

    
393
    if( !fromDMESH || !fromJSON )
394
      {
395
      FactoryCubit factory = FactoryCubit.getInstance();
396
      factory.clear();
397

    
398
      mShapes = new ObjectShape[mNumCubitVariants];
399
      for(int v=0; v<mNumCubitVariants; v++) mShapes[v] = getObjectShape(v);
400
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
401
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
402

    
403
      mOrigQuat = new Static4D[mNumCubits];
404
      for(int i=0; i<mNumCubits; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
405

    
406
      if( !fromJSON )
407
        {
408
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
409
        createOuterFaces();
410
        }
411

    
412
      if( fromDMESH )
413
        {
414
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
415
        }
416
      }
417
    }
418

    
419
///////////////////////////////////////////////////////////////////////////////////////////////////
420

    
421
  private void createMeshAndCubits(InputStream stream, boolean fromDMESH)
422
    {
423
    mCubits = new TwistyObjectCubit[mNumCubits];
424

    
425
    if( fromDMESH )
426
      {
427
      DataInputStream dos = new DataInputStream(stream);
428
      mMesh = new MeshFile(dos);
429

    
430
      try
431
        {
432
        stream.close();
433
        }
434
      catch(IOException e)
435
        {
436
        android.util.Log.e("meshFile", "Error closing InputStream: "+e);
437
        }
438
      }
439
    else
440
      {
441
      MeshBase[] cubitMesh = new MeshBase[mNumCubits];
442

    
443
      for(int i=0; i<mNumCubits; i++)
444
        {
445
        cubitMesh[i] = createCubitMesh(i,mNumLayers,mNumCubitFaces);
446
        Static3D pos = getPos(mOrigPos[i]);
447
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
448
        }
449

    
450
      mMesh = new MeshJoined(cubitMesh);
451

    
452
      float pillowCoeff = getPillowCoeff();
453

    
454
      if( pillowCoeff!=1.0f )
455
        {
456
        float radius = getCircumscribedRadius();
457
        Static1D coeff = new Static1D(pillowCoeff);
458
        Static4D region= new Static4D(0,0,0,radius);
459
        VertexEffectSink sink = new VertexEffectSink(coeff,CENTER,region);
460
        mMesh.apply(sink);
461
        }
462
      }
463

    
464
    for(int i=0; i<mNumCubits; i++)
465
      {
466
      mCubits[i] = new TwistyObjectCubit(this,mOrigPos[i],mNumAxis,mMaxNumLayers,i);
467
      setCubitQuat(i,0);
468

    
469
      if( !mThereAreDeciders && mCubits[i].getType()==TwistyObjectCubit.TYPE_DECIDER )
470
        {
471
        mThereAreDeciders = true;
472
        }
473
      }
474
    }
475

    
476
///////////////////////////////////////////////////////////////////////////////////////////////////
477

    
478
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int numComponents)
479
    {
480
    int variant = getCubitVariant(cubit,numLayers);
481

    
482
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
483

    
484
    if( mMeshes[variant]==null )
485
      {
486
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
487
      ObjectVertexEffects effects = getVertexEffects(variant);
488
      FactoryCubit factory = FactoryCubit.getInstance();
489
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
490
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,effects,numComponents);
491
      }
492

    
493
    MeshBase mesh = mMeshes[variant].copy(true);
494
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
495
    mesh.apply(quat,0xffffffff,0);
496

    
497
    return mesh;
498
    }
499

    
500
///////////////////////////////////////////////////////////////////////////////////////////////////
501

    
502
  private void figureOutBitmapDimensions(int numTextures)
503
    {
504
    int maxSize = DistortedLibrary.getMaxTextureSize();
505

    
506
    mTexHeight  = DEFAULT_TEXTURE_HEIGHT;
507

    
508
    while(true)
509
      {
510
      mNumTexCols = DEFAULT_TEXTURE_ROWS;
511
      mNumTexRows = numTextures/mNumTexCols + 1;
512

    
513
      if( mNumTexRows*mTexHeight <= maxSize &&
514
          mNumTexCols*mTexHeight <= maxSize  ) break;
515

    
516
      mTexHeight/=2;
517
      }
518
    }
519

    
520
///////////////////////////////////////////////////////////////////////////////////////////////////
521

    
522
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
523
    {
524
    mTexture = new DistortedTexture();
525

    
526
    if( fromJSON )
527
      {
528
      mNumStickerTypes = getNumStickerTypes();
529
      mNumCubitFaces = getNumCubitFaces();
530
      }
531
    else
532
      {
533
      FactoryCubit factory = FactoryCubit.getInstance();
534
      mStickerCoords   = factory.getStickerCoords();
535
      mStickerVariants = factory.getStickerVariants();
536
      mStickerScales   = factory.getStickerScales();
537
      adjustStickerCoords();
538
      mNumStickerTypes = (mStickerCoords==null ? 0 : mStickerCoords.length);
539
      }
540

    
541
    mStickerOverrides = getStickerOverrides();
542
    mNumOverrides = mStickerOverrides==null ? 0 : mStickerOverrides.length;
543

    
544
    mNumTextures= mNumFaceColors*mNumStickerTypes + mNumOverrides;
545
    figureOutBitmapDimensions(mNumTextures);
546
    if( mNumTexCols*mNumTexRows < mNumTextures+1 ) mNumTexRows++;
547

    
548
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
549
    else overrideCubitFaceColor();
550

    
551
    setTexture();
552
    }
553

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

    
556
  public Metadata getMetadata()
557
    {
558
    return mMetadata;
559
    }
560

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

    
563
  public boolean isInIconMode()
564
    {
565
    return mIconMode==MODE_ICON;
566
    }
567

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

    
570
  public int getVariantStickerShape(int variant, int face)
571
    {
572
    if( variant <mStickerVariants.length )
573
      {
574
      int[] var = mStickerVariants[variant];
575
      return face>=var.length ? -1 : var[face];
576
      }
577
    return -1;
578
    }
579

    
580
///////////////////////////////////////////////////////////////////////////////////////////////////
581

    
582
  public boolean shouldResetTextureMaps()
583
    {
584
    return false;
585
    }
586

    
587
///////////////////////////////////////////////////////////////////////////////////////////////////
588

    
589
  public int[][] getScrambleAlgorithms()
590
    {
591
    return ScrambleEdgeGenerator.getScramblingAlgorithms(mBasicAngles);
592
    }
593

    
594
///////////////////////////////////////////////////////////////////////////////////////////////////
595

    
596
  private boolean sticksOut(Static3D[] faceAxis, float[] dist, float x, float y, float z )
597
    {
598
    final float MAXERR = 0.05f;
599
    int numAxis = dist.length;
600

    
601
    for(int i=0; i<numAxis; i++)
602
      {
603
      Static3D ax = faceAxis[i];
604
      float len = ax.get0()*x + ax.get1()*y + ax.get2()*z;
605
      if( len>mSize*dist[i]+MAXERR ) return true;
606
      }
607

    
608
    return false;
609
    }
610

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

    
613
  private boolean doesNotStickOut(int variant, float px, float py, float pz, float[] tmp, Static4D quat)
614
    {
615
    float[][] vertices = mShapes[variant].getVertices();
616
    Static3D[] axis = getFaceAxis();
617
    float[] dist3D = getDist3D(mNumLayers);
618

    
619
    for( float[] vertex : vertices)
620
      {
621
      float x = vertex[0];
622
      float y = vertex[1];
623
      float z = vertex[2];
624

    
625
      QuatHelper.rotateVectorByQuat(tmp, x, y, z, 1, quat);
626

    
627
      float mx = tmp[0] + px;
628
      float my = tmp[1] + py;
629
      float mz = tmp[2] + pz;
630

    
631
      if( sticksOut(axis, dist3D, mx,my,mz) ) return false;
632
      }
633

    
634
    return true;
635
    }
636

    
637
///////////////////////////////////////////////////////////////////////////////////////////////////
638

    
639
  private float computeAvg(float[] pos, int offset)
640
    {
641
    int len = pos.length/3;
642
    float ret=0.0f;
643
    for(int i=0; i<len; i++) ret += pos[3*i+offset];
644
    ret /= len;
645

    
646
    return ret;
647
    }
648

    
649
///////////////////////////////////////////////////////////////////////////////////////////////////
650

    
651
  protected void displayCubitQuats()
652
    {
653
    StringBuilder builder = new StringBuilder();
654
    float[] tmp = new float[4];
655
    float ERR = 0.01f;
656

    
657
    for(int cubit=0; cubit<mNumCubits; cubit++)
658
      {
659
      builder.append(cubit);
660
      builder.append(" : ");
661

    
662
      int refCubit,variant = getCubitVariant(cubit,mNumLayers);
663

    
664
      for(refCubit=0; refCubit<mNumCubits; refCubit++)
665
        {
666
        if( getCubitVariant(refCubit,mNumLayers)==variant ) break;
667
        }
668

    
669
      float[] curpos = mOrigPos[cubit];
670
      float[] refpos = mOrigPos[refCubit];
671
      float refX = computeAvg(refpos,0);
672
      float refY = computeAvg(refpos,1);
673
      float refZ = computeAvg(refpos,2);
674
      float curX = computeAvg(curpos,0);
675
      float curY = computeAvg(curpos,1);
676
      float curZ = computeAvg(curpos,2);
677

    
678
      for(int quat=0; quat<mNumQuats; quat++)
679
        {
680
        QuatHelper.rotateVectorByQuat(tmp,refX,refY,refZ,0,mObjectQuats[quat]);
681

    
682
        float dx = tmp[0]-curX;
683
        float dy = tmp[1]-curY;
684
        float dz = tmp[2]-curZ;
685

    
686
        if( dx>-ERR && dx<ERR && dy>-ERR && dy<ERR && dz>-ERR && dz<ERR )
687
          {
688
          if( doesNotStickOut(variant,curX,curY,curZ,tmp,mObjectQuats[quat]) )
689
            {
690
            builder.append(quat);
691
            builder.append(',');
692
            }
693
          else
694
            {
695
            android.util.Log.e("D", "cubit: "+cubit+" quat: "+quat+" : center correct, but shape sticks out");
696
            }
697
          }
698
        }
699

    
700
      builder.append('\n');
701
      }
702

    
703
    android.util.Log.e("D", "cubitQuats: \n"+builder );
704
    }
705

    
706
///////////////////////////////////////////////////////////////////////////////////////////////////
707

    
708
  public int getCubitRotationType(int cubit)
709
    {
710
    return TwistyObjectCubit.TYPE_NORMAL;
711
    }
712

    
713
///////////////////////////////////////////////////////////////////////////////////////////////////
714

    
715
  float[] getTrackingPoint(int cubitIndex, int cubitType)
716
    {
717
    if( cubitType!=TwistyObjectCubit.TYPE_NORMAL )
718
      {
719
      int variant = getCubitVariant(cubitIndex,mNumLayers);
720

    
721
      // object must have been created from JSON
722
      if( mVariantFaceIsOuter==null || mVariantFaceIsOuter[variant]==null )
723
        {
724
        mVariantFaceIsOuter = getVariantFaceIsOuter();
725
        }
726
      if( mShapes==null )
727
        {
728
        mShapes = new ObjectShape[mNumCubitVariants];
729
        }
730
      if( mShapes[variant]==null )
731
        {
732
        mShapes[variant] = getObjectShape(variant);
733
        }
734
      if( mOrigQuat==null )
735
        {
736
        mOrigQuat = new Static4D[mNumCubits];
737
        }
738
      if( mOrigQuat[cubitIndex]==null )
739
        {
740
        mOrigQuat[cubitIndex] = getCubitQuats(cubitIndex,mNumLayers);
741
        }
742

    
743
      int outer=-1, faces = mShapes[variant].getNumFaces();
744

    
745
      for(int i=0; i<faces; i++)
746
        {
747
        if( mVariantFaceIsOuter[variant][i]==1 )
748
          {
749
          outer=i;
750
          break;
751
          }
752
        }
753

    
754
      if( outer>=0 )
755
        {
756
        float[] v = mShapes[variant].getFirstVertexInFace(outer);
757
        float[] ret = new float[3];
758
        float[] curpos = mOrigPos[cubitIndex];
759
        Static4D quat = mOrigQuat[cubitIndex];
760
        QuatHelper.rotateVectorByQuat(mTmp, v[0], v[1], v[2], 1, quat);
761

    
762
        ret[0] = mTmp[0]+computeAvg(curpos,0);
763
        ret[1] = mTmp[1]+computeAvg(curpos,1);
764
        ret[2] = mTmp[2]+computeAvg(curpos,2);
765

    
766
        return ret;
767
        }
768
      else
769
        {
770
        android.util.Log.e("D", "Error in getTrackingPoint: no outer face??");
771
        }
772
      }
773

    
774
    return null;
775
    }
776

    
777
///////////////////////////////////////////////////////////////////////////////////////////////////
778

    
779
  public int computeCurrentPuzzleFace(int type, float[] vertex)
780
    {
781
    if( type!=TwistyObjectCubit.TYPE_NORMAL )
782
      {
783
      Static3D[] axis = getFaceAxis();
784
      float[] dist3D = getDist3D(mNumLayers);
785
      final float MAXERR = 0.98f;
786
      int numAxis = axis.length;
787
      float x = vertex[0];
788
      float y = vertex[1];
789
      float z = vertex[2];
790

    
791
      for(int i=0; i<numAxis; i++)
792
        {
793
        Static3D ax = axis[i];
794
        float len = ax.get0()*x + ax.get1()*y + ax.get2()*z;
795
        if( len>mSize*dist3D[i]*MAXERR ) return i;
796
        }
797

    
798
      return -2;
799
      }
800

    
801
    return -1;
802
    }
803

    
804
///////////////////////////////////////////////////////////////////////////////////////////////////
805

    
806
  public float[] getCubitRowOffset(int cubitIndex)
807
    {
808
    return null;
809
    }
810

    
811
///////////////////////////////////////////////////////////////////////////////////////////////////
812

    
813
  void setRotationRowOffset(int puzzleFace, float[] offset)
814
    {
815
    mRowOffsets[puzzleFace][0] = offset[0];
816
    mRowOffsets[puzzleFace][1] = offset[1];
817
    mRowOffsets[puzzleFace][2] = offset[2];
818
    }
819

    
820
///////////////////////////////////////////////////////////////////////////////////////////////////
821

    
822
  int getNumAxis()
823
    {
824
    return mNumAxis;
825
    }
826

    
827
///////////////////////////////////////////////////////////////////////////////////////////////////
828

    
829
  public int[][] getSolvedQuats()
830
    {
831
    return null;
832
    }
833

    
834
///////////////////////////////////////////////////////////////////////////////////////////////////
835

    
836
  protected int[][] getOldSolvedQuats()
837
    {
838
    return mSolved.getSolvedQuats(mNumLayers,mNumCubitFaces,mCubitFaceColors);
839
    }
840

    
841
///////////////////////////////////////////////////////////////////////////////////////////////////
842
// 0: old, groups-of-quaternions based function.
843
// Still used by: Masterball, Mirror Sqewb, Mirror Jing, Mirror Pyraminx & the Penrose Cubes.
844
//
845
// 1: specific function only for the Dino4.
846
//
847
// 2: the new default; automatic way based on automatic detection of monochromatic puzzle surfaces.
848

    
849
  public int getSolvedFunctionIndex()
850
    {
851
    return 2;
852
    }
853

    
854
///////////////////////////////////////////////////////////////////////////////////////////////////
855

    
856
  int computeRow(float[] pos, int axisIndex, int cubitType, int puzzleFace)
857
    {
858
    int ret=0;
859
    int len = pos.length / 3;
860
    Static3D axis = mAxis[axisIndex];
861
    float axisX = axis.get0();
862
    float axisY = axis.get1();
863
    float axisZ = axis.get2();
864
    float casted, xoff=0, yoff=0, zoff=0;
865

    
866
    if( cubitType!=TwistyObjectCubit.TYPE_NORMAL )
867
      {
868
      xoff = mRowOffsets[puzzleFace][0];
869
      yoff = mRowOffsets[puzzleFace][1];
870
      zoff = mRowOffsets[puzzleFace][2];
871
      }
872

    
873
    for(int i=0; i<len; i++)
874
      {
875
      casted = (pos[3*i]+xoff)*axisX + (pos[3*i+1]+yoff)*axisY + (pos[3*i+2]+zoff)*axisZ;
876
      ret |= computeSingleRow(axisIndex,casted);
877
      }
878

    
879
    return ret;
880
    }
881

    
882
///////////////////////////////////////////////////////////////////////////////////////////////////
883

    
884
  private int computeSingleRow(int axisIndex,float casted)
885
    {
886
    int num = mNumCuts[axisIndex];
887
    float[] cuts = mCuts[axisIndex];
888

    
889
    for(int i=0; i<num; i++)
890
      {
891
      if( casted<cuts[i] ) return (1<<i);
892
      }
893

    
894
    return (1<<num);
895
    }
896

    
897
///////////////////////////////////////////////////////////////////////////////////////////////////
898

    
899
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
900
    {
901
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
902
    }
903

    
904
///////////////////////////////////////////////////////////////////////////////////////////////////
905
// note the minus in front of the sin() - we rotate counterclockwise
906
// when looking towards the direction where the axis increases in values.
907

    
908
  private Static4D makeQuaternion(float axisX, float axisY, float axisZ, int angleInDegrees)
909
    {
910
    while( angleInDegrees<0 ) angleInDegrees += 360;
911
    angleInDegrees %= 360;
912
    
913
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
914
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
915

    
916
    return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
917
    }
918

    
919
///////////////////////////////////////////////////////////////////////////////////////////////////
920

    
921
  void rotateAllCubits(int axisIndex, int rowBitmap, int angle)
922
    {
923
    Static3D axis = mAxis[axisIndex];
924
    float axisX = axis.get0();
925
    float axisY = axis.get1();
926
    float axisZ = axis.get2();
927
    Static4D quat = makeQuaternion(axisX,axisY,axisZ,angle);
928

    
929
    for(int i=0; i<mNumCubits; i++)
930
      {
931
      mBelongs[i] = belongsToRotation(i,axisIndex,rowBitmap);
932
      if( mBelongs[i] )
933
        {
934
        boolean result = mCubits[i].rotateCubit(quat,false);
935
        if( !result ) debugQuat(quat,i,axisX,axisY,axisZ,angle,1);
936
        }
937
      }
938

    
939
    recomputeFaceOffsets();
940

    
941
    for(int i=0; i<mNumCubits; i++)
942
      {
943
      if( mBelongs[i] )
944
        {
945
        int index = mCubits[i].postRotateCubit(quat);
946
        setCubitQuat(i,index);
947
        }
948
      else if( mCubits[i].getType()==TwistyObjectCubit.TYPE_FOLLOWER )
949
        {
950
        mCubits[i].computeRotationRow();
951
        setCubitQuat(i,mCubits[i].mQuatIndex);
952
        }
953
      }
954
    }
955

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

    
958
  private synchronized void setupPosition(int[][] moves)
959
    {
960
    if( moves!=null )
961
      {
962
      int axisIndex, row, rowBitmap, basic, angle;
963

    
964
      for(int[] move: moves)
965
        {
966
        axisIndex= move[0];
967
        rowBitmap= computeBandagedBitmap( move[1],axisIndex);
968
        row      = computeRowFromBitmap( move[1] );
969
        basic    = mBasicAngles[axisIndex][row];
970
        angle    = move[2]*(360/basic);   // this assumes that all layers from
971
                                          // the bitmap have the same BasicAngle.
972
                                          // at the moment this is always true as
973
                                          // there are no bandaged objects with
974
                                          // different per-layer BasicAngles.
975

    
976
        rotateAllCubits(axisIndex,rowBitmap,angle);
977
        }
978

    
979
      for(int i=0; i<mNumCubits; i++)
980
        {
981
        float[] pos = mCubits[i].getCurrentPos();
982
        int len = pos.length/3;
983
        for(int j=0; j<len; j++) clampPos(pos,3*j);
984
        }
985
      }
986
    }
987

    
988
///////////////////////////////////////////////////////////////////////////////////////////////////
989

    
990
  public int getScrambleType()
991
    {
992
    return ObjectScrambler.SCRAMBLING_ALGORITHMS;
993
    }
994

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

    
997
  public int[][] getMinimalCubiesInRow()
998
    {
999
    return null;
1000
    }
1001

    
1002
///////////////////////////////////////////////////////////////////////////////////////////////////
1003

    
1004
  int computeBandagedBitmap(int rowBitmap, int axisIndex)
1005
    {
1006
    if( mIsBandaged )
1007
      {
1008
      int bitmap, initBitmap=0;
1009

    
1010
      while( initBitmap!=rowBitmap )
1011
        {
1012
        initBitmap = rowBitmap;
1013

    
1014
        for(int cubit=0; cubit<mNumCubits; cubit++)
1015
          {
1016
          bitmap = mCubits[cubit].getRotRow(axisIndex);
1017
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
1018
          }
1019
        }
1020
      }
1021

    
1022
    if( mMinimalCubiesInRow!=null )
1023
      {
1024
      int[] minC = mMinimalCubiesInRow[axisIndex];
1025
      int numL = minC.length;
1026
      int[] numC = new int[numL];
1027

    
1028
      for(int cubit=0; cubit<mNumCubits; cubit++)
1029
        {
1030
        int bitmap = mCubits[cubit].getRotRow(axisIndex);
1031

    
1032
        for(int i=0; i<numL; i++)
1033
          {
1034
          if( (bitmap&0x1)!=0 ) numC[i]++;
1035
          bitmap>>=1;
1036
          }
1037
        }
1038

    
1039
      int bitmap,initBitmap = 0;
1040

    
1041
      while( initBitmap!=rowBitmap )
1042
        {
1043
        initBitmap = rowBitmap;
1044
        bitmap = rowBitmap;
1045
        int last = 0;
1046

    
1047
        for(int i=0; i<numL; i++)
1048
          {
1049
          if( numC[i]<minC[i] && numC[i]>0 )
1050
            {
1051
            if( (bitmap&0x1)!=0 )
1052
              {
1053
              if( i>0     ) rowBitmap |= (1<<(i-1));
1054
              if( i<numL-1) rowBitmap |= (1<<(i+1));
1055
              }
1056
            else if( (bitmap&0x2)!=0 || last>0 ) // we are not rotating this row, but
1057
                                                 // we are rotating the next or the prev
1058
              {
1059
              rowBitmap |= (1<<i);
1060
              }
1061
            }
1062

    
1063
          last = (bitmap&0x1);
1064
          bitmap>>=1;
1065
          }
1066
        }
1067
      }
1068

    
1069
    return rowBitmap;
1070
    }
1071

    
1072
///////////////////////////////////////////////////////////////////////////////////////////////////
1073

    
1074
  private int computeRowFromBitmap(int rowBitmap)
1075
    {
1076
    int index = 0;
1077

    
1078
    while(index<32)
1079
      {
1080
      if( (rowBitmap&0x1) != 0 ) return index;
1081
      rowBitmap>>=1;
1082
      index++;
1083
      }
1084
    return 0;
1085
    }
1086

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

    
1091
  void clampPos(float[] pos, int offset)
1092
    {
1093
    float currError, minError = Float.MAX_VALUE;
1094
    int minErrorIndex1 = -1;
1095
    int minErrorIndex2 = -1;
1096

    
1097
    float x = pos[offset  ];
1098
    float y = pos[offset+1];
1099
    float z = pos[offset+2];
1100

    
1101
    float xo,yo,zo;
1102

    
1103
    for(int i=0; i<mNumCubits; i++)
1104
      {
1105
      int len = mOrigPos[i].length / 3;
1106

    
1107
      for(int j=0; j<len; j++)
1108
        {
1109
        xo = mOrigPos[i][3*j  ];
1110
        yo = mOrigPos[i][3*j+1];
1111
        zo = mOrigPos[i][3*j+2];
1112

    
1113
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
1114

    
1115
        if( currError<minError )
1116
          {
1117
          minError = currError;
1118
          minErrorIndex1 = i;
1119
          minErrorIndex2 = j;
1120
          }
1121
        }
1122
      }
1123

    
1124
    if( minError< 0.05f ) // TODO: 0.05 ?
1125
      {
1126
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
1127
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
1128
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
1129
      }
1130
    }
1131

    
1132
///////////////////////////////////////////////////////////////////////////////////////////////////
1133

    
1134
  void setLibInterface(ObjectLibInterface inter)
1135
    {
1136
    mInterface = inter;
1137
    }
1138

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

    
1141
  void applyScrambles(int[][] moves)
1142
    {
1143
    setupPosition(moves);
1144
    }
1145

    
1146
///////////////////////////////////////////////////////////////////////////////////////////////////
1147

    
1148
  void initializeObject(int[][] moves)
1149
    {
1150
    solve();
1151
    setupPosition(moves);
1152
    }
1153

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

    
1156
  private void recomputeFaceOffsets()
1157
    {
1158
    if( mThereAreDeciders )
1159
      {
1160
      for(int i=0; i<mNumPuzzleFaces; i++)
1161
        {
1162
        mRowOffsets[i][0] =0;
1163
        mRowOffsets[i][1] =0;
1164
        mRowOffsets[i][2] =0;
1165
        }
1166

    
1167
      for(int i=0; i<mNumCubits; i++)
1168
        if( mCubits[i].getType()==TwistyObjectCubit.TYPE_DECIDER )
1169
          {
1170
          float[] offset = mCubits[i].getOffset();
1171
          int face = mCubits[i].getPuzzleFace();
1172
          mRowOffsets[face][0] = offset[0];
1173
          mRowOffsets[face][1] = offset[1];
1174
          mRowOffsets[face][2] = offset[2];
1175
          }
1176
      }
1177
    }
1178

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

    
1181
  synchronized float removeRotation()
1182
    {
1183
    return mRotation.removeRotation();
1184
    }
1185

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

    
1188
  long finishRotation(ObjectPreRender pre, int finishAx, int finishRow, float finishAngle, float avgSpeed)
1189
    {
1190
    int basicAngle = mBasicAngles[finishAx][finishRow];
1191
    return mRotation.finishRotation(pre,finishAx,finishRow,basicAngle,finishAngle,avgSpeed);
1192
    }
1193

    
1194
///////////////////////////////////////////////////////////////////////////////////////////////////
1195

    
1196
  void continueRotation(float angleInDegrees)
1197
    {
1198
    mRotation.continueRotation(angleInDegrees);
1199
    }
1200

    
1201
///////////////////////////////////////////////////////////////////////////////////////////////////
1202

    
1203
  synchronized long addRotation(EffectListener listener, int axis, int rowBitmap, int angle, long durationMillis )
1204
    {
1205
    return mRotation.addRotation(listener,axis,rowBitmap,angle,durationMillis);
1206
    }
1207

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

    
1210
  void enableGhostAxis(int axNum, boolean enable)
1211
    {
1212
    mTouchControl.enableGhostAxis(axNum,enable);
1213
    }
1214

    
1215
///////////////////////////////////////////////////////////////////////////////////////////////////
1216

    
1217
  synchronized boolean beginRotation(int axis, int row )
1218
    {
1219
    if( axis<0 || axis>=mNumAxis )
1220
      {
1221
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1222
      return false;
1223
      }
1224

    
1225
    return mRotation.beginRotation(axis,row);
1226
    }
1227

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

    
1230
  void setTextureMap(int cubit, int face, int color)
1231
    {
1232
    int variant  = getCubitVariant(cubit,mNumLayers);
1233
    int shape    = getVariantStickerShape(variant,face);
1234
    int texIndex = color<0 || shape<0 ? mNumTextures-mNumOverrides : shape*mNumFaceColors + color;
1235
    int row      = (mNumTexRows-1) - texIndex/mNumTexCols;
1236
    int col      = texIndex%mNumTexCols;
1237

    
1238
    final float ratioW = 1.0f/mNumTexCols;
1239
    final float ratioH = 1.0f/mNumTexRows;
1240
    final Static4D[] maps = new Static4D[1];
1241
    maps[0] = new Static4D(col*ratioW, row*ratioH, ratioW, ratioH);
1242
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit+face);
1243
    }
1244

    
1245
///////////////////////////////////////////////////////////////////////////////////////////////////
1246
// figure out the whole face to which (cubit,face) belongs, repaint all (cubit,face) pairs to
1247
// the new color.
1248

    
1249
  void repaintPuzzleFace(int cubit, int face, int newColor)
1250
    {
1251
    int oldColorIndex = getCubitFaceColor(cubit,face);
1252

    
1253
    if( oldColorIndex<0 || oldColorIndex>=mNumFaceColors )
1254
      {
1255
      android.util.Log.e("D", "error in TwistyObject.repaintPuzzleFace, index="+oldColorIndex);
1256
      return;
1257
      }
1258

    
1259
    int oldColor = mColorTable[oldColorIndex];
1260

    
1261
    if( oldColor!=newColor )
1262
      {
1263
      oldColor = mOriginalColorTable[oldColorIndex];
1264
      changeColorInTexture(oldColor,newColor);
1265
      mColorTable[oldColorIndex] = newColor;
1266
      setTexture();
1267
      }
1268
    }
1269

    
1270
///////////////////////////////////////////////////////////////////////////////////////////////////
1271
// this doesn't have to return the real, displayed color - but the default one (from Shape classes).
1272
// The real displayed color can be different because of the sticker color overrides in 'Config'.
1273

    
1274
  int getCubitFaceColor(int cubit, int face)
1275
    {
1276
    int puzzleFace = getCubitFaceMap(cubit,face);
1277
    if( puzzleFace>=0 ) puzzleFace %= mNumFaceColors;
1278
    return puzzleFace;
1279
    }
1280

    
1281
///////////////////////////////////////////////////////////////////////////////////////////////////
1282

    
1283
  public int getCubitFaceMap(int cubit, int face)
1284
    {
1285
    int numFaces = mCubitFaceColors[cubit].length;
1286
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1287
    return puzzleFace<0 ? -1 : puzzleFace;
1288
    }
1289

    
1290
///////////////////////////////////////////////////////////////////////////////////////////////////
1291
// this would return the REAL value of outer; the 'getCubitFaceColor()>=0' returns if the face is
1292
// colored, which for example in case of Container (which has colored internal faces) is not the
1293
// same thing
1294

    
1295
  boolean faceIsOuter(int cubit, int face)
1296
    {
1297
    if( mCubitFaceColors==null )
1298
      {
1299
      if( mShapes==null )
1300
        {
1301
        mShapes = new ObjectShape[mNumCubitVariants];
1302
        }
1303

    
1304
      if( mShapes[0]==null )
1305
        {
1306
        for(int v=0; v<mNumCubitVariants; v++) mShapes[v] = getObjectShape(v);
1307
        }
1308

    
1309
      if( mOrigQuat==null )
1310
        {
1311
        mOrigQuat = new Static4D[mNumCubits];
1312
        }
1313

    
1314
      if( mOrigQuat[0]==null )
1315
        {
1316
        for(int c=0; c<mNumCubits; c++) mOrigQuat[c] = getCubitQuats(c,mNumLayers);
1317
        }
1318

    
1319
      mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
1320
      }
1321

    
1322
    return mCubitFaceColors[cubit][face]>=0;
1323
    }
1324

    
1325
///////////////////////////////////////////////////////////////////////////////////////////////////
1326

    
1327
  void resetAllTextureMaps()
1328
    {
1329
    final float ratioW = 1.0f/mNumTexCols;
1330
    final float ratioH = 1.0f/mNumTexRows;
1331
    int cubColor, stiShape, texIndex, variant, row, col;
1332

    
1333
    for(int cubit=0; cubit<mNumCubits; cubit++)
1334
      {
1335
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1336
      variant = getCubitVariant(cubit,mNumLayers);
1337

    
1338
      for(int face=0; face<mNumCubitFaces; face++)
1339
        {
1340
        cubColor = getCubitFaceColor(cubit,face);
1341
        stiShape = getVariantStickerShape(variant,face);
1342
        texIndex = cubColor<0 || stiShape<0 ? mNumTextures-mNumOverrides : stiShape*mNumFaceColors + cubColor;
1343
        row      = (mNumTexRows-1) - texIndex/mNumTexCols;
1344
        col      = texIndex%mNumTexCols;
1345

    
1346
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1347
        }
1348

    
1349
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1350
      }
1351

    
1352
    overrideCubitFaceColor();
1353
    }
1354

    
1355
///////////////////////////////////////////////////////////////////////////////////////////////////
1356

    
1357
  private void overrideCubitFaceColor()
1358
    {
1359
    final float ratioW = 1.0f/mNumTexCols;
1360
    final float ratioH = 1.0f/mNumTexRows;
1361

    
1362
    for(int i=0; i<mNumOverrides; i++)
1363
      {
1364
      int[] cubitFaces = mStickerOverrides[i].getCubitFaces();
1365
      int length = cubitFaces.length/2;
1366

    
1367
      for(int j=0; j<length; j++)
1368
        {
1369
        final Static4D[] maps = new Static4D[1];
1370
        int color = mNumTextures-mNumOverrides+1+i;
1371
        int row   = (mNumTexRows-1) - color/mNumTexCols;
1372
        int col   = color%mNumTexCols;
1373
        int cubit = cubitFaces[2*j];
1374
        int face  = cubitFaces[2*j+1];
1375
        maps[0] = new Static4D(col*ratioW, row*ratioH, ratioW, ratioH);
1376
        mMesh.setTextureMap(maps,mNumCubitFaces*cubit+face);
1377
        }
1378
      }
1379
    }
1380

    
1381
///////////////////////////////////////////////////////////////////////////////////////////////////
1382

    
1383
  void releaseResources()
1384
    {
1385
    mTexture.markForDeletion();
1386
    mMesh.markForDeletion();
1387
    mEffects.markForDeletion();
1388

    
1389
    if( mBitmap!=null )
1390
      {
1391
      mBitmap.recycle();
1392
      mBitmap = null;
1393
      }
1394

    
1395
    for(int j=0; j<mNumCubits; j++)
1396
      {
1397
      mCubits[j].releaseResources();
1398
      }
1399
    }
1400

    
1401
///////////////////////////////////////////////////////////////////////////////////////////////////
1402

    
1403
  private void setCubitQuat(int cubit, int equAssociation)
1404
    {
1405
    int andAssociation = mCubits[cubit].computeAssociation();
1406

    
1407
    if( !mIsInMixupMode )
1408
      {
1409
      mMesh.setEffectAssociation(cubit,andAssociation,equAssociation);
1410
      }
1411
    else
1412
      {
1413
      mMesh.setEffectAssociation(cubit,andAssociation,cubit);
1414
      Static4D tmp = mObjectQuats[equAssociation];
1415
      mMixupModeQuats[cubit].set(tmp);
1416
      }
1417
    }
1418

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

    
1421

    
1422
///////////////////////////////////////////////////////////////////////////////////////////////////
1423

    
1424
  synchronized void restorePreferences(OperatingSystemInterface os)
1425
    {
1426
    boolean error = false;
1427
    String key = getShortName();
1428

    
1429
    for(int i=0; i<mNumCubits; i++)
1430
      {
1431
      mQuatDebug[i] = mCubits[i].restorePreferences(key,os);
1432

    
1433
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1434
        {
1435
        boolean result = mCubits[i].rotateCubit(mObjectQuats[mQuatDebug[i]],true);
1436
        if( !result ) debugQuat(mObjectQuats[mQuatDebug[i]],i,0,0,0,mQuatDebug[i],3);
1437
        }
1438
      else { error = true; break; }
1439
      }
1440

    
1441
    if( !error )
1442
      {
1443
      recomputeFaceOffsets();
1444

    
1445
      for(int i=0; i<mNumCubits; i++)
1446
        {
1447
        if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1448
          {
1449
          mCubits[i].computeRotationRow();
1450
          setCubitQuat(i,mQuatDebug[i]);
1451
          }
1452
        else { error = true; break; }
1453
        }
1454
      }
1455

    
1456
    if( error )
1457
      {
1458
      for(int i=0; i<mNumCubits; i++)
1459
        {
1460
        mCubits[i].solve();
1461
        setCubitQuat(i,0);
1462
        }
1463
      }
1464

    
1465
    mTextureBorderMultiplier = os.getFloat(key+"_border", 1.0f);
1466
    mTextureCornerMultiplier = os.getFloat(key+"_corner", 1.0f);
1467
    String colors = os.getString(key+"_colors", null);
1468
    boolean different = false;
1469

    
1470
    if( colors!=null ) different = restoreColors(colors,mColorTable);
1471

    
1472
    if( different || mTextureBorderMultiplier!=1.0f || mTextureCornerMultiplier!=1.0f )
1473
      {
1474
      createTexture(mTextureBorderMultiplier,mTextureCornerMultiplier);
1475
      setTexture();
1476
      mSolved.setPuzzleFaceColor(mColorTable);
1477
      }
1478
    }
1479

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

    
1482
  synchronized void restoreStickers(OperatingSystemInterface os)
1483
    {
1484
    String key = getShortName();
1485
    mTextureBorderMultiplier = os.getFloat(key+"_border", 1.0f);
1486
    mTextureCornerMultiplier = os.getFloat(key+"_corner", 1.0f);
1487
    String colors = os.getString(key+"_colors", null);
1488
    boolean different = false;
1489

    
1490
    if( colors!=null ) different = restoreColors(colors,mColorTable);
1491

    
1492
    if( different || mTextureBorderMultiplier!=1.0f || mTextureCornerMultiplier!=1.0f )
1493
      {
1494
      createTexture(mTextureBorderMultiplier,mTextureCornerMultiplier);
1495
      setTexture();
1496
      mSolved.setPuzzleFaceColor(mColorTable);
1497
      }
1498
    }
1499

    
1500

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

    
1503
  void savePreferences(OperatingSystemInterface os)
1504
    {
1505
    String key = getShortName();
1506
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(key,os);
1507

    
1508
    os.putFloat(key+"_border", mTextureBorderMultiplier);
1509
    os.putFloat(key+"_corner", mTextureCornerMultiplier);
1510
    os.putString(key+"_colors", createColors(mColorTable) );
1511
    }
1512

    
1513
///////////////////////////////////////////////////////////////////////////////////////////////////
1514

    
1515
  public void removePreferences(OperatingSystemInterface os)
1516
    {
1517
    String key = getShortName();
1518
    for(int i=0; i<mNumCubits; i++) mCubits[i].removePreferences(key,os);
1519

    
1520
    os.remove(key+"_border");
1521
    os.remove(key+"_corner");
1522
    os.remove(key+"_colors");
1523
    }
1524

    
1525
///////////////////////////////////////////////////////////////////////////////////////////////////
1526

    
1527
  private String createColors(int[] table)
1528
    {
1529
    StringBuilder sb = new StringBuilder();
1530
    int len = table!=null ? table.length : 0;
1531

    
1532
    for(int i=0; i<len; i++)
1533
      {
1534
      sb.append(table[i]);
1535
      sb.append(',');
1536
      }
1537

    
1538
    return sb.toString();
1539
    }
1540

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

    
1543
  private boolean restoreColors(String colors, int[] table)
1544
    {
1545
    String[] parts = colors.split(",");
1546
    int len = parts.length;
1547
    boolean ret = false;
1548

    
1549
    try
1550
      {
1551
      for(int s=0; s<len; s++)
1552
        {
1553
        table[s] = Integer.parseInt(parts[s]);
1554
        if( table[s]!=mOriginalColorTable[s] ) ret = true;
1555
        }
1556
      }
1557
    catch(NumberFormatException nfe)
1558
      {
1559
      for(int s=0; s<len; s++) table[s] = mOriginalColorTable[s];
1560
      return false;
1561
      }
1562

    
1563
    return ret;
1564
    }
1565

    
1566
///////////////////////////////////////////////////////////////////////////////////////////////////
1567

    
1568
  private float computeRadiusCorrection(float[][] sticker, int curr, int len)
1569
    {
1570
    final float A = 0.8f;  // 0<A<1
1571

    
1572
    int prev = curr>0 ? curr-1 : len-1;
1573
    int next = curr<len-1 ? curr+1 : 0;
1574

    
1575
    float v1x = sticker[prev][0]-sticker[curr][0];
1576
    float v1y = sticker[prev][1]-sticker[curr][1];
1577
    float v2x = sticker[next][0]-sticker[curr][0];
1578
    float v2y = sticker[next][1]-sticker[curr][1];
1579

    
1580
    float len1= v1x*v1x+v1y*v1y;
1581
    float len2= v2x*v2x+v2y*v2y;
1582

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

    
1585
    return 1-A*cos;
1586
    }
1587

    
1588
///////////////////////////////////////////////////////////////////////////////////////////////////
1589
// Radius of the sphere circumscribed on the puzzle. Needed for pillowing.
1590
//
1591
// This won't work correctly for pillowing off-center puzzles (e.g. mirrors) - for those we'd need
1592
// to introduce the concept of a 'sink center' as well.
1593
//
1594
// public because needed in TouchControlShapemod
1595

    
1596
  public float getCircumscribedRadius()
1597
    {
1598
    switch(mNumPuzzleFaces)
1599
      {
1600
      case  4: return (SQ6/4)*mSize;
1601
      case  6: return (SQ3/2)*mSize;
1602
      case  8: return (SQ2/2)*mSize;
1603
      case 12: return (SQ3/2)*((SQ5+1)/2)*mSize;
1604
      case 16: return 0.50f*mSize;
1605
      }
1606

    
1607
    return 0.0f;
1608
    }
1609

    
1610
///////////////////////////////////////////////////////////////////////////////////////////////////
1611
// might be overridden in subclasses which want per-edge radii
1612

    
1613
  protected float[][][] getStickerRadii()
1614
    {
1615
    float radius = getStickerRadius();
1616
    int numStickers = mStickerCoords.length;
1617
    float[][][] ret = new float[numStickers][][];
1618

    
1619
    for(int s=0; s<numStickers; s++)
1620
      {
1621
      int numLoops = mStickerCoords[s].length;
1622
      ret[s] = new float[numLoops][];
1623

    
1624
      for(int l=0; l<numLoops; l++)
1625
        {
1626
        int numVertices = mStickerCoords[s][l].length;
1627
        ret[s][l] = new float[numVertices];
1628
        for(int v=0; v<numVertices; v++) ret[s][l][v] = radius;
1629
        }
1630
      }
1631

    
1632
    return ret;
1633
    }
1634

    
1635
///////////////////////////////////////////////////////////////////////////////////////////////////
1636
// might be overridden in subclasses which want per-edge strokes
1637

    
1638
  protected float[][][] getStickerStrokes()
1639
    {
1640
    float stroke = getStickerStroke();
1641
    int numStickers = mStickerCoords.length;
1642
    float[][][] ret = new float[numStickers][][];
1643

    
1644
    for(int s=0; s<numStickers; s++)
1645
      {
1646
      int numLoops = mStickerCoords[s].length;
1647
      ret[s] = new float[numLoops][];
1648

    
1649
      for(int l=0; l<numLoops; l++)
1650
        {
1651
        int numVertices = mStickerCoords[s][l].length;
1652
        ret[s][l] = new float[numVertices];
1653
        for(int v=0; v<numVertices; v++) ret[s][l][v] = stroke;
1654
        }
1655
      }
1656

    
1657
    return ret;
1658
    }
1659

    
1660
///////////////////////////////////////////////////////////////////////////////////////////////////
1661

    
1662
  public ObjectSticker retSticker(int sticker)
1663
    {
1664
    if( mStickers==null )
1665
      {
1666
      float[][][] radii   = getStickerRadii();
1667
      float[][][] strokes = getStickerStrokes();
1668
      float[][][] angles  = getStickerAngles();
1669
      int numStickers = mStickerCoords.length;
1670
      mStickers = new ObjectSticker[numStickers];
1671

    
1672
      for(int s=0; s<numStickers; s++)
1673
        {
1674
        float scale = mStickerScales.length>s ? mStickerScales[s] : 1.0f;
1675
        int numLoops = mStickerCoords[s].length;
1676
        float[][] rad = new float[numLoops][];
1677
        float[][] str = new float[numLoops][];
1678

    
1679
        for(int l=0; l<numLoops; l++)
1680
          {
1681
          int numVerts = mStickerCoords[s][l].length;
1682
          rad[l] = new float[numVerts];
1683
          str[l] = new float[numVerts];
1684
          float[] st = strokes[s][l];
1685
          float[] ra = radii[s][l];
1686

    
1687
          for(int v=0; v<numVerts; v++)
1688
            {
1689
            rad[l][v] = ra[v] * computeRadiusCorrection(mStickerCoords[s][l],v,numVerts) / scale;
1690
            str[l][v] = st[v] / scale;
1691
            }
1692
          }
1693

    
1694
        mStickers[s] = new ObjectSticker(mStickerCoords[s], (angles==null ? null : angles[s]) ,rad, str);
1695
        }
1696
      }
1697

    
1698
    return mStickers[sticker];
1699
    }
1700

    
1701
///////////////////////////////////////////////////////////////////////////////////////////////////
1702
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1703

    
1704
  public void adjustStickerCoords()
1705
    {
1706

    
1707
    }
1708

    
1709
///////////////////////////////////////////////////////////////////////////////////////////////////
1710

    
1711
  public Static4D[] getQuats()
1712
    {
1713
    if( mObjectQuats==null )
1714
      {
1715
      mObjectQuats = QuatGroupGenerator.computeGroup(mAxis,mBasicAngles);
1716
      }
1717

    
1718
    return mObjectQuats;
1719
    }
1720

    
1721
///////////////////////////////////////////////////////////////////////////////////////////////////
1722

    
1723
  public int[][] getVariantFaceIsOuter()
1724
    {
1725
    return mVariantFaceIsOuter;
1726
    }
1727

    
1728
///////////////////////////////////////////////////////////////////////////////////////////////////
1729

    
1730
  public int getInternalColor()
1731
    {
1732
    return COLOR_INTERNAL;
1733
    }
1734

    
1735
///////////////////////////////////////////////////////////////////////////////////////////////////
1736

    
1737
  public float getTextureBorders()
1738
    {
1739
    return mTextureBorderMultiplier;
1740
    }
1741

    
1742
///////////////////////////////////////////////////////////////////////////////////////////////////
1743

    
1744
  public float getTextureCorners()
1745
    {
1746
    return mTextureCornerMultiplier;
1747
    }
1748

    
1749
///////////////////////////////////////////////////////////////////////////////////////////////////
1750
// the getFaceColors + final INTERNAL_COLOR in a grid (so that we do not exceed the maximum texture size)
1751

    
1752
  void createTexture(float border, float corner)
1753
    {
1754
    Paint paint = new Paint();
1755
    Canvas canvas = new Canvas(mBitmap);
1756

    
1757
    paint.setAntiAlias(true);
1758
    paint.setTextAlign(Paint.Align.CENTER);
1759
    paint.setStyle(Paint.Style.FILL);
1760
    paint.setColor(getInternalColor());
1761
    canvas.drawRect(0, 0, mNumTexCols*mTexHeight, mNumTexRows*mTexHeight, paint);
1762

    
1763
    mTextureBorderMultiplier = border;
1764
    mTextureCornerMultiplier = corner;
1765

    
1766
    int texture = 0;
1767
    FactorySticker factory = FactorySticker.getInstance();
1768

    
1769
    for(int row=0; row<mNumTexRows; row++)
1770
      for(int col=0; col<mNumTexCols; col++)
1771
        {
1772
        if( texture<mNumTextures-mNumOverrides )
1773
          {
1774
          ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1775
          int color = mColorTable[texture%mNumFaceColors];
1776
          factory.drawRoundedPolygons( canvas, paint, col*mTexHeight, (mNumTexRows-row)*mTexHeight, color,
1777
                                       mTexHeight, sticker,mTextureBorderMultiplier,mTextureCornerMultiplier);
1778
          }
1779
        else if( texture>mNumTextures-mNumOverrides && texture<=mNumTextures )
1780
          {
1781
          int color = mStickerOverrides[mNumTextures-texture].getColor();
1782
          factory.drawSolidColor(canvas, paint, col*mTexHeight, (mNumTexRows-row)*mTexHeight, color, mTexHeight);
1783
          }
1784

    
1785
        texture++;
1786
        }
1787
    }
1788

    
1789
///////////////////////////////////////////////////////////////////////////////////////////////////
1790

    
1791
  private void changeColorInTexture(int oldColor, int newColor)
1792
    {
1793
    Paint paint = new Paint();
1794
    Canvas canvas = new Canvas(mBitmap);
1795
    paint.setAntiAlias(true);
1796
    int texture = 0;
1797
    FactorySticker factory = FactorySticker.getInstance();
1798

    
1799
    for(int row=0; row<mNumTexRows; row++)
1800
      for(int col=0; col<mNumTexCols; col++)
1801
        {
1802
        if( texture<mNumTextures-mNumOverrides )
1803
          {
1804
          int color = mOriginalColorTable[texture%mNumFaceColors];
1805

    
1806
          if( color==oldColor )
1807
            {
1808
            ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1809
            factory.drawRoundedPolygons( canvas, paint, col*mTexHeight, (mNumTexRows-row)*mTexHeight,
1810
                                         newColor, mTexHeight, sticker,mTextureBorderMultiplier,mTextureCornerMultiplier);
1811
            }
1812
          }
1813

    
1814
        texture++;
1815
        }
1816
    }
1817

    
1818
///////////////////////////////////////////////////////////////////////////////////////////////////
1819

    
1820
  void setTexture()
1821
    {
1822
    if( mBitmap==null )
1823
      {
1824
      mBitmap = Bitmap.createBitmap( mNumTexCols*mTexHeight, mNumTexRows*mTexHeight, Bitmap.Config.ARGB_4444);
1825
      createTexture(mTextureBorderMultiplier,mTextureCornerMultiplier);
1826
      }
1827

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

    
1835
///////////////////////////////////////////////////////////////////////////////////////////////////
1836

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

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

    
1847
///////////////////////////////////////////////////////////////////////////////////////////////////
1848

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

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

    
1856
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1857
    }
1858

    
1859
///////////////////////////////////////////////////////////////////////////////////////////////////
1860

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

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

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

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

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

    
1880
///////////////////////////////////////////////////////////////////////////////////////////////////
1881

    
1882
  boolean isSolved()
1883
    {
1884
    boolean solved = mSolved.isSolved(mCubits);
1885
    return mRotation.isSolved(solved);
1886
    }
1887

    
1888
///////////////////////////////////////////////////////////////////////////////////////////////////
1889
// INTERNAL API - those are called from 'effects' package
1890
///////////////////////////////////////////////////////////////////////////////////////////////////
1891

    
1892
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1893
    {
1894
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total, getSignature() );
1895
    }
1896

    
1897
///////////////////////////////////////////////////////////////////////////////////////////////////
1898

    
1899
  public Static4D getRotationQuat()
1900
    {
1901
    return mQuat;
1902
    }
1903

    
1904
///////////////////////////////////////////////////////////////////////////////////////////////////
1905

    
1906
  public float getSize()
1907
    {
1908
    return mSize;
1909
    }
1910

    
1911
///////////////////////////////////////////////////////////////////////////////////////////////////
1912

    
1913
  public void applyEffect(Effect effect, int position)
1914
    {
1915
    mEffects.apply(effect, position);
1916
    }
1917

    
1918
///////////////////////////////////////////////////////////////////////////////////////////////////
1919

    
1920
  public void removeEffect(long effectID)
1921
    {
1922
    mEffects.abortById(effectID);
1923
    }
1924

    
1925
///////////////////////////////////////////////////////////////////////////////////////////////////
1926

    
1927
  public MeshBase getObjectMesh()
1928
    {
1929
    return mMesh;
1930
    }
1931

    
1932
///////////////////////////////////////////////////////////////////////////////////////////////////
1933

    
1934
  public DistortedEffects getObjectEffects()
1935
    {
1936
    return mEffects;
1937
    }
1938

    
1939
///////////////////////////////////////////////////////////////////////////////////////////////////
1940

    
1941
  public int getCubitType(int cubit)
1942
    {
1943
    return mCubits[cubit].getType();
1944
    }
1945

    
1946
///////////////////////////////////////////////////////////////////////////////////////////////////
1947

    
1948
  public float[] getCubitOffset(int cubit)
1949
    {
1950
    return mCubits[cubit].getOffset();
1951
    }
1952

    
1953
///////////////////////////////////////////////////////////////////////////////////////////////////
1954

    
1955
  public ObjectStickerOverride[] getStickerOverrides()
1956
    {
1957
    return null;
1958
    }
1959

    
1960
///////////////////////////////////////////////////////////////////////////////////////////////////
1961

    
1962
  public boolean getError()
1963
    {
1964
    return mError;
1965
    }
1966

    
1967
///////////////////////////////////////////////////////////////////////////////////////////////////
1968

    
1969
  public String getErrorString()
1970
    {
1971
    return mErrorString;
1972
    }
1973

    
1974
///////////////////////////////////////////////////////////////////////////////////////////////////
1975
// PUBLIC API
1976
///////////////////////////////////////////////////////////////////////////////////////////////////
1977

    
1978
  public int getCubitFaceStickerIndex(int cubit, int face)
1979
    {
1980
    Static4D texMap = mMesh.getTextureMap(mNumCubitFaces*cubit + face);
1981

    
1982
    int x = (int)(texMap.get0()/texMap.get2());
1983
    int y = (int)(texMap.get1()/texMap.get3());
1984

    
1985
    return (mNumTexRows-1-y)*mNumTexCols + x;
1986
    }
1987

    
1988
///////////////////////////////////////////////////////////////////////////////////////////////////
1989

    
1990
  public int[] getNumLayers()
1991
    {
1992
    return mNumLayers;
1993
    }
1994

    
1995
///////////////////////////////////////////////////////////////////////////////////////////////////
1996

    
1997
  public synchronized void solve()
1998
    {
1999
    for(int i=0; i<mNumCubits; i++) mCubits[i].solve();
2000

    
2001
    recomputeFaceOffsets();
2002

    
2003
    for(int i=0; i<mNumCubits; i++)
2004
      {
2005
      mCubits[i].computeRotationRow();
2006
      setCubitQuat(i,0);
2007
      }
2008
    }
2009

    
2010
///////////////////////////////////////////////////////////////////////////////////////////////////
2011

    
2012
  public int getCubitQuatIndex(int cubit)
2013
    {
2014
    return (cubit>=0 && cubit<mNumCubits) ? mCubits[cubit].mQuatIndex : 0;
2015
    }
2016

    
2017
///////////////////////////////////////////////////////////////////////////////////////////////////
2018

    
2019
  public int getCubitRotRow(int cubit, int axis)
2020
    {
2021
    return mCubits[cubit].getRotRow(axis);
2022
    }
2023

    
2024
///////////////////////////////////////////////////////////////////////////////////////////////////
2025

    
2026
  public Bitmap getStickerBitmap()
2027
    {
2028
    return mBitmap;
2029
    }
2030

    
2031
///////////////////////////////////////////////////////////////////////////////////////////////////
2032

    
2033
  public DistortedNode getNode()
2034
    {
2035
    return mNode;
2036
    }
2037

    
2038
///////////////////////////////////////////////////////////////////////////////////////////////////
2039

    
2040
  public int getNumStickerTypes()
2041
    {
2042
    return mNumStickerTypes;
2043
    }
2044

    
2045
///////////////////////////////////////////////////////////////////////////////////////////////////
2046

    
2047
  public String reportState()
2048
    {
2049
    StringBuilder builder = new StringBuilder();
2050

    
2051
    for(int i=0; i<mNumCubits; i++ )
2052
      {
2053
      if( i>0 ) builder.append('.');
2054
      builder.append(mCubits[i].mQuatIndex);
2055
      }
2056

    
2057
    return builder.toString();
2058
    }
2059

    
2060
///////////////////////////////////////////////////////////////////////////////////////////////////
2061
// this is here only so it can be overridden in TwistyJSON so that we can get this from JSON.
2062

    
2063
  public int getNumCubitFaces()
2064
    {
2065
    return 0;
2066
    }
2067

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

    
2073
  public float getPillowCoeff()
2074
    {
2075
    return 1.0f;
2076
    }
2077

    
2078
///////////////////////////////////////////////////////////////////////////////////////////////////
2079

    
2080
  public TouchControl getTouchControl()
2081
    {
2082
    if( mTouchControl==null )
2083
      {
2084
      switch(getTouchControlType())
2085
        {
2086
        case TC_TETRAHEDRON      : mTouchControl = new TouchControlTetrahedron(this);
2087
                                   break;
2088
        case TC_HEXAHEDRON       : mTouchControl = new TouchControlHexahedron(this);
2089
                                   break;
2090
        case TC_OCTAHEDRON       : mTouchControl = new TouchControlOctahedron(this);
2091
                                   break;
2092
        case TC_DODECAHEDRON     : mTouchControl = new TouchControlDodecahedron(this);
2093
                                   break;
2094
        case TC_ICOSAHEDRON      : mTouchControl = new TouchControlIcosahedron(this);
2095
                                   break;
2096
        case TC_CUBOID           : int[] numLayers = getNumLayers();
2097
                                   mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
2098
                                   break;
2099
        case TC_BALL             : mTouchControl = new TouchControlBall(this);
2100
                                   break;
2101
        case TC_CHANGING_MIRROR  : mTouchControl = new TouchControlMirror(this);
2102
                                   break;
2103
        case TC_CHANGING_SQUARE  : mTouchControl = new TouchControlSquare(this);
2104
                                   break;
2105
        case TC_CHANGING_SHAPEMOD: mTouchControl = new TouchControlShapemod(this);
2106
                                   break;
2107
        }
2108
      }
2109
    return mTouchControl;
2110
    }
2111

    
2112
///////////////////////////////////////////////////////////////////////////////////////////////////
2113

    
2114
  public float[][] returnRotationFactor()
2115
    {
2116
    float[][] factor = new float[mNumAxis][];
2117

    
2118
    for(int ax=0; ax<mNumAxis; ax++)
2119
      {
2120
      int numL = mNumLayers[ax];
2121
      factor[ax] = new float[numL];
2122
      for(int la=0; la<numL; la++) factor[ax][la] = 1.0f;
2123
      }
2124

    
2125
    return factor;
2126
    }
2127

    
2128
///////////////////////////////////////////////////////////////////////////////////////////////////
2129

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

    
2135
///////////////////////////////////////////////////////////////////////////////////////////////////
2136

    
2137
  public String getInventor()
2138
    {
2139
    return mMetadata.getAuthor();
2140
    }
2141

    
2142
///////////////////////////////////////////////////////////////////////////////////////////////////
2143

    
2144
  public int getYearOfInvention()
2145
    {
2146
    return mMetadata.getYearOfInvention();
2147
    }
2148

    
2149
///////////////////////////////////////////////////////////////////////////////////////////////////
2150

    
2151
  public float getComplexity()
2152
    {
2153
    return mMetadata.getDifficulty();
2154
    }
2155

    
2156
///////////////////////////////////////////////////////////////////////////////////////////////////
2157

    
2158
  public String getObjectName()
2159
    {
2160
    return mMetadata.getObjectName();
2161
    }
2162

    
2163
///////////////////////////////////////////////////////////////////////////////////////////////////
2164

    
2165
  public ObjectSignature getSignature()
2166
    {
2167
    return mMetadata.getSignature();
2168
    }
2169

    
2170
///////////////////////////////////////////////////////////////////////////////////////////////////
2171
  // for JSON only
2172
  public abstract int getTouchControlType();
2173
  public abstract int getTouchControlSplit();
2174
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
2175
  public abstract int[][][] getEnabled();
2176
  public abstract float[] getDist3D(int[] numLayers);
2177
  public abstract Static3D[] getFaceAxis();
2178
  public abstract int[][] getScrambleEdges();
2179
  public abstract float[][] getCuts(int[] numLayers);
2180
  public abstract float getStickerRadius();
2181
  public abstract float getStickerStroke();
2182
  public abstract float[][][] getStickerAngles();
2183
  public abstract int getCubitVariant(int cubit, int[] numLayers);
2184
  public abstract ObjectShape getObjectShape(int variant);
2185
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
2186
  public abstract ObjectVertexEffects getVertexEffects(int variant);
2187
  public abstract int getNumCubitVariants(int[] numLayers);
2188
  public abstract float[][] getCubitPositions(int[] numLayers);
2189
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
2190
  public abstract float getScreenRatio();
2191
  public abstract int[] getColorTable();
2192
  public abstract String getShortName();
2193

    
2194
  // not only for JSON
2195
  public abstract Static3D[] getRotationAxis();
2196
  public abstract int[][] getBasicAngles();
2197
  public abstract int getNumPuzzleFaces();
2198
  public abstract int getFOV();
2199
  public abstract String[][] getTutorials();
2200
  }
(6-6/9)