Project

General

Profile

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

magiccube / src / main / java / org / distorted / main / RubikSurfaceView.java @ 168b6b56

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.view.MotionEvent;
28

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

    
39
///////////////////////////////////////////////////////////////////////////////////////////////////
40

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

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

    
49
    // Moving the finger from the middle of the vertical screen to the right edge will rotate a
50
    // given face by SWIPING_SENSITIVITY/2 degrees.
51
    private final static int SWIPING_SENSITIVITY  = 240;
52
    // Moving the finger by 1/15 the distance of min(scrWidth,scrHeight) will start a Rotation.
53
    private final static int ROTATION_SENSITIVITY =  15;
54
    // Every 1/12 the distance of min(scrWidth,scrHeight) the direction of cube rotation will reset.
55
    private final static int DIRECTION_SENSITIVITY=  12;
56

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

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

    
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[] mLastAngles;
82
    private long[] mLastTimestamps;
83
    private int mFirstIndex, mLastIndex;
84

    
85
    private static Static4D mQuatCurrent    = new Static4D(0,0,0,1);
86
    private static Static4D mQuatAccumulated= new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
87
    private static Static4D mTempCurrent    = new Static4D(0,0,0,1);
88
    private static Static4D mTempAccumulated= 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 setQuatAccumulated()
124
      {
125
      mQuatAccumulated.set(mTempAccumulated);
126
      }
127

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

    
130
    void setQuatCurrent()
131
      {
132
      mQuatCurrent.set(mTempCurrent);
133
      }
134

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

    
137
    Static4D getQuatAccumulated()
138
      {
139
      return mQuatAccumulated;
140
      }
141

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

    
144
    Static4D getQuatCurrent()
145
      {
146
      return mQuatCurrent;
147
      }
148

    
149
///////////////////////////////////////////////////////////////////////////////////////////////////
150

    
151
    void setMovement(RubikObjectMovement movement)
152
      {
153
      mMovement = movement;
154
      }
155

    
156
///////////////////////////////////////////////////////////////////////////////////////////////////
157

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

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

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

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

    
177
        return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
178
        }
179

    
180
      return new Static4D(0f, 0f, 0f, 1f);
181
      }
182

    
183
///////////////////////////////////////////////////////////////////////////////////////////////////
184

    
185
    private void setUpDragOrRotate(boolean down, float x, float y)
186
      {
187
      int mode = RubikState.getMode();
188

    
189
      if( mode==MODE_DRAG )
190
        {
191
        mDragging           = true;
192
        mBeginningRotation  = false;
193
        mContinuingRotation = false;
194
        }
195
      else
196
        {
197
        Static4D touchPoint1 = new Static4D(x, y, 0, 0);
198
        Static4D rotatedTouchPoint1= rotateVectorByInvertedQuat(touchPoint1, mQuatAccumulated);
199
        Static4D rotatedCamera= rotateVectorByInvertedQuat(CAMERA_POINT, mQuatAccumulated);
200

    
201
        if( mMovement!=null && mMovement.faceTouched(rotatedTouchPoint1,rotatedCamera) )
202
          {
203
          mDragging           = false;
204
          mContinuingRotation = false;
205

    
206
          if( mode==MODE_ROTATE )
207
            {
208
            mBeginningRotation= mPreRender.canRotate();
209
            }
210
          else if( mode==MODE_REPLACE )
211
            {
212
            mBeginningRotation= false;
213

    
214
            if( down )
215
              {
216
              RubikStateSolver solver = (RubikStateSolver) RubikState.SVER.getStateClass();
217
              mLastCubitFace = mMovement.getTouchedFace();
218
              float[] point = mMovement.getTouchedPoint3D();
219
              int color = solver.getCurrentColor();
220
              RubikObject object = mPreRender.getObject();
221
              mLastCubit = object.getCubit(point);
222
              mPreRender.setTextureMap( mLastCubit, mLastCubitFace, color );
223
              mLastCubitColor = SolverMain.cubitIsLocked(object.getObjectList(), object.getSize(), mLastCubit);
224
              }
225
            }
226
          }
227
        else
228
          {
229
          mDragging           = true;
230
          mBeginningRotation  = false;
231
          mContinuingRotation = false;
232
          }
233
        }
234
      }
235

    
236
///////////////////////////////////////////////////////////////////////////////////////////////////
237
// cast the 3D axis we are currently rotating along to the 2D in-screen-surface axis
238

    
239
    private void computeCurrentAxis(Static3D axis)
240
      {
241
      Static4D axis4D = new Static4D(axis.get0(), axis.get1(), axis.get2(), 0);
242
      Static4D result = rotateVectorByQuat(axis4D, mQuatAccumulated);
243

    
244
      mAxisX =result.get0();
245
      mAxisY =result.get1();
246

    
247
      float len = (float)Math.sqrt(mAxisX*mAxisX + mAxisY*mAxisY);
248
      mAxisX /= len;
249
      mAxisY /= len;
250
      }
251

    
252
///////////////////////////////////////////////////////////////////////////////////////////////////
253

    
254
    private float continueRotation(float dx, float dy)
255
      {
256
      float alpha = dx*mAxisX + dy*mAxisY;
257
      float x = dx - alpha*mAxisX;
258
      float y = dy - alpha*mAxisY;
259

    
260
      float len = (float)Math.sqrt(x*x + y*y);
261

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

    
265
      return (tmp>0 ? 1:-1)*len*mRotationFactor;
266
      }
267

    
268
///////////////////////////////////////////////////////////////////////////////////////////////////
269
// return quat1*quat2
270

    
271
    public static Static4D quatMultiply( Static4D quat1, Static4D quat2 )
272
      {
273
      float qx = quat1.get0();
274
      float qy = quat1.get1();
275
      float qz = quat1.get2();
276
      float qw = quat1.get3();
277

    
278
      float rx = quat2.get0();
279
      float ry = quat2.get1();
280
      float rz = quat2.get2();
281
      float rw = quat2.get3();
282

    
283
      float tx = rw*qx - rz*qy + ry*qz + rx*qw;
284
      float ty = rw*qy + rz*qx + ry*qw - rx*qz;
285
      float tz = rw*qz + rz*qw - ry*qx + rx*qy;
286
      float tw = rw*qw - rz*qz - ry*qy - rx*qx;
287

    
288
      return new Static4D(tx,ty,tz,tw);
289
      }
290

    
291
///////////////////////////////////////////////////////////////////////////////////////////////////
292
// rotate 'vector' by quat  ( i.e. return quat*vector*(quat^-1) )
293

    
294
    public static Static4D rotateVectorByQuat(Static4D vector, Static4D quat)
295
      {
296
      float qx = quat.get0();
297
      float qy = quat.get1();
298
      float qz = quat.get2();
299
      float qw = quat.get3();
300

    
301
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
302
      Static4D tmp = quatMultiply(quat,vector);
303

    
304
      return quatMultiply(tmp,quatInverted);
305
      }
306

    
307
///////////////////////////////////////////////////////////////////////////////////////////////////
308
// rotate 'vector' by quat^(-1)  ( i.e. return (quat^-1)*vector*quat )
309

    
310
    public static Static4D rotateVectorByInvertedQuat(Static4D vector, Static4D quat)
311
      {
312
      float qx = quat.get0();
313
      float qy = quat.get1();
314
      float qz = quat.get2();
315
      float qw = quat.get3();
316

    
317
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
318
      Static4D tmp = quatMultiply(quatInverted,vector);
319

    
320
      return quatMultiply(tmp,quat);
321
      }
322

    
323
///////////////////////////////////////////////////////////////////////////////////////////////////
324

    
325
    private void addSpeedProbe(float angle)
326
      {
327
      long currTime = System.currentTimeMillis();
328
      boolean theSame = mLastIndex==mFirstIndex;
329

    
330
      mLastIndex++;
331
      if( mLastIndex>=NUM_SPEED_PROBES ) mLastIndex=0;
332

    
333
      mLastTimestamps[mLastIndex] = currTime;
334
      mLastAngles[mLastIndex] = angle;
335

    
336
      if( mLastIndex==mFirstIndex)
337
        {
338
        mFirstIndex++;
339
        if( mFirstIndex>=NUM_SPEED_PROBES ) mFirstIndex=0;
340
        }
341

    
342
      if( theSame )
343
        {
344
        mLastTimestamps[mFirstIndex] = currTime;
345
        mLastAngles[mFirstIndex] = angle;
346
        }
347
      }
348

    
349
///////////////////////////////////////////////////////////////////////////////////////////////////
350

    
351
    private void computeCurrentSpeed()
352
      {
353
      long firstTime = mLastTimestamps[mFirstIndex];
354
      long lastTime  = mLastTimestamps[mLastIndex];
355
      float firstAngle = mLastAngles[mFirstIndex];
356
      float lastAngle  = mLastAngles[mLastIndex];
357

    
358
      long timeDiff = lastTime-firstTime;
359

    
360
      mLastIndex = 0;
361
      mFirstIndex= 0;
362

    
363
      mCurrRotSpeed = timeDiff>0 ? (lastAngle-firstAngle)/timeDiff : 0;
364
      }
365

    
366
///////////////////////////////////////////////////////////////////////////////////////////////////
367
// PUBLIC API
368
///////////////////////////////////////////////////////////////////////////////////////////////////
369

    
370
    public RubikSurfaceView(Context context, AttributeSet attrs)
371
      {
372
      super(context,attrs);
373

    
374
      if(!isInEditMode())
375
        {
376
        mLastCubitColor = -1;
377
        mCurrRotSpeed   = 0.0f;
378

    
379
        mLastAngles = new float[NUM_SPEED_PROBES];
380
        mLastTimestamps = new long[NUM_SPEED_PROBES];
381
        mFirstIndex =0;
382
        mLastIndex  =0;
383

    
384
        mRenderer  = new RubikRenderer(this);
385
        mPreRender = new RubikPreRender(this);
386

    
387
        final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
388
        final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
389
        setEGLContextClientVersion( (configurationInfo.reqGlEsVersion>>16) >= 3 ? 3:2 );
390
        setRenderer(mRenderer);
391
        }
392
      }
393

    
394
///////////////////////////////////////////////////////////////////////////////////////////////////
395

    
396
    @Override
397
    public boolean onTouchEvent(MotionEvent event)
398
      {
399
      int action = event.getAction();
400
      float x = (event.getX() - mScreenWidth*0.5f)/mScreenMin;
401
      float y = (mScreenHeight*0.5f -event.getY())/mScreenMin;
402

    
403
      switch(action)
404
         {
405
         case MotionEvent.ACTION_DOWN: mX = x;
406
                                       mY = y;
407
                                       setUpDragOrRotate(true,x,y);
408
                                       break;
409
         case MotionEvent.ACTION_MOVE: if( mBeginningRotation )
410
                                         {
411
                                         if( (mX-x)*(mX-x)+(mY-y)*(mY-y) > 1.0f/(ROTATION_SENSITIVITY*ROTATION_SENSITIVITY) )
412
                                           {
413
                                           mStartRotX = x;
414
                                           mStartRotY = y;
415

    
416
                                           Static4D touchPoint2 = new Static4D(x, y, 0, 0);
417
                                           Static4D rotatedTouchPoint2= rotateVectorByInvertedQuat(touchPoint2, mQuatAccumulated);
418

    
419
                                           Static2D res = mMovement.newRotation(rotatedTouchPoint2);
420
                                           RubikObject object = mPreRender.getObject();
421

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

    
428
                                           object.beginNewRotation( mCurrentAxis, mCurrentRow );
429

    
430
                                           if( RubikState.getCurrentState()==RubikState.READ )
431
                                             {
432
                                             RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
433
                                             solving.resetElapsed();
434

    
435
                                             final RubikActivity act = (RubikActivity)getContext();
436

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

    
447
                                           addSpeedProbe(0.0f);
448

    
449
                                           mBeginningRotation = false;
450
                                           mContinuingRotation= true;
451
                                           }
452
                                         }
453
                                       else if( mContinuingRotation )
454
                                         {
455
                                         float angle = continueRotation(x-mStartRotX,y-mStartRotY);
456
                                         mCurrentAngle = SWIPING_SENSITIVITY*angle;
457
                                         mPreRender.getObject().continueRotation(mCurrentAngle);
458

    
459
                                         addSpeedProbe(mCurrentAngle);
460
                                         }
461
                                       else if( mDragging )
462
                                         {
463
                                         mTempCurrent.set(quatFromDrag(mX-x,y-mY));
464
                                         mPreRender.setQuatCurrentOnNextRender();
465

    
466
                                         if( (mX-x)*(mX-x) + (mY-y)*(mY-y) > 1.0f/(DIRECTION_SENSITIVITY*DIRECTION_SENSITIVITY) )
467
                                           {
468
                                           mX = x;
469
                                           mY = y;
470
                                           mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
471
                                           mTempCurrent.set(0f, 0f, 0f, 1f);
472
                                           mPreRender.setQuatCurrentOnNextRender();
473
                                           mPreRender.setQuatAccumulatedOnNextRender();
474
                                           }
475
                                         }
476
                                       else
477
                                         {
478
                                         setUpDragOrRotate(false,x,y);
479
                                         }
480
                                       break;
481
         case MotionEvent.ACTION_UP  : if( mDragging )
482
                                         {
483
                                         mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
484
                                         mTempCurrent.set(0f, 0f, 0f, 1f);
485
                                         mPreRender.setQuatCurrentOnNextRender();
486
                                         mPreRender.setQuatAccumulatedOnNextRender();
487
                                         }
488

    
489
                                       if( mContinuingRotation )
490
                                         {
491
                                         computeCurrentSpeed();
492
                                         int angle = mPreRender.getObject().computeNearestAngle(mCurrentAngle, mCurrRotSpeed);
493
                                         mPreRender.finishRotation(angle);
494

    
495
                                         if( RubikState.getCurrentState()==RubikState.SOLV )
496
                                           {
497
                                           RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
498

    
499
                                           if( angle!=0 )
500
                                             solving.addMove(mCurrentAxis, mCurrentRow, angle);
501
                                           }
502
                                         }
503
                                       if( mLastCubitColor>=0 )
504
                                         {
505
                                          mPreRender.setTextureMap( mLastCubit, mLastCubitFace, mLastCubitColor );
506
                                         }
507
                                       break;
508
         }
509

    
510
      return true;
511
      }
512
}
513

    
(4-4/4)