Project

General

Profile

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

magiccube / src / main / java / org / distorted / main / RubikSurfaceView.java @ 46a961fd

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
    public static final int MODE_ROTATE  = 0;
44
    public static final int MODE_DRAG    = 1;
45
    public static final int MODE_REPLACE = 2;
46

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

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

    
66
    private RubikRenderer mRenderer;
67
    private RubikPostRender mPostRender;
68
    private RubikObjectMovement mMovement;
69
    private boolean mDragging, mBeginningRotation, mContinuingRotation;
70
    private int mScreenWidth, mScreenHeight, mScreenMin;
71

    
72
    private float mX, mY;
73
    private float mStartRotX, mStartRotY;
74
    private float mAxisX, mAxisY;
75
    private float mRotationFactor;
76
    private int mLastCubitColor, mLastCubitFace, mLastCubit;
77

    
78
    private static Static4D mQuatCurrent    = new Static4D(0,0,0,1);
79
    private static Static4D mQuatAccumulated= new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
80
    private static Static4D mTempCurrent    = new Static4D(0,0,0,1);
81
    private static Static4D mTempAccumulated= new Static4D(0,0,0,1);
82

    
83
///////////////////////////////////////////////////////////////////////////////////////////////////
84

    
85
    void setScreenSize(int width, int height)
86
      {
87
      mScreenWidth = width;
88
      mScreenHeight= height;
89

    
90
      mScreenMin = Math.min(width, height);
91
      }
92

    
93
///////////////////////////////////////////////////////////////////////////////////////////////////
94

    
95
    boolean isVertical()
96
      {
97
      return mScreenHeight>mScreenWidth;
98
      }
99

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

    
102
    RubikRenderer getRenderer()
103
      {
104
      return mRenderer;
105
      }
106

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

    
109
    RubikPostRender getPostRender()
110
      {
111
      return mPostRender;
112
      }
113

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

    
116
    void setQuatAccumulated()
117
      {
118
      mQuatAccumulated.set(mTempAccumulated);
119
      }
120

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

    
123
    void setQuatCurrent()
124
      {
125
      mQuatCurrent.set(mTempCurrent);
126
      }
127

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

    
130
    Static4D getQuatAccumulated()
131
      {
132
      return mQuatAccumulated;
133
      }
134

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

    
137
    Static4D getQuatCurrent()
138
      {
139
      return mQuatCurrent;
140
      }
141

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

    
144
    void setMovement(RubikObjectMovement movement)
145
      {
146
      mMovement = movement;
147
      }
148

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

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

    
158
      if( axisL>0 )
159
        {
160
        axisX /= axisL;
161
        axisY /= axisL;
162
        axisZ /= axisL;
163

    
164
        float ratio = axisL;
165
        ratio = ratio - (int)ratio;     // the cos() is only valid in (0,Pi)
166

    
167
        float cosA = (float)Math.cos(Math.PI*ratio);
168
        float sinA = (float)Math.sqrt(1-cosA*cosA);
169

    
170
        return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
171
        }
172

    
173
      return new Static4D(0f, 0f, 0f, 1f);
174
      }
175

    
176
///////////////////////////////////////////////////////////////////////////////////////////////////
177

    
178
    private void setUpDragOrRotate(boolean down, float x, float y)
179
      {
180
      int mode = RubikState.getMode();
181

    
182
      if( mode==MODE_DRAG )
183
        {
184
        mDragging           = true;
185
        mBeginningRotation  = false;
186
        mContinuingRotation = false;
187
        }
188
      else
189
        {
190
        Static4D touchPoint1 = new Static4D(x, y, 0, 0);
191
        Static4D rotatedTouchPoint1= rotateVectorByInvertedQuat(touchPoint1, mQuatAccumulated);
192
        Static4D rotatedCamera= rotateVectorByInvertedQuat(CAMERA_POINT, mQuatAccumulated);
193

    
194
        if( mMovement!=null && mMovement.faceTouched(rotatedTouchPoint1,rotatedCamera) )
195
          {
196
          mDragging           = false;
197
          mContinuingRotation = false;
198

    
199
          if( mode==MODE_ROTATE )
200
            {
201
            mBeginningRotation= mPostRender.canRotate();
202
            }
203
          else if( mode==MODE_REPLACE )
204
            {
205
            mBeginningRotation= false;
206

    
207
            if( down )
208
              {
209
              RubikStateSolver solver = (RubikStateSolver) RubikState.SVER.getStateClass();
210
              mLastCubitFace = mMovement.getTouchedFace();
211
              float[] point = mMovement.getTouchedPoint3D();
212
              int color = solver.getCurrentColor();
213
              RubikObject object = mPostRender.getObject();
214
              mLastCubit = object.getCubit(point);
215
              mPostRender.setTextureMap( mLastCubit, mLastCubitFace, color );
216
              mLastCubitColor = SolverMain.cubitIsLocked(object.getObjectList(), object.getSize(), mLastCubit);
217
              }
218
            }
219
          }
220
        else
221
          {
222
          mDragging           = true;
223
          mBeginningRotation  = false;
224
          mContinuingRotation = false;
225
          }
226
        }
227
      }
228

    
229
///////////////////////////////////////////////////////////////////////////////////////////////////
230
// cast the 3D axis we are currently rotating along to the 2D in-screen-surface axis
231

    
232
    private void computeCurrentAxis(Static3D axis)
233
      {
234
      Static4D axis4D = new Static4D(axis.get0(), axis.get1(), axis.get2(), 0);
235
      Static4D result = rotateVectorByQuat(axis4D, mQuatAccumulated);
236

    
237
      mAxisX =result.get0();
238
      mAxisY =result.get1();
239

    
240
      float len = (float)Math.sqrt(mAxisX*mAxisX + mAxisY*mAxisY);
241
      mAxisX /= len;
242
      mAxisY /= len;
243
      }
244

    
245
///////////////////////////////////////////////////////////////////////////////////////////////////
246

    
247
    private float continueRotation(float dx, float dy)
248
      {
249
      float alpha = dx*mAxisX + dy*mAxisY;
250
      float x = dx - alpha*mAxisX;
251
      float y = dy - alpha*mAxisY;
252

    
253
      float len = (float)Math.sqrt(x*x + y*y);
254

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

    
258
      return (tmp>0 ? 1:-1)*len*mRotationFactor;
259
      }
260

    
261
///////////////////////////////////////////////////////////////////////////////////////////////////
262
// return quat1*quat2
263

    
264
    public static Static4D quatMultiply( Static4D quat1, Static4D quat2 )
265
      {
266
      float qx = quat1.get0();
267
      float qy = quat1.get1();
268
      float qz = quat1.get2();
269
      float qw = quat1.get3();
270

    
271
      float rx = quat2.get0();
272
      float ry = quat2.get1();
273
      float rz = quat2.get2();
274
      float rw = quat2.get3();
275

    
276
      float tx = rw*qx - rz*qy + ry*qz + rx*qw;
277
      float ty = rw*qy + rz*qx + ry*qw - rx*qz;
278
      float tz = rw*qz + rz*qw - ry*qx + rx*qy;
279
      float tw = rw*qw - rz*qz - ry*qy - rx*qx;
280

    
281
      return new Static4D(tx,ty,tz,tw);
282
      }
283

    
284
///////////////////////////////////////////////////////////////////////////////////////////////////
285
// rotate 'vector' by quat  ( i.e. return quat*vector*(quat^-1) )
286

    
287
    public static Static4D rotateVectorByQuat(Static4D vector, Static4D quat)
288
      {
289
      float qx = quat.get0();
290
      float qy = quat.get1();
291
      float qz = quat.get2();
292
      float qw = quat.get3();
293

    
294
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
295
      Static4D tmp = quatMultiply(quat,vector);
296

    
297
      return quatMultiply(tmp,quatInverted);
298
      }
299

    
300
///////////////////////////////////////////////////////////////////////////////////////////////////
301
// rotate 'vector' by quat^(-1)  ( i.e. return (quat^-1)*vector*quat )
302

    
303
    public static Static4D rotateVectorByInvertedQuat(Static4D vector, Static4D quat)
304
      {
305
      float qx = quat.get0();
306
      float qy = quat.get1();
307
      float qz = quat.get2();
308
      float qw = quat.get3();
309

    
310
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
311
      Static4D tmp = quatMultiply(quatInverted,vector);
312

    
313
      return quatMultiply(tmp,quat);
314
      }
315

    
316
///////////////////////////////////////////////////////////////////////////////////////////////////
317
// PUBLIC API
318
///////////////////////////////////////////////////////////////////////////////////////////////////
319

    
320
    public RubikSurfaceView(Context context, AttributeSet attrs)
321
      {
322
      super(context,attrs);
323

    
324
      if(!isInEditMode())
325
        {
326
        mRenderer   = new RubikRenderer(this);
327
        mPostRender = new RubikPostRender(this);
328

    
329
        final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
330
        final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
331
        setEGLContextClientVersion( (configurationInfo.reqGlEsVersion>>16) >= 3 ? 3:2 );
332
        setRenderer(mRenderer);
333
        }
334
      }
335

    
336
///////////////////////////////////////////////////////////////////////////////////////////////////
337

    
338
    @Override
339
    public boolean onTouchEvent(MotionEvent event)
340
      {
341
      int action = event.getAction();
342
      float x = (event.getX() - mScreenWidth*0.5f)/mScreenMin;
343
      float y = (mScreenHeight*0.5f -event.getY())/mScreenMin;
344

    
345
      switch(action)
346
         {
347
         case MotionEvent.ACTION_DOWN: mX = x;
348
                                       mY = y;
349
                                       setUpDragOrRotate(true,x,y);
350
                                       break;
351
         case MotionEvent.ACTION_MOVE: if( mBeginningRotation )
352
                                         {
353
                                         if( (mX-x)*(mX-x)+(mY-y)*(mY-y) > 1.0f/(ROTATION_SENSITIVITY*ROTATION_SENSITIVITY) )
354
                                           {
355
                                           mStartRotX = x;
356
                                           mStartRotY = y;
357

    
358
                                           Static4D touchPoint2 = new Static4D(x, y, 0, 0);
359
                                           Static4D rotatedTouchPoint2= rotateVectorByInvertedQuat(touchPoint2, mQuatAccumulated);
360

    
361
                                           Static2D res = mMovement.newRotation(rotatedTouchPoint2);
362
                                           RubikObject object = mPostRender.getObject();
363

    
364
                                           int axis = (int)res.get0();
365
                                           float offset = res.get1();
366
                                           computeCurrentAxis( object.getRotationAxis()[axis] );
367
                                           mRotationFactor = object.returnRotationFactor(offset);
368

    
369
                                           object.beginNewRotation( axis, (int)(object.returnMultiplier()*offset) );
370

    
371
                                           if( RubikState.getCurrentState()==RubikState.SOLV )
372
                                             {
373
                                             RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
374
                                             solving.startCounting( (RubikActivity)getContext() );
375
                                             }
376

    
377
                                           mBeginningRotation = false;
378
                                           mContinuingRotation= true;
379
                                           }
380
                                         }
381
                                       else if( mContinuingRotation )
382
                                         {
383
                                         float angle = continueRotation(x-mStartRotX,y-mStartRotY);
384
                                         mPostRender.getObject().continueRotation(SWIPING_SENSITIVITY*angle);
385
                                         }
386
                                       else if( mDragging )
387
                                         {
388
                                         mTempCurrent.set(quatFromDrag(mX-x,y-mY));
389
                                         mPostRender.setQuatCurrentOnNextRender();
390

    
391
                                         if( (mX-x)*(mX-x) + (mY-y)*(mY-y) > 1.0f/(DIRECTION_SENSITIVITY*DIRECTION_SENSITIVITY) )
392
                                           {
393
                                           mX = x;
394
                                           mY = y;
395
                                           mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
396
                                           mTempCurrent.set(0f, 0f, 0f, 1f);
397
                                           mPostRender.setQuatCurrentOnNextRender();
398
                                           mPostRender.setQuatAccumulatedOnNextRender();
399
                                           }
400
                                         }
401
                                       else
402
                                         {
403
                                         setUpDragOrRotate(false,x,y);
404
                                         }
405
                                       break;
406
         case MotionEvent.ACTION_UP  : if( mDragging )
407
                                         {
408
                                         mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
409
                                         mTempCurrent.set(0f, 0f, 0f, 1f);
410
                                         mPostRender.setQuatCurrentOnNextRender();
411
                                         mPostRender.setQuatAccumulatedOnNextRender();
412
                                         }
413

    
414
                                       if( mContinuingRotation )
415
                                         {
416
                                         mPostRender.finishRotation();
417
                                         }
418
                                       if( mLastCubitColor>=0 )
419
                                         {
420
                                          mPostRender.setTextureMap( mLastCubit, mLastCubitFace, mLastCubitColor );
421
                                         }
422
                                       break;
423
         }
424

    
425
      return true;
426
      }
427
}
428

    
(4-4/4)