Project

General

Profile

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

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

1 e26eb4e7 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 82eb152a Leszek Koltunski
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.json.JSONArray;
29
import org.json.JSONException;
30
import org.json.JSONObject;
31
32 e26eb4e7 Leszek Koltunski
import org.distorted.library.type.Static3D;
33
import org.distorted.library.type.Static4D;
34 82eb152a Leszek Koltunski
35 e26eb4e7 Leszek Koltunski
import org.distorted.objectlib.helpers.ObjectShape;
36
import org.distorted.objectlib.helpers.ObjectSticker;
37
import org.distorted.objectlib.helpers.ScrambleState;
38
import org.distorted.objectlib.main.TwistyObject;
39
40
///////////////////////////////////////////////////////////////////////////////////////////////////
41
42
public class JsonWriter
43
{
44
  private static final int VERSION_MAJOR = 1;
45
  private static final int VERSION_MINOR = 0;
46
47
  private static JsonWriter mThis;
48
49
///////////////////////////////////////////////////////////////////////////////////////////////////
50
51
  private JsonWriter()
52
    {
53
54
    }
55
56
///////////////////////////////////////////////////////////////////////////////////////////////////
57
58
  private JSONArray generateCubits(TwistyObject object) throws JSONException
59
    {
60
    JSONArray array = new JSONArray();
61
62
    int[] numLayers     = object.getNumLayers();
63
    float[][] positions = object.getCubitPositions(numLayers);
64
    int numCubits = positions.length;
65
    int numFaces = object.getNumCubitFaces();
66
67
    for(int i=0; i<numCubits; i++)
68
      {
69
      JSONObject cubit = new JSONObject();
70
      Static4D rotQuat  = object.getQuat(i,numLayers);
71
      int variant       = object.getCubitVariant(i,numLayers);
72
      int[] solvedQuats = object.getSolvedQuats(i,numLayers);
73
74
      JSONArray pos = new JSONArray();
75
      int numPos = positions[i].length;
76
      for(int j=0; j<numPos; j++) pos.put(positions[i][j]);
77
      cubit.put("centers", pos);
78
      cubit.put("qx", rotQuat.get0() );
79
      cubit.put("qy", rotQuat.get1() );
80
      cubit.put("qz", rotQuat.get2() );
81
      cubit.put("qw", rotQuat.get3() );
82
      cubit.put("variant", variant );
83
84
      if( solvedQuats!=null )
85
        {
86
        JSONArray solved = new JSONArray();
87
        for (int solvedQuat : solvedQuats) solved.put(solvedQuat);
88
        cubit.put("solvedQuats",solved);
89
        }
90
91
      JSONArray colors = new JSONArray();
92
93
      for(int j=0; j<numFaces; j++)
94
        {
95
        int cubColor = object.getCubitFaceColor(i,j,numLayers);
96
        colors.put(cubColor);
97
        }
98
      cubit.put("colors",colors);
99
100
      array.put(cubit);
101
      }
102
103
    return array;
104
    }
105
106
///////////////////////////////////////////////////////////////////////////////////////////////////
107
108
  private JSONArray generateCorners(float[][] corners) throws JSONException
109
    {
110
    JSONArray array = new JSONArray();
111
112
    for(float[] c : corners)
113
      {
114
      JSONObject corner = new JSONObject();
115
      corner.put("strength", c[0]);
116
      corner.put("radius"  , c[1]);
117
      array.put(corner);
118
      }
119
120
    return array;
121
    }
122
123
///////////////////////////////////////////////////////////////////////////////////////////////////
124
125
  private JSONArray generateCenters(float[][] centers) throws JSONException
126
    {
127
    JSONArray array = new JSONArray();
128
129
    for(float[] c : centers)
130
      {
131
      JSONObject center = new JSONObject();
132
      center.put("x", c[0]);
133
      center.put("y", c[1]);
134
      center.put("z", c[2]);
135
      array.put(center);
136
      }
137
138
    return array;
139
    }
140
141
///////////////////////////////////////////////////////////////////////////////////////////////////
142
143
  private JSONArray generateBands(float[][] bands) throws JSONException
144
    {
145
    JSONArray array = new JSONArray();
146
147
    for (float[] b : bands)
148
      {
149
      JSONObject band = new JSONObject();
150
      band.put("height"          , b[0]);
151
      band.put("angle"           , b[1]);
152
      band.put("distanceToCenter", b[2]);
153
      band.put("distanceToFlat"  , b[3]);
154
      band.put("numOfBands"      , b[4]);
155
      band.put("extraI"          , b[5]);
156
      band.put("extraJ"          , b[6]);
157
      array.put(band);
158
      }
159
160
    return array;
161
    }
162
163
///////////////////////////////////////////////////////////////////////////////////////////////////
164
165
  private JSONArray generateFaces(TwistyObject object, int[][] vertIndices, int[] bandIndices, int cubit, int[] numLayers) throws JSONException
166
    {
167
    JSONArray array = new JSONArray();
168
    int numFaces = vertIndices.length;
169
    int variant = object.getCubitVariant(cubit,numLayers);
170
171
    for(int i=0; i<numFaces; i++)
172
      {
173
      JSONObject face = new JSONObject();
174
      face.put("bandIndex", bandIndices[i]);
175
176
      int sticker = object.getVariantFaceColor(variant,i,numLayers);
177
      face.put("sticker",sticker);
178
179
      JSONArray vertArr = new JSONArray();
180
      int numV = vertIndices[i].length;
181
      for(int j=0; j<numV; j++) vertArr.put(vertIndices[i][j]);
182
      face.put("vertexIndices",vertArr);
183
184
      array.put(face);
185
      }
186
187
    return array;
188
    }
189
190
///////////////////////////////////////////////////////////////////////////////////////////////////
191
192
  private JSONArray generateVertices(double[][] vertices, int[] cornerIndices, int[] centerIndices) throws JSONException
193
    {
194
    JSONArray array = new JSONArray();
195
    int numVertices = vertices.length;
196
197
    for(int j=0; j<numVertices; j++)
198
      {
199
      JSONObject vert = new JSONObject();
200
      vert.put("x", vertices[j][0]);
201
      vert.put("y", vertices[j][1]);
202
      vert.put("z", vertices[j][2]);
203
      vert.put("cornerIndex", cornerIndices[j]);
204
      vert.put("centerIndex", centerIndices[j]);
205
      array.put(vert);
206
      }
207
208
    return array;
209
    }
210
211
///////////////////////////////////////////////////////////////////////////////////////////////////
212
213
  private JSONObject generateConvexity(float[] convexity) throws JSONException
214
    {
215
    JSONObject object = new JSONObject();
216
    object.put("x", convexity[0]);
217
    object.put("y", convexity[1]);
218
    object.put("z", convexity[2]);
219
    return object;
220
    }
221
222
///////////////////////////////////////////////////////////////////////////////////////////////////
223
224
  private int findCubitWithVariant(TwistyObject object, int variant, int numCubits, int[] numLayers)
225
    {
226
    for(int i=0; i<numCubits; i++)
227
      {
228
      if( object.getCubitVariant(i,numLayers)==variant ) return i;
229
      }
230
231
    return -1;
232
    }
233
234
///////////////////////////////////////////////////////////////////////////////////////////////////
235
236
  private JSONArray generateShapes(TwistyObject object) throws JSONException
237
    {
238
    JSONArray shapes = new JSONArray();
239
240
    int[] numLayers = object.getNumLayers();
241
    int numVariants = object.getNumCubitVariants(numLayers);
242
    float[][] positions = object.getCubitPositions(numLayers);
243
    int numCubits = positions.length;
244
245
    for(int i=0; i<numVariants; i++)
246
      {
247
      JSONObject shapeObj = new JSONObject();
248
249
      ObjectShape shape = object.getObjectShape(i);
250
251
      float[] convexity  = shape.getConvexityCenter();
252
      double[][] vertices= shape.getVertices();
253
      int[][] vertIndices= shape.getVertIndices();
254
      float[][] bands    = shape.getBands();
255
      int[] bandIndices  = shape.getBandIndices();
256
      float[][] corners  = shape.getCorners();
257
      int[] cornerIndices= shape.getCornerIndices();
258
      float[][] centers  = shape.getCenters();
259
      int[] centerIndices= shape.getCenterIndices();
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 9e8eb9e4 Leszek Koltunski
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 e26eb4e7 Leszek Koltunski
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[] numLayers = object.getNumLayers();
301
    int numStickers = object.getNumStickerTypes(numLayers);
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 cubits   = generateCubits(object);
341
    JSONArray shapes   = generateShapes(object);
342
    JSONArray stickers = generateStickers(object);
343
344
    mesh.put("cubits"  , cubits);
345
    mesh.put("shapes"  , shapes);
346
    mesh.put("stickers", stickers);
347
348
    return mesh;
349
    }
350
351
///////////////////////////////////////////////////////////////////////////////////////////////////
352
353
  private JSONObject generateMetadata(TwistyObject object) throws JSONException
354
    {
355
    JSONObject metadata = new JSONObject();
356
357 de4a7e02 Leszek Koltunski
    metadata.put("longname"   , object.getObjectName() );
358
    metadata.put("inventor"   , object.getInventor());
359
    metadata.put("year"       , object.getYearOfInvention());
360
    metadata.put("complexity" , object.getComplexity());
361
    metadata.put("size"       , object.getSize() );
362
    metadata.put("solved_func", object.getSolvedFunctionIndex() );
363 e26eb4e7 Leszek Koltunski
364
    return metadata;
365
    }
366
367
///////////////////////////////////////////////////////////////////////////////////////////////////
368
369
  private JSONArray generateQuats(TwistyObject object) throws JSONException
370
    {
371
    JSONArray quatsArray = new JSONArray();
372
    Static4D[] quats = object.getQuats();
373
374
    for(Static4D quat : quats)
375
      {
376
      JSONObject q = new JSONObject();
377
      q.put("x",quat.get0());
378
      q.put("y",quat.get1());
379
      q.put("z",quat.get2());
380
      q.put("w",quat.get3());
381
      quatsArray.put(q);
382
      }
383
384
    return quatsArray;
385
    }
386
387
///////////////////////////////////////////////////////////////////////////////////////////////////
388
389
  private JSONArray generateAxis(TwistyObject object) throws JSONException
390
    {
391
    JSONArray axis = new JSONArray();
392
393
    Static3D[] rotAxis = object.getRotationAxis();
394
    int numAxis = rotAxis.length;
395
    int[] basicAngle = object.getBasicAngle();
396
    int[] numLayers = object.getNumLayers();
397
    float[][] cuts = object.getCuts(numLayers);
398
    boolean[][] rotatable = object.getLayerRotatable(numLayers);
399
400
    for( int i=0; i<numAxis; i++ )
401
      {
402
      JSONObject axObject = new JSONObject();
403
      Static3D ax = rotAxis[i];
404
405
      axObject.put("x", ax.get0() );
406
      axObject.put("y", ax.get1() );
407
      axObject.put("z", ax.get2() );
408
      axObject.put("basicAngle", basicAngle[i] );
409
410
      JSONArray cutsArray = new JSONArray();
411
      for(float cut : cuts[i]) cutsArray.put(cut);
412
      axObject.put("cuts", cutsArray);
413
      JSONArray rotaArray = new JSONArray();
414
      for(boolean rot : rotatable[i]) rotaArray.put(rot);
415
      axObject.put("rotatable", rotaArray );
416
417
      axis.put(axObject);
418
      }
419
420
    return axis;
421
    }
422
423
///////////////////////////////////////////////////////////////////////////////////////////////////
424
425
  private JSONObject generateScrambling(TwistyObject object) throws JSONException
426
    {
427
    JSONObject scrambling = new JSONObject();
428
429
    ScrambleState[] states = object.getScrambleStates();
430
    int scrambleType = object.getScrambleType();
431
    scrambling.put("scrambleType",scrambleType );
432
433
    if( states!=null )
434
      {
435
      JSONArray scrambleStates = new JSONArray();
436
437
      for(ScrambleState state : states)
438
        {
439
        JSONArray axisArray = new JSONArray();
440
        int numAxis = state.getNumAxis();
441
442
        for(int ax=0; ax<numAxis; ax++)
443
          {
444
          JSONArray axArray = new JSONArray();
445
          int[] axData = state.getAx(ax);
446
447
          if( axData!=null )
448
            for(int data : axData) axArray.put(data);
449
450
          axisArray.put(axArray);
451
          }
452
453
        scrambleStates.put(axisArray);
454
        }
455
456
      scrambling.put("scrambleStates", scrambleStates);
457
      }
458
459
    return scrambling;
460
    }
461
462
///////////////////////////////////////////////////////////////////////////////////////////////////
463
464
  private JSONObject generateTouchControl(TwistyObject object) throws JSONException
465
    {
466
    JSONObject touchControl = new JSONObject();
467
468
    touchControl.put("movementType" , object.getMovementType() );
469
    touchControl.put("movementSplit", object.getMovementSplit() );
470
471
    int[][][] enabled = object.getEnabled();
472
473
    JSONArray enabledArray = new JSONArray();
474
475
    for(int[][] faceEnabled : enabled)
476
      {
477
      JSONArray faceArray = new JSONArray();
478
479
      for(int[] sectionEnabled : faceEnabled)
480
        {
481
        JSONArray sectionArray = new JSONArray();
482
        for(int ax : sectionEnabled) sectionArray.put(ax);
483
        faceArray.put(sectionArray);
484
        }
485
      enabledArray.put(faceArray);
486
      }
487
488
    touchControl.put("enabledAxis", enabledArray);
489
490 82eb152a Leszek Koltunski
    int[] numLayers = object.getNumLayers();
491
    float[] dist3D = object.getDist3D(numLayers);
492
493
    if( dist3D!=null )
494
      {
495
      JSONArray distArray = new JSONArray();
496
      for( float dist: dist3D ) distArray.put(dist);
497
      touchControl.put("dist3D", distArray);
498
      }
499
500 e26eb4e7 Leszek Koltunski
    return touchControl;
501
    }
502
503 82eb152a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
504
505
  private JSONArray generateColors(TwistyObject object)
506
    {
507
    JSONArray jsonColors = new JSONArray();
508
    int numFaceColors = object.getNumFaceColors();
509
    for(int i=0; i<numFaceColors; i++) jsonColors.put(object.getColor(i));
510
511
    return jsonColors;
512
    }
513
514 e26eb4e7 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
515
516
  public String createJsonString(TwistyObject object) throws JSONException
517
    {
518
    JSONObject json = new JSONObject();
519
520
    JSONObject metadata    = generateMetadata(object);
521
    JSONObject mesh        = generateMesh(object);
522
    JSONArray  axis        = generateAxis(object);
523
    JSONArray  quats       = generateQuats(object);
524
    JSONObject scrambling  = generateScrambling(object);
525
    JSONObject touchControl= generateTouchControl(object);
526 82eb152a Leszek Koltunski
    JSONArray  colors      = generateColors(object);
527 e26eb4e7 Leszek Koltunski
528
    json.put("major"       , VERSION_MAJOR);
529
    json.put("minor"       , VERSION_MINOR);
530
    json.put("metadata"    , metadata);
531
    json.put("mesh"        , mesh);
532
    json.put("axis"        , axis);
533
    json.put("quats"       , quats);
534
    json.put("scrambling"  , scrambling);
535
    json.put("touchcontrol", touchControl);
536 82eb152a Leszek Koltunski
    json.put("colors"      , colors);
537
538
    return json.toString();
539
    }
540 e26eb4e7 Leszek Koltunski
541 82eb152a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
542 e26eb4e7 Leszek Koltunski
543 82eb152a Leszek Koltunski
  public void write(String filename, String contents) throws IOException
544
    {
545
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8);
546
    BufferedWriter bw = new BufferedWriter(osw);
547
    bw.write(contents);
548
    bw.flush();
549 e26eb4e7 Leszek Koltunski
    }
550
551
///////////////////////////////////////////////////////////////////////////////////////////////////
552
553
  public static JsonWriter getInstance()
554
    {
555
    if( mThis==null ) mThis = new JsonWriter();
556
    return mThis;
557
    }
558
}