topotopo 0.3.0 → 0.4.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.
- package/NOTICE +30 -0
- package/README.md +35 -14
- package/dist/cli.js +28 -10
- package/dist/core/analysis.d.ts +5 -1
- package/dist/core/analysis.js +8 -3
- package/dist/core/bake.d.ts +2 -5
- package/dist/core/bake.js +12 -25
- package/dist/core/bevel.js +165 -97
- package/dist/core/geometry.js +1 -1
- package/dist/core/imageops.d.ts +6 -0
- package/dist/core/imageops.js +51 -0
- package/dist/core/materials.d.ts +4 -0
- package/dist/core/materials.js +11 -0
- package/dist/core/packed.js +11 -0
- package/dist/core/particles.d.ts +1 -1
- package/dist/core/particles.js +1 -1
- package/dist/core/rbd.js +13 -1
- package/dist/core/scatter.d.ts +1 -1
- package/dist/core/scatter.js +1 -1
- package/dist/core/scene.d.ts +20 -0
- package/dist/core/scene.js +71 -0
- package/dist/core/snippet-lib.d.ts +1 -1
- package/dist/core/snippet-lib.js +1 -1
- package/dist/core/solidify.d.ts +38 -0
- package/dist/core/solidify.js +356 -0
- package/dist/core/tangents.d.ts +52 -0
- package/dist/core/tangents.js +214 -0
- package/dist/core/texcoord.d.ts +4 -0
- package/dist/core/texcoord.js +14 -0
- package/dist/core/topology.d.ts +22 -0
- package/dist/core/topology.js +70 -7
- package/dist/core/traceimage.d.ts +7 -0
- package/dist/core/traceimage.js +221 -0
- package/dist/core/tritri.d.ts +5 -0
- package/dist/core/tritri.js +120 -0
- package/dist/core/uv.d.ts +13 -0
- package/dist/core/uv.js +3 -3
- package/dist/core/uvreport.d.ts +66 -0
- package/dist/core/uvreport.js +308 -0
- package/dist/core/xatlas.js +32 -2
- package/dist/gallery/app/gallery.css +100 -0
- package/dist/gallery/app/gallery.js +80 -0
- package/dist/gallery/bake.d.ts +34 -0
- package/dist/gallery/bake.js +144 -0
- package/dist/gallery/cli.d.ts +4 -0
- package/dist/gallery/cli.js +157 -0
- package/dist/gallery/library.d.ts +124 -0
- package/dist/gallery/library.js +366 -0
- package/dist/gallery/pages.d.ts +94 -0
- package/dist/gallery/pages.js +148 -0
- package/dist/gallery/server.d.ts +21 -0
- package/dist/gallery/server.js +391 -0
- package/dist/host/export-targets.js +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/inspect.d.ts +6 -1
- package/dist/inspect.js +13 -1
- package/dist/io/common.d.ts +8 -0
- package/dist/io/gltf.js +236 -19
- package/dist/io/targets.js +1 -1
- package/dist/mcp/docs.d.ts +1 -1
- package/dist/mcp/docs.js +58 -4
- package/dist/mcp/library.d.ts +12 -0
- package/dist/mcp/library.js +159 -0
- package/dist/mcp/server.js +29 -12
- package/dist/mcp/tools.js +16 -10
- package/dist/nodes/bake.js +56 -36
- package/dist/nodes/bevel.js +4 -3
- package/dist/nodes/code.js +1 -1
- package/dist/nodes/curves.js +7 -0
- package/dist/nodes/generate.js +1 -1
- package/dist/nodes/imageops.d.ts +1 -0
- package/dist/nodes/imageops.js +206 -0
- package/dist/nodes/index.d.ts +3 -0
- package/dist/nodes/index.js +3 -0
- package/dist/nodes/material.js +3 -0
- package/dist/nodes/measure.js +3 -2
- package/dist/nodes/rbd.js +1 -1
- package/dist/nodes/scene.d.ts +1 -0
- package/dist/nodes/scene.js +53 -0
- package/dist/nodes/solidify.d.ts +1 -0
- package/dist/nodes/solidify.js +52 -0
- package/dist/nodes/transform.js +5 -1
- package/dist/nodes/util.d.ts +1 -1
- package/dist/nodes/wasmcall.js +1 -1
- package/dist/render/options.js +1 -1
- package/dist/render/pbr.d.ts +28 -0
- package/dist/render/pbr.js +378 -0
- package/dist/render/preview.d.ts +58 -0
- package/dist/render/preview.js +24 -0
- package/dist/render/raster.d.ts +12 -2
- package/dist/render/raster.js +98 -11
- package/dist/render/texview.d.ts +1 -1
- package/dist/render/texview.js +7 -2
- package/dist/viewer/app/camera.js +1 -1
- package/dist/viewer/app/embed.js +80 -0
- package/dist/viewer/app/grid.js +1 -1
- package/dist/viewer/app/guides.js +1 -1
- package/dist/viewer/app/keymap.js +1 -1
- package/dist/viewer/app/layers.js +1 -1
- package/dist/viewer/app/main.js +1 -1
- package/dist/viewer/app/markers.js +1 -1
- package/dist/viewer/app/outliner.js +1 -1
- package/dist/viewer/app/props.js +1 -1
- package/dist/viewer/app/scene.js +6 -2
- package/dist/viewer/app/select.js +1 -1
- package/dist/viewer/app/selection.js +1 -1
- package/dist/viewer/app/status.js +1 -1
- package/dist/viewer/app/style.css +1 -1
- package/dist/viewer/app/units.js +1 -1
- package/dist/viewer/app/vars.js +1 -1
- package/dist/viewer/index.html +1 -1
- package/dist/viewer/server.d.ts +14 -2
- package/dist/viewer/server.js +30 -10
- package/dist/workspace.d.ts +13 -0
- package/dist/workspace.js +87 -1
- package/kernels/pkg/README.md +21 -28
- package/kernels/pkg-simd/README.md +21 -28
- package/package.json +9 -3
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
// The gallery web server: every library's projects as a grid, a page per project with its 3D
|
|
2
|
+
// preview, and stable URLs a board pastes (link, thumbnail, iframe embed). It reads files and serves baked previews;
|
|
3
|
+
// it never cooks: bakes run in child processes (BakeQueue) and "Open in editor" starts a `topotopo edit` child.
|
|
4
|
+
// Bound to 127.0.0.1 on a fixed port (stable links); requests must name this server as their Host, and writes must
|
|
5
|
+
// come from its own pages.
|
|
6
|
+
import http from 'node:http';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import zlib from 'node:zlib';
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
import { encodePNG } from '../render/png.js';
|
|
13
|
+
import { MIME, appDir, threeDir } from '../viewer/server.js';
|
|
14
|
+
import { galleryDir, graphNames, isStale, listFiles, loadConfig, readBakeState, readGraph, scanLibrary } from './library.js';
|
|
15
|
+
import { BakeQueue } from './bake.js';
|
|
16
|
+
import { embedPage, galleryPage, projectPage } from './pages.js';
|
|
17
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
18
|
+
const assetDir = path.join(here, 'app');
|
|
19
|
+
const cli = path.resolve(here, '..', import.meta.url.endsWith('.ts') ? 'cli.ts' : 'cli.js');
|
|
20
|
+
const RESCAN_MS = 5 * 60_000;
|
|
21
|
+
const EDITOR_START_MS = 60_000;
|
|
22
|
+
const FILE_TYPES = {
|
|
23
|
+
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.avif': 'image/avif',
|
|
24
|
+
'.pdf': 'application/pdf', '.txt': 'text/plain; charset=utf-8', '.md': 'text/plain; charset=utf-8', '.json': 'application/json',
|
|
25
|
+
'.glb': 'model/gltf-binary', '.csv': 'text/csv; charset=utf-8',
|
|
26
|
+
};
|
|
27
|
+
/** shown inline; everything else (SVG and HTML among them: they run scripts) is a download */
|
|
28
|
+
const INLINE = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif', '.pdf', '.txt', '.md', '.json', '.csv']);
|
|
29
|
+
class HttpError extends Error {
|
|
30
|
+
status;
|
|
31
|
+
constructor(status, msg) { super(msg); this.status = status; }
|
|
32
|
+
}
|
|
33
|
+
/** A gallery answers here already: its URL, or null. */
|
|
34
|
+
export async function runningGallery(port) {
|
|
35
|
+
try {
|
|
36
|
+
const res = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1500) });
|
|
37
|
+
const j = await res.json();
|
|
38
|
+
return j?.gallery ? `http://127.0.0.1:${port}/` : null;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export async function startGallery(o = {}) {
|
|
45
|
+
const cfg = o.config ?? loadConfig();
|
|
46
|
+
const log = o.log ?? (() => { });
|
|
47
|
+
const bakeOn = o.bake ?? true;
|
|
48
|
+
let base = '';
|
|
49
|
+
// ---------------------------------------------------------------- libraries
|
|
50
|
+
let scans = [];
|
|
51
|
+
const projects = new Map();
|
|
52
|
+
const keyOf = (p) => `${p.lib}/${p.id}`;
|
|
53
|
+
const rescan = () => {
|
|
54
|
+
scans = cfg.libraries.map(scanLibrary);
|
|
55
|
+
projects.clear();
|
|
56
|
+
for (const s of scans)
|
|
57
|
+
for (const p of s.projects)
|
|
58
|
+
projects.set(keyOf(p), p);
|
|
59
|
+
};
|
|
60
|
+
const find = (lib, id) => {
|
|
61
|
+
let p = projects.get(`${lib}/${id}`);
|
|
62
|
+
if (!p) {
|
|
63
|
+
rescan();
|
|
64
|
+
p = projects.get(`${lib}/${id}`);
|
|
65
|
+
} // made a moment ago, before the watch noticed
|
|
66
|
+
if (!p)
|
|
67
|
+
throw new HttpError(404, `no project "${id}" in library "${lib}"`);
|
|
68
|
+
return p;
|
|
69
|
+
};
|
|
70
|
+
// ---------------------------------------------------------------- events (SSE) and bakes
|
|
71
|
+
const clients = new Set();
|
|
72
|
+
const broadcast = (ev) => { const m = `data: ${JSON.stringify(ev)}\n\n`; for (const c of clients)
|
|
73
|
+
c.write(m); };
|
|
74
|
+
const queue = new BakeQueue({
|
|
75
|
+
log,
|
|
76
|
+
onDone: (dir, state) => {
|
|
77
|
+
const p = [...projects.values()].find((x) => x.dir === dir);
|
|
78
|
+
if (p)
|
|
79
|
+
broadcast({ project: keyOf(p), ok: state?.ok ?? false, version: state?.at ?? 0 });
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
const bakeIfStale = (p) => {
|
|
83
|
+
if (!bakeOn || queue.pending(p.dir))
|
|
84
|
+
return;
|
|
85
|
+
try {
|
|
86
|
+
if (isStale(p) && queue.add(p.dir))
|
|
87
|
+
broadcast({ project: keyOf(p), baking: true });
|
|
88
|
+
}
|
|
89
|
+
catch { /* removed meanwhile */ }
|
|
90
|
+
};
|
|
91
|
+
rescan();
|
|
92
|
+
for (const p of projects.values())
|
|
93
|
+
bakeIfStale(p);
|
|
94
|
+
// A change below a library: project.json, graphs/, assets/ and inputs/ may need a bake; anything else may be a
|
|
95
|
+
// project made, moved or removed, or attachments: read the libraries again and tell the pages.
|
|
96
|
+
const touched = new Set();
|
|
97
|
+
let changeTimer;
|
|
98
|
+
const onChange = () => {
|
|
99
|
+
clearTimeout(changeTimer);
|
|
100
|
+
changeTimer = setTimeout(() => {
|
|
101
|
+
const before = [...projects.keys()].join('\n');
|
|
102
|
+
rescan();
|
|
103
|
+
for (const k of touched) {
|
|
104
|
+
const p = projects.get(k);
|
|
105
|
+
if (p)
|
|
106
|
+
bakeIfStale(p);
|
|
107
|
+
}
|
|
108
|
+
for (const p of projects.values())
|
|
109
|
+
if (!readBakeState(p.dir))
|
|
110
|
+
bakeIfStale(p);
|
|
111
|
+
broadcast({ changed: [...touched], list: before !== [...projects.keys()].join('\n') });
|
|
112
|
+
touched.clear();
|
|
113
|
+
}, 500);
|
|
114
|
+
};
|
|
115
|
+
const watchers = [];
|
|
116
|
+
for (const s of scans) {
|
|
117
|
+
try {
|
|
118
|
+
const w = fs.watch(s.root, { recursive: true }, (_ev, f) => {
|
|
119
|
+
const rel = f ? String(f).split(path.sep).join('/') : '';
|
|
120
|
+
if (path.isAbsolute(rel))
|
|
121
|
+
return; // the root itself went away: the periodic rescan notices
|
|
122
|
+
const parts = rel.split('/');
|
|
123
|
+
if (parts.some((x) => x.startsWith('.') || x === 'node_modules'))
|
|
124
|
+
return; // .gallery/, .cache/, .part files
|
|
125
|
+
const p = scans.find((x) => x.root === s.root)?.projects.find((x) => rel === x.rel || rel.startsWith(x.rel + '/'));
|
|
126
|
+
if (p)
|
|
127
|
+
touched.add(keyOf(p));
|
|
128
|
+
onChange();
|
|
129
|
+
});
|
|
130
|
+
w.on('error', () => w.close());
|
|
131
|
+
w.unref();
|
|
132
|
+
watchers.push(w);
|
|
133
|
+
}
|
|
134
|
+
catch { /* no folder (a problem on the page) or no recursive watch: the periodic rescan covers it */ }
|
|
135
|
+
}
|
|
136
|
+
const periodic = setInterval(() => { rescan(); for (const p of projects.values())
|
|
137
|
+
bakeIfStale(p); }, RESCAN_MS);
|
|
138
|
+
periodic.unref();
|
|
139
|
+
// ---------------------------------------------------------------- editors
|
|
140
|
+
const editors = new Map();
|
|
141
|
+
const editorFor = (p) => {
|
|
142
|
+
const have = editors.get(p.dir);
|
|
143
|
+
if (have && have.child.exitCode === null)
|
|
144
|
+
return have.url;
|
|
145
|
+
const child = spawn(process.execPath, [cli, 'edit', p.dir, '--json'], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
146
|
+
const url = new Promise((resolve, reject) => {
|
|
147
|
+
let out = '', err = '';
|
|
148
|
+
const t = setTimeout(() => { child.kill(); reject(new Error('the editor did not start within a minute')); }, EDITOR_START_MS);
|
|
149
|
+
child.stdout.on('data', (d) => {
|
|
150
|
+
out += d;
|
|
151
|
+
const line = out.split('\n').find((l) => l.startsWith('{'));
|
|
152
|
+
if (line) {
|
|
153
|
+
clearTimeout(t);
|
|
154
|
+
try {
|
|
155
|
+
resolve(JSON.parse(line).url);
|
|
156
|
+
}
|
|
157
|
+
catch (e) {
|
|
158
|
+
reject(e);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
child.stderr.on('data', (d) => { if (err.length < 4000)
|
|
163
|
+
err += d; });
|
|
164
|
+
child.on('exit', (code) => { clearTimeout(t); editors.delete(p.dir); reject(new Error(`the editor stopped (exit ${code}): ${err.trim().split('\n').slice(-3).join(' ')}`)); });
|
|
165
|
+
});
|
|
166
|
+
url.catch(() => { });
|
|
167
|
+
editors.set(p.dir, { child, url });
|
|
168
|
+
return url;
|
|
169
|
+
};
|
|
170
|
+
const reveal = (dir) => {
|
|
171
|
+
const [cmd, args] = process.platform === 'win32' ? ['explorer.exe', [dir]] : process.platform === 'darwin' ? ['open', [dir]] : ['xdg-open', [dir]];
|
|
172
|
+
const c = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: false });
|
|
173
|
+
c.on('error', () => { });
|
|
174
|
+
c.unref();
|
|
175
|
+
};
|
|
176
|
+
// ---------------------------------------------------------------- page data
|
|
177
|
+
const enc = encodeURIComponent;
|
|
178
|
+
const urls = {
|
|
179
|
+
home: '/',
|
|
180
|
+
project: (lib, id) => `/p/${enc(lib)}/${enc(id)}`,
|
|
181
|
+
thumb: (lib, id, v) => `/p/${enc(lib)}/${enc(id)}/thumb.png${v ? `?v=${enc(String(v))}` : ''}`,
|
|
182
|
+
glb: (lib, id, v) => `/p/${enc(lib)}/${enc(id)}/preview.glb${v ? `?v=${enc(String(v))}` : ''}`,
|
|
183
|
+
embed: (lib, id) => `/embed/${enc(lib)}/${enc(id)}`,
|
|
184
|
+
file: (lib, id, rel) => `/p/${enc(lib)}/${enc(id)}/files/${rel.split('/').map(enc).join('/')}`,
|
|
185
|
+
edit: (lib, id) => `/p/${enc(lib)}/${enc(id)}/edit`,
|
|
186
|
+
asset: (name) => `/static/${name}`,
|
|
187
|
+
app: (name) => `/app/${name}`,
|
|
188
|
+
three: '/vendor/three/',
|
|
189
|
+
};
|
|
190
|
+
const status = (p, s) => (queue.pending(p.dir) ? 'baking' : !s ? 'new' : s.ok ? 'ok' : 'failed');
|
|
191
|
+
const cardOf = (p) => {
|
|
192
|
+
const s = readBakeState(p.dir);
|
|
193
|
+
const m = p.manifest;
|
|
194
|
+
return { lib: p.lib, id: p.id, title: m.title, collection: p.collection, tags: m.tags, description: m.description, updated: p.updated, status: status(p, s), version: String(s?.at ?? 0) };
|
|
195
|
+
};
|
|
196
|
+
const projectData = (p) => {
|
|
197
|
+
const s = readBakeState(p.dir);
|
|
198
|
+
const graphs = graphNames(p.dir).map((name) => {
|
|
199
|
+
const g = readGraph(p.dir, name) ?? {};
|
|
200
|
+
const meta = g.params ?? {};
|
|
201
|
+
return {
|
|
202
|
+
name, nodes: Object.keys(g.nodes ?? {}).length,
|
|
203
|
+
vars: Object.entries(g.vars ?? {}).map(([k, v]) => ({ name: k, value: v, desc: meta[k]?.desc ?? meta[k]?.label, min: meta[k]?.min, max: meta[k]?.max })),
|
|
204
|
+
};
|
|
205
|
+
});
|
|
206
|
+
const abs = (u) => base + u;
|
|
207
|
+
return {
|
|
208
|
+
...cardOf(p), rel: p.rel, links: p.manifest.links, graph: p.manifest.graph, graphs, created: p.manifest.created,
|
|
209
|
+
attachments: listFiles(path.join(p.dir, 'attachments')), exports: listFiles(path.join(p.dir, 'exports')),
|
|
210
|
+
glb: fs.existsSync(path.join(galleryDir(p.dir), 'preview.glb')), bake: s,
|
|
211
|
+
share: { link: abs(urls.project(p.lib, p.id)), thumb: abs(urls.thumb(p.lib, p.id)), embed: abs(urls.embed(p.lib, p.id)) },
|
|
212
|
+
};
|
|
213
|
+
};
|
|
214
|
+
const listJSON = () => [...projects.values()].map((p) => {
|
|
215
|
+
const c = cardOf(p);
|
|
216
|
+
return {
|
|
217
|
+
lib: p.lib, id: p.id, title: c.title, description: c.description, tags: c.tags, collection: c.collection, updated: p.updated, status: c.status,
|
|
218
|
+
url: base + urls.project(p.lib, p.id), thumb: base + urls.thumb(p.lib, p.id, c.version), embed: base + urls.embed(p.lib, p.id),
|
|
219
|
+
};
|
|
220
|
+
});
|
|
221
|
+
let placeholder = null;
|
|
222
|
+
const placeholderPNG = () => {
|
|
223
|
+
if (!placeholder) {
|
|
224
|
+
const n = 64, rgba = new Uint8Array(n * n * 4);
|
|
225
|
+
for (let i = 0; i < n * n; i++)
|
|
226
|
+
rgba.set([0x2b, 0x2d, 0x31, 0xff], i * 4);
|
|
227
|
+
placeholder = encodePNG(rgba, n, n, (d) => zlib.deflateSync(d));
|
|
228
|
+
}
|
|
229
|
+
return placeholder;
|
|
230
|
+
};
|
|
231
|
+
/** `files/<rest>` of a project: below attachments/ or exports/, never outside them (links included). */
|
|
232
|
+
const projectFile = (p, rest) => {
|
|
233
|
+
const parts = rest.split('/').map((x) => decodeURIComponent(x));
|
|
234
|
+
// decoded segments: "%2F" and "%5C" must not smuggle separators (and so "..") past the split
|
|
235
|
+
if (!['attachments', 'exports'].includes(parts[0]) || parts.length < 2 || parts.some((x) => !x || x === '.' || x === '..' || /[\\/\0]/.test(x)))
|
|
236
|
+
throw new HttpError(400, 'files/ serves attachments/<path> and exports/<path>');
|
|
237
|
+
const root = path.join(p.dir, parts[0]);
|
|
238
|
+
const abs = path.join(root, ...parts.slice(1));
|
|
239
|
+
if (!abs.startsWith(root + path.sep))
|
|
240
|
+
throw new HttpError(400, 'the path leaves the project');
|
|
241
|
+
if (!fs.statSync(abs, { throwIfNoEntry: false })?.isFile())
|
|
242
|
+
throw new HttpError(404, `no file ${parts.join('/')}`);
|
|
243
|
+
const real = path.relative(fs.realpathSync(root), fs.realpathSync(abs));
|
|
244
|
+
if (real.startsWith('..') || path.isAbsolute(real))
|
|
245
|
+
throw new HttpError(400, 'the path leaves the project');
|
|
246
|
+
return abs;
|
|
247
|
+
};
|
|
248
|
+
const readStatic = (dir, rel) => {
|
|
249
|
+
const p = path.resolve(dir, decodeURIComponent(rel));
|
|
250
|
+
if (!p.startsWith(dir + path.sep) || !fs.statSync(p, { throwIfNoEntry: false })?.isFile())
|
|
251
|
+
return null;
|
|
252
|
+
return p;
|
|
253
|
+
};
|
|
254
|
+
// ---------------------------------------------------------------- routes
|
|
255
|
+
const server = http.createServer(async (req, res) => {
|
|
256
|
+
const head = (code, type, extra = {}) => res.writeHead(code, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...extra });
|
|
257
|
+
const send = (code, body, type = 'text/plain; charset=utf-8', extra = {}) => { head(code, type, extra); res.end(req.method === 'HEAD' ? undefined : body); };
|
|
258
|
+
// pages may only be framed by the gallery itself; the embed page is made to be framed by a board
|
|
259
|
+
const html = (body, framable = false) => send(200, body, MIME['.html'], framable ? {} : { 'content-security-policy': "frame-ancestors 'self'" });
|
|
260
|
+
const json = (code, body, extra = {}) => send(code, JSON.stringify(body), MIME['.json'], extra);
|
|
261
|
+
try {
|
|
262
|
+
const host = String(req.headers.host ?? '');
|
|
263
|
+
if (!/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(host))
|
|
264
|
+
return json(403, { error: `unexpected Host "${host}"` });
|
|
265
|
+
const origin = req.headers.origin;
|
|
266
|
+
const write = req.method !== 'GET' && req.method !== 'HEAD';
|
|
267
|
+
if (write && origin !== undefined && origin !== `http://${host}`)
|
|
268
|
+
return json(403, { error: `cross-origin ${req.method} refused (${origin})` });
|
|
269
|
+
const u = new URL(req.url ?? '/', 'http://localhost');
|
|
270
|
+
const seg = u.pathname.split('/').slice(1);
|
|
271
|
+
if (u.pathname === '/' || u.pathname === '/index.html') {
|
|
272
|
+
return html(galleryPage({ libraries: scans.map((s) => ({ name: s.name, cards: s.projects.map(cardOf) })), problems: scans.flatMap((s) => s.problems) }, urls));
|
|
273
|
+
}
|
|
274
|
+
if (seg[0] === 'static') {
|
|
275
|
+
const p = readStatic(assetDir, seg.slice(1).join('/'));
|
|
276
|
+
return p ? send(200, fs.readFileSync(p), MIME[path.extname(p)] ?? 'application/octet-stream') : send(404, 'not found');
|
|
277
|
+
}
|
|
278
|
+
if (seg[0] === 'app') {
|
|
279
|
+
const p = readStatic(appDir, seg.slice(1).join('/'));
|
|
280
|
+
return p ? send(200, fs.readFileSync(p), MIME[path.extname(p)] ?? 'application/octet-stream') : send(404, 'not found');
|
|
281
|
+
}
|
|
282
|
+
if (seg[0] === 'vendor' && seg[1] === 'three') {
|
|
283
|
+
const p = readStatic(threeDir, seg.slice(2).join('/'));
|
|
284
|
+
return p ? send(200, fs.readFileSync(p), MIME[path.extname(p)] ?? 'application/octet-stream', { 'cache-control': 'max-age=3600' }) : send(404, 'not found');
|
|
285
|
+
}
|
|
286
|
+
if (u.pathname === '/api/health')
|
|
287
|
+
return json(200, { gallery: true, libraries: scans.length, projects: projects.size, baking: queue.size });
|
|
288
|
+
if (u.pathname === '/api/events') {
|
|
289
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' });
|
|
290
|
+
res.write(': hello\n\n');
|
|
291
|
+
clients.add(res);
|
|
292
|
+
req.on('close', () => clients.delete(res));
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (u.pathname === '/api/projects') {
|
|
296
|
+
// a board on another origin may read the list when the config allows it (gallery.cors)
|
|
297
|
+
const cors = origin && cfg.gallery.cors.includes(origin) ? { 'access-control-allow-origin': origin, vary: 'Origin' } : { vary: 'Origin' };
|
|
298
|
+
if (req.method === 'OPTIONS')
|
|
299
|
+
return send(204, '', 'text/plain', { ...cors, 'access-control-allow-methods': 'GET' });
|
|
300
|
+
return json(200, { libraries: scans.map((s) => ({ name: s.name, projects: s.projects.length, problems: s.problems })), projects: listJSON() }, cors);
|
|
301
|
+
}
|
|
302
|
+
if (seg[0] === 'embed' && seg.length === 3) {
|
|
303
|
+
const p = find(decodeURIComponent(seg[1]), decodeURIComponent(seg[2]));
|
|
304
|
+
const s = readBakeState(p.dir);
|
|
305
|
+
const glb = fs.existsSync(path.join(galleryDir(p.dir), 'preview.glb'));
|
|
306
|
+
return html(embedPage({ lib: p.lib, id: p.id, title: p.manifest.title, glb, version: String(s?.at ?? 0), projectUrl: urls.project(p.lib, p.id) }, urls), true);
|
|
307
|
+
}
|
|
308
|
+
if (seg[0] === 'p' && seg.length >= 3) {
|
|
309
|
+
const p = find(decodeURIComponent(seg[1]), decodeURIComponent(seg[2]));
|
|
310
|
+
const rest = seg.slice(3);
|
|
311
|
+
if (!rest.length || (rest.length === 1 && !rest[0]))
|
|
312
|
+
return html(projectPage(projectData(p), urls));
|
|
313
|
+
if (rest[0] === 'thumb.png' || rest[0] === 'preview.glb') {
|
|
314
|
+
const s = readBakeState(p.dir);
|
|
315
|
+
const file = path.join(galleryDir(p.dir), rest[0]);
|
|
316
|
+
if (!fs.existsSync(file)) {
|
|
317
|
+
bakeIfStale(p);
|
|
318
|
+
if (rest[0] === 'thumb.png')
|
|
319
|
+
return send(200, placeholderPNG(), 'image/png');
|
|
320
|
+
return json(404, { error: s?.ok === false ? `the bake failed: ${s.error}` : 'not baked yet' });
|
|
321
|
+
}
|
|
322
|
+
const etag = `"${s?.key ?? 'x'}-${s?.at ?? 0}"`;
|
|
323
|
+
if (req.headers['if-none-match'] === etag) {
|
|
324
|
+
res.writeHead(304, { etag });
|
|
325
|
+
return res.end();
|
|
326
|
+
}
|
|
327
|
+
return send(200, fs.readFileSync(file), rest[0] === 'thumb.png' ? 'image/png' : MIME['.glb'], { etag, 'cache-control': 'no-cache' });
|
|
328
|
+
}
|
|
329
|
+
if (rest[0] === 'files' && rest.length > 1) {
|
|
330
|
+
const abs = projectFile(p, rest.slice(1).join('/'));
|
|
331
|
+
const ext = path.extname(abs).toLowerCase();
|
|
332
|
+
const disp = INLINE.has(ext) ? {} : { 'content-disposition': `attachment; filename="${path.basename(abs).replace(/["\\\r\n]/g, '_')}"` };
|
|
333
|
+
return send(200, fs.readFileSync(abs), FILE_TYPES[ext] ?? 'application/octet-stream', { ...disp, 'content-security-policy': 'sandbox' });
|
|
334
|
+
}
|
|
335
|
+
if (rest[0] === 'edit') {
|
|
336
|
+
const url = await editorFor(p);
|
|
337
|
+
res.writeHead(302, { location: url, 'cache-control': 'no-store' });
|
|
338
|
+
return res.end();
|
|
339
|
+
}
|
|
340
|
+
if (rest[0] === 'bake') {
|
|
341
|
+
if (req.method !== 'POST')
|
|
342
|
+
throw new HttpError(405, 'POST to bake again');
|
|
343
|
+
const queued = queue.add(p.dir);
|
|
344
|
+
if (queued)
|
|
345
|
+
broadcast({ project: keyOf(p), baking: true });
|
|
346
|
+
return json(200, { ok: true, queued });
|
|
347
|
+
}
|
|
348
|
+
if (rest[0] === 'reveal') {
|
|
349
|
+
if (req.method !== 'POST')
|
|
350
|
+
throw new HttpError(405, 'POST to show the folder');
|
|
351
|
+
reveal(p.dir);
|
|
352
|
+
return json(200, { ok: true });
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
send(404, 'not found');
|
|
356
|
+
}
|
|
357
|
+
catch (e) {
|
|
358
|
+
if (res.headersSent || res.destroyed)
|
|
359
|
+
return;
|
|
360
|
+
const code = e instanceof HttpError ? e.status : 500;
|
|
361
|
+
json(code, { ok: false, error: String(e?.message ?? e) });
|
|
362
|
+
}
|
|
363
|
+
});
|
|
364
|
+
const port = o.port ?? cfg.gallery.port;
|
|
365
|
+
await new Promise((resolve, reject) => {
|
|
366
|
+
server.once('error', reject);
|
|
367
|
+
server.listen(port, '127.0.0.1', () => resolve());
|
|
368
|
+
});
|
|
369
|
+
const actual = server.address().port;
|
|
370
|
+
base = `http://127.0.0.1:${actual}`;
|
|
371
|
+
const keepAlive = setInterval(() => { for (const c of clients)
|
|
372
|
+
c.write(': ping\n\n'); }, 20000);
|
|
373
|
+
keepAlive.unref();
|
|
374
|
+
return {
|
|
375
|
+
url: base + '/', port: actual, rescan, queue,
|
|
376
|
+
close: () => {
|
|
377
|
+
clearInterval(periodic);
|
|
378
|
+
clearInterval(keepAlive);
|
|
379
|
+
clearTimeout(changeTimer);
|
|
380
|
+
for (const w of watchers)
|
|
381
|
+
w.close();
|
|
382
|
+
queue.close();
|
|
383
|
+
for (const e of editors.values())
|
|
384
|
+
e.child.kill();
|
|
385
|
+
for (const c of clients)
|
|
386
|
+
c.end();
|
|
387
|
+
server.close();
|
|
388
|
+
server.closeAllConnections?.();
|
|
389
|
+
},
|
|
390
|
+
};
|
|
391
|
+
}
|
|
@@ -12,7 +12,7 @@ export async function serializeExport(geo, format, p, a, host) {
|
|
|
12
12
|
const outDir = format === 'unreal_landscape' && !/\.json$/i.test(p) ? p : path.dirname(p);
|
|
13
13
|
const res = await exportFilesAsync(geo, format, p, {
|
|
14
14
|
upAxis: a.up_axis, scale: a.scale, splitByName: a.split_by_name ?? true, custom: a.custom_attribs,
|
|
15
|
-
materials: a.materials, compress: a.compress, quantize: a.quantize, attributes: a.attributes, pcg: a.pcg || a.pcg_struct, pcgStruct: a.pcg_struct,
|
|
15
|
+
materials: a.materials, compress: a.compress, quantize: a.quantize, tangents: a.tangents, attributes: a.attributes, pcg: a.pcg || a.pcg_struct, pcgStruct: a.pcg_struct,
|
|
16
16
|
precision: a.precision, instancing: a.instancing, instances: a.instances, meshes: a.meshes,
|
|
17
17
|
layer: a.layer, layers: a.layers, heightMin: a.height_min, heightMax: a.height_max, heightfield: a.heightfield, tile_size: a.tile_size,
|
|
18
18
|
deflate: (d) => zlib.deflateSync(d, { level: 6 }),
|
package/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export type { CookReport, NodeResult, Issue } from './graph/engine.ts';
|
|
|
4
4
|
export type { GraphSpec, NodeSpec, NodeDef, ParamDef } from './graph/types.ts';
|
|
5
5
|
export { allNodeDefs, getNodeDef, CATEGORY_ORDER } from './graph/registry.ts';
|
|
6
6
|
export { Geometry, GeoBuilder } from './core/geometry.ts';
|
|
7
|
-
export { renderGeometry } from './render/raster.ts';
|
|
7
|
+
export { renderGeometry, renderGeometryAsync } from './render/raster.ts';
|
|
8
8
|
export { encodePNG } from './render/png.ts';
|
|
9
9
|
export { exportGeometry, exportGeometryAsync } from './io/export.ts';
|
|
10
10
|
export type { ExportFormat, ExportOptions } from './io/export.ts';
|
|
@@ -23,3 +23,5 @@ export { decodePNG, inflateZlib, pngChannel } from './io/png-decode.ts';
|
|
|
23
23
|
export { Image, imagesOf, findImage, imageToBytes } from './core/image.ts';
|
|
24
24
|
export { imagePNG, texturesExport } from './io/textures.ts';
|
|
25
25
|
export { summarize, inspect } from './inspect.ts';
|
|
26
|
+
export { uvReport } from './core/uvreport.ts';
|
|
27
|
+
export type { UVReport, UVReportOptions } from './core/uvreport.ts';
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import './nodes/index.js';
|
|
|
4
4
|
export { Engine } from './graph/engine.js';
|
|
5
5
|
export { allNodeDefs, getNodeDef, CATEGORY_ORDER } from './graph/registry.js';
|
|
6
6
|
export { Geometry, GeoBuilder } from './core/geometry.js';
|
|
7
|
-
export { renderGeometry } from './render/raster.js';
|
|
7
|
+
export { renderGeometry, renderGeometryAsync } from './render/raster.js';
|
|
8
8
|
export { encodePNG } from './render/png.js';
|
|
9
9
|
export { exportGeometry, exportGeometryAsync } from './io/export.js';
|
|
10
10
|
export { importGeometry, importGeometryAsync } from './io/import.js';
|
|
@@ -18,3 +18,4 @@ export { decodePNG, inflateZlib, pngChannel } from './io/png-decode.js';
|
|
|
18
18
|
export { Image, imagesOf, findImage, imageToBytes } from './core/image.js';
|
|
19
19
|
export { imagePNG, texturesExport } from './io/textures.js';
|
|
20
20
|
export { summarize, inspect } from './inspect.js';
|
|
21
|
+
export { uvReport } from './core/uvreport.js';
|
package/dist/inspect.d.ts
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
import { Geometry } from './core/geometry.ts';
|
|
2
2
|
export declare function summarize(g: Geometry): string;
|
|
3
3
|
export interface InspectOptions {
|
|
4
|
-
|
|
4
|
+
/** 'uv': the structured uv report (core/uvreport.ts); not part of 'all' */
|
|
5
|
+
detail?: 'summary' | 'attributes' | 'topology' | 'elements' | 'all' | 'uv';
|
|
5
6
|
cls?: 'point' | 'prim' | 'vertex' | 'detail' | 'edge';
|
|
6
7
|
attribs?: string[];
|
|
7
8
|
start?: number;
|
|
8
9
|
count?: number;
|
|
9
10
|
group?: string;
|
|
11
|
+
/** detail 'uv': uv attribute (default "uv"), texture size for texel density, and the report as JSON after the text */
|
|
12
|
+
uvAttrib?: string;
|
|
13
|
+
uvResolution?: number | [number, number];
|
|
14
|
+
json?: boolean;
|
|
10
15
|
}
|
|
11
16
|
export declare function inspect(g: Geometry, o?: InspectOptions): string;
|
package/dist/inspect.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Text-first geometry introspection for LLMs: compact summaries, attribute statistics,
|
|
2
2
|
// topology health, and element listings.
|
|
3
3
|
import { Geometry } from './core/geometry.js';
|
|
4
|
-
import { primArea, signedVolume, topologyReport } from './core/topology.js';
|
|
4
|
+
import { primArea, signedVolume, topologyReport, triangleReport } from './core/topology.js';
|
|
5
5
|
import { evalGroup } from './core/groups.js';
|
|
6
6
|
import { edgeList } from './core/edges.js';
|
|
7
7
|
import { halfEdges } from './core/halfedge.js';
|
|
@@ -10,6 +10,7 @@ import { packedSummaryLine } from './core/packed.js';
|
|
|
10
10
|
import { heightfieldSummary, volumeCounts } from './core/heightfield.js';
|
|
11
11
|
import { imageSummary } from './core/image.js';
|
|
12
12
|
import { sdfGridSummary } from './core/sdfgrid.js';
|
|
13
|
+
import { uvReport, uvReportText } from './core/uvreport.js';
|
|
13
14
|
const n = (x) => x.toLocaleString('en-US');
|
|
14
15
|
const v3 = (a) => `(${a.map(fmtNum).join(', ')})`;
|
|
15
16
|
const typeCode = (a) => (a.isArray ? a.type : (a.type === 'float' ? 'f' : a.type === 'int' ? 'i' : 's') + a.size);
|
|
@@ -226,6 +227,11 @@ export function inspect(g, o = {}) {
|
|
|
226
227
|
out.push('topology:');
|
|
227
228
|
out.push(` ${r.closed ? 'CLOSED manifold surface (watertight)' : `open/non-manifold: ${r.boundaryEdges} boundary edges, ${r.nonManifoldEdges} non-manifold edges`}`);
|
|
228
229
|
out.push(` ${r.pieces} connected piece(s); ${r.edges} edges; ${r.degenerate} degenerate prims; ${r.unusedPoints} unused points`);
|
|
230
|
+
const t = triangleReport(g);
|
|
231
|
+
if (t.triangles) {
|
|
232
|
+
const ids = (a) => (a.length ? ` (prims ${a.slice(0, 12).join(' ')}${a.length > 12 ? ' …' : ''})` : '');
|
|
233
|
+
out.push(` ${t.triangles} render/export triangles; min area ${fmtNum(t.minArea)}, min quality ${fmtNum(t.minQuality)}; ${t.degenerate} degenerate${ids(t.degeneratePrims)}, ${t.nearDegenerate} near-degenerate${ids(t.nearDegeneratePrims)}`);
|
|
234
|
+
}
|
|
229
235
|
const flipped = halfEdges(g).flippedEdges.size;
|
|
230
236
|
if (flipped)
|
|
231
237
|
out.push(` ${flipped} edge(s) with inconsistent winding between neighbouring polygons (use reverse on part of the mesh or clean fix_winding)`);
|
|
@@ -236,6 +242,12 @@ export function inspect(g, o = {}) {
|
|
|
236
242
|
if (r.closed && r.pieces === 1)
|
|
237
243
|
out.push(` euler ${r.euler} → genus ${(2 - r.euler) / 2}`);
|
|
238
244
|
}
|
|
245
|
+
if (detail === 'uv') {
|
|
246
|
+
const r = uvReport(g, { attribute: o.uvAttrib, resolution: o.uvResolution });
|
|
247
|
+
out.push(...uvReportText(r));
|
|
248
|
+
if (o.json)
|
|
249
|
+
out.push('uv report (JSON):', JSON.stringify(r));
|
|
250
|
+
}
|
|
239
251
|
if ((detail === 'elements' || detail === 'all') && o.cls === 'edge')
|
|
240
252
|
out.push(...edgeElements(g, o));
|
|
241
253
|
else if (detail === 'elements' || detail === 'all') {
|
package/dist/io/common.d.ts
CHANGED
|
@@ -16,6 +16,14 @@ export interface ExportOptions {
|
|
|
16
16
|
custom?: boolean;
|
|
17
17
|
/** glTF: write NORMAL (N if present, else computed with cuspAngle). false = only when N exists. Default true. */
|
|
18
18
|
normals?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* glTF TANGENT accessors (MikkTSpace, xyz + handedness w): 'auto' (default) generates them for primitives whose
|
|
21
|
+
* material has a normal map and writes a valid supplied point/vertex "tangent" (float[4]) attribute on the others
|
|
22
|
+
* (a malformed one is dropped with a warning); 'preserve' writes the supplied attribute everywhere it exists (a
|
|
23
|
+
* malformed one is an error) and generates only where it is missing on normal-mapped primitives; 'none' never
|
|
24
|
+
* writes TANGENT.
|
|
25
|
+
*/
|
|
26
|
+
tangents?: 'auto' | 'preserve' | 'none';
|
|
19
27
|
/** glTF: 'none' (default), 'meshopt' (EXT_meshopt_compression + KHR_mesh_quantization), 'draco' (needs draco3dgltf) */
|
|
20
28
|
compress?: 'none' | 'meshopt' | 'draco';
|
|
21
29
|
/** glTF: KHR_mesh_quantization (16-bit positions, 8-bit normals, 16-bit uv/colour) without compression */
|