-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1689 lines (1395 loc) · 49.7 KB
/
main.js
File metadata and controls
1689 lines (1395 loc) · 49.7 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
// main.js
import { buildColorLabels } from './colors.js';
import { contentsToStacksTopBottom, stacksToContentsTopBottom, solveBfs, applyMove } from './solver.js';
// --- Defaults (UI is intentionally minimal) ---
const DEFAULT_CV_VER = '4.9.0';
const DEFAULT_DBSCAN_EPS = 16.0;
const DEFAULT_MAX_STATES = 200000;
const DEFAULT_USE_TESSERACT = true;
const elFile = document.getElementById('file');
const btnAnalyze = document.getElementById('btnAnalyze');
const btnSolve = document.getElementById('btnSolve');
const statusLine = document.getElementById('statusLine');
const legend = document.getElementById('legend');
const legendTitle = document.getElementById('legendTitle');
const boardDetectedEl = document.getElementById('boardDetected');
const boardFinalEl = document.getElementById('boardFinal');
const solverTitleEl = document.getElementById('solverTitle');
const solverMetaEl = document.getElementById('solverMeta');
const movesEl = document.getElementById('moves');
// Manual box controls (bottle + rock)
const btnEditBottles = document.getElementById('btnEditBottles');
const btnEditRocks = document.getElementById('btnEditRocks');
const btnResetBoxes = document.getElementById('btnResetBoxes');
const btnClearRock = document.getElementById('btnClearRock');
const boxHintEl = document.getElementById('boxHint');
const rockLegendEl = document.getElementById('rockLegend');
const canvas = document.getElementById('canvas');
const overlay = document.getElementById('overlay');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
const octx = overlay.getContext('2d');
let imageBitmap = null;
let lastImageData = null; // ImageData on base canvas
let parseResult = null; // result from vision worker, later augmented with OCR
let colorLabels = null;
let visionWorker = null;
let visionWorkerCvVer = null;
let isAnalyzing = false;
let analyzeRequestId = 0;
let activeAnalyzeRequestId = 0;
let lastDebug = null;
// Legend selection + merge UI
let legendSelectedId = null;
// --- Manual bottle + rock boxes (6 fixed positions) ---
const BOX_STORAGE_KEY = 'ws_manual_boxes_v1';
// Absolute (image-space) boxes in pixels.
let manualBoxes = {
bottles: null, // Array<{x,y,w,h}> length 6
rocks: null, // Array<null|{x,y,w,h}> length 6
};
let editBoxes = {
active: false,
mode: null, // 'bottles' | 'rocks'
selected: null, // { type: 'bottle'|'rock', index: number }
action: null, // 'move' | 'resize'
handle: null, // 'nw'|'ne'|'se'|'sw'
startX: 0,
startY: 0,
startBox: null,
};
const canvasWrapEl = document.querySelector('.canvasWrap');
function resetAnalysisLogs() {
// UI intentionally hides debug logs; keep this as a no-op hook.
}
function pushAnalysisLog(line) {
if (isAnalyzing && statusLine) statusLine.textContent = line;
}
function setStatus(msg) {
if (statusLine) statusLine.textContent = msg;
}
function ensureVisionWorker(cvVer) {
if (visionWorker && visionWorkerCvVer === cvVer) return visionWorker;
// If we already have a worker (different cv version or previously crashed),
// tear it down so we can start clean.
if (visionWorker) {
try { visionWorker.terminate(); } catch (_) {}
visionWorker = null;
}
visionWorkerCvVer = cvVer;
visionWorker = new Worker('./vision.worker.js');
const hardReset = (statusMsg) => {
try { visionWorker?.terminate(); } catch (_) {}
visionWorker = null;
visionWorkerCvVer = null;
isAnalyzing = false;
btnAnalyze.disabled = false;
btnSolve.disabled = true;
setStatus(statusMsg);
};
// If the worker throws (e.g., importScripts fails, CORS blocked, syntax error),
// it will NOT send us a postMessage. It will land here.
visionWorker.onerror = (err) => {
console.error('[vision worker error event]', err);
hardReset(`Vision worker crashed: ${err?.message || err}`);
};
visionWorker.onmessageerror = (err) => {
console.error('[vision worker message error]', err);
hardReset('Vision worker message error (structured clone failed).');
};
visionWorker.onmessage = (e) => {
const data = e.data || {};
const { type, requestId } = data;
// Ignore stale messages (e.g., from a previous analysis run that finished late).
if (typeof requestId === 'number' && requestId !== activeAnalyzeRequestId) return;
if (type === 'log') {
console.log('[vision]', data.message);
pushAnalysisLog(String(data.message || ''));
return;
}
if (type === 'error') {
console.error(data.error);
setStatus(`Vision worker error: ${data.error}`);
isAnalyzing = false;
// allow retry without reloading the image
btnAnalyze.disabled = false;
btnSolve.disabled = true;
return;
}
if (type === 'result') {
onVisionResult(data.result, data.debug);
return;
}
};
return visionWorker;
}
function clearOverlay() {
octx.clearRect(0, 0, overlay.width, overlay.height);
}
function drawOverlay(debug) {
clearOverlay();
if (!debug) return;
// Make the overlay visually obvious by default.
octx.lineWidth = 4;
// bottle boxes
for (const b of debug.bottles) {
const { x, y, w, h, idx, rock } = b;
octx.strokeStyle = rock ? 'rgba(255, 200, 0, 0.95)' : 'rgba(0, 255, 0, 0.9)';
octx.strokeRect(x, y, w, h);
octx.fillStyle = 'rgba(0,0,0,0.55)';
octx.fillRect(x, Math.max(0, y - 20), 78, 20);
octx.fillStyle = 'rgba(255,255,255,0.95)';
octx.font = '14px ui-monospace, monospace';
octx.fillText(`${idx + 1}${rock ? ' R' : ''}`, x + 6, Math.max(14, y - 6));
}
// rock boxes (detected rock piles)
if (debug.rockBoxes && debug.rockBoxes.length) {
octx.save();
octx.strokeStyle = 'rgba(255, 200, 0, 0.95)';
if (typeof octx.setLineDash === 'function') octx.setLineDash([6, 3]);
for (const rb of debug.rockBoxes) {
if (!rb) continue;
const { x, y, w, h, idx } = rb;
octx.strokeRect(x, y, w, h);
// label
octx.fillStyle = 'rgba(0,0,0,0.55)';
octx.fillRect(x, Math.min(overlay.height - 20, y + h + 2), 78, 20);
octx.fillStyle = 'rgba(255,255,255,0.95)';
octx.font = '14px ui-monospace, monospace';
octx.fillText(`ROCK${typeof idx === 'number' ? ` b${idx + 1}` : ''}`, x + 6, Math.min(overlay.height - 6, y + h + 16));
}
octx.restore();
}
// slot sample points
for (const p of debug.samplePoints) {
octx.beginPath();
octx.fillStyle = p.colorHex ? p.colorHex : 'rgba(180,180,180,0.8)';
octx.arc(p.x, p.y, 7, 0, Math.PI * 2);
octx.fill();
// subtle outline so light colors still pop
octx.strokeStyle = 'rgba(0,0,0,0.6)';
octx.lineWidth = 2;
octx.stroke();
}
// Restore defaults for subsequent strokes
octx.lineWidth = 4;
// badge boxes
for (let i = 0; i < (debug.badgeBoxes || []).length; i++) {
const [x, y, w, h] = debug.badgeBoxes[i];
octx.strokeStyle = 'rgba(0, 255, 255, 0.95)';
octx.strokeRect(x, y, w, h);
octx.fillStyle = 'rgba(0,0,0,0.55)';
octx.fillRect(x, y - 16, 70, 16);
octx.fillStyle = 'rgba(255,255,255,0.95)';
octx.font = '13px ui-monospace, monospace';
octx.fillText(`badge ${i + 1}`, x + 4, y - 4);
}
}
function redrawOverlay() {
if (editBoxes.active) {
drawManualOverlay();
} else {
drawOverlay(lastDebug);
}
}
function clamp(n, lo, hi) {
return Math.max(lo, Math.min(hi, n));
}
function clampBox(box, W, H) {
const minW = 12;
const minH = 12;
const w = clamp(box.w, minW, W);
const h = clamp(box.h, minH, H);
const x = clamp(box.x, 0, W - w);
const y = clamp(box.y, 0, H - h);
return { x, y, w, h };
}
function defaultBottleBoxes(W, H) {
// Tuned for the fixed 3x2 layout shown in user examples.
const fracW = 0.13;
const fracH = 0.34;
const xCenters = [0.36, 0.50, 0.64];
const yCenters = [0.30, 0.69];
const bw = Math.round(fracW * W);
const bh = Math.round(fracH * H);
const out = [];
for (let r = 0; r < 2; r++) {
for (let c = 0; c < 3; c++) {
const cx = Math.round(xCenters[c] * W);
const cy = Math.round(yCenters[r] * H);
const b = clampBox({ x: cx - bw / 2, y: cy - bh / 2, w: bw, h: bh }, W, H);
out.push(b);
}
}
return out;
}
function defaultRockBoxes(bottleBoxes) {
// Default: only bottom-right (bottle 6) has a rock pile.
const out = new Array(6).fill(null);
const b = bottleBoxes?.[5];
if (b) {
out[5] = {
x: b.x + b.w * 0.10,
y: b.y + b.h * 0.78,
w: b.w * 0.80,
h: b.h * 0.22,
};
}
return out;
}
function boxesAbsToRel(boxes, W, H) {
if (!Array.isArray(boxes)) return null;
return boxes.map((b) => {
if (!b) return null;
return {
x: b.x / W,
y: b.y / H,
w: b.w / W,
h: b.h / H,
};
});
}
function boxesRelToAbs(boxes, W, H) {
if (!Array.isArray(boxes)) return null;
return boxes.map((b) => {
if (!b) return null;
return clampBox({
x: b.x * W,
y: b.y * H,
w: b.w * W,
h: b.h * H,
}, W, H);
});
}
function loadBoxesFromStorage(W, H) {
try {
const raw = localStorage.getItem(BOX_STORAGE_KEY);
if (!raw) return null;
const data = JSON.parse(raw);
if (!data || data.v !== 1) return null;
const bottlesRel = data.bottles;
const rocksRel = data.rocks;
if (!Array.isArray(bottlesRel) || bottlesRel.length !== 6) return null;
const bottles = boxesRelToAbs(bottlesRel, W, H);
const rocks = Array.isArray(rocksRel) && rocksRel.length === 6 ? boxesRelToAbs(rocksRel, W, H) : new Array(6).fill(null);
return { bottles, rocks };
} catch (_) {
return null;
}
}
function saveBoxesToStorage(W, H) {
try {
const payload = {
v: 1,
bottles: boxesAbsToRel(manualBoxes.bottles, W, H),
rocks: boxesAbsToRel(manualBoxes.rocks, W, H),
};
localStorage.setItem(BOX_STORAGE_KEY, JSON.stringify(payload));
} catch (_) {
// ignore
}
}
function initManualBoxesForImage(W, H) {
const stored = loadBoxesFromStorage(W, H);
if (stored?.bottles && stored.bottles.length === 6) {
manualBoxes = {
bottles: stored.bottles,
rocks: (stored.rocks && stored.rocks.length === 6) ? stored.rocks : defaultRockBoxes(stored.bottles),
};
} else {
const bottles = defaultBottleBoxes(W, H);
manualBoxes = {
bottles,
rocks: defaultRockBoxes(bottles),
};
saveBoxesToStorage(W, H);
}
// Exit edit mode when a new image is loaded.
setEditMode(null);
// Show boxes while editing; otherwise show debug (none yet).
redrawOverlay();
}
function serializeBoxesForWorker(boxes, W, H) {
if (!Array.isArray(boxes)) return null;
return boxes.map((b) => {
if (!b) return null;
const bb = clampBox({
x: Math.round(b.x),
y: Math.round(b.y),
w: Math.round(b.w),
h: Math.round(b.h),
}, W, H);
return { x: bb.x, y: bb.y, w: bb.w, h: bb.h };
});
}
function setBoxHint(msg) {
if (!boxHintEl) return;
boxHintEl.textContent = msg || '';
}
function setEditMode(mode) {
const nextMode = mode || null;
const isSame = editBoxes.active && editBoxes.mode === nextMode;
// Toggle off if clicking the same mode.
const active = nextMode && !isSame;
editBoxes.active = !!active;
editBoxes.mode = active ? nextMode : null;
editBoxes.selected = null;
editBoxes.action = null;
editBoxes.handle = null;
editBoxes.startBox = null;
if (canvasWrapEl) {
if (editBoxes.active) canvasWrapEl.classList.add('editing');
else canvasWrapEl.classList.remove('editing');
}
if (btnEditBottles) btnEditBottles.classList.toggle('active', editBoxes.active && editBoxes.mode === 'bottles');
if (btnEditRocks) btnEditRocks.classList.toggle('active', editBoxes.active && editBoxes.mode === 'rocks');
if (editBoxes.active) {
setBoxHint(editBoxes.mode === 'bottles'
? 'Editing bottles: drag to move, corners to resize.'
: 'Editing rocks: click inside a bottle to add, drag/resize. Del clears selected rock.');
} else {
setBoxHint('');
}
redrawOverlay();
}
function drawHandle(x, y) {
const s = 6;
octx.fillRect(x - s, y - s, s * 2, s * 2);
}
function drawManualOverlay() {
clearOverlay();
if (!manualBoxes.bottles || manualBoxes.bottles.length !== 6) return;
const sel = editBoxes.selected;
const selType = sel?.type || null;
const selIdx = (typeof sel?.index === 'number') ? sel.index : null;
// bottles
octx.lineWidth = 3;
octx.font = '14px ui-monospace, monospace';
for (let i = 0; i < manualBoxes.bottles.length; i++) {
const b = manualBoxes.bottles[i];
const isSel = (selType === 'bottle' && selIdx === i);
octx.strokeStyle = isSel ? 'rgba(125, 211, 252, 0.95)' : 'rgba(0, 255, 0, 0.9)';
octx.strokeRect(b.x, b.y, b.w, b.h);
octx.fillStyle = 'rgba(0,0,0,0.55)';
octx.fillRect(b.x, Math.max(0, b.y - 20), 54, 20);
octx.fillStyle = 'rgba(255,255,255,0.95)';
octx.fillText(`${i + 1}`, b.x + 6, Math.max(14, b.y - 6));
}
// rocks
if (manualBoxes.rocks && manualBoxes.rocks.length === 6) {
octx.save();
octx.strokeStyle = 'rgba(255, 200, 0, 0.95)';
if (typeof octx.setLineDash === 'function') octx.setLineDash([6, 3]);
for (let i = 0; i < manualBoxes.rocks.length; i++) {
const rb = manualBoxes.rocks[i];
if (!rb) continue;
const isSel = (selType === 'rock' && selIdx === i);
octx.strokeStyle = isSel ? 'rgba(125, 211, 252, 0.95)' : 'rgba(255, 200, 0, 0.95)';
octx.strokeRect(rb.x, rb.y, rb.w, rb.h);
octx.fillStyle = 'rgba(0,0,0,0.55)';
octx.fillRect(rb.x, clamp(rb.y + rb.h + 2, 0, overlay.height - 20), 78, 20);
octx.fillStyle = 'rgba(255,255,255,0.95)';
octx.fillText(`ROCK ${i + 1}`, rb.x + 6, clamp(rb.y + rb.h + 16, 14, overlay.height - 6));
}
octx.restore();
}
// selection handles
if (selType && selIdx !== null) {
const b = selType === 'bottle' ? manualBoxes.bottles?.[selIdx] : manualBoxes.rocks?.[selIdx];
if (b) {
octx.save();
octx.fillStyle = 'rgba(125, 211, 252, 0.95)';
drawHandle(b.x, b.y);
drawHandle(b.x + b.w, b.y);
drawHandle(b.x + b.w, b.y + b.h);
drawHandle(b.x, b.y + b.h);
octx.restore();
}
}
}
function canvasPointFromEvent(ev) {
const rect = overlay.getBoundingClientRect();
const sx = overlay.width / rect.width;
const sy = overlay.height / rect.height;
return {
x: (ev.clientX - rect.left) * sx,
y: (ev.clientY - rect.top) * sy,
};
}
function pointInBox(p, b) {
return p.x >= b.x && p.x <= b.x + b.w && p.y >= b.y && p.y <= b.y + b.h;
}
function getHandleForPoint(p, b) {
const hs = 10;
const corners = [
{ h: 'nw', x: b.x, y: b.y },
{ h: 'ne', x: b.x + b.w, y: b.y },
{ h: 'se', x: b.x + b.w, y: b.y + b.h },
{ h: 'sw', x: b.x, y: b.y + b.h },
];
for (const c of corners) {
const dx = p.x - c.x;
const dy = p.y - c.y;
if ((dx * dx + dy * dy) <= hs * hs) return c.h;
}
return null;
}
function makeDefaultRockBoxForBottle(b) {
return {
x: b.x + b.w * 0.15,
y: b.y + b.h * 0.75,
w: b.w * 0.70,
h: b.h * 0.22,
};
}
function setSelectedBox(type, index) {
editBoxes.selected = { type, index };
redrawOverlay();
}
function clearSelectedRock() {
const sel = editBoxes.selected;
if (!sel || sel.type !== 'rock' || typeof sel.index !== 'number') return;
clearRockForBottle(sel.index);
editBoxes.selected = null;
redrawOverlay();
}
function clearRockForBottle(bottleIndex) {
if (!lastImageData) return;
const W = lastImageData.width;
const H = lastImageData.height;
if (!manualBoxes.rocks || manualBoxes.rocks.length !== 6) return;
const i = Number(bottleIndex);
if (!Number.isFinite(i) || i < 0 || i >= 6) return;
manualBoxes.rocks[i] = null;
saveBoxesToStorage(W, H);
// Update parsed result (so Solve uses the corrected rock set)
if (parseResult) {
parseResult.rock_bottles = (parseResult.rock_bottles || []).filter((x) => x !== i);
if (Array.isArray(parseResult.bottles) && parseResult.bottles[i]) {
parseResult.bottles[i].rock = false;
parseResult.bottles[i].rock_bbox = null;
}
}
// Update debug overlay if present
if (lastDebug) {
if (Array.isArray(lastDebug.bottles) && lastDebug.bottles[i]) {
lastDebug.bottles[i].rock = false;
}
if (Array.isArray(lastDebug.rockBoxes)) {
lastDebug.rockBoxes[i] = null;
}
}
if (parseResult) {
// Rerender boards + legend title/rock chips
if (colorLabels) setLegend(parseResult.colors_by_id || {}, colorLabels);
const cap = parseResult.capacity;
const stacks = parseResult.bottle_contents_ids.map((slots) => contentsToStacksTopBottom(slots, cap));
renderOutput(stacks, null, null);
updateSelectionHighlight();
}
redrawOverlay();
}
function onOverlayPointerDown(ev) {
if (!editBoxes.active || !lastImageData) return;
const p = canvasPointFromEvent(ev);
const W = lastImageData.width;
const H = lastImageData.height;
if (editBoxes.mode === 'bottles') {
const boxes = manualBoxes.bottles || [];
let hit = -1;
for (let i = 0; i < boxes.length; i++) {
if (boxes[i] && pointInBox(p, boxes[i])) { hit = i; break; }
}
if (hit < 0) return;
const b = boxes[hit];
const handle = getHandleForPoint(p, b);
editBoxes.selected = { type: 'bottle', index: hit };
editBoxes.action = handle ? 'resize' : 'move';
editBoxes.handle = handle;
editBoxes.startX = p.x;
editBoxes.startY = p.y;
editBoxes.startBox = { ...b };
try { overlay.setPointerCapture(ev.pointerId); } catch (_) {}
redrawOverlay();
ev.preventDefault();
return;
}
if (editBoxes.mode === 'rocks') {
const rocks = manualBoxes.rocks || new Array(6).fill(null);
const bottles = manualBoxes.bottles || [];
// Prefer selecting an existing rock box
let hit = -1;
for (let i = 0; i < rocks.length; i++) {
const rb = rocks[i];
if (rb && pointInBox(p, rb)) { hit = i; break; }
}
// Otherwise, click inside a bottle to create/select its rock box
if (hit < 0) {
let bottleHit = -1;
for (let i = 0; i < bottles.length; i++) {
const b = bottles[i];
if (b && pointInBox(p, b)) { bottleHit = i; break; }
}
if (bottleHit < 0) return;
hit = bottleHit;
if (!rocks[hit]) {
rocks[hit] = clampBox(makeDefaultRockBoxForBottle(bottles[hit]), W, H);
manualBoxes.rocks = rocks;
}
}
const rb = manualBoxes.rocks[hit];
if (!rb) return;
const handle = getHandleForPoint(p, rb);
editBoxes.selected = { type: 'rock', index: hit };
editBoxes.action = handle ? 'resize' : 'move';
editBoxes.handle = handle;
editBoxes.startX = p.x;
editBoxes.startY = p.y;
editBoxes.startBox = { ...rb };
try { overlay.setPointerCapture(ev.pointerId); } catch (_) {}
redrawOverlay();
ev.preventDefault();
return;
}
}
function onOverlayPointerMove(ev) {
if (!editBoxes.active || !lastImageData) return;
if (!editBoxes.action || !editBoxes.startBox || !editBoxes.selected) return;
const p = canvasPointFromEvent(ev);
const W = lastImageData.width;
const H = lastImageData.height;
const dx = p.x - editBoxes.startX;
const dy = p.y - editBoxes.startY;
const { type, index } = editBoxes.selected;
const targetArr = (type === 'bottle') ? manualBoxes.bottles : manualBoxes.rocks;
if (!targetArr || !targetArr[index]) return;
let b = { ...editBoxes.startBox };
if (editBoxes.action === 'move') {
b.x = editBoxes.startBox.x + dx;
b.y = editBoxes.startBox.y + dy;
} else if (editBoxes.action === 'resize') {
const h = editBoxes.handle;
if (h === 'nw') {
b.x = editBoxes.startBox.x + dx;
b.y = editBoxes.startBox.y + dy;
b.w = editBoxes.startBox.w - dx;
b.h = editBoxes.startBox.h - dy;
} else if (h === 'ne') {
b.y = editBoxes.startBox.y + dy;
b.w = editBoxes.startBox.w + dx;
b.h = editBoxes.startBox.h - dy;
} else if (h === 'se') {
b.w = editBoxes.startBox.w + dx;
b.h = editBoxes.startBox.h + dy;
} else if (h === 'sw') {
b.x = editBoxes.startBox.x + dx;
b.w = editBoxes.startBox.w - dx;
b.h = editBoxes.startBox.h + dy;
}
}
b = clampBox(b, W, H);
targetArr[index] = b;
if (type === 'rock') manualBoxes.rocks = targetArr;
if (type === 'bottle') manualBoxes.bottles = targetArr;
redrawOverlay();
ev.preventDefault();
}
function onOverlayPointerUp(ev) {
if (!editBoxes.active || !lastImageData) return;
if (!editBoxes.action) return;
try { overlay.releasePointerCapture(ev.pointerId); } catch (_) {}
editBoxes.action = null;
editBoxes.handle = null;
editBoxes.startBox = null;
saveBoxesToStorage(lastImageData.width, lastImageData.height);
redrawOverlay();
ev.preventDefault();
}
function onOverlayKeyDown(ev) {
if (!editBoxes.active) return;
if (editBoxes.mode !== 'rocks') return;
if (ev.key === 'Delete' || ev.key === 'Backspace') {
clearSelectedRock();
ev.preventDefault();
}
}
function renderRockLegend() {
if (!rockLegendEl) return;
rockLegendEl.innerHTML = '';
const rocks = parseResult?.rock_bottles || [];
if (!Array.isArray(rocks) || rocks.length === 0) {
rockLegendEl.style.display = 'none';
return;
}
rockLegendEl.style.display = 'flex';
for (const idx of rocks) {
const bi = Number(idx);
if (!Number.isFinite(bi)) continue;
const item = document.createElement('div');
item.className = 'item';
item.dataset.bottle = String(bi);
const sw = document.createElement('div');
sw.className = 'swatch';
sw.style.background = 'rgba(255, 200, 0, 0.95)';
item.appendChild(sw);
const label = document.createElement('div');
label.textContent = `Rock bottle ${bi + 1}`;
item.appendChild(label);
// Clicking the chip jumps to rock edit mode for that bottle (handy to nudge the box)
item.addEventListener('click', () => {
if (!(editBoxes.active && editBoxes.mode === 'rocks')) setEditMode('rocks');
if (manualBoxes.rocks?.[bi]) {
setSelectedBox('rock', bi);
}
});
const del = document.createElement('button');
del.className = 'del';
del.type = 'button';
del.title = 'Remove rock from this bottle';
del.textContent = '×';
del.addEventListener('click', (ev) => {
ev.stopPropagation();
clearRockForBottle(bi);
});
item.appendChild(del);
rockLegendEl.appendChild(item);
}
}
function setLegend(colorsById, labels) {
legend.innerHTML = '';
if (legendTitle) {
const rockCount = (parseResult?.rock_bottles || []).length;
legendTitle.textContent = `Colors: ${labels.orderedIds.length} · Rock Bottles: ${rockCount} · (click 2 colors to merge, × to delete)`;
}
renderRockLegend();
const ids = labels.orderedIds;
for (const id of ids) {
const hex = colorsById[String(id)];
const name = labels.namesById[id];
const abbr = labels.abbrById[id];
const item = document.createElement('div');
item.className = 'item';
item.dataset.cid = String(id);
item.title = `${abbr} (${hex})`;
item.addEventListener('click', () => onLegendItemClick(id));
const sw = document.createElement('span');
sw.className = 'swatch';
sw.style.background = hex;
const txt = document.createElement('span');
txt.textContent = name;
const del = document.createElement('button');
del.className = 'del';
del.type = 'button';
del.title = 'Remove this color from detection';
del.textContent = '×';
del.addEventListener('click', (ev) => {
ev.stopPropagation();
clearLegendSelection();
deleteDetectedColor(id);
});
item.appendChild(sw);
item.appendChild(txt);
item.appendChild(del);
legend.appendChild(item);
}
updateSelectionHighlight();
}
function updateSelectionHighlight() {
const sel = (typeof legendSelectedId === 'number') ? legendSelectedId : null;
// Legend items
legend.querySelectorAll('.item').forEach((el) => {
const cid = parseInt(el.dataset.cid || '-1', 10);
if (sel !== null && cid === sel) el.classList.add('selected');
else el.classList.remove('selected');
});
// Board slots (both detected + final boards)
const slots = document.querySelectorAll('.slot');
slots.forEach((el) => {
const cidStr = el.dataset.cid;
const cid = (cidStr === undefined || cidStr === null || cidStr === '') ? null : parseInt(cidStr, 10);
if (sel !== null && cid === sel) el.classList.add('selectedColor');
else el.classList.remove('selectedColor');
});
}
function clearLegendSelection() {
legendSelectedId = null;
updateSelectionHighlight();
}
function hexToRgb(hex) {
const h = String(hex || '').replace('#', '').trim();
if (h.length !== 6) return { r: 0, g: 0, b: 0 };
return {
r: parseInt(h.slice(0, 2), 16),
g: parseInt(h.slice(2, 4), 16),
b: parseInt(h.slice(4, 6), 16),
};
}
function bgrToHex(b, g, r) {
const rr = Math.max(0, Math.min(255, Math.round(r)));
const gg = Math.max(0, Math.min(255, Math.round(g)));
const bb = Math.max(0, Math.min(255, Math.round(b)));
return '#' + rr.toString(16).padStart(2, '0').toUpperCase()
+ gg.toString(16).padStart(2, '0').toUpperCase()
+ bb.toString(16).padStart(2, '0').toUpperCase();
}
function mergeDetectedColors(keepId, dropId) {
if (!parseResult) return;
const colorsById = parseResult.colors_by_id || {};
const k = Number(keepId);
const d = Number(dropId);
if (!Number.isFinite(k) || !Number.isFinite(d) || k === d) return;
if (!(String(k) in colorsById) || !(String(d) in colorsById)) return;
const counts = parseResult.color_unit_counts || {};
const cK = (counts[String(k)] ?? 0) | 0;
const cD = (counts[String(d)] ?? 0) | 0;
const total = cK + cD;
// Pull BGR from the worker's cluster info if present; otherwise fall back to hex.
const infoK = Array.isArray(parseResult.colors) ? parseResult.colors.find((c) => c.id === k) : null;
const infoD = Array.isArray(parseResult.colors) ? parseResult.colors.find((c) => c.id === d) : null;
const bgrK = infoK?.center_bgr ? infoK.center_bgr : (() => {
const { r, g, b } = hexToRgb(colorsById[String(k)]);
return [b, g, r];
})();
const bgrD = infoD?.center_bgr ? infoD.center_bgr : (() => {
const { r, g, b } = hexToRgb(colorsById[String(d)]);
return [b, g, r];
})();
const wK = total > 0 ? cK / total : 0.5;
const wD = total > 0 ? cD / total : 0.5;
const mb = bgrK[0] * wK + bgrD[0] * wD;
const mg = bgrK[1] * wK + bgrD[1] * wD;
const mr = bgrK[2] * wK + bgrD[2] * wD;
const mergedHex = bgrToHex(mb, mg, mr);
// --- Update parseResult ---
colorsById[String(k)] = mergedHex;
delete colorsById[String(d)];
if (parseResult.color_unit_counts) {
parseResult.color_unit_counts[String(k)] = total;
delete parseResult.color_unit_counts[String(d)];
}
if (Array.isArray(parseResult.colors)) {
// update keep entry
if (infoK) {
infoK.count = total;
infoK.center_bgr = [mb, mg, mr];
infoK.center_hex = mergedHex;
}
// drop
parseResult.colors = parseResult.colors.filter((c) => c.id !== d);
}
// Replace ids in detected bottles
parseResult.bottle_contents_ids = (parseResult.bottle_contents_ids || []).map((b) => b.map((cid) => (cid === d ? k : cid)));
// Rebuild hex contents
parseResult.bottle_contents_hex = (parseResult.bottle_contents_ids || []).map((b) => b.map((cid) => (cid === null || cid === undefined) ? null : (colorsById[String(cid)] || null)));
// Keep bottles[] in sync for downstream debug consumers
if (Array.isArray(parseResult.bottles)) {
for (const b of parseResult.bottles) {
if (!b?.slots) continue;
for (const s of b.slots) {
if (!s?.filled) continue;
if (s.color_id === d) s.color_id = k;
if (s.color_id === k) s.color_hex = colorsById[String(k)] || s.color_hex;
}
}
}
parseResult.num_colors = Object.keys(colorsById).length;
// Rebuild labels + rerender UI
colorLabels = buildColorLabels(colorsById);
setLegend(colorsById, colorLabels);
const cap = parseResult.capacity;
const stacks = parseResult.bottle_contents_ids.map((slots) => contentsToStacksTopBottom(slots, cap));
renderOutput(stacks, null, null);
btnSolve.disabled = false;
setStatus(`Merged colors.`);
}
function deleteDetectedColor(colorId) {
if (!parseResult) return;
const d = Number(colorId);
if (!Number.isFinite(d)) return;
const colorsById = parseResult.colors_by_id || {};
if (!(String(d) in colorsById)) return;
// Remove from palette
delete colorsById[String(d)];
if (parseResult.color_unit_counts) delete parseResult.color_unit_counts[String(d)];
if (Array.isArray(parseResult.colors)) {
parseResult.colors = parseResult.colors.filter((c) => c.id !== d);
}
// Replace occurrences in detected bottles with empty
parseResult.bottle_contents_ids = (parseResult.bottle_contents_ids || []).map((b) => b.map((cid) => (cid === d ? null : cid)));
parseResult.bottle_contents_hex = (parseResult.bottle_contents_ids || []).map((b) => b.map((cid) => (cid === null || cid === undefined) ? null : (colorsById[String(cid)] || null)));
// Keep bottles[] in sync (so any downstream consumers don't see a ghost color)
if (Array.isArray(parseResult.bottles)) {
for (const b of parseResult.bottles) {
if (!b?.slots) continue;
for (const s of b.slots) {
if (s?.color_id === d) {
s.filled = false;
s.color_id = null;
s.color_hex = null;
}
}
}
}
parseResult.num_colors = Object.keys(colorsById).length;