Project

General

Profile

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

magiccube / src / main / java / org / distorted / objects / RubikObject.java @ 001cc0e4

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.graphics.Bitmap;
24
import android.graphics.Canvas;
25
import android.graphics.Paint;
26

    
27
import org.distorted.library.effect.Effect;
28
import org.distorted.library.effect.MatrixEffectQuaternion;
29
import org.distorted.library.effect.MatrixEffectScale;
30
import org.distorted.library.effect.VertexEffectSink;
31
import org.distorted.library.main.DistortedEffects;
32
import org.distorted.library.main.DistortedNode;
33
import org.distorted.library.main.DistortedTexture;
34
import org.distorted.library.mesh.MeshBase;
35
import org.distorted.library.mesh.MeshRectangles;
36
import org.distorted.library.message.EffectListener;
37
import org.distorted.library.type.Static1D;
38
import org.distorted.library.type.Static3D;
39
import org.distorted.library.type.Static4D;
40

    
41
///////////////////////////////////////////////////////////////////////////////////////////////////
42

    
43
public abstract class RubikObject extends DistortedNode
44
  {
45
  public static final int NODE_FBO_SIZE = 600;
46

    
47
  private static final int TEXTURE_HEIGHT = 128;
48
  final float[] LEGAL_QUATS;
49
  final Static3D[] ROTATION_AXIS;
50

    
51
  static float OBJECT_SCREEN_RATIO;
52

    
53
  private final int NUM_CUBITS;
54
  private int mRotRowBitmap;
55
  private int mRotAxis;
56
  private Static3D[] mOrigPos;
57
  private Static3D mNodeScale;
58
  private Static4D mQuatAccumulated;
59
  private Cubit[] mCubits;
60
  private int mSize;
61
  private RubikObjectList mList;
62

    
63
  float mStart, mStep;
64

    
65
  Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
66
  DistortedTexture mTexture;
67

    
68
  VertexEffectSink mSinkEffect;
69
  MatrixEffectScale mScaleEffect;
70
  MatrixEffectQuaternion mQuatCEffect;
71
  MatrixEffectQuaternion mQuatAEffect;
72

    
73
///////////////////////////////////////////////////////////////////////////////////////////////////
74

    
75
  RubikObject(int size, int fov, Static4D quatCur, Static4D quatAcc, DistortedTexture nodeTexture,
76
              MeshRectangles nodeMesh, DistortedEffects nodeEffects, int[][] moves, RubikObjectList list)
77
    {
78
    super(nodeTexture,nodeEffects,nodeMesh);
79

    
80
    resizeFBO(NODE_FBO_SIZE, NODE_FBO_SIZE);
81

    
82
    mList = list;
83
    mOrigPos = getCubitPositions(size);
84

    
85
    LEGAL_QUATS = getLegalQuats();
86
    NUM_CUBITS  = mOrigPos.length;
87
    ROTATION_AXIS = getRotationAxis();
88
    OBJECT_SCREEN_RATIO = getScreenRatio();
89

    
90
    mSize = size;
91
    computeStartAndStep(mOrigPos);
92
    mNodeScale= new Static3D(1,1,1);
93
    mQuatAccumulated = quatAcc;
94
    mSinkEffect  = getSink(mSize);
95

    
96
    mRotationAngleStatic = new Static1D(0);
97
    mRotationAngleMiddle = new Static1D(0);
98
    mRotationAngleFinal  = new Static1D(0);
99

    
100
    Static3D center = new Static3D(0,0,0);
101
    float scale = OBJECT_SCREEN_RATIO*NODE_FBO_SIZE/mSize;
102
    mScaleEffect = new MatrixEffectScale(new Static3D(scale,scale,scale));
103
    mQuatCEffect = new MatrixEffectQuaternion(quatCur, center);
104
    mQuatAEffect = new MatrixEffectQuaternion(quatAcc, center);
105

    
106
    MatrixEffectScale nodeScaleEffect = new MatrixEffectScale(mNodeScale);
107
    nodeEffects.apply(nodeScaleEffect);
108

    
109
    mCubits = new Cubit[NUM_CUBITS];
110
    mTexture = new DistortedTexture();
111

    
112
    int vertices = (int)(24.0f/mSize + 2.0f);
113

    
114
    for(int i=0; i<NUM_CUBITS; i++)
115
      {
116
      MeshBase cubitMesh = createCubitMesh(i,vertices);
117
      mCubits[i] = new Cubit(this,cubitMesh,mOrigPos[i]);
118
      textureCubitMesh(cubitMesh,i);
119

    
120
      attach(mCubits[i].mNode);
121
      }
122

    
123
    setupPosition(moves);
124

    
125
    setProjection(fov, 0.1f);
126
    }
127

    
128
///////////////////////////////////////////////////////////////////////////////////////////////////
129

    
130
  private void textureCubitMesh(MeshBase mesh, int cubit)
131
    {
132
    boolean belongs;
133
    final int numFaces = getNumFaces();
134
    final Static4D[] maps = new Static4D[numFaces];
135
    final float ratio = 1.0f/(numFaces+1);
136

    
137
    if( 2*ROTATION_AXIS.length == numFaces )  // i.e. there are faces on both ends of the axis (cube)
138
      {
139
      for(int i=0; i<numFaces; i++)
140
        {
141
        belongs = isOnFace(cubit, i/2, i%2==0 ? mSize-1:0 );
142
        maps[i] = new Static4D( (belongs?i:6)*ratio, 0.0f, ratio, 1.0f);
143
        }
144
      }
145
    else if( ROTATION_AXIS.length == numFaces )  // just a single face on the right end of an axis (pyraminx)
146
      {
147
      for(int i=0; i<numFaces; i++)
148
        {
149
        belongs = isOnFace(cubit, i, 0 );
150
        maps[i] = new Static4D( (belongs?i:6)*ratio, 0.0f, ratio, 1.0f);
151
        }
152
      }
153

    
154
    mesh.setTextureMap(maps);
155
    }
156

    
157
///////////////////////////////////////////////////////////////////////////////////////////////////
158
// Cast centers of all Cubits on the first rotation Axis and compute the leftmost and rightmost
159
// one. From there compute the 'start' (i.e. the leftmost) and 'step' (i.e. distance between two
160
// consecutive).
161
// it is assumed that other rotation axis have the same 'start' and 'step' - this is the case with
162
// the Cube and the Pyraminx.
163
// Start and Step are then needed to compute which rotation row (with respect to a given axis) a
164
// given Cubit belongs to.
165

    
166
  private void computeStartAndStep(Static3D[] pos)
167
    {
168
    float min = Float.MAX_VALUE;
169
    float max = Float.MIN_VALUE;
170
    float axisX = ROTATION_AXIS[0].get0();
171
    float axisY = ROTATION_AXIS[0].get1();
172
    float axisZ = ROTATION_AXIS[0].get2();
173
    float tmp;
174

    
175
    for(int i=0; i<NUM_CUBITS; i++)
176
      {
177
      tmp = pos[i].get0()*axisX + pos[i].get1()*axisY + pos[i].get2()*axisZ;
178
      if( tmp<min ) min=tmp;
179
      if( tmp>max ) max=tmp;
180
      }
181

    
182
    mStart = min;
183
    mStep  = (max-min+1.0f)/mSize;
184
    }
185

    
186
///////////////////////////////////////////////////////////////////////////////////////////////////
187

    
188
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
189
    {
190
    int cubitRow = (int)(mCubits[cubit].mRotationRow[axis]+0.5f);
191
    return ((1<<cubitRow)&rowBitmap)!=0;
192
    }
193

    
194
///////////////////////////////////////////////////////////////////////////////////////////////////
195
// we cannot use belongsToRotation for deciding if to texture a face. Counterexample: the 'rotated'
196
// tetrahedrons of Pyraminx nearby the edge: they belong to rotation but their face which is rotated
197
// away from the face of the Pyraminx shouldn't be textured.
198

    
199
  private boolean isOnFace( int cubit, int axis, int row)
200
    {
201
    final float MAX_ERROR = 0.0001f;
202
    float diff = mCubits[cubit].mRotationRow[axis] - row;
203
    return diff*diff < MAX_ERROR;
204
    }
205

    
206
///////////////////////////////////////////////////////////////////////////////////////////////////
207
// note the minus in front of the sin() - we rotate counterclockwise
208
// when looking towards the direction where the axis increases in values.
209

    
210
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
211
    {
212
    Static3D axis = ROTATION_AXIS[axisIndex];
213

    
214
    while( angleInDegrees<0 ) angleInDegrees += 360;
215
    angleInDegrees %= 360;
216
    
217
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
218
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
219

    
220
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
221
    }
222

    
223
///////////////////////////////////////////////////////////////////////////////////////////////////
224

    
225
  private void setupPosition(int[][] moves)
226
    {
227
    if( moves!=null )
228
      {
229
      Static4D quat;
230
      int axis, rowBitmap, angle;
231
      int corr = (360/getBasicAngle());
232

    
233
      for(int[] move: moves)
234
        {
235
        axis     = move[0];
236
        rowBitmap= move[1];
237
        angle    = move[2]*corr;
238
        quat     = makeQuaternion(axis,angle);
239

    
240
        for(int j=0; j<NUM_CUBITS; j++)
241
          if( belongsToRotation(j,axis,rowBitmap) )
242
            {
243
            mCubits[j].removeRotationNow(quat);
244
            }
245
        }
246
      }
247
    }
248

    
249
///////////////////////////////////////////////////////////////////////////////////////////////////
250

    
251
  int getCubitFaceColorIndex(int cubit, int face)
252
    {
253
    return mCubits[cubit].getColorIndex(face);
254
    }
255

    
256
///////////////////////////////////////////////////////////////////////////////////////////////////
257
// Clamp all rotated positions to one of those original ones to avoid accumulating errors.
258

    
259
  void clampPos(Static3D pos)
260
    {
261
    float currError, minError = Float.MAX_VALUE;
262
    int minErrorIndex= -1;
263
    float x = pos.get0();
264
    float y = pos.get1();
265
    float z = pos.get2();
266
    float xo,yo,zo;
267

    
268
    for(int i=0; i<NUM_CUBITS; i++)
269
      {
270
      xo = mOrigPos[i].get0();
271
      yo = mOrigPos[i].get1();
272
      zo = mOrigPos[i].get2();
273

    
274
      currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
275

    
276
      if( currError<minError )
277
        {
278
        minError = currError;
279
        minErrorIndex = i;
280
        }
281
      }
282

    
283
    pos.set( mOrigPos[minErrorIndex] );
284
    }
285

    
286
///////////////////////////////////////////////////////////////////////////////////////////////////
287
// the getFaceColors + final black in a horizontal strip.
288

    
289
  public void createTexture()
290
    {
291
    Bitmap bitmap;
292

    
293
    final int numColors = getNumFaces();
294

    
295
    Paint paint = new Paint();
296
    bitmap = Bitmap.createBitmap( (numColors+1)*TEXTURE_HEIGHT, TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
297
    Canvas canvas = new Canvas(bitmap);
298

    
299
    paint.setAntiAlias(true);
300
    paint.setTextAlign(Paint.Align.CENTER);
301
    paint.setStyle(Paint.Style.FILL);
302

    
303
    paint.setColor(0xff000000);
304
    canvas.drawRect(0, 0, (numColors+1)*TEXTURE_HEIGHT, TEXTURE_HEIGHT, paint);
305

    
306
    for(int i=0; i<numColors; i++)
307
      {
308
      createFaceTexture(canvas, paint, i, i*TEXTURE_HEIGHT, 0, TEXTURE_HEIGHT);
309
      }
310

    
311
    mTexture.setTexture(bitmap);
312
    }
313

    
314
///////////////////////////////////////////////////////////////////////////////////////////////////
315

    
316
  public int getSize()
317
    {
318
    return mSize;
319
    }
320

    
321
///////////////////////////////////////////////////////////////////////////////////////////////////
322

    
323
  public void continueRotation(float angleInDegrees)
324
    {
325
    mRotationAngleStatic.set0(angleInDegrees);
326
    }
327

    
328
///////////////////////////////////////////////////////////////////////////////////////////////////
329

    
330
  public Static4D getRotationQuat()
331
      {
332
      return mQuatAccumulated;
333
      }
334

    
335
///////////////////////////////////////////////////////////////////////////////////////////////////
336

    
337
  public void recomputeScaleFactor(int scrWidth, int scrHeight)
338
    {
339
    float factor = Math.min(scrWidth,scrHeight);
340
    mNodeScale.set(factor,factor,factor);
341
    }
342

    
343
///////////////////////////////////////////////////////////////////////////////////////////////////
344

    
345
  public void savePreferences(SharedPreferences.Editor editor)
346
    {
347
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].savePreferences(editor);
348
    }
349

    
350
///////////////////////////////////////////////////////////////////////////////////////////////////
351

    
352
  public void restorePreferences(SharedPreferences preferences)
353
    {
354
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].restorePreferences(preferences);
355
    }
356

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

    
359
  public void releaseResources()
360
    {
361
    mTexture.markForDeletion();
362

    
363
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].releaseResources();
364
    }
365

    
366
///////////////////////////////////////////////////////////////////////////////////////////////////
367

    
368
  public void apply(Effect effect, int position)
369
    {
370
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].mEffect.apply(effect, position);
371
    }
372

    
373
///////////////////////////////////////////////////////////////////////////////////////////////////
374

    
375
  public void remove(long effectID)
376
    {
377
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].mEffect.abortById(effectID);
378
    }
379

    
380
///////////////////////////////////////////////////////////////////////////////////////////////////
381

    
382
  public void solve()
383
    {
384
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].solve();
385
    }
386

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

    
389
  public boolean isSolved()
390
    {
391
    Static4D q = mCubits[0].mQuatScramble;
392

    
393
    for(int i=1; i<NUM_CUBITS; i++)
394
      {
395
      if( !mCubits[i].thereIsNoVisibleDifference(q) ) return false;
396
      }
397

    
398
    return true;
399
    }
400

    
401
///////////////////////////////////////////////////////////////////////////////////////////////////
402

    
403
  public void resetAllTextureMaps()
404
    {
405
    for(int i=0; i<NUM_CUBITS; i++)
406
      {
407
      textureCubitMesh( mCubits[i].getMesh() , i );
408
      }
409
    }
410

    
411
///////////////////////////////////////////////////////////////////////////////////////////////////
412

    
413
  public void setTextureMap(int cubit, int face, int newColor)
414
    {
415
    final int numFaces = getNumFaces();
416
    final float ratio = 1.0f/(numFaces+1);
417

    
418
    final Static4D[] maps = new Static4D[numFaces];
419
    maps[face] = new Static4D( newColor*ratio, 0.0f, ratio, 1.0f);
420

    
421
    mCubits[cubit].getMesh().setTextureMap(maps);
422
    }
423

    
424
///////////////////////////////////////////////////////////////////////////////////////////////////
425

    
426
  public void beginNewRotation(int axis, int row )
427
    {
428
    if( axis<0 || axis>=ROTATION_AXIS.length )
429
      {
430
      android.util.Log.e("object", "invalid rotation axis: "+axis);
431
      return;
432
      }
433
    if( row<0 || row>=mSize )
434
      {
435
      android.util.Log.e("object", "invalid rotation row: "+row);
436
      return;
437
      }
438

    
439
    mRotAxis       = axis;
440
    mRotRowBitmap  = (1<<row);
441

    
442
    mRotationAngleStatic.set0(0.0f);
443

    
444
    for(int i=0; i<NUM_CUBITS; i++)
445
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
446
        {
447
        mCubits[i].beginNewRotation(axis);
448
        }
449
     }
450

    
451
///////////////////////////////////////////////////////////////////////////////////////////////////
452

    
453
  public long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
454
     {
455
     long effectID=0;
456
     int firstCubit = -1;
457

    
458
     mRotAxis       = axis;
459
     mRotRowBitmap  = rowBitmap;
460

    
461
     mRotationAngleStatic.set0(0.0f);
462

    
463
     for(int i=0; i<NUM_CUBITS; i++)
464
       if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
465
         {
466
         mCubits[i].addNewRotation(axis,durationMillis,angle);
467
         if( firstCubit<0 ) firstCubit = i;
468
         }
469

    
470
     if( firstCubit>=0 ) effectID = mCubits[firstCubit].setUpCallback(listener);
471

    
472
     return effectID;
473
     }
474

    
475
///////////////////////////////////////////////////////////////////////////////////////////////////
476

    
477
  public long finishRotationNow(EffectListener listener)
478
    {
479
    int firstCubit= -1;
480
    long effectID =  0;
481

    
482
    for(int i=0; i<NUM_CUBITS; i++)
483
      {
484
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
485
        {
486
        if( firstCubit<0 )
487
          {
488
          firstCubit=i;
489

    
490
          float angle = mRotationAngleStatic.get0();
491
          int nearestAngleInDegrees = computeNearestAngle(angle);
492
          mRotationAngleStatic.set0(angle);
493
          mRotationAngleFinal.set0(nearestAngleInDegrees);
494
          mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
495
          }
496
        mCubits[i].resetRotationAngle();
497
        }
498
      }
499

    
500
    if( firstCubit>=0 ) effectID = mCubits[firstCubit].setUpCallback(listener);
501

    
502
    return effectID;
503
    }
504

    
505
///////////////////////////////////////////////////////////////////////////////////////////////////
506

    
507
  public void removeRotationNow()
508
     {
509
     boolean first = true;
510
     Static4D quat = null;
511

    
512
     for(int i=0; i<NUM_CUBITS; i++)
513
       if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
514
         {
515
         if( first )
516
           {
517
           first = false;
518

    
519
           float angle = mRotationAngleFinal.get0();
520
           int nearestAngleInDegrees = computeNearestAngle(angle);
521
           double nearestAngleInRadians = nearestAngleInDegrees*Math.PI/180;
522
           float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
523
           float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
524
           float axisX = ROTATION_AXIS[mRotAxis].get0();
525
           float axisY = ROTATION_AXIS[mRotAxis].get1();
526
           float axisZ = ROTATION_AXIS[mRotAxis].get2();
527
           quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
528
           }
529

    
530
         mCubits[i].removeRotationNow(quat);
531
         }
532

    
533
     mRotationAngleStatic.set0(0);
534
     }
535

    
536
///////////////////////////////////////////////////////////////////////////////////////////////////
537

    
538
  public void initializeObject(int[][] moves)
539
    {
540
    solve();
541
    setupPosition(moves);
542
    }
543

    
544
///////////////////////////////////////////////////////////////////////////////////////////////////
545

    
546
  public int getCubit(float[] point3D)
547
    {
548
    float dist, minDist = Float. MAX_VALUE;
549
    int currentBest=-1;
550
    float multiplier = returnMultiplier();
551

    
552
    point3D[0] *= multiplier;
553
    point3D[1] *= multiplier;
554
    point3D[2] *= multiplier;
555

    
556
    for(int i=0; i<NUM_CUBITS; i++)
557
      {
558
      dist = mCubits[i].getDistSquared(point3D);
559
      if( dist<minDist )
560
        {
561
        minDist = dist;
562
        currentBest = i;
563
        }
564
      }
565

    
566
    return currentBest;
567
    }
568

    
569
///////////////////////////////////////////////////////////////////////////////////////////////////
570

    
571
  public int computeNearestAngle(float angle)
572
    {
573
    final int NEAREST = 360/getBasicAngle();
574

    
575
    int tmp = (int)((angle+NEAREST/2)/NEAREST);
576
    if( angle< -(NEAREST*0.5) ) tmp-=1;
577

    
578
    return NEAREST*tmp;
579
    }
580

    
581
///////////////////////////////////////////////////////////////////////////////////////////////////
582

    
583
  public RubikObjectList getObjectList()
584
    {
585
    return mList;
586
    }
587

    
588
///////////////////////////////////////////////////////////////////////////////////////////////////
589

    
590
  abstract float getScreenRatio();
591
  abstract VertexEffectSink getSink(int size);
592
  abstract Static3D[] getCubitPositions(int size);
593
  abstract float[] getLegalQuats();
594
  abstract int getNumFaces();
595
  abstract MeshBase createCubitMesh(int cubit, int vertices);
596
  abstract void createFaceTexture(Canvas canvas, Paint paint, int face, int left, int top, int side);
597
  public abstract Static3D[] getRotationAxis();
598
  public abstract int getBasicAngle();
599
  public abstract float returnMultiplier();
600
  public abstract float returnRotationFactor(float offset);
601
  public abstract String retObjectString();
602
  public abstract float[] getRowChances();
603
  }
(4-4/8)