File size: 50,974 Bytes
f8506a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Why does this orbit do that? — Gravity sandbox (+ colored noise)</title>
<style>
  :root {
    --bg: #07070f; --panel: #111120; --border: #27273a; --text: #e8e8f2;
    --dim: #8a8aa4; --accent: #6cf; --good: #4caf50; --bad: #ff5566;
    --warn: #ffb454; --star: #ffd257; --planet: #5ea8ff; --hole: #b47aff;
  }
  * { box-sizing: border-box; }
  body {
    margin: 0; background: var(--bg); color: var(--text);
    font-family: ui-sans-serif, system-ui, -apple-system, sans-serif;
    font-size: 14px; line-height: 1.55;
  }
  header { padding: 14px 22px; border-bottom: 1px solid var(--border); }
  header h1 { margin: 0 0 3px; font-size: 17px; font-weight: 600; }
  header p { margin: 0; color: var(--dim); font-size: 12.5px; max-width: 980px; }
  main {
    display: grid; grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr);
    gap: 14px; padding: 14px; max-width: 1480px; margin: 0 auto;
  }
  @media (max-width: 1000px) { main { grid-template-columns: 1fr; } }
  .panel { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
  .panel-header {
    padding: 8px 12px; border-bottom: 1px solid var(--border);
    display: flex; align-items: center; justify-content: space-between;
    gap: 8px; flex-wrap: wrap;
  }
  .panel-header h2 {
    margin: 0; font-size: 11px; font-weight: 600;
    text-transform: uppercase; letter-spacing: 0.07em; color: var(--dim);
  }
  .toolrow { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
  button, select {
    background: #0d0d19; color: var(--text); border: 1px solid var(--border);
    border-radius: 4px; padding: 4px 9px; font-size: 11.5px; cursor: pointer;
    font-family: inherit;
  }
  button:hover { border-color: var(--accent); color: var(--accent); }
  button.on { border-color: var(--accent); color: var(--accent); background: rgba(102,204,255,0.10); }
  .canvas-wrap { position: relative; background: #04040a; line-height: 0; }
  canvas { display: block; width: 100%; height: auto; touch-action: none; }
  #stage { cursor: crosshair; }
  .badge {
    position: absolute; font-family: ui-monospace, monospace; font-size: 10.5px;
    color: var(--dim); background: rgba(0,0,0,0.55); padding: 3px 7px;
    border-radius: 4px; pointer-events: none;
  }
  #coordBadge { bottom: 8px; left: 8px; }
  #modeBadge { top: 8px; left: 8px; }
  #modeBadge.armed { color: var(--accent); border: 1px solid rgba(102,204,255,0.4); }
  .strip {
    display: grid; grid-template-columns: repeat(4, minmax(0,1fr));
    gap: 1px; background: var(--border); border-top: 1px solid var(--border);
  }
  .stat { background: var(--panel); padding: 7px 10px; }
  .stat .k { font-size: 9.5px; color: var(--dim); text-transform: uppercase; letter-spacing: 0.05em; }
  .stat .v { font-family: ui-monospace, monospace; font-size: 13px; color: var(--text); margin-top: 1px; }
  @media (max-width: 620px) { .strip { grid-template-columns: repeat(2, minmax(0,1fr)); } }
  #explanation { padding: 12px 15px; font-size: 12.5px; max-height: 560px; overflow-y: auto; }
  #explanation h3 { margin: 0 0 8px; font-size: 12.5px; color: var(--accent); font-weight: 600; }
  #explanation h4 { margin: 14px 0 4px; font-size: 11px; color: var(--dim); text-transform: uppercase; letter-spacing: 0.06em; }
  #explanation p { margin: 7px 0; }
  .verdict { padding: 7px 11px; border-radius: 4px; margin: 9px 0; font-weight: 600; font-size: 12.5px; }
  .verdict.bad { background: rgba(255,85,102,0.12); color: #ff8a99; border-left: 3px solid #ff5566; }
  .verdict.good { background: rgba(76,175,80,0.12); color: #8fdc92; border-left: 3px solid #4caf50; }
  .verdict.warn { background: rgba(255,180,84,0.12); color: #ffcf8a; border-left: 3px solid #ffb454; }
  .verdict.info { background: rgba(180,122,255,0.12); color: #d3b3ff; border-left: 3px solid #b47aff; }
  #explanation table { width: 100%; border-collapse: collapse; font-family: ui-monospace, monospace; font-size: 11px; margin: 7px 0; }
  #explanation th, #explanation td { text-align: left; padding: 3px 6px; border-bottom: 1px solid var(--border); }
  #explanation th { color: var(--dim); font-weight: 500; }
  .eq { font-family: ui-monospace, monospace; font-size: 12px; background: #0d0d19; border: 1px solid var(--border); border-radius: 4px; padding: 7px 10px; margin: 7px 0; line-height: 1.85; overflow-x: auto; }
  .note { color: var(--dim); font-size: 11.5px; border-top: 1px solid var(--border); padding-top: 9px; margin-top: 13px; line-height: 1.6; }
  .legend { display: flex; gap: 11px; flex-wrap: wrap; font-size: 10.5px; color: var(--dim); align-items: center; }
  .legend span { display: inline-flex; align-items: center; gap: 4px; }
  .swatch { width: 9px; height: 9px; border-radius: 50%; display: inline-block; }
  .slider-row { display: flex; align-items: center; gap: 7px; font-size: 10.5px; color: var(--dim); }
  input[type="range"] { width: 92px; accent-color: var(--accent); }
  .massval { font-family: ui-monospace, monospace; color: var(--text); min-width: 34px; display: inline-block; }

  /* ---- colored-noise panel ---- */
  .noise-box {
    border-top: 1px solid var(--border); padding: 9px 12px; display: flex;
    gap: 16px; flex-wrap: wrap; align-items: center;
    background: rgba(180,122,255,0.045);
  }
  .noise-box.disabled { opacity: 0.4; pointer-events: none; }
  .noise-title {
    font-size: 10px; text-transform: uppercase; letter-spacing: 0.07em;
    color: #c9a8ff; font-weight: 600; display: flex; align-items: center; gap: 6px;
  }
  .noise-title input { accent-color: #b47aff; }
  .tau-meter {
    font-family: ui-monospace, monospace; font-size: 10.5px;
    padding: 2px 7px; border-radius: 4px; border: 1px solid var(--border);
    white-space: nowrap;
  }
  .tau-meter.stiff { color: #8fdc92; border-color: rgba(76,175,80,0.55); background: rgba(76,175,80,0.08); }
  .tau-meter.mid { color: #ffcf8a; border-color: rgba(255,180,84,0.55); background: rgba(255,180,84,0.08); }
  .tau-meter.soft { color: #ff8a99; border-color: rgba(255,85,102,0.55); background: rgba(255,85,102,0.08); }
  .gamma-note { font-size: 10px; color: var(--dim); font-family: ui-monospace, monospace; }
</style>
</head>
<body>
<header>
  <h1>Why does this orbit do that?</h1>
  <p>A gravitational sandbox. Place stars, planets and black holes, drop test particles, and read <i>why</i> the motion is what it is. Now with a <b>colored-noise</b> bath: an Ornstein–Uhlenbeck process with its own relaxation time τ, paired to damping by the fluctuation–dissipation relation.</p>
</header>
<main>
  <div class="panel">
    <div class="panel-header">
      <h2>Space</h2>
      <div class="toolrow">
        <button id="btnStar" class="tool">+ Star</button>
        <button id="btnPlanet" class="tool">+ Planet</button>
        <button id="btnHole" class="tool">+ Black hole</button>
        <button id="btnClear">Clear</button>
      </div>
    </div>
    <div class="canvas-wrap">
      <canvas id="stage" width="720" height="620"></canvas>
      <div class="badge" id="modeBadge">click to drop a test particle</div>
      <div class="badge" id="coordBadge">—</div>
    </div>
    <div class="toolrow" style="padding:8px 12px; border-top:1px solid var(--border);">
      <button id="btnParticle" class="tool on">+ Test particle</button>
      <button id="btnEnsemble">+ noise ensemble</button>
      <button id="btnPause">Pause</button>
      <button id="btnReset">Reset sim</button>
      <button id="btnPreset">Sun + planets</button>
      <button id="btnBinary">binary + circumbinary</button>
      <button id="btnBH">black hole + star</button>
      <span class="slider-row">mass <input type="range" id="massSlider" min="1" max="60" value="10"><span class="massval" id="massVal">10</span></span>
      <span class="slider-row">GR <input type="range" id="grSlider" min="0" max="1" step="0.05" value="0"><span class="massval" id="grVal">0.00</span></span>
    </div>

    <!-- ======== colored noise controls ======== -->
    <div class="noise-box" id="noiseBox">
      <label class="noise-title"><input type="checkbox" id="noiseEnable"> colored-noise bath (OU)</label>
      <span class="slider-row">τ <input type="range" id="tauSlider" min="-3.3" max="1.3" step="0.05" value="-0.7"><span class="massval" id="tauVal">0.20</span></span>
      <span class="slider-row">D <input type="range" id="dSlider" min="-6" max="0" step="0.05" value="-3.30"><span class="massval" id="dVal">0.0005</span></span>
      <span class="tau-meter" id="tauMeter">dt/τ —</span>
      <span class="gamma-note" id="gammaNote">γ = 1/τ = — , pairing active</span>
    </div>

    <div class="legend" style="padding:0 12px 9px;">
      <span><i class="swatch" style="background:var(--star)"></i>star</span>
      <span><i class="swatch" style="background:var(--planet)"></i>planet</span>
      <span><i class="swatch" style="background:var(--hole)"></i>black hole</span>
      <span><i class="swatch" style="background:#ff5566"></i>deterministic particle</span>
      <span><i class="swatch" style="background:#b47aff"></i>noisy particle (OU)</span>
      <span>drag a body to move · drag empty space to pan · scroll to zoom</span>
    </div>
    <div class="strip">
      <div class="stat"><div class="k">Flux through ring</div><div class="v" id="s-flux">—</div></div>
      <div class="stat"><div class="k">Enclosed mass</div><div class="v" id="s-menc">—</div></div>
      <div class="stat"><div class="k">ω_r / ω_φ</div><div class="v" id="s-ratio">—</div></div>
      <div class="stat"><div class="k">escape time</div><div class="v" id="s-escape">safe</div></div>
    </div>
  </div>

  <div class="panel">
    <div class="panel-header">
      <h2>Why — local analysis</h2>
      <div class="toolrow">
        <button id="btnProbe" class="on">ring probe</button>
        <button id="btnField" class="on">field</button>
        <button id="btnStream" class="on">streamlines</button>
        <button id="btnTrace" class="on">trace orbits</button>
        <button id="btnNoiseHist" class="on">noise η(t)</button>
      </div>
    </div>
    <div class="canvas-wrap">
      <canvas id="noisePlot" width="720" height="130"></canvas>
    </div>
    <div id="explanation">
      <p style="color:var(--dim)">Place a body, move the cursor to probe Gauss's law, drop a test particle to trace an orbit, or enable the colored-noise bath.</p>
    </div>
  </div>
</main>

<script>
"use strict";

// ================================================================ constants
const W = 720, H = 620;
const G_CONST = 1.0;
const SOFT2 = 0.05;
const DT = 0.0012;
const SUBS = 4;
const ESCAPE_RADIUS = 18;

const stage = document.getElementById("stage");
const ctx = stage.getContext("2d");
const noisePlot = document.getElementById("noisePlot");
const nctx = noisePlot.getContext("2d");
const explanationEl = document.getElementById("explanation");
const coordBadge = document.getElementById("coordBadge");
const modeBadge = document.getElementById("modeBadge");

// ================================================================ state
let bodies = [];
let particles = [];
let view = { xmin: -5, xmax: 5, ymin: -4.3, ymax: 4.3 };
const HOME_VIEW = { ...view };

let placing = "star";
let placingParticle = true;
let paused = false;
let newMass = 10;
let grMode = 0;
let cursor = null;
let dragBody = null;
let dragging = false, dragStart = null;

let showProbe = true, showField = true, showStream = true, showTrace = true, showNoiseHist = true;

// ---- colored-noise (Ornstein–Uhlenbeck) bath parameters
//     dη = -(1/τ) η dt + sqrt(2D/τ) dW      (stationary variance = D)
//     dv += η dt  (the random force)   AND   dv += -(1/τ) v dt  (the paired damping)
let noiseEnabled = false;
let tau = 0.2;      // relaxation time
let D = 0.0005;     // noise strength (stationary variance of η)

const STAR_PRESET_M = 20;
const HOLE_PRESET_M = 55;
const PLANET_PRESET_M = 1.2;

// gaussian sampler (Box–Muller)
let _gaussSpare = null;
function gauss() {
  if (_gaussSpare !== null) { const s = _gaussSpare; _gaussSpare = null; return s; }
  let u = 0, v = 0, s = 0;
  do {
    u = Math.random() * 2 - 1;
    v = Math.random() * 2 - 1;
    s = u * u + v * v;
  } while (s >= 1 || s === 0);
  const mul = Math.sqrt(-2 * Math.log(s) / s);
  _gaussSpare = v * mul;
  return u * mul;
}

// ================================================================ presets
function loadSunSystem() {
  bodies = []; particles = [];
  bodies.push({ x: 0, y: 0, vx: 0, vy: 0, m: STAR_PRESET_M, type: "star" });
  const Rs = [1.1, 1.8, 2.6, 3.5];
  const ts = [0, 0.9, -1.8, 2.4];
  Rs.forEach((r, i) => {
    const v = Math.sqrt(G_CONST * STAR_PRESET_M / r);
    bodies.push({
      x: r * Math.cos(ts[i]), y: r * Math.sin(ts[i]),
      vx: -v * Math.sin(ts[i]), vy: v * Math.cos(ts[i]),
      m: PLANET_PRESET_M * (1 + 0.3 * i), type: "planet",
    });
  });
  view = { xmin: -4.1, xmax: 4.1, ymin: -3.5, ymax: 3.5 };
  dropTestParticle(2.15, 0.0);
}

function loadBinary() {
  bodies = []; particles = [];
  const m = STAR_PRESET_M * 0.75, d = 1.2;
  const v = Math.sqrt(G_CONST * m / (2 * d));
  bodies.push({ x: -d / 2, y: 0, vx: 0, vy: -v, m, type: "star" });
  bodies.push({ x: d / 2, y: 0, vx: 0, vy: v, m, type: "star" });
  view = { xmin: -5.5, xmax: 5.5, ymin: -4.7, ymax: 4.7 };
  dropTestParticle(4.0, 0, -Math.sqrt(G_CONST * 2 * m / 4.0));
}

function loadBlackHole() {
  bodies = []; particles = [];
  bodies.push({ x: 0, y: 0, vx: 0, vy: 0, m: HOLE_PRESET_M, type: "hole" });
  view = { xmin: -6, xmax: 6, ymin: -5.2, ymax: 5.2 };
  dropTestParticle(4.2, 0, -Math.sqrt(G_CONST * HOLE_PRESET_M / 4.2) * 0.72);
}

// ================================================================ physics
const _acc = { ax: 0, ay: 0 };
function accelAt(x, y, out) {
  let ax = 0, ay = 0;
  for (const b of bodies) {
    const dx = b.x - x, dy = b.y - y;
    const r2 = dx * dx + dy * dy + SOFT2;
    const r = Math.sqrt(r2);
    let a = G_CONST * b.m / (r2 * r);
    if (grMode > 0 && b.type === "hole") {
      const rs = 0.35 * (b.m / HOLE_PRESET_M);
      a *= (1 + grMode * 3 * rs / r);
    }
    ax += a * dx;
    ay += a * dy;
  }
  out.ax = ax; out.ay = ay;
  return out;
}
function accel(x, y) { return accelAt(x, y, _acc); }
function speedAt(x, y) { const a = accel(x, y); return Math.hypot(a.ax, a.ay); }
function fieldAt(x, y) { const a = accel(x, y); return { f: a.ax, g: a.ay }; }

function fluxThroughRing(cx, cy, R, samples = 480) {
  let sum = 0;
  const dL = 2 * Math.PI * R / samples;
  for (let i = 0; i < samples; i++) {
    const t = 2 * Math.PI * i / samples;
    const nx = Math.cos(t), ny = Math.sin(t);
    const F = fieldAt(cx + R * nx, cy + R * ny);
    sum += (F.f * nx + F.g * ny) * dL;
  }
  return sum;
}
function enclosedMass(cx, cy, R) {
  let M = 0;
  for (const b of bodies) if (Math.hypot(b.x - cx, b.y - cy) <= R) M += b.m;
  return M;
}
function totalMassInside(cx, cy, R) { return enclosedMass(cx, cy, R); }

// ================================================================ integrator
function bodyAccel(i, out) {
  let ax = 0, ay = 0;
  const bi = bodies[i];
  for (let j = 0; j < bodies.length; j++) {
    if (j === i) continue;
    const bj = bodies[j];
    const dx = bj.x - bi.x, dy = bj.y - bi.y;
    const r2 = dx * dx + dy * dy + SOFT2;
    const r = Math.sqrt(r2);
    let a = G_CONST * bj.m / (r2 * r);
    if (grMode > 0 && bj.type === "hole") {
      const rs = 0.35 * (bj.m / HOLE_PRESET_M);
      a *= (1 + grMode * 3 * rs / r);
    }
    ax += a * dx; ay += a * dy;
  }
  out.ax = ax; out.ay = ay;
  return out;
}

const _ba1 = { ax: 0, ay: 0 }, _ba2 = { ax: 0, ay: 0 };
function stepBodies() {
  const n = bodies.length;
  if (n === 0) return;
  for (let i = 0; i < n; i++) {
    bodyAccel(i, _ba1);
    bodies[i].vx += _ba1.ax * DT * 0.5;
    bodies[i].vy += _ba1.ay * DT * 0.5;
    bodies[i].x += bodies[i].vx * DT;
    bodies[i].y += bodies[i].vy * DT;
  }
  for (let i = n - 1; i >= 0; i--) {
    if (!bodies[i]) continue;
    bodyAccel(i, _ba2);
    bodies[i].vx += _ba2.ax * DT * 0.5;
    bodies[i].vy += _ba2.ay * DT * 0.5;
    if (!isFinite(bodies[i].x) || !isFinite(bodies[i].y) ||
        !isFinite(bodies[i].vx) || !isFinite(bodies[i].vy)) {
      bodies.splice(i, 1); continue;
    }
    const sp = Math.hypot(bodies[i].vx, bodies[i].vy);
    if (sp > 80) { bodies[i].vx *= 80 / sp; bodies[i].vy *= 80 / sp; }
  }
}

// ---- one substep of a test particle, including optional OU noise bath
function stepParticle(p) {
  // deterministic part: velocity-Verlet
  let a = accel(p.x, p.y);
  p.vx += a.ax * DT * 0.5; p.vy += a.ay * DT * 0.5;

  // OU colored noise: evolve η, then apply it as an acceleration AND
  // apply the fluctuation–dissipation paired damping -γv (γ = 1/τ).
  let etaX = 0, etaY = 0;
  if (noiseEnabled && p.noisy) {
    const gamma = 1 / tau;
    // exact OU update: η ← η e^{-γ dt} + sqrt(D (1 - e^{-2γ dt})) * N(0,1)
    const decay = Math.exp(-gamma * DT);
    const amp = Math.sqrt(D * (1 - decay * decay));
    p.etaX = p.etaX * decay + amp * gauss();
    p.etaY = p.etaY * decay + amp * gauss();
    etaX = p.etaX; etaY = p.etaY;
    // paired damping (the "flow re-fitting the perturbation"), same γ as the noise
    p.vx -= gamma * p.vx * DT;
    p.vy -= gamma * p.vy * DT;
    // the noise force itself
    p.vx += etaX * DT;
    p.vy += etaY * DT;
    // record η history for the little plot
    p.etaHist.push(p.etaX);
    if (p.etaHist.length > 220) p.etaHist.shift();
  }

  p.x += p.vx * DT; p.y += p.vy * DT;

  a = accel(p.x, p.y);
  p.vx += a.ax * DT * 0.5; p.vy += a.ay * DT * 0.5;

  if (!isFinite(p.x) || !isFinite(p.y)) { p.dead = true; return; }
  const sp = Math.hypot(p.vx, p.vy);
  if (sp > 120) { p.vx *= 120 / sp; p.vy *= 120 / sp; }

  p.trail.push([p.x, p.y]);
  if (p.trail.length > 1400) p.trail.shift();

  // ---- orbital clocks about the heaviest body
  const host = heaviestBody();
  if (host) {
    const dx = p.x - host.x, dy = p.y - host.y;
    const r = Math.hypot(dx, dy);
    const th = Math.atan2(dy, dx);
    if (p.prevTheta === undefined) { p.prevTheta = th; p.prevR = r; }
    let dth = th - p.prevTheta;
    while (dth > Math.PI) dth -= 2 * Math.PI;
    while (dth < -Math.PI) dth += 2 * Math.PI;
    p.angleTotal = (p.angleTotal || 0) + dth;
    p.prevTheta = th;
    p.phiCycles = Math.abs(p.angleTotal) / (2 * Math.PI);

    const drdt = r - p.prevR;
    if (p.lastDrdt !== undefined && Math.sign(drdt) !== Math.sign(p.lastDrdt)) {
      p.radialTurns = (p.radialTurns || 0) + 1;
    }
    p.lastDrdt = drdt;
    p.prevR = r;
    p.radialCycles = (p.radialTurns || 0) / 2;
    p.radius = r;
    if (r > p.far) p.far = r;
    if (r < p.near) p.near = r;

    // ---- escape detection: unbind from the host
    const Menc = totalMassInside(host.x, host.y, Math.max(r, 1e-6));
    const vEsc = Math.sqrt(2 * G_CONST * Math.max(Menc, 1e-9) / Math.max(r, 1e-6));
    const vNow = Math.hypot(p.vx, p.vy);
    if (!p.escaped && (r > ESCAPE_RADIUS || (vNow > vEsc && r > p.far * 0.9 && r > 2.5))) {
      p.escaped = true;
      p.escapeTime = simTime;
    }
  }
}

function stepParticles() {
  for (const p of particles) stepParticle(p);
  particles = particles.filter(p => !p.dead && Math.hypot(p.x, p.y) < 60);
}

function heaviestBody() {
  let best = null;
  for (const b of bodies) if (!best || b.m > best.m) best = b;
  return best;
}

function dropTestParticle(x, y, vyOverride, noisy) {
  const host = heaviestBody();
  let vx = 0, vy = 0;
  if (host) {
    const dx = x - host.x, dy = y - host.y;
    const r = Math.hypot(dx, dy) + 1e-9;
    const Menc = totalMassInside(host.x, host.y, r);
    const vc = Math.sqrt(G_CONST * Math.max(Menc, 1e-9) / r);
    vx = -dy / r * vc; vy = dx / r * vc;
  }
  if (vyOverride !== undefined && vyOverride !== null) vy = vyOverride;
  particles.push({
    x, y, vx, vy, trail: [[x, y]],
    near: Infinity, far: 0, radialTurns: 0, angleTotal: 0,
    noisy: !!noisy, etaX: 0, etaY: 0, etaHist: [],
    escaped: false, escapeTime: 0,
  });
}

// drop a fan of noisy copies drawn from a Gaussian around (x,y)
function dropNoiseEnsemble(x, y, n, sigma) {
  const host = heaviestBody();
  if (!host) return;
  const dx = x - host.x, dy = y - host.y;
  const r = Math.hypot(dx, dy) + 1e-9;
  const Menc = totalMassInside(host.x, host.y, r);
  const vc = Math.sqrt(G_CONST * Math.max(Menc, 1e-9) / r);
  const baseVx = -dy / r * vc, baseVy = dx / r * vc;
  for (let i = 0; i < n; i++) {
    particles.push({
      x: x + gauss() * sigma, y: y + gauss() * sigma,
      vx: baseVx + gauss() * sigma * 0.35, vy: baseVy + gauss() * sigma * 0.35,
      trail: [], near: Infinity, far: 0, radialTurns: 0, angleTotal: 0,
      noisy: true, etaX: 0, etaY: 0, etaHist: [],
      escaped: false, escapeTime: 0,
    });
  }
}

// ================================================================ drawing
function toPx(x, y) {
  return {
    sx: (x - view.xmin) / (view.xmax - view.xmin) * W,
    sy: (view.ymax - y) / (view.ymax - view.ymin) * H,
  };
}
function toWorld(sx, sy) {
  return {
    x: view.xmin + (sx / W) * (view.xmax - view.xmin),
    y: view.ymax - (sy / H) * (view.ymax - view.ymin),
  };
}

const PAL = [
  [8, 8, 20], [14, 20, 48], [26, 44, 96], [48, 84, 160],
  [92, 140, 220], [170, 208, 255], [255, 255, 255],
  [255, 236, 170], [255, 190, 90], [240, 120, 30], [170, 40, 10],
];
function lerp(a, b, t) { return a + (b - a) * t; }
function palColor(u) {
  u = Math.max(0, Math.min(1, u));
  const n = PAL.length - 1, x = u * n, i = Math.floor(x), f = x - i;
  const c0 = PAL[i], c1 = PAL[Math.min(n, i + 1)];
  return [Math.round(lerp(c0[0], c1[0], f)), Math.round(lerp(c0[1], c1[1], f)), Math.round(lerp(c0[2], c1[2], f))];
}

function bodyRadius(b) {
  if (b.type === "hole") return 7 + Math.sqrt(b.m) * 0.55;
  if (b.type === "star") return 5 + Math.sqrt(b.m) * 0.55;
  return 3.2 + Math.sqrt(b.m) * 0.7;
}
function bodyColor(b) {
  if (b.type === "hole") return "#b47aff";
  if (b.type === "star") return "#ffd257";
  return "#5ea8ff";
}

const offCanvas = document.createElement("canvas");
offCanvas.width = W; offCanvas.height = H;
const offCtx = offCanvas.getContext("2d");

function drawFieldLayer() {
  const img = offCtx.createImageData(W, H);
  const data = img.data;
  let maxA = 0;
  const N = 40;
  for (let i = 0; i <= N; i++) for (let j = 0; j <= N; j++) {
    const w = toWorld(i / N * W, j / N * H);
    const s = speedAt(w.x, w.y);
    if (isFinite(s) && s > maxA) maxA = s;
  }
  if (maxA === 0) maxA = 1;
  const lmax = Math.log(1 + maxA);
  const step = 4;
  for (let py = 0; py < H; py += step) {
    for (let px = 0; px < W; px += step) {
      const w = toWorld(px, py);
      const s = speedAt(w.x, w.y);
      const u = isFinite(s) ? Math.log(1 + s) / lmax : 0;
      const c = palColor(u * 0.85);
      for (let dy = 0; dy < step && py + dy < H; dy++) {
        for (let dx = 0; dx < step && px + dx < W; dx++) {
          const idx = ((py + dy) * W + px + dx) * 4;
          data[idx] = c[0]; data[idx + 1] = c[1]; data[idx + 2] = c[2]; data[idx + 3] = 255;
        }
      }
    }
  }
  offCtx.putImageData(img, 0, 0);
  ctx.drawImage(offCanvas, 0, 0);
}

function drawGlyphs() {
  const n = 26;
  const cell = Math.min(W / n, H / n);
  const cols = Math.ceil(W / cell), rows = Math.ceil(H / cell);
  const maxLen = cell * 0.8;
  let amax = 1e-9;
  const cells = [];
  for (let i = 0; i < cols; i++) for (let j = 0; j < rows; j++) {
    const sx = (i + 0.5) * cell, sy = (j + 0.5) * cell;
    const w = toWorld(sx, sy);
    const F = fieldAt(w.x, w.y);
    const m = Math.hypot(F.f, F.g);
    cells.push({ sx, sy, F, m });
    if (isFinite(m) && m > amax) amax = m;
  }
  for (const c of cells) {
    if (!isFinite(c.m) || c.m < 1e-7) continue;
    const ang = Math.atan2(c.F.g, c.F.f);
    const u = Math.pow(c.m / amax, 0.32);
    const L = maxLen * u;
    const ux = Math.cos(ang), uy = -Math.sin(ang);
    const x0 = c.sx - ux * L * 0.5, y0 = c.sy - uy * L * 0.5;
    const x1 = c.sx + ux * L * 0.5, y1 = c.sy + uy * L * 0.5;
    let hue = ang * 180 / Math.PI; if (hue < 0) hue += 360;
    const light = 32 + 40 * u, sat = 65 + 25 * u;
    ctx.strokeStyle = `hsla(${hue}, ${sat}%, ${light}%, 0.85)`;
    ctx.fillStyle = ctx.strokeStyle;
    ctx.lineWidth = 1.2;
    const dx = x1 - x0, dy = y1 - y0, len = Math.hypot(dx, dy);
    if (len < 2) continue;
    const vx = dx / len, vy = dy / len;
    const head = Math.min(6, 2.4 + len * 0.22);
    ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1 - vx * head * 0.7, y1 - vy * head * 0.7); ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x1 - vx * head - vy * head * 0.5, y1 - vy * head + vx * head * 0.5);
    ctx.lineTo(x1 - vx * head + vy * head * 0.5, y1 - vy * head - vx * head * 0.5);
    ctx.closePath(); ctx.fill();
  }
}

function traceStreamline(x0, y0, dir, color) {
  let x = x0, y = y0;
  const pts = [];
  for (let i = 0; i < 240; i++) {
    const a = accel(x, y);
    const m = Math.hypot(a.ax, a.ay);
    if (!isFinite(m) || m < 1e-9) break;
    const stepLen = 0.04;
    x += (a.ax / m) * stepLen * dir;
    y += (a.ay / m) * stepLen * dir;
    pts.push(toPx(x, y));
    if (x < view.xmin - 1 || x > view.xmax + 1 || y < view.ymin - 1 || y > view.ymax + 1) break;
  }
  if (pts.length < 2) return;
  ctx.strokeStyle = color; ctx.lineWidth = 1.2;
  ctx.beginPath(); ctx.moveTo(pts[0].sx, pts[0].sy);
  for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].sx, pts[i].sy);
  ctx.stroke();
}

function drawBodies() {
  for (const b of bodies) {
    const p = toPx(b.x, b.y);
    const R = bodyRadius(b);
    const col = bodyColor(b);
    if (b.type === "hole") {
      const g = ctx.createRadialGradient(p.sx, p.sy, R * 0.4, p.sx, p.sy, R * 3.2);
      g.addColorStop(0, "rgba(180,122,255,0.55)");
      g.addColorStop(1, "rgba(180,122,255,0)");
      ctx.fillStyle = g;
      ctx.beginPath(); ctx.arc(p.sx, p.sy, R * 3.2, 0, 2 * Math.PI); ctx.fill();
      ctx.fillStyle = "#0a0612";
      ctx.beginPath(); ctx.arc(p.sx, p.sy, R, 0, 2 * Math.PI); ctx.fill();
      ctx.strokeStyle = col; ctx.lineWidth = 2;
      ctx.beginPath(); ctx.arc(p.sx, p.sy, R, 0, 2 * Math.PI); ctx.stroke();
      ctx.strokeStyle = "rgba(180,122,255,0.35)"; ctx.lineWidth = 1;
      ctx.beginPath(); ctx.arc(p.sx, p.sy, R * 1.55, 0, 2 * Math.PI); ctx.stroke();
    } else {
      if (b.type === "star") {
        const g = ctx.createRadialGradient(p.sx, p.sy, R * 0.3, p.sx, p.sy, R * 3.5);
        g.addColorStop(0, "rgba(255,210,87,0.55)");
        g.addColorStop(1, "rgba(255,160,40,0)");
        ctx.fillStyle = g;
        ctx.beginPath(); ctx.arc(p.sx, p.sy, R * 3.5, 0, 2 * Math.PI); ctx.fill();
      }
      ctx.fillStyle = col;
      ctx.beginPath(); ctx.arc(p.sx, p.sy, R, 0, 2 * Math.PI); ctx.fill();
      ctx.strokeStyle = "rgba(255,255,255,0.55)"; ctx.lineWidth = 1;
      ctx.stroke();
    }
    ctx.fillStyle = "rgba(255,255,255,0.6)";
    ctx.font = "9.5px ui-monospace, monospace";
    ctx.fillText("m=" + b.m.toFixed(1), p.sx + R + 4, p.sy + 3);
  }
}

function drawParticles() {
  for (const p of particles) {
    const tr = p.trail;
    const isNoisy = p.noisy;
    if (tr.length > 1) {
      ctx.strokeStyle = isNoisy ? "rgba(180,122,255,0.60)" : "rgba(255,85,102,0.75)";
      ctx.lineWidth = 1.2;
      ctx.beginPath();
      const s0 = toPx(tr[0][0], tr[0][1]);
      ctx.moveTo(s0.sx, s0.sy);
      for (let i = 1; i < tr.length; i++) {
        const s = toPx(tr[i][0], tr[i][1]);
        ctx.lineTo(s.sx, s.sy);
      }
      ctx.stroke();
    }
    const s = toPx(p.x, p.y);
    const sp = Math.hypot(p.vx, p.vy);
    if (sp > 1e-6 && !isNoisy) {
      const ux = p.vx / sp, uy = -p.vy / sp;
      const L = 12 + 8 * Math.log(1 + sp);
      ctx.strokeStyle = "#ff8a99"; ctx.lineWidth = 1.6;
      ctx.beginPath(); ctx.moveTo(s.sx, s.sy); ctx.lineTo(s.sx + ux * L, s.sy + uy * L); ctx.stroke();
    }
    ctx.fillStyle = isNoisy ? "#b47aff" : "#ff5566";
    ctx.beginPath(); ctx.arc(s.sx, s.sy, isNoisy ? 2.4 : 3.4, 0, 2 * Math.PI); ctx.fill();
    if (!isNoisy) { ctx.strokeStyle = "#fff"; ctx.lineWidth = 1; ctx.stroke(); }

    // escape halo
    if (p.escaped) {
      ctx.strokeStyle = "rgba(255,85,102,0.8)";
      ctx.lineWidth = 1.2;
      ctx.beginPath(); ctx.arc(s.sx, s.sy, 7, 0, 2 * Math.PI); ctx.stroke();
    }
  }
}

function drawRingProbe(cx, cy, R) {
  const p = toPx(cx, cy);
  const rpx = R / (view.xmax - view.xmin) * W;

  ctx.strokeStyle = "rgba(108,204,255,0.55)";
  ctx.lineWidth = 1.4;
  ctx.setLineDash([6, 5]);
  ctx.beginPath(); ctx.arc(p.sx, p.sy, rpx, 0, 2 * Math.PI); ctx.stroke();
  ctx.setLineDash([]);

  const samples = 40;
  let fluxSum = 0;
  const dL = 2 * Math.PI * R / samples;
  let maxN = 1e-9;
  const vals = [];
  for (let i = 0; i < samples; i++) {
    const t = 2 * Math.PI * i / samples;
    const nx = Math.cos(t), ny = Math.sin(t);
    const F = fieldAt(cx + R * nx, cy + R * ny);
    const ncomp = F.f * nx + F.g * ny;
    fluxSum += ncomp * dL;
    vals.push({ nx, ny, ncomp });
    if (Math.abs(ncomp) > maxN) maxN = Math.abs(ncomp);
  }

  const Menc = enclosedMass(cx, cy, R);
  const predicted = -2 * Math.PI * G_CONST * Menc;
  const consistent = Math.abs(fluxSum - predicted) < 0.3 * Math.max(1, Math.abs(predicted));

  for (const v of vals) {
    const x = cx + R * v.nx, y = cy + R * v.ny;
    const q = toPx(x, y);
    const u = Math.abs(v.ncomp) / maxN;
    const L = 4 + 13 * u;
    const inward = v.ncomp < 0;
    const ux = inward ? -v.nx : v.nx;
    const uy = inward ? -v.ny : v.ny;
    ctx.strokeStyle = inward ? "rgba(108,204,255,0.85)" : "rgba(76,175,80,0.9)";
    ctx.fillStyle = ctx.strokeStyle;
    ctx.lineWidth = 1.3;
    ctx.beginPath();
    ctx.moveTo(q.sx, q.sy);
    ctx.lineTo(q.sx + ux * L, q.sy - uy * L);
    ctx.stroke();
    const hx = q.sx + ux * L, hy = q.sy - uy * L;
    ctx.beginPath();
    ctx.moveTo(hx, hy);
    ctx.lineTo(hx - ux * 3 - uy * 2, hy + uy * 3 - ux * 2);
    ctx.lineTo(hx - ux * 3 + uy * 2, hy + uy * 3 + ux * 2);
    ctx.closePath(); ctx.fill();
  }

  ctx.fillStyle = "#6cf";
  ctx.beginPath(); ctx.arc(p.sx, p.sy, 2.6, 0, 2 * Math.PI); ctx.fill();

  return { flux: fluxSum, Menc, predicted, consistent, R, cx, cy };
}

// ---- the η(t) strip chart
function drawNoisePlot() {
  const w = noisePlot.width, h = noisePlot.height;
  nctx.clearRect(0, 0, w, h);
  nctx.fillStyle = "#0a0a14";
  nctx.fillRect(0, 0, w, h);

  if (!showNoiseHist) return;

  // find the noisiest particle with history
  let p = null;
  for (const q of particles) if (q.etaHist && q.etaHist.length > 5) { p = q; break; }

  nctx.strokeStyle = "#1e1e2e";
  nctx.beginPath(); nctx.moveTo(0, h / 2); nctx.lineTo(w, h / 2); nctx.stroke();

  nctx.fillStyle = "#8a8aa4";
  nctx.font = "10px ui-monospace, monospace";
  nctx.fillText("η(t) — Ornstein–Uhlenbeck colored noise", 8, 13);

  if (!p) {
    nctx.fillStyle = "#55556a";
    nctx.fillText(noiseEnabled ? "enable + add a noisy particle to see the trace" : "noise bath off", 8, h / 2 - 6);
    return;
  }

  const hist = p.etaHist;
  // scale to ±3σ_stationary, σ² = D
  const lim = Math.sqrt(D) * 3 || 1e-6;
  nctx.strokeStyle = "rgba(180,122,255,0.9)";
  nctx.lineWidth = 1.3;
  nctx.beginPath();
  for (let i = 0; i < hist.length; i++) {
    const x = (i / (hist.length - 1)) * w;
    const y = h / 2 - (hist[i] / lim) * (h / 2 - 14);
    if (i === 0) nctx.moveTo(x, y); else nctx.lineTo(x, y);
  }
  nctx.stroke();

  // reference bands at ±σ
  nctx.strokeStyle = "rgba(180,122,255,0.25)";
  nctx.setLineDash([3, 4]);
  [1, -1].forEach(s => {
    const y = h / 2 - s * (Math.sqrt(D) / lim) * (h / 2 - 14);
    nctx.beginPath(); nctx.moveTo(0, y); nctx.lineTo(w, y); nctx.stroke();
  });
  nctx.setLineDash([]);

  // correlation length marker: τ in samples
  const tauSamples = Math.min(hist.length, Math.max(2, tau / DT));
  const xTau = (tauSamples / hist.length) * w;
  nctx.strokeStyle = "rgba(108,204,255,0.5)";
  nctx.beginPath(); nctx.moveTo(xTau, 14); nctx.lineTo(xTau, h); nctx.stroke();
  nctx.fillStyle = "rgba(108,204,255,0.8)";
  nctx.fillText("τ", xTau + 4, h - 6);
}

// ================================================================ render
let lastProbe = null;
let simTime = 0;

function render() {
  ctx.fillStyle = "#04040a";
  ctx.fillRect(0, 0, W, H);

  if (showField) { drawFieldLayer(); drawGlyphs(); }

  if (showStream && cursor) {
    traceStreamline(cursor.x, cursor.y, 1, "rgba(108,204,255,0.28)");
    traceStreamline(cursor.x, cursor.y, -1, "rgba(108,204,255,0.16)");
  }

  drawBodies();
  if (showTrace) drawParticles();

  if (showProbe && cursor) {
    const host = heaviestBody();
    if (host) {
      const R = Math.hypot(cursor.x - host.x, cursor.y - host.y);
      if (R > 0.15) lastProbe = drawRingProbe(host.x, host.y, R);
      else lastProbe = null;
    }
    const c = toPx(cursor.x, cursor.y);
    ctx.strokeStyle = "rgba(255,255,255,0.75)";
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(c.sx - 12, c.sy); ctx.lineTo(c.sx - 4, c.sy);
    ctx.moveTo(c.sx + 4, c.sy); ctx.lineTo(c.sx + 12, c.sy);
    ctx.moveTo(c.sx, c.sy - 12); ctx.lineTo(c.sx, c.sy - 4);
    ctx.moveTo(c.sx, c.sy + 4); ctx.lineTo(c.sx, c.sy + 12);
    ctx.stroke();
  }
}

// ================================================================ explanation
function fmt(x, d = 3) {
  if (!isFinite(x)) return "∞";
  if (Math.abs(x) < 1e-10) return "0";
  if (Math.abs(x) >= 1e4 || Math.abs(x) < 1e-3) return x.toExponential(2);
  return x.toFixed(d);
}

function regimetext() {
  const r = DT / tau;   // dt/τ
  if (r < 0.1) return { klass: "stiff", text: "stiff limit (dt ≪ τ): the flow outruns the noise — perturbations are re-absorbed before they grow. Effectively deterministic." };
  if (r > 1.0) return { klass: "soft", text: "soft limit (dt ≫ τ): each step re-draws fresh noise — you are back to white noise, and the bath injects energy every step. Orbits diffuse and escape." };
  return { klass: "mid", text: "intermediate (dt ~ τ): the noise is correlated over several steps — the regime where the deterministic flow is genuinely competing with the bath. Look for metastable orbits that survive a long time then escape." };
}

function buildExplanation() {
  let html = "";

  if (cursor) {
    const F = fieldAt(cursor.x, cursor.y);
    const mag = Math.hypot(F.f, F.g);
    html += `<h4>At the cursor (${fmt(cursor.x, 2)}, ${fmt(cursor.y, 2)})</h4>`;
    html += `<p>Acceleration <b>g = (${fmt(F.f, 3)}, ${fmt(F.g, 3)})</b>, magnitude <b>${fmt(mag, 3)}</b>.</p>`;
  }

  // ---- noise regime analysis
  if (noiseEnabled) {
    const reg = regimetext();
    html += `<h4>Colored-noise bath — which regime are you in?</h4>`;
    html += `<div class="verdict ${reg.klass === "stiff" ? "good" : reg.klass === "soft" ? "bad" : "warn"}">${reg.text}</div>`;
    html += `<p>The bath is an Ornstein–Uhlenbeck process with relaxation time <b>τ = ${fmt(tau, 3)}</b> and strength <b>D = ${fmt(D, 5)}</b> (stationary variance of η). The update is <b>exact</b>, not a naive Euler step:</p>`;
    html += `<div class="eq">η ← η·e^(−Δt/τ) + √(D(1−e^(−2Δt/τ)))·N(0,1)<br>dv ← −(1/τ)·v·Δt &nbsp;+&nbsp; η·Δt</div>`;
    html += `<p>The damping <b>γ = 1/τ = ${fmt(1 / tau, 3)}</b> is <i>not</i> optional. It is the fluctuation–dissipation partner of the noise: without it the bath only injects energy and every orbit spirals outward regardless of your other settings. With it, energy input and removal balance, and the long-run behaviour is a Kramers-type escape from the well.</p>`;
    const ratio = DT / tau;
    html += `<table>
      <tr><th>quantity</th><th>value</th><th>meaning</th></tr>
      <tr><td>τ</td><td>${fmt(tau, 3)}</td><td>memory time of the noise</td></tr>
      <tr><td>γ = 1/τ</td><td>${fmt(1 / tau, 3)}</td><td>damping rate (paired)</td></tr>
      <tr><td>Δt</td><td>${fmt(DT, 5)}</td><td>integrator step</td></tr>
      <tr><td>Δt/τ</td><td><b>${fmt(ratio, 4)}</b></td><td>the one number that sets the regime</td></tr>
      <tr><td>σ_stationary</td><td>${fmt(Math.sqrt(D), 5)}</td><td>typical kick size</td></tr>
    </table>`;
    html += `<p>Contrast the two limits deliberately: pull τ down to the minimum (fast memory) and the bath behaves like white noise — orbits smear diffusively. Push τ up (slow memory) and the same D produces gentle, trackable drift that the flow can follow. <b>Same noise strength, different physics</b> — because the flow's ability to re-fit a perturbation depends on the perturbation's memory, not just its size.</p>`;
  } else {
    html += `<h4>Colored-noise bath</h4>`;
    html += `<p style="color:var(--dim)">Tick <b>colored-noise bath (OU)</b> below the canvas to switch it on. A noisy particle is drawn in violet. Use <b>+ noise ensemble</b> to drop a fan of copies from a Gaussian cloud.</p>`;
  }

  // ---- escape statistics
  const noisyParticles = particles.filter(p => p.noisy);
  if (noisyParticles.length) {
    const escaped = noisyParticles.filter(p => p.escaped);
    html += `<h4>Escape statistics (live)</h4>`;
    html += `<p>${escaped.length} of ${noisyParticles.length} noisy particles have left the well (r > ${ESCAPE_RADIUS} or unbound). ${
      escaped.length ? "First escape at sim time t = " + fmt(Math.min(...escaped.map(p => p.escapeTime)), 2) + "." : "None yet."
    }</p>`;
    if (escaped.length) {
      const meanT = escaped.reduce((a, p) => a + p.escapeTime, 0) / escaped.length;
      html += `<p><b>Mean escape time</b> = ${fmt(meanT, 2)} over the escapees. This grows <i>exponentially</i> as D falls (a Kramers law), which is why small noise looks like stability for a very long time and then abruptly isn't.</p>`;
    }
    html += `<p style="color:var(--dim); font-size:11.5px;">Note the honest caveat: pure two-body gravity has <i>no</i> attractor and no restoring τ of its own — the damping here is a modelled bath (gas drag / tidal dissipation / radiation reaction), not gravity. This is exactly why real orbits need an extra dissipative mechanism to be stable.</p>`;
  }

  // ---- orbital clocks
  let p = null;
  for (const q of particles) if (!p || (q.trail && q.trail.length > (p.trail ? p.trail.length : 0))) p = q;
  if (p && p.phiCycles > 0.12) {
    const ratio = p.radialCycles / p.phiCycles;
    const closed = ratio > 0.97 && ratio < 1.03;
    html += `<h4>The orbit's two clocks</h4>`;
    html += `<table>
      <tr><th>quantity</th><th>value</th><th>meaning</th></tr>
      <tr><td>ω_φ</td><td>${fmt(p.phiCycles, 3)}</td><td>angle wound</td></tr>
      <tr><td>ω_r</td><td>${fmt(p.radialCycles, 3)}</td><td>radial cycles</td></tr>
      <tr><td>ω_r/ω_φ</td><td><b>${fmt(ratio, 4)}</b></td><td>${closed ? "1:1 — closed (Kepler)" : "≠1 — precessing"}</td></tr>
    </table>`;
    if (noiseEnabled && p.noisy) {
      html += `<div class="verdict ${closed ? "good" : "info"}">${closed
        ? "Despite the noise, the two clocks are still near 1:1 — the bath is too weak (or too fast) to break the degeneracy yet."
        : "The noise has pulled ω_r/ω_φ off 1:1 faster than damping can restore it — the bath is winning on this timescale."}</div>`;
    }
  }

  if (lastProbe) {
    const P = lastProbe;
    html += `<h4>Gauss's law on the ring</h4>`;
    html += `<div class="verdict ${P.consistent ? "good" : "warn"}">Φ = ${fmt(P.flux, 3)} vs −2πG·M<sub>enc</sub> = ${fmt(P.predicted, 3)} — ${P.consistent ? "consistent" : "differing (mass outside ring / softening)"}</div>`;
  }

  html += `<div class="note"><b>Model honesty.</b> The bath is an OU process with the fluctuation–dissipation damping paired to it, integrated exactly. It is a <i>modelled</i> environment (gas, tides, radiation reaction) — not gravity itself. The gravitational field is Newtonian with a softening length, plus the optional GR cartoon near black holes. No geodesics, no shadow.</div>`;
  return html;
}

function updateReadout() {
  if (lastProbe) {
    document.getElementById("s-flux").textContent = fmt(lastProbe.flux, 3);
    document.getElementById("s-menc").textContent = fmt(lastProbe.Menc, 3);
  } else {
    document.getElementById("s-flux").textContent = "—";
    document.getElementById("s-menc").textContent = "—";
  }
  let p = null;
  for (const q of particles) if (!p || (q.trail && q.trail.length > (p.trail ? p.trail.length : 0))) p = q;
  if (p && p.phiCycles > 0.12) {
    document.getElementById("s-ratio").textContent = fmt(p.radialCycles / p.phiCycles, 4);
  } else {
    document.getElementById("s-ratio").textContent = "—";
  }
  // escape stat
  const noisyParticles = particles.filter(q => q.noisy);
  const escaped = noisyParticles.filter(q => q.escaped);
  const el = document.getElementById("s-escape");
  if (noisyParticles.length === 0) { el.textContent = "safe"; el.style.color = ""; }
  else if (escaped.length === 0) { el.textContent = "0 / " + noisyParticles.length; el.style.color = "#8fdc92"; }
  else {
    const meanT = escaped.reduce((a, q) => a + q.escapeTime, 0) / escaped.length;
    el.textContent = escaped.length + " / " + noisyParticles.length + "  (t̄=" + meanT.toFixed(2) + ")";
    el.style.color = "#ff8a99";
  }
}

// ================================================================ UI helpers
function syncNoiseUI() {
  document.getElementById("tauVal").textContent = tau.toFixed(3);
  document.getElementById("dVal").textContent = D.toExponential(1).replace("e-", "e−");
  const ratio = DT / tau;
  const meter = document.getElementById("tauMeter");
  if (ratio < 0.1) { meter.textContent = "Δt/τ = " + ratio.toFixed(3) + "  stiff (flow wins)"; meter.className = "tau-meter stiff"; }
  else if (ratio > 1.0) { meter.textContent = "Δt/τ = " + ratio.toFixed(3) + "  soft (noise wins)"; meter.className = "tau-meter soft"; }
  else { meter.textContent = "Δt/τ = " + ratio.toFixed(3) + "  intermediate"; meter.className = "tau-meter mid"; }
  document.getElementById("gammaNote").textContent = "γ = 1/τ = " + (1 / tau).toFixed(3) + " , fluctuation–dissipation pairing active";
  document.getElementById("noiseBox").classList.toggle("disabled", !noiseEnabled);
}

// ================================================================ interaction
function mouseWorld(e) {
  const rect = stage.getBoundingClientRect();
  const sx = (e.clientX - rect.left) / rect.width * W;
  const sy = (e.clientY - rect.top) / rect.height * H;
  return { w: toWorld(sx, sy), sx, sy, rect };
}

stage.addEventListener("mousemove", (e) => {
  const m = mouseWorld(e);
  const w = m.w;
  if (dragBody) { dragBody.x = w.x; dragBody.y = w.y; return; }
  if (dragging) {
    const dx = (e.clientX - dragStart.x) / m.rect.width * (dragStart.view.xmax - dragStart.view.xmin);
    const dy = (e.clientY - dragStart.y) / m.rect.height * (dragStart.view.ymax - dragStart.view.ymin);
    view.xmin = dragStart.view.xmin - dx;
    view.xmax = dragStart.view.xmax - dx;
    view.ymin = dragStart.view.ymin + dy;
    view.ymax = dragStart.view.ymax + dy;
    return;
  }
  cursor = w;
  coordBadge.textContent = `(${w.x.toFixed(3)}, ${w.y.toFixed(3)})`;
  explanationEl.innerHTML = buildExplanation();
  updateReadout();
});

stage.addEventListener("mouseleave", () => { cursor = null; });

// ensemble mode flag
let placingEnsemble = false;

stage.addEventListener("mousedown", (e) => {
  const m = mouseWorld(e);
  const { w, sx, sy } = m;

  let grabbed = null;
  for (const b of bodies) {
    const p = toPx(b.x, b.y);
    if (Math.hypot(p.sx - sx, p.sy - sy) < bodyRadius(b) + 8) { grabbed = b; break; }
  }
  if (grabbed) { dragBody = grabbed; return; }

  if (placingEnsemble && bodies.length) {
    dropNoiseEnsemble(w.x, w.y, 36, 0.02 + 0.04 * Math.sqrt(D * 1e4));
    explanationEl.innerHTML = buildExplanation();
    return;
  }

  if (placingParticle) {
    dropTestParticle(w.x, w.y, null, noiseEnabled);
    explanationEl.innerHTML = buildExplanation();
  } else {
    let mm = newMass;
    if (placing === "star") mm = Math.max(4, newMass * 1.6);
    if (placing === "planet") mm = Math.max(0.4, newMass * 0.12);
    if (placing === "hole") mm = Math.max(20, newMass * 4.2);
    const b = { x: w.x, y: w.y, vx: 0, vy: 0, m: mm, type: placing };
    const host = heaviestBody();
    if (host && (host.x !== w.x || host.y !== w.y)) {
      const dx = w.x - host.x, dy = w.y - host.y, r = Math.hypot(dx, dy);
      const Menc = totalMassInside(host.x, host.y, r);
      const vc = Math.sqrt(G_CONST * Math.max(Menc, 1e-9) / Math.max(r, 0.2));
      b.vx = -dy / r * vc; b.vy = dx / r * vc;
    }
    bodies.push(b);
    explanationEl.innerHTML = buildExplanation();
  }
});

stage.addEventListener("mouseup", () => { dragBody = null; dragging = false; });
window.addEventListener("mouseup", () => { dragBody = null; dragging = false; });

stage.addEventListener("dblclick", () => { view = { ...HOME_VIEW }; });

stage.addEventListener("wheel", (e) => {
  e.preventDefault();
  const rect = stage.getBoundingClientRect();
  const pxFrac = (e.clientX - rect.left) / rect.width;
  const pyFrac = (e.clientY - rect.top) / rect.height;
  const cx = view.xmin + pxFrac * (view.xmax - view.xmin);
  const cy = view.ymax - pyFrac * (view.ymax - view.ymin);
  const factor = e.deltaY < 0 ? 0.82 : 1.22;
  const nw = (view.xmax - view.xmin) * factor;
  const nh = (view.ymax - view.ymin) * factor;
  view.xmin = cx - pxFrac * nw; view.xmax = view.xmin + nw;
  view.ymax = cy + pyFrac * nh; view.ymin = view.ymax - nh;
}, { passive: false });

stage.addEventListener("mousedown", (e) => {
  const m = mouseWorld(e);
  let overBody = false;
  for (const b of bodies) {
    const p = toPx(b.x, b.y);
    if (Math.hypot(p.sx - m.sx, p.sy - m.sy) < bodyRadius(b) + 8) { overBody = true; break; }
  }
  if (!overBody && !placingParticle && !placingEnsemble) {
    dragging = true;
    dragStart = { x: e.clientX, y: e.clientY, view: { ...view } };
  }
});

// ================================================================ tools
function selectTool(which) {
  placingParticle = (which === "particle");
  placingEnsemble = (which === "ensemble");
  if (!placingParticle && !placingEnsemble) placing = which;
  document.getElementById("btnStar").classList.toggle("on", which === "star");
  document.getElementById("btnPlanet").classList.toggle("on", which === "planet");
  document.getElementById("btnHole").classList.toggle("on", which === "hole");
  document.getElementById("btnParticle").classList.toggle("on", which === "particle");
  document.getElementById("btnEnsemble").classList.toggle("on", which === "ensemble");
  modeBadge.textContent = placingParticle ? "click to drop a test particle"
    : placingEnsemble ? "click to drop a 36-copy noise ensemble"
    : "click to place a " + which;
  modeBadge.classList.add("armed");
}
document.getElementById("btnStar").addEventListener("click", () => selectTool("star"));
document.getElementById("btnPlanet").addEventListener("click", () => selectTool("planet"));
document.getElementById("btnHole").addEventListener("click", () => selectTool("hole"));
document.getElementById("btnParticle").addEventListener("click", () => selectTool("particle"));
document.getElementById("btnEnsemble").addEventListener("click", () => selectTool("ensemble"));

document.getElementById("btnClear").addEventListener("click", () => {
  bodies = []; particles = []; lastProbe = null; simTime = 0;
  explanationEl.innerHTML = '<p style="color:var(--dim)">Cleared. Place a body to begin.</p>';
});
document.getElementById("btnPause").addEventListener("click", (e) => {
  paused = !paused;
  e.target.textContent = paused ? "Resume" : "Pause";
  e.target.classList.toggle("on", paused);
});
document.getElementById("btnReset").addEventListener("click", () => {
  particles = []; simTime = 0;
  const host = heaviestBody();
  if (host) dropTestParticle(host.x + 2.2, host.y, null, noiseEnabled);
});
document.getElementById("btnPreset").addEventListener("click", () => { loadSunSystem(); lastProbe = null; simTime = 0; });
document.getElementById("btnBinary").addEventListener("click", () => { loadBinary(); lastProbe = null; simTime = 0; });
document.getElementById("btnBH").addEventListener("click", () => { loadBlackHole(); lastProbe = null; simTime = 0; });

document.getElementById("massSlider").addEventListener("input", (e) => {
  newMass = Number(e.target.value);
  document.getElementById("massVal").textContent = e.target.value;
});
document.getElementById("grSlider").addEventListener("input", (e) => {
  grMode = Number(e.target.value);
  document.getElementById("grVal").textContent = grMode.toFixed(2);
});

// ---- colored noise controls
document.getElementById("noiseEnable").addEventListener("change", (e) => {
  noiseEnabled = e.target.checked;
  syncNoiseUI();
  explanationEl.innerHTML = buildExplanation();
  // existing noisy particles keep going; new ones will be noisy
  if (noiseEnabled) {
    // tag the most recent particle as noisy so something is visible
    const last = particles[particles.length - 1];
    if (last && !last.noisy && last.etaHist) {
      last.noisy = true;
      last.etaX = 0; last.etaY = 0;
    }
  }
});

document.getElementById("tauSlider").addEventListener("input", (e) => {
  // slider is log10(τ)
  tau = Math.pow(10, Number(e.target.value));
  syncNoiseUI();
});
document.getElementById("dSlider").addEventListener("input", (e) => {
  // slider is log10(D)
  D = Math.pow(10, Number(e.target.value));
  syncNoiseUI();
});

document.getElementById("btnProbe").addEventListener("click", (e) => { showProbe = !showProbe; e.target.classList.toggle("on", showProbe); });
document.getElementById("btnField").addEventListener("click", (e) => { showField = !showField; e.target.classList.toggle("on", showField); });
document.getElementById("btnStream").addEventListener("click", (e) => { showStream = !showStream; e.target.classList.toggle("on", showStream); });
document.getElementById("btnTrace").addEventListener("click", (e) => { showTrace = !showTrace; e.target.classList.toggle("on", showTrace); });
document.getElementById("btnNoiseHist").addEventListener("click", (e) => { showNoiseHist = !showNoiseHist; e.target.classList.toggle("on", showNoiseHist); });

// ================================================================ main loop
function loop() {
  if (!paused) {
    for (let s = 0; s < SUBS; s++) { stepBodies(); stepParticles(); simTime += DT; }
  }
  render();
  drawNoisePlot();
  if (cursor) explanationEl.innerHTML = buildExplanation();
  updateReadout();
  requestAnimationFrame(loop);
}

// ================================================================ init
loadSunSystem();
selectTool("particle");
syncNoiseUI();
requestAnimationFrame(loop);
</script>
</body>
</html>