-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabsorption-18.js
More file actions
2079 lines (1815 loc) · 65.3 KB
/
absorption-18.js
File metadata and controls
2079 lines (1815 loc) · 65.3 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
// === SECTION 1: INITIALIZATION AND CONSTANTS ===
document.addEventListener("DOMContentLoaded", async () => {
// Silence existing console logs (only console.debug will output)
// console.log = () => {};
// Fixed canvas size as per brief: _x_ cells
const GRID_WIDTH = 64;
const GRID_HEIGHT = 64;
const SCALE_SIZE = 8;
const app = new PIXI.Application({
width: GRID_WIDTH * SCALE_SIZE,
height: GRID_HEIGHT * SCALE_SIZE,
backgroundColor: 0x000000,
});
document.getElementById("canvas-div").appendChild(app.view);
// === COMPREHENSIVE CONSTANTS SYSTEM ===
const CONSTANTS = {
// World and canvas parameters
WORLD: {
SCALE_SIZE: SCALE_SIZE,
TICK_INTERVAL: 40,
COLS: GRID_WIDTH,
ROWS: GRID_HEIGHT,
SEED_DISTANCE_FROM_BOTTOM: 5, // Seed placement: rows - _
},
// Visual appearance constants
VISUAL: {
// Alpha transparency values
PLANT_ALPHA: 0.5, // Plant particles base transparency
ENERGY_PARTICLE_ALPHA: 0.3, // Individual energy particles
ENERGY_AURA_ALPHA: 0.3, // Energy particle _x_ aura
WATER_AURA_ALPHA: 0.3, // Water particle aura when bound
WATER_OVERLAY_ALPHA: 0.3, // Water layer overlays
ENERGY_OVERLAY_ALPHA: 0.3, // Energy layer overlays
PHANTOM_ALPHA: 1.0, // Debug phantom images
// Sizes and dimensions
AURA_SIZE: 3, // _x_ aura around particles
PHANTOM_VERTICAL_OFFSET_RATIO: 0.5, // _/_ of canvas height
PHANTOM_HORIZONTAL_OFFSET_RATIO: 0.1, // _/_ of canvas width
// UI positioning
UI_MARGIN: 10,
TEXT_FONT_SIZE: 12,
TEXT_LINE_HEIGHT: 30,
},
// Physics and movement constants
PHYSICS: {
// Bound particle flow probabilities
BOUND_FLOW_PREFERRED_CHANCE: 0.9, // _% chance for preferred vs any direction in bound particle flow
// Unbound water physics probabilities (monochromagic-style)
WATER_LEFT_BIAS_CHANCE: 0.5, // _% chance unbound water chooses left vs right when blocked
WATER_DIAGONAL_CHANCE: 0.3, // _% chance unbound water takes diagonal path vs lateral
// Movement boundaries
NEIGHBOR_OFFSET_MIN: -1,
NEIGHBOR_OFFSET_MAX: 1,
NEIGHBOR_OFFSET_CENTER: 0,
},
// Particle spawning and flux
FLUX: {
P_ENERGY: 0.5, // _% chance per tick for energy spawning near leaves
FLOWER_REPRODUCTION_CHANCE: 0.01, // 1% chance per tick for flower reproduction
},
// Plant genetics and growth
GENETICS: {
INTERNODE_SPACING: 6, // Fixed spacing between nodes
},
// Growth and maturity thresholds
GROWTH: {
PLANT_MATURITY_SIZE: 40, // Plant becomes flower at this size
PLANT_FALLBACK_MATURITY_SIZE: 30, // Fallback flower size when blocked
},
// Per-cell resource slot limits
RESOURCE: {
MAX_FIXED_PER_CELL: 1, // one fixed water or energy
MAX_EXCESS_PER_CELL: 1, // one excess water or energy
},
// Seed and bootstrap system
SEED: {
INITIAL_ENERGY_CAPACITY: 30, // Seed starts with capacity for _ energy
BOOTSTRAP_ENERGY_COUNT: 30, // Number of _ particles to start with
ENERGY_GIVEN_START: 0, // Initial energy given counter
},
// Resource flow timing
FLOW: {
FIXED_PARTICLE_UPDATE_FREQUENCY: 1, // Fixed particles move every _ ticks
EXCESS_PARTICLE_UPDATE_FREQUENCY: 1, // Excess particles move every _ tick
RANDOM_OFFSET_MAX: 10, // Maximum random offset for flow timing
},
// Simulation initialization
SIMULATION: {
INITIAL_WATER_COUNT: 400,
INITIAL_SEED_COUNT: 1,
FAST_FORWARD_FACTOR: 10,
FRAME_START: 0,
ID_COUNTER_START: 1,
},
// UI text positioning
UI: {
FPS_TEXT_X: 10,
FPS_TEXT_Y: 10,
PARTICLE_COUNT_X: 10,
PARTICLE_COUNT_Y: 40,
FAST_FORWARD_X: 10,
FAST_FORWARD_Y: 70,
STATUS_TEXT_X: 10,
STATUS_TEXT_Y: 100,
},
};
// Colors and mode definitions
const colors = {
ENERGY: 0xffff00,
WATER: 0x0066ff,
VAPOR: 0xffffff, // White for visibility
SEED: 0x8b4513,
STEM: 0x228b22,
LEAF: 0x00ff00,
LEAF_BUD: 0x2ecc71, // darker green for leaf buds
BUD: 0x90ee90, // Light green - visible but natural
NODE: 0x14a014,
FLOWER: 0xff69b4,
};
const modeTextures = Object.entries(colors).reduce((acc, [mode, color]) => {
const graphics = new PIXI.Graphics();
graphics.beginFill(color);
graphics.drawRect(0, 0, 1, 1);
graphics.endFill();
acc[mode] = app.renderer.generateTexture(graphics);
return acc;
}, {});
// Performance monitoring setup
const fpsTextStyle = new PIXI.TextStyle({
fontFamily: "Arial",
fontSize: CONSTANTS.VISUAL.TEXT_FONT_SIZE,
fill: "white",
});
const fpsText = new PIXI.Text("FPS: 0", fpsTextStyle);
fpsText.x = CONSTANTS.UI.FPS_TEXT_X;
fpsText.y = CONSTANTS.UI.FPS_TEXT_Y;
app.stage.addChild(fpsText);
const particleCountText = new PIXI.Text("Particles: 0", fpsTextStyle);
particleCountText.x = CONSTANTS.UI.PARTICLE_COUNT_X;
particleCountText.y = CONSTANTS.UI.PARTICLE_COUNT_Y;
app.stage.addChild(particleCountText);
const fastForwardText = new PIXI.Text("", fpsTextStyle);
fastForwardText.x = CONSTANTS.UI.FAST_FORWARD_X;
fastForwardText.y = CONSTANTS.UI.FAST_FORWARD_Y;
app.stage.addChild(fastForwardText);
const statusText = new PIXI.Text(
"PAUSED - Press SPACE to step | R for report",
fpsTextStyle
);
statusText.x = CONSTANTS.UI.STATUS_TEXT_X;
statusText.y = CONSTANTS.UI.STATUS_TEXT_Y;
app.stage.addChild(statusText);
// Core simulation parameters
let particles = [];
let frame = CONSTANTS.SIMULATION.FRAME_START;
let fastForward = false;
let fastForwardFactor = CONSTANTS.SIMULATION.FAST_FORWARD_FACTOR;
let paused = true; // Start paused for controlled study
let lastRenderTime = performance.now();
let idCounter = CONSTANTS.SIMULATION.ID_COUNTER_START;
// Grid setup with fixed dimensions
let scaleSize = CONSTANTS.WORLD.SCALE_SIZE;
let cols = CONSTANTS.WORLD.COLS;
let rows = CONSTANTS.WORLD.ROWS;
// Particle modes and states
const Mode = {
ENERGY: "ENERGY",
WATER: "WATER",
VAPOR: "VAPOR",
SEED: "SEED",
STEM: "STEM",
LEAF: "LEAF",
LEAF_BUD: "LEAF_BUD",
BUD: "BUD",
NODE: "NODE",
FLOWER: "FLOWER",
};
const ParticleState = {
UNBOUND: "UNBOUND", // Free-floating, can move anywhere
BOUND: "BOUND", // Attached to plant, follows plant flow rules
};
// === SECTION 2: LAYERED OCCUPANCY GRIDS ===
class LayeredOccupancyGrid {
constructor(cols, rows) {
this.cols = cols;
this.rows = rows;
// Separate layers for different particle types
this.plantLayer = new Array(cols * rows).fill(null);
this.waterLayer = new Array(cols * rows).fill(null);
this.energyLayer = new Array(cols * rows).fill(null);
// Visual overlays for water and energy
this.waterOverlays = new Array(cols * rows).fill(null);
this.energyOverlays = new Array(cols * rows).fill(null);
// Per-cell fixed/excess flags (Uint8Arrays = fast byte arrays)
this.hasFixedWater = new Uint8Array(cols * rows);
this.hasExcessWater = new Uint8Array(cols * rows);
this.hasFixedEnergy = new Uint8Array(cols * rows);
this.hasExcessEnergy = new Uint8Array(cols * rows);
}
getIndex(x, y) {
return y * this.cols + x;
}
// Plant layer methods
setPlant(x, y, particle) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
this.plantLayer[this.getIndex(x, y)] = particle;
}
}
getPlant(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
return this.plantLayer[this.getIndex(x, y)];
}
return null;
}
removePlant(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
this.plantLayer[this.getIndex(x, y)] = null;
}
}
// Water layer methods
setWater(x, y, particle = null) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
const index = this.getIndex(x, y);
this.waterLayer[index] = particle;
// Create/remove visual overlay
if (particle && !this.waterOverlays[index]) {
const overlay = new PIXI.Graphics();
overlay.beginFill(0x0066ff, CONSTANTS.VISUAL.WATER_OVERLAY_ALPHA);
overlay.drawRect(0, 0, scaleSize, scaleSize);
overlay.endFill();
overlay.x = x * scaleSize;
overlay.y = y * scaleSize;
app.stage.addChild(overlay);
this.waterOverlays[index] = overlay;
} else if (!particle && this.waterOverlays[index]) {
app.stage.removeChild(this.waterOverlays[index]);
this.waterOverlays[index] = null;
}
}
}
getWater(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
return this.waterLayer[this.getIndex(x, y)];
}
return null;
}
hasWater(x, y) {
return this.getWater(x, y) !== null;
}
// Energy layer methods
setEnergy(x, y, particle = null) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
const index = this.getIndex(x, y);
this.energyLayer[index] = particle;
// Create/remove visual overlay
if (particle && !this.energyOverlays[index]) {
const overlay = new PIXI.Graphics();
overlay.beginFill(0xffff00, CONSTANTS.VISUAL.ENERGY_OVERLAY_ALPHA);
overlay.drawRect(0, 0, scaleSize, scaleSize);
overlay.endFill();
overlay.x = x * scaleSize;
overlay.y = y * scaleSize;
app.stage.addChild(overlay);
this.energyOverlays[index] = overlay;
} else if (!particle && this.energyOverlays[index]) {
app.stage.removeChild(this.energyOverlays[index]);
this.energyOverlays[index] = null;
}
}
}
getEnergy(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
return this.energyLayer[this.getIndex(x, y)];
}
return null;
}
hasEnergy(x, y) {
return this.getEnergy(x, y) !== null;
}
// Check if plant layer is occupied (for movement/growth)
isPlantOccupied(x, y) {
if (x < 0 || x >= this.cols || y < 0 || y >= this.rows) return true;
return this.getPlant(x, y) !== null;
}
// Moore neighborhood check for crown shyness
isEmptyMooreNeighborhood(x, y) {
for (
let dx = CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_MIN;
dx <= CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_MAX;
dx++
) {
for (
let dy = CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_MIN;
dy <= CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_MAX;
dy++
) {
if (
dx === CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_CENTER &&
dy === CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_CENTER
)
continue;
const nx = x + dx,
ny = y + dy;
if (nx < 0 || nx >= this.cols || ny < 0 || ny >= this.rows) continue;
if (this.getPlant(nx, ny)) return false;
}
}
return true;
}
// Get plant neighbors for resource flow
getPlantNeighbors(x, y) {
let neighbors = [];
for (
let dx = CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_MIN;
dx <= CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_MAX;
dx++
) {
for (
let dy = CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_MIN;
dy <= CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_MAX;
dy++
) {
if (
dx === CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_CENTER &&
dy === CONSTANTS.PHYSICS.NEIGHBOR_OFFSET_CENTER
)
continue;
let nx = x + dx,
ny = y + dy;
if (nx >= 0 && nx < this.cols && ny >= 0 && ny < this.rows) {
const plant = this.getPlant(nx, ny);
if (plant !== null) {
neighbors.push({ plant, x: nx, y: ny });
}
}
}
}
return neighbors;
}
setFixed(x, y, mode, val) {
const arr =
mode === Mode.WATER ? this.hasFixedWater : this.hasFixedEnergy;
arr[this.getIndex(x, y)] = val ? 1 : 0;
}
setExcess(x, y, mode, val) {
const arr =
mode === Mode.WATER ? this.hasExcessWater : this.hasExcessEnergy;
arr[this.getIndex(x, y)] = val ? 1 : 0;
}
cellHasFixed(x, y, mode) {
if (x < 0 || x >= this.cols || y < 0 || y >= this.rows) return false;
const arr =
mode === Mode.WATER ? this.hasFixedWater : this.hasFixedEnergy;
return arr[this.getIndex(x, y)] === 1;
}
cellHasExcess(x, y, mode) {
if (x < 0 || x >= this.cols || y < 0 || y >= this.rows) return false;
const arr =
mode === Mode.WATER ? this.hasExcessWater : this.hasExcessEnergy;
return arr[this.getIndex(x, y)] === 1;
}
}
let occupancyGrid = new LayeredOccupancyGrid(cols, rows);
// Helper function to count plant cells for a given plant ID
function countPlantCells(plantId) {
return particles.filter((p) => p.isPlantPart() && p.plantId === plantId)
.length;
}
// --- Fast helpers for slot logic & performance -----------------
function hasBoundParticleAt(x, y, mode) {
return particles.some(
(p) =>
p.state === ParticleState.BOUND &&
p.mode === mode &&
p.pos.x === x &&
p.pos.y === y
);
}
function countExcessParticlesAt(x, y, mode) {
return particles.filter(
(p) =>
p.state === ParticleState.BOUND &&
p.mode === mode &&
!p.isFixed &&
p.pos.x === x &&
p.pos.y === y
).length;
}
// === SECTION 3: PLANT GENETICS SYSTEM ===
class PlantGenetics {
constructor(parent = null) {
if (parent) {
this.inheritFromParent(parent);
} else {
this.generateRandom();
}
}
generateRandom() {
this.genes = {
// Only keep properties that are actually used
internodeSpacing: CONSTANTS.GENETICS.INTERNODE_SPACING,
budGrowthLimit: CONSTANTS.GENETICS.BUD_GROWTH_LIMIT,
};
}
inheritFromParent(parent) {
this.genes = JSON.parse(JSON.stringify(parent.genes));
// No mutation since we have fixed genetics
}
}
// === SECTION 4: PARTICLE CLASS ===
class Particle {
constructor(x, y, mode = Mode.WATER) {
this.pos = { x, y };
this.id = idCounter++;
this.mode = mode;
this.age = 0;
this.state = ParticleState.UNBOUND; // All particles start unbound
// Plant-specific properties
this.plantId = null;
this.genetics = null;
this.parent = null;
this.children = [];
this.hasAttemptedSprout = false;
this.hasAttemptedGrow = false;
this.hasLoggedBlocked = false;
this.hasLoggedGrowth = false;
this.hasLoggedStemCreation = false;
this.hasLoggedFirstRender = false;
this.hasLoggedNoGenetics = false;
this.hasLoggedResourceCheck = false;
this.hasLoggedAbsorption = false;
// --- Local need-flags for targeted resource pull
this.needsWater = false; // true when this plant cell holds no bound WATER
this.needsEnergy = false; // true when this plant cell holds no bound ENERGY
this.isFixed = false; // true when this particle is the fixed copy
this.isExcess = false; // second slot if fixed already taken
// Movement properties (for flux particles)
this.isFalling = true;
this.fallingDirection = null;
// Seed capacity tracking
this.initialEnergyCapacity = CONSTANTS.SEED.INITIAL_ENERGY_CAPACITY;
this.energyGiven = CONSTANTS.SEED.ENERGY_GIVEN_START;
// Always create sprite
this.sprite = new PIXI.Sprite(modeTextures[this.mode]);
this.sprite.x = Math.floor(x * scaleSize);
this.sprite.y = Math.floor(y * scaleSize);
this.sprite.scale.set(scaleSize, scaleSize);
// Set plant particles to specified alpha (painted first, resources painted over)
if (this.isPlantPart()) {
this.sprite.alpha = CONSTANTS.VISUAL.PLANT_ALPHA;
} else if (this.mode === Mode.VAPOR) {
// Vapor particles should be 100% visible for debugging
this.sprite.alpha = 1.0;
}
app.stage.addChild(this.sprite);
// Creation debug
console.log(
`🆕 Created ${this.mode} (id=${this.id}) at (${this.pos.x},${this.pos.y})`
);
// Create aura for bound particles
if (this.state === ParticleState.BOUND) {
this.createAura();
}
// TEMPORARILY DISABLED: Energy particle auras
// Create aura for energy particles (subtle visual feedback)
// if (this.mode === Mode.ENERGY && !this.auraSprite) {
// this.auraSprite = new PIXI.Graphics();
// this.auraSprite.beginFill(0xffff00, CONSTANTS.VISUAL.ENERGY_AURA_ALPHA);
// this.auraSprite.drawRect(
// 0,
// 0,
// scaleSize * CONSTANTS.VISUAL.AURA_SIZE,
// scaleSize * CONSTANTS.VISUAL.AURA_SIZE
// );
// this.auraSprite.endFill();
// // Center the aura on the energy particle
// this.auraSprite.x = (x - 1) * scaleSize;
// this.auraSprite.y = (y - 1) * scaleSize;
// app.stage.addChildAt(this.auraSprite, 0); // Add behind other sprites
// // Make energy particle itself low alpha
// this.sprite.alpha = CONSTANTS.VISUAL.ENERGY_PARTICLE_ALPHA;
// }
// Set in appropriate occupancy grid layer
if (this.isPlantPart()) {
occupancyGrid.setPlant(x, y, this);
} else if (this.mode === Mode.ENERGY) {
// Only register in energy layer if unbound
if (this.state === ParticleState.UNBOUND) {
occupancyGrid.setEnergy(x, y, this);
}
} else if (this.mode === Mode.WATER) {
// Only register in water layer if unbound
if (this.state === ParticleState.UNBOUND) {
occupancyGrid.setWater(x, y, this);
}
}
}
isPlantPart() {
return [
Mode.SEED,
Mode.STEM,
Mode.LEAF,
Mode.LEAF_BUD,
Mode.BUD,
Mode.NODE,
Mode.FLOWER,
].includes(this.mode);
}
createAura() {
// Always create phantom image for bound particles, even if aura already exists
if (!this.phantomSprite) {
this.createPhantomImage();
}
// TEMPORARILY DISABLED: Aura effects
// if (this.auraSprite) return; // Already has aura
// const auraColor = this.mode === Mode.WATER ? 0x0066ff : 0xffff00;
// const auraAlpha =
// this.mode === Mode.WATER
// ? CONSTANTS.VISUAL.WATER_AURA_ALPHA
// : CONSTANTS.VISUAL.ENERGY_AURA_ALPHA;
// this.auraSprite = new PIXI.Graphics();
// this.auraSprite.beginFill(auraColor, auraAlpha);
// this.auraSprite.drawRect(
// 0,
// 0,
// scaleSize * CONSTANTS.VISUAL.AURA_SIZE,
// scaleSize * CONSTANTS.VISUAL.AURA_SIZE
// );
// this.auraSprite.endFill();
// this.auraSprite.x = (this.pos.x - 1) * scaleSize;
// this.auraSprite.y = (this.pos.y - 1) * scaleSize;
// app.stage.addChildAt(this.auraSprite, 0);
// Aura created
}
createPhantomImage() {
if (this.phantomSprite) return; // Already has phantom
// Phantom offset in CELLS: configurable ratios of canvas dimensions
const verticalOffset = Math.floor(
CONSTANTS.WORLD.ROWS * CONSTANTS.VISUAL.PHANTOM_VERTICAL_OFFSET_RATIO
);
const horizontalOffset = Math.floor(
CONSTANTS.WORLD.COLS * CONSTANTS.VISUAL.PHANTOM_HORIZONTAL_OFFSET_RATIO
);
// Energy = left, Water = right
const phantomOffsetXCells =
this.mode === Mode.ENERGY ? -horizontalOffset : horizontalOffset;
const phantomOffsetYCells = -verticalOffset;
// Convert to pixel offsets
const phantomOffsetX = phantomOffsetXCells * scaleSize;
const phantomOffsetY = phantomOffsetYCells * scaleSize;
this.phantomSprite = new PIXI.Sprite(modeTextures[this.mode]);
this.phantomSprite.x = this.pos.x * scaleSize + phantomOffsetX;
this.phantomSprite.y = this.pos.y * scaleSize + phantomOffsetY;
this.phantomSprite.scale.set(scaleSize, scaleSize);
this.phantomSprite.alpha = CONSTANTS.VISUAL.PHANTOM_ALPHA;
this.phantomSprite.visible = true; // Always visible regardless of main sprite
// Ensure phantom stays on screen by clamping position
this.phantomSprite.x = Math.max(
0,
Math.min(this.phantomSprite.x, (CONSTANTS.WORLD.COLS - 1) * scaleSize)
);
this.phantomSprite.y = Math.max(
0,
Math.min(this.phantomSprite.y, (CONSTANTS.WORLD.ROWS - 1) * scaleSize)
);
app.stage.addChild(this.phantomSprite);
// Phantom image created
}
updatePhantomPosition() {
if (this.phantomSprite) {
// Use same cell-based offsets as createPhantomImage
const verticalOffset = Math.floor(
CONSTANTS.WORLD.ROWS * CONSTANTS.VISUAL.PHANTOM_VERTICAL_OFFSET_RATIO
);
const horizontalOffset = Math.floor(
CONSTANTS.WORLD.COLS *
CONSTANTS.VISUAL.PHANTOM_HORIZONTAL_OFFSET_RATIO
);
const phantomOffsetXCells =
this.mode === Mode.ENERGY ? -horizontalOffset : horizontalOffset;
const phantomOffsetYCells = -verticalOffset;
const phantomOffsetX = phantomOffsetXCells * scaleSize;
const phantomOffsetY = phantomOffsetYCells * scaleSize;
this.phantomSprite.x = this.pos.x * scaleSize + phantomOffsetX;
this.phantomSprite.y = this.pos.y * scaleSize + phantomOffsetY;
// Ensure phantom stays on screen by clamping position
this.phantomSprite.x = Math.max(
0,
Math.min(this.phantomSprite.x, (CONSTANTS.WORLD.COLS - 1) * scaleSize)
);
this.phantomSprite.y = Math.max(
0,
Math.min(this.phantomSprite.y, (CONSTANTS.WORLD.ROWS - 1) * scaleSize)
);
}
}
removeAura() {
if (this.auraSprite) {
app.stage.removeChild(this.auraSprite);
this.auraSprite = null;
}
if (this.phantomSprite) {
app.stage.removeChild(this.phantomSprite);
this.phantomSprite = null;
}
}
clearSlotFlags(oldX, oldY) {
if (this.isFixed) occupancyGrid.setFixed(oldX, oldY, this.mode, false);
if (this.isExcess) occupancyGrid.setExcess(oldX, oldY, this.mode, false);
}
claimSlotFlags(newX, newY) {
if (!occupancyGrid.cellHasFixed(newX, newY, this.mode)) {
this.isFixed = true;
this.isExcess = false;
occupancyGrid.setFixed(newX, newY, this.mode, true);
} else if (!occupancyGrid.cellHasExcess(newX, newY, this.mode)) {
this.isFixed = false;
this.isExcess = true;
occupancyGrid.setExcess(newX, newY, this.mode, true);
} else {
// both slots taken; this particle should not remain bound here
this.isFixed = this.isExcess = false;
}
}
bindToPlant(plantId) {
const plantHere = occupancyGrid.getPlant(this.pos.x, this.pos.y);
const isSeedCell = plantHere && plantHere.mode === Mode.SEED;
// Refuse to bind if target cell already full — except for the seed cell,
// which may store many energy particles.
if (
!isSeedCell &&
occupancyGrid.cellHasFixed(this.pos.x, this.pos.y, this.mode) &&
occupancyGrid.cellHasExcess(this.pos.x, this.pos.y, this.mode)
) {
return; // caller must relocate particle first
}
this.state = ParticleState.BOUND;
this.plantId = plantId;
// allocate slot flags for non‑seed cells, or for the first two particles
// arriving at the seed
if (
!isSeedCell ||
!(
occupancyGrid.cellHasFixed(this.pos.x, this.pos.y, this.mode) &&
occupancyGrid.cellHasExcess(this.pos.x, this.pos.y, this.mode)
)
) {
this.claimSlotFlags(this.pos.x, this.pos.y);
}
this.createAura();
// If this is a bound energy particle, hide its main sprite and aura
if (this.mode === Mode.ENERGY) {
if (this.sprite) this.sprite.visible = false;
if (this.auraSprite) this.auraSprite.visible = false;
}
// remove from unbound layers
if (this.mode === Mode.ENERGY)
occupancyGrid.setEnergy(this.pos.x, this.pos.y, null);
if (this.mode === Mode.WATER)
occupancyGrid.setWater(this.pos.x, this.pos.y, null);
// Debug
// console.log(
// `🔗 ${this.mode} bound (${this.isFixed ? "fixed" : "excess"}) at ${
// this.pos.x
// },${this.pos.y}`
// );
}
unbindFromPlant() {
this.clearSlotFlags(this.pos.x, this.pos.y);
this.state = ParticleState.UNBOUND;
this.plantId = null;
this.isFixed = false;
this.isExcess = false;
this.removeAura();
// Re-register in occupancy grid layers
if (this.mode === Mode.ENERGY) {
occupancyGrid.setEnergy(this.pos.x, this.pos.y, this);
} else if (this.mode === Mode.WATER) {
occupancyGrid.setWater(this.pos.x, this.pos.y, this);
}
}
// Get current seed capacity (shrinks as energy is given out)
getCurrentSeedCapacity() {
if (this.mode !== Mode.SEED) return 1;
return Math.max(1, this.initialEnergyCapacity - this.energyGiven);
}
// Count bound particles of a specific type at this position
countBoundParticlesAt(x, y, particleMode) {
return particles.filter(
(p) =>
p.state === ParticleState.BOUND &&
p.mode === particleMode &&
p.pos.x === x &&
p.pos.y === y
).length;
}
// Get connected plant neighbors for bound particle flow
getConnectedPlantNeighbors() {
const neighbors = [];
const plantHere = occupancyGrid.getPlant(this.pos.x, this.pos.y);
if (!plantHere || plantHere.plantId !== this.plantId) return neighbors;
// Add parent
if (plantHere.parent) {
neighbors.push({
x: plantHere.parent.pos.x,
y: plantHere.parent.pos.y,
plant: plantHere.parent,
direction: "parent",
});
}
// Add children
plantHere.children.forEach((child) => {
neighbors.push({
x: child.pos.x,
y: child.pos.y,
plant: child,
direction: "child",
});
});
return neighbors;
}
hasFixedAt(x, y, mode) {
return particles.some(
(p) =>
p.state === ParticleState.BOUND &&
p.mode === mode &&
p.isFixed &&
p.pos.x === x &&
p.pos.y === y
);
}
// Find least crowded target among candidates
findLeastCrowdedTarget(candidates) {
if (candidates.length === 0) return null;
// Sort by particle count (ascending)
candidates.sort((a, b) => {
const aCount = this.countBoundParticlesAt(a.x, a.y, this.mode);
const bCount = this.countBoundParticlesAt(b.x, b.y, this.mode);
return aCount - bCount;
});
return candidates[0];
}
updateBoundParticle() {
const plantHere = occupancyGrid.getPlant(this.pos.x, this.pos.y);
if (!plantHere) return;
const neighbors = this.getConnectedPlantNeighbors();
if (neighbors.length === 0) return;
const wantsChild = this.mode === Mode.WATER; // water up, energy down
// capacityReached: true when both fixed & excess already present
const capacityReached = (cx, cy) =>
occupancyGrid.cellHasFixed(cx, cy, this.mode) &&
occupancyGrid.cellHasExcess(cx, cy, this.mode);
// needy = neighbours that still want this resource and are not full
const needy = (dir) =>
neighbors.filter(
(n) =>
n.direction === dir &&
!this.hasFixedAt(n.x, n.y, this.mode) &&
!capacityReached(n.x, n.y)
);
let targets = needy(wantsChild ? "child" : "parent");
// Excess particles may reverse; fixed particles may not
if (targets.length === 0 && !this.isFixed) {
targets = neighbors.filter((n) => !capacityReached(n.x, n.y));
}
if (targets.length) {
const t = this.findLeastCrowdedTarget(targets);
this.moveToCell(t.x, t.y);
}
}
setMode(mode) {
if (this.mode !== mode) {
const oldMode = this.mode;
this.mode = mode;
// Update sprite texture
if (this.sprite) {
this.sprite.texture = modeTextures[mode];
// No color tinting since we removed genetics colors
}
// Update alpha based on new mode
if (this.sprite) {
if (this.isPlantPart()) {
this.sprite.alpha = CONSTANTS.VISUAL.PLANT_ALPHA;
} else if (this.mode === Mode.VAPOR) {
// Vapor particles should be 100% visible for debugging
this.sprite.alpha = 1.0;
} else if (this.mode === Mode.ENERGY) {
this.sprite.alpha = CONSTANTS.VISUAL.ENERGY_PARTICLE_ALPHA;
}
}
// Handle occupancy grid changes
if (this.isPlantPart() && !this.wasPlantPart(oldMode)) {
occupancyGrid.setPlant(this.pos.x, this.pos.y, this);
} else if (!this.isPlantPart() && this.wasPlantPart(oldMode)) {
occupancyGrid.removePlant(this.pos.x, this.pos.y);
}
}
}
wasPlantPart(mode) {
return [
Mode.SEED,
Mode.STEM,
Mode.LEAF,
Mode.BUD,
Mode.NODE,
Mode.FLOWER,
].includes(mode);
}
update() {
this.age++;
// Update based on state first
if (this.state === ParticleState.BOUND) {
this.updateBoundParticle();
}
// Update based on mode
if (this.mode === Mode.WATER) {
if (this.state === ParticleState.UNBOUND) {
this.updateWater();
}
} else if (this.mode === Mode.ENERGY) {
if (this.state === ParticleState.UNBOUND) {
this.updateEnergy();
}
} else if (this.mode === Mode.VAPOR) {
this.updateVapor();
} else if (this.mode === Mode.SEED) {
this.updateSeed();
} else if (this.mode === Mode.BUD) {
this.updateBud();
} else if (this.mode === Mode.FLOWER) {
this.updateFlower();
this.updatePlantPart(); // Also update energy visuals
} else if (this.isPlantPart()) {
// All other plant parts (STEM, LEAF, NODE)
this.updatePlantPart();
}
}
// === PARTICLE MOVEMENT METHODS ===
moveRel(x, y) {
// Handle vertical bounds (no wrapping - water accumulates at bottom)
let newY = this.pos.y + y;
if (newY < 0) {
newY = 0;
} else if (newY >= rows) {
newY = rows - 1;
}
// Handle horizontal bounds (closed edges)
let newX = this.pos.x + x;
if (newX < 0 || newX >= cols) {
return false; // Can't move outside horizontal bounds
}
// Update position
this.pos.x = newX;
this.pos.y = newY;
// Update sprite position
if (this.sprite) {
this.sprite.x = Math.floor(this.pos.x * scaleSize);
this.sprite.y = Math.floor(this.pos.y * scaleSize);
}
// Update aura position
if (this.auraSprite) {
this.auraSprite.x = (this.pos.x - 1) * scaleSize;
this.auraSprite.y = (this.pos.y - 1) * scaleSize;
}
// Update occupancy grid for unbound particles only
if (this.state === ParticleState.UNBOUND) {
if (this.isPlantPart()) {