Project

General

Profile

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

magiccube / src / main / java / org / distorted / main / RubikSurfaceView.java @ cd83d0aa

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.33 of an inch will start a Rotation.
54
    private final static float ROTATION_SENSITIVITY =  0.33f;
55
    // Every 0.33 of an inch the direction of cube drag will reset.
56
    private final static float DIRECTION_SENSITIVITY=  0.33f;
57

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

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

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

    
87
    private static Static4D mQuatCurrent    = new Static4D(0,0,0,1);
88
    private static Static4D mQuatAccumulated= new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
89
    private static Static4D mTempCurrent    = new Static4D(0,0,0,1);
90
    private static Static4D mTempAccumulated= new Static4D(0,0,0,1);
91

    
92
///////////////////////////////////////////////////////////////////////////////////////////////////
93

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

    
99
      mScreenMin = Math.min(width, height);
100
      }
101

    
102
///////////////////////////////////////////////////////////////////////////////////////////////////
103

    
104
    boolean isVertical()
105
      {
106
      return mScreenHeight>mScreenWidth;
107
      }
108

    
109
///////////////////////////////////////////////////////////////////////////////////////////////////
110

    
111
    RubikRenderer getRenderer()
112
      {
113
      return mRenderer;
114
      }
115

    
116
///////////////////////////////////////////////////////////////////////////////////////////////////
117

    
118
    RubikPreRender getPreRender()
119
      {
120
      return mPreRender;
121
      }
122

    
123
///////////////////////////////////////////////////////////////////////////////////////////////////
124

    
125
    void setQuatAccumulated()
126
      {
127
      mQuatAccumulated.set(mTempAccumulated);
128
      }
129

    
130
///////////////////////////////////////////////////////////////////////////////////////////////////
131

    
132
    void setQuatCurrent()
133
      {
134
      mQuatCurrent.set(mTempCurrent);
135
      }
136

    
137
///////////////////////////////////////////////////////////////////////////////////////////////////
138

    
139
    Static4D getQuatAccumulated()
140
      {
141
      return mQuatAccumulated;
142
      }
143

    
144
///////////////////////////////////////////////////////////////////////////////////////////////////
145

    
146
    Static4D getQuatCurrent()
147
      {
148
      return mQuatCurrent;
149
      }
150

    
151
///////////////////////////////////////////////////////////////////////////////////////////////////
152

    
153
    void setMovement(RubikObjectMovement movement)
154
      {
155
      mMovement = movement;
156
      }
157

    
158
///////////////////////////////////////////////////////////////////////////////////////////////////
159

    
160
    private Static4D quatFromDrag(float dragX, float dragY)
161
      {
162
      float axisX = dragY;  // inverted X and Y - rotation axis is perpendicular to (dragX,dragY)
163
      float axisY = dragX;  // Why not (-dragY, dragX) ? because Y axis is also inverted!
164
      float axisZ = 0;
165
      float axisL = (float)Math.sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);
166

    
167
      if( axisL>0 )
168
        {
169
        axisX /= axisL;
170
        axisY /= axisL;
171
        axisZ /= axisL;
172

    
173
        float ratio = axisL;
174
        ratio = ratio - (int)ratio;     // the cos() is only valid in (0,Pi)
175

    
176
        float cosA = (float)Math.cos(Math.PI*ratio);
177
        float sinA = (float)Math.sqrt(1-cosA*cosA);
178

    
179
        return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
180
        }
181

    
182
      return new Static4D(0f, 0f, 0f, 1f);
183
      }
184

    
185
///////////////////////////////////////////////////////////////////////////////////////////////////
186
// cast the 3D axis we are currently rotating along to the 2D in-screen-surface axis
187

    
188
    private void computeCurrentAxis(Static3D axis)
189
      {
190
      Static4D axis4D = new Static4D(axis.get0(), axis.get1(), axis.get2(), 0);
191
      Static4D result = rotateVectorByQuat(axis4D, mQuatAccumulated);
192

    
193
      mAxisX =result.get0();
194
      mAxisY =result.get1();
195

    
196
      float len = (float)Math.sqrt(mAxisX*mAxisX + mAxisY*mAxisY);
197
      mAxisX /= len;
198
      mAxisY /= len;
199
      }
200

    
201
///////////////////////////////////////////////////////////////////////////////////////////////////
202

    
203
    private float continueRotation(float dx, float dy)
204
      {
205
      float alpha = dx*mAxisX + dy*mAxisY;
206
      float x = dx - alpha*mAxisX;
207
      float y = dy - alpha*mAxisY;
208

    
209
      float len = (float)Math.sqrt(x*x + y*y);
210

    
211
      // we have the length of 1D vector 'angle', now the direction:
212
      float tmp = mAxisY==0 ? -mAxisX*y : mAxisY*x;
213

    
214
      return (tmp>0 ? 1:-1)*len*mRotationFactor;
215
      }
216

    
217
///////////////////////////////////////////////////////////////////////////////////////////////////
218
// return quat1*quat2
219

    
220
    public static Static4D quatMultiply( Static4D quat1, Static4D quat2 )
221
      {
222
      float qx = quat1.get0();
223
      float qy = quat1.get1();
224
      float qz = quat1.get2();
225
      float qw = quat1.get3();
226

    
227
      float rx = quat2.get0();
228
      float ry = quat2.get1();
229
      float rz = quat2.get2();
230
      float rw = quat2.get3();
231

    
232
      float tx = rw*qx - rz*qy + ry*qz + rx*qw;
233
      float ty = rw*qy + rz*qx + ry*qw - rx*qz;
234
      float tz = rw*qz + rz*qw - ry*qx + rx*qy;
235
      float tw = rw*qw - rz*qz - ry*qy - rx*qx;
236

    
237
      return new Static4D(tx,ty,tz,tw);
238
      }
239

    
240
///////////////////////////////////////////////////////////////////////////////////////////////////
241
// rotate 'vector' by quat  ( i.e. return quat*vector*(quat^-1) )
242

    
243
    public static Static4D rotateVectorByQuat(Static4D vector, Static4D quat)
244
      {
245
      float qx = quat.get0();
246
      float qy = quat.get1();
247
      float qz = quat.get2();
248
      float qw = quat.get3();
249

    
250
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
251
      Static4D tmp = quatMultiply(quat,vector);
252

    
253
      return quatMultiply(tmp,quatInverted);
254
      }
255

    
256
///////////////////////////////////////////////////////////////////////////////////////////////////
257
// rotate 'vector' by quat^(-1)  ( i.e. return (quat^-1)*vector*quat )
258

    
259
    public static Static4D rotateVectorByInvertedQuat(Static4D vector, Static4D quat)
260
      {
261
      float qx = quat.get0();
262
      float qy = quat.get1();
263
      float qz = quat.get2();
264
      float qw = quat.get3();
265

    
266
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
267
      Static4D tmp = quatMultiply(quatInverted,vector);
268

    
269
      return quatMultiply(tmp,quat);
270
      }
271

    
272
///////////////////////////////////////////////////////////////////////////////////////////////////
273

    
274
    private void addSpeedProbe(float angle)
275
      {
276
      long currTime = System.currentTimeMillis();
277
      boolean theSame = mLastIndex==mFirstIndex;
278

    
279
      mLastIndex++;
280
      if( mLastIndex>=NUM_SPEED_PROBES ) mLastIndex=0;
281

    
282
      mLastTimestamps[mLastIndex] = currTime;
283
      mLastAngles[mLastIndex] = angle;
284

    
285
      if( mLastIndex==mFirstIndex)
286
        {
287
        mFirstIndex++;
288
        if( mFirstIndex>=NUM_SPEED_PROBES ) mFirstIndex=0;
289
        }
290

    
291
      if( theSame )
292
        {
293
        mLastTimestamps[mFirstIndex] = currTime;
294
        mLastAngles[mFirstIndex] = angle;
295
        }
296
      }
297

    
298
///////////////////////////////////////////////////////////////////////////////////////////////////
299

    
300
    private void computeCurrentSpeed()
301
      {
302
      long firstTime = mLastTimestamps[mFirstIndex];
303
      long lastTime  = mLastTimestamps[mLastIndex];
304
      float firstAngle = mLastAngles[mFirstIndex];
305
      float lastAngle  = mLastAngles[mLastIndex];
306

    
307
      long timeDiff = lastTime-firstTime;
308

    
309
      mLastIndex = 0;
310
      mFirstIndex= 0;
311

    
312
      mCurrRotSpeed = timeDiff>0 ? (lastAngle-firstAngle)/timeDiff : 0;
313
      }
314

    
315
///////////////////////////////////////////////////////////////////////////////////////////////////
316

    
317
    private float retFingerDragDistanceInInches(float xFrom, float yFrom, float xTo, float yTo)
318
      {
319
      float xDist = mScreenWidth*(xFrom-xTo);
320
      float yDist = mScreenHeight*(yFrom-yTo);
321
      float distInPixels = (float)Math.sqrt(xDist*xDist + yDist*yDist);
322

    
323
      return distInPixels/mDensity;
324
      }
325

    
326
///////////////////////////////////////////////////////////////////////////////////////////////////
327

    
328
    private void setUpDragOrRotate(boolean down, float x, float y)
329
      {
330
      int mode = RubikState.getMode();
331

    
332
      if( mode==MODE_DRAG )
333
        {
334
        mDragging           = true;
335
        mBeginningRotation  = false;
336
        mContinuingRotation = false;
337
        }
338
      else
339
        {
340
        Static4D touchPoint1 = new Static4D(x, y, 0, 0);
341
        Static4D rotatedTouchPoint1= rotateVectorByInvertedQuat(touchPoint1, mQuatAccumulated);
342
        Static4D rotatedCamera= rotateVectorByInvertedQuat(CAMERA_POINT, mQuatAccumulated);
343

    
344
        if( mMovement!=null && mMovement.faceTouched(rotatedTouchPoint1,rotatedCamera) )
345
          {
346
          mDragging           = false;
347
          mContinuingRotation = false;
348

    
349
          if( mode==MODE_ROTATE )
350
            {
351
            mBeginningRotation= mPreRender.canRotate();
352
            }
353
          else if( mode==MODE_REPLACE )
354
            {
355
            mBeginningRotation= false;
356

    
357
            if( down )
358
              {
359
              RubikStateSolver solver = (RubikStateSolver) RubikState.SVER.getStateClass();
360
              mLastCubitFace = mMovement.getTouchedFace();
361
              float[] point = mMovement.getTouchedPoint3D();
362
              int color = solver.getCurrentColor();
363
              RubikObject object = mPreRender.getObject();
364
              mLastCubit = object.getCubit(point);
365
              mPreRender.setTextureMap( mLastCubit, mLastCubitFace, color );
366
              mLastCubitColor = SolverMain.cubitIsLocked(object.getObjectList(), object.getSize(), mLastCubit);
367
              }
368
            }
369
          }
370
        else
371
          {
372
          mDragging           = true;
373
          mBeginningRotation  = false;
374
          mContinuingRotation = false;
375
          }
376
        }
377
      }
378

    
379
///////////////////////////////////////////////////////////////////////////////////////////////////
380

    
381
    private void actionDown(float x, float y)
382
      {
383
      mX = x;
384
      mY = y;
385
      setUpDragOrRotate(true,x,y);
386
      }
387

    
388
///////////////////////////////////////////////////////////////////////////////////////////////////
389

    
390
    private void actionMove(float x, float y)
391
      {
392
      if( mBeginningRotation )
393
        {
394
        if( retFingerDragDistanceInInches(mX,mY,x,y) > ROTATION_SENSITIVITY )
395
          {
396
          mStartRotX = x;
397
          mStartRotY = y;
398

    
399
          Static4D touchPoint2 = new Static4D(x, y, 0, 0);
400
          Static4D rotatedTouchPoint2= rotateVectorByInvertedQuat(touchPoint2, mQuatAccumulated);
401

    
402
          Static2D res = mMovement.newRotation(rotatedTouchPoint2);
403
          RubikObject object = mPreRender.getObject();
404

    
405
          mCurrentAxis = (int)res.get0();
406
          float offset = res.get1();
407
          mCurrentRow = (int)(object.returnMultiplier()*offset);
408
          computeCurrentAxis( object.getRotationAxis()[mCurrentAxis] );
409
          mRotationFactor = object.returnRotationFactor(offset);
410

    
411
          object.beginNewRotation( mCurrentAxis, mCurrentRow );
412

    
413
          if( RubikState.getCurrentState()==RubikState.READ )
414
            {
415
            RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
416
            solving.resetElapsed();
417

    
418
            final RubikActivity act = (RubikActivity)getContext();
419

    
420
            act.runOnUiThread(new Runnable()
421
              {
422
              @Override
423
              public void run()
424
                {
425
                RubikState.switchState( act, RubikState.SOLV);
426
                }
427
              });
428
            }
429

    
430
          addSpeedProbe(0.0f);
431

    
432
          mBeginningRotation = false;
433
          mContinuingRotation= true;
434
          }
435
        }
436
      else if( mContinuingRotation )
437
        {
438
        float angle = continueRotation(x-mStartRotX,y-mStartRotY);
439
        mCurrentAngle = SWIPING_SENSITIVITY*angle;
440
        mPreRender.getObject().continueRotation(mCurrentAngle);
441

    
442
        addSpeedProbe(mCurrentAngle);
443
        }
444
      else if( mDragging )
445
        {
446
        mTempCurrent.set(quatFromDrag(mX-x,y-mY));
447
        mPreRender.setQuatCurrentOnNextRender();
448

    
449
        if( retFingerDragDistanceInInches(mX,mY,x,y) > DIRECTION_SENSITIVITY )
450
          {
451
          mX = x;
452
          mY = y;
453
          mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
454
          mTempCurrent.set(0f, 0f, 0f, 1f);
455
          mPreRender.setQuatCurrentOnNextRender();
456
          mPreRender.setQuatAccumulatedOnNextRender();
457
          }
458
        }
459
      else
460
        {
461
        setUpDragOrRotate(false,x,y);
462
        }
463
      }
464

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

    
467
    private void actionUp()
468
      {
469
      if( mDragging )
470
        {
471
        mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
472
        mTempCurrent.set(0f, 0f, 0f, 1f);
473
        mPreRender.setQuatCurrentOnNextRender();
474
        mPreRender.setQuatAccumulatedOnNextRender();
475
        }
476

    
477
      if( mContinuingRotation )
478
        {
479
        computeCurrentSpeed();
480
        int angle = mPreRender.getObject().computeNearestAngle(mCurrentAngle, mCurrRotSpeed);
481
        mPreRender.finishRotation(angle);
482

    
483
        if( RubikState.getCurrentState()==RubikState.SOLV && angle!=0 )
484
          {
485
          RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
486
          solving.addMove(mCurrentAxis, mCurrentRow, angle);
487
          }
488
        }
489

    
490
      if( mLastCubitColor>=0 )
491
        {
492
        mPreRender.setTextureMap( mLastCubit, mLastCubitFace, mLastCubitColor );
493
        }
494
      }
495

    
496
///////////////////////////////////////////////////////////////////////////////////////////////////
497
// PUBLIC API
498
///////////////////////////////////////////////////////////////////////////////////////////////////
499

    
500
    public RubikSurfaceView(Context context, AttributeSet attrs)
501
      {
502
      super(context,attrs);
503

    
504
      if(!isInEditMode())
505
        {
506
        mLastCubitColor = -1;
507
        mCurrRotSpeed   = 0.0f;
508

    
509
        mLastAngles = new float[NUM_SPEED_PROBES];
510
        mLastTimestamps = new long[NUM_SPEED_PROBES];
511
        mFirstIndex =0;
512
        mLastIndex  =0;
513

    
514
        mRenderer  = new RubikRenderer(this);
515
        mPreRender = new RubikPreRender(this);
516

    
517
        RubikActivity act = (RubikActivity)context;
518
        DisplayMetrics dm = new DisplayMetrics();
519
        act.getWindowManager().getDefaultDisplay().getMetrics(dm);
520

    
521
        mDensity = dm.densityDpi;
522

    
523
        final ActivityManager activityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
524

    
525
        if( activityManager!=null )
526
          {
527
          final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
528
          setEGLContextClientVersion( (configurationInfo.reqGlEsVersion>>16) >= 3 ? 3:2 );
529
          setRenderer(mRenderer);
530
          }
531
        }
532
      }
533

    
534
///////////////////////////////////////////////////////////////////////////////////////////////////
535

    
536
    @Override
537
    public boolean onTouchEvent(MotionEvent event)
538
      {
539
      int action = event.getAction();
540
      float x = (event.getX() - mScreenWidth*0.5f)/mScreenMin;
541
      float y = (mScreenHeight*0.5f -event.getY())/mScreenMin;
542

    
543
      switch(action)
544
         {
545
         case MotionEvent.ACTION_DOWN: actionDown(x,y); break;
546
         case MotionEvent.ACTION_MOVE: actionMove(x,y); break;
547
         case MotionEvent.ACTION_UP  : actionUp()     ; break;
548
         }
549

    
550
      return true;
551
      }
552
}
553

    
(4-4/4)