File size: 194,328 Bytes
1dab883
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Neuraxon Game of Life v3.0 (3d) - By David Vivancos & Dr. Jose Sanchez for Qubic Science</title>
    <style>

        * {

            margin: 0;

            padding: 0;

            box-sizing: border-box;

        }



        body {

            font-family: 'Consolas', 'Courier New', monospace;

            background: #000;

            color: #eee;

            overflow: hidden;

        }



        #gameCanvas {

            display: block;

            width: 100vw;

            height: 100vh;

            outline: none;

        }



        

        .splash-screen {

    position: fixed;

    top: 0;

    left: 0;

    width: 100%;

    height: 100%;    

    background: #000 url('GameOfLife3.0ByDavidVivancosAndJoseSanchez.jpg') center center no-repeat;

    background-size: 100% 100%; 

    display: flex;

    flex-direction: column;

    justify-content: center;

    align-items: center;

    z-index: 1000;

    animation: fadeIn 0.5s;

}



        @keyframes fadeIn {

            from { opacity: 0; }

            to { opacity: 1; }

        }



        .splash-screen h1 {

            font-size: 48px;

            color: #28b46c;

            text-align: center;

            margin-bottom: 20px;

            text-shadow: 0 0 20px rgba(40, 180, 108, 0.5);

        }



        .splash-screen p {

            font-size: 18px;

            color: #aaa;

            text-align: center;

            margin: 10px 0;

        }



        .config-screen {

            position: fixed;

            top: 0;

            left: 0;

            width: 100%;

            height: 100%;

            background: rgba(15, 15, 18, 0.95);

            display: flex;

            flex-direction: column;

            align-items: center;

            padding: 50px 20px;

            overflow-y: auto;

            z-index: 999;

        }



        .config-screen h1 {

            font-size: 32px;

            color: #ebebf0;

            margin-bottom: 40px;

        }



        .slider-container {

            width: 700px;

            max-width: 90%;

            margin-bottom: 25px;

        }



        .slider-label {

            font-size: 16px;

            color: #dcdcdc;

            margin-bottom: 8px;

        }



        .slider-wrapper {

            display: flex;

            align-items: center;

            gap: 15px;

        }



        .slider {

            flex: 1;

            height: 6px;

            background: #646464;

            border-radius: 3px;

            outline: none;

            -webkit-appearance: none;

        }



        .slider::-webkit-slider-thumb {

            -webkit-appearance: none;

            appearance: none;

            width: 20px;

            height: 20px;

            background: #c8c8c8;

            border: 2px solid #969696;

            border-radius: 50%;

            cursor: pointer;

        }



        .slider-value {

            font-size: 16px;

            color: #ff0;

            min-width: 60px;

            text-align: right;

        }



        .start-button {

            margin-top: 30px;

            padding: 15px 40px;

            font-size: 18px;

            background: #23b45c;

            color: #fff;

            border: 2px solid #3cdc5a;

            border-radius: 8px;

            cursor: pointer;

            font-family: 'Consolas', monospace;

            transition: all 0.3s;

        }



        .start-button:hover {

            background: #2cd068;

            transform: scale(1.05);

        }



        .hud {

            position: fixed;

            top: 12px;

            right: 16px;

            background: rgba(0, 0, 0, 0.75);

            border: 1px solid #3c3c3c;

            border-radius: 8px;

            padding: 15px;

            min-width: 120px;

            max-width: 240px;

            max-height: 90vh;

            overflow-y: auto;

            z-index: 500;

        }



        .hud-title {

            font-size: 20px;

            font-weight: bold;

            color: #e6e6f0;

            margin-bottom: 15px;

            text-align: center;

        }



        .hud-section { margin-bottom: 10px; }

        .hud-section-title { font-size: 12px; color: #b4b4b4; margin-bottom: 6px; font-weight: bold; }

        

        .hud-entry {

            font-size: 10px;

            color: #e6e6e6;

            margin-bottom: 4px;

            display: flex;

            justify-content: space-between;

            cursor: pointer;

            padding: 3px 5px;

            border-radius: 3px;

            transition: background 0.2s;

        }

        .hud-entry:hover { background: rgba(255, 255, 255, 0.2); }



        .hud-dot {

            display: inline-block;

            width: 10px;

            height: 10px;

            border-radius: 50%;

            margin-right: 8px;

            border: 1px solid rgba(0,0,0,0.3);

        }



        .hud-stats { font-size: 12px; color: #dcdcdc; margin-bottom: 0px; }

        .button-group { display: flex; flex-direction: column; gap: 4px; margin-top: 10px; }

        .button-row { display: flex; gap: 8px; }



        .hud-button {

            flex: 1;

            padding: 8px 12px;

            font-size: 13px;

            background: #232328;

            color: #e6e6e6;

            border: 1px solid #5a5a64;

            border-radius: 6px;

            cursor: pointer;

            font-family: 'Consolas', monospace;

            transition: all 0.2s;

        }

        .hud-button:hover { background: #2d2d35; border-color: #7a7a84; }

        .hud-button:active { transform: scale(0.98); }



        .detail-panel {

            position: fixed;

            top: 12px;

            right: 360px;

            background: rgba(0, 0, 0, 0.75);

            border: 1px solid #505050;

            border-radius: 8px;

            padding: 15px;

            min-width: 320px;

            max-width: 400px;

            max-height: 90vh;

            overflow-y: auto;

            z-index: 500;

        }



        .detail-title { font-size: 18px; font-weight: bold; color: #e6e6f0; margin-bottom: 12px; }

        .detail-info { font-size: 13px; color: #dcdcdc; margin-bottom: 3px; }

        .detail-section { margin-top: 12px; padding-top: 12px; border-top: 1px solid #3c3c3c; }



        .modal {

            position: fixed;

            top: 50%;

            left: 50%;

            transform: translate(-50%, -50%);

            background: #0f0f12;

            border: 2px solid #5a5a64;

            border-radius: 12px;

            padding: 30px;

            z-index: 1001;

            min-width: 400px;

            box-shadow: 0 10px 40px rgba(0,0,0,0.8);

        }



        .modal-overlay {

            position: fixed;

            top: 0;

            left: 0;

            width: 100%;

            height: 100%;

            background: rgba(0, 0, 0, 0.6);

            z-index: 1000;

        }



        .modal-title { font-size: 20px; font-weight: bold; color: #ebebf0; margin-bottom: 10px; text-align: center; }

        .modal-subtitle { font-size: 14px; color: #dcdcdc; margin-bottom: 30px; text-align: center; }

        .modal-buttons { display: flex; gap: 20px; justify-content: center; }

        .modal-button { padding: 12px 40px; font-size: 16px; border-radius: 10px; cursor: pointer; font-family: 'Consolas', monospace; border: 2px solid; transition: all 0.3s; }

        

        .modal-button.yes { background: #232328; color: #ebebf0; border-color: #6e6e82; }

        .modal-button.yes:hover { background: #2d2d35; }

        .modal-button.no { background: #232328; color: #ebebf0; border-color: #6e6e82; }

        .modal-button.no:hover { background: #2d2d35; }



        .hidden { display: none !important; }



        .controls-hint {

            position: fixed;

            bottom: 20px;

            left: 20px;

            background: rgba(0, 0, 0, 0.65);

            border: 1px solid #3c3c3c;

            border-radius: 8px;

            padding: 12px 20px;

            font-size: 12px;

            color: #aaa;

            pointer-events: auto;

            z-index: 500;

        }



        .controls-hint div { margin-bottom: 4px; }

        a:visited { color: white; }



        /* Loading spinner for 3D init */

        #loader {

            position: absolute;

            top: 50%; left: 50%;

            transform: translate(-50%, -50%);

            color: white;

            font-size: 24px;

            z-index: 2000;

            display: none;

        }

    </style>
    
    <!-- Import Map for Three.js -->
    <script type="importmap">

        {

            "imports": {

                "three": "https://unpkg.com/three@0.160.0/build/three.module.js",

                "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/",

                "postprocessing": "https://unpkg.com/postprocessing@6.33.0/build/postprocessing.esm.js"

            }

        }

    </script>
</head>
<body>
    <div id="loader">Initializing 3D World...</div>

    <!-- Splash Screen -->
    <div id="splashScreen" class="splash-screen">
        
        <p style="margin-top: auto; font-size: 14px; opacity: 0.7; text-align: center; padding-bottom: 20px;">Click anywhere to continue...</p>
    </div>

    <!-- Configuration Screen -->
    <div id="configScreen" class="config-screen hidden">
        <h1>Neuraxon Game Of Life 3.0 - World Configuration</h1>
        
        <div class="slider-container">
            <div class="slider-label">World Size (3D NxN Grid Sphere)</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="worldSize" min="30" max="200" value="150">
                <span class="slider-value" id="worldSizeValue">150</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Sea Percentage</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="seaPct" min="15" max="80" value="60">
                <span class="slider-value" id="seaPctValue">60%</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Rock Percentage</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="rockPct" min="1" max="30" value="10">
                <span class="slider-value" id="rockPctValue">5%</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Starting NxErs (initial population size)</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="startingNxErs" min="10" max="400" value="300">
                <span class="slider-value" id="startingNxErsValue">300</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Maximum Possible Number of NxErs</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="maxNxErs" min="50" max="1000" value="500">
                <span class="slider-value" id="maxNxErsValue">500</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Food Sources (Red Pyramids)</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="maxFood" min="50" max="1500" value="300">
                <span class="slider-value" id="maxFoodValue">300</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Food Respawn (seconds to reappear)</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="foodRespawn" min="200" max="1000" value="300">
                <span class="slider-value" id="foodRespawnValue">300</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Starting Food for each NxEr (Energy)</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="startFood" min="20" max="300" value="150">
                <span class="slider-value" id="startFoodValue">150</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Max Neurons per NxEr</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="maxNeurons" min="5" max="35" value="20">
                <span class="slider-value" id="maxNeuronsValue">20</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Global Time Steps (Mental Time Scale)</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="globalTimeSteps" min="30" max="120" value="60">
                <span class="slider-value" id="globalTimeStepsValue">60</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Mate Cooldown (seconds between mating again)</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="mateCooldown" min="5" max="30" value="10">
                <span class="slider-value" id="mateCooldownValue">10</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Day/Night Cycle Length (seconds per full cycle)</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="dayNightCycle" min="60" max="600" value="180">
                <span class="slider-value" id="dayNightCycleValue">180</span>
            </div>
        </div>

        <div class="slider-container">
            <div class="slider-label">Base Temperature (environment baseline °C)</div>
            <div class="slider-wrapper">
                <input type="range" class="slider" id="baseTemperature" min="15" max="35" value="25">
                <span class="slider-value" id="baseTemperatureValue">25</span>
            </div>
        </div>

        <div class="slider-container" style="margin-top: 20px; background: #1a1a20; padding: 15px; border-radius: 8px; border: 1px solid #333;">
          <label class="slider-label" style="display:flex; align-items:center; cursor: pointer; justify-content: space-between;">
              <span style="color: #4a9eff; font-weight: bold;">🌍 Use Simulated Earth Map (select 150 World Size for best results)</span>
              <input type="checkbox" id="useEarth" checked style="width:24px; height:24px; cursor: pointer; accent-color: #4a9eff;">
          </label>          
      </div>

      <button class="start-button" id="startButton">Start Simulation</button>
    </div>

    <!-- Game Canvas (WebGL) -->
    <canvas id="gameCanvas" class="hidden"></canvas>

    <!-- HUD -->
    <div id="hud" class="hud hidden">
        <div class="hud-title" id="hudTitle">Metrics: Round #1</div>
        <div id="hudContent"></div>
        <div id="hudStats"></div>
        <div class="button-group" id="buttonGroup"></div>
    </div>

    <!-- Detail Panel -->
    <div id="detailPanel" class="detail-panel hidden">
        <div class="detail-title" id="detailTitle"></div>
        <div id="detailContent"></div>
        <div class="button-group" id="detailButtons"></div>
    </div>

    <!-- Controls Hint -->
    <div id="controlsHint" class="controls-hint hidden">
        <div style="text-align: center;"><strong><a href="https://www.researchgate.net/publication/397331336_Neuraxon" target="_blank">Neuraxon</a> Game of Life 3.0 3d</strong></div>
        <div style="text-align: center;"><strong>By <a href="https://vivancos.com/" target="_blank">David Vivancos</a> & <a href="https://josesanchezgarcia.com/" target="_blank">Jose Sanchez</a></strong></div>
        <div style="text-align: center;"><strong>for <a href="https://qubic.org/" target="_blank">Qubic</a> Science</strong></div>
     
        <div>🖱️ Left Click + Drag: Rotate Camera</div>
        <div>🖱️ Right Click + Drag: Pan Camera</div>
        <div>🖱️ Scroll: Zoom</div>
        <div>🖱️ Click Object: Select NxEr</div>
        <div>⌨️ Space: Pause/Play</div>                
        <div>🌓 Day/Night cycle affects behavior & metabolism</div>
        <div>⌨️ H: Toggle HUD</div>  
        <div id="hideControlsHint" style="cursor: pointer; color: #4a9eff; text-decoration: underline; margin-top: 8px;">Hide Hints</div>  
    </div>

    <!-- Game Over Modal -->
    <div id="gameOverOverlay" class="modal-overlay hidden"></div>
    <div id="gameOverModal" class="modal hidden">
        <div class="modal-title">Extinction Event</div>
        <div class="modal-subtitle">Restart with genetic champions?</div>
        <div class="modal-buttons">
            <button class="modal-button yes" id="restartYes">Yes</button>
            <button class="modal-button no" id="restartNo">No</button>
        </div>
    </div>

    <script type="module">

        import * as THREE from 'three';

        import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

        import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';

        import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';

        import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';

        import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';



        // =====================================================================

        // LOGIC UTILITIES

        // =====================================================================

        

        function clamp(v, min, max) {

            return Math.max(min, Math.min(max, v));

        }



        function random(min, max) {

            return Math.random() * (max - min) + min;

        }



        function randomInt(min, max) {

            return Math.floor(Math.random() * (max - min + 1)) + min;

        }



        function randomChoice(arr) {

            return arr[Math.floor(Math.random() * arr.length)];

        }



        function base26Name(n) {

            let letters = [];

            let n0 = n;

            while (true) {

                const div = Math.floor(n0 / 26);

                const rem = n0 % 26;

                letters.push(String.fromCharCode(65 + rem));

                if (div === 0) break;

                n0 = div - 1;

            }

            return letters.reverse().join('');

        }



        function noise(x, y, scale, offset) {

            const ox = offset[0];

            const oy = offset[1];

            return (Math.sin((x + ox) * 0.15 * scale) +

                    Math.cos((y + oy) * 0.13 * scale) +

                    Math.sin(((x + ox) + (y + oy)) * 0.07 * scale)) * 0.333;

        }



        function stripLeadingDigits(name) {

            let i = 0;

            while (i < name.length && /\d/.test(name[i])) {

                i++;

            }

            return name.substring(i);

        }



        // =====================================================================

        // NEURAL NETWORK CLASSES v 2.00

        // =====================================================================

        

        class NetworkParameters {

            constructor(hiddenNeurons = 10) {

                this.networkName = "Neuraxon NxEr";

                this.numInputNeurons = 9; // v3.0: +DayNight, +Temperature, +Proprioception

                this.numHiddenNeurons = hiddenNeurons;

                this.numOutputNeurons = 6; // v3.0: +Rest/Sleep output

                this.dt = 1.0;

                this.simulationSteps = randomInt(20, 50);

                this.connectionProbability = random(0.10, 0.25);

                this.smallWorldK = 6;

                this.smallWorldRewireProb = 0.15;

                this.membraneTimeConstant = random(10.0, 40.0);

                this.firingThresholdExcitatory = random(0.6, 1.5);

                this.firingThresholdInhibitory = random(-1.5, -0.6);

                this.adaptationRate = random(0.01, 0.15);

                this.spontaneousFireRate = random(0.01, 0.05);

                this.neuronHealthDecay = random(0.0005, 0.005);

                this.numDendriticBranches = 3;

                this.branchThreshold = 0.6;

                this.plateauDecay = 500.0;

                this.tauFast = random(3.0, 8.0);

                this.tauSlow = random(30.0, 80.0);

                this.tauMeta = random(800.0, 2000.0);

                this.tauLTP = 15.0;

                this.tauLTD = 35.0;

                this.wFastInitMin = -1.0;

                this.wFastInitMax = 1.0;

                this.wSlowInitMin = -0.5;

                this.wSlowInitMax = 0.5;

                this.wMetaInitMin = -0.3;

                this.wMetaInitMax = 0.3;

                this.learningRate = random(0.005, 0.03);

                this.stdpWindow = random(15.0, 35.0);

                this.plasticityThreshold = 0.5;

                this.associativityStrength = random(0.05, 0.15);

                this.synapseIntegrityThreshold = 0.1;

                this.synapseFormationProb = random(0.01, 0.05);

                this.synapseDeathProb = random(0.005, 0.02);

                this.neuronDeathThreshold = 0.1;

                this.dopamineBaseline = random(0.08, 0.20);

                this.serotoninBaseline = random(0.08, 0.20);

                this.acetylcholineBaseline = random(0.08, 0.20);

                this.norepinephrineBaseline = random(0.08, 0.20);

                this.neuromodDecayRate = 0.1;

                this.energyBaseline = 100.0;

                this.firingEnergyCost = random(3.0, 8.0);

                this.plasticityEnergyCost = 10.0;

                this.metabolicRate = random(0.8, 1.3);

                this.recoveryRate = 0.5;

                this.targetFiringRate = 0.1;

                this.homeostaticPlasticityRate = 0.001;

                this.oscillatorLowFreq = 0.05;

                this.oscillatorMidFreq = 0.5;

                this.oscillatorHighFreq = 4.0;

                this.oscillatorStrength = 0.15;

                this.phaseCouplingStrength = 0.1;

                this.maxAxonalDelay = 10.0;

            }



            clone() {

                const p = new NetworkParameters(this.numHiddenNeurons);

                Object.assign(p, this);

                return p;

            }

        }



        class DendriticBranch {

            constructor(branchId, parentNeuronId, params) {

                this.branchId = branchId;

                this.parentNeuronId = parentNeuronId;

                this.params = params;

                this.branchPotential = 0.0;

                this.plateauPotential = 0.0;

                this.localSpikeHistory = [];

            }

            integrateInputs(synapticInputs, dt) {

                if (!synapticInputs || synapticInputs.length === 0) {

                    this.plateauPotential += dt / this.params.plateauDecay * (-this.plateauPotential);

                    this.branchPotential += dt / (this.params.membraneTimeConstant * 0.5) * (-this.branchPotential);

                    return this.branchPotential + this.plateauPotential;

                }

                const linearSum = synapticInputs.reduce((sum, val) => sum + val, 0);

                const branchSignal = Math.tanh(linearSum);

                if (Math.abs(branchSignal) > this.params.branchThreshold) {

                    this.plateauPotential = branchSignal * 0.8;

                }

                const tauBranch = Math.max(1.0, this.params.membraneTimeConstant * 0.3);

                this.branchPotential += dt / tauBranch * (branchSignal - this.branchPotential);

                this.localSpikeHistory.push(Math.abs(this.branchPotential) > this.params.branchThreshold ? 1.0 : 0.0);

                if (this.localSpikeHistory.length > 10) this.localSpikeHistory.shift();

                return this.branchPotential + this.plateauPotential;

            }

        }



        class Synapse {

            constructor(preId, postId, params) {

                this.preId = preId;

                this.postId = postId;

                this.params = params;

                this.wFast = random(params.wFastInitMin, params.wFastInitMax);

                this.wSlow = random(params.wSlowInitMin, params.wSlowInitMax);

                this.wMeta = random(params.wMetaInitMin, params.wMetaInitMax);

                this.isSilent = Math.random() < 0.1;

                this.isModulatory = Math.random() < 0.2;

                this.integrity = 1.0;

                this.axonalDelay = random(0, params.maxAxonalDelay);

                this.preTrace = 0.0;

                this.postTrace = 0.0;

                this.preTraceLTD = 0.0;

                this.learningRateMod = 1.0;

                this.neighborSynapses = [];

                this.potentialDeltaW = 0.0;

            }

            computeInput(preState) {

                if (this.isSilent) return 0.0;

                const delayFactor = Math.max(0.0, 1.0 - this.axonalDelay / 10.0);

                return (this.wFast + this.wSlow) * preState * delayFactor;

            }

            calculateDeltaW(preState, postState, neuromodulators, dt) {

                this.preTrace += (-this.preTrace / this.params.tauLTP + (preState === 1 ? 1 : 0)) * dt;

                this.preTraceLTD += (-this.preTraceLTD / this.params.tauLTD + (preState === 1 ? 1 : 0)) * dt;

                this.postTrace += (-this.postTrace / this.params.tauLTP + (postState === 1 ? 1 : 0)) * dt;

                const da = neuromodulators.dopamine || 0.5;

                const daHigh = da > 0.01 ? 1.0 : 0.0;

                const daLow = da > 1.0 ? 1.0 : 1.0;

                this.learningRateMod = 1.0 + (daHigh * 0.5) + (daLow * 0.2);

                let deltaW = 0;

                if (preState === 1 && postState === 1) {

                    deltaW = this.params.learningRate * this.learningRateMod * daHigh * this.preTrace;

                } else if (preState === 1 && postState === -1) {

                    deltaW = -this.params.learningRate * this.learningRateMod * daLow * this.preTraceLTD;

                }

                return deltaW;

            }

            applyUpdate(dt, neuromodulators, neighborDeltas) {

                let deltaW = this.potentialDeltaW;

                if (neighborDeltas && neighborDeltas.length > 0) {

                    const assoc = this.params.associativityStrength * 

                        neighborDeltas.slice(0, 3).reduce((sum, dw, i) => sum + dw / (i + 1), 0);

                    deltaW += assoc;

                }

                const hFast = this.preTrace;

                const hSlow = 0.5 * this.preTrace + 0.5 * this.postTrace;

                this.wFast += dt / this.params.tauFast * (-this.wFast + hFast + deltaW * 0.3);

                this.wFast = clamp(this.wFast, -1.0, 1.0);

                this.wSlow += dt / this.params.tauSlow * (-this.wSlow + hSlow + deltaW * 0.1);

                this.wSlow = clamp(this.wSlow, -1.0, 1.0);

                const serotonin = neuromodulators.serotonin || 0.5;

                const metaTarget = deltaW * 0.05 * (serotonin > 0.5 ? 1.0 : 0.5);

                this.wMeta += dt / this.params.tauMeta * (-this.wMeta + metaTarget);

                this.wMeta = clamp(this.wMeta, -0.5, 0.5);

                const activity = Math.abs(this.wFast) + Math.abs(this.wSlow);

                if (activity < 0.01) this.integrity -= this.params.synapseDeathProb * dt;

                else this.integrity = Math.min(1.0, this.integrity + 0.001 * dt * activity);

                if (this.isSilent && this.preTrace > 0.5 && Math.random() < 0.01) this.isSilent = false;

            }

            getModulatoryEffect() { return this.isModulatory ? this.wMeta * 0.5 : 0.0; }

        }



        class Neuraxon {

            constructor(id, type, params) {

                this.id = id;

                this.type = type;

                this.params = params;

                this.membranePotential = 0.0;

                this.trinaryState = 0;

                this.adaptation = 0.0;

                this.autoreceptor = 0.0;

                this.health = 1.0;

                this.isActive = true;

                this.dendriticBranches = [];

                for (let i = 0; i < params.numDendriticBranches; i++) {

                    this.dendriticBranches.push(new DendriticBranch(i, id, params));

                }

                this.energyLevel = params.energyBaseline;

                this.lastFiringTime = -1000.0;

                this.phase = Math.random() * 2 * Math.PI;

                this.naturalFrequency = random(0.5, 2.0);

                this.stateHistory = [];

                this.intrinsicTimescale = params.membraneTimeConstant;

            }

            nonlinearDendriticIntegration(synapticInputs, modulatoryInputs, dt) {

                const branchOutputs = [];

                let totalSynaptic = 0.0;

                for (let i = 0; i < this.dendriticBranches.length; i++) {

                    const branch = this.dendriticBranches[i];

                    const branchSynInputs = [];

                    for (let j = i; j < synapticInputs.length; j += this.dendriticBranches.length) {

                        branchSynInputs.push(synapticInputs[j]);

                    }

                    const branchOut = branch.integrateInputs(branchSynInputs, dt);

                    branchOutputs.push(branchOut);

                    totalSynaptic += branchOut;

                }

                const totalModulatory = modulatoryInputs.reduce((sum, val) => sum + val, 0);

                totalSynaptic *= (1.0 + totalModulatory * 0.2);

                return [totalSynaptic, branchOutputs];

            }

            updatePhaseOscillator(dt, globalOsc) {

                const dPhase = 2 * Math.PI * this.naturalFrequency * dt;

                const coupling = this.params.phaseCouplingStrength * Math.sin(globalOsc - this.phase) * dt;

                this.phase += dPhase + coupling;

                this.phase %= 2 * Math.PI;

            }

            updateEnergy(activity, plasticityCost, dt) {

                if (!this.isActive) return;

                const consumption = this.params.metabolicRate * (this.params.firingEnergyCost * activity + this.params.plasticityEnergyCost * plasticityCost) * dt;

                const recovery = this.params.recoveryRate * (1.0 - activity) * dt;

                this.energyLevel += (recovery - consumption);

                this.energyLevel = clamp(this.energyLevel, 0, this.params.energyBaseline * 1.5);

                if (this.energyLevel < 10.0) {

                    this.health -= this.params.neuronHealthDecay * dt * 2.0;

                    this.membranePotential *= 0.9;

                }

            }

            updateAutocorrelation() {

                if (this.stateHistory.length < 10) return;

                const states = this.stateHistory.slice(-10);

                let sum1 = 0, sum2 = 0;

                for (let i = 0; i < states.length - 1; i++) {

                    sum1 += states[i] * states[i + 1];

                    sum2 += states[i] * states[i];

                }

                const autocorr = sum2 > 0 ? sum1 / sum2 : 0;

                if (!isNaN(autocorr)) this.intrinsicTimescale = this.params.membraneTimeConstant * (1.0 + Math.abs(autocorr) * 2.0);

            }

            update(synapticInputs, modulatoryInputs, externalInput, neuromodulators, dt, globalOsc) {

                if (!this.isActive || this.energyLevel <= 0) return;

                this.updatePhaseOscillator(dt, globalOsc);

                const [totalSynaptic, branchOutputs] = this.nonlinearDendriticIntegration(synapticInputs, modulatoryInputs, dt);

                let spontaneous = 0.0;

                const spontProb = this.params.spontaneousFireRate * dt * (1.0 + Math.cos(this.phase) * 0.3);

                if (Math.random() < spontProb) spontaneous = random(-0.5, 0.5);

                const acetylcholine = neuromodulators.acetylcholine || 0.5;

                const norepi = neuromodulators.norepinephrine || 0.5;

                const thresholdMod = (acetylcholine - 0.5) * 0.5 + modulatoryInputs.reduce((sum, val) => sum + val, 0) * 0.3;

                const gain = 1.0 + (norepi - 0.5) * 0.4;

                const drive = (totalSynaptic + externalInput + spontaneous) * gain;

                const tauEff = Math.max(1.0, this.intrinsicTimescale);

                this.membranePotential += dt / tauEff * (-this.membranePotential + drive - this.adaptation);

                this.adaptation += dt / 100.0 * (-this.adaptation + 0.1 * Math.abs(this.trinaryState));

                this.autoreceptor += dt / 200.0 * (-this.autoreceptor + 0.2 * this.trinaryState);

                const thetaExc = this.params.firingThresholdExcitatory - thresholdMod - 0.1 * this.autoreceptor;

                const thetaInh = this.params.firingThresholdInhibitory - thresholdMod + 0.1 * this.autoreceptor;

                const prevState = this.trinaryState;

                if (this.membranePotential > thetaExc) this.trinaryState = 1;

                else if (this.membranePotential < thetaInh) this.trinaryState = -1;

                else this.trinaryState = 0;

                this.stateHistory.push(this.trinaryState);

                if (this.stateHistory.length > 50) this.stateHistory.shift();

                this.updateAutocorrelation();

                const activityLevel = Math.abs(this.trinaryState);

                if (activityLevel < 0.01) this.health -= this.params.neuronHealthDecay * dt;

                else this.health = Math.min(1.0, this.health + 0.0005 * dt);

                const plasticityCost = Math.abs(this.trinaryState - prevState) * 0.1;

                this.updateEnergy(activityLevel, plasticityCost, dt);

                if (this.type === 'hidden' && (this.health < this.params.neuronDeathThreshold || this.energyLevel < 1.0)) {

                    if (Math.random() < 0.001) this.isActive = false;

                }

            }

            setState(state) {

                if ([-1, 0, 1].includes(state)) {

                    this.trinaryState = state;

                    this.membranePotential = state * this.params.firingThresholdExcitatory;

                }

            }

        }



        class NeuraxonNetwork {

            constructor(params) {

                this.params = params || new NetworkParameters();

                this.inputNeurons = [];

                this.hiddenNeurons = [];

                this.outputNeurons = [];

                this.allNeurons = [];

                this.synapses = [];

                this.neuromodulators = {

                    dopamine: this.params.dopamineBaseline,

                    serotonin: this.params.serotoninBaseline,

                    acetylcholine: this.params.acetylcholineBaseline,

                    norepinephrine: this.params.norepinephrineBaseline

                };

                this.time = 0.0;

                this.stepCount = 0;

                this.totalEnergyConsumed = 0.0;

                this.oscillatorPhaseOffsets = [Math.random() * 2 * Math.PI, Math.random() * 2 * Math.PI, Math.random() * 2 * Math.PI];

                this.activationHistory = [];

                this.branchingRatio = 1.0;

                this.initializeNeurons();

                this.initializeSynapses();

            }

            initializeNeurons() {

                let nid = 0;

                for (let i = 0; i < this.params.numInputNeurons; i++) {

                    const n = new Neuraxon(nid++, 'input', this.params);

                    this.inputNeurons.push(n);

                    this.allNeurons.push(n);

                }

                for (let i = 0; i < this.params.numHiddenNeurons; i++) {

                    const n = new Neuraxon(nid++, 'hidden', this.params);

                    this.hiddenNeurons.push(n);

                    this.allNeurons.push(n);

                }

                for (let i = 0; i < this.params.numOutputNeurons; i++) {

                    const n = new Neuraxon(nid++, 'output', this.params);

                    this.outputNeurons.push(n);

                    this.allNeurons.push(n);

                }

            }

            initializeSynapses() {

                const numNeurons = this.allNeurons.length;

                if (numNeurons <= 1) return;

                const k = Math.max(2, Math.min(numNeurons - 1, this.params.smallWorldK));

                const rewireP = clamp(this.params.smallWorldRewireProb, 0, 1);

                const existing = new Set();

                for (let idx = 0; idx < numNeurons; idx++) {

                    const pre = this.allNeurons[idx];

                    for (let offset = 1; offset <= Math.floor(k / 2); offset++) {

                        let j = (idx + offset) % numNeurons;

                        let post = this.allNeurons[j];

                        if (Math.random() < rewireP) {

                            const candidates = this.allNeurons.filter(n => n.id !== pre.id);

                            if (candidates.length > 0) post = randomChoice(candidates);

                        }

                        if (pre.id === post.id) continue;

                        if (pre.type === 'output' && post.type === 'input') continue;

                        const key = `${pre.id},${post.id}`;

                        if (existing.has(key)) continue;

                        const syn = new Synapse(pre.id, post.id, this.params);

                        this.synapses.push(syn);

                        existing.add(key);

                    }

                }

                for (const pre of this.allNeurons) {

                    for (const post of this.allNeurons) {

                        if (pre.id === post.id) continue;

                        if (pre.type === 'output' && post.type === 'input') continue;

                        if (Math.random() < this.params.connectionProbability * 0.25) {

                            const key = `${pre.id},${post.id}`;

                            if (existing.has(key)) continue;

                            const syn = new Synapse(pre.id, post.id, this.params);

                            this.synapses.push(syn);

                            existing.add(key);

                        }

                    }

                }

                for (const syn of this.synapses) {

                    syn.neighborSynapses = this.synapses.filter(s => s.preId === syn.preId && s.postId !== syn.postId);

                }

            }

            globalOscillatoryDrive() {

                const t = this.time;

                const low = Math.sin(2.0 * Math.PI * this.params.oscillatorLowFreq * t + this.oscillatorPhaseOffsets[0]);

                const mid = Math.sin(2.0 * Math.PI * this.params.oscillatorMidFreq * t + this.oscillatorPhaseOffsets[1]);

                const high = Math.sin(2.0 * Math.PI * this.params.oscillatorHighFreq * t + this.oscillatorPhaseOffsets[2]);

                return this.params.oscillatorStrength * (low * 0.5 + low * mid * 0.3 + mid * high * 0.2);

            }

            simulateStep(externalInputs = {}) {

                const dt = this.params.dt;

                const oscDrive = this.globalOscillatoryDrive();

                const synInputs = {};

                const modInputs = {};

                this.allNeurons.forEach(n => { synInputs[n.id] = []; modInputs[n.id] = []; });

                for (const s of this.synapses) {

                    if (s.integrity <= 0) continue;

                    const pre = this.allNeurons[s.preId];

                    if (!pre || !pre.isActive) continue;

                    synInputs[s.postId].push(s.computeInput(pre.trinaryState));

                    const mod = s.getModulatoryEffect();

                    if (mod !== 0) modInputs[s.postId].push(mod);

                }

                for (const n of this.allNeurons) {

                    if (!n.isActive) continue;

                    const ext = externalInputs[n.id] || 0.0;

                    n.update(synInputs[n.id], modInputs[n.id], ext + oscDrive, this.neuromodulators, dt, oscDrive);

                    this.activationHistory.push(Math.abs(n.trinaryState));

                }

                if (this.activationHistory.length > 1000) this.activationHistory.shift();

                for (const s of this.synapses) {

                    if (s.integrity <= 0) continue;

                    const pre = this.allNeurons[s.preId];

                    const post = this.allNeurons[s.postId];

                    if (pre && pre.isActive && post && post.isActive) {

                        s.potentialDeltaW = s.calculateDeltaW(pre.trinaryState, post.trinaryState, this.neuromodulators, dt);

                    }

                }

                for (const s of this.synapses) {

                    if (s.integrity <= 0) continue;

                    const pre = this.allNeurons[s.preId];

                    const post = this.allNeurons[s.postId];

                    if (pre && pre.isActive && post && post.isActive) {

                        s.applyUpdate(dt, this.neuromodulators, s.neighborSynapses.map(ns => ns.potentialDeltaW));

                    }

                }

                this.neuromodulators.dopamine = clamp(this.neuromodulators.dopamine + oscDrive * 0.02, 0, 2);

                this.neuromodulators.serotonin = clamp(this.neuromodulators.serotonin + oscDrive * 0.01, 0, 2);

                this.neuromodulators.acetylcholine = clamp(this.neuromodulators.acetylcholine + oscDrive * 0.01, 0, 2);

                this.neuromodulators.norepinephrine = clamp(this.neuromodulators.norepinephrine + oscDrive * 0.015, 0, 2);

                

                if (this.stepCount % 100 === 0) {

                    for (const neuron of this.hiddenNeurons) {

                        if (neuron.stateHistory.length === 0) continue;

                        const recentActivity = neuron.stateHistory.reduce((sum, s) => sum + Math.abs(s), 0) / neuron.stateHistory.length;

                        if (recentActivity > this.params.targetFiringRate * 1.2) neuron.params.firingThresholdExcitatory += this.params.homeostaticPlasticityRate;

                        else if (recentActivity < this.params.targetFiringRate * 0.8) neuron.params.firingThresholdExcitatory -= this.params.homeostaticPlasticityRate;

                    }

                }

                this.synapses = this.synapses.filter(s => s.integrity > this.params.synapseIntegrityThreshold);

                if (Math.random() < this.params.synapseFormationProb) {

                    const active = this.allNeurons.filter(n => n.isActive && n.energyLevel > 20);

                    if (active.length >= 2) {

                        const pre = randomChoice(active);

                        const post = randomChoice(active);

                        if (pre.id !== post.id && !(pre.type === 'output' && post.type === 'input')) {

                            if (!this.synapses.some(s => s.preId === pre.id && s.postId === post.id)) {

                                this.synapses.push(new Synapse(pre.id, post.id, this.params));

                            }

                        }

                    }

                }

                if (this.activationHistory.length > 2) {

                    const activations = this.activationHistory.slice(-100);

                    const denom = activations.slice(0, -1).reduce((sum, val) => sum + val, 0);

                    if (denom > 0) this.branchingRatio = clamp(activations.slice(1).reduce((sum, val) => sum + val, 0) / denom, 0.1, 10.0);

                }

                this.time += dt;

                this.stepCount++;

            }

            setInputStates(states) { states.forEach((state, i) => { if (i < this.inputNeurons.length) this.inputNeurons[i].setState(state); }); }

            getOutputStates() { return this.outputNeurons.map(n => n.isActive ? n.trinaryState : 0); }

            getEnergyStatus() {

                const activeNeurons = this.allNeurons.filter(n => n.isActive);

                if (activeNeurons.length === 0) return { totalEnergy: 0, averageEnergy: 0, efficiency: 0, branchingRatio: this.branchingRatio };

                const totalEnergy = activeNeurons.reduce((sum, n) => sum + n.energyLevel, 0);

                return { totalEnergy, averageEnergy: totalEnergy / activeNeurons.length, efficiency: this.stepCount > 0 ? this.totalEnergyConsumed / this.stepCount : 0, branchingRatio: this.branchingRatio };

            }

            clone() { return new NeuraxonNetwork(this.params.clone()); }

        }



        // =====================================================================

        // WORLD GENERATION (Data-Based Earth Map)

        // =====================================================================

        

        const TERRAIN_SEA = 0;

        const TERRAIN_LAND = 1;

        const TERRAIN_ROCK = 2;



        class World {

            constructor(N, seaPct, rockPct, useEarth = false) {

                this.N = N;

                this.grid = Array(N).fill(null).map(() => Array(N).fill(TERRAIN_LAND));

                this.noiseOffsets = [

                    [Math.random() * 1000, Math.random() * 1000],

                    [Math.random() * 1000, Math.random() * 1000],

                    [Math.random() * 1000, Math.random() * 1000],

                    [Math.random() * 1000, Math.random() * 1000],

                    [Math.random() * 1000, Math.random() * 1000] 

                ];



                if (useEarth) {

                    this.generateEarth();

                } else {

                    this.generate(seaPct, rockPct);

                }

            }



            // --- REAL EARTH DATA MAP ---

            generateEarth() {             

             

         

// . = Sea

// : = Land

// ^ = Mountains (Andes, Rockies, Himalayas, Alps)

// = = Ice (polar regions)

const earthMap = [

    "................................................................................................................................................................................................................................................",

"................................................................................................................................................................................................................................................",

"................................................................................................................................................................................................................................................",

"................................................................................................................................................................................................................................................",

"..............................................................................................^^^^^^^^^.........................................................................................................................................",

"...........................................................^^^^^^^^^^^^^^^^^..^^^^^^^^^^^^^^^^^^^^^^^^^^^...^^^.................................................................................................................................",

"........................................................^^^^^^...^^^^^^^^..^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^........................^^^^^^.............^^............................^^^^^......................................................",

".............................................^....^^^.^^.^^^^.^^^^^^^....^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.....................^^^^^......................................................^^^..................................................",

"........................................^^...................^^^^^^.......^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^......................^^^........................................................^^..................................................",

"..........................................^^^^.^^...^^^...^^....^...............^^^^^^^^^^^^^^^^^^^^^^^^^^^....................................................^^^^...................^^^^^^^^^^^^^^................^^^^........................",

".....................................^^^..........................................^^^^^^^^^^^^^^^^^^^^^^^^...................................................^^...................^^^^^^^^^^^^^^^...............................................",

".....................................^^^^.^^^.^.^^..^^^.^^..^^^^^^.................^^^^^^^^^^^^^^^^^^^^^^..................................................^^.........^^......^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.......^^.........................",

"^^.............^......................^...^^^^^^^^......^^..^^^^^^^^^^^^.............^^^^^^^^^^^^^^^^^^^^..................................................^^^.......^^^.^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^..^^^^^^^^^^^^^..................^",

"...........^^^^^^^^^^^^^^^......^^^^..^...^^^^^^^^^^^.^.^^.....^....^^^^^^^.........^^^^^^^^^^^^^^^^^^^^.............................^^^^^^^^^..................^....^^^.^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.......^^^^^..",

"^^.......^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^....^^....^^.^^^^..^^......^^^^..........^^^^^^^^^^^^^^^..............................^^^^^^^^^^^^^^^^...^^...^^.^^^^^^^^.^^^.^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^",

"^^^.^^......^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^......^^^^^^^^.....^^^^^^^^^^^^^................................^^^^^^^^^^^^^^^^^^...^^^^^^^^^^^^^^^^^^.^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^",

"...^^....^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^....^^^^^^^..^.......^^^^^^^^............^^^^^^.................^^^^^^...^^^^^^....^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^",

".............^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^..^^.^^.....^^^^^.........^^^^^^^.............^^..................^^^^^^^..^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.",

"..........^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^......^...^^^...^^...........^^^^^................................^^^^^^^^..^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^^^^^^^^..",

"..........^^^^^^^^^^^.^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...........^^^^^^...............^^................................^^^^^^^^^..^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.....^^^^^......",

"............:::::..........::::::::::::::::::::::::::::::...........::::::..::..............................................::::::::....::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::..:..::....::...........",

"...............:.:.............:::::::::::::::::::::::::::...........::::::::::.....................................:...........:::.....:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::............:::............",

".............:..................::::::::::::::::::::::::::::::.......::::::::::.....................................::.......::.:::...::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::............:::::...........",

"..........:......................::::::::::::::::::::::::::::::::..:::::::::::::::.................................:.::.......:....:.:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::..............::::............",

"...............................:..:::::::::::::::::::::::::::::::..::::::::::::::::...............................::.:::...::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::.........:::.............",

"...................................:::::::::::::::::::::::::::::::.:::::::::::::::...................................::::..:::::::::::^^:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::.........:...............",

"...................................:::::::::::::::::::::::::::::::::::::::::..::....................................::...::::::::::::::^^:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::.:........................",

"....................................::::::::::::::::::::::::::::::::::::::.::....:::.................................:.:::::::::::::::^^^^:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::...........................",

".....................................::::::::::::::::::::::::::::::::::::::::.......:.................................:::::::::::::::::^^::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::...........................",

".....................................::::::^^:::::::::::::::::::::::::::::::::::.......................................:::::::::::::::::::::..:..:::::::...:::::::::::::::::::::::::::::::::::::::::::::::::::::::::............................",

".....................................::::::^^:::::::::::::::::::::::::::::..:.........................................^^::::::::..:::::::::.......:::::...:::::::::::::::::::::::::::::::::::::::::::::::::::::::::...::........................",

".....................................::::::^^::::::::::::::::::::::::::::.........................................::::::::.....::...:::::::.........::::...:::::::::::::::::::::::::::::::::::::::::::::::::::::.....:::........................",

".....................................:::::::^^::::::::::::::::::::::::::..........................................:::::::........::..::::::..::::..::::::...::::::::::::::::::::::::::::::::::::::::::::::::::..................................",

".....................................::::::::^^::::::::::::::::::::::::...........................................::::::..........:..::...:::::::::::::::...::::::::::::::::::::::::::::::::::::::::::::.:.::........::.........................",

"......................................:::::::^^:::::::::::::::::::::::............................................::::::..........:...::..:::::::::::::::...:::::::::::::::::::::::::::::::::::::::::::....:::.......:..........................",

".......................................::::::::::::::::::::::::::::::.......................................................:::...........:::::::::::::::::::::::::::::^^^^^^^^^^^^^^^:::::::::::::::::::...::.....:::..........................",

".......................................::::::::::::::::::::::::::::::...............................................:::::::::::.........::....:.:::::::::::::::::::::::::^^^^^^^^^^^^^^:::::::::::::::::....::..::::::..........................",

".........................................:::::::::::::::::::::::::::...............................................::::::::::::.................::::::::::::::::::::::::::^^^^^^^^^^^^^:::::::::::::::::........:::.............................",

"..........................................::::::::::::::::::::::::................................................::::::::::::::::...::........:::::::::::::::::::::::::::::::::^^^^^^^^:::::::::::::::::......:................................",

"...........................................:.:::::::::::::::::::::................................................::::::::::::::::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::.......................................",

"...........................................:.::::::::::::..:.....:...............................................:::::::::::::::::::::::::::::::::::::::..:::::::::::::::::::::::::::::::::::::::::::::::.......................................",

"...........................................::.:::::::::..........:.............................................:::::::::::::::::::::::::::::::..:::::::::..::::::::::::::::::::::::::::::::::::::::::::::.......................................",

".............................................:.::::::::..........::.:.........................................:::::::::::::::::::::::::::::::::.:::::::::....:::::::::::::::::::::::::::::::::::::::::::........................................",

".............................................:..:::::::.......................................................:::::::::::::::::::::::::::::::::..:::::::::..::.......::::::::::::::::::::::::::::::::::.........................................",

".................................................::::::......................................................:::::::::::::::::::::::::::::::::::..:::::::::::::.......::::::::::::::::::::::::::::::::..:.......................................",

"..................................................:::::............:.........................................::::::::::::::::::::::::::::::::::::.::::::::::::::......:::::::::::::..::::::::::::::.............................................",

"..................................................:::::.....::......:::......................................::::::::::::::::::::::::::::::::::::..::::::::::::..........:::::::::....:::::::::.................................................",

"...................................................:::::...:::..........::...................................::::::::::::::::::::::::::::::::::::..:::::::::::...........:::::::.......::::::::.::..............................................",

".....................................................::::::::................................................:::::::::::::::::::::::::::::::::::::..:::::::::............::::::........::::::::.........::......................................",

".......................................................:::::::::.............................................:::::::::::::::::::::::::::::::::::::..:::::::..............:::::.........:.:::::::........:.......................................",

"...........................................................::::::............................................:::::::::::::::::::::::::::::::::::::::.::::.................:::............::::::::.......:.......................................",

".............................................................:::.............................................:::::::::::::::::::::::::::::::::::::::::....................:::.............:::::::.........:.....................................",

"..............................................................:::......:.:....................................:::::::::::::::::::::::::::::::::::::::...::.................::................:::.........:.:....................................",

"..............................................................:::::::::::::::::................................:::::::::::::::::::::::::::::::::::::::::::.................::.................:.................................................",

".................................................................:::::::::::::::...............................::::::::::::::::::::::::::::::::::::::::::....................:...........::...............::....................................",

"....................................................................:::::::::::::...............................:::::::::::::::::::::::::::::::::::::::::....................:.............:...............:....................................",

"....................................................................:::::::::::::::::.............................::::::...:::::::::::::::::::::::::::::................................:..::........::.........................................",

".....................................................................:::::::::::::::::........................................::::::::::::::::::::::::::................................::.::.......::..........................................",

"....................................................................::^^::::::::::::::........................................:::::::::::::::::::::::::..................................::.:.....:::::.........................................",

"...................................................................::::^^::::::::::::::.......................................:::::::::::::::::::::::.....................................:::....::::::.:::..:..................................",

"..................................................................:::::^^::::::::::::::::.....................................::::::::::::::::::::::.......................................::....:::::.......:..:...............................",

"..................................................................:::::^^:::::::::::::::::....................................:::::::::::::::::::::........................................:::...:::::.::........:.::...........................",

"..................................................................:::::^^:::::::::::::::::::::.................................::::::::::::::::::::.........................................:::.....:....:..:....:::::::........................",

"..................................................................:::::^^:::::::::::::::::::::::................................::::::::::::::::::...........................................::.....................:::::.......................",

"..................................................................:::::^^::::::::::::::::::::::::...............................::::::::::::::::::............................................::..:..............:..::::::......:...............",

"...................................................................:::::^^:::::::::::::::::::::::................................:::::::::::::::::................................................:::...............::::.::.......:.............",

"....................................................................::::^^::::::::::::::::::::::.................................::::::::::::::::::.......................................................:...............::....................",

"....................................................................::::^^:::::::::::::::::::::..................................::::::::::::::::::.............................................................................................",

".....................................................................::::^^::::::::::::::::::::..................................::::::::::::::::::............................................................::::....:........................",

".....................................................................::::^^^::::::::::::::::::..................................:::::::::::::::::::.....:...................................................:.:::::...::........................",

"......................................................................:::::^^::::::::::::::::..................................:::::::::::::::::::....:::.................................................::::::::...:::.......................",

"........................................................................:::^^:::::::::::::::::..................................:::::::::::::::::....::::.................................................:::::::::::.:::.......................",

".........................................................................::^^:::::::::::::::::..................................::::::::::::::::.....::::................................................:::::::::::::::::......................",

".........................................................................::^^::::::::::::::::....................................::::::::::::::.......::...............................................::::::::::::::::::::..........:..........",

".........................................................................::^^::::::::::::::::....................................:::::::::::::::.....:::.............................................:::::::::::::::::::::::..........:.........",

".........................................................................::^^::::::::::::::.......................................::::::::::::::.....:::............................................:::::::::::::::::::::::::...................",

".........................................................................::^^:::::::::::..........................................:::::::::::::......::.............................................::::::::::::::::::::::::::..................",

".........................................................................::^^:::::::::::..........................................::::::::::::......................................................::::::::::::::::::::::::::..................",

".........................................................................:^^:::::::::::..........................................::::::::::::......................................................::::::::::::::::::::::::::..................",

"........................................................................::^^:::::::::::............................................::::::::::........................................................:::::::::::::::::::::::::..................",

"........................................................................::^^::::::::::..............................................::::::::.........................................................:::::::::::::::::::::::::..................",

"........................................................................::^^:::::::::...............................................:::::::..........................................................::::::::....:::::::::::::..................",

"........................................................................:^::::::::::................................................:::::............................................................::::::.......:.:::::::::...................",

"........................................................................:^::::::::..................................................................................................................................::::::::...............:....",

".......................................................................::^::::::::...................................................................................................................................:::::::................:...",

".......................................................................::^:::::::.....................................................................................................................................::.:..................:::.",

".......................................................................::^:::::.............................................................................................................................................................::..",

".......................................................................::^:::............................................................................................................................................::.................:...",

".......................................................................::^:::............................................................................................................................................::...............::....",

"......................................................................::::::............................................................................................................................................................::......",

"......................................................................:::::............................................................................................................................................................:::......",

"......................................................................::::::....................................................................................................................................................................",

"......................................................................:::::.....................................................................................................................................................................",

"......................................................................::::......................................................................................................................................................................",

"......................................................................::::.....::...............................................................................................................................................................",

".......................................................................::::.....................................................................................................................................................................",

"........................................................................:::::...................................................................................................................................................................",

"................................................................................................................................................................................................................................................",

"................................................................................................................................................................................................................................................",

"................................................................................................................................................................................................................................................",

"................................................................................................................................................................................................................................................",

"................................................................................................................................................................................................................................................",

"................................................................................^^..............................................................................................................................................................",

".............................................................................^..................................................................................................................................................................",

"...........................................................................^^.............................................................................^^^^....................^........^^^^..^^^^^...^^^^^^^^^^.............................",

"...........................................................................^.........................................................................^^^^^^^^^^^^^^^^^.......^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.....................",

"........................................................................^^^^^^...............................................................^^^^^^^^^^^^^^^^^^^^^^^^^....^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^..............",

".......................................................................^^^.^^^^....................................^..^^.^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^..^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.......",

"............................................................^..............^^^^................................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^......",

".........................................^^^^........^^^^^^^^^^^^^^^^^^^^^^^^^^...............................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.........",

"......................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...............................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...........",

"..............^.^^..^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^..............................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...........",

"...........^^...^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...................^^^^.....^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.........",

"......................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.........^....^^^^^^...........^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.............",

".................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.........^^...^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^............",

"..................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^........",

"^^^^^^^^^^...............^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^",

"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^",

"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^",

"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"

];

const mapH = earthMap.length;

    const mapW = earthMap[0].length;

    

    // Use the N from the constructor (which we set to 150 in HTML now)

    const N = this.N; 



    for (let y = 0; y < N; y++) {

        for (let x = 0; x < N; x++) {

            

            // Nearest Neighbor Scaling

            const mapY = Math.floor((y / N) * mapH);

            const mapX = Math.floor((x / N) * mapW);



            // Safety check to prevent crashing if mapX is out of bounds

            const char = (earthMap[mapY] && earthMap[mapY][mapX]) ? earthMap[mapY][mapX] : '.';



            if (char === '^' || char === '=') {

                this.grid[y][x] = TERRAIN_ROCK;

            } else if (char === ':') {

                this.grid[y][x] = TERRAIN_LAND;

            } else {

                this.grid[y][x] = TERRAIN_SEA;

            }

        }

    }



              

            }



            // --- STANDARD GENERATION ---

            generate(seaPct, rockPct) {

                const N = this.N;

                const elevation = Array(N).fill(null).map(() => Array(N).fill(0));

                const rockDensity = Array(N).fill(null).map(() => Array(N).fill(0));



                for (let y = 0; y < N; y++) {

                    for (let x = 0; x < N; x++) {

                        const r = Math.hypot(x - N/2, y - N/2) / (N * 0.5);

                        let h = noise(x, y, 0.5, this.noiseOffsets[0]) + 

                                noise(x, y, 1.0, this.noiseOffsets[1]) + 

                                noise(x, y, 2.0, this.noiseOffsets[2]) * 0.5;

                        h = h / 2.5 - Math.pow(r, 2) * 0.8; 

                        elevation[y][x] = h;

                        

                        rockDensity[y][x] = noise(x, y, 3.0, this.noiseOffsets[4]);

                    }

                }



                const flat = elevation.flat().sort((a, b) => a - b);

                const seaThresh = flat[Math.floor(flat.length * seaPct)] || flat[0];



                for (let y = 0; y < N; y++) {

                    for (let x = 0; x < N; x++) {

                        this.grid[y][x] = elevation[y][x] <= seaThresh ? TERRAIN_SEA : TERRAIN_LAND;

                    }

                }

                

                // Hydraulic Rivers

                const numRivers = Math.floor(N/2);

                for(let i=0; i<numRivers; i++) {

                    let cx=Math.floor(Math.random()*N), cy=Math.floor(Math.random()*N);

                    if(this.grid[cy][cx]!==TERRAIN_LAND) continue;

                    let steps=0;

                    while(steps++ < N*2) {

                        let minH = elevation[cy][cx], bx=-1, by=-1;

                        for(let dy=-1; dy<=1; dy++) for(let dx=-1; dx<=1; dx++) {

                            if(dx===0 && dy===0) continue;

                            const nx=(cx+dx+N)%N, ny=cy+dy;

                            if(ny>=0 && ny<N && elevation[ny][nx]<minH) { minH=elevation[ny][nx]; bx=nx; by=ny; }

                        }

                        if(bx!==-1) {

                            cx=bx; cy=by; this.grid[cy][cx]=TERRAIN_SEA;

                            if(this.grid[cy][cx]===TERRAIN_SEA && Math.random()<0.1) break; 

                        } else break;

                    }

                }

                

                // Rocks

                const landCells = [];

                for(let y=0; y<N; y++) for(let x=0; x<N; x++) if(this.grid[y][x]===TERRAIN_LAND) landCells.push({x,y,v:rockDensity[y][x]});

                landCells.sort((a,b)=>b.v - a.v);

                const nR = Math.floor(landCells.length*rockPct);

                for(let i=0; i<nR; i++) this.grid[landCells[i].y][landCells[i].x] = TERRAIN_ROCK;

            }



            terrain(x, y) {

                x = ((x % this.N) + this.N) % this.N;

                if (y < 0 || y >= this.N) return TERRAIN_SEA; 

                return this.grid[y][x];

            }

        }



        class NxEr {

            constructor(config) {

                Object.assign(this, config);

                this.alive = true;

                // v3.0: Now 9 inputs

                this.lastInputs = [0, 0, 0, 0, 0, 0, 0, 0, 0];

                this.tickAccum = 0;

                this.lastPos = [...this.pos];

                this.matingWith = null;

                this.matingEndTick = null;

                this.matingIntentUntilTick = 0;

                this.mateCooldownUntilTick = 0;

                this.parents = config.parents || [null, null];

                this.stats = config.stats || { foodFound: 0, foodTaken: 0, explored: 0, timeLived: 0, matesPerformed: 0, energyEfficiency: 0, temporalSyncScore: 0, fitness: 0 };

                this.visited = new Set([`${this.pos[0]},${this.pos[1]}`]);

                this.dopamineBoostTicks = 0;

                this.lastO4 = 0;



                // NEW: Sensory & Clan attributes

                this.visionRange = config.visionRange || randomInt(2, 15);

                this.smellRadius = config.smellRadius || randomInt(2, 5);

                this.heading = config.heading !== undefined ? config.heading : randomInt(0, 7); // 0=NW...7=W

                this.clanId = config.clanId || null;



                // v3.0: NEW - Temperature system (bioinspired thermoregulation)

                this.bodyTemperature = config.bodyTemperature || 37.0; // Normal body temp

                this.optimalTempLow = 35.0;

                this.optimalTempHigh = 39.0;

                

                // v3.0: NEW - Proprioception (rock hit counter for obstacle avoidance)

                this.consecutiveRockHits = 0;

                

                // v3.0: Track resting state for reduced metabolism

                this.isResting = false;

            }

            updateStats(dt) {

                this.stats.timeLived += dt;

                this.stats.explored = this.visited.size;

                const energyStatus = this.net.getEnergyStatus();

                this.stats.energyEfficiency = energyStatus.efficiency || 0;

                this.stats.temporalSyncScore = energyStatus.branchingRatio || 1.0;

                this.stats.fitness = (Math.min(this.stats.foodFound/100, 1)*0.3 + Math.min(this.stats.explored/1000, 1)*0.2 + Math.min(this.stats.timeLived/1000, 1)*0.2 + Math.min(this.stats.energyEfficiency/10, 1)*0.15 + Math.min(this.stats.temporalSyncScore/2, 1)*0.15);

            }

        }



        class Food {

            constructor(id, pos) {

                this.id = id;

                this.anchor = [...pos];

                this.pos = [...pos];

                this.alive = true;

                this.respawnAtTick = null;

                this.remaining = 25;

                this.progress = {};

            }

        }



        // =====================================================================

        // GAME ENGINE

        // =====================================================================

        class GameEngine {

            // v3.0: Day/Night cycle constants

            static DAY_PHASE = 0;

            static DUSK_PHASE = 1;

            static NIGHT_PHASE = 2;

            static DAWN_PHASE = 3;

            

            // v3.0: Temperature constants

            static TEMP_TRANSFER_RATE = 0.1;



            constructor(config) {

            this.config = config;

            this.world = new World(config.worldSize, config.seaPct / 100, config.rockPct / 100, config.useEarth);

            

            this.nxers = new Map();

            this.foods = new Map();

            this.occupied = new Set();

            this.effects = [];

            this.stepTick = 0;

            this.birthsCount = 0;

            this.deathsCount = 0;

            this.gameIndex = 1;

            this.paused = true;

            this.gameOver = false;

            this.usedColors = new Set();

            this.championCounts = {};

            this.allTimeBest = { foodFound: [], foodTaken: [], explored: [], timeLived: [], matesPerformed: [], fitness: [] };

            

            // NEW: Clan Counter

            this.nextClanId = 1;

            

            // v3.0: Day/Night cycle state

            this.dayNightPhase = 0; // 0=day, 1=dusk, 2=night, 3=dawn

            this.dayNightProgress = 0.0; // 0.0 to 1.0 within phase

            this.globalTimeOfDay = 0.0; // 0.0 to 1.0 full cycle

            // v3.1: Sun position for spatial day/night (longitude angle)

            this.sunLongitude = 0.0; // 0 to 2*PI - where the sun is pointing

            

            this.environmentTemperature = config.baseTemperature || 25;

            

            this.initializeFood();

            this.initializeNxErs();

        }



            mate(a, b) {

                const dur = Math.max(a.net.params.simulationSteps, b.net.params.simulationSteps);

                

                a.matingWith = b.id; 

                b.matingWith = a.id;

                a.matingEndTick = this.stepTick + dur;

                b.matingEndTick = this.stepTick + dur;

                

                // Cost

                a.food -= 3; 

                b.food -= 3; 

                

                a.stats.matesPerformed++; 

                b.stats.matesPerformed++;

                

                

                this.effects.push({ type: 'heart', pos: [...a.pos], startTick: this.stepTick });

                

                this.spawnChild(a, b, a.pos);

            }



            initializeFood() {

                const count = Math.floor(this.config.maxFood / 2);

                for (let i = 0; i < count; i++) {

                    const pos = this.findFreePosition(true, true);

                    if (pos) this.foods.set(i, new Food(i, pos));

                }

            }



            initializeNxErs() {

                for (let i = 0; i < this.config.startingNxErs; i++) {

                    const nxer = this.createNxEr(i);

                    this.nxers.set(nxer.id, nxer);

                    this.occupied.add(`${nxer.pos[0]},${nxer.pos[1]}`);

                }

            }



            createNxEr(id, params = null) {

            const netParams = params || new NetworkParameters(randomInt(1, this.config.maxNeurons));

            const net = new NeuraxonNetwork(netParams);

            

            const pos = this.findFreePosition(true, true) || [

                randomInt(0, this.world.N - 1),

                randomInt(0, this.world.N - 1)

            ];

            

            const terrain = this.world.terrain(pos[0], pos[1]);

            let canLand, canSea;

            

            if (terrain === TERRAIN_LAND) { canLand = true; canSea = false; }

            else if (terrain === TERRAIN_SEA) { canLand = false; canSea = true; }

            else { canLand = true; canSea = false; }



            const color = this.randomColor();

            const isMale = Math.random() < 0.5;

            

            const ticksPerAction = Math.max(2, Math.floor((this.config.globalTimeSteps * 1.2) / Math.max(1, netParams.simulationSteps)));



            // NEW: Init Vision, Smell, Heading

            const vision = randomInt(2, 15);

            const smell = randomInt(2, 5);

            const heading = randomInt(0, 7);



            const nxer = new NxEr({

                id,

                name: base26Name(id),

                color,

                pos,

                canLand,

                canSea,

                net,

                food: this.config.startFood,

                isMale,

                ticksPerAction,

                bornTick: this.stepTick,

                lastMoveTick: this.stepTick,

                visionRange: vision,

                smellRadius: smell,

                heading: heading,

                clanId: null // No clan for generated starters

            });

            

            // v3.0: Initialize temperature based on terrain (terrain already computed above)

            return nxer;

        }



        spawnChild(A, B, nearPos) {

            if (this.nxers.size >= this.config.maxNxErs) return null;

            

            const childId = this.nxers.size > 0 ? Math.max(...this.nxers.keys()) + 1 : 0;

            

            const baseParams = Math.random() < 0.5 ? A.net.params.clone() : B.net.params.clone();

            baseParams.numHiddenNeurons = randomInt(

                Math.max(1, baseParams.numHiddenNeurons - 2),

                Math.min(this.config.maxNeurons, baseParams.numHiddenNeurons + 2)

            );

            

            let canLand, canSea;

            const isAMarine = A.canSea && !A.canLand;

            const isALand = A.canLand && !A.canSea;

            const isBMarine = B.canSea && !B.canLand;

            const isBLand = B.canLand && !B.canSea;



            if ((isAMarine && isBLand) || (isALand && isBMarine)) {

                canLand = true; canSea = true;

            } else {

                canLand = A.canLand || B.canLand;

                canSea = A.canSea || B.canSea;

            }

            

            const pos = this.findFreePosition(canSea, canLand, nearPos, 3) || nearPos;

            const transfer = Math.min(5.0, Math.min(A.food / 2, B.food / 2));

            A.food -= transfer; B.food -= transfer;

            

            // NEW: Clan Inheritance Logic

            let familyClan = null;

            if (A.clanId === null && B.clanId === null) {

                familyClan = this.nextClanId++;

                A.clanId = familyClan;

                B.clanId = familyClan;

            } else if (A.clanId !== null) {

                familyClan = A.clanId;

                if (B.clanId === null) B.clanId = familyClan;

            } else if (B.clanId !== null) {

                familyClan = B.clanId;

                if (A.clanId === null) A.clanId = familyClan;

            }



            // NEW: Inherit sensory traits

            const vision = randomChoice([A.visionRange, B.visionRange, randomInt(2, 15)]);

            const smell = randomChoice([A.smellRadius, B.smellRadius, randomInt(2, 5)]);

            const heading = randomInt(0, 7);



            const child = new NxEr({

                id: childId, 

                name: `${stripLeadingDigits(A.name).replace(/^-+/, '')}-${stripLeadingDigits(B.name).replace(/^-+/, '')}`,

                color: this.randomColor(), 

                pos, 

                canLand, 

                canSea,

                net: new NeuraxonNetwork(baseParams), 

                food: transfer * 2, 

                isMale: Math.random() < 0.5,

                ticksPerAction: Math.max(2, Math.floor((this.config.globalTimeSteps * 1.2) / Math.max(1, baseParams.simulationSteps))),

                parents: [A.id, B.id], 

                bornTick: this.stepTick, 

                lastMoveTick: this.stepTick,

                // Pass new props

                visionRange: vision,

                smellRadius: smell,

                heading: heading,

                bodyTemperature: (A.bodyTemperature + B.bodyTemperature) / 2 + random(-0.5, 0.5),

                consecutiveRockHits: 0,

                clanId: familyClan

            });

            

            child.stats.fitness = (A.stats.fitness + B.stats.fitness) / 2;

            

            this.nxers.set(childId, child);

            this.occupied.add(`${pos[0]},${pos[1]}`);

            

            A.stats.matesPerformed++; 

            B.stats.matesPerformed++;

            this.birthsCount++;

            

            return child;

        }

findFreePosition(allowSea = true, allowLand = true, near = null, searchRadius = 5) {

                const N = this.world.N;

                

                if (near) {

                    for (let r = 0; r < searchRadius; r++) {

                        const candidates = [];

                        for (let dy = -r; dy <= r; dy++) {

                            for (let dx = -r; dx <= r; dx++) {

                                // X Wraps

                                const x = (near[0] + dx + N) % N;

                                // Y Clamps (No Wrap)

                                const y = near[1] + dy;

                                

                                if (y < 0 || y >= N) continue; // Skip out of bounds

                                

                                const key = `${x},${y}`;

                                if (this.occupied.has(key)) continue;

                                

                                const terrain = this.world.terrain(x, y);

                                if (terrain === TERRAIN_ROCK) continue;

                                if (terrain === TERRAIN_LAND && !allowLand) continue;

                                if (terrain === TERRAIN_SEA && !allowSea) continue;

                                

                                candidates.push([x, y]);

                            }

                        }

                        

                        if (candidates.length > 0) {

                            return randomChoice(candidates);

                        }

                    }

                }

                

                for (let i = 0; i < 100; i++) {

                    const x = randomInt(0, N - 1);

                    const y = randomInt(0, N - 1); // Random pick is always safe

                    const key = `${x},${y}`;

                    

                    if (this.occupied.has(key)) continue;

                    

                    const terrain = this.world.terrain(x, y);

                    if (terrain === TERRAIN_ROCK) continue;

                    if (terrain === TERRAIN_LAND && !allowLand) continue;

                    if (terrain === TERRAIN_SEA && !allowSea) continue;

                    

                    return [x, y];

                }

                

                return null;

            }



            randomColor() {

                const r = randomInt(30, 235), g = randomInt(30, 235), b = randomInt(30, 235);

                return `rgb(${r},${g},${b})`;

            }



            // v3.0: NEW - Update day/night cycle

            updateDayNightCycle(dt) {

                const cycleDuration = this.config.dayNightCycle || 180; // seconds

                const cycleTickDuration = cycleDuration * this.config.globalTimeSteps;

                

                this.globalTimeOfDay = (this.stepTick % cycleTickDuration) / cycleTickDuration;

                

                // Determine phase: day (0-0.4), dusk (0.4-0.5), night (0.5-0.9), dawn (0.9-1.0)

                if (this.globalTimeOfDay < 0.4) {

                    this.dayNightPhase = GameEngine.DAY_PHASE;

                    this.dayNightProgress = this.globalTimeOfDay / 0.4;

                } else if (this.globalTimeOfDay < 0.5) {

                    this.dayNightPhase = GameEngine.DUSK_PHASE;

                    this.dayNightProgress = (this.globalTimeOfDay - 0.4) / 0.1;

                } else if (this.globalTimeOfDay < 0.9) {

                    this.dayNightPhase = GameEngine.NIGHT_PHASE;

                    this.dayNightProgress = (this.globalTimeOfDay - 0.5) / 0.4;

                } else {

                    this.dayNightPhase = GameEngine.DAWN_PHASE;

                    this.dayNightProgress = (this.globalTimeOfDay - 0.9) / 0.1;

                }

                

                // v3.1: Update sun position (rotates around planet)

                this.sunLongitude = this.globalTimeOfDay * Math.PI * 2;

                

                // v3.0: Update environment temperature based on day/night

                const baseTemp = this.config.baseTemperature || 25;

                const dayBonus = 8; // Warmer during day

                const nightPenalty = -6; // Colder at night

                

                if (this.dayNightPhase === GameEngine.DAY_PHASE) {

                    this.environmentTemperature = baseTemp + dayBonus * Math.sin(this.dayNightProgress * Math.PI);

                } else if (this.dayNightPhase === GameEngine.NIGHT_PHASE) {

                    this.environmentTemperature = baseTemp + nightPenalty * Math.sin(this.dayNightProgress * Math.PI);

                } else if (this.dayNightPhase === GameEngine.DUSK_PHASE) {

                    this.environmentTemperature = baseTemp + dayBonus * (1 - this.dayNightProgress);

                } else { // DAWN

                    this.environmentTemperature = baseTemp + nightPenalty * (1 - this.dayNightProgress);

                }

            }

            

            // v3.1: Get local daylight factor based on position on sphere

            getLocalDaylightFactor(x, y) {

                const N = this.world.N;

                // Convert grid position to longitude (0 to 2*PI)

                const longitude = (x / N) * Math.PI * 2;

                

                // Calculate angle difference from sun position

                let angleDiff = Math.abs(longitude - this.sunLongitude);

                if (angleDiff > Math.PI) angleDiff = Math.PI * 2 - angleDiff;

                

                // Daylight factor: 1.0 when facing sun, 0.0 when opposite

                // Use cosine for smooth transition (terminator)

                const rawFactor = Math.cos(angleDiff);

                

                // Map from [-1, 1] to [0, 1] with sharper transition

                const daylight = Math.max(0, Math.min(1, (rawFactor + 0.3) / 1.3));

                

                return daylight;

            }

            

            // v3.1: Get local temperature based on position (sun exposure + latitude)

            getLocalTemperature(x, y) {

                const baseTemp = this.config.baseTemperature || 25;

                const localDaylight = this.getLocalDaylightFactor(x, y);

                

                // Latitude effect (equator warmer, poles colder)

                const N = this.world.N;

                const latitude = Math.abs(y - N/2) / (N/2); // 0 at equator, 1 at poles

                const latitudePenalty = latitude * 8; // Up to 8°C colder at poles

                

                // Sun exposure effect

                const sunBonus = localDaylight * 12; // Up to 12°C warmer in direct sunlight

                

                return baseTemp + sunBonus - latitudePenalty;

            }



            // v3.0: Get daylight factor for metabolic/behavior modulation

            getDaylightFactor() {

                // Returns 0.0 (full night) to 1.0 (full day)

                if (this.dayNightPhase === GameEngine.DAY_PHASE) {

                    return 0.7 + 0.3 * Math.sin(this.dayNightProgress * Math.PI);

                } else if (this.dayNightPhase === GameEngine.NIGHT_PHASE) {

                    return 0.2 - 0.15 * Math.sin(this.dayNightProgress * Math.PI);

                } else if (this.dayNightPhase === GameEngine.DUSK_PHASE) {

                    return 0.7 - 0.5 * this.dayNightProgress;

                } else { // DAWN

                    return 0.2 + 0.5 * this.dayNightProgress;

                }

            }

            

            // v3.0: Bioinspired neurotransmitter modulation based on circadian rhythm

            getCircadianNeuromodFactors() {

                const daylight = this.getDaylightFactor();

                return {

                    dopamineBoost: daylight * 0.3, // More active during day

                    serotoninBoost: (1 - daylight) * 0.25, // Melatonin-like, higher at night

                    norepinephrineBoost: Math.abs(daylight - 0.5) * 0.2 // Alert during transitions

                };

            }



            step() {

            if (this.paused || this.gameOver) return;

            this.stepTick++;

            const dt = 1.0 / this.config.globalTimeSteps;

            

            // v3.0: Update day/night cycle

            this.updateDayNightCycle(dt);

            const daylightFactor = this.getDaylightFactor();

            const circadianFactors = this.getCircadianNeuromodFactors();



            // Pre-calc maps for sensory efficiency

            const occupantAt = new Map();

            this.nxers.forEach(n => { if(n.alive) occupantAt.set(`${n.pos[0]},${n.pos[1]}`, n); });

            const foodAt = new Set();

            this.foods.forEach(f => { if(f.alive) foodAt.add(`${f.pos[0]},${f.pos[1]}`); });



            // Direction Vectors (0=NW to 7=W)

            const DIR_OFFSETS = [

                [-1, -1], [0, -1], [1, -1], [1, 0], 

                [1, 1],   [0, 1],  [-1, 1], [-1, 0]

            ];



            for (const nxer of this.nxers.values()) {

                if (!nxer.alive) continue;

                nxer.updateStats(dt);

                

                // v3.0: Metabolic rate affected by day/night and temperature

                let metabolicMultiplier = 1.0;

                

                // Slower metabolism at night (bioinspired circadian rhythm)

                metabolicMultiplier *= (0.6 + 0.4 * daylightFactor);

                

                // Temperature affects metabolism (colder = more energy to maintain temp)

                const tempDiff = Math.abs(nxer.bodyTemperature - 37.0);

                metabolicMultiplier *= (1.0 + tempDiff * 0.05);

                

                // v3.0: Much lower metabolism when resting (not moving)

                if (nxer.isResting) {

                    metabolicMultiplier *= 0.3; // 70% reduction when resting

                }

                

                nxer.food -= 0.01 * dt * metabolicMultiplier;

                

                // v3.0: Apply circadian neuromodulator effects

                nxer.net.neuromodulators.dopamine = clamp(

                    nxer.net.neuromodulators.dopamine + circadianFactors.dopamineBoost * dt * 0.1,

                    0, 2

                );

                nxer.net.neuromodulators.serotonin = clamp(

                    nxer.net.neuromodulators.serotonin + circadianFactors.serotoninBoost * dt * 0.1,

                    0, 2

                );

                nxer.net.neuromodulators.norepinephrine = clamp(

                    nxer.net.neuromodulators.norepinephrine + circadianFactors.norepinephrineBoost * dt * 0.1,

                    0, 2

                );

                

                // v3.1: Update local environment temperature based on position

                const localTemp = this.getLocalTemperature(nxer.pos[0], nxer.pos[1]);

                this.updateNxErTemperature(nxer, dt, occupantAt, localTemp);

                

                if (nxer.food <= 0 || this.stepTick - nxer.lastMoveTick > 10 * this.config.globalTimeSteps) this.killNxEr(nxer);

                if (nxer.matingWith !== null && this.stepTick >= nxer.matingEndTick) {

                    nxer.matingWith = null;

                    nxer.matingEndTick = null;

                    nxer.mateCooldownUntilTick = this.stepTick + this.config.mateCooldown * this.config.globalTimeSteps;

                }

            }



            const processNxErs = Array.from(this.nxers.values()).filter(n => n.alive && n.matingWith === null);

            

            processNxErs.forEach(nxer => {

                nxer.tickAccum++;

                if (nxer.tickAccum >= nxer.ticksPerAction) {

                    nxer.tickAccum = 0;

                    

                    // --- SENSORY LOGIC ---

                    // 4. Hunger

                    const hungerVal = nxer.food < (this.config.startFood * 0.2) ? -1 : 0;

                    

                    // 5. Vision (Raycast in Heading)

                    let sightVal = -1; // -1=Nothing/Enemy, 0=Clan, 1=Food

                    const dir = DIR_OFFSETS[nxer.heading];

                    let foundObj = false;

                    for (let d = 1; d <= nxer.visionRange; d++) {

                        const tx = (nxer.pos[0] + (dir[0] * d) + this.world.N) % this.world.N;

                        const ty = nxer.pos[1] + (dir[1] * d); // Y doesn't wrap in lookups usually, but safe check

                        if (ty < 0 || ty >= this.world.N) break;

                        const k = `${tx},${ty}`;

                        

                        if (this.world.terrain(tx, ty) === TERRAIN_ROCK) break; // Blocked

                        

                        if (foodAt.has(k)) { sightVal = 1; foundObj = true; break; }

                        if (occupantAt.has(k)) {

                            const other = occupantAt.get(k);

                            if (other.clanId !== null && nxer.clanId !== null && other.clanId === nxer.clanId) {

                                sightVal = 0; // Friendly

                            } else {

                                sightVal = -1; // Neutral/Enemy

                            }

                            foundObj = true; break;

                        }

                    }

                    

                    // 6. Smell (Square Radius)

                    let smellVal = -1;

                    let foundFoodSmell = false, foundNxerSmell = false;

                    for(let dy = -nxer.smellRadius; dy <= nxer.smellRadius; dy++) {

                        for(let dx = -nxer.smellRadius; dx <= nxer.smellRadius; dx++) {

                            if(dx===0 && dy===0) continue;

                            const sx = (nxer.pos[0] + dx + this.world.N) % this.world.N;

                            const sy = nxer.pos[1] + dy;

                            if(sy < 0 || sy >= this.world.N) continue;

                            const k = `${sx},${sy}`;

                            if(foodAt.has(k)) foundFoodSmell = true;

                            if(occupantAt.has(k)) foundNxerSmell = true;

                        }

                    }

                    if(foundFoodSmell) smellVal = 1;

                    else if(foundNxerSmell) smellVal = 0;

                    

                    // v3.0: NEW INPUTS - DayNight, Temperature, Proprioception

                    // Input 7: Day/Night signal (-1=night, 0=transition, 1=day)

                    let dayNightInput = 0;

                    if (this.dayNightPhase === GameEngine.DAY_PHASE) {

                        dayNightInput = 1;

                    } else if (this.dayNightPhase === GameEngine.NIGHT_PHASE) {

                        dayNightInput = -1;

                    } else {

                        dayNightInput = 0; // Transitions (dusk/dawn)

                    }

                    

                    // v3.1: Override with LOCAL daylight for this NxEr's position

                    const localDaylight = this.getLocalDaylightFactor(nxer.pos[0], nxer.pos[1]);

                    if (localDaylight > 0.6) dayNightInput = 1;

                    else if (localDaylight < 0.3) dayNightInput = -1;

                    else dayNightInput = 0;

                    

                    // Input 8: Temperature comfort (-1=cold, 0=optimal, 1=hot)

                    let tempInput = 0;

                    if (nxer.bodyTemperature < nxer.optimalTempLow) {

                        tempInput = -1; // Too cold

                    } else if (nxer.bodyTemperature > nxer.optimalTempHigh) {

                        tempInput = 1; // Too hot

                    } else {

                        tempInput = 0; // Comfortable

                    }

                    

                    // Input 9: Proprioception - obstacle awareness (-1=stuck, 0=clear, 1=recent hit)

                    let proprioInput = 0;

                    if (nxer.consecutiveRockHits >= 3) {

                        proprioInput = -1; // Stuck - need to change direction

                        // v3.0: Force direction change when stuck

                        nxer.heading = (nxer.heading + randomInt(2, 6)) % 8;

                        nxer.consecutiveRockHits = 0; // Reset after forced turn

                        // Stress response - increase norepinephrine

                        nxer.net.neuromodulators.norepinephrine = Math.min(2.0, 

                            nxer.net.neuromodulators.norepinephrine + 0.3);

                    } else if (nxer.consecutiveRockHits > 0) {

                        proprioInput = 1; // Recent hit, be cautious

                    }

                    

                    // v3.0: Night behavior - tendency to rest

                    let restTendency = 0;

                    if (this.dayNightPhase === GameEngine.NIGHT_PHASE && nxer.food > this.config.startFood * 0.5) {

                        // Well-fed NxErs rest more at night

                        restTendency = Math.random() < 0.3 ? 1 : 0;

                    }

                    

                    // v3.0: Construct full inputs (Last 3 + 3 Sensory + 3 New)

                    const inputs = [...nxer.lastInputs.slice(0, 3), hungerVal, sightVal, smellVal, dayNightInput, tempInput, proprioInput];

                    

                    const steps = Math.max(1, Math.floor(nxer.net.params.simulationSteps / this.config.globalTimeSteps));

                    

                    if (nxer.dopamineBoostTicks > 0) {

                        nxer.net.neuromodulators.dopamine = Math.max(nxer.net.neuromodulators.dopamine, 0.9);

                        nxer.dopamineBoostTicks--;

                    }

                    

                    for(let i=0; i<steps; i++) { nxer.net.setInputStates(inputs); nxer.net.simulateStep(); }

                    

                    // v3.0: Get Outputs (Now 6)

                    // O1=X, O2=Y, O3=Steal, O4=Mate, O5=GiveFood, O6=Rest

                    let outs = nxer.net.getOutputStates();

                    while(outs.length < 6) outs.push(0);

                    let [O1, O2, O3, O4, O5, O6] = outs;



                    // v3.0: Rest output - if resting, reduce movement

                    if (O6 === 1 || restTendency === 1) {

                        // Resting behavior - stay still, recover energy slightly

                        O1 = 0;

                        O2 = 0;

                        nxer.isResting = true;

                        nxer.food += 0.02 * dt; // Improved energy recovery from rest

                        // Resting helps regulate temperature

                        nxer.bodyTemperature += (37.0 - nxer.bodyTemperature) * 0.01;

                    } else {

                        nxer.isResting = false;

                    }



                    if (O1 === 0 && O2 === 0 && Math.random() < 0.4) { 

                        if(Math.random() < 0.5) O1 = Math.random()<0.5?-1:1; else O2 = Math.random()<0.5?-1:1; 

                    }

                    if (O4 === 0 && Math.random() < 0.08) O4 = Math.random() < 0.5 ? -1 : 1;

                    

                    // v3.0: Temperature-seeking behavior

                    if (tempInput === -1 && this.dayNightPhase === GameEngine.DAY_PHASE) {

                        // Cold NxEr during day - seek sunlight (move towards equator)

                        if (nxer.pos[1] < this.world.N / 2) O2 = 1; // Move south

                        else O2 = -1; // Move north

                    }



                    // --- OUTPUT 5: GIVE FOOD (Altruism) ---

                    if (O5 >= 0 && nxer.food > this.config.startFood) {

                         // Check neighbors

                         for(let ndy=-1; ndy<=1; ndy++) {

                             for(let ndx=-1; ndx<=1; ndx++) {

                                 if(ndx===0 && ndy===0) continue;

                                 const tx = (nxer.pos[0] + ndx + this.world.N) % this.world.N;

                                 const ty = nxer.pos[1] + ndy;

                                 if(ty < 0 || ty >= this.world.N) continue;

                                 const rec = occupantAt.get(`${tx},${ty}`);

                                 

                                 // Only give to Clan members

                                 if(rec && nxer.clanId !== null && rec.clanId === nxer.clanId) {

                                     if(rec.food < this.config.startFood) {

                                         const amt = (O5 === 1) ? 5.0 : 2.0;

                                         if(nxer.food > amt) {

                                             nxer.food -= amt;

                                             rec.food += amt;

                                         }

                                     }

                                 }

                             }

                         }

                    }



                    const dx = -O1;

                    const dy = -O2;

                    

                    // Update Heading based on move

                    if(dx !== 0 || dy !== 0) {

                        // Map dx,dy to 0-7

                        if(dx===-1 && dy===-1) nxer.heading=0;

                        else if(dx===0 && dy===-1) nxer.heading=1;

                        else if(dx===1 && dy===-1) nxer.heading=2;

                        else if(dx===1 && dy===0) nxer.heading=3;

                        else if(dx===1 && dy===1) nxer.heading=4;

                        else if(dx===0 && dy===1) nxer.heading=5;

                        else if(dx===-1 && dy===1) nxer.heading=6;

                        else if(dx===-1 && dy===0) nxer.heading=7;

                    }



                    nxer.pendingMove = {dx, dy, O3, O4};

                }

            });



            this.processMovements(processNxErs.filter(n => n.pendingMove));

            this.tryRespawnFood();

            this.effects = this.effects.filter(e => this.stepTick - e.startTick < this.config.globalTimeSteps);

            if (Array.from(this.nxers.values()).filter(n => n.alive).length === 0) this.gameOver = true;

        }





processMovements(nxers) {

                const intents = [];

                for (const nxer of nxers) {

                    if (!nxer.pendingMove) continue;

                    const {dx, dy, O3, O4} = nxer.pendingMove; delete nxer.pendingMove;

                    

                    if (dx===0 && dy===0) {

                        nxer.lastInputs = [-1, 0, this.world.terrain(nxer.pos[0], nxer.pos[1]) === TERRAIN_LAND ? 1 : 0];

                        nxer.isResting = true; // v3.0: Mark as resting when not moving

                        continue;

                    }



                    // Cylinder Topology (Wrap X, Clamp Y)

                    const tx = (nxer.pos[0] + dx + this.world.N) % this.world.N;

                    const rawTy = nxer.pos[1] + dy;

                    

                    if (rawTy < 0 || rawTy >= this.world.N) {

                        nxer.lastInputs = [-1, 0, -1]; // Wall hit

                        nxer.consecutiveRockHits++; // v3.0: Track wall hits too

                        continue; 

                    }

                    const ty = rawTy;



                    intents.push({nxer, target: [tx, ty], O3, O4});

                }



                const byPos = {};

                intents.forEach(i => {

                    const k = `${i.target[0]},${i.target[1]}`;

                    if(!byPos[k]) byPos[k] = [];

                    byPos[k].push(i);

                });



                const occupants = {}; this.nxers.forEach(n => { if(n.alive) occupants[`${n.pos[0]},${n.pos[1]}`] = n; });

                const foods = {}; this.foods.forEach(f => { if(f.alive) foods[`${f.pos[0]},${f.pos[1]}`] = f; });



                for (const [key, list] of Object.entries(byPos)) {

                    const [tx, ty] = key.split(',').map(Number);

                    const terrain = this.world.terrain(tx, ty);



                    if (terrain === TERRAIN_ROCK) {

                        list.forEach(i => i.nxer.lastInputs = [-1, 0, -1]);

                        list.forEach(i => i.nxer.consecutiveRockHits++); // v3.0: Track rock hits

                        continue;

                    }



                    const valid = list.filter(i => {

                        const n = i.nxer;

                        const ot = this.world.terrain(n.pos[0], n.pos[1]);

                        if ((ot===1 && terrain===0) || (ot===0 && terrain===1)) return true; 

                        if (terrain===1 && !n.canLand) { n.lastInputs = [-1,0,1]; return false; }

                        if (terrain===0 && !n.canSea) { n.lastInputs = [-1,0,0]; return false; }

                        return true;

                    });

                    if (!valid.length) continue;



                    // v3.0: Clear rock hit counter on successful terrain validation

                    // Food Interaction

                    if (foods[key]) {

                        const f = foods[key];

                        valid.forEach(i => {

                            i.nxer.dopamineBoostTicks = 30;

                            if(f.remaining>0) { f.remaining--; i.nxer.food++; i.nxer.stats.foodFound++; }

                            i.nxer.lastInputs = [1,0,terrain===1?1:0];

                        });

                        // v3.0: Food consumption generates heat

                        valid.forEach(i => i.nxer.bodyTemperature += 0.1);

                        valid.forEach(i => i.nxer.consecutiveRockHits = 0);

                        if(f.remaining <= 0) {

                            const winner = valid.sort((a,b) => a.nxer.ticksPerAction - b.nxer.ticksPerAction)[0].nxer;

                            this.moveNxEr(winner, [tx, ty]);

                            f.alive = false; f.respawnAtTick = this.stepTick + this.config.foodRespawn * this.config.globalTimeSteps;

                        }

                        continue;

                    }



                    // Occupied Interaction

                    if (occupants[key]) {

                        const occ = occupants[key];

                        valid.forEach(i => {

                            const n = i.nxer;

                            if (n.id === occ.id) return;

                            n.lastInputs = [-1, 1, terrain===1?1:0];



                            // --- TUNED MATING LOGIC ---

                            // 1. Explicit Desire (Neural Output) OR Very Low Chance (0.2%)

                            // 2. Must have significant food reserves ( > 15) to prioritize survival over reproduction

                            const naturalUrge = Math.random() < 0.002; 

                            const wantsMate = (i.O4 === 1 || naturalUrge) && n.food > 15;

                            

                            if (wantsMate && this.canMate(n, occ)) {

                                this.mate(n, occ);

                            } else if ((i.O4 === -1 || i.O3 === -1) && occ.food > 0) {

                                occ.food--; n.food++; n.stats.foodTaken++;

                            }

                            n.lastO4 = i.O4;

                        });

                        continue;

                    }



                    // Empty Cell Meeting

                    const mates = valid.filter(i => 

                        (i.O4===1 || Math.random() < 0.002) && 

                        i.nxer.food >= 15 && 

                        !i.nxer.matingWith

                    );

                    

                    if(mates.length >= 2) {

                        const a = mates[0].nxer;

                        const b = mates[1].nxer;

                        if(this.canMate(a, b)) this.mate(a, b);

                        

                        valid.forEach(i => { i.nxer.lastInputs = [-1, 1, terrain===1?1:0]; i.nxer.lastO4 = i.O4; });

                        continue;

                    }



                    // Move Winner

                    const winner = valid.sort((a,b) => a.nxer.ticksPerAction - b.nxer.ticksPerAction)[0].nxer;

                    this.moveNxEr(winner, [tx, ty]);

                    // v3.0: Successful movement clears rock hit counter

                    winner.consecutiveRockHits = 0;

                    valid.forEach(i => { if(i.nxer.id !== winner.id) i.nxer.lastInputs=[-1,1,terrain===1?1:0]; i.nxer.lastO4 = i.O4; });

                }

            }







            canMate(A, B) {

                // 1. Self Check

                if (A.id === B.id) return false;

                // 2. Life Check

                if (!A.alive || !B.alive) return false;

                // 3. Gender Check (Must be opposites)

                if (A.isMale === B.isMale) return false;

                // 4. Status Check (Must be free)

                if (A.matingWith !== null || B.matingWith !== null) return false;

                // 5. Energy Check (Must have enough food)

                if (A.food < 5 || B.food < 5) return false;

                // 6. Cooldown Check

                if (this.stepTick < A.mateCooldownUntilTick || this.stepTick < B.mateCooldownUntilTick) return false;

                // 7. Incest Check

                if (A.parents.includes(B.id) || B.parents.includes(A.id)) return false;

                

                return true;

            }



            moveNxEr(nxer, target, terrain) {

                this.occupied.delete(`${nxer.pos[0]},${nxer.pos[1]}`);

                if (nxer.pos[0] !== target[0] || nxer.pos[1] !== target[1]) {

                    nxer.lastPos = [...nxer.pos]; nxer.lastMoveTick = this.stepTick;

                    nxer.isResting = false; // v3.0: Reset resting state on movement

                }

                nxer.pos = [...target];

                this.occupied.add(`${target[0]},${target[1]}`);

                nxer.visited.add(`${target[0]},${target[1]}`);

                nxer.lastInputs = [-1, 0, terrain === TERRAIN_LAND ? 1 : 0];

                nxer.food -= 0.1;

                // v3.0: Movement generates heat

                nxer.bodyTemperature += 0.02;

                if (nxer.food <= 0) this.killNxEr(nxer);

            }



            killNxEr(nxer) {

                if (!nxer.alive) return;

                nxer.alive = false; this.deathsCount++;

                this.occupied.delete(`${nxer.pos[0]},${nxer.pos[1]}`);

                this.effects.push({type: 'skull', pos: [...nxer.pos], startTick: this.stepTick});

            }



            tryRespawnFood() {

                const aliveCount = Array.from(this.foods.values()).filter(f => f.alive).length;

                if (aliveCount >= this.config.maxFood) return;

                for (const f of this.foods.values()) {

                    if (!f.alive && f.respawnAtTick && this.stepTick >= f.respawnAtTick) {

                        const pos = this.findFreePosition(true, true, f.anchor, 6);

                        if (pos) { f.pos = pos; f.alive = true; f.respawnAtTick = null; f.remaining = 25; }

                        if (Array.from(this.foods.values()).filter(x => x.alive).length >= this.config.maxFood) break;

                    }

                }

            }



            updateAllTimeBest() {

                const current = Array.from(this.nxers.values());

                if (!current.length) return;

                const cats = { foodFound: 'foodFound', foodTaken: 'foodTaken', explored: 'explored', timeLived: 'timeLived', matesPerformed: 'matesPerformed', fitness: 'fitness' };

                for (const [key, prop] of Object.entries(cats)) {

                    const combined = [...this.allTimeBest[key], ...current.slice().sort((a, b) => b.stats[prop] - a.stats[prop]).slice(0, 3)];

                    const seen = new Set(), unique = [];

                    combined.forEach(n => { const b = stripLeadingDigits(n.name).replace(/^-+/, '') || n.name; if(!seen.has(b)) { seen.add(b); unique.push(n); } });

                    this.allTimeBest[key] = unique.sort((a, b) => b.stats[prop] - a.stats[prop]).slice(0, 5);

                }

            }



            restartWithChampions() {

            this.updateAllTimeBest();

            

            const champions = [];

            const addChamp = (list) => { if(list && list.length) champions.push(list[0]); };

            Object.values(this.allTimeBest).forEach(list => addChamp(list));

            

            this.gameIndex++; 

            this.stepTick = 0; 

            this.birthsCount = 0; 

            this.deathsCount = 0;

            this.effects = []; 

            this.paused = false; 

            this.gameOver = false;

            

            

            this.world = new World(this.config.worldSize, this.config.seaPct/100, this.config.rockPct/100, this.config.useEarth);

            

            this.nxers.clear(); 

            this.foods.clear(); 

            this.occupied.clear();

            this.initializeFood();

            

            let id = 0;

            

            champions.slice(0, 10).forEach(c => {

                const name = stripLeadingDigits(c.name).replace(/^-+/, '') || c.name;

                this.championCounts[name] = (this.championCounts[name]||0)+1;

                const pos = this.findFreePosition(c.canSea, c.canLand) || [0,0];

                

                const p = c.net.params.clone();

                

                // Inherit new sensory stats or randomize if champion is from old version

                const vision = c.visionRange || 5;

                const smell = c.smellRadius || 3;

                

                const n = new NxEr({

                    id: id++, 

                    name: `${this.championCounts[name]}${name}`, 

                    color: this.randomColor(), 

                    pos,

                    canLand: c.canLand, 

                    canSea: c.canSea, 

                    net: new NeuraxonNetwork(p),

                    food: this.config.startFood * 1.1, 

                    isMale: c.isMale, 

                    bornTick: 0, 

                    lastMoveTick: 0,

                    ticksPerAction: Math.max(2, Math.floor((this.config.globalTimeSteps * 1.2) / Math.max(1, p.simulationSteps))),

                    visionRange: vision,

                    smellRadius: smell,

                    heading: randomInt(0, 7),

                    clanId: null // Reset clan for fresh game start

                });

                

                this.nxers.set(n.id, n); 

                this.occupied.add(`${pos[0]},${pos[1]}`);

            });

            

            while (this.nxers.size < this.config.startingNxErs) {

                const n = this.createNxEr(id++);

                this.nxers.set(n.id, n);

                this.occupied.add(`${n.pos[0]},${n.pos[1]}`);

            }

        }



        // v3.0: NEW - Temperature regulation system

        updateNxErTemperature(nxer, dt, occupantAt, localEnvTemp = null) {

            const baseTemp = 37.0; // Normal body temperature

            

            // v3.1: Use local temperature if provided

            const envTemp = localEnvTemp !== null ? localEnvTemp : this.environmentTemperature;

            

            // Heat gain from food metabolism

            const foodHeat = nxer.food > this.config.startFood ? 0.02 : -0.01;

            

            // Heat gain from activity (movement increases temp)

            const activityHeat = nxer.tickAccum > 0 ? 0.05 : 0.0;

            

            // Environmental heat exchange (using local temp)

            const envDiff = envTemp - nxer.bodyTemperature;

            const envHeatExchange = envDiff * GameEngine.TEMP_TRANSFER_RATE * dt;

            

            // Social thermoregulation - heat from nearby NxErs (bioinspired huddling)

            let socialHeat = 0;

            for (let dy = -1; dy <= 1; dy++) {

                for (let dx = -1; dx <= 1; dx++) {

                    if (dx === 0 && dy === 0) continue;

                    const nx = (nxer.pos[0] + dx + this.world.N) % this.world.N;

                    const ny = nxer.pos[1] + dy;

                    if (ny < 0 || ny >= this.world.N) continue;

                    const neighbor = occupantAt.get(`${nx},${ny}`);

                    if (neighbor && neighbor.alive) {

                        // Heat transfer between NxErs

                        socialHeat += (neighbor.bodyTemperature - nxer.bodyTemperature) * 0.02;

                    }

                }

            }

            

            // Update temperature

            nxer.bodyTemperature += activityHeat + foodHeat + envHeatExchange + socialHeat;

            

            // Homeostatic regulation (body tries to maintain 37°C)

            const homeostaticCorrection = (baseTemp - nxer.bodyTemperature) * 0.05 * dt;

            nxer.bodyTemperature += homeostaticCorrection;

            

            // Clamp to survivable range

            nxer.bodyTemperature = clamp(nxer.bodyTemperature, 30.0, 42.0);

            

            // Extreme temperatures cause damage

            if (nxer.bodyTemperature < 32.0 || nxer.bodyTemperature > 41.0) {

                nxer.food -= 0.1 * dt; // Energy drain from thermal stress

                nxer.net.neuromodulators.norepinephrine = Math.min(2.0, 

                    nxer.net.neuromodulators.norepinephrine + 0.1); // Stress response

            }

        }



            getStats() {

                 const alive = Array.from(this.nxers.values()).filter(n => n.alive);

                 let avgE = 0, avgB = 0;

                 if (alive.length) {

                     avgE = alive.reduce((s, n) => s + n.net.getEnergyStatus().averageEnergy, 0) / alive.length;

                     avgB = alive.reduce((s, n) => s + n.net.branchingRatio, 0) / alive.length;

                 }

                 // v3.0: Add day/night and temperature stats

                 const phaseNames = ['Day', 'Dusk', 'Night', 'Dawn'];

                 let avgTemp = 0;

                 if (alive.length) {

                     avgTemp = alive.reduce((s, n) => s + n.bodyTemperature, 0) / alive.length;

                 }

                 return { 

                     alive: alive.length, 

                     dead: this.deathsCount, 

                     born: this.birthsCount, 

                     avgEnergy: avgE.toFixed(1), 

                     avgBranching: avgB.toFixed(2),

                     dayNightPhase: phaseNames[this.dayNightPhase],

                     envTemp: this.environmentTemperature.toFixed(1),

                     avgBodyTemp: avgTemp.toFixed(1)

                 };

            }

        }



        // =====================================================================

        // 3D RENDERER (THREE.JS) 

        // =====================================================================



        // =====================================================================

        // PARTICLE SYSTEM FOR LIFE EVENTS

        // =====================================================================

        

        class ParticleSystem {

            constructor(scene) {

                this.scene = scene;

                this.particleGroups = [];

                this.maxParticles = 5000;

                

                // Shared geometries and materials for performance

                this.sparkGeometry = new THREE.BufferGeometry();

                const positions = new Float32Array(this.maxParticles * 3);

                const colors = new Float32Array(this.maxParticles * 3);

                const sizes = new Float32Array(this.maxParticles);

                const alphas = new Float32Array(this.maxParticles);

                

                this.sparkGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));

                this.sparkGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));

                this.sparkGeometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));

                this.sparkGeometry.setAttribute('alpha', new THREE.BufferAttribute(alphas, 1));

                

                this.sparkMaterial = new THREE.ShaderMaterial({

                    uniforms: { time: { value: 0 } },

                    vertexShader: `

                        attribute float size;

                        attribute float alpha;

                        attribute vec3 color;

                        varying vec3 vColor;

                        varying float vAlpha;

                        void main() {

                            vColor = color;

                            vAlpha = alpha;

                            vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);

                            gl_PointSize = size * (300.0 / -mvPosition.z);

                            gl_Position = projectionMatrix * mvPosition;

                        }

                    `,

                    fragmentShader: `

                        varying vec3 vColor;

                        varying float vAlpha;

                        void main() {

                            float r = distance(gl_PointCoord, vec2(0.5));

                            if (r > 0.5) discard;

                            float glow = 1.0 - smoothstep(0.0, 0.5, r);

                            gl_FragColor = vec4(vColor, vAlpha * glow);

                        }

                    `,

                    transparent: true,

                    depthWrite: false,

                    blending: THREE.AdditiveBlending

                });

                

                this.particles = [];

                this.activeCount = 0;

            }

            

            emit(type, position, count = 20) {

                const configs = {

                    birth: { color: [0.3, 1.0, 0.5], size: 2.5, speed: 0.08, life: 80, gravity: -0.001 },

                    death: { color: [0.6, 0.4, 0.8], size: 1.8, speed: 0.04, life: 120, gravity: 0.002 },

                    mate: { color: [1.0, 0.3, 0.5], size: 2.0, speed: 0.05, life: 60, gravity: 0.0 },

                    eat: { color: [1.0, 0.8, 0.2], size: 1.5, speed: 0.03, life: 40, gravity: -0.001 }

                };

                const cfg = configs[type] || configs.birth;

                

                for (let i = 0; i < count; i++) {

                    const theta = Math.random() * Math.PI * 2;

                    const phi = Math.random() * Math.PI;

                    const vel = new THREE.Vector3(

                        Math.sin(phi) * Math.cos(theta),

                        Math.sin(phi) * Math.sin(theta),

                        Math.cos(phi)

                    ).multiplyScalar(cfg.speed * (0.5 + Math.random()));

                    

                    this.particles.push({

                        pos: position.clone(),

                        vel: vel,

                        color: cfg.color.map(c => c * (0.8 + Math.random() * 0.4)),

                        size: cfg.size * (0.7 + Math.random() * 0.6),

                        life: cfg.life,

                        maxLife: cfg.life,

                        gravity: cfg.gravity

                    });

                }

            }

            

            update() {

                const positions = this.sparkGeometry.attributes.position.array;

                const colors = this.sparkGeometry.attributes.color.array;

                const sizes = this.sparkGeometry.attributes.size.array;

                const alphas = this.sparkGeometry.attributes.alpha.array;

                

                let idx = 0;

                this.particles = this.particles.filter(p => {

                    p.life--;

                    if (p.life <= 0 || idx >= this.maxParticles) return false;

                    

                    p.vel.y += p.gravity;

                    p.pos.add(p.vel);

                    

                    const i3 = idx * 3;

                    positions[i3] = p.pos.x; positions[i3+1] = p.pos.y; positions[i3+2] = p.pos.z;

                    colors[i3] = p.color[0]; colors[i3+1] = p.color[1]; colors[i3+2] = p.color[2];

                    sizes[idx] = p.size * (p.life / p.maxLife);

                    alphas[idx] = p.life / p.maxLife;

                    idx++;

                    return true;

                });

                

                this.sparkGeometry.setDrawRange(0, idx);

                this.sparkGeometry.attributes.position.needsUpdate = true;

                this.sparkGeometry.attributes.color.needsUpdate = true;

                this.sparkGeometry.attributes.size.needsUpdate = true;

                this.sparkGeometry.attributes.alpha.needsUpdate = true;

            }

            

            getMesh() {

                if (!this.mesh) {

                    this.mesh = new THREE.Points(this.sparkGeometry, this.sparkMaterial);

                    this.mesh.frustumCulled = false;

                    this.scene.add(this.mesh);

                }

                return this.mesh;

            }

        }



        class Renderer3D {

            constructor(canvas) {

                this.canvas = canvas;

                this.scene = new THREE.Scene();

                // v3.0: Dynamic background for day/night

                this.dayColor = new THREE.Color(0x2a3a55);

                this.nightColor = new THREE.Color(0x030305);

                this.currentBgColor = new THREE.Color(0x101015);

                this.scene.background = this.currentBgColor;

                this.scene.fog = new THREE.Fog(this.currentBgColor, 500, 2000);

                this.ambientLight = null;

                this.dirLight = null;

                

                // Animation time tracking

                this.clock = new THREE.Clock();

                this.animTime = 0;

                

                // v3.1: Sun position tracking

                this.sunAngle = 0;



                this.camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);

                this.camera.position.set(25, 40, 50);



                this.webgl = new THREE.WebGLRenderer({ canvas: this.canvas, antialias: true });

                this.webgl.setSize(window.innerWidth, window.innerHeight);

                this.webgl.shadowMap.enabled = true;

                this.webgl.toneMapping = THREE.ACESFilmicToneMapping;

                this.webgl.toneMappingExposure = 1.2;

                

                // Post-processing setup

                this.composer = new EffectComposer(this.webgl);

                const renderPass = new RenderPass(this.scene, this.camera);

                this.composer.addPass(renderPass);

                

                // Bloom pass for glow effects

                this.bloomPass = new UnrealBloomPass(

                    new THREE.Vector2(window.innerWidth, window.innerHeight),

                    0.8,   // strength

                    0.4,   // radius

                    0.85   // threshold

                );

                this.composer.addPass(this.bloomPass);

                

                // Particle system

                this.particles = new ParticleSystem(this.scene);



                this.controls = new OrbitControls(this.camera, this.canvas);

                this.controls.enableDamping = true;

                this.controls.dampingFactor = 0.05;



                // v3.1: Lower ambient for more contrast between day/night sides

                this.ambientLight = new THREE.AmbientLight(0x303040, 0.4); 

                this.scene.add(this.ambientLight);



                const hemiLight = new THREE.HemisphereLight(0xffffff, 0x111122, 1.0);

                this.scene.add(hemiLight);



                // v3.1: Main sun light - will orbit around planet

                this.dirLight = new THREE.DirectionalLight(0xffffee, 4.0);

                this.dirLight.position.set(200, 50, 0);

                this.dirLight.castShadow = true;

                this.dirLight.shadow.mapSize.width = 4096;

                this.dirLight.shadow.mapSize.height = 4096;

                const d = 200; 

                this.dirLight.shadow.camera.left = -d; this.dirLight.shadow.camera.right = d;

                this.dirLight.shadow.camera.top = d; this.dirLight.shadow.camera.bottom = -d;

                this.dirLight.shadow.camera.near = 0.5; this.dirLight.shadow.camera.far = 500;

                this.scene.add(this.dirLight);

                

                // Sun sphere (visible glowing sun)

                const sunGeo = new THREE.SphereGeometry(8, 32, 32);

                const sunMat = new THREE.MeshBasicMaterial({ 

                    color: 0xffdd44,

                    transparent: true,

                    opacity: 1.0

                });

                this.sunMesh = new THREE.Mesh(sunGeo, sunMat);

                this.sunMesh.position.set(200, 50, 0);

                this.sunMesh.layers.enable(1); // Bloom layer

                this.scene.add(this.sunMesh);

                

                // Atmosphere glow around planet

                this.atmosphereGlow = null;

                

                // v3.1: Add a subtle backlight for night side visibility

                this.nightLight = new THREE.DirectionalLight(0x4455aa, 0.08);

                this.nightLight.position.set(-200, 30, 0);

                this.scene.add(this.nightLight);

                

                // v3.1: Add point light at sun position for glow effect

                this.sunGlow = new THREE.PointLight(0xffaa44, 2.0, 500);

                this.sunGlow.position.set(200, 50, 0);

                this.scene.add(this.sunGlow);



                this.nxerMeshes = new Map();

                this.foodMeshes = new Map();

                this.effectMeshes = [];

                this.terrainMesh = null;



                // NEW: Visual helpers for selection

                this.selectionHelpers = {

                    sightLine: null,

                    smellRing: null,

                    group: new THREE.Group()

                };

                this.scene.add(this.selectionHelpers.group);



                this.raycaster = new THREE.Raycaster();

                this.mouse = new THREE.Vector2();

                this.selectedNxerId = null;



                window.addEventListener('resize', () => this.onWindowResize());

            }



            // ... [Keep onWindowResize, getSpherePos, createEmojiTexture, initTerrain as they were] ...

            

            onWindowResize() {

                this.camera.aspect = window.innerWidth / window.innerHeight;

                this.camera.updateProjectionMatrix();

                this.webgl.setSize(window.innerWidth, window.innerHeight);

                this.composer.setSize(window.innerWidth, window.innerHeight);

            }



            getSpherePos(x, y, worldN, radius) {

                const phi = (x / worldN) * Math.PI * 2;

                const v = y / worldN;

                const theta = (v * 0.99 + 0.005) * Math.PI;

                const px = radius * Math.sin(theta) * Math.cos(phi);

                const py = radius * Math.cos(theta);

                const pz = radius * Math.sin(theta) * Math.sin(phi);

                return new THREE.Vector3(px, py, pz);

            }



            createEmojiTexture(emoji) {

                const canvas = document.createElement('canvas');

                canvas.width = 64; canvas.height = 64;

                const ctx = canvas.getContext('2d');

                ctx.font = '48px "Segoe UI Emoji", sans-serif';

                ctx.textAlign = 'center'; ctx.textBaseline = 'middle';

                ctx.fillText(emoji, 32, 32);

                return new THREE.CanvasTexture(canvas);

            }



            initTerrain(world) {

                // [Code same as provided in previous turn]

                if (this.terrainMesh) {

                    if(this.terrainMesh.geometry) this.terrainMesh.geometry.dispose();

                    if(this.terrainMesh.material) this.terrainMesh.material.dispose();

                    this.scene.remove(this.terrainMesh);

                }

                if (this.coreSphere) this.scene.remove(this.coreSphere);



                this.planetRadius = (world.N * 0.8) / 2; 



                const coreGeo = new THREE.SphereGeometry(this.planetRadius, 64, 64);

                const coreMat = new THREE.MeshStandardMaterial({ color: 0x1964c8, roughness: 0.2, metalness: 0.1 });

                this.coreSphere = new THREE.Mesh(coreGeo, coreMat);

                this.coreSphere.receiveShadow = true;

                this.scene.add(this.coreSphere);



                // Atmosphere glow effect

                if (this.atmosphereGlow) this.scene.remove(this.atmosphereGlow);

                const atmosGeo = new THREE.SphereGeometry(this.planetRadius * 1.05, 64, 64);

                const atmosMat = new THREE.ShaderMaterial({

                    uniforms: {

                        glowColor: { value: new THREE.Color(0x4488ff) },

                        viewVector: { value: this.camera.position }

                    },

                    vertexShader: `

                        varying vec3 vNormal;

                        void main() {

                            vNormal = normalize(normalMatrix * normal);

                            gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

                        }`,

                    fragmentShader: `

                        uniform vec3 glowColor;

                        varying vec3 vNormal;

                        void main() {

                            float intensity = pow(0.7 - dot(vNormal, vec3(0.0, 0.0, 1.0)), 2.0);

                            gl_FragColor = vec4(glowColor, intensity * 0.4);

                        }`,

                    side: THREE.BackSide,

                    blending: THREE.AdditiveBlending,

                    transparent: true

                });

                this.atmosphereGlow = new THREE.Mesh(atmosGeo, atmosMat);

                this.scene.add(this.atmosphereGlow);



                const geometry = new THREE.IcosahedronGeometry(this.planetRadius, 40);

                const count = geometry.attributes.position.count;

                const posAttr = geometry.attributes.position;

                const colAttr = new THREE.BufferAttribute(new Float32Array(count * 3), 3);

                const vertex = new THREE.Vector3();

                const color = new THREE.Color();



                for (let i = 0; i < count; i++) {

                    vertex.fromBufferAttribute(posAttr, i);

                    const normal = vertex.clone().normalize();

                    let phi = Math.atan2(vertex.z, vertex.x);

                    if (phi < 0) phi += Math.PI * 2;

                    const u = 1.0 - (phi / (Math.PI * 2));

                    const theta = Math.acos(Math.max(-1, Math.min(1, vertex.y / this.planetRadius)));

                    const v = theta / Math.PI;

                    const uOffset = (u + 0.25) % 1.0; 

                    const gx = Math.floor(uOffset * world.N) % world.N;

                    const gy = Math.floor(v * world.N) % world.N;

                    const t = world.terrain(gx, gy);

                    let h = -0.1;

                    if (t === 1) { h = 0.3; color.setHex(0x28b43c); }

                    else if (t === 2) { h = 1.0; color.setHex(0x6e6e6e); }

                    else { color.setHex(0x1964c8); }

                    vertex.copy(normal).multiplyScalar(this.planetRadius + h);

                    posAttr.setXYZ(i, vertex.x, vertex.y, vertex.z);

                    colAttr.setXYZ(i, color.r, color.g, color.b);

                }

                geometry.setAttribute('color', colAttr);

                geometry.computeVertexNormals();

                const mat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.8, flatShading: false });

                this.terrainMesh = new THREE.Mesh(geometry, mat);

                this.terrainMesh.castShadow = true;

                this.terrainMesh.receiveShadow = true;

                this.scene.add(this.terrainMesh);

                

                this.controls.target.set(0, 0, 0);

                this.camera.position.set(0, 0, this.planetRadius * 2.5);

                this.controls.minPolarAngle = 0; 

                this.controls.maxPolarAngle = Math.PI; 

                this.controls.minDistance = this.planetRadius * 1.2;

                this.controls.maxDistance = this.planetRadius * 6;

            }



            clearEntities() {

                this.nxerMeshes.forEach(m => this.scene.remove(m)); this.nxerMeshes.clear();

                this.foodMeshes.forEach(m => this.scene.remove(m)); this.foodMeshes.clear();

                this.effectMeshes.forEach(e => this.scene.remove(e.mesh)); this.effectMeshes = [];

                this.clearSelectionVisuals();

            }



            // NEW: Clears visual helpers

            clearSelectionVisuals() {

                // Remove Line

                if (this.selectionHelpers.sightLine) {

                    this.selectionHelpers.group.remove(this.selectionHelpers.sightLine);

                    if (this.selectionHelpers.sightLine.geometry) this.selectionHelpers.sightLine.geometry.dispose();

                    if (this.selectionHelpers.sightLine.material) this.selectionHelpers.sightLine.material.dispose();

                    this.selectionHelpers.sightLine = null;

                }

                

                // Hide Ring (don't dispose geometry, just hide/reset)

                if (this.selectionHelpers.smellRing) {

                    this.selectionHelpers.smellRing.visible = false;

                }

            }



            updateSelectionVisuals(nxer, world) {

    if (!nxer || !nxer.alive) {

        this.clearSelectionVisuals();

        return;

    }



    // --- 1. SETUP HELPERS IF MISSING ---

    if (!this.selectionHelpers.smellRing) {

        // TUBE THICKNESS INCREASED: 0.03 -> 0.1 for visibility

        const geometry = new THREE.TorusGeometry(1, 0.1, 16, 64); 

        // DOUBLE SIDE & DEPTH TEST FALSE ensures it's seen even if slightly underground

        const material = new THREE.MeshBasicMaterial({ 

            color: 0xffff00, 

            transparent: true, 

            opacity: 0.6,

            side: THREE.DoubleSide,

            depthTest: false // Optional: makes it always render on top

        });

        const ring = new THREE.Mesh(geometry, material);

        // Important: renderOrder ensures it draws on top of terrain

        ring.renderOrder = 999; 

        this.selectionHelpers.group.add(ring);

        this.selectionHelpers.smellRing = ring;

    }



    // --- 2. CALCULATE START POSITION ---

    const t = world.terrain(nxer.pos[0], nxer.pos[1]);

    

    // INCREASED OFFSET: Lifted higher (+0.8) to avoid z-fighting with mountains

    const hOffset = (t === 1 ? 0.3 : (t === 2 ? 1.0 : 0.0)) + 0.8; 

    

    const startPos = this.getSpherePos(nxer.pos[0], nxer.pos[1], world.N, this.planetRadius + hOffset);



    // --- 3. UPDATE SMELL RING (Yellow) ---

    const ring = this.selectionHelpers.smellRing;

    ring.visible = true;

    ring.position.copy(startPos);

    

    // Orient ring tangent to sphere surface

    ring.lookAt(0, 0, 0); 

    

    // Calculate Scale

    const gridUnitSize = (2 * Math.PI * this.planetRadius) / world.N;

    const ringRadius = (nxer.smellRadius || 3) * gridUnitSize;

    

    ring.scale.set(ringRadius, ringRadius, 1);



    // --- 4. UPDATE SIGHT LINE (Blue Curve) ---

    if (this.selectionHelpers.sightLine) {

        this.selectionHelpers.group.remove(this.selectionHelpers.sightLine);

        if(this.selectionHelpers.sightLine.geometry) this.selectionHelpers.sightLine.geometry.dispose();

        this.selectionHelpers.sightLine = null;

    }



    const DIR_OFFSETS = [

        [-1, -1], [0, -1], [1, -1], [1, 0], 

        [1, 1],   [0, 1],  [-1, 1], [-1, 0]

    ]; // 0=NW to 7=W

    

    // Fallback if heading is undefined

    const headingIndex = (nxer.heading !== undefined) ? nxer.heading : 0;

    const dir = DIR_OFFSETS[headingIndex] || [0,0];

    

    // Calculate Target

    const vRange = nxer.visionRange || 5;

    

    // Handle wrapping for X, clamping for Y

    let tx = (nxer.pos[0] + (dir[0] * vRange));

    tx = ((tx % world.N) + world.N) % world.N;

    

    let ty = nxer.pos[1] + (dir[1] * vRange);

    ty = clamp(ty, 0, world.N - 1);



    const tt = world.terrain(tx, ty);

    

    const hOffsetT = (tt === 1 ? 0.3 : (tt === 2 ? 1.0 : 0.0)) + 0.8;

    const endPos = this.getSpherePos(tx, ty, world.N, this.planetRadius + hOffsetT);



 

    const midPos = startPos.clone().add(endPos).normalize().multiplyScalar(this.planetRadius + hOffset + (vRange * 0.15));



    const curve = new THREE.QuadraticBezierCurve3(startPos, midPos, endPos);

    const points = curve.getPoints(12);

    const lineGeo = new THREE.BufferGeometry().setFromPoints(points);

    

        

    const lineMat = new THREE.LineBasicMaterial({ 

        color: 0x00ffff, 

        linewidth: 2,

        depthTest: false // Always visible

    });

    

    const line = new THREE.Line(lineGeo, lineMat);

    line.renderOrder = 999; // Draw on top

    this.selectionHelpers.sightLine = line;

    this.selectionHelpers.group.add(line);

}



            updateNxErs(nxers, world) {

                const delta = this.clock.getDelta();

                this.animTime += delta;

                

                let coldestId = null, hottestId = null, minTemp = Infinity, maxTemp = -Infinity;

                for (const nx of nxers.values()) {

                    if (!nx.alive) continue;

                    if (nx.bodyTemperature < minTemp) { minTemp = nx.bodyTemperature; coldestId = nx.id; }

                    if (nx.bodyTemperature > maxTemp) { maxTemp = nx.bodyTemperature; hottestId = nx.id; }

                }

                

                const N = world.N;

                for(const [id, m] of this.nxerMeshes) {

                    if(!nxers.has(id) || !nxers.get(id).alive) { this.scene.remove(m); this.nxerMeshes.delete(id); }

                }



                for(const nxer of nxers.values()) {

                    if(!nxer.alive) continue;

                    let mesh = this.nxerMeshes.get(nxer.id);

                    

                    const t = world.terrain(nxer.pos[0], nxer.pos[1]);

                    let hOffset = 0.0; 

                    if (t === 1) hOffset = 0.3; else if (t === 2) hOffset = 1.0;



                    const targetPos = this.getSpherePos(nxer.pos[0], nxer.pos[1], N, this.planetRadius + hOffset + 0.35);



                    if(!mesh) {

                        const g = new THREE.SphereGeometry(0.35, 12, 12);

                        

                        // Emissive material for glow effect

                        const baseColor = new THREE.Color(nxer.color);

                        const m = new THREE.MeshStandardMaterial({ 

                            color: nxer.color,

                            emissive: baseColor,

                            emissiveIntensity: 0.15,

                            roughness: 0.4,

                            metalness: 0.3

                        });

                        mesh = new THREE.Mesh(g, m); 

                        mesh.castShadow = true;

                        mesh.userData = { id: nxer.id, type: 'nxer' };

                        

                        // Energy ring with glow

                        const ringMat = new THREE.MeshBasicMaterial({ 

                            color: 0xff3333,

                            transparent: true,

                            opacity: 0.8

                        });

                        const r = new THREE.Mesh(new THREE.TorusGeometry(0.5, 0.04, 8, 24), ringMat);

                        r.rotation.x = Math.PI/2; 

                        mesh.add(r);

                        

                        // Gender indicator (small sphere on top)

                        const genderColor = nxer.isMale ? 0x4488ff : 0xff88aa;

                        const genderGeo = new THREE.SphereGeometry(0.08, 8, 8);

                        const genderMat = new THREE.MeshBasicMaterial({ color: genderColor });

                        const genderMarker = new THREE.Mesh(genderGeo, genderMat);

                        genderMarker.position.y = 0.4;

                        mesh.add(genderMarker);

                        

                        const clanCanvas = document.createElement('canvas');

                        clanCanvas.width = 64; clanCanvas.height = 64;

                        const clanCtx = clanCanvas.getContext('2d');

                        const clanTexture = new THREE.CanvasTexture(clanCanvas);

                        const clanSprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: clanTexture, transparent: true }));

                        clanSprite.scale.set(0.4, 0.4, 1);

                        clanSprite.position.y = 0.7;

                        mesh.add(clanSprite);

                        mesh.userData.clanSprite = clanSprite;

                        mesh.userData.clanCtx = clanCtx;

                        mesh.userData.clanTexture = clanTexture;

                        

                        const tempCanvas = document.createElement('canvas');

                        tempCanvas.width = 64; tempCanvas.height = 64;

                        const tempCtx = tempCanvas.getContext('2d');

                        const tempTexture = new THREE.CanvasTexture(tempCanvas);

                        const tempSprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: tempTexture, transparent: true }));

                        tempSprite.scale.set(0.5, 0.5, 1);

                        tempSprite.position.y = 1.0;

                        tempSprite.visible = false;

                        mesh.add(tempSprite);

                        mesh.userData.tempSprite = tempSprite;

                        mesh.userData.tempCtx = tempCtx;

                        mesh.userData.tempTexture = tempTexture;

                        

                        this.scene.add(mesh); this.nxerMeshes.set(nxer.id, mesh);

                        mesh.position.copy(targetPos);

                    }



                    const dist = mesh.position.distanceTo(targetPos);

                    if(dist > this.planetRadius) {

                        mesh.position.copy(targetPos);

                        mesh.visible = false;

                    } else {

                        mesh.visible = true;

                        const c = mesh.position.clone().normalize();

                        const t = targetPos.clone().normalize();

                        c.lerp(t, 0.15);

                        mesh.position.copy(c.multiplyScalar(this.planetRadius + hOffset + 0.35));

                    }



                    const up = new THREE.Vector3(0,1,0);

                    const norm = mesh.position.clone().normalize();

                    mesh.setRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(up, norm));

                    

                    // Animated idle behavior - breathing/pulsing

                    const energyRatio = Math.max(0.3, Math.min(1.0, nxer.food / 100));

                    const breathe = 1.0 + Math.sin(this.animTime * 3 + nxer.id) * 0.05 * energyRatio;

                    mesh.scale.setScalar(breathe);

                    

                    // Resting creatures bob slower and dimmer

                    if (nxer.isResting) {

                        mesh.scale.multiplyScalar(0.9);

                        mesh.material.emissiveIntensity = 0.05;

                    } else {

                        mesh.material.emissiveIntensity = 0.1 + energyRatio * 0.2;

                    }

                    

                    // Low energy = more transparent/dimmer

                    if (nxer.food < 30) {

                        mesh.material.opacity = 0.5 + (nxer.food / 30) * 0.5;

                        mesh.material.transparent = true;

                    } else {

                        mesh.material.opacity = 1.0;

                        mesh.material.transparent = false;

                    }



                    const ring = mesh.children[0];

                    if(ring) {

                        const es = nxer.net.getEnergyStatus();

                        const s = Math.max(0.1, Math.min(1.5, es.averageEnergy/80));

                        ring.scale.set(s, s, s);

                        ring.rotation.z = this.animTime * 2; // Spinning ring

                        ring.material.color.setHex(nxer.id === this.selectedNxerId ? 0x00ffff : 0xff3333);

                        ring.material.opacity = 0.6 + Math.sin(this.animTime * 5) * 0.2;

                    }

                    

                    if (mesh.userData.clanSprite) {

                        if (nxer.clanId !== null) {

                            const ctx = mesh.userData.clanCtx;

                            ctx.clearRect(0, 0, 64, 64);

                            ctx.fillStyle = '#ffffff';

                            ctx.font = 'bold 40px Arial';

                            ctx.textAlign = 'center';

                            ctx.textBaseline = 'middle';

                            ctx.fillText(nxer.clanId, 32, 32);

                            mesh.userData.clanTexture.needsUpdate = true;

                            mesh.userData.clanSprite.visible = true;

                        } else {

                            mesh.userData.clanSprite.visible = false;

                        }

                    }

                    

                    if (mesh.userData.tempSprite) {

                        const ctx = mesh.userData.tempCtx;

                        ctx.clearRect(0, 0, 64, 64);

                        if (nxer.id === coldestId) {

                            ctx.font = '48px Arial';

                            ctx.textAlign = 'center';

                            ctx.textBaseline = 'middle';

                            ctx.fillText('❄️', 32, 32);

                            mesh.userData.tempTexture.needsUpdate = true;

                            mesh.userData.tempSprite.visible = true;

                        } else if (nxer.id === hottestId) {

                            ctx.font = '48px Arial';

                            ctx.textAlign = 'center';

                            ctx.textBaseline = 'middle';

                            ctx.fillText('🔥', 32, 32);

                            mesh.userData.tempTexture.needsUpdate = true;

                            mesh.userData.tempSprite.visible = true;

                        } else {

                            mesh.userData.tempSprite.visible = false;

                        }

                    }

                }

            }

            

            // [updateFood, updateEffects, handleClick remain same]

            updateFood(foods, world) {

                for(const [id, m] of this.foodMeshes) if(!foods.has(id) || !foods.get(id).alive) { this.scene.remove(m); this.foodMeshes.delete(id); }

                for(const food of foods.values()) {

                    if(!food.alive) continue;

                    let mesh = this.foodMeshes.get(food.id);

                    if(!mesh) {

                        const g = new THREE.OctahedronGeometry(0.4, 0);

                        const m = new THREE.MeshStandardMaterial({ 

                            color: 0xff4444, 

                            emissive: 0xff2200,

                            emissiveIntensity: 0.4,

                            roughness: 0.3,

                            metalness: 0.5

                        });

                        mesh = new THREE.Mesh(g, m); mesh.castShadow = true;

                        this.scene.add(mesh); this.foodMeshes.set(food.id, mesh);

                    }

                    const t = world.terrain(food.pos[0], food.pos[1]);

                    let h = 0.0; if(t===1) h=0.3; else if(t===2) h=1.0;

                    const pos = this.getSpherePos(food.pos[0], food.pos[1], world.N, this.planetRadius + h + 0.45);

                    mesh.position.copy(pos);

                    const up = new THREE.Vector3(0,1,0);

                    const norm = pos.clone().normalize();

                    mesh.setRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(up, norm));

                    // Floating and rotating animation

                    mesh.rotateY(0.03);

                    const float = Math.sin(this.animTime * 2 + food.id * 0.5) * 0.1;

                    mesh.position.add(norm.multiplyScalar(float));

                }

            }



            updateEffects(engine) {

                this.effectMeshes = this.effectMeshes.filter(ef => {

                    const age = engine.stepTick - ef.startTick;

                    const upVec = ef.mesh.position.clone().normalize();

                    ef.mesh.position.add(upVec.multiplyScalar(0.08)); 

                    ef.mesh.material.opacity = 1.0 - (age / 60.0);

                    ef.mesh.scale.multiplyScalar(1.02); // Growing effect

                    if (age >= 80) { 

                        this.scene.remove(ef.mesh); 

                        if(ef.mesh.material.map) ef.mesh.material.map.dispose();

                        ef.mesh.material.dispose();

                        return false; 

                    }

                    return true;

                });

                

                if (!this.processedEffects) this.processedEffects = new Set();

                engine.effects.forEach(e => {

                    const eid = `${e.type}-${e.pos[0]}-${e.pos[1]}-${e.startTick}`;

                    if (!this.processedEffects.has(eid)) {

                        this.processedEffects.add(eid);

                        

                        // Emit particles for events

                        const pos3d = this.getSpherePos(e.pos[0], e.pos[1], engine.world.N, this.planetRadius + 1.0);

                        if (e.type === 'heart') {

                            this.particles.emit('birth', pos3d, 30);

                            this.particles.emit('mate', pos3d, 15);

                        } else if (e.type === 'skull') {

                            this.particles.emit('death', pos3d, 40);

                        }

                        

                        const icon = e.type === 'heart' ? '❤️' : '💀';

                        const map = this.createEmojiTexture(icon);

                        const mat = new THREE.SpriteMaterial({ map: map, transparent: true });

                        const sprite = new THREE.Sprite(mat);

                        const pos = this.getSpherePos(e.pos[0], e.pos[1], engine.world.N, this.planetRadius + 1.5);

                        sprite.position.copy(pos);

                        sprite.scale.set(1.5, 1.5, 1.5); 

                        this.scene.add(sprite);

                        this.effectMeshes.push({ mesh: sprite, startTick: e.startTick });

                    }

                });

                if (this.processedEffects.size > 100) this.processedEffects.clear();

                

                // Update particle system

                this.particles.update();

            }



            handleClick(x, y) {

                this.mouse.x = (x/window.innerWidth)*2-1; this.mouse.y = -(y/window.innerHeight)*2+1;

                this.raycaster.setFromCamera(this.mouse, this.camera);

                const hits = this.raycaster.intersectObjects(this.scene.children, true);

                for(const hit of hits) {

                    let o = hit.object;

                    while(o) { if(o.userData && o.userData.type==='nxer') return o.userData.id; o = o.parent; }

                }

                return null;

            }



            // v3.1: Update lighting with sun orbiting the planet

            updateDayNightLighting(engine) {

                if (!engine) return;

                

                // v3.1: Get sun longitude and orbit the light around the planet

                const sunLong = engine.sunLongitude || 0;

                const orbitRadius = this.planetRadius ? this.planetRadius * 3 : 200;

                

                // Calculate sun position (orbits in XZ plane)

                const sunX = Math.cos(sunLong) * orbitRadius;

                const sunZ = Math.sin(sunLong) * orbitRadius;

                const sunY = 50; // Slight elevation

                

                // Update directional light position

                if (this.dirLight) {

                    this.dirLight.position.set(sunX, sunY, sunZ);

                    this.dirLight.target.position.set(0, 0, 0);

                    

                    // Update sun mesh position

                    if (this.sunMesh) {

                        this.sunMesh.position.set(sunX, sunY, sunZ);

                    }

                    

                    // Warm sunrise/sunset colors

                    const globalDaylight = engine.getDaylightFactor();

                    const warmth = Math.sin(globalDaylight * Math.PI); // Peak at midday

                    const sunColor = new THREE.Color().setHSL(0.1 - warmth * 0.05, 0.8, 0.5 + globalDaylight * 0.3);

                    this.dirLight.color = sunColor;

                    this.dirLight.intensity = 2.0 + globalDaylight * 3.0;

                }

                

                // Update night light (opposite side)

                if (this.nightLight) {

                    this.nightLight.position.set(-sunX, sunY * 0.5, -sunZ);

                }

                

                // Update sun glow position

                if (this.sunGlow) {

                    this.sunGlow.position.set(sunX, sunY, sunZ);

                }

                

                // Update atmosphere glow color based on time of day

                if (this.atmosphereGlow && this.atmosphereGlow.material.uniforms) {

                    const daylightFactor = engine.getDaylightFactor();

                    const atmosColor = new THREE.Color().lerpColors(

                        new THREE.Color(0x2244aa), // Night - deep blue

                        new THREE.Color(0x88ccff), // Day - bright blue

                        daylightFactor

                    );

                    this.atmosphereGlow.material.uniforms.glowColor.value = atmosColor;

                    this.atmosphereGlow.material.uniforms.viewVector.value.copy(this.camera.position);

                }

                

                // v3.1: Background based on camera's view of sun

                // If camera is looking at lit side, brighter background

                const camDir = new THREE.Vector3();

                this.camera.getWorldDirection(camDir);

                const sunDir = new THREE.Vector3(sunX, sunY, sunZ).normalize();

                const viewingSun = camDir.dot(sunDir);

                const bgFactor = Math.max(0.1, Math.min(0.9, (viewingSun + 1) / 2));

                

                const daylightFactor = engine.getDaylightFactor();

                this.currentBgColor.copy(this.nightColor).lerp(this.dayColor, daylightFactor);

                this.scene.background = this.currentBgColor;

                this.scene.fog.color = this.currentBgColor;

                

                // Adjust bloom intensity based on time of day

                if (this.bloomPass) {

                    this.bloomPass.strength = 0.5 + daylightFactor * 0.5;

                }

                

                // Adjust ambient light intensity

                if (this.ambientLight) {

                    this.ambientLight.intensity = 0.8 + daylightFactor * 1.2;

                }

            }



            render(engine) {

                this.updateNxErs(engine.nxers, engine.world);

                this.updateFood(engine.foods, engine.world);

                this.updateEffects(engine);

                

                // v3.0: Update day/night lighting

                this.updateDayNightLighting(engine);

                

                // NEW: Update Selection Visuals every frame

                if (this.selectedNxerId !== null && engine.nxers.has(this.selectedNxerId)) {

                    this.updateSelectionVisuals(engine.nxers.get(this.selectedNxerId), engine.world);

                } else if (this.selectionHelpers.sightLine || this.selectionHelpers.smellRing) {

                    this.clearSelectionVisuals();

                }

                

                // Ensure particle mesh is created

                this.particles.getMesh();

                

                this.controls.update();

                this.composer.render(); // Use composer instead of direct render

            }

        }

        // =====================================================================

        // UI CONTROLLER

        // =====================================================================

        

        class UIController {

            constructor(engine, renderer) {

                this.engine = engine;

                this.renderer = renderer;

                

                this.hud = document.getElementById('hud');

                this.hudTitle = document.getElementById('hudTitle');

                this.hudContent = document.getElementById('hudContent');

                this.hudStats = document.getElementById('hudStats');

                this.buttonGroup = document.getElementById('buttonGroup');

                this.detailPanel = document.getElementById('detailPanel');

                this.detailTitle = document.getElementById('detailTitle');

                this.detailContent = document.getElementById('detailContent');

                this.gameOverModal = document.getElementById('gameOverModal');

                this.gameOverOverlay = document.getElementById('gameOverOverlay');

                this.controlsHint = document.getElementById('controlsHint');



                this.setupButtons();

                this.setupKeyboard();

                this.setupMouse();

            }



            setupButtons() {

                this.buttonGroup.innerHTML = `

                    <div class="button-row"><button class="hud-button" id="pauseBtn">Play</button></div>       

                    <div class="button-row"><button class="hud-button" id="saveBestBtn">Save Bests</button></div>

                    <div class="button-row"><button class="hud-button" id="exitBtn">Exit</button></div>                

                `;

                document.getElementById('pauseBtn').addEventListener('click', () => {

                    this.engine.paused = !this.engine.paused;

                    document.getElementById('pauseBtn').textContent = this.engine.paused ? 'Play' : 'Pause';

                });

                document.getElementById('exitBtn').addEventListener('click', () => { if (confirm('Return to menu?')) location.reload(); });

                document.getElementById('saveBestBtn').addEventListener('click', () => this.saveBestChampions());

                document.getElementById('restartYes').addEventListener('click', () => {

                    this.engine.restartWithChampions();

                    this.renderer.clearEntities();

                    this.renderer.initTerrain(this.engine.world);

                    this.gameOverModal.classList.add('hidden');

                    this.gameOverOverlay.classList.add('hidden');

                });

                document.getElementById('restartNo').addEventListener('click', () => location.reload());

                document.getElementById('hideControlsHint').addEventListener('click', () => this.controlsHint.classList.add('hidden'));

            }



            setupKeyboard() {

                document.addEventListener('keydown', (e) => {

                    if (e.key === ' ') {

                        e.preventDefault();

                        if (!this.engine.gameOver) {

                            this.engine.paused = !this.engine.paused;

                            document.getElementById('pauseBtn').textContent = this.engine.paused ? 'Play' : 'Pause';

                        }

                    } else if (e.key.toLowerCase() === 'h') {

                        e.preventDefault();

                        this.hud.classList.toggle('hidden');

                    }

                });

            }



            setupMouse() {

                this.renderer.canvas.addEventListener('click', (e) => {

                    // Don't trigger if dragging

                    const nxerId = this.renderer.handleClick(e.clientX, e.clientY);

                    this.updateDetailPanel(nxerId);

                });

            }



            update() {

                // 1. Update Title

                this.hudTitle.textContent = `Metrics: Round #${this.engine.gameIndex}`;

                

                // 2. Update Rankings

                const rankings = this.getRankings();

                // v3.1: Add sun position indicator

                const sunPos = ((this.engine.sunLongitude || 0) / (Math.PI * 2) * 360).toFixed(0);

                const phaseIcon = this.engine.dayNightPhase === 0 ? '☀️' : 

                                  this.engine.dayNightPhase === 2 ? '🌙' : '🌓';

                let html = `<div class="hud-section"><div class="hud-section-title">${phaseIcon} ${this.engine.getStats().dayNightPhase} | Sun: ${sunPos}° | Env: ${this.engine.getStats().envTemp}°C</div></div>`;

                for (const [title, data] of Object.entries(rankings)) {

                    html += `<div class="hud-section"><div class="hud-section-title">${title} (${data.best.toFixed(1)})</div>`;

                    for (const entry of data.entries) {

                        html += `<div class="hud-entry" data-nxer-id="${entry.id}"><span><span class="hud-dot" style="background:${entry.color}"></span>${entry.name}</span><span>${entry.value}</span></div>`;

                    }

                    html += `</div>`;

                }

                this.hudContent.innerHTML = html;

                

                // Re-attach click listeners for HUD items

                this.hudContent.querySelectorAll('.hud-entry').forEach(entry => {

                    entry.addEventListener('click', () => {

                        const nxerId = parseInt(entry.dataset.nxerId);

                        this.renderer.selectedNxerId = nxerId;

                        this.updateDetailPanel(nxerId);

                    });

                });



                // 3. Stats Display

                const stats = this.engine.getStats();

                this.hudStats.innerHTML = `

                    <div class="hud-stats">Alive: ${stats.alive} | Born: ${stats.born} | Dead: ${stats.dead}</div><div class="hud-stats">Avg Energy: ${stats.avgEnergy} | Branching: ${stats.avgBranching}</div><div class="hud-stats">Avg Body Temp: ${stats.avgBodyTemp}°C</div>

                    <div class="hud-stats">Branching: ${stats.avgBranching}</div>

                `;



                // 4. Game Over Modal

                if (this.engine.gameOver) {

                    this.gameOverModal.classList.remove('hidden');

                    this.gameOverOverlay.classList.remove('hidden');

                } else {

                    this.gameOverModal.classList.add('hidden');

                    this.gameOverOverlay.classList.add('hidden');

                }

                

                // 5. REAL-TIME DETAIL UPDATE

                // This ensures the numbers and the 3D visuals update even when not paused

                if (this.renderer.selectedNxerId !== null) {

                    this.updateDetailPanel(this.renderer.selectedNxerId);

                }

            }



            getRankings() {

    const all = Array.from(this.engine.nxers.values());

    if (all.length === 0) return {};



    // Sorters

    const byFood = all.slice().sort((a, b) => b.stats.foodFound - a.stats.foodFound);

    const byFoodTaken = all.slice().sort((a, b) => b.stats.foodTaken - a.stats.foodTaken);

    const byExplored = all.slice().sort((a, b) => b.stats.explored - a.stats.explored);

    const byLived = all.slice().sort((a, b) => b.stats.timeLived - a.stats.timeLived);

    const byMates = all.slice().sort((a, b) => b.stats.matesPerformed - a.stats.matesPerformed);

    const byFitness = all.slice().sort((a, b) => b.stats.fitness - a.stats.fitness);



    // Helper to format entries

    const format = (arr, key) => arr.slice(0, 3).map(n => ({

        name: n.alive ? n.name : `${n.name}†`,

        value: typeof n.stats[key] === 'number' ? n.stats[key].toFixed(1) : '0.0',

        color: n.color,

        id: n.id

    }));



    // Helper to get best historical score

    const getBestScore = (category, arr) => {

        const allCandidates = [...arr, ...(this.engine.allTimeBest[category] || [])];

        if (allCandidates.length === 0) return 0;

        return Math.max(...allCandidates.map(n => n.stats[category] || 0));

    };



    return {

        'Food Found': {

            entries: format(byFood, 'foodFound'),

            best: getBestScore('foodFound', byFood)

        },

        'Food Stolen': {

            entries: format(byFoodTaken, 'foodTaken'),

            best: getBestScore('foodTaken', byFoodTaken)

        },

        'Explored': {

            entries: format(byExplored, 'explored'),

            best: getBestScore('explored', byExplored)

        },

        'Time Lived': {

            entries: format(byLived, 'timeLived'),

            best: getBestScore('timeLived', byLived)

        },

        'Mates': {

            entries: format(byMates, 'matesPerformed'),

            best: getBestScore('matesPerformed', byMates)

        },

        'Fitness': {

            entries: format(byFitness, 'fitness'),

            best: getBestScore('fitness', byFitness)

        }

    };

}

    updateDetailPanel(nxerId) {

                // Check if valid

                if (nxerId === null || !this.engine.nxers.has(nxerId)) {

                    this.detailPanel.classList.add('hidden');               

                    this.renderer.clearSelectionVisuals();

                    return;

                }

                

                const nxer = this.engine.nxers.get(nxerId);

                this.detailPanel.classList.remove('hidden');

                

                // Update Title

                const gender = nxer.isMale ? 'Male' : 'Female';

                this.detailTitle.textContent = `${nxer.name} (id ${nxer.id}) - ${gender}`;

                

                // Helper strings

                const terrain = nxer.canLand && !nxer.canSea ? 'Land' :

                               nxer.canSea && !nxer.canLand ? 'Sea' : 'Both';

                

                const energyStatus = nxer.net.getEnergyStatus();

                const params = nxer.net.params;

                const clanDisplay = nxer.clanId !== null ? `Clan #${nxer.clanId}` : "No Clan";

                

                // Convert Heading Integer to String

                const headings = ["NW", "N", "NE", "E", "SE", "S", "SW", "W"];

                const headingStr = headings[nxer.heading] || "?";

                

                this.detailContent.innerHTML = `

                    <div class="detail-info">Color: <span style="display:inline-block;width:10px;height:10px;background:${nxer.color};border-radius:50%"></span> ${nxer.color}</div>

                    <div class="detail-info">Pos: [${nxer.pos[0]}, ${nxer.pos[1]}]  Food: ${nxer.food.toFixed(1)}</div>

                    <div class="detail-info">Alive: ${nxer.alive}  Terrain: ${terrain}</div>

                    <div class="detail-info"><strong>${clanDisplay}</strong></div>

                    

                    <div class="detail-section" style="border-top: 1px solid #444; margin-top: 5px; padding-top: 5px;">

                        <div style="color: #4a9eff; font-weight: bold; margin-bottom: 2px;">Sensory Data:</div>

                        <div class="detail-info">👁️ Vision Range: ${nxer.visionRange}</div>

                        <div class="detail-info">🧭 Facing: ${headingStr}</div>

                        <div class="detail-info">👃 Smell Radius: ${nxer.smellRadius}</div>

                    </div>



                    <div class="detail-section">

                        <div class="detail-info">Lived: ${nxer.stats.timeLived.toFixed(1)}s</div>

                        <div class="detail-info">Found: ${nxer.stats.foodFound.toFixed(1)}  Stolen: ${nxer.stats.foodTaken.toFixed(1)}</div>

                        <div class="detail-info">Mates: ${nxer.stats.matesPerformed}  Explored: ${nxer.stats.explored}</div>

                        <div class="detail-info">Energy: ${energyStatus.averageEnergy.toFixed(1)}  Fitness: ${nxer.stats.fitness.toFixed(3)}</div>

                        <div class="detail-info">Branching: ${energyStatus.branchingRatio.toFixed(2)}</div>

                    </div>

                    

                    <div class="detail-section">

                        <div style="color: #ff9944; font-weight: bold; margin-bottom: 2px;">v3.0 Bioinspired:</div>

                        <div class="detail-info">🌡️ Body Temp: ${nxer.bodyTemperature.toFixed(1)}°C</div>

                        <div class="detail-info">🧱 Rock Hits: ${nxer.consecutiveRockHits}</div>

                    </div>

                    

                    <div class="detail-section">

                        <div style="font-size: 14px; color: #c8c8c8; margin-bottom: 6px;">Network Parameters:</div>

                        <div class="detail-info" style="font-size: 11px;">inputs=${params.numInputNeurons} hidden=${params.numHiddenNeurons} outputs=${params.numOutputNeurons}</div>

                        <div class="detail-info" style="font-size: 11px;">conn=${params.connectionProbability.toFixed(2)} steps=${params.simulationSteps}</div>

                        <div class="detail-info" style="font-size: 11px;">τ_fast=${params.tauFast.toFixed(1)} τ_slow=${params.tauSlow.toFixed(1)} τ_meta=${params.tauMeta.toFixed(0)}</div>

                        <div class="detail-info" style="font-size: 11px;">θ_exc=${params.firingThresholdExcitatory.toFixed(2)} θ_inh=${params.firingThresholdInhibitory.toFixed(2)}</div>

                        <div class="detail-info" style="font-size: 11px;">learn=${params.learningRate.toFixed(3)} stdp=${params.stdpWindow.toFixed(1)}</div>

                    </div>

                `;



                // Re-bind save button if it exists

                const btn = document.getElementById('saveSingleBtn');

                if(btn) btn.onclick = () => this.saveNxEr(nxer);

            }



saveNxEr(nxer) {

            const data = {

                meta: {

                    created: new Date().toISOString(),

                    type: 'NxEr',

                    engine: 'Neuraxon 3D v3'

                },

                nxer: {

                    name: nxer.name,

                    color: nxer.color,

                    canLand: nxer.canLand,

                    canSea: nxer.canSea,

                    isMale: nxer.isMale,

                    // NEW: Save Clan and Senses

                    visionRange: nxer.visionRange,

                    smellRadius: nxer.smellRadius,

                    heading: nxer.heading,

                    clanId: nxer.clanId,

                    stats: nxer.stats,

                    // v3.0: Save new properties

                    bodyTemperature: nxer.bodyTemperature,

                    consecutiveRockHits: nxer.consecutiveRockHits,

                    networkParams: nxer.net.params

                }

            };

            const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });

            const url = URL.createObjectURL(blob);

            const a = document.createElement('a');

            a.href = url;

            a.download = `nxer_${nxer.name}_3d_v3.json`;

            a.click();

            URL.revokeObjectURL(url);

        }



            saveBestChampions() {

                this.engine.updateAllTimeBest();

                const data = { meta: { created: new Date().toISOString(), type: 'Neuraxon3D' }, champions: {} };

                for (const [cat, nxers] of Object.entries(this.engine.allTimeBest)) {

                    data.champions[cat] = nxers.map(n => ({ name: n.name, color: n.color, stats: n.stats, params: n.net.params }));

                }

                const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });

                const url = URL.createObjectURL(blob);

                const a = document.createElement('a'); a.href = url; a.download = `neuraxon_3d_v3_bests.json`; a.click();

            }

        }



        // =====================================================================

        // MAIN APPLICATION

        // =====================================================================

        

        class Application {

            constructor() {

                this.setupSplashScreen();

            }



            setupSplashScreen() {

                const splash = document.getElementById('splashScreen');

                splash.addEventListener('click', () => {

                    splash.classList.add('hidden');

                    this.showConfigScreen();

                });

            }



            showConfigScreen() {

                const configScreen = document.getElementById('configScreen');

                configScreen.classList.remove('hidden');

                const sliders = ['worldSize','seaPct','rockPct','startingNxErs','maxNxErs','maxFood','foodRespawn','startFood','maxNeurons','globalTimeSteps','mateCooldown','dayNightCycle','baseTemperature'];

                sliders.forEach(id => {

                    const el = document.getElementById(id);

                    const span = document.getElementById(id+'Value');

                    el.addEventListener('input', () => span.textContent = el.value + (id.includes('Pct')?'%':''));

                });



                document.getElementById('startButton').addEventListener('click', () => {

                    const config = {};

                    sliders.forEach(id => config[id] = parseFloat(document.getElementById(id).value));

                    

         

                    config.useEarth = document.getElementById('useEarth').checked;

                    

                    configScreen.classList.add('hidden');

                    document.getElementById('loader').style.display = 'block';

                    setTimeout(() => this.startGame(config), 100);

                });

            }



            startGame(config) {

                const canvas = document.getElementById('gameCanvas');

                canvas.classList.remove('hidden');

                document.getElementById('hud').classList.remove('hidden');

                document.getElementById('controlsHint').classList.remove('hidden');

                document.getElementById('loader').style.display = 'none';



                const engine = new GameEngine(config);

                const renderer = new Renderer3D(canvas);

                renderer.initTerrain(engine.world);

                const ui = new UIController(engine, renderer);



                let lastTime = performance.now();

                let accumulator = 0;

                const fixedDt = 1.0 / 60.0;



                const gameLoop = (currentTime) => {

                    const dt = Math.min((currentTime - lastTime) / 1000, 0.1);

                    lastTime = currentTime;

                    accumulator += dt;

                    

                    let steps = 0;

                    while (accumulator >= fixedDt && steps < 10) {

                        engine.step();

                        accumulator -= fixedDt;

                        steps++;

                    }

                    if (steps >= 5) accumulator = 0; 



                    renderer.render(engine);

                    ui.update();

                    requestAnimationFrame(gameLoop);

                };



                requestAnimationFrame(gameLoop);

            }

        }



        new Application();

    </script>
</body>
</html>