Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / ObjectControl.java @ 046104f5

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.objectlib.main;
21

    
22
import java.lang.ref.WeakReference;
23

    
24
import android.util.DisplayMetrics;
25
import android.view.MotionEvent;
26

    
27
import org.distorted.library.main.QuatHelper;
28
import org.distorted.library.type.Static2D;
29
import org.distorted.library.type.Static4D;
30

    
31
import org.distorted.objectlib.helpers.ObjectStateActioner;
32
import org.distorted.objectlib.helpers.TwistyActivity;
33

    
34
///////////////////////////////////////////////////////////////////////////////////////////////////
35

    
36
public class ObjectControl
37
{
38
    public static final int NUM_SPEED_PROBES = 10;
39
    public static final int INVALID_POINTER_ID = -1;
40

    
41
    public static final int MODE_ROTATE  = 0;
42
    public static final int MODE_DRAG    = 1;
43
    public static final int MODE_REPLACE = 2;
44

    
45
    // Moving the finger from the middle of the vertical screen to the right edge will rotate a
46
    // given face by SWIPING_SENSITIVITY/2 degrees.
47
    public final static int SWIPING_SENSITIVITY  = 240;
48
    // Moving the finger by 0.3 of an inch will start a Rotation.
49
    public final static float ROTATION_SENSITIVITY = 0.3f;
50

    
51
    private final Static4D CAMERA_POINT = new Static4D(0, 0, 0, 0);
52

    
53
    private final WeakReference<TwistyActivity> mAct;
54
    private final ObjectStateActioner mActioner;
55
    private final 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 float mStartRotX, mStartRotY;
62
    private float mAxisX, mAxisY;
63
    private float mRotationFactor;
64
    private int mLastCubitColor, mLastCubitFace, mLastCubit;
65
    private int mCurrentAxis, mCurrentRow;
66
    private float mCurrentAngle, mCurrRotSpeed;
67
    private final float[] mLastX;
68
    private final float[] mLastY;
69
    private final long[] mLastT;
70
    private int mFirstIndex, mLastIndex;
71
    private final int mDensity;
72

    
73
    private int mPointer1, mPointer2;
74
    private float mX1, mY1, mX2, mY2, mX, mY;
75
    private final boolean mIsAutomatic;
76

    
77
    private static final Static4D mQuat= new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
78
    private static final Static4D mTemp= new Static4D(0,0,0,1);
79

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

    
84
    private void computeCurrentAxis(Static4D axis)
85
      {
86
      Static4D result = QuatHelper.rotateVectorByQuat(axis, mQuat);
87

    
88
      mAxisX =result.get0();
89
      mAxisY =result.get1();
90

    
91
      float len = (float)Math.sqrt(mAxisX*mAxisX + mAxisY*mAxisY);
92
      mAxisX /= len;
93
      mAxisY /= len;
94
      }
95

    
96
///////////////////////////////////////////////////////////////////////////////////////////////////
97

    
98
    private void addSpeedProbe(float x, float y)
99
      {
100
      long currTime = System.currentTimeMillis();
101
      boolean theSame = mLastIndex==mFirstIndex;
102

    
103
      mLastIndex++;
104
      if( mLastIndex>=NUM_SPEED_PROBES ) mLastIndex=0;
105

    
106
      mLastT[mLastIndex] = currTime;
107
      mLastX[mLastIndex] = x;
108
      mLastY[mLastIndex] = y;
109

    
110
      if( mLastIndex==mFirstIndex)
111
        {
112
        mFirstIndex++;
113
        if( mFirstIndex>=NUM_SPEED_PROBES ) mFirstIndex=0;
114
        }
115

    
116
      if( theSame )
117
        {
118
        mLastT[mFirstIndex] = currTime;
119
        mLastX[mFirstIndex] = x;
120
        mLastY[mFirstIndex] = y;
121
        }
122
      }
123

    
124
///////////////////////////////////////////////////////////////////////////////////////////////////
125

    
126
    private void computeCurrentSpeedInInchesPerSecond()
127
      {
128
      long firstTime = mLastT[mFirstIndex];
129
      long lastTime  = mLastT[mLastIndex];
130
      float fX = mLastX[mFirstIndex];
131
      float fY = mLastY[mFirstIndex];
132
      float lX = mLastX[mLastIndex];
133
      float lY = mLastY[mLastIndex];
134

    
135
      long timeDiff = lastTime-firstTime;
136

    
137
      mLastIndex = 0;
138
      mFirstIndex= 0;
139

    
140
      mCurrRotSpeed = timeDiff>0 ? 1000*retFingerDragDistanceInInches(fX,fY,lX,lY)/timeDiff : 0;
141
      }
142

    
143
///////////////////////////////////////////////////////////////////////////////////////////////////
144

    
145
    private float retFingerDragDistanceInInches(float xFrom, float yFrom, float xTo, float yTo)
146
      {
147
      float xDist = mScreenWidth*(xFrom-xTo);
148
      float yDist = mScreenHeight*(yFrom-yTo);
149
      float distInPixels = (float)Math.sqrt(xDist*xDist + yDist*yDist);
150

    
151
      return distInPixels/mDensity;
152
      }
153

    
154
///////////////////////////////////////////////////////////////////////////////////////////////////
155

    
156
    private void setUpDragOrRotate(boolean down, float x, float y, int mode)
157
      {
158
      if( mode==MODE_DRAG )
159
        {
160
        mDragging           = true;
161
        mBeginningRotation  = false;
162
        mContinuingRotation = false;
163
        }
164
      else
165
        {
166
        TwistyObject object = mPreRender.getObject();
167
        CAMERA_POINT.set2( object==null ? 1.21f : object.getCameraDist() );
168

    
169
        Static4D touchPoint = new Static4D(x, y, 0, 0);
170
        Static4D rotatedTouchPoint= QuatHelper.rotateVectorByInvertedQuat(touchPoint, mQuat);
171
        Static4D rotatedCamera= QuatHelper.rotateVectorByInvertedQuat(CAMERA_POINT, mQuat);
172

    
173
        if( object!=null && mMovement!=null && mMovement.faceTouched(rotatedTouchPoint,rotatedCamera,object.getObjectRatio() ) )
174
          {
175
          mDragging           = false;
176
          mContinuingRotation = false;
177

    
178
          if( mode==MODE_ROTATE )
179
            {
180
            mBeginningRotation= !mPreRender.isTouchBlocked();
181
            }
182
          else if( mode==MODE_REPLACE )
183
            {
184
            mBeginningRotation= false;
185

    
186
            if( down )
187
              {
188
              int color = mActioner.getCurrentColor();
189
              mLastCubitFace = mMovement.getTouchedFace();
190
              float[] point = mMovement.getTouchedPoint3D();
191
              mLastCubit = object.getCubit(point);
192
              mPreRender.setTextureMap( mLastCubit, mLastCubitFace, color );
193
              mLastCubitColor = mActioner.cubitIsLocked(object.getObjectType(),mLastCubit);
194
              }
195
            }
196
          }
197
        else
198
          {
199
          final TwistyActivity act = mAct.get();
200
          final boolean locked= act.isLocked();
201
          mDragging           = (!locked || mIsAutomatic);
202
          mBeginningRotation  = false;
203
          mContinuingRotation = false;
204
          if( !mDragging ) mActioner.failedToDrag(act);
205
          }
206
        }
207
      }
208

    
209
///////////////////////////////////////////////////////////////////////////////////////////////////
210

    
211
    private void drag(float x, float y)
212
      {
213
      if( mPointer1!=INVALID_POINTER_ID && mPointer2!=INVALID_POINTER_ID)
214
        {
215
        float x2 = (mX2 - mScreenWidth*0.5f)/mScreenMin;
216
        float y2 = (mScreenHeight*0.5f - mY2)/mScreenMin;
217

    
218
        float angleNow = getAngle(x,y,x2,y2);
219
        float angleDiff = angleNow-mRotAngle;
220
        float sinA =-(float)Math.sin(angleDiff);
221
        float cosA = (float)Math.cos(angleDiff);
222

    
223
        Static4D dragQuat = QuatHelper.quatMultiply(new Static4D(0,0,sinA,cosA), mQuat);
224
        mTemp.set(dragQuat);
225

    
226
        mRotAngle = angleNow;
227

    
228
        float distNow  = (float)Math.sqrt( (x-x2)*(x-x2) + (y-y2)*(y-y2) );
229
        float distQuot = mInitDistance<0 ? 1.0f : distNow/ mInitDistance;
230
        mInitDistance = distNow;
231
        TwistyObject object = mPreRender.getObject();
232
        if( object!=null ) object.setObjectRatio(distQuot);
233
        }
234
      else
235
        {
236
        Static4D dragQuat = QuatHelper.quatMultiply(QuatHelper.quatFromDrag(mX-x,y-mY), mQuat);
237
        mTemp.set(dragQuat);
238
        }
239

    
240
      mPreRender.setQuatOnNextRender();
241
      mX = x;
242
      mY = y;
243
      }
244

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

    
247
    private void finishRotation()
248
      {
249
      computeCurrentSpeedInInchesPerSecond();
250
      int angle = mPreRender.getObject().computeNearestAngle(mCurrentAxis,mCurrentAngle, mCurrRotSpeed);
251
      mPreRender.finishRotation(angle);
252
      mPreRender.rememberMove(mCurrentAxis,mCurrentRow,angle);
253

    
254
      if( angle!=0 )
255
        {
256
        TwistyActivity act = mAct.get();
257
        mActioner.onFinishRotation(act,mCurrentAxis,mCurrentRow,angle);
258
        }
259

    
260
      mContinuingRotation = false;
261
      mBeginningRotation  = false;
262
      mDragging           = true;
263
      }
264

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

    
267
    private void continueRotation(float x, float y)
268
      {
269
      float dx = x-mStartRotX;
270
      float dy = y-mStartRotY;
271
      float alpha = dx*mAxisX + dy*mAxisY;
272
      float x2 = dx - alpha*mAxisX;
273
      float y2 = dy - alpha*mAxisY;
274

    
275
      float len = (float)Math.sqrt(x2*x2 + y2*y2);
276

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

    
280
      float angle = (tmp>0 ? 1:-1)*len*mRotationFactor;
281
      mCurrentAngle = SWIPING_SENSITIVITY*angle;
282
      mPreRender.getObject().continueRotation(mCurrentAngle);
283

    
284
      addSpeedProbe(x2,y2);
285
      }
286

    
287
///////////////////////////////////////////////////////////////////////////////////////////////////
288

    
289
    private void beginRotation(float x, float y)
290
      {
291
      mStartRotX = x;
292
      mStartRotY = y;
293

    
294
      TwistyObject object = mPreRender.getObject();
295
      int numLayers = object.getNumLayers();
296

    
297
      Static4D touchPoint2 = new Static4D(x, y, 0, 0);
298
      Static4D rotatedTouchPoint2= QuatHelper.rotateVectorByInvertedQuat(touchPoint2, mQuat);
299
      Static2D res = mMovement.newRotation(rotatedTouchPoint2,object.getObjectRatio());
300

    
301
      mCurrentAxis = (int)res.get0();
302
      mCurrentRow  = (int)res.get1();
303

    
304
      computeCurrentAxis( mMovement.getCastedRotAxis(mCurrentAxis) );
305
      mRotationFactor = mMovement.returnRotationFactor(numLayers,mCurrentRow);
306

    
307
      object.beginNewRotation( mCurrentAxis, mCurrentRow );
308

    
309
      TwistyActivity act = mAct.get();
310
      mActioner.onBeginRotation(act);
311

    
312
      addSpeedProbe(x,y);
313

    
314
      mBeginningRotation = false;
315
      mContinuingRotation= true;
316
      }
317

    
318
///////////////////////////////////////////////////////////////////////////////////////////////////
319

    
320
    private float getAngle(float x1, float y1, float x2, float y2)
321
      {
322
      return (float) Math.atan2(y1-y2, x1-x2);
323
      }
324

    
325
///////////////////////////////////////////////////////////////////////////////////////////////////
326

    
327
    private void prepareDown(MotionEvent event)
328
      {
329
      mPointer1 = event.getPointerId(0);
330
      mX1 = event.getX();
331
      mY1 = event.getY();
332
      mPointer2 = INVALID_POINTER_ID;
333
      }
334

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

    
337
    private void prepareMove(MotionEvent event)
338
      {
339
      int index1 = event.findPointerIndex(mPointer1);
340

    
341
      if( index1>=0 )
342
        {
343
        mX1 = event.getX(index1);
344
        mY1 = event.getY(index1);
345
        }
346

    
347
      int index2 = event.findPointerIndex(mPointer2);
348

    
349
      if( index2>=0 )
350
        {
351
        mX2 = event.getX(index2);
352
        mY2 = event.getY(index2);
353
        }
354
      }
355

    
356
///////////////////////////////////////////////////////////////////////////////////////////////////
357

    
358
    private void prepareUp(MotionEvent event)
359
      {
360
      mPointer1 = INVALID_POINTER_ID;
361
      mPointer2 = INVALID_POINTER_ID;
362
      }
363

    
364
///////////////////////////////////////////////////////////////////////////////////////////////////
365

    
366
    private void prepareDown2(MotionEvent event)
367
      {
368
      int index = event.getActionIndex();
369

    
370
      if( mPointer1==INVALID_POINTER_ID )
371
        {
372
        mPointer1 = event.getPointerId(index);
373
        mX1 = event.getX(index);
374
        mY1 = event.getY(index);
375
        }
376
      else if( mPointer2==INVALID_POINTER_ID )
377
        {
378
        mPointer2 = event.getPointerId(index);
379
        mX2 = event.getX(index);
380
        mY2 = event.getY(index);
381
        }
382
      }
383

    
384
///////////////////////////////////////////////////////////////////////////////////////////////////
385

    
386
    private void prepareUp2(MotionEvent event)
387
      {
388
      int index = event.getActionIndex();
389

    
390
           if( index==event.findPointerIndex(mPointer1) ) mPointer1 = INVALID_POINTER_ID;
391
      else if( index==event.findPointerIndex(mPointer2) ) mPointer2 = INVALID_POINTER_ID;
392
      }
393

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

    
396
    private void actionMove(float x1, float y1, float x2, float y2, int mode)
397
      {
398
      float pX = mPointer1 != INVALID_POINTER_ID ? x1 : x2;
399
      float pY = mPointer1 != INVALID_POINTER_ID ? y1 : y2;
400

    
401
      float x = (pX - mScreenWidth*0.5f)/mScreenMin;
402
      float y = (mScreenHeight*0.5f -pY)/mScreenMin;
403

    
404
      if( mBeginningRotation )
405
        {
406
        if( retFingerDragDistanceInInches(mX,mY,x,y) > ROTATION_SENSITIVITY )
407
          {
408
          beginRotation(x,y);
409
          }
410
        }
411
      else if( mContinuingRotation )
412
        {
413
        continueRotation(x,y);
414
        }
415
      else if( mDragging )
416
        {
417
        drag(x,y);
418
        }
419
      else
420
        {
421
        setUpDragOrRotate(false,x,y,mode);
422
        }
423
      }
424

    
425
///////////////////////////////////////////////////////////////////////////////////////////////////
426

    
427
    private void actionDown(float x, float y, int mode)
428
      {
429
      mX = (x -  mScreenWidth*0.5f)/mScreenMin;
430
      mY = (mScreenHeight*0.5f - y)/mScreenMin;
431

    
432
      setUpDragOrRotate(true,mX,mY,mode);
433
      }
434

    
435
///////////////////////////////////////////////////////////////////////////////////////////////////
436

    
437
    private void actionUp()
438
      {
439
      if( mContinuingRotation )
440
        {
441
        finishRotation();
442
        }
443

    
444
      if( mLastCubitColor>=0 )
445
        {
446
        mPreRender.setTextureMap( mLastCubit, mLastCubitFace, mLastCubitColor );
447
        mLastCubitColor = -1;
448
        }
449
      }
450

    
451
///////////////////////////////////////////////////////////////////////////////////////////////////
452

    
453
    private void actionDown2(float x1, float y1, float x2, float y2)
454
      {
455
      mRotAngle = getAngle(x1,-y1, x2,-y2);
456
      mInitDistance = -1;
457

    
458
      mX = (x1 - mScreenWidth*0.5f )/mScreenMin;
459
      mY = (mScreenHeight*0.5f - y1)/mScreenMin;
460

    
461
      if( mBeginningRotation )
462
        {
463
        mContinuingRotation = false;
464
        mBeginningRotation  = false;
465
        mDragging           = true;
466
        }
467
      else if( mContinuingRotation )
468
        {
469
        finishRotation();
470
        }
471
      }
472

    
473
///////////////////////////////////////////////////////////////////////////////////////////////////
474

    
475
    private void actionUp2(boolean p1isUp, float x1, float y1, boolean p2isUp, float x2, float y2)
476
      {
477
      if( p1isUp )
478
        {
479
        mX = (x2 -  mScreenWidth*0.5f)/mScreenMin;
480
        mY = (mScreenHeight*0.5f - y2)/mScreenMin;
481
        }
482
      if( p2isUp )
483
        {
484
        mX = (x1 -  mScreenWidth*0.5f)/mScreenMin;
485
        mY = (mScreenHeight*0.5f - y1)/mScreenMin;
486
        }
487
      }
488

    
489
///////////////////////////////////////////////////////////////////////////////////////////////////
490
// PUBLIC API
491
///////////////////////////////////////////////////////////////////////////////////////////////////
492

    
493
    public ObjectControl(TwistyActivity act, ObjectStateActioner actioner)
494
      {
495
      mIsAutomatic = false;
496

    
497
      mLastCubitColor = -1;
498
      mCurrRotSpeed   = 0.0f;
499

    
500
      mLastX = new float[NUM_SPEED_PROBES];
501
      mLastY = new float[NUM_SPEED_PROBES];
502
      mLastT = new long[NUM_SPEED_PROBES];
503
      mFirstIndex =0;
504
      mLastIndex  =0;
505

    
506
      DisplayMetrics dm = new DisplayMetrics();
507
      act.getWindowManager().getDefaultDisplay().getMetrics(dm);
508

    
509
      mDensity = dm.densityDpi;
510

    
511
      mPreRender = new ObjectPreRender(act,this,actioner);
512
      mAct = new WeakReference<>(act);
513
      mActioner = actioner;
514
      }
515

    
516
///////////////////////////////////////////////////////////////////////////////////////////////////
517

    
518
    public void setScreenSize(int width, int height)
519
      {
520
      mScreenWidth = width;
521
      mScreenHeight= height;
522

    
523
      mScreenMin = Math.min(width, height);
524
      }
525

    
526
///////////////////////////////////////////////////////////////////////////////////////////////////
527

    
528
    public void initialize()
529
      {
530
      mPointer1 = INVALID_POINTER_ID;
531
      mPointer2 = INVALID_POINTER_ID;
532
      }
533

    
534
///////////////////////////////////////////////////////////////////////////////////////////////////
535

    
536
    public void setQuat()
537
      {
538
      mQuat.set(mTemp);
539
      }
540

    
541
///////////////////////////////////////////////////////////////////////////////////////////////////
542

    
543
    public Static4D getQuat()
544
      {
545
      return mQuat;
546
      }
547

    
548
///////////////////////////////////////////////////////////////////////////////////////////////////
549

    
550
    public void setMovement(Movement movement)
551
      {
552
      mMovement = movement;
553
      }
554

    
555
///////////////////////////////////////////////////////////////////////////////////////////////////
556

    
557
    public ObjectPreRender getPreRender()
558
      {
559
      return mPreRender;
560
      }
561

    
562
///////////////////////////////////////////////////////////////////////////////////////////////////
563

    
564
    public boolean onTouchEvent(MotionEvent event, int mode)
565
      {
566
      int action = event.getActionMasked();
567

    
568
      switch(action)
569
         {
570
         case MotionEvent.ACTION_DOWN        : prepareDown(event);
571
                                               actionDown(mX1, mY1, mode);
572
                                               break;
573
         case MotionEvent.ACTION_MOVE        : prepareMove(event);
574
                                               actionMove(mX1, mY1, mX2, mY2, mode);
575
                                               break;
576
         case MotionEvent.ACTION_UP          : prepareUp(event);
577
                                               actionUp();
578
                                               break;
579
         case MotionEvent.ACTION_POINTER_DOWN: prepareDown2(event);
580
                                               actionDown2(mX1, mY1, mX2, mY2);
581
                                               break;
582
         case MotionEvent.ACTION_POINTER_UP  : prepareUp2(event);
583
                                               boolean p1isUp = mPointer1==INVALID_POINTER_ID;
584
                                               boolean p2isUp = mPointer2==INVALID_POINTER_ID;
585
                                               actionUp2(p1isUp, mX1, mY1, p2isUp, mX2, mY2);
586
                                               break;
587
         }
588

    
589
      return true;
590
      }
591
}
592

    
(7-7/15)