Project

General

Profile

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

magiccube / src / main / java / org / distorted / magic / RubikSurfaceView.java @ 33499c56

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.SharedPreferences;
25
import android.content.pm.ConfigurationInfo;
26
import android.graphics.PorterDuff;
27
import android.graphics.drawable.Drawable;
28
import android.opengl.GLSurfaceView;
29
import android.support.v4.content.ContextCompat;
30
import android.util.AttributeSet;
31
import android.util.DisplayMetrics;
32
import android.view.LayoutInflater;
33
import android.view.MotionEvent;
34
import android.view.View;
35
import android.view.ViewGroup;
36
import android.widget.Button;
37
import android.widget.ImageButton;
38
import android.widget.LinearLayout;
39

    
40
import org.distorted.component.HorizontalNumberPicker;
41
import org.distorted.library.type.Static2D;
42
import org.distorted.library.type.Static4D;
43
import org.distorted.object.RubikCube;
44
import org.distorted.object.RubikCubeMovement;
45

    
46
///////////////////////////////////////////////////////////////////////////////////////////////////
47

    
48
public class RubikSurfaceView extends GLSurfaceView
49
{
50
    public static final int BUTTON_ID_BACK= 1023;
51

    
52
    public static final int MIN_SCRAMBLE =  1;
53
    public static final int DEF_SCRAMBLE =  1;
54
    public static final int MAX_SCRAMBLE = 18;
55

    
56
    // Moving the finger from the middle of the vertical screen to the right edge will rotate a
57
    // given face by SWIPING_SENSITIVITY/2 degrees.
58
    private final static int SWIPING_SENSITIVITY  = 240;
59
    // Moving the finger by 1/12 the distance of min(scrWidth,scrHeight) will start a Rotation.
60
    private final static int ROTATION_SENSITIVITY =  12;
61
    // Every 1/12 the distance of min(scrWidth,scrHeight) the direction of cube rotation will reset.
62
    private final static int DIRECTION_SENSITIVITY=  12;
63

    
64
    private final Static4D CAMERA_POINT = new Static4D(0, 0, RubikRenderer.CAMERA_DISTANCE, 0);
65

    
66
    private RubikRenderer mRenderer;
67
    private RubikCubeMovement mMovement;
68
    private boolean mDragging, mBeginningRotation, mContinuingRotation;
69
    private float mX, mY;
70
    private int mScreenWidth, mScreenHeight, mScreenMin;
71

    
72
    private HorizontalNumberPicker mPicker;
73
    private int mScrambleValue;
74

    
75
    private static int mButton = RubikSize.SIZE3.ordinal();
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 scramble()
84
      {
85
      int scramble = mPicker.getValue();
86
      mRenderer.scrambleCube(scramble);
87
      }
88

    
89
///////////////////////////////////////////////////////////////////////////////////////////////////
90

    
91
    void savePreferences(SharedPreferences.Editor editor)
92
      {
93
      editor.putInt("scramble", mScrambleValue );
94
      }
95

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

    
98
    void restorePreferences(SharedPreferences preferences)
99
      {
100
      mScrambleValue= preferences.getInt("scramble", DEF_SCRAMBLE);
101
      }
102

    
103
///////////////////////////////////////////////////////////////////////////////////////////////////
104

    
105
    void setScreenSize(int width, int height)
106
      {
107
      mScreenWidth = width;
108
      mScreenHeight= height;
109

    
110
      mScreenMin = width<height ? width:height;
111
      }
112

    
113
///////////////////////////////////////////////////////////////////////////////////////////////////
114

    
115
    RubikRenderer getRenderer()
116
      {
117
      return mRenderer;
118
      }
119

    
120
///////////////////////////////////////////////////////////////////////////////////////////////////
121

    
122
    static int getRedButton()
123
      {
124
      return mButton;
125
      }
126

    
127
///////////////////////////////////////////////////////////////////////////////////////////////////
128

    
129
    void setQuatAccumulated()
130
      {
131
      mQuatAccumulated.set(mTempAccumulated);
132
      }
133

    
134
///////////////////////////////////////////////////////////////////////////////////////////////////
135

    
136
    void setQuatCurrent()
137
      {
138
      mQuatCurrent.set(mTempCurrent);
139
      }
140

    
141
///////////////////////////////////////////////////////////////////////////////////////////////////
142

    
143
    Static4D getQuatAccumulated()
144
      {
145
      return mQuatAccumulated;
146
      }
147

    
148
///////////////////////////////////////////////////////////////////////////////////////////////////
149

    
150
    Static4D getQuatCurrent()
151
      {
152
      return mQuatCurrent;
153
      }
154

    
155
///////////////////////////////////////////////////////////////////////////////////////////////////
156

    
157
    private Static4D quatFromDrag(float dragX, float dragY)
158
      {
159
      float axisX = dragY;  // inverted X and Y - rotation axis is perpendicular to (dragX,dragY)
160
      float axisY = dragX;  // Why not (-dragY, dragX) ? because Y axis is also inverted!
161
      float axisZ = 0;
162
      float axisL = (float)Math.sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);
163

    
164
      if( axisL>0 )
165
        {
166
        axisX /= axisL;
167
        axisY /= axisL;
168
        axisZ /= axisL;
169

    
170
        float ratio = axisL;
171
        ratio = ratio - (int)ratio;     // the cos() is only valid in (0,Pi)
172

    
173
        float cosA = (float)Math.cos(Math.PI*ratio);
174
        float sinA = (float)Math.sqrt(1-cosA*cosA);
175

    
176
        return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
177
        }
178

    
179
      return new Static4D(0f, 0f, 0f, 1f);
180
      }
181

    
182
///////////////////////////////////////////////////////////////////////////////////////////////////
183
// return quat1*quat2
184

    
185
    public static Static4D quatMultiply( Static4D quat1, Static4D quat2 )
186
      {
187
      float qx = quat1.get0();
188
      float qy = quat1.get1();
189
      float qz = quat1.get2();
190
      float qw = quat1.get3();
191

    
192
      float rx = quat2.get0();
193
      float ry = quat2.get1();
194
      float rz = quat2.get2();
195
      float rw = quat2.get3();
196

    
197
      float tx = rw*qx - rz*qy + ry*qz + rx*qw;
198
      float ty = rw*qy + rz*qx + ry*qw - rx*qz;
199
      float tz = rw*qz + rz*qw - ry*qx + rx*qy;
200
      float tw = rw*qw - rz*qz - ry*qy - rx*qx;
201

    
202
      return new Static4D(tx,ty,tz,tw);
203
      }
204

    
205
///////////////////////////////////////////////////////////////////////////////////////////////////
206
// rotate 'vector' by quat  ( i.e. return quat*vector*(quat^-1) )
207

    
208
    public static Static4D rotateVectorByQuat(Static4D vector, Static4D quat)
209
      {
210
      float qx = quat.get0();
211
      float qy = quat.get1();
212
      float qz = quat.get2();
213
      float qw = quat.get3();
214

    
215
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
216
      Static4D tmp = quatMultiply(quat,vector);
217

    
218
      return quatMultiply(tmp,quatInverted);
219
      }
220

    
221
///////////////////////////////////////////////////////////////////////////////////////////////////
222
// rotate 'vector' by quat^(-1)  ( i.e. return (quat^-1)*vector*quat )
223

    
224
    public static Static4D rotateVectorByInvertedQuat(Static4D vector, Static4D quat)
225
      {
226
      float qx = quat.get0();
227
      float qy = quat.get1();
228
      float qz = quat.get2();
229
      float qw = quat.get3();
230

    
231
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
232
      Static4D tmp = quatMultiply(quatInverted,vector);
233

    
234
      return quatMultiply(tmp,quat);
235
      }
236

    
237
///////////////////////////////////////////////////////////////////////////////////////////////////
238

    
239
    void markButton(int button)
240
      {
241
      mButton = button;
242
      RubikActivity act = (RubikActivity)getContext();
243

    
244
      for(int b=0; b<RubikSize.LENGTH; b++)
245
        {
246
        Drawable d = act.findViewById(b).getBackground();
247

    
248
        if( b==button )
249
          {
250
          d.setColorFilter(ContextCompat.getColor(act,R.color.red), PorterDuff.Mode.MULTIPLY);
251
          }
252
        else
253
          {
254
          d.clearColorFilter();
255
          }
256
        }
257
      }
258

    
259
///////////////////////////////////////////////////////////////////////////////////////////////////
260

    
261
    void enterState(RubikActivity act, RubikState state)
262
      {
263
      switch(state)
264
        {
265
        case MAIN: enterMainState(act); break;
266
        case PLAY: enterPlayState(act); break;
267
        }
268
      }
269

    
270
///////////////////////////////////////////////////////////////////////////////////////////////////
271

    
272
    private void enterMainState(RubikActivity act)
273
      {
274
      LayoutInflater inflater = act.getLayoutInflater();
275

    
276
      // TOP ////////////////////////////
277
      LinearLayout layoutTop = act.findViewById(R.id.mainTitle);
278
      layoutTop.removeAllViews();
279
      final View viewTop = inflater.inflate(R.layout.main_title, null);
280
      layoutTop.addView(viewTop);
281

    
282
      // BOT ////////////////////////////
283
      LinearLayout layoutBot = act.findViewById(R.id.mainBar);
284
      layoutBot.removeAllViews();
285

    
286
      DisplayMetrics metrics = getResources().getDisplayMetrics();
287
      float scale = metrics.density;
288
      int size = (int)(60*scale +0.5f);
289
      int padding = (int)(5*scale + 0.5f);
290
      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,size,0.5f);
291

    
292
      Button buttonL = new Button(act);
293
      buttonL.setLayoutParams(params);
294
      buttonL.setId(BUTTON_ID_BACK);
295
      buttonL.setPadding(padding,0,padding,0);
296
      buttonL.setText(R.string.back);
297
      buttonL.setOnClickListener(act);
298
      layoutBot.addView(buttonL);
299

    
300
      Button buttonR = new Button(act);
301
      buttonR.setLayoutParams(params);
302
      buttonR.setId(BUTTON_ID_BACK);
303
      buttonR.setPadding(padding,0,padding,0);
304
      buttonR.setText(R.string.exit);
305
      buttonR.setOnClickListener(act);
306
      layoutBot.addView(buttonR);
307

    
308
      buttonL.setVisibility(INVISIBLE);
309
      }
310

    
311
///////////////////////////////////////////////////////////////////////////////////////////////////
312

    
313
    private void enterPlayState(RubikActivity act)
314
      {
315
      LayoutInflater inflater = act.getLayoutInflater();
316

    
317
      // TOP ////////////////////////////
318
      LinearLayout layoutTop = act.findViewById(R.id.mainTitle);
319
      layoutTop.removeAllViews();
320

    
321
      final View viewTop = inflater.inflate(R.layout.play_title, null);
322
      layoutTop.addView(viewTop);
323

    
324
      // BOT ////////////////////////////
325
      LinearLayout layoutBot = act.findViewById(R.id.mainBar);
326
      layoutBot.removeAllViews();
327

    
328
      DisplayMetrics metrics = getResources().getDisplayMetrics();
329
      float scale = metrics.density;
330
      int size = (int)(60*scale +0.5f);
331
      int padding = (int)(3*scale + 0.5f);
332
      ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(size,size);
333

    
334
      for(int i=0; i<RubikSize.LENGTH; i++)
335
        {
336
        ImageButton button = new ImageButton(act);
337
        button.setLayoutParams(params);
338
        button.setId(i);
339
        button.setPadding(padding,0,padding,0);
340
        int iconID = RubikSize.getSize(i).getIconID();
341
        button.setImageResource(iconID);
342
        button.setOnClickListener(act);
343
        layoutBot.addView(button);
344
        }
345

    
346
      ViewGroup.LayoutParams params2 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,size);
347

    
348
      Button button = new Button(act);
349
      button.setLayoutParams(params2);
350
      button.setId(BUTTON_ID_BACK);
351
      button.setPadding(padding,0,padding,0);
352
      button.setText(R.string.back);
353
      button.setOnClickListener(act);
354
      layoutBot.addView(button);
355

    
356
      markButton(mButton);
357

    
358
      mPicker = act.findViewById(R.id.rubikNumberPicker);
359

    
360
      if( mPicker!=null )
361
        {
362
        mPicker.setMin(MIN_SCRAMBLE);
363
        mPicker.setMax(MAX_SCRAMBLE);
364
        mPicker.setValue(mScrambleValue);
365
        }
366
      }
367

    
368
///////////////////////////////////////////////////////////////////////////////////////////////////
369
// PUBLIC API
370
///////////////////////////////////////////////////////////////////////////////////////////////////
371

    
372
    public RubikSurfaceView(Context context, AttributeSet attrs)
373
      {
374
      super(context,attrs);
375

    
376
      if(!isInEditMode())
377
        {
378
        mRenderer = new RubikRenderer(this);
379
        mMovement = new RubikCubeMovement();
380

    
381
        final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
382
        final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
383
        setEGLContextClientVersion( (configurationInfo.reqGlEsVersion>>16) >= 3 ? 3:2 );
384
        setRenderer(mRenderer);
385
        }
386
      }
387

    
388
///////////////////////////////////////////////////////////////////////////////////////////////////
389

    
390
    @Override
391
    public boolean onTouchEvent(MotionEvent event)
392
      {
393
      int action = event.getAction();
394
      float x = (event.getX() - mScreenWidth*0.5f)/mScreenMin;
395
      float y = (mScreenHeight*0.5f -event.getY())/mScreenMin;
396

    
397
      switch(action)
398
         {
399
         case MotionEvent.ACTION_DOWN: mX = x;
400
                                       mY = y;
401

    
402
                                       Static4D touchPoint1 = new Static4D(x, y, 0, 0);
403
                                       Static4D rotatedTouchPoint1= rotateVectorByInvertedQuat(touchPoint1, mQuatAccumulated);
404
                                       Static4D rotatedCamera= rotateVectorByInvertedQuat(CAMERA_POINT, mQuatAccumulated);
405

    
406
                                       if( mMovement.faceTouched(rotatedTouchPoint1, rotatedCamera) )
407
                                         {
408
                                         mDragging           = false;
409
                                         mBeginningRotation  = mRenderer.canRotate();
410
                                         mContinuingRotation = false;
411
                                         }
412
                                       else
413
                                         {
414
                                         mDragging           = mRenderer.canDrag();
415
                                         mBeginningRotation  = false;
416
                                         mContinuingRotation = false;
417
                                         }
418
                                       break;
419
         case MotionEvent.ACTION_MOVE: if( mDragging )
420
                                         {
421
                                         mTempCurrent.set(quatFromDrag(mX-x,y-mY));
422
                                         mRenderer.setQuatCurrentOnNextRender();
423

    
424
                                         if( (mX-x)*(mX-x) + (mY-y)*(mY-y) > 1.0f/(DIRECTION_SENSITIVITY*DIRECTION_SENSITIVITY) )
425
                                           {
426
                                           mX = x;
427
                                           mY = y;
428
                                           mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
429
                                           mTempCurrent.set(0f, 0f, 0f, 1f);
430
                                           mRenderer.setQuatCurrentOnNextRender();
431
                                           mRenderer.setQuatAccumulatedOnNextRender();
432
                                           }
433
                                         }
434
                                       if( mBeginningRotation )
435
                                         {
436
                                         if( (mX-x)*(mX-x)+(mY-y)*(mY-y) > 1.0f/(ROTATION_SENSITIVITY*ROTATION_SENSITIVITY) )
437
                                           {
438
                                           Static4D touchPoint2 = new Static4D(x, y, 0, 0);
439
                                           Static4D rotatedTouchPoint2= rotateVectorByInvertedQuat(touchPoint2, mQuatAccumulated);
440

    
441
                                           Static2D rot = mMovement.newRotation(rotatedTouchPoint2);
442
                                           RubikCube cube = mRenderer.getCube();
443

    
444
                                           cube.addNewRotation( (int)rot.get0(), (int)(cube.getSize()*rot.get1()) );
445

    
446
                                           mBeginningRotation = false;
447
                                           mContinuingRotation= true;
448
                                           }
449
                                         }
450
                                       else if( mContinuingRotation )
451
                                         {
452
                                         Static4D touchPoint3 = new Static4D(x, y, 0, 0);
453
                                         Static4D rotatedTouchPoint3= rotateVectorByInvertedQuat(touchPoint3, mQuatAccumulated);
454

    
455
                                         float angle = mMovement.continueRotation(rotatedTouchPoint3);
456
                                         mRenderer.getCube().continueRotation(SWIPING_SENSITIVITY*angle);
457
                                         }
458
                                       break;
459
         case MotionEvent.ACTION_UP  : if( mDragging )
460
                                         {
461
                                         mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
462
                                         mTempCurrent.set(0f, 0f, 0f, 1f);
463
                                         mRenderer.setQuatCurrentOnNextRender();
464
                                         mRenderer.setQuatAccumulatedOnNextRender();
465
                                         }
466

    
467
                                       if( mContinuingRotation )
468
                                         {
469
                                         mRenderer.finishRotation();
470
                                         }
471
                                       break;
472
         }
473

    
474
      return true;
475
      }
476
}
477

    
(12-12/12)