Project

General

Profile

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

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

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.helpers.ScrambleState;
39
import org.distorted.objectlib.main.TwistyObject;
40
import org.distorted.objectlib.main.ObjectType;
41

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

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

    
49
  private static JsonWriter mThis;
50
  private static int mNumCubitFaces;
51

    
52
///////////////////////////////////////////////////////////////////////////////////////////////////
53

    
54
  private JsonWriter()
55
    {
56

    
57
    }
58

    
59
///////////////////////////////////////////////////////////////////////////////////////////////////
60

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

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

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

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

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

    
93
      JSONArray colors = new JSONArray();
94

    
95
      for(int f=0; f<mNumCubitFaces; f++)
96
        {
97
        int cubColor = object.getCubitFaceColor(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 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

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

    
186
      array.put(face);
187
      }
188

    
189
    return array;
190
    }
191

    
192
///////////////////////////////////////////////////////////////////////////////////////////////////
193

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

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

    
210
    return array;
211
    }
212

    
213
///////////////////////////////////////////////////////////////////////////////////////////////////
214

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

    
224
///////////////////////////////////////////////////////////////////////////////////////////////////
225

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

    
233
    return -1;
234
    }
235

    
236
///////////////////////////////////////////////////////////////////////////////////////////////////
237

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

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

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

    
252
      ObjectShape shape = object.getObjectShape(i);
253
      ObjectFaceShape face = object.getObjectFaceShape(i);
254

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

    
265
      int num = vertIndices.length;
266
      if( num>mNumCubitFaces ) mNumCubitFaces=num;
267

    
268
      int cubit = findCubitWithVariant(object,i,numCubits,numLayers);
269

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

    
276
      JSONArray verticesArr = generateVertices(vertices,cornerIndices,centerIndices);
277
      shapeObj.put("vertices", verticesArr);
278
      JSONArray facesArr = generateFaces(object,vertIndices,bandIndices,cubit,numLayers);
279
      shapeObj.put("faces", facesArr);
280
      JSONArray bandsArr = generateBands(bands);
281
      shapeObj.put("bands", bandsArr);
282

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

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

    
295
      shapes.put(shapeObj);
296
      }
297

    
298
    return shapes;
299
    }
300

    
301
///////////////////////////////////////////////////////////////////////////////////////////////////
302

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

    
307
    int numStickers = object.getNumStickerTypes();
308

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

    
314
      ObjectSticker sticker = object.retSticker(i);
315

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

    
321
      stickerObj.put("stroke", stroke);
322
      int numVertices = radii.length;
323

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

    
337
    return stickers;
338
    }
339

    
340
///////////////////////////////////////////////////////////////////////////////////////////////////
341

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

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

    
350
    mesh.put("shapes"  , shapes);
351
    mesh.put("cubits"  , cubits);
352
    mesh.put("stickers", stickers);
353

    
354
    return mesh;
355
    }
356

    
357
///////////////////////////////////////////////////////////////////////////////////////////////////
358

    
359
  private JSONObject generateMetadata(TwistyObject object) throws JSONException
360
    {
361
    JSONObject metadata = new JSONObject();
362

    
363
    ObjectType type = object.getObjectType();
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("solved_func", object.getSolvedFunctionIndex() );
371
    metadata.put("scrambles"  , type.getNumScramble() );
372
    metadata.put("shortname"  , type.name() );
373
    metadata.put("resetmaps"  , object.shouldResetTextureMaps() );
374
    metadata.put("num_faces"  , object.getNumFaces() );
375

    
376
    return metadata;
377
    }
378

    
379
///////////////////////////////////////////////////////////////////////////////////////////////////
380

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

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

    
396
    return quatsArray;
397
    }
398

    
399
///////////////////////////////////////////////////////////////////////////////////////////////////
400

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

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

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

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

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

    
429
      axis.put(axObject);
430
      }
431

    
432
    return axis;
433
    }
434

    
435
///////////////////////////////////////////////////////////////////////////////////////////////////
436

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

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

    
445
    if( states!=null )
446
      {
447
      JSONArray scrambleStates = new JSONArray();
448

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

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

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

    
462
          axisArray.put(axArray);
463
          }
464

    
465
        scrambleStates.put(axisArray);
466
        }
467

    
468
      scrambling.put("scrambleStates", scrambleStates);
469
      }
470

    
471
    return scrambling;
472
    }
473

    
474
///////////////////////////////////////////////////////////////////////////////////////////////////
475

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

    
480
    touchControl.put("movementType" , object.getTouchControlType() );
481
    touchControl.put("movementSplit", object.getTouchControlSplit() );
482

    
483
    int[][][] enabled = object.getEnabled();
484

    
485
    JSONArray enabledArray = new JSONArray();
486

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

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

    
500
    touchControl.put("enabledAxis", enabledArray);
501

    
502
    int[] numLayers = object.getNumLayers();
503
    float[] dist3D = object.getDist3D(numLayers);
504

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

    
512
    return touchControl;
513
    }
514

    
515
///////////////////////////////////////////////////////////////////////////////////////////////////
516

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

    
523
    return jsonColors;
524
    }
525

    
526
///////////////////////////////////////////////////////////////////////////////////////////////////
527

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

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

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

    
550
    return json.toString();
551
    }
552

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

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

    
563
///////////////////////////////////////////////////////////////////////////////////////////////////
564

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