Project

General

Profile

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

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

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.ObjectSignature;
58
import org.distorted.objectlib.helpers.ObjectSticker;
59
import org.distorted.objectlib.helpers.QuatGroupGenerator;
60
import org.distorted.objectlib.scrambling.ScrambleState;
61
import org.distorted.objectlib.scrambling.ObjectScrambler;
62
import org.distorted.objectlib.json.JsonReader;
63
import org.distorted.objectlib.touchcontrol.*;
64

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

    
67
///////////////////////////////////////////////////////////////////////////////////////////////////
68

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

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

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

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

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

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

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

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

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

    
155
  //////////////////// SOLVED1 ////////////////////////
156

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

    
161
///////////////////////////////////////////////////////////////////////////////////////////////////
162

    
163
  TwistyObject(InputStream jsonStream, int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream meshStream)
164
    {
165
    JsonReader reader = JsonReader.getInstance();
166
    reader.parseJsonFile(jsonStream);
167
    setReader(reader);
168

    
169
    mNumLayers = reader.getNumLayers();
170
    mSize      = reader.getSize();
171
    mInitData  = null;
172
    initialize(meshState,iconMode,quat,move,scale,meshStream,true);
173
    }
174

    
175
///////////////////////////////////////////////////////////////////////////////////////////////////
176

    
177
  TwistyObject(InitData data, int meshState, int iconMode, float size, Static4D quat, Static3D move, float scale, InputStream meshStream)
178
    {
179
    mNumLayers = data.getNumLayers();
180
    mSize      = size;
181
    mInitData  = data;
182
    initialize(meshState,iconMode,quat,move,scale,meshStream,false);
183
    }
184

    
185
///////////////////////////////////////////////////////////////////////////////////////////////////
186

    
187
  private void initialize(int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream stream, boolean fromJSON)
188
    {
189
    mIconMode = iconMode;
190
    mQuat = quat;
191
    mAxis = getRotationAxis();
192
    mInitScreenRatio = getScreenRatio();
193
    mSolvedFunctionIndex = getSolvedFunctionIndex();
194
    mBasicAngles = getBasicAngles();
195
    mObjectQuats = getQuats();
196
    mNumQuats = mObjectQuats.length;
197
    mOrigPos = getCubitPositions(mNumLayers);
198

    
199
    int numAxis = mAxis.length;
200
    mMaxNumLayers = -1;
201
    mCuts = getCuts(mNumLayers);
202
    mNumCuts = new int[numAxis];
203
    for(int i=0; i<numAxis; i++)
204
      {
205
      if( mMaxNumLayers<mNumLayers[i] ) mMaxNumLayers = mNumLayers[i];
206
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
207
      }
208

    
209
    mNumCubits = mOrigPos.length;
210
    mNumFaceColors = getNumFaceColors();
211
    mNumAxis = mAxis.length;
212

    
213
    int scramblingType = getScrambleType();
214
    ScrambleState[] states = getScrambleStates();
215
    mScrambler = new ObjectScrambler(scramblingType, mNumAxis,mNumLayers,states);
216

    
217
    boolean bandaged=false;
218

    
219
    for( int c=0; c<mNumCubits; c++)
220
      {
221
      if( mOrigPos[c].length>3 )
222
        {
223
        bandaged=true;
224
        break;
225
        }
226
      }
227
    mIsBandaged = bandaged;
228
    mQuatDebug = new int[mNumCubits];
229

    
230
    mRotationAngle= new Dynamic1D();
231
    mRotationAxis = new Static3D(1,0,0);
232
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
233

    
234
    mRotationAngleStatic = new Static1D(0);
235
    mRotationAngleMiddle = new Static1D(0);
236
    mRotationAngleFinal  = new Static1D(0);
237

    
238
    mObjectScale = new Static3D(scale,scale,scale);
239
    setObjectRatioNow(scale,720);
240

    
241
    mEffects = new DistortedEffects();
242
    createQuaternionEffects();
243

    
244
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
245
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
246
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
247

    
248
    boolean fromDMESH = (stream!=null && meshState==MESH_NICE);
249
    getQuatsAndShapes(fromDMESH,fromJSON);
250
    createMeshAndCubits(stream,meshState,fromDMESH);
251
    setUpTextures(fromDMESH,fromJSON);
252
    createDataStructuresForSolved();
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 void createQuaternionEffects()
265
    {
266
    if( mNumQuats<=ObjectControl.MAX_QUATS )
267
      {
268
      mIsInMixupMode = false;
269

    
270
      for( int q=0; q<mNumQuats; q++)
271
        {
272
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mObjectQuats[q],CENTER);
273
        vq.setMeshAssociation(0,q);
274
        mEffects.apply(vq);
275
        }
276
      }
277
    else if( mNumCubits<=ObjectControl.MAX_QUATS )
278
      {
279
      mIsInMixupMode = true;
280
      mMixupModeQuats = new Static4D[mNumCubits];
281

    
282
      for( int q=0; q<mNumCubits; q++)
283
        {
284
        mMixupModeQuats[q] = new Static4D(mObjectQuats[0]);
285
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mMixupModeQuats[q],CENTER);
286
        vq.setMeshAssociation(0,q);
287
        mEffects.apply(vq);
288
        }
289
      }
290
    else
291
      {
292
      android.util.Log.e("D", "object has too many quaternions ("+mNumQuats+") or too many cubits ("+mNumCubits+")");
293
      }
294
    }
295

    
296
///////////////////////////////////////////////////////////////////////////////////////////////////
297

    
298
  private Static3D getPos(float[] origPos)
299
    {
300
    int len = origPos.length/3;
301
    float sumX = 0.0f;
302
    float sumY = 0.0f;
303
    float sumZ = 0.0f;
304

    
305
    for(int i=0; i<len; i++)
306
      {
307
      sumX += origPos[3*i  ];
308
      sumY += origPos[3*i+1];
309
      sumZ += origPos[3*i+2];
310
      }
311

    
312
    sumX /= len;
313
    sumY /= len;
314
    sumZ /= len;
315

    
316
    return new Static3D(sumX,sumY,sumZ);
317
    }
318

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

    
321
  private void createOuterFaces()
322
    {
323
    for(int v=0; v<mNumCubitVariants; v++)
324
      {
325
      int[][] indices = mShapes[v].getVertIndices();
326
      int faces = indices.length;
327
      mVariantFaceIsOuter[v] = new int[faces];
328
      }
329

    
330
    for( int cubit=0; cubit<mNumCubits; cubit++)
331
      {
332
      int variant = getCubitVariant(cubit,mNumLayers);
333
      int[][] indices = mShapes[variant].getVertIndices();
334
      int numFaces = indices.length;
335

    
336
      for(int face=0; face<numFaces; face++)
337
        if( getCubitFaceColor(cubit,face)>=0 )
338
          {
339
          mVariantFaceIsOuter[variant][face] = 1;
340
          }
341
      }
342
    }
343

    
344
///////////////////////////////////////////////////////////////////////////////////////////////////
345

    
346
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
347
    {
348
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
349

    
350
    if( !fromDMESH || !fromJSON )
351
      {
352
      FactoryCubit factory = FactoryCubit.getInstance();
353
      factory.clear();
354

    
355
      mOrigQuat = new Static4D[mNumCubits];
356
      for(int i=0; i<mNumCubits; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
357

    
358
      mShapes = new ObjectShape[mNumCubitVariants];
359
      for(int i=0; i<mNumCubitVariants; i++) mShapes[i] = getObjectShape(i);
360
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
361
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
362

    
363
      if( !fromJSON )
364
        {
365
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
366
        createOuterFaces();
367
        }
368

    
369
      if( fromDMESH )
370
        {
371
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
372
        }
373
      }
374
    }
375

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

    
378
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH)
379
    {
380
    mCubits = new Cubit[mNumCubits];
381

    
382
    if( fromDMESH )
383
      {
384
      DataInputStream dos = new DataInputStream(stream);
385
      mMesh = new MeshFile(dos);
386

    
387
      try
388
        {
389
        stream.close();
390
        }
391
      catch(IOException e)
392
        {
393
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
394
        }
395
      }
396
    else
397
      {
398
      MeshBase[] cubitMesh = new MeshBase[mNumCubits];
399

    
400
      for(int i=0; i<mNumCubits; i++)
401
        {
402
        cubitMesh[i] = createCubitMesh(i,mNumLayers,meshState,mNumCubitFaces);
403
        Static3D pos = getPos(mOrigPos[i]);
404
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
405
        }
406

    
407
      mMesh = new MeshJoined(cubitMesh);
408
      }
409

    
410
    for(int i=0; i<mNumCubits; i++)
411
      {
412
      mCubits[i] = new Cubit(this,mOrigPos[i], mNumAxis);
413
      setCubitQuat(i,mCubits[i].computeAssociation(),0);
414
      }
415
    }
416

    
417
///////////////////////////////////////////////////////////////////////////////////////////////////
418

    
419
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState, int numComponents)
420
    {
421
    int variant = getCubitVariant(cubit,numLayers);
422

    
423
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
424

    
425
    if( mMeshes[variant]==null )
426
      {
427
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
428
      FactoryCubit factory = FactoryCubit.getInstance();
429
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
430
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,meshState, numComponents);
431
      }
432

    
433
    MeshBase mesh = mMeshes[variant].copy(true);
434
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
435
    mesh.apply(quat,0xffffffff,0);
436

    
437
    return mesh;
438
    }
439

    
440
///////////////////////////////////////////////////////////////////////////////////////////////////
441

    
442
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
443
    {
444
    mTexture = new DistortedTexture();
445

    
446
    if( fromJSON )
447
      {
448
      mNumStickerTypes = getNumStickerTypes();
449
      mNumCubitFaces = getNumCubitFaces();
450
      }
451
    else
452
      {
453
      FactoryCubit factory = FactoryCubit.getInstance();
454
      mStickerCoords   = factory.getStickerCoords();
455
      mStickerVariants = factory.getStickerVariants();
456
      mStickerScales   = factory.getStickerScales();
457
      adjustStickerCoords();
458
      mNumStickerTypes = (mStickerCoords==null ? 0 : mStickerCoords.length);
459
      }
460

    
461
    mNumTextures= mNumFaceColors *mNumStickerTypes;
462
    mNumTexCols = NUM_STICKERS_IN_ROW;
463
    mNumTexRows = (mNumTextures+1)/NUM_STICKERS_IN_ROW;
464
    if( mNumTexCols*mNumTexRows < mNumTextures+1 ) mNumTexRows++;
465

    
466
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
467
    setTexture();
468
    }
469

    
470
///////////////////////////////////////////////////////////////////////////////////////////////////
471

    
472
  private int getMultQuat(int index1, int index2)
473
    {
474
    if( mQuatMult==null )
475
      {
476
      mQuatMult = new int[mNumQuats][mNumQuats];
477

    
478
      for(int i=0; i<mNumQuats; i++)
479
        for(int j=0; j<mNumQuats; j++) mQuatMult[i][j] = -1;
480
      }
481

    
482
    if( mQuatMult[index1][index2]==-1 )
483
      {
484
      mQuatMult[index1][index2] = mulQuat(index1,index2);
485
      }
486

    
487
    return mQuatMult[index1][index2];
488
    }
489

    
490
///////////////////////////////////////////////////////////////////////////////////////////////////
491

    
492
  public InitData getInitData()
493
    {
494
    return mInitData;
495
    }
496

    
497
///////////////////////////////////////////////////////////////////////////////////////////////////
498

    
499
  public boolean isInIconMode()
500
    {
501
    return mIconMode==MODE_ICON;
502
    }
503

    
504
///////////////////////////////////////////////////////////////////////////////////////////////////
505

    
506
  public int getVariantFaceColor(int variant, int face)
507
    {
508
    return face>=mStickerVariants[variant].length ? -1 : mStickerVariants[variant][face];
509
    }
510

    
511
///////////////////////////////////////////////////////////////////////////////////////////////////
512

    
513
  public boolean shouldResetTextureMaps()
514
    {
515
    return false;
516
    }
517

    
518
///////////////////////////////////////////////////////////////////////////////////////////////////
519

    
520
  private void createDataStructuresForSolved()
521
    {
522
    mTmpQuats = new int[mNumQuats];
523
    mSolvedQuats = getSolvedQuats();
524
    }
525

    
526
///////////////////////////////////////////////////////////////////////////////////////////////////
527
// This is used to build internal data structures for the generic 'isSolved()'
528
//
529
// if this is an internal cubit (all faces black): return -1
530
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
531
// Color index, i.e. the index into the 'FACE_COLORS' table.
532
// else (edge or corner cubit, more than one non-black face): return -2.
533

    
534
  protected int retCubitSolvedStatus(int cubit)
535
    {
536
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
537
    int variant = getCubitVariant(cubit,mNumLayers);
538

    
539
    for(int face=0; face<mNumCubitFaces; face++)
540
      {
541
      varColor = getVariantFaceColor(variant,face);
542
      int numFaces = mCubitFaceColors[cubit].length;
543
      cubColor = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
544

    
545
      if( varColor>=0 && cubColor>=0 )
546
        {
547
        numNonBlack++;
548
        nonBlackIndex = cubColor;
549
        }
550
      }
551

    
552
    if( numNonBlack==0 ) return -1;
553
    if( numNonBlack>=2 ) return -2;
554

    
555
    return nonBlackIndex;
556
    }
557

    
558
///////////////////////////////////////////////////////////////////////////////////////////////////
559

    
560
  private boolean sticksOut(Static3D[] faceAxis, float[] dist, float x, float y, float z )
561
    {
562
    final float MAXERR = 0.05f;
563
    int numAxis = dist.length;
564

    
565
    for(int i=0; i<numAxis; i++)
566
      {
567
      Static3D ax = faceAxis[i];
568
      float len = ax.get0()*x + ax.get1()*y + ax.get2()*z;
569
      if( len>mSize*dist[i]+MAXERR ) return true;
570
      }
571

    
572
    return false;
573
    }
574

    
575
///////////////////////////////////////////////////////////////////////////////////////////////////
576

    
577
  private boolean doesNotStickOut(int variant, float px, float py, float pz, float[] tmp, Static4D quat)
578
    {
579
    ObjectShape shape = getObjectShape(variant);
580
    float[][] vertices = shape.getVertices();
581
    Static3D[] axis = getFaceAxis();
582
    float[] dist3D = getDist3D(mNumLayers);
583

    
584
    for( float[] vertex : vertices)
585
      {
586
      float x = vertex[0];
587
      float y = vertex[1];
588
      float z = vertex[2];
589

    
590
      QuatHelper.rotateVectorByQuat(tmp, x, y, z, 1, quat);
591

    
592
      float mx = tmp[0] + px;
593
      float my = tmp[1] + py;
594
      float mz = tmp[2] + pz;
595

    
596
      if( sticksOut(axis, dist3D, mx,my,mz) ) return false;
597
      }
598

    
599
    return true;
600
    }
601

    
602
///////////////////////////////////////////////////////////////////////////////////////////////////
603

    
604
  private float computeAvg(float[] pos, int offset)
605
    {
606
    int len = pos.length/3;
607
    float ret=0.0f;
608
    for(int i=0; i<len; i++) ret += pos[3*i+offset];
609
    ret /= len;
610

    
611
    return ret;
612
    }
613

    
614
///////////////////////////////////////////////////////////////////////////////////////////////////
615

    
616
  protected void displayCubitQuats()
617
    {
618
    StringBuilder builder = new StringBuilder();
619
    float[] tmp = new float[4];
620
    float ERR = 0.01f;
621

    
622
    for(int cubit=0; cubit<mNumCubits; cubit++)
623
      {
624
      builder.append(cubit);
625
      builder.append(" : ");
626

    
627
      int refCubit,variant = getCubitVariant(cubit,mNumLayers);
628

    
629
      for(refCubit=0; refCubit<mNumCubits; refCubit++)
630
        {
631
        if( getCubitVariant(refCubit,mNumLayers)==variant ) break;
632
        }
633

    
634
      float[] curpos = mOrigPos[cubit];
635
      float[] refpos = mOrigPos[refCubit];
636
      float refX = computeAvg(refpos,0);
637
      float refY = computeAvg(refpos,1);
638
      float refZ = computeAvg(refpos,2);
639
      float curX = computeAvg(curpos,0);
640
      float curY = computeAvg(curpos,1);
641
      float curZ = computeAvg(curpos,2);
642

    
643
      for(int quat=0; quat<mNumQuats; quat++)
644
        {
645
        QuatHelper.rotateVectorByQuat(tmp,refX,refY,refZ,0,mObjectQuats[quat]);
646

    
647
        float dx = tmp[0]-curX;
648
        float dy = tmp[1]-curY;
649
        float dz = tmp[2]-curZ;
650

    
651
        if( dx>-ERR && dx<ERR && dy>-ERR && dy<ERR && dz>-ERR && dz<ERR )
652
          {
653
          if( doesNotStickOut(variant,curX,curY,curZ,tmp,mObjectQuats[quat]) )
654
            {
655
            builder.append(quat);
656
            builder.append(',');
657
            }
658
          else
659
            {
660
            android.util.Log.e("D", "cubit: "+cubit+" quat: "+quat+" : center correct, but shape sticks out");
661
            }
662
          }
663
        }
664

    
665
      builder.append('\n');
666
      }
667

    
668
    android.util.Log.e("D", "cubitQuats: \n"+builder.toString() );
669
    }
670

    
671
///////////////////////////////////////////////////////////////////////////////////////////////////
672

    
673
  protected int[] buildSolvedQuats(Static3D faceAx)
674
    {
675
    final float MAXD = 0.0001f;
676
    float x = faceAx.get0();
677
    float y = faceAx.get1();
678
    float z = faceAx.get2();
679
    float a,dx,dy,dz,qx,qy,qz;
680
    Static4D quat;
681
    int place = 0;
682

    
683
    for(int q=1; q<mNumQuats; q++)
684
      {
685
      quat = mObjectQuats[q];
686
      qx = quat.get0();
687
      qy = quat.get1();
688
      qz = quat.get2();
689

    
690
           if( x!=0.0f ) { a = qx/x; }
691
      else if( y!=0.0f ) { a = qy/y; }
692
      else               { a = qz/z; }
693

    
694
      dx = a*x-qx;
695
      dy = a*y-qy;
696
      dz = a*z-qz;
697

    
698
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
699
        {
700
        mTmpQuats[place++] = q;
701
        }
702
      }
703

    
704
    if( place!=0 )
705
      {
706
      int[] ret = new int[place];
707
      System.arraycopy(mTmpQuats,0,ret,0,place);
708
      return ret;
709
      }
710

    
711
    return null;
712
    }
713

    
714
///////////////////////////////////////////////////////////////////////////////////////////////////
715

    
716
  public int[][] getSolvedQuats()
717
    {
718
    int[] groups = new int[mNumCubits];
719
    int numGroups = 1;
720
    int numFirst  = 0;
721

    
722
    for(int cubit=0; cubit<mNumCubits; cubit++)
723
      {
724
      groups[cubit] = retCubitSolvedStatus(cubit);
725
      if( groups[cubit]>=0 ) numGroups++;
726
      else                   numFirst++;
727
      }
728

    
729
    int firstIndex = 1;
730
    int groupIndex = 1;
731
    int[][] solvedQuats = new int[numGroups][];
732
    solvedQuats[0] = new int[1+numFirst];
733
    solvedQuats[0][0] = numFirst;
734
    Static3D[] axis = getFaceAxis();
735

    
736
    for(int cubit=0; cubit<mNumCubits; cubit++)
737
      {
738
      int group = groups[cubit];
739

    
740
      if( group<0 )
741
        {
742
        solvedQuats[0][firstIndex] = cubit;
743
        firstIndex++;
744
        }
745
      else
746
        {
747
        int[] quats = buildSolvedQuats(axis[group]);
748
        int len = quats==null ? 0 : quats.length;
749
        solvedQuats[groupIndex] = new int[2+len];
750
        solvedQuats[groupIndex][0] = 1;
751
        solvedQuats[groupIndex][1] = cubit;
752
        for(int i=0; i<len; i++) solvedQuats[groupIndex][i+2] = quats[i];
753
        groupIndex++;
754
        }
755
      }
756
/*
757
    String dbg = "SOLVED GROUPS:\n";
758

    
759
    for(int g=0; g<numGroups; g++)
760
      {
761
      int len = solvedQuats[g].length;
762
      for(int i=0; i<len; i++) dbg += (" "+solvedQuats[g][i]);
763
      dbg+="\n";
764
      }
765

    
766
    android.util.Log.e("D", dbg);
767
*/
768
    return solvedQuats;
769
    }
770

    
771
///////////////////////////////////////////////////////////////////////////////////////////////////
772

    
773
  public int getSolvedFunctionIndex()
774
    {
775
    return 0;
776
    }
777

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

    
783
  private boolean isSolvedCentersOnly()
784
    {
785
    int numGroups = mSolvedQuats.length;
786

    
787
    for(int group=1; group<numGroups; group++)
788
      {
789
      int numEntries= mSolvedQuats[group].length;
790
      int numCubits = mSolvedQuats[group][0];
791
      int firstCubit= mSolvedQuats[group][1];
792
      int firstQuat = mCubits[firstCubit].mQuatIndex;
793

    
794
      for(int cubit=2; cubit<=numCubits; cubit++)
795
        {
796
        int currCubit= mSolvedQuats[group][cubit];
797
        int currQuat = mCubits[currCubit].mQuatIndex;
798
        boolean isGood= (firstQuat==currQuat);
799

    
800
        for(int q=numCubits+1; !isGood && q<numEntries; q++)
801
          {
802
          int quat = mSolvedQuats[group][q];
803
          if( firstQuat == getMultQuat(currQuat,quat) ) isGood = true;
804
          }
805

    
806
        if( !isGood ) return false;
807
        }
808
      }
809

    
810
    return true;
811
    }
812

    
813
///////////////////////////////////////////////////////////////////////////////////////////////////
814

    
815
  private boolean isSolved0()
816
    {
817
    if( mSolvedQuats[0][0]==0 ) return isSolvedCentersOnly();
818

    
819
    for( int[] solvedQuat : mSolvedQuats )
820
      {
821
      int numCubits = solvedQuat[0];
822
      int firstCubit= solvedQuat[1];
823
      int quat = mCubits[firstCubit].mQuatIndex;
824

    
825
      for( int cubit=2; cubit<=numCubits; cubit++ )
826
        {
827
        int c = solvedQuat[cubit];
828
        if( quat != mCubits[c].mQuatIndex ) return false;
829
        }
830
      }
831

    
832
    int cubit= mSolvedQuats[0][1];
833
    int quat0= mCubits[cubit].mQuatIndex;
834
    int numGroups = mSolvedQuats.length;
835

    
836
    for(int group=1; group<numGroups; group++)
837
      {
838
      int firstCubit= mSolvedQuats[group][1];
839
      int currQuat  = mCubits[firstCubit].mQuatIndex;
840

    
841
      if( quat0==currQuat ) continue;
842

    
843
      boolean isGood= false;
844
      int numEntries= mSolvedQuats[group].length;
845
      int numCubits = mSolvedQuats[group][0];
846

    
847
      for(int q=numCubits+1; q<numEntries; q++)
848
        {
849
        int quat = mSolvedQuats[group][q];
850

    
851
        if( quat0 == getMultQuat(currQuat,quat) )
852
          {
853
          isGood = true;
854
          break;
855
          }
856
        }
857

    
858
      if( !isGood ) return false;
859
      }
860

    
861
    return true;
862
    }
863

    
864
///////////////////////////////////////////////////////////////////////////////////////////////////
865

    
866
  private int computeScramble(int quatNum, int centerNum)
867
    {
868
    float MAXDIFF = 0.01f;
869
    float[] center= mOrigPos[centerNum];
870
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
871
    Static4D result = QuatHelper.rotateVectorByQuat(sc,mObjectQuats[quatNum]);
872

    
873
    float x = result.get0();
874
    float y = result.get1();
875
    float z = result.get2();
876

    
877
    for(int c=0; c<mNumCubits; c++)
878
      {
879
      float[] cent = mOrigPos[c];
880

    
881
      float qx = cent[0] - x;
882
      float qy = cent[1] - y;
883
      float qz = cent[2] - z;
884

    
885
      if( qx>-MAXDIFF && qx<MAXDIFF &&
886
          qy>-MAXDIFF && qy<MAXDIFF &&
887
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
888
      }
889

    
890
    return -1;
891
    }
892

    
893
///////////////////////////////////////////////////////////////////////////////////////////////////
894
// Dino4 uses this. It is solved if and only if groups of cubits
895
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
896
// or
897
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
898
// are all the same color.
899

    
900
  private boolean isSolved1()
901
    {
902
    if( mScramble==null )
903
      {
904
      mScramble = new int[mNumQuats][mNumCubits];
905
      mColors   = new int[mNumCubits];
906

    
907
      for(int q=0; q<mNumQuats; q++)
908
        for(int c=0; c<mNumCubits; c++) mScramble[q][c] = computeScramble(q,c);
909
      }
910

    
911
    if( mFaceMap==null )
912
      {
913
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
914
      }
915

    
916
    for(int c=0; c<mNumCubits; c++)
917
      {
918
      int index = mScramble[mCubits[c].mQuatIndex][c];
919
      mColors[index] = mFaceMap[c];
920
      }
921

    
922
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
923
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
924
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
925

    
926
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
927
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
928
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
929

    
930
    return false;
931
    }
932

    
933
///////////////////////////////////////////////////////////////////////////////////////////////////
934

    
935
  int computeRow(float[] pos, int axisIndex)
936
    {
937
    int ret=0;
938
    int len = pos.length / 3;
939
    Static3D axis = mAxis[axisIndex];
940
    float axisX = axis.get0();
941
    float axisY = axis.get1();
942
    float axisZ = axis.get2();
943
    float casted;
944

    
945
    for(int i=0; i<len; i++)
946
      {
947
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
948
      ret |= computeSingleRow(axisIndex,casted);
949
      }
950

    
951
    return ret;
952
    }
953

    
954
///////////////////////////////////////////////////////////////////////////////////////////////////
955

    
956
  private int computeSingleRow(int axisIndex,float casted)
957
    {
958
    int num = mNumCuts[axisIndex];
959

    
960
    for(int i=0; i<num; i++)
961
      {
962
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
963
      }
964

    
965
    return (1<<num);
966
    }
967

    
968
///////////////////////////////////////////////////////////////////////////////////////////////////
969

    
970
  private boolean wasRotateApplied()
971
    {
972
    return mEffects.exists(mRotateEffect.getID());
973
    }
974

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

    
977
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
978
    {
979
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
980
    }
981

    
982
///////////////////////////////////////////////////////////////////////////////////////////////////
983
// note the minus in front of the sin() - we rotate counterclockwise
984
// when looking towards the direction where the axis increases in values.
985

    
986
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
987
    {
988
    Static3D axis = mAxis[axisIndex];
989

    
990
    while( angleInDegrees<0 ) angleInDegrees += 360;
991
    angleInDegrees %= 360;
992
    
993
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
994
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
995

    
996
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
997
    }
998

    
999
///////////////////////////////////////////////////////////////////////////////////////////////////
1000

    
1001
  private synchronized void setupPosition(int[][] moves)
1002
    {
1003
    if( moves!=null )
1004
      {
1005
      Static4D quat;
1006
      int index, axis, row, rowBitmap, angle;
1007

    
1008
      for(int[] move: moves)
1009
        {
1010
        axis     = move[0];
1011
        rowBitmap= computeBitmapFromRow( move[1],axis );
1012
        row      = computeRowFromBitmap( move[1] );
1013
        angle    = move[2]*(360/mBasicAngles[axis][row]);   // this assumes that all layers from
1014
                                                            // the bitmap have the same BasicAngle.
1015
                                                            // at the moment this is always true as
1016
                                                            // there are no bandaged objects with
1017
                                                            // different per-layer BasicAngles.
1018
        quat     = makeQuaternion(axis,angle);
1019

    
1020
        for(int j=0; j<mNumCubits; j++)
1021
          if( belongsToRotation(j,axis,rowBitmap) )
1022
            {
1023
            index = mCubits[j].removeRotationNow(quat);
1024
            setCubitQuat(j,mCubits[j].computeAssociation(),index);
1025
            }
1026
        }
1027
      }
1028
    }
1029

    
1030
///////////////////////////////////////////////////////////////////////////////////////////////////
1031

    
1032
  public int getScrambleType()
1033
    {
1034
    return 0;
1035
    }
1036

    
1037
///////////////////////////////////////////////////////////////////////////////////////////////////
1038

    
1039
  int computeBitmapFromRow(int rowBitmap, int axis)
1040
    {
1041
    if( mIsBandaged )
1042
      {
1043
      int bitmap, initBitmap=0;
1044

    
1045
      while( initBitmap!=rowBitmap )
1046
        {
1047
        initBitmap = rowBitmap;
1048

    
1049
        for(int cubit=0; cubit<mNumCubits; cubit++)
1050
          {
1051
          bitmap = mCubits[cubit].getRotRow(axis);
1052
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
1053
          }
1054
        }
1055
      }
1056

    
1057
    return rowBitmap;
1058
    }
1059

    
1060
///////////////////////////////////////////////////////////////////////////////////////////////////
1061

    
1062
  private int computeRowFromBitmap(int rowBitmap)
1063
    {
1064
    int index = 0;
1065

    
1066
    while(index<32)
1067
      {
1068
      if( (rowBitmap&0x1) != 0 ) return index;
1069
      rowBitmap>>=1;
1070
      index++;
1071
      }
1072
    return 0;
1073
    }
1074

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

    
1079
  void clampPos(float[] pos, int offset)
1080
    {
1081
    float currError, minError = Float.MAX_VALUE;
1082
    int minErrorIndex1 = -1;
1083
    int minErrorIndex2 = -1;
1084

    
1085
    float x = pos[offset  ];
1086
    float y = pos[offset+1];
1087
    float z = pos[offset+2];
1088

    
1089
    float xo,yo,zo;
1090

    
1091
    for(int i=0; i<mNumCubits; i++)
1092
      {
1093
      int len = mOrigPos[i].length / 3;
1094

    
1095
      for(int j=0; j<len; j++)
1096
        {
1097
        xo = mOrigPos[i][3*j  ];
1098
        yo = mOrigPos[i][3*j+1];
1099
        zo = mOrigPos[i][3*j+2];
1100

    
1101
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
1102

    
1103
        if( currError<minError )
1104
          {
1105
          minError = currError;
1106
          minErrorIndex1 = i;
1107
          minErrorIndex2 = j;
1108
          }
1109
        }
1110
      }
1111

    
1112
    if( minError< 0.1f ) // TODO: 0.1 ?
1113
      {
1114
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
1115
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
1116
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
1117
      }
1118
    }
1119

    
1120
///////////////////////////////////////////////////////////////////////////////////////////////////
1121
// remember about the double cover or unit quaternions!
1122

    
1123
  int mulQuat(int q1, int q2)
1124
    {
1125
    Static4D result = QuatHelper.quatMultiply(mObjectQuats[q1],mObjectQuats[q2]);
1126

    
1127
    float rX = result.get0();
1128
    float rY = result.get1();
1129
    float rZ = result.get2();
1130
    float rW = result.get3();
1131

    
1132
    final float MAX_ERROR = 0.1f;
1133
    float dX,dY,dZ,dW;
1134

    
1135
    for(int i=0; i<mNumQuats; i++)
1136
      {
1137
      dX = mObjectQuats[i].get0() - rX;
1138
      dY = mObjectQuats[i].get1() - rY;
1139
      dZ = mObjectQuats[i].get2() - rZ;
1140
      dW = mObjectQuats[i].get3() - rW;
1141

    
1142
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1143
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1144
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1145
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1146

    
1147
      dX = mObjectQuats[i].get0() + rX;
1148
      dY = mObjectQuats[i].get1() + rY;
1149
      dZ = mObjectQuats[i].get2() + rZ;
1150
      dW = mObjectQuats[i].get3() + rW;
1151

    
1152
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1153
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1154
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1155
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1156
      }
1157

    
1158
    return -1;
1159
    }
1160

    
1161
///////////////////////////////////////////////////////////////////////////////////////////////////
1162

    
1163
  private float getAngle()
1164
    {
1165
    int pointNum = mRotationAngle.getNumPoints();
1166

    
1167
    if( pointNum>=1 )
1168
      {
1169
      return mRotationAngle.getPoint(pointNum-1).get0();
1170
      }
1171
    else
1172
      {
1173
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
1174
      return 0;
1175
      }
1176
    }
1177

    
1178
///////////////////////////////////////////////////////////////////////////////////////////////////
1179

    
1180
  void setLibInterface(ObjectLibInterface inter)
1181
    {
1182
    mInterface = inter;
1183
    }
1184

    
1185
///////////////////////////////////////////////////////////////////////////////////////////////////
1186

    
1187
  void initializeObject(int[][] moves)
1188
    {
1189
    solve();
1190
    setupPosition(moves);
1191
    }
1192

    
1193
///////////////////////////////////////////////////////////////////////////////////////////////////
1194

    
1195
  synchronized void removeRotationNow()
1196
    {
1197
    float angle = getAngle();
1198
    double nearestAngleInRadians = angle*Math.PI/180;
1199
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
1200
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
1201
    float axisX = mAxis[mCurrentRotAxis].get0();
1202
    float axisY = mAxis[mCurrentRotAxis].get1();
1203
    float axisZ = mAxis[mCurrentRotAxis].get2();
1204
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
1205

    
1206
    mRotationAngle.removeAll();
1207
    mRotationAngleStatic.set0(0);
1208

    
1209
    for(int i=0; i<mNumCubits; i++)
1210
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
1211
        {
1212
        int index = mCubits[i].removeRotationNow(quat);
1213
        setCubitQuat(i,mCubits[i].computeAssociation(),index);
1214
        }
1215
    }
1216

    
1217
///////////////////////////////////////////////////////////////////////////////////////////////////
1218

    
1219
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
1220
    {
1221
    if( wasRotateApplied() )
1222
      {
1223
      float angle = getAngle();
1224
      mRotationAngleStatic.set0(angle);
1225
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1226
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1227

    
1228
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1229
      mRotationAngle.resetToBeginning();
1230
      mRotationAngle.removeAll();
1231
      mRotationAngle.add(mRotationAngleStatic);
1232
      mRotationAngle.add(mRotationAngleMiddle);
1233
      mRotationAngle.add(mRotationAngleFinal);
1234
      mRotateEffect.notifyWhenFinished(listener);
1235

    
1236
      return mRotateEffect.getID();
1237
      }
1238

    
1239
    return 0;
1240
    }
1241

    
1242
///////////////////////////////////////////////////////////////////////////////////////////////////
1243

    
1244
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1245
    {
1246
    if( wasRotateApplied() )
1247
      {
1248
      mCurrentRotAxis = axis;
1249
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1250

    
1251
      mRotationAngleStatic.set0(0.0f);
1252
      mRotationAxis.set( mAxis[axis] );
1253
      mRotationAngle.setDuration(durationMillis);
1254
      mRotationAngle.resetToBeginning();
1255
      mRotationAngle.add(new Static1D(0));
1256
      mRotationAngle.add(new Static1D(angle));
1257
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1258
      mRotateEffect.notifyWhenFinished(listener);
1259

    
1260
      return mRotateEffect.getID();
1261
      }
1262

    
1263
    return 0;
1264
    }
1265

    
1266
///////////////////////////////////////////////////////////////////////////////////////////////////
1267

    
1268
  void continueRotation(float angleInDegrees)
1269
    {
1270
    mRotationAngleStatic.set0(angleInDegrees);
1271
    }
1272

    
1273
///////////////////////////////////////////////////////////////////////////////////////////////////
1274

    
1275
  synchronized void beginNewRotation(int axis, int row )
1276
    {
1277
    if( axis<0 || axis>=mNumAxis )
1278
      {
1279
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1280
      return;
1281
      }
1282
    if( row<0 || row>=mNumLayers[axis] )
1283
      {
1284
      android.util.Log.e("object", "invalid rotation row: "+row);
1285
      return;
1286
      }
1287

    
1288
    mCurrentRotAxis = axis;
1289
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1290
    mRotationAngleStatic.set0(0.0f);
1291
    mRotationAxis.set( mAxis[axis] );
1292
    mRotationAngle.add(mRotationAngleStatic);
1293
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1294
    }
1295

    
1296
///////////////////////////////////////////////////////////////////////////////////////////////////
1297

    
1298
  void setTextureMap(int cubit, int face, int newColor)
1299
    {
1300
    final float ratioW = 1.0f/mNumTexCols;
1301
    final float ratioH = 1.0f/mNumTexRows;
1302
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1303
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1304
    int col = newColor%mNumTexCols;
1305

    
1306
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1307
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1308
    }
1309

    
1310
///////////////////////////////////////////////////////////////////////////////////////////////////
1311

    
1312
  private int getCubitFaceColor(int cubit, int face)
1313
    {
1314
    int puzzleFace = getCubitFaceMap(cubit,face);
1315
    if( puzzleFace>=0 ) puzzleFace %= mNumFaceColors;
1316
    return puzzleFace;
1317
    }
1318

    
1319
///////////////////////////////////////////////////////////////////////////////////////////////////
1320

    
1321
  public int getCubitFaceMap(int cubit, int face)
1322
    {
1323
    int numFaces = mCubitFaceColors[cubit].length;
1324
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1325
    return puzzleFace<0 ? -1 : puzzleFace;
1326
    }
1327

    
1328
///////////////////////////////////////////////////////////////////////////////////////////////////
1329

    
1330
  void resetAllTextureMaps()
1331
    {
1332
    final float ratioW = 1.0f/mNumTexCols;
1333
    final float ratioH = 1.0f/mNumTexRows;
1334
    int cubColor, varColor, color, variant, row, col;
1335

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

    
1341
      for(int face=0; face<mNumCubitFaces; face++)
1342
        {
1343
        cubColor = getCubitFaceColor(cubit,face);
1344
        varColor = getVariantFaceColor(variant,face);
1345
        color    = cubColor<0 || varColor<0 ? mNumTextures : varColor*mNumFaceColors + cubColor;
1346
        row      = (mNumTexRows-1) - color/mNumTexCols;
1347
        col      = color%mNumTexCols;
1348

    
1349
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1350
        }
1351

    
1352
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1353
      }
1354
    }
1355

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

    
1358
  void releaseResources()
1359
    {
1360
    mTexture.markForDeletion();
1361
    mMesh.markForDeletion();
1362
    mEffects.markForDeletion();
1363

    
1364
    for(int j=0; j<mNumCubits; j++)
1365
      {
1366
      mCubits[j].releaseResources();
1367
      }
1368
    }
1369

    
1370
///////////////////////////////////////////////////////////////////////////////////////////////////
1371

    
1372
  private void setCubitQuat(int cubit, int andAssociation, int equAssociation)
1373
    {
1374
    if( !mIsInMixupMode )
1375
      {
1376
      mMesh.setEffectAssociation(cubit,andAssociation,equAssociation);
1377
      }
1378
    else
1379
      {
1380
      mMesh.setEffectAssociation(cubit,andAssociation,cubit);
1381
      Static4D tmp = mObjectQuats[equAssociation];
1382
      mMixupModeQuats[cubit].set(tmp);
1383
      }
1384
    }
1385

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

    
1388
  synchronized void restorePreferences(SharedPreferences preferences)
1389
    {
1390
    boolean error = false;
1391
    String key = getShortName();
1392

    
1393
    for(int i=0; i<mNumCubits; i++)
1394
      {
1395
      mQuatDebug[i] = mCubits[i].restorePreferences(key,preferences);
1396

    
1397
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1398
        {
1399
        mCubits[i].modifyCurrentPosition(mObjectQuats[mQuatDebug[i]]);
1400
        setCubitQuat(i,mCubits[i].computeAssociation(),mQuatDebug[i]);
1401
        }
1402
      else
1403
        {
1404
        error = true;
1405
        }
1406
      }
1407

    
1408
    if( error )
1409
      {
1410
      for(int i=0; i<mNumCubits; i++)
1411
        {
1412
        mCubits[i].solve();
1413
        setCubitQuat(i,mCubits[i].computeAssociation(),0);
1414
        }
1415
      }
1416
    }
1417

    
1418
///////////////////////////////////////////////////////////////////////////////////////////////////
1419

    
1420
  void savePreferences(SharedPreferences.Editor editor)
1421
    {
1422
    String key = getShortName();
1423
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(key,editor);
1424
    }
1425

    
1426
///////////////////////////////////////////////////////////////////////////////////////////////////
1427

    
1428
  public void removePreferences(SharedPreferences.Editor editor)
1429
    {
1430
    String key = getShortName();
1431
    for(int i=0; i<mNumCubits; i++) mCubits[i].removePreferences(key,editor);
1432
    }
1433

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

    
1436
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1437
    {
1438
    final float A = 0.8f;  // 0<A<1
1439

    
1440
    int prev = curr>0 ? curr-1 : len-1;
1441
    int next = curr<len-1 ? curr+1 : 0;
1442

    
1443
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1444
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1445
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1446
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1447

    
1448
    float len1= v1x*v1x+v1y*v1y;
1449
    float len2= v2x*v2x+v2y*v2y;
1450

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

    
1453
    return 1-A*cos;
1454
    }
1455

    
1456
///////////////////////////////////////////////////////////////////////////////////////////////////
1457

    
1458
  public ObjectSticker retSticker(int sticker)
1459
    {
1460
    if( mStickers==null )
1461
      {
1462
      float rad = getStickerRadius();
1463
      float str = getStickerStroke();
1464
      float[][] angles = getStickerAngles();
1465
      int numStickers = mStickerCoords.length;
1466
      mStickers = new ObjectSticker[numStickers];
1467

    
1468
      for(int s=0; s<numStickers; s++)
1469
        {
1470
        float scale = mStickerScales[s];
1471
        float radius = rad / scale;
1472
        float stroke = str / scale;
1473
        int len = mStickerCoords[s].length/2;
1474
        float[] radii = new float[len];
1475
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1476
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1477
        }
1478
      }
1479

    
1480
    return mStickers[sticker];
1481
    }
1482

    
1483
///////////////////////////////////////////////////////////////////////////////////////////////////
1484
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1485

    
1486
  public void adjustStickerCoords()
1487
    {
1488

    
1489
    }
1490

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

    
1493
  public Static4D[] getQuats()
1494
    {
1495
    if( mObjectQuats==null )
1496
      {
1497
      mObjectQuats = QuatGroupGenerator.computeGroup(mAxis,mBasicAngles);
1498
      }
1499

    
1500
    return mObjectQuats;
1501
    }
1502

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

    
1505
  public int getInternalColor()
1506
    {
1507
    return COLOR_INTERNAL;
1508
    }
1509

    
1510
///////////////////////////////////////////////////////////////////////////////////////////////////
1511
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1512

    
1513
  private void createTexture()
1514
    {
1515
    Paint paint = new Paint();
1516
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_4444);
1517
    Canvas canvas = new Canvas(mBitmap);
1518

    
1519
    paint.setAntiAlias(true);
1520
    paint.setTextAlign(Paint.Align.CENTER);
1521
    paint.setStyle(Paint.Style.FILL);
1522

    
1523
    paint.setColor(getInternalColor());
1524
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1525

    
1526
    int texture = 0;
1527
    FactorySticker factory = FactorySticker.getInstance();
1528

    
1529
    for(int row=0; row<mNumTexRows; row++)
1530
      for(int col=0; col<mNumTexCols; col++)
1531
        {
1532
        if( texture>=mNumTextures ) break;
1533
        ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1534
        int color = getColor(texture% mNumFaceColors);
1535
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, (mNumTexRows-row)*TEXTURE_HEIGHT, color, sticker);
1536
        texture++;
1537
        }
1538
    }
1539

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

    
1542
  void setTexture()
1543
    {
1544
    if( mBitmap==null ) createTexture();
1545

    
1546
    if( !mTexture.setTextureAlreadyInverted(mBitmap) )
1547
      {
1548
      int max = DistortedLibrary.getMaxTextureSize();
1549
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1550
      }
1551
    }
1552

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

    
1555
  void setObjectRatioNow(float sc, int nodeSize)
1556
    {
1557
    mObjectScreenRatio = sc;
1558
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1559
    mObjectScale.set(scale,scale,scale);
1560

    
1561
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1562
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1563
    }
1564

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

    
1567
  void setObjectRatio(float sizeChange, int nodeSize)
1568
    {
1569
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1570

    
1571
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1572
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1573

    
1574
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1575
    }
1576

    
1577
///////////////////////////////////////////////////////////////////////////////////////////////////
1578

    
1579
  void setNodeSize(int nodeSize)
1580
    {
1581
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1582
    }
1583

    
1584
///////////////////////////////////////////////////////////////////////////////////////////////////
1585

    
1586
  public float getRatio()
1587
    {
1588
    return mObjectScreenRatio;
1589
    }
1590

    
1591
///////////////////////////////////////////////////////////////////////////////////////////////////
1592

    
1593
  public float getObjectRatio()
1594
    {
1595
    return mObjectScreenRatio*mInitScreenRatio;
1596
    }
1597

    
1598
///////////////////////////////////////////////////////////////////////////////////////////////////
1599

    
1600
  boolean isSolved()
1601
    {
1602
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1603
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1604

    
1605
    return false;
1606
    }
1607

    
1608
///////////////////////////////////////////////////////////////////////////////////////////////////
1609

    
1610
  int computeNearestAngle(int basicAngle, float angle, float speed)
1611
    {
1612
    int nearestAngle = 360/basicAngle;
1613
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1614
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1615

    
1616
    if( tmp!=0 ) return nearestAngle*tmp;
1617

    
1618
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1619
    }
1620

    
1621
///////////////////////////////////////////////////////////////////////////////////////////////////
1622
// INTERNAL API - those are called from 'effects' package
1623
///////////////////////////////////////////////////////////////////////////////////////////////////
1624

    
1625
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1626
    {
1627
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total, getSignature() );
1628
    }
1629

    
1630
///////////////////////////////////////////////////////////////////////////////////////////////////
1631

    
1632
  public Static4D getRotationQuat()
1633
    {
1634
    return mQuat;
1635
    }
1636

    
1637
///////////////////////////////////////////////////////////////////////////////////////////////////
1638

    
1639
  public float getSize()
1640
    {
1641
    return mSize;
1642
    }
1643

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

    
1646
  public void apply(Effect effect, int position)
1647
    {
1648
    mEffects.apply(effect, position);
1649
    }
1650

    
1651
///////////////////////////////////////////////////////////////////////////////////////////////////
1652

    
1653
  public void remove(long effectID)
1654
    {
1655
    mEffects.abortById(effectID);
1656
    }
1657

    
1658
///////////////////////////////////////////////////////////////////////////////////////////////////
1659

    
1660
  public MeshBase getObjectMesh()
1661
    {
1662
    return mMesh;
1663
    }
1664

    
1665
///////////////////////////////////////////////////////////////////////////////////////////////////
1666

    
1667
  public DistortedEffects getObjectEffects()
1668
    {
1669
    return mEffects;
1670
    }
1671

    
1672
///////////////////////////////////////////////////////////////////////////////////////////////////
1673
// PUBLIC API
1674
///////////////////////////////////////////////////////////////////////////////////////////////////
1675

    
1676
  public int getCubitFaceColorIndex(int cubit, int face)
1677
    {
1678
    Static4D texMap = mMesh.getTextureMap(mNumFaceColors *cubit + face);
1679

    
1680
    int x = (int)(texMap.get0()/texMap.get2());
1681
    int y = (int)(texMap.get1()/texMap.get3());
1682

    
1683
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1684
    }
1685

    
1686
///////////////////////////////////////////////////////////////////////////////////////////////////
1687

    
1688
  public int[] getNumLayers()
1689
    {
1690
    return mNumLayers;
1691
    }
1692

    
1693
///////////////////////////////////////////////////////////////////////////////////////////////////
1694

    
1695
  public synchronized void solve()
1696
    {
1697
    for(int i=0; i<mNumCubits; i++)
1698
      {
1699
      mCubits[i].solve();
1700
      setCubitQuat(i,mCubits[i].computeAssociation(),0);
1701
      }
1702
    }
1703

    
1704
///////////////////////////////////////////////////////////////////////////////////////////////////
1705

    
1706
  public int getCubitQuatIndex(int cubit)
1707
    {
1708
    return (cubit>=0 && cubit<mNumCubits) ? mCubits[cubit].mQuatIndex : 0;
1709
    }
1710

    
1711
///////////////////////////////////////////////////////////////////////////////////////////////////
1712

    
1713
  public int getCubitRotRow(int cubit, int axis)
1714
    {
1715
    return mCubits[cubit].getRotRow(axis);
1716
    }
1717

    
1718
///////////////////////////////////////////////////////////////////////////////////////////////////
1719

    
1720
  public Bitmap getStickerBitmap()
1721
    {
1722
    return mBitmap;
1723
    }
1724

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

    
1727
  public DistortedNode getNode()
1728
    {
1729
    return mNode;
1730
    }
1731

    
1732
///////////////////////////////////////////////////////////////////////////////////////////////////
1733

    
1734
  public int getNumStickerTypes()
1735
    {
1736
    return mNumStickerTypes;
1737
    }
1738

    
1739
///////////////////////////////////////////////////////////////////////////////////////////////////
1740
// this is here only so it can be overridden in TwistyJSON soo that we can get this from JSON.
1741

    
1742
  public int getNumCubitFaces()
1743
    {
1744
    return 0;
1745
    }
1746

    
1747
///////////////////////////////////////////////////////////////////////////////////////////////////
1748

    
1749
  public TouchControl getTouchControl()
1750
    {
1751
    if( mTouchControl==null )
1752
      {
1753
      switch(getTouchControlType())
1754
        {
1755
        case TC_TETRAHEDRON      : mTouchControl = new TouchControlTetrahedron(this);
1756
                                   break;
1757
        case TC_HEXAHEDRON       : mTouchControl = new TouchControlHexahedron(this);
1758
                                   break;
1759
        case TC_OCTAHEDRON       : mTouchControl = new TouchControlOctahedron(this);
1760
                                   break;
1761
        case TC_DODECAHEDRON     : mTouchControl = new TouchControlDodecahedron(this);
1762
                                   break;
1763
        case TC_CUBOID           : int[] numLayers = getNumLayers();
1764
                                   mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1765
                                   break;
1766
        case TC_CHANGING_MIRROR  : mTouchControl = new TouchControlMirror(this);
1767
                                   break;
1768
        case TC_CHANGING_SQUARE  : mTouchControl = new TouchControlSquare(this);
1769
                                   break;
1770
        case TC_CHANGING_SHAPEMOD: mTouchControl = new TouchControlShapemod(this);
1771
                                   break;
1772
        }
1773
      }
1774
    return mTouchControl;
1775
    }
1776

    
1777
///////////////////////////////////////////////////////////////////////////////////////////////////
1778

    
1779
  protected void setReader(JsonReader reader)
1780
    {
1781
    // empty
1782
    }
1783

    
1784
///////////////////////////////////////////////////////////////////////////////////////////////////
1785
  // for JSON only
1786
  public abstract int getTouchControlType();
1787
  public abstract int getTouchControlSplit();
1788
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1789
  public abstract int[][][] getEnabled();
1790
  public abstract float[] getDist3D(int[] numLayers);
1791
  public abstract Static3D[] getFaceAxis();
1792
  public abstract ScrambleState[] getScrambleStates();
1793
  public abstract float[][] getCuts(int[] numLayers);
1794
  public abstract float getStickerRadius();
1795
  public abstract float getStickerStroke();
1796
  public abstract float[][] getStickerAngles();
1797
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1798
  public abstract ObjectShape getObjectShape(int variant);
1799
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
1800
  public abstract int getNumCubitVariants(int[] numLayers);
1801
  public abstract float[][] getCubitPositions(int[] numLayers);
1802
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
1803
  public abstract int getNumFaceColors();
1804
  public abstract float getScreenRatio();
1805
  public abstract int getColor(int face);
1806
  public abstract String getShortName();
1807
  public abstract ObjectSignature getSignature();
1808

    
1809
  // not only for JSON
1810
  public abstract Static3D[] getRotationAxis();
1811
  public abstract int[][] getBasicAngles();
1812
  public abstract int getNumFaces();
1813
  public abstract String getObjectName();
1814
  public abstract String getInventor();
1815
  public abstract int getYearOfInvention();
1816
  public abstract int getComplexity();
1817
  public abstract int getFOV();
1818
  public abstract String[][] getTutorials();
1819
  }
(12-12/13)