Project

General

Profile

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

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

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2020 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Magic Cube.                                                              //
5
//                                                                                               //
6
// Magic Cube is free software: you can redistribute it and/or modify                            //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Magic Cube is distributed in the hope that it will be useful,                                 //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Magic Cube.  If not, see <http://www.gnu.org/licenses/>.                           //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.objectlib.main;
21

    
22
import java.io.DataInputStream;
23
import java.io.IOException;
24
import java.io.InputStream;
25
import java.util.Random;
26

    
27
import android.content.SharedPreferences;
28
import android.graphics.Bitmap;
29
import android.graphics.Canvas;
30
import android.graphics.Paint;
31

    
32
import org.distorted.library.effect.Effect;
33
import org.distorted.library.effect.MatrixEffectMove;
34
import org.distorted.library.effect.MatrixEffectQuaternion;
35
import org.distorted.library.effect.MatrixEffectScale;
36
import org.distorted.library.effect.VertexEffectQuaternion;
37
import org.distorted.library.effect.VertexEffectRotate;
38
import org.distorted.library.main.DistortedEffects;
39
import org.distorted.library.main.DistortedLibrary;
40
import org.distorted.library.main.DistortedNode;
41
import org.distorted.library.main.DistortedTexture;
42
import org.distorted.library.main.QuatHelper;
43
import org.distorted.library.mesh.MeshBase;
44
import org.distorted.library.mesh.MeshFile;
45
import org.distorted.library.mesh.MeshJoined;
46
import org.distorted.library.message.EffectListener;
47
import org.distorted.library.type.Dynamic1D;
48
import org.distorted.library.type.Static1D;
49
import org.distorted.library.type.Static3D;
50
import org.distorted.library.type.Static4D;
51

    
52
import org.distorted.objectlib.helpers.FactoryCubit;
53
import org.distorted.objectlib.helpers.FactorySticker;
54
import org.distorted.objectlib.helpers.ObjectFaceShape;
55
import org.distorted.objectlib.helpers.ObjectLibInterface;
56
import org.distorted.objectlib.helpers.ObjectShape;
57
import org.distorted.objectlib.helpers.ObjectSticker;
58
import org.distorted.objectlib.helpers.QuatGroupGenerator;
59
import org.distorted.objectlib.scrambling.ScrambleState;
60
import org.distorted.objectlib.scrambling.ObjectScrambler;
61
import org.distorted.objectlib.json.JsonReader;
62
import org.distorted.objectlib.touchcontrol.*;
63

    
64
import static org.distorted.objectlib.touchcontrol.TouchControl.*;
65

    
66
///////////////////////////////////////////////////////////////////////////////////////////////////
67

    
68
public abstract class TwistyObject
69
  {
70
  public static final int MESH_NICE = 0;
71
  public static final int MESH_FAST = 1;
72

    
73
  public static final int MODE_ICON = 0;
74
  public static final int MODE_NORM = 1;
75

    
76
  public static final int COLOR_YELLOW   = 0xffffff00;
77
  public static final int COLOR_WHITE    = 0xffffffff;
78
  public static final int COLOR_BLUE     = 0xff0000ff;
79
  public static final int COLOR_GREEN    = 0xff00bb00;
80
  public static final int COLOR_RED      = 0xff990000;
81
  public static final int COLOR_ORANGE   = 0xffff6200;
82
  public static final int COLOR_GREY     = 0xff727c7b;
83
  public static final int COLOR_VIOLET   = 0xff7700bb;
84
  public static final int COLOR_STROKE   = 0xff000000;
85
  private static final int COLOR_INTERNAL= 0xff000000;
86

    
87
  public static final int TEXTURE_HEIGHT = 256;
88
  static final int NUM_STICKERS_IN_ROW = 4;
89

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

    
95
  private static final float MAX_SIZE_CHANGE = 1.35f;
96
  private static final float MIN_SIZE_CHANGE = 0.75f;
97

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

    
101
  protected float[][] mStickerCoords;
102
  protected Static4D[] mObjectQuats;
103
  int mNumAxis, mMaxNumLayers;
104

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

    
151
  //////////////////// SOLVED1 ////////////////////////
152

    
153
  private int[] mFaceMap;
154
  private int[][] mScramble;
155
  private int[] mColors;
156

    
157
///////////////////////////////////////////////////////////////////////////////////////////////////
158

    
159
  TwistyObject(InputStream jsonStream, int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream meshStream)
160
    {
161
    JsonReader reader = JsonReader.getInstance();
162
    reader.parseJsonFile(jsonStream);
163
    setReader(reader);
164

    
165
    mNumLayers = reader.getNumLayers();
166
    mSize      = reader.getSize();
167
    initialize(meshState,iconMode,quat,move,scale,meshStream,true);
168
    }
169

    
170
///////////////////////////////////////////////////////////////////////////////////////////////////
171

    
172
  TwistyObject(int[] numLayers, int meshState, int iconMode, float size, Static4D quat, Static3D move, float scale, InputStream meshStream)
173
    {
174
    mNumLayers = numLayers;
175
    mSize      = size;
176
    initialize(meshState,iconMode,quat,move,scale,meshStream,false);
177
    }
178

    
179
///////////////////////////////////////////////////////////////////////////////////////////////////
180

    
181
  private void initialize(int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream stream, boolean fromJSON)
182
    {
183
    mIconMode = iconMode;
184
    mQuat = quat;
185
    mAxis = getRotationAxis();
186
    mInitScreenRatio = getScreenRatio();
187
    mSolvedFunctionIndex = getSolvedFunctionIndex();
188
    mBasicAngles = getBasicAngles();
189
    mObjectQuats = getQuats();
190
    mNumQuats = mObjectQuats.length;
191
    mOrigPos = getCubitPositions(mNumLayers);
192

    
193
    int numAxis = mAxis.length;
194
    mMaxNumLayers = -1;
195
    mCuts = getCuts(mNumLayers);
196
    mNumCuts = new int[numAxis];
197
    for(int i=0; i<numAxis; i++)
198
      {
199
      if( mMaxNumLayers<mNumLayers[i] ) mMaxNumLayers = mNumLayers[i];
200
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
201
      }
202

    
203
    mNumCubits = mOrigPos.length;
204
    mNumFaceColors = getNumFaceColors();
205
    mNumAxis = mAxis.length;
206

    
207
    int scramblingType = getScrambleType();
208
    ScrambleState[] states = getScrambleStates();
209
    mScrambler = new ObjectScrambler(scramblingType, mNumAxis,mNumLayers,states);
210

    
211
    boolean bandaged=false;
212

    
213
    for( int c=0; c<mNumCubits; c++)
214
      {
215
      if( mOrigPos[c].length>3 )
216
        {
217
        bandaged=true;
218
        break;
219
        }
220
      }
221
    mIsBandaged = bandaged;
222
    mQuatDebug = new int[mNumCubits];
223

    
224
    mRotationAngle= new Dynamic1D();
225
    mRotationAxis = new Static3D(1,0,0);
226
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
227

    
228
    mRotationAngleStatic = new Static1D(0);
229
    mRotationAngleMiddle = new Static1D(0);
230
    mRotationAngleFinal  = new Static1D(0);
231

    
232
    mObjectScale = new Static3D(scale,scale,scale);
233
    setObjectRatioNow(scale,720);
234

    
235
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
236
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
237
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
238

    
239
    boolean fromDMESH = (stream!=null && meshState==MESH_NICE);
240
    getQuatsAndShapes(fromDMESH,fromJSON);
241
    createMeshAndCubits(stream,meshState,fromDMESH);
242
    setUpTextures(fromDMESH,fromJSON);
243
    createDataStructuresForSolved();
244

    
245
    mEffects = new DistortedEffects();
246

    
247
    for( int q=0; q<mNumQuats; q++)
248
      {
249
      VertexEffectQuaternion vq = new VertexEffectQuaternion(mObjectQuats[q],CENTER);
250
      vq.setMeshAssociation(0,q);
251
      mEffects.apply(vq);
252
      }
253

    
254
    mEffects.apply(mRotateEffect);
255
    mEffects.apply(quatEffect);
256
    mEffects.apply(scaleEffect);
257
    mEffects.apply(moveEffect);
258

    
259
    mNode = new DistortedNode(mTexture,mEffects,mMesh);
260
    }
261

    
262
///////////////////////////////////////////////////////////////////////////////////////////////////
263

    
264
  private Static3D getPos(float[] origPos)
265
    {
266
    int len = origPos.length/3;
267
    float sumX = 0.0f;
268
    float sumY = 0.0f;
269
    float sumZ = 0.0f;
270

    
271
    for(int i=0; i<len; i++)
272
      {
273
      sumX += origPos[3*i  ];
274
      sumY += origPos[3*i+1];
275
      sumZ += origPos[3*i+2];
276
      }
277

    
278
    sumX /= len;
279
    sumY /= len;
280
    sumZ /= len;
281

    
282
    return new Static3D(sumX,sumY,sumZ);
283
    }
284

    
285
///////////////////////////////////////////////////////////////////////////////////////////////////
286

    
287
  private void createOuterFaces()
288
    {
289
    for(int v=0; v<mNumCubitVariants; v++)
290
      {
291
      int[][] indices = mShapes[v].getVertIndices();
292
      int faces = indices.length;
293
      mVariantFaceIsOuter[v] = new int[faces];
294
      }
295

    
296
    for( int cubit=0; cubit<mNumCubits; cubit++)
297
      {
298
      int variant = getCubitVariant(cubit,mNumLayers);
299
      int[][] indices = mShapes[variant].getVertIndices();
300
      int numFaces = indices.length;
301

    
302
      for(int face=0; face<numFaces; face++)
303
        if( getCubitFaceColor(cubit,face)>=0 )
304
          {
305
          mVariantFaceIsOuter[variant][face] = 1;
306
          }
307
      }
308
    }
309

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

    
312
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
313
    {
314
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
315

    
316
    if( !fromDMESH || !fromJSON )
317
      {
318
      FactoryCubit factory = FactoryCubit.getInstance();
319
      factory.clear();
320

    
321
      mOrigQuat = new Static4D[mNumCubits];
322
      for(int i=0; i<mNumCubits; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
323

    
324
      mShapes = new ObjectShape[mNumCubitVariants];
325
      for(int i=0; i<mNumCubitVariants; i++) mShapes[i] = getObjectShape(i);
326
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
327
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
328

    
329
      if( !fromJSON )
330
        {
331
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
332
        createOuterFaces();
333
        }
334

    
335
      if( fromDMESH )
336
        {
337
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
338
        }
339
      }
340
    }
341

    
342
///////////////////////////////////////////////////////////////////////////////////////////////////
343

    
344
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH)
345
    {
346
    mCubits = new Cubit[mNumCubits];
347

    
348
    if( fromDMESH )
349
      {
350
      DataInputStream dos = new DataInputStream(stream);
351
      mMesh = new MeshFile(dos);
352

    
353
      try
354
        {
355
        stream.close();
356
        }
357
      catch(IOException e)
358
        {
359
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
360
        }
361

    
362
      for(int i=0; i<mNumCubits; i++)
363
        {
364
        mCubits[i] = new Cubit(this,mOrigPos[i], mNumAxis);
365
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(), 0);
366
        }
367
      }
368
    else
369
      {
370
      MeshBase[] cubitMesh = new MeshBase[mNumCubits];
371

    
372
      for(int i=0; i<mNumCubits; i++)
373
        {
374
        mCubits[i] = new Cubit(this,mOrigPos[i], mNumAxis);
375
        cubitMesh[i] = createCubitMesh(i,mNumLayers,meshState,mNumCubitFaces);
376
        Static3D pos = getPos(mOrigPos[i]);
377
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
378
        cubitMesh[i].setEffectAssociation(0, mCubits[i].computeAssociation(), 0);
379
        }
380

    
381
      mMesh = new MeshJoined(cubitMesh);
382
      }
383
    }
384

    
385
///////////////////////////////////////////////////////////////////////////////////////////////////
386

    
387
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState, int numComponents)
388
    {
389
    int variant = getCubitVariant(cubit,numLayers);
390

    
391
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
392

    
393
    if( mMeshes[variant]==null )
394
      {
395
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
396
      FactoryCubit factory = FactoryCubit.getInstance();
397
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
398
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,meshState, numComponents);
399
      }
400

    
401
    MeshBase mesh = mMeshes[variant].copy(true);
402
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
403
    mesh.apply(quat,0xffffffff,0);
404

    
405
    return mesh;
406
    }
407

    
408
///////////////////////////////////////////////////////////////////////////////////////////////////
409

    
410
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
411
    {
412
    mTexture = new DistortedTexture();
413

    
414
    if( fromJSON )
415
      {
416
      mNumStickerTypes = getNumStickerTypes();
417
      mNumCubitFaces = getNumCubitFaces();
418
      }
419
    else
420
      {
421
      FactoryCubit factory = FactoryCubit.getInstance();
422
      mStickerCoords   = factory.getStickerCoords();
423
      mStickerVariants = factory.getStickerVariants();
424
      mStickerScales   = factory.getStickerScales();
425
      adjustStickerCoords();
426
      mNumStickerTypes = (mStickerCoords==null ? 0 : mStickerCoords.length);
427
      }
428

    
429
    mNumTextures= mNumFaceColors *mNumStickerTypes;
430
    mNumTexCols = NUM_STICKERS_IN_ROW;
431
    mNumTexRows = (mNumTextures+1)/NUM_STICKERS_IN_ROW;
432
    if( mNumTexCols*mNumTexRows < mNumTextures+1 ) mNumTexRows++;
433

    
434
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
435
    setTexture();
436
    }
437

    
438
///////////////////////////////////////////////////////////////////////////////////////////////////
439

    
440
  private int getMultQuat(int index1, int index2)
441
    {
442
    if( mQuatMult==null )
443
      {
444
      mQuatMult = new int[mNumQuats][mNumQuats];
445

    
446
      for(int i=0; i<mNumQuats; i++)
447
        for(int j=0; j<mNumQuats; j++) mQuatMult[i][j] = -1;
448
      }
449

    
450
    if( mQuatMult[index1][index2]==-1 )
451
      {
452
      mQuatMult[index1][index2] = mulQuat(index1,index2);
453
      }
454

    
455
    return mQuatMult[index1][index2];
456
    }
457

    
458
///////////////////////////////////////////////////////////////////////////////////////////////////
459

    
460
  public boolean isInIconMode()
461
    {
462
    return mIconMode==MODE_ICON;
463
    }
464

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

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

    
472
///////////////////////////////////////////////////////////////////////////////////////////////////
473

    
474
  public boolean shouldResetTextureMaps()
475
    {
476
    return false;
477
    }
478

    
479
///////////////////////////////////////////////////////////////////////////////////////////////////
480

    
481
  private void createDataStructuresForSolved()
482
    {
483
    mTmpQuats = new int[mNumQuats];
484
    mSolvedQuats = getSolvedQuats();
485
    }
486

    
487
///////////////////////////////////////////////////////////////////////////////////////////////////
488
// This is used to build internal data structures for the generic 'isSolved()'
489
//
490
// if this is an internal cubit (all faces black): return -1
491
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
492
// Color index, i.e. the index into the 'FACE_COLORS' table.
493
// else (edge or corner cubit, more than one non-black face): return -2.
494

    
495
  protected int retCubitSolvedStatus(int cubit)
496
    {
497
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
498
    int variant = getCubitVariant(cubit,mNumLayers);
499

    
500
    for(int face=0; face<mNumCubitFaces; face++)
501
      {
502
      varColor = getVariantFaceColor(variant,face);
503
      int numFaces = mCubitFaceColors[cubit].length;
504
      cubColor = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
505

    
506
      if( varColor>=0 && cubColor>=0 )
507
        {
508
        numNonBlack++;
509
        nonBlackIndex = cubColor;
510
        }
511
      }
512

    
513
    if( numNonBlack==0 ) return -1;
514
    if( numNonBlack>=2 ) return -2;
515

    
516
    return nonBlackIndex;
517
    }
518

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

    
521
  protected int[] buildSolvedQuats(Static3D faceAx)
522
    {
523
    final float MAXD = 0.0001f;
524
    float x = faceAx.get0();
525
    float y = faceAx.get1();
526
    float z = faceAx.get2();
527
    float a,dx,dy,dz,qx,qy,qz;
528
    Static4D quat;
529
    int place = 0;
530

    
531
    for(int q=1; q<mNumQuats; q++)
532
      {
533
      quat = mObjectQuats[q];
534
      qx = quat.get0();
535
      qy = quat.get1();
536
      qz = quat.get2();
537

    
538
           if( x!=0.0f ) { a = qx/x; }
539
      else if( y!=0.0f ) { a = qy/y; }
540
      else               { a = qz/z; }
541

    
542
      dx = a*x-qx;
543
      dy = a*y-qy;
544
      dz = a*z-qz;
545

    
546
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
547
        {
548
        mTmpQuats[place++] = q;
549
        }
550
      }
551

    
552
    if( place!=0 )
553
      {
554
      int[] ret = new int[place];
555
      System.arraycopy(mTmpQuats,0,ret,0,place);
556
      return ret;
557
      }
558

    
559
    return null;
560
    }
561

    
562
///////////////////////////////////////////////////////////////////////////////////////////////////
563

    
564
  public int[][] getSolvedQuats()
565
    {
566
    int[] groups = new int[mNumCubits];
567
    int numGroups = 1;
568
    int numFirst  = 0;
569

    
570
    for(int cubit=0; cubit<mNumCubits; cubit++)
571
      {
572
      groups[cubit] = retCubitSolvedStatus(cubit);
573
      if( groups[cubit]>=0 ) numGroups++;
574
      else                   numFirst++;
575
      }
576

    
577
    int firstIndex = 1;
578
    int groupIndex = 1;
579
    int[][] solvedQuats = new int[numGroups][];
580
    solvedQuats[0] = new int[1+numFirst];
581
    solvedQuats[0][0] = numFirst;
582
    Static3D[] axis = getFaceAxis();
583

    
584
    for(int cubit=0; cubit<mNumCubits; cubit++)
585
      {
586
      int group = groups[cubit];
587

    
588
      if( group<0 )
589
        {
590
        solvedQuats[0][firstIndex] = cubit;
591
        firstIndex++;
592
        }
593
      else
594
        {
595
        int[] quats = buildSolvedQuats(axis[group]);
596
        int len = quats==null ? 0 : quats.length;
597
        solvedQuats[groupIndex] = new int[2+len];
598
        solvedQuats[groupIndex][0] = 1;
599
        solvedQuats[groupIndex][1] = cubit;
600
        for(int i=0; i<len; i++) solvedQuats[groupIndex][i+2] = quats[i];
601
        groupIndex++;
602
        }
603
      }
604
/*
605
    String dbg = "SOLVED GROUPS:\n";
606

    
607
    for(int g=0; g<numGroups; g++)
608
      {
609
      int len = solvedQuats[g].length;
610
      for(int i=0; i<len; i++) dbg += (" "+solvedQuats[g][i]);
611
      dbg+="\n";
612
      }
613

    
614
    android.util.Log.e("D", dbg);
615
*/
616
    return solvedQuats;
617
    }
618

    
619
///////////////////////////////////////////////////////////////////////////////////////////////////
620

    
621
  public int getSolvedFunctionIndex()
622
    {
623
    return 0;
624
    }
625

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

    
631
  private boolean isSolvedCentersOnly()
632
    {
633
    int numGroups = mSolvedQuats.length;
634

    
635
    for(int group=1; group<numGroups; group++)
636
      {
637
      int numEntries= mSolvedQuats[group].length;
638
      int numCubits = mSolvedQuats[group][0];
639
      int firstCubit= mSolvedQuats[group][1];
640
      int firstQuat = mCubits[firstCubit].mQuatIndex;
641

    
642
      for(int cubit=2; cubit<=numCubits; cubit++)
643
        {
644
        int currCubit= mSolvedQuats[group][cubit];
645
        int currQuat = mCubits[currCubit].mQuatIndex;
646
        boolean isGood= (firstQuat==currQuat);
647

    
648
        for(int q=numCubits+1; !isGood && q<numEntries; q++)
649
          {
650
          int quat = mSolvedQuats[group][q];
651
          if( firstQuat == getMultQuat(currQuat,quat) ) isGood = true;
652
          }
653

    
654
        if( !isGood ) return false;
655
        }
656
      }
657

    
658
    return true;
659
    }
660

    
661
///////////////////////////////////////////////////////////////////////////////////////////////////
662

    
663
  private boolean isSolved0()
664
    {
665
    if( mSolvedQuats[0][0]==0 ) return isSolvedCentersOnly();
666

    
667
    for( int[] solvedQuat : mSolvedQuats )
668
      {
669
      int numCubits = solvedQuat[0];
670
      int firstCubit= solvedQuat[1];
671
      int quat = mCubits[firstCubit].mQuatIndex;
672

    
673
      for( int cubit=2; cubit<=numCubits; cubit++ )
674
        {
675
        int c = solvedQuat[cubit];
676
        if( quat != mCubits[c].mQuatIndex ) return false;
677
        }
678
      }
679

    
680
    int cubit= mSolvedQuats[0][1];
681
    int quat0= mCubits[cubit].mQuatIndex;
682
    int numGroups = mSolvedQuats.length;
683

    
684
    for(int group=1; group<numGroups; group++)
685
      {
686
      int firstCubit= mSolvedQuats[group][1];
687
      int currQuat  = mCubits[firstCubit].mQuatIndex;
688

    
689
      if( quat0==currQuat ) continue;
690

    
691
      boolean isGood= false;
692
      int numEntries= mSolvedQuats[group].length;
693
      int numCubits = mSolvedQuats[group][0];
694

    
695
      for(int q=numCubits+1; q<numEntries; q++)
696
        {
697
        int quat = mSolvedQuats[group][q];
698

    
699
        if( quat0 == getMultQuat(currQuat,quat) )
700
          {
701
          isGood = true;
702
          break;
703
          }
704
        }
705

    
706
      if( !isGood ) return false;
707
      }
708

    
709
    return true;
710
    }
711

    
712
///////////////////////////////////////////////////////////////////////////////////////////////////
713

    
714
  private int computeScramble(int quatNum, int centerNum)
715
    {
716
    float MAXDIFF = 0.01f;
717
    float[] center= mOrigPos[centerNum];
718
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
719
    Static4D result = QuatHelper.rotateVectorByQuat(sc,mObjectQuats[quatNum]);
720

    
721
    float x = result.get0();
722
    float y = result.get1();
723
    float z = result.get2();
724

    
725
    for(int c=0; c<mNumCubits; c++)
726
      {
727
      float[] cent = mOrigPos[c];
728

    
729
      float qx = cent[0] - x;
730
      float qy = cent[1] - y;
731
      float qz = cent[2] - z;
732

    
733
      if( qx>-MAXDIFF && qx<MAXDIFF &&
734
          qy>-MAXDIFF && qy<MAXDIFF &&
735
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
736
      }
737

    
738
    return -1;
739
    }
740

    
741
///////////////////////////////////////////////////////////////////////////////////////////////////
742
// Dino4 uses this. It is solved if and only if groups of cubits
743
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
744
// or
745
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
746
// are all the same color.
747

    
748
  private boolean isSolved1()
749
    {
750
    if( mScramble==null )
751
      {
752
      mScramble = new int[mNumQuats][mNumCubits];
753
      mColors   = new int[mNumCubits];
754

    
755
      for(int q=0; q<mNumQuats; q++)
756
        for(int c=0; c<mNumCubits; c++) mScramble[q][c] = computeScramble(q,c);
757
      }
758

    
759
    if( mFaceMap==null )
760
      {
761
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
762
      }
763

    
764
    for(int c=0; c<mNumCubits; c++)
765
      {
766
      int index = mScramble[mCubits[c].mQuatIndex][c];
767
      mColors[index] = mFaceMap[c];
768
      }
769

    
770
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
771
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
772
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
773

    
774
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
775
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
776
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
777

    
778
    return false;
779
    }
780

    
781
///////////////////////////////////////////////////////////////////////////////////////////////////
782

    
783
  int computeRow(float[] pos, int axisIndex)
784
    {
785
    int ret=0;
786
    int len = pos.length / 3;
787
    Static3D axis = mAxis[axisIndex];
788
    float axisX = axis.get0();
789
    float axisY = axis.get1();
790
    float axisZ = axis.get2();
791
    float casted;
792

    
793
    for(int i=0; i<len; i++)
794
      {
795
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
796
      ret |= computeSingleRow(axisIndex,casted);
797
      }
798

    
799
    return ret;
800
    }
801

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

    
804
  private int computeSingleRow(int axisIndex,float casted)
805
    {
806
    int num = mNumCuts[axisIndex];
807

    
808
    for(int i=0; i<num; i++)
809
      {
810
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
811
      }
812

    
813
    return (1<<num);
814
    }
815

    
816
///////////////////////////////////////////////////////////////////////////////////////////////////
817

    
818
  private boolean wasRotateApplied()
819
    {
820
    return mEffects.exists(mRotateEffect.getID());
821
    }
822

    
823
///////////////////////////////////////////////////////////////////////////////////////////////////
824

    
825
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
826
    {
827
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
828
    }
829

    
830
///////////////////////////////////////////////////////////////////////////////////////////////////
831
// note the minus in front of the sin() - we rotate counterclockwise
832
// when looking towards the direction where the axis increases in values.
833

    
834
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
835
    {
836
    Static3D axis = mAxis[axisIndex];
837

    
838
    while( angleInDegrees<0 ) angleInDegrees += 360;
839
    angleInDegrees %= 360;
840
    
841
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
842
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
843

    
844
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
845
    }
846

    
847
///////////////////////////////////////////////////////////////////////////////////////////////////
848

    
849
  private synchronized void setupPosition(int[][] moves)
850
    {
851
    if( moves!=null )
852
      {
853
      Static4D quat;
854
      int index, axis, rowBitmap, angle;
855

    
856
      for(int[] move: moves)
857
        {
858
        axis     = move[0];
859
        rowBitmap= move[1];
860
        angle    = move[2]*(360/mBasicAngles[axis]);
861
        quat     = makeQuaternion(axis,angle);
862

    
863
        for(int j=0; j<mNumCubits; j++)
864
          if( belongsToRotation(j,axis,rowBitmap) )
865
            {
866
            index = mCubits[j].removeRotationNow(quat);
867
            mMesh.setEffectAssociation(j, mCubits[j].computeAssociation(),index);
868
            }
869
        }
870
      }
871
    }
872

    
873
///////////////////////////////////////////////////////////////////////////////////////////////////
874

    
875
  public int getScrambleType()
876
    {
877
    return 0;
878
    }
879

    
880
///////////////////////////////////////////////////////////////////////////////////////////////////
881

    
882
  int computeBitmapFromRow(int rowBitmap, int axis)
883
    {
884
    if( mIsBandaged )
885
      {
886
      int bitmap, initBitmap=0;
887

    
888
      while( initBitmap!=rowBitmap )
889
        {
890
        initBitmap = rowBitmap;
891

    
892
        for(int cubit=0; cubit<mNumCubits; cubit++)
893
          {
894
          bitmap = mCubits[cubit].getRotRow(axis);
895
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
896
          }
897
        }
898
      }
899

    
900
    return rowBitmap;
901
    }
902

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

    
907
  void clampPos(float[] pos, int offset)
908
    {
909
    float currError, minError = Float.MAX_VALUE;
910
    int minErrorIndex1 = -1;
911
    int minErrorIndex2 = -1;
912

    
913
    float x = pos[offset  ];
914
    float y = pos[offset+1];
915
    float z = pos[offset+2];
916

    
917
    float xo,yo,zo;
918

    
919
    for(int i=0; i<mNumCubits; i++)
920
      {
921
      int len = mOrigPos[i].length / 3;
922

    
923
      for(int j=0; j<len; j++)
924
        {
925
        xo = mOrigPos[i][3*j  ];
926
        yo = mOrigPos[i][3*j+1];
927
        zo = mOrigPos[i][3*j+2];
928

    
929
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
930

    
931
        if( currError<minError )
932
          {
933
          minError = currError;
934
          minErrorIndex1 = i;
935
          minErrorIndex2 = j;
936
          }
937
        }
938
      }
939

    
940
    if( minError< 0.1f ) // TODO: 0.1 ?
941
      {
942
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
943
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
944
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
945
      }
946
    }
947

    
948
///////////////////////////////////////////////////////////////////////////////////////////////////
949
// remember about the double cover or unit quaternions!
950

    
951
  int mulQuat(int q1, int q2)
952
    {
953
    Static4D result = QuatHelper.quatMultiply(mObjectQuats[q1],mObjectQuats[q2]);
954

    
955
    float rX = result.get0();
956
    float rY = result.get1();
957
    float rZ = result.get2();
958
    float rW = result.get3();
959

    
960
    final float MAX_ERROR = 0.1f;
961
    float dX,dY,dZ,dW;
962

    
963
    for(int i=0; i<mNumQuats; i++)
964
      {
965
      dX = mObjectQuats[i].get0() - rX;
966
      dY = mObjectQuats[i].get1() - rY;
967
      dZ = mObjectQuats[i].get2() - rZ;
968
      dW = mObjectQuats[i].get3() - rW;
969

    
970
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
971
          dY<MAX_ERROR && dY>-MAX_ERROR &&
972
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
973
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
974

    
975
      dX = mObjectQuats[i].get0() + rX;
976
      dY = mObjectQuats[i].get1() + rY;
977
      dZ = mObjectQuats[i].get2() + rZ;
978
      dW = mObjectQuats[i].get3() + rW;
979

    
980
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
981
          dY<MAX_ERROR && dY>-MAX_ERROR &&
982
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
983
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
984
      }
985

    
986
    return -1;
987
    }
988

    
989
///////////////////////////////////////////////////////////////////////////////////////////////////
990

    
991
  private float getAngle()
992
    {
993
    int pointNum = mRotationAngle.getNumPoints();
994

    
995
    if( pointNum>=1 )
996
      {
997
      return mRotationAngle.getPoint(pointNum-1).get0();
998
      }
999
    else
1000
      {
1001
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
1002
      return 0;
1003
      }
1004
    }
1005

    
1006
///////////////////////////////////////////////////////////////////////////////////////////////////
1007

    
1008
  void setLibInterface(ObjectLibInterface inter)
1009
    {
1010
    mInterface = inter;
1011
    }
1012

    
1013
///////////////////////////////////////////////////////////////////////////////////////////////////
1014

    
1015
  void initializeObject(int[][] moves)
1016
    {
1017
    solve();
1018
    setupPosition(moves);
1019
    }
1020

    
1021
///////////////////////////////////////////////////////////////////////////////////////////////////
1022

    
1023
  synchronized void removeRotationNow()
1024
    {
1025
    float angle = getAngle();
1026
    double nearestAngleInRadians = angle*Math.PI/180;
1027
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
1028
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
1029
    float axisX = mAxis[mCurrentRotAxis].get0();
1030
    float axisY = mAxis[mCurrentRotAxis].get1();
1031
    float axisZ = mAxis[mCurrentRotAxis].get2();
1032
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
1033

    
1034
    mRotationAngle.removeAll();
1035
    mRotationAngleStatic.set0(0);
1036

    
1037
    for(int i=0; i<mNumCubits; i++)
1038
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
1039
        {
1040
        int index = mCubits[i].removeRotationNow(quat);
1041
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),index);
1042
        }
1043
    }
1044

    
1045
///////////////////////////////////////////////////////////////////////////////////////////////////
1046

    
1047
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
1048
    {
1049
    if( wasRotateApplied() )
1050
      {
1051
      float angle = getAngle();
1052
      mRotationAngleStatic.set0(angle);
1053
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1054
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1055

    
1056
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1057
      mRotationAngle.resetToBeginning();
1058
      mRotationAngle.removeAll();
1059
      mRotationAngle.add(mRotationAngleStatic);
1060
      mRotationAngle.add(mRotationAngleMiddle);
1061
      mRotationAngle.add(mRotationAngleFinal);
1062
      mRotateEffect.notifyWhenFinished(listener);
1063

    
1064
      return mRotateEffect.getID();
1065
      }
1066

    
1067
    return 0;
1068
    }
1069

    
1070
///////////////////////////////////////////////////////////////////////////////////////////////////
1071

    
1072
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1073
    {
1074
    if( wasRotateApplied() )
1075
      {
1076
      mCurrentRotAxis = axis;
1077
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1078

    
1079
      mRotationAngleStatic.set0(0.0f);
1080
      mRotationAxis.set( mAxis[axis] );
1081
      mRotationAngle.setDuration(durationMillis);
1082
      mRotationAngle.resetToBeginning();
1083
      mRotationAngle.add(new Static1D(0));
1084
      mRotationAngle.add(new Static1D(angle));
1085
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1086
      mRotateEffect.notifyWhenFinished(listener);
1087

    
1088
      return mRotateEffect.getID();
1089
      }
1090

    
1091
    return 0;
1092
    }
1093

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

    
1096
  void continueRotation(float angleInDegrees)
1097
    {
1098
    mRotationAngleStatic.set0(angleInDegrees);
1099
    }
1100

    
1101
///////////////////////////////////////////////////////////////////////////////////////////////////
1102

    
1103
  synchronized void beginNewRotation(int axis, int row )
1104
    {
1105
    if( axis<0 || axis>=mNumAxis )
1106
      {
1107
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1108
      return;
1109
      }
1110
    if( row<0 || row>=mNumLayers[axis] )
1111
      {
1112
      android.util.Log.e("object", "invalid rotation row: "+row);
1113
      return;
1114
      }
1115

    
1116
    mCurrentRotAxis = axis;
1117
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1118
    mRotationAngleStatic.set0(0.0f);
1119
    mRotationAxis.set( mAxis[axis] );
1120
    mRotationAngle.add(mRotationAngleStatic);
1121
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1122
    }
1123

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

    
1126
  void setTextureMap(int cubit, int face, int newColor)
1127
    {
1128
    final float ratioW = 1.0f/mNumTexCols;
1129
    final float ratioH = 1.0f/mNumTexRows;
1130
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1131
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1132
    int col = newColor%mNumTexCols;
1133

    
1134
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1135
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1136
    }
1137

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

    
1140
  private int getCubitFaceColor(int cubit, int face)
1141
    {
1142
    int puzzleFace = getCubitFaceMap(cubit,face);
1143
    if( puzzleFace>=0 ) puzzleFace %= mNumFaceColors;
1144
    return puzzleFace;
1145
    }
1146

    
1147
///////////////////////////////////////////////////////////////////////////////////////////////////
1148

    
1149
  public int getCubitFaceMap(int cubit, int face)
1150
    {
1151
    int numFaces = mCubitFaceColors[cubit].length;
1152
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1153
    return puzzleFace<0 ? -1 : puzzleFace;
1154
    }
1155

    
1156
///////////////////////////////////////////////////////////////////////////////////////////////////
1157

    
1158
  void resetAllTextureMaps()
1159
    {
1160
    final float ratioW = 1.0f/mNumTexCols;
1161
    final float ratioH = 1.0f/mNumTexRows;
1162
    int cubColor, varColor, color, variant, row, col;
1163

    
1164
    for(int cubit=0; cubit<mNumCubits; cubit++)
1165
      {
1166
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1167
      variant = getCubitVariant(cubit,mNumLayers);
1168

    
1169
      for(int face=0; face<mNumCubitFaces; face++)
1170
        {
1171
        cubColor = getCubitFaceColor(cubit,face);
1172
        varColor = getVariantFaceColor(variant,face);
1173
        color    = cubColor<0 || varColor<0 ? mNumTextures : varColor*mNumFaceColors + cubColor;
1174
        row      = (mNumTexRows-1) - color/mNumTexCols;
1175
        col      = color%mNumTexCols;
1176

    
1177
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1178
        }
1179

    
1180
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1181
      }
1182
    }
1183

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

    
1186
  void releaseResources()
1187
    {
1188
    mTexture.markForDeletion();
1189
    mMesh.markForDeletion();
1190
    mEffects.markForDeletion();
1191

    
1192
    for(int j=0; j<mNumCubits; j++)
1193
      {
1194
      mCubits[j].releaseResources();
1195
      }
1196
    }
1197

    
1198
///////////////////////////////////////////////////////////////////////////////////////////////////
1199

    
1200
  synchronized void restorePreferences(SharedPreferences preferences)
1201
    {
1202
    boolean error = false;
1203
    String key = getShortName();
1204

    
1205
    for(int i=0; i<mNumCubits; i++)
1206
      {
1207
      mQuatDebug[i] = mCubits[i].restorePreferences(key,i,preferences);
1208

    
1209
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1210
        {
1211
        mCubits[i].modifyCurrentPosition(mObjectQuats[mQuatDebug[i]]);
1212
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),mQuatDebug[i]);
1213
        }
1214
      else
1215
        {
1216
        error = true;
1217
        }
1218
      }
1219

    
1220
    if( error )
1221
      {
1222
      for(int i=0; i<mNumCubits; i++)
1223
        {
1224
        mCubits[i].solve();
1225
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),0);
1226
        }
1227
      }
1228
    }
1229

    
1230
///////////////////////////////////////////////////////////////////////////////////////////////////
1231

    
1232
  void savePreferences(SharedPreferences.Editor editor)
1233
    {
1234
    String key = getShortName();
1235
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(key,i,editor);
1236
    }
1237

    
1238
///////////////////////////////////////////////////////////////////////////////////////////////////
1239

    
1240
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1241
    {
1242
    final float A = 0.8f;  // 0<A<1
1243

    
1244
    int prev = curr>0 ? curr-1 : len-1;
1245
    int next = curr<len-1 ? curr+1 : 0;
1246

    
1247
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1248
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1249
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1250
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1251

    
1252
    float len1= v1x*v1x+v1y*v1y;
1253
    float len2= v2x*v2x+v2y*v2y;
1254

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

    
1257
    return 1-A*cos;
1258
    }
1259

    
1260
///////////////////////////////////////////////////////////////////////////////////////////////////
1261

    
1262
  public ObjectSticker retSticker(int sticker)
1263
    {
1264
    if( mStickers==null )
1265
      {
1266
      float rad = getStickerRadius();
1267
      float str = getStickerStroke();
1268
      float[][] angles = getStickerAngles();
1269
      int numStickers = mStickerCoords.length;
1270
      mStickers = new ObjectSticker[numStickers];
1271

    
1272
      for(int s=0; s<numStickers; s++)
1273
        {
1274
        float scale = mStickerScales[s];
1275
        float radius = rad / scale;
1276
        float stroke = str / scale;
1277
        int len = mStickerCoords[s].length/2;
1278
        float[] radii = new float[len];
1279
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1280
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1281
        }
1282
      }
1283

    
1284
    return mStickers[sticker];
1285
    }
1286

    
1287
///////////////////////////////////////////////////////////////////////////////////////////////////
1288
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1289

    
1290
  public void adjustStickerCoords()
1291
    {
1292

    
1293
    }
1294

    
1295
///////////////////////////////////////////////////////////////////////////////////////////////////
1296

    
1297
  public Static4D[] getQuats()
1298
    {
1299
    if( mObjectQuats==null )
1300
      {
1301
      mObjectQuats = QuatGroupGenerator.computeGroup(mAxis,mBasicAngles);
1302
      }
1303

    
1304
    return mObjectQuats;
1305
    }
1306

    
1307
///////////////////////////////////////////////////////////////////////////////////////////////////
1308

    
1309
  public int getInternalColor()
1310
    {
1311
    return COLOR_INTERNAL;
1312
    }
1313

    
1314
///////////////////////////////////////////////////////////////////////////////////////////////////
1315
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1316

    
1317
  private void createTexture()
1318
    {
1319
    Paint paint = new Paint();
1320
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_4444);
1321
    Canvas canvas = new Canvas(mBitmap);
1322

    
1323
    paint.setAntiAlias(true);
1324
    paint.setTextAlign(Paint.Align.CENTER);
1325
    paint.setStyle(Paint.Style.FILL);
1326

    
1327
    paint.setColor(getInternalColor());
1328
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1329

    
1330
    int texture = 0;
1331
    FactorySticker factory = FactorySticker.getInstance();
1332

    
1333
    for(int row=0; row<mNumTexRows; row++)
1334
      for(int col=0; col<mNumTexCols; col++)
1335
        {
1336
        if( texture>=mNumTextures ) break;
1337
        ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1338
        int color = getColor(texture% mNumFaceColors);
1339
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, color, sticker);
1340
        texture++;
1341
        }
1342
    }
1343

    
1344
///////////////////////////////////////////////////////////////////////////////////////////////////
1345

    
1346
  void setTexture()
1347
    {
1348
    if( mBitmap==null ) createTexture();
1349

    
1350
    if( !mTexture.setTexture(mBitmap) )
1351
      {
1352
      int max = DistortedLibrary.getMaxTextureSize();
1353
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1354
      }
1355
    }
1356

    
1357
///////////////////////////////////////////////////////////////////////////////////////////////////
1358

    
1359
  void setObjectRatioNow(float sc, int nodeSize)
1360
    {
1361
    mObjectScreenRatio = sc;
1362
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1363
    mObjectScale.set(scale,scale,scale);
1364

    
1365
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1366
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1367
    }
1368

    
1369
///////////////////////////////////////////////////////////////////////////////////////////////////
1370

    
1371
  void setObjectRatio(float sizeChange, int nodeSize)
1372
    {
1373
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1374

    
1375
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1376
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1377

    
1378
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1379
    }
1380

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

    
1383
  void setNodeSize(int nodeSize)
1384
    {
1385
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1386
    }
1387

    
1388
///////////////////////////////////////////////////////////////////////////////////////////////////
1389

    
1390
  public float getRatio()
1391
    {
1392
    return mObjectScreenRatio;
1393
    }
1394

    
1395
///////////////////////////////////////////////////////////////////////////////////////////////////
1396

    
1397
  public float getObjectRatio()
1398
    {
1399
    return mObjectScreenRatio*mInitScreenRatio;
1400
    }
1401

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

    
1404
  boolean isSolved()
1405
    {
1406
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1407
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1408

    
1409
    return false;
1410
    }
1411

    
1412
///////////////////////////////////////////////////////////////////////////////////////////////////
1413

    
1414
  int computeNearestAngle(int axis, float angle, float speed)
1415
    {
1416
    int basicAngle   = mBasicAngles[axis>=mBasicAngles.length ? 0 : axis];
1417
    int nearestAngle = 360/basicAngle;
1418

    
1419
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1420
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1421

    
1422
    if( tmp!=0 ) return nearestAngle*tmp;
1423

    
1424
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1425
    }
1426

    
1427
///////////////////////////////////////////////////////////////////////////////////////////////////
1428
// INTERNAL API - those are called from 'effects' package
1429
///////////////////////////////////////////////////////////////////////////////////////////////////
1430

    
1431
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1432
    {
1433
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1434
    }
1435

    
1436
///////////////////////////////////////////////////////////////////////////////////////////////////
1437

    
1438
  public Static4D getRotationQuat()
1439
    {
1440
    return mQuat;
1441
    }
1442

    
1443
///////////////////////////////////////////////////////////////////////////////////////////////////
1444

    
1445
  public float getSize()
1446
    {
1447
    return mSize;
1448
    }
1449

    
1450
///////////////////////////////////////////////////////////////////////////////////////////////////
1451

    
1452
  public void apply(Effect effect, int position)
1453
    {
1454
    mEffects.apply(effect, position);
1455
    }
1456

    
1457
///////////////////////////////////////////////////////////////////////////////////////////////////
1458

    
1459
  public void remove(long effectID)
1460
    {
1461
    mEffects.abortById(effectID);
1462
    }
1463

    
1464
///////////////////////////////////////////////////////////////////////////////////////////////////
1465

    
1466
  public MeshBase getObjectMesh()
1467
    {
1468
    return mMesh;
1469
    }
1470

    
1471
///////////////////////////////////////////////////////////////////////////////////////////////////
1472

    
1473
  public DistortedEffects getObjectEffects()
1474
    {
1475
    return mEffects;
1476
    }
1477

    
1478
///////////////////////////////////////////////////////////////////////////////////////////////////
1479
// PUBLIC API
1480
///////////////////////////////////////////////////////////////////////////////////////////////////
1481

    
1482
  public int getCubitFaceColorIndex(int cubit, int face)
1483
    {
1484
    Static4D texMap = mMesh.getTextureMap(mNumFaceColors *cubit + face);
1485

    
1486
    int x = (int)(texMap.get0()/texMap.get2());
1487
    int y = (int)(texMap.get1()/texMap.get3());
1488

    
1489
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1490
    }
1491

    
1492
///////////////////////////////////////////////////////////////////////////////////////////////////
1493

    
1494
  public int[] getNumLayers()
1495
    {
1496
    return mNumLayers;
1497
    }
1498

    
1499
///////////////////////////////////////////////////////////////////////////////////////////////////
1500

    
1501
  public synchronized void solve()
1502
    {
1503
    for(int i=0; i<mNumCubits; i++)
1504
      {
1505
      mCubits[i].solve();
1506
      mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(), 0);
1507
      }
1508
    }
1509

    
1510
///////////////////////////////////////////////////////////////////////////////////////////////////
1511

    
1512
  public int getCubitQuatIndex(int cubit)
1513
    {
1514
    return (cubit>=0 && cubit<mNumCubits) ? mCubits[cubit].mQuatIndex : 0;
1515
    }
1516

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

    
1519
  public int getCubitRotRow(int cubit, int axis)
1520
    {
1521
    return mCubits[cubit].getRotRow(axis);
1522
    }
1523

    
1524
///////////////////////////////////////////////////////////////////////////////////////////////////
1525

    
1526
  public Bitmap getStickerBitmap()
1527
    {
1528
    return mBitmap;
1529
    }
1530

    
1531
///////////////////////////////////////////////////////////////////////////////////////////////////
1532

    
1533
  public DistortedNode getNode()
1534
    {
1535
    return mNode;
1536
    }
1537

    
1538
///////////////////////////////////////////////////////////////////////////////////////////////////
1539

    
1540
  public int getNumStickerTypes()
1541
    {
1542
    return mNumStickerTypes;
1543
    }
1544

    
1545
///////////////////////////////////////////////////////////////////////////////////////////////////
1546
// this is here only so it can be overridden in TwistyJSON soo that we can get this from JSON.
1547

    
1548
  public int getNumCubitFaces()
1549
    {
1550
    return 0;
1551
    }
1552

    
1553
///////////////////////////////////////////////////////////////////////////////////////////////////
1554

    
1555
  public TouchControl getTouchControl()
1556
    {
1557
    if( mTouchControl==null )
1558
      {
1559
      switch(getTouchControlType())
1560
        {
1561
        case TC_TETRAHEDRON      : mTouchControl = new TouchControlTetrahedron(this);
1562
                                   break;
1563
        case TC_HEXAHEDRON       : mTouchControl = new TouchControlHexahedron(this);
1564
                                   break;
1565
        case TC_OCTAHEDRON       : mTouchControl = new TouchControlOctahedron(this);
1566
                                   break;
1567
        case TC_DODECAHEDRON     : mTouchControl = new TouchControlDodecahedron(this);
1568
                                   break;
1569
        case TC_CUBOID           : int[] numLayers = getNumLayers();
1570
                                   mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1571
                                   break;
1572
        case TC_CHANGING_MIRROR  : mTouchControl = new TouchControlMirror(this);
1573
                                   break;
1574
        case TC_CHANGING_SQUARE  : mTouchControl = new TouchControlSquare(this);
1575
                                   break;
1576
        case TC_CHANGING_SHAPEMOD: mTouchControl = new TouchControlShapemod(this);
1577
                                   break;
1578
        }
1579
      }
1580
    return mTouchControl;
1581
    }
1582

    
1583
///////////////////////////////////////////////////////////////////////////////////////////////////
1584

    
1585
  protected void setReader(JsonReader reader)
1586
    {
1587
    // empty
1588
    }
1589

    
1590
///////////////////////////////////////////////////////////////////////////////////////////////////
1591
  // for JSON only
1592
  public abstract int getTouchControlType();
1593
  public abstract int getTouchControlSplit();
1594
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1595
  public abstract int[][][] getEnabled();
1596
  public abstract float[] getDist3D(int[] numLayers);
1597
  public abstract Static3D[] getFaceAxis();
1598
  public abstract ScrambleState[] getScrambleStates();
1599
  public abstract float[][] getCuts(int[] numLayers);
1600
  public abstract float getStickerRadius();
1601
  public abstract float getStickerStroke();
1602
  public abstract float[][] getStickerAngles();
1603
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1604
  public abstract ObjectShape getObjectShape(int variant);
1605
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
1606
  public abstract int getNumCubitVariants(int[] numLayers);
1607
  public abstract float[][] getCubitPositions(int[] numLayers);
1608
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
1609
  public abstract int getNumFaceColors();
1610
  public abstract float getScreenRatio();
1611
  public abstract int getColor(int face);
1612
  public abstract String getShortName();
1613
  public abstract long getSignature();
1614

    
1615
  // not only for JSON
1616
  public abstract Static3D[] getRotationAxis();
1617
  public abstract int[] getBasicAngles();
1618
  public abstract int getNumFaces();
1619
  public abstract String getObjectName();
1620
  public abstract String getInventor();
1621
  public abstract int getYearOfInvention();
1622
  public abstract int getComplexity();
1623
  public abstract int getFOV();
1624
  public abstract String[][] getTutorials();
1625
  }
(11-11/12)