-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.html
More file actions
4007 lines (3437 loc) · 149 KB
/
Copy pathclient.html
File metadata and controls
4007 lines (3437 loc) · 149 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>agent-model simulation client</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #1a1a2e;
color: #eee;
display: flex;
height: 100vh;
}
#sidebar {
width: 300px;
background: #16213e;
padding: 20px;
display: flex;
flex-direction: column;
gap: 15px;
overflow-y: auto;
}
h1 {
font-size: 1.4em;
color: #0f4c75;
border-bottom: 2px solid #0f4c75;
padding-bottom: 10px;
}
.control-group {
background: #1a1a2e;
padding: 12px;
border-radius: 8px;
}
.control-group h3 {
font-size: 0.9em;
color: #888;
margin-bottom: 8px;
text-transform: uppercase;
}
button {
background: #0f4c75;
color: white;
border: none;
padding: 6px 10px;
border-radius: 5px;
cursor: pointer;
font-size: 0.9em;
transition: background 0.2s;
}
button:hover { background: #1a6fa8; }
button:disabled { background: #444; cursor: not-allowed; }
button.danger { background: #c23616; }
button.danger:hover { background: #e84118; }
button.success { background: #27ae60; }
.button-row {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.stat {
display: flex;
justify-content: space-between;
padding: 5px 0;
border-bottom: 1px solid #333;
}
.stat-value {
font-weight: bold;
font-family: monospace;
}
.stat-value.good { color: #4CAF50; }
.stat-value.warn { color: #ff9800; }
.stat-value.bad { color: #f44336; }
#main {
flex: 1;
display: flex;
flex-direction: column;
padding: 10px;
position: relative;
}
#canvas-container {
flex: 1;
position: relative;
background: #0d0d1a;
border-radius: 5px;
overflow: hidden;
}
#threejs-canvas {
width: 100%;
height: 100%;
display: block;
cursor: grab;
}
#threejs-canvas:active {
cursor: grabbing;
}
/* Floating minimap */
#minimap-container {
position: absolute;
bottom: 20px;
right: 20px;
width: 200px;
height: 200px;
background: rgba(13, 13, 26, 0.9);
border: 2px solid #0f4c75;
border-radius: 5px;
overflow: hidden;
z-index: 100;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}
#minimap-canvas {
width: 100%;
height: 100%;
cursor: crosshair;
}
/* Inspect Agent Popup */
#inspect-popup {
display: none;
position: absolute;
top: 20px;
left: 20px;
width: 280px;
background: rgba(22, 33, 62, 0.95);
border: 2px solid #0f4c75;
border-radius: 8px;
z-index: 200;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
font-size: 0.85em;
}
#inspect-popup.visible {
display: block;
}
#inspect-popup .popup-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 12px;
background: #0f4c75;
border-radius: 6px 6px 0 0;
}
#inspect-popup .popup-header h4 {
margin: 0;
font-size: 1em;
}
#inspect-popup .popup-close {
background: none;
border: none;
color: #fff;
font-size: 1.4em;
cursor: pointer;
padding: 0 4px;
line-height: 1;
opacity: 0.7;
transition: opacity 0.2s;
}
#inspect-popup .popup-close:hover {
opacity: 1;
background: none;
}
#inspect-popup .popup-content {
padding: 12px;
max-height: 400px;
overflow-y: auto;
}
#inspect-popup .agent-row {
display: flex;
align-items: flex-start;
padding: 6px 8px;
margin: 2px 0;
background: rgba(0, 0, 0, 0.2);
border-radius: 4px;
gap: 8px;
}
#inspect-popup .agent-row.selected {
background: rgba(255, 255, 0, 0.15);
border: 1px solid rgba(255, 255, 0, 0.3);
}
#inspect-popup .agent-icon {
font-size: 1.5em;
}
#inspect-popup .agent-left {
display: flex;
flex-direction: column;
align-items: center;
min-width: 40px;
}
#inspect-popup .agent-id {
font-weight: bold;
font-family: monospace;
font-size: 0.9em;
}
#inspect-popup .agent-info {
flex: 1;
font-family: monospace;
}
#inspect-popup .agent-internal-state {
color: #888;
}
#inspect-popup .empty-cell {
color: #666;
font-style: italic;
padding: 8px 0;
}
#inspect-popup .loading {
color: #888;
font-style: italic;
padding: 8px 0;
}
/* Track Agent Popup */
#track-agent {
display: none;
position: absolute;
top: 20px;
left: 320px;
width: 280px;
background: rgba(22, 33, 62, 0.95);
border: 2px solid #27ae60;
border-radius: 8px;
z-index: 200;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
font-size: 0.85em;
}
#track-agent.visible {
display: block;
}
#track-agent .popup-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 12px;
background: #27ae60;
border-radius: 6px 6px 0 0;
}
#track-agent .popup-header h4 {
margin: 0;
font-size: 1em;
}
#track-agent .popup-close {
background: none;
border: none;
color: #fff;
font-size: 1.4em;
cursor: pointer;
padding: 0 4px;
line-height: 1;
opacity: 0.7;
transition: opacity 0.2s;
}
#track-agent .popup-close:hover {
opacity: 1;
background: none;
}
#track-agent .popup-content {
padding: 12px;
}
#track-agent .agent-field {
display: flex;
justify-content: space-between;
padding: 4px 0;
border-bottom: 1px solid rgba(255,255,255,0.1);
gap: 8px;
}
#track-agent .agent-field:last-child {
border-bottom: none;
flex-direction: column;
align-items: flex-start;
}
#track-agent .field-name {
color: #888;
flex-shrink: 0;
}
#track-agent .field-value {
font-family: monospace;
font-weight: bold;
}
#track-agent .field-value.agent-internal-state {
font-weight: normal;
color: #aaa;
word-break: break-word;
}
#track-agent .agent-dead {
color: #f44336;
font-style: italic;
padding: 8px 0;
text-align: center;
}
/* Make agent rows in inspect-popup clickable */
#inspect-popup .agent-row {
cursor: pointer;
transition: background 0.2s;
}
#inspect-popup .agent-row:hover {
background: rgba(39, 174, 96, 0.2);
}
/* Population Graph */
#population-graph {
position: absolute;
top: 20px;
right: 20px;
width: 350px;
height: 200px;
background: rgba(22, 33, 62, 0.95);
border: 2px solid #0f4c75;
border-radius: 8px;
z-index: 100;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
cursor: pointer;
user-select: none;
}
#population-graph .graph-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 6px 10px;
background: #0f4c75;
border-radius: 6px 6px 0 0;
font-size: 0.85em;
}
#population-graph .graph-header h4 {
margin: 0;
font-size: 0.95em;
}
#population-graph .graph-legend {
display: flex;
gap: 12px;
font-size: 0.8em;
}
#population-graph .legend-item {
display: flex;
align-items: center;
gap: 4px;
}
#population-graph .legend-dot {
width: 10px;
height: 10px;
border-radius: 50%;
}
#population-graph .legend-dot.m { background: #4C50AF; }
#population-graph .legend-dot.f { background: #f44336; }
#population-graph canvas {
width: 100%;
height: calc(100% - 32px);
display: block;
}
#connection-status {
font-size: 0.75em;
padding: 4px 14px;
border-radius: 12px;
font-weight: bold;
}
#connection-status.connected { background: #27ae60; color: white; }
#connection-status.disconnected { background: #c0392b; color: white; }
#connection-status.connecting { background: #f39c12; color: white; }
#log {
min-height: 120px;
max-height: 200px;
overflow-y: auto;
font-family: monospace;
font-size: 0.75em;
background: #0d0d1a;
padding: 10px;
border-radius: 5px;
}
.log-entry { color: #666; }
.log-entry.info { color: #4CAF50; }
.log-entry.warn { color: #ff9800; }
.log-entry.error { color: #f44336; }
.log-entry.ws { color: #9b59b6; }
.slider-group { margin: 8px 0; }
.slider-group label { display: block; font-size: 0.85em; margin-bottom: 4px; }
.slider-group input[type="range"] { width: 100%; }
select, input[type="text"], input[type="number"] {
width: 100%;
padding: 8px;
border: 1px solid #333;
border-radius: 4px;
background: #1a1a2e;
color: #eee;
font-size: 0.9em;
margin-bottom: 8px;
}
select:focus, input[type="text"]:focus, input[type="number"]:focus {
outline: none;
border-color: #0f4c75;
}
.param-group { margin-top: 8px; }
.param-group label { display: block; font-size: 0.8em; color: #888; margin-bottom: 4px; }
.controls-hint {
font-size: 0.7em;
color: #666;
margin-top: 4px;
line-height: 1.4;
}
</style>
</head>
<body>
<div id="sidebar">
<h1>τὰ ἀνθρώπινα</h1>
<div class="control-group">
<h3>Simulation</h3>
<div class="button-row" style="margin-top: 8px;">
<button id="btn-init">Initialize</button>
<button id="btn-start">Start</button>
<button id="btn-stop" disabled>Stop</button>
</div>
<div class="button-row" style="margin-top: 8px;">
<button id="btn-step">Step</button>
<button id="btn-step10">Step 10</button>
</div>
</div>
<div class="control-group">
<h3>Server Statistics</h3>
<div class="stat">
<span>Server Tick:</span>
<span id="stat-server-tick" class="stat-value">0</span>
</div>
<div class="stat">
<span>Server M:</span>
<span id="stat-m" class="stat-value m">0</span>
</div>
<div class="stat">
<span>Server F:</span>
<span id="stat-f" class="stat-value f">0</span>
</div>
</div>
<div class="control-group">
<h3>Client Statistics</h3>
<div class="stat">
<span>Local Agents:</span>
<span id="stat-local" class="stat-value">0</span>
</div>
<div class="stat">
<span>Last Update Tick:</span>
<span id="stat-last-tick" class="stat-value">0</span>
</div>
<div class="stat">
<span>Updates/sec:</span>
<span id="stat-ups" class="stat-value">-</span>
</div>
<div class="stat">
<span>Agents/sec:</span>
<span id="stat-aps" class="stat-value">-</span>
</div>
<div class="stat">
<span>Render FPS:</span>
<span id="stat-fps" class="stat-value">-</span>
</div>
</div>
<div class="control-group">
<h3>Edit Parameters</h3>
<div class="param-group">
<label>Parameter:</label>
<select id="param-select">
<option value="">-- Initialize first --</option>
</select>
</div>
<div class="param-group">
<label>Value:</label>
<input type="text" id="param-value" placeholder="Select a parameter">
</div>
<div class="button-row">
<button id="btn-param-set">Set Value</button>
<button id="btn-param-refresh">Refresh</button>
</div>
<div class="stat" style="margin-top: 8px;">
<span>Status:</span>
<span id="param-status" class="stat-value">-</span>
</div>
</div>
<div class="control-group">
<h3>Viewport</h3>
<div class="stat">
<span>Center:</span>
<span id="stat-viewport-center" class="stat-value">-</span>
</div>
<div class="stat">
<span>Zoom:</span>
<span id="stat-viewport-zoom" class="stat-value">-</span>
</div>
<div class="stat">
<span>Agents:</span>
<span id="stat-viewport-agents" class="stat-value">0</span>
</div>
<div class="stat">
<span>Poll RTT:</span>
<span id="stat-viewport-rtt" class="stat-value">-</span>
</div>
<div class="slider-group">
<label>Poll Rate: <span id="poll-rate-value">20</span> fps</label>
<input type="range" id="poll-rate" min="1" max="60" value="20">
</div>
<div class="controls-hint">
WASD or drag to pan • Wheel or +/- to zoom
</div>
<h3>Websocket Stream</h3>
<div id="connection-status" class="disconnected">Disconnected</div>
<div class="button-row" style="margin-top: 8px;">
<button id="btn-connect" class="success">Connect</button>
<button id="btn-disconnect" class="danger" disabled>Disconnect</button>
</div>
<div class="slider-group">
<label>Interval: <span id="rate-interval-value">10</span>ms</label>
<input type="range" id="rate-interval" min="5" max="100" value="10">
</div>
<div class="slider-group">
<label>Chunk size: <span id="rate-chunk-value">200</span></label>
<input type="range" id="rate-chunk" min="10" max="500" value="200" step="10">
</div>
<div class="button-row">
<button id="btn-rate-apply">Apply Rate</button>
</div>
<div class="stat" style="margin-top: 8px;">
<span>Agents/sec:</span>
<span id="stat-theoretical-rate" class="stat-value">20000</span>
</div>
</div>
<div id="log"></div>
</div>
<div id="main">
<div id="canvas-container">
<canvas id="threejs-canvas"></canvas>
</div>
<!-- Floating minimap -->
<div id="minimap-container">
<canvas id="minimap-canvas"></canvas>
</div>
<!-- Population Graph -->
<div id="population-graph">
<div class="graph-header">
<h4>Population</h4>
<div class="graph-legend">
<div class="legend-item">
<div class="legend-dot m"></div>
<span>m</span>
</div>
<div class="legend-item">
<div class="legend-dot f"></div>
<span>f</span>
</div>
</div>
</div>
<canvas id="graph-canvas"></canvas>
</div>
<!-- Inspect Agent Popup -->
<div id="inspect-popup">
<div class="popup-header">
<h4>Cell <span class="cell-coords"></span> <span class="cell-tick"></span></h4>
<button class="popup-close" onclick="closeInspectPopup()">×</button>
</div>
<div class="popup-content">
<!-- Agent list will be populated dynamically -->
</div>
</div>
<div id="track-agent">
<div class="popup-header">
<h4><span class="track-title"></span></h4>
<button class="popup-close" onclick="closeTrackAgent()">×</button>
</div>
<div class="popup-content">
<!-- Agent details will be populated dynamically -->
</div>
</div>
</div>
<script>
// ============================================================
// Configuration
// ============================================================
const HTTP_URL = 'http://localhost:5000';
const WS_URL = 'ws://localhost:8765';
const TWOPI = Math.PI*2;
const DEG_PER_RAD = 180/Math.PI;
const NEG_HALF_PI = -Math.PI/2;
const SIXTY_DEG = Math.PI/3;
const ORTHOGRAPHIC = false;
const RENDER_NONVIEWPORT = false;
const SYLLABIC = true;
const SYLLABLES = generateSyllables();
const SYL_BASE = SYLLABLES.length;
if(SYLLABIC){
console.log(SYL_BASE + "(" + toSyllabic(SYL_BASE) + ") syllables");
}
const MALE_ICON = '♂'; // ♂ ♂️
const FEMALE_ICON = '♀'; // ♀ ♀️
const INFANT_ICON = '👶🏻'; //👶 👶🏻 infant
const BOY_ICON = '👦🏻'; //👦 👦🏻 boy
const GIRL_ICON = '👧🏻'; //👧 👧🏻 girl
const MAN_ICON = '🧔🏻♂️'; //🧔🏻♂️ 👨🧔🧔♂️ man
const WOMAN_ICON = '👩🏻'; //👩 👩🏻 woman
const GRAMPS_ICON = '👴🏻'; //👴 👴🏻 old man
const GRANNY_ICON = '👵🏻'; //👵 👵🏻 old woman
const SKULL_ICON = '💀'; //💀☠️
const EMOJIS = [ // id = min(4,int(5*trust))+5*min(4,int(5*hap))
'😞','😟','🙁','😖','😶',
'😒','😔','🙁','😕','🥲',
'😳','🥺','😐','🫤','🙂',
'🥴','😅','🙂','😄','😊',
'😬','😃','😄','😊','😌'
];
const INFANCY = 3;
const CHILDHOOD = 7;
const ADOLESCENCE = 14;
const ADULTHOOD = 21;
const SENESCENCE = 60;
// ============================================================
// State Management
// ============================================================
// Agent store: id -> {id, type, x, y, energy}
const agentStore = new Map();
// World info
let worldWidth = 10; // unused except for grid initialization? formerly posted by initWorld
let worldHeight = 10;
let lastUpdateTick = 0;
let serverTick = 0;
// Camera state (floating point for smooth movement)
let cameraX = 5; // world X coordinate of camera center
let cameraY = 5; // world Y coordinate of camera center
let cameraZoom = 5; // number of cells visible (vertical extent)
let aspect = 1;
// Zoom limits
const MIN_ZOOM = 0.5; // min cells visible (max zoom in)
const MAX_ZOOM = 10; // max cells visible
// Derived viewport params for HTTP polling (integers)
let viewportCenter = [5, 5];
let viewportRadius = 3;
// WebSocket
let ws = null;
let wsConnected = false;
// Performance tracking
let messageCount = 0;
let agentUpdateCount = 0;
let frameCount = 0;
let lastPerfTime = Date.now();
// Simulation parameters
let simulationParams = {};
// Viewport polling
let viewportPollingActive = false;
let viewportPollTimeoutId = null;
let viewportFetchInFlight = false; // Guard against overlapping requests
let viewportAgentStore = new Map(); // Agents
let CellsStore = new Map(); // Map cells
let viewportRTT = [];
// Cache for PD data - persists between updates so cells keep their color
// when pd data is temporarily unavailable. Key: "x,y", Value: [cc, cd, dd]
const pdCache = new Map();
// Float positions for viewport agents (client-side physics simulation)
// Maps agent id -> { x: float, y: float, targetCellX: int, targetCellY: int, scale: float }
// targetCell is the cell center the agent is attracted to (from server's integer position)
// x,y is the actual rendered position which may differ during transitions
// scale is the age-based size multiplier (affects mesh size and Coulomb repulsion)
const viewportFloatPositions = new Map();
// Physics constants for agent positioning within cells
const PHYSICS = {
SPRING_STRENGTH: 0.06, // Linear spring constant for attraction to cell center
BASE_REPULSION: 0.01, // Base Coulomb-like repulsion (will be scaled by density)
REPULSION_FLOOR: 0.05, // Minimum effective distance for repulsion (prevents infinity)
MAX_STEP: 0.04, // Maximum displacement per frame
// Adaptive repulsion parameters
REFERENCE_POPULATION: 4, // Population at which BASE_REPULSION applies directly
ADAPTATION_RATE: 0.02, // How fast the effective repulsion adapts (0-1, lower = smoother)
// Parent attraction
PARENT_ATTRACTION: 0.03, // Linear spring constant for attraction to parents
PARENT_DISTANCE_CAP: 0.8, // Max effective distance for parent attraction (caps force for remote parents)
// Spouse attraction
SPOUSE_ATTRACTION: 0.05, // Linear spring constant for attraction to spouse
};
// Time conversion: one tick represents this many years
const TICK_YEARS = 0.25;
/**
* Computes age-based scale factor for an agent.
* Models human growth: small at birth, full size at 21, slight shrinkage after 40.
* @param {number} ageYears - Agent's age in years
* @returns {number} Scale factor (0.2 to 1.0+)
*/
function getAgeScale(ageYears) {
if (ageYears < 0) return 0.2; // Safety check
if (ageYears < 21) {
// Growth phase: 0.2 at birth, 1.0 at age 21
return 0.2 + 0.8 * (ageYears / 21);
} else if (ageYears <= 40) {
// Prime years: full size
return 1.0;
} else {
// Aging: slight shrinkage, but floor at 0.4 to stay visible
return Math.max(0.4, 1.0 - 0.01 * (ageYears - 40));
}
}
// Adaptive state for dynamic repulsion scaling
let effectiveRepulsion = PHYSICS.BASE_REPULSION; // Current effective repulsion constant
let observedTypicalPopulation = PHYSICS.REFERENCE_POPULATION; // Smoothed population estimate
// Simulation pause state for physics damping
let simulationPausedAt = null; // null when running, timestamp when paused
const PAUSE_DAMP_TIME = 10000; // 10 seconds to come to rest after pause
// Last known positions for bearing calculation: id -> {x, y}
const lastKnownPositions = new Map();
// Input state
const keysPressed = new Set();
let isDragging = false;
let lastMouseX = 0;
let lastMouseY = 0;
// Movement speeds
const PAN_SPEED_KEYS = 0.3; // cells per frame when using keys
const PAN_SPEED_MOUSE = 0.01; // multiplier for mouse drag
const ZOOM_SPEED_KEYS = 1.05; // zoom factor per keypress
const ZOOM_SPEED_WHEEL = 1.1; // zoom factor per wheel tick
// Population history for graph
const populationHistory = {
ticks: [],
popM: [],
popF: [],
};
let graphUpdateInterval = null;
// Histogram data from server (latest snapshot)
// Each property array has format: [mean, bin1, bin2, ..., bin10]
const histogramData = {
age: [],
energy: [],
kin: [],
o: [],
c: [],
e: [],
a: [],
n: [],
kin_trait: [],
xeno: [],
hap: [],
trust: [],
};
// Graph display mode: 0 = population time series, >0 = histograms
let graphMode = 0;
// Shared geometries - created once, never disposed
let sharedAgentGeometries = null;
// Agent mesh cache: agentId -> { mesh, material, geomKey }
// This replaces the old agentMeshes Map
let agentMeshCache = new Map();
// ============================================================
// Viewport Parameter Calculation
// ============================================================
function updateViewportParams() {
// integer viewport center and radius to cover the camera view
viewportCenter = [Math.round(cameraX-.5), Math.round(cameraY-.5)];
//viewport radius: allow aspect (w/h) up to 1.6
viewportRadius = Math.ceil((cameraZoom / 2)*Math.max(aspect,1.6));
// Clamp to world bounds
viewportCenter[0] = Math.max(0, Math.min(worldWidth - 1, viewportCenter[0]));
viewportCenter[1] = Math.max(0, Math.min(worldHeight - 1, viewportCenter[1]));
}
function getViewportRadius() {
return viewportRadius;
}
// ============================================================
// Three.js Setup
// ============================================================
let scene, camera, renderer;
let groundMesh;
let gridLines;
let agentMeshes = new Map();
let cellInstancedMesh = null; // InstancedMesh for cells
let cellInstanceCount = 0; // Current number of visible cells
// Raycaster for click detection (perspective camera)
const raycaster = new THREE.Raycaster();
const mouseNDC = new THREE.Vector2();
// Colors
const COLOR_EMPTY = new THREE.Color(0.05, 0.05, 0.10);
const COLOR_GRID = new THREE.Color(0.06, 0.06, 0.15); // default cell background
const COLOR_GRID_LINE = 0x2a2a3e;
const COLOR_M = 0x444488;
const COLOR_M_BRIGHT = 0x8888ff;
const COLOR_F = 0x886666;
const COLOR_F_BRIGHT = 0xffaaaa;
//same but for canvas:
const COLOR_M_STR = "#" + COLOR_M.toString(16).padStart(6, "0");
const COLOR_M_BRIGHT_STR = "#" + COLOR_M_BRIGHT.toString(16).padStart(6, "0");
const COLOR_F_STR = "#" + COLOR_F.toString(16).padStart(6, "0");
const COLOR_F_BRIGHT_STR = "#" + COLOR_F_BRIGHT.toString(16).padStart(6, "0");
// Histogram colors (by graphMode):
HISTO_COLORS=[
[], // graphMode 0 has no histograms
['#a8a8a8', '#ff8800', '#4444ff', '#00ffff', '#ffff00', '#ff0088'], // age, energy, n_kin, happiness, trust
['#C5547C', '#B66D00', '#3D9640', '#0094B9', '#7E6ED3', '#808080'], // big 5
['#FF5555', '#5555FF', '#808080', '#808080', '#808080', '#808080'], // race
['#55FF55', '#FF5555', '#808080', '#808080', '#808080', '#808080'] // culture
];
// Compute color based on Prisoner's Dilemma outcomes [cc, cd, dd]
// Returns { r, g, b } with values in [0, 1] for Three.js or [0, 255] for canvas
function computePDColor(pd, forCanvas = false) {
if (!pd || pd.length < 3) {
// No PD data - return default grid color
return forCanvas
? { r: Math.round(0.06 * 255), g: Math.round(0.06 * 255), b: Math.round(0.15 * 255) }
: { r: 0.06, g: 0.06, b: 0.15 };
}
const [cc, cd, dd] = pd;
const total = cc + cd + dd;
if (total === 0) {
// No games played - return default grid color
return forCanvas
? { r: Math.round(0.06 * 255), g: Math.round(0.06 * 255), b: Math.round(0.15 * 255) }
: { r: 0.06, g: 0.06, b: 0.15 };
}
// redgreen: 0 = more cooperation (green), 1 = more defection (red)
const ccPlusDd = cc + dd;
const redgreen = ccPlusDd > 0 ? (1 + (dd - cc) / ccPlusDd) / 2 : 0.5;
// yellow: proportion of mixed outcomes (one cooperate, one defect)
const yellow = cd / total;
// brightness: scales with activity, capped at 400 games
const brightness = Math.min(400, total) / 400;
// Calculate RGB components
const r = 0.05 + 0.6 * brightness * ((1 - yellow) * redgreen + yellow);
const g = 0.05 + 0.6 * brightness * ((1 - yellow) * (1 - redgreen) + yellow);
const b = 0.05 + 0.6 * brightness * ((1 - yellow) * (0.5 - Math.abs(redgreen) / 2));
if (forCanvas) {
return {
r: Math.round(Math.max(0, Math.min(1, r)) * 255),
g: Math.round(Math.max(0, Math.min(1, g)) * 255),
b: Math.round(Math.max(0, Math.min(1, b)) * 255)
};
}
return {
r: Math.max(0, Math.min(1, r/2)),
g: Math.max(0, Math.min(1, g/2)),
b: Math.max(0, Math.min(1, b/2))
};
}
function initThreeJS() {
const container = document.getElementById('canvas-container');
const canvas = document.getElementById('threejs-canvas');
scene = new THREE.Scene();
scene.background = COLOR_EMPTY;
// Orthographic camera - we'll update bounds dynamically
if(ORTHOGRAPHIC){
camera = new THREE.OrthographicCamera(-10, 10, 10, -10, 0.1, 1000);
} else {
// option for 3d effects, but need to move camera position when zooming for this
camera = new THREE.PerspectiveCamera(5, 1.6, 0.05, 2000);
}
camera.position.set(0, 80, 0);
camera.lookAt(0, 0, 0);
renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
renderer.setSize(container.clientWidth, container.clientHeight);
renderer.setPixelRatio(window.devicePixelRatio);
// Create grid lines
createGridLines();
// Create cell instanced mesh for cooperation display
setupCellMesh();
// Ambient light
const ambientLight = new THREE.AmbientLight(0xffffff, ORTHOGRAPHIC ? 1 : 0.4);
scene.add(ambientLight);
// Directional light for 3D depth cues (perspective mode only)
if (!ORTHOGRAPHIC) {
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(0, 1, 1); // Light from upper-front-right
scene.add(directionalLight);
}
// Initial camera update
updateCameraProjection();
initSharedAgentGeometries()
}
function initSharedAgentGeometries() {
sharedAgentGeometries = {
m: createGeometry(false),
f: createGeometry(true)
};
console.log('Shared agent geometries initialized');
console.log('Male geometry type:', sharedAgentGeometries.m.type);
console.log('Female geometry type:', sharedAgentGeometries.f.type);
console.log('Male geometry vertices:', sharedAgentGeometries.m.attributes.position?.count);
console.log('Female geometry vertices:', sharedAgentGeometries.f.attributes.position?.count);
}
/**
* Creates agent geometry at unit scale.
* @param {boolean} isFemale - If true, creates wider/shorter variant
* @returns {THREE.BufferGeometry}
*/
function createGeometry(isFemale) {
// Unit scale dimensions (will be multiplied by baseSize via mesh.scale)
let geometry = new THREE.BufferGeometry();
if(ORTHOGRAPHIC){
const frontWidth = isFemale ? 0.6 : 0.0;
const backWidth = isFemale ? 0.6 : 0.8;
const height = isFemale ? 0.6 : 0.6;
// Trapezoid: front (narrow) at +Y, back (wide) at -Y
// Two triangles to form the quad
const vertices = isFemale?
(new Float32Array([
// Triangle 1: bottom-left, bottom-right, top-right
-backWidth/2, -height/2, 0,
backWidth/2, -height/2, 0,
frontWidth/2, height/2, 0,
// Triangle 2: bottom-left, top-right, top-left
-backWidth/2, -height/2, 0,
frontWidth/2, height/2, 0,
-frontWidth/2, height/2, 0
])) :
(new Float32Array([
// Triangle 1: bottom-left, bottom-right, top-center
-backWidth/2, -height/2, 0,
backWidth/2, -height/2, 0,
0, height/2, 0,
]));
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
}
else{
if(isFemale){
//geometry = new THREE.BoxGeometry( 0.45, 2.5, 0.45 ); // cube
geometry = new THREE.ConeGeometry( 0.4, 0.6, 4 ); // pyramid
} else {
geometry = new THREE.ConeGeometry(0.4, 0.6, 3); // tetrahedron
}
}
return geometry;
}
function createGridLines() {
// Remove old grid lines if they exist