Project

General

Profile

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

magiccube / src / main / java / org / distorted / main / RubikSurfaceView.java @ 4da7d87a

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2019 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.main;
21

    
22
import android.app.ActivityManager;
23
import android.content.Context;
24
import android.content.pm.ConfigurationInfo;
25
import android.opengl.GLSurfaceView;
26
import android.util.AttributeSet;
27
import android.util.DisplayMetrics;
28
import android.view.MotionEvent;
29

    
30
import org.distorted.library.type.Static2D;
31
import org.distorted.library.type.Static3D;
32
import org.distorted.library.type.Static4D;
33
import org.distorted.objects.RubikObject;
34
import org.distorted.objects.RubikObjectMovement;
35
import org.distorted.solvers.SolverMain;
36
import org.distorted.states.RubikState;
37
import org.distorted.states.RubikStateSolver;
38
import org.distorted.states.RubikStateSolving;
39

    
40
///////////////////////////////////////////////////////////////////////////////////////////////////
41

    
42
public class RubikSurfaceView extends GLSurfaceView
43
{
44
    private static final int NUM_SPEED_PROBES = 10;
45

    
46
    public static final int MODE_ROTATE  = 0;
47
    public static final int MODE_DRAG    = 1;
48
    public static final int MODE_REPLACE = 2;
49

    
50
    // Moving the finger from the middle of the vertical screen to the right edge will rotate a
51
    // given face by SWIPING_SENSITIVITY/2 degrees.
52
    private final static int SWIPING_SENSITIVITY  = 240;
53
    // Moving the finger by 0.3 of an inch will start a Rotation.
54
    private final static float ROTATION_SENSITIVITY = 0.3f;
55

    
56
    // Where did we get this sqrt(3)/2 ? From the (default, i.e. 60 degrees - see InternalOutputSurface!)
57
    // FOV of the projection matrix of the Node onto the Screen.
58
    // Take a look how the CAMERA_POINT is used in onTouchEvent - (x,y) there are expressed in sort of
59
    // 'half-NDC' coordinates i.e. they range from +0.5 to -0.5; thus CAMERA_POINT also needs to be
60
    // in 'half-NDC'. Since in this coordinate system the height of the screen is equal to 1, then the
61
    // Z-distance from the center of the object to the camera is equal to (scrHeight/2)/tan(FOV/2) =
62
    // 0.5/tan(30) = sqrt(3)/2.
63
    // Why is the Z-distance between the camera and the object equal to (scrHeight/2)/tan(FOV/2)?
64
    // Because of the way the View part of the ModelView matrix is constructed in EffectQueueMatrix.send().
65
    private final Static4D CAMERA_POINT = new Static4D(0, 0, (float)Math.sqrt(3)*0.5f, 0);
66

    
67
    private RubikRenderer mRenderer;
68
    private RubikPreRender mPreRender;
69
    private RubikObjectMovement mMovement;
70
    private boolean mDragging, mBeginningRotation, mContinuingRotation;
71
    private int mScreenWidth, mScreenHeight, mScreenMin;
72

    
73
    private int mNumFingersDown;
74
    private float mX, mY;
75
    private float mStartRotX, mStartRotY;
76
    private float mAxisX, mAxisY;
77
    private float mRotationFactor;
78
    private int mLastCubitColor, mLastCubitFace, mLastCubit;
79
    private int mCurrentAxis, mCurrentRow;
80
    private float mCurrentAngle, mCurrRotSpeed;
81
    private float[] mLastX;
82
    private float[] mLastY;
83
    private long[] mLastT;
84
    private int mFirstIndex, mLastIndex;
85
    private int mDensity;
86

    
87
    private static Static4D mQuat= new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
88
    private static Static4D mTemp= new Static4D(0,0,0,1);
89

    
90
///////////////////////////////////////////////////////////////////////////////////////////////////
91

    
92
    void setScreenSize(int width, int height)
93
      {
94
      mScreenWidth = width;
95
      mScreenHeight= height;
96

    
97
      mScreenMin = Math.min(width, height);
98
      }
99

    
100
///////////////////////////////////////////////////////////////////////////////////////////////////
101

    
102
    boolean isVertical()
103
      {
104
      return mScreenHeight>mScreenWidth;
105
      }
106

    
107
///////////////////////////////////////////////////////////////////////////////////////////////////
108

    
109
    RubikRenderer getRenderer()
110
      {
111
      return mRenderer;
112
      }
113

    
114
///////////////////////////////////////////////////////////////////////////////////////////////////
115

    
116
    RubikPreRender getPreRender()
117
      {
118
      return mPreRender;
119
      }
120

    
121
///////////////////////////////////////////////////////////////////////////////////////////////////
122

    
123
    void setQuat()
124
      {
125
      mQuat.set(mTemp);
126
      }
127

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

    
130
    Static4D getQuat()
131
      {
132
      return mQuat;
133
      }
134

    
135
///////////////////////////////////////////////////////////////////////////////////////////////////
136

    
137
    void setMovement(RubikObjectMovement movement)
138
      {
139
      mMovement = movement;
140
      }
141

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

    
144
    private Static4D quatFromAngle(float angle)
145
      {
146
      float cosA = (float)Math.cos(angle);
147
      float sinA =-(float)Math.sin(angle);
148

    
149
      return new Static4D(0, 0, sinA, cosA);
150
      }
151

    
152
///////////////////////////////////////////////////////////////////////////////////////////////////
153

    
154
    private Static4D quatFromDrag(float dragX, float dragY)
155
      {
156
      float axisX = dragY;  // inverted X and Y - rotation axis is perpendicular to (dragX,dragY)
157
      float axisY = dragX;  // Why not (-dragY, dragX) ? because Y axis is also inverted!
158
      float axisZ = 0;
159
      float axisL = (float)Math.sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);
160

    
161
      if( axisL>0 )
162
        {
163
        axisX /= axisL;
164
        axisY /= axisL;
165
        axisZ /= axisL;
166

    
167
        float ratio = axisL;
168
        ratio = ratio - (int)ratio;     // the cos() is only valid in (0,Pi)
169

    
170
        float cosA = (float)Math.cos(Math.PI*ratio);
171
        float sinA = (float)Math.sqrt(1-cosA*cosA);
172

    
173
        return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
174
        }
175

    
176
      return new Static4D(0f, 0f, 0f, 1f);
177
      }
178

    
179
///////////////////////////////////////////////////////////////////////////////////////////////////
180
// cast the 3D axis we are currently rotating along to the 2D in-screen-surface axis
181

    
182
    private void computeCurrentAxis(Static3D axis)
183
      {
184
      Static4D axis4D = new Static4D(axis.get0(), axis.get1(), axis.get2(), 0);
185
      Static4D result = rotateVectorByQuat(axis4D, mQuat);
186

    
187
      mAxisX =result.get0();
188
      mAxisY =result.get1();
189

    
190
      float len = (float)Math.sqrt(mAxisX*mAxisX + mAxisY*mAxisY);
191
      mAxisX /= len;
192
      mAxisY /= len;
193
      }
194

    
195
///////////////////////////////////////////////////////////////////////////////////////////////////
196
// return quat1*quat2
197

    
198
    public static Static4D quatMultiply( Static4D quat1, Static4D quat2 )
199
      {
200
      float qx = quat1.get0();
201
      float qy = quat1.get1();
202
      float qz = quat1.get2();
203
      float qw = quat1.get3();
204

    
205
      float rx = quat2.get0();
206
      float ry = quat2.get1();
207
      float rz = quat2.get2();
208
      float rw = quat2.get3();
209

    
210
      float tx = rw*qx - rz*qy + ry*qz + rx*qw;
211
      float ty = rw*qy + rz*qx + ry*qw - rx*qz;
212
      float tz = rw*qz + rz*qw - ry*qx + rx*qy;
213
      float tw = rw*qw - rz*qz - ry*qy - rx*qx;
214

    
215
      return new Static4D(tx,ty,tz,tw);
216
      }
217

    
218
///////////////////////////////////////////////////////////////////////////////////////////////////
219
// rotate 'vector' by quat  ( i.e. return quat*vector*(quat^-1) )
220

    
221
    public static Static4D rotateVectorByQuat(Static4D vector, Static4D quat)
222
      {
223
      float qx = quat.get0();
224
      float qy = quat.get1();
225
      float qz = quat.get2();
226
      float qw = quat.get3();
227

    
228
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
229
      Static4D tmp = quatMultiply(quat,vector);
230

    
231
      return quatMultiply(tmp,quatInverted);
232
      }
233

    
234
///////////////////////////////////////////////////////////////////////////////////////////////////
235
// rotate 'vector' by quat^(-1)  ( i.e. return (quat^-1)*vector*quat )
236

    
237
    public static Static4D rotateVectorByInvertedQuat(Static4D vector, Static4D quat)
238
      {
239
      float qx = quat.get0();
240
      float qy = quat.get1();
241
      float qz = quat.get2();
242
      float qw = quat.get3();
243

    
244
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
245
      Static4D tmp = quatMultiply(quatInverted,vector);
246

    
247
      return quatMultiply(tmp,quat);
248
      }
249

    
250
///////////////////////////////////////////////////////////////////////////////////////////////////
251

    
252
    private void addSpeedProbe(float x, float y)
253
      {
254
      long currTime = System.currentTimeMillis();
255
      boolean theSame = mLastIndex==mFirstIndex;
256

    
257
      mLastIndex++;
258
      if( mLastIndex>=NUM_SPEED_PROBES ) mLastIndex=0;
259

    
260
      mLastT[mLastIndex] = currTime;
261
      mLastX[mLastIndex] = x;
262
      mLastY[mLastIndex] = y;
263

    
264
      if( mLastIndex==mFirstIndex)
265
        {
266
        mFirstIndex++;
267
        if( mFirstIndex>=NUM_SPEED_PROBES ) mFirstIndex=0;
268
        }
269

    
270
      if( theSame )
271
        {
272
        mLastT[mFirstIndex] = currTime;
273
        mLastX[mFirstIndex] = x;
274
        mLastY[mFirstIndex] = y;
275
        }
276
      }
277

    
278
///////////////////////////////////////////////////////////////////////////////////////////////////
279

    
280
    private void computeCurrentSpeedInInchesPerSecond()
281
      {
282
      long firstTime = mLastT[mFirstIndex];
283
      long lastTime  = mLastT[mLastIndex];
284
      float fX = mLastX[mFirstIndex];
285
      float fY = mLastY[mFirstIndex];
286
      float lX = mLastX[mLastIndex];
287
      float lY = mLastY[mLastIndex];
288

    
289
      long timeDiff = lastTime-firstTime;
290

    
291
      mLastIndex = 0;
292
      mFirstIndex= 0;
293

    
294
      mCurrRotSpeed = timeDiff>0 ? 1000*retFingerDragDistanceInInches(fX,fY,lX,lY)/timeDiff : 0;
295
      }
296

    
297
///////////////////////////////////////////////////////////////////////////////////////////////////
298

    
299
    private float retFingerDragDistanceInInches(float xFrom, float yFrom, float xTo, float yTo)
300
      {
301
      float xDist = mScreenWidth*(xFrom-xTo);
302
      float yDist = mScreenHeight*(yFrom-yTo);
303
      float distInPixels = (float)Math.sqrt(xDist*xDist + yDist*yDist);
304

    
305
      return distInPixels/mDensity;
306
      }
307

    
308
///////////////////////////////////////////////////////////////////////////////////////////////////
309

    
310
    private void setUpDragOrRotate(boolean down, float x, float y)
311
      {
312
      int mode = RubikState.getMode();
313

    
314
      if( mode==MODE_DRAG )
315
        {
316
        mDragging           = true;
317
        mBeginningRotation  = false;
318
        mContinuingRotation = false;
319
        }
320
      else
321
        {
322
        Static4D touchPoint1 = new Static4D(x, y, 0, 0);
323
        Static4D rotatedTouchPoint1= rotateVectorByInvertedQuat(touchPoint1, mQuat);
324
        Static4D rotatedCamera= rotateVectorByInvertedQuat(CAMERA_POINT, mQuat);
325

    
326
        if( mMovement!=null && mMovement.faceTouched(rotatedTouchPoint1,rotatedCamera) )
327
          {
328
          mDragging           = false;
329
          mContinuingRotation = false;
330

    
331
          if( mode==MODE_ROTATE )
332
            {
333
            mBeginningRotation= mPreRender.canRotate();
334
            }
335
          else if( mode==MODE_REPLACE )
336
            {
337
            mBeginningRotation= false;
338

    
339
            if( down )
340
              {
341
              RubikStateSolver solver = (RubikStateSolver) RubikState.SVER.getStateClass();
342
              mLastCubitFace = mMovement.getTouchedFace();
343
              float[] point = mMovement.getTouchedPoint3D();
344
              int color = solver.getCurrentColor();
345
              RubikObject object = mPreRender.getObject();
346
              mLastCubit = object.getCubit(point);
347
              mPreRender.setTextureMap( mLastCubit, mLastCubitFace, color );
348
              mLastCubitColor = SolverMain.cubitIsLocked(object.getObjectList(), object.getSize(), mLastCubit);
349
              }
350
            }
351
          }
352
        else
353
          {
354
          mDragging           = true;
355
          mBeginningRotation  = false;
356
          mContinuingRotation = false;
357
          }
358
        }
359
      }
360

    
361
///////////////////////////////////////////////////////////////////////////////////////////////////
362

    
363
    private void drag(float x, float y)
364
      {
365
      mTemp.set(quatMultiply(quatFromDrag(mX-x,y-mY), mQuat));
366
      mPreRender.setQuatOnNextRender();
367
      mX = x;
368
      mY = y;
369
      }
370

    
371
///////////////////////////////////////////////////////////////////////////////////////////////////
372

    
373
    private void finishRotation()
374
      {
375
      computeCurrentSpeedInInchesPerSecond();
376
      int angle = mPreRender.getObject().computeNearestAngle(mCurrentAngle, mCurrRotSpeed);
377
      mPreRender.finishRotation(angle);
378

    
379
      if( RubikState.getCurrentState()==RubikState.SOLV && angle!=0 )
380
        {
381
        RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
382
        solving.addMove(mCurrentAxis, mCurrentRow, angle);
383
        }
384

    
385
      mContinuingRotation = false;
386
      mBeginningRotation  = false;
387
      mDragging           = true;
388
      }
389

    
390
///////////////////////////////////////////////////////////////////////////////////////////////////
391

    
392
    private void continueRotation(float x, float y)
393
      {
394
      float dx = x-mStartRotX;
395
      float dy = y-mStartRotY;
396
      float alpha = dx*mAxisX + dy*mAxisY;
397
      float x2 = dx - alpha*mAxisX;
398
      float y2 = dy - alpha*mAxisY;
399

    
400
      float len = (float)Math.sqrt(x2*x2 + y2*y2);
401

    
402
      // we have the length of 1D vector 'angle', now the direction:
403
      float tmp = mAxisY==0 ? -mAxisX*y2 : mAxisY*x2;
404

    
405
      float angle = (tmp>0 ? 1:-1)*len*mRotationFactor;
406
      mCurrentAngle = SWIPING_SENSITIVITY*angle;
407
      mPreRender.getObject().continueRotation(mCurrentAngle);
408

    
409
      addSpeedProbe(x2,y2);
410
      }
411

    
412
///////////////////////////////////////////////////////////////////////////////////////////////////
413

    
414
    private void beginRotation(float x, float y)
415
      {
416
      mStartRotX = x;
417
      mStartRotY = y;
418

    
419
      Static4D touchPoint2 = new Static4D(x, y, 0, 0);
420
      Static4D rotatedTouchPoint2= rotateVectorByInvertedQuat(touchPoint2, mQuat);
421

    
422
      Static2D res = mMovement.newRotation(rotatedTouchPoint2);
423
      RubikObject object = mPreRender.getObject();
424

    
425
      mCurrentAxis = (int)res.get0();
426
      float offset = res.get1();
427
      mCurrentRow = (int)(object.returnMultiplier()*offset);
428
      computeCurrentAxis( object.getRotationAxis()[mCurrentAxis] );
429
      mRotationFactor = object.returnRotationFactor(offset);
430

    
431
      object.beginNewRotation( mCurrentAxis, mCurrentRow );
432

    
433
      if( RubikState.getCurrentState()==RubikState.READ )
434
        {
435
        RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
436
        solving.resetElapsed();
437

    
438
        final RubikActivity act = (RubikActivity)getContext();
439

    
440
        act.runOnUiThread(new Runnable()
441
          {
442
          @Override
443
          public void run()
444
            {
445
            RubikState.switchState( act, RubikState.SOLV);
446
            }
447
          });
448
        }
449

    
450
      addSpeedProbe(x,y);
451

    
452
      mBeginningRotation = false;
453
      mContinuingRotation= true;
454
      }
455

    
456
///////////////////////////////////////////////////////////////////////////////////////////////////
457

    
458
    private void actionMove(MotionEvent event)
459
      {
460
      float x = (event.getX() - mScreenWidth*0.5f)/mScreenMin;
461
      float y = (mScreenHeight*0.5f -event.getY())/mScreenMin;
462

    
463
      //android.util.Log.e("view", "num fingers: "+mNumFingersDown+" x="+event.getX()+" y="+event.getY());
464

    
465
      if( mBeginningRotation )
466
        {
467
        if( retFingerDragDistanceInInches(mX,mY,x,y) > ROTATION_SENSITIVITY )
468
          {
469
          beginRotation(x,y);
470
          }
471
        }
472
      else if( mContinuingRotation )
473
        {
474
        continueRotation(x,y);
475
        }
476
      else if( mDragging )
477
        {
478
        drag(x,y);
479
        }
480
      else
481
        {
482
        setUpDragOrRotate(false,x,y);
483
        }
484
      }
485

    
486
///////////////////////////////////////////////////////////////////////////////////////////////////
487

    
488
    private void actionDown(MotionEvent event)
489
      {
490
      mNumFingersDown++;
491

    
492
      int index = event.getActionIndex();
493
      float x = event.getX();
494
      float y = event.getY();
495

    
496
      android.util.Log.e("view", "down1 num fingers: "+mNumFingersDown+" index="+index+" x="+x+" y="+y);
497

    
498
      mX = (x - mScreenWidth*0.5f)/mScreenMin;
499
      mY = (mScreenHeight*0.5f -y)/mScreenMin;
500

    
501
      setUpDragOrRotate(true,mX,mY);
502
      }
503

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

    
506
    private void actionUp(MotionEvent event)
507
      {
508
      mNumFingersDown--;
509

    
510
      int index = event.getActionIndex();
511
      float x = event.getX();
512
      float y = event.getY();
513

    
514
      android.util.Log.e("view", "up1 num fingers: "+mNumFingersDown+" index="+index+" x="+x+" y="+y);
515

    
516
      if( mContinuingRotation )
517
        {
518
        finishRotation();
519
        }
520

    
521
      if( mLastCubitColor>=0 )
522
        {
523
        mPreRender.setTextureMap( mLastCubit, mLastCubitFace, mLastCubitColor );
524
        }
525
      }
526

    
527
///////////////////////////////////////////////////////////////////////////////////////////////////
528

    
529
    private void actionDown2(MotionEvent event)
530
      {
531
      mNumFingersDown++;
532

    
533
      if( mBeginningRotation )
534
        {
535
        mContinuingRotation = false;
536
        mBeginningRotation  = false;
537
        mDragging           = true;
538
        }
539
      else if( mContinuingRotation )
540
        {
541
        finishRotation();
542
        }
543

    
544
      int index = event.getActionIndex();
545
      float x = event.getX();
546
      float y = event.getY();
547

    
548
      android.util.Log.e("view", "down2 num fingers: "+mNumFingersDown+" index="+index+" x="+x+" y="+y);
549
      }
550

    
551
///////////////////////////////////////////////////////////////////////////////////////////////////
552

    
553
    private void actionUp2(MotionEvent event)
554
      {
555
      mNumFingersDown--;
556

    
557
      int index = event.getActionIndex();
558
      float x = event.getX();
559
      float y = event.getY();
560

    
561
      android.util.Log.e("view", "up2 num fingers: "+mNumFingersDown+" index="+index+" x="+x+" y="+y);
562
      }
563

    
564
///////////////////////////////////////////////////////////////////////////////////////////////////
565
// PUBLIC API
566
///////////////////////////////////////////////////////////////////////////////////////////////////
567

    
568
    public RubikSurfaceView(Context context, AttributeSet attrs)
569
      {
570
      super(context,attrs);
571

    
572
      if(!isInEditMode())
573
        {
574
        mLastCubitColor = -1;
575
        mCurrRotSpeed   = 0.0f;
576

    
577
        mLastX = new float[NUM_SPEED_PROBES];
578
        mLastY = new float[NUM_SPEED_PROBES];
579
        mLastT = new long[NUM_SPEED_PROBES];
580
        mFirstIndex =0;
581
        mLastIndex  =0;
582

    
583
        mNumFingersDown = 0;
584

    
585
        mRenderer  = new RubikRenderer(this);
586
        mPreRender = new RubikPreRender(this);
587

    
588
        RubikActivity act = (RubikActivity)context;
589
        DisplayMetrics dm = new DisplayMetrics();
590
        act.getWindowManager().getDefaultDisplay().getMetrics(dm);
591

    
592
        mDensity = dm.densityDpi;
593

    
594
        final ActivityManager activityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
595

    
596
        if( activityManager!=null )
597
          {
598
          final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
599
          setEGLContextClientVersion( (configurationInfo.reqGlEsVersion>>16) >= 3 ? 3:2 );
600
          setRenderer(mRenderer);
601
          }
602
        }
603
      }
604

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

    
607
    @Override
608
    public boolean onTouchEvent(MotionEvent event)
609
      {
610
      int action = event.getActionMasked();
611

    
612
      switch(action)
613
         {
614
         case MotionEvent.ACTION_DOWN        : actionDown(event) ; break;
615
         case MotionEvent.ACTION_MOVE        : actionMove(event) ; break;
616
         case MotionEvent.ACTION_UP          : actionUp(event)   ; break;
617
         case MotionEvent.ACTION_POINTER_DOWN: actionDown2(event); break;
618
         case MotionEvent.ACTION_POINTER_UP  : actionUp2(event)  ; break;
619
         }
620

    
621
      return true;
622
      }
623
}
624

    
(4-4/4)