-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCaDoodleFile.java
More file actions
1528 lines (1379 loc) · 43.2 KB
/
CaDoodleFile.java
File metadata and controls
1528 lines (1379 loc) · 43.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.neuronrobotics.bowlerstudio.scripting.cadoodle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import javafx.scene.image.WritableImage;
import org.apache.commons.io.FileUtils;
import org.apache.hc.client5.http.impl.Operations;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.reflect.TypeToken;
import com.neuronrobotics.bowlerstudio.BowlerKernel;
import com.neuronrobotics.bowlerstudio.creature.MobileBaseBuilder;
import com.neuronrobotics.bowlerstudio.creature.NoImageException;
import com.neuronrobotics.bowlerstudio.creature.ThumbnailImage;
import com.neuronrobotics.bowlerstudio.physics.TransformFactory;
import com.neuronrobotics.bowlerstudio.scripting.DownloadManager;
import com.neuronrobotics.bowlerstudio.scripting.ScriptingEngine;
import com.neuronrobotics.bowlerstudio.scripting.cadoodle.robot.MakeRobot;
import com.neuronrobotics.bowlerstudio.vitamins.VitaminBomManager;
import com.neuronrobotics.sdk.addons.kinematics.MobileBase;
import com.neuronrobotics.sdk.addons.kinematics.VitaminLocation;
import com.neuronrobotics.sdk.addons.kinematics.math.RotationNR;
import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR;
import com.neuronrobotics.sdk.common.Log;
import com.neuronrobotics.sdk.common.TickToc;
import eu.mihosoft.vrl.v3d.CSG;
import eu.mihosoft.vrl.v3d.FileUtil;
import eu.mihosoft.vrl.v3d.Polygon;
import eu.mihosoft.vrl.v3d.PropertyStorage;
import eu.mihosoft.vrl.v3d.parametrics.CSGDatabase;
import eu.mihosoft.vrl.v3d.parametrics.CSGDatabaseInstance;
import eu.mihosoft.vrl.v3d.parametrics.IParametric;
import eu.mihosoft.vrl.v3d.parametrics.Parameter;
import eu.mihosoft.vrl.v3d.parametrics.StringParameter;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import static com.neuronrobotics.bowlerstudio.scripting.DownloadManager.*;
public class CaDoodleFile {
public static final String NO_NAME = "NoName";
@Expose(serialize = true, deserialize = true)
private ArrayList<CaDoodleOperation> opperations = new ArrayList<CaDoodleOperation>();
@Expose(serialize = true, deserialize = true)
private int currentIndex = 0;
@Expose(serialize = true, deserialize = true)
private long timeCreated = -1;
@Expose(serialize = true, deserialize = true)
private String projectName = NO_NAME;
@Expose(serialize = true, deserialize = true)
private TransformNR rulerLocation = new TransformNR();
@Expose(serialize = true, deserialize = true)
private TransformNR workplane = new TransformNR();
@Expose(serialize = true, deserialize = true)
private CaDoodleParameters parameters;
private File self;
// @Expose (serialize = false, deserialize = false)
// private List<CSG> currentState = new ArrayList<CSG>();
private double percentInitialized = 0;
private final HashMap<CaDoodleOperation, List<CSG>> cache = new HashMap<CaDoodleOperation, List<CSG>>();
private static Type TT_CaDoodleFile = new TypeToken<CaDoodleFile>() {
}.getType();
private static Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()
.excludeFieldsWithoutExposeAnnotation()
.registerTypeAdapterFactory(new CaDoodleJsonOperationAdapterFactory()).create();
private final ArrayList<ICaDoodleStateUpdate> listeners = new ArrayList<ICaDoodleStateUpdate>();
private final ArrayList<Thread> opperationRunner = new ArrayList<Thread>();
private boolean regenerating;
private final CopyOnWriteArrayList<CaDoodleOperation> toProcess = new CopyOnWriteArrayList<CaDoodleOperation>();
private javafx.scene.image.WritableImage img;
private boolean initializing;
private static HashMap<String, VitaminBomManager> bomManagers = new HashMap<>();
private VitaminBomManager bom;
private IAcceptPruneForward accept = null;
private long timeOfLastUpdate = 0;
private OperationResult result = OperationResult.APPEND;
private ThumbnailImage imageEngine = null;
private ICadoodleSaveStatusUpdate defaultSaver = new ICadoodleSaveStatusUpdate() {
@Override
public void renderSplashFrame(int percent, String message) {
com.neuronrobotics.sdk.common.Log.debug(percent + "% " + message);
}
};
private ICadoodleSaveStatusUpdate saveUpdate = null;
private boolean timelineOpen = false;
private HashMap<String, MobileBaseBuilder> robots = new HashMap<String, MobileBaseBuilder>();
private CSGDatabaseInstance csgDBinstance;
private File objectDir;
private ExecutorService executor = Executors.newFixedThreadPool(5);
private File imageCacheDir;
private boolean saveing;
@Override
public String toString() {
return projectName;
}
public void deleteTailFromCurrent() {
fireRegenerateStart(getCurrentOpperation());
IAcceptPruneForward oldAccept = getAccept();
setAccept(() -> OperationResult.PRUNE);
try {
pruneForward(getCurrentOpperation());
} catch (Exception ex) {
com.neuronrobotics.sdk.common.Log.error("Failed to prune tail" + ex);
}
setAccept(oldAccept);
fireRegenerateDone();
}
public ArrayList<MobileBase> getMobileBases() {
ArrayList<MobileBase> back = new ArrayList<MobileBase>();
for (MobileBaseBuilder b : robots.values()) {
back.add(b.getMobileBase());
}
return back;
}
public void close() {
// new Exception("CaDoodle File Closed here").printStackTrace();
for (CaDoodleOperation op : getOpperations()) {
op.setCaDoodleFile(null);
}
// for (CaDoodleOperation op : cache.keySet()) {
// clearCache(op);
// }
cache.clear();
clearListeners();
toProcess.clear();
img = null;
for (Thread t : opperationRunner)
t.interrupt();
}
private int opToIndex(CaDoodleOperation op) {
for (int i = 0; i < opperations.size(); i++) {
if (op == opperations.get(i))
return i;
}
throw new IndexOutOfBoundsException();
}
private boolean inCache(CaDoodleOperation op) {
int opIndex = opToIndex(op);
File cacheFile = new File(getObjectDir().getAbsolutePath() + delim() + opIndex);
return cacheFile.exists();
}
private List<CSG> getCachedCSGs(CaDoodleOperation op) {
try {
if (Platform.isFxApplicationThread()) {
// new RuntimeException("This should not be called from the UI
// thread!").printStackTrace();
;
}
} catch (Exception ex) {
// skipping no toolkit exceptions
}
// if (cache.get(op) == null && isInitialized()) {
// try {
// int opIndex = opToIndex(op);
// File cacheFile = new File(getObjectDir().getAbsolutePath() + delim() + opIndex + ".csg");
// if (cacheFile.exists()) {
// Log.debug("Loading Cached Objects from file: " + cacheFile.getAbsolutePath());
// // Log.error(new Exception());
// ObjectInputStream ois = new ObjectInputStream(new FileInputStream(cacheFile));
// cache.put(op, (List<CSG>) ois.readObject());
// ois.close();
// }
// } catch (Exception ex) {
// Log.error(ex);
// }
// }
return cache.get(op);
}
private void memoryCheck() {
if (getFreeMemory() > 85) {
com.neuronrobotics.sdk.common.Log.error("\n\nClearing Memory use: " + getFreeMemory() + "\n\n");
CaDoodleOperation op = getCurrentOpperation();
List<CSG> back = cache.get(op);
cache.clear();
cache.put(op, back);
System.gc();
com.neuronrobotics.sdk.common.Log.debug("Memory use down to: " + getFreeMemory());
} else {
// com.neuronrobotics.sdk.common.Log.debug("Memory use: " + getFreeMemory());
}
}
private void placeCSGsInCache(CaDoodleOperation op, List<CSG> cachedCopyIn) {
memoryCheck();
// clear the stale cache value
List<CSG> back = cache.remove(op);
if (back != null)
back.clear();
List<CSG> cachedCopy = new ArrayList<>(cachedCopyIn);
cache.put(op, cachedCopy);
// executor.submit(() -> {
// File cacheFile = new File(getObjectDir().getAbsolutePath() + delim() + opToIndex(op) + ".csg");
// if (cacheFile.exists() && !isInitialized())
// return;
// if (cacheFile.exists())
// cacheFile.delete();
// try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(cacheFile))) {
// oos.writeObject(cachedCopy);
// Log.debug("Saved " + cacheFile.getAbsolutePath());
// } catch (Exception ex) {
// Log.error(ex);
// throw new RuntimeException(ex);
// }
// });
}
private void clearCache(CaDoodleOperation key) {
int opIndex = opToIndex(key);
File cacheFile = new File(getObjectDir().getAbsolutePath() + delim() + opIndex);
if (cacheFile.exists())
cacheFile.delete();
List<CSG> back = cache.remove(key);
if (back != null)
back.clear();
}
public CaDoodleFile clearListeners() {
listeners.clear();
return this;
}
public CaDoodleFile removeListener(ICaDoodleStateUpdate l) {
if (listeners.contains(l))
listeners.remove(l);
return this;
}
public CaDoodleFile addListener(ICaDoodleStateUpdate l) {
if (!listeners.contains(l))
listeners.add(l);
return this;
}
public void initialize() {
// if (initializing)
// throw new RuntimeException("Can not initialize while initializing.");
fireInitializationStart();
setImageEngine(new ThumbnailImage());
initializing = true;
if (timeCreated < 0)
timeCreated = System.currentTimeMillis();
if (self != null) {
getImageCacheDir();
getObjectDir();
getCsgDBinstance();// initialize the instance on initialize
// CSGDatabase.setInstance(getCsgDBinstance());
getBom().clear();
getBom().save();
}
int indexStarting = getCurrentIndex();
if (indexStarting == 0) {
indexStarting = opperations.size();
}
this.currentIndex = 0;
setPercentInitialized(0);
opperations = opperations.stream().filter(Objects::nonNull).collect(Collectors.toCollection(ArrayList::new));
if (indexStarting > opperations.size())
indexStarting = opperations.size();
ArrayList<CaDoodleOperation> toRem = new ArrayList<CaDoodleOperation>();
for (int i = 0; i < getOpperations().size(); i++) {
CaDoodleOperation op = getOpperations().get(i);
if (op == null)
continue;
op.setCaDoodleFile(this);
setPercentInitialized(((double) i) / (double) getOpperations().size());
// if(!inCache(op))
try {
process(op);
} catch (Throwable t) {
com.neuronrobotics.sdk.common.Log.error(t);
// indexStarting = i ;
// break;
// toRem.add(op);
}
}
// opperations.removeAll(toRem);
// if(indexStarting>opperations.size()) {
// indexStarting = opperations.size();
// }
setCurrentIndex(indexStarting);
updateCurrentFromCache();
loadImageFromFile();
setPercentInitialized(1);
for (ICaDoodleStateUpdate l : listeners) {
try {
l.onInitializationDone();
} catch (Throwable e) {
com.neuronrobotics.sdk.common.Log.error(e);
}
}
updateBoM();
initializing = false;
}
public void updateBoM() {
if (bom == null)
return;
getBom().clear();
getBom().save();
for (CSG c : getCurrentState()) {
String type = null;
String size = null;
Set<String> parameters = c.getParameters(getCsgDBinstance());
for (String param : parameters) {
if (!param.contains(c.getName()))
continue;
if (param.contains("_CaDoodle_Vitamin_Type")) {
Parameter p = getCsgDBinstance().get(param);
type = p.getStrValue();
}
if (param.contains("_CaDoodle_Vitamin_Size")) {
Parameter p = getCsgDBinstance().get(param);
size = p.getStrValue();
}
if (type != null && size != null) {
getBom().addVitamin(new VitaminLocation(false, c.getName(), type, size, new TransformNR()));
break;
}
}
}
getBom().save();
}
public static VitaminBomManager getBillOfMaterials(CaDoodleFile cf) {
String strValue = cf.getSelf().getAbsolutePath();
File file = new File(strValue).getParentFile();
if (bomManagers.get(strValue) == null) {
bomManagers.put(strValue, new VitaminBomManager(file));
}
return bomManagers.get(strValue);
}
// private static String getCadoodleFileLocation() {
//
// return get;
// }
public Thread regenerateFrom(CaDoodleOperation source) {
if (initializing)
return null;
if (isRegenerating() || isOperationRunning() || source == null) {
com.neuronrobotics.sdk.common.Log.error(new Exception("Operation Running, bailing"));
return null;
}
fireRegenerateStart(source);
int endIndex = getCurrentIndex();
double size = getOpperations().size();
if (endIndex != size) {
// new Exception("Regenerationg from a position back in time " + endIndex + " but have " + size)
// .printStackTrace();
}
Thread t = null;
CaDoodleFile cf = this;
t = new Thread() {
public void run() {
this.setName("Regeneration Threads");
try {
timeOfLastUpdate = System.currentTimeMillis();
setRegenerating(true);
// com.neuronrobotics.sdk.common.Log.error("Regenerating Object from
// "+source.getType());
int opIndex = 0;
for (int i = 0; i < size; i++) {
CaDoodleOperation op = getOpperations().get(i);
if (source == op) {
opIndex = i;
break;
}
}
setCurrentIndex(opIndex);
try {
for (; getCurrentIndex() < size;) {
int percent = (int) (((double) getCurrentIndex()) / ((double) getOpperations().size())
* 100.0);
setCurrentIndex(getCurrentIndex() + 1);
setPercentInitialized(((double) getCurrentIndex()) / size);
// com.neuronrobotics.sdk.common.Log.error("Regenerating "+currentIndex);
int currentIndex2 = getCurrentIndex() - 1;
CaDoodleOperation op = getOpperations().get(currentIndex2);
getSaveUpdate().renderSplashFrame(percent,
"Regenerating " + op.getType() + " " + currentIndex2);
getTimelineImageFile(op).delete();
// clearCache(op);
try {
op.setCaDoodleFile(cf);
List<CSG> process = op.process(getPreviouState());
storeResultInCache(op, process);
setCurrentState(op, process);
} catch (Throwable tr) {
com.neuronrobotics.sdk.common.Log.error(tr);
}
}
if (getCurrentIndex() != endIndex) {
setCurrentIndex(endIndex);
updateCurrentFromCache();
}
} catch (Exception ex) {
com.neuronrobotics.sdk.common.Log.error(ex);
;
}
setPercentInitialized(1);
updateBoM();
setRegenerating(false);
fireSaveSuggestion();
fireRegenerateDone();
} catch (Throwable th) {
com.neuronrobotics.sdk.common.Log.error(th);
}
opperationRunner.remove(this);
}
};
opperationRunner.add(t);
t.start();
return t;
}
public Thread regenerateCurrent() {
if (isOperationRunning()) {
com.neuronrobotics.sdk.common.Log.error(new Exception("Operation Running, bailing"));
return opperationRunner.get(0);
}
if (initializing) {
Thread t = new Thread();
t.start();
return t;
}
CaDoodleOperation op = getCurrentOpperation();
fireRegenerateStart(op);
Thread t = null;
CaDoodleFile cf = this;
t = new Thread() {
public void run() {
timeOfLastUpdate = System.currentTimeMillis();
// TickToc.setEnabled(true);
this.setName("regenerateCurrent Thread");
TickToc.tic("Start regenerate");
op.setCaDoodleFile(cf);
List<CSG> process = op.process(getPreviouState());
TickToc.tic("Finish regenerate");
int currentIndex2 = getCurrentIndex();
getTimelineImageFile(currentIndex2).delete();
TickToc.tic("Get timeline file");
storeResultInCache(op, process);
TickToc.tic("Stored results in cache");
setCurrentState(op, process);
TickToc.tic("set current state");
fireSaveSuggestion();
TickToc.tic("Fired save suggestion");
fireRegenerateDone();
TickToc.tic("Fired regeneration Done");
opperationRunner.remove(this);
}
};
opperationRunner.add(t);
t.start();
return t;
}
private void process(CaDoodleOperation op) throws Exception {
op.setCaDoodleFile(this);
List<CSG> process = null;
Exception ex = null;
try {
process = op.process(getCurrentState());
if (MakeRobot.class.isInstance(op)) {
MakeRobot mr = (MakeRobot) op;
getRobots().put(mr.getName(), mr.getBuilder());
}
} catch (Exception ex1) {
ex = ex1;
}
if (process == null) {
process = getCurrentState();
}
if (process.size() == 0) {
Log.error("Nothing returned int he process step?");
}
int currentIndex2 = getCurrentIndex();
storeResultInCache(op, process);
setCurrentIndex(currentIndex2 + 1);
setCurrentState(op, process);
if (ex != null)
throw ex;
}
public boolean isOperationRunning() {
for (int i = 0; i < opperationRunner.size(); i++) {
Thread t = opperationRunner.get(i);
if (t != null) {
if (!t.isAlive()) {
opperationRunner.remove(t);
// new Exception("Thread failed to remove itself
// "+t.getName()).printStackTrace();
continue;
}
if (Thread.currentThread().getId() == t.getId())
return false;
return true;
}
}
return false;
}
public Thread addOpperation(CaDoodleOperation o) throws CadoodleConcurrencyException {
if (o == null)
throw new NullPointerException();
toProcess.add(o);
if (isOperationRunning()) {
com.neuronrobotics.sdk.common.Log.error(new Exception("Operation Running, bailing"));
return opperationRunner.get(0);
}
Thread t = null;
t = new Thread() {
public void run() {
timeOfLastUpdate = System.currentTimeMillis();
while (toProcess.size() > 0) {
result = OperationResult.APPEND;
this.setName("addOpperation Thread " + toProcess.size());
CaDoodleOperation op = toProcess.remove(0);
com.neuronrobotics.sdk.common.Log.debug("Adding Operation " + op);
if (getCurrentIndex() != getOpperations().size()) {
try {
fireRegenerateStart(op);
setResult(pruneForward(op));
} catch (Exception e) {
com.neuronrobotics.sdk.common.Log.error(e);
break;
}
}
if (getResult() == OperationResult.APPEND || getResult() == OperationResult.PRUNE) {
try {
getOpperations().add(op);
process(op);
} catch (Exception ex) {
com.neuronrobotics.sdk.common.Log.error(ex);
;
}
}
if (getResult() == OperationResult.INSERT) {
getOpperations().add(getCurrentIndex(), op);
try {
process(op);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
regenerateFrom(op).join();
} catch (InterruptedException e) {
com.neuronrobotics.sdk.common.Log.error(e);
}
updateCurrentFromCache();
}
if (getResult() == OperationResult.ABORT) {
setCurrentState(getCurrentOpperation(), getCurrentState());
}
updateBoM();
fireSaveSuggestion();
fireRegenerateDone();
}
opperationRunner.remove(this);
}
};
opperationRunner.add(t);
t.start();
return t;
}
public Thread deleteOperation(CaDoodleOperation op) {
if (op == null)
throw new NullPointerException();
if (isOperationRunning()) {
com.neuronrobotics.sdk.common.Log.error(new Exception("Operation Running, bailing"));
return opperationRunner.get(0);
}
Thread t = null;
t = new Thread() {
public void run() {
timeOfLastUpdate = System.currentTimeMillis();
this.setName("deleteOpperation Thread " + toProcess.size());
int index = 0;
for (int i = 0; i < getOpperations().size(); i++)
if (getOpperations().get(i) == op)
index = i;
getOpperations().remove(op);
op.pruneCleanup();
// if (index == getOpperations().size())
// index -= 1;
if (index < 1)
index = 1;
CaDoodleOperation newTar = getOpperations().get(index - 1);
setCurrentIndex(index);
try {
regenerateFrom(newTar).join();
} catch (InterruptedException e) {
com.neuronrobotics.sdk.common.Log.error(e);
}
updateCurrentFromCache();
updateBoM();
fireSaveSuggestion();
opperationRunner.remove(this);
}
};
opperationRunner.add(t);
t.start();
return t;
}
public static CSG getByName(List<CSG> back, String name) throws NameMissingException {
for (CSG c : back) {
if (c.getName().contentEquals(name))
return c;
}
throw new NameMissingException("Fail! there was no object named " + name);
}
public static int applyToAllConstituantElements(boolean addRet, List<String> targetNames, ArrayList<CSG> back,
ICadoodleRecursiveEvent p, int depth) {
HashSet<String> appliedMemory = new HashSet<String>();
for (int i = 0; i < targetNames.size(); i++) {
String s = targetNames.get(i);
try {
CSG c = getByName(back, s);
if (c.isInGroup())
continue;
} catch (NameMissingException e) {
continue;
}
applyToAllConstituantElements(addRet, s, back, p, depth, appliedMemory);
}
return back.size();
}
public static int applyToAllConstituantElements(boolean addRet, String targetName, ArrayList<CSG> back,
ICadoodleRecursiveEvent p, int depth, HashSet<String> appliedMemory) {
if (appliedMemory.contains(targetName))
return back.size();
appliedMemory.add(targetName);
ArrayList<CSG> immutable = new ArrayList<>();
immutable.addAll(back);
for (int i = 0; i < immutable.size(); i++) {
CSG csg = immutable.get(i);
if (csg == null || csg.isLock())
continue;
// boolean inGroup = csg.isInGroup();
boolean thisCSGIsInGroupNamedAfterTarget = csg.checkGroupMembership(targetName);
String thisCSGName = csg.getName();
boolean thisCSGIsTheTarget = thisCSGName.contentEquals(targetName);
boolean groupResult = csg.isGroupResult();
if (thisCSGIsTheTarget) {
// move it
ArrayList<CSG> tmpToAdd = p.process(csg, depth);
if (addRet) {
back.addAll(tmpToAdd);
} else {
for (int j = 0; j < back.size(); j++) {
if (back.get(j).getName().contentEquals(csg.getName())) {
back.remove(j);
break;
}
}
back.addAll(tmpToAdd);
}
continue;
}
if (thisCSGIsInGroupNamedAfterTarget) {
// composite group
applyToAllConstituantElements(addRet, thisCSGName, back, p, depth + 1, appliedMemory);
}
}
back.removeAll(Collections.singleton(null));
return back.size();
}
public File getTimelineImageFile(CaDoodleOperation test) {
for (int i = 0; i < getOpperations().size(); i++) {
CaDoodleOperation key = getOpperations().get(i);
if (key == test) {
File file = getTimelineImageFile(i);
return file;
}
}
throw new RuntimeException("File not found!");
}
public File getTimelineImageFile(int i) {
File file = new File(getImageCacheDir().getAbsolutePath() + delim() + (i + 1) + ".png");
return file;
}
private OperationResult pruneForward(CaDoodleOperation op) throws Exception {
if (op == null)
throw new NullPointerException();
OperationResult res = OperationResult.INSERT;
if (getAccept() != null) {
res = getAccept().accept();
if (res == OperationResult.ABORT) {
return res;
}
}
if (getCurrentIndex() > 0)
for (int i = getCurrentIndex() - 1; i < getOpperations().size(); i++) {
CaDoodleOperation key = getOpperations().get(i);
if (i >= getCurrentIndex()) {
clearCache(key);
}
File imageCache = getTimelineImageFile(i);
// System.err.println("Deleting " + imageCache.getAbsolutePath());
imageCache.delete();
}
if (res == OperationResult.PRUNE) {
List<CaDoodleOperation> subList = (List<CaDoodleOperation>) getOpperations().subList(0, getCurrentIndex());
for (int i = getCurrentIndex(); i < getOpperations().size(); i++) {
getOpperations().get(i).pruneCleanup();
}
ArrayList<CaDoodleOperation> newList = new ArrayList<CaDoodleOperation>();
newList.addAll(subList);
setOpperations(newList);
com.neuronrobotics.sdk.common.Log.error("Pruning forward here!");
fireSaveSuggestion();
}
return res;
}
private void storeResultInCache(CaDoodleOperation op, List<CSG> process) {
ArrayList<CSG> cachedCopy = new ArrayList<CSG>();
HashSet<String> names = new HashSet<>();
for (CSG c : process) {
if (names.contains(c.getName()))
continue;
names.add(c.getName());
CSG cachedVer = cloneCSG(c).setStorage(new PropertyStorage()).syncProperties(getCsgDBinstance(), c)
.setName(c.getName()).setRegenerate(c.getRegenerate()).setID(c);
if (cachedVer.isHole() != c.isHole() || cachedVer.isHide() != c.isHide()) {
throw new RuntimeException("Lost properties");
}
cachedCopy.add(cachedVer);
// cachedCopy.add(c);
}
placeCSGsInCache(op, cachedCopy);
}
public static double getFreeMemory() {
Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory(); // Maximum memory the JVM will attempt to use
long totalMemory = runtime.totalMemory(); // Total memory currently allocated to the JVM
long freeMemory = runtime.freeMemory(); // Free memory within the allocated memory
long usedMemory = totalMemory - freeMemory; // Actually used memory
// Calculate the percentage of maximum memory that's currently being used
return (usedMemory * 100.0) / maxMemory;
}
private CSG cloneCSG(CSG dyingCSG) {
CSG csg = new CSG();
ArrayList<Polygon> collect = new ArrayList<Polygon>();
for (Polygon p : dyingCSG.getPolygons()) {
if (p == null)
continue;
try {
collect.add(p);
} catch (Exception ex) {
com.neuronrobotics.sdk.common.Log.error(ex);
;
}
}
csg.setPolygons(collect);
Set<String> params = dyingCSG.getParameters(getCsgDBinstance());
for (String param : params) {
boolean existing = false;
for (String s : csg.getParameters(getCsgDBinstance())) {
if (s.contentEquals(param))
existing = true;
}
if (!existing) {
Parameter vals = getCsgDBinstance().get(param);
if (vals != null)
csg.setParameter(getCsgDBinstance(), vals,
getCsgDBinstance().getMapOfparametrics(dyingCSG).get(param));
}
}
if (csg.getName().length() == 0)
csg.setName(dyingCSG.getName());
csg.setColor(dyingCSG.getColor());
return csg;
}
public void back() {
CaDoodleOperation op = getCurrentOpperation();
if (isBackAvailible())
setCurrentIndex(getCurrentIndex() - 1);
updateCurrentFromCache();
if (ICadoodleOperationUndo.class.isInstance(op)) {
ICadoodleOperationUndo un = (ICadoodleOperationUndo) op;
un.undo();
}
fireSaveSuggestion();
}
public void forward() {
if (isForwardAvailible())
setCurrentIndex(getCurrentIndex() + 1);
updateCurrentFromCache();
CaDoodleOperation op = getCurrentOpperation();
if (ICadoodleOperationUndo.class.isInstance(op)) {
ICadoodleOperationUndo un = (ICadoodleOperationUndo) op;
un.redo();
}
fireSaveSuggestion();
}
public void moveToOpIndex(int newIndex) {
if (newIndex > getOpperations().size())
return;
if (newIndex < 0)
return;
int ci = getCurrentIndex();
int ni = newIndex + 1;
boolean forward = ci < ni;
if (forward) {
for (int i = ci; i < ni + 1; i++) {
try {
CaDoodleOperation op = opperations.get(i - 1);
if (ICadoodleOperationUndo.class.isInstance(op)) {
ICadoodleOperationUndo un = (ICadoodleOperationUndo) op;
un.redo();
}
} catch (Exception ex) {
Log.error(ex);
}
}
} else {
for (int i = ni; i < ci + 1; i++) {
CaDoodleOperation op = opperations.get(i - 1);
if (ICadoodleOperationUndo.class.isInstance(op)) {
ICadoodleOperationUndo un = (ICadoodleOperationUndo) op;
un.undo();
}
}
}
setCurrentIndex(ni);
updateCurrentFromCache();
fireSaveSuggestion();
}
public boolean isBackAvailible() {
return getCurrentIndex() > 1;
}
private void updateCurrentFromCache() {
CaDoodleOperation key = getCurrentOpperation();
if (key == null)
return;
com.neuronrobotics.sdk.common.Log.debug("Current opperation results: " + key.getType());
setCurrentState(key, getCurrentState());
}
public CaDoodleOperation getCurrentOpperation() {
if (getCurrentIndex() == 0)
return null;
return getOpperations().get(getCurrentIndex() - 1);
}
public boolean isForwardAvailible() {
return getCurrentIndex() < getOpperations().size();
}
public File getSelf() {
if (self == null) {
try {
self = File.createTempFile(DownloadManager.sanitizeString(getMyProjectName()), ".doodle");
} catch (IOException e) {
// Auto-generated catch block
com.neuronrobotics.sdk.common.Log.error(e);
}
}
return self;
}
public CaDoodleFile setSelf(File self) {
this.self = self.getAbsoluteFile();
return this;
}
public List<CSG> getCurrentState() {
return getStateAtOperation(getCurrentOpperation());
}
public List<CSG> getStateAtOperation(CaDoodleOperation op) {
if (getCurrentIndex() == 0)
return new ArrayList<CSG>();
List<CSG> list = getCachedCSGs(op);
if (list == null)
list = new ArrayList<CSG>();
return list;
}
public List<CSG> getSelect(List<String> selectedSnapshot) {
List<CSG> cur = getCurrentState();
ArrayList<CSG> back = new ArrayList<CSG>();
if (cur != null)
for (CSG c : cur) {
for (String s : selectedSnapshot) {
if (c.getName().contentEquals(s)) {
back.add(c);
}
}
}
return back;
}
public List<CSG> getPreviouState() {
if (getCurrentIndex() < 2)
return new ArrayList<CSG>();
CaDoodleOperation key = getOpperations().get(getCurrentIndex() - 2);
return getCachedCSGs(key);
}
private void setCurrentState(CaDoodleOperation op, List<CSG> currentState) {
for (ICaDoodleStateUpdate l : listeners) {
try {
l.onUpdate(currentState, op, this);
} catch (Throwable e) {
com.neuronrobotics.sdk.common.Log.error(e);
}
}
}
private void fireSaveSuggestion() {
for (ICaDoodleStateUpdate l : listeners) {
try {
l.onSaveSuggestion();
} catch (Throwable e) {
com.neuronrobotics.sdk.common.Log.error(e);
}
}
}