Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(forge): add an opt-in lods option that stores a real MSFT_lod chain variant
nirholas10983f31571f
diff --git a/api/_lib/forge-options.js b/api/_lib/forge-options.jsindex a4a79fc21..44adb3ed9 100644--- a/api/_lib/forge-options.js+++ b/api/_lib/forge-options.js@@ -20,6 +20,10 @@// completion pass (glb-pbr-derive.js) runs on every delivered mesh, because// an albedo-only material is a defect rather than a preference. Send// `derive_pbr: false` to receive the lane's own materials untouched.+// • lods : opt-IN. Build a real MSFT_lod chain (packages/glb-tools+// buildLodChain) alongside the base mesh and store it as a separate variant,+// same real-decimation work the Engine QA panel's "Build & grade LOD chain"+// upgrade already triggers on demand (see public/engine-qa-panel.js).//// normalizeForgeOptions() validates and clamps; an explicitly-present but invalid// value is reported in `errors` so the endpoint can answer 400 with an actionable@@ -60,6 +64,7 @@ function compressionFor(format) {* fillOtherSides: boolean, // synthesize the other sides from one photo* numParts: number | null, // PartCrafter's requested part count (2-16)* derivePbr: boolean, // material completion pass, true unless opted out+ * lods: boolean, // build and store a real MSFT_lod chain, opt-in* hasOptions: boolean, // true iff any non-default option was supplied* errors: Array<{ field: string, message: string }>,* }}@@ -203,6 +208,17 @@ export function normalizeForgeOptions(body) {}}+ // lods: opt-IN. Builds a real LOD chain in addition to the base mesh; off by+ // default because it is real decimation work, same reasoning as fill_other_sides.+ let lods = false;+ if (b.lods !== undefined && b.lods !== null) {+ if (typeof b.lods !== 'boolean') {+ errors.push({ field: 'lods', message: 'lods must be true or false.' });+ } else {+ lods = b.lods;+ }+ }+const hasOptions =seed !== null ||outputFormat !== 'glb' ||@@ -212,7 +228,8 @@ export function normalizeForgeOptions(body) {viewLabels !== null ||fillOtherSides ||numParts !== null ||- !derivePbr;+ !derivePbr ||+ lods;return {seed,@@ -225,6 +242,7 @@ export function normalizeForgeOptions(body) {fillOtherSides,numParts,derivePbr,+ lods,hasOptions,errors,};@@ -261,5 +279,6 @@ export function summarizeForgeOptions(opts) {fill_other_sides: Boolean(opts.fillOtherSides),num_parts: opts.numParts ?? null,derive_pbr: opts.derivePbr !== false,+ lods: Boolean(opts.lods),};}diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex 728b3e5e2..1a48f64a2 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -558,6 +558,50 @@ export function buildWebVariant({ buffer, creationId, keyPrefix }) {});}+// The opt-in LOD chain variant: a real MSFT_lod GLB (packages/glb-tools's+// buildLodChain, meshoptimizer decimation) a real-time engine can switch levels+// from at runtime, built alongside the base mesh when the caller asks for it+// (forge-options.js's `lods` flag). Same reasoning as buildWebVariant above:+// a SECOND object (glb_url stays exactly the requested output_format), built+// fire-and-forget after the row is already 'done' so a slow or failed build+// never delays delivery of the mesh itself. lod_levels carries the per-level+// triangle/vertex counts so a reader never has to fetch and parse the GLB just+// to show the chain's shape.+export function buildLodVariant({ buffer, creationId, keyPrefix }) {+ if (!buffer?.length) return Promise.resolve(null);+ const key = `${keyPrefix}.lod.glb`;+ return Promise.resolve()+ .then(() => import('../../packages/glb-tools/src/lod.js'))+ .then(({ buildLodChain }) => buildLodChain(buffer))+ .then(async (chain) => {+ const levels = chain.levels.map((l) => ({+ name: l.name,+ ratio: l.ratio,+ triangleCount: l.triangleCount,+ vertexCount: l.vertexCount,+ }));+ await putObject({+ key,+ body: chain.combined,+ contentType: 'model/gltf-binary',+ metadata: { source: 'forge-lod-variant' },+ });+ await sql`+ update forge_creations+ set lod_glb_key = ${key},+ lod_glb_url = ${publicUrl(key)},+ lod_levels = ${JSON.stringify(levels)},+ updated_at = now()+ where id = ${creationId}+ `;+ return { key, url: publicUrl(key), levels };+ })+ .catch((err) => {+ console.warn('[forge-store] LOD chain variant failed:', err?.message);+ return null;+ });+}+// Copy a finished generation into durable storage and flip the row to 'done'.// Copies the mesh (required) and the reference image (best-effort). Returns the// durable { id, glbUrl, previewImageUrl, quality, compression } or null on any@@ -584,7 +628,11 @@ export function buildWebVariant({ buffer, creationId, keyPrefix }) {// glTF's default fully-metallic material renders them as rough// metal). Best-effort like the rest of the chain; pass false to// deliver the lane's own materials untouched.-export async function materializeCreation({ replicateJobId, clientKey, glbUrl, quality = false, compress = null, cleanup = true, derivePbr = true }) {+// lods - build and store a real MSFT_lod chain (buildLodVariant above).+// Off by default: it is real decimation work, worth its own opt-in+// exactly like forge-options.js documents. Fire-and-forget, same+// as the web-delivery variant it sits beside.+export async function materializeCreation({ replicateJobId, clientKey, glbUrl, quality = false, compress = null, cleanup = true, derivePbr = true, lods = false }) {if (!forgeStoreEnabled() || !replicateJobId || !glbUrl) return null;const existing = await findByJob({ replicateJobId, clientKey });if (!existing) return null;@@ -670,6 +718,8 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl, q// …and a phone-sized delivery variant. See buildWebVariant for why this is// a second object and why it runs after the row is already 'done'.buildWebVariant({ buffer: glb.buffer, creationId: existing.id, keyPrefix });+ // …and, when the caller opted in, a real LOD chain. See buildLodVariant.+ if (lods) buildLodVariant({ buffer: glb.buffer, creationId: existing.id, keyPrefix });// A finished, signed-in creation is a qualifying streak action + the// trigger for the "first creation" badge. Fire-and-forget — never blocks// delivery of the model itself.diff --git a/api/_lib/migrations/20261015020000_forge_lod_variant.sql b/api/_lib/migrations/20261015020000_forge_lod_variant.sqlnew file mode 100644index 000000000..73cb110b7--- /dev/null+++ b/api/_lib/migrations/20261015020000_forge_lod_variant.sql@@ -0,0 +1,22 @@+-- LOD chain variant of a finished forge mesh, opt-in via { lods: true } on the+-- generation request (api/_lib/forge-options.js).+--+-- Building a real MSFT_lod chain (packages/glb-tools's buildLodChain,+-- meshoptimizer decimation under the hood) costs real CPU, so it only runs when+-- a caller asks for it, exactly like the web-delivery variant it sits beside+-- (see 20260904120000_forge_web_glb.sql). Stored as a THIRD object: glb_url+-- stays the caller's requested output_format untouched, web_glb_url stays the+-- phone-sized delivery variant, and lod_glb_url is the combined, single-file+-- MSFT_lod GLB a real-time engine can switch levels from at runtime.+--+-- lod_levels carries the per-level triangle/vertex counts (name, ratio,+-- triangleCount, vertexCount) so a reader can show the chain's shape without+-- fetching and parsing the GLB itself (the same shape the Engine QA report's+-- triangleBudget check already renders in public/engine-qa-panel.js).+--+-- Null on every existing row and on any row whose caller did not opt in, or+-- whose build failed; readers must treat null as "no LOD chain available."+alter table forge_creations+ add column if not exists lod_glb_key text,+ add column if not exists lod_glb_url text,+ add column if not exists lod_levels jsonb;diff --git a/api/forge.js b/api/forge.jsindex 778f91dba..0a4864ae9 100644--- a/api/forge.js+++ b/api/forge.js@@ -661,6 +661,7 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, optquality: true,compress: opts?.compression && opts.compression !== 'none' ? opts.compression : null,derivePbr: opts?.derivePbr !== false,+ lods: opts?.lods === true,});// One auto-retry on a flagged low-quality/degenerate output (CLAUDE.md: no@@ -699,6 +700,7 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, optquality: true,compress: opts?.compression && opts.compression !== 'none' ? opts.compression : null,derivePbr: opts?.derivePbr !== false,+ lods: opts?.lods === true,});if (retryDurable) {durable = retryDurable;@@ -739,6 +741,7 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, optglbUrl: r.resultGlbUrl, quality: true,compress: opts?.compression && opts.compression !== 'none' ? opts.compression : null,derivePbr: opts?.derivePbr !== false,+ lods: opts?.lods === true,});return rd ? { glbUrl: rd.glbUrl, durable: rd } : null;},@@ -965,6 +968,7 @@ async function runHfImageLane({quality: true,compress: wantCompress,derivePbr: opts?.derivePbr !== false,+ lods: opts?.lods === true,});// One auto-retry on a flagged low-quality/degenerate output. Only attempted@@ -1009,6 +1013,7 @@ async function runHfImageLane({quality: true,compress: wantCompress,derivePbr: opts?.derivePbr !== false,+ lods: opts?.lods === true,});if (retryDurable) {durable = retryDurable;@@ -1059,6 +1064,7 @@ async function runHfImageLane({replicateJobId: rj, clientKey, userId: await sessionUserIdFromReq(req),glbUrl: rf.resultGlbUrl, quality: true, compress: wantCompress,derivePbr: opts?.derivePbr !== false,+ lods: opts?.lods === true,});return rd ? { glbUrl: rd.glbUrl, durable: rd } : null;} finally {@@ -1777,6 +1783,7 @@ async function startJobWithBody(req, res, body) {quality: true,compress: opts.compression !== 'none' ? opts.compression : null,derivePbr: opts.derivePbr !== false,+ lods: opts.lods === true,});return json(res, 200, {job_id: null,@@ -3209,6 +3216,7 @@ async function pollJob(req, res, jobId) {quality: true,compress: boundOpts?.compression || null,derivePbr: boundOpts?.derivePbr !== false,+ lods: boundOpts?.lods === true,});// Populate the result cache this job was bound to at submit time (text→3D,// non-high-tier, platform-keyed lanes only: see forgeResultCacheKey). Adiff --git a/tests/forge-options.test.js b/tests/forge-options.test.jsindex 49a160c0f..972325194 100644--- a/tests/forge-options.test.js+++ b/tests/forge-options.test.js@@ -159,6 +159,21 @@ describe('normalizeForgeOptions: num_parts (PartCrafter)', () => {});});+describe('normalizeForgeOptions: lods (LOD chain)', () => {+ it('accepts lods as a boolean and defaults to false', () => {+ expect(normalizeForgeOptions({ lods: true }).lods).toBe(true);+ expect(normalizeForgeOptions({}).lods).toBe(false);+ });++ it('rejects a non-boolean lods', () => {+ expect(normalizeForgeOptions({ lods: 'yes' }).errors[0].field).toBe('lods');+ });++ it('flips hasOptions when lods is requested', () => {+ expect(normalizeForgeOptions({ lods: true }).hasOptions).toBe(true);+ });+});+describe('summarizeForgeOptions', () => {it('echoes the resolved options for the response', () => {const o = normalizeForgeOptions({ seed: 9, output_format: 'glb-draco', texture_size: 1024 });@@ -174,9 +189,15 @@ describe('summarizeForgeOptions', () => {// Material completion is on unless the caller opts out, and the echo// says so, so a client can tell why its delivered file carries maps.derive_pbr: true,+ lods: false,});});+ it('echoes lods when requested', () => {+ const o = normalizeForgeOptions({ lods: true });+ expect(summarizeForgeOptions(o).lods).toBe(true);+ });+it('echoes num_parts when supplied', () => {const o = normalizeForgeOptions({ num_parts: 8 });expect(summarizeForgeOptions(o).num_parts).toBe(8);diff --git a/tests/forge-store-materialize.test.js b/tests/forge-store-materialize.test.jsindex 18642c834..8e1090ebd 100644--- a/tests/forge-store-materialize.test.js+++ b/tests/forge-store-materialize.test.js@@ -69,7 +69,7 @@ vi.mock('../api/_lib/forge-events.js', () => ({recordGenerationEvent: vi.fn(async () => {}),}));-const { materializeCreation } = await import('../api/_lib/forge-store.js');+const { materializeCreation, buildLodVariant } = await import('../api/_lib/forge-store.js');function stubFetch(buf) {global.fetch = vi.fn(async () => ({@@ -178,3 +178,35 @@ describe('materializeCreation — quality + compression (additive, opt-in)', ()expect(out.quality.flag).toBe('invalid');});});++describe('buildLodVariant: real MSFT_lod chain (prompt-071 "LOD and Engine QA" work order)', () => {+ // Opt-in, fire-and-forget variant builder materializeCreation calls when the+ // caller sends { lods: true } (api/_lib/forge-options.js). Tested directly+ // against the real bundled GLB, through the real buildLodChain pipeline+ // (packages/glb-tools), with only the storage/db boundary stubbed, matching+ // this file's existing conventions for the other variant/pipeline passes.+ it('builds a real, strictly-decreasing LOD chain and stores it as a third object', async () => {+ const out = await buildLodVariant({ buffer: FOX_GLB, creationId: existingRow.id, keyPrefix: `forge/client-1/${existingRow.id}` });+ expect(out).not.toBeNull();+ expect(out.key).toBe(`forge/client-1/${existingRow.id}.lod.glb`);+ expect(out.url).toBe(`https://cdn.example.com/forge/client-1/${existingRow.id}.lod.glb`);+ expect(out.levels.length).toBeGreaterThanOrEqual(2);+ for (let i = 1; i < out.levels.length; i++) {+ expect(out.levels[i].triangleCount).toBeLessThanOrEqual(out.levels[i - 1].triangleCount);+ }++ const written = putObjectMock.mock.calls.find((c) => c[0].key.endsWith('.lod.glb'));+ expect(written).toBeTruthy();+ expect(written[0].body.length).toBeGreaterThan(0);++ const update = sqlMock.mock.calls.map((c) => c[0].join(' ')).find((text) => text.includes('lod_glb_key'));+ expect(update).toBeTruthy();+ }, 20_000);++ it('returns null without writing anything for an empty buffer', async () => {+ putObjectMock.mockClear();+ const out = await buildLodVariant({ buffer: Buffer.alloc(0), creationId: existingRow.id, keyPrefix: 'forge/client-1/empty' });+ expect(out).toBeNull();+ expect(putObjectMock).not.toHaveBeenCalled();+ });+});