topotopo 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +61 -12
  2. package/dist/cli.js +161 -23
  3. package/dist/graph/engine.js +18 -1
  4. package/dist/graph/params.d.ts +7 -1
  5. package/dist/graph/params.js +21 -8
  6. package/dist/graph/types.d.ts +28 -2
  7. package/dist/host/artifacts.d.ts +21 -0
  8. package/dist/host/artifacts.js +58 -0
  9. package/dist/host/export-targets.d.ts +33 -0
  10. package/dist/host/export-targets.js +84 -0
  11. package/dist/host/export_scene.py +200 -0
  12. package/dist/host/node.d.ts +8 -0
  13. package/dist/host/node.js +114 -0
  14. package/dist/host/types.d.ts +5 -0
  15. package/dist/inspect.js +5 -2
  16. package/dist/io/common.d.ts +6 -0
  17. package/dist/io/export.js +7 -4
  18. package/dist/io/gltf.d.ts +1 -1
  19. package/dist/io/gltf.js +167 -32
  20. package/dist/io/heightmap.d.ts +1 -1
  21. package/dist/io/import.d.ts +2 -2
  22. package/dist/io/import.js +10 -3
  23. package/dist/io/png-decode.d.ts +5 -2
  24. package/dist/io/png-decode.js +10 -3
  25. package/dist/io/targets.d.ts +31 -0
  26. package/dist/io/targets.js +75 -0
  27. package/dist/io/textures.d.ts +31 -2
  28. package/dist/io/textures.js +66 -18
  29. package/dist/io/unreal.js +22 -5
  30. package/dist/mcp/docs.d.ts +9 -2
  31. package/dist/mcp/docs.js +126 -2
  32. package/dist/mcp/inputs.d.ts +28 -0
  33. package/dist/mcp/inputs.js +377 -0
  34. package/dist/mcp/server.js +4 -1
  35. package/dist/mcp/tools.d.ts +1 -1
  36. package/dist/mcp/tools.js +118 -51
  37. package/dist/nodes/code.js +34 -6
  38. package/dist/nodes/copy.js +14 -4
  39. package/dist/nodes/flow.js +136 -35
  40. package/dist/nodes/heightfield.js +67 -11
  41. package/dist/nodes/texture.d.ts +1 -1
  42. package/dist/nodes/texture.js +61 -5
  43. package/dist/render/options.js +2 -1
  44. package/dist/render/raster.d.ts +2 -0
  45. package/dist/render/raster.js +3 -3
  46. package/dist/render/texview.d.ts +9 -1
  47. package/dist/render/texview.js +43 -2
  48. package/dist/viewer/app/api.js +64 -0
  49. package/dist/viewer/app/camera.js +250 -0
  50. package/dist/viewer/app/export-popover.js +68 -0
  51. package/dist/viewer/app/grid.js +217 -0
  52. package/dist/viewer/app/guides.js +402 -0
  53. package/dist/viewer/app/image-view.js +114 -0
  54. package/dist/viewer/app/keymap.js +199 -0
  55. package/dist/viewer/app/layers.js +244 -0
  56. package/dist/viewer/app/main.js +646 -0
  57. package/dist/viewer/app/markers.js +206 -0
  58. package/dist/viewer/app/mesh.js +172 -0
  59. package/dist/viewer/app/outliner.js +225 -0
  60. package/dist/viewer/app/outputs.css +73 -0
  61. package/dist/viewer/app/outputs.js +240 -0
  62. package/dist/viewer/app/props.js +432 -0
  63. package/dist/viewer/app/scene.js +529 -0
  64. package/dist/viewer/app/select.js +153 -0
  65. package/dist/viewer/app/selection.js +79 -0
  66. package/dist/viewer/app/status.js +20 -0
  67. package/dist/viewer/app/style.css +173 -0
  68. package/dist/viewer/app/undo.js +49 -0
  69. package/dist/viewer/app/units.js +51 -0
  70. package/dist/viewer/app/vars.js +64 -0
  71. package/dist/viewer/index.html +67 -184
  72. package/dist/viewer/outputs.d.ts +54 -0
  73. package/dist/viewer/outputs.js +436 -0
  74. package/dist/viewer/server.d.ts +47 -1
  75. package/dist/viewer/server.js +480 -17
  76. package/dist/workspace.d.ts +60 -4
  77. package/dist/workspace.js +131 -5
  78. package/package.json +9 -3
  79. package/shelf/brick_wall.json +1 -1
  80. package/shelf/wall_segment.json +2 -2
@@ -0,0 +1,199 @@
1
+ // The keymap of docs/design/viewer.md section 9: one table of actions, four presets (TopoTopo, the default;
2
+ // Maya, Houdini, Blender). Each row carries the text the overlay prints per preset and the built actions' bindings:
3
+ // chord → action. Transform and snapping rows (phase 2) ship their text but no bindings, so a preset never changes
4
+ // shape later. Plain data and functions: the overlay is the only DOM code, and it runs only when called.
5
+
6
+ export const PRESETS = [
7
+ { id: 'topotopo', label: 'TopoTopo' },
8
+ { id: 'maya', label: 'Maya' },
9
+ { id: 'houdini', label: 'Houdini' },
10
+ { id: 'blender', label: 'Blender' },
11
+ ];
12
+ export const DEFAULT_PRESET = 'topotopo';
13
+
14
+ const place = { 'Shift+1': 'placeNull', 'Shift+2': 'placeCurve', 'Shift+3': 'placeArea', 'Shift+4': 'placeVolume' };
15
+ const curve = { Enter: 'finish', Backspace: 'removeLast', Esc: 'cancel' };
16
+
17
+ /**
18
+ * The rows of section 9 in order. `keys` binds key chords, `drag` mouse drags (L / M / R with modifiers); a row
19
+ * without bindings for a preset is not built yet (phase 2) or has none in that application.
20
+ */
21
+ export const ROWS = [
22
+ { label: 'tumble', maya: ['Alt + L drag', { drag: { 'Alt+L': 'tumble' } }], houdini: ['Space + L drag', { drag: { 'Space+L': 'tumble' } }], blender: ['M drag', { drag: { M: 'tumble' } }] },
23
+ { label: 'track', maya: ['Alt + M drag', { drag: { 'Alt+M': 'track' } }], houdini: ['Space + M drag', { drag: { 'Space+M': 'track' } }], blender: ['Shift + M drag', { drag: { 'Shift+M': 'track' } }] },
24
+ { label: 'dolly', maya: ['Alt + R drag, wheel', { drag: { 'Alt+R': 'dolly' } }], houdini: ['Space + R drag, wheel', { drag: { 'Space+R': 'dolly' } }], blender: ['Ctrl + M drag, wheel', { drag: { 'Ctrl+M': 'dolly' } }] },
25
+ { label: 'frame selection', maya: ['F', { keys: { F: 'frameSelection' } }], houdini: ['Space+G', { keys: { 'Space+G': 'frameSelection' } }], blender: ['Numpad .', { keys: { 'Numpad.': 'frameSelection' } }] },
26
+ { label: 'frame all', maya: ['A', { keys: { A: 'frameAll' } }], houdini: ['Space+H', { keys: { 'Space+H': 'frameAll' } }], blender: ['Home', { keys: { Home: 'frameAll' } }] },
27
+ { label: 'single / quad view', maya: ['Space (tap)', { keys: { Space: 'quad' } }], houdini: ['Space+B', { keys: { 'Space+B': 'quad' } }], blender: ['Ctrl+Alt+Q', { keys: { 'Ctrl+Alt+Q': 'quad' } }] },
28
+ { label: 'perspective', maya: ['Alt+1', { keys: { 'Alt+1': 'viewPersp' } }], houdini: ['Space+1', { keys: { 'Space+1': 'viewPersp' } }], blender: ['Numpad 5 (toggles with ortho)', { keys: { Numpad5: 'ortho' } }] },
29
+ {
30
+ label: 'top / front / right',
31
+ maya: ['Alt+2 / Alt+3 / Alt+4', { keys: { 'Alt+2': 'viewTop', 'Alt+3': 'viewFront', 'Alt+4': 'viewRight' } }],
32
+ houdini: ['Space+2 / Space+3 / Space+4', { keys: { 'Space+2': 'viewTop', 'Space+3': 'viewFront', 'Space+4': 'viewRight' } }],
33
+ blender: ['Numpad 7 / 1 / 3', { keys: { Numpad7: 'viewTop', Numpad1: 'viewFront', Numpad3: 'viewRight' } }],
34
+ },
35
+ { label: 'orthographic toggle', maya: ['O', { keys: { O: 'ortho' } }], houdini: ['O', { keys: { O: 'ortho' } }], blender: ['Numpad 5', { keys: { Numpad5: 'ortho' } }] },
36
+ { label: 'select mode', maya: ['Q', { keys: { Q: 'selectMode' } }], houdini: ['S', { keys: { S: 'selectMode' } }], blender: ['W', { keys: { W: 'selectMode' } }] },
37
+ { label: 'move / rotate / scale', phase: 2, maya: ['W / E / R'], houdini: ['T / R / E'], blender: ['G / R / S'] },
38
+ { label: 'snap to grid (held)', phase: 2, maya: ['X'], houdini: ['X'], blender: ['Ctrl (held, with the snap target set to grid)'] },
39
+ { label: 'snap to surface or curve (held)', phase: 2, maya: ['C'], houdini: ['C'], blender: ['Ctrl (target: surface)'] },
40
+ { label: 'snap to point (held)', phase: 2, maya: ['V'], houdini: ['V'], blender: ['Ctrl (target: point)'] },
41
+ { label: 'snapping on / off', phase: 2, maya: ['toolbar'], houdini: ['toolbar'], blender: ['Shift+Tab'] },
42
+ {
43
+ label: 'wire / shaded / shaded + wire',
44
+ maya: ['4 / 5 / 6', { keys: { 4: 'displayWire', 5: 'displayShaded', 6: 'displayShadedWire' } }],
45
+ houdini: ['W (cycles)', { keys: { W: 'displayCycle' } }],
46
+ blender: ['Shift+Z (wire toggle), Z (cycles)', { keys: { 'Shift+Z': 'wireToggle', Z: 'displayCycle' } }],
47
+ },
48
+ { label: 'place a null / curve / area / volume', maya: ['Shift+1 / 2 / 3 / 4', { keys: place }], houdini: ['Shift+1 / 2 / 3 / 4', { keys: place }], blender: ['Shift+1 / 2 / 3 / 4', { keys: place }] },
49
+ { label: 'finish a curve / remove its last point / cancel', maya: ['Enter / Backspace / Esc', { keys: curve }], houdini: ['Enter / Backspace / Esc', { keys: curve }], blender: ['Enter / Backspace / Esc', { keys: curve }] },
50
+ { label: 'delete the selection', maya: ['Delete', { keys: { Delete: 'delete' } }], houdini: ['Delete', { keys: { Delete: 'delete' } }], blender: ['X, Delete', { keys: { X: 'delete', Delete: 'delete' } }] },
51
+ {
52
+ label: 'undo / redo (guides and vars)',
53
+ maya: ['Ctrl+Z / Ctrl+Y (also Z / Shift+Z)', { keys: { 'Ctrl+Z': 'undo', 'Ctrl+Y': 'redo', Z: 'undo', 'Shift+Z': 'redo' } }],
54
+ houdini: ['Ctrl+Z / Ctrl+Y', { keys: { 'Ctrl+Z': 'undo', 'Ctrl+Y': 'redo' } }],
55
+ blender: ['Ctrl+Z / Ctrl+Shift+Z', { keys: { 'Ctrl+Z': 'undo', 'Ctrl+Shift+Z': 'redo' } }],
56
+ },
57
+ { label: 'hide the selection / show all', maya: ['H / Shift+H', { keys: { H: 'hide', 'Shift+H': 'showAll' } }], houdini: ['H / Shift+H', { keys: { H: 'hide', 'Shift+H': 'showAll' } }], blender: ['H / Alt+H', { keys: { H: 'hide', 'Alt+H': 'showAll' } }] },
58
+ { label: 'keymap overlay', maya: ['?', { keys: { '?': 'overlay' } }], houdini: ['?', { keys: { '?': 'overlay' } }], blender: ['?', { keys: { '?': 'overlay' } }] },
59
+ ];
60
+
61
+ // Editing shortcuts follow Maya; navigation is available without held modifiers.
62
+ const topo = {
63
+ tumble: ['Right drag (pan in orthographic)', { drag: { R: 'tumble' } }],
64
+ track: ['Middle drag', { drag: { M: 'track' } }],
65
+ dolly: ['Wheel toward cursor'],
66
+ perspective: ['1', { keys: { 1: 'viewPersp' } }],
67
+ 'top / front / right': ['2 / 3 / 4', { keys: { 2: 'viewTop', 3: 'viewFront', 4: 'viewRight' } }],
68
+ 'wire / shaded / shaded + wire': ['5 / 6 / 7', { keys: { 5: 'displayWire', 6: 'displayShaded', 7: 'displayShadedWire' } }],
69
+ };
70
+ for (const row of ROWS) row.topotopo = topo[row.label] ?? row.maya;
71
+
72
+ /** Every action a binding may name (main.js handles each). */
73
+ export const ACTIONS = [
74
+ 'tumble', 'track', 'dolly', 'frameSelection', 'frameAll', 'quad', 'viewPersp', 'viewTop', 'viewFront', 'viewRight', 'ortho',
75
+ 'selectMode', 'displayWire', 'displayShaded', 'displayShadedWire', 'displayCycle', 'wireToggle',
76
+ 'placeNull', 'placeCurve', 'placeArea', 'placeVolume', 'finish', 'removeLast', 'cancel',
77
+ 'delete', 'undo', 'redo', 'hide', 'showAll', 'overlay',
78
+ ];
79
+
80
+ const MODS = ['Ctrl', 'Alt', 'Shift', 'Space'];
81
+ /** A chord written as in ROWS ("ctrl+alt+q", "Space+G") in one spelling: modifiers in MODS order, then the key. */
82
+ export function canonical(chord) {
83
+ const parts = String(chord).split('+').map((s) => s.trim()).filter(Boolean);
84
+ // "Space" alone is the key (a tap); before another part it is the held modifier
85
+ const key = parts.pop() ?? '';
86
+ const mods = new Set(parts.map((p) => MODS.find((m) => m.toLowerCase() === p.toLowerCase()) ?? p));
87
+ for (const m of mods) if (!MODS.includes(m)) throw new Error(`unknown modifier "${m}" in "${chord}"`);
88
+ const k = key.length === 1 ? key.toUpperCase() : key;
89
+ return [...MODS.filter((m) => mods.has(m)), k].join('+');
90
+ }
91
+
92
+ /** The bindings of one preset: chord → action for keys and for drags. */
93
+ export function bindings(presetId) {
94
+ const keys = new Map(), drag = new Map();
95
+ for (const row of ROWS) {
96
+ const b = row[presetId]?.[1];
97
+ if (!b) continue;
98
+ for (const [c, a] of Object.entries(b.keys ?? {})) keys.set(canonical(c), a);
99
+ for (const [c, a] of Object.entries(b.drag ?? {})) drag.set(canonical(c), a);
100
+ }
101
+ return { keys, drag };
102
+ }
103
+ const cache = new Map();
104
+ const bound = (presetId) => { if (!cache.has(presetId)) cache.set(presetId, bindings(presetId)); return cache.get(presetId); };
105
+
106
+ /**
107
+ * The key part of a chord for a keyboard event: letters by the character typed (falling back to the physical key on
108
+ * other alphabets), digits and the numpad by the physical key, "?" whatever it takes to type it.
109
+ */
110
+ export function keyToken(e) {
111
+ const code = e.code ?? '', key = e.key ?? '';
112
+ if (code.startsWith('Numpad')) {
113
+ const rest = code.slice(6);
114
+ if (/^\d$/.test(rest)) return 'Numpad' + rest;
115
+ if (rest === 'Decimal') return 'Numpad.';
116
+ if (rest === 'Enter') return 'Enter';
117
+ return null;
118
+ }
119
+ // "?" by the character; Shift with the "/" key gives it on US layouts even when the event names only the key
120
+ if (key === '?' || (code === 'Slash' && e.shiftKey)) return '?';
121
+ if (/^Digit\d$/.test(code)) return code.slice(5);
122
+ if (/^[a-z]$/i.test(key)) return key.toUpperCase();
123
+ if (/^Key[A-Z]$/.test(code)) return code.slice(3);
124
+ if (key === ' ' || code === 'Space') return 'Space';
125
+ if (key === 'Escape') return 'Esc';
126
+ if (['Enter', 'Backspace', 'Delete', 'Home', 'Tab'].includes(key)) return key;
127
+ return null;
128
+ }
129
+
130
+ /** The canonical chord of a keyboard event; `space` is true while Space is held (Houdini's modifier). */
131
+ export function chordOf(e, space = false) {
132
+ const k = keyToken(e);
133
+ if (!k) return null;
134
+ const mods = [];
135
+ if (e.ctrlKey || e.metaKey) mods.push('Ctrl');
136
+ if (e.altKey) mods.push('Alt');
137
+ // typing "?" takes Shift on most layouts: the chord is "?" alone
138
+ if (e.shiftKey && k !== '?') mods.push('Shift');
139
+ if (space && k !== 'Space') mods.push('Space');
140
+ return [...mods, k].join('+');
141
+ }
142
+
143
+ /** The action a key press means in a preset, or null. */
144
+ export function matchKey(presetId, e, space = false) {
145
+ const c = chordOf(e, space);
146
+ return c ? bound(presetId).keys.get(c) ?? null : null;
147
+ }
148
+
149
+ /** The navigation a mouse drag starts in a preset (tumble, track, dolly), or null. `button` 0 / 1 / 2 = L / M / R. */
150
+ export function matchDrag(presetId, { button, altKey = false, ctrlKey = false, metaKey = false, shiftKey = false, space = false }) {
151
+ const b = ['L', 'M', 'R'][button];
152
+ if (!b) return null;
153
+ const mods = [];
154
+ if (ctrlKey || metaKey) mods.push('Ctrl');
155
+ if (altKey) mods.push('Alt');
156
+ if (shiftKey) mods.push('Shift');
157
+ if (space) mods.push('Space');
158
+ return bound(presetId).drag.get([...mods, b].join('+')) ?? null;
159
+ }
160
+
161
+ /** True when Space acts as a held modifier in the preset (Houdini) rather than as a key of its own. */
162
+ export const spaceIsModifier = (presetId) => [...bound(presetId).keys.keys(), ...bound(presetId).drag.keys()].some((c) => c.startsWith('Space+') || c.includes('+Space+'));
163
+
164
+ /** The overlay's table for a preset: [action label, binding text, built] per row of section 9. */
165
+ export function overlayRows(presetId) {
166
+ return ROWS.map((r) => ({ label: r.label, text: r[presetId]?.[0] ?? '', built: !r.phase }));
167
+ }
168
+
169
+ /** Show (or hide, when shown) the keymap overlay for a preset over `host`. Returns the overlay element or null. */
170
+ export function toggleOverlay(host, presetId) {
171
+ const old = host.querySelector('.keymap-overlay');
172
+ if (old) { old.remove(); return null; }
173
+ const doc = host.ownerDocument;
174
+ const box = doc.createElement('div');
175
+ box.className = 'keymap-overlay';
176
+ const panel = doc.createElement('div');
177
+ panel.className = 'km-panel';
178
+ const head = doc.createElement('div');
179
+ head.className = 'km-head';
180
+ head.textContent = `Keymap — ${PRESETS.find((p) => p.id === presetId)?.label ?? presetId}`;
181
+ const table = doc.createElement('table');
182
+ for (const r of overlayRows(presetId)) {
183
+ const tr = doc.createElement('tr');
184
+ if (!r.built) tr.className = 'later';
185
+ const a = doc.createElement('td'), b = doc.createElement('td');
186
+ a.textContent = r.label;
187
+ b.textContent = r.text + (r.built ? '' : ' (phase 2)');
188
+ tr.append(a, b);
189
+ table.append(tr);
190
+ }
191
+ const foot = doc.createElement('div');
192
+ foot.className = 'km-foot';
193
+ foot.textContent = 'click selects, Shift-click adds, Ctrl-click removes, a drag selects what lies wholly inside its box, Esc clears · ? or Esc closes';
194
+ panel.append(head, table, foot);
195
+ box.append(panel);
196
+ box.addEventListener('pointerdown', (e) => { if (e.target === box) box.remove(); });
197
+ host.append(box);
198
+ return box;
199
+ }
@@ -0,0 +1,244 @@
1
+ // Reference layers (docs/design/viewer.md section 7): the person's files in inputs/, one outliner row each, shown
2
+ // when their eye is on (remembered in this browser), drawn in a display mode of their own (as the view by default;
3
+ // ghost is one of the modes). PNGs stand as unlit image planes at their pixel aspect, one metre tall, beside the
4
+ // scene. Files dropped on the page are uploaded to inputs/ (POST /api/inputs).
5
+ import { api } from './api.js';
6
+ import { MeshObject, parseGLB, isPicture, LAYER_MODES } from './scene.js';
7
+ import { fmtBytes } from './units.js';
8
+ import * as THREE from 'three';
9
+
10
+ export const MAX_UPLOAD = 512 * 1024 * 1024; // POST /api/inputs limit (src/viewer/server.ts)
11
+ const stampOf = (f) => `${f.mtime}:${f.size}`;
12
+ const errText = (e) => String(e?.message ?? e).replace(/^\[f\] /gm, '');
13
+ export const layerId = (path) => `layer:${path}`;
14
+ export const isInputImage = (path) => /\.(png|jpe?g|webp)$/i.test(path);
15
+ export const inputImageURL = (f) => '/api/input_image?' + new URLSearchParams({ path: f.path, rev: stampOf(f) });
16
+
17
+ export function createLayers(ctx) {
18
+ const memo = ctx.store;
19
+ const L = {
20
+ list: [], where: '', dir: '',
21
+ shown: new Set(memo.get('layers.shown', [])),
22
+ display: new Map(Object.entries(memo.get('layers.display', {}))),
23
+ loaded: new Map(), // path → {stamp, mesh: MeshObject|null}
24
+ info: new Map(), // path → {stamp, summary?, error?, pending?}
25
+ errors: new Map(), // path → {stamp, msg}
26
+ placedX: null, // where the next picture stands
27
+ restored: false,
28
+ };
29
+ const remember = () => { memo.set('layers.shown', [...L.shown]); memo.set('layers.display', Object.fromEntries(L.display)); };
30
+ const changed = () => ctx.emit('layers');
31
+
32
+ /** The outliner / properties entry of an input file. */
33
+ const entry = (path) => {
34
+ const f = L.list.find((x) => x.path === path);
35
+ const id = layerId(path);
36
+ const prev = ctx.objects.get(id);
37
+ const e = prev ?? { id, kind: 'layer', path };
38
+ e.file = f;
39
+ e.label = path;
40
+ e.mesh = L.loaded.get(path)?.mesh ?? null;
41
+ e.loading = !!L.loaded.get(path) && !e.mesh;
42
+ e.visible = L.shown.has(path);
43
+ e.display = L.display.get(path) ?? 'view';
44
+ e.pickable = !!e.mesh && path !== 'markers.json';
45
+ e.surface = !!e.mesh && path !== 'markers.json' && !e.mesh.picture;
46
+ ctx.objects.set(id, e);
47
+ return e;
48
+ };
49
+
50
+ function drop(path) {
51
+ const l = L.loaded.get(path);
52
+ if (!l) return;
53
+ L.loaded.delete(path);
54
+ if (l.mesh) l.mesh.dispose();
55
+ entry(path);
56
+ ctx.requestRender();
57
+ }
58
+ async function load(path) {
59
+ const f = L.list.find((x) => x.path === path);
60
+ if (!f) return;
61
+ drop(path);
62
+ const slot = { stamp: stampOf(f), mesh: null };
63
+ L.loaded.set(path, slot);
64
+ L.errors.delete(path);
65
+ entry(path); changed();
66
+ let src = null;
67
+ try {
68
+ if (isInputImage(path)) {
69
+ const img = new Image(); img.src = inputImageURL(f); await img.decode();
70
+ const texture = new THREE.Texture(img); texture.colorSpace = THREE.SRGBColorSpace; texture.needsUpdate = true;
71
+ const material = new THREE.MeshBasicMaterial({ map: texture, transparent: true, side: THREE.DoubleSide });
72
+ material.name = 'image:' + path;
73
+ src = new THREE.Mesh(new THREE.PlaneGeometry(img.naturalWidth / img.naturalHeight, 1), material);
74
+ } else {
75
+ const r = await api.input(path);
76
+ if (!r.ok) throw new Error(r.error);
77
+ src = await parseGLB(r.buf);
78
+ }
79
+ } catch (e) {
80
+ if (L.loaded.get(path) === slot) {
81
+ L.loaded.delete(path); L.shown.delete(path); remember();
82
+ L.errors.set(path, { stamp: slot.stamp, msg: errText(e) });
83
+ }
84
+ entry(path); changed();
85
+ return;
86
+ }
87
+ if (L.loaded.get(path) !== slot) { new MeshObject('', src).dispose(); return; } // hidden or replaced meanwhile
88
+ const picture = isPicture(src);
89
+ if (picture) placePicture(src);
90
+ src.name = `inputs/${path}`;
91
+ const mesh = new MeshObject(layerId(path), src, { picture });
92
+ mesh.onReady = () => ctx.requestRender();
93
+ slot.mesh = mesh;
94
+ ctx.layersRoot.add(mesh.root);
95
+ entry(path);
96
+ fetchInfo(path);
97
+ changed();
98
+ ctx.requestRender();
99
+ }
100
+ /** One metre tall at its pixel aspect, standing in a row right of the scene, its foot on the scene's floor. */
101
+ function placePicture(src) {
102
+ src.updateMatrixWorld(true);
103
+ const b0 = new THREE.Box3().setFromObject(src);
104
+ const h = Math.max(1e-6, b0.max.y - b0.min.y), s = 1 / h;
105
+ const scene = ctx.sceneBounds({ pictures: false });
106
+ const gap = 0.25;
107
+ if (L.placedX === null) L.placedX = scene.isEmpty() ? 0 : scene.max.x + gap;
108
+ src.scale.setScalar(s);
109
+ src.position.set(L.placedX - b0.min.x * s, (scene.isEmpty() ? 0 : scene.min.y) - b0.min.y * s, scene.isEmpty() ? 0 : (scene.min.z + scene.max.z) / 2);
110
+ src.updateMatrixWorld(true);
111
+ L.placedX += (b0.max.x - b0.min.x) * s + gap;
112
+ }
113
+ async function fetchInfo(path) {
114
+ const f = L.list.find((x) => x.path === path);
115
+ if (!f) return;
116
+ const stamp = stampOf(f), have = L.info.get(path);
117
+ if (have && have.stamp === stamp) return;
118
+ L.info.set(path, { stamp, pending: true });
119
+ let r;
120
+ if (isInputImage(path)) {
121
+ try {
122
+ const img = new Image(); img.src = inputImageURL(f); await img.decode();
123
+ r = { ok: true, summary: `${img.naturalWidth} × ${img.naturalHeight} · ${L.fileText(f)}` };
124
+ } catch { r = { ok: false, error: 'Cannot decode this image. Check that the file is a valid PNG, JPEG or WebP.' }; }
125
+ } else r = await api.inputInfo(path);
126
+ if (L.info.get(path)?.stamp !== stamp) return;
127
+ if (r.ok) L.info.set(path, { stamp, summary: r.summary });
128
+ else { L.info.set(path, { stamp, error: errText(r.error) }); L.errors.set(path, { stamp, msg: errText(r.error) }); }
129
+ if (r.ok) L.errors.delete(path);
130
+ changed();
131
+ }
132
+
133
+ L.fetchInfo = fetchInfo;
134
+ /** Eye on / off: on loads the layer, off frees it. */
135
+ L.show = (path, on) => {
136
+ if (on) { L.shown.add(path); if (!L.loaded.has(path)) load(path); }
137
+ else { L.shown.delete(path); drop(path); }
138
+ remember(); entry(path); changed();
139
+ };
140
+ L.setDisplay = (path, mode) => {
141
+ if (!LAYER_MODES.some(([m]) => m === mode)) return;
142
+ if (mode === 'view') L.display.delete(path); else L.display.set(path, mode);
143
+ remember(); entry(path); changed(); ctx.requestRender();
144
+ };
145
+ L.refresh = ctx.coalesce(async () => {
146
+ const list = await api.inputs();
147
+ if (!list) return;
148
+ L.list = list;
149
+ const byPath = new Map(list.map((f) => [f.path, f]));
150
+ if (!L.restored) { L.restored = true; for (const p of [...L.shown]) if (!byPath.has(p)) L.shown.delete(p); }
151
+ // a replaced file reloads; a removed one goes away
152
+ for (const p of [...L.shown]) {
153
+ const f = byPath.get(p);
154
+ if (!f) { L.shown.delete(p); drop(p); continue; }
155
+ const l = L.loaded.get(p);
156
+ if (!l || l.stamp !== stampOf(f)) load(p);
157
+ }
158
+ for (const [p] of L.loaded) if (!byPath.has(p)) drop(p);
159
+ for (const m of [L.info, L.errors]) for (const [p, v] of m) if (!byPath.has(p) || v.stamp !== stampOf(byPath.get(p))) m.delete(p);
160
+ for (const id of [...ctx.objects.keys()]) if (id.startsWith('layer:') && !byPath.has(id.slice(6))) ctx.objects.delete(id);
161
+ for (const f of list) entry(f.path);
162
+ remember(); changed();
163
+ });
164
+ L.loadWhere = async () => {
165
+ const j = await api.inputsDir();
166
+ if (!j?.where) return;
167
+ L.where = String(j.where); L.dir = String(j.dir ?? '');
168
+ const dw = document.getElementById('drop-where');
169
+ if (dw) dw.textContent = `inputs/ ${L.where}`;
170
+ changed();
171
+ };
172
+ /** Bounds of the shown layers (pictures too unless `pictures` is false). */
173
+ L.bounds = ({ pictures = true } = {}) => {
174
+ const b = new THREE.Box3();
175
+ for (const [, l] of L.loaded) if (l.mesh && l.mesh.root.visible && (pictures || !l.mesh.picture)) b.union(l.mesh.bounds());
176
+ return b;
177
+ };
178
+ L.fileText = (f) => `${f.kind}${f.ext ? ` (.${f.ext})` : ''} · ${fmtBytes(f.size)} · ${new Date(f.mtime).toLocaleString()}`;
179
+
180
+ // ------------------------------------------------------------------ drop zone: files go to inputs/
181
+ async function uploadOne(f, tag) {
182
+ if (f.size > MAX_UPLOAD) return { error: `${f.name}: ${fmtBytes(f.size)} is over the ${MAX_UPLOAD / 1024 ** 2} MB limit` };
183
+ const put = async (overwrite) => {
184
+ const t0 = performance.now();
185
+ const tick = () => ctx.message(`uploading ${f.name}${tag} · ${fmtBytes(f.size)} · ${((performance.now() - t0) / 1000).toFixed(0)} s`, 'busy');
186
+ tick();
187
+ const timer = setInterval(tick, 500);
188
+ try { return await api.upload(f, overwrite); } finally { clearInterval(timer); }
189
+ };
190
+ let r = await put(false);
191
+ if (r.status === 409) {
192
+ ctx.message(`${f.name}${tag}: inputs/ already has this file`);
193
+ if (!await ctx.ask(`inputs/${r.j.path ?? f.name} exists — replace it?`, 'Replace', 'Keep')) return { kept: r.j.path ?? f.name };
194
+ r = await put(true);
195
+ }
196
+ if (r.status !== 200 || !r.j.ok) return { error: `${f.name}: ${r.j.error ?? `upload failed (${r.status})`}` };
197
+ return { path: r.j.path };
198
+ }
199
+ let uploads = Promise.resolve();
200
+ L.upload = (files, folders) => {
201
+ uploads = uploads.then(async () => {
202
+ const added = [], kept = [], errors = [];
203
+ if (folders.length) errors.push(`folders are not supported, drop the files inside instead (skipped ${folders.map((f) => f + '/').join(', ')})`);
204
+ for (const [i, f] of files.entries()) {
205
+ const r = await uploadOne(f, files.length > 1 ? ` (${i + 1}/${files.length})` : '');
206
+ if (r.path) {
207
+ added.push(r.path);
208
+ if (/\.(png|jpe?g|webp)$/i.test(r.path)) { await L.refresh(); await ctx.outputs?.openInput(r.path); continue; }
209
+ // show it at once, and select it
210
+ L.shown.add(r.path);
211
+ for (const m of [L.info, L.errors]) m.delete(r.path);
212
+ remember();
213
+ await L.refresh();
214
+ ctx.selection.apply([layerId(r.path)]);
215
+ } else if (r.kept) kept.push(r.kept);
216
+ else if (r.error) errors.push(r.error);
217
+ }
218
+ const msg = [added.length ? `added ${added.map((p) => 'inputs/' + p).join(', ')}${L.where ? ' ' + L.where : ''}` : '', kept.length ? `kept the existing ${kept.map((p) => 'inputs/' + p).join(', ')}` : '', ...errors].filter(Boolean).join(' · ');
219
+ if (msg) ctx.message(msg, errors.length ? 'err' : added.length ? 'ok' : '');
220
+ });
221
+ };
222
+ let depth = 0;
223
+ const fileDrag = (e) => [...(e.dataTransfer?.types ?? [])].includes('Files');
224
+ addEventListener('dragenter', (e) => { if (!fileDrag(e)) return; e.preventDefault(); if (++depth === 1) document.body.classList.add('dropping'); });
225
+ addEventListener('dragover', (e) => { if (!fileDrag(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; });
226
+ addEventListener('dragleave', (e) => { if (!fileDrag(e)) return; if (--depth <= 0) { depth = 0; document.body.classList.remove('dropping'); } });
227
+ addEventListener('drop', (e) => {
228
+ if (!fileDrag(e)) return;
229
+ e.preventDefault();
230
+ depth = 0; document.body.classList.remove('dropping');
231
+ // read the items now: the browser empties the DataTransfer after this event
232
+ const files = [], folders = [];
233
+ for (const it of Array.from(e.dataTransfer.items ?? [])) {
234
+ if (it.kind !== 'file') continue;
235
+ const en = it.webkitGetAsEntry?.();
236
+ if (en?.isDirectory) { folders.push(en.name); continue; }
237
+ const f = it.getAsFile();
238
+ if (f) files.push(f);
239
+ }
240
+ if (!e.dataTransfer.items) files.push(...e.dataTransfer.files);
241
+ L.upload(files, folders);
242
+ });
243
+ return L;
244
+ }