-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstar-debug.html
More file actions
1004 lines (882 loc) · 35.6 KB
/
Copy pathstar-debug.html
File metadata and controls
1004 lines (882 loc) · 35.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Star Detection Debug Tool</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { width: 100%; height: 100%; overflow: hidden; background: #0e0e1a; color: #ccc; font-family: 'SF Mono', 'Menlo', 'Monaco', monospace; font-size: 13px; }
/* Layout */
#app { display: flex; flex-direction: column; height: 100%; }
#toolbar { display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: #161625; border-bottom: 1px solid #2a2a40; flex-shrink: 0; }
#main { display: flex; flex: 1; overflow: hidden; }
#viewport { flex: 1; position: relative; overflow: hidden; cursor: crosshair; }
#sidebar { width: 300px; background: #12121f; border-left: 1px solid #2a2a40; overflow-y: auto; flex-shrink: 0; }
#status-bar { display: flex; align-items: center; gap: 16px; padding: 6px 12px; background: #161625; border-top: 1px solid #2a2a40; font-size: 11px; color: #888; flex-shrink: 0; }
/* Toolbar */
.tb-btn { padding: 5px 12px; background: #1e1e32; border: 1px solid #3a3a55; border-radius: 4px; color: #aaa; cursor: pointer; font-size: 12px; font-family: inherit; }
.tb-btn:hover { background: #2a2a45; color: #ddd; }
.tb-btn.active { background: #3a2050; border-color: #ff6b9d; color: #ff6b9d; }
.tb-label { color: #666; font-size: 11px; margin-left: 8px; }
.tb-spacer { flex: 1; }
#export-btn { background: #1a3020; border-color: #4a8; color: #6c8; }
#export-btn:hover { background: #254030; }
/* Sidebar sections */
.section { padding: 12px; border-bottom: 1px solid #2a2a40; }
.section-title { font-size: 11px; color: #ff6b9d; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px; }
/* Sliders */
.slider-row { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
.slider-label { width: 100px; font-size: 11px; color: #888; }
.slider-row input[type="range"] { flex: 1; accent-color: #ff6b9d; }
.slider-value { width: 36px; text-align: right; color: #fff; font-size: 12px; }
/* Inspector */
.insp-row { display: flex; justify-content: space-between; margin-bottom: 4px; }
.insp-label { color: #888; }
.insp-value { color: #fff; }
.insp-swatch { display: inline-block; width: 14px; height: 14px; border-radius: 2px; vertical-align: middle; border: 1px solid #444; }
.score-bar { display: flex; align-items: center; gap: 6px; margin-bottom: 4px; }
.score-bar-label { width: 70px; font-size: 11px; color: #888; }
.score-bar-track { flex: 1; height: 6px; background: #1a1a30; border-radius: 3px; overflow: hidden; }
.score-bar-fill { height: 100%; border-radius: 3px; transition: width 0.1s; }
.score-bar-val { width: 32px; text-align: right; font-size: 11px; color: #aaa; }
.starness-result { margin-top: 8px; padding: 8px; background: #1a1a30; border-radius: 4px; text-align: center; }
.starness-big { font-size: 20px; font-weight: bold; }
/* Magnifier */
#magnifier-canvas { width: 100%; border-radius: 4px; background: #000; image-rendering: pixelated; }
/* Minimap */
#minimap-wrap { position: absolute; bottom: 12px; left: 12px; border: 1px solid #3a3a55; border-radius: 4px; overflow: hidden; background: #000; }
#minimap { display: block; }
/* Loading */
#loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; background: #0e0e1a; z-index: 100; }
#loading.hidden { display: none; }
.spinner { color: #ff6b9d; font-size: 14px; }
/* Progress bar in status */
#progress-bar { width: 100px; height: 4px; background: #1a1a30; border-radius: 2px; overflow: hidden; }
#progress-fill { height: 100%; width: 0%; background: #ff6b9d; transition: width 0.1s; }
</style>
</head>
<body>
<div id="app">
<!-- Toolbar -->
<div id="toolbar">
<button class="tb-btn active" id="btn-mask" onclick="setOverlay('mask')">Star Mask</button>
<button class="tb-btn" id="btn-heatmap" onclick="setOverlay('heatmap')">Heatmap</button>
<button class="tb-btn" id="btn-clean" onclick="setOverlay('clean')">Clean Preview</button>
<button class="tb-btn" id="btn-original" onclick="setOverlay('original')">Original</button>
<span class="tb-spacer"></span>
<span class="tb-label" id="star-count">— stars detected</span>
<button class="tb-btn" id="export-btn" onclick="exportParams()">Export JSON</button>
</div>
<!-- Main area -->
<div id="main">
<div id="viewport">
<canvas id="main-canvas"></canvas>
<div id="minimap-wrap">
<canvas id="minimap" width="200" height="133"></canvas>
</div>
<div id="loading"><span class="spinner">Loading sky-panorama.jpg...</span></div>
</div>
<!-- Sidebar -->
<div id="sidebar">
<!-- Sliders -->
<div class="section">
<div class="section-title">Detection Thresholds</div>
<div class="slider-row">
<span class="slider-label">Min Luminance</span>
<input type="range" id="sl-lum" min="0" max="100" value="75" oninput="onSlider()">
<span class="slider-value" id="sv-lum">0.75</span>
</div>
<div class="slider-row">
<span class="slider-label">Max Saturation</span>
<input type="range" id="sl-sat" min="0" max="100" value="15" oninput="onSlider()">
<span class="slider-value" id="sv-sat">0.15</span>
</div>
<div class="slider-row">
<span class="slider-label">Min Contrast</span>
<input type="range" id="sl-con" min="0" max="50" value="5" oninput="onSlider()">
<span class="slider-value" id="sv-con">0.05</span>
</div>
<div class="slider-row">
<span class="slider-label">Sample Radius</span>
<input type="range" id="sl-rad" min="1" max="20" value="4" oninput="onSlider()">
<span class="slider-value" id="sv-rad">4</span>
</div>
<div class="slider-row">
<span class="slider-label">Score Threshold</span>
<input type="range" id="sl-thresh" min="0" max="100" value="50" oninput="onSlider()">
<span class="slider-value" id="sv-thresh">0.50</span>
</div>
<div class="slider-row">
<span class="slider-label">Mask Padding</span>
<input type="range" id="sl-pad" min="0" max="15" value="0" oninput="onPadding()">
<span class="slider-value" id="sv-pad">0</span>
</div>
</div>
<!-- Magnifier -->
<div class="section">
<div class="section-title">Magnifier (31x31 @ 8x)</div>
<canvas id="magnifier-canvas" width="248" height="248"></canvas>
</div>
<!-- Pixel Inspector -->
<div class="section">
<div class="section-title">Pixel Inspector</div>
<div class="insp-row"><span class="insp-label">Position</span><span class="insp-value" id="insp-pos">—</span></div>
<div class="insp-row"><span class="insp-label">RGB</span><span class="insp-value" id="insp-rgb">—</span></div>
<div class="insp-row"><span class="insp-label">Luminance</span><span class="insp-value" id="insp-lum">—</span></div>
<div class="insp-row"><span class="insp-label">Saturation</span><span class="insp-value" id="insp-sat">—</span></div>
<div class="insp-row"><span class="insp-label">Local Contrast</span><span class="insp-value" id="insp-con">—</span></div>
</div>
<!-- Score Breakdown -->
<div class="section">
<div class="section-title">Score Breakdown</div>
<div class="score-bar">
<span class="score-bar-label">Brightness</span>
<div class="score-bar-track"><div class="score-bar-fill" id="bar-lum" style="width:0%;background:#4fc3f7;"></div></div>
<span class="score-bar-val" id="bv-lum">—</span>
</div>
<div class="score-bar">
<span class="score-bar-label">Desaturation</span>
<div class="score-bar-track"><div class="score-bar-fill" id="bar-sat" style="width:0%;background:#66bb6a;"></div></div>
<span class="score-bar-val" id="bv-sat">—</span>
</div>
<div class="score-bar">
<span class="score-bar-label">Contrast</span>
<div class="score-bar-track"><div class="score-bar-fill" id="bar-con" style="width:0%;background:#ffa726;"></div></div>
<span class="score-bar-val" id="bv-con">—</span>
</div>
<div class="starness-result">
<div style="color:#888;font-size:11px;">STARNESS</div>
<div class="starness-big" id="starness-val" style="color:#444;">—</div>
</div>
</div>
</div>
</div>
<!-- Status bar -->
<div id="status-bar">
<span id="status-zoom">Zoom: —</span>
<span id="status-cursor">Cursor: —</span>
<div id="progress-bar"><div id="progress-fill"></div></div>
<span id="status-progress"></span>
</div>
</div>
<script>
// ============================================================
// STATE
// ============================================================
const IMG_SRC = 'sky-panorama.jpg';
let imgW = 0, imgH = 0;
let pixels = null; // Uint8ClampedArray (raw RGBA)
let sourceCanvas = null; // offscreen canvas with full image
// Camera
const cam = { x: 0, y: 0, zoom: 0.25 };
let dirty = true;
// Overlay
let overlayMode = 'mask'; // 'mask' | 'heatmap' | 'clean' | 'original'
let starnessMap = null; // Uint8Array from worker (0-255)
// Drag state
let dragging = false;
let dragStartX = 0, dragStartY = 0;
let camStartX = 0, camStartY = 0;
// Hover
let hoverImgX = -1, hoverImgY = -1;
// Canvases
const mainCanvas = document.getElementById('main-canvas');
const mainCtx = mainCanvas.getContext('2d');
const minimapCanvas = document.getElementById('minimap');
const minimapCtx = minimapCanvas.getContext('2d');
const magCanvas = document.getElementById('magnifier-canvas');
const magCtx = magCanvas.getContext('2d');
// Overlay canvas (full resolution, drawn when starnessMap updates)
let overlayCanvas = null;
let overlayCtx = null;
let cleanCanvas = null;
let cleanCtx = null;
// Web Worker
let worker = null;
let workerReady = false;
let detecting = false; // true while worker is running a detect pass
let detectPending = false; // true if a new detect was requested during a run
// ============================================================
// SLIDER HELPERS
// ============================================================
function getParams() {
return {
minLum: parseInt(document.getElementById('sl-lum').value) / 100,
maxSat: parseInt(document.getElementById('sl-sat').value) / 100,
minCon: parseInt(document.getElementById('sl-con').value) / 100,
radius: parseInt(document.getElementById('sl-rad').value),
threshold: parseInt(document.getElementById('sl-thresh').value) / 100,
padding: parseInt(document.getElementById('sl-pad').value),
};
}
function updateSliderLabels() {
const p = getParams();
document.getElementById('sv-lum').textContent = p.minLum.toFixed(2);
document.getElementById('sv-sat').textContent = p.maxSat.toFixed(2);
document.getElementById('sv-con').textContent = p.minCon.toFixed(2);
document.getElementById('sv-rad').textContent = p.radius;
document.getElementById('sv-thresh').textContent = p.threshold.toFixed(2);
document.getElementById('sv-pad').textContent = p.padding;
}
let sliderTimer = null;
function onSlider() {
updateSliderLabels();
clearTimeout(sliderTimer);
sliderTimer = setTimeout(() => requestDetection(), 100);
}
// Padding doesn't need a full re-detect — just re-dilate and rebuild overlays
let lastDetectResult = null;
function onPadding() {
document.getElementById('sv-pad').textContent = document.getElementById('sl-pad').value;
if (lastDetectResult) {
applyPaddingAndBuild(lastDetectResult);
}
}
// ============================================================
// OVERLAY MODE
// ============================================================
function setOverlay(mode) {
overlayMode = mode;
document.querySelectorAll('#toolbar .tb-btn').forEach(b => b.classList.remove('active'));
document.getElementById('btn-' + (mode === 'original' ? 'original' : mode === 'mask' ? 'mask' : mode === 'heatmap' ? 'heatmap' : 'clean')).classList.add('active');
dirty = true;
renderLoop();
}
// ============================================================
// IMAGE LOADING
// ============================================================
function loadImage() {
const img = new Image();
img.onload = () => {
imgW = img.width;
imgH = img.height;
// Draw to offscreen canvas
sourceCanvas = document.createElement('canvas');
sourceCanvas.width = imgW;
sourceCanvas.height = imgH;
const sctx = sourceCanvas.getContext('2d');
sctx.drawImage(img, 0, 0);
// Get pixel data
const imageData = sctx.getImageData(0, 0, imgW, imgH);
pixels = imageData.data;
// Center camera
cam.x = imgW / 2;
cam.y = imgH / 2;
cam.zoom = Math.min(
mainCanvas.width / imgW,
mainCanvas.height / imgH
) * 0.95;
// Draw minimap
minimapCtx.drawImage(sourceCanvas, 0, 0, 200, 133);
// Prepare overlay canvases
overlayCanvas = document.createElement('canvas');
overlayCanvas.width = imgW;
overlayCanvas.height = imgH;
overlayCtx = overlayCanvas.getContext('2d');
cleanCanvas = document.createElement('canvas');
cleanCanvas.width = imgW;
cleanCanvas.height = imgH;
cleanCtx = cleanCanvas.getContext('2d');
cleanCtx.drawImage(sourceCanvas, 0, 0);
// Hide loading
document.getElementById('loading').classList.add('hidden');
// Init worker
initWorker();
// Initial render
dirty = true;
renderLoop();
};
img.onerror = () => {
document.querySelector('.spinner').textContent = 'Failed to load sky-panorama.jpg — run from localhost:8080';
};
img.src = IMG_SRC;
}
// ============================================================
// WEB WORKER (inline via Blob URL)
// ============================================================
function initWorker() {
const code = `
let W = 0, H = 0;
let lumMap = null;
let satMap = null;
let integralLum = null;
let rawPixels = null;
self.onmessage = function(e) {
if (e.data.type === 'init') {
W = e.data.width;
H = e.data.height;
rawPixels = new Uint8ClampedArray(e.data.pixels);
const N = W * H;
// Compute luminance and saturation maps
lumMap = new Float32Array(N);
satMap = new Float32Array(N);
for (let i = 0; i < N; i++) {
const idx = i * 4;
const r = rawPixels[idx] / 255;
const g = rawPixels[idx + 1] / 255;
const b = rawPixels[idx + 2] / 255;
lumMap[i] = 0.2126 * r + 0.7152 * g + 0.0722 * b;
const maxC = Math.max(r, g, b);
const minC = Math.min(r, g, b);
satMap[i] = maxC > 0 ? (maxC - minC) / maxC : 0;
}
// Compute integral image (summed-area table) of luminance
integralLum = new Float64Array(N);
for (let y = 0; y < H; y++) {
for (let x = 0; x < W; x++) {
const i = y * W + x;
integralLum[i] = lumMap[i]
+ (x > 0 ? integralLum[i - 1] : 0)
+ (y > 0 ? integralLum[i - W] : 0)
- (x > 0 && y > 0 ? integralLum[i - W - 1] : 0);
}
}
self.postMessage({ type: 'ready' });
}
if (e.data.type === 'detect') {
const { minLum, maxSat, minCon, radius, threshold } = e.data.params;
const N = W * H;
const starness = new Uint8Array(N);
// Also compute clean RGB for star pixels
const cleanR = new Uint8Array(N);
const cleanG = new Uint8Array(N);
const cleanB = new Uint8Array(N);
let starCount = 0;
const r = radius;
for (let y = 0; y < H; y++) {
// Progress every 200 rows
if (y % 200 === 0) {
self.postMessage({ type: 'progress', pct: y / H });
}
for (let x = 0; x < W; x++) {
const i = y * W + x;
const lum = lumMap[i];
const sat = satMap[i];
// Luminance score
const lumScore = smoothstep(minLum, minLum + 0.2, lum);
if (lumScore < 0.01) { starness[i] = 0; continue; }
// Saturation score
const satScore = 1.0 - smoothstep(0.0, maxSat, sat);
if (satScore < 0.01) { starness[i] = 0; continue; }
// Local contrast via integral image (box difference approximation of ring)
const outerX0 = Math.max(0, x - r);
const outerY0 = Math.max(0, y - r);
const outerX1 = Math.min(W - 1, x + r);
const outerY1 = Math.min(H - 1, y + r);
const innerR = Math.max(1, Math.floor(r * 0.3));
const innerX0 = Math.max(0, x - innerR);
const innerY0 = Math.max(0, y - innerR);
const innerX1 = Math.min(W - 1, x + innerR);
const innerY1 = Math.min(H - 1, y + innerR);
const outerSum = boxSum(outerX0, outerY0, outerX1, outerY1);
const innerSum = boxSum(innerX0, innerY0, innerX1, innerY1);
const outerArea = (outerX1 - outerX0 + 1) * (outerY1 - outerY0 + 1);
const innerArea = (innerX1 - innerX0 + 1) * (innerY1 - innerY0 + 1);
const ringArea = outerArea - innerArea;
const ringAvg = ringArea > 0 ? (outerSum - innerSum) / ringArea : lum;
const localContrast = lum - ringAvg;
const conScore = smoothstep(minCon, minCon + 0.1, localContrast);
const score = lumScore * satScore * conScore;
starness[i] = Math.round(Math.min(1, score) * 255);
if (score >= threshold) {
starCount++;
// Compute ring-average RGB for clean preview
const ringPixelCount = ringArea > 0 ? ringArea : 1;
let sumR = 0, sumG = 0, sumB = 0, cnt = 0;
for (let dy = -r; dy <= r; dy++) {
for (let dx = -r; dx <= r; dx++) {
const dist = Math.abs(dx) + Math.abs(dy);
if (dist < innerR) continue; // skip inner
const px = x + dx, py = y + dy;
if (px < 0 || px >= W || py < 0 || py >= H) continue;
const pi = (py * W + px) * 4;
sumR += rawPixels[pi];
sumG += rawPixels[pi + 1];
sumB += rawPixels[pi + 2];
cnt++;
}
}
cleanR[i] = cnt > 0 ? Math.round(sumR / cnt) : rawPixels[i * 4];
cleanG[i] = cnt > 0 ? Math.round(sumG / cnt) : rawPixels[i * 4 + 1];
cleanB[i] = cnt > 0 ? Math.round(sumB / cnt) : rawPixels[i * 4 + 2];
}
}
}
self.postMessage({
type: 'result',
starness: starness,
cleanR: cleanR,
cleanG: cleanG,
cleanB: cleanB,
starCount: starCount,
threshold: threshold,
}, [starness.buffer, cleanR.buffer, cleanG.buffer, cleanB.buffer]);
}
};
function boxSum(x0, y0, x1, y1) {
let s = integralLum[y1 * W + x1];
if (x0 > 0) s -= integralLum[y1 * W + x0 - 1];
if (y0 > 0) s -= integralLum[(y0 - 1) * W + x1];
if (x0 > 0 && y0 > 0) s += integralLum[(y0 - 1) * W + x0 - 1];
return s;
}
function smoothstep(edge0, edge1, x) {
const t = Math.max(0, Math.min(1, (x - edge0) / (edge1 - edge0)));
return t * t * (3 - 2 * t);
}
`;
const blob = new Blob([code], { type: 'application/javascript' });
worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = (e) => {
if (e.data.type === 'ready') {
workerReady = true;
document.getElementById('status-progress').textContent = 'Ready';
requestDetection();
}
if (e.data.type === 'progress') {
const pct = Math.round(e.data.pct * 100);
document.getElementById('progress-fill').style.width = pct + '%';
document.getElementById('status-progress').textContent = 'Analyzing... ' + pct + '%';
}
if (e.data.type === 'result') {
detecting = false;
// Store raw result so padding can be re-applied without re-detecting
lastDetectResult = {
starness: e.data.starness,
cleanR: e.data.cleanR,
cleanG: e.data.cleanG,
cleanB: e.data.cleanB,
starCount: e.data.starCount,
threshold: e.data.threshold,
};
document.getElementById('progress-fill').style.width = '100%';
document.getElementById('status-progress').textContent = 'Done';
applyPaddingAndBuild(lastDetectResult);
// If a slider changed while this was running, run ONE more detection
if (detectPending) {
detectPending = false;
requestDetection();
}
}
};
// Send pixel data to worker
document.getElementById('status-progress').textContent = 'Pre-computing...';
worker.postMessage({
type: 'init',
width: imgW,
height: imgH,
pixels: pixels.buffer,
});
}
function requestDetection() {
if (!workerReady) { detectPending = true; return; }
// If already running, just mark pending — don't queue another message
if (detecting) { detectPending = true; return; }
detecting = true;
document.getElementById('progress-fill').style.width = '0%';
document.getElementById('status-progress').textContent = 'Analyzing...';
worker.postMessage({ type: 'detect', params: getParams() });
}
// ============================================================
// MASK DILATION (padding)
// ============================================================
function dilateMask(starness, threshold, padding) {
// Create a binary mask: 1 = star, 0 = not
const N = imgW * imgH;
const mask = new Uint8Array(N);
for (let i = 0; i < N; i++) {
mask[i] = (starness[i] / 255) >= threshold ? 1 : 0;
}
if (padding <= 0) return mask;
// Dilate: for each star pixel, mark all pixels within `padding` distance
const dilated = new Uint8Array(N);
const pad = padding;
for (let y = 0; y < imgH; y++) {
for (let x = 0; x < imgW; x++) {
const i = y * imgW + x;
if (mask[i] === 0) continue;
// This pixel is a star — expand in all directions
const y0 = Math.max(0, y - pad);
const y1 = Math.min(imgH - 1, y + pad);
const x0 = Math.max(0, x - pad);
const x1 = Math.min(imgW - 1, x + pad);
for (let py = y0; py <= y1; py++) {
for (let px = x0; px <= x1; px++) {
// Circular dilation (not square)
const dx = px - x, dy = py - y;
if (dx * dx + dy * dy <= pad * pad) {
dilated[py * imgW + px] = 1;
}
}
}
}
}
return dilated;
}
// ============================================================
// APPLY PADDING + BUILD OVERLAYS
// ============================================================
function applyPaddingAndBuild(data) {
const { starness, threshold } = data;
const padding = parseInt(document.getElementById('sl-pad').value);
// Dilate the mask
const mask = dilateMask(starness, threshold, padding);
// Count stars after dilation
let starCount = 0;
for (let i = 0; i < mask.length; i++) {
if (mask[i]) starCount++;
}
document.getElementById('star-count').textContent = starCount + ' pixels masked';
// Update starnessMap for hover inspector
starnessMap = starness;
buildOverlays(data, mask);
dirty = true;
renderLoop();
}
// ============================================================
// BUILD OVERLAY CANVASES
// ============================================================
function buildOverlays(data, mask) {
const { starness, threshold } = data;
const N = imgW * imgH;
const sampleRadius = parseInt(document.getElementById('sl-rad').value);
// Star mask overlay
const maskData = overlayCtx.createImageData(imgW, imgH);
const md = maskData.data;
// Heatmap overlay
const heatData = new ImageData(imgW, imgH);
const hd = heatData.data;
for (let i = 0; i < N; i++) {
const s = starness[i];
const s01 = s / 255;
const idx = i * 4;
// Mask: magenta on dilated mask pixels
if (mask[i]) {
md[idx] = 255; md[idx + 1] = 0; md[idx + 2] = 200; md[idx + 3] = 120;
} else {
md[idx + 3] = 0;
}
// Heatmap: blue (0) → yellow (0.5) → white (1)
if (s > 0) {
if (s01 < 0.5) {
const t = s01 / 0.5;
hd[idx] = Math.round(t * 255);
hd[idx + 1] = Math.round(t * 255);
hd[idx + 2] = Math.round((1 - t) * 255);
hd[idx + 3] = Math.round(s01 * 200);
} else {
const t = (s01 - 0.5) / 0.5;
hd[idx] = 255;
hd[idx + 1] = 255;
hd[idx + 2] = Math.round(t * 255);
hd[idx + 3] = Math.round(s01 * 200);
}
}
}
// Store as canvases for compositing
overlayCtx.putImageData(maskData, 0, 0);
// Store heatmap on a second offscreen canvas
if (!window._heatCanvas) {
window._heatCanvas = document.createElement('canvas');
window._heatCanvas.width = imgW;
window._heatCanvas.height = imgH;
}
window._heatCanvas.getContext('2d').putImageData(heatData, 0, 0);
// Clean preview: copy source, replace masked pixels with ring-average
cleanCtx.drawImage(sourceCanvas, 0, 0);
const cleanImgData = cleanCtx.getImageData(0, 0, imgW, imgH);
const cd = cleanImgData.data;
const r = sampleRadius;
const innerR = Math.max(1, Math.floor(r * 0.3));
for (let i = 0; i < N; i++) {
if (!mask[i]) continue;
const x = i % imgW;
const y = (i - x) / imgW;
// Compute ring-average RGB from non-masked neighbors
let sumR = 0, sumG = 0, sumB = 0, cnt = 0;
const outerR = r + parseInt(document.getElementById('sl-pad').value);
for (let dy = -outerR; dy <= outerR; dy++) {
for (let dx = -outerR; dx <= outerR; dx++) {
const px = x + dx, py = y + dy;
if (px < 0 || px >= imgW || py < 0 || py >= imgH) continue;
const ni = py * imgW + px;
if (mask[ni]) continue; // skip masked pixels for cleaner estimate
sumR += pixels[ni * 4];
sumG += pixels[ni * 4 + 1];
sumB += pixels[ni * 4 + 2];
cnt++;
}
}
const idx = i * 4;
if (cnt > 0) {
cd[idx] = Math.round(sumR / cnt);
cd[idx + 1] = Math.round(sumG / cnt);
cd[idx + 2] = Math.round(sumB / cnt);
}
}
cleanCtx.putImageData(cleanImgData, 0, 0);
}
// ============================================================
// RENDERING
// ============================================================
function resizeCanvas() {
const vp = document.getElementById('viewport');
const w = vp.clientWidth;
const h = vp.clientHeight;
if (mainCanvas.width !== w || mainCanvas.height !== h) {
mainCanvas.width = w;
mainCanvas.height = h;
dirty = true;
}
}
function render() {
if (!sourceCanvas) return;
resizeCanvas();
const cw = mainCanvas.width;
const ch = mainCanvas.height;
// Compute source rect from camera
const viewW = cw / cam.zoom;
const viewH = ch / cam.zoom;
const sx = cam.x - viewW / 2;
const sy = cam.y - viewH / 2;
// Clear and draw source image
mainCtx.imageSmoothingEnabled = cam.zoom < 2;
mainCtx.fillStyle = '#0e0e1a';
mainCtx.fillRect(0, 0, cw, ch);
mainCtx.drawImage(sourceCanvas, sx, sy, viewW, viewH, 0, 0, cw, ch);
// Draw overlay
if (overlayMode === 'mask' && starnessMap) {
mainCtx.drawImage(overlayCanvas, sx, sy, viewW, viewH, 0, 0, cw, ch);
} else if (overlayMode === 'heatmap' && window._heatCanvas) {
mainCtx.drawImage(window._heatCanvas, sx, sy, viewW, viewH, 0, 0, cw, ch);
} else if (overlayMode === 'clean' && cleanCanvas) {
// Redraw clean instead of original
mainCtx.fillRect(0, 0, cw, ch);
mainCtx.drawImage(cleanCanvas, sx, sy, viewW, viewH, 0, 0, cw, ch);
}
// Draw minimap viewport rectangle
minimapCtx.drawImage(sourceCanvas, 0, 0, 200, 133);
minimapCtx.strokeStyle = '#ff6b9d';
minimapCtx.lineWidth = 1.5;
const mx = (sx / imgW) * 200;
const my = (sy / imgH) * 133;
const mw = (viewW / imgW) * 200;
const mh = (viewH / imgH) * 133;
minimapCtx.strokeRect(mx, my, mw, mh);
// Update status
document.getElementById('status-zoom').textContent = 'Zoom: ' + cam.zoom.toFixed(2) + 'x';
}
function renderLoop() {
if (dirty) {
dirty = false;
render();
}
}
// ============================================================
// HOVER INSPECTOR
// ============================================================
function screenToImage(screenX, screenY) {
const cw = mainCanvas.width;
const ch = mainCanvas.height;
const viewW = cw / cam.zoom;
const viewH = ch / cam.zoom;
const sx = cam.x - viewW / 2;
const sy = cam.y - viewH / 2;
const imgX = Math.floor(sx + (screenX / cw) * viewW);
const imgY = Math.floor(sy + (screenY / ch) * viewH);
return { x: imgX, y: imgY };
}
function updateInspector(imgX, imgY) {
if (!pixels || imgX < 0 || imgX >= imgW || imgY < 0 || imgY >= imgH) {
document.getElementById('insp-pos').textContent = '—';
document.getElementById('insp-rgb').innerHTML = '—';
document.getElementById('insp-lum').textContent = '—';
document.getElementById('insp-sat').textContent = '—';
document.getElementById('insp-con').textContent = '—';
document.getElementById('starness-val').textContent = '—';
document.getElementById('starness-val').style.color = '#444';
return;
}
const idx = (imgY * imgW + imgX) * 4;
const r = pixels[idx], g = pixels[idx + 1], b = pixels[idx + 2];
// Luminance
const lum = 0.2126 * (r / 255) + 0.7152 * (g / 255) + 0.0722 * (b / 255);
// Saturation (HSV)
const maxC = Math.max(r, g, b) / 255;
const minC = Math.min(r, g, b) / 255;
const sat = maxC > 0 ? (maxC - minC) / maxC : 0;
// Local contrast (direct ring computation for single pixel)
const params = getParams();
const rad = params.radius;
let ringSum = 0, ringCount = 0;
const innerR = Math.max(1, Math.floor(rad * 0.3));
for (let dy = -rad; dy <= rad; dy++) {
for (let dx = -rad; dx <= rad; dx++) {
if (Math.abs(dx) < innerR && Math.abs(dy) < innerR) continue;
const px = imgX + dx, py = imgY + dy;
if (px < 0 || px >= imgW || py < 0 || py >= imgH) continue;
const pi = (py * imgW + px) * 4;
ringSum += 0.2126 * (pixels[pi] / 255) + 0.7152 * (pixels[pi + 1] / 255) + 0.0722 * (pixels[pi + 2] / 255);
ringCount++;
}
}
const ringAvg = ringCount > 0 ? ringSum / ringCount : lum;
const localContrast = lum - ringAvg;
// Scores
const lumScore = smoothstep(params.minLum, params.minLum + 0.2, lum);
const satScore = 1.0 - smoothstep(0.0, params.maxSat, sat);
const conScore = smoothstep(params.minCon, params.minCon + 0.1, localContrast);
const starness = lumScore * satScore * conScore;
// Update display
document.getElementById('insp-pos').textContent = `(${imgX}, ${imgY})`;
document.getElementById('insp-rgb').innerHTML = `${r}, ${g}, ${b} <span class="insp-swatch" style="background:rgb(${r},${g},${b})"></span>`;
document.getElementById('insp-lum').textContent = lum.toFixed(3);
document.getElementById('insp-sat').textContent = sat.toFixed(3);
document.getElementById('insp-con').textContent = localContrast.toFixed(4);
// Score bars
setBar('bar-lum', 'bv-lum', lumScore);
setBar('bar-sat', 'bv-sat', satScore);
setBar('bar-con', 'bv-con', conScore);
// Starness
const sv = document.getElementById('starness-val');
sv.textContent = starness.toFixed(3);
if (starness >= params.threshold) {
sv.style.color = '#ff6b9d';
} else if (starness > 0.1) {
sv.style.color = '#ffa726';
} else {
sv.style.color = '#444';
}
// Status bar cursor
document.getElementById('status-cursor').textContent = `Cursor: (${imgX}, ${imgY})`;
// Magnifier
updateMagnifier(imgX, imgY);
}
function setBar(barId, valId, score) {
document.getElementById(barId).style.width = (score * 100) + '%';
document.getElementById(valId).textContent = score.toFixed(2);
}
function smoothstep(edge0, edge1, x) {
const t = Math.max(0, Math.min(1, (x - edge0) / (edge1 - edge0)));
return t * t * (3 - 2 * t);
}
// ============================================================
// MAGNIFIER
// ============================================================
function updateMagnifier(cx, cy) {
if (!pixels) return;
const half = 15; // 31x31 patch
const pxSize = 8; // 8x zoom
magCtx.fillStyle = '#000';
magCtx.fillRect(0, 0, 248, 248);
for (let dy = -half; dy <= half; dy++) {
for (let dx = -half; dx <= half; dx++) {
const px = cx + dx;
const py = cy + dy;
if (px >= 0 && px < imgW && py >= 0 && py < imgH) {
const idx = (py * imgW + px) * 4;
magCtx.fillStyle = `rgb(${pixels[idx]},${pixels[idx + 1]},${pixels[idx + 2]})`;
} else {
magCtx.fillStyle = '#111';
}
magCtx.fillRect((dx + half) * pxSize, (dy + half) * pxSize, pxSize, pxSize);
}
}
// Crosshair on center pixel
const cx2 = half * pxSize;
const cy2 = half * pxSize;
magCtx.strokeStyle = 'rgba(255, 107, 157, 0.8)';
magCtx.lineWidth = 1;
magCtx.strokeRect(cx2, cy2, pxSize, pxSize);
}
// ============================================================
// EXPORT
// ============================================================
function exportParams() {
const p = getParams();
const json = JSON.stringify({
minLuminance: p.minLum,
maxSaturation: p.maxSat,
minLocalContrast: p.minCon,
sampleRadius: p.radius,
scoreThreshold: p.threshold,
maskPadding: p.padding,
}, null, 2);
navigator.clipboard.writeText(json).then(() => {
const btn = document.getElementById('export-btn');
btn.textContent = 'Copied!';
setTimeout(() => { btn.textContent = 'Export JSON'; }, 1500);
});
console.log('Star Detection Params:', json);
}
// ============================================================
// INPUT HANDLERS
// ============================================================
// Pan
mainCanvas.addEventListener('pointerdown', (e) => {
dragging = true;
dragStartX = e.clientX;
dragStartY = e.clientY;
camStartX = cam.x;
camStartY = cam.y;
mainCanvas.style.cursor = 'grabbing';
});
window.addEventListener('pointermove', (e) => {
// Get canvas-relative position for hover
const rect = mainCanvas.getBoundingClientRect();
const sx = e.clientX - rect.left;
const sy = e.clientY - rect.top;
if (dragging) {
const dx = (e.clientX - dragStartX) / cam.zoom;
const dy = (e.clientY - dragStartY) / cam.zoom;
cam.x = camStartX - dx;
cam.y = camStartY - dy;
dirty = true;
renderLoop();
}
// Hover inspector (always update)
if (sx >= 0 && sx < mainCanvas.width && sy >= 0 && sy < mainCanvas.height) {
const img = screenToImage(sx, sy);
hoverImgX = img.x;
hoverImgY = img.y;
updateInspector(img.x, img.y);
}
});
window.addEventListener('pointerup', () => {
dragging = false;
mainCanvas.style.cursor = 'crosshair';
});
// Zoom (scroll wheel, centered on cursor)
mainCanvas.addEventListener('wheel', (e) => {
e.preventDefault();
const rect = mainCanvas.getBoundingClientRect();
const sx = e.clientX - rect.left;
const sy = e.clientY - rect.top;
// Image position under cursor before zoom
const before = screenToImage(sx, sy);
// Adjust zoom
const factor = e.deltaY > 0 ? 0.85 : 1.18;
cam.zoom = Math.max(0.05, Math.min(8, cam.zoom * factor));
// Image position under cursor after zoom
const after = screenToImage(sx, sy);
// Adjust camera so the same image point stays under the cursor
cam.x += before.x - after.x;
cam.y += before.y - after.y;
dirty = true;
renderLoop();
}, { passive: false });
// Resize
window.addEventListener('resize', () => {
dirty = true;
renderLoop();
});
// ============================================================
// INIT
// ============================================================
resizeCanvas();
updateSliderLabels();