-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpixelrealm.pde
executable file
·7284 lines (5935 loc) · 251 KB
/
pixelrealm.pde
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
import java.util.concurrent.atomic.AtomicBoolean;
import java.io.BufferedInputStream;
import java.nio.file.attribute.*;
import java.nio.file.*;
import java.util.ListIterator;
import java.util.Iterator;
import java.io.RandomAccessFile;
// ---- The Pixel Realm screen -----
// Your folders are realms, your hard drive is a universe.
//
// There are two parts to it:
// - The screen which contains things like the canvas, default textures, constants, and basically
// anything that doesn't rely on a single state.
// - The specific state of the realm e.g. the files in the realm, the sky/terrain/grass textures,
// the player's positions. You know. All of the important stuff.
public class PixelRealm extends Screen {
// Constants and stuff
final static String COMPATIBILITY_VERSION = "2.1";
final static String SHORTCUT_COMPATIBILITY_VERSION = "1.0";
final static String QUICK_WARP_DATASET = "quick_warp_dataset"; // The name of this really doesn't matter as long as it's consistant when quick warping
final static String QUICK_WARP_ID = "quick_warp_id"; // Name doesn't matter as long as it doesnt change.
final static float PSHAPE_SIZE_FACTOR = 100.;
final static int MAX_CACHE_SIZE = 512;
final static float BACKWARD_COMPAT_SCALE = 256./(float)MAX_CACHE_SIZE;
final static int MAX_MEM_USAGE = 1024*1024*1024; // 1GB
int DISPLAY_SCALE = 4;
final static int FOLDER_SIZE_LIMIT = 500; // If a folder has over this number of files, moving is restricted to prevent any potentially dangerous data moves.
final static float MIN_PORTAL_LIGHT_THRESHOLD = 19600.; // 140 ^ 2
final static int CHUNK_SIZE = 8;
final static int MAX_CHUNKS_XZ = 32768;
final static int MAX_VIDEOS_ALLOWED = 0;
final static String BREADCRUMBS_PATH = "history.txt";
// Movement/player constants.
final static float BOB_SPEED = 0.4;
final static float WALK_ACCELERATION = 5.;
final static float RUN_SPEED = 10.0;
final static float RUN_ACCELERATION = 0.1;
final static float MAX_SPEED = 30.;
final static float UNDERWATER_SPEED_MULTIPLIER = 0.4;
final static float SNEAK_SPEED = 1.5;
final static float TURN_SPEED = 0.05;
final static float MEDIUM_TURN_SPEED = 0.03;
final static float SLOW_TURN_SPEED = 0.01;
final static float TERMINAL_VEL = 30.;
final static float GRAVITY = 0.4;
final static float UNDERWATER_GRAVITY = 0.1;
final static float JUMP_STRENGTH = 8.;
final static float UNDERWATER_JUMP_STRENGTH = 4.;
final static float PLAYER_HEIGHT = 80;
final static float PLAYER_WIDTH = 20;
final static float UNDERWATER_TEMINAL_VEL = 3.0;
final static float SWIM_UP_SPEED = 0.8;
final static float SLIP_THRESHOLD = 2.5;
// Tool constants
protected final static int TOOL_NORMAL = 1;
protected final static int TOOL_GRABBER = 2;
protected final static int TOOL_MORPHER = 3;
// Morpher
protected final static int MORPHER_BULGE = 1;
protected final static int MORPHER_FLAT = 2;
protected final static int MORPHER_BLOCK = 3;
protected final static int MORPHER_PIT = 4;
protected final static int MORPHER_RESTORE = 5;
// For API
public final int MODE_PRESCENE = 1;
public final int MODE_SCENE = 2;
public final int MODE_POSTSCENE = 3;
public final int MODE_UI = 4;
protected int apiMode = 1;
// File names without an extension accept various file types (png, jpeg, gif)
public final static String REALM_GRASS = ".pixelrealm-grass";
public final static String REALM_SKY = ".pixelrealm-sky";
public final static String REALM_TREE_LEGACY = ".pixelrealm-terrain_object";
public final static String REALM_TREE = ".pixelrealm-tree";
public final static String REALM_BGM = ".pixelrealm-bgm";
public final static String REALM_TURF = ".pixelrealm-turf.json";
public final static String REALM_BGM_DEFAULT = "engine/music/pixelrealm_default_bgm.wav";
public final static String REALM_PLUGIN = ".pixelrealm-plugin.java";
// Defaults (Loaded on constructor)
private PImage REALM_GRASS_DEFAULT;
private PImage REALM_SKY_DEFAULT;
private PImage REALM_TREE_DEFAULT;
private PShape CASSETTE_OBJ;
// --- Cache (sort of) ---
private float cache_flatSinDirection;
private float cache_flatCosDirection;
private float cache_playerSinDirection;
private float cache_playerCosDirection;
private boolean primaryAction = false;
private boolean secondaryAction = false;
private boolean realmCaching = false;
private boolean usingFadeShader = false;
private RealmTexture IMG_COIN;
private int drawnEntries = 0;
private int entriesTotal = 0;
private int timeInRealm = 0;
private float timeNotMoving = 0.;
//protected HashMap<Integer, PVector> tilesCache = new HashMap<Integer, PVector>();
private float lastXBlockGetHeightAction = 0.;
private float lastZBlockGetHeightAction = 0.;
private boolean playingWarpingSound = false;
// --- Legacy backward-compatibility stuff & easter eggs ---
protected float height = HEIGHT-myUpperBarWeight-myLowerBarWeight;
private PGraphics legacy_portal;
private boolean legacy_portalEasteregg = false;
private float coinCounterBounce = 0.;
public PImage REALM_GRASS_DEFAULT_LEGACY;
public PImage REALM_SKY_DEFAULT_LEGACY;
public PImage REALM_TREE_DEFAULT_LEGACY;
public final static String REALM_BGM_DEFAULT_LEGACY = "engine/music/pixelrealm_default_bgm_legacy.wav";
// --- Global state and working variables (doesn't require per-realm states) ---
private PGraphics scene;
private float runAcceleration = 0.;
private float bob = 0.0;
private float jumpTimeout = 0;
private float coyoteJump = 0.;
private boolean showExperimentalGifs = false;
private boolean finderEnabled = false; // Maybe this could be part of Pixel Realm state?
protected boolean launchWhenPlaced = false;
protected int currentTool = TOOL_NORMAL;
protected int subTool = 0;
private boolean isWalking = false;
public boolean movementPaused = false;
protected float portalLight = 255.;
protected boolean isInWater = false;
protected boolean isUnderwater = false;
private float portalCoolDown = 45;
protected boolean usePortalAllowed = true;
protected boolean modifyTerrain = false;
protected int nodeSound = 0;
private boolean drawEntryOnce = true;
protected float morpherRadius = 150.;
protected float morpherBlockHeight = 0.;
protected float fovx = PI/3.0;
protected float fovy = 0.;
private int slippingJumpsAllowed = 2;
private ArrayList<String> realmBreadcrumbs = new ArrayList<String>();
private int breadcrumbIndex = 0;
protected PixelRealmState.PRObject optionHighlightedItem = null;
private boolean loadFromCache = false;
protected String cassettePlaying = ""; // Empty string for realm bgm.
private AtomicBoolean refreshRealm = new AtomicBoolean(false);
private AtomicInteger refresherCommand = new AtomicInteger(0);
// 0 means no command.
public static final int REFRESHER_PAUSE = 1; // Force pauses for 100ms. This allows us to update the list.
public static final int REFRESHER_TERMINATE = 2; // Stops and kills the thread.
public static final int REFRESHER_RESTART = 3; // Tells the thread to refresh its lastmodified list, use this when you're switching realms to prevent an unintended realm refresh.
public static final int REFRESHER_LONGPAUSE = 4;
public static final int REFRESHER_EXITLONGPAUSE = 5;
// TODO: Animationtick not required with display.getTime()?
private float animationTick = 0.;
// Inventory//pocket
protected LinkedList<PocketItem> pockets = new LinkedList<PocketItem>();
protected LinkedList<PocketItem> hotbar = new LinkedList<PocketItem>(); // Items in hotbar are also in inventory.
protected HashSet<String> pocketItemNames = new HashSet<String>();
protected PocketItem globalHoldingObject = null;
protected ItemSlot<PocketItem> globalHoldingObjectSlot = null;
// Debug-based variables.
@SuppressWarnings("unused")
private int operationCount = 0;
// Memory protection (TODO: Move to engine)
private AtomicInteger memUsage = new AtomicInteger(0);
private boolean memExceeded = false;
private boolean showMemUsage = false;
private int loading = 0;
private int MAX_LOADER_THREADS;
private AtomicInteger loadThreadsUsed = new AtomicInteger(0);
private ArrayList<AtomicBoolean> loadQueue = new ArrayList<AtomicBoolean>();
// --- Pixel realm state ---
protected PixelRealmState currRealm = null;
private PixelRealmState[] quickWarpRealms = new PixelRealmState[10];
private int quickWarpIndex = 1; // 1 because we start from 1 on our keyboard
private PixelRealmState prevRealm = null; // For caching and to use the backspace button
// --- Our constructors ---
// Remember, these are for the screen which does NOT rely on per-realm states.
// i.e. canvas creation, asset loading etc should only be done ONCE.
public PixelRealm(TWEngine engine, String dir) {
super(engine);
// --- Load default assets ---
// TODO (eventually): load screen's assets, not everything from the loading screen (even tho that would be a minor optimisation)
// (get rid of the . at the start cus hidden files are no good)
REALM_SKY_DEFAULT = display.systemImages.get("pixelrealm-sky");
REALM_TREE_DEFAULT = display.systemImages.get("pixelrealm-terrain_object");
REALM_GRASS_DEFAULT = display.systemImages.get("pixelrealm-grass");
CASSETTE_OBJ = app.loadShape(engine.APPPATH+"engine/other/cassette.obj");
REALM_SKY_DEFAULT_LEGACY = display.systemImages.get("pixelrealm-sky-legacy");
REALM_TREE_DEFAULT_LEGACY = display.systemImages.get("pixelrealm-terrain_object-legacy");
REALM_GRASS_DEFAULT_LEGACY = display.systemImages.get("pixelrealm-grass-legacy");
String[] COINS = { "coin_0", "coin_1", "coin_2", "coin_3", "coin_4", "coin_5"};
IMG_COIN = new RealmTexture(COINS);
// --- Sounds and music ---
sound.loopSound("portal");
sound.setSoundVolume("underwater", 0.);
sound.loopSound("underwater");
// --- Create graphics canvas ---
// Disable texture filtering
scene = createGraphics((int(WIDTH/DISPLAY_SCALE)), int(this.height/DISPLAY_SCALE), P3D);
((PGraphicsOpenGL)scene).textureSampling(2);
scene.hint(DISABLE_OPENGL_ERRORS);
fovy = (float)scene.width/scene.height;
// Only set up legacy portal when we go into the easter egg.
// TODO: re-add. Or most likely remove it :(
//setupLegacyPortal();
// TODO: I'd love to do a performance benchmark based on the number of cores we're using.
int numCores = Runtime.getRuntime().availableProcessors();
// We want to reserve at least one core to run the main thread otherwise it's gonna be REALLY laggy as the
// OS scheduler dedicates all of its processing resources to loading images.
MAX_LOADER_THREADS = (numCores/2)-1;
console.info("# cores reserved for loading: "+MAX_LOADER_THREADS);
String startRealm = file.directorify(file.getPrevDir(dir));
// Start the refresher thread (to automatically refresh realms when files have been changed)
refresherFilesList[0] = startRealm;
startRefresherThread();
// Load the breadcrumbs/history
if (file.exists(engine.APPPATH+BREADCRUMBS_PATH)) {
String[] history = app.loadStrings(engine.APPPATH+BREADCRUMBS_PATH);
for (String s : history) {
realmBreadcrumbs.add(s);
}
}
currRealm = new PixelRealmState(dir, startRealm);
sound.streamMusicWithFade(currRealm.musicPath);
}
public PixelRealm(TWEngine engine) {
this(engine, engine.DEFAULT_DIR);
}
// Classes we need
class RealmTexture {
private PImage singleImg = null;
private PImage[] aniImg = null;
private final static float ANIMATION_INTERVAL = 10.;
public float width = 0;
public float height = 0;
public RealmTexture() {
// Nothing
}
public RealmTexture(PImage img) {
set(img);
}
public void set(PImage img) {
if (img == null) {
console.bugWarn("set: passing a null image");
singleImg = display.systemImages.get("white");
width = singleImg.width;
height = singleImg.height;
return;
}
singleImg = img;
aniImg = null;
width = singleImg.width;
height = singleImg.height;
}
public RealmTexture(PImage[] imgs) {
set(imgs);
}
public void set(PImage[] imgs) {
if (imgs.length == 0) {
console.bugWarn("set PImage[]: passing an empty list");
singleImg = display.systemImages.get("white");
width = singleImg.width;
height = singleImg.height;
return;
}
else if (imgs.length == 1) {
singleImg = imgs[0];
width = imgs[0].width;
height = imgs[0].height;
return;
}
singleImg = null;
aniImg = new PImage[imgs.length];
int i = 0;
for (PImage p : imgs) {
aniImg[i++] = p;
}
width = aniImg[0].width;
height = aniImg[0].height;
}
public RealmTexture(ArrayList<PImage> imgs) {
set(imgs);
}
public void set(ArrayList<PImage> imgs) {
if (imgs.size() == 0) {
console.bugWarn("set ArrayList: passing an empty list");
singleImg = display.systemImages.get("white");
return;
}
else if (imgs.size() == 1) {
singleImg = imgs.get(0);
width = singleImg.width;
height = singleImg.height;
return;
}
singleImg = null;
aniImg = new PImage[imgs.size()];
int i = 0;
for (PImage p : imgs) {
aniImg[i++] = p;
}
width = aniImg[0].width;
height = aniImg[0].height;
}
public RealmTexture(String[] imgs) {
set(imgs);
}
public void set(String[] imgs) {
if (imgs.length == 0) {
console.bugWarn("set String[]: passing an empty list");
singleImg = display.systemImages.get("white");
return;
}
else if (imgs.length == 1) {
singleImg = display.systemImages.get(imgs[0]);
width = singleImg.width;
height = singleImg.height;
return;
}
singleImg = null;
aniImg = new PImage[imgs.length];
int i = 0;
for (String s : imgs) {
aniImg[i++] = display.systemImages.get(s);
}
width = aniImg[0].width;
height = aniImg[0].height;
}
public RealmTexture(String imgName) {
singleImg = display.systemImages.get(imgName);
}
public int length() {
if (singleImg != null) return 1;
else if (aniImg != null) return aniImg.length;
else return 1;
}
public PImage get(int index) {
if (singleImg != null) {
width = singleImg.width;
height = singleImg.height;
return singleImg;
}
else if (aniImg != null) {
width = aniImg[0].width;
height = aniImg[0].height;
return aniImg[index%aniImg.length];
}
else {
return display.errorImg;
}
}
public PImage get() {
return this.get(int(animationTick/ANIMATION_INTERVAL));
}
public PImage getRandom() {
return this.get(int(app.random(0., aniImg.length)));
}
public PImage getRandom(float seed) {
PImage p;
if (aniImg != null) {
p = this.get(int( engine.noise(seed) * float(aniImg.length) * 3.)%aniImg.length);
}
else {
p = this.get();
}
width = p.width;
height = p.height;
return p;
}
}
// We need some linkedlist functionality
// --- Linked list stuff ---
class ItemSlot<T> {
public ItemSlot next = null;
public ItemSlot prev = null;
public T carrying = null;
public float val = 0.;
public ItemSlot(T o) {
this.carrying = o;
}
//public void remove() {
// if (this == head)
// head = this.next;
// if (this == tail)
// tail = this.prev;
// if (this == inventorySelectedItem) {
// inventorySelectedItem = this.prev;
// if (inventorySelectedItem == null)
// inventorySelectedItem = this.next;
// // Will be null as intended if next is null too.
// // i.e., the item just removed happens to be the last item in the inventory.
// }
// if (this.prev != null)
// this.prev.next = this.next;
// if (this.next != null)
// this.next.prev = this.prev;
//}
//public void addAfterMe(ItemSlot newNode) {
// ItemSlot prev = this;
// ItemSlot next = this.next;
// newNode.next = next;
// newNode.prev = prev;
// if (next != null) next.prev = newNode;
// prev.next = newNode;
// if (this == tail) {
// tail = prev;
// }
//}
//public void addEnd() {
// if (head == null) {
// head = this;
// tail = this;
// head.prev = null;
// tail.next = null;
// inventorySelectedItem = this;
// } else {
// //add newNode to the end of list. tail->next set to newNode
// tail.next = this;
// //newNode->previous set to tail
// this.prev = tail;
// //newNode becomes new tail
// tail = this;
// //tail's next point to null
// tail.next = null;
// }
// inventorySelectedItem = this;
//}
}
class LinkedList<T> implements Iterable<T> {
public ItemSlot<T> head = null;
public ItemSlot<T> tail = null;
public ItemSlot<T> inventorySelectedItem = null;
public Iterator<T> iterator() {
ArrayList<T> ll = new ArrayList<T>();
itCurr = head;
ItemSlot<T> n = head;
int counter = 0;
while (n != null) {
ll.add(n.carrying);
n = n.next;
// Safety check
counter++;
if (counter > 5000000) {
// Hard to recover from.
// We don't really have a choice but to crash the program at this point
throw new RuntimeException("A fatal linkedlist bug occured. Program self-crashed to save your computer from exploding.");
}
}
return ll.iterator();
}
ItemSlot itCurr = null;
//public T next() {
// ItemSlot tmp = itCurr;
// itCurr = itCurr.next;
// return tmp.carrying;
//}
//public boolean hasNext() {
// return itCurr != null;
//}
public ItemSlot add(T o) {
ItemSlot node = new ItemSlot(o);
this.add(node);
return node;
}
public ItemSlot add(ItemSlot node) {
if (head == null) {
head = tail = node;
head.prev = null;
tail.next = null;
} else {
//add newNode to the end of list. tail->next set to newNode
tail.next = node;
//newNode->previous set to tail
node.prev = tail;
//newNode becomes new tail
tail = node;
//tail's next point to null
tail.next = null;
}
return node;
}
public ItemSlot remove(ItemSlot node) {
if (node == head)
head = node.next;
if (node == tail)
tail = node.prev;
if (node.prev != null)
node.prev.next = node.next;
if (node.next != null)
node.next.prev = node.prev;
// Object should be dereferenced now.
return node;
}
public void insertionSort() {
operationCount = 0;
if (head == null || head.next == null) {
return; // List is empty or has only one element, so it is already sorted
}
ItemSlot current = head.next; // Node to be inserted into the sorted portion
while (current != null) {
ItemSlot nextNode = current.next; // Store the next node before modifying current.next
boolean run = true;
while (current.prev != null && run) {
operationCount++;
if (current.prev.val < current.val) {
// Swap them.
ItemSlot previous = current.prev;
ItemSlot next = current.next;
previous.next = next;
current.prev = previous.prev;
current.next = previous;
if (previous.prev != null) {
previous.prev.next = current;
}
previous.prev = current;
if (next != null) {
next.prev = previous;
}
if (head == previous) {
head = current;
}
if (tail == current) {
tail = previous;
}
} else run = false;
}
current = nextNode; // Move to the next node
}
if (head == null) console.bugWarn("Null head!");
if (tail == null) console.bugWarn("Null tail!");
}
}
protected class PocketItem {
public String name = "";
// Abstract objects are PRObjects (most likely fileobjects) that aren't actually files on computers.
// Non-abstract if it is null
public PixelRealmState.PRObject item = null;
public boolean abstractObject = false;
// Inventory is stored in folder in files.
public boolean syncd = false;
public boolean isDuplicate = false;
public PocketItem(String name, PixelRealmState.PRObject item, boolean abstractObject) {
this.name = name;
this.abstractObject = abstractObject;
this.item = item;
// If there's a duplicate, it's ok for the time being,
// but if we exit the realm and try to sync the duplicate item,
// throw a big fat error.
if (pocketItemNames.contains(name)) {
isDuplicate = true;
}
}
// This method is called when we change realms
// any item that's in the inventory but not sync'd must be moved to the inventory.
// Returns true if successful.
// If unsuccessful, the change realm operation must be terminated if even one item
// returns false on this method.
// Any file changes (e.g. mv to inventory) won't affect things.
// This method handles specific-error cases using the upper pixelrealm_ui class.
public boolean changeRealm(String fro) {
fro = file.directorify(fro);
// Can't move abstract objects.
if (abstractObject) {
promptMoveAbstractObject(name);
return false;
}
// Safety measure: can't move back certain files.
// TODO
if (!syncd) {
// Can't move files that have the same filename as another file
// in the pocket.
if (isDuplicate) {
promptPocketConflict(name);
return false;
}
// Can't move directoryPortals with over a certain limit of files.
if (item instanceof PixelRealmState.DirectoryPortal) {
PixelRealmState.DirectoryPortal p = (PixelRealmState.DirectoryPortal)item;
if (file.countFiles(p.dir) > FOLDER_SIZE_LIMIT) {
prompt("Folder size limit", name+" has over "+str(FOLDER_SIZE_LIMIT)+" files in it. As a safety precaution, "+engine.getAppName()+" won't move large folders.", 20);
return false;
}
}
boolean success = file.mv(fro+name, engine.APPPATH+engine.POCKET_PATH+name);
if (!success) {
//console.warn("failed to move");
//console.warn("to: "+engine.APPPATH+engine.POCKET_PATH+name);
//console.warn("fro: "+fro+name);
promptFailedToMove(name);
return false;
}
// At this point, the file should be moved therefore it is now sync'd with the memory
// as we move realms.
this.syncd = true;
}
return true;
}
}
// Overridden by the upper pixelrealm_ui class.
@SuppressWarnings("unused")
protected void promptPocketConflict(String filename) {}
@SuppressWarnings("unused")
protected void promptFileConflict(String filename) {}
@SuppressWarnings("unused")
protected void promptMoveAbstractObject(String filename) {}
@SuppressWarnings("unused")
protected void promptFailedToMove(String filename) {}
protected void promptNewRealm() {}
protected void promptPickedUpItem() {}
protected void promptPlonkedDownItem() {}
@SuppressWarnings("unused")
protected void promptFileOptions(PixelRealmState.FileObject probject) {}
@SuppressWarnings("unused")
protected void prompt(String title, String text, int appearDelay) {}
@SuppressWarnings("unused")
protected void prompt(String title, String text) {}
private Thread refresherThread;
protected boolean cassettePlaying() {
return !cassettePlaying.equals("");
}
// Use by the refresher thread only, to check each file to see if it's been refreshed, and if so,
// signal a file change.
// NOTE: While programming this, I was originally going to check each file's lastmodified date, only to realise
// if I check the DIRECTORY's lastmodfied date, this would be way more efficient, and thus eliminating the need
// for a list, since I would only need to check one dir. But, imma keep it as a list, cus even if it's not used,
// its useful functionality in case I ever do need it.
private String[] refresherFilesList = new String[1];
protected void issueRefresherCommand(int cmd) {
refresherCommand.set(cmd);
refresherThread.interrupt();
}
private void startRefresherThread() {
refresherThread = new Thread(new Runnable() {
public void run() {
boolean active = true;
String[] mylist = new String[refresherFilesList.length];
boolean needsUpdate = true;
while (active) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
// When interrupted, this means we're issuing a command.
switch (refresherCommand.getAndSet(0)) {
case 0:
// Do nothing.
break;
case REFRESHER_PAUSE:
// Pause for 100ms.
try {
Thread.sleep(100);
}
catch (InterruptedException e2) {
// There really shouldn't be another command issued while in this state.
console.bugWarn("refresherThread: You're still issuing commands while paused! Slow down!");
}
// Then we need to update our lastmodified list.
needsUpdate = true;
break;
case REFRESHER_LONGPAUSE:
try {
// Wait until interrupt called.
Thread.sleep(99999999);
}
catch (InterruptedException e2) {
}
// Then we need to update our lastmodified list.
needsUpdate = true;
break;
case REFRESHER_TERMINATE:
console.log("REFRESHER_TERMINATE");
active = false;
break;
case REFRESHER_RESTART:
needsUpdate = true;
break;
}
}
// If a terminate command was issued.
if (!active) break;
if (needsUpdate) {
// Update the list.
mylist = new String[refresherFilesList.length];
for (int i = 0; i < refresherFilesList.length; i++) {
mylist[i] = file.getLastModified(refresherFilesList[i]);
}
needsUpdate = false;
}
else {
// Normal mode: we continously check for lastmodified changes.
for (int i = 0; i < refresherFilesList.length; i++) {
if (!mylist[i].equals(file.getLastModified(refresherFilesList[i]))) {
needsUpdate = true;
refreshRealm.set(true);
}
}
}
}
}
});
refresherThread.start();
}
// --- Pixel realm state ---
public class PixelRealmState {
public String stateDirectory;
public String stateFilename;
// --- Player state ---
// (1000, 0, 1000) is our default position (and it's imporant for shortcuts)
public float playerX = 1000.0, playerY = 0., playerZ = 1000.0;
public float prevPlayerX = 1000.0, prevPlayerY = 0., prevPlayerZ = 1000.0;
public float xvel = 0., yvel = 0., zvel = 0.;
public float direction = PApplet.PI;
private float lastPlacedPosX = 0;
private float lastPlacedPosZ = 0;
private float exitPortalX = 0;
private float exitPortalZ = 0;
// Whenever we switch realms, we need to make sure this is being updated with the global
// state!
public PRObject holdingObject = null;
// --- Realm textures & state ---
// Initially defaults, gets loaded with realm-specific files (if exists) later.
public RealmTexture img_grass = new RealmTexture(REALM_GRASS_DEFAULT);
public RealmTexture img_tree = new RealmTexture(REALM_TREE_DEFAULT);
public RealmTexture img_sky = new RealmTexture(REALM_SKY_DEFAULT);
protected TerrainAttributes terrain;
private DirectoryPortal exitPortal = null;
private String musicPath = engine.APPPATH+REALM_BGM_DEFAULT;
private boolean loadMinimal = false;
private TWEngine.PluginModule.Plugin realmPlugin;
public String realmPluginPath = "";
private AtomicBoolean successfulCompile = new AtomicBoolean();
private AtomicBoolean pluginCompiled = new AtomicBoolean();
private boolean showDebugMessageOnce = true;
public HashMap<Integer, TerrainChunkV2> chunks = new HashMap<Integer, TerrainChunkV2>();
public String version = COMPATIBILITY_VERSION;
public int versionCompatibility = 2;
// --- Legacy stuff for backward compatibility ---
private Stack<PixelRealmState.PRObject> legacy_terrainObjects;
public HashSet<String> legacy_autogenStuff;
public boolean lights = false;
public int collectedCoins = 0;
public boolean coins = false;
private boolean createdCoins = false;
public boolean terraformWarning = true;
// All objects that are visible on the scene, their interactable actions are run.
protected LinkedList<PRObject> ordering = new LinkedList<PRObject>();
// Not necessary lists here, just useful and faster.
protected LinkedList<FileObject> files = new LinkedList<FileObject>();
protected LinkedList<PRObject> pocketObjects = new LinkedList<PRObject>();
public ArrayList<CustomNode> lightingUINodes = new ArrayList<CustomNode>();
public CustomSlider ambientSlider;
public CustomSlider reffectSlider;
public CustomSlider geffectSlider;
public CustomSlider beffectSlider;
public CustomSliderInt lightDirectionSlider;
public CustomSliderInt lightHeightSlider;
final int[] lightDirectionsX = { -2, -1, 0, 1, 2, 2, 2, 2, 2, 1, 0, -1, -2, -2, -2, -2 };
final int[] lightDirectionsZ = { -2, -2, -2, -2, -2, -1, 0, 1, 2, 2, 2, 2, 2, 1, 0, -1 };
// --- Constructor ---
public PixelRealmState(String dir) {
this.stateDirectory = file.directorify(dir);
this.stateFilename = file.getFilename(stateDirectory);
populateLightingUINodes();
loadMinimal = false;
if (isNewRealm()) promptNewRealm();
// Load realm emerging from our exit portal.
loadRealm();
// For backwards compatibility (just set version = "1.0")
if (version.equals("1.0") || version.equals("1.1")) {
legacy_terrainObjects = new Stack<PRObject>(int(((terrain.getRenderDistance()+5)*2)*((terrain.getRenderDistance()+5)*2)));
legacy_autogenStuff = new HashSet<String>();
engine.noiseSeed(getHash(dir));
}
if (!loadMinimal) {
stats.increase("REALMVISITED_"+stateFilename, 1);
}
}
public PixelRealmState(String dir, String emergeFrom) {
this(dir);
emergeFromPortal(file.directorify(emergeFrom));
}
public abstract class CustomNode {
public String label = "";
public float x = 0.;
public float wi = 100.;
private float y = 0;
public int sound = 0;
public float valFloat = 0.;
public boolean valBool = false;
public int valInt = 0;
public static final float CONTROL_X = 300.;
public CustomNode(String l) {
label = l;
}
public float getHeight() {
return 100.;
}
protected boolean inBox() {
boolean hovering = (engine.mouseX() > x+CONTROL_X-10 && engine.mouseY() > y && engine.mouseX() < x+wi+10 && engine.mouseY() < y+getHeight());
return hovering && !ui.miniMenuShown();
}
public boolean getValBool() {
return false;
}
public void display(float y) {
this.y = y;
y += 20;
app.fill(255);
app.textFont(engine.DEFAULT_FONT, 20);
app.textAlign(LEFT, CENTER);
app.text(label, x, y);
}
}
public class CustomSlider extends CustomNode {
public float min = 0.;
public float max = 100.;
protected String maxLabel = null;
protected String minLabel = null;
public CustomSlider(String l, float min, float max, float initVal, int s) {
super(l);
this.min = min;
this.max = max;
this.valFloat = initVal;
this.sound = s;
}
@Override
public float getHeight() {
return 40.;
}