Project

General

Profile

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

magiccube / src / main / java / org / distorted / bandaged / BandagedCreatorRenderer.java @ a41e3c94

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2022 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.bandaged;
21

    
22
import javax.microedition.khronos.egl.EGLConfig;
23
import javax.microedition.khronos.opengles.GL10;
24

    
25
import android.app.Activity;
26
import android.opengl.GLES31;
27
import android.opengl.GLSurfaceView;
28
import android.widget.Toast;
29

    
30
import org.distorted.dialogs.RubikDialogSaveBandaged;
31
import org.distorted.library.effect.PostprocessEffectBorder;
32
import org.distorted.library.main.DistortedEffects;
33
import org.distorted.library.main.DistortedFramebuffer;
34
import org.distorted.library.main.DistortedLibrary;
35
import org.distorted.library.main.DistortedNode;
36
import org.distorted.library.main.DistortedScreen;
37

    
38
import org.distorted.library.main.InternalOutputSurface;
39
import org.distorted.library.type.Static1D;
40
import org.distorted.library.type.Static3D;
41
import org.distorted.library.type.Static4D;
42
import org.distorted.objectlib.json.JsonWriter;
43
import org.distorted.objectlib.main.ShapeHexahedron;
44
import org.distorted.objectlib.main.TwistyObject;
45
import org.distorted.objectlib.objects.TwistyBandagedGeneric;
46
import org.json.JSONException;
47

    
48
import java.io.File;
49
import java.io.FileNotFoundException;
50
import java.io.IOException;
51
import java.nio.ByteBuffer;
52
import java.nio.ByteOrder;
53

    
54
///////////////////////////////////////////////////////////////////////////////////////////////////
55

    
56
public class BandagedCreatorRenderer implements GLSurfaceView.Renderer, DistortedLibrary.ExceptionListener
57
{
58
   public static final float BRIGHTNESS = 0.333f;
59
   private static final int DURATION = 1000;
60

    
61
   static final int COLOR_DEFAULT = 0xffffff55;
62
   static final int COLOR_MARKED  = 0xffff0000;
63

    
64
   static final float SCREEN_RATIO = 0.5f;
65
   static final float OBJECT_SIZE  = 3.0f;
66

    
67
   private final float[][] POSITIONS = new float[][]
68
        {
69
          {-1,  1,  1},
70
          {-1,  1,  0},
71
          {-1,  1, -1},
72
          {-1,  0,  1},
73
          {-1,  0,  0},
74
          {-1,  0, -1},
75
          {-1, -1,  1},
76
          {-1, -1,  0},
77
          {-1, -1, -1},
78
          { 0, -1,  1},
79
          { 0, -1,  0},
80
          { 0,  1,  1},
81
          { 0,  1,  0},
82
          { 0,  1, -1},
83
          { 0,  0,  1},
84
          { 0,  0, -1},
85
          { 1,  1,  1},
86
          { 1,  1,  0},
87
          { 1,  1, -1},
88
          { 1,  0,  1},
89
          { 1,  0,  0},
90
          { 1, -1,  1},
91
          { 1,  0, -1},
92
          { 1, -1, -1},
93
          { 1, -1,  0},
94
          { 0, -1, -1},
95
        };
96

    
97
   private final BandagedCreatorView mView;
98
   private final DistortedScreen mScreen;
99
   private final Static3D mScale;
100
   private final BandagedCubit[] mCubits;
101
   private final Static4D mQuatT, mQuatA;
102

    
103
   private boolean mInitialPhase;
104
   private long mStartTime;
105
   private float mScaleValue;
106
   private float mX, mY, mZ, mW;
107
   private boolean mResetQuats, mSetQuatT, mResettingObject;
108
   private int mSaveIcon;
109
   private DistortedFramebuffer mFramebuffer;
110
   private String mPath;
111

    
112
///////////////////////////////////////////////////////////////////////////////////////////////////
113

    
114
   BandagedCreatorRenderer(BandagedCreatorView v)
115
     {
116
     mQuatT = new Static4D(0,0,0,1);
117
     mQuatA = new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
118

    
119
     mView = v;
120

    
121
     mResetQuats     = false;
122
     mSetQuatT       = false;
123
     mResettingObject= false;
124

    
125
     mSaveIcon = -1;
126

    
127
     mScreen = new DistortedScreen();
128
     mScreen.glClearColor(BRIGHTNESS, BRIGHTNESS, BRIGHTNESS, 1.0f);
129
     mScale = new Static3D(1,1,1);
130
     mCubits= createCubits();
131
     }
132

    
133
///////////////////////////////////////////////////////////////////////////////////////////////////
134

    
135
   private boolean isAdjacent(float[] pos1, float[] pos2)
136
     {
137
     int len1 = pos1.length/3;
138
     int len2 = pos2.length/3;
139

    
140
     for(int i=0; i<len1; i++)
141
       for(int j=0; j<len2; j++)
142
         {
143
         float d0 = pos1[3*i  ] - pos2[3*j  ];
144
         float d1 = pos1[3*i+1] - pos2[3*j+1];
145
         float d2 = pos1[3*i+2] - pos2[3*j+2];
146

    
147
         if( d0*d0 + d1*d1 + d2*d2 == 1 ) return true;
148
         }
149

    
150
     return false;
151
     }
152

    
153
///////////////////////////////////////////////////////////////////////////////////////////////////
154

    
155
   private BandagedCubit[] createCubits()
156
     {
157
     int len = POSITIONS.length;
158
     BandagedCubit[] cubits = new BandagedCubit[len];
159

    
160
     for(int c=0; c<len; c++)
161
       {
162
       cubits[c] = new BandagedCubit(POSITIONS[c],mQuatT,mQuatA,mScale,COLOR_DEFAULT);
163
       }
164

    
165
     return cubits;
166
     }
167

    
168
///////////////////////////////////////////////////////////////////////////////////////////////////
169

    
170
   private void resetObject()
171
     {
172
     mView.resetCubits();
173

    
174
     int len = POSITIONS.length;
175

    
176
     for(int c=0; c<len; c++)
177
       {
178
       if( !mCubits[c].isAttached() )
179
         {
180
         mCubits[c].attach();
181
         mCubits[c].setTexture( COLOR_DEFAULT);
182
         mScreen.attach(mCubits[c].getNode());
183
         }
184
       if( mCubits[c].getPosition().length>3 )
185
         {
186
         mCubits[c].reset(mScaleValue);
187
         }
188
       }
189
     }
190

    
191
///////////////////////////////////////////////////////////////////////////////////////////////////
192

    
193
   @Override
194
   public void onDrawFrame(GL10 glUnused)
195
     {
196
     long time = System.currentTimeMillis();
197
     mScreen.render(time);
198

    
199
     if( mSetQuatT )
200
       {
201
       mSetQuatT = false;
202
       mQuatT.set(mX,mY,mZ,mW);
203
       }
204

    
205
     if( mResetQuats )
206
       {
207
       mResetQuats = false;
208

    
209
       float qx = mQuatT.get0();
210
       float qy = mQuatT.get1();
211
       float qz = mQuatT.get2();
212
       float qw = mQuatT.get3();
213

    
214
       float rx = mQuatA.get0();
215
       float ry = mQuatA.get1();
216
       float rz = mQuatA.get2();
217
       float rw = mQuatA.get3();
218

    
219
       float tx = rw*qx - rz*qy + ry*qz + rx*qw;
220
       float ty = rw*qy + rz*qx + ry*qw - rx*qz;
221
       float tz = rw*qz + rz*qw - ry*qx + rx*qy;
222
       float tw = rw*qw - rz*qz - ry*qy - rx*qx;
223

    
224
       mQuatT.set(0f, 0f, 0f, 1f);
225
       mQuatA.set(tx, ty, tz, tw);
226
       }
227

    
228
     if( mResettingObject )
229
       {
230
       boolean done = continueResetting(time);
231
       if( done ) mResettingObject = false;
232
       }
233

    
234
     if( mSaveIcon>=0 )
235
       {
236
       renderIcon(time); // for some reason we need to call render() twice here, otherwise the
237
       mSaveIcon++;      // icon turns out black. Probably some problem with binding the texture.
238
       }
239
     if( mSaveIcon>=2 )
240
       {
241
       saveIcon();
242
       mSaveIcon = -1;
243
       }
244
     }
245

    
246
///////////////////////////////////////////////////////////////////////////////////////////////////
247

    
248
   @Override
249
   public void onSurfaceChanged(GL10 glUnused, int width, int height)
250
      {
251
      final float Q = SCREEN_RATIO/OBJECT_SIZE;
252
      mScaleValue = width<height ? Q*width : Q*height;
253

    
254
      mScreen.detachAll();
255
      int len = POSITIONS.length;
256
      int touched = mView.getTouched();
257

    
258
      for(int i=0; i<len; i++)
259
        if( mCubits[i].isAttached() )
260
          {
261
          mCubits[i].scaleMove(mScaleValue);
262
          mCubits[i].setTexture( touched==i ? COLOR_MARKED : COLOR_DEFAULT);
263
          DistortedNode node = mCubits[i].getNode();
264
          mScreen.attach(node);
265
          }
266

    
267
      mScale.set( mScaleValue,mScaleValue,mScaleValue );
268
      mView.setScreenSize(width,height);
269
      mScreen.resize(width,height);
270
      }
271

    
272
///////////////////////////////////////////////////////////////////////////////////////////////////
273

    
274
   @Override
275
   public void onSurfaceCreated(GL10 glUnused, EGLConfig config)
276
      {
277
      DistortedLibrary.onSurfaceCreated(mView.getContext(),this,1);
278
      }
279

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

    
282
   public void distortedException(Exception ex)
283
     {
284
     android.util.Log.e("CREATOR", "unexpected exception: "+ex.getMessage() );
285
     }
286

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

    
289
   public BandagedCubit[] getCubits()
290
     {
291
     return mCubits;
292
     }
293

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

    
296
   public DistortedScreen getScreen()
297
     {
298
     return mScreen;
299
     }
300

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

    
303
   public void tryConnectingCubits(int index1, int index2)
304
     {
305
     if( index1!=index2 )
306
       {
307
       float[] pos1 = mCubits[index1].getPosition();
308
       float[] pos2 = mCubits[index2].getPosition();
309

    
310
       if( isAdjacent(pos1,pos2) )
311
         {
312
         mCubits[index2].join(pos1,mScaleValue);
313
         mCubits[index1].detach();
314
         mScreen.detach(mCubits[index1].getNode());
315
         }
316
       }
317
     }
318

    
319
///////////////////////////////////////////////////////////////////////////////////////////////////
320

    
321
   public Static4D getQuatAccu()
322
     {
323
     return mQuatA;
324
     }
325

    
326
///////////////////////////////////////////////////////////////////////////////////////////////////
327

    
328
   public void setQuatTemp(float x, float y, float z, float w)
329
     {
330
     mX = x;
331
     mY = y;
332
     mZ = z;
333
     mW = w;
334

    
335
     mSetQuatT = true;
336
     }
337

    
338
///////////////////////////////////////////////////////////////////////////////////////////////////
339

    
340
   public void resetQuats()
341
     {
342
     mResetQuats = true;
343
     }
344

    
345
///////////////////////////////////////////////////////////////////////////////////////////////////
346

    
347
   public boolean isBusy()
348
     {
349
     return mResettingObject;
350
     }
351

    
352
///////////////////////////////////////////////////////////////////////////////////////////////////
353

    
354
   public void saveObject()
355
     {
356
     int len = POSITIONS.length;
357
     int numAttached=0;
358

    
359
     for(int i=0; i<len; i++)
360
       if( mCubits[i].isAttached() ) numAttached++;
361

    
362
     float[][] pos = new float[numAttached][];
363
     int attached=0;
364

    
365
     for(int i=0; i<len; i++)
366
       if( mCubits[i].isAttached() )
367
         {
368
         pos[attached++] = mCubits[i].getPosition();
369
         }
370

    
371
     TwistyBandagedGeneric.setPositions(pos);
372
     TwistyObject obj = new TwistyBandagedGeneric( new Static4D(0,0,0,1), 1.0f, TwistyObject.MODE_NORM);
373
     BandagedCreatorActivity act = (BandagedCreatorActivity) mView.getContext();
374

    
375
     boolean success = createObjectJson(obj,act);
376
     setupIconCreation(act);
377

    
378
     if( success )
379
       {
380
       act.addObject(obj.getShortName());
381
       }
382
     }
383

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

    
386
   private boolean createObjectJson(TwistyObject object, Activity act)
387
     {
388
     final String name = object.getShortName()+"_object.json";
389
     File file = new File(act.getFilesDir(), name);
390
     String filename = file.getAbsolutePath();
391

    
392
     try
393
       {
394
       JsonWriter writer = JsonWriter.getInstance();
395
       String json = writer.createObjectString(object,24);
396
       writer.write(filename,json);
397
       return true;
398
       }
399
     catch(JSONException ex)
400
       {
401
       act.runOnUiThread(new Runnable()
402
         {
403
         public void run()
404
           {
405
           String message = "JSON Exception saving to \n\n"+filename+"\n\n failed:\n\n"+ex.getMessage();
406
           Toast.makeText(act,message,Toast.LENGTH_LONG).show();
407
           }
408
         });
409

    
410
       return false;
411
       }
412
     catch(FileNotFoundException ex)
413
       {
414
       act.runOnUiThread(new Runnable()
415
         {
416
         public void run()
417
           {
418
           String message = "FileNotFound exception saving to \n\n"+filename+"\n\n failed:\n\n"+ex.getMessage();
419
           Toast.makeText(act,message,Toast.LENGTH_LONG).show();
420
           }
421
         });
422

    
423
       return false;
424
       }
425
     catch(IOException ex)
426
       {
427
       act.runOnUiThread(new Runnable()
428
         {
429
         public void run()
430
           {
431
           String message = "IO exception saving to \n\n"+filename+"\n\n failed:\n\n"+ex.getMessage();
432
           Toast.makeText(act,message,Toast.LENGTH_LONG).show();
433
           }
434
         });
435

    
436
       return false;
437
       }
438
     }
439

    
440
///////////////////////////////////////////////////////////////////////////////////////////////////
441

    
442
   private void setupIconCreation(Activity act)
443
     {
444
     final float R=1.0f;
445
     final int FBO_WIDTH  = (int)(R*240);
446
     final int FBO_HEIGHT = (int)(R*360);
447
     final float OBJECT_SIZE = R*0.38f;
448

    
449
     TwistyObject object = new TwistyBandagedGeneric(ShapeHexahedron.DEFAULT_ROT, OBJECT_SIZE, TwistyObject.MODE_ICON);
450
     DistortedEffects effects = object.getObjectEffects();
451
     DistortedNode node = object.getNode();
452

    
453
     if( mFramebuffer==null )
454
       {
455
       mFramebuffer = new DistortedFramebuffer(FBO_WIDTH,FBO_HEIGHT,1, InternalOutputSurface.DEPTH_NO_STENCIL);
456
       mFramebuffer.glClearColor(BRIGHTNESS, BRIGHTNESS, BRIGHTNESS, 1.0f);
457
       }
458

    
459
     mFramebuffer.detachAll();
460
     mFramebuffer.attach(node);
461

    
462
     Static1D halo = new Static1D(5);
463
     Static4D color = new Static4D(0,0,0,1);
464
     PostprocessEffectBorder border = new PostprocessEffectBorder(halo,color);
465
     border.setHaloDepth(false);
466
     effects.apply(border);
467

    
468
     final String name = object.getShortName()+".png";
469
     File file = new File(act.getFilesDir(), name);
470
     String filename = file.getAbsolutePath();
471

    
472
     mSaveIcon = 0;
473
     mPath = filename;
474
     }
475

    
476
///////////////////////////////////////////////////////////////////////////////////////////////////
477

    
478
   private void renderIcon(long time)
479
     {
480
     mFramebuffer.render(time);
481
     }
482

    
483
///////////////////////////////////////////////////////////////////////////////////////////////////
484

    
485
   private void saveIcon()
486
     {
487
     int fW = mFramebuffer.getWidth();
488
     int fH = mFramebuffer.getHeight();
489

    
490
     ByteBuffer buf = ByteBuffer.allocateDirect(fW*fH*4);
491
     buf.order(ByteOrder.LITTLE_ENDIAN);
492

    
493
     mFramebuffer.setAsReadFramebuffer(0);
494
     GLES31.glReadBuffer(GLES31.GL_COLOR_ATTACHMENT0);
495
     GLES31.glReadPixels( 0, 0, fW, fH, GLES31.GL_RGBA, GLES31.GL_UNSIGNED_BYTE, buf);
496
     BandagedCreatorWorkerThread.newBuffer(buf,fW,fH,6,mPath);
497
     GLES31.glBindFramebuffer(GLES31.GL_READ_FRAMEBUFFER, 0);
498

    
499
     mSaveIcon = -1;
500
     }
501

    
502
///////////////////////////////////////////////////////////////////////////////////////////////////
503

    
504
   public void displaySavingDialog()
505
     {
506
     BandagedCreatorActivity act = (BandagedCreatorActivity)mView.getContext();
507
     RubikDialogSaveBandaged saveDiag = new RubikDialogSaveBandaged();
508
     saveDiag.show(act.getSupportFragmentManager(), null);
509
     }
510

    
511
///////////////////////////////////////////////////////////////////////////////////////////////////
512

    
513
   public void setupReset()
514
     {
515
     mResettingObject = true;
516
     mInitialPhase    = true;
517
     mStartTime       = System.currentTimeMillis();
518
     }
519

    
520
///////////////////////////////////////////////////////////////////////////////////////////////////
521

    
522
   public boolean continueResetting(long time)
523
     {
524
     long diff = time-mStartTime;
525
     float quotient = ((float)diff)/DURATION;
526

    
527
     if( mInitialPhase && quotient>0.5f )
528
       {
529
       mInitialPhase=false;
530
       resetObject();
531
       }
532

    
533
     double angle = 2*Math.PI*quotient*quotient*(3-2*quotient);
534

    
535
     float sinA = (float)Math.sin(angle);
536
     float cosA = (float)Math.cos(angle);
537

    
538
     mQuatT.set(0, -sinA, 0, cosA);
539

    
540
     return quotient>1.0f;
541
     }
542
}
(3-3/13)