Project

General

Profile

Download (17.5 KB) Statistics
| Branch: | Revision:

examples / src / main / java / org / distorted / examples / rubik / RubikSurfaceView.java @ 201376f3

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2019 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted 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
// Distorted 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 Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.examples.rubik;
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.Static4D;
30

    
31
///////////////////////////////////////////////////////////////////////////////////////////////////
32

    
33
class RubikSurfaceView extends GLSurfaceView
34
{
35
    private final static int NONE   =-1;
36
    private final static int FRONT  = 0;  // has to be 6 consecutive ints
37
    private final static int BACK   = 1;  // FRONT ... BOTTOM
38
    private final static int LEFT   = 2;  //
39
    private final static int RIGHT  = 3;  //
40
    private final static int TOP    = 4;  //
41
    private final static int BOTTOM = 5;  //
42

    
43
    static final int VECTX = 0;  //
44
    static final int VECTY = 1;  // dont change this
45
    static final int VECTZ = 2;  //
46

    
47
    private static final int[] VECT = {VECTX,VECTY,VECTZ};
48

    
49
    private boolean mDragging, mBeginningRotation, mContinuingRotation;
50
    private int mX, mY;
51
    private Static4D mQuatCurrent, mQuatAccumulated;
52
    private int mRotationVect;
53
    private RubikRenderer mRenderer;
54
    private RubikCube mCube;
55

    
56
    private float[] mPoint, mCamera, mTouchPointCastOntoFace, mDiff, mTouchPoint; // all in screen space
57
    private int mLastTouchedFace;
58
    private int mScreenWidth, mScreenHeight, mScreenMin;
59
    private float mCameraDistance;
60

    
61
///////////////////////////////////////////////////////////////////////////////////////////////////
62

    
63
    public RubikSurfaceView(Context context, AttributeSet attrs)
64
      {
65
      super(context,attrs);
66

    
67
      if(!isInEditMode())
68
        {
69
        mRotationVect = VECT[0];
70

    
71
        mPoint = new float[3];
72
        mCamera= new float[3];
73
        mDiff  = new float[3];
74
        mTouchPoint = new float[3];
75
        mTouchPointCastOntoFace = new float[3];
76

    
77
        mScreenWidth = mScreenHeight = mScreenMin = 0;
78

    
79
        mRenderer = new RubikRenderer(this);
80
        mCube = mRenderer.getCube();
81

    
82
        mQuatCurrent     = new Static4D(0,0,0,1);
83
        mQuatAccumulated = mRenderer.initializeQuat();
84

    
85
        final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
86
        final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
87
        setEGLContextClientVersion( (configurationInfo.reqGlEsVersion>>16) >= 3 ? 3:2 );
88
        setRenderer(mRenderer);
89
        }
90
      }
91

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

    
94
    public RubikRenderer getRenderer()
95
      {
96
      return mRenderer;
97
      }
98

    
99
///////////////////////////////////////////////////////////////////////////////////////////////////
100

    
101
    @Override
102
    public boolean onTouchEvent(MotionEvent event)
103
      {
104
      int action = event.getAction();
105
      int x = (int)event.getX();
106
      int y = (int)event.getY();
107

    
108
      switch(action)
109
         {
110
         case MotionEvent.ACTION_DOWN: mX = x;
111
                                       mY = y;
112
                                       mLastTouchedFace = faceTouched(x,y);
113

    
114
                                       if( mLastTouchedFace != NONE )
115
                                         {
116
                                         mDragging           = false;
117
                                         mBeginningRotation  = mRenderer.canRotate();
118
                                         mContinuingRotation = false;
119
                                         }
120
                                       else
121
                                         {
122
                                         mDragging           = true;
123
                                         mBeginningRotation  = false;
124
                                         mContinuingRotation = false;
125
                                         }
126
                                       break;
127
         case MotionEvent.ACTION_MOVE: if( mDragging )
128
                                         {
129
                                         mQuatCurrent.set(quatFromDrag(mX-x,mY-y));
130
                                         mRenderer.setQuatCurrent(mQuatCurrent);
131
                                         }
132
                                       if( mBeginningRotation )
133
                                         {
134
                                         int minimumDistToStartRotating = (mScreenMin*mScreenMin)/100;
135

    
136
                                         if( (mX-x)*(mX-x)+(mY-y)*(mY-y) > minimumDistToStartRotating )
137
                                           {
138
                                           addNewRotation(x,y);
139
                                           mBeginningRotation = false;
140
                                           mContinuingRotation= true;
141
                                           }
142
                                         }
143
                                       else if( mContinuingRotation )
144
                                         {
145
                                         continueRotation(x,y);
146
                                         }
147
                                       break;
148
         case MotionEvent.ACTION_UP  : if( mDragging )
149
                                         {
150
                                         mQuatAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
151
                                         mQuatCurrent.set(0f, 0f, 0f, 1f);
152
                                         mRenderer.setQuatCurrent(mQuatCurrent);
153
                                         mRenderer.setQuatAccumulated(mQuatAccumulated);
154
                                         }
155

    
156
                                       if( mContinuingRotation )
157
                                         {
158
                                         finishRotation();
159
                                         }
160

    
161
                                       break;
162
         }
163

    
164
      return true;
165
      }
166

    
167
///////////////////////////////////////////////////////////////////////////////////////////////////
168

    
169
    void setScreenSize(int width, int height)
170
      {
171
      mScreenWidth = width;
172
      mScreenHeight= height;
173

    
174
      mScreenMin = width<height ? width:height;
175
      }
176

    
177
///////////////////////////////////////////////////////////////////////////////////////////////////
178

    
179
    void setCameraDist(float distance)
180
      {
181
      mCameraDistance = distance;
182
      }
183

    
184
///////////////////////////////////////////////////////////////////////////////////////////////////
185

    
186
    private int faceTouched(int xTouch, int yTouch)
187
      {
188
      float cubeHalfSize= mRenderer.returnCubeSizeInScreenSpace()*0.5f;
189

    
190
      convertTouchPointToScreenSpace(xTouch,yTouch);
191
      convertCameraPointToScreenSpace();
192

    
193
      for(int face=FRONT; face<=BOTTOM; face++)
194
        {
195
        if( faceIsVisible(face,cubeHalfSize) )
196
          {
197
          castTouchPointOntoFace(face,cubeHalfSize, mTouchPointCastOntoFace);
198

    
199
          float qX= (mTouchPointCastOntoFace[0]+cubeHalfSize) / (2*cubeHalfSize);
200
          float qY= (mTouchPointCastOntoFace[1]+cubeHalfSize) / (2*cubeHalfSize);
201
          float qZ= (mTouchPointCastOntoFace[2]+cubeHalfSize) / (2*cubeHalfSize);
202

    
203
          if( qX<=1 && qX>=0 && qY<=1 && qY>=0 && qZ<=1 && qZ>=0 ) return face;
204
          }
205
        }
206

    
207
      return NONE;
208
      }
209

    
210
///////////////////////////////////////////////////////////////////////////////////////////////////
211

    
212
    private void addNewRotation(int x, int y)
213
      {
214
      float cubeHalfSize= mRenderer.returnCubeSizeInScreenSpace()*0.5f;
215

    
216
      convertTouchPointToScreenSpace(x,y);
217
      castTouchPointOntoFace(mLastTouchedFace,cubeHalfSize,mDiff);
218

    
219
      mDiff[0] -= mTouchPointCastOntoFace[0];
220
      mDiff[1] -= mTouchPointCastOntoFace[1];
221
      mDiff[2] -= mTouchPointCastOntoFace[2];
222

    
223
      int xAxis = retFaceXaxis(mLastTouchedFace);
224
      int yAxis = retFaceYaxis(mLastTouchedFace);
225
      mRotationVect = (isVertical( mDiff[xAxis], mDiff[yAxis]) ? VECT[xAxis]:VECT[yAxis]);
226
      float offset= (mTouchPointCastOntoFace[mRotationVect]+cubeHalfSize)/(2*cubeHalfSize);
227

    
228
      mTouchPoint[0] = mPoint[0];
229
      mTouchPoint[1] = mPoint[1];
230
      mTouchPoint[2] = mPoint[2];
231

    
232
      mCube.addNewRotation(mRotationVect,offset);
233
      }
234

    
235
///////////////////////////////////////////////////////////////////////////////////////////////////
236

    
237
    private boolean isVertical(float x, float y)
238
      {
239
      return (y>x) ? (y>=-x) : (y< -x);
240
      }
241

    
242
///////////////////////////////////////////////////////////////////////////////////////////////////
243
// 240 --> moving finger from the middle of the vertical screen to the right edge will rotate a
244
// given face by 240/2 = 120 degrees.
245

    
246
    private void continueRotation(int x, int y)
247
      {
248
      convertTouchPointToScreenSpace(x,y);
249

    
250
      mDiff[0] = mPoint[0]-mTouchPoint[0];
251
      mDiff[1] = mPoint[1]-mTouchPoint[1];
252
      mDiff[2] = mPoint[2]-mTouchPoint[2];
253

    
254
      int xAxis= retFaceXaxis(mLastTouchedFace);
255
      int yAxis= retFaceYaxis(mLastTouchedFace);
256
      int sign = retFaceRotationSign(mLastTouchedFace);
257
      float angle = (mRotationVect==xAxis ? mDiff[yAxis] : -mDiff[xAxis]);
258

    
259
      mCube.continueRotation(240.0f*sign*angle/mScreenMin);
260
      }
261

    
262
///////////////////////////////////////////////////////////////////////////////////////////////////
263

    
264
    private void finishRotation()
265
      {
266
      mRenderer.finishRotation();
267
      }
268

    
269
///////////////////////////////////////////////////////////////////////////////////////////////////
270
// return quat1*quat2
271

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

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

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

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

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

    
295
    static Static4D rotateVectorByInvertedQuat(Static4D vector, Static4D quat)
296
      {
297
      float qx = quat.get1();
298
      float qy = quat.get2();
299
      float qz = quat.get3();
300
      float qw = quat.get4();
301

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

    
305
      return quatMultiply(tmp,quat);
306
      }
307

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

    
311
    static Static4D rotateVectorByQuat(Static4D vector, Static4D quat)
312
      {
313
      float qx = quat.get1();
314
      float qy = quat.get2();
315
      float qz = quat.get3();
316
      float qw = quat.get4();
317

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

    
321
      return quatMultiply(tmp,quatInverted);
322
      }
323

    
324
///////////////////////////////////////////////////////////////////////////////////////////////////
325

    
326
    private Static4D quatFromDrag(float dragX, float dragY)
327
      {
328
      float axisX = dragY;  // inverted X and Y - rotation axis is
329
      float axisY = dragX;  // perpendicular to (dragX,dragY)   Why not (-dragY, dragX) ? because Y axis is also inverted!
330
      float axisZ = 0;
331
      float axisL = (float)Math.sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);
332

    
333
      if( axisL>0 )
334
        {
335
        axisX /= axisL;
336
        axisY /= axisL;
337
        axisZ /= axisL;
338

    
339
        float cosA = (float)Math.cos(axisL*Math.PI/mScreenMin);
340
        float sinA = (float)Math.sqrt(1-cosA*cosA);
341

    
342
        return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
343
        }
344

    
345
      return new Static4D(0f, 0f, 0f, 1f);
346
      }
347

    
348
///////////////////////////////////////////////////////////////////////////////////////////////////
349

    
350
    private boolean faceIsVisible(int face, float cubeHalfSize)
351
      {
352
      int sign = retFaceSign(face);
353
      int zAxis= retFaceZaxis(face);
354

    
355
      return sign*mCamera[zAxis] > cubeHalfSize;
356
      }
357

    
358
///////////////////////////////////////////////////////////////////////////////////////////////////
359

    
360
    private void convertTouchPointToScreenSpace(int x, int y)
361
      {
362
      float halfScrWidth  = mScreenWidth *0.5f;
363
      float halfScrHeight = mScreenHeight*0.5f;
364
      Static4D touchPoint = new Static4D(x-halfScrWidth, halfScrHeight-y, 0, 0);
365
      Static4D rotatedTouchPoint= rotateVectorByInvertedQuat(touchPoint, mQuatAccumulated);
366

    
367
      mPoint[0] = rotatedTouchPoint.get1();
368
      mPoint[1] = rotatedTouchPoint.get2();
369
      mPoint[2] = rotatedTouchPoint.get3();
370
      }
371

    
372
///////////////////////////////////////////////////////////////////////////////////////////////////
373

    
374
    private void convertCameraPointToScreenSpace()
375
      {
376
      Static4D cameraPoint = new Static4D(0, 0, mCameraDistance, 0);
377
      Static4D rotatedCamera= rotateVectorByInvertedQuat(cameraPoint, mQuatAccumulated);
378

    
379
      mCamera[0] = rotatedCamera.get1();
380
      mCamera[1] = rotatedCamera.get2();
381
      mCamera[2] = rotatedCamera.get3();
382
      }
383

    
384
///////////////////////////////////////////////////////////////////////////////////////////////////
385
// given precomputed mCamera and mPoint, respectively camera and touch point positions in ScreenSpace,
386
// cast this touch point onto the surface defined by the 'face' and write the cast coords to 'output'.
387
// Center of the 'face' = (0,0), third coord always +- cubeHalfSize.
388

    
389
    private void castTouchPointOntoFace(int face, float cubeHalfSize, float[] output)
390
      {
391
      int sign = retFaceSign(face);
392
      int zAxis= retFaceZaxis(face);
393
      float diff = mPoint[zAxis]-mCamera[zAxis];
394

    
395
      float ratio =  diff!=0.0f ? (sign*cubeHalfSize-mCamera[zAxis])/diff : 0.0f;
396

    
397
      output[0] = (mPoint[0]-mCamera[0])*ratio + mCamera[0];
398
      output[1] = (mPoint[1]-mCamera[1])*ratio + mCamera[1];
399
      output[2] = (mPoint[2]-mCamera[2])*ratio + mCamera[2];
400
      }
401

    
402
///////////////////////////////////////////////////////////////////////////////////////////////////
403

    
404
    private int retFaceSign(int face)
405
      {
406
      return (face==FRONT || face==RIGHT || face==TOP) ? 1:-1;
407
      }
408

    
409
///////////////////////////////////////////////////////////////////////////////////////////////////
410

    
411
    private int retFaceRotationSign(int face)
412
      {
413
      return (face==BACK || face==RIGHT || face==TOP) ? 1:-1;
414
      }
415

    
416
///////////////////////////////////////////////////////////////////////////////////////////////////
417
// retFace{X,Y,Z}axis: 3 functions which return which real AXIS gets mapped to which when we look
418
// directly at a given face. For example, when we look at the RIGHT face of the cube (with TOP still
419
// in the top) then the 'real' X axis becomes the 'Z' axis, thus retFaceZaxis(RIGHT) = VECTX.
420

    
421
    private int retFaceXaxis(int face)
422
      {
423
      switch(face)
424
        {
425
        case FRONT :
426
        case BACK  : return VECTX;
427
        case LEFT  :
428
        case RIGHT : return VECTZ;
429
        case TOP   :
430
        case BOTTOM: return VECTX;
431
        }
432

    
433
      return -1;
434
      }
435

    
436
///////////////////////////////////////////////////////////////////////////////////////////////////
437

    
438
    private int retFaceYaxis(int face)
439
      {
440
      switch(face)
441
        {
442
        case FRONT :
443
        case BACK  : return VECTY;
444
        case LEFT  :
445
        case RIGHT : return VECTY;
446
        case TOP   :
447
        case BOTTOM: return VECTZ;
448
        }
449

    
450
      return -1;
451
      }
452

    
453
///////////////////////////////////////////////////////////////////////////////////////////////////
454

    
455
    private int retFaceZaxis(int face)
456
      {
457
      switch(face)
458
        {
459
        case FRONT :
460
        case BACK  : return VECTZ;
461
        case LEFT  :
462
        case RIGHT : return VECTX;
463
        case TOP   :
464
        case BOTTOM: return VECTY;
465
        }
466

    
467
      return -1;
468
      }
469
}
470

    
(4-4/4)