Project

General

Profile

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

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

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2021 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Magic Cube is proprietary software licensed under an EULA which you should have received      //
7
// along with the code. If not, check https://distorted.org/magic/License-Magic-Cube.html        //
8
///////////////////////////////////////////////////////////////////////////////////////////////////
9

    
10
package org.distorted.objectlib.json;
11

    
12
import java.io.BufferedWriter;
13
import java.io.FileOutputStream;
14
import java.io.IOException;
15
import java.io.OutputStreamWriter;
16
import java.nio.charset.StandardCharsets;
17

    
18
import org.distorted.objectlib.helpers.ObjectFaceShape;
19
import org.distorted.objectlib.helpers.ObjectStickerOverride;
20
import org.json.JSONArray;
21
import org.json.JSONException;
22
import org.json.JSONObject;
23

    
24
import org.distorted.library.type.Static3D;
25
import org.distorted.library.type.Static4D;
26

    
27
import org.distorted.objectlib.helpers.ObjectShape;
28
import org.distorted.objectlib.helpers.ObjectSticker;
29
import org.distorted.objectlib.scrambling.ScrambleState;
30
import org.distorted.objectlib.main.TwistyObject;
31

    
32
///////////////////////////////////////////////////////////////////////////////////////////////////
33

    
34
public class JsonWriter
35
{
36
  public static final int VERSION_OBJECT_MAJOR = 5;
37
  public static final int VERSION_OBJECT_MINOR = 0;
38
  public static final int VERSION_EXTRAS_MAJOR = 1;
39
  public static final int VERSION_EXTRAS_MINOR = 0;
40

    
41
  private static JsonWriter mThis;
42
  private static int mNumCubitFaces;
43

    
44
///////////////////////////////////////////////////////////////////////////////////////////////////
45

    
46
  private JsonWriter()
47
    {
48

    
49
    }
50

    
51
///////////////////////////////////////////////////////////////////////////////////////////////////
52

    
53
  private JSONArray generateCubits(TwistyObject object) throws JSONException
54
    {
55
    JSONArray array = new JSONArray();
56

    
57
    int[] numLayers     = object.getNumLayers();
58
    float[][] positions = object.getCubitPositions(numLayers);
59
    int numCubits       = positions.length;
60

    
61
    for(int c=0; c<numCubits; c++)
62
      {
63
      JSONObject cubit = new JSONObject();
64
      Static4D rotQuat = object.getCubitQuats(c,numLayers);
65
      int variant      = object.getCubitVariant(c,numLayers);
66
      int type         = object.getCubitType(c);
67
      float[] offset   = object.getCubitOffset(c);
68

    
69
      JSONArray pos = new JSONArray();
70
      int numPos = positions[c].length;
71
      for(int j=0; j<numPos; j++) pos.put(positions[c][j]);
72
      cubit.put("centers", pos);
73
      cubit.put("qx", rotQuat.get0() );
74
      cubit.put("qy", rotQuat.get1() );
75
      cubit.put("qz", rotQuat.get2() );
76
      cubit.put("qw", rotQuat.get3() );
77
      cubit.put("variant", variant );
78
      cubit.put("type", type);
79

    
80
      if( offset!=null )
81
        {
82
        cubit.put("offsetX", offset[0]);
83
        cubit.put("offsetY", offset[1]);
84
        cubit.put("offsetZ", offset[2]);
85
        }
86

    
87
      JSONArray colors = new JSONArray();
88

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

    
96
      array.put(cubit);
97
      }
98

    
99
    return array;
100
    }
101

    
102
///////////////////////////////////////////////////////////////////////////////////////////////////
103

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

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

    
116
    return array;
117
    }
118

    
119
///////////////////////////////////////////////////////////////////////////////////////////////////
120

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

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

    
134
    return array;
135
    }
136

    
137
///////////////////////////////////////////////////////////////////////////////////////////////////
138

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

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

    
156
    return array;
157
    }
158

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

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

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

    
172
      int sticker = object.getVariantFaceColor(variant,i);
173
      face.put("sticker", sticker);
174
      face.put("isOuter", faceOuter[i]);
175

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

    
181
      array.put(face);
182
      }
183

    
184
    return array;
185
    }
186

    
187
///////////////////////////////////////////////////////////////////////////////////////////////////
188

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

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

    
205
    return array;
206
    }
207

    
208
///////////////////////////////////////////////////////////////////////////////////////////////////
209

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

    
219
///////////////////////////////////////////////////////////////////////////////////////////////////
220

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

    
228
    return -1;
229
    }
230

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

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

    
237
    int[] numLayers = object.getNumLayers();
238
    int numVariants = object.getNumCubitVariants(numLayers);
239
    float[][] positions = object.getCubitPositions(numLayers);
240
    int[][] faceOuter   = object.getVariantFaceIsOuter();
241
    int numCubits = positions.length;
242
    mNumCubitFaces = 0;
243

    
244
    for(int i=0; i<numVariants; i++)
245
      {
246
      JSONObject shapeObj = new JSONObject();
247

    
248
      ObjectShape shape = object.getObjectShape(i);
249
      ObjectFaceShape face = object.getObjectFaceShape(i);
250

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

    
261
      int num = vertIndices.length;
262
      if( num>mNumCubitFaces ) mNumCubitFaces=num;
263

    
264
      int cubit = findCubitWithVariant(object,i,numCubits,numLayers);
265

    
266
      if( convexity!=null )
267
        {
268
        JSONObject convObj = generateConvexity(convexity);
269
        shapeObj.put("convexity", convObj);
270
        }
271

    
272
      JSONArray verticesArr = generateVertices(vertices,cornerIndices,centerIndices);
273
      shapeObj.put("vertices", verticesArr);
274
      JSONArray facesArr = generateFaces(object,vertIndices,bandIndices,faceOuter[i],cubit,numLayers);
275
      shapeObj.put("faces", facesArr);
276
      JSONArray bandsArr = generateBands(bands);
277
      shapeObj.put("bands", bandsArr);
278

    
279
      if( corners!=null )
280
        {
281
        JSONArray cornerArr = generateCorners(corners);
282
        shapeObj.put("cornerPush", cornerArr);
283
        }
284

    
285
      if( centers!=null )
286
        {
287
        JSONArray centerArr = generateCenters(centers);
288
        shapeObj.put("centerPush", centerArr);
289
        }
290

    
291
      shapes.put(shapeObj);
292
      }
293

    
294
    return shapes;
295
    }
296

    
297
///////////////////////////////////////////////////////////////////////////////////////////////////
298

    
299
  private JSONArray generateStickers(TwistyObject object) throws JSONException
300
    {
301
    JSONArray stickers = new JSONArray();
302

    
303
    int numStickers = object.getNumStickerTypes();
304

    
305
    for(int i=0; i<numStickers; i++)
306
      {
307
      JSONObject stickerObj = new JSONObject();
308
      JSONArray  vertexArray= new JSONArray();
309

    
310
      ObjectSticker sticker = object.retSticker(i);
311

    
312
      float[] coords     = sticker.getCoords();
313
      float[] curvatures = sticker.getCurvature();
314
      float[] radii      = sticker.getRadii();
315
      float   stroke     = sticker.getStroke();
316

    
317
      stickerObj.put("stroke", stroke);
318
      int numVertices = radii.length;
319

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

    
333
    return stickers;
334
    }
335

    
336
///////////////////////////////////////////////////////////////////////////////////////////////////
337

    
338
  private JSONArray generateOverrides(TwistyObject object) throws JSONException
339
    {
340
    ObjectStickerOverride[] overrides = object.getStickerOverrides();
341

    
342
    if( overrides!=null )
343
      {
344
      JSONArray overrideArray = new JSONArray();
345

    
346
      for (ObjectStickerOverride objectStickerOverride : overrides)
347
        {
348
        JSONObject override = new JSONObject();
349
        int[] cubfac = objectStickerOverride.getCubitFaces();
350
        int color    = objectStickerOverride.getColor();
351
        JSONArray cubfacArray = new JSONArray();
352
        for (int cf : cubfac) cubfacArray.put(cf);
353

    
354
        override.put("cubitfaces", cubfacArray);
355
        override.put("color", color);
356

    
357
        overrideArray.put(override);
358
        }
359

    
360
      return overrideArray;
361
      }
362

    
363
    return null;
364
    }
365

    
366
///////////////////////////////////////////////////////////////////////////////////////////////////
367

    
368
  private JSONObject generateMesh(TwistyObject object) throws JSONException
369
    {
370
    JSONObject mesh = new JSONObject();
371

    
372
    JSONArray shapes   = generateShapes(object);  // do this before cubits so we calculate numCubitFaces
373
    JSONArray cubits   = generateCubits(object);
374
    JSONArray stickers = generateStickers(object);
375

    
376
    mesh.put("shapes"  , shapes);
377
    mesh.put("cubits"  , cubits);
378
    mesh.put("stickers", stickers);
379
    mesh.put("pillow"  , object.getPillowCoeff() );
380

    
381
    JSONArray overrides = generateOverrides(object);
382
    if( overrides!=null ) mesh.put("overrides", overrides);
383

    
384
    return mesh;
385
    }
386

    
387
///////////////////////////////////////////////////////////////////////////////////////////////////
388

    
389
  private JSONObject generateMetadata(TwistyObject object, int numScramble, boolean isFree) throws JSONException
390
    {
391
    JSONObject metadata = new JSONObject();
392

    
393
    metadata.put("longname"   , object.getObjectName() );
394
    metadata.put("inventor"   , object.getInventor());
395
    metadata.put("year"       , object.getYearOfInvention());
396
    metadata.put("complexity" , object.getComplexity());
397
    metadata.put("size"       , object.getSize() );
398
    metadata.put("scrambles"  , numScramble );
399
    metadata.put("shortname"  , object.getShortName() );
400
    metadata.put("resetmaps"  , object.shouldResetTextureMaps() );
401
    metadata.put("num_faces"  , object.getNumFaces() );
402
    metadata.put("free"       , isFree );
403

    
404
    JSONArray sigArray = new JSONArray();
405
    long[] sig = object.getSignature().getArray();
406
    for (long l : sig) sigArray.put(l);
407
    metadata.put("signature" , sigArray );
408

    
409
    return metadata;
410
    }
411

    
412
///////////////////////////////////////////////////////////////////////////////////////////////////
413

    
414
  private JSONArray generateQuats(TwistyObject object) throws JSONException
415
    {
416
    JSONArray quatsArray = new JSONArray();
417
    Static4D[] quats = object.getQuats();
418

    
419
    for(Static4D quat : quats)
420
      {
421
      JSONObject q = new JSONObject();
422
      q.put("x",quat.get0());
423
      q.put("y",quat.get1());
424
      q.put("z",quat.get2());
425
      q.put("w",quat.get3());
426
      quatsArray.put(q);
427
      }
428

    
429
    return quatsArray;
430
    }
431

    
432
///////////////////////////////////////////////////////////////////////////////////////////////////
433

    
434
  private JSONArray generateAxis(TwistyObject object) throws JSONException
435
    {
436
    JSONArray axis = new JSONArray();
437

    
438
    Static3D[] rotAxis = object.getRotationAxis();
439
    int numAxis = rotAxis.length;
440
    int[][] basicAngle = object.getBasicAngles();
441
    int[] numLayers = object.getNumLayers();
442
    float[][] cuts = object.getCuts(numLayers);
443
    boolean[][] rotatable = object.getLayerRotatable(numLayers);
444

    
445
    for( int i=0; i<numAxis; i++ )
446
      {
447
      JSONObject axObject = new JSONObject();
448
      Static3D ax = rotAxis[i];
449

    
450
      axObject.put("x", ax.get0() );
451
      axObject.put("y", ax.get1() );
452
      axObject.put("z", ax.get2() );
453

    
454
      JSONArray angleArray = new JSONArray();
455
      for(float angle : basicAngle[i]) angleArray.put(angle);
456
      axObject.put("basicAngles", angleArray);
457
      JSONArray cutsArray = new JSONArray();
458
      if( cuts[i]!=null ) for(float cut : cuts[i]) cutsArray.put(cut);
459
      axObject.put("cuts", cutsArray);
460
      JSONArray rotaArray = new JSONArray();
461
      for(boolean rot : rotatable[i]) rotaArray.put(rot);
462
      axObject.put("rotatable", rotaArray );
463

    
464
      axis.put(axObject);
465
      }
466

    
467
    return axis;
468
    }
469

    
470
///////////////////////////////////////////////////////////////////////////////////////////////////
471

    
472
  private JSONObject generateScrambling(TwistyObject object) throws JSONException
473
    {
474
    JSONObject scrambling = new JSONObject();
475

    
476
    ScrambleState[] states = object.getScrambleStates();
477
    int scrambleType = object.getScrambleType();
478
    scrambling.put("scrambleType",scrambleType );
479

    
480
    if( states!=null )
481
      {
482
      JSONArray scrambleStates = new JSONArray();
483

    
484
      for(ScrambleState state : states)
485
        {
486
        JSONArray axisArray = new JSONArray();
487
        int numAxis = state.getNumAxis();
488

    
489
        for(int ax=0; ax<numAxis; ax++)
490
          {
491
          JSONArray axArray = new JSONArray();
492
          int[] axData = state.getAx(ax);
493

    
494
          if( axData!=null )
495
            for(int data : axData) axArray.put(data);
496

    
497
          axisArray.put(axArray);
498
          }
499

    
500
        scrambleStates.put(axisArray);
501
        }
502

    
503
      scrambling.put("scrambleStates", scrambleStates);
504
      }
505

    
506
    return scrambling;
507
    }
508

    
509
///////////////////////////////////////////////////////////////////////////////////////////////////
510

    
511
  private JSONObject generateTouchControl(TwistyObject object) throws JSONException
512
    {
513
    JSONObject touchControl = new JSONObject();
514

    
515
    touchControl.put("movementType" , object.getTouchControlType() );
516
    touchControl.put("movementSplit", object.getTouchControlSplit() );
517

    
518
    int[][][] enabled = object.getEnabled();
519

    
520
    if( enabled!=null )
521
      {
522
      JSONArray enabledArray = new JSONArray();
523

    
524
      for(int[][] faceEnabled : enabled)
525
        {
526
        JSONArray faceArray = new JSONArray();
527

    
528
        for(int[] sectionEnabled : faceEnabled)
529
          {
530
          JSONArray sectionArray = new JSONArray();
531
          for(int ax : sectionEnabled) sectionArray.put(ax);
532
          faceArray.put(sectionArray);
533
          }
534
        enabledArray.put(faceArray);
535
        }
536

    
537
      touchControl.put("enabledAxis", enabledArray);
538
      }
539

    
540
    int[] numLayers = object.getNumLayers();
541
    float[] dist3D = object.getDist3D(numLayers);
542

    
543
    if( dist3D!=null )
544
      {
545
      JSONArray distArray = new JSONArray();
546
      for( float dist: dist3D ) distArray.put(dist);
547
      touchControl.put("dist3D", distArray);
548
      }
549

    
550
    return touchControl;
551
    }
552

    
553
///////////////////////////////////////////////////////////////////////////////////////////////////
554

    
555
  private JSONArray generateColors(TwistyObject object)
556
    {
557
    JSONArray jsonColors = new JSONArray();
558
    int numFaceColors = object.getNumFaceColors();
559
    for(int i=0; i<numFaceColors; i++) jsonColors.put(object.getColor(i));
560

    
561
    jsonColors.put(object.getInternalColor());
562

    
563
    return jsonColors;
564
    }
565

    
566
///////////////////////////////////////////////////////////////////////////////////////////////////
567

    
568
  private JSONObject generateSolved(TwistyObject object) throws JSONException
569
    {
570
    JSONObject solved = new JSONObject();
571
    int[][] solvedGroups = object.getSolvedQuats();
572

    
573
    solved.put("functionIndex", object.getSolvedFunctionIndex() );
574

    
575
    if( solvedGroups!=null )
576
      {
577
      JSONArray groupArray = new JSONArray();
578

    
579
      for( int[] group : solvedGroups )
580
        {
581
        JSONArray groupElements = new JSONArray();
582
        for( int element : group ) groupElements.put(element);
583
        groupArray.put(groupElements);
584
        }
585

    
586
      solved.put("groups", groupArray );
587
      }
588

    
589
    return solved;
590
    }
591

    
592
///////////////////////////////////////////////////////////////////////////////////////////////////
593

    
594
  public String createObjectString(TwistyObject object,int numScramble, boolean isFree) throws JSONException
595
    {
596
    JSONObject json = new JSONObject();
597

    
598
    JSONObject metadata    = generateMetadata(object,numScramble,isFree);
599
    JSONObject mesh        = generateMesh(object);
600
    JSONArray  axis        = generateAxis(object);
601
    JSONArray  quats       = generateQuats(object);
602
    JSONObject scrambling  = generateScrambling(object);
603
    JSONObject touchControl= generateTouchControl(object);
604
    JSONArray  colors      = generateColors(object);
605
    JSONObject solved      = generateSolved(object);
606

    
607
    json.put("major"       , VERSION_OBJECT_MAJOR);
608
    json.put("minor"       , VERSION_OBJECT_MINOR);
609
    json.put("metadata"    , metadata);
610
    json.put("mesh"        , mesh);
611
    json.put("axis"        , axis);
612
    json.put("quats"       , quats);
613
    json.put("scrambling"  , scrambling);
614
    json.put("touchcontrol", touchControl);
615
    json.put("colors"      , colors);
616
    json.put("solved"      , solved);
617

    
618
    return json.toString();
619
    }
620

    
621
///////////////////////////////////////////////////////////////////////////////////////////////////
622

    
623
  public String createExtrasString(TwistyObject object) throws JSONException
624
    {
625
    String[][] tuts = object.getTutorials();
626

    
627
    if( tuts!=null )
628
      {
629
      JSONObject json = new JSONObject();
630
      JSONArray  tutorials = new JSONArray();
631

    
632
      for(String[] tut : tuts)
633
        {
634
        String language = tut[0];
635
        String link     = tut[1];
636
        String title    = tut[2];
637
        String author   = tut[3];
638

    
639
        JSONObject oneTut = new JSONObject();
640

    
641
        oneTut.put("language", language);
642
        oneTut.put("link"    , link    );
643
        oneTut.put("title"   , title   );
644
        oneTut.put("author"  , author  );
645

    
646
        tutorials.put(oneTut);
647
        }
648

    
649
      json.put("major"     , VERSION_EXTRAS_MAJOR);
650
      json.put("minor"     , VERSION_EXTRAS_MINOR);
651
      json.put("object"    , object.getShortName() );
652
      json.put("tutorials" , tutorials);
653

    
654
      return json.toString();
655
      }
656

    
657
    return null;
658
    }
659

    
660
///////////////////////////////////////////////////////////////////////////////////////////////////
661

    
662
  public void write(String filename, String contents) throws IOException
663
    {
664
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8);
665
    BufferedWriter bw = new BufferedWriter(osw);
666
    bw.write(contents);
667
    bw.flush();
668
    }
669

    
670
///////////////////////////////////////////////////////////////////////////////////////////////////
671

    
672
  public static JsonWriter getInstance()
673
    {
674
    if( mThis==null ) mThis = new JsonWriter();
675
    return mThis;
676
    }
677
}
(2-2/2)