@displayxr/inline3d-tools 0.0.1 → 0.1.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/AGENTS.md +351 -0
- package/LICENSE +190 -0
- package/README.md +192 -1
- package/bin/inline3d-tools.mjs +40 -0
- package/lib/assets/asset-check.mjs +262 -0
- package/lib/assets/blender/prep.py +74 -0
- package/lib/assets/prep.mjs +50 -0
- package/lib/check/analyze.mjs +244 -0
- package/lib/check/cdp.mjs +174 -0
- package/lib/check/cli.mjs +66 -0
- package/lib/check/fake-env.js +435 -0
- package/lib/check/png.mjs +75 -0
- package/lib/check/probe.js +245 -0
- package/lib/check/run.mjs +811 -0
- package/lib/check/server.mjs +33 -0
- package/lib/gen.mjs +172 -0
- package/lib/mcp.mjs +168 -0
- package/lib/scaffold.mjs +62 -0
- package/package.json +50 -4
- package/templates/app.js +153 -0
- package/templates/esm/index.html +29 -0
- package/templates/style.css +17 -0
- package/templates/vite/index.html +20 -0
- package/templates/vite/package.template.json +18 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Static file server for a directory target (127.0.0.1, an ephemeral port).
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
4
|
+
import { resolve, join, extname, sep } from 'node:path';
|
|
5
|
+
|
|
6
|
+
const TYPES = {
|
|
7
|
+
'.html': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
|
|
8
|
+
'.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json',
|
|
9
|
+
'.map': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
10
|
+
'.webp': 'image/webp', '.gif': 'image/gif', '.avif': 'image/avif', '.webm': 'video/webm', '.mp4': 'video/mp4',
|
|
11
|
+
'.wasm': 'application/wasm', '.gltf': 'model/gltf+json', '.glb': 'model/gltf-binary', '.bin': 'application/octet-stream',
|
|
12
|
+
'.ktx2': 'image/ktx2', '.sog': 'application/octet-stream', '.ply': 'application/octet-stream', '.woff2': 'font/woff2',
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export function serveDir(rootDir) {
|
|
16
|
+
const root = resolve(rootDir);
|
|
17
|
+
const srv = createServer(async (req, res) => {
|
|
18
|
+
let p;
|
|
19
|
+
try { p = decodeURIComponent(new URL(req.url, 'http://x').pathname); } catch { res.writeHead(400).end(); return; }
|
|
20
|
+
const file = resolve(join(root, p));
|
|
21
|
+
if (file !== root && !file.startsWith(root + sep)) { res.writeHead(403).end(); return; }
|
|
22
|
+
try {
|
|
23
|
+
let f = file;
|
|
24
|
+
if ((await stat(f)).isDirectory()) f = join(f, 'index.html');
|
|
25
|
+
const body = await readFile(f);
|
|
26
|
+
res.writeHead(200, { 'content-type': TYPES[extname(f).toLowerCase()] || 'application/octet-stream', 'cache-control': 'no-store' });
|
|
27
|
+
res.end(body);
|
|
28
|
+
} catch {
|
|
29
|
+
res.writeHead(404, { 'content-type': 'text/plain' }).end('not found');
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
return new Promise((r) => srv.listen(0, '127.0.0.1', () => r({ url: `http://127.0.0.1:${srv.address().port}`, close: () => new Promise((c) => srv.close(() => c())) })));
|
|
33
|
+
}
|
package/lib/gen.mjs
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// inline3d-tools gen — optional online asset generation behind one adapter interface, plus provenance.
|
|
2
|
+
//
|
|
3
|
+
// inline3d-tools gen providers which adapters have a key in the environment (names only)
|
|
4
|
+
// inline3d-tools gen run <adapter> --kind <kind> --prompt "<text>" [--image <url>] [--size WxH] --out <file> --confirm-paid
|
|
5
|
+
// inline3d-tools gen provenance --file <path> --source "<where it came from>" --license "<licence>" [--notes "..."]
|
|
6
|
+
//
|
|
7
|
+
// Kinds: text-to-3d, image-to-3d (3D adapters, output .glb), image (image adapter, output .png:
|
|
8
|
+
// textures, posters, HDR-free backdrops).
|
|
9
|
+
//
|
|
10
|
+
// RULES (the skill repeats them): keys come ONLY from the environment and are never printed,
|
|
11
|
+
// logged, written to a file or committed. Every paid call needs --confirm-paid, which the agent
|
|
12
|
+
// passes only after the user said yes to that call and its estimated cost. Every output gets an
|
|
13
|
+
// ASSETS.md entry (provider, kind, prompt, date, licence note) next to it.
|
|
14
|
+
import { writeFileSync, appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
15
|
+
import { dirname, resolve, relative, join } from 'node:path';
|
|
16
|
+
|
|
17
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
18
|
+
export const GEN_USAGE = 'usage: inline3d-tools gen providers | run <adapter> --kind <kind> --prompt "<text>" [--image <url>] [--size WxH] --out <file> --confirm-paid | provenance --file <f> --source <s> --license <l> [--notes <n>]';
|
|
19
|
+
|
|
20
|
+
// ------------------------------------------------------------------------------ adapters
|
|
21
|
+
// Each adapter: { env, kinds, estimate(kind), terms, async run({ kind, prompt, image }) -> Buffer }.
|
|
22
|
+
// Endpoints follow each provider's public developer API; they are not exercised by this repo's
|
|
23
|
+
// tests (no keys in CI). An adapter that fails says which HTTP status it got and stops.
|
|
24
|
+
async function http(url, init, key) {
|
|
25
|
+
const r = await fetch(url, { ...init, headers: { 'content-type': 'application/json', authorization: `Bearer ${key}`, ...(init.headers || {}) } });
|
|
26
|
+
const text = await r.text();
|
|
27
|
+
if (!r.ok) throw new Error(`${new URL(url).host} answered HTTP ${r.status}: ${text.slice(0, 300).replace(/[A-Za-z0-9_-]{32,}/g, '[redacted]')}`);
|
|
28
|
+
try { return JSON.parse(text); } catch { return text; }
|
|
29
|
+
}
|
|
30
|
+
async function download(url) {
|
|
31
|
+
const r = await fetch(url);
|
|
32
|
+
if (!r.ok) throw new Error(`download failed: HTTP ${r.status}`);
|
|
33
|
+
return Buffer.from(await r.arrayBuffer());
|
|
34
|
+
}
|
|
35
|
+
async function poll(fn, { everyMs = 5000, maxMs = 15 * 60_000 } = {}) {
|
|
36
|
+
const t0 = Date.now();
|
|
37
|
+
for (;;) {
|
|
38
|
+
const v = await fn();
|
|
39
|
+
if (v) return v;
|
|
40
|
+
if (Date.now() - t0 > maxMs) throw new Error('timed out waiting for the task');
|
|
41
|
+
await sleep(everyMs);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const ADAPTERS = {
|
|
46
|
+
meshy: {
|
|
47
|
+
env: 'MESHY_API_KEY',
|
|
48
|
+
kinds: ['text-to-3d', 'image-to-3d'],
|
|
49
|
+
estimate: () => 'a few US$ per model at list price (preview + refine); check the provider\'s current pricing',
|
|
50
|
+
terms: 'Meshy terms of service: check the licence of generated models for your plan before shipping',
|
|
51
|
+
async run({ kind, prompt, image }, key) {
|
|
52
|
+
const base = 'https://api.meshy.ai/openapi';
|
|
53
|
+
let path, id;
|
|
54
|
+
if (kind === 'text-to-3d') {
|
|
55
|
+
path = `${base}/v2/text-to-3d`;
|
|
56
|
+
id = (await http(path, { method: 'POST', body: JSON.stringify({ mode: 'preview', prompt }) }, key)).result;
|
|
57
|
+
await poll(async () => { const t = await http(`${path}/${id}`, { method: 'GET' }, key); if (t.status === 'FAILED') throw new Error('task failed'); return t.status === 'SUCCEEDED' ? t : null; });
|
|
58
|
+
id = (await http(path, { method: 'POST', body: JSON.stringify({ mode: 'refine', preview_task_id: id }) }, key)).result;
|
|
59
|
+
} else {
|
|
60
|
+
path = `${base}/v1/image-to-3d`;
|
|
61
|
+
id = (await http(path, { method: 'POST', body: JSON.stringify({ image_url: image, enable_pbr: true }) }, key)).result;
|
|
62
|
+
}
|
|
63
|
+
const done = await poll(async () => { const t = await http(`${path}/${id}`, { method: 'GET' }, key); if (t.status === 'FAILED') throw new Error('task failed'); return t.status === 'SUCCEEDED' ? t : null; });
|
|
64
|
+
return download(done.model_urls.glb);
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
tripo: {
|
|
68
|
+
env: 'TRIPO_API_KEY',
|
|
69
|
+
kinds: ['text-to-3d', 'image-to-3d'],
|
|
70
|
+
estimate: () => 'tens of provider credits per model (roughly US$0.2–1); check the provider\'s current pricing',
|
|
71
|
+
terms: 'Tripo terms of service: check the licence of generated models for your plan before shipping',
|
|
72
|
+
async run({ kind, prompt, image }, key) {
|
|
73
|
+
const base = 'https://api.tripo3d.ai/v2/openapi';
|
|
74
|
+
const body = kind === 'text-to-3d' ? { type: 'text_to_model', prompt } : { type: 'image_to_model', file: { type: 'jpg', url: image } };
|
|
75
|
+
const id = (await http(`${base}/task`, { method: 'POST', body: JSON.stringify(body) }, key)).data.task_id;
|
|
76
|
+
const done = await poll(async () => { const t = (await http(`${base}/task/${id}`, { method: 'GET' }, key)).data; if (['failed', 'cancelled', 'banned', 'expired'].includes(t.status)) throw new Error(`task ${t.status}`); return t.status === 'success' ? t : null; });
|
|
77
|
+
const url = done.output.pbr_model || done.output.model;
|
|
78
|
+
return download(url);
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
openai: {
|
|
82
|
+
env: 'OPENAI_API_KEY',
|
|
83
|
+
kinds: ['image'],
|
|
84
|
+
estimate: () => 'a few US cents to ~US$0.25 per image depending on size/quality; check the provider\'s current pricing',
|
|
85
|
+
terms: 'OpenAI usage policies: you own generated images subject to their terms',
|
|
86
|
+
async run({ prompt, size }, key) {
|
|
87
|
+
const r = await http('https://api.openai.com/v1/images/generations', { method: 'POST', body: JSON.stringify({ model: process.env.OPENAI_IMAGE_MODEL || 'gpt-image-2.5-flare', prompt, size: size || '1024x1024' }) }, key);
|
|
88
|
+
const d = r.data[0];
|
|
89
|
+
return d.b64_json ? Buffer.from(d.b64_json, 'base64') : download(d.url);
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// ------------------------------------------------------------------------------ provenance
|
|
95
|
+
// The ledger is ASSETS.md in `cwd` (default: the process's working directory = the project root).
|
|
96
|
+
export function provenance({ file, source, license, notes, extra = {}, cwd = process.cwd() }) {
|
|
97
|
+
const abs = resolve(cwd, file);
|
|
98
|
+
const ledger = join(cwd, 'ASSETS.md');
|
|
99
|
+
if (!existsSync(ledger)) writeFileSync(ledger, '# Assets\n\nWhere every 3D asset, texture and image on this page came from, and under what licence.\n\n| file | source | licence | date | notes |\n|---|---|---|---|---|\n');
|
|
100
|
+
const esc = (s) => String(s ?? '').replace(/\|/g, '\\|').replace(/\n/g, ' ');
|
|
101
|
+
const row = `| ${esc(relative(cwd, abs))} | ${esc(source)} | ${esc(license)} | ${new Date().toISOString().slice(0, 10)} | ${esc([notes, ...Object.entries(extra).map(([k, v]) => `${k}: ${v}`)].filter(Boolean).join('; '))} |\n`;
|
|
102
|
+
appendFileSync(ledger, row);
|
|
103
|
+
return ledger;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ------------------------------------------------------------------------------ API
|
|
107
|
+
// Names and key presence only; never the key itself.
|
|
108
|
+
export function listProviders() {
|
|
109
|
+
return Object.entries(ADAPTERS).map(([name, a]) => ({ name, env: a.env, keyPresent: !!process.env[a.env], kinds: a.kinds, cost: a.estimate() }));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export class GenError extends Error {
|
|
113
|
+
constructor(message, code) { super(message); this.code = code; }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Runs one paid generation. Throws GenError with the CLI's exit code: 2 bad arguments, 3 no key in
|
|
117
|
+
// the environment, 4 not confirmed (no call made; the message carries the estimate), 1 provider error.
|
|
118
|
+
export async function genRun({ adapter, kind, prompt = '', image, size, out, confirmPaid = false, cwd = process.cwd() }) {
|
|
119
|
+
const a = ADAPTERS[adapter];
|
|
120
|
+
if (!a) throw new GenError(`unknown adapter "${adapter}" (known: ${Object.keys(ADAPTERS).join(', ')})`, 2);
|
|
121
|
+
if (!a.kinds.includes(kind)) throw new GenError(`${adapter} does ${a.kinds.join(', ')}, not "${kind}"`, 2);
|
|
122
|
+
if (!out) throw new GenError('run needs an output file (--out <file>)', 2);
|
|
123
|
+
const key = process.env[a.env];
|
|
124
|
+
if (!key) throw new GenError(`no ${a.env} in the environment: this adapter is unavailable (keys are read from the environment only)`, 3);
|
|
125
|
+
if (confirmPaid !== true) {
|
|
126
|
+
throw new GenError(`PAID CALL NOT MADE. ${adapter} ${kind} costs ${a.estimate()}.\nAsk the user to approve this one call, then re-run with --confirm-paid.`, 4);
|
|
127
|
+
}
|
|
128
|
+
let bytes;
|
|
129
|
+
try {
|
|
130
|
+
bytes = await a.run({ kind, prompt, image, size }, key);
|
|
131
|
+
} catch (e) {
|
|
132
|
+
throw new GenError(`${adapter} failed: ${String(e.message || e).split(key).join('[redacted]')}`, 1);
|
|
133
|
+
}
|
|
134
|
+
const abs = resolve(cwd, out);
|
|
135
|
+
mkdirSync(dirname(abs), { recursive: true });
|
|
136
|
+
writeFileSync(abs, bytes);
|
|
137
|
+
const ledger = provenance({ file: abs, cwd, source: `generated: ${adapter} ${kind}`, license: a.terms, notes: prompt ? `prompt: ${prompt}` : image ? `from image ${image}` : '' });
|
|
138
|
+
return { file: abs, bytes: bytes.length, ledger, message: `wrote ${out} (${(bytes.length / 1048576).toFixed(2)} MB); provenance in ${ledger}. Next: optimise + asset-check it.` };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ------------------------------------------------------------------------------ CLI
|
|
142
|
+
// Returns the exit code.
|
|
143
|
+
export async function main(args) {
|
|
144
|
+
const cmd = args[0];
|
|
145
|
+
const opt = (k, d = undefined) => { const i = args.indexOf(`--${k}`); return i >= 0 ? args[i + 1] : d; };
|
|
146
|
+
const flag = (k) => args.includes(`--${k}`);
|
|
147
|
+
if (cmd === 'providers') {
|
|
148
|
+
for (const p of listProviders()) {
|
|
149
|
+
console.log(`${p.name.padEnd(8)} ${p.keyPresent ? 'key present' : 'no key'} (${p.env}) kinds: ${p.kinds.join(', ')} cost: ${p.cost}`);
|
|
150
|
+
}
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
153
|
+
if (cmd === 'provenance') {
|
|
154
|
+
const file = opt('file');
|
|
155
|
+
if (!file) { console.error('provenance needs --file'); return 2; }
|
|
156
|
+
const l = provenance({ file, source: opt('source', 'unknown'), license: opt('license', 'unknown: check before shipping'), notes: opt('notes') });
|
|
157
|
+
console.log(`recorded ${file} in ${l}`);
|
|
158
|
+
return 0;
|
|
159
|
+
}
|
|
160
|
+
if (cmd === 'run') {
|
|
161
|
+
try {
|
|
162
|
+
const r = await genRun({ adapter: args[1], kind: opt('kind'), prompt: opt('prompt', ''), image: opt('image'), size: opt('size'), out: opt('out'), confirmPaid: flag('confirm-paid') });
|
|
163
|
+
console.log(r.message);
|
|
164
|
+
return 0;
|
|
165
|
+
} catch (e) {
|
|
166
|
+
console.error(e.message);
|
|
167
|
+
return e.code || 1;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
console.error(GEN_USAGE);
|
|
171
|
+
return cmd === '-h' || cmd === '--help' ? 0 : 2;
|
|
172
|
+
}
|
package/lib/mcp.mjs
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// inline3d-tools mcp — a stdio MCP server exposing the same operations as the CLI, for any MCP
|
|
2
|
+
// client (Claude Code, OpenAI Codex, Cursor, ...).
|
|
3
|
+
//
|
|
4
|
+
// inline3d-tools mcp
|
|
5
|
+
//
|
|
6
|
+
// Tools: check, asset_check, scaffold, gen_providers, gen_run, gen_provenance, authoring_guide.
|
|
7
|
+
// Relative paths resolve against the server's working directory (start it in the project root, or
|
|
8
|
+
// set the client's `cwd`). Generator keys come from the server's environment only and are never
|
|
9
|
+
// returned, logged or written. gen_run makes a paid call only when `confirm_paid` is literally
|
|
10
|
+
// true, which an agent may pass only after the user approved that one call and its cost.
|
|
11
|
+
import { readFileSync } from 'node:fs';
|
|
12
|
+
import { dirname, join } from 'node:path';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
15
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
16
|
+
import * as z from 'zod';
|
|
17
|
+
import { runCheck, formatHuman, VERSION } from './check/run.mjs';
|
|
18
|
+
import { assetCheck, formatAssetReport } from './assets/asset-check.mjs';
|
|
19
|
+
import { scaffold } from './scaffold.mjs';
|
|
20
|
+
import { listProviders, genRun, provenance, ADAPTERS } from './gen.mjs';
|
|
21
|
+
|
|
22
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
23
|
+
|
|
24
|
+
// Every env key value a generator could read, so no tool result can ever echo one.
|
|
25
|
+
function redact(text) {
|
|
26
|
+
let s = String(text);
|
|
27
|
+
for (const a of Object.values(ADAPTERS)) {
|
|
28
|
+
const k = process.env[a.env];
|
|
29
|
+
if (k && k.length >= 8) s = s.split(k).join('[redacted]');
|
|
30
|
+
}
|
|
31
|
+
return s;
|
|
32
|
+
}
|
|
33
|
+
const ok = (text, structured) => ({ content: [{ type: 'text', text: redact(text) }], ...(structured ? { structuredContent: JSON.parse(redact(JSON.stringify(structured))) } : {}) });
|
|
34
|
+
const fail = (text) => ({ isError: true, content: [{ type: 'text', text: redact(text) }] });
|
|
35
|
+
|
|
36
|
+
export function createServer() {
|
|
37
|
+
const server = new McpServer({ name: 'displayxr-inline3d-tools', version: VERSION });
|
|
38
|
+
|
|
39
|
+
server.registerTool('check', {
|
|
40
|
+
title: 'Check an inline-3D page',
|
|
41
|
+
description: 'Load an @displayxr/inline3d page in headless Chrome twice: inside a fake DisplayXR Browser (two real eye views) and plain (the 2D fallback). Returns pass/warn/fail per rule (session, stereo, blank eyes, flat side-by-side, buffer, CSS, overlay, layer-lost, console, 2D fallback, detection, pins, depth). Needs a local Chrome. A pass is a fake-environment check, not a test on a real 3D panel. Read-only on the project.',
|
|
42
|
+
inputSchema: {
|
|
43
|
+
target: z.string().describe('A running page URL (http://localhost:5173/), a directory holding index.html, or an .html file'),
|
|
44
|
+
root: z.string().optional().describe('Directory to serve; use the project root when the page imports ../ or /node_modules/'),
|
|
45
|
+
max_texture: z.number().int().positive().optional().describe('Simulate a device MAX_TEXTURE_SIZE (4096 = the Android tablet)'),
|
|
46
|
+
timeout_ms: z.number().int().positive().optional().describe('How long to wait for the 3D run to settle (default 15000)'),
|
|
47
|
+
viewport: z.string().regex(/^\d+x\d+$/).optional().describe('WxH, default 1280x800'),
|
|
48
|
+
fallback: z.boolean().optional().describe('Also run the plain-browser (2D fallback) pass (default true)'),
|
|
49
|
+
},
|
|
50
|
+
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
|
|
51
|
+
}, async ({ target, root, max_texture, timeout_ms, viewport, fallback }) => {
|
|
52
|
+
const opt = {};
|
|
53
|
+
if (root) opt.root = root;
|
|
54
|
+
if (max_texture) opt.maxTexture = max_texture;
|
|
55
|
+
if (timeout_ms) opt.timeoutMs = timeout_ms;
|
|
56
|
+
if (fallback === false) opt.fallback = false;
|
|
57
|
+
if (viewport) { const [w, h] = viewport.split('x').map(Number); opt.viewport = { width: w, height: h, dpr: 1 }; }
|
|
58
|
+
try {
|
|
59
|
+
const r = await runCheck(target, opt);
|
|
60
|
+
return ok(`${formatHuman(r)}\n\nFix every FAIL (each line names the rule and the doc under node_modules/@displayxr/inline3d/docs/), re-run until nothing fails, and judge every WARN.`, r);
|
|
61
|
+
} catch (e) { return fail(`check could not run: ${e.message}`); }
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
server.registerTool('asset_check', {
|
|
65
|
+
title: 'Check a glTF/GLB asset',
|
|
66
|
+
description: 'Is this glTF/GLB ready for an inline-3D page? Reports missing external files, decoders the page must serve, triangles (both eyes draw them), draw calls, size/units/pivot, texture sizes and decoded GPU memory, alpha-BLEND and metal/glass materials, file size, animations, against a tablet (default) or desktop budget. Read-only, no network.',
|
|
67
|
+
inputSchema: {
|
|
68
|
+
file: z.string().describe('Path to a .glb or .gltf'),
|
|
69
|
+
target: z.enum(['tablet', 'desktop']).optional().describe('Device budget (default tablet: the weakest supported device)'),
|
|
70
|
+
},
|
|
71
|
+
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
|
|
72
|
+
}, async ({ file, target }) => {
|
|
73
|
+
try {
|
|
74
|
+
const r = assetCheck(file, { target: target || 'tablet' });
|
|
75
|
+
return ok(formatAssetReport(r), r);
|
|
76
|
+
} catch (e) { return fail(`asset_check: ${e.message}`); }
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
server.registerTool('scaffold', {
|
|
80
|
+
title: 'Scaffold an inline-3D page',
|
|
81
|
+
description: 'Copy a known-good page template into a directory: esm (index.html with an import map of exact CDN pins + app.js + style.css, no build step) or vite (adds package.json with exact npm pins). One persistent canvas, a cover that always comes off, a mono 2D fallback. Refuses to overwrite existing files unless force is true.',
|
|
82
|
+
inputSchema: {
|
|
83
|
+
flavour: z.enum(['esm', 'vite']).describe('esm unless the project already uses npm/a bundler'),
|
|
84
|
+
dir: z.string().describe('Target directory (created if missing)'),
|
|
85
|
+
title: z.string().optional().describe('Page title'),
|
|
86
|
+
name: z.string().optional().describe('npm package name for the vite flavour (default: the directory name)'),
|
|
87
|
+
force: z.boolean().optional().describe('Overwrite existing files'),
|
|
88
|
+
},
|
|
89
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
|
|
90
|
+
}, async (a) => {
|
|
91
|
+
try {
|
|
92
|
+
const r = scaffold(a);
|
|
93
|
+
return ok(`scaffolded ${r.flavour} page in ${r.dir}:\n${r.files.map((f) => ` ${f}`).join('\n')}\nNext: run the check tool on it before calling it done.`, r);
|
|
94
|
+
} catch (e) { return fail(`scaffold: ${e.message}`); }
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
server.registerTool('gen_providers', {
|
|
98
|
+
title: 'List asset generators',
|
|
99
|
+
description: 'Which optional paid generator adapters (meshy, tripo: text/image to GLB; openai: image) have an API key in the server environment. Names and presence only; never a key.',
|
|
100
|
+
inputSchema: {},
|
|
101
|
+
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
|
|
102
|
+
}, async () => {
|
|
103
|
+
const p = listProviders();
|
|
104
|
+
return ok(p.map((x) => `${x.name.padEnd(8)} ${x.keyPresent ? 'key present' : 'no key'} (${x.env}) kinds: ${x.kinds.join(', ')} cost: ${x.cost}`).join('\n'), { providers: p });
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
server.registerTool('gen_run', {
|
|
108
|
+
title: 'Generate an asset (PAID)',
|
|
109
|
+
description: 'PAID: send a prompt or image URL to one generator provider with the user\'s own key (from the server environment) and write the result plus an ASSETS.md provenance row. Ask the user before EVERY call: tell them the adapter, the prompt/image and the cost estimate (call once with confirm_paid=false to get it; no call is made). Only after they say yes, call again with confirm_paid=true. One yes covers one call.',
|
|
110
|
+
inputSchema: {
|
|
111
|
+
adapter: z.enum(Object.keys(ADAPTERS)).describe('meshy | tripo (text-to-3d, image-to-3d) | openai (image)'),
|
|
112
|
+
kind: z.enum(['text-to-3d', 'image-to-3d', 'image']),
|
|
113
|
+
prompt: z.string().optional(),
|
|
114
|
+
image: z.string().url().optional().describe('Source image URL for image-to-3d'),
|
|
115
|
+
size: z.string().optional().describe('Image size for the openai adapter, e.g. 1024x1024'),
|
|
116
|
+
out: z.string().describe('Output file (.glb for 3D, .png for images)'),
|
|
117
|
+
confirm_paid: z.boolean().describe('true ONLY after the user approved this one paid call and its estimated cost'),
|
|
118
|
+
},
|
|
119
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true, idempotentHint: false },
|
|
120
|
+
}, async (a) => {
|
|
121
|
+
try {
|
|
122
|
+
const r = await genRun({ adapter: a.adapter, kind: a.kind, prompt: a.prompt || '', image: a.image, size: a.size, out: a.out, confirmPaid: a.confirm_paid === true });
|
|
123
|
+
return ok(r.message, { file: r.file, bytes: r.bytes, ledger: r.ledger });
|
|
124
|
+
} catch (e) { return fail(e.message); }
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
server.registerTool('gen_provenance', {
|
|
128
|
+
title: 'Record asset provenance',
|
|
129
|
+
description: 'Append a row (file, source, licence, date, notes) to ASSETS.md in the server working directory, creating it if needed. Use for every asset the page loads that you did not write.',
|
|
130
|
+
inputSchema: {
|
|
131
|
+
file: z.string(),
|
|
132
|
+
source: z.string().describe('URL, "supplied by the user", or "generated: <adapter> <kind>"'),
|
|
133
|
+
license: z.string(),
|
|
134
|
+
notes: z.string().optional(),
|
|
135
|
+
},
|
|
136
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
|
|
137
|
+
}, async (a) => {
|
|
138
|
+
try {
|
|
139
|
+
const l = provenance(a);
|
|
140
|
+
return ok(`recorded ${a.file} in ${l}`, { ledger: l });
|
|
141
|
+
} catch (e) { return fail(`gen_provenance: ${e.message}`); }
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
server.registerTool('authoring_guide', {
|
|
145
|
+
title: 'Inline-3D authoring guide',
|
|
146
|
+
description: 'The authoring checklist for @displayxr/inline3d pages (content type and entry point, view rig, depth/comfort, woven-canvas rules, page chrome, exact pins, asset workflow). Read it before writing or fixing a page.',
|
|
147
|
+
inputSchema: {},
|
|
148
|
+
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
|
|
149
|
+
}, async () => ok(readFileSync(join(HERE, '..', 'AGENTS.md'), 'utf8')));
|
|
150
|
+
|
|
151
|
+
return server;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function main() {
|
|
155
|
+
// stdout carries the protocol: anything else printed there would corrupt it.
|
|
156
|
+
console.log = console.info = console.debug = (...a) => console.error(...a);
|
|
157
|
+
const server = createServer();
|
|
158
|
+
// Resolves when the client disconnects (closes our stdin), so the process exits cleanly.
|
|
159
|
+
const closed = new Promise((resolve) => {
|
|
160
|
+
server.server.onclose = resolve;
|
|
161
|
+
process.stdin.once('end', resolve);
|
|
162
|
+
});
|
|
163
|
+
await server.connect(new StdioServerTransport());
|
|
164
|
+
console.error(`inline3d-tools mcp ${VERSION}: ready on stdio`);
|
|
165
|
+
await closed;
|
|
166
|
+
await server.close().catch(() => {});
|
|
167
|
+
return 0;
|
|
168
|
+
}
|
package/lib/scaffold.mjs
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// inline3d-tools scaffold — copy a known-good inline-3D page template into a directory.
|
|
2
|
+
//
|
|
3
|
+
// inline3d-tools scaffold <esm|vite> <target-dir> [--title "<page title>"] [--name <npm-name>] [--force]
|
|
4
|
+
//
|
|
5
|
+
// esm = no build step: index.html with an import map of exact CDN pins + app.js + style.css
|
|
6
|
+
// vite = index.html + app.js + style.css + package.json with exact npm pins
|
|
7
|
+
// The untouched template passes every `inline3d-tools check` rule. Never overwrites an existing
|
|
8
|
+
// file unless --force is given.
|
|
9
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
10
|
+
import { dirname, join, resolve, basename } from 'node:path';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
|
|
13
|
+
export const TEMPLATES = join(dirname(fileURLToPath(import.meta.url)), '..', 'templates');
|
|
14
|
+
export const SCAFFOLD_USAGE = 'usage: inline3d-tools scaffold <esm|vite> <target-dir> [--title "<page title>"] [--name <npm-name>] [--force]';
|
|
15
|
+
|
|
16
|
+
// [template path, output name] per flavour.
|
|
17
|
+
const FILES = {
|
|
18
|
+
esm: [['app.js', 'app.js'], ['style.css', 'style.css'], ['esm/index.html', 'index.html']],
|
|
19
|
+
vite: [['app.js', 'app.js'], ['style.css', 'style.css'], ['vite/index.html', 'index.html'], ['vite/package.template.json', 'package.json']],
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const npmName = (s) => String(s).toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[-._]+|[-._]+$/g, '') || 'inline3d-page';
|
|
23
|
+
|
|
24
|
+
export function scaffold({ flavour = 'esm', dir, title, name, force = false }) {
|
|
25
|
+
if (!FILES[flavour]) throw new Error(`unknown flavour "${flavour}" (esm | vite)`);
|
|
26
|
+
if (!dir) throw new Error('scaffold needs a target directory');
|
|
27
|
+
const abs = resolve(dir);
|
|
28
|
+
const t = title || 'Inline 3D page';
|
|
29
|
+
const n = npmName(name || basename(abs));
|
|
30
|
+
const plan = FILES[flavour].map(([src, out]) => ({ src: join(TEMPLATES, src), out: join(abs, out) }));
|
|
31
|
+
const clash = plan.filter((p) => existsSync(p.out));
|
|
32
|
+
if (clash.length && !force) throw new Error(`would overwrite ${clash.map((p) => p.out).join(', ')} (pass --force to replace)`);
|
|
33
|
+
mkdirSync(abs, { recursive: true });
|
|
34
|
+
const written = [];
|
|
35
|
+
for (const p of plan) {
|
|
36
|
+
const text = readFileSync(p.src, 'utf8').replaceAll('__TITLE__', t).replaceAll('__NAME__', n);
|
|
37
|
+
mkdirSync(dirname(p.out), { recursive: true });
|
|
38
|
+
writeFileSync(p.out, text);
|
|
39
|
+
written.push(p.out);
|
|
40
|
+
}
|
|
41
|
+
return { flavour, dir: abs, files: written };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Returns the exit code.
|
|
45
|
+
export function main(argv) {
|
|
46
|
+
if (argv.includes('-h') || argv.includes('--help')) { console.log(SCAFFOLD_USAGE); return 0; }
|
|
47
|
+
const val = (k) => { const i = argv.indexOf(`--${k}`); return i >= 0 ? argv[i + 1] : undefined; };
|
|
48
|
+
const pos = argv.filter((a, i) => !a.startsWith('--') && !['--title', '--name'].includes(argv[i - 1]));
|
|
49
|
+
const [flavour, dir] = pos;
|
|
50
|
+
if (!flavour || !dir) { console.error(SCAFFOLD_USAGE); return 2; }
|
|
51
|
+
try {
|
|
52
|
+
const r = scaffold({ flavour, dir, title: val('title'), name: val('name'), force: argv.includes('--force') });
|
|
53
|
+
console.log(`scaffolded ${r.flavour} page in ${r.dir}:\n${r.files.map((f) => ` ${f}`).join('\n')}`);
|
|
54
|
+
console.log(r.flavour === 'esm'
|
|
55
|
+
? `next: inline3d-tools check ${dir}`
|
|
56
|
+
: `next: cd ${dir} && npm install && npm run dev, then inline3d-tools check http://localhost:5173/`);
|
|
57
|
+
return 0;
|
|
58
|
+
} catch (e) {
|
|
59
|
+
console.error(`scaffold: ${e.message}`);
|
|
60
|
+
return 2;
|
|
61
|
+
}
|
|
62
|
+
}
|
package/package.json
CHANGED
|
@@ -1,8 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@displayxr/inline3d-tools",
|
|
3
|
-
"version": "0.0
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Agent-agnostic tools for @displayxr/inline3d pages: a headless checker (fake DisplayXR Browser + plain 2D run), a glTF/GLB asset check, page scaffolds, optional asset generation with provenance, and a stdio MCP server exposing the same operations.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"inline3d-tools": "./bin/inline3d-tools.mjs"
|
|
8
|
+
},
|
|
9
|
+
"exports": {
|
|
10
|
+
"./package.json": "./package.json"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"bin/",
|
|
14
|
+
"lib/",
|
|
15
|
+
"templates/",
|
|
16
|
+
"AGENTS.md",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
},
|
|
23
|
+
"scripts": {
|
|
24
|
+
"test": "node --test test/*.test.mjs"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@modelcontextprotocol/sdk": "1.32.2",
|
|
28
|
+
"zod": "4.6.7"
|
|
29
|
+
},
|
|
30
|
+
"keywords": [
|
|
31
|
+
"displayxr",
|
|
32
|
+
"inline-3d",
|
|
33
|
+
"glasses-free-3d",
|
|
34
|
+
"3d-display",
|
|
35
|
+
"mcp",
|
|
36
|
+
"model-context-protocol",
|
|
37
|
+
"agent",
|
|
38
|
+
"gltf",
|
|
39
|
+
"checker"
|
|
40
|
+
],
|
|
41
|
+
"homepage": "https://github.com/DisplayXR/displayxr-web/tree/main/tools/inline3d-tools#readme",
|
|
42
|
+
"repository": {
|
|
43
|
+
"type": "git",
|
|
44
|
+
"url": "git+https://github.com/DisplayXR/displayxr-web.git",
|
|
45
|
+
"directory": "tools/inline3d-tools"
|
|
46
|
+
},
|
|
47
|
+
"bugs": {
|
|
48
|
+
"url": "https://github.com/DisplayXR/displayxr-web/issues"
|
|
49
|
+
},
|
|
5
50
|
"license": "Apache-2.0",
|
|
6
|
-
"
|
|
7
|
-
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public"
|
|
53
|
+
}
|
|
8
54
|
}
|
package/templates/app.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// A known-good inline-3D page: one persistent canvas, a cover that always comes off, a 2D fallback.
|
|
2
|
+
// Display rig (the user turns a SUBJECT). Scene units are metres for a 0.24 m virtual display;
|
|
3
|
+
// the subject straddles z = 0 (the glass). Replace buildScene() with your content.
|
|
4
|
+
import * as THREE from 'three';
|
|
5
|
+
import { createInline3D } from '@displayxr/inline3d';
|
|
6
|
+
import { EyeCamera } from '@displayxr/inline3d/three';
|
|
7
|
+
|
|
8
|
+
const VIRTUAL_DISPLAY_HEIGHT = 0.24; // metres of virtual display the canvas shows
|
|
9
|
+
const canvas = document.getElementById('stage');
|
|
10
|
+
const cover = document.getElementById('cover');
|
|
11
|
+
const statusEl = document.getElementById('status');
|
|
12
|
+
|
|
13
|
+
// ---- the cover: on top of the canvas, removed by a hard cut, and ALWAYS removed --------------
|
|
14
|
+
let coverDone = false;
|
|
15
|
+
function dropCover() {
|
|
16
|
+
if (coverDone) return;
|
|
17
|
+
coverDone = true;
|
|
18
|
+
cover.remove();
|
|
19
|
+
}
|
|
20
|
+
const coverTimer = setTimeout(dropCover, 4000); // a missed signal never leaves the page without its scene
|
|
21
|
+
|
|
22
|
+
// ---- renderer + scene --------------------------------------------------------------------
|
|
23
|
+
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
|
|
24
|
+
renderer.setPixelRatio(1); // getViewport() returns buffer pixels; three must not rescale them
|
|
25
|
+
renderer.autoClear = false;
|
|
26
|
+
renderer.setClearColor(0x9aa3ad, 1); // mid-tone, low contrast behind the subject (never pure black)
|
|
27
|
+
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
|
28
|
+
|
|
29
|
+
const scene = new THREE.Scene();
|
|
30
|
+
const subject = buildScene(scene);
|
|
31
|
+
|
|
32
|
+
function buildScene(s) {
|
|
33
|
+
s.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.6));
|
|
34
|
+
const key = new THREE.DirectionalLight(0xffffff, 1.6);
|
|
35
|
+
key.position.set(0.3, 0.5, 0.6);
|
|
36
|
+
s.add(key);
|
|
37
|
+
// ~0.11 m across: about half the virtual display's height, centred on the glass (z = 0).
|
|
38
|
+
const mesh = new THREE.Mesh(
|
|
39
|
+
new THREE.TorusKnotGeometry(0.035, 0.011, 160, 24),
|
|
40
|
+
new THREE.MeshStandardMaterial({ color: 0xd9822b, roughness: 0.45, metalness: 0.1 }),
|
|
41
|
+
);
|
|
42
|
+
s.add(mesh);
|
|
43
|
+
return mesh;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Rotate the SUBJECT, not the camera (display rig).
|
|
47
|
+
let last = performance.now();
|
|
48
|
+
function animate(now) {
|
|
49
|
+
const dt = Math.min(0.05, (now - last) / 1000);
|
|
50
|
+
last = now;
|
|
51
|
+
subject.rotation.y += dt * 0.5;
|
|
52
|
+
subject.rotation.x = 0.35;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// ---- backing store: 2 x the box in 3D, 1 x in 2D; dpr <= 2; within the GPU's limits ---------
|
|
56
|
+
function sizeBuffer(stereo) {
|
|
57
|
+
const r = canvas.getBoundingClientRect();
|
|
58
|
+
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
|
59
|
+
let w = Math.round(r.width * dpr * (stereo ? 2 : 1));
|
|
60
|
+
let h = Math.round(r.height * dpr);
|
|
61
|
+
const gl = renderer.getContext();
|
|
62
|
+
const max = Math.min(gl.getParameter(gl.MAX_TEXTURE_SIZE), gl.getParameter(gl.MAX_RENDERBUFFER_SIZE), ...gl.getParameter(gl.MAX_VIEWPORT_DIMS));
|
|
63
|
+
const k = Math.min(1, max / Math.max(w, h)); // one factor for both axes keeps the eyes' shape
|
|
64
|
+
w = Math.max(2, Math.floor(w * k) & ~1);
|
|
65
|
+
h = Math.max(1, Math.floor(h * k));
|
|
66
|
+
// Writing width/height clears the buffer even when the value is the same: only on a change.
|
|
67
|
+
if (canvas.width !== w || canvas.height !== h) {
|
|
68
|
+
canvas.width = w;
|
|
69
|
+
canvas.height = h;
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ---- 2D fallback: one mono camera framed like the virtual display ----------------------------
|
|
76
|
+
const monoCam = new THREE.PerspectiveCamera(35, 1, 0.01, 10);
|
|
77
|
+
monoCam.position.set(0, 0, VIRTUAL_DISPLAY_HEIGHT / 2 / Math.tan(THREE.MathUtils.degToRad(35 / 2)));
|
|
78
|
+
function render2D(now) {
|
|
79
|
+
sizeBuffer(false);
|
|
80
|
+
animate(now);
|
|
81
|
+
monoCam.aspect = canvas.width / canvas.height;
|
|
82
|
+
monoCam.updateProjectionMatrix();
|
|
83
|
+
renderer.setViewport(0, 0, canvas.width, canvas.height);
|
|
84
|
+
renderer.clear();
|
|
85
|
+
renderer.render(scene, monoCam);
|
|
86
|
+
requestAnimationFrame(render2D);
|
|
87
|
+
}
|
|
88
|
+
function start2D(reason) {
|
|
89
|
+
statusEl.textContent = `2D (${reason})`;
|
|
90
|
+
clearTimeout(coverTimer);
|
|
91
|
+
dropCover();
|
|
92
|
+
requestAnimationFrame(render2D);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ---- 3D -------------------------------------------------------------------------------------
|
|
96
|
+
const eye = new EyeCamera(THREE);
|
|
97
|
+
const lastGood = [0, 1].map(() => ({ proj: new Float32Array(16), xf: new Float32Array(16), vp: null }));
|
|
98
|
+
let haveLast = false;
|
|
99
|
+
|
|
100
|
+
function drawEyes(eyes) {
|
|
101
|
+
renderer.setScissorTest(true);
|
|
102
|
+
renderer.setViewport(0, 0, canvas.width, canvas.height);
|
|
103
|
+
renderer.setScissor(0, 0, canvas.width, canvas.height);
|
|
104
|
+
renderer.clear();
|
|
105
|
+
for (const e of eyes) {
|
|
106
|
+
renderer.setViewport(e.vp.x, e.vp.y, e.vp.width, e.vp.height);
|
|
107
|
+
renderer.setScissor(e.vp.x, e.vp.y, e.vp.width, e.vp.height);
|
|
108
|
+
eye.setFromMatrices(e.proj, e.xf);
|
|
109
|
+
renderer.render(scene, eye.camera);
|
|
110
|
+
}
|
|
111
|
+
renderer.setScissorTest(false);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function onFrame(views, layer) {
|
|
115
|
+
animate(performance.now());
|
|
116
|
+
// Validate BEFORE clearing: a short view list or a null viewport must not become a black frame.
|
|
117
|
+
const vps = views.length >= 2 ? views.map((v) => layer.getViewport(v)) : null;
|
|
118
|
+
if (vps && vps.every(Boolean)) {
|
|
119
|
+
views.forEach((v, i) => {
|
|
120
|
+
const g = lastGood[i];
|
|
121
|
+
g.proj.set(v.projectionMatrix);
|
|
122
|
+
g.xf.set(v.transform.matrix);
|
|
123
|
+
const vp = vps[i];
|
|
124
|
+
g.vp = { x: vp.x, y: vp.y, width: vp.width, height: vp.height }; // copy fields by name
|
|
125
|
+
});
|
|
126
|
+
haveLast = true;
|
|
127
|
+
}
|
|
128
|
+
if (haveLast) drawEyes(lastGood); // also repaints the last good frame when this one was short
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function start() {
|
|
132
|
+
const wall = await createInline3D();
|
|
133
|
+
if (!wall.supported) return start2D('no inline 3D here');
|
|
134
|
+
sizeBuffer(true); // size before registering (woven-canvas rule 4)
|
|
135
|
+
const handle = wall.addScene(canvas, onFrame, {
|
|
136
|
+
virtualDisplayHeight: VIRTUAL_DISPLAY_HEIGHT,
|
|
137
|
+
onResize: () => { if (sizeBuffer(true) && haveLast) drawEyes(lastGood); }, // repaint at once
|
|
138
|
+
// The layer went away for good (session ended / layer failed): go flat. An empty callback
|
|
139
|
+
// would leave the last side-by-side pair on screen, unwoven.
|
|
140
|
+
onLayerLost: () => start2D('3D layer lost'),
|
|
141
|
+
});
|
|
142
|
+
statusEl.textContent = 'glasses-free 3D';
|
|
143
|
+
addEventListener('pagehide', () => wall.close());
|
|
144
|
+
const result = await handle.firstWoven; // never rejects
|
|
145
|
+
clearTimeout(coverTimer);
|
|
146
|
+
dropCover(); // woven or not: drop it and keep drawing both eyes
|
|
147
|
+
if (!result.woven) statusEl.textContent = `3D (${result.reason})`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
start().catch((err) => {
|
|
151
|
+
console.warn('inline 3D setup failed, showing 2D', err);
|
|
152
|
+
start2D('error');
|
|
153
|
+
});
|