Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(create-3d): 3D kind in Create, mesh viewer core (load, facts, export)

purpledd28f46c93f1
diff --git a/e2e/howto/create-fx.ts b/e2e/howto/create-fx.ts
index c25bec4c..5f78db14 100644
--- a/e2e/howto/create-fx.ts
+++ b/e2e/howto/create-fx.ts
@@ -80,7 +80,7 @@ export async function bootCreate(page: Page, id: string, title: string, fx: Fx =
await page.route('https://lu-labs.ai/api/jobs/catalog*', (route) => route.fulfill({
status: 200, headers: CORS, contentType: 'application/json',
body: JSON.stringify({
- models: CLOUD_MODEL_SEED.map((m) => ({ ...m, credits: m.credits ?? { base: BASE[m.kind] } })),
+ models: CLOUD_MODEL_SEED.map((m) => ({ ...m, credits: m.credits ?? { base: BASE[m.kind === '3d' ? 'image' : m.kind] } })),
ops: { removebg: 1000, eraser: 2500, upscale_image: 1000, upscale_video_per_s: 500, upscale_video_min: 2500 },
voice: { stt: 600, tts_per_1k_chars: 8000 },
media_live: true, tier: 'hosted-max', monthly_credits: 2_550_000,
diff --git a/package-lock.json b/package-lock.json
index 592ee55e..50f13e48 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -33,7 +33,7 @@
"remark-gfm": "^4.0.1",
"remark-math": "^6.0.0",
"tailwindcss": "^4.2.2",
- "three": "^0.183.2",
+ "three": "0.183.2",
"uuid": "^13.0.0",
"zustand": "^5.0.12"
},
@@ -47,6 +47,7 @@
"@types/node": "^24.12.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
+ "@types/three": "0.183.1",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
diff --git a/package.json b/package.json
index c2f9986e..ebc04a88 100644
--- a/package.json
+++ b/package.json
@@ -65,7 +65,7 @@
"remark-gfm": "^4.0.1",
"remark-math": "^6.0.0",
"tailwindcss": "^4.2.2",
- "three": "^0.183.2",
+ "three": "0.183.2",
"uuid": "^13.0.0",
"zustand": "^5.0.12"
},
@@ -79,6 +79,7 @@
"@types/node": "^24.12.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
+ "@types/three": "0.183.1",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
diff --git a/src/components/create/experimental/Composer.tsx b/src/components/create/experimental/Composer.tsx
index e7637755..2458c720 100644
--- a/src/components/create/experimental/Composer.tsx
+++ b/src/components/create/experimental/Composer.tsx
@@ -10,7 +10,7 @@ import { useCreateStore, MODEL_TYPE_DEFAULTS, EDIT_MAX_DENOISE, imageQualityLadd
import { classifyModel, resolveLocalOpPick } from '../../../api/comfyui'
import { readsEditStrength, EDIT_STRENGTH_HINT, EDIT_DENOISE_HINT } from '../../../lib/edit-references'
import { useCreateExp } from './CreateContext'
-import { intentToJob } from '../../../lib/render/cloud-jobs'
+import { intentToJob, quotaCostKind } from '../../../lib/render/cloud-jobs'
import { meterState } from '../../../lib/render/credits-meter'
import { runImageCount } from '../../../lib/render/image-count'
import { useCloudCatalogStore, cloudModelById, defaultCloudModel, editNeedsMask, modelForOp, runCredits, lengthCredits, lengthPrice } from '../../../stores/cloudCatalogStore'
@@ -255,7 +255,7 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {
// Dieselbe Zahl wie im Zaehler: nach einem 409 steht im Speicher der Preis
// des Servers, und die Deckungspruefung muss ihn benutzen.
const cloudStudioCredits = useCreateStore((s) => s.cloudStudioCredits)
- const costFallback = quota?.costs[runKind === 'audio' ? 'image' : runKind] ?? 0
+ const costFallback = quota?.costs[quotaCostKind(runKind)] ?? 0
// The exact rule the meter chip renders, so the button can never invite a run
// the chip is already refusing. Credits alone were not enough: a user out of
// monthly character trainings kept an enabled Create button and got a 429.
diff --git a/src/components/create/experimental/galleryDownload.ts b/src/components/create/experimental/galleryDownload.ts
index baa147ed..dc02961c 100644
--- a/src/components/create/experimental/galleryDownload.ts
+++ b/src/components/create/experimental/galleryDownload.ts
@@ -10,7 +10,9 @@ import { isMlxImageHost } from '../../../api/mlx-image'
import { refreshResultUrl } from '../../../api/cloud/jobs'
import { blobFromUrl } from '../../../lib/render/data-url'
-export function extFor(contentType: string, kind: 'image' | 'video' | 'audio'): string {
+export function extFor(contentType: string, kind: GalleryItem['type']): string {
+ // A 3D model is always handed over as the GLB it was made as.
+ if (kind === '3d') return 'glb'
if (contentType.includes('png')) return 'png'
if (contentType.includes('jpeg') || contentType.includes('jpg')) return 'jpg'
if (contentType.includes('webp')) return 'webp'
@@ -45,11 +47,12 @@ const MIME_BY_EXT: Record<string, string> = {
png: 'image/png', jpg: 'image/jpeg', webp: 'image/webp',
mp4: 'video/mp4', webm: 'video/webm',
mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg',
+ glb: 'model/gltf-binary', obj: 'model/obj', stl: 'model/stl', usdz: 'model/vnd.usdz+zip',
}
/** The extension a phone asks for before it has seen the bytes. */
-function extByKind(kind: 'image' | 'video' | 'audio'): string {
- return kind === 'video' ? 'mp4' : kind === 'audio' ? 'mp3' : 'png'
+function extByKind(kind: GalleryItem['type']): string {
+ return kind === '3d' ? 'glb' : kind === 'video' ? 'mp4' : kind === 'audio' ? 'mp3' : 'png'
}
export async function downloadGalleryItem(item: GalleryItem): Promise<void> {
diff --git a/src/components/create/experimental/useRunCredits.ts b/src/components/create/experimental/useRunCredits.ts
index b6944052..fab9714d 100644
--- a/src/components/create/experimental/useRunCredits.ts
+++ b/src/components/create/experimental/useRunCredits.ts
@@ -1,6 +1,6 @@
import { useCreateStore } from '../../../stores/createStore'
import { useCreateExp } from './CreateContext'
-import { intentToJob, type RenderKind, type RenderOp } from '../../../lib/render/cloud-jobs'
+import { intentToJob, quotaCostKind, type RenderKind, type RenderOp } from '../../../lib/render/cloud-jobs'
import { lengthCredits, lengthPrice, runCredits } from '../../../stores/cloudCatalogStore'
import { createRunModel, createStudioCost, isStudioModel, startImageCount } from '../../../lib/render/create-studio'
import { STUDIO_MODELS } from '../../../lib/render/studio-contract'
@@ -92,7 +92,7 @@ export function useRunCredits(): RunCredits | null {
? cloudStudioCredits ?? lengthCredits(model, lengthRate.basis === 'chars' ? Array.from(prompt).length || undefined : undefined)
: studioPick
? cloudStudioCredits ?? createStudioCost(studioPick, cloudStudioOptions, Array.from(prompt).length, undefined, startImageCount(studioPick, extraPhotos) ?? 1)
- : runCredits(kind, op, model, seconds, quota.costs[kind === 'audio' ? 'image' : kind], targetResolution)
+ : runCredits(kind, op, model, seconds, quota.costs[quotaCostKind(kind)], targetResolution)
// Mehrere Bilder: jedes ist ein eigener Auftrag zum vollen Preis, die Summe
// ist, was der Lauf bindet. Der Zaehler "noch N Bilder" rechnet je Bild.
const imageCount = runImageCount(intent, cloudImageCount, characterUse)
diff --git a/src/lib/create/chat-catalog.ts b/src/lib/create/chat-catalog.ts
index f31a52b0..76eb10e3 100644
--- a/src/lib/create/chat-catalog.ts
+++ b/src/lib/create/chat-catalog.ts
@@ -38,12 +38,13 @@ export const INTENT_LABEL: Record<CreateIntent, string> = {
image: 'Image', edit: 'Edit image', removebg: 'Remove background', upscale: 'Enhance image', eraser: 'Erase',
character: 'Character Studio', video: 'Video', animate: 'Animate image', extend: 'Extend clip',
video_upscale: 'Enhance video', lipsync: 'Talking character', motion: 'Motion transfer', music: 'Music',
+ '3d': '3D model',
}
export const INTENT_KIND: Record<CreateIntent, RenderKind> = {
image: 'image', edit: 'image', removebg: 'image', upscale: 'image', eraser: 'image', character: 'image',
video: 'video', animate: 'video', extend: 'video', video_upscale: 'video', lipsync: 'video', motion: 'video',
- music: 'audio',
+ music: 'audio', '3d': '3d',
}
function create(m: { id: string; label: string; kind: RenderKind; adult?: boolean }): ChatModel {
diff --git a/src/lib/create/chat-context.ts b/src/lib/create/chat-context.ts
index 766a4637..d68a76e3 100644
--- a/src/lib/create/chat-context.ts
+++ b/src/lib/create/chat-context.ts
@@ -45,8 +45,9 @@ export function chatHandleContext(conversationId: string, now = Date.now()): Omi
}
// Only what the cloud made: a local render has no job on the server that a
// run could take as an input (handles.ts, isCloud).
+ // A 3D model is no input any chat run takes.
const gallery = useCreateStore.getState().gallery
- .filter((g) => !!g.jobId)
+ .filter((g): g is typeof g & { type: 'image' | 'video' | 'audio' } => !!g.jobId && g.type !== '3d')
.map((g) => ({
id: g.id,
jobId: g.jobId,
diff --git a/src/lib/create/chat-tools.ts b/src/lib/create/chat-tools.ts
index be73b495..e014f4af 100644
--- a/src/lib/create/chat-tools.ts
+++ b/src/lib/create/chat-tools.ts
@@ -149,6 +149,7 @@ const INTENT_WHAT: Record<CreateIntent, string> = {
character: 'train a character from photos, or create images with a trained one', video: 'text to clip',
animate: 'image to clip', extend: 'continue a clip', video_upscale: 'sharpen a clip', lipsync: 'a portrait speaks a voice track',
motion: 'movement of a clip onto a character image', music: 'a track from a description',
+ '3d': 'a 3D model, not available in chat',
}
function inputsOf(intent: CreateIntent, model?: ChatModel): string[] {
diff --git a/src/lib/create/order.ts b/src/lib/create/order.ts
index a4fe6022..6e697ef7 100644
--- a/src/lib/create/order.ts
+++ b/src/lib/create/order.ts
@@ -4,6 +4,7 @@
// under PATCHES in that script, and the classes under CLASSES.
import type { CreateIntent } from './bridge/create-store'
import type { CloudJob, CloudJobParams, CloudJobSubmit, UploadRole } from './bridge/cloud-jobs'
+import type { RenderKind } from '../render/cloud-jobs'
import { cloudModelById, resolveCharacterModel } from './bridge/cloud-models'
import { pricesByInput } from '../render/create-studio'
import {
@@ -169,6 +170,13 @@ function spec(error: string): never {
throw new OrderSpecError(error)
}
+/** What a chat order may render. 3D models (3.1.0) are made in the Create tab
+ * only: chat results are images, clips and tracks. */
+function chatKind(kind: RenderKind): MediaKind {
+ if (kind === '3d') spec('3D models are made in the Create tab, not in chat.')
+ return kind
+}
+
function isIntent(s: ItemSpec): s is IntentItemSpec {
return typeof (s as IntentItemSpec).intent === 'string'
}
@@ -443,7 +451,7 @@ async function planCreate(p: Planner, s: IntentItemSpec, intent: CreateIntent, m
engine: 'create',
title: INTENT_LABEL[intent],
model: resolved.model,
- kind: resolved.op === 'lora-train' ? 'image' : resolved.kind,
+ kind: resolved.op === 'lora-train' ? 'image' : chatKind(resolved.kind),
prompt,
options,
inputs,
@@ -593,7 +601,7 @@ async function planStep(
engine: 'step',
title,
model: r.step.model,
- kind: r.step.kind,
+ kind: chatKind(r.step.kind),
prompt,
options,
inputs,
diff --git a/src/lib/gallery-restore.ts b/src/lib/gallery-restore.ts
index 286d4fca..f4ffd2a3 100644
--- a/src/lib/gallery-restore.ts
+++ b/src/lib/gallery-restore.ts
@@ -19,7 +19,7 @@ import { useCreateStore, type GalleryItem } from '../stores/createStore'
export interface ScannedFile {
filename: string
subfolder: string
- kind: 'image' | 'video' | 'audio'
+ kind: 'image' | 'video' | 'audio' | '3d'
modifiedMs: number
bytes: number
width?: number | null
diff --git a/src/lib/pending-cloud-jobs.ts b/src/lib/pending-cloud-jobs.ts
index 933d7b08..4c0ad53a 100644
--- a/src/lib/pending-cloud-jobs.ts
+++ b/src/lib/pending-cloud-jobs.ts
@@ -50,7 +50,7 @@ export type PendingCloudJobLanding =
export interface PendingCloudJob {
/** The id of the job on the server. */
id: string
- kind: 'image' | 'video' | 'audio'
+ kind: 'image' | 'video' | 'audio' | '3d'
/** The op of the run (generate, edit, tts, upscale, lora-train, studio ...). */
op: string
model: string
@@ -74,7 +74,7 @@ export interface CloudSubmitIntent {
requestId: string
/** How many jobs the run asked for (several images). */
count: number
- kind: 'image' | 'video' | 'audio'
+ kind: 'image' | 'video' | 'audio' | '3d'
op: string
model: string
prompt: string
diff --git a/src/lib/remote-create-lanes.ts b/src/lib/remote-create-lanes.ts
index 34b2b96f..439271ad 100644
--- a/src/lib/remote-create-lanes.ts
+++ b/src/lib/remote-create-lanes.ts
@@ -419,7 +419,7 @@ export const FROM_YOUR_PHONE = 'From your phone'
/** The entries of the desktop gallery that are files on this machine. A
* cloud entry or one that only lives in memory has none and is left out. */
export function galleryForRemote(items: readonly {
- id: string; type: 'image' | 'video' | 'audio'; filename: string; subfolder: string; comfyType?: string
+ id: string; type: 'image' | 'video' | 'audio' | '3d'; filename: string; subfolder: string; comfyType?: string
localPath?: string; remoteUrl?: string; prompt: string; model: string; createdAt: number; label?: string
hidden?: boolean
}[]): GalleryOut[] {
@@ -427,6 +427,8 @@ export function galleryForRemote(items: readonly {
for (const it of items) {
// Hidden on the computer (D27, 3.1.0): not shown on the phone either.
if (it.hidden) continue
+ // 3D (3.1.0) is not on the phone's view of this computer in v1.
+ if (it.type === '3d') continue
const base = { key: it.id, media: it.type, prompt: it.prompt ?? '', model: it.model ?? '', created_at: it.createdAt ?? 0, from_phone: it.label === FROM_YOUR_PHONE }
if (it.localPath) out.push({ ...base, path: it.localPath })
else if (!it.remoteUrl && it.filename && (it.comfyType ?? 'output') === 'output') out.push({ ...base, comfy_filename: it.filename, comfy_subfolder: it.subfolder ?? '' })
diff --git a/src/lib/render/__tests__/cloud-jobs.test.ts b/src/lib/render/__tests__/cloud-jobs.test.ts
index cd4e37c2..6ba0c4f8 100644
--- a/src/lib/render/__tests__/cloud-jobs.test.ts
+++ b/src/lib/render/__tests__/cloud-jobs.test.ts
@@ -10,6 +10,7 @@ describe('intentToJob', () => {
removebg: { kind: 'image', op: 'removebg' },
upscale: { kind: 'image', op: 'upscale' },
eraser: { kind: 'image', op: 'eraser' },
+ '3d': { kind: '3d', op: 'studio' },
video: { kind: 'video', op: 'generate' },
animate: { kind: 'video', op: 'animate' },
// The five 2.5.8 cloud categories. The Record<CreateIntent, ...> type
diff --git a/src/lib/render/cloud-jobs.ts b/src/lib/render/cloud-jobs.ts
index cc02b688..e0a57067 100644
--- a/src/lib/render/cloud-jobs.ts
+++ b/src/lib/render/cloud-jobs.ts
@@ -12,9 +12,10 @@
// too and which therefore cannot name CreateIntent either.
export type CreateIntentLike =
| 'image' | 'edit' | 'removebg' | 'video' | 'animate' | 'upscale' | 'eraser'
- | 'character' | 'lipsync' | 'music' | 'extend' | 'motion'
+ | 'character' | 'lipsync' | 'music' | 'extend' | 'motion' | '3d'
-export type RenderKind = 'image' | 'video' | 'audio'
+// '3d' (3.1.0): a GLB model. Cloud 3D runs as op 'studio' only.
+export type RenderKind = 'image' | 'video' | 'audio' | '3d'
// 'upscale'/'eraser' are hosted utility endpoints (super-resolution /
// masked object removal) — cloud-only intents in the Create UI since 2.5.7.
// 2.5.8 adds the specialized ops behind the new Create categories: 'lipsync'
@@ -51,6 +52,13 @@ export interface CloudQuota {
trainings?: { limit: number; used: number; remaining: number }
}
+/** The flat fallback price of the quota a kind is counted under when the
+ * server sent no own price. Audio and 3D have none in `costs` and count as an
+ * image; a 3D run is a studio pick and always carries a server quote. */
+export function quotaCostKind(kind: RenderKind): 'image' | 'video' {
+ return kind === 'video' ? 'video' : 'image'
+}
+
/** Which queue kind + workflow op a Create intent renders as.
* 'character' maps per characterTab (train vs use) — see useCloudCreate; the
* default here is the training op, the use-surface submits a plain image
@@ -79,6 +87,9 @@ export function intentToJob(intent: CreateIntentLike): { kind: RenderKind; op: R
return { kind: 'video', op: 'extend' }
case 'motion':
return { kind: 'video', op: 'motion' }
+ case '3d':
+ // Every cloud 3D model is a studio model (C3D 2.5): no op of its own.
+ return { kind: '3d', op: 'studio' }
default:
return { kind: 'image', op: 'generate' }
}
diff --git a/src/lib/render/gallery-label.ts b/src/lib/render/gallery-label.ts
index 2e884408..d837a2ad 100644
--- a/src/lib/render/gallery-label.ts
+++ b/src/lib/render/gallery-label.ts
@@ -31,6 +31,7 @@ const TYPE_NAME: Record<GalleryItem['type'], string> = {
image: 'Image',
video: 'Clip',
audio: 'Audio',
+ '3d': '3D model',
}
// Review A kleiner Punkt 3: this used to be its own copy (STUDIO_MODELS
diff --git a/src/lib/three/__tests__/mesh-load.test.ts b/src/lib/three/__tests__/mesh-load.test.ts
new file mode 100644
index 00000000..d2278a8b
--- /dev/null
+++ b/src/lib/three/__tests__/mesh-load.test.ts
@@ -0,0 +1,89 @@
+import { describe, it, expect } from 'vitest'
+import { cubeGlb, buildGlb } from '../glb-build'
+import { loadGlb, allowedUrl, MeshLoadError, NOT_A_MODEL, COMPRESSED } from '../mesh-load'
+import { exportObj, exportStl, exportMesh } from '../mesh-export'
+import { factsLine, isGlb, requiredExtensions, trianglesText, bytesText, triangleCount, unsupportedCompression } from '../mesh-facts'
+
+const ab = (u: Uint8Array) => u.buffer.slice(u.byteOffset, u.byteOffset + u.byteLength) as ArrayBuffer
+
+describe('mesh facts', () => {
+ it('counts triangles with and without an index', () => {
+ expect(triangleCount([{ indexCount: 36, vertexCount: 8 }, { indexCount: null, vertexCount: 9 }])).toBe(15)
+ })
+ it('writes the line under the view', () => {
+ expect(trianglesText(1)).toBe('1 triangle')
+ expect(trianglesText(940)).toBe('940 triangles')
+ expect(trianglesText(128_400)).toBe('128k triangles')
+ expect(trianglesText(1_240_000)).toBe('1.2M triangles')
+ expect(bytesText(14_200_000)).toBe('14 MB')
+ expect(bytesText(820_000)).toBe('820 KB')
+ expect(factsLine(128_000, 14_000_000)).toBe('128k triangles · 14 MB')
+ expect(factsLine(12)).toBe('12 triangles')
+ })
+ it('knows a GLB by its first bytes', () => {
+ expect(isGlb(cubeGlb())).toBe(true)
+ expect(isGlb(new TextEncoder().encode('<html>not a model</html>'))).toBe(false)
+ expect(isGlb(new Uint8Array([0x67, 0x6c, 0x54]))).toBe(false)
+ })
+ it('reads the required extensions', () => {
+ const draco = cubeGlb({ extensionsRequired: ['KHR_draco_mesh_compression'] })
+ expect(requiredExtensions(draco)).toEqual(['KHR_draco_mesh_compression'])
+ expect(unsupportedCompression(draco)).toBe(true)
+ expect(unsupportedCompression(cubeGlb())).toBe(false)
+ })
+})
+
+describe('loadGlb', () => {
+ it('parses the cube with its colours', async () => {
+ const m = await loadGlb(ab(cubeGlb()))
+ expect(m.triangles).toBe(12)
+ expect(m.blockedUrls).toBe(0)
+ let colors = 0
+ m.root.traverse((o) => { const g = (o as { geometry?: { attributes: Record<string, unknown> } }).geometry; if (g?.attributes.color) colors += 1 })
+ expect(colors).toBe(1)
+ })
+ it('refuses a file that is no GLB', async () => {
+ await expect(loadGlb(ab(new TextEncoder().encode('just text, padded to be long')))).rejects.toThrow(NOT_A_MODEL)
+ })
+ it('refuses Draco and KTX2 with its own sentence', async () => {
+ const e = await loadGlb(ab(cubeGlb({ extensionsRequired: ['KHR_texture_basisu'] }))).catch((x) => x)
+ expect(e).toBeInstanceOf(MeshLoadError)
+ expect(e.message).toBe(COMPRESSED)
+ })
+ it('never lets a model reach a foreign address', async () => {
+ expect(allowedUrl('https://evil.example/x.png')).toBe(false)
+ expect(allowedUrl('http://localhost/x.png')).toBe(false)
+ expect(allowedUrl('file:///etc/passwd')).toBe(false)
+ expect(allowedUrl('blob:http://x/1')).toBe(true)
+ expect(allowedUrl('data:image/png;base64,AAAA')).toBe(true)
+ const fetched: string[] = []
+ const orig = globalThis.fetch
+ globalThis.fetch = (async (u: RequestInfo | URL) => { fetched.push(String(u)); throw new Error('no network in tests') }) as typeof fetch
+ try {
+ const glb = buildGlb({ positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2], externalImageUri: 'https://tracker.example/pixel.png' })
+ const m = await loadGlb(ab(glb)).catch(() => null)
+ expect(fetched.some((u) => u.includes('tracker.example'))).toBe(false)
+ if (m) expect(m.blockedUrls).toBeGreaterThan(0)
+ } finally {
+ globalThis.fetch = orig
+ }
+ })
+})
+
+describe('mesh export', () => {
+ it('writes a valid OBJ and binary STL of the cube', async () => {
+ const { root } = await loadGlb(ab(cubeGlb()))
+ const obj = new TextDecoder().decode(exportObj(root))
+ expect(obj.match(/^v /gm)?.length).toBe(8)
+ expect(obj.match(/^f /gm)?.length).toBe(12)
+ const stl = exportStl(root)
+ // 80-byte header, a uint32 count, 50 bytes per triangle.
+ expect(new DataView(stl.buffer, stl.byteOffset).getUint32(80, true)).toBe(12)
+ expect(stl.byteLength).toBe(84 + 12 * 50)
+ })
+ it('hands the GLB back unchanged', async () => {
+ const glb = cubeGlb()
+ const { root } = await loadGlb(ab(glb))
+ expect(await exportMesh('glb', root, glb)).toBe(glb)
+ })
+})
diff --git a/src/lib/three/glb-build.ts b/src/lib/three/glb-build.ts
new file mode 100644
index 00000000..ec347a67
--- /dev/null
+++ b/src/lib/three/glb-build.ts
@@ -0,0 +1,108 @@
+// A small binary glTF written by hand: one mesh with positions, an index and
+// a colour per vertex. The tests parse it, and the stand-ins hand it out as a
+// finished model. No exporter, no DOM: the bytes are laid out as the glTF 2.0
+// spec names them (12-byte header, a JSON chunk, a BIN chunk, each padded to
+// four bytes).
+
+export interface GlbMesh {
+ positions: number[]
+ indices: number[]
+ /** RGB from 0 to 1, three per vertex. */
+ colors?: number[]
+ /** glTF extensions the file says it requires (for tests of the refusals). */
+ extensionsRequired?: string[]
+ /** An image the file points at by address (for the URL filter's tests). */
+ externalImageUri?: string
+}
+
+const pad4 = (n: number) => (n + 3) & ~3
+
+export function buildGlb(mesh: GlbMesh): Uint8Array {
+ const pos = new Float32Array(mesh.positions)
+ const idx = new Uint16Array(mesh.indices)
+ const col = mesh.colors ? new Float32Array(mesh.colors) : null
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity]
+ for (let i = 0; i < pos.length; i += 3) {
+ for (let k = 0; k < 3; k++) {
+ min[k] = Math.min(min[k], pos[i + k])
+ max[k] = Math.max(max[k], pos[i + k])
+ }
+ }
+ const posOff = 0
+ const idxOff = pad4(pos.byteLength)
+ const colOff = pad4(idxOff + idx.byteLength)
+ const binLength = pad4(col ? colOff + col.byteLength : idxOff + idx.byteLength)
+ const bin = new Uint8Array(binLength)
+ bin.set(new Uint8Array(pos.buffer), posOff)
+ bin.set(new Uint8Array(idx.buffer), idxOff)
+ if (col) bin.set(new Uint8Array(col.buffer), colOff)
+
+ const bufferViews: object[] = [
+ { buffer: 0, byteOffset: posOff, byteLength: pos.byteLength, target: 34962 },
+ { buffer: 0, byteOffset: idxOff, byteLength: idx.byteLength, target: 34963 },
+ ]
+ const accessors: object[] = [
+ { bufferView: 0, componentType: 5126, count: pos.length / 3, type: 'VEC3', min, max },
+ { bufferView: 1, componentType: 5123, count: idx.length, type: 'SCALAR' },
+ ]
+ const attributes: Record<string, number> = { POSITION: 0 }
+ if (col) {
+ bufferViews.push({ buffer: 0, byteOffset: colOff, byteLength: col.byteLength, target: 34962 })
+ accessors.push({ bufferView: 2, componentType: 5126, count: col.length / 3, type: 'VEC3' })
+ attributes.COLOR_0 = 2
+ }
+ const json: Record<string, unknown> = {
+ asset: { version: '2.0', generator: 'LU test' },
+ scene: 0,
+ scenes: [{ nodes: [0] }],
+ nodes: [{ mesh: 0 }],
+ meshes: [{ primitives: [{ attributes, indices: 1, material: 0 }] }],
+ materials: [{ pbrMetallicRoughness: { baseColorFactor: [1, 1, 1, 1], metallicFactor: 0, roughnessFactor: 1 } }],
+ buffers: [{ byteLength: binLength }],
+ bufferViews,
+ accessors,
+ }
+ if (mesh.extensionsRequired?.length) {
+ json.extensionsUsed = mesh.extensionsRequired
+ json.extensionsRequired = mesh.extensionsRequired
+ }
+ if (mesh.externalImageUri) {
+ json.images = [{ uri: mesh.externalImageUri }]
+ json.textures = [{ source: 0 }]
+ ;(json.materials as Array<{ pbrMetallicRoughness: Record<string, unknown> }>)[0].pbrMetallicRoughness.baseColorTexture = { index: 0 }
+ ;(json.meshes as Array<{ primitives: Array<{ attributes: Record<string, number> }> }>)[0].primitives[0].attributes.TEXCOORD_0 = 0
+ }
+ const jsonBytes = new TextEncoder().encode(JSON.stringify(json))
+ const jsonLength = pad4(jsonBytes.length)
+ const total = 12 + 8 + jsonLength + 8 + binLength
+ const out = new Uint8Array(total)
+ const v = new DataView(out.buffer)
+ v.setUint32(0, 0x46546c67, true) // "glTF"
+ v.setUint32(4, 2, true)
+ v.setUint32(8, total, true)
+ v.setUint32(12, jsonLength, true)
+ v.setUint32(16, 0x4e4f534a, true) // "JSON"
+ out.fill(0x20, 20, 20 + jsonLength)
+ out.set(jsonBytes, 20)
+ v.setUint32(20 + jsonLength, binLength, true)
+ v.setUint32(24 + jsonLength, 0x004e4942, true) // "BIN\0"
+ out.set(bin, 28 + jsonLength)
+ return out
+}
+
+/** A unit cube with a colour per corner: 8 vertices, 12 triangles. */
+export function cubeGlb(extra: Partial<GlbMesh> = {}): Uint8Array {
+ const positions = [
+ -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5,
+ -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5,
+ ]
+ const indices = [
+ 0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4,
+ 2, 3, 7, 2, 7, 6, 1, 2, 6, 1, 6, 5, 0, 4, 7, 0, 7, 3,
+ ]
+ const colors = [
+ 0.9, 0.3, 0.2, 0.9, 0.6, 0.2, 0.9, 0.9, 0.2, 0.3, 0.9, 0.2,
+ 0.2, 0.9, 0.6, 0.2, 0.6, 0.9, 0.4, 0.2, 0.9, 0.8, 0.2, 0.9,
+ ]
+ return buildGlb({ positions, indices, colors, ...extra })
+}
diff --git a/src/lib/three/mesh-export.ts b/src/lib/three/mesh-export.ts
new file mode 100644
index 00000000..6206e06f
--- /dev/null
+++ b/src/lib/three/mesh-export.ts
@@ -0,0 +1,49 @@
+// The formats of the Download menu besides the GLB (C3D-PLAN 1.4). The GLB is
+// the delivered file, unchanged. OBJ, STL and USDZ are computed from the
+// loaded scene with three's own exporters.
+import type * as THREE from 'three'
+import { OBJExporter } from 'three/addons/exporters/OBJExporter.js'
+import { STLExporter } from 'three/addons/exporters/STLExporter.js'
+
+export type MeshFormat = 'glb' | 'obj' | 'stl' | 'usdz'
+
+export interface MeshFormatInfo {
+ id: MeshFormat
+ label: string
+ note: string
+ mime: string
+}
+
+export const MESH_FORMATS: readonly MeshFormatInfo[] = [
+ { id: 'glb', label: 'GLB', note: 'the original, with colors', mime: 'model/gltf-binary' },
+ { id: 'obj', label: 'OBJ', note: 'shape only', mime: 'model/obj' },
+ { id: 'stl', label: 'STL', note: 'for 3D printing, shape only', mime: 'model/stl' },
+ { id: 'usdz', label: 'USDZ', note: 'for iPhone and Mac', mime: 'model/vnd.usdz+zip' },
+]
+
+export function exportObj(root: THREE.Object3D): Uint8Array {
+ return new TextEncoder().encode(new OBJExporter().parse(root))
+}
+
+export function exportStl(root: THREE.Object3D): Uint8Array {
+ const view = new STLExporter().parse(root, { binary: true }) as unknown as DataView
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength)
+}
+
+/** USDZ takes only standard materials (three's own note). Loaded lazily: the
+ * exporter pulls a zip writer the other formats do not need. */
+export async function exportUsdz(root: THREE.Object3D): Promise<Uint8Array> {
+ const { USDZExporter } = await import('three/addons/exporters/USDZExporter.js')
+ const buffer = await new USDZExporter().parseAsync(root as THREE.Object3D)
+ return new Uint8Array(buffer)
+}
+
+/** The bytes of one format. `original` is the GLB as it was delivered. */
+export async function exportMesh(format: MeshFormat, root: THREE.Object3D, original: Uint8Array): Promise<Uint8Array> {
+ switch (format) {
+ case 'glb': return original
+ case 'obj': return exportObj(root)
+ case 'stl': return exportStl(root)
+ case 'usdz': return exportUsdz(root)
+ }
+}
diff --git a/src/lib/three/mesh-facts.ts b/src/lib/three/mesh-facts.ts
new file mode 100644
index 00000000..0d2584a5
--- /dev/null
+++ b/src/lib/three/mesh-facts.ts
@@ -0,0 +1,82 @@
+// What the 3D view says about a model under the picture ("128k triangles ·
+// 14 MB"), and the limits above which it asks before it draws one. Pure, so
+// the numbers are tested without a canvas.
+
+/** One mesh as the facts read it: the number of indices of its geometry (null
+ * for a geometry without an index) and its number of vertices. */
+export interface MeshShape {
+ indexCount: number | null
+ vertexCount: number
+}
+
+/** Triangles of a set of meshes. A geometry without an index draws its
+ * vertices three by three. */
+export function triangleCount(meshes: readonly MeshShape[]): number {
+ let n = 0
+ for (const m of meshes) n += Math.floor((m.indexCount ?? m.vertexCount) / 3)
+ return n
+}
+
+/** "128k triangles", "1.2M triangles", "940 triangles". */
+export function trianglesText(n: number): string {
+ if (n >= 1_000_000) return `${trim(n / 1_000_000)}M triangles`
+ if (n >= 1_000) return `${Math.round(n / 1_000)}k triangles`
+ return `${n} ${n === 1 ? 'triangle' : 'triangles'}`
+}
+
+/** "14 MB", "820 KB". */
+export function bytesText(bytes: number): string {
+ if (bytes >= 1_000_000) return `${trim(bytes / 1_000_000)} MB`
+ return `${Math.max(1, Math.round(bytes / 1_000))} KB`
+}
+
+/** The line under the view. Bytes are left out when they are not known. */
+export function factsLine(triangles: number, bytes?: number): string {
+ return bytes && bytes > 0 ? `${trianglesText(triangles)} · ${bytesText(bytes)}` : trianglesText(triangles)
+}
+
+function trim(v: number): string {
+ return v >= 10 ? String(Math.round(v)) : v.toFixed(1).replace(/\.0$/, '')
+}
+
+/** Above these the view asks before it loads (C3D-PLAN 1.3): a file this
+ * large can stall a phone or a small laptop for seconds. */
+export const HEAVY_BYTES = 150_000_000
+export const HEAVY_TRIANGLES = 5_000_000
+
+/** Whether a file is too large to draw without asking first. */
+export function isHeavyFile(bytes: number): boolean {
+ return bytes > HEAVY_BYTES
+}
+
+/** The first four bytes of every binary glTF. A file without them is no GLB,
+ * whatever its name says. */
+export function isGlb(bytes: ArrayBuffer | Uint8Array): boolean {
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
+ return b.length >= 12 && b[0] === 0x67 && b[1] === 0x6c && b[2] === 0x54 && b[3] === 0x46
+}
+
+/** The extensions a GLB says it needs, read from its JSON chunk without
+ * parsing the rest. Used to name Draco and KTX2 files the view cannot draw. */
+export function requiredExtensions(bytes: ArrayBuffer | Uint8Array): string[] {
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
+ if (!isGlb(b) || b.length < 20) return []
+ const view = new DataView(b.buffer, b.byteOffset, b.byteLength)
+ const length = view.getUint32(12, true)
+ const type = view.getUint32(16, true)
+ if (type !== 0x4e4f534a || 20 + length > b.length) return []
+ try {
+ const json = JSON.parse(new TextDecoder().decode(b.subarray(20, 20 + length))) as { extensionsRequired?: unknown }
+ return Array.isArray(json.extensionsRequired) ? json.extensionsRequired.filter((e): e is string => typeof e === 'string') : []
+ } catch {
+ return []
+ }
+}
+
+/** Compression the view cannot unpack in v1: both need a worker the app's
+ * content policy does not allow (C3D-PLAN 1.3). */
+export const UNSUPPORTED_EXTENSIONS: ReadonlySet<string> = new Set(['KHR_draco_mesh_compression', 'KHR_texture_basisu'])
+
+export function unsupportedCompression(bytes: ArrayBuffer | Uint8Array): boolean {
+ return requiredExtensions(bytes).some((e) => UNSUPPORTED_EXTENSIONS.has(e))
+}
diff --git a/src/lib/three/mesh-load.ts b/src/lib/three/mesh-load.ts
new file mode 100644
index 00000000..d57ec8ed
--- /dev/null
+++ b/src/lib/three/mesh-load.ts
@@ -0,0 +1,91 @@
+// Turning the bytes of a GLB into a three scene, with no network.
+//
+// The 3D view never fetches an address. The file arrives as bytes over the
+// paths every result takes (a local file, a cloud result fetched like any
+// other medium), and it is parsed here with GLTFLoader.parse. A GLB may still
+// NAME addresses (an external texture or buffer): the LoadingManager below
+// turns every address that is not `blob:` or `data:` into an empty data URL
+// and counts it, so a model can never make the app reach a foreign server.
+import * as THREE from 'three'
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js'
+import { triangleCount, unsupportedCompression, isGlb, type MeshShape } from './mesh-facts'
+
+/** What the loader hands back: the model, its triangles, how many addresses
+ * it named that were dropped. */
+export interface LoadedMesh {
+ root: THREE.Group
+ triangles: number
+ blockedUrls: number
+}
+
+export class MeshLoadError extends Error {
+ constructor(message: string, readonly reason: 'not-glb' | 'compressed' | 'broken') {
+ super(message)
+ this.name = 'MeshLoadError'
+ }
+}
+
+export const NOT_A_MODEL = 'This file is not a 3D model LU can show. You can still download it.'
+export const COMPRESSED = 'This model is packed in a way the 3D view cannot open yet. You can still download it.'
+
+/** Only addresses that carry their bytes with them may load. */
+export function allowedUrl(url: string): boolean {
+ return /^(blob|data):/i.test(url.trim())
+}
+
+/** An empty stand-in for a refused address. GLTFLoader then fails that one
+ * texture and draws the model without it. */
+const REFUSED = 'data:application/octet-stream;base64,'
+
+export function safeManager(onBlocked: () => void): THREE.LoadingManager {
+ const manager = new THREE.LoadingManager()
+ manager.setURLModifier((url) => {
+ if (allowedUrl(url)) return url
+ onBlocked()
+ return REFUSED
+ })
+ return manager
+}
+
+/** The shape of every mesh below `root`, for the facts line. */
+export function meshShapes(root: THREE.Object3D): MeshShape[] {
+ const out: MeshShape[] = []
+ root.traverse((o) => {
+ const mesh = o as THREE.Mesh
+ if (!mesh.isMesh || !mesh.geometry) return
+ const g = mesh.geometry
+ out.push({ indexCount: g.index ? g.index.count : null, vertexCount: g.attributes.position?.count ?? 0 })
+ })
+ return out
+}
+
+export async function loadGlb(bytes: ArrayBuffer): Promise<LoadedMesh> {
+ if (!isGlb(bytes)) throw new MeshLoadError(NOT_A_MODEL, 'not-glb')
+ if (unsupportedCompression(bytes)) throw new MeshLoadError(COMPRESSED, 'compressed')
+ let blockedUrls = 0
+ const loader = new GLTFLoader(safeManager(() => { blockedUrls += 1 }))
+ loader.setMeshoptDecoder(MeshoptDecoder)
+ try {
+ const gltf = await loader.parseAsync(bytes, '')
+ const root = gltf.scene as THREE.Group
+ return { root, triangles: triangleCount(meshShapes(root)), blockedUrls }
+ } catch (err) {
+ throw new MeshLoadError(err instanceof Error && /draco|ktx2|basisu/i.test(err.message) ? COMPRESSED : NOT_A_MODEL, 'broken')
+ }
+}
+
+/** Free the GPU side of a model: geometry, materials and their textures. */
+export function disposeTree(root: THREE.Object3D): void {
+ root.traverse((o) => {
+ const mesh = o as THREE.Mesh
+ if (!mesh.isMesh) return
+ mesh.geometry?.dispose()
+ const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material]
+ for (const m of mats) {
+ if (!m) continue
+ for (const v of Object.values(m)) if (v instanceof THREE.Texture) v.dispose()
+ m.dispose()
+ }
+ })
+}
diff --git a/src/lib/three/mesh-viewer.ts b/src/lib/three/mesh-viewer.ts
new file mode 100644
index 00000000..61e41d9a
--- /dev/null
+++ b/src/lib/three/mesh-viewer.ts
@@ -0,0 +1,186 @@
+// The 3D view of Create: plain three, no React, so the desktop, the phone and
+// lu-labs.ai draw a model the same way (C3D-PLAN 2.2).
+//
+// Drag turns, wheel or pinch zooms, right-drag or two fingers pan, a double
+// click puts the view back. The light is three's RoomEnvironment, computed on
+// the spot: an HDR preset would be fetched from a foreign server.
+import * as THREE from 'three'
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js'
+import { loadGlb, disposeTree, type LoadedMesh } from './mesh-load'
+
+export type MeshLook = 'color' | 'clay' | 'wireframe'
+export type MeshBackdrop = 'dark' | 'light'
+
+export interface MeshViewer {
+ load(bytes: ArrayBuffer): Promise<LoadedMesh>
+ setLook(look: MeshLook): void
+ setBackdrop(backdrop: MeshBackdrop): void
+ setAutoTurn(on: boolean): void
+ reset(): void
+ /** A still of what the view shows, as a JPEG data URL `size` pixels wide. */
+ poster(size?: number): string | null
+ /** The loaded model, for the exporters. */
+ model(): THREE.Object3D | null
+ dispose(): void
+}
+
+const BACKDROP: Record<MeshBackdrop, number> = { dark: 0x15161a, light: 0xeceef2 }
+
+/** Whether this device can draw WebGL at all. */
+export function webglAvailable(): boolean {
+ try {
+ const c = document.createElement('canvas')
+ return !!(c.getContext('webgl2') || c.getContext('webgl'))
+ } catch {
+ return false
+ }
+}
+
+export function createMeshViewer(canvas: HTMLCanvasElement, opts: { onUserTouch?: () => void } = {}): MeshViewer {
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false, preserveDrawingBuffer: true })
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2))
+ renderer.outputColorSpace = THREE.SRGBColorSpace
+ renderer.toneMapping = THREE.ACESFilmicToneMapping
+
+ const scene = new THREE.Scene()
+ scene.background = new THREE.Color(BACKDROP.dark)
+ const pmrem = new THREE.PMREMGenerator(renderer)
+ const room = new RoomEnvironment()
+ scene.environment = pmrem.fromScene(room, 0.04).texture
+ room.dispose?.()
+
+ const camera = new THREE.PerspectiveCamera(35, 1, 0.01, 1000)
+ const controls = new OrbitControls(camera, canvas)
+ controls.enableDamping = true
+ controls.autoRotateSpeed = 1.2
+
+ let current: LoadedMesh | null = null
+ let originals = new Map<THREE.Mesh, THREE.Material | THREE.Material[]>()
+ let look: MeshLook = 'color'
+ let home = { pos: new THREE.Vector3(0, 0, 3), target: new THREE.Vector3() }
+ let disposed = false
+ const clay = new THREE.MeshStandardMaterial({ color: 0xbfb8ad, roughness: 0.85, metalness: 0 })
+ const wire = new THREE.MeshBasicMaterial({ color: 0x9aa4b5, wireframe: true })
+
+ const stopTurn = () => {
+ if (controls.autoRotate) controls.autoRotate = false
+ opts.onUserTouch?.()
+ }
+ controls.addEventListener('start', stopTurn)
+ const onDouble = () => reset()
+ canvas.addEventListener('dblclick', onDouble)
+
+ const resize = () => {
+ const w = canvas.clientWidth || 1, h = canvas.clientHeight || 1
+ if (canvas.width !== Math.floor(w * renderer.getPixelRatio()) || canvas.height !== Math.floor(h * renderer.getPixelRatio())) {
+ renderer.setSize(w, h, false)
+ camera.aspect = w / h
+ camera.updateProjectionMatrix()
+ }
+ }
+ const observer = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(resize) : null
+ observer?.observe(canvas)
+
+ renderer.setAnimationLoop(() => {
+ if (disposed) return
+ resize()
+ controls.update()
+ renderer.render(scene, camera)
+ })
+
+ function frame(root: THREE.Object3D) {
+ const box = new THREE.Box3().setFromObject(root)
+ const size = box.getSize(new THREE.Vector3())
+ const center = box.getCenter(new THREE.Vector3())
+ root.position.sub(center)
+ const radius = Math.max(size.length() / 2, 1e-3)
+ const dist = radius / Math.sin(THREE.MathUtils.degToRad(camera.fov / 2))
+ camera.near = dist / 100
+ camera.far = dist * 100
+ camera.updateProjectionMatrix()
+ home = { pos: new THREE.Vector3(dist * 0.55, dist * 0.35, dist * 0.8), target: new THREE.Vector3() }
+ reset()
+ }
+
+ function applyLook() {
+ if (!current) return
+ current.root.traverse((o) => {
+ const mesh = o as THREE.Mesh
+ if (!mesh.isMesh) return
+ const orig = originals.get(mesh)
+ if (!orig) return
+ mesh.material = look === 'color' ? orig : look === 'clay' ? clay : wire
+ })
+ }
+
+ function reset() {
+ camera.position.copy(home.pos)
+ controls.target.copy(home.target)
+ controls.update()
+ }
+
+ return {
+ async load(bytes) {
+ const next = await loadGlb(bytes)
+ if (disposed) {
+ disposeTree(next.root)
+ return next
+ }
+ if (current) {
+ scene.remove(current.root)
+ disposeTree(current.root)
+ }
+ current = next
+ originals = new Map()
+ next.root.traverse((o) => {
+ const mesh = o as THREE.Mesh
+ if (mesh.isMesh) originals.set(mesh, mesh.material)
+ })
+ scene.add(next.root)
+ frame(next.root)
+ applyLook()
+ controls.autoRotate = true
+ return next
+ },
+ setLook(next) {
+ look = next
+ applyLook()
+ },
+ setBackdrop(b) {
+ ;(scene.background as THREE.Color).set(BACKDROP[b])
+ },
+ setAutoTurn(on) {
+ controls.autoRotate = on
+ },
+ reset,
+ poster(size = 384) {
+ if (!current) return null
+ renderer.render(scene, camera)
+ const w = canvas.width, h = canvas.height
+ if (!w || !h) return null
+ const out = document.createElement('canvas')
+ out.width = size
+ out.height = Math.round((size * h) / w)
+ const ctx = out.getContext('2d')
+ if (!ctx) return null
+ ctx.drawImage(canvas, 0, 0, out.width, out.height)
+ return out.toDataURL('image/jpeg', 0.82)
+ },
+ model: () => current?.root ?? null,
+ dispose() {
+ disposed = true
+ renderer.setAnimationLoop(null)
+ observer?.disconnect()
+ canvas.removeEventListener('dblclick', onDouble)
+ controls.removeEventListener('start', stopTurn)
+ controls.dispose()
+ if (current) disposeTree(current.root)
+ clay.dispose()
+ wire.dispose()
+ scene.environment?.dispose()
+ pmrem.dispose()
+ renderer.dispose()
+ },
+ }
+}
diff --git a/src/mobile/screens/create/PresetSheet.tsx b/src/mobile/screens/create/PresetSheet.tsx
index 3e437228..0cccbdbb 100644
--- a/src/mobile/screens/create/PresetSheet.tsx
+++ b/src/mobile/screens/create/PresetSheet.tsx
@@ -10,7 +10,7 @@
* ideas, `gallery` the gallery as a picker for an input of the step.
*/
import { memo, useRef } from 'react'
-import { AudioLines, Play } from 'lucide-react'
+import { AudioLines, Box, Play } from 'lucide-react'
import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
import { useContentPolicy } from '../../../hooks/useContentPolicy'
import { useSheet } from '../../nav'
@@ -41,11 +41,12 @@ const PickTile = memo(function PickTile({ item, onPick }: { item: GalleryItem; o
{show && item.type === 'image' ? <img src={media.url ?? undefined} alt="" loading="lazy" decoding="async" onError={media.onError} /> : null}
{show && item.type === 'video' ? <video src={`${media.url}#t=0.1`} muted playsInline preload="metadata" onError={media.onError} /> : null}
{item.type === 'audio' && media.state === 'ok' ? <Icon icon={AudioLines} /> : null}
+ {item.type === '3d' && media.state === 'ok' ? <Icon icon={Box} /> : null}
{media.state !== 'ok' ? <MediaStateBox state={media.state} compact /> : null}
</button>
{item.type !== 'image' && media.state === 'ok' ? (
<span className="m-k-tile-badge">
- {item.type === 'video' ? <Play /> : <AudioLines />}
+ {item.type === 'video' ? <Play /> : item.type === '3d' ? <Box /> : <AudioLines />}
{T.gal.kind[item.type]}
</span>
) : null}
diff --git a/src/mobile/screens/create/parts/GalleryBody.tsx b/src/mobile/screens/create/parts/GalleryBody.tsx
index a339ca3e..2b7ba30a 100644
--- a/src/mobile/screens/create/parts/GalleryBody.tsx
+++ b/src/mobile/screens/create/parts/GalleryBody.tsx
@@ -13,7 +13,7 @@
* loaded (content-visibility and an observer).
*/
import { memo, useMemo, useRef, useState } from 'react'
-import { AudioLines, Check, ListChecks, Play, X } from 'lucide-react'
+import { AudioLines, Box, Check, ListChecks, Play, X } from 'lucide-react'
import { useCreateStore, type GalleryItem } from '../../../../stores/createStore'
import { nav } from '../../../nav'
import { COMPUTER_STRINGS as C, CREATE_STRINGS as T } from '../../../strings/create'
@@ -61,11 +61,12 @@ const Tile = memo(function Tile({ item, selecting, selected, onPress }: TileProp
{showMedia && item.type === 'image' ? <img src={media.url ?? undefined} alt="" loading="lazy" decoding="async" onError={media.onError} /> : null}
{showMedia && item.type === 'video' ? <video src={`${media.url}#t=0.1`} muted playsInline preload="metadata" onError={media.onError} /> : null}
{item.type === 'audio' && state === 'ok' ? <Icon icon={AudioLines} /> : null}
+ {item.type === '3d' && state === 'ok' ? <Icon icon={Box} /> : null}
{state !== 'ok' ? <MediaStateBox state={state} compact /> : null}
</button>
{item.type !== 'image' && state === 'ok' ? (
<span className="m-k-tile-badge">
- {item.type === 'video' ? <Play /> : <AudioLines />}
+ {item.type === 'video' ? <Play /> : item.type === '3d' ? <Box /> : <AudioLines />}
{T.gal.kind[item.type]}
</span>
) : null}
diff --git a/src/mobile/screens/create/parts/facts.ts b/src/mobile/screens/create/parts/facts.ts
index 7fc02fe9..2bc23286 100644
--- a/src/mobile/screens/create/parts/facts.ts
+++ b/src/mobile/screens/create/parts/facts.ts
@@ -12,7 +12,7 @@ import { useCreateStore, imageQualityLadder, type CharacterRef, type ImageRef, t
import { useCloudAuthStore, deriveCloudAvailable } from '../../../../stores/cloudAuthStore'
import { useCloudCatalogStore, lengthPrice, runCredits } from '../../../../stores/cloudCatalogStore'
import { useSettingsStore } from '../../../../stores/settingsStore'
-import { intentToJob, type CloudQuota, type RenderKind, type RenderOp } from '../../../../lib/render/cloud-jobs'
+import { intentToJob, quotaCostKind, type CloudQuota, type RenderKind, type RenderOp } from '../../../../lib/render/cloud-jobs'
import { createStudioCost, intentRequiredInputs, startImageCount, studioExtraPhotoSlots } from '../../../../lib/render/create-studio'
import { STUDIO_MODELS, studioFields } from '../../../../lib/render/studio-contract'
import { runImageCount } from '../../../../lib/render/image-count'
@@ -221,7 +221,7 @@ export function useCreateFacts(): CreateFacts {
unit = (mine ? cloudStudioCredits : null) ?? lengthUnit(model.id, op, prompt, mine ? price.inputSeconds : undefined)
if (mine && price.measuring) priceState = 'measuring'
} else if (quota && model.id) {
- unit = runCredits(kind, op, model.id, runSeconds, quota.costs[kind === 'audio' ? 'image' : kind], targetResolution)
+ unit = runCredits(kind, op, model.id, runSeconds, quota.costs[quotaCostKind(kind)], targetResolution)
} else if (quota && !facts.hasModels) {
unit = runCredits(kind, op, '', runSeconds, quota.costs.image, targetResolution)
}
diff --git a/src/mobile/screens/create/parts/files.ts b/src/mobile/screens/create/parts/files.ts
index f056afde..a26f2319 100644
--- a/src/mobile/screens/create/parts/files.ts
+++ b/src/mobile/screens/create/parts/files.ts
@@ -29,11 +29,20 @@ const KIND_FALLBACK: Record<MediaKind, { ext: string; mime: string }> = {
audio: { ext: 'mp3', mime: 'audio/mpeg' },
}
+/** What a result can be: a medium, or a 3D model (3.1.0). */
+export type ResultKind = MediaKind | '3d'
+
+/** A 3D model is stored as plain bytes, so its type never names it. It is
+ * always the GLB it was made as. */
+const GLB = { ext: 'glb', mime: 'model/gltf-binary' }
+
/** File name and type for a result that is saved or shared. */
-export function saveName(kind: MediaKind, blobType: string, createdAt: number, id: string): { name: string; mime: string } {
+export function saveName(kind: ResultKind, blobType: string, createdAt: number, id: string): { name: string; mime: string } {
const type = blobType.split(';')[0].trim().toLowerCase()
- const ext = MIME_EXT[type] ?? KIND_FALLBACK[kind].ext
- const mime = MIME_EXT[type] ? type : KIND_FALLBACK[kind].mime
+ const fallback = kind === '3d' ? GLB : KIND_FALLBACK[kind]
+ const known = kind !== '3d' && !!MIME_EXT[type]
+ const ext = known ? MIME_EXT[type] : fallback.ext
+ const mime = known ? type : fallback.mime
const d = new Date(createdAt)
const pad = (n: number) => String(n).padStart(2, '0')
const stamp = Number.isFinite(d.getTime())
@@ -43,7 +52,7 @@ export function saveName(kind: MediaKind, blobType: string, createdAt: number, i
return { name: `lu-${stamp}-${tail}.${ext}`, mime }
}
-/** Where a result is saved: pictures and clips to Photos, sound to Files. */
-export function saveTarget(kind: MediaKind): 'photos' | 'files' {
- return kind === 'audio' ? 'files' : 'photos'
+/** Where a result is saved: pictures and clips to Photos, sound and 3D models to Files. */
+export function saveTarget(kind: ResultKind): 'photos' | 'files' {
+ return kind === 'audio' || kind === '3d' ? 'files' : 'photos'
}
diff --git a/src/mobile/screens/create/parts/guided-run.ts b/src/mobile/screens/create/parts/guided-run.ts
index a13b9f3e..56ffc646 100644
--- a/src/mobile/screens/create/parts/guided-run.ts
+++ b/src/mobile/screens/create/parts/guided-run.ts
@@ -50,7 +50,7 @@ export interface Attached {
export interface StepDone {
jobId: string
- kind: 'image' | 'video' | 'audio'
+ kind: 'image' | 'video' | 'audio' | '3d'
}
export type FileTrouble =
diff --git a/src/mobile/screens/create/parts/policy.ts b/src/mobile/screens/create/parts/policy.ts
index 2216730b..6526b813 100644
--- a/src/mobile/screens/create/parts/policy.ts
+++ b/src/mobile/screens/create/parts/policy.ts
@@ -12,11 +12,15 @@ export type { ReportTarget, StorePolicy } from '../../../policy'
/** Report a result of the gallery. A result of the user's computer is reported as made outside the cloud. */
export function reportItem(item: GalleryItem): void {
+ // The server's report kinds have no 3D yet (content_reports.kind): a model
+ // goes as an image, and the excerpt says what it is.
+ const kind = item.type === '3d' ? 'image' : item.type
+ const excerpt = `${item.type === '3d' ? '3D model: ' : ''}${galleryLabelShort(item, 120)}`
if (isComputerItem(item)) {
- openReport({ kind: item.type, id: item.id, model: item.model, source: 'local', origin: 'computer', excerpt: galleryLabelShort(item, 120) })
+ openReport({ kind, id: item.id, model: item.model, source: 'local', origin: 'computer', excerpt })
return
}
- openReport({ kind: item.type, id: item.jobId ?? item.id, model: item.model, source: 'cloud', excerpt: galleryLabelShort(item, 120) })
+ openReport({ kind, id: item.jobId ?? item.id, model: item.model, source: 'cloud', excerpt })
}
/** Run `start` once the user agreed that content goes to an AI service. On "no" nothing starts and nothing is cleared. */
diff --git a/src/mobile/screens/create/parts/ui.tsx b/src/mobile/screens/create/parts/ui.tsx
index 21dda37c..e305fb8f 100644
--- a/src/mobile/screens/create/parts/ui.tsx
+++ b/src/mobile/screens/create/parts/ui.tsx
@@ -8,7 +8,7 @@
*/
import { useCallback, useEffect, useRef, useState, type RefObject } from 'react'
import {
- Eraser, FastForward, Film, Image as ImageIcon, Maximize2, Mic, Music, PersonStanding, RefreshCw, Scissors,
+ Box, Eraser, FastForward, Film, Image as ImageIcon, Maximize2, Mic, Music, PersonStanding, RefreshCw, Scissors,
TimerOff, UserRound, Video, Wand2, X,
} from 'lucide-react'
import { useCreateStore, type GalleryItem } from '../../../../stores/createStore'
@@ -37,6 +37,7 @@ export const TOOL_ICON: Record<ToolId, IconType> = {
music: Music,
extend: FastForward,
motion: PersonStanding,
+ '3d': Box,
}
/** The small round X on a thumbnail. Its target is 44 px, the mark is 22 px. */
diff --git a/src/mobile/strings/create.ts b/src/mobile/strings/create.ts
index bf5175a3..ff198549 100644
--- a/src/mobile/strings/create.ts
+++ b/src/mobile/strings/create.ts
@@ -77,6 +77,11 @@ const TOOL: Record<CreateIntent, ToolText> = {
empty: 'Add a portrait and a video. The portrait moves like the person in the video.',
show: 'Move a figure from a photo the way someone moves in a video.',
},
+ '3d': {
+ name: '3D model', short: '3D', placeholder: 'Describe one object',
+ empty: 'Describe an object, or add a photo or a short video of one.',
+ show: 'Turn words, a photo or a short video into a 3D model you can spin around.',
+ },
}
/** A getter here is a text in two wordings; the store switches of the build pick one (policy/gates.ts). */
@@ -531,7 +536,7 @@ export const CREATE_STRINGS = {
deleteTitle: (n: number) => (n === 1 ? 'Delete this result?' : `Delete ${n} results?`),
deleteText: 'It will be removed from your gallery on this phone.',
deleted: (n: number) => (n === 1 ? 'Deleted' : `${n} deleted`),
- kind: { image: 'Image', video: 'Video', audio: 'Audio' },
+ kind: { image: 'Image', video: 'Video', audio: 'Audio', '3d': '3D model' },
saving: (i: number, n: number) => `Saving ${i} of ${n}`,
preparing: 'Preparing',
},
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index 46309dac..fd4373bd 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -27,6 +27,8 @@ const RUNTIME_ONLY_KEYS: readonly string[] = [
'backend', 'source', 'mask', 'references', 'endImage', 'imageReferences', 'caps', 'isGenerating', 'comfyCorsBlocked',
// A queue of source images from yesterday must never start a run today.
'batchSources', 'batchRun', 'batchOriginal',
+ // The further sides of a 3D model are pictures of this session only.
+ 'threeDViews',
// Ein gespeicherter Preis von gestern ist eine Luege (siehe partialize
// unten): auch wenn ein fremder/aelterer Blob ihn doch mitbringt, darf er
// nie zurueckkommen.
@@ -108,7 +110,12 @@ export const LOCAL_UTILITY_OPS: ReadonlySet<UtilityOp> = new Set(['upscale'])
* Character-Studio (LoRA training + generation), talking character (lipsync),
* music, video extend and motion control. Like `utilityOp`, an escape hatch
* over the image/video mode axis: when set it wins the intent derivation. */
-export type CloudOp = 'character' | 'lipsync' | 'music' | 'extend' | 'motion'
+export type CloudOp = 'character' | 'lipsync' | 'music' | 'extend' | 'motion' | '3d'
+
+/** The three ways of the 3D tab (3.1.0). */
+export type ThreeDWay = 'text' | 'image' | 'video'
+/** The Detail step of the 3D tab. Each model maps it onto its own field. */
+export type ThreeDDetail = 'draft' | 'standard' | 'fine'
/** Which of the specialized categories ALSO run on the local ComfyUI backend
* (2.5.8 local lanes: ACE music, Wan S2V talking character, last-frame-chain
@@ -262,7 +269,7 @@ export function hidreamDefaults(model: string): (typeof MODEL_TYPE_DEFAULTS)['hi
export interface GalleryItem {
id: string
- type: 'image' | 'video' | 'audio'
+ type: 'image' | 'video' | 'audio' | '3d'
filename: string
comfyType?: string
subfolder: string
@@ -431,6 +438,17 @@ export interface CreateState {
cloudOp: CloudOp | null
/** Character-Studio sub-surface: train a new character vs generate with one. */
characterTab: 'train' | 'use'
+ /** 3D (3.1.0): which way the tab builds a model, from words, one picture
+ * or still frames of a video. Kept across sessions like characterTab. */
+ threeDWay: ThreeDWay
+ /** 3D: cut the object out of its picture before the model is built. */
+ threeDCutout: boolean
+ /** 3D: how fine the model gets, where the picked model offers a choice. */
+ threeDDetail: ThreeDDetail
+ /** 3D: the further sides (left, back, right) for a model that takes several
+ * views, or the still frames picked from a video. Front is the Stage
+ * source. Runtime-only like every ImageRef. */
+ threeDViews: ImageRef[]
/** Character-Studio training set (4-30 images). Runtime-only (blobs). */
trainImages: MediaRef[]
/** Character-Studio trigger word — the token that summons the character. */
@@ -708,6 +726,10 @@ export interface CreateState {
setTargetResolution: (r: '2k' | '4k' | '8k') => void
setMacUpscaleScale: (scale: MacUpscaleFactor) => void
setCharacterTab: (tab: 'train' | 'use') => void
+ setThreeDWay: (way: ThreeDWay) => void
+ setThreeDCutout: (on: boolean) => void
+ setThreeDDetail: (detail: ThreeDDetail) => void
+ setThreeDViews: (views: ImageRef[]) => void
addTrainImages: (imgs: MediaRef[]) => void
removeTrainImage: (name: string) => void
clearTrainImages: () => void
@@ -1201,6 +1223,10 @@ export const useCreateStore = create<CreateState>()(
utilityOp: null as UtilityOp | null,
cloudOp: null as CloudOp | null,
characterTab: 'train' as 'train' | 'use',
+ threeDWay: 'image' as ThreeDWay,
+ threeDCutout: true,
+ threeDDetail: 'standard' as ThreeDDetail,
+ threeDViews: [] as ImageRef[],
trainImages: [] as MediaRef[],
triggerWord: '',
triggerWordNote: null,
@@ -1400,6 +1426,10 @@ export const useCreateStore = create<CreateState>()(
// ── 2.5.8 cloud categories. Inputs specific to each (train set,
// audio, driving video, extend pick) live in their own slots and are
// only read by their own intent — no cross-intent bleed to clear.
+ // 3D keeps the source slot: "From image" builds from it, and the
+ // picture of a two-step "From text" lands there.
+ case '3d':
+ return { ...base, cloudOp: '3d' as const, mode: 'image' as const, imageSubMode: 'text2img' as const, mask: null, references: [], endImage: null }
case 'character':
return { ...base, cloudOp: 'character' as const, mode: 'image' as const, imageSubMode: 'text2img' as const, ...dropAll }
case 'lipsync': {
@@ -1509,6 +1539,13 @@ export const useCreateStore = create<CreateState>()(
setTargetResolution: (targetResolution) => set({ targetResolution }),
setMacUpscaleScale: (macUpscaleScale) => set({ macUpscaleScale }),
setCharacterTab: (characterTab) => set((s) => withOwnStudioOptions(s, { characterTab })),
+ // Another way runs another model (words, one picture, several sides), so
+ // the studio options of the old one go, and the sides of one way never
+ // ride into another.
+ setThreeDWay: (threeDWay) => set((s) => withOwnStudioOptions(s, { threeDWay, threeDViews: [] })),
+ setThreeDCutout: (threeDCutout) => set({ threeDCutout }),
+ setThreeDDetail: (threeDDetail) => set({ threeDDetail }),
+ setThreeDViews: (threeDViews) => set({ threeDViews: threeDViews.slice(0, 4) }),
// Cap at the backend's photo limit (lib/train-image-cap) and skip a
// re-drop of a file already in the set, so the same folder twice does
// not double it. Every photo keeps a name of its own: a DIFFERENT photo
@@ -2038,6 +2075,9 @@ export const useCreateStore = create<CreateState>()(
storage: safeJSONStorage({ skipUnchanged: true }),
partialize: (state) => ({
mode: state.mode,
+ threeDWay: state.threeDWay,
+ threeDCutout: state.threeDCutout,
+ threeDDetail: state.threeDDetail,
videoBackend: state.videoBackend,
videoBackendInitialized: state.videoBackendInitialized,
imageModel: state.imageModel,
@@ -2175,6 +2215,10 @@ export const useCreateStore = create<CreateState>()(
if ('trainStyleTrigger' in safe && typeof safe.trainStyleTrigger !== 'boolean') safe.trainStyleTrigger = true
// 3.1.0 C75: anything but the one other shape is the source's.
if ('qwenEditShape' in safe && safe.qwenEditShape !== 'canvas') safe.qwenEditShape = 'source'
+ // 3.1.0 3D: a damaged way or detail falls back to the default.
+ if ('threeDWay' in safe && !['text', 'image', 'video'].includes(safe.threeDWay as string)) safe.threeDWay = 'image'
+ if ('threeDDetail' in safe && !['draft', 'standard', 'fine'].includes(safe.threeDDetail as string)) safe.threeDDetail = 'standard'
+ if ('threeDCutout' in safe && typeof safe.threeDCutout !== 'boolean') safe.threeDCutout = true
// The persisted slice is ~30 independent scalar preferences (see
// partialize). They are adopted as written, which is what the store
// has always done; the fields that could actually do damage — the
@@ -2187,8 +2231,9 @@ export const useCreateStore = create<CreateState>()(
/** Which pick slot the current sub-category owns. Character Studio USE picks a
* generation endpoint, TRAIN a trainer, so they are two slots. */
-export function opSlot(s: Pick<CreateState, 'characterTab' | 'removebg' | 'utilityOp' | 'cloudOp' | 'mode' | 'imageSubMode' | 'videoSubMode'>): string {
+export function opSlot(s: Pick<CreateState, 'characterTab' | 'removebg' | 'utilityOp' | 'cloudOp' | 'mode' | 'imageSubMode' | 'videoSubMode'> & Partial<Pick<CreateState, 'threeDWay'>>): string {
const intent = deriveIntent(s)
+ if (intent === '3d') return `3d:${s.threeDWay ?? 'image'}`
return intent === 'character' && s.characterTab === 'use' ? 'character:use' : intent
}