Project

General

Profile

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

magiccube / src / main / java / org / distorted / main / RubikSurfaceView.java @ 9621255f

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.states.RubikState;
35
import org.distorted.states.RubikStateSolver;
36
import org.distorted.states.RubikStateSolving;
37

    
38
///////////////////////////////////////////////////////////////////////////////////////////////////
39

    
40
public class RubikSurfaceView extends GLSurfaceView
41
{
42
    public static final int MODE_ROTATE  = 0;
43
    public static final int MODE_DRAG    = 1;
44
    public static final int MODE_REPLACE = 2;
45

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

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

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

    
71
    private float mX, mY;
72
    private float mStartRotX, mStartRotY;
73
    private float mAxisX, mAxisY;
74
    private float mRotationFactor;
75

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

    
81
///////////////////////////////////////////////////////////////////////////////////////////////////
82

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

    
88
      mScreenMin = Math.min(width, height);
89
      }
90

    
91
///////////////////////////////////////////////////////////////////////////////////////////////////
92

    
93
    boolean isVertical()
94
      {
95
      return mScreenHeight>mScreenWidth;
96
      }
97

    
98
///////////////////////////////////////////////////////////////////////////////////////////////////
99

    
100
    RubikRenderer getRenderer()
101
      {
102
      return mRenderer;
103
      }
104

    
105
///////////////////////////////////////////////////////////////////////////////////////////////////
106

    
107
    RubikPostRender getPostRender()
108
      {
109
      return mPostRender;
110
      }
111

    
112
///////////////////////////////////////////////////////////////////////////////////////////////////
113

    
114
    void setQuatAccumulated()
115
      {
116
      mQuatAccumulated.set(mTempAccumulated);
117
      }
118

    
119
///////////////////////////////////////////////////////////////////////////////////////////////////
120

    
121
    void setQuatCurrent()
122
      {
123
      mQuatCurrent.set(mTempCurrent);
124
      }
125

    
126
///////////////////////////////////////////////////////////////////////////////////////////////////
127

    
128
    Static4D getQuatAccumulated()
129
      {
130
      return mQuatAccumulated;
131
      }
132

    
133
///////////////////////////////////////////////////////////////////////////////////////////////////
134

    
135
    Static4D getQuatCurrent()
136
      {
137
      return mQuatCurrent;
138
      }
139

    
140
///////////////////////////////////////////////////////////////////////////////////////////////////
141

    
142
    void setMovement(RubikObjectMovement movement)
143
      {
144
      mMovement = movement;
145
      }
146

    
147
///////////////////////////////////////////////////////////////////////////////////////////////////
148

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

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

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

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

    
168
        return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
169
        }
170

    
171
      return new Static4D(0f, 0f, 0f, 1f);
172
      }
173

    
174
///////////////////////////////////////////////////////////////////////////////////////////////////
175

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

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

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

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

    
205
            if( down )
206
              {
207
              RubikStateSolver solver = (RubikStateSolver) RubikState.SVER.getStateClass();
208
              int face      = mMovement.getTouchedFace();
209
              float[] point = mMovement.getTouchedPoint3D();
210
              int color = solver.getCurrentColor();
211
              RubikObject object = mPostRender.getObject();
212
              int cubit = object.getCubit(point);
213

    
214
              mPostRender.setTextureMap( cubit, face, color );
215
              }
216
            }
217
          }
218
        else
219
          {
220
          mDragging           = true;
221
          mBeginningRotation  = false;
222
          mContinuingRotation = false;
223
          }
224
        }
225
      }
226

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

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

    
235
      mAxisX =result.get0();
236
      mAxisY =result.get1();
237

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

    
243
///////////////////////////////////////////////////////////////////////////////////////////////////
244

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

    
251
      float len = (float)Math.sqrt(x*x + y*y);
252

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

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

    
259
///////////////////////////////////////////////////////////////////////////////////////////////////
260
// return quat1*quat2
261

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

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

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

    
279
      return new Static4D(tx,ty,tz,tw);
280
      }
281

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

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

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

    
295
      return quatMultiply(tmp,quatInverted);
296
      }
297

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

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

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

    
311
      return quatMultiply(tmp,quat);
312
      }
313

    
314
///////////////////////////////////////////////////////////////////////////////////////////////////
315
// PUBLIC API
316
///////////////////////////////////////////////////////////////////////////////////////////////////
317

    
318
    public RubikSurfaceView(Context context, AttributeSet attrs)
319
      {
320
      super(context,attrs);
321

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

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

    
334
///////////////////////////////////////////////////////////////////////////////////////////////////
335

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

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

    
356
                                           Static4D touchPoint2 = new Static4D(x, y, 0, 0);
357
                                           Static4D rotatedTouchPoint2= rotateVectorByInvertedQuat(touchPoint2, mQuatAccumulated);
358

    
359
                                           Static2D res = mMovement.newRotation(rotatedTouchPoint2);
360
                                           RubikObject object = mPostRender.getObject();
361

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

    
367
                                           object.beginNewRotation( axis, (int)(object.returnMultiplier()*offset) );
368

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

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

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

    
412
                                       if( mContinuingRotation )
413
                                         {
414
                                         mPostRender.finishRotation();
415
                                         }
416
                                       break;
417
         }
418

    
419
      return true;
420
      }
421
}
422

    
(4-4/4)