Project

General

Profile

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

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

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.distorted.objectlib.helpers.ObjectSignature;
30
import org.json.JSONArray;
31
import org.json.JSONException;
32
import org.json.JSONObject;
33

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

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

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

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

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

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

    
56
  private JsonWriter()
57
    {
58

    
59
    }
60

    
61
///////////////////////////////////////////////////////////////////////////////////////////////////
62

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

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

    
71
    for(int c=0; c<numCubits; c++)
72
      {
73
      JSONObject cubit = new JSONObject();
74
      Static4D rotQuat = object.getCubitQuats(c,numLayers);
75
      int variant      = object.getCubitVariant(c,numLayers);
76
      int type         = object.getCubitType(c);
77
      float[] offset   = object.getCubitOffset(c);
78

    
79
      JSONArray pos = new JSONArray();
80
      int numPos = positions[c].length;
81
      for(int j=0; j<numPos; j++) pos.put(positions[c][j]);
82
      cubit.put("centers", pos);
83
      cubit.put("qx", rotQuat.get0() );
84
      cubit.put("qy", rotQuat.get1() );
85
      cubit.put("qz", rotQuat.get2() );
86
      cubit.put("qw", rotQuat.get3() );
87
      cubit.put("variant", variant );
88
      cubit.put("type", type);
89
      cubit.put("offsetX", offset[0]);
90
      cubit.put("offsetY", offset[1]);
91
      cubit.put("offsetZ", offset[2]);
92

    
93
      JSONArray colors = new JSONArray();
94

    
95
      for(int f=0; f<mNumCubitFaces; f++)
96
        {
97
        int cubColor = object.getCubitFaceMap(c,f);
98
        colors.put(cubColor);
99
        }
100
      cubit.put("colors",colors);
101

    
102
      array.put(cubit);
103
      }
104

    
105
    return array;
106
    }
107

    
108
///////////////////////////////////////////////////////////////////////////////////////////////////
109

    
110
  private JSONArray generateCorners(float[][] corners) throws JSONException
111
    {
112
    JSONArray array = new JSONArray();
113

    
114
    for(float[] c : corners)
115
      {
116
      JSONObject corner = new JSONObject();
117
      corner.put("strength", c[0]);
118
      corner.put("radius"  , c[1]);
119
      array.put(corner);
120
      }
121

    
122
    return array;
123
    }
124

    
125
///////////////////////////////////////////////////////////////////////////////////////////////////
126

    
127
  private JSONArray generateCenters(float[][] centers) throws JSONException
128
    {
129
    JSONArray array = new JSONArray();
130

    
131
    for(float[] c : centers)
132
      {
133
      JSONObject center = new JSONObject();
134
      center.put("x", c[0]);
135
      center.put("y", c[1]);
136
      center.put("z", c[2]);
137
      array.put(center);
138
      }
139

    
140
    return array;
141
    }
142

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

    
145
  private JSONArray generateBands(float[][] bands) throws JSONException
146
    {
147
    JSONArray array = new JSONArray();
148

    
149
    for (float[] b : bands)
150
      {
151
      JSONObject band = new JSONObject();
152
      band.put("height"          , b[0]);
153
      band.put("angle"           , b[1]);
154
      band.put("distanceToCenter", b[2]);
155
      band.put("distanceToFlat"  , b[3]);
156
      band.put("numOfBands"      , b[4]);
157
      band.put("extraI"          , b[5]);
158
      band.put("extraJ"          , b[6]);
159
      array.put(band);
160
      }
161

    
162
    return array;
163
    }
164

    
165
///////////////////////////////////////////////////////////////////////////////////////////////////
166

    
167
  private JSONArray generateFaces(TwistyObject object, int[][] vertIndices, int[] bandIndices, int[] faceOuter, int cubit, int[] numLayers) throws JSONException
168
    {
169
    JSONArray array = new JSONArray();
170
    int numFaces = vertIndices.length;
171
    int variant = object.getCubitVariant(cubit,numLayers);
172

    
173
    for(int i=0; i<numFaces; i++)
174
      {
175
      JSONObject face = new JSONObject();
176
      face.put("bandIndex", bandIndices[i]);
177

    
178
      int sticker = object.getVariantFaceColor(variant,i);
179
      face.put("sticker", sticker);
180
      face.put("isOuter", faceOuter[i]);
181

    
182
      JSONArray vertArr = new JSONArray();
183
      int numV = vertIndices[i].length;
184
      for(int j=0; j<numV; j++) vertArr.put(vertIndices[i][j]);
185
      face.put("vertexIndices",vertArr);
186

    
187
      array.put(face);
188
      }
189

    
190
    return array;
191
    }
192

    
193
///////////////////////////////////////////////////////////////////////////////////////////////////
194

    
195
  private JSONArray generateVertices(float[][] vertices, int[] cornerIndices, int[] centerIndices) throws JSONException
196
    {
197
    JSONArray array = new JSONArray();
198
    int numVertices = vertices.length;
199

    
200
    for(int j=0; j<numVertices; j++)
201
      {
202
      JSONObject vert = new JSONObject();
203
      vert.put("x", vertices[j][0]);
204
      vert.put("y", vertices[j][1]);
205
      vert.put("z", vertices[j][2]);
206
      vert.put("cornerIndex", cornerIndices[j]);
207
      vert.put("centerIndex", centerIndices[j]);
208
      array.put(vert);
209
      }
210

    
211
    return array;
212
    }
213

    
214
///////////////////////////////////////////////////////////////////////////////////////////////////
215

    
216
  private JSONObject generateConvexity(float[] convexity) throws JSONException
217
    {
218
    JSONObject object = new JSONObject();
219
    object.put("x", convexity[0]);
220
    object.put("y", convexity[1]);
221
    object.put("z", convexity[2]);
222
    return object;
223
    }
224

    
225
///////////////////////////////////////////////////////////////////////////////////////////////////
226

    
227
  private int findCubitWithVariant(TwistyObject object, int variant, int numCubits, int[] numLayers)
228
    {
229
    for(int i=0; i<numCubits; i++)
230
      {
231
      if( object.getCubitVariant(i,numLayers)==variant ) return i;
232
      }
233

    
234
    return -1;
235
    }
236

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

    
239
  private JSONArray generateShapes(TwistyObject object) throws JSONException
240
    {
241
    JSONArray shapes = new JSONArray();
242

    
243
    int[] numLayers = object.getNumLayers();
244
    int numVariants = object.getNumCubitVariants(numLayers);
245
    float[][] positions = object.getCubitPositions(numLayers);
246
    int[][] faceOuter   = object.getVariantFaceIsOuter();
247
    int numCubits = positions.length;
248
    mNumCubitFaces = 0;
249

    
250
    for(int i=0; i<numVariants; i++)
251
      {
252
      JSONObject shapeObj = new JSONObject();
253

    
254
      ObjectShape shape = object.getObjectShape(i);
255
      ObjectFaceShape face = object.getObjectFaceShape(i);
256

    
257
      float[] convexity  = face.getConvexityCenter();
258
      float[][] vertices = shape.getVertices();
259
      int[][] vertIndices= shape.getVertIndices();
260
      float[][] bands    = face.getBands();
261
      int[] bandIndices  = face.getBandIndices();
262
      float[][] corners  = face.getCorners();
263
      int[] cornerIndices= face.getCornerIndices();
264
      float[][] centers  = face.getCenters();
265
      int[] centerIndices= face.getCenterIndices();
266

    
267
      int num = vertIndices.length;
268
      if( num>mNumCubitFaces ) mNumCubitFaces=num;
269

    
270
      int cubit = findCubitWithVariant(object,i,numCubits,numLayers);
271

    
272
      if( convexity!=null )
273
        {
274
        JSONObject convObj = generateConvexity(convexity);
275
        shapeObj.put("convexity", convObj);
276
        }
277

    
278
      JSONArray verticesArr = generateVertices(vertices,cornerIndices,centerIndices);
279
      shapeObj.put("vertices", verticesArr);
280
      JSONArray facesArr = generateFaces(object,vertIndices,bandIndices,faceOuter[i],cubit,numLayers);
281
      shapeObj.put("faces", facesArr);
282
      JSONArray bandsArr = generateBands(bands);
283
      shapeObj.put("bands", bandsArr);
284

    
285
      if( corners!=null )
286
        {
287
        JSONArray cornerArr = generateCorners(corners);
288
        shapeObj.put("cornerPush", cornerArr);
289
        }
290

    
291
      if( centers!=null )
292
        {
293
        JSONArray centerArr = generateCenters(centers);
294
        shapeObj.put("centerPush", centerArr);
295
        }
296

    
297
      shapes.put(shapeObj);
298
      }
299

    
300
    return shapes;
301
    }
302

    
303
///////////////////////////////////////////////////////////////////////////////////////////////////
304

    
305
  private JSONArray generateStickers(TwistyObject object) throws JSONException
306
    {
307
    JSONArray stickers = new JSONArray();
308

    
309
    int numStickers = object.getNumStickerTypes();
310

    
311
    for(int i=0; i<numStickers; i++)
312
      {
313
      JSONObject stickerObj = new JSONObject();
314
      JSONArray  vertexArray= new JSONArray();
315

    
316
      ObjectSticker sticker = object.retSticker(i);
317

    
318
      float[] coords     = sticker.getCoords();
319
      float[] curvatures = sticker.getCurvature();
320
      float[] radii      = sticker.getRadii();
321
      float   stroke     = sticker.getStroke();
322

    
323
      stickerObj.put("stroke", stroke);
324
      int numVertices = radii.length;
325

    
326
      for(int j=0; j<numVertices; j++)
327
        {
328
        JSONObject vertex = new JSONObject();
329
        vertex.put("x", coords[2*j  ]);
330
        vertex.put("y", coords[2*j+1]);
331
        vertex.put("angle", curvatures==null ? 0 : curvatures[j]);
332
        vertex.put("radius",radii[j]);
333
        vertexArray.put(vertex);
334
        }
335
      stickerObj.put("vertices", vertexArray);
336
      stickers.put(stickerObj);
337
      }
338

    
339
    return stickers;
340
    }
341

    
342
///////////////////////////////////////////////////////////////////////////////////////////////////
343

    
344
  private JSONObject generateMesh(TwistyObject object) throws JSONException
345
    {
346
    JSONObject mesh = new JSONObject();
347

    
348
    JSONArray shapes   = generateShapes(object);  // do this before cubits so we calculate numCubitFaces
349
    JSONArray cubits   = generateCubits(object);
350
    JSONArray stickers = generateStickers(object);
351

    
352
    mesh.put("shapes"  , shapes);
353
    mesh.put("cubits"  , cubits);
354
    mesh.put("stickers", stickers);
355

    
356
    return mesh;
357
    }
358

    
359
///////////////////////////////////////////////////////////////////////////////////////////////////
360

    
361
  private JSONObject generateMetadata(TwistyObject object, int numScramble) throws JSONException
362
    {
363
    JSONObject metadata = new JSONObject();
364

    
365
    metadata.put("longname"   , object.getObjectName() );
366
    metadata.put("inventor"   , object.getInventor());
367
    metadata.put("year"       , object.getYearOfInvention());
368
    metadata.put("complexity" , object.getComplexity());
369
    metadata.put("size"       , object.getSize() );
370
    metadata.put("scrambles"  , numScramble );
371
    metadata.put("shortname"  , object.getShortName() );
372
    metadata.put("resetmaps"  , object.shouldResetTextureMaps() );
373
    metadata.put("num_faces"  , object.getNumFaces() );
374

    
375
    ObjectSignature signature = object.getSignature();
376

    
377
    metadata.put("signature1" , signature.getLong1() );
378
    metadata.put("signature2" , signature.getLong2() );
379
    metadata.put("signature3" , signature.getLong3() );
380

    
381
    return metadata;
382
    }
383

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

    
386
  private JSONArray generateQuats(TwistyObject object) throws JSONException
387
    {
388
    JSONArray quatsArray = new JSONArray();
389
    Static4D[] quats = object.getQuats();
390

    
391
    for(Static4D quat : quats)
392
      {
393
      JSONObject q = new JSONObject();
394
      q.put("x",quat.get0());
395
      q.put("y",quat.get1());
396
      q.put("z",quat.get2());
397
      q.put("w",quat.get3());
398
      quatsArray.put(q);
399
      }
400

    
401
    return quatsArray;
402
    }
403

    
404
///////////////////////////////////////////////////////////////////////////////////////////////////
405

    
406
  private JSONArray generateAxis(TwistyObject object) throws JSONException
407
    {
408
    JSONArray axis = new JSONArray();
409

    
410
    Static3D[] rotAxis = object.getRotationAxis();
411
    int numAxis = rotAxis.length;
412
    int[][] basicAngle = object.getBasicAngles();
413
    int[] numLayers = object.getNumLayers();
414
    float[][] cuts = object.getCuts(numLayers);
415
    boolean[][] rotatable = object.getLayerRotatable(numLayers);
416

    
417
    for( int i=0; i<numAxis; i++ )
418
      {
419
      JSONObject axObject = new JSONObject();
420
      Static3D ax = rotAxis[i];
421

    
422
      axObject.put("x", ax.get0() );
423
      axObject.put("y", ax.get1() );
424
      axObject.put("z", ax.get2() );
425

    
426
      JSONArray angleArray = new JSONArray();
427
      for(float angle : basicAngle[i]) angleArray.put(angle);
428
      axObject.put("basicAngles", angleArray);
429
      JSONArray cutsArray = new JSONArray();
430
      if( cuts[i]!=null ) for(float cut : cuts[i]) cutsArray.put(cut);
431
      axObject.put("cuts", cutsArray);
432
      JSONArray rotaArray = new JSONArray();
433
      for(boolean rot : rotatable[i]) rotaArray.put(rot);
434
      axObject.put("rotatable", rotaArray );
435

    
436
      axis.put(axObject);
437
      }
438

    
439
    return axis;
440
    }
441

    
442
///////////////////////////////////////////////////////////////////////////////////////////////////
443

    
444
  private JSONObject generateScrambling(TwistyObject object) throws JSONException
445
    {
446
    JSONObject scrambling = new JSONObject();
447

    
448
    ScrambleState[] states = object.getScrambleStates();
449
    int scrambleType = object.getScrambleType();
450
    scrambling.put("scrambleType",scrambleType );
451

    
452
    if( states!=null )
453
      {
454
      JSONArray scrambleStates = new JSONArray();
455

    
456
      for(ScrambleState state : states)
457
        {
458
        JSONArray axisArray = new JSONArray();
459
        int numAxis = state.getNumAxis();
460

    
461
        for(int ax=0; ax<numAxis; ax++)
462
          {
463
          JSONArray axArray = new JSONArray();
464
          int[] axData = state.getAx(ax);
465

    
466
          if( axData!=null )
467
            for(int data : axData) axArray.put(data);
468

    
469
          axisArray.put(axArray);
470
          }
471

    
472
        scrambleStates.put(axisArray);
473
        }
474

    
475
      scrambling.put("scrambleStates", scrambleStates);
476
      }
477

    
478
    return scrambling;
479
    }
480

    
481
///////////////////////////////////////////////////////////////////////////////////////////////////
482

    
483
  private JSONObject generateTouchControl(TwistyObject object) throws JSONException
484
    {
485
    JSONObject touchControl = new JSONObject();
486

    
487
    touchControl.put("movementType" , object.getTouchControlType() );
488
    touchControl.put("movementSplit", object.getTouchControlSplit() );
489

    
490
    int[][][] enabled = object.getEnabled();
491

    
492
    if( enabled!=null )
493
      {
494
      JSONArray enabledArray = new JSONArray();
495

    
496
      for(int[][] faceEnabled : enabled)
497
        {
498
        JSONArray faceArray = new JSONArray();
499

    
500
        for(int[] sectionEnabled : faceEnabled)
501
          {
502
          JSONArray sectionArray = new JSONArray();
503
          for(int ax : sectionEnabled) sectionArray.put(ax);
504
          faceArray.put(sectionArray);
505
          }
506
        enabledArray.put(faceArray);
507
        }
508

    
509
      touchControl.put("enabledAxis", enabledArray);
510
      }
511

    
512
    int[] numLayers = object.getNumLayers();
513
    float[] dist3D = object.getDist3D(numLayers);
514

    
515
    if( dist3D!=null )
516
      {
517
      JSONArray distArray = new JSONArray();
518
      for( float dist: dist3D ) distArray.put(dist);
519
      touchControl.put("dist3D", distArray);
520
      }
521

    
522
    return touchControl;
523
    }
524

    
525
///////////////////////////////////////////////////////////////////////////////////////////////////
526

    
527
  private JSONArray generateColors(TwistyObject object)
528
    {
529
    JSONArray jsonColors = new JSONArray();
530
    int numFaceColors = object.getNumFaceColors();
531
    for(int i=0; i<numFaceColors; i++) jsonColors.put(object.getColor(i));
532

    
533
    jsonColors.put(object.getInternalColor());
534

    
535
    return jsonColors;
536
    }
537

    
538
///////////////////////////////////////////////////////////////////////////////////////////////////
539

    
540
  private JSONObject generateSolved(TwistyObject object) throws JSONException
541
    {
542
    JSONObject solved = new JSONObject();
543
    int[][] solvedGroups = object.getSolvedQuats();
544

    
545
    solved.put("functionIndex", object.getSolvedFunctionIndex() );
546

    
547
    if( solvedGroups!=null )
548
      {
549
      JSONArray groupArray = new JSONArray();
550

    
551
      for( int[] group : solvedGroups )
552
        {
553
        JSONArray groupElements = new JSONArray();
554
        for( int element : group ) groupElements.put(element);
555
        groupArray.put(groupElements);
556
        }
557

    
558
      solved.put("groups", groupArray );
559
      }
560

    
561
    return solved;
562
    }
563

    
564
///////////////////////////////////////////////////////////////////////////////////////////////////
565

    
566
  public String createObjectString(TwistyObject object,int numScramble) throws JSONException
567
    {
568
    JSONObject json = new JSONObject();
569

    
570
    JSONObject metadata    = generateMetadata(object,numScramble);
571
    JSONObject mesh        = generateMesh(object);
572
    JSONArray  axis        = generateAxis(object);
573
    JSONArray  quats       = generateQuats(object);
574
    JSONObject scrambling  = generateScrambling(object);
575
    JSONObject touchControl= generateTouchControl(object);
576
    JSONArray  colors      = generateColors(object);
577
    JSONObject solved      = generateSolved(object);
578

    
579
    json.put("major"       , VERSION_OBJECT_MAJOR);
580
    json.put("minor"       , VERSION_OBJECT_MINOR);
581
    json.put("metadata"    , metadata);
582
    json.put("mesh"        , mesh);
583
    json.put("axis"        , axis);
584
    json.put("quats"       , quats);
585
    json.put("scrambling"  , scrambling);
586
    json.put("touchcontrol", touchControl);
587
    json.put("colors"      , colors);
588
    json.put("solved"      , solved);
589

    
590
    return json.toString();
591
    }
592

    
593
///////////////////////////////////////////////////////////////////////////////////////////////////
594

    
595
  public String createExtrasString(TwistyObject object) throws JSONException
596
    {
597
    String[][] tuts = object.getTutorials();
598

    
599
    if( tuts!=null )
600
      {
601
      JSONObject json = new JSONObject();
602
      JSONArray  tutorials = new JSONArray();
603

    
604
      for(String[] tut : tuts)
605
        {
606
        String language = tut[0];
607
        String link     = tut[1];
608
        String title    = tut[2];
609
        String author   = tut[3];
610

    
611
        JSONObject oneTut = new JSONObject();
612

    
613
        oneTut.put("language", language);
614
        oneTut.put("link"    , link    );
615
        oneTut.put("title"   , title   );
616
        oneTut.put("author"  , author  );
617

    
618
        tutorials.put(oneTut);
619
        }
620

    
621
      json.put("major"     , VERSION_EXTRAS_MAJOR);
622
      json.put("minor"     , VERSION_EXTRAS_MINOR);
623
      json.put("object"    , object.getShortName() );
624
      json.put("tutorials" , tutorials);
625

    
626
      return json.toString();
627
      }
628

    
629
    return null;
630
    }
631

    
632
///////////////////////////////////////////////////////////////////////////////////////////////////
633

    
634
  public void write(String filename, String contents) throws IOException
635
    {
636
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8);
637
    BufferedWriter bw = new BufferedWriter(osw);
638
    bw.write(contents);
639
    bw.flush();
640
    }
641

    
642
///////////////////////////////////////////////////////////////////////////////////////////////////
643

    
644
  public static JsonWriter getInstance()
645
    {
646
    if( mThis==null ) mThis = new JsonWriter();
647
    return mThis;
648
    }
649
}
(2-2/2)