-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
870 lines (783 loc) · 51.3 KB
/
index.html
File metadata and controls
870 lines (783 loc) · 51.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spatial Hashing Masterclass | Trent Sterling</title>
<!-- Open Graph / Social Media -->
<meta property="og:title" content="Spatial Hashing Masterclass | Trent Sterling">
<meta property="og:description" content="A visual and technical deep-dive into high-performance spatial partitioning for Unity. From O(N²) to million-particle performance.">
<meta property="og:image" content="https://github.com/TrentSterling/spatialhash/raw/master/spatialhash_preview.png">
<meta property="og:url" content="http://tront.xyz/spatialhash/">
<meta name="twitter:card" content="summary_large_image">
<meta name="theme-color" content="#FFD700">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet" />
<style>
:root {
/* OLED Gold (Default) */
--bg: #000000;
--surface: #0a0a0a;
--surface-hover: #141414;
--text: #ffffff;
--text-dim: #a3a3a3;
--accent: #FFD700;
--accent-muted: #9a6700;
--accent-bg: rgba(255, 215, 0, 0.1);
--border: #1f1f1f;
--grid: #111111;
--nav-bg: rgba(0, 0, 0, 0.8);
}
[data-theme="cyber-neon"] {
--bg: #050505;
--surface: #0f0f1a;
--text: #ffffff;
--text-dim: #8888aa;
--accent: #ff00ff;
--accent-muted: #aa00aa;
--accent-bg: rgba(255, 0, 255, 0.1);
--border: #2a1a3a;
--grid: #1a1a2a;
--nav-bg: rgba(5, 5, 5, 0.8);
}
[data-theme="pastel-dream"] {
--bg: #fdf6ff;
--surface: #f5f0ff;
--text: #2d1b4d;
--text-dim: #6b5b8b;
--accent: #d946ef;
--accent-muted: #a21caf;
--accent-bg: rgba(217, 70, 239, 0.05);
--border: #c084fc;
--grid: #e9d5ff;
--nav-bg: rgba(253, 246, 255, 0.8);
}
[data-theme="matrix"] {
--bg: #000000;
--surface: #050505;
--text: #00ff41;
--text-dim: #008f11;
--accent: #00ff41;
--accent-muted: #003b00;
--accent-bg: rgba(0, 255, 65, 0.05);
--border: #003b00;
--grid: #001a00;
--nav-bg: rgba(0, 0, 0, 0.8);
}
[data-theme="paper-light"] {
--bg: #ffffff;
--surface: #f3f4f6;
--text: #111111;
--text-dim: #4b5563;
--accent: #2563eb;
--accent-muted: #1d4ed8;
--accent-bg: rgba(37, 99, 235, 0.05);
--border: #9ca3af;
--grid: #d1d5db;
--nav-bg: rgba(255, 255, 255, 0.8);
}
[data-theme="deep-slate"] {
--bg: #0f172a;
--surface: #1e293b;
--text: #f8fafc;
--text-dim: #94a3b8;
--accent: #38bdf8;
--accent-muted: #0ea5e9;
--accent-bg: rgba(56, 189, 248, 0.1);
--border: #334155;
--grid: #1e293b;
--nav-bg: rgba(15, 23, 42, 0.8);
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Plus Jakarta Sans', sans-serif; line-height: 1.6; color: var(--text); background: var(--bg); max-width: 1000px; margin: 0 auto; padding: 4rem 1.5rem; -webkit-font-smoothing: antialiased; transition: all 0.3s ease; scroll-behavior: smooth; }
/* Links */
a { color: var(--accent); text-decoration: none; font-weight: 600; transition: color 0.2s; }
a:hover { color: var(--text); opacity: 0.8; }
/* Theme Switcher */
.theme-switcher { display: flex; gap: 0.4rem; align-items: center; background: var(--surface); padding: 0.4rem; border-radius: 99px; border: 1px solid var(--border); }
.theme-btn { width: 18px; height: 18px; border-radius: 50%; border: 2px solid transparent; cursor: pointer; transition: all 0.2s; position: relative; }
.theme-btn:hover { transform: scale(1.2); }
.theme-btn.active { border-color: var(--text); box-shadow: 0 0 10px var(--accent); }
nav { display: flex; justify-content: space-between; align-items: center; gap: 2rem; margin-bottom: 4rem; font-size: 0.9rem; font-weight: 600; border-bottom: 1px solid var(--border); padding-bottom: 1.5rem; position: sticky; top: 0; background: var(--nav-bg); backdrop-filter: blur(12px); z-index: 100; transition: all 0.3s; }
.nav-links { display: flex; gap: 2rem; }
nav a { color: var(--text-dim); }
nav a:hover { color: var(--accent); }
h1 { font-size: 4rem; font-weight: 800; letter-spacing: -0.04em; line-height: 1.1; margin-bottom: 1rem; color: var(--accent); transition: color 0.3s; }
h2 { font-size: 2.5rem; font-weight: 700; margin: 5rem 0 1.5rem; border-left: 6px solid var(--accent); padding-left: 1.5rem; letter-spacing: -0.02em; transition: all 0.3s; color: var(--text); }
h3 { font-size: 1.6rem; font-weight: 600; margin: 3rem 0 1.25rem; color: var(--accent-muted); transition: color 0.3s; }
p { margin-bottom: 1.5rem; font-size: 1.2rem; color: var(--text-dim); transition: color 0.3s; }
strong { color: var(--text); font-weight: 700; }
.subtitle { font-size: 1.6rem; color: var(--text-dim); margin-bottom: 3rem; font-weight: 400; max-width: 800px; }
.meta { display: flex; align-items: center; gap: 1.5rem; color: var(--text-dim); font-size: 0.9rem; margin-bottom: 4rem; }
.meta img { width: 48px; height: 42px; border-radius: 12px; border: 1px solid var(--accent); transition: border-color 0.3s; }
code { font-family: 'JetBrains Mono', monospace; font-size: 0.95em; background: var(--surface); color: var(--accent); padding: 0.2em 0.4em; border-radius: 4px; transition: all 0.3s; }
pre { background: var(--surface) !important; padding: 2.5rem; border-radius: 16px; border: 1px solid var(--border); margin: 2.5rem 0; overflow-x: auto; position: relative; transition: all 0.3s; }
pre::after { content: 'C#'; position: absolute; top: 0.75rem; right: 1.25rem; font-size: 0.75rem; color: var(--accent-muted); font-family: 'JetBrains Mono'; font-weight: 700; }
pre code { background: none !important; padding: 0 !important; font-size: 0.95em !important; color: var(--text) !important; }
/* Prism override for high contrast on all backgrounds */
.token.comment, .token.prolog, .token.doctype, .token.cdata { color: var(--text-dim); font-style: italic; }
.token.punctuation { color: var(--text); opacity: 0.7; }
.token.namespace { opacity: .7; }
.token.property, .token.tag, .token.boolean, .token.number, .token.constant, .token.symbol, .token.deleted { color: var(--accent); }
.token.selector, .token.attr-name, .token.string, .token.char, .token.builtin, .token.inserted { color: var(--accent-muted); }
.token.operator, .token.entity, .token.url, .language-css .token.string, .style .token.string { color: var(--text); }
.token.atrule, .token.attr-value, .token.keyword { color: var(--accent); font-weight: bold; }
.token.function, .token.class-name { color: var(--text); font-weight: 600; text-decoration: underline decoration-thickness: 1px; text-underline-offset: 3px; text-decoration-color: var(--accent-bg); }
.token.regex, .token.important, .token.variable { color: var(--accent); }
/* Chapter Navigation Bar */
.chapter-nav {
position: fixed; bottom: 2rem; left: 50%; transform: translateX(-50%);
z-index: 50; background: var(--surface); backdrop-filter: blur(16px);
padding: 1rem 2rem; border: 1px solid var(--border);
display: flex; align-items: center; gap: 2rem;
box-shadow: 0 20px 50px rgba(0,0,0,0.5); border-radius: 99px;
transition: all 0.3s;
}
.chapter-nav a { font-size: 0.75rem; font-weight: 800; letter-spacing: 0.15em; color: var(--text-dim); transition: all 0.2s; }
.chapter-nav a:hover { color: var(--accent); transform: translateY(-1px); }
/* Canvas Styles */
.visualizer-container { background: var(--surface); border: 1px solid var(--border); border-radius: 28px; padding: 2rem; margin: 4rem 0; text-align: center; transition: all 0.3s; box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
canvas { background: var(--bg); border-radius: 16px; border: 1px solid var(--border); cursor: crosshair; max-width: 100%; display: block; margin: 0 auto; transition: background 0.3s, border-color 0.3s; }
.vis-controls { margin-top: 1.5rem; color: var(--text-dim); font-size: 0.9rem; display: flex; justify-content: space-between; align-items: center; padding: 0 1.5rem; font-family: 'JetBrains Mono'; }
.math-box { background: var(--accent-bg); border: 1px solid var(--border); padding: 2.5rem; border-radius: 20px; text-align: center; margin: 4rem 0; transition: all 0.3s; }
.formula { font-family: 'JetBrains Mono', monospace; font-size: 1.6rem; color: var(--accent); transition: color 0.3s; font-weight: 700; }
.feature-grid { display: grid; grid-template-cols: 1fr 1fr; gap: 2rem; margin: 4rem 0; }
.feature { background: var(--surface); border: 1px solid var(--border); padding: 2.5rem; border-radius: 20px; transition: all 0.3s; }
.feature h4 { color: var(--accent); margin-bottom: 0.75rem; font-size: 1.25rem; transition: color 0.3s; font-weight: 800; }
blockquote { background: var(--accent-bg); border-radius: 16px; padding: 2.5rem; margin: 4rem 0; border-left: 6px solid var(--accent); transition: all 0.3s; }
blockquote p { color: var(--text); font-style: italic; margin-bottom: 0; font-size: 1.4rem; font-weight: 500; }
.learning-step { background: var(--surface); border: 1px solid var(--border); border-radius: 28px; padding: 3rem; margin-bottom: 3rem; transition: all 0.3s; }
.step-label { font-size: 0.8rem; font-weight: 900; color: var(--accent); letter-spacing: 0.3em; text-transform: uppercase; margin-bottom: 0.75rem; transition: color 0.3s; display: block; }
header { padding-top: 4rem; padding-bottom: 2rem; border-bottom: 1px solid var(--border); }
.part-header { text-align: center; margin: 6rem 0 4rem; padding-top: 4rem; border-top: 1px solid var(--border); }
.part-title { font-size: 4.5rem; font-weight: 900; letter-spacing: -0.05em; margin-bottom: 1rem; color: var(--text); line-height: 1; }
footer { margin-top: 12rem; padding: 6rem 0; border-top: 1px solid var(--border); text-align: center; background: var(--surface); transition: all 0.3s; }
.footer-links { display: flex; justify-content: center; gap: 3rem; margin-top: 2rem; }
.footer-links a { color: var(--text-dim); text-decoration: none; font-size: 1rem; transition: color 0.2s; font-weight: 700; }
.footer-links a:hover { color: var(--accent); }
@media (max-width: 768px) {
h1 { font-size: 2.5rem; }
.part-title { font-size: 3rem; }
.feature-grid { grid-template-cols: 1fr; }
body { padding-top: 2rem; }
.chapter-nav { width: 90%; gap: 1rem; padding: 0.75rem 1rem; }
.chapter-nav a { font-size: 0.6rem; }
}
</style>
</head>
<body data-theme="deep-slate">
<nav>
<div class="nav-links">
<a href="https://tront.xyz">Home</a>
<a href="https://blog.tront.xyz">Blog</a>
<a href="https://github.com/TrentSterling/spatialhash">GitHub</a>
<a href="https://discord.gg/0hyoWZyM6y7kkFCN">Discord</a>
</div>
<div class="theme-switcher">
<div class="theme-btn" style="background: #FFD700;" onclick="setTheme('gold', this)" title="OLED Gold"></div>
<div class="theme-btn" style="background: #ff00ff;" onclick="setTheme('cyber-neon', this)" title="Cyber Neon"></div>
<div class="theme-btn" style="background: #ff7eb9;" onclick="setTheme('pastel-dream', this)" title="Pastel Dream"></div>
<div class="theme-btn" style="background: #00ff41;" onclick="setTheme('matrix', this)" title="Matrix"></div>
<div class="theme-btn" style="background: #0066cc;" onclick="setTheme('paper-light', this)" title="Paper Light"></div>
<div class="theme-btn active" style="background: #38bdf8;" onclick="setTheme('deep-slate', this)" title="Deep Slate"></div>
</div>
</nav>
<!-- Chapter Navigation -->
<div class="chapter-nav">
<a href="#part1">PART 1: CORE</a>
<span style="color: var(--border)">|</span>
<a href="#part2">PART 2: MEMORY</a>
<span style="color: var(--border)">|</span>
<a href="#part3">PART 3: PRO</a>
<span style="color: var(--border)">|</span>
<a href="#part4">PART 4: EXTREME</a>
<span style="color: var(--border)">|</span>
<a href="#part5">PART 5: GAME</a>
<span style="color: var(--border)">|</span>
<a href="#toolkit">PART 6: TOOLKIT</a>
</div>
<header>
<h1>Spatial Hashing <br/>Masterclass.</h1>
<p class="subtitle">Architecting O(1) performance for Unity games. A deep dive from brute-force chaos to million-particle optimization.</p>
<div class="meta">
<img src="https://github.com/TrentSterling.png" alt="Trent Sterling">
<span>By <strong>Trent Sterling</strong></span>
<span>•</span>
<span>Feb 14, 2026</span>
<span>•</span>
<span style="color: var(--accent); font-weight: 800;">High-Performance Technical Series</span>
</div>
<div style="display: flex; gap: 1rem; margin-top: 2rem; justify-content: center;">
<a href="#part1" class="bg-accent text-bg px-8 py-4 rounded-2xl font-black tracking-widest text-xs hover:scale-105 transition-all shadow-lg shadow-accent/20">START LEARNING</a>
<a href="#toolkit" class="border border-border bg-surface text-text px-8 py-4 rounded-2xl font-black tracking-widest text-xs hover:bg-surface-hover transition-all">DOWNLOAD API</a>
</div>
</header>
<!-- PART 1: THE CORE CONCEPT -->
<div id="part1">
<div class="part-header">
<span class="step-label">PART ONE</span>
<h2 class="part-title">The Core Concept</h2>
<p style="max-width: 600px; margin: 1rem auto; color: var(--text-dim);">Understanding the geometry of optimization.</p>
</div>
<section id="step0">
<div class="step-label">Step 0: The Web of Death</div>
<h2 style="color: var(--text);">The Brute Force Nightmare</h2>
<p>In a standard, naive collision or proximity system, every object checks every other object. This is <strong>O(N²)</strong> complexity. At small scales, it's fine. At game-scale, it's a death sentence.</p>
<div class="visualizer-container">
<div style="margin-bottom: 1.5rem; display: flex; align-items: center; justify-content: center; gap: 2rem;">
<button onclick="window.setWebMode('brute')" id="btnBrute" class="bg-red-900/20 border border-red-500/50 text-red-500 px-6 py-2 rounded-full text-xs font-black tracking-widest">BRUTE FORCE</button>
<button onclick="window.setWebMode('hash')" id="btnHash" class="bg-gray-900 border border-gray-800 text-gray-500 px-6 py-2 rounded-full text-xs font-black tracking-widest transition-all">SPATIAL HASH</button>
</div>
<canvas id="visWeb" width="800" height="400"></canvas>
<div class="vis-controls">
<span>Active Checks: <strong id="webChecks" style="color:#ff4444">1,770</strong></span>
<span id="webComplexity" style="color:#ff4444; font-weight: 800;">O(N²) COMPLEXITY</span>
</div>
</div>
<p>Toggle the <strong>Spatial Hash</strong> mode above. Watch the lines collapse. By only checking objects in the same "neighborhood," we reduce the workload from thousands of checks to a handful of clustered tests.</p>
</section>
<section id="step1">
<div class="step-label">Step 1: The O(N²) Trap</div>
<h2 style="color: var(--text);">Visualization of Proximity</h2>
<p>Imagine 1,000 bullets and 100 enemies. A brute-force system doesn't care if a bullet is 1,000 meters away; it still runs the distance math. <strong>Spatial Hashing</strong> filters out the irrelevant noise before the math even starts.</p>
<div class="visualizer-container">
<canvas id="vis1" width="800" height="400"></canvas>
<div class="vis-controls">
<span>Point Cloud: 150 Units</span>
<span>Narrow-Phase Filter: <strong style="color:var(--accent)">ACTIVE</strong></span>
</div>
</div>
</section>
<section id="step2">
<div class="step-label">Step 2: Spatial Partitioning</div>
<h2 style="color: var(--text);">The Grid Strategy</h2>
<p>By dividing the world into a fixed grid of "buckets," we can map any 3D coordinate to a specific bucket in constant time. This is the foundation of almost every modern physics engine.</p>
<div class="math-box">
<div class="formula">Cell = floor(Position / CellSize)</div>
</div>
<div class="visualizer-container">
<div style="margin-bottom: 1.5rem; display: flex; align-items: center; justify-content: center; gap: 1.5rem;">
<label for="cellSize2" style="font-size: 0.8rem; font-weight: 900; color: var(--accent); letter-spacing: 0.1em;">GRID SCALE:</label>
<input type="range" id="cellSize2" min="20" max="200" value="60" style="width: 200px; accent-color: var(--accent);">
<span id="cellSizeVal2" style="font-family: 'JetBrains Mono'; color: var(--accent); font-weight: 700;">60</span>
</div>
<canvas id="vis2" width="800" height="400"></canvas>
<div class="vis-controls">
<span>AABBs: 150</span>
<span>Hash Lookups: <strong id="checkCount2">0</strong></span>
<span style="color: var(--accent); font-weight: 800;">Optimization: <strong id="savings2">0%</strong></span>
</div>
</div>
<p>Tuning the <strong>Cell Size</strong> is critical. If cells are too small, objects span many buckets. If they are too large, we check too many irrelevant objects. The goal is to maximize the <strong>Optimization %</strong> shown above.</p>
</section>
</div>
<!-- PART 2: MEMORY & EFFICIENCY -->
<div id="part2">
<div class="part-header">
<span class="step-label">PART TWO</span>
<h2 class="part-title">Memory & Efficiency</h2>
<p style="max-width: 600px; margin: 1rem auto; color: var(--text-dim);">Solving the Garbage Collection nightmare in Unity.</p>
</div>
<section id="step3">
<div class="step-label">Step 3: Zero-GC Patterns</div>
<h2 style="color: var(--text);">Bucket Pooling</h2>
<p>In C#, calling <code>new List<T>()</code> in an Update loop creates "Garbage." When Unity's Garbage Collector runs to clean this up, your game stutters. We solve this by <strong>recycling memory</strong>.</p>
<div class="learning-step">
<h3 style="color: var(--text);">The Lifecycle of a Pooled Bucket</h3>
<ol style="margin: 1.5rem 2rem; color: var(--text-dim); list-style-type: decimal;">
<li style="margin-bottom:0.75rem"><strong>Request:</strong> When an object enters a new cell, we grab a list from a <code>Stack<List<T>></code>.</li>
<li style="margin-bottom:0.75rem"><strong>Recycle:</strong> When a cell becomes empty, we <code>Clear()</code> the list and push it back onto the stack.</li>
<li style="margin-bottom:0.75rem"><strong>Result:</strong> Zero allocations. Smooth frames.</li>
</ol>
</div>
<pre><code class="language-csharp">// The internal pooling logic
private Stack<List<T>> _pool = new();
private List<T> GetNewList() {
return _pool.Count > 0 ? _pool.Pop() : new List<T>();
}
private void RecycleList(List<T> list) {
list.Clear(); // Critical: keep the capacity, dump the items
_pool.Push(list);
}</code></pre>
</section>
<section id="density">
<div class="step-label">Visualizer: Bucket Density</div>
<h2 style="color: var(--text);">The Density Heatmap</h2>
<p>Watch how the hash populates buckets in real-time. The intensity of the color represents how many entities are fighting for attention in that specific memory address.</p>
<div class="visualizer-container">
<canvas id="visDensity" width="800" height="400"></canvas>
<div class="vis-controls">
<span>Entities: 200</span>
<span>Max Bucket Depth: <strong id="maxDepth" style="color:var(--accent)">0</strong></span>
</div>
</div>
</section>
</div>
<!-- PART 3: PROFESSIONAL GRADE -->
<div id="part3">
<div class="part-header">
<span class="step-label">PART THREE</span>
<h2 class="part-title">Professional Grade</h2>
<p style="max-width: 600px; margin: 1rem auto; color: var(--text-dim);">Data-Oriented Design and Cache Locality.</p>
</div>
<section id="step4">
<div class="step-label">Step 4: The Müller Pattern</div>
<h2 style="color: var(--text);">Flattened Arrays & Prefix Sums</h2>
<p>For the ultimate performance (as seen in <a href="https://matthias-research.github.io/pages/tenMinutePhysics/11-hashing.pdf" target="_blank">Matthias Müller's Ten Minute Physics</a>), we ditch Dictionaries entirely. We move to <strong>Flat Arrays</strong>.</p>
<div class="feature-grid">
<div class="feature">
<h4>1. Count Phase</h4>
<p>Iterate all objects once to count how many fall into each cell. No allocations, just integer increments.</p>
</div>
<div class="feature">
<h4>2. Prefix Sum Phase</h4>
<p>Calculate starting offsets for every cell. This creates a "Map" of contiguous memory for your objects.</p>
</div>
</div>
<div class="learning-step">
<h3 style="margin-top:0; color: var(--text);">Why this wins? Cache Locality.</h3>
<p>When you use <code>List<T></code>, your data is scattered across RAM. The CPU has to "jump" around to find it. When you use <strong>Spatial Sorting</strong>, your data is lined up perfectly. The CPU pre-fetches the data before you even ask for them.</p>
</div>
<pre><code class="language-csharp">// Contiguous memory structure
NativeArray<int> cellStart; // Offsets into the object array
NativeArray<int> sortedObjects; // Objects sorted by their CellID
// Reading a cell is now a single, contiguous memory sweep:
int start = cellStart[cellID];
int end = cellStart[cellID + 1];
for (int i = start; i < end; i++) {
Process(sortedObjects[i]); // Ultra-fast!
}</code></pre>
</section>
</div>
<!-- PART 4: UNITY EXTREME -->
<div id="part4">
<div class="part-header">
<span class="step-label">PART FOUR</span>
<h2 class="part-title">Unity Extreme</h2>
<p style="max-width: 600px; margin: 1rem auto; color: var(--text-dim);">Burst, Jobs, and Parallel Power.</p>
</div>
<section>
<div class="step-label">Parallel Architecture</div>
<h2 style="color: var(--text);">Burst & Job System</h2>
<p>Spatial hashing is <strong>embarrassingly parallel</strong>. By using Unity's <code>NativeMultiHashMap</code> and the <strong>Burst Compiler</strong>, you can move these checks off the main thread and into high-speed C++ level machine code.</p>
<div class="feature-grid">
<div class="feature">
<h4>Parallel Writing</h4>
<p>Use <code>NativeMultiHashMap.ParallelWriter</code> to populate the grid across all CPU cores simultaneously.</p>
</div>
<div class="feature">
<h4>Burst Query Kernels</h4>
<p>The compiler optimizes the spatial math into SIMD instructions, checking multiple objects per CPU cycle.</p>
</div>
</div>
<pre><code class="language-csharp">[BurstCompile]
struct SpatialQueryJob : IJobParallelFor {
[ReadOnly] public NativeMultiHashMap<int, EntityData> hash;
public void Execute(int index) {
// Run proximity checks at 100x speed
}
}</code></pre>
</section>
</div>
<!-- PART 5: THE ARENA -->
<div id="part5">
<div class="part-header">
<span class="step-label">PART FIVE</span>
<h2 class="part-title">The Arena</h2>
<p style="max-width: 600px; margin: 1rem auto; color: var(--text-dim);">Pixel Pickup: A real-time stress test.</p>
</div>
<div class="visualizer-container" style="background: var(--bg); padding: 0; overflow: hidden; position: relative; border-color: var(--accent); border-width: 2px;">
<canvas id="gameCanvas" width="800" height="600" style="cursor: none;"></canvas>
<!-- Game UI Overlays -->
<div style="position: absolute; top: 30px; left: 30px; text-align: left; font-family: 'JetBrains Mono'; pointer-events: none;">
<div style="color: var(--accent); font-size: 1.5rem; font-weight: 900; letter-spacing: -0.05em;">PIXELS PICKED: <span id="gameScore">0</span></div>
<div style="color: var(--text-dim); font-size: 0.8rem; margin-top: 8px; font-weight: 700;">TOTAL PIXELS: <span id="pixelCount" style="color: var(--text);">0</span></div>
<div style="color: var(--text-dim); font-size: 0.8rem; margin-top: 4px; font-weight: 700;">AVG PER BUCKET: <span id="avgBucket" style="color: var(--text);">0</span></div>
<div style="color: var(--text-dim); font-size: 0.8rem; margin-top: 4px; font-weight: 700;">SPATIAL HASH: <span id="gameStats" style="color: var(--text);">ACTIVE (O(N))</span></div>
</div>
<div id="gameOverlay" style="position: absolute; inset: 0; background: rgba(0,0,0,0.9); display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; cursor: default; backdrop-filter: blur(10px);">
<div style="padding: 4rem; border: 1px solid var(--border); border-radius: 40px; background: var(--surface);">
<h3 style="color: var(--accent); font-size: 3rem; margin-bottom: 1rem; font-weight: 900; letter-spacing: -0.05em;">PIXEL PICKUP</h3>
<p style="margin-bottom: 3rem; font-size: 1.1rem; color: var(--text-dim);">The Final Exam. Move mouse to steer ship.<br/>Watch the grid flash as the hash calculates collisions.</p>
<button onclick="startGame()" style="background: var(--accent); color: black; border: none; padding: 1.25rem 3.5rem; border-radius: 16px; font-weight: 900; cursor: pointer; transition: all 0.2s; font-size: 1.2rem; letter-spacing: 0.1em;">START ENGINE</button>
</div>
</div>
</div>
<div class="learning-step" style="margin-top: 4rem;">
<h3 style="color: var(--text);">Tutorial Review:</h3>
<p>Every floating pixel and enemy in the arena above is registered into a custom Spatial Hash. The ship queries its local cells to attract pixels (Magnet) and bullets query their cells to destroy enemies. The result is a chaotic experience running at a solid 60fps.</p>
</div>
</div>
<!-- PART 6: THE TOOLKIT -->
<div id="toolkit">
<div class="part-header">
<span class="step-label">PART SIX</span>
<h2 class="part-title">The Toolkit</h2>
<p style="max-width: 600px; margin: 1rem auto; color: var(--text-dim);">Ready-to-use API and modules for your Unity projects.</p>
</div>
<div class="feature-grid">
<div class="feature">
<div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 1rem;">
<h4>SpatialHash.cs</h4>
<span class="badge" style="font-size: 0.6rem; background: var(--accent); color: var(--bg); padding: 2px 8px; border-radius: 4px; font-weight: 900;">CORE API</span>
</div>
<p style="font-size: 0.95rem; margin-bottom: 1.5rem;">The generic, non-allocating 3D hash engine. Support for AABBs, Sphere queries, and Bucket Pooling.</p>
<a href="https://github.com/TrentSterling/spatialhash/blob/master/spatialhash/SpatialHash.cs" target="_blank" class="text-accent font-black tracking-widest text-xs">VIEW SOURCE →</a>
</div>
<div class="feature">
<h4>NetworkAOI.cs</h4>
<p style="font-size: 0.95rem; margin-bottom: 1.5rem;">A plug-and-play module for <strong>PurrNet</strong>, FishNet, and Mirror. Optimized Area of Interest management.</p>
<a href="https://github.com/TrentSterling/spatialhash/blob/master/spatialhash/NetworkAOIManager.cs" target="_blank" class="text-accent font-black tracking-widest text-xs">VIEW SOURCE →</a>
</div>
<div class="feature">
<h4>RoomManager.cs</h4>
<p style="font-size: 0.95rem; margin-bottom: 1.5rem;">The logic behind <strong>CellGen</strong>. Handle portal-based visibility and room-to-room state synchronization.</p>
<a href="https://github.com/TrentSterling/spatialhash/blob/master/spatialhash/RoomManager.cs" target="_blank" class="text-accent font-black tracking-widest text-xs">VIEW SOURCE →</a>
</div>
<div class="feature">
<h4>Samples Package</h4>
<p style="font-size: 0.95rem; margin-bottom: 1.5rem;">Complete Unity samples including the Collision, Pathfinding, and World Streaming demos from this tutorial.</p>
<a href="https://github.com/TrentSterling/spatialhash/tree/master/spatialhash/Examples" target="_blank" class="text-accent font-black tracking-widest text-xs">BROWSE SAMPLES →</a>
</div>
</div>
<div class="learning-step" style="text-align: center;">
<h3 style="color: var(--text); margin-top: 0;">Clone the Repository</h3>
<p>Get the entire Masterclass project, including the visualizers and the game arena code.</p>
<pre style="display: inline-block; text-align: left; padding: 1.5rem 3rem;"><code class="language-bash">git clone https://github.com/TrentSterling/spatialhash.git</code></pre>
</div>
</div>
<!-- PAYOFF -->
<section id="payoff">
<div class="step-label">Summary</div>
<h2 style="color: var(--text);">Real-World Power</h2>
<div class="feature-grid">
<div class="feature">
<h4>Netcode AOI</h4>
<p>Perfect for <strong>PurrNet</strong>. Synchronize only the entities in a player's spatial "bubble." Save 90% of your network bandwidth.</p>
</div>
<div class="feature">
<h4>Room Sync</h4>
<p>Solve Mikkel's "Room Connectivity" problem. Instantly find "Which room am I in?" and propagate state through connected portals in $O(1)$.</p>
</div>
</div>
</section>
<footer>
<p>© 2026 Trent Sterling | spatialhash masterclass</p>
<div class="footer-links">
<a href="https://discord.gg/0hyoWZyM6y7kkFCN">Discord</a>
<a href="https://github.com/TrentSterling">GitHub</a>
<a href="https://twitter.com/Trent_Sterling">Twitter</a>
<a href="https://blog.tront.xyz">Blog</a>
</div>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-csharp.min.js"></script>
<script>
// --- Shared State & Themes ---
window.currentAccent = '#FFD700';
window.currentBg = '#000000';
window.currentText = '#ffffff';
window.isLight = false;
function setTheme(theme, btn) {
document.body.setAttribute('data-theme', theme);
localStorage.setItem('spatialhash-theme', theme);
document.querySelectorAll('.theme-btn').forEach(b => b.classList.remove('active'));
if (btn) {
btn.classList.add('active');
} else {
const activeBtn = document.querySelector(`.theme-btn[title="${theme}"], .theme-btn[onclick*="'${theme}'"]`);
if (activeBtn) activeBtn.classList.add('active');
}
const style = getComputedStyle(document.body);
window.currentAccent = style.getPropertyValue('--accent').trim();
window.currentBg = style.getPropertyValue('--bg').trim();
window.currentText = style.getPropertyValue('--text').trim();
window.currentGrid = style.getPropertyValue('--grid').trim();
window.isLight = (theme === 'paper-light' || theme === 'pastel-dream');
}
// Load saved theme
window.addEventListener('DOMContentLoaded', () => {
const savedTheme = localStorage.getItem('spatialhash-theme') || 'deep-slate';
setTheme(savedTheme, null);
});
// --- Visualizer 0: The Web ---
const vWeb = document.getElementById('visWeb');
const ctxWeb = vWeb.getContext('2d');
const webDots = Array.from({length: 60}, () => ({
x: Math.random() * vWeb.width,
y: Math.random() * vWeb.height,
vx: (Math.random() - 0.5) * 0.5,
vy: (Math.random() - 0.5) * 0.5
}));
let webMode = 'brute';
window.setWebMode = (mode) => {
webMode = mode;
const bB = document.getElementById('btnBrute');
const bH = document.getElementById('btnHash');
if(mode === 'brute') {
bB.className = "bg-red-900/20 border border-red-500/50 text-red-500 px-6 py-2 rounded-full text-xs font-black tracking-widest";
bH.className = "bg-gray-900 border border-gray-800 text-gray-500 px-6 py-2 rounded-full text-xs font-black tracking-widest";
document.getElementById('webComplexity').innerText = "O(N²) COMPLEXITY";
document.getElementById('webComplexity').style.color = "#ff4444";
document.getElementById('webChecks').style.color = "#ff4444";
} else {
bH.className = "bg-green-900/20 border border-green-500/50 text-green-500 px-6 py-2 rounded-full text-xs font-black tracking-widest";
bB.className = "bg-gray-900 border border-gray-800 text-gray-500 px-6 py-2 rounded-full text-xs font-black tracking-widest";
document.getElementById('webComplexity').innerText = "O(N) OPTIMIZED";
document.getElementById('webComplexity').style.color = window.currentAccent;
document.getElementById('webChecks').style.color = window.currentAccent;
}
};
function drawWeb() {
ctxWeb.fillStyle = window.currentBg;
ctxWeb.fillRect(0,0,vWeb.width,vWeb.height);
const wCellSize = 80;
let checks = 0;
webDots.forEach(d => {
d.x += d.vx; d.y += d.vy;
if(d.x < 0 || d.x > vWeb.width) d.vx *= -1;
if(d.y < 0 || d.y > vWeb.height) d.vy *= -1;
});
const alphaLine = window.isLight ? '44' : '1A';
for(let i=0; i<webDots.length; i++) {
for(let j=i+1; j<webDots.length; j++) {
const d1 = webDots[i]; const d2 = webDots[j];
let shouldCheck = true;
if(webMode === 'hash') {
const g1X = Math.floor(d1.x / wCellSize); const g1Y = Math.floor(d1.y / wCellSize);
const g2X = Math.floor(d2.x / wCellSize); const g2Y = Math.floor(d2.y / wCellSize);
shouldCheck = Math.abs(g1X - g2X) <= 1 && Math.abs(g1Y - g2Y) <= 1;
}
if(shouldCheck) {
checks++;
ctxWeb.strokeStyle = webMode === 'brute' ? (window.isLight ? 'rgba(255,0,0,0.2)' : 'rgba(255,68,68,0.1)') : window.currentAccent + alphaLine;
ctxWeb.beginPath(); ctxWeb.moveTo(d1.x, d1.y); ctxWeb.lineTo(d2.x, d2.y); ctxWeb.stroke();
}
}
}
webDots.forEach(d => {
ctxWeb.beginPath(); ctxWeb.arc(d.x, d.y, 2.5, 0, Math.PI*2);
ctxWeb.fillStyle = webMode === 'brute' ? '#ff4444' : window.currentAccent;
ctxWeb.fill();
});
document.getElementById('webChecks').innerText = checks.toLocaleString();
requestAnimationFrame(drawWeb);
}
drawWeb();
// --- Visualizer 1: Brute Force Sphere ---
const v1 = document.getElementById('vis1');
const ctx1 = v1.getContext('2d');
const dots = Array.from({length: 150}, () => ({x: Math.random() * v1.width, y: Math.random() * v1.height}));
let mouse1 = {x: 400, y: 200};
v1.addEventListener('mousemove', e => { const r = v1.getBoundingClientRect(); mouse1 = {x: e.clientX - r.left, y: e.clientY - r.top}; });
function draw1() {
ctx1.fillStyle = window.currentBg; ctx1.fillRect(0,0,v1.width,v1.height);
const lineAlpha = window.isLight ? '33' : '11';
dots.forEach(d => {
ctx1.beginPath(); ctx1.arc(d.x, d.y, 2, 0, Math.PI*2);
ctx1.fillStyle = window.isLight ? '#888' : '#333'; ctx1.fill();
ctx1.strokeStyle = window.currentGrid;
ctx1.beginPath(); ctx1.moveTo(mouse1.x, mouse1.y); ctx1.lineTo(d.x, d.y); ctx1.stroke();
});
ctx1.fillStyle = '#ff4444'; ctx1.fillRect(mouse1.x-4, mouse1.y-4, 8, 8);
requestAnimationFrame(draw1);
}
draw1();
// --- Visualizer 2: Spatial Hash (AABBs) ---
const v2 = document.getElementById('vis2');
const ctx2 = v2.getContext('2d');
const slider2 = document.getElementById('cellSize2');
const display2 = document.getElementById('cellSizeVal2');
const aabbs = Array.from({length: 150}, () => ({
x: Math.random() * v2.width, y: Math.random() * v2.height,
w: 10 + Math.random()*20, h: 10 + Math.random()*20
}));
let mouse2 = {x: 400, y: 200};
let cSize2 = 60;
v2.addEventListener('mousemove', e => { const r = v2.getBoundingClientRect(); mouse2 = {x: e.clientX - r.left, y: e.clientY - r.top}; });
slider2.addEventListener('input', e => { cSize2 = parseInt(e.target.value); display2.innerText = cSize2; });
function draw2() {
ctx2.fillStyle = window.currentBg; ctx2.fillRect(0,0,v2.width,v2.height);
const radius = 100; const gX = Math.floor(mouse2.x / cSize2); const gY = Math.floor(mouse2.y / cSize2); const range = Math.ceil(radius / cSize2);
ctx2.strokeStyle = window.currentGrid; ctx2.lineWidth = 1;
for(let x=0; x<=v2.width; x+=cSize2) { ctx2.beginPath(); ctx2.moveTo(x,0); ctx2.lineTo(x,v2.height); ctx2.stroke(); }
for(let y=0; y<=v2.height; y+=cSize2) { ctx2.beginPath(); ctx2.moveTo(0,y); ctx2.lineTo(v2.width,y); ctx2.stroke(); }
ctx2.fillStyle = window.currentAccent + '22';
for(let x=gX-range; x<=gX+range; x++) for(let y=gY-range; y<=gY+range; y++) ctx2.fillRect(x*cSize2, y*cSize2, cSize2, cSize2);
let checks = 0;
aabbs.forEach(obj => {
const minX = Math.floor(obj.x / cSize2); const maxX = Math.floor((obj.x + obj.w) / cSize2);
const minY = Math.floor(obj.y / cSize2); const maxY = Math.floor((obj.y + obj.h) / cSize2);
const active = maxX >= gX-range && minX <= gX+range && maxY >= gY-range && minY <= gY+range;
if(active) checks++;
ctx2.strokeStyle = active ? window.currentAccent : (window.isLight ? '#ccc' : '#222'); ctx2.lineWidth = active ? 2 : 1;
ctx2.strokeRect(obj.x, obj.y, obj.w, obj.h);
if(active) { ctx2.fillStyle = window.currentAccent + '44'; ctx2.fillRect(obj.x, obj.y, obj.w, obj.h); }
});
ctx2.strokeStyle = window.currentAccent; ctx2.setLineDash([5,5]); ctx2.beginPath(); ctx2.arc(mouse2.x, mouse2.y, radius, 0, Math.PI*2); ctx2.stroke(); ctx2.setLineDash([]);
ctx2.fillStyle = '#ff4444'; ctx2.fillRect(mouse2.x-6, mouse2.y-6, 12, 12);
document.getElementById('checkCount2').innerText = checks;
document.getElementById('savings2').innerText = Math.round((1 - checks/150)*100) + '%';
requestAnimationFrame(draw2);
}
draw2();
// --- Visualizer: Density Map ---
const vDen = document.getElementById('visDensity');
const ctxDen = vDen.getContext('2d');
const denDots = Array.from({length: 200}, () => ({
x: Math.random() * vDen.width, y: Math.random() * vDen.height,
vx: (Math.random()-0.5) * 2, vy: (Math.random()-0.5) * 2
}));
function drawDensity() {
ctxDen.fillStyle = window.currentBg; ctxDen.fillRect(0,0,vDen.width,vDen.height);
const dSize = 50; const density = {};
denDots.forEach(d => {
d.x += d.vx; d.y += d.vy;
if(d.x < 0 || d.x > vDen.width) d.vx *= -1;
if(d.y < 0 || d.y > vDen.height) d.vy *= -1;
const k = `${Math.floor(d.x/dSize)},${Math.floor(d.y/dSize)}`;
density[k] = (density[k] || 0) + 1;
});
let maxD = 0;
for(let x=0; x<vDen.width; x+=dSize) {
for(let y=0; y<vDen.height; y+=dSize) {
const count = density[`${x/dSize},${y/dSize}`] || 0;
maxD = Math.max(maxD, count);
if(count > 0) {
ctxDen.fillStyle = window.currentAccent + Math.min(255, count * (window.isLight ? 40 : 20)).toString(16).padStart(2, '0');
ctxDen.fillRect(x, y, dSize, dSize);
ctxDen.fillStyle = window.isLight ? '#000' : window.currentAccent; ctxDen.font = 'bold 12px JetBrains Mono';
ctxDen.fillText(count, x+5, y+15);
}
ctxDen.strokeStyle = window.currentGrid; ctxDen.strokeRect(x,y,dSize,dSize);
}
}
denDots.forEach(d => { ctxDen.fillStyle = window.isLight ? '#000' : '#fff'; ctxDen.fillRect(d.x-1, d.y-1, 2, 2); });
document.getElementById('maxDepth').innerText = maxD;
requestAnimationFrame(drawDensity);
}
drawDensity();
// --- PART 5: PIXEL PICKUP GAME ---
const gCanvas = document.getElementById('gameCanvas');
const gCtx = gCanvas.getContext('2d');
let gameRunning = false; let score = 0;
class GameHash {
constructor(size) { this.size = size; this.grid = new Map(); this.activeCells = new Map(); }
clear() { this.grid.clear(); this.activeCells.clear(); }
insert(obj) {
const k = `${Math.floor(obj.x/this.size)},${Math.floor(obj.y/this.size)}`;
if(!this.grid.has(k)) this.grid.set(k, []);
this.grid.get(k).push(obj);
}
query(x, y, rad, results, type = 'default') {
const gX = Math.floor(x/this.size); const gY = Math.floor(y/this.size); const r = Math.ceil(rad/this.size);
for(let ix=gX-r; ix<=gX+r; ix++) for(let iy=gY-r; iy<=gY+r; iy++) {
const key = `${ix},${iy}`;
if (!this.activeCells.has(key) || type === 'combat') this.activeCells.set(key, type);
const cell = this.grid.get(key);
if(cell) for(let i=0; i<cell.length; i++) {
const dX = cell[i].x - x; const dY = cell[i].y - y;
if(dX*dX + dY*dY <= rad*rad) results.push(cell[i]);
}
}
}
}
const spatialHash = new GameHash(40); const player = { x: 400, y: 300, r: 15, mag: 140 };
const bullets = []; const enemies = []; const pixels = []; let frame = 0;
window.startGame = () => { document.getElementById('gameOverlay').style.display = 'none'; gameRunning = true; loop(); };
function loop() {
if(!gameRunning) return; frame++;
spatialHash.clear(); enemies.forEach(e => spatialHash.insert(e)); pixels.forEach(p => spatialHash.insert(p));
if(frame % 6 === 0) {
const targets = []; spatialHash.query(player.x, player.y, 500, targets, 'targeting');
let nearest = null; let minDist = Infinity;
targets.forEach(t => { if(enemies.includes(t)) { const d = Math.sqrt((t.x-player.x)**2+(t.y-player.y)**2); if(d<minDist){minDist=d; nearest=t;} } });
if(nearest) {
const dx = nearest.x - player.x; const dy = nearest.y - player.y; const dist = Math.sqrt(dx*dx+dy*dy);
bullets.push({ x: player.x, y: player.y, vx: (dx/dist)*10, vy: (dy/dist)*10, r: 5 });
}
}
if(frame % 15 === 0 && enemies.length < 50) {
const side = Math.floor(Math.random()*4); let ex, ey;
if(side === 0) { ex = Math.random()*800; ey = -20; } else if(side === 1) { ex = 820; ey = Math.random()*600; }
else if(side === 2) { ex = Math.random()*800; ey = 620; } else { ex = -20; ey = Math.random()*600; }
enemies.push({ x: ex, y: ey, hp: 1, r: 12 });
}
for(let i=bullets.length-1; i>=0; i--) {
bullets[i].x += bullets[i].vx; bullets[i].y += bullets[i].vy;
if(bullets[i].y<-50||bullets[i].y>650||bullets[i].x<-50||bullets[i].x>850) bullets.splice(i, 1);
}
enemies.forEach(e => {
const dx = player.x-e.x; const dy = player.y-e.y; const dist = Math.sqrt(dx*dx+dy*dy);
e.x += (dx/dist)*2.2; e.y += (dy/dist)*2.2;
});
bullets.forEach(b => {
const hits = []; spatialHash.query(b.x, b.y, b.r + 20, hits, 'combat');
hits.forEach(h => {
if(enemies.includes(h)) {
for(let k=0; k<25; k++) {
if (pixels.length < 5000) {
pixels.push({
x: h.x, y: h.y,
vx: (Math.random()-0.5)*8, vy: (Math.random()-0.5)*8,
active: false, color: `hsl(${Math.random()*360}, 70%, 60%)`,
life: 1000 // Lifetime counter
});
}
}
enemies.splice(enemies.indexOf(h), 1);
}
});
});
const pulled = []; spatialHash.query(player.x, player.y, player.mag, pulled, 'magnet');
pulled.forEach(p => {
if(pixels.includes(p)) {
p.active = true; const dx = player.x-p.x; const dy = player.y-p.y; const dist = Math.sqrt(dx*dx+dy*dy);
p.vx += (dx/dist)*1.2; p.vy += (dy/dist)*1.2;
if(dist<20) { pixels.splice(pixels.indexOf(p), 1); score++; document.getElementById('gameScore').innerText = score; }
}
});
// Move and Despawn Pixels
for (let i = pixels.length - 1; i >= 0; i--) {
const p = pixels[i];
p.x += p.vx; p.y += p.vy;
p.vx *= 0.92; p.vy *= 0.92;
p.life--;
if (p.life <= 0) pixels.splice(i, 1);
}
gCtx.fillStyle = window.currentBg; gCtx.fillRect(0,0,800,600);
gCtx.strokeStyle = window.currentGrid;
for(let x=0; x<800; x+=40) { gCtx.beginPath(); gCtx.moveTo(x,0); gCtx.lineTo(x,600); gCtx.stroke(); }
for(let y=0; y<600; y+=40) { gCtx.beginPath(); gCtx.moveTo(0,y); gCtx.lineTo(800,y); gCtx.stroke(); }
spatialHash.activeCells.forEach((type, key) => {
const [cx, cy] = key.split(',').map(Number);
let color = window.currentAccent;
if (type === 'combat') color = '#ff4444';
else if (type === 'targeting') color = '#00f2ff';
gCtx.fillStyle = color + (window.isLight ? '33' : '15');
gCtx.fillRect(cx*spatialHash.size, cy*spatialHash.size, spatialHash.size, spatialHash.size);
gCtx.strokeStyle = color + (window.isLight ? '66' : '44');
gCtx.strokeRect(cx*spatialHash.size, cy*spatialHash.size, spatialHash.size, spatialHash.size);
});
pixels.forEach(p => {
if(p.active) { gCtx.fillStyle = `hsl(${(frame*15)%360}, 100%, 70%)`; gCtx.shadowBlur = window.isLight ? 0 : 8; gCtx.shadowColor = gCtx.fillStyle; }
else { gCtx.fillStyle = p.color || (window.isLight ? '#aaa' : '#333'); gCtx.shadowBlur = 0; }
gCtx.fillRect(p.x-1.5, p.y-1.5, 3, 3);
});
gCtx.shadowBlur = 0;
enemies.forEach(e => { gCtx.strokeStyle = '#ff4444'; gCtx.lineWidth = 2; gCtx.strokeRect(e.x-10, e.y-10, 20, 20); });
bullets.forEach(b => { gCtx.fillStyle = window.currentAccent; gCtx.shadowBlur = window.isLight ? 0 : 10; gCtx.shadowColor = window.currentAccent; gCtx.beginPath(); gCtx.arc(b.x, b.y, b.r, 0, Math.PI*2); gCtx.fill(); });
gCtx.shadowBlur = 0;
gCtx.strokeStyle = window.currentAccent; gCtx.setLineDash([5, 5]); gCtx.beginPath(); gCtx.arc(player.x, player.y, player.mag, 0, Math.PI*2); gCtx.stroke(); gCtx.setLineDash([]);
gCtx.fillStyle = '#ff4444'; gCtx.shadowBlur = window.isLight ? 0 : 20; gCtx.shadowColor = '#ff4444'; gCtx.fillRect(player.x-10, player.y-10, 20, 20); gCtx.shadowBlur = 0;
document.getElementById('pixelCount').innerText = pixels.length.toLocaleString();
const bucketCount = spatialHash.grid.size;
const totalInHash = enemies.length + pixels.length;
const avg = bucketCount > 0 ? (totalInHash / bucketCount).toFixed(1) : 0;
document.getElementById('avgBucket').innerText = avg;
requestAnimationFrame(loop);
}
gCanvas.addEventListener('mousemove', e => { const r = gCanvas.getBoundingClientRect(); player.x = e.clientX - r.left; player.y = e.clientY - r.top; });
</script>
</body>
</html>