Project

General

Profile

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

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

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
import org.distorted.objectlib.main.ObjectType;
41

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

    
44
public class JsonWriter
45
{
46
  public static final int VERSION_OBJECT_MAJOR = 1;
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

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

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

    
180
      array.put(face);
181
      }
182

    
183
    return array;
184
    }
185

    
186
///////////////////////////////////////////////////////////////////////////////////////////////////
187

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

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

    
204
    return array;
205
    }
206

    
207
///////////////////////////////////////////////////////////////////////////////////////////////////
208

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

    
218
///////////////////////////////////////////////////////////////////////////////////////////////////
219

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

    
227
    return -1;
228
    }
229

    
230
///////////////////////////////////////////////////////////////////////////////////////////////////
231

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

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

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

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

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

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

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

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

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

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

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

    
289
      shapes.put(shapeObj);
290
      }
291

    
292
    return shapes;
293
    }
294

    
295
///////////////////////////////////////////////////////////////////////////////////////////////////
296

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

    
301
    int numStickers = object.getNumStickerTypes();
302

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

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

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

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

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

    
331
    return stickers;
332
    }
333

    
334
///////////////////////////////////////////////////////////////////////////////////////////////////
335

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

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

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

    
348
    return mesh;
349
    }
350

    
351
///////////////////////////////////////////////////////////////////////////////////////////////////
352

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

    
357
    ObjectType type = ObjectType.getObject(ordinal);
358

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

    
370
    return metadata;
371
    }
372

    
373
///////////////////////////////////////////////////////////////////////////////////////////////////
374

    
375
  private JSONArray generateQuats(TwistyObject object) throws JSONException
376
    {
377
    JSONArray quatsArray = new JSONArray();
378
    Static4D[] quats = object.getQuats();
379

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

    
390
    return quatsArray;
391
    }
392

    
393
///////////////////////////////////////////////////////////////////////////////////////////////////
394

    
395
  private JSONArray generateAxis(TwistyObject object) throws JSONException
396
    {
397
    JSONArray axis = new JSONArray();
398

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

    
406
    for( int i=0; i<numAxis; i++ )
407
      {
408
      JSONObject axObject = new JSONObject();
409
      Static3D ax = rotAxis[i];
410

    
411
      axObject.put("x", ax.get0() );
412
      axObject.put("y", ax.get1() );
413
      axObject.put("z", ax.get2() );
414
      axObject.put("basicAngle", basicAngle[i] );
415

    
416
      JSONArray cutsArray = new JSONArray();
417
      for(float cut : cuts[i]) cutsArray.put(cut);
418
      axObject.put("cuts", cutsArray);
419
      JSONArray rotaArray = new JSONArray();
420
      for(boolean rot : rotatable[i]) rotaArray.put(rot);
421
      axObject.put("rotatable", rotaArray );
422

    
423
      axis.put(axObject);
424
      }
425

    
426
    return axis;
427
    }
428

    
429
///////////////////////////////////////////////////////////////////////////////////////////////////
430

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

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

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

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

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

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

    
456
          axisArray.put(axArray);
457
          }
458

    
459
        scrambleStates.put(axisArray);
460
        }
461

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

    
465
    return scrambling;
466
    }
467

    
468
///////////////////////////////////////////////////////////////////////////////////////////////////
469

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

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

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

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

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

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

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

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

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

    
509
    return touchControl;
510
    }
511

    
512
///////////////////////////////////////////////////////////////////////////////////////////////////
513

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

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

    
522
    return jsonColors;
523
    }
524

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

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

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

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

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

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

    
548
    return solved;
549
    }
550

    
551
///////////////////////////////////////////////////////////////////////////////////////////////////
552

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

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

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

    
577
    return json.toString();
578
    }
579

    
580
///////////////////////////////////////////////////////////////////////////////////////////////////
581

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

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

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

    
598
        JSONObject oneTut = new JSONObject();
599

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

    
605
        tutorials.put(oneTut);
606
        }
607

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

    
613
      return json.toString();
614
      }
615

    
616
    return null;
617
    }
618

    
619
///////////////////////////////////////////////////////////////////////////////////////////////////
620

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

    
629
///////////////////////////////////////////////////////////////////////////////////////////////////
630

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