forked from Elkwizard/SandSim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSandSim.js
6999 lines (6097 loc) · 224 KB
/
SandSim.js
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
const synth = new Synth();
let simFrameCount = 0;
title = "Sandulation";
document.getElementsByTagName("link")[0].href = "./favicon.ico";
const controls = {
"Touch/Click": "Draw with current brush",
"Up/Down Arrows": "Change brush size",
"</> & Left/Right Arrows": "Change brush type",
"p": "Toggle erase only",
"Space": "Pause/Play",
"Enter": "Advance one step while paused",
"s": "Open element selection window",
"d": "Save current world locally",
"u": "Reset most recently saved/loaded world",
"Shift + d": "Download current world to file",
"Shift + u": "Upload world from file",
"r": "Reset world",
"e": "Restore zoom",
"Shift + = & Mouse Wheel Up": "Zoom in",
"Shift + - & Mouse Wheel Down": "Zoom out",
"Shift + Arrow Keys & Control + Drag": "Move camera",
"Control + Click & Drag": "Move camera",
"g": "Toggle 'RTX'",
"a": "Animate Wall",
"v": "toggle debug view",
"n, m, & k": "(line brush) place, apply, clear (respectively)",
"t": "switch render view (normal, information, and ant views)"
};
canvas.clearScreen = () => renderer.fill(Color.BLACK);
const TYPES = Object.fromEntries([
"AIR",
"TEST", //"URANIUM", "ORANGEJUICE", "POWDER", "OXYGEN", "BURNING_BRICKS", "COPPER_BRICKS",
"THICKET_SEED", "THICKET", "THICKET_BUD", "THICKET_STEM", "INCENSE_SMOKE", "INCENSE",
"SUNFLOWER_PETAL", "SUNFLOWER_STEM", "SUNFLOWER_SEED", "TREE_SEED", "TREE_GENERATOR", "LEAVES",
"SOIL", "DAMP_SOIL", "ROOT", "GRASS", "FLOWER",
"HIGH_EXPLOSIVE", "EXPLOSIVE", "EXPLOSIVE_DUST", "FLASH_PAPER", "WET_PAPER",
"STONE", "CONDENSED_STONE", "MARBLE", "GRANITE", "MEDUSAS_GEM", "CARO_GEM",
"CLAY", "BRICK",
"TILE_BASE", "DECUMAN_TILE",
"GLAZE_BASE", "DECUMAN_GLAZE",
"PRIDIUM", "GENDERFLUID",
"PARTICLE",
"EXOTHERMIA", "FIRE", "BLUE_FIRE", "SPIRAL_FIRE", "BOUNCE_BEAM", "BOUNCE_GREEN_BEAM",
"BAHHUM", //"GREEK_FIRE",
"ESTIUM", "ESTIUM_GAS",
"DDT",
"ANT", "DAMSELFLY", "MINNOW", "MITE", "LIGHTNING_BUG", "BEE", "TERMITE", "ANT_HILL",
"HIVE", "HONEY", "SUGAR", "CARMEL",
"WATER", "WATER_VAPOR", "POND_WATER", "ICE", "SNOW", "STAINED_SNOW", "SALT", "SALT_WATER",
"SAND", "KELP", "KELP_TOP", "PNEUMATOCYST",
"COTTON", "DYED_COTTON",
"WOOD", "COAL", "OIL", "FUSE", "ASH",
"WAX", "GRAINY_WAX", "MOLTEN_WAX",
"LAVA", "POWER_LAVA", "GREEN_LAVA",
"STEAM", "SMOKE", "HYDROGEN",
"GLASS", "ACID", "UNSTABLE_ELEMENT", "SEMI_STABLE_ELEMENT", "GROUNDING_METAL", "POSITIVE_METAL", "CONDUCTIVE_FLUID", "BLUE_ELECTRICITY",
"BATTERY", "ELECTRICITY","GERMANIUM", "ACTIVE_GERMANIUM", "BOID",
"CONVEYOR_LEFT", "CONVEYOR_RIGHT", "STEEL",
"COPPER", "LIQUID_COPPER",
"LEAD", "LIQUID_LEAD",
"GOLD", "AUREATE_DUST", "LIQUID_GOLD", "MAGNESIUM", "MAGNESIUM_FIRE",
"IRON", "LIQUID_IRON", "RUST",
"MERCURY", "TERMINATOR",
"RADIUM", "RADIUM_GEM", "ACTINIUM", "THORIUM",
"ANTIMATTER",
"LIGHTNING", "LIGHT", "LIGHT_SAD", "BOUNCY_BALL", "CONWAY_ALIVE", "CONWAY_DEAD",
"BLOOD", "MUSCLE", "BONE", "BONE_DUST", "EPIDERMIS", "INACTIVE_NEURON", "ACTIVE_NEURON", "CEREBRUM",
"CORAL", "DEAD_CORAL", "ELDER_CORAL", "PETRIFIED_CORAL", "COMPRESSED_CORAL", "DEAD_COMPRESSED_CORAL",
"CORAL_STIMULANT", "CORAL_PRODUCER", "CORAL_CONSUMER", "GHOST_CORAL", "CORPOREAL_CORAL",
"FLUORESCENCE", "DORMANT_FLUORESCENCE", "SCREEN_WIPE"
].map((n, i) => [n, i]));
const ELEMENT_COUNT = Object.keys(TYPES).length;
class WorldSave {
static MAGIC_SAVE_CONSTANT_ELEMENT = 0xcc910831; // indicates elements are stored absolutely
static MAGIC_SAVE_CONSTANT_RIGIDBODY = 0xfebc1828;
constructor(grid, rigidbodies) {
this.grid = grid;
this.rigidbodies = rigidbodies;
}
static instantiateRigidbodies(bodies) {
for (let i = 0; i < bodies.length; i++) {
const body = bodies[i];
const obj = scene.main.addPhysicsElement("obj", 0, 0, true);
obj.transform.rotation = body.rotation;
obj.scripts.add(DYNAMIC_OBJECT, body.grid, body.upperLeft, Vector2.origin);
}
}
static getRigidbodies() {
return scene.main.getElementsWithScript(DYNAMIC_OBJECT)
.map(obj => {
const l = obj.scripts.DYNAMIC_OBJECT;
return {
rotation: obj.transform.rotation,
grid: l.grid.map(cell => cell.get()),
upperLeft: Vector2.floor(obj.transform.localSpaceToGlobalSpace(l.centerOfMass.inverse).over(CELL)).get()
};
});
}
toByteBuffer(buffer = new ByteBuffer()) {
buffer.write.uint32(WorldSave.MAGIC_SAVE_CONSTANT_RIGIDBODY);
buffer.write.object(TYPES);
buffer.write.uint32(this.grid.length);
buffer.write.uint32(this.grid[0].length);
let lId, lActs, lReference;
let duration = 0;
const writeBlock = () => {
if (duration) {
buffer.write.uint16(duration);
buffer.write.uint8(lId);
if (lId) {
buffer.write.uint8(lReference);
buffer.write.int32(lActs);
}
}
};
for (let i = 0; i < this.grid.length; i++) {
for (let j = 0; j < this.grid[0].length; j++) {
const { id, reference, acts } = this.grid[i][j];
//if A. the previouse block is not the same as the current block or
//B. the duration is larger than 16 bits
//then write a new line
if (lId !== id || lReference !== reference || lActs !== acts || duration === 0xFFFF) {
writeBlock();
lId = id;
lReference = reference;
lActs = acts;
duration = 1;
} else duration++;
}
}
writeBlock();
const dyn = this.rigidbodies;
buffer.write.uint32(dyn.length);
for (let i = 0; i < dyn.length; i++) {
const obj = dyn[i];
buffer.write.float64(obj.rotation);
obj.upperLeft.toByteBuffer(buffer);
buffer.write.uint32(obj.grid.length);
buffer.write.uint32(obj.grid[0].length);
for (let i = 0; i < obj.grid.length; i++) for (let j = 0; j < obj.grid[0].length; j++) {
const cell = obj.grid[i][j];
buffer.write.uint8(cell.id);
if (cell.id) {
buffer.write.uint8(cell.reference);
// buffer.write.unit16(cell.vel); //TODO add vel to save and load game
buffer.write.uint32(cell.acts);
}
}
}
return buffer;
}
static fromByteBuffer(buffer) {
let initial = buffer.read.uint32();
let width = initial;
let encodedTypes = TYPES;
if (
initial === WorldSave.MAGIC_SAVE_CONSTANT_ELEMENT ||
initial === WorldSave.MAGIC_SAVE_CONSTANT_RIGIDBODY
) {
encodedTypes = buffer.read.object();
width = buffer.read.uint32();
}
const height = buffer.read.uint32();
const idMap = [];
for (const element in encodedTypes)
idMap[encodedTypes[element]] = TYPES[element];
const save = new WorldSave(
Array.dim(width, height)
.map(() => new Cell(TYPES.AIR)),
[]
);
let totalCells = 0;
let x = 0, y = 0;
while (totalCells < width * height) {
const duration = buffer.read.uint16();
totalCells += duration;
const id = buffer.read.uint8();
if (id) {
const reference = buffer.read.uint8();
// const vel = buffer.read.unit16(); //TODO add vel to save and load game
const acts = buffer.read.int32();
for (let i = 0; i < duration; i++) {
const cell = save.grid[x][y];
cell.id = idMap[id];
cell.reference = idMap[reference];
// cell.vel = vel;
cell.acts = acts;
y++;
if (y === height) {
y = 0;
x++;
}
}
} else {
y += duration;
x += ~~(y / height);
y %= height;
continue;
}
}
if (initial === WorldSave.MAGIC_SAVE_CONSTANT_RIGIDBODY) {
const rigidbodyCount = buffer.read.uint32();
for (let i = 0; i < rigidbodyCount; i++) {
const obj = {};
obj.rotation = buffer.read.float64();
obj.upperLeft = Vector2.fromByteBuffer(buffer);
obj.grid = Array.dim(buffer.read.uint32(), buffer.read.uint32())
.map(() => new Cell(TYPES.AIR));
for (let i = 0; i < obj.grid.length; i++) for (let j = 0; j < obj.grid[0].length; j++) {
const cell = obj.grid[i][j];
cell.id = buffer.read.uint8();
if (cell.id) {
cell.reference = buffer.read.uint8();
cell.acts = buffer.read.uint32();
}
}
save.rigidbodies.push(obj);
}
}
return save;
}
}
const SAVE_FILE_PATH = "world.vand";
fileSystem.createFileType(WorldSave, ["sand", "vand"]);
class Cell {
constructor(id) {
this.id = id;
this.updated = false;
this.vel = Vector2.origin;
// delete this.vel.x;
// delete this.vel.y;
// let _x = 0, _y = 0;
// Object.defineProperties(this.vel, {
// x: {
// get: () => _x,
// set: a => _x = a
// },
// y: {
// get: () => _y,
// set: a => {
// if (this.id === TYPES.SMOKE && a) debugger;
// _y = a;
// }
// }
// });
this.acts = 0;
this.reference = 0;
}
get(result = new Cell()) {
result.id = this.id;
result.reference = this.reference;
result.acts = this.acts;
result.vel.set(this.vel);
return result;
}
sameType(cell) {
if (cell.id !== this.id) return false;
if (DATA[cell.id].reference && cell.reference !== this.reference) return false;
return true;
}
}
const CELL = 3;
const grid = Array.dim(width / CELL, height / CELL)
.map(() => new Cell(TYPES.AIR));
const WIDTH = grid.length;
const HEIGHT = grid[0].length;
class DYNAMIC_OBJECT extends ElementScript {
static RES = 2;
static SKIP = 20;
static DISTRIBUTION = 8;
static nextSlot = 0;
init(obj, grid, upperLeft, textureOffset) {
obj.scripts.removeDefault();
this.rb = obj.scripts.PHYSICS;
this.colors = new Map();
this.textureOffset = textureOffset ?? upperLeft.get();
obj.transform.position = upperLeft.times(CELL);
this.centerOfMass = Vector2.origin;
this.setGrid(grid, Vector2.origin);
this.slot = (DYNAMIC_OBJECT.nextSlot++) % DYNAMIC_OBJECT.DISTRIBUTION;
this.collidingObjects = new Map();
this.worryCells = new Set();
this.lastVelocity = Vector2.origin;
this.lastAngularVelocity = 0;
}
static computeCenterOfMass(grid) {
const centerOfMass = Vector2.origin;
let total = 0;
for (let i = 0; i < grid.length; i++) for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j].id) {
total++;
centerOfMass.x += i;
centerOfMass.y += j;
}
}
return centerOfMass.mul(CELL / total);
}
collideGeneral(obj, { element, contacts, direction }) {
if (!this.collidingObjects.get(element)) {
this.collidingObjects.set(element, 20);
const mass = element => element.scripts.PHYSICS.mobile ? element.scripts.PHYSICS.mass : 0;
const contactVelocity = (element, contact) => {
if (!element.scripts.DYNAMIC_OBJECT) return 0;
const { lastVelocity, lastAngularVelocity } = element.scripts.DYNAMIC_OBJECT;
return lastVelocity.plus(contact.minus(element.transform.position).normal.times(lastAngularVelocity)).dot(direction);
};
const m0 = mass(obj);
const m1 = mass(element);
const systemMass = m0 + m1;
let momentum = 0;
for (let i = 0; i < contacts.length; i++) {
const contact = contacts[i];
momentum += Math.abs(m0 * contactVelocity(obj, contact) - m1 * contactVelocity(element, contact));
}
// frequency scales with sqrt(mass)
// volume scales with momentum
// const frequency = 40 / (0.01 * Math.sqrt(systemMass));
// const volume = momentum * 0.0005;
// console.log(frequency, volume);
// if (volume > 1e-1) synth.play({
// duration: 10,
// frequency,
// volume,
// wave: "sine",
// fadeOut: 10
// });
}
}
setGrid(obj, grid, gridOffset) {
this.grid = grid;
obj.transform.position = obj.transform.localSpaceToGlobalSpace(this.centerOfMass.inverse);
this.centerOfMass = DYNAMIC_OBJECT.computeCenterOfMass(this.grid);
obj.transform.position = obj.transform.localSpaceToGlobalSpace(this.centerOfMass.plus(gridOffset));
this.width = this.grid.length;
this.height = this.grid[0].length;
this.gridBounds = new Rect(-this.centerOfMass.x, -this.centerOfMass.y, this.width * CELL, this.height * CELL);
this.smallGrid = Array.dim(
Math.ceil(this.width / DYNAMIC_OBJECT.RES),
Math.ceil(this.height / DYNAMIC_OBJECT.RES)
).fill(false);
this.skipGrid = Array.dim(
Math.floor(this.width / DYNAMIC_OBJECT.SKIP),
Math.floor(this.height / DYNAMIC_OBJECT.SKIP)
).map((_, x, y) => {
x *= DYNAMIC_OBJECT.SKIP;
y *= DYNAMIC_OBJECT.SKIP;
for (let i = 0; i < DYNAMIC_OBJECT.SKIP; i++)
for (let j = 0; j < DYNAMIC_OBJECT.SKIP; j++) {
if (this.grid[x + i][y + j].id)
return false;
}
return true;
});
for (let i = 0; i < this.width; i++) for (let j = 0; j < this.height; j++) {
const cell = this.grid[i][j];
if (cell.id && !this.colors.has(cell))
this.colors.set(cell, DATA[cell.id].getColor(
this.textureOffset.x + i,
this.textureOffset.y + j
).get());
}
}
explode(obj, ox, oy, r, vel) {
if (!obj.defaultShape) return;
const v = new Vector2(ox, oy).times(CELL);
const closest = obj.getModel("default").closestPointTo(v);
const diff = closest.minus(v);
if (diff.mag > r * CELL) return;
this.rb.applyImpulseMass(closest, diff.times(vel));
}
forEachCell(obj, fn) {
const { grid, skipGrid } = this;
const { SKIP } = DYNAMIC_OBJECT;
const gridBounds = this.gridBounds
.getModel(obj.transform)
.scaleAbout(Vector2.origin, 1 / CELL);
const bounds = gridBounds.getBoundingBox();
const globalMin = Vector2.origin;
const globalMax = new Vector2(WIDTH - 1, HEIGHT - 1);
const min = Vector2.clamp(Vector2.floor(bounds.min), globalMin, globalMax);
const max = Vector2.clamp(Vector2.ceil(bounds.max), globalMin, globalMax);
const c = Vector2.origin;
const local = Vector2.origin;
const toLocal = Matrix3.mulMatrices([
Matrix3.scale(1 / CELL),
Matrix3.translation(this.centerOfMass),
obj.transform.inverse,
Matrix3.scale(CELL)
]);
const localDY = new Vector2(toLocal.m01, toLocal.m11);
// border precomputing
const edges = gridBounds
.getEdges()
.sort((a, b) => a.middle.y - b.middle.y);
let topEdgeLeft = edges[0];
let topEdgeRight = edges[1];
if (topEdgeRight.middle.x < topEdgeLeft.middle.x)
[topEdgeLeft, topEdgeRight] = [topEdgeRight, topEdgeLeft];
let bottomEdgeLeft = edges[2];
let bottomEdgeRight = edges[3];
if (bottomEdgeRight.middle.x < bottomEdgeLeft.middle.x)
[bottomEdgeLeft, bottomEdgeRight] = [bottomEdgeRight, bottomEdgeLeft];
const topCutoff = topEdgeLeft.b.x;
const bottomCutoff = bottomEdgeLeft.a.x;
let top = topEdgeLeft;
let bottom = bottomEdgeLeft;
// skip grid precomputing
const angle = Geometry.normalizeAngle(obj.transform.rotation);
const skipRadius = SKIP * Math.SQRT1_2;
const modAngle = Math.PI / 4 + (angle % (Math.PI / 2));
const offAngle = Math.PI / 4 + angle;
const vertexOffsetX = (Math.cos(modAngle) + Math.cos(offAngle)) * skipRadius;
const vertexOffsetY = (Math.sin(modAngle) + Math.sin(offAngle)) * skipRadius;
const leftSkipSlope = Math.tan((angle % (Math.PI / 2)));
const rightSkipSlope = Math.tan((angle % (Math.PI / 2)) + Math.PI / 2);
const skipToVertex = Matrix3.mulMatrices([
Matrix3.translation(vertexOffsetX, vertexOffsetY),
toLocal.inverse,
Matrix3.scale(SKIP)
]);
const skip = Vector2.origin;
const vertex = Vector2.origin;
for (c.x = min.x; c.x <= max.x; c.x++) {
if (c.x > topCutoff) top = topEdgeRight;
if (c.x > bottomCutoff) bottom = bottomEdgeRight;
const minY = Math.max(Math.floor(top.evaluate(c.x)), min.y);
const maxY = Math.min(Math.ceil(bottom.evaluate(c.x)) - 1, max.y);
c.y = minY;
toLocal.times(c, local);
for (; c.y <= maxY; c.y++) {
local.add(localDY);
const lx = Math.floor(local.x);
const ly = Math.floor(local.y);
const cell = grid[lx]?.[ly];
if (cell?.id) fn(cell, c.x, c.y, lx, ly);
else {
skip.x = Math.floor(lx / SKIP);
skip.y = Math.floor(ly / SKIP);
if (skipGrid[skip.x]?.[skip.y]) {
skipToVertex.times(skip, vertex);
const slope = c.x > vertex.x ? rightSkipSlope : leftSkipSlope;
const intersectY = (c.x - vertex.x) * slope + vertex.y;
c.y = Math.floor(intersectY);
}
}
}
}
}
removeIfNecessary(obj) {
if ((obj.defaultShape && !obj.getBoundingBox().intersect(new Rect(0, 0, width, height))) || isNaN(obj.transform.position)) {
obj.remove();
return true;
}
return false;
}
inject(obj) {
if ((obj.defaultShape && !obj.getBoundingBox().intersect(new Rect(0, 0, width, height))) || isNaN(obj.transform.position)) {
obj.remove();
return;
}
this.forEachCell((cell, x, y) => {
const c = grid[x][y];
if (c.id && !STATIC_SOLID.has(c.id))
createParticle(new Vector2(x, y), new Vector2(Random.range(-1, 1), Random.range(-1, 1)));
cell.get(c);
Element.updateCell(x, y);
});
}
extract(obj) {
this.forEachCell((cell, x, y) => {
if (grid[x][y].sameType(cell)) {
Element.die(x, y);
tex.shaderSetPixel(x, y, this.colors.get(cell));
} else cell.id = TYPES.AIR;
});
tex.loaded = false;
const { defaultShape } = obj;
for (let i = 0; i < this.width; i += DYNAMIC_OBJECT.RES)
for (let j = 0; j < this.height; j += DYNAMIC_OBJECT.RES) {
const sx = ~~(i / DYNAMIC_OBJECT.RES);
const sy = ~~(j / DYNAMIC_OBJECT.RES);
this.smallGrid[sx][sy] = this.grid[i][j].id !== TYPES.AIR;
}
const extractSubGrid = shape => {
const bounds = shape.getBoundingBox();
const grid = Array.dim(
Math.ceil(1 + bounds.width) * DYNAMIC_OBJECT.RES,
Math.ceil(1 + bounds.height) * DYNAMIC_OBJECT.RES
).map(() => new Cell(TYPES.AIR));
let {
xRange: { min: minX, max: maxX },
yRange: { min: minY, max: maxY }
} = bounds;
minX = Math.floor(minX);
minY = Math.floor(minY);
maxX = Math.ceil(maxX) + 1;
maxY = Math.ceil(maxY) + 1;
const minCellX = minX * DYNAMIC_OBJECT.RES;
const minCellY = minY * DYNAMIC_OBJECT.RES;
const edges = shape.getEdges()
.filter(edge => edge.a.x !== edge.b.x);
for (let i = minX; i <= maxX; i++) {
const stops = edges
.filter(edge => edge.a.x > edge.b.x ? edge.b.x <= i && i < edge.a.x : edge.a.x <= i && i < edge.b.x)
.map(edge => edge.a.y === edge.b.y ? edge.a.y : edge.evaluate(i))
.sort((a, b) => a - b);
for (let n = 0; n < stops.length; n += 2) {
const startY = Math.max(minY, Math.floor(stops[n]) - 1);
const endY = Math.ceil(stops[n + 1]);
for (let j = startY; j <= endY; j++) {
for (let ii = 0; ii < DYNAMIC_OBJECT.RES; ii++)
for (let jj = 0; jj < DYNAMIC_OBJECT.RES; jj++) {
const x = i * DYNAMIC_OBJECT.RES + ii;
const y = j * DYNAMIC_OBJECT.RES + jj;
if (x >= 0 && y >= 0 && x < this.width && y < this.height) {
grid[x - minCellX][y - minCellY] = this.grid[x][y];
this.grid[x][y] = new Cell(TYPES.AIR);
}
}
}
}
}
return grid;
};
const shapes = Geometry.gridToExactPolygons(this.smallGrid, 1)
.filter(shape => shape.area > 2 ** 2)
.map(shape => Geometry.simplify(shape, 0.5))
.sort((a, b) => a.area - b.area);
if (!shapes.length) {
obj.remove();
return;
}
const inflateDist = CELL;//Math.SQRT2 * CELL;
if (shapes.length === 1 && intervals.frameCount % DYNAMIC_OBJECT.DISTRIBUTION !== this.slot) {
const newCenterOfMass = DYNAMIC_OBJECT.computeCenterOfMass(this.grid);
obj.transform.position = obj.transform.localSpaceToGlobalSpace(newCenterOfMass.minus(this.centerOfMass));
this.centerOfMass = newCenterOfMass;
this.gridBounds.x = -this.centerOfMass.x;
this.gridBounds.y = -this.centerOfMass.y;
const newShape = Geometry.inflate(
shapes[0]
.scaleAbout(Vector2.origin, CELL * DYNAMIC_OBJECT.RES)
.move(this.centerOfMass.inverse),
inflateDist
);
let shouldReplace = !defaultShape;
if (!shouldReplace)
shouldReplace = newShape.vertices.length !== defaultShape.vertices.length;
if (!shouldReplace) {
const totalDist = newShape.vertices
.map((v, i) => Vector2.sqrDist(v, defaultShape.vertices[i]))
.reduce((a, b) => a + b, 0);
shouldReplace = totalDist > 1;
}
if (shouldReplace)
obj.defaultShape = newShape;
} else for (let i = 0; i < shapes.length; i++) {
let shape = shapes[i];
const subgrid = extractSubGrid(shape);
shape = shape
.scaleAbout(Vector2.origin, CELL * DYNAMIC_OBJECT.RES);
const gridOffset = shape.getBoundingBox().min;
shape = Geometry.inflate(shape, inflateDist);
if (i === shapes.length - 1) { // guarentee other things have been placed before moving
this.setGrid(subgrid, gridOffset);
obj.defaultShape = shape.move(this.centerOfMass.plus(gridOffset).inverse);
} else {
const obj2 = scene.main.addPhysicsElement("obj", 0, 0, true);
obj2.transform.rotation = obj.transform.rotation;
const pos = Vector2.floor(obj.transform.localSpaceToGlobalSpace(gridOffset.minus(this.centerOfMass)).over(CELL));
obj2.scripts.add(
DYNAMIC_OBJECT, subgrid, pos, this.textureOffset.plus(Vector2.floor(gridOffset.over(CELL)))
);
obj2.defaultShape = shape.move(obj2.scripts.DYNAMIC_OBJECT.centerOfMass.plus(gridOffset).inverse);
}
}
}
update(obj) {
const { rb } = this;
rb.mobile = !paused || keyboard.justPressed("Enter");
this.lastVelocity = rb.velocity.get();
this.lastAngularVelocity = rb.angularVelocity;
for (const [key, count] of this.collidingObjects) {
this.collidingObjects.set(key, Math.max(0, count - 1));
}
}
draw(obj, name, shape) {
if (keyboard.pressed("c")) {
renderer.stroke(Color.RED).infer(shape);
renderer.draw(Color.RED).circle(0, 0, CELL);
renderer.stroke(new Color(255, 255, 0, 0.5), CELL).rect(this.gridBounds);
}
// renderer.drawThrough(obj.transform, () => {
// renderer.image(this.tex).rect(this.gridBounds);
// });
}
escapeDraw(obj) {
// this.forEachCell((cell, x, y) => {
// console.log(x, y);
// renderer.draw(Color.BLUE).circle(x * CELL, y * CELL, CELL / 2);
// });
}
}
class CHUNK_COLLIDER extends ElementScript {
static RES = 3;
static MIN_FILL_PERCENT = 0.05;
static MIN_SHAPE_AREA_PERCENT = 0.03;
static DISTRIBUTION = 4;
static nextSlot = 0;
static isSolid(cell) {
if (cell.id === TYPES.ELECTRICITY) return SOLID.has(cell.reference);
return SOLID.has(cell.id) && !cell.vel.sqrMag;
}
init(obj, pos, chunk) {
obj.scripts.removeDefault();
this.offset = pos.times(CHUNK);
this.size = ~~(CHUNK / CHUNK_COLLIDER.RES);
this.grid = Array.dim(this.size, this.size).fill(false);
this.chunk = chunk;
this.area = this.size ** 2;
this.slot = (CHUNK_COLLIDER.nextSlot++) % CHUNK_COLLIDER.DISTRIBUTION;
this.shouldUpdate = false;
obj.mouseEvents = false;
}
remesh(obj) {
this.shouldUpdate = false;
let solid = 0;
for (let i = 0; i < this.size; i++)
for (let j = 0; j < this.size; j++) {
const x = this.offset.x + i * CHUNK_COLLIDER.RES;
const y = this.offset.y + j * CHUNK_COLLIDER.RES;
if (!Element.inBounds(x, y)) continue;
const cell = grid[x][y];
const isSolid = CHUNK_COLLIDER.isSolid(cell);
this.grid[i][j] = isSolid;
if (isSolid) solid++;
}
obj.removeAllShapes();
if (solid < this.area * CHUNK_COLLIDER.MIN_FILL_PERCENT) return;
const shapes = Geometry.gridToExactPolygons(this.grid, CELL * CHUNK_COLLIDER.RES);
for (let i = 0; i < shapes.length; i++) {
const shape = shapes[i];
if (shape.area < CHUNK_COLLIDER.MIN_SHAPE_AREA_PERCENT * this.area * (CHUNK_COLLIDER.RES * CELL) ** 2)
continue;
obj.addShape(String(i), Geometry.joinEdges(shape, 0.5));
}
}
update(obj) {
this.shouldUpdate ||= !this.chunk.sleep;
if (!this.shouldUpdate)
return;
if (intervals.frameCount % CHUNK_COLLIDER.DISTRIBUTION !== this.slot)
return;
this.remesh();
}
draw(obj, name, shape) {
if (keyboard.pressed("c")) renderer.stroke(Color.CYAN, 2).infer(shape);
}
}
{ // walls
const floor = scene.main.addPhysicsRectElement("floor", width / 2, height + 50, width + 200, 100, false, new Controls("w", "s", "a", "d"), "No Tag");
const ceiling = scene.main.addPhysicsRectElement("ceiling", width / 2, -50, width + 200, 100, false, new Controls("w", "s", "a", "d"), "No Tag");
const leftWall = scene.main.addPhysicsRectElement("leftWall", -50, height / 2, 100, height, false, new Controls("w", "s", "a", "d"), "No Tag");
const rightWall = scene.main.addPhysicsRectElement("rightWall", width + 50, height / 2, 100, height, false, new Controls("w", "s", "a", "d"), "No Tag");
};
// intervals.continuous(time => {
// if (keyboard.pressed("Control") && mouse.justPressed("Left") && STATIC_SOLID.has(brush)) {
// const obj = scene.main.addPhysicsElement("obj", 0, 0, true, new Controls("w", "s", "a", "d"), "No Tag");
// const radius = Math.ceil(Random.range(10, 20));
// const grid = Array.dim(radius * 2 + 1, radius * 2 + 1);
// for (let i = -radius; i <= radius; i++) {
// for (let j = -radius; j <= radius; j++) {
// grid[i + radius][j + radius] = new Cell(i ** 2 + j ** 2 < radius ** 2 ? brush : TYPES.AIR);
// }
// }
// obj.scripts.add(DYNAMIC_OBJECT, grid, Vector2.floor(mouse.world.over(CELL)).minus(radius));
// }
// }, IntervalFunction.AFTER_UPDATE);
class Chunk {
constructor(x, y) {
this.x = x;
this.y = y;
this.sleep = false;
this.sleepNext = true;
this.sceneObject = scene.main.addPhysicsElement("chunk", x * CHUNK * CELL, y * CHUNK * CELL, false);
this.sceneObject.scripts.add(CHUNK_COLLIDER, new Vector2(x, y), this);
}
}
const CHUNK = 16;
const chunks = Array.dim(WIDTH / CHUNK, HEIGHT / CHUNK)
.map((_, x, y) => new Chunk(x, y));
// here! alert(chunks[1][14])
const CHUNK_WIDTH = chunks.length;
const CHUNK_HEIGHT = chunks[0].length;
const lastIds = Array.dim(WIDTH, HEIGHT)
.fill(TYPES.AIR);
class Element {
static DEFAULT_PASSTHROUGH = new Set([TYPES.AIR]);
constructor(alpha, color, resistance = 0, flammability = 0, update = () => null, onburn = () => null, reference = false) {
if (typeof resistance === "function")
this.getResistance = resistance;
else this.resistance = resistance;
this.flammability = flammability;
this.onburn = onburn;
if (typeof color === "function") {
this.getColorInternal = color;
} else {
this.multipleColors = Array.isArray(color);
alpha /= 255;
if (this.multipleColors)
this.color = color.map(color => Color.alpha(color, alpha));
else this.color = Color.alpha(color, alpha);
}
this.update = update;
this.reference = reference;
this.textureCache = !(this.reference || this.color);
if (this.textureCache) {
this.tex = new Texture(WIDTH, HEIGHT);
this.colorCached = Array.dim(WIDTH, HEIGHT);
}
}
getResistance(x, y) {
return this.resistance;
}
getColor(x, y) {
if (this.textureCache) {
if (!this.colorCached[x][y]) {
this.tex.setPixel(x, y, this.getColorInternal(x, y));
this.colorCached[x][y] = true;
}
return this.tex.getPixel(x, y);
}
return this.getColorInternal(x, y);
}
getColorInternal(x, y) {
if (this.multipleColors) return Random.choice(this.color);
return this.color;
}
burn(x, y, fireType, burn = false) {
if (burn || Random.bool(this.flammability)) {
if (!this.onburn(x, y)) {
Element.setCell(x, y, fireType);
} else {
Element.affectNeighbors(x, y, (x, y) => {
if (Element.isType(x, y, fireType)) Element.setCell(x, y, TYPES.AIR);
});
}
}
}
static onLine(x, y, x1, y1, x2, y2){
if(!(x >= Math.min(x1, x2) && x <= Math.max(x1, x2) && y >= Math.min(y1, y2) && y <= Math.max(y1, y2))) return false;
let N = Math.max(Math.abs(x2 - x1), Math.abs(y2 - y1))
let ox;
let oy;
for (let step = 0; step <= N; step++) {
let t = N === 0 ? 0.0 : step / N;
ox = Math.round(x1 * (1.0 - t) + t * x2);
oy = Math.round(y1 * (1.0 - t) + t * y2);
if(x === ox && y === oy) return true;
}
return false;
}
static inCircle(x, y, x1, y1, r){
return (Math.sqrt((x-x1)**2 + (y-y1)**2) <= r)
}
static onRing(x, y, x1, y1, r){
return this.inCircle(x, y, x1, y1, r) && !this.inCircle(x, y, x1, y1, r-1)
}
static inRect(x, y, x1, y1, x2, y2){
return (x >= x1 && x <= x2 && y >= y1 && y <= y2);
}
static inTriangle(x, y, x1, y1, x2, y2, x3, y3){
let xMin = Math.min(x1, Math.min(x2, x3));
let xMax = Math.max(x1, Math.max(x2, x3));
let yMin = Math.min(y1, Math.min(y2, y3));
let yMax = Math.max(y1, Math.max(y2, y3));
if(!(x >= xMin && x <= xMax && y >= yMin && y <= yMax)) return false;
let N = Math.max(Math.abs(x3 - x2), Math.abs(y3 - y2))
let ox;
let oy;
for (let step = 0; step <= N; step++) {
let t = N === 0 ? 0.0 : step / N;
ox = Math.round(x2 * (1.0 - t) + t * x3);
oy = Math.round(y2 * (1.0 - t) + t * y3);
if(this.onLine(x, y, x1, y1, ox, oy)) return true;
}
return false;
}
static inRhombus(x, y, x1, y1, width, height, angle){
if(!(x >= x1-width/2 && x <= x1+width/2 && y >= y1-height/2 && y <= y1+height/2)) return false;
const c = Math.cos(angle);
const s = Math.sin(angle);
const rotate = (x1, y1, angle) => [Math.cos(angle) * x1 - Math.sin(angle) * y1, Math.sin(angle) * x1 + Math.cos(angle) * y1];
const points = [
rotate(-width / 2, -height / 2, angle),
rotate(width / 2, -height / 2, angle),
rotate(-width / 2, height / 2, angle),
rotate(width / 2, height / 2, angle)];
const minX = Math.floor(Math.min(...points.map(point => point[0])));
const maxX = Math.round(Math.max(...points.map(point => point[0])));
const minY = Math.floor(Math.min(...points.map(point => point[1])));
const maxY = Math.round(Math.max(...points.map(point => point[1])));
for (let i = minX; i <= maxX; i++) {
for (let j = minY; j <= maxY; j++) {
let [ox, oy] = rotate(i, j, -angle);
ox = Math.abs(ox) / (width / 2);
oy = Math.abs(oy) / (height / 2);
if (oy <= 1 - ox)
if(Math.round(i + x1) === x && Math.round(j + y1) === y) return true;
}
}
return false;
}
static getNeighborsOfType(x, y, id) {
return [
Element.isType(x, y - 1, id),
Element.isType(x + 1, y - 1, id),
Element.isType(x + 1, y, id),
Element.isType(x + 1, y + 1, id),
Element.isType(x, y + 1, id),
Element.isType(x - 1, y + 1, id),
Element.isType(x - 1, y, id),
Element.isType(x - 1, y - 1, id)
];
}
static getNeighborsOfTypes(x, y, set) {
return [
Element.isTypes(x, y - 1, set),
Element.isTypes(x + 1, y - 1, set),
Element.isTypes(x + 1, y, set),
Element.isTypes(x + 1, y + 1, set),
Element.isTypes(x, y + 1, set),
Element.isTypes(x - 1, y + 1, set),
Element.isTypes(x - 1, y, set),
Element.isTypes(x - 1, y - 1, set)
];
}
static inBounds(x, y) {
return x >= 0 && y >= 0 && x < WIDTH && y < HEIGHT;
}
static react(x, y, reactant, product, chance = 1, cardinal = false) {
let reacted = false;
if(cardinal){
Element.affectCardinalNeighbors(x, y, (ox, oy) => {
if (Element.isType(ox, oy, reactant) && Random.bool(chance)) {
Element.setCell(ox, oy, product);
reacted = true;
}
});
return reacted;
}
else {
Element.affectAllNeighbors(x, y, (ox, oy) => {
if (Element.isType(ox, oy, reactant) && Random.bool(chance)) {
Element.setCell(ox, oy, product);
reacted = true;
}
});
return reacted;
}
}
static consumeReact(x, y, reactant, product, chance = 1) {
let reacted = false;
Element.affectAllNeighbors(x, y, (ox, oy) => {
if (!reacted && Element.isType(ox, oy, reactant) && Random.bool(chance)) {
Element.setCell(x, y, product);
Element.die(ox, oy);
reacted = true;
}
});
return reacted;
}
static mixReact(x, y, reactant, product, chance = 1) {
let reacted = false;
Element.affectAllNeighbors(x, y, (ox, oy) => {
if (!reacted && Element.isType(ox, oy, reactant) && Random.bool(chance)) {
Element.setCell(x, y, product);
Element.setCell(ox, oy, product);
reacted = true;
}
});
return reacted;
}
static reactMany(x, y, reactant, product, chance = 1) {
let reacted = false;
Element.affectAllNeighbors(x, y, (ox, oy) => {