Project

General

Profile

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

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

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.json.JSONArray;
29
import org.json.JSONException;
30
import org.json.JSONObject;
31

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

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

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

    
43
public class JsonWriter
44
{
45
  private static final int VERSION_MAJOR = 1;
46
  private static final int VERSION_MINOR = 0;
47

    
48
  private static JsonWriter mThis;
49

    
50
///////////////////////////////////////////////////////////////////////////////////////////////////
51

    
52
  private JsonWriter()
53
    {
54

    
55
    }
56

    
57
///////////////////////////////////////////////////////////////////////////////////////////////////
58

    
59
  private JSONArray generateCubits(TwistyObject object) throws JSONException
60
    {
61
    JSONArray array = new JSONArray();
62

    
63
    int[] numLayers     = object.getNumLayers();
64
    float[][] positions = object.getCubitPositions(numLayers);
65
    int numCubits = positions.length;
66
    int numFaces = object.getNumCubitFaces();
67

    
68
    for(int i=0; i<numCubits; i++)
69
      {
70
      JSONObject cubit = new JSONObject();
71
      Static4D rotQuat  = object.getQuat(i,numLayers);
72
      int variant       = object.getCubitVariant(i,numLayers);
73
      int[] solvedQuats = object.getSolvedQuats(i,numLayers);
74

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

    
85
      if( solvedQuats!=null )
86
        {
87
        JSONArray solved = new JSONArray();
88
        for (int solvedQuat : solvedQuats) solved.put(solvedQuat);
89
        cubit.put("solvedQuats",solved);
90
        }
91

    
92
      JSONArray colors = new JSONArray();
93

    
94
      for(int j=0; j<numFaces; j++)
95
        {
96
        int cubColor = object.getCubitFaceColor(i,j,numLayers);
97
        colors.put(cubColor);
98
        }
99
      cubit.put("colors",colors);
100

    
101
      array.put(cubit);
102
      }
103

    
104
    return array;
105
    }
106

    
107
///////////////////////////////////////////////////////////////////////////////////////////////////
108

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

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

    
121
    return array;
122
    }
123

    
124
///////////////////////////////////////////////////////////////////////////////////////////////////
125

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

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

    
139
    return array;
140
    }
141

    
142
///////////////////////////////////////////////////////////////////////////////////////////////////
143

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

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

    
161
    return array;
162
    }
163

    
164
///////////////////////////////////////////////////////////////////////////////////////////////////
165

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

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

    
177
      int sticker = object.getVariantFaceColor(variant,i,numLayers);
178
      face.put("sticker",sticker);
179

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

    
185
      array.put(face);
186
      }
187

    
188
    return array;
189
    }
190

    
191
///////////////////////////////////////////////////////////////////////////////////////////////////
192

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

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

    
209
    return array;
210
    }
211

    
212
///////////////////////////////////////////////////////////////////////////////////////////////////
213

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

    
223
///////////////////////////////////////////////////////////////////////////////////////////////////
224

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

    
232
    return -1;
233
    }
234

    
235
///////////////////////////////////////////////////////////////////////////////////////////////////
236

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

    
241
    int[] numLayers = object.getNumLayers();
242
    int numVariants = object.getNumCubitVariants(numLayers);
243
    float[][] positions = object.getCubitPositions(numLayers);
244
    int numCubits = positions.length;
245

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

    
250
      ObjectShape shape = object.getObjectShape(i);
251

    
252
      float[] convexity  = shape.getConvexityCenter();
253
      double[][] vertices= shape.getVertices();
254
      int[][] vertIndices= shape.getVertIndices();
255
      float[][] bands    = shape.getBands();
256
      int[] bandIndices  = shape.getBandIndices();
257
      float[][] corners  = shape.getCorners();
258
      int[] cornerIndices= shape.getCornerIndices();
259
      float[][] centers  = shape.getCenters();
260
      int[] centerIndices= shape.getCenterIndices();
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[] numLayers = object.getNumLayers();
302
    int numStickers = object.getNumStickerTypes(numLayers);
303

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

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

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

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

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

    
332
    return stickers;
333
    }
334

    
335
///////////////////////////////////////////////////////////////////////////////////////////////////
336

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

    
341
    JSONArray cubits   = generateCubits(object);
342
    JSONArray shapes   = generateShapes(object);
343
    JSONArray stickers = generateStickers(object);
344

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

    
349
    return mesh;
350
    }
351

    
352
///////////////////////////////////////////////////////////////////////////////////////////////////
353

    
354
  private JSONObject generateMetadata(TwistyObject object) throws JSONException
355
    {
356
    JSONObject metadata = new JSONObject();
357

    
358
    ObjectType type  = object.getObjectType();
359
    String inventor  = object.getInventor();
360
    String shortname = type.name();
361
    String lowerShort= shortname.toLowerCase();
362
    String longname  = object.getObjectName();
363

    
364
    metadata.put("longname"     , longname );
365
    metadata.put("shortname"    , shortname );
366
    metadata.put("inventor"     , inventor);
367
    metadata.put("year"         , object.getYearOfInvention());
368
    metadata.put("complexity"   , object.getComplexity());
369
    metadata.put("icon_huge"    , "h_"+lowerShort+".png");
370
    metadata.put("icon_big"     , "b_"+lowerShort+".png");
371
    metadata.put("icon_medium"  , "m_"+lowerShort+".png");
372
    metadata.put("icon_small"   , "s_"+lowerShort+".png");
373
    metadata.put("mesh"         , lowerShort+".dmesh");
374
    metadata.put("num_scrambles", type.getNumScramble() );
375
    metadata.put("size"         , object.getSize() );
376
    metadata.put("solved_func"  , object.getSolvedFunctionIndex() );
377

    
378
    return metadata;
379
    }
380

    
381
///////////////////////////////////////////////////////////////////////////////////////////////////
382

    
383
  private JSONArray generateQuats(TwistyObject object) throws JSONException
384
    {
385
    JSONArray quatsArray = new JSONArray();
386
    Static4D[] quats = object.getQuats();
387

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

    
398
    return quatsArray;
399
    }
400

    
401
///////////////////////////////////////////////////////////////////////////////////////////////////
402

    
403
  private JSONArray generateAxis(TwistyObject object) throws JSONException
404
    {
405
    JSONArray axis = new JSONArray();
406

    
407
    Static3D[] rotAxis = object.getRotationAxis();
408
    int numAxis = rotAxis.length;
409
    int[] basicAngle = object.getBasicAngle();
410
    int[] numLayers = object.getNumLayers();
411
    float[][] cuts = object.getCuts(numLayers);
412
    boolean[][] rotatable = object.getLayerRotatable(numLayers);
413

    
414
    for( int i=0; i<numAxis; i++ )
415
      {
416
      JSONObject axObject = new JSONObject();
417
      Static3D ax = rotAxis[i];
418

    
419
      axObject.put("x", ax.get0() );
420
      axObject.put("y", ax.get1() );
421
      axObject.put("z", ax.get2() );
422
      axObject.put("basicAngle", basicAngle[i] );
423

    
424
      JSONArray cutsArray = new JSONArray();
425
      for(float cut : cuts[i]) cutsArray.put(cut);
426
      axObject.put("cuts", cutsArray);
427
      JSONArray rotaArray = new JSONArray();
428
      for(boolean rot : rotatable[i]) rotaArray.put(rot);
429
      axObject.put("rotatable", rotaArray );
430

    
431
      axis.put(axObject);
432
      }
433

    
434
    return axis;
435
    }
436

    
437
///////////////////////////////////////////////////////////////////////////////////////////////////
438

    
439
  private JSONObject generateScrambling(TwistyObject object) throws JSONException
440
    {
441
    JSONObject scrambling = new JSONObject();
442

    
443
    ScrambleState[] states = object.getScrambleStates();
444
    int scrambleType = object.getScrambleType();
445
    scrambling.put("scrambleType",scrambleType );
446

    
447
    if( states!=null )
448
      {
449
      JSONArray scrambleStates = new JSONArray();
450

    
451
      for(ScrambleState state : states)
452
        {
453
        JSONArray axisArray = new JSONArray();
454
        int numAxis = state.getNumAxis();
455

    
456
        for(int ax=0; ax<numAxis; ax++)
457
          {
458
          JSONArray axArray = new JSONArray();
459
          int[] axData = state.getAx(ax);
460

    
461
          if( axData!=null )
462
            for(int data : axData) axArray.put(data);
463

    
464
          axisArray.put(axArray);
465
          }
466

    
467
        scrambleStates.put(axisArray);
468
        }
469

    
470
      scrambling.put("scrambleStates", scrambleStates);
471
      }
472

    
473
    return scrambling;
474
    }
475

    
476
///////////////////////////////////////////////////////////////////////////////////////////////////
477

    
478
  private JSONObject generateTouchControl(TwistyObject object) throws JSONException
479
    {
480
    JSONObject touchControl = new JSONObject();
481

    
482
    touchControl.put("movementType" , object.getMovementType() );
483
    touchControl.put("movementSplit", object.getMovementSplit() );
484

    
485
    int[][][] enabled = object.getEnabled();
486

    
487
    JSONArray enabledArray = new JSONArray();
488

    
489
    for(int[][] faceEnabled : enabled)
490
      {
491
      JSONArray faceArray = new JSONArray();
492

    
493
      for(int[] sectionEnabled : faceEnabled)
494
        {
495
        JSONArray sectionArray = new JSONArray();
496
        for(int ax : sectionEnabled) sectionArray.put(ax);
497
        faceArray.put(sectionArray);
498
        }
499
      enabledArray.put(faceArray);
500
      }
501

    
502
    touchControl.put("enabledAxis", enabledArray);
503

    
504
    int[] numLayers = object.getNumLayers();
505
    float[] dist3D = object.getDist3D(numLayers);
506

    
507
    if( dist3D!=null )
508
      {
509
      JSONArray distArray = new JSONArray();
510
      for( float dist: dist3D ) distArray.put(dist);
511
      touchControl.put("dist3D", distArray);
512
      }
513

    
514
    return touchControl;
515
    }
516

    
517
///////////////////////////////////////////////////////////////////////////////////////////////////
518

    
519
  private JSONArray generateColors(TwistyObject object)
520
    {
521
    JSONArray jsonColors = new JSONArray();
522
    int numFaceColors = object.getNumFaceColors();
523
    for(int i=0; i<numFaceColors; i++) jsonColors.put(object.getColor(i));
524

    
525
    return jsonColors;
526
    }
527

    
528
///////////////////////////////////////////////////////////////////////////////////////////////////
529

    
530
  public String createJsonString(TwistyObject object) throws JSONException
531
    {
532
    JSONObject json = new JSONObject();
533

    
534
    JSONObject metadata    = generateMetadata(object);
535
    JSONObject mesh        = generateMesh(object);
536
    JSONArray  axis        = generateAxis(object);
537
    JSONArray  quats       = generateQuats(object);
538
    JSONObject scrambling  = generateScrambling(object);
539
    JSONObject touchControl= generateTouchControl(object);
540
    JSONArray  colors      = generateColors(object);
541

    
542
    json.put("major"       , VERSION_MAJOR);
543
    json.put("minor"       , VERSION_MINOR);
544
    json.put("metadata"    , metadata);
545
    json.put("mesh"        , mesh);
546
    json.put("axis"        , axis);
547
    json.put("quats"       , quats);
548
    json.put("scrambling"  , scrambling);
549
    json.put("touchcontrol", touchControl);
550
    json.put("colors"      , colors);
551

    
552
    return json.toString();
553
    }
554

    
555
///////////////////////////////////////////////////////////////////////////////////////////////////
556

    
557
  public void write(String filename, String contents) throws IOException
558
    {
559
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8);
560
    BufferedWriter bw = new BufferedWriter(osw);
561
    bw.write(contents);
562
    bw.flush();
563
    }
564

    
565
///////////////////////////////////////////////////////////////////////////////////////////////////
566

    
567
  public static JsonWriter getInstance()
568
    {
569
    if( mThis==null ) mThis = new JsonWriter();
570
    return mThis;
571
    }
572
}
(2-2/2)