Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1474 lines (1348 loc) · 48.2 KB
/
Copy pathapp.js
File metadata and controls
1474 lines (1348 loc) · 48.2 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
import {
BLANK,
COLORS,
MODES,
TIMING,
colorAt,
colorHex,
decodePalette,
encodePalette,
modeTimeline,
planProgramming,
} from "./lib/void.js";
const STORAGE_KEY = "voidstar-programmer:v1";
const PRESETS = [
{ name: "Squid", palette: [16, 27, 34] },
{ name: "Fire", palette: [24, 28, 29] },
{ name: "Ocean", palette: [10, 6, 32] },
{ name: "Galaxy", palette: [18, 13, 9] },
{ name: "Aurora", palette: [4, 5, 17] },
{ name: "Sunset", palette: [29, 21, 18] },
{ name: "Neon", palette: [27, 13, 8] },
{ name: "Ice", palette: [25, 32, 34] },
{ name: "Duo", palette: [22, 7, BLANK] },
];
const LEAD_IN_BEATS = 2;
const STARS = [
{ id: "moon-vortex", name: "Moon Vortex", front: "stars/moon-vortex-8.png", back: "stars/moon-vortex-16.png" },
{ id: "sherbet", name: "Rainbow Sherbet", front: "stars/sherbet-8.png", back: "stars/sherbet-16.png" },
{ id: "mandela", name: "Mandela Dreams", front: "stars/mandela-8.png", back: "stars/mandela-16.png" },
];
const LEGACY_STARS = {
"moon-vortex-8": ["moon-vortex", "front"],
"moon-vortex-16": ["moon-vortex", "back"],
"sherbet-8": ["sherbet", "front"],
"sherbet-16": ["sherbet", "back"],
"mandela-8": ["mandela", "front"],
"mandela-16": ["mandela", "back"],
};
const $ = (id) => document.getElementById(id);
const asPalette = (p) => (Array.isArray(p) ? decodePalette(p.join("-")) : null);
const colorName = (id) => (id === BLANK ? "#1 Blank" : `#${id}`);
const modeName = (id) => `${id} ${MODES.find((m) => m.id === id)?.name ?? ""}`.trim();
const USER_ICON = "M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0";
const FLIP_ICON = "M4 8h13l-3-3M20 16H7l3 3";
const isDark = (hex) => {
const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
return 0.2126 * r + 0.7152 * g + 0.0722 * b < 110;
};
const LIGHT_COUNT = 8;
const IDEA_NAME_MAX = 24;
const state = loadState();
function loadState() {
const defaults = {
palette: PRESETS[0].palette,
mode: MODES.find((m) => m.name === "Smooth Cycle").id,
star: "moon-vortex",
face: "front",
settings: { startColor: BLANK, carryOver: false, tempo: 2, sound: true, handsFree: true },
};
let stored = {};
try {
stored = JSON.parse(localStorage.getItem(STORAGE_KEY)) ?? {};
} catch {}
const fromHash = decodePalette(new URLSearchParams(location.hash.slice(1)).get("p") ?? "");
const palette = asPalette(stored.palette) ?? defaults.palette;
const mode = MODES.some((m) => m.id === stored.mode) ? stored.mode : defaults.mode;
const storedLights = Array.isArray(stored.lights) ? stored.lights : [];
const lights = Array.from({ length: LIGHT_COUNT }, (_, i) => {
const saved = storedLights[i];
const savedPalette = asPalette(saved?.palette);
const savedMode = MODES.some((m) => m.id === saved?.mode) ? saved.mode : null;
return {
palette: savedPalette ? [...savedPalette] : [...palette],
mode: savedMode ?? mode,
};
});
const selectedLight = Number.isInteger(stored.selectedLight) && stored.selectedLight >= 0 && stored.selectedLight < LIGHT_COUNT
? stored.selectedLight
: 0;
const programAll = stored.programAll !== false;
let allProgram = readProgram(stored.allProgram);
if (fromHash) {
if (programAll) {
allProgram = {
palette: [...fromHash],
mode: allProgram?.mode ?? lights[selectedLight].mode,
};
} else {
lights[selectedLight].palette = [...fromHash];
}
} else if (programAll && !allProgram) {
allProgram = { palette: [...lights[selectedLight].palette], mode: lights[selectedLight].mode };
}
const active = programAll ? allProgram : lights[selectedLight];
return {
lights,
selectedLight,
allProgram,
palette: [...active.palette],
mode: active.mode,
varySpin: stored.varySpin === true,
ledsOn: stored.ledsOn !== false,
programAll,
applyAll: stored.applyAll === true,
savedIdeas: readIdeas(stored.savedIdeas) ?? [],
...storedStar(stored, defaults),
settings: { ...defaults.settings, ...stored.settings },
activeSlot: 0,
};
}
function readProgram(saved) {
const palette = asPalette(saved?.palette);
const mode = MODES.some((m) => m.id === saved?.mode) ? saved.mode : null;
return palette && mode ? { palette: [...palette], mode } : null;
}
function readIdea(saved) {
const name = typeof saved?.name === "string" ? saved.name.trim() : "";
const program = readProgram(saved);
if (!name || name.length > IDEA_NAME_MAX || !program) return null;
return { name, ...program };
}
function readIdeas(saved) {
if (!Array.isArray(saved)) return null;
const ideas = saved.map(readIdea);
return ideas.every(Boolean) ? ideas : null;
}
function storedStar(stored, defaults) {
const legacy = LEGACY_STARS[stored.star];
const star = legacy?.[0] ?? (STARS.some((s) => s.id === stored.star) ? stored.star : defaults.star);
const face = stored.face === "back" || stored.face === "front"
? stored.face
: legacy?.[1] ?? defaults.face;
return { star, face };
}
function syncActiveProgram() {
const program = { palette: [...state.palette], mode: state.mode };
if (state.programAll) state.allProgram = program;
else state.lights[state.selectedLight] = program;
}
function persist() {
syncActiveProgram();
const { lights, selectedLight, allProgram, palette, mode, varySpin, ledsOn, star, face, settings, programAll, applyAll, savedIdeas } = state;
const saved = { lights, selectedLight, palette, mode, varySpin, ledsOn, star, face, settings, programAll, applyAll, savedIdeas };
if (allProgram) saved.allProgram = { palette: [...allProgram.palette], mode: allProgram.mode };
localStorage.setItem(STORAGE_KEY, JSON.stringify(saved));
history.replaceState(null, "", `#p=${encodePalette(palette)}`);
}
const SETTINGS_HISTORY_LIMIT = 50;
const settingsHistory = { past: [], future: [] };
let isEditingSettings = false;
function copySettings() {
return {
lights: state.lights.map((light) => ({ palette: [...light.palette], mode: light.mode })),
selectedLight: state.selectedLight,
allProgram: state.allProgram
? { palette: [...state.allProgram.palette], mode: state.allProgram.mode }
: null,
palette: [...state.palette],
mode: state.mode,
programAll: state.programAll,
applyAll: state.applyAll,
activeSlot: state.activeSlot,
savedIdeas: state.savedIdeas.map((idea) => ({ name: idea.name, palette: [...idea.palette], mode: idea.mode })),
};
}
function sameSettings(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
function editSettings(change) {
if (isEditingSettings) {
change();
return;
}
const before = copySettings();
isEditingSettings = true;
try {
change();
} finally {
isEditingSettings = false;
}
if (sameSettings(before, copySettings())) return;
settingsHistory.past.push(before);
if (settingsHistory.past.length > SETTINGS_HISTORY_LIMIT) settingsHistory.past.shift();
settingsHistory.future = [];
renderHistory();
}
function restoreSettings(snapshot) {
state.lights = snapshot.lights.map((light) => ({ palette: [...light.palette], mode: light.mode }));
state.selectedLight = snapshot.selectedLight;
state.allProgram = snapshot.allProgram
? { palette: [...snapshot.allProgram.palette], mode: snapshot.allProgram.mode }
: null;
state.palette = [...snapshot.palette];
state.mode = snapshot.mode;
state.programAll = snapshot.programAll;
state.applyAll = snapshot.applyAll;
state.activeSlot = snapshot.activeSlot;
state.savedIdeas = snapshot.savedIdeas.map((idea) => ({ name: idea.name, palette: [...idea.palette], mode: idea.mode }));
persist();
rebuildTimeline();
render();
}
function undo() {
const snapshot = settingsHistory.past.pop();
if (!snapshot) return;
settingsHistory.future.push(copySettings());
restoreSettings(snapshot);
}
function redo() {
const snapshot = settingsHistory.future.pop();
if (!snapshot) return;
settingsHistory.past.push(copySettings());
restoreSettings(snapshot);
}
function renderHistory() {
$("undo").disabled = settingsHistory.past.length === 0;
$("redo").disabled = settingsHistory.future.length === 0;
}
$("undo").addEventListener("click", undo);
$("redo").addEventListener("click", redo);
document.addEventListener("keydown", (event) => {
const target = event.target;
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) return;
if (target instanceof HTMLElement && target.isContentEditable) return;
if ($("coach").open || $("idea-dialog").open) return;
const meta = event.metaKey || event.ctrlKey;
if (!meta || event.altKey) return;
const key = event.key.toLowerCase();
if (key === "z") {
event.preventDefault();
if (event.shiftKey) redo();
else undo();
} else if (key === "y") {
event.preventDefault();
redo();
}
});
function el(tag, props = {}, children = []) {
const node = Object.assign(document.createElement(tag), props);
node.append(...children);
return node;
}
function swatch(id, className = "swatch") {
const node = el("span", { className });
if (id === BLANK) node.classList.add("blank");
else node.style.background = colorHex(id);
return node;
}
function paletteDots(palette) {
return palette.map((id) => swatch(id, "chip-dot"));
}
// ---------- Palette ----------
const slotButtons = [0, 1, 2].map((slot) => {
const button = el("button", { type: "button", className: "slot" });
button.addEventListener("click", () => {
state.activeSlot = slot;
render();
});
return button;
});
$("slots").append(...slotButtons);
function buildChart(container, onPick) {
return COLORS.map(({ id, hex }) => {
const button = el("button", {
type: "button",
textContent: String(id),
ariaLabel: id === BLANK ? "Color 1, blank" : `Color ${id}`,
});
if (hex) {
button.style.background = hex;
if (isDark(hex)) button.style.color = "#fff";
} else button.classList.add("swatch", "blank");
button.addEventListener("click", () => onPick(id));
container.append(button);
return button;
});
}
const chartButtons = buildChart($("chart"), (id) => {
editSettings(() => {
const slot = state.activeSlot;
state.palette = state.palette.with(slot, id);
state.activeSlot = (slot + 1) % 3;
paletteChanged({ slot });
if (slot === 2) selectLight((state.selectedLight + 1) % LIGHT_COUNT);
});
});
function mirrorProgram({ palette = false, mode = false, slot = null } = {}) {
if (state.programAll || !state.applyAll) return;
for (const light of state.lights) {
if (slot != null) light.palette[slot] = state.palette[slot];
else if (palette) light.palette = [...state.palette];
if (mode) light.mode = state.mode;
}
}
function paletteChanged(fields) {
mirrorProgram(fields);
persist();
rebuildTimeline();
render();
}
function randomProgram() {
const colorId = () => COLORS[Math.floor(Math.random() * COLORS.length)].id;
const mode = MODES[Math.floor(Math.random() * MODES.length)].id;
return { palette: [colorId(), colorId(), colorId()], mode };
}
function randomizeLights() {
editSettings(() => {
if (state.programAll) {
const program = randomProgram();
state.palette = program.palette;
state.mode = program.mode;
paletteChanged({ palette: true, mode: true });
return;
}
for (const light of state.lights) {
const program = randomProgram();
light.palette = program.palette;
light.mode = program.mode;
}
const current = state.lights[state.selectedLight];
state.palette = [...current.palette];
state.mode = current.mode;
persist();
rebuildTimeline();
render();
});
}
$("random-program").addEventListener("click", randomizeLights);
function renderPalette() {
slotButtons.forEach((button, slot) => {
const id = state.palette[slot];
button.setAttribute("aria-pressed", String(slot === state.activeSlot));
button.replaceChildren(
el("span", { className: "label", textContent: `Color ${slot + 1}` }),
swatch(id),
el("span", { className: "value", textContent: colorName(id) }),
);
});
const current = state.palette[state.activeSlot];
chartButtons.forEach((b, i) => b.setAttribute("aria-pressed", String(i + 1 === current)));
const samePalette = (palette) => palette.every((id, i) => id === state.palette[i]);
$("presets").replaceChildren(
...PRESETS.map(({ name, palette }) => {
const chip = el("button", { type: "button", className: "chip" }, [
...paletteDots(palette),
el("span", { className: "chip-name", textContent: name }),
]);
chip.setAttribute("aria-pressed", String(samePalette(palette)));
chip.addEventListener("click", () => {
editSettings(() => {
state.palette = palette;
paletteChanged({ palette: true });
});
});
return chip;
}),
...state.savedIdeas.map(({ name, palette, mode }) => {
const chip = el("button", {
type: "button",
className: "chip",
ariaLabel: `${name}, your idea, ${modeName(mode)}`,
title: `${name} · ${modeName(mode)}`,
}, [
...paletteDots(palette),
el("span", { className: "chip-name", textContent: name }),
strokeIcon(USER_ICON),
]);
chip.setAttribute("aria-pressed", String(samePalette(palette) && mode === state.mode));
chip.addEventListener("click", () => {
editSettings(() => {
state.palette = [...palette];
state.mode = mode;
paletteChanged({ palette: true, mode: true });
});
});
return chip;
}),
);
lightButtons.forEach((button, i) => button.setAttribute("aria-pressed", String(i === state.selectedLight)));
}
function selectLight(i) {
if (state.programAll || i === state.selectedLight) return;
state.lights[state.selectedLight] = { palette: [...state.palette], mode: state.mode };
state.selectedLight = i;
state.palette = [...state.lights[i].palette];
state.mode = state.lights[i].mode;
persist();
rebuildTimeline();
render();
}
const lightButtons = Array.from({ length: LIGHT_COUNT }, (_, i) => {
const button = el("button", { type: "button", textContent: String(i + 1), ariaLabel: `Light ${i + 1}` });
button.addEventListener("click", () => editSettings(() => selectLight(i)));
$("lights").append(button);
return button;
});
function setProgramAll(programAll) {
editSettings(() => {
if (state.programAll === programAll) return;
syncActiveProgram();
state.programAll = programAll;
if (programAll && !state.allProgram) {
const source = state.lights[state.selectedLight];
state.allProgram = { palette: [...source.palette], mode: source.mode };
}
const active = programAll ? state.allProgram : state.lights[state.selectedLight];
state.palette = [...active.palette];
state.mode = active.mode;
persist();
rebuildTimeline();
render();
});
}
$("program-all").addEventListener("click", () => setProgramAll(true));
$("program-individual").addEventListener("click", () => setProgramAll(false));
function renderProgramScope() {
$("program-all").setAttribute("aria-pressed", String(state.programAll));
$("program-individual").setAttribute("aria-pressed", String(!state.programAll));
$("lights").hidden = state.programAll;
$("apply-all").checked = state.applyAll;
$("apply-all-label").hidden = state.programAll;
}
$("apply-all").addEventListener("change", () => {
editSettings(() => {
state.applyAll = $("apply-all").checked;
persist();
});
});
// ---------- Preview ----------
const canvas = $("preview");
const ctx = canvas.getContext("2d");
const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
let timeline;
let playing = !reducedMotion;
let lastFrame = performance.now();
let timelines = [];
function rebuildTimeline() {
syncActiveProgram();
if (state.programAll) {
const shared = modeTimeline(state.allProgram.mode, state.allProgram.palette);
timelines = Array.from({ length: LIGHT_COUNT }, () => shared);
timeline = shared;
return;
}
timelines = state.lights.map((light) => modeTimeline(light.mode, light.palette));
timeline = timelines[state.selectedLight];
}
function pocketHex(index, t) {
return colorAt(timelines[index] ?? timeline, t);
}
function resizeCanvas() {
const dpr = Math.min(window.devicePixelRatio || 1, 1.5);
canvas.width = Math.round(canvas.clientWidth * dpr);
canvas.height = Math.round(canvas.clientHeight * dpr);
}
new ResizeObserver(resizeCanvas).observe(canvas);
const TAU = 2 * Math.PI;
const FLOWSTAR_SPIN_MS = 800;
// A hand-spun flowstar runs about 0.9 to 2.5 turns per second.
const SPIN_VERY_FAST_MS = 400;
const SPIN_VERY_SLOW_MS = 1100;
const SPIN_VARY_CYCLE_MS = 16000;
let spinAngle = 0;
let spinTime = 0;
function spinPeriod(t) {
if (!state.varySpin) return FLOWSTAR_SPIN_MS;
const wave = (1 - Math.cos((t / SPIN_VARY_CYCLE_MS) * TAU)) / 2;
const fast = Math.log(SPIN_VERY_FAST_MS);
const slow = Math.log(SPIN_VERY_SLOW_MS);
return Math.exp(fast + (slow - fast) * wave);
}
function spinAt(t) {
if (!spinTime) spinTime = t;
const dt = t - spinTime;
if (dt > 0) {
spinTime = t;
spinAngle += (Math.min(50, dt) / spinPeriod(t)) * TAU;
}
return spinAngle;
}
// Tips sit this far from the image center, as a fraction of half the image.
const STAR_TIP = 0.88;
// Opaque tip and inner notch, as a fraction of the drawn image half.
const IMAGE_TIP = 0.905;
const IMAGE_VALLEY = 0.7;
function currentStar() {
return STARS.find((s) => s.id === state.star) ?? STARS[0];
}
const starImages = new Map(STARS.flatMap((star) => ["front", "back"].map((face) => {
const img = new Image();
img.src = star[face];
return [`${star.id}:${face}`, img];
})));
function flowstarPose(t, w, h) {
return {
cx: w / 2,
cy: h / 2,
spin: spinAt(t),
reach: Math.min(w, h) * 0.4,
};
}
function starPocket(cx, cy, angle, tipR, valleyR) {
const point = (r, a) => [cx + r * Math.cos(a), cy + r * Math.sin(a)];
const tip = point(tipR, angle);
const left = point(valleyR, angle - Math.PI / 8);
const right = point(valleyR, angle + Math.PI / 8);
return {
tip,
left,
right,
mid: [(tip[0] + left[0] + right[0]) / 3, (tip[1] + left[1] + right[1]) / 3],
};
}
function pocketAngle(spin, index) {
return spin - Math.PI / 2 + (index / 8) * TAU;
}
function pocketLed(pocket) {
const [mx, my] = pocket.mid;
const [tx, ty] = pocket.tip;
return [mx + (tx - mx) * 0.4, my + (ty - my) * 0.4];
}
const FABRIC = 480;
const fabric = document.createElement("canvas");
const lightMap = document.createElement("canvas");
fabric.width = lightMap.width = FABRIC;
fabric.height = lightMap.height = FABRIC;
const fabricCtx = fabric.getContext("2d");
const lightCtx = lightMap.getContext("2d");
const preparedStars = new Map();
function starKey() {
return `${currentStar().id}:${state.face === "back" ? "back" : "front"}`;
}
function preparedStar() {
const key = starKey();
const cached = preparedStars.get(key);
if (cached) return cached;
const img = starImages.get(key);
if (!img?.complete || !img.naturalWidth) return null;
const probe = document.createElement("canvas");
probe.width = probe.height = FABRIC;
const probeCtx = probe.getContext("2d", { willReadFrequently: true });
probeCtx.drawImage(img, 0, 0, FABRIC, FABRIC);
const pixels = probeCtx.getImageData(0, 0, FABRIC, FABRIC).data;
const fitted = document.createElement("canvas");
fitted.width = fitted.height = FABRIC;
const fittedCtx = fitted.getContext("2d", { willReadFrequently: true });
fittedCtx.setTransform(...trueStarTransform(pixels));
fittedCtx.drawImage(probe, 0, 0);
const [mx, my] = massCenter(fittedCtx.getImageData(0, 0, FABRIC, FABRIC).data);
const copy = document.createElement("canvas");
copy.width = copy.height = FABRIC;
copy.getContext("2d").drawImage(fitted, FABRIC / 2 - mx, FABRIC / 2 - my);
preparedStars.set(key, copy);
return copy;
}
// Spinning about the silhouette's center of mass keeps it from orbiting,
// even where the photographed fabric is not perfectly regular.
function massCenter(pixels) {
let sum = 0;
let sx = 0;
let sy = 0;
for (let y = 0; y < FABRIC; y++) {
for (let x = 0; x < FABRIC; x++) {
const a = pixels[(y * FABRIC + x) * 4 + 3];
sum += a;
sx += a * (x + 0.5);
sy += a * (y + 0.5);
}
}
return sum ? [sx / sum, sy / sum] : [FABRIC / 2, FABRIC / 2];
}
function opaqueAt(pixels, x, y) {
const px = Math.round(x);
const py = Math.round(y);
if (px < 0 || py < 0 || px >= FABRIC || py >= FABRIC) return false;
return pixels[(py * FABRIC + px) * 4 + 3] > 128;
}
// Photos are slightly off-center and skewed, so the artwork orbits when spun.
// Find the 8 tips and fit the affine map that puts them on a regular star
// centered in the buffer; rotating that is a true spin about the star's center.
function trueStarTransform(pixels) {
let minX = FABRIC;
let minY = FABRIC;
let maxX = 0;
let maxY = 0;
for (let y = 0; y < FABRIC; y += 2) {
for (let x = 0; x < FABRIC; x += 2) {
if (opaqueAt(pixels, x, y)) {
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
}
}
const ox = (minX + maxX) / 2;
const oy = (minY + maxY) / 2;
const shift = [1, 0, 0, 1, FABRIC / 2 - ox, FABRIC / 2 - oy];
if (maxX <= minX) return shift;
const tips = [];
for (let i = 0; i < 8; i++) {
const center = pocketAngle(0, i);
let best = null;
for (let step = -40; step <= 40; step++) {
const a = center + (step / 40) * (Math.PI / 8);
let r = FABRIC / 2;
while (r > 0 && !opaqueAt(pixels, ox + r * Math.cos(a), oy + r * Math.sin(a))) r -= 0.5;
if (!best || r > best.r) best = { r, x: ox + r * Math.cos(a), y: oy + r * Math.sin(a) };
}
tips.push(best);
}
const radius = tips.reduce((sum, tip) => sum + Math.hypot(tip.x - ox, tip.y - oy), 0) / 8;
const targets = tips.map((_, i) => [
FABRIC / 2 + radius * Math.cos(pocketAngle(0, i)),
FABRIC / 2 + radius * Math.sin(pocketAngle(0, i)),
]);
const rowX = solveAffineRow(tips, targets.map((t) => t[0]));
const rowY = solveAffineRow(tips, targets.map((t) => t[1]));
if (!rowX || !rowY) return shift;
return [rowX[0], rowY[0], rowX[1], rowY[1], rowX[2], rowY[2]];
}
// Least squares for out = a*x + b*y + c over the tip points.
function solveAffineRow(points, out) {
const m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
const v = [0, 0, 0];
points.forEach(({ x, y }, i) => {
const row = [x, y, 1];
for (let r = 0; r < 3; r++) {
v[r] += row[r] * out[i];
for (let c = 0; c < 3; c++) m[r][c] += row[r] * row[c];
}
});
for (let col = 0; col < 3; col++) {
let pivot = col;
for (let r = col + 1; r < 3; r++) if (Math.abs(m[r][col]) > Math.abs(m[pivot][col])) pivot = r;
if (Math.abs(m[pivot][col]) < 1e-9) return null;
[m[col], m[pivot]] = [m[pivot], m[col]];
[v[col], v[pivot]] = [v[pivot], v[col]];
for (let r = 0; r < 3; r++) {
if (r === col) continue;
const f = m[r][col] / m[col][col];
for (let c = col; c < 3; c++) m[r][c] -= f * m[col][c];
v[r] -= f * v[col];
}
}
return v.map((value, i) => value / m[i][i]);
}
function rgb(hex) {
return [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
}
// Light scattered through cloth from a point source: I(d) ~ 1 / (1 + (d/d0)^2),
// windowed to reach zero at the gradient edge.
function scatter(t, d0) {
return (1 / (1 + (t / d0) ** 2)) * (1 - t * t) ** 2;
}
const IRRADIANCE_STOPS = [0, 0.03, 0.08, 0.15, 0.25, 0.4, 0.6, 0.8, 1];
// Light landing on the fabric. Additive so neighboring LEDs mix like real light.
function irradiate(ctx, x, y, radius, hex, gain) {
const [r, g, b] = rgb(hex);
const grad = ctx.createRadialGradient(x, y, 0, x, y, radius);
for (const t of IRRADIANCE_STOPS) {
const k = gain * scatter(t, 0.1);
grad.addColorStop(t, `rgb(${Math.min(255, r * k)},${Math.min(255, g * k)},${Math.min(255, b * k)})`);
}
ctx.fillStyle = grad;
ctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
}
// Soft radial glow with alpha stops [t, alpha], tinted toward white near the core.
function glow(ctx, x, y, radius, hex, stops, whiteCore = 0) {
const [r, g, b] = rgb(hex);
const grad = ctx.createRadialGradient(x, y, 0, x, y, radius);
for (const [t, a] of stops) {
const w = whiteCore * Math.max(0, 1 - t / 0.12);
const mix = (c) => Math.round(c + (255 - c) * w);
grad.addColorStop(t, `rgba(${mix(r)},${mix(g)},${mix(b)},${a})`);
}
ctx.fillStyle = grad;
ctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
}
// Light leaking out of the translucent pocket into the air behind the star.
const HALO = [[0, 0.55], [0.12, 0.32], [0.3, 0.13], [0.55, 0.04], [0.8, 0.01], [1, 0]];
// The pocket itself glowing as light transmits through it.
const POCKET = [[0, 0.9], [0.08, 0.75], [0.25, 0.42], [0.5, 0.18], [0.8, 0.07], [1, 0.03]];
// Glare in the eye or camera from the bright pocket, in front of the star.
const GLARE = [[0, 0.5], [0.05, 0.3], [0.15, 0.12], [0.35, 0.04], [0.65, 0.01], [1, 0]];
// The LED seen through the pocket cloth: a diffused hot spot, overexposed toward white.
const CORE = [[0, 0.95], [0.2, 0.7], [0.5, 0.25], [1, 0]];
function drawFlowstarBody(c, t, w, h) {
const print = preparedStar();
if (!print) return;
const { cx, cy, spin, reach } = flowstarPose(t, w, h);
const half = Math.round(reach / STAR_TIP);
const ledsOn = state.ledsOn;
const size = half * 2;
const drawFabric = () => {
c.save();
c.translate(cx, cy);
c.rotate(spin);
c.drawImage(fabric, -size / 2, -size / 2, size, size);
c.restore();
};
fabricCtx.globalCompositeOperation = "source-over";
fabricCtx.clearRect(0, 0, FABRIC, FABRIC);
fabricCtx.drawImage(print, 0, 0);
if (!ledsOn) {
drawFabric();
return;
}
const lit = [];
for (let i = 0; i < 8; i++) {
const color = pocketHex(i, t);
if (color) lit.push([i, color]);
}
// The print only shows where light lands on it.
const origin = FABRIC / 2;
lightCtx.globalCompositeOperation = "source-over";
lightCtx.fillStyle = "#040406";
lightCtx.fillRect(0, 0, FABRIC, FABRIC);
lightCtx.globalCompositeOperation = "lighter";
for (const [i, color] of lit) {
const pocket = starPocket(origin, origin, pocketAngle(0, i), IMAGE_TIP * origin, IMAGE_VALLEY * origin);
const [x, y] = pocketLed(pocket);
irradiate(lightCtx, x, y, origin * 0.85, color, 1.7);
}
lightCtx.globalCompositeOperation = "source-over";
fabricCtx.globalCompositeOperation = "multiply";
fabricCtx.drawImage(lightMap, 0, 0);
fabricCtx.globalCompositeOperation = "destination-in";
fabricCtx.drawImage(print, 0, 0);
fabricCtx.globalCompositeOperation = "source-over";
const tipR = IMAGE_TIP * half;
const valleyR = IMAGE_VALLEY * half;
const pockets = lit.map(([i, color]) => {
const pocket = starPocket(cx, cy, pocketAngle(spin, i), tipR, valleyR);
return { pocket, color, led: pocketLed(pocket) };
});
c.save();
c.globalCompositeOperation = "lighter";
for (const { color, led: [x, y] } of pockets) glow(c, x, y, half * 0.62, color, HALO);
c.restore();
drawFabric();
c.save();
c.globalCompositeOperation = "lighter";
for (const { pocket, color, led: [x, y] } of pockets) {
const span = Math.hypot(pocket.left[0] - x, pocket.left[1] - y);
c.save();
clipPocket(c, pocket);
glow(c, x, y, span, color, POCKET, 0.5);
c.restore();
glow(c, x, y, half * 0.5, color, GLARE);
glow(c, x, y, half * 0.09, color, CORE, 0.85);
}
c.restore();
}
function clipPocket(ctx, pocket) {
ctx.beginPath();
ctx.moveTo(pocket.tip[0], pocket.tip[1]);
ctx.lineTo(pocket.left[0], pocket.left[1]);
ctx.lineTo(pocket.right[0], pocket.right[1]);
ctx.closePath();
ctx.clip();
}
function drawFrame(now) {
const { width: w, height: h } = canvas;
if (!w || !h) {
lastFrame = now;
if (playing) requestAnimationFrame(drawFrame);
return;
}
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, w, h);
drawFlowstarBody(ctx, now, w, h);
lastFrame = now;
if (playing) requestAnimationFrame(drawFrame);
}
function startPreview() {
lastFrame = performance.now();
if (playing) requestAnimationFrame(drawFrame);
else drawFrame(lastFrame);
}
function strokeIcon(d) {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("class", "icon");
svg.setAttribute("aria-hidden", "true");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", d);
path.setAttribute("fill", "none");
path.setAttribute("stroke", "currentColor");
path.setAttribute("stroke-width", "2");
path.setAttribute("stroke-linecap", "round");
path.setAttribute("stroke-linejoin", "round");
svg.append(path);
return svg;
}
function renderPause() {
const button = $("pause");
const label = playing ? "Pause" : "Play";
const icon = playing ? "M9 4v16M15 4v16" : "M8 5v14l11-7z";
button.replaceChildren(strokeIcon(icon), label);
button.setAttribute("aria-pressed", String(!playing));
}
$("pause").addEventListener("click", () => {
playing = !playing;
renderPause();
if (playing) startPreview();
});
renderPause();
$("logo").addEventListener("click", () => location.reload());
$("vary-speed").addEventListener("click", () => {
state.varySpin = !state.varySpin;
persist();
render();
});
function renderVarySpeed() {
$("vary-speed").setAttribute("aria-pressed", String(state.varySpin));
}
$("leds").addEventListener("click", () => {
state.ledsOn = !state.ledsOn;
persist();
render();
if (!playing) drawFrame(lastFrame);
});
function renderLeds() {
$("leds").setAttribute("aria-pressed", String(state.ledsOn));
}
const previewWrap = document.querySelector(".preview-wrap");
function fullscreenTarget() {
return document.fullscreenElement || document.webkitFullscreenElement || null;
}
function renderFullscreen() {
const on = fullscreenTarget() === previewWrap;
const button = $("fullscreen");
const icon = on ? "M3 9h6V3M15 3v6h6M9 21v-6H3M21 15h-6v6" : "M8 3H3v5M16 3h5v5M3 16v5h5M21 16v5h-5";
button.replaceChildren(strokeIcon(icon), on ? "Exit full screen" : "Full screen");
button.setAttribute("aria-pressed", String(on));
requestAnimationFrame(resizeCanvas);
}
$("fullscreen").addEventListener("click", () => {
if (fullscreenTarget()) {
const exit = document.exitFullscreen || document.webkitExitFullscreen;
exit.call(document);
return;
}
const request = previewWrap.requestFullscreen || previewWrap.webkitRequestFullscreen;
const pending = request.call(previewWrap);
if (pending && typeof pending.catch === "function") pending.catch(() => {});
});
document.addEventListener("fullscreenchange", renderFullscreen);
document.addEventListener("webkitfullscreenchange", renderFullscreen);
renderFullscreen();
$("flip").addEventListener("click", () => {
state.face = state.face === "back" ? "front" : "back";
persist();
render();
if (!playing) drawFrame(lastFrame);
});
function renderStars() {
const side = state.face === "back" ? "Back" : "Front";
const flip = $("flip");
flip.replaceChildren(strokeIcon(FLIP_ICON), "Flip");
flip.title = `Show the ${state.face === "back" ? "front" : "back"}`;
const row = el("div", { className: "star-row" });
for (const star of STARS) {
const button = el("button", {
type: "button",
className: "star",
ariaLabel: `${star.name}, ${side}`,
});
button.setAttribute("aria-pressed", String(star.id === state.star));
button.append(
el("img", { src: star[state.face === "back" ? "back" : "front"], alt: "" }),
el("span", { textContent: star.name }),
);
button.addEventListener("click", () => {
state.star = star.id;
persist();
render();
if (!playing) drawFrame(lastFrame);
});
row.append(button);
}
$("stars").replaceChildren(row);
}
// ---------- Saved ideas ----------
const ideaDialog = $("idea-dialog");
$("save-idea").addEventListener("click", () => {
$("idea-name").value = "";
$("idea-colors").replaceChildren(
...state.palette.map((id, slot) => el("figure", {}, [
swatch(id),
el("figcaption", { textContent: `Color ${slot + 1} · ${colorName(id)}` }),
])),
);
$("idea-mode").replaceChildren(
"Mode: ",
el("span", { className: "n", textContent: String(state.mode) }),
` ${MODES.find((m) => m.id === state.mode)?.name ?? ""}`,
);
ideaDialog.showModal();
$("idea-name").focus();
});
$("idea-cancel").addEventListener("click", () => ideaDialog.close());
$("idea-form").addEventListener("submit", (event) => {
event.preventDefault();
const idea = readIdea({ name: $("idea-name").value, palette: state.palette, mode: state.mode });
if (!idea) {
$("idea-name").reportValidity();
return;
}
editSettings(() => {
state.savedIdeas = [...state.savedIdeas, idea];