Project

General

Profile

Download (28.5 KB) Statistics
| Branch: | Tag: | Revision:

magiccube / src / main / java / org / distorted / objects / TwistyObject.java @ f0450fcc

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.objects;
21

    
22
import android.content.SharedPreferences;
23
import android.content.res.Resources;
24
import android.graphics.Bitmap;
25
import android.graphics.Canvas;
26
import android.graphics.Paint;
27

    
28
import com.google.firebase.crashlytics.FirebaseCrashlytics;
29

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

    
52
import java.io.DataInputStream;
53
import java.io.IOException;
54
import java.io.InputStream;
55
import java.util.Random;
56

    
57
///////////////////////////////////////////////////////////////////////////////////////////////////
58

    
59
public abstract class TwistyObject extends DistortedNode
60
  {
61
  static final int COLOR_YELLOW = 0xffffff00;
62
  static final int COLOR_WHITE  = 0xffffffff;
63
  static final int COLOR_BLUE   = 0xff0000ff;
64
  static final int COLOR_GREEN  = 0xff00bb00;
65
  static final int COLOR_RED    = 0xff990000;
66
  static final int COLOR_ORANGE = 0xffff6200;
67
  static final int COLOR_GREY   = 0xff727c7b;
68
  static final int COLOR_VIOLET = 0xff7700bb;
69
  static final int COLOR_BLACK  = 0xff000000;
70

    
71
  static final int TEXTURE_HEIGHT = 256;
72
  static final int NUM_STICKERS_IN_ROW = 4;
73

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

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

    
83
  private static final boolean mCreateFromDMesh = false;
84

    
85
  private static final Static3D CENTER = new Static3D(0,0,0);
86
  private static final int POST_ROTATION_MILLISEC = 500;
87

    
88
  final Static3D[] ROTATION_AXIS;
89
  final Static4D[] QUATS;
90
  final Cubit[] CUBITS;
91
  final int NUM_FACES;
92
  final int NUM_TEXTURES;
93
  final int NUM_CUBIT_FACES;
94
  final int NUM_AXIS;
95
  final int NUM_CUBITS;
96
  final float[] CUTS;
97
  final int NUM_CUTS;
98

    
99
  private static float mInitScreenRatio;
100
  private static float mObjectScreenRatio = 1.0f;
101

    
102
  private final int mNodeSize;
103
  private final Static3D[] mOrigPos;
104
  private final Static3D mNodeScale;
105
  private final Static4D mQuat;
106
  private final int mNumLayers, mRealSize;
107
  private final ObjectList mList;
108
  private final DistortedEffects mEffects;
109
  private final VertexEffectRotate mRotateEffect;
110
  private final Dynamic1D mRotationAngle;
111
  private final Static3D mRotationAxis;
112
  private final Static3D mObjectScale;
113
  private final int[] mQuatDebug;
114
  private final float mCameraDist;
115
  private int mNumTexRows, mNumTexCols;
116
  private int mRotRowBitmap;
117
  private int mRotAxis;
118
  private MeshBase mMesh;
119

    
120
  float[] mRowChances;
121
  Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
122
  DistortedTexture mTexture;
123
  MatrixEffectScale mScaleEffect;
124
  MatrixEffectQuaternion mQuatEffect;
125

    
126
///////////////////////////////////////////////////////////////////////////////////////////////////
127

    
128
  TwistyObject(int numLayers, int realSize, Static4D quat, DistortedTexture nodeTexture, MeshSquare nodeMesh,
129
               DistortedEffects nodeEffects, int[][] moves, ObjectList list, Resources res, int screenWidth)
130
    {
131
    super(nodeTexture,nodeEffects,nodeMesh);
132

    
133
    mNodeSize = screenWidth;
134

    
135
    resizeFBO(mNodeSize, (int)(NODE_RATIO*mNodeSize));
136

    
137
    mNumLayers = numLayers;
138
    mRealSize = realSize;
139
    mList = list;
140
    mOrigPos = getCubitPositions(mNumLayers);
141

    
142
    QUATS = getQuats();
143
    NUM_CUBITS  = mOrigPos.length;
144
    ROTATION_AXIS = getRotationAxis();
145
    NUM_AXIS = ROTATION_AXIS.length;
146
    mInitScreenRatio = getScreenRatio();
147
    NUM_FACES = getNumFaces();
148
    NUM_CUBIT_FACES = getNumCubitFaces();
149
    NUM_TEXTURES = getNumStickerTypes(mNumLayers)*NUM_FACES;
150
    CUTS = getCuts(mNumLayers);
151
    NUM_CUTS = CUTS.length;
152

    
153
    mQuatDebug = new int[NUM_CUBITS];
154

    
155
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
156
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
157

    
158
    mNodeScale= new Static3D(1,NODE_RATIO,1);
159
    mQuat = quat;
160

    
161
    mRowChances = getRowChances(mNumLayers);
162

    
163
    mRotationAngle= new Dynamic1D();
164
    mRotationAxis = new Static3D(1,0,0);
165
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
166

    
167
    mRotationAngleStatic = new Static1D(0);
168
    mRotationAngleMiddle = new Static1D(0);
169
    mRotationAngleFinal  = new Static1D(0);
170

    
171
    float scale  = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
172
    mObjectScale = new Static3D(scale,scale,scale);
173
    mScaleEffect = new MatrixEffectScale(mObjectScale);
174
    mQuatEffect  = new MatrixEffectQuaternion(quat, CENTER);
175

    
176
    MatrixEffectScale nodeScaleEffect = new MatrixEffectScale(mNodeScale);
177
    nodeEffects.apply(nodeScaleEffect);
178

    
179
    mNumTexCols = NUM_STICKERS_IN_ROW;
180
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
181

    
182
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
183

    
184
    CUBITS = new Cubit[NUM_CUBITS];
185
    createMeshAndCubits(list,res);
186

    
187
    mTexture = new DistortedTexture();
188
    mEffects = new DistortedEffects();
189

    
190
    int num_quats = QUATS.length;
191
    for(int q=0; q<num_quats; q++)
192
      {
193
      VertexEffectQuaternion vq = new VertexEffectQuaternion(QUATS[q],CENTER);
194
      vq.setMeshAssociation(0,q);
195
      mEffects.apply(vq);
196
      }
197

    
198
    mEffects.apply(mRotateEffect);
199
    mEffects.apply(mQuatEffect);
200
    mEffects.apply(mScaleEffect);
201

    
202
    // Now postprocessed effects (the glow when you solve an object) require component centers. In
203
    // order for the effect to be in front of the object, we need to set the center to be behind it.
204
    getMesh().setComponentCenter(0,0,0,-0.1f);
205

    
206
    attach( new DistortedNode(mTexture,mEffects,mMesh) );
207

    
208
    setupPosition(moves);
209

    
210
    float fov = list.getFOV();
211
    double halfFOV = fov * (Math.PI/360);
212
    mCameraDist = 0.5f*NODE_RATIO / (float)Math.tan(halfFOV);
213

    
214
    setProjection( fov, 0.1f);
215
    }
216

    
217
///////////////////////////////////////////////////////////////////////////////////////////////////
218

    
219
  private void createMeshAndCubits(ObjectList list, Resources res)
220
    {
221
    if( mCreateFromDMesh )
222
      {
223
      int sizeIndex = ObjectList.getSizeIndex(list.ordinal(),mNumLayers);
224
      int resourceID= list.getResourceIDs()[sizeIndex];
225

    
226
      InputStream is = res.openRawResource(resourceID);
227
      DataInputStream dos = new DataInputStream(is);
228
      mMesh = new MeshFile(dos);
229

    
230
      try
231
        {
232
        is.close();
233
        }
234
      catch(IOException e)
235
        {
236
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
237
        }
238

    
239
      for(int i=0; i<NUM_CUBITS; i++)
240
        {
241
        CUBITS[i] = new Cubit(this,mOrigPos[i]);
242
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
243
        }
244

    
245
      if( shouldResetTextureMaps() ) resetAllTextureMaps();
246
      }
247
    else
248
      {
249
      MeshBase[] cubitMesh = new MeshBase[NUM_CUBITS];
250

    
251
      for(int i=0; i<NUM_CUBITS; i++)
252
        {
253
        CUBITS[i] = new Cubit(this,mOrigPos[i]);
254
        cubitMesh[i] = createCubitMesh(i,mNumLayers);
255
        cubitMesh[i].apply(new MatrixEffectMove(mOrigPos[i]),1,0);
256
        cubitMesh[i].setEffectAssociation(0, CUBITS[i].computeAssociation(), 0);
257
        }
258

    
259
      mMesh = new MeshJoined(cubitMesh);
260
      resetAllTextureMaps();
261
      }
262
    }
263

    
264
///////////////////////////////////////////////////////////////////////////////////////////////////
265

    
266
  public void setObjectRatio(float sizeChange)
267
    {
268
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
269

    
270
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
271
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
272

    
273
    float scale = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
274
    mObjectScale.set(scale,scale,scale);
275
    }
276

    
277
///////////////////////////////////////////////////////////////////////////////////////////////////
278

    
279
  static float getObjectRatio()
280
    {
281
    return mObjectScreenRatio*mInitScreenRatio;
282
    }
283

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

    
286
  int computeRow(float x, float y, float z, int rotIndex)
287
    {
288
    Static3D axis = ROTATION_AXIS[rotIndex];
289
    float tmp = x*axis.get0() + y*axis.get1() + z*axis.get2();
290

    
291
    for(int i=0; i<NUM_CUTS; i++)
292
      {
293
      if( tmp<CUTS[i] ) return (1<<i);
294
      }
295

    
296
    return (1<<NUM_CUTS);
297
    }
298

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

    
301
  private boolean wasRotateApplied()
302
    {
303
    return mEffects.exists(mRotateEffect.getID());
304
    }
305

    
306
///////////////////////////////////////////////////////////////////////////////////////////////////
307

    
308
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
309
    {
310
    return (CUBITS[cubit].mRotationRow[axis] & rowBitmap) != 0;
311
    }
312

    
313
///////////////////////////////////////////////////////////////////////////////////////////////////
314
// note the minus in front of the sin() - we rotate counterclockwise
315
// when looking towards the direction where the axis increases in values.
316

    
317
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
318
    {
319
    Static3D axis = ROTATION_AXIS[axisIndex];
320

    
321
    while( angleInDegrees<0 ) angleInDegrees += 360;
322
    angleInDegrees %= 360;
323
    
324
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
325
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
326

    
327
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
328
    }
329

    
330
///////////////////////////////////////////////////////////////////////////////////////////////////
331

    
332
  private synchronized void setupPosition(int[][] moves)
333
    {
334
    if( moves!=null )
335
      {
336
      Static4D quat;
337
      int index, axis, rowBitmap, angle;
338
      int corr = (360/getBasicAngle());
339

    
340
      for(int[] move: moves)
341
        {
342
        axis     = move[0];
343
        rowBitmap= move[1];
344
        angle    = move[2]*corr;
345
        quat     = makeQuaternion(axis,angle);
346

    
347
        for(int j=0; j<NUM_CUBITS; j++)
348
          if( belongsToRotation(j,axis,rowBitmap) )
349
            {
350
            index = CUBITS[j].removeRotationNow(quat);
351
            mMesh.setEffectAssociation(j, CUBITS[j].computeAssociation(),index);
352
            }
353
        }
354
      }
355
    }
356

    
357
///////////////////////////////////////////////////////////////////////////////////////////////////
358

    
359
  int getCubitFaceColorIndex(int cubit, int face)
360
    {
361
    Static4D texMap = mMesh.getTextureMap(NUM_FACES*cubit + face);
362

    
363
    int x = (int)(texMap.get0()/texMap.get2());
364
    int y = (int)(texMap.get1()/texMap.get3());
365

    
366
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
367
    }
368

    
369
///////////////////////////////////////////////////////////////////////////////////////////////////
370
// Clamp all rotated positions to one of those original ones to avoid accumulating errors.
371

    
372
  void clampPos(Static3D pos)
373
    {
374
    float currError, minError = Float.MAX_VALUE;
375
    int minErrorIndex= -1;
376
    float x = pos.get0();
377
    float y = pos.get1();
378
    float z = pos.get2();
379
    float xo,yo,zo;
380

    
381
    for(int i=0; i<NUM_CUBITS; i++)
382
      {
383
      xo = mOrigPos[i].get0();
384
      yo = mOrigPos[i].get1();
385
      zo = mOrigPos[i].get2();
386

    
387
      currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
388

    
389
      if( currError<minError )
390
        {
391
        minError = currError;
392
        minErrorIndex = i;
393
        }
394
      }
395

    
396
    pos.set( mOrigPos[minErrorIndex] );
397
    }
398

    
399
///////////////////////////////////////////////////////////////////////////////////////////////////
400
// return if the Cubit, when rotated with its own mQuatScramble, would have looked any different
401
// then if it were rotated by quaternion 'quat'.
402
// No it is not so simple as the quats need to be the same - imagine a 4x4x4 cube where the two
403
// middle squares get interchanged. No visible difference!
404
//
405
// So: this is true iff the cubit
406
// a) is a corner or edge and the quaternions are the same
407
// b) is inside one of the faces and after rotations by both quats it ends up on the same face.
408

    
409
  boolean thereIsVisibleDifference(Cubit cubit, int quatIndex)
410
    {
411
    if ( cubit.mQuatIndex == quatIndex ) return false;
412

    
413
    int belongsToHowManyFaces = 0;
414
    int bitmap = (1<<(getNumLayers()-1)) + 1;
415

    
416
    for(int i=0; i<NUM_AXIS; i++)
417
      {
418
      if( (cubit.mRotationRow[i] & bitmap) != 0 ) belongsToHowManyFaces++;
419
      }
420

    
421
    switch(belongsToHowManyFaces)
422
      {
423
      case 0 : return false;  // 'inside' cubit that does not lie on any face
424
      case 1 :                // cubit that lies inside one of the faces
425
               Static3D orig = cubit.getOrigPosition();
426
               Static4D quat1 = QUATS[quatIndex];
427
               Static4D quat2 = QUATS[cubit.mQuatIndex];
428

    
429
               Static4D cubitCenter = new Static4D( orig.get0(), orig.get1(), orig.get2(), 0);
430
               Static4D rotated1 = RubikSurfaceView.rotateVectorByQuat( cubitCenter, quat1 );
431
               Static4D rotated2 = RubikSurfaceView.rotateVectorByQuat( cubitCenter, quat2 );
432

    
433
               int row1, row2;
434
               float x1 = rotated1.get0();
435
               float y1 = rotated1.get1();
436
               float z1 = rotated1.get2();
437
               float x2 = rotated2.get0();
438
               float y2 = rotated2.get1();
439
               float z2 = rotated2.get2();
440

    
441
               for(int i=0; i<NUM_AXIS; i++)
442
                 {
443
                 row1 = computeRow(x1,y1,z1,i);
444
                 row2 = computeRow(x2,y2,z2,i);
445

    
446
                 if( ((row1 & row2) & bitmap) != 0 ) return false;
447
                 }
448
               return true;
449

    
450
      default: return true;  // edge or corner
451
      }
452
    }
453

    
454
///////////////////////////////////////////////////////////////////////////////////////////////////
455
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
456

    
457
  public void createTexture()
458
    {
459
    Bitmap bitmap;
460

    
461
    Paint paint = new Paint();
462
    bitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
463
    Canvas canvas = new Canvas(bitmap);
464

    
465
    paint.setAntiAlias(true);
466
    paint.setTextAlign(Paint.Align.CENTER);
467
    paint.setStyle(Paint.Style.FILL);
468

    
469
    paint.setColor(COLOR_BLACK);
470
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
471

    
472
    int tex = 0;
473

    
474
    for(int row=0; row<mNumTexRows; row++)
475
      for(int col=0; col<mNumTexCols; col++)
476
        {
477
        if( tex>=NUM_TEXTURES ) break;
478
        createFaceTexture(canvas, paint, tex, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT);
479
        tex++;
480
        }
481

    
482
    if( !mTexture.setTexture(bitmap) )
483
      {
484
      int max = DistortedLibrary.getMaxTextureSize();
485
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
486
      crashlytics.log("failed to set texture of size "+bitmap.getWidth()+"x"+bitmap.getHeight()+" max is "+max);
487
      }
488
    }
489

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

    
492
  public int getNumLayers()
493
    {
494
    return mNumLayers;
495
    }
496

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

    
499
  public void continueRotation(float angleInDegrees)
500
    {
501
    mRotationAngleStatic.set0(angleInDegrees);
502
    }
503

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

    
506
  public Static4D getRotationQuat()
507
      {
508
      return mQuat;
509
      }
510

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

    
513
  public void recomputeScaleFactor(int scrWidth)
514
    {
515
    mNodeScale.set(scrWidth,NODE_RATIO*scrWidth,scrWidth);
516
    }
517

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

    
520
  public void savePreferences(SharedPreferences.Editor editor)
521
    {
522
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
523
    }
524

    
525
///////////////////////////////////////////////////////////////////////////////////////////////////
526

    
527
  public synchronized void restorePreferences(SharedPreferences preferences)
528
    {
529
    boolean error = false;
530

    
531
    for(int i=0; i<NUM_CUBITS; i++)
532
      {
533
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
534

    
535
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<QUATS.length)
536
        {
537
        CUBITS[i].modifyCurrentPosition(QUATS[mQuatDebug[i]]);
538
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
539
        }
540
      else
541
        {
542
        error = true;
543
        }
544
      }
545

    
546
    if( error )
547
      {
548
      for(int i=0; i<NUM_CUBITS; i++)
549
        {
550
        CUBITS[i].solve();
551
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
552
        }
553
      recordQuatsState("Failed to restorePreferences");
554
      }
555
    }
556

    
557
///////////////////////////////////////////////////////////////////////////////////////////////////
558

    
559
  public void recordQuatsState(String message)
560
    {
561
    StringBuilder quats = new StringBuilder();
562

    
563
    for(int j=0; j<NUM_CUBITS; j++)
564
      {
565
      quats.append(mQuatDebug[j]);
566
      quats.append(" ");
567
      }
568

    
569
    if( BuildConfig.DEBUG )
570
      {
571
      android.util.Log.e("quats" , quats.toString());
572
      android.util.Log.e("object", mList.name()+"_"+mNumLayers);
573
      }
574
    else
575
      {
576
      Exception ex = new Exception(message);
577
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
578
      crashlytics.setCustomKey("quats" , quats.toString());
579
      crashlytics.setCustomKey("object", mList.name()+"_"+mNumLayers );
580
      crashlytics.recordException(ex);
581
      }
582
    }
583

    
584
///////////////////////////////////////////////////////////////////////////////////////////////////
585

    
586
  public void releaseResources()
587
    {
588
    mTexture.markForDeletion();
589
    mMesh.markForDeletion();
590
    mEffects.markForDeletion();
591

    
592
    for(int j=0; j<NUM_CUBITS; j++)
593
      {
594
      CUBITS[j].releaseResources();
595
      }
596
    }
597

    
598
///////////////////////////////////////////////////////////////////////////////////////////////////
599

    
600
  public void apply(Effect effect, int position)
601
    {
602
    mEffects.apply(effect, position);
603
    }
604

    
605
///////////////////////////////////////////////////////////////////////////////////////////////////
606

    
607
  public void remove(long effectID)
608
    {
609
    mEffects.abortById(effectID);
610
    }
611

    
612
///////////////////////////////////////////////////////////////////////////////////////////////////
613

    
614
  public synchronized void solve()
615
    {
616
    for(int i=0; i<NUM_CUBITS; i++)
617
      {
618
      CUBITS[i].solve();
619
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
620
      }
621
    }
622

    
623
///////////////////////////////////////////////////////////////////////////////////////////////////
624

    
625
  public void resetAllTextureMaps()
626
    {
627
    final float ratioW = 1.0f/mNumTexCols;
628
    final float ratioH = 1.0f/mNumTexRows;
629
    int color, row, col;
630

    
631
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
632
      {
633
      final Static4D[] maps = new Static4D[NUM_CUBIT_FACES];
634

    
635
      for(int cubitface=0; cubitface<NUM_CUBIT_FACES; cubitface++)
636
        {
637
        color = getFaceColor(cubit,cubitface,mNumLayers);
638
        row = (mNumTexRows-1) - color/mNumTexCols;
639
        col = color%mNumTexCols;
640
        maps[cubitface] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
641
        }
642

    
643
      mMesh.setTextureMap(maps,NUM_CUBIT_FACES*cubit);
644
      }
645
    }
646

    
647
///////////////////////////////////////////////////////////////////////////////////////////////////
648

    
649
  public void setTextureMap(int cubit, int face, int newColor)
650
    {
651
    final float ratioW = 1.0f/mNumTexCols;
652
    final float ratioH = 1.0f/mNumTexRows;
653
    final Static4D[] maps = new Static4D[NUM_CUBIT_FACES];
654
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
655
    int col = newColor%mNumTexCols;
656

    
657
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
658
    mMesh.setTextureMap(maps,NUM_CUBIT_FACES*cubit);
659
    }
660

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

    
663
  public synchronized void beginNewRotation(int axis, int row )
664
    {
665
    if( axis<0 || axis>=ROTATION_AXIS.length )
666
      {
667
      android.util.Log.e("object", "invalid rotation axis: "+axis);
668
      return;
669
      }
670
    if( row<0 || row>=mNumLayers )
671
      {
672
      android.util.Log.e("object", "invalid rotation row: "+row);
673
      return;
674
      }
675

    
676
    mRotAxis     = axis;
677
    mRotRowBitmap= (1<<row);
678
    mRotationAngleStatic.set0(0.0f);
679
    mRotationAxis.set( ROTATION_AXIS[axis] );
680
    mRotationAngle.add(mRotationAngleStatic);
681
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
682
    }
683

    
684
///////////////////////////////////////////////////////////////////////////////////////////////////
685

    
686
  public synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
687
    {
688
    if( wasRotateApplied() )
689
      {
690
      mRotAxis     = axis;
691
      mRotRowBitmap= rowBitmap;
692

    
693
      mRotationAngleStatic.set0(0.0f);
694
      mRotationAxis.set( ROTATION_AXIS[axis] );
695
      mRotationAngle.setDuration(durationMillis);
696
      mRotationAngle.resetToBeginning();
697
      mRotationAngle.add(new Static1D(0));
698
      mRotationAngle.add(new Static1D(angle));
699
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
700
      mRotateEffect.notifyWhenFinished(listener);
701

    
702
      return mRotateEffect.getID();
703
      }
704

    
705
    return 0;
706
    }
707

    
708
///////////////////////////////////////////////////////////////////////////////////////////////////
709

    
710
  public long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
711
    {
712
    if( wasRotateApplied() )
713
      {
714
      float angle = getAngle();
715
      mRotationAngleStatic.set0(angle);
716
      mRotationAngleFinal.set0(nearestAngleInDegrees);
717
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
718

    
719
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
720
      mRotationAngle.resetToBeginning();
721
      mRotationAngle.removeAll();
722
      mRotationAngle.add(mRotationAngleStatic);
723
      mRotationAngle.add(mRotationAngleMiddle);
724
      mRotationAngle.add(mRotationAngleFinal);
725
      mRotateEffect.notifyWhenFinished(listener);
726

    
727
      return mRotateEffect.getID();
728
      }
729

    
730
    return 0;
731
    }
732

    
733
///////////////////////////////////////////////////////////////////////////////////////////////////
734

    
735
  private float getAngle()
736
    {
737
    int pointNum = mRotationAngle.getNumPoints();
738

    
739
    if( pointNum>=1 )
740
      {
741
      return mRotationAngle.getPoint(pointNum-1).get0();
742
      }
743
    else
744
      {
745
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
746
      crashlytics.log("points in RotationAngle: "+pointNum);
747
      return 0;
748
      }
749
    }
750

    
751
///////////////////////////////////////////////////////////////////////////////////////////////////
752

    
753
  public synchronized void removeRotationNow()
754
    {
755
    float angle = getAngle();
756
    double nearestAngleInRadians = angle*Math.PI/180;
757
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
758
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
759
    float axisX = ROTATION_AXIS[mRotAxis].get0();
760
    float axisY = ROTATION_AXIS[mRotAxis].get1();
761
    float axisZ = ROTATION_AXIS[mRotAxis].get2();
762
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
763

    
764
    mRotationAngle.removeAll();
765
    mRotationAngleStatic.set0(0);
766

    
767
    for(int i=0; i<NUM_CUBITS; i++)
768
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
769
        {
770
        int index = CUBITS[i].removeRotationNow(quat);
771
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
772
        }
773
    }
774

    
775
///////////////////////////////////////////////////////////////////////////////////////////////////
776

    
777
  public void initializeObject(int[][] moves)
778
    {
779
    solve();
780
    setupPosition(moves);
781
    }
782

    
783
///////////////////////////////////////////////////////////////////////////////////////////////////
784

    
785
  public int getCubit(float[] point3D)
786
    {
787
    float dist, minDist = Float.MAX_VALUE;
788
    int currentBest=-1;
789
    float multiplier = returnMultiplier();
790

    
791
    point3D[0] *= multiplier;
792
    point3D[1] *= multiplier;
793
    point3D[2] *= multiplier;
794

    
795
    for(int i=0; i<NUM_CUBITS; i++)
796
      {
797
      dist = CUBITS[i].getDistSquared(point3D);
798
      if( dist<minDist )
799
        {
800
        minDist = dist;
801
        currentBest = i;
802
        }
803
      }
804

    
805
    return currentBest;
806
    }
807

    
808
///////////////////////////////////////////////////////////////////////////////////////////////////
809

    
810
  public int computeNearestAngle(float angle, float speed)
811
    {
812
    final int NEAREST = 360/getBasicAngle();
813

    
814
    int tmp = (int)((angle+NEAREST/2)/NEAREST);
815
    if( angle< -(NEAREST*0.5) ) tmp-=1;
816

    
817
    if( tmp!=0 ) return NEAREST*tmp;
818

    
819
    return speed> 1.2f ? NEAREST*(angle>0 ? 1:-1) : 0;
820
    }
821

    
822
///////////////////////////////////////////////////////////////////////////////////////////////////
823

    
824
  public float getCameraDist()
825
    {
826
    return mCameraDist;
827
    }
828

    
829
///////////////////////////////////////////////////////////////////////////////////////////////////
830

    
831
  public int getNodeSize()
832
    {
833
    return mNodeSize;
834
    }
835

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

    
838
  public ObjectList getObjectList()
839
    {
840
    return mList;
841
    }
842

    
843
///////////////////////////////////////////////////////////////////////////////////////////////////
844

    
845
  abstract float getScreenRatio();
846
  abstract Static3D[] getCubitPositions(int numLayers);
847
  abstract Static4D[] getQuats();
848
  abstract int getNumFaces();
849
  abstract int getNumStickerTypes(int numLayers);
850
  abstract int getNumCubitFaces();
851
  abstract MeshBase createCubitMesh(int cubit, int numLayers);
852
  abstract void createFaceTexture(Canvas canvas, Paint paint, int face, int left, int top);
853
  abstract int getFaceColor(int cubit, int cubitface, int numLayers);
854
  abstract float returnMultiplier();
855
  abstract float[] getRowChances(int numLayers);
856
  abstract float[] getCuts(int numLayers);
857
  abstract boolean shouldResetTextureMaps();
858

    
859
  public abstract boolean isSolved();
860
  public abstract Static3D[] getRotationAxis();
861
  public abstract int getBasicAngle();
862
  public abstract String retObjectString();
863
  public abstract int randomizeNewRotAxis(Random rnd, int oldRotAxis);
864
  public abstract int randomizeNewRow(Random rnd, int oldRotAxis, int oldRow, int newRotAxis);
865
  public abstract int getObjectName(int numLayers);
866
  public abstract int getInventor(int numLayers);
867
  public abstract int getComplexity(int numLayers);
868
  }
(31-31/35)