Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / json / JsonWriter.java @ d8e03a81

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2021 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted 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
// Distorted 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 Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.objectlib.json;
21

    
22
import java.io.BufferedWriter;
23
import java.io.FileOutputStream;
24
import java.io.IOException;
25
import java.io.OutputStreamWriter;
26
import java.nio.charset.StandardCharsets;
27

    
28
import org.distorted.objectlib.helpers.ObjectFaceShape;
29
import org.json.JSONArray;
30
import org.json.JSONException;
31
import org.json.JSONObject;
32

    
33
import org.distorted.library.type.Static3D;
34
import org.distorted.library.type.Static4D;
35

    
36
import org.distorted.objectlib.helpers.ObjectShape;
37
import org.distorted.objectlib.helpers.ObjectSticker;
38
import org.distorted.objectlib.scrambling.ScrambleState;
39
import org.distorted.objectlib.main.TwistyObject;
40

    
41
///////////////////////////////////////////////////////////////////////////////////////////////////
42

    
43
public class JsonWriter
44
{
45
  public static final int VERSION_OBJECT_MAJOR = 2;
46
  public static final int VERSION_OBJECT_MINOR = 0;
47
  public static final int VERSION_EXTRAS_MAJOR = 1;
48
  public static final int VERSION_EXTRAS_MINOR = 0;
49

    
50
  private static JsonWriter mThis;
51
  private static int mNumCubitFaces;
52

    
53
///////////////////////////////////////////////////////////////////////////////////////////////////
54

    
55
  private JsonWriter()
56
    {
57

    
58
    }
59

    
60
///////////////////////////////////////////////////////////////////////////////////////////////////
61

    
62
  private JSONArray generateCubits(TwistyObject object) throws JSONException
63
    {
64
    JSONArray array = new JSONArray();
65

    
66
    int[] numLayers     = object.getNumLayers();
67
    float[][] positions = object.getCubitPositions(numLayers);
68
    int numCubits       = positions.length;
69

    
70
    for(int c=0; c<numCubits; c++)
71
      {
72
      JSONObject cubit = new JSONObject();
73
      Static4D rotQuat  = object.getCubitQuats(c,numLayers);
74
      int variant       = object.getCubitVariant(c,numLayers);
75

    
76
      JSONArray pos = new JSONArray();
77
      int numPos = positions[c].length;
78
      for(int j=0; j<numPos; j++) pos.put(positions[c][j]);
79
      cubit.put("centers", pos);
80
      cubit.put("qx", rotQuat.get0() );
81
      cubit.put("qy", rotQuat.get1() );
82
      cubit.put("qz", rotQuat.get2() );
83
      cubit.put("qw", rotQuat.get3() );
84
      cubit.put("variant", variant );
85

    
86
      JSONArray colors = new JSONArray();
87

    
88
      for(int f=0; f<mNumCubitFaces; f++)
89
        {
90
        int cubColor = object.getCubitFaceMap(c,f);
91
        colors.put(cubColor);
92
        }
93
      cubit.put("colors",colors);
94

    
95
      array.put(cubit);
96
      }
97

    
98
    return array;
99
    }
100

    
101
///////////////////////////////////////////////////////////////////////////////////////////////////
102

    
103
  private JSONArray generateCorners(float[][] corners) throws JSONException
104
    {
105
    JSONArray array = new JSONArray();
106

    
107
    for(float[] c : corners)
108
      {
109
      JSONObject corner = new JSONObject();
110
      corner.put("strength", c[0]);
111
      corner.put("radius"  , c[1]);
112
      array.put(corner);
113
      }
114

    
115
    return array;
116
    }
117

    
118
///////////////////////////////////////////////////////////////////////////////////////////////////
119

    
120
  private JSONArray generateCenters(float[][] centers) throws JSONException
121
    {
122
    JSONArray array = new JSONArray();
123

    
124
    for(float[] c : centers)
125
      {
126
      JSONObject center = new JSONObject();
127
      center.put("x", c[0]);
128
      center.put("y", c[1]);
129
      center.put("z", c[2]);
130
      array.put(center);
131
      }
132

    
133
    return array;
134
    }
135

    
136
///////////////////////////////////////////////////////////////////////////////////////////////////
137

    
138
  private JSONArray generateBands(float[][] bands) throws JSONException
139
    {
140
    JSONArray array = new JSONArray();
141

    
142
    for (float[] b : bands)
143
      {
144
      JSONObject band = new JSONObject();
145
      band.put("height"          , b[0]);
146
      band.put("angle"           , b[1]);
147
      band.put("distanceToCenter", b[2]);
148
      band.put("distanceToFlat"  , b[3]);
149
      band.put("numOfBands"      , b[4]);
150
      band.put("extraI"          , b[5]);
151
      band.put("extraJ"          , b[6]);
152
      array.put(band);
153
      }
154

    
155
    return array;
156
    }
157

    
158
///////////////////////////////////////////////////////////////////////////////////////////////////
159

    
160
  private JSONArray generateFaces(TwistyObject object, int[][] vertIndices, int[] bandIndices, int cubit, int[] numLayers) throws JSONException
161
    {
162
    JSONArray array = new JSONArray();
163
    int numFaces = vertIndices.length;
164
    int variant = object.getCubitVariant(cubit,numLayers);
165

    
166
    for(int i=0; i<numFaces; i++)
167
      {
168
      JSONObject face = new JSONObject();
169
      face.put("bandIndex", bandIndices[i]);
170

    
171
      int sticker = object.getVariantFaceColor(variant,i);
172
      face.put("sticker",sticker);
173

    
174
      JSONArray vertArr = new JSONArray();
175
      int numV = vertIndices[i].length;
176
      for(int j=0; j<numV; j++) vertArr.put(vertIndices[i][j]);
177
      face.put("vertexIndices",vertArr);
178

    
179
      array.put(face);
180
      }
181

    
182
    return array;
183
    }
184

    
185
///////////////////////////////////////////////////////////////////////////////////////////////////
186

    
187
  private JSONArray generateVertices(float[][] vertices, int[] cornerIndices, int[] centerIndices) throws JSONException
188
    {
189
    JSONArray array = new JSONArray();
190
    int numVertices = vertices.length;
191

    
192
    for(int j=0; j<numVertices; j++)
193
      {
194
      JSONObject vert = new JSONObject();
195
      vert.put("x", vertices[j][0]);
196
      vert.put("y", vertices[j][1]);
197
      vert.put("z", vertices[j][2]);
198
      vert.put("cornerIndex", cornerIndices[j]);
199
      vert.put("centerIndex", centerIndices[j]);
200
      array.put(vert);
201
      }
202

    
203
    return array;
204
    }
205

    
206
///////////////////////////////////////////////////////////////////////////////////////////////////
207

    
208
  private JSONObject generateConvexity(float[] convexity) throws JSONException
209
    {
210
    JSONObject object = new JSONObject();
211
    object.put("x", convexity[0]);
212
    object.put("y", convexity[1]);
213
    object.put("z", convexity[2]);
214
    return object;
215
    }
216

    
217
///////////////////////////////////////////////////////////////////////////////////////////////////
218

    
219
  private int findCubitWithVariant(TwistyObject object, int variant, int numCubits, int[] numLayers)
220
    {
221
    for(int i=0; i<numCubits; i++)
222
      {
223
      if( object.getCubitVariant(i,numLayers)==variant ) return i;
224
      }
225

    
226
    return -1;
227
    }
228

    
229
///////////////////////////////////////////////////////////////////////////////////////////////////
230

    
231
  private JSONArray generateShapes(TwistyObject object) throws JSONException
232
    {
233
    JSONArray shapes = new JSONArray();
234

    
235
    int[] numLayers = object.getNumLayers();
236
    int numVariants = object.getNumCubitVariants(numLayers);
237
    float[][] positions = object.getCubitPositions(numLayers);
238
    int numCubits = positions.length;
239
    mNumCubitFaces = 0;
240

    
241
    for(int i=0; i<numVariants; i++)
242
      {
243
      JSONObject shapeObj = new JSONObject();
244

    
245
      ObjectShape shape = object.getObjectShape(i);
246
      ObjectFaceShape face = object.getObjectFaceShape(i);
247

    
248
      float[] convexity  = face.getConvexityCenter();
249
      float[][] vertices = shape.getVertices();
250
      int[][] vertIndices= shape.getVertIndices();
251
      float[][] bands    = face.getBands();
252
      int[] bandIndices  = face.getBandIndices();
253
      float[][] corners  = face.getCorners();
254
      int[] cornerIndices= face.getCornerIndices();
255
      float[][] centers  = face.getCenters();
256
      int[] centerIndices= face.getCenterIndices();
257

    
258
      int num = vertIndices.length;
259
      if( num>mNumCubitFaces ) mNumCubitFaces=num;
260

    
261
      int cubit = findCubitWithVariant(object,i,numCubits,numLayers);
262

    
263
      if( convexity!=null )
264
        {
265
        JSONObject convObj = generateConvexity(convexity);
266
        shapeObj.put("convexity", convObj);
267
        }
268

    
269
      JSONArray verticesArr = generateVertices(vertices,cornerIndices,centerIndices);
270
      shapeObj.put("vertices", verticesArr);
271
      JSONArray facesArr = generateFaces(object,vertIndices,bandIndices,cubit,numLayers);
272
      shapeObj.put("faces", facesArr);
273
      JSONArray bandsArr = generateBands(bands);
274
      shapeObj.put("bands", bandsArr);
275

    
276
      if( corners!=null )
277
        {
278
        JSONArray cornerArr = generateCorners(corners);
279
        shapeObj.put("cornerPush", cornerArr);
280
        }
281

    
282
      if( centers!=null )
283
        {
284
        JSONArray centerArr = generateCenters(centers);
285
        shapeObj.put("centerPush", centerArr);
286
        }
287

    
288
      shapes.put(shapeObj);
289
      }
290

    
291
    return shapes;
292
    }
293

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

    
296
  private JSONArray generateStickers(TwistyObject object) throws JSONException
297
    {
298
    JSONArray stickers = new JSONArray();
299

    
300
    int numStickers = object.getNumStickerTypes();
301

    
302
    for(int i=0; i<numStickers; i++)
303
      {
304
      JSONObject stickerObj = new JSONObject();
305
      JSONArray  vertexArray= new JSONArray();
306

    
307
      ObjectSticker sticker = object.retSticker(i);
308

    
309
      float[] coords     = sticker.getCoords();
310
      float[] curvatures = sticker.getCurvature();
311
      float[] radii      = sticker.getRadii();
312
      float   stroke     = sticker.getStroke();
313

    
314
      stickerObj.put("stroke", stroke);
315
      int numVertices = radii.length;
316

    
317
      for(int j=0; j<numVertices; j++)
318
        {
319
        JSONObject vertex = new JSONObject();
320
        vertex.put("x", coords[2*j  ]);
321
        vertex.put("y", coords[2*j+1]);
322
        vertex.put("angle", curvatures==null ? 0 : curvatures[j]);
323
        vertex.put("radius",radii[j]);
324
        vertexArray.put(vertex);
325
        }
326
      stickerObj.put("vertices", vertexArray);
327
      stickers.put(stickerObj);
328
      }
329

    
330
    return stickers;
331
    }
332

    
333
///////////////////////////////////////////////////////////////////////////////////////////////////
334

    
335
  private JSONObject generateMesh(TwistyObject object) throws JSONException
336
    {
337
    JSONObject mesh = new JSONObject();
338

    
339
    JSONArray shapes   = generateShapes(object);  // do this before cubits so we calculate numCubitFaces
340
    JSONArray cubits   = generateCubits(object);
341
    JSONArray stickers = generateStickers(object);
342

    
343
    mesh.put("shapes"  , shapes);
344
    mesh.put("cubits"  , cubits);
345
    mesh.put("stickers", stickers);
346

    
347
    return mesh;
348
    }
349

    
350
///////////////////////////////////////////////////////////////////////////////////////////////////
351

    
352
  private JSONObject generateMetadata(TwistyObject object, int numScramble) throws JSONException
353
    {
354
    JSONObject metadata = new JSONObject();
355

    
356
    metadata.put("longname"   , object.getObjectName() );
357
    metadata.put("inventor"   , object.getInventor());
358
    metadata.put("year"       , object.getYearOfInvention());
359
    metadata.put("complexity" , object.getComplexity());
360
    metadata.put("size"       , object.getSize() );
361
    metadata.put("scrambles"  , numScramble );
362
    metadata.put("shortname"  , object.getShortName() );
363
    metadata.put("resetmaps"  , object.shouldResetTextureMaps() );
364
    metadata.put("num_faces"  , object.getNumFaces() );
365
    metadata.put("signature"  , object.getSignature() );
366

    
367
    return metadata;
368
    }
369

    
370
///////////////////////////////////////////////////////////////////////////////////////////////////
371

    
372
  private JSONArray generateQuats(TwistyObject object) throws JSONException
373
    {
374
    JSONArray quatsArray = new JSONArray();
375
    Static4D[] quats = object.getQuats();
376

    
377
    for(Static4D quat : quats)
378
      {
379
      JSONObject q = new JSONObject();
380
      q.put("x",quat.get0());
381
      q.put("y",quat.get1());
382
      q.put("z",quat.get2());
383
      q.put("w",quat.get3());
384
      quatsArray.put(q);
385
      }
386

    
387
    return quatsArray;
388
    }
389

    
390
///////////////////////////////////////////////////////////////////////////////////////////////////
391

    
392
  private JSONArray generateAxis(TwistyObject object) throws JSONException
393
    {
394
    JSONArray axis = new JSONArray();
395

    
396
    Static3D[] rotAxis = object.getRotationAxis();
397
    int numAxis = rotAxis.length;
398
    int[][] basicAngle = object.getBasicAngles();
399
    int[] numLayers = object.getNumLayers();
400
    float[][] cuts = object.getCuts(numLayers);
401
    boolean[][] rotatable = object.getLayerRotatable(numLayers);
402

    
403
    for( int i=0; i<numAxis; i++ )
404
      {
405
      JSONObject axObject = new JSONObject();
406
      Static3D ax = rotAxis[i];
407

    
408
      axObject.put("x", ax.get0() );
409
      axObject.put("y", ax.get1() );
410
      axObject.put("z", ax.get2() );
411

    
412
      JSONArray angleArray = new JSONArray();
413
      for(float angle : basicAngle[i]) angleArray.put(angle);
414
      axObject.put("basicAngles", angleArray);
415
      JSONArray cutsArray = new JSONArray();
416
      if( cuts[i]!=null ) for(float cut : cuts[i]) cutsArray.put(cut);
417
      axObject.put("cuts", cutsArray);
418
      JSONArray rotaArray = new JSONArray();
419
      for(boolean rot : rotatable[i]) rotaArray.put(rot);
420
      axObject.put("rotatable", rotaArray );
421

    
422
      axis.put(axObject);
423
      }
424

    
425
    return axis;
426
    }
427

    
428
///////////////////////////////////////////////////////////////////////////////////////////////////
429

    
430
  private JSONObject generateScrambling(TwistyObject object) throws JSONException
431
    {
432
    JSONObject scrambling = new JSONObject();
433

    
434
    ScrambleState[] states = object.getScrambleStates();
435
    int scrambleType = object.getScrambleType();
436
    scrambling.put("scrambleType",scrambleType );
437

    
438
    if( states!=null )
439
      {
440
      JSONArray scrambleStates = new JSONArray();
441

    
442
      for(ScrambleState state : states)
443
        {
444
        JSONArray axisArray = new JSONArray();
445
        int numAxis = state.getNumAxis();
446

    
447
        for(int ax=0; ax<numAxis; ax++)
448
          {
449
          JSONArray axArray = new JSONArray();
450
          int[] axData = state.getAx(ax);
451

    
452
          if( axData!=null )
453
            for(int data : axData) axArray.put(data);
454

    
455
          axisArray.put(axArray);
456
          }
457

    
458
        scrambleStates.put(axisArray);
459
        }
460

    
461
      scrambling.put("scrambleStates", scrambleStates);
462
      }
463

    
464
    return scrambling;
465
    }
466

    
467
///////////////////////////////////////////////////////////////////////////////////////////////////
468

    
469
  private JSONObject generateTouchControl(TwistyObject object) throws JSONException
470
    {
471
    JSONObject touchControl = new JSONObject();
472

    
473
    touchControl.put("movementType" , object.getTouchControlType() );
474
    touchControl.put("movementSplit", object.getTouchControlSplit() );
475

    
476
    int[][][] enabled = object.getEnabled();
477

    
478
    if( enabled!=null )
479
      {
480
      JSONArray enabledArray = new JSONArray();
481

    
482
      for(int[][] faceEnabled : enabled)
483
        {
484
        JSONArray faceArray = new JSONArray();
485

    
486
        for(int[] sectionEnabled : faceEnabled)
487
          {
488
          JSONArray sectionArray = new JSONArray();
489
          for(int ax : sectionEnabled) sectionArray.put(ax);
490
          faceArray.put(sectionArray);
491
          }
492
        enabledArray.put(faceArray);
493
        }
494

    
495
      touchControl.put("enabledAxis", enabledArray);
496
      }
497

    
498
    int[] numLayers = object.getNumLayers();
499
    float[] dist3D = object.getDist3D(numLayers);
500

    
501
    if( dist3D!=null )
502
      {
503
      JSONArray distArray = new JSONArray();
504
      for( float dist: dist3D ) distArray.put(dist);
505
      touchControl.put("dist3D", distArray);
506
      }
507

    
508
    return touchControl;
509
    }
510

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

    
513
  private JSONArray generateColors(TwistyObject object)
514
    {
515
    JSONArray jsonColors = new JSONArray();
516
    int numFaceColors = object.getNumFaceColors();
517
    for(int i=0; i<numFaceColors; i++) jsonColors.put(object.getColor(i));
518

    
519
    jsonColors.put(object.getInternalColor());
520

    
521
    return jsonColors;
522
    }
523

    
524
///////////////////////////////////////////////////////////////////////////////////////////////////
525

    
526
  private JSONObject generateSolved(TwistyObject object) throws JSONException
527
    {
528
    JSONObject solved = new JSONObject();
529
    int[][] solvedGroups = object.getSolvedQuats();
530

    
531
    solved.put("functionIndex", object.getSolvedFunctionIndex() );
532

    
533
    if( solvedGroups!=null )
534
      {
535
      JSONArray groupArray = new JSONArray();
536

    
537
      for( int[] group : solvedGroups )
538
        {
539
        JSONArray groupElements = new JSONArray();
540
        for( int element : group ) groupElements.put(element);
541
        groupArray.put(groupElements);
542
        }
543

    
544
      solved.put("groups", groupArray );
545
      }
546

    
547
    return solved;
548
    }
549

    
550
///////////////////////////////////////////////////////////////////////////////////////////////////
551

    
552
  public String createObjectString(TwistyObject object,int numScramble) throws JSONException
553
    {
554
    JSONObject json = new JSONObject();
555

    
556
    JSONObject metadata    = generateMetadata(object,numScramble);
557
    JSONObject mesh        = generateMesh(object);
558
    JSONArray  axis        = generateAxis(object);
559
    JSONArray  quats       = generateQuats(object);
560
    JSONObject scrambling  = generateScrambling(object);
561
    JSONObject touchControl= generateTouchControl(object);
562
    JSONArray  colors      = generateColors(object);
563
    JSONObject solved      = generateSolved(object);
564

    
565
    json.put("major"       , VERSION_OBJECT_MAJOR);
566
    json.put("minor"       , VERSION_OBJECT_MINOR);
567
    json.put("metadata"    , metadata);
568
    json.put("mesh"        , mesh);
569
    json.put("axis"        , axis);
570
    json.put("quats"       , quats);
571
    json.put("scrambling"  , scrambling);
572
    json.put("touchcontrol", touchControl);
573
    json.put("colors"      , colors);
574
    json.put("solved"      , solved);
575

    
576
    return json.toString();
577
    }
578

    
579
///////////////////////////////////////////////////////////////////////////////////////////////////
580

    
581
  public String createExtrasString(TwistyObject object) throws JSONException
582
    {
583
    String[][] tuts = object.getTutorials();
584

    
585
    if( tuts!=null )
586
      {
587
      JSONObject json = new JSONObject();
588
      JSONArray  tutorials = new JSONArray();
589

    
590
      for(String[] tut : tuts)
591
        {
592
        String language = tut[0];
593
        String link     = tut[1];
594
        String title    = tut[2];
595
        String author   = tut[3];
596

    
597
        JSONObject oneTut = new JSONObject();
598

    
599
        oneTut.put("language", language);
600
        oneTut.put("link"    , link    );
601
        oneTut.put("title"   , title   );
602
        oneTut.put("author"  , author  );
603

    
604
        tutorials.put(oneTut);
605
        }
606

    
607
      json.put("major"     , VERSION_EXTRAS_MAJOR);
608
      json.put("minor"     , VERSION_EXTRAS_MINOR);
609
      json.put("object"    , object.getShortName() );
610
      json.put("tutorials" , tutorials);
611

    
612
      return json.toString();
613
      }
614

    
615
    return null;
616
    }
617

    
618
///////////////////////////////////////////////////////////////////////////////////////////////////
619

    
620
  public void write(String filename, String contents) throws IOException
621
    {
622
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8);
623
    BufferedWriter bw = new BufferedWriter(osw);
624
    bw.write(contents);
625
    bw.flush();
626
    }
627

    
628
///////////////////////////////////////////////////////////////////////////////////////////////////
629

    
630
  public static JsonWriter getInstance()
631
    {
632
    if( mThis==null ) mThis = new JsonWriter();
633
    return mThis;
634
    }
635
}
(2-2/2)