Project

General

Profile

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

magiccube / src / main / java / org / distorted / tutorials / TutorialSurfaceView.java @ eaf46415

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2020 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.tutorials;
21

    
22
import android.app.ActivityManager;
23
import android.content.Context;
24
import android.content.pm.ConfigurationInfo;
25
import android.opengl.GLES30;
26
import android.opengl.GLSurfaceView;
27
import android.util.AttributeSet;
28
import android.util.DisplayMetrics;
29
import android.view.MotionEvent;
30

    
31
import com.google.firebase.crashlytics.FirebaseCrashlytics;
32

    
33
import org.distorted.library.main.DistortedScreen;
34
import org.distorted.library.type.Static2D;
35
import org.distorted.library.type.Static4D;
36
import org.distorted.library.main.QuatHelper;
37

    
38
import org.distorted.objectlib.helpers.ObjectSurfaceView;
39
import org.distorted.objectlib.helpers.TwistyActivity;
40
import org.distorted.objectlib.main.Movement;
41
import org.distorted.objectlib.main.ObjectPreRender;
42
import org.distorted.objectlib.main.TwistyObject;
43

    
44
import static org.distorted.main.RubikSurfaceView.INVALID_POINTER_ID;
45
import static org.distorted.main.RubikSurfaceView.NUM_SPEED_PROBES;
46
import static org.distorted.main.RubikSurfaceView.ROTATION_SENSITIVITY;
47
import static org.distorted.main.RubikSurfaceView.SWIPING_SENSITIVITY;
48

    
49
///////////////////////////////////////////////////////////////////////////////////////////////////
50

    
51
public class TutorialSurfaceView extends GLSurfaceView implements ObjectSurfaceView
52
{
53
    private final Static4D CAMERA_POINT = new Static4D(0, 0, 0, 0);
54
    private TutorialRenderer mRenderer;
55
    private ObjectPreRender mPreRender;
56
    private Movement mMovement;
57
    private boolean mDragging, mBeginningRotation, mContinuingRotation;
58
    private int mScreenWidth, mScreenHeight, mScreenMin;
59

    
60
    private float mRotAngle, mInitDistance;
61
    private int mPtrID1, mPtrID2;
62
    private float mX, mY;
63
    private float mStartRotX, mStartRotY;
64
    private float mAxisX, mAxisY;
65
    private float mRotationFactor;
66
    private int mCurrentAxis, mCurrentRow;
67
    private float mCurrentAngle, mCurrRotSpeed;
68
    private float[] mLastX;
69
    private float[] mLastY;
70
    private long[] mLastT;
71
    private int mFirstIndex, mLastIndex;
72
    private int mDensity;
73

    
74
    private static final Static4D mQuat= new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
75
    private static final Static4D mTemp= new Static4D(0,0,0,1);
76

    
77
///////////////////////////////////////////////////////////////////////////////////////////////////
78

    
79
    void setScreenSize(int width, int height)
80
      {
81
      mScreenWidth = width;
82
      mScreenHeight= height;
83

    
84
      mScreenMin = Math.min(width, height);
85
      }
86

    
87
///////////////////////////////////////////////////////////////////////////////////////////////////
88

    
89
    boolean isVertical()
90
      {
91
      return mScreenHeight>mScreenWidth;
92
      }
93

    
94
///////////////////////////////////////////////////////////////////////////////////////////////////
95

    
96
    ObjectPreRender getPreRender()
97
      {
98
      return mPreRender;
99
      }
100

    
101
///////////////////////////////////////////////////////////////////////////////////////////////////
102
// cast the 3D axis we are currently rotating along (which is already casted to the surface of the
103
// currently touched face AND converted into a 4D vector - fourth 0) to a 2D in-screen-surface axis
104

    
105
    private void computeCurrentAxis(Static4D axis)
106
      {
107
      Static4D result = QuatHelper.rotateVectorByQuat(axis, mQuat);
108

    
109
      mAxisX =result.get0();
110
      mAxisY =result.get1();
111

    
112
      float len = (float)Math.sqrt(mAxisX*mAxisX + mAxisY*mAxisY);
113
      mAxisX /= len;
114
      mAxisY /= len;
115
      }
116

    
117
///////////////////////////////////////////////////////////////////////////////////////////////////
118

    
119
    private void addSpeedProbe(float x, float y)
120
      {
121
      long currTime = System.currentTimeMillis();
122
      boolean theSame = mLastIndex==mFirstIndex;
123

    
124
      mLastIndex++;
125
      if( mLastIndex>=NUM_SPEED_PROBES ) mLastIndex=0;
126

    
127
      mLastT[mLastIndex] = currTime;
128
      mLastX[mLastIndex] = x;
129
      mLastY[mLastIndex] = y;
130

    
131
      if( mLastIndex==mFirstIndex)
132
        {
133
        mFirstIndex++;
134
        if( mFirstIndex>=NUM_SPEED_PROBES ) mFirstIndex=0;
135
        }
136

    
137
      if( theSame )
138
        {
139
        mLastT[mFirstIndex] = currTime;
140
        mLastX[mFirstIndex] = x;
141
        mLastY[mFirstIndex] = y;
142
        }
143
      }
144

    
145
///////////////////////////////////////////////////////////////////////////////////////////////////
146

    
147
    private void computeCurrentSpeedInInchesPerSecond()
148
      {
149
      long firstTime = mLastT[mFirstIndex];
150
      long lastTime  = mLastT[mLastIndex];
151
      float fX = mLastX[mFirstIndex];
152
      float fY = mLastY[mFirstIndex];
153
      float lX = mLastX[mLastIndex];
154
      float lY = mLastY[mLastIndex];
155

    
156
      long timeDiff = lastTime-firstTime;
157

    
158
      mLastIndex = 0;
159
      mFirstIndex= 0;
160

    
161
      mCurrRotSpeed = timeDiff>0 ? 1000*retFingerDragDistanceInInches(fX,fY,lX,lY)/timeDiff : 0;
162
      }
163

    
164
///////////////////////////////////////////////////////////////////////////////////////////////////
165

    
166
    private float retFingerDragDistanceInInches(float xFrom, float yFrom, float xTo, float yTo)
167
      {
168
      float xDist = mScreenWidth*(xFrom-xTo);
169
      float yDist = mScreenHeight*(yFrom-yTo);
170
      float distInPixels = (float)Math.sqrt(xDist*xDist + yDist*yDist);
171

    
172
      return distInPixels/mDensity;
173
      }
174

    
175
///////////////////////////////////////////////////////////////////////////////////////////////////
176

    
177
    private void setUpDragOrRotate(float x, float y)
178
      {
179
      TwistyObject object = mPreRender.getObject();
180
      CAMERA_POINT.set2( object==null ? 1.21f : object.getCameraDist() );
181

    
182
      Static4D touchPoint = new Static4D(x, y, 0, 0);
183
      Static4D rotatedTouchPoint= QuatHelper.rotateVectorByInvertedQuat(touchPoint, mQuat);
184
      Static4D rotatedCamera= QuatHelper.rotateVectorByInvertedQuat(CAMERA_POINT, mQuat);
185

    
186
      if( mMovement!=null && mMovement.faceTouched(rotatedTouchPoint,rotatedCamera,object.getObjectRatio()) )
187
        {
188
        mDragging           = false;
189
        mContinuingRotation = false;
190
        mBeginningRotation= !mPreRender.isTouchBlocked();
191
        }
192
      else
193
        {
194
        final TutorialActivity act = (TutorialActivity)getContext();
195
        boolean locked      = act.isLocked();
196
        mDragging           = !locked;
197
        mContinuingRotation = false;
198
        mBeginningRotation  = false;
199

    
200
        if( !mDragging )
201
          {
202
          TutorialState state = act.getState();
203
          state.reddenLock(act);
204
          }
205
        }
206
      }
207

    
208
///////////////////////////////////////////////////////////////////////////////////////////////////
209

    
210
    private void drag(MotionEvent event, float x, float y)
211
      {
212
      if( mPtrID1!=INVALID_POINTER_ID && mPtrID2!=INVALID_POINTER_ID)
213
        {
214
        int pointer = event.findPointerIndex(mPtrID2);
215
        float pX,pY;
216

    
217
        try
218
          {
219
          pX = event.getX(pointer);
220
          pY = event.getY(pointer);
221
          }
222
        catch(IllegalArgumentException ex)
223
          {
224
          mPtrID1=INVALID_POINTER_ID;
225
          mPtrID2=INVALID_POINTER_ID;
226

    
227
          FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
228
          crashlytics.setCustomKey("DragError", "pointer="+pointer );
229
          crashlytics.recordException(ex);
230

    
231
          return;
232
          }
233

    
234
        float x2 = (pX - mScreenWidth*0.5f)/mScreenMin;
235
        float y2 = (mScreenHeight*0.5f -pY)/mScreenMin;
236

    
237
        float angleNow = getAngle(x,y,x2,y2);
238
        float angleDiff = angleNow-mRotAngle;
239
        float sinA =-(float)Math.sin(angleDiff);
240
        float cosA = (float)Math.cos(angleDiff);
241

    
242
        Static4D dragQuat = QuatHelper.quatMultiply(new Static4D(0,0,sinA,cosA), mQuat);
243
        mTemp.set(dragQuat);
244

    
245
        mRotAngle = angleNow;
246

    
247
        float distNow  = (float)Math.sqrt( (x-x2)*(x-x2) + (y-y2)*(y-y2) );
248
        float distQuot = mInitDistance<0 ? 1.0f : distNow/ mInitDistance;
249
        mInitDistance = distNow;
250

    
251
        TwistyObject object = mPreRender.getObject();
252
        if( object!=null ) object.setObjectRatio(distQuot);
253
        }
254
      else
255
        {
256
        Static4D dragQuat = QuatHelper.quatMultiply(QuatHelper.quatFromDrag(mX-x,y-mY), mQuat);
257
        mTemp.set(dragQuat);
258
        }
259

    
260
      mPreRender.setQuatOnNextRender();
261
      mX = x;
262
      mY = y;
263
      }
264

    
265
///////////////////////////////////////////////////////////////////////////////////////////////////
266

    
267
    private void finishRotation()
268
      {
269
      computeCurrentSpeedInInchesPerSecond();
270
      int angle = mPreRender.getObject().computeNearestAngle(mCurrentAxis,mCurrentAngle, mCurrRotSpeed);
271
      mPreRender.finishRotation(angle);
272

    
273
      if( angle!=0 )
274
        {
275
        final TutorialActivity act = (TutorialActivity)getContext();
276
        TutorialState state = act.getState();
277
        state.addMove(act,mCurrentAxis, mCurrentRow, angle);
278
        }
279

    
280
      mContinuingRotation = false;
281
      mBeginningRotation  = false;
282
      mDragging           = true;
283
      }
284

    
285
///////////////////////////////////////////////////////////////////////////////////////////////////
286

    
287
    private void continueRotation(float x, float y)
288
      {
289
      float dx = x-mStartRotX;
290
      float dy = y-mStartRotY;
291
      float alpha = dx*mAxisX + dy*mAxisY;
292
      float x2 = dx - alpha*mAxisX;
293
      float y2 = dy - alpha*mAxisY;
294

    
295
      float len = (float)Math.sqrt(x2*x2 + y2*y2);
296

    
297
      // we have the length of 1D vector 'angle', now the direction:
298
      float tmp = mAxisY==0 ? -mAxisX*y2 : mAxisY*x2;
299

    
300
      float angle = (tmp>0 ? 1:-1)*len*mRotationFactor;
301
      mCurrentAngle = SWIPING_SENSITIVITY*angle;
302
      mPreRender.getObject().continueRotation(mCurrentAngle);
303

    
304
      addSpeedProbe(x2,y2);
305
      }
306

    
307
///////////////////////////////////////////////////////////////////////////////////////////////////
308

    
309
    private void beginRotation(float x, float y)
310
      {
311
      mStartRotX = x;
312
      mStartRotY = y;
313

    
314
      TwistyObject object = mPreRender.getObject();
315
      int numLayers = object.getNumLayers();
316

    
317
      Static4D touchPoint2 = new Static4D(x, y, 0, 0);
318
      Static4D rotatedTouchPoint2= QuatHelper.rotateVectorByInvertedQuat(touchPoint2, mQuat);
319
      Static2D res = mMovement.newRotation(rotatedTouchPoint2,object.getObjectRatio());
320

    
321
      mCurrentAxis = (int)res.get0();
322
      mCurrentRow  = (int)res.get1();
323

    
324
      computeCurrentAxis( mMovement.getCastedRotAxis(mCurrentAxis) );
325
      mRotationFactor = mMovement.returnRotationFactor(numLayers,mCurrentRow);
326

    
327
      object.beginNewRotation( mCurrentAxis, mCurrentRow );
328

    
329
      addSpeedProbe(x,y);
330

    
331
      mBeginningRotation = false;
332
      mContinuingRotation= true;
333
      }
334

    
335
///////////////////////////////////////////////////////////////////////////////////////////////////
336

    
337
    private float getAngle(float x1, float y1, float x2, float y2)
338
      {
339
      return (float) Math.atan2(y1-y2, x1-x2);
340
      }
341

    
342
///////////////////////////////////////////////////////////////////////////////////////////////////
343

    
344
    private void actionMove(MotionEvent event)
345
      {
346
      int pointer = event.findPointerIndex(mPtrID1 != INVALID_POINTER_ID ? mPtrID1:mPtrID2);
347

    
348
      if( pointer<0 ) return;
349

    
350
      float pX = event.getX(pointer);
351
      float pY = event.getY(pointer);
352

    
353
      float x = (pX - mScreenWidth*0.5f)/mScreenMin;
354
      float y = (mScreenHeight*0.5f -pY)/mScreenMin;
355

    
356
      if( mBeginningRotation )
357
        {
358
        if( retFingerDragDistanceInInches(mX,mY,x,y) > ROTATION_SENSITIVITY )
359
          {
360
          beginRotation(x,y);
361
          }
362
        }
363
      else if( mContinuingRotation )
364
        {
365
        continueRotation(x,y);
366
        }
367
      else if( mDragging )
368
        {
369
        drag(event,x,y);
370
        }
371
      else
372
        {
373
        setUpDragOrRotate(x,y);
374
        }
375
      }
376

    
377
///////////////////////////////////////////////////////////////////////////////////////////////////
378

    
379
    private void actionDown(MotionEvent event)
380
      {
381
      mPtrID1 = event.getPointerId(0);
382

    
383
      float x = event.getX();
384
      float y = event.getY();
385

    
386
      mX = (x - mScreenWidth*0.5f)/mScreenMin;
387
      mY = (mScreenHeight*0.5f -y)/mScreenMin;
388

    
389
      setUpDragOrRotate(mX,mY);
390
      }
391

    
392
///////////////////////////////////////////////////////////////////////////////////////////////////
393

    
394
    private void actionUp(MotionEvent event)
395
      {
396
      mPtrID1 = INVALID_POINTER_ID;
397
      mPtrID2 = INVALID_POINTER_ID;
398

    
399
      if( mContinuingRotation )
400
        {
401
        finishRotation();
402
        }
403
      }
404

    
405
///////////////////////////////////////////////////////////////////////////////////////////////////
406

    
407
    private void actionDown2(MotionEvent event)
408
      {
409
      int index = event.getActionIndex();
410

    
411
      if( mPtrID1==INVALID_POINTER_ID )
412
        {
413
        mPtrID1 = event.getPointerId(index);
414
        float x = event.getX();
415
        float y = event.getY();
416

    
417
        if( mPtrID2 != INVALID_POINTER_ID )
418
          {
419
          int pointer = event.findPointerIndex(mPtrID2);
420

    
421
          try
422
            {
423
            float x2 = event.getX(pointer);
424
            float y2 = event.getY(pointer);
425

    
426
            mRotAngle = getAngle(x,-y,x2,-y2);
427
            mInitDistance = -1;
428
            }
429
          catch(IllegalArgumentException ex)
430
            {
431
            mPtrID1=INVALID_POINTER_ID;
432
            mPtrID2=INVALID_POINTER_ID;
433

    
434
            FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
435
            crashlytics.setCustomKey("DragError", "pointer="+pointer );
436
            crashlytics.recordException(ex);
437

    
438
            return;
439
            }
440
          }
441

    
442
        mX = (x - mScreenWidth*0.5f)/mScreenMin;
443
        mY = (mScreenHeight*0.5f -y)/mScreenMin;
444
        }
445
      else if( mPtrID2==INVALID_POINTER_ID )
446
        {
447
        mPtrID2 = event.getPointerId(index);
448

    
449
        float x = event.getX();
450
        float y = event.getY();
451

    
452
        if( mPtrID2 != INVALID_POINTER_ID )
453
          {
454
          int pointer = event.findPointerIndex(mPtrID2);
455

    
456
          try
457
            {
458
            float x2 = event.getX(pointer);
459
            float y2 = event.getY(pointer);
460

    
461
            mRotAngle = getAngle(x,-y,x2,-y2);
462
            mInitDistance = -1;
463
            }
464
          catch(IllegalArgumentException ex)
465
            {
466
            mPtrID1=INVALID_POINTER_ID;
467
            mPtrID2=INVALID_POINTER_ID;
468

    
469
            FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
470
            crashlytics.setCustomKey("DragError", "pointer="+pointer );
471
            crashlytics.recordException(ex);
472

    
473
            return;
474
            }
475
          }
476

    
477
        if( mBeginningRotation || mContinuingRotation )
478
          {
479
          mX = (x - mScreenWidth*0.5f)/mScreenMin;
480
          mY = (mScreenHeight*0.5f -y)/mScreenMin;
481
          }
482
        }
483

    
484
      if( mBeginningRotation )
485
        {
486
        mContinuingRotation = false;
487
        mBeginningRotation  = false;
488
        mDragging           = true;
489
        }
490
      else if( mContinuingRotation )
491
        {
492
        finishRotation();
493
        }
494
      }
495

    
496
///////////////////////////////////////////////////////////////////////////////////////////////////
497

    
498
    private void actionUp2(MotionEvent event)
499
      {
500
      int index = event.getActionIndex();
501

    
502
      if( index==event.findPointerIndex(mPtrID1) )
503
        {
504
        mPtrID1 = INVALID_POINTER_ID;
505
        int pointer = event.findPointerIndex(mPtrID2);
506

    
507
        if( pointer>=0 )
508
          {
509
          float x1 = event.getX(pointer);
510
          float y1 = event.getY(pointer);
511

    
512
          mX = (x1 - mScreenWidth*0.5f)/mScreenMin;
513
          mY = (mScreenHeight*0.5f -y1)/mScreenMin;
514
          }
515
        }
516
      else if( index==event.findPointerIndex(mPtrID2) )
517
        {
518
        mPtrID2 = INVALID_POINTER_ID;
519
        }
520
      }
521

    
522
///////////////////////////////////////////////////////////////////////////////////////////////////
523

    
524
    void initialize()
525
      {
526
      mPtrID1 = INVALID_POINTER_ID;
527
      mPtrID2 = INVALID_POINTER_ID;
528
      }
529

    
530
///////////////////////////////////////////////////////////////////////////////////////////////////
531
// PUBLIC API
532
///////////////////////////////////////////////////////////////////////////////////////////////////
533

    
534
    public TutorialSurfaceView(Context context, AttributeSet attrs)
535
      {
536
      super(context,attrs);
537

    
538
      if(!isInEditMode())
539
        {
540
        mCurrRotSpeed= 0.0f;
541

    
542
        mLastX = new float[NUM_SPEED_PROBES];
543
        mLastY = new float[NUM_SPEED_PROBES];
544
        mLastT = new long[NUM_SPEED_PROBES];
545
        mFirstIndex =0;
546
        mLastIndex  =0;
547

    
548
        mRenderer  = new TutorialRenderer(this);
549
        mPreRender = new ObjectPreRender(this,new TutorialObjectStateActioner());
550

    
551
        TutorialActivity act = (TutorialActivity)context;
552
        DisplayMetrics dm = new DisplayMetrics();
553
        act.getWindowManager().getDefaultDisplay().getMetrics(dm);
554

    
555
        mDensity = dm.densityDpi;
556

    
557
        final ActivityManager activityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
558

    
559
        try
560
          {
561
          final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
562
          int esVersion = configurationInfo.reqGlEsVersion>>16;
563
          setEGLContextClientVersion(esVersion);
564
          setRenderer(mRenderer);
565
          }
566
        catch(Exception ex)
567
          {
568
          act.OpenGLError();
569

    
570
          String shading = GLES30.glGetString(GLES30.GL_SHADING_LANGUAGE_VERSION);
571
          String version = GLES30.glGetString(GLES30.GL_VERSION);
572
          String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
573
          String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
574

    
575
          FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
576
          crashlytics.setCustomKey("GLSL Version"  , shading );
577
          crashlytics.setCustomKey("GLversion"     , version );
578
          crashlytics.setCustomKey("GL Vendor "    , vendor  );
579
          crashlytics.setCustomKey("GLSLrenderer"  , renderer);
580
          crashlytics.recordException(ex);
581
          }
582
        }
583
      }
584

    
585
///////////////////////////////////////////////////////////////////////////////////////////////////
586

    
587
    public void setQuat()
588
      {
589
      mQuat.set(mTemp);
590
      }
591

    
592
///////////////////////////////////////////////////////////////////////////////////////////////////
593

    
594
    public Static4D getQuat()
595
      {
596
      return mQuat;
597
      }
598

    
599
///////////////////////////////////////////////////////////////////////////////////////////////////
600

    
601
    public void setMovement(Movement movement)
602
      {
603
      mMovement = movement;
604
      }
605

    
606
///////////////////////////////////////////////////////////////////////////////////////////////////
607

    
608
    public TwistyActivity getActivity()
609
      {
610
      return (TwistyActivity)getContext();
611
      }
612

    
613
///////////////////////////////////////////////////////////////////////////////////////////////////
614

    
615
    public DistortedScreen getScreen()
616
      {
617
      return mRenderer.getScreen();
618
      }
619

    
620
///////////////////////////////////////////////////////////////////////////////////////////////////
621

    
622
    @Override
623
    public boolean onTouchEvent(MotionEvent event)
624
      {
625
      int action = event.getActionMasked();
626

    
627
      switch(action)
628
         {
629
         case MotionEvent.ACTION_DOWN        : actionDown(event) ; break;
630
         case MotionEvent.ACTION_MOVE        : actionMove(event) ; break;
631
         case MotionEvent.ACTION_UP          : actionUp(event)   ; break;
632
         case MotionEvent.ACTION_POINTER_DOWN: actionDown2(event); break;
633
         case MotionEvent.ACTION_POINTER_UP  : actionUp2(event)  ; break;
634
         }
635

    
636
      return true;
637
      }
638
}
639

    
(6-6/7)