-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
721 lines (637 loc) · 20.8 KB
/
app.js
File metadata and controls
721 lines (637 loc) · 20.8 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
// ====== Palettes ======
const PALETTE_BASIC_HEX = [
"#000000",
"#3c3c3c",
"#787878",
"#d2d2d2",
"#ffffff",
"#600018",
"#ed1c24",
"#ff7f27",
"#f6aa09",
"#f9dd3b",
"#fffabc",
"#9c8431",
"#0eb968",
"#13e67b",
"#87ff5e",
"#0c816e",
"#10aea6",
"#13e1be",
"#60f7f2",
"#28509e",
"#4093e4",
"#6b50f6",
"#99b1fb",
"#780c99",
"#aa38b9",
"#e09ff9",
"#cb007a",
"#ec1f80",
"#f38da9",
"#684634",
"#95682a",
"#f8b277"
];
const PALETTE_EXTENDED_HEX = [
"#000000",
"#3c3c3c",
"#787878",
"#aaaaaa",
"#d2d2d2",
"#ffffff",
"#600018",
"#a50e1e",
"#ed1c24",
"#fa8072",
"#e45c1a",
"#ff7f27",
"#f6aa09",
"#f9dd3b",
"#fffabc",
"#9c8431",
"#c5ad31",
"#e8d45f",
"#4a6b3a",
"#5a944a",
"#84c573",
"#0eb968",
"#13e67b",
"#87ff5e",
"#0c816e",
"#10aea6",
"#13e1be",
"#0f799f",
"#60f7f2",
"#bbfaf2",
"#28509e",
"#4093e4",
"#7dc7ff",
"#4d31b8",
"#6b50f6",
"#99b1fb",
"#4a4284",
"#7a71c4",
"#b5aef1",
"#780c99",
"#aa38b9",
"#e09ff9",
"#cb007a",
"#ec1f80",
"#f38da9",
"#9b5249",
"#d18078",
"#fab6a4",
"#684634",
"#95682a",
"#dba463",
"#7b6352",
"#9c846b",
"#d6b594",
"#d18051",
"#f8b277",
"#ffc5a5",
"#6d643f",
"#948c6b",
"#cdc59e",
"#333941",
"#6d758d",
"#b3b9d1"
];
// ====== UI ======
const fileInput = document.getElementById("fileInput");
const processBtn = document.getElementById("processBtn");
const downloadBtn = document.getElementById("downloadBtn");
const canvas = document.getElementById("canvas");
const metaEl = document.getElementById("meta");
const ctx = canvas.getContext("2d", { willReadFrequently: true });
const scaleInput = document.getElementById("scaleFactor");
const gridColorEl = document.getElementById("gridColor");
const enlargeToggle= document.getElementById("enlargeToggle");
const helpBtn = document.getElementById("helpBtn");
const helpModal = document.getElementById("helpModal");
const helpClose = document.getElementById("helpClose");
const helpBackdrop = document.getElementById("helpBackdrop");
const canvasWrap = document.querySelector(".canvas-wrap");
const footerVersion = document.getElementById("footerVersionString");
let sourceImageBitmap = null;
let lastOutputBlobUrl = null;
let uploadedFileName = null;
// ====== Utils ======
function hexToRgb(hex) {
const s = hex.replace("#", "");
const n = parseInt(s.length === 3 ? s.split("").map(c => c+c).join("") : s, 16);
return [(n>>16)&255, (n>>8)&255, n&255];
}
function buildPalette(hexList){ return hexList.map(hexToRgb); }
function dist2(r,g,b, pr,pg,pb) {
const dr=r-pr, dg=g-pg, db=b-pb;
return dr*dr + dg*dg + db*db;
}
function nearestPaletteIndex(r,g,b, palette) {
let best=0, bestD=Infinity;
for (let i=0;i<palette.length;i++){
const p=palette[i];
const d=dist2(r,g,b, p[0],p[1],p[2]);
if (d<bestD){ bestD=d; best=i; }
}
return best;
}
// 8×8 Bayer matrix for ordered dithering
const BAYER8 = [
[0,48,12,60,3,51,15,63],
[32,16,44,28,35,19,47,31],
[8,56,4,52,11,59,7,55],
[40,24,36,20,43,27,39,23],
[2,50,14,62,1,49,13,61],
[34,18,46,30,33,17,45,29],
[10,58,6,54,9,57,5,53],
[42,26,38,22,41,25,37,21]
].map(row => row.map(v => (v+0.5)/64));
function clamp255(v){ return v<0?0:v>255?255:v; }
// ====== Manual resamplers for first resize ======
function sampleRGBA(srcData, sw, sh, x, y){
const xi = x < 0 ? 0 : x >= sw ? sw-1 : x|0;
const yi = y < 0 ? 0 : y >= sh ? sh-1 : y|0;
const idx = (yi*sw + xi) * 4;
return [srcData[idx], srcData[idx+1], srcData[idx+2], srcData[idx+3]];
}
function resizeBilinear(srcImgData, dstW, dstH){
const sw = srcImgData.width, sh = srcImgData.height;
const src = srcImgData.data;
const out = new ImageData(dstW, dstH);
const dst = out.data;
const scaleX = sw / dstW;
const scaleY = sh / dstH;
for (let y=0; y<dstH; y++){
const sy = (y + 0.5) * scaleY - 0.5;
const y0 = Math.floor(sy), y1 = y0 + 1, fy = sy - y0;
for (let x=0; x<dstW; x++){
const sx = (x + 0.5) * scaleX - 0.5;
const x0 = Math.floor(sx), x1 = x0 + 1, fx = sx - x0;
const c00 = sampleRGBA(src, sw, sh, x0, y0);
const c10 = sampleRGBA(src, sw, sh, x1, y0);
const c01 = sampleRGBA(src, sw, sh, x0, y1);
const c11 = sampleRGBA(src, sw, sh, x1, y1);
const idx = (y*dstW + x)*4;
for (let k=0;k<4;k++){
const v0 = c00[k]*(1-fx) + c10[k]*fx;
const v1 = c01[k]*(1-fx) + c11[k]*fx;
dst[idx+k] = clamp255(v0*(1-fy) + v1*fy);
}
}
}
return out;
}
// Bicubic: separable Mitchell–Netravali (B=1/3, C=1/3)
function mitchellNetravali(t){
const B = 1/3, C = 1/3;
const at = Math.abs(t), at2 = at*at, at3 = at2*at;
if (at < 1){
return ((12 - 9*B - 6*C)*at3 + (-18 + 12*B + 6*C)*at2 + (6 - 2*B)) / 6;
} else if (at < 2){
return ((-B - 6*C)*at3 + (6*B + 30*C)*at2 + (-12*B - 48*C)*at + (8*B - 24*C)) / 6 + (48*C)/6;
} else return 0;
}
// Correct the Mitchell polynomial (expanded safely)
function mitchellNetravali(t){
const B = 1/3, C = 1/3;
const x = Math.abs(t);
const x2 = x*x, x3 = x2*x;
if (x < 1) {
return ((12 - 9*B - 6*C)*x3 + (-18 + 12*B + 6*C)*x2 + (6 - 2*B)) / 6;
} else if (x < 2) {
return ((-B - 6*C)*x3 + (6*B + 30*C)*x2 + (-12*B - 48*C)*x + (8*B + 24*C)) / 6;
}
return 0;
}
function resizeBicubic(srcImgData, dstW, dstH){
const sw = srcImgData.width, sh = srcImgData.height;
const src = srcImgData.data;
const tmp = new Float32Array(dstW * sh * 4);
const scaleX = sw / dstW;
for (let y=0; y<sh; y++){
for (let x=0; x<dstW; x++){
const sx = (x + 0.5)*scaleX - 0.5;
const ix = Math.floor(sx);
const wts = new Float32Array(4);
const xs = new Int32Array(4);
let sumW = 0;
for (let k=-1; k<=2; k++){
const xx = ix + k;
xs[k+1] = xx;
const w = mitchellNetravali(sx - xx);
wts[k+1] = w; sumW += w;
}
if (sumW !== 0){ for (let i=0;i<4;i++) wts[i] /= sumW; }
let r=0,g=0,b=0,a=0;
for (let t=0; t<4; t++){
const sxx = xs[t] < 0 ? 0 : xs[t] >= sw ? sw-1 : xs[t];
const idx = (y*sw + sxx)*4;
const wt = wts[t];
r += src[idx] * wt;
g += src[idx+1] * wt;
b += src[idx+2] * wt;
a += src[idx+3] * wt;
}
const oidx = (y*dstW + x)*4;
tmp[oidx] = r; tmp[oidx+1] = g; tmp[oidx+2] = b; tmp[oidx+3] = a;
}
}
const out = new ImageData(dstW, dstH);
const dst = out.data;
const scaleY = sh / dstH;
for (let y=0; y<dstH; y++){
const sy = (y + 0.5)*scaleY - 0.5;
const iy = Math.floor(sy);
const wts = new Float32Array(4);
const ys = new Int32Array(4);
let sumW = 0;
for (let k=-1; k<=2; k++){
const yy = iy + k;
ys[k+1] = yy;
const w = mitchellNetravali(sy - yy);
wts[k+1] = w; sumW += w;
}
if (sumW !== 0){ for (let i=0;i<4;i++) wts[i] /= sumW; }
for (let x=0; x<dstW; x++){
let r=0,g=0,b=0,a=0;
for (let t=0;t<4;t++){
const syy = ys[t] < 0 ? 0 : ys[t] >= sh ? sh-1 : ys[t];
const idx = (syy*dstW + x)*4;
const wt = wts[t];
r += tmp[idx] * wt;
g += tmp[idx+1] * wt;
b += tmp[idx+2] * wt;
a += tmp[idx+3] * wt;
}
const oidx = (y*dstW + x)*4;
dst[oidx] = clamp255(r);
dst[oidx+1] = clamp255(g);
dst[oidx+2] = clamp255(b);
dst[oidx+3] = clamp255(a);
}
}
return out;
}
// ====== Dithering / Quantization ======
function quantizeNone(img, out, palette) {
const s = img.data, d = out.data;
for (let i=0;i<s.length;i+=4){
const r=s[i], g=s[i+1], b=s[i+2], a=s[i+3];
const pi = nearestPaletteIndex(r,g,b, palette);
const p = palette[pi];
d[i]=p[0]; d[i+1]=p[1]; d[i+2]=p[2]; d[i+3]=a;
}
}
function quantizeOrdered(img, out, palette) {
const s = img.data, d = out.data;
const w = img.width, h = img.height;
const amp = 24;
for (let y=0;y<h;y++){
for (let x=0;x<w;x++){
const idx = (y*w + x)*4;
const a = s[idx+3];
const t = (BAYER8[y & 7][x & 7] - 0.5)*2;
let r = s[idx] + amp*t;
let g = s[idx+1] + amp*t;
let b = s[idx+2] + amp*t;
r = r<0?0:r>255?255:r|0;
g = g<0?0:g>255?255:g|0;
b = b<0?0:b>255?255:b|0;
const pi = nearestPaletteIndex(r,g,b, palette);
const p = palette[pi];
d[idx]=p[0]; d[idx+1]=p[1]; d[idx+2]=p[2]; d[idx+3]=a;
}
}
}
function diffuse(buf, w, h, x, y, er,eg,eb, k){
if (x<0||x>=w||y<0||y>=h) return;
const i4=(y*w+x)*4;
buf[i4] = clamp255(buf[i4] + er*k);
buf[i4+1] = clamp255(buf[i4+1] + eg*k);
buf[i4+2] = clamp255(buf[i4+2] + eb*k);
}
function quantizeErrorDiffusion(img, out, palette) {
const w=img.width, h=img.height;
const s=img.data;
const d=out.data;
const buf = new Float32Array(s.length);
for (let i=0;i<s.length;i++) buf[i]=s[i];
for (let y=0;y<h;y++){
for (let x=0;x<w;x++){
const i4=(y*w+x)*4;
const r0=buf[i4], g0=buf[i4+1], b0=buf[i4+2], a0=buf[i4+3];
const pi = nearestPaletteIndex(r0,g0,b0, palette);
const p = palette[pi];
d[i4]=p[0]; d[i4+1]=p[1]; d[i4+2]=p[2]; d[i4+3]=a0;
const er=r0-p[0], eg=g0-p[1], eb=b0-p[2];
diffuse(buf,w,h, x+1,y, er,eg,eb, 7/16);
diffuse(buf,w,h, x-1,y+1, er,eg,eb, 3/16);
diffuse(buf,w,h, x, y+1, er,eg,eb, 5/16);
diffuse(buf,w,h, x+1,y+1, er,eg,eb, 1/16);
}
}
}
// Dizzy dithering: randomized traversal; diffuse only into unprocessed neighbors
// ref: https://liamappelbe.medium.com/dizzy-dithering-2ae76dbceba1
function quantizeDizzy(img, out, palette, seed) {
const w = img.width, h = img.height, N = w * h;
const s = img.data;
const d = out.data;
// Working buffer (RGB error accumulation). Copy source into float buffer.
const buf = new Float32Array(s.length);
for (let i = 0; i < s.length; i++) buf[i] = s[i];
// Processed mask
const seen = new Uint8Array(N);
// Randomized order of all pixel indices
const order = new Uint32Array(N);
for (let i = 0; i < N; i++) order[i] = i;
const rng = mulberry32((seed >>> 0) || 0xC0FFEE);
// Shuffle: need a plain array for our swap helper or implement typed swap:
// Here we do typed-array swap manually:
for (let i = N - 1; i > 0; i--) {
const j = (rng() * (i + 1)) | 0;
const tmp = order[i]; order[i] = order[j]; order[j] = tmp;
}
// Neighbor offsets (8-neighborhood). Heavier weight for orthogonals.
// [dx, dy, weight]
const NB = [
[ 1, 0, 10], [-1, 0, 10], [ 0, 1, 10], [ 0, -1, 10], // orthogonal
[ 1, 1, 1], [ 1, -1, 1], [-1, 1, 1], [-1, -1, 1] // diagonals
];
for (let k = 0; k < N; k++) {
const i = order[k];
const x = i % w;
const y = (i / w) | 0;
const idx = i * 4;
// Read current value with accumulated error
const r0 = buf[idx], g0 = buf[idx + 1], b0 = buf[idx + 2], a0 = buf[idx + 3];
// Quantize to nearest palette
const pi = nearestPaletteIndex(r0, g0, b0, palette);
const p = palette[pi];
// Write output
d[idx] = p[0]; d[idx + 1] = p[1]; d[idx + 2] = p[2]; d[idx + 3] = a0;
// Compute error (RGB)
const er = r0 - p[0], eg = g0 - p[1], eb = b0 - p[2];
// Gather unprocessed neighbors and total weight
let denom = 0;
// We’ll stash neighbor positions and weights in small fixed arrays
const nx = new Int16Array(8);
const ny = new Int16Array(8);
const nw = new Uint8Array(8);
let ncnt = 0;
for (let t = 0; t < NB.length; t++) {
const xx = x + NB[t][0];
const yy = y + NB[t][1];
if (xx < 0 || xx >= w || yy < 0 || yy >= h) continue;
const ni = yy * w + xx;
if (seen[ni]) continue; // only diffuse into unprocessed neighbors
nx[ncnt] = xx; ny[ncnt] = yy; nw[ncnt] = NB[t][2];
denom += NB[t][2];
ncnt++;
}
if (denom > 0 && (er || eg || eb)) {
for (let t = 0; t < ncnt; t++) {
const wfrac = nw[t] / denom;
const j = (ny[t] * w + nx[t]) * 4;
buf[j] = clamp255(buf[j] + er * wfrac);
buf[j + 1] = clamp255(buf[j + 1] + eg * wfrac);
buf[j + 2] = clamp255(buf[j + 2] + eb * wfrac);
// alpha left as-is
}
}
seen[i] = 1;
}
}
// ====== I/O and pipeline ======
fileInput.addEventListener("change", async (e) => {
const file = e.target.files && e.target.files[0];
if (!file){
sourceImageBitmap=null;
processBtn.disabled=true;
downloadBtn.disabled=true;
ctx.clearRect(0,0,canvas.width,canvas.height);
metaEl.textContent="";
// pulse back to Browse
fileInput.classList.add("pulse");
processBtn.classList.remove("pulse");
downloadBtn.classList.remove("pulse");
uploadedFileName = null;
return;
}
uploadedFileName = file.name;
canvasWrap.classList.add("no-placeholder");
const blobURL = URL.createObjectURL(file);
try {
sourceImageBitmap = await createImageBitmap(await fetch(blobURL).then(r=>r.blob()));
} finally {
URL.revokeObjectURL(blobURL);
}
// Show original image immediately (unmodified)
canvas.width = sourceImageBitmap.width;
canvas.height = sourceImageBitmap.height;
ctx.imageSmoothingEnabled = true; // default; explicit
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(sourceImageBitmap, 0, 0);
setPreviewZoomDisplay(canvas.width, canvas.height);
processBtn.disabled=false;
downloadBtn.disabled=true;
fileInput.classList.remove("pulse");
processBtn.classList.add("pulse");
downloadBtn.classList.remove("pulse");
metaEl.textContent = `Loaded ${file.name} (${sourceImageBitmap.width}×${sourceImageBitmap.height})`;
});
// Enable/disable scale inputs based on toggle
function refreshScaleInputs() {
const on = !!enlargeToggle.checked;
scaleInput.disabled = !on;
gridColorEl.disabled = !on;
enlargeToggle.title = on
? "Nearest-neighbor enlarge and 1px grid will be applied."
: "Leave off for Blue Marble (no enlarge/grid).";
}
enlargeToggle.addEventListener("change", refreshScaleInputs);
refreshScaleInputs();
// Display Version
footerVersion.textContent = PixelGridReleaseString;
// Cue the first action (browse) on load
fileInput.classList.add("pulse");
// Help modal wiring
function openHelp(){ helpModal.setAttribute("aria-hidden","false"); }
function closeHelp(){ helpModal.setAttribute("aria-hidden","true"); }
helpBtn.addEventListener("click", openHelp);
helpClose.addEventListener("click", closeHelp);
helpBackdrop.addEventListener("click", closeHelp);
document.addEventListener("keydown", (e)=>{ if(e.key==="Escape") closeHelp(); });
document.getElementById("processBtn").addEventListener("click", () => {
if (!sourceImageBitmap) return;
const maxXStr = document.getElementById("maxX").value.trim();
const maxYStr = document.getElementById("maxY").value.trim();
const maxX = maxXStr ? Math.max(1, Math.floor(+maxXStr)) : null;
const maxY = maxYStr ? Math.max(1, Math.floor(+maxYStr)) : null;
const paletteChoice = document.querySelector('input[name="palette"]:checked').value;
const ditherChoice = document.querySelector('input[name="dither"]:checked').value;
const resampleChoice= document.querySelector('input[name="resample"]:checked').value;
const doEnlarge = !!enlargeToggle.checked;
const scaleFactor = Math.max(1, Math.floor(+scaleInput.value || 5));
const gridColor = gridColorEl.value || "#000000";
let paletteHex;
switch (paletteChoice) {
case "basic":
paletteHex = PALETTE_BASIC_HEX;
break;
case "extended":
paletteHex = PALETTE_EXTENDED_HEX;
break;
case "lego":
// From lego-palette.js loaded before app.js
paletteHex = (window.PALETTE_LEGO_HEX && window.PALETTE_LEGO_HEX.length)
? window.PALETTE_LEGO_HEX
: PALETTE_BASIC_HEX; // fallback
break;
default:
paletteHex = PALETTE_BASIC_HEX;
}
const palette = buildPalette(paletteHex);
const srcW = sourceImageBitmap.width;
const srcH = sourceImageBitmap.height;
let dstW, dstH;
if (maxX && maxY) {
dstW = maxX; dstH = maxY; // forced non-proportional
} else if (maxX) {
dstW = maxX; dstH = Math.max(1, Math.round(srcH * (maxX / srcW)));
} else if (maxY) {
dstH = maxY; dstW = Math.max(1, Math.round(srcW * (maxY / srcH)));
} else {
dstW = 512; dstH = Math.max(1, Math.round(srcH * (512 / srcW)));
}
// Read original pixels
const tmpCanvas = document.createElement("canvas");
tmpCanvas.width = srcW; tmpCanvas.height = srcH;
const tctx = tmpCanvas.getContext("2d", { willReadFrequently: true });
tctx.drawImage(sourceImageBitmap, 0, 0);
const srcImgData = tctx.getImageData(0, 0, srcW, srcH);
// Manual resample to target size
const resized = resampleChoice === "bicubic"
? resizeBicubic(srcImgData, dstW, dstH)
: resizeBilinear(srcImgData, dstW, dstH);
// Quantize + dither to palette
const quantized = new ImageData(dstW, dstH);
switch (ditherChoice) {
case "none": quantizeNone(resized, quantized, palette); break;
case "ordered": quantizeOrdered(resized, quantized, palette); break;
case "diffusion": quantizeErrorDiffusion(resized, quantized, palette); break;
case "dizzy": quantizeDizzy(resized, quantized, palette, Date.now() & 0xffffffff); break; /* If we want deterministic results run-to-run, replace Date.now() with a fixed seed */
}
// Draw result, optionally enlarge + grid
if (!doEnlarge) {
canvas.width = dstW; canvas.height = dstH;
ctx.putImageData(quantized, 0, 0);
setPreviewZoomDisplay(canvas.width, canvas.height);
} else {
const upW = dstW * scaleFactor;
const upH = dstH * scaleFactor;
// place quantized on small offscreen
const smallCanvas = document.createElement("canvas");
smallCanvas.width = dstW; smallCanvas.height = dstH;
smallCanvas.getContext("2d").putImageData(quantized, 0, 0);
// upscale NN and draw to visible canvas
canvas.width = upW; canvas.height = upH;
ctx.clearRect(0,0,upW,upH);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(smallCanvas, 0, 0, upW, upH);
// grid overlay
drawGrid(ctx, upW, upH, scaleFactor, gridColor);
setPreviewZoomDisplay(canvas.width, canvas.height); // will likely resolve to scale=1
}
downloadBtn.disabled = false;
// Move pulsing cue to Download
processBtn.classList.remove("pulse");
downloadBtn.classList.add("pulse");
metaEl.textContent =
`Output ${dstW}×${dstH}${doEnlarge ? ` → upscaled ×${scaleFactor}` : ""}, `
+ `resample=${resampleChoice}, palette=${paletteChoice} (${palette.length}), `
+ `dither=${ditherChoice}${doEnlarge ? `, grid step=${scaleFactor}` : ""}`;
});
function drawGrid(ctx, w, h, step, color){
ctx.save();
ctx.strokeStyle = color;
ctx.lineWidth = 1;
ctx.globalAlpha = 1.0;
// Vertical lines
for (let x = 0; x <= w; x += step) {
ctx.beginPath();
ctx.moveTo(x + 0.5, 0); // 0.5 for crisp 1px lines
ctx.lineTo(x + 0.5, h);
ctx.stroke();
}
// Horizontal lines
for (let y = 0; y <= h; y += step) {
ctx.beginPath();
ctx.moveTo(0, y + 0.5);
ctx.lineTo(w, y + 0.5);
ctx.stroke();
}
ctx.restore();
}
// ====== Download ======
downloadBtn.addEventListener("click", () => {
if (!canvas.width || !canvas.height) return;
// Stop pulsing once download is invoked
downloadBtn.classList.remove("pulse");
if (lastOutputBlobUrl){ URL.revokeObjectURL(lastOutputBlobUrl); lastOutputBlobUrl=null; }
canvas.toBlob((blob)=>{
if (!blob) return;
lastOutputBlobUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
let baseName = uploadedFileName || "output.png";
let dot = baseName.lastIndexOf(".");
if (dot > 0) {
a.download = baseName.slice(0, dot) + "-PixelGrid" + baseName.slice(dot);
} else {
a.download = baseName + "-PixelGrid.png";
}
a.href = lastOutputBlobUrl;
document.body.appendChild(a);
a.click();
a.remove();
}, "image/png");
});
function setPreviewZoomDisplay(w, h) {
// Default: no zoom – use intrinsic size
let scale = 1;
// Heuristic: if small (e.g., ≤128px on the shorter side), zoom until ≈256px
const minDim = Math.min(w, h);
if (minDim <= 128) {
scale = Math.floor(256 / Math.max(1, minDim));
scale = Math.max(scale, 2); // at least 2×
scale = Math.min(scale, 12); // sanity cap
}
if (scale === 1) {
// Clear any previous explicit sizing
canvas.style.width = "";
canvas.style.height = "";
} else {
canvas.style.width = (w * scale) + "px";
canvas.style.height = (h * scale) + "px";
}
}
// --- Seeded PRNG: Mulberry32 (fast, decent for ordering) ---
function mulberry32(seed) {
let t = seed >>> 0;
return function() {
t += 0x6D2B79F5;
let x = t;
x = Math.imul(x ^ (x >>> 15), 1 | x);
x ^= x + Math.imul(x ^ (x >>> 7), 61 | x);
return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
};
}
// --- Fisher–Yates shuffle using provided RNG in [0,1) ---
function shuffleInPlace(arr, rand) {
for (let i = arr.length - 1; i > 0; i--) {
const j = (rand() * (i + 1)) | 0;
const tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
}
}