Project

General

Profile

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

magiccube / src / main / java / org / distorted / magic / RubikSurfaceView.java @ 775e675d

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

    
22
import android.app.ActivityManager;
23
import android.content.Context;
24
import android.content.pm.ConfigurationInfo;
25
import android.graphics.PorterDuff;
26
import android.graphics.drawable.Drawable;
27
import android.opengl.GLSurfaceView;
28
import android.support.v4.content.ContextCompat;
29
import android.util.AttributeSet;
30
import android.util.DisplayMetrics;
31
import android.view.MotionEvent;
32
import android.view.ViewGroup;
33
import android.widget.Button;
34
import android.widget.ImageButton;
35
import android.widget.LinearLayout;
36

    
37
import org.distorted.library.type.Static2D;
38
import org.distorted.library.type.Static4D;
39
import org.distorted.object.RubikCube;
40
import org.distorted.object.RubikCubeMovement;
41

    
42
///////////////////////////////////////////////////////////////////////////////////////////////////
43

    
44
public class RubikSurfaceView extends GLSurfaceView
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

    
50
    // Moving the finger by 1/12 the distance of min(scrWidth,scrHeight) will start a Rotation.
51
    private final static int ROTATION_SENSITIVITY =  12;
52

    
53
    // Every 1/12 the distance of min(scrWidth,scrHeight) the direction of cube rotation will reset.
54
    private final static int DIRECTION_SENSITIVITY=  12;
55

    
56
    private RubikRenderer mRenderer;
57
    private RubikCubeMovement mMovement;
58

    
59
    private boolean mInScrambleMode;
60
    private int mButton = RubikSize.SIZE3.ordinal();
61

    
62
    private boolean mDragging, mBeginningRotation, mContinuingRotation;
63
    private float mX, mY;
64
    private int mLastTouchedFace;
65
    private float mCameraDistance;
66
    private int mScreenWidth, mScreenHeight, mScreenMin;
67

    
68
    private static Static4D mQuatCurrent    = new Static4D(0,0,0,1);
69
    private static Static4D mQuatAccumulated= new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
70
    private static Static4D mTempCurrent    = new Static4D(0,0,0,1);
71
    private static Static4D mTempAccumulated= new Static4D(0,0,0,1);
72

    
73
///////////////////////////////////////////////////////////////////////////////////////////////////
74
// return quat1*quat2
75

    
76
    public static Static4D quatMultiply( Static4D quat1, Static4D quat2 )
77
      {
78
      float qx = quat1.get1();
79
      float qy = quat1.get2();
80
      float qz = quat1.get3();
81
      float qw = quat1.get4();
82

    
83
      float rx = quat2.get1();
84
      float ry = quat2.get2();
85
      float rz = quat2.get3();
86
      float rw = quat2.get4();
87

    
88
      float tx = rw*qx - rz*qy + ry*qz + rx*qw;
89
      float ty = rw*qy + rz*qx + ry*qw - rx*qz;
90
      float tz = rw*qz + rz*qw - ry*qx + rx*qy;
91
      float tw = rw*qw - rz*qz - ry*qy - rx*qx;
92

    
93
      return new Static4D(tx,ty,tz,tw);
94
      }
95

    
96
///////////////////////////////////////////////////////////////////////////////////////////////////
97
// rotate 'vector' by quat  ( i.e. return quat*vector*(quat^-1) )
98

    
99
    public static Static4D rotateVectorByQuat(Static4D vector, Static4D quat)
100
      {
101
      float qx = quat.get1();
102
      float qy = quat.get2();
103
      float qz = quat.get3();
104
      float qw = quat.get4();
105

    
106
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
107
      Static4D tmp = quatMultiply(quat,vector);
108

    
109
      return quatMultiply(tmp,quatInverted);
110
      }
111

    
112
///////////////////////////////////////////////////////////////////////////////////////////////////
113
// rotate 'vector' by quat^(-1)  ( i.e. return (quat^-1)*vector*quat )
114

    
115
    public static Static4D rotateVectorByInvertedQuat(Static4D vector, Static4D quat)
116
      {
117
      float qx = quat.get1();
118
      float qy = quat.get2();
119
      float qz = quat.get3();
120
      float qw = quat.get4();
121

    
122
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
123
      Static4D tmp = quatMultiply(quatInverted,vector);
124

    
125
      return quatMultiply(tmp,quat);
126
      }
127

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

    
130
    void setScreenSize(int width, int height)
131
      {
132
      mScreenWidth = width;
133
      mScreenHeight= height;
134

    
135
      mScreenMin = width<height ? width:height;
136
      }
137

    
138
///////////////////////////////////////////////////////////////////////////////////////////////////
139

    
140
    void setCameraDist(float distance)
141
      {
142
      mCameraDistance = distance;
143
      }
144

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

    
147
    RubikRenderer getRenderer()
148
      {
149
      return mRenderer;
150
      }
151

    
152
///////////////////////////////////////////////////////////////////////////////////////////////////
153

    
154
    int getRedButton()
155
      {
156
      return mButton;
157
      }
158

    
159
///////////////////////////////////////////////////////////////////////////////////////////////////
160

    
161
    void markButton(int button)
162
      {
163
      mButton = button;
164
      RubikActivity act = (RubikActivity)getContext();
165

    
166
      for(int b=0; b<RubikSize.LENGTH; b++)
167
        {
168
        Drawable d = act.findViewById(b).getBackground();
169

    
170
        if( b==button )
171
          {
172
          d.setColorFilter(ContextCompat.getColor(act,R.color.red), PorterDuff.Mode.MULTIPLY);
173
          }
174
        else
175
          {
176
          d.clearColorFilter();
177
          }
178
        }
179
      }
180

    
181
///////////////////////////////////////////////////////////////////////////////////////////////////
182

    
183
    void addSizeButtons(RubikActivity act)
184
      {
185
      LinearLayout layout = act.findViewById(R.id.sizeLayout);
186
      DisplayMetrics metrics = getResources().getDisplayMetrics();
187
      float scale = metrics.density;
188
      int size = (int)(64*scale +0.5f);
189
      int padding = (int)(3*scale + 0.5f);
190
      ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(size,size);
191

    
192
      for(int i=0; i<RubikSize.LENGTH; i++)
193
        {
194
        ImageButton button = new ImageButton(act);
195
        button.setLayoutParams(params);
196
        button.setId(i);
197
        button.setPadding(padding,0,padding,0);
198
        int iconID = RubikSize.getSize(i).getIconID();
199
        button.setImageResource(iconID);
200
        button.setOnClickListener(act);
201
        layout.addView(button);
202
        }
203
      }
204

    
205
///////////////////////////////////////////////////////////////////////////////////////////////////
206

    
207
    void enterScrambleMode()
208
      {
209
      if( !mInScrambleMode )
210
        {
211
        mInScrambleMode = true;
212

    
213
        android.util.Log.e("view", "entering scramble mode");
214

    
215
        RubikActivity act = (RubikActivity)getContext();
216

    
217
        Button scrambleButt = act.findViewById(R.id.rubikScramble);
218

    
219
        if( scrambleButt!=null )
220
          {
221
          scrambleButt.setClickable(false);
222
          scrambleButt.setVisibility(INVISIBLE);
223
          }
224
        else
225
          {
226
          android.util.Log.e("view", "button null!");
227
          }
228
        }
229
      }
230

    
231
///////////////////////////////////////////////////////////////////////////////////////////////////
232

    
233
    void leaveScrambleMode()
234
      {
235
      if( mInScrambleMode )
236
        {
237
        mInScrambleMode = false;
238

    
239
        android.util.Log.e("view", "leaving scramble mode");
240

    
241
        RubikActivity act = (RubikActivity)getContext();
242

    
243
        Button scrambleButt = act.findViewById(R.id.rubikScramble);
244

    
245
        if( scrambleButt!=null )
246
          {
247
          scrambleButt.setClickable(true);
248
          scrambleButt.setVisibility(VISIBLE);
249
          }
250
        else
251
          {
252
          android.util.Log.e("view", "button null!");
253
          }
254
        }
255
      }
256

    
257
///////////////////////////////////////////////////////////////////////////////////////////////////
258

    
259
    void leaveScrambleModeNonUI()
260
      {
261
      RubikActivity act = (RubikActivity)getContext();
262

    
263
      act.runOnUiThread(new Runnable()
264
        {
265
        @Override
266
        public void run()
267
          {
268
          leaveScrambleMode();
269
          }
270
        });
271
      }
272

    
273
///////////////////////////////////////////////////////////////////////////////////////////////////
274

    
275
    void setQuatAccumulated()
276
      {
277
      mQuatAccumulated.set(mTempAccumulated);
278
      }
279

    
280
///////////////////////////////////////////////////////////////////////////////////////////////////
281

    
282
    void setQuatCurrent()
283
      {
284
      mQuatCurrent.set(mTempCurrent);
285
      }
286

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

    
289
    Static4D getQuatAccumulated()
290
      {
291
      return mQuatAccumulated;
292
      }
293

    
294
///////////////////////////////////////////////////////////////////////////////////////////////////
295

    
296
    Static4D getQuatCurrent()
297
      {
298
      return mQuatCurrent;
299
      }
300

    
301
///////////////////////////////////////////////////////////////////////////////////////////////////
302

    
303
    private Static4D quatFromDrag(float dragX, float dragY)
304
      {
305
      float axisX = dragY;  // inverted X and Y - rotation axis is perpendicular to (dragX,dragY)
306
      float axisY = dragX;  // Why not (-dragY, dragX) ? because Y axis is also inverted!
307
      float axisZ = 0;
308
      float axisL = (float)Math.sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);
309

    
310
      if( axisL>0 )
311
        {
312
        axisX /= axisL;
313
        axisY /= axisL;
314
        axisZ /= axisL;
315

    
316
        float ratio = axisL;
317
        ratio = ratio - (int)ratio;     // the cos() is only valid in (0,Pi)
318

    
319
        float cosA = (float)Math.cos(Math.PI*ratio);
320
        float sinA = (float)Math.sqrt(1-cosA*cosA);
321

    
322
        return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
323
        }
324

    
325
      return new Static4D(0f, 0f, 0f, 1f);
326
      }
327

    
328
///////////////////////////////////////////////////////////////////////////////////////////////////
329
// PUBLIC API
330
///////////////////////////////////////////////////////////////////////////////////////////////////
331

    
332
    public RubikSurfaceView(Context context, AttributeSet attrs)
333
      {
334
      super(context,attrs);
335

    
336
      if(!isInEditMode())
337
        {
338
        mInScrambleMode = false;
339
        mRenderer = new RubikRenderer(this);
340
        mMovement = new RubikCubeMovement();
341

    
342
        final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
343
        final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
344
        setEGLContextClientVersion( (configurationInfo.reqGlEsVersion>>16) >= 3 ? 3:2 );
345
        setRenderer(mRenderer);
346
        }
347
      }
348

    
349
///////////////////////////////////////////////////////////////////////////////////////////////////
350

    
351
    @Override
352
    public boolean onTouchEvent(MotionEvent event)
353
      {
354
      int action = event.getAction();
355
      float x = (event.getX() - mScreenWidth*0.5f)/mScreenMin;
356
      float y = (mScreenHeight*0.5f -event.getY())/mScreenMin;
357

    
358
      switch(action)
359
         {
360
         case MotionEvent.ACTION_DOWN: mX = x;
361
                                       mY = y;
362
                                       mLastTouchedFace = mMovement.faceTouched(mQuatAccumulated,mCameraDistance/mScreenMin, x, y);
363

    
364
                                       if( mLastTouchedFace != RubikCubeMovement.NONE )
365
                                         {
366
                                         mDragging           = false;
367
                                         mBeginningRotation  = mRenderer.canRotate();
368
                                         mContinuingRotation = false;
369
                                         }
370
                                       else
371
                                         {
372
                                         mDragging           = mRenderer.canDrag();
373
                                         mBeginningRotation  = false;
374
                                         mContinuingRotation = false;
375
                                         }
376
                                       break;
377
         case MotionEvent.ACTION_MOVE: if( mDragging )
378
                                         {
379
                                         mTempCurrent.set(quatFromDrag(mX-x,y-mY));
380
                                         mRenderer.setQuatCurrentOnNextRender();
381

    
382
                                         if( (mX-x)*(mX-x) + (mY-y)*(mY-y) > 1.0f/(DIRECTION_SENSITIVITY*DIRECTION_SENSITIVITY) )
383
                                           {
384
                                           mX = x;
385
                                           mY = y;
386
                                           mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
387
                                           mTempCurrent.set(0f, 0f, 0f, 1f);
388
                                           mRenderer.setQuatCurrentOnNextRender();
389
                                           mRenderer.setQuatAccumulatedOnNextRender();
390
                                           }
391
                                         }
392
                                       if( mBeginningRotation )
393
                                         {
394
                                         if( (mX-x)*(mX-x)+(mY-y)*(mY-y) > 1.0f/(ROTATION_SENSITIVITY*ROTATION_SENSITIVITY) )
395
                                           {
396
                                           Static2D rot = mMovement.newRotation(mQuatAccumulated,mLastTouchedFace, x, y);
397
                                           RubikCube cube = mRenderer.getCube();
398

    
399
                                           cube.addNewRotation( (int)rot.get1(), (int)(cube.getSize()*rot.get2()) );
400

    
401
                                           mBeginningRotation = false;
402
                                           mContinuingRotation= true;
403
                                           }
404
                                         }
405
                                       else if( mContinuingRotation )
406
                                         {
407
                                         float angle = mMovement.continueRotation(mQuatAccumulated,mLastTouchedFace, x, y);
408

    
409
                                         mRenderer.getCube().continueRotation(SWIPING_SENSITIVITY*angle);
410
                                         }
411
                                       break;
412
         case MotionEvent.ACTION_UP  : if( mDragging )
413
                                         {
414
                                         mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
415
                                         mTempCurrent.set(0f, 0f, 0f, 1f);
416
                                         mRenderer.setQuatCurrentOnNextRender();
417
                                         mRenderer.setQuatAccumulatedOnNextRender();
418
                                         }
419

    
420
                                       if( mContinuingRotation )
421
                                         {
422
                                         mRenderer.finishRotation();
423
                                         }
424
                                       break;
425
         }
426

    
427
      return true;
428
      }
429
}
430

    
(10-10/10)