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 on the phone (cloud ways), touch-sized viewer

purple23e751511074
diff --git a/e2e/mobile/create.mobile.ts b/e2e/mobile/create.mobile.ts
index 7d3eb8b0..1549bf45 100644
--- a/e2e/mobile/create.mobile.ts
+++ b/e2e/mobile/create.mobile.ts
@@ -12,7 +12,10 @@ import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { deflateSync } from 'node:zlib'
import { expect, test, type Locator, type Page, type Route } from '@playwright/test'
+import { readFileSync } from 'node:fs'
import { SIZES, declareAdult, measureLayout, screensLoaded, shellUrl, watchErrors, type OpenOptions } from './support'
+import { cubeGlb } from '../../src/lib/three/glb-build'
+import { THREE_D_SCHEMAS, THREE_D_STUDIO, MESH_TEXT, MESH_VIEWS, threeDCatalogEntries } from '../../src/mobile/screens/create/__tests__/fixtures/three-d-models'
// ---------- test media ----------
@@ -107,6 +110,8 @@ function pngCutOut(width: number, height: number): Buffer {
}
const RESULT_PNG = png(256, 256, 30)
+/** A finished 3D model: the hand built cube of the 3D tests. */
+const GLB = Buffer.from(cubeGlb())
const photo = (name: string, tint = 0, w = 640, h = 480) => ({ name, mimeType: 'image/png', buffer: png(w, h, tint) })
const clip = (name = 'clip.webm') => ({ name, mimeType: 'video/webm', buffer: WEBM })
const sound = (name = 'voice.wav') => ({ name, mimeType: 'audio/wav', buffer: wav() })
@@ -149,7 +154,7 @@ const STUDIO_MODEL = { id: 'nucleus-image', label: 'Nucleus', kind: 'image', adu
interface MockJob {
id: string
- kind: 'image' | 'video' | 'audio'
+ kind: 'image' | 'video' | 'audio' | '3d'
model: string
op: string
prompt: string
@@ -237,7 +242,7 @@ class Cloud {
}
private resultUrl(job: MockJob): string {
- const ext = job.kind === 'image' ? 'png' : job.kind === 'video' ? 'webm' : 'wav'
+ const ext = job.kind === 'image' ? 'png' : job.kind === 'video' ? 'webm' : job.kind === '3d' ? 'glb' : 'wav'
return `https://lu-labs.ai/mock-result/${job.id}.${ext}?sig=${this.sig}`
}
@@ -318,8 +323,8 @@ class Cloud {
if (p.startsWith('/mock-result/')) {
if (this.mediaDown) return route.abort('connectionfailed')
if (Number(url.searchParams.get('sig') ?? 0) < this.validFrom || this.resultsGone) return route.fulfill({ status: 403, headers: CORS, body: 'expired' })
- const body = p.endsWith('.png') ? this.resultPng : p.endsWith('.webm') ? WEBM : wav()
- const type = p.endsWith('.png') ? 'image/png' : p.endsWith('.webm') ? 'video/webm' : 'audio/wav'
+ const body = p.endsWith('.png') ? this.resultPng : p.endsWith('.webm') ? WEBM : p.endsWith('.glb') ? GLB : wav()
+ const type = p.endsWith('.png') ? 'image/png' : p.endsWith('.webm') ? 'video/webm' : p.endsWith('.glb') ? 'model/gltf-binary' : 'audio/wav'
return route.fulfill({ status: 200, headers: { ...CORS, 'content-type': type, 'accept-ranges': 'bytes', 'cache-control': 'no-store' }, body })
}
@@ -383,7 +388,7 @@ class Cloud {
if (p === '/api/jobs' && req.method() === 'POST') {
const reply = this.submitReplies.shift()
if (reply) return answer(route, reply)
- const submit = req.postDataJSON() as { kind: 'image' | 'video' | 'audio'; model: string; prompt: string; params: Record<string, unknown> }
+ const submit = req.postDataJSON() as { kind: 'image' | 'video' | 'audio' | '3d'; model: string; prompt: string; params: Record<string, unknown> }
this.submits.push(submit)
const count = typeof submit.params.count === 'number' ? submit.params.count : 1
const cost = this.priceOf(submit)
@@ -3991,3 +3996,146 @@ test.describe('a prompt that is already there can be changed (3.0.10)', () => {
})
}
})
+
+// ---------- 3D (3.1.0, cloud only) ----------
+
+/**
+ * The cloud 3D models are not in the shipped registry yet. The app gets the
+ * three stand ins of the unit tests in place of the two registry files, and
+ * the catalog lists them. Nothing else of the app changes.
+ */
+async function serveThreeDRegistry(page: Page): Promise<void> {
+ const here = path.dirname(fileURLToPath(import.meta.url))
+ const read = (name: string) => JSON.parse(readFileSync(path.join(here, '../../src/lib/render', name), 'utf8')) as Record<string, unknown>
+ const models = { ...read('studio-models.json'), ...THREE_D_STUDIO }
+ const schemas = { ...read('provider-schemas.json'), ...THREE_D_SCHEMAS }
+ const asModule = (body: unknown) => ({ status: 200, headers: { 'content-type': 'text/javascript', 'cache-control': 'no-store' }, body: `export default ${JSON.stringify(body)}\n` })
+ await page.route(/\/src\/lib\/render\/studio-models\.json(\?.*)?$/, (route) => route.fulfill(asModule(models)))
+ await page.route(/\/src\/lib\/render\/provider-schemas\.json(\?.*)?$/, (route) => route.fulfill(asModule(schemas)))
+}
+
+const SHOTS_3D = process.env.LU_3D_SHOTS ?? ''
+
+test.describe('3D on the phone', () => {
+ test('the tool is only there when the catalog lists a 3D model', async ({ page }) => {
+ const cloud = new Cloud()
+ await openCreate(page, cloud)
+ await tid(page, 'm-create-tools-all').tap()
+ await expect(tid(page, 'm-sheet-tools')).toBeVisible()
+ await expect(tid(page, 'm-create-tools-3d')).toHaveCount(0)
+ })
+
+ test('from words: the prompt field, the model of the way, no detail step and no photo', async ({ page }) => {
+ await serveThreeDRegistry(page)
+ const cloud = new Cloud()
+ cloud.models = [...CATALOG_MODELS, ...threeDCatalogEntries()]
+ await openCreate(page, cloud)
+ await chooseTool(page, '3d')
+ await expect(tid(page, 'm-create-3d-way')).toBeVisible()
+ // The way a fresh phone starts on: a photo, so no prompt field.
+ await expect(tid(page, 'm-create-prompt')).toHaveCount(0)
+ await tid(page, 'm-create-3d-way-text').tap()
+ await expect(tid(page, 'm-create-model')).toContainText('Hunyuan3D')
+ await expect(tid(page, 'm-create-3d-detail-card')).toHaveCount(0)
+ await expect(tid(page, 'm-create-source-empty')).toHaveCount(0)
+ await expect(tid(page, 'm-create-blocked')).toHaveAttribute('data-m-reason', 'no-prompt')
+ await typePrompt(page, 'a clay teapot with a bamboo handle')
+ await expect(tid(page, 'm-create-generate')).toBeEnabled()
+ })
+
+ test('from words: the run sends the prompt and no picture', async ({ page }) => {
+ await serveThreeDRegistry(page)
+ const cloud = new Cloud()
+ cloud.models = [...CATALOG_MODELS, ...threeDCatalogEntries()]
+ await openCreate(page, cloud)
+ await chooseTool(page, '3d')
+ await tid(page, 'm-create-3d-way-text').tap()
+ await typePrompt(page, 'a clay teapot with a bamboo handle')
+ await run(page)
+ await expect(tid(page, 'm-create-result')).toHaveAttribute('data-m-kind', '3d', { timeout: 20_000 })
+ const submit = cloud.submits[cloud.submits.length - 1]
+ expect(submit).toMatchObject({ model: MESH_TEXT, kind: '3d', prompt: 'a clay teapot with a bamboo handle' })
+ expect(cloud.uploads).toHaveLength(0)
+ })
+
+ test('from a video: still frames, picked like on the desktop, and only the frames are uploaded', async ({ page }) => {
+ await serveThreeDRegistry(page)
+ const cloud = new Cloud()
+ cloud.models = [...CATALOG_MODELS, ...threeDCatalogEntries()]
+ await openCreate(page, cloud)
+ await chooseTool(page, '3d')
+ await tid(page, 'm-create-3d-way-video').tap()
+ await expect(tid(page, 'm-create-blocked')).toHaveAttribute('data-m-reason', 'no-3d-video')
+ await expect(tid(page, 'm-create-prompt')).toHaveCount(0)
+ await pick(page, tid(page, 'm-create-3d-video-add'), [clip('teapot.webm')])
+ await expect(tid(page, 'm-create-3d-video')).toHaveAttribute('data-state', 'ready', { timeout: 20_000 })
+ await expect(tid(page, 'm-create-3d-frame')).toHaveCount(8)
+ await expect(tid(page, 'm-create-3d-video')).toHaveAttribute('data-m-picked', '0,2,4,5')
+ await expect(tid(page, 'm-create-3d-detail')).toBeVisible()
+ if (SHOTS_3D) await page.screenshot({ path: path.join(SHOTS_3D, '3d-video.png') })
+ // Swap a moment: the oldest goes, the order of the video stays.
+ await tid(page, 'm-create-3d-frame').nth(7).tap()
+ await expect(tid(page, 'm-create-3d-video')).toHaveAttribute('data-m-picked', '2,4,5,7')
+ await tid(page, 'm-create-3d-detail-fine').tap()
+ await run(page)
+ await expect(tid(page, 'm-create-result')).toHaveAttribute('data-m-kind', '3d', { timeout: 20_000 })
+ const submit = cloud.submits[cloud.submits.length - 1]
+ expect(submit.model).toBe(MESH_VIEWS)
+ expect(submit.params.image_paths as string[]).toHaveLength(4)
+ expect((submit.params.studio_options as Record<string, unknown>).texture_quality).toBe('extreme')
+ expect(cloud.uploads).toHaveLength(4)
+ // No upload is the video (WebM starts with 1A 45 DF A3).
+ expect(cloud.uploads.some((u) => u.head.join(',') === '26,69,223,163')).toBe(false)
+ })
+
+ test('from a photo: further sides, the 3D view of the result, shared as a GLB, a tile in the gallery', async ({ page }) => {
+ const errors = watchErrors(page)
+ await serveThreeDRegistry(page)
+ const cloud = new Cloud()
+ cloud.models = [...CATALOG_MODELS, ...threeDCatalogEntries()]
+ await openCreate(page, cloud)
+ await chooseTool(page, '3d')
+ await tid(page, 'm-create-3d-way-image').tap()
+ await tid(page, 'm-create-add-source').tap()
+ await expect(tid(page, 'm-create-source-video')).toBeVisible()
+ await pick(page, tid(page, 'm-create-source-library'), [photo('front.png', 10)])
+ await expect(tid(page, 'm-sheet-source')).toHaveCount(0)
+ await expect(tid(page, 'm-create-source')).toBeVisible()
+ await tid(page, 'm-create-model').tap()
+ await page.locator(`[data-m-id="${MESH_VIEWS}"]`).first().tap()
+ await expect(tid(page, 'm-create-3d-sides')).toHaveAttribute('data-state', '0')
+ await pick(page, tid(page, 'm-create-3d-side-add'), [photo('left.png', 40)])
+ await expect(tid(page, 'm-create-3d-sides')).toHaveAttribute('data-state', '1')
+ if (SHOTS_3D) await page.screenshot({ path: path.join(SHOTS_3D, '3d-image.png') })
+ await run(page)
+ await expect(tid(page, 'm-create-result')).toHaveAttribute('data-m-kind', '3d', { timeout: 20_000 })
+ const submit = cloud.submits[cloud.submits.length - 1]
+ expect(submit.model).toBe(MESH_VIEWS)
+ expect(submit.params.image_paths as string[]).toHaveLength(2)
+
+ // The result turns in the 3D view right on the stage.
+ const viewer = tid(page, 'm-create-result-3d').getByTestId('model-viewer')
+ await expect(viewer).toHaveAttribute('data-phase', /ready|no-webgl/, { timeout: 20_000 })
+ if ((await viewer.getAttribute('data-phase')) === 'ready') await expect(tid(page, 'm-create-result-3d').getByTestId('model-viewer-facts')).toContainText('triangles')
+ if (SHOTS_3D) await page.screenshot({ path: path.join(SHOTS_3D, '3d-result.png') })
+
+ // Shared as the GLB it was made as.
+ await tid(page, 'm-create-result-share').tap()
+ await expect.poll(() => page.evaluate(() => (window as unknown as { __shared: { name: string; type: string }[] }).__shared)).toEqual([
+ expect.objectContaining({ name: expect.stringMatching(/\.glb$/), type: 'model/gltf-binary' }),
+ ])
+
+ await tid(page, 'm-create-result-fullscreen').tap()
+ await expect(tid(page, 'm-create-item-3d')).toBeVisible()
+ await expect(tid(page, 'm-create-item-3d').getByTestId('model-viewer')).toHaveAttribute('data-phase', /ready|no-webgl/, { timeout: 20_000 })
+ if (SHOTS_3D) await page.screenshot({ path: path.join(SHOTS_3D, '3d-item.png') })
+ await tid(page, 'm-create-item-close').tap()
+ await tid(page, 'm-create-gallery').tap()
+ const tile = page.locator('[data-testid="m-create-gallery-tile"][data-m-kind="3d"]')
+ await expect(tile).toHaveCount(1)
+ await expect(tile.getByTestId('thumb-3d')).toBeVisible()
+ await expect(tid(page, 'm-create-gallery-filter-3d')).toBeVisible()
+ if (SHOTS_3D) await page.screenshot({ path: path.join(SHOTS_3D, '3d-gallery.png') })
+ expect(errors()).toEqual([])
+ })
+})
diff --git a/mobile-tests/TESTIDS.md b/mobile-tests/TESTIDS.md
index 9ea4990d..8695a5a8 100644
--- a/mobile-tests/TESTIDS.md
+++ b/mobile-tests/TESTIDS.md
@@ -140,3 +140,17 @@ Altersfrage (vor der Shell, Wort `age`, Android und iOS gleich):
- `m-age-confirm-back` ("Go back"): zurueck zur ersten Frage, nichts ist gespeichert.
- `m-age-confirm-minor` ("Yes, I am under 18"): erst diese Antwort speichert. Traegt `data-m-risk="destructive"`, weil sie sich auf dem Geraet nicht zuruecknehmen laesst; ein Fluss tippt sie nur ueber `tapBewusst` (`flows/alter.mjs`).
- Die Sperrseite `m-age-blocked` hat weiter keinen Knopf.
+
+## Neu in 3.1.0: 3D in Create (Handy, nur LU Cloud)
+
+Das Werkzeug `3d` steht als letztes in der Leiste (`m-create-tool-3d`, im Blatt `m-create-tools-3d`). Es erscheint nur, wenn der Katalog ein 3D-Modell fuehrt. Auf "My computer" gibt es 3D in v1 nicht.
+
+- `m-create-3d-way` (Segmented) mit `m-create-3d-way-text`, `m-create-3d-way-image`, `m-create-3d-way-video`: der Weg. Die Zeile darum heisst `m-create-3d-way-row`.
+- Weg Image: die Quelle wie bei jedem Werkzeug (`m-create-source`, `m-create-source-add`). Nimmt das Modell mehrere Seiten: `m-create-3d-sides` (`data-state` ist die Zahl der weiteren Seiten), `m-create-3d-side-add` (traegt `sensor`), `m-create-3d-side-remove`.
+- Weg Video: `m-create-3d-video` mit `data-state` `empty`, `reading` oder `ready`; `m-create-3d-video-add` (traegt `sensor`), `m-create-3d-video-remove`, `m-create-3d-video-error`. Die Standbilder: `m-create-3d-frames` mit je `m-create-3d-frame` (`data-m-id` ist die Nummer des Moments, `aria-pressed` sagt, ob er gewaehlt ist). `data-m-picked` am Kasten nennt die gewaehlten Nummern. Das Video wird nie hochgeladen.
+- Im Blatt "Add source" (`m-sheet-source`) beim Werkzeug 3D zusaetzlich `m-create-source-video` (traegt `sensor`).
+- Detailstufe, wo das Modell eine hat: `m-create-3d-detail-card`, `m-create-3d-detail` (Segmented) mit `m-create-3d-detail-draft`, `m-create-3d-detail-standard`, `m-create-3d-detail-fine`.
+- Sperrgrund ohne Video: `m-create-blocked` mit `data-m-reason="no-3d-video"`.
+- Ergebnis auf der Buehne: `m-create-result` mit `data-m-kind="3d"`, darin `m-create-result-3d` mit dem 3D-Betrachter (`model-viewer`, `data-phase` `loading`, `ready`, `heavy`, `error` oder `no-webgl`; Leiste `model-viewer-bar` mit `mv-turn`, `mv-look-color`, `mv-look-clay`, `mv-look-wireframe`, `mv-backdrop`, `mv-reset`, `mv-fullscreen`, `mv-download`, Faktenzeile `model-viewer-facts`). Die Kennungen des Betrachters kommen aus `src/components/three` und folgen nicht dem Schema `m-*`.
+- Grosser Blick (`/create/item/:id`): `m-create-item-3d` im `m-create-item-stage`. Speichern und Teilen gehen als `.glb` nach Files.
+- Galerie: die Kachel `m-create-gallery-tile` mit `data-m-kind="3d"` zeigt `thumb-3d` (Standbild oder Wuerfel). Der Filter `m-create-gallery-filter-3d` erscheint nur, wenn die Galerie ein 3D-Modell hat.
diff --git a/src/components/create/experimental/__tests__/ein-zustand-eine-stimme.test.ts b/src/components/create/experimental/__tests__/ein-zustand-eine-stimme.test.ts
index 87802d3d..69178a64 100644
--- a/src/components/create/experimental/__tests__/ein-zustand-eine-stimme.test.ts
+++ b/src/components/create/experimental/__tests__/ein-zustand-eine-stimme.test.ts
@@ -86,13 +86,14 @@ describe('D-S31: die Regel gibt es genau einmal', () => {
})
it('der Balken haengt an ihr', () => {
- expect(CREATE).toMatch(/setupCardOwnsStage \|\| comfyStarting \? null : modelLoadError/)
+ // 3.1.0: the Mac's 3D tab runs its own engine and is silent too (threeDOwnEngine).
+ expect(CREATE).toMatch(/setupCardOwnsStage \|\| comfyStarting \|\| threeDOwnEngine \? null : modelLoadError/)
})
it('schweigt, waehrend ComfyUI startet (Gegenprobe 8, 02.10.)', () => {
// "is not running" in Rot neben "is starting up" sagte zweimal Gegensaetzliches.
const b = CREATE.match(/const banner = ([^\n]+)/)
- expect(b![1]).toContain('comfyStarting ? null')
+ expect(b![1]).toContain('comfyStarting || threeDOwnEngine ? null')
})
it('schweigt im Cloud-Modus: dort rendert nichts lokal (12.10.2026)', () => {
diff --git a/src/components/three/ModelViewer.tsx b/src/components/three/ModelViewer.tsx
index 6594f69f..9e4716f0 100644
--- a/src/components/three/ModelViewer.tsx
+++ b/src/components/three/ModelViewer.tsx
@@ -146,11 +146,11 @@ export default function ModelViewer({ item, className, onFullscreen, touch }: Mo
)}
</div>
)}
- <div className="absolute top-2 right-2 flex gap-1" data-testid="model-viewer-bar">
+ <div className="absolute top-2 right-2 left-2 flex flex-wrap justify-end gap-1 pointer-events-none [&>*]:pointer-events-auto" data-testid="model-viewer-bar">
{phase === 'ready' && (
<>
- <Btn title={VIEWER_TEXT.turn} pressed={turning} onClick={() => setTurning((t) => !t)} testid="mv-turn"><RefreshCw size={14} /></Btn>
- <div className="flex rounded-lg bg-black/50 backdrop-blur overflow-hidden" role="group" aria-label="Look">
+ <Btn touch={touch} title={VIEWER_TEXT.turn} pressed={turning} onClick={() => setTurning((t) => !t)} testid="mv-turn"><RefreshCw size={14} /></Btn>
+ <div className="flex gap-px rounded-lg bg-black/50 backdrop-blur overflow-hidden" role="group" aria-label="Look">
{LOOKS.map((l) => (
<button
key={l}
@@ -158,21 +158,21 @@ export default function ModelViewer({ item, className, onFullscreen, touch }: Mo
aria-pressed={look === l}
data-testid={`mv-look-${l}`}
onClick={() => setLook(l)}
- className={cn('lu-on-dark px-2 h-7 t-control', look === l ? 'text-white bg-white/10' : 'text-gray-300 hover:text-white')}
+ className={cn('lu-on-dark px-2 t-control', touch ? 'h-11 px-3' : 'h-7', look === l ? 'text-white bg-white/10' : 'text-gray-300 hover:text-white')}
>
{VIEWER_TEXT.looks[l]}
</button>
))}
</div>
- <Btn title={VIEWER_TEXT.backdrop} onClick={() => setBackdrop((b) => (b === 'dark' ? 'light' : 'dark'))} testid="mv-backdrop">
+ <Btn touch={touch} title={VIEWER_TEXT.backdrop} onClick={() => setBackdrop((b) => (b === 'dark' ? 'light' : 'dark'))} testid="mv-backdrop">
{backdrop === 'dark' ? <Sun size={14} /> : <Moon size={14} />}
</Btn>
- <Btn title={VIEWER_TEXT.reset} onClick={() => viewerRef.current?.reset()} testid="mv-reset"><RotateCcw size={14} /></Btn>
+ <Btn touch={touch} title={VIEWER_TEXT.reset} onClick={() => viewerRef.current?.reset()} testid="mv-reset"><RotateCcw size={14} /></Btn>
</>
)}
- {onFullscreen && <Btn title={VIEWER_TEXT.fullscreen} onClick={onFullscreen} testid="mv-fullscreen"><Maximize2 size={14} /></Btn>}
+ {onFullscreen && <Btn touch={touch} title={VIEWER_TEXT.fullscreen} onClick={onFullscreen} testid="mv-fullscreen"><Maximize2 size={14} /></Btn>}
<div className="relative">
- <Btn title={VIEWER_TEXT.download} onClick={() => (canExport ? setMenu((m) => !m) : void save('glb'))} testid="mv-download"><Download size={14} /></Btn>
+ <Btn touch={touch} title={VIEWER_TEXT.download} onClick={() => (canExport ? setMenu((m) => !m) : void save('glb'))} testid="mv-download"><Download size={14} /></Btn>
{menu && (
<div className="absolute right-0 top-8 z-10 min-w-[230px] rounded-lg bg-[var(--lu-surface,#1c1d22)] border border-white/10 shadow-xl py-1" role="menu">
{MESH_FORMATS.map((f) => (
@@ -194,7 +194,7 @@ export default function ModelViewer({ item, className, onFullscreen, touch }: Mo
{phase === 'ready' && (
<div className="absolute bottom-2 left-3 right-3 flex justify-between gap-3 t-mono text-gray-400 pointer-events-none">
<span data-testid="model-viewer-facts">{facts}</span>
- <span className="hidden sm:inline">{touch ? VIEWER_TEXT.hintTouch : VIEWER_TEXT.hint}</span>
+ <span className={touch ? undefined : 'hidden sm:inline'}>{touch ? VIEWER_TEXT.hintTouch : VIEWER_TEXT.hint}</span>
</div>
)}
{phase === 'ready' && message && (
@@ -204,7 +204,7 @@ export default function ModelViewer({ item, className, onFullscreen, touch }: Mo
)
}
-function Btn({ children, title, onClick, pressed, testid }: { children: React.ReactNode; title: string; onClick: () => void; pressed?: boolean; testid: string }) {
+function Btn({ children, title, onClick, pressed, testid, touch }: { children: React.ReactNode; title: string; onClick: () => void; pressed?: boolean; testid: string; touch?: boolean }) {
return (
<button
type="button"
@@ -214,7 +214,9 @@ function Btn({ children, title, onClick, pressed, testid }: { children: React.Re
onClick={onClick}
data-testid={testid}
className={cn(
- 'lu-on-dark w-7 h-7 flex items-center justify-center rounded-lg bg-black/50 backdrop-blur transition-colors',
+ 'lu-on-dark flex items-center justify-center rounded-lg bg-black/50 backdrop-blur transition-colors',
+ // A finger needs 44 px (the phone's rule), a mouse 28.
+ touch ? 'w-11 h-11' : 'w-7 h-7',
pressed ? 'text-white bg-white/15' : 'text-gray-200 hover:text-white hover:bg-black/70',
)}
>
diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.ts
index b8aa36b9..6073e172 100644
--- a/src/hooks/useCloudCreate.ts
+++ b/src/hooks/useCloudCreate.ts
@@ -419,7 +419,17 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {
s.setError('Motion control needs a character image and a driving video.')
return
}
- if (!specialOp && op !== 'generate' && !s.source) {
+ // 3D from text builds from words alone, under op 'studio'.
+ const threeDFromText = intent === '3d' && s.threeDWay === 'text'
+ if (intent === '3d' && !threeDFromText && !s.source) {
+ s.setError(s.threeDWay === 'video' ? THREE_D_TEXT.needVideo : THREE_D_TEXT.needSource)
+ return
+ }
+ if (threeDFromText && !prompt.trim()) {
+ s.setError('Describe the object first.')
+ return
+ }
+ if (!specialOp && op !== 'generate' && !s.source && !threeDFromText) {
s.setError('Add a source image first.')
return
}
diff --git a/src/lib/remote-create-runner.ts b/src/lib/remote-create-runner.ts
index 93326b13..e03e94b0 100644
--- a/src/lib/remote-create-runner.ts
+++ b/src/lib/remote-create-runner.ts
@@ -30,6 +30,9 @@ import { FROM_YOUR_PHONE, type GalleryOut, type LaneCaps, type LaneInput, type L
export const REMOTE_CREATE_EVENT = 'remote-create-job'
export type RemoteCreateKind = LaneKind
+
+/** 3D (3.1.0) is made in LU Cloud only in v1, never on the user's computer. */
+export const THREE_D_NOT_ON_COMPUTER = '3D models are made in LU Cloud, not on your computer.'
export type RemoteCreateTool = 'mlx' | 'comfyui'
export interface RemoteCreateJob {
@@ -217,6 +220,8 @@ export function createRemoteCreateRunner(deps: RemoteCreateDeps): RemoteCreateRu
// The negative prompt is read apart (B30).
const verdict = checkPromptSafety(`${job.prompt} ${job.lyrics ?? ''} ${job.character ?? ''}`, { negative: job.negative })
if (verdict.blocked) throw new Error(blockMessageFor(verdict.reason))
+ // After the gate on purpose: a refused prompt reads as refused, whatever the kind.
+ if ((job.kind as string) === '3d') throw new Error(THREE_D_NOT_ON_COMPUTER)
if (!(await deps.progress(job.id, { progress: 0, stepText: 'Starting', index: 0 }))) return
stopWatch = deps.watchEngine?.(report)
if (lane) {
diff --git a/src/lib/three/mesh-load.ts b/src/lib/three/mesh-load.ts
index bc87b1d3..9303accb 100644
--- a/src/lib/three/mesh-load.ts
+++ b/src/lib/three/mesh-load.ts
@@ -29,7 +29,7 @@ export class MeshLoadError extends Error {
}
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.'
+export const COMPRESSED = 'This model is packed in a way the 3D view cannot open. You can still download it.'
/** Only addresses that carry their bytes with them may load. */
export function allowedUrl(url: string): boolean {
diff --git a/src/mobile/__tests__/risk-marks-outward.test.ts b/src/mobile/__tests__/risk-marks-outward.test.ts
index 1c36405b..d5eb401b 100644
--- a/src/mobile/__tests__/risk-marks-outward.test.ts
+++ b/src/mobile/__tests__/risk-marks-outward.test.ts
@@ -443,6 +443,9 @@ export const OUTWARD_BY_ID: Record<string, Outward> = {
'm-create-char-add': 'sensor',
'm-create-batch-add': 'sensor',
'm-create-reference-add': 'sensor',
+ 'm-create-3d-side-add': 'sensor',
+ 'm-create-3d-video-add': 'sensor',
+ 'm-create-source-video': 'sensor',
'm-create-preset-input-file': 'sensor',
'm-create-item-save': 'sensor',
'm-create-result-save': 'sensor',
diff --git a/src/mobile/screens/create/CreateModelSheet.tsx b/src/mobile/screens/create/CreateModelSheet.tsx
index 3c6ee53e..cbaaaea7 100644
--- a/src/mobile/screens/create/CreateModelSheet.tsx
+++ b/src/mobile/screens/create/CreateModelSheet.tsx
@@ -80,6 +80,7 @@ export default function CreateModelSheet() {
characterUse: f.characterUse,
musicSeconds,
fallbackCredits: { image: quota?.costs.image ?? null, video: quota?.costs.video ?? null, audio: quota?.costs.image ?? null },
+ threeDWay: f.threeDWay,
}),
)
const cheapest = cheapestModel(rows)
diff --git a/src/mobile/screens/create/CreatePage.tsx b/src/mobile/screens/create/CreatePage.tsx
index e0a6a7aa..2f7a3b23 100644
--- a/src/mobile/screens/create/CreatePage.tsx
+++ b/src/mobile/screens/create/CreatePage.tsx
@@ -43,6 +43,7 @@ import { explainError } from './parts/errors'
import { cancelGuided, isGuidedRunning } from './parts/guided-run'
import { useCreateFacts, useGate, type CreateFacts, type GateState } from './parts/facts'
import { CharacterCard, EnhanceCard, ExtendCard, MusicCard, ReferenceCard, SourceCard, VideoInputCard, VoiceCard } from './parts/InputCards'
+import { ThreeDDetailCard, ThreeDSidesCard, ThreeDVideoCard, ThreeDWaySwitch } from './parts/ThreeDCards'
import { creditsLabel, formatClock, formatCredits } from './parts/params'
import { stylesFor, useStyleStore } from './parts/styles'
import { purchaseView, reportItem, storePolicy, withAiConsent } from './parts/policy'
@@ -274,7 +275,7 @@ function Result({ item, ids, busy }: { item: GalleryItem; ids: string[]; busy: b
data-m-id={g.id}
onClick={() => dispatch({ type: 'show', id: g.id })}
>
- {g.type === 'image' && (g.remoteUrl ?? g.dataUrl) ? <img src={g.remoteUrl ?? g.dataUrl} alt="" loading="lazy" /> : <Icon icon={TOOL_ICON[g.type === 'video' ? 'video' : 'music']} />}
+ {g.type === 'image' && (g.remoteUrl ?? g.dataUrl) ? <img src={g.remoteUrl ?? g.dataUrl} alt="" loading="lazy" /> : <Icon icon={TOOL_ICON[g.type === 'video' ? 'video' : g.type === '3d' ? '3d' : 'music']} />}
</button>
))}
</div>
@@ -370,6 +371,9 @@ function Stage({ f, onRetry, onCancel, onMakeVoice }: { f: CreateFacts; onRetry:
{stageError && error ? <ErrorNotice message={error} stillBooked={pending.length > 0} onRetry={onRetry} retryDisabled={isGenerating || f.block !== null} /> : null}
+ {/* 3D: the way heads the tool (C3D-PLAN 1.1), Text, Image or Video. */}
+ {tool === '3d' ? <ThreeDWaySwitch f={f} disabled={isGenerating} /> : null}
+
{showRunning ? <Running f={f} onCancel={onCancel} /> : null}
{showResult && item ? <Result item={item} ids={run.resultIds} busy={isGenerating} /> : null}
@@ -388,7 +392,12 @@ function Stage({ f, onRetry, onCancel, onMakeVoice }: { f: CreateFacts; onRetry:
{/* The inputs of the tool. */}
{tool === 'character' ? <CharacterCard f={f} /> : null}
- {f.facts.needsSource ? <SourceCard f={f} disabled={isGenerating} /> : null}
+ {f.facts.needsSource && !(tool === '3d' && f.threeDWay === 'video') ? (
+ tool === '3d' ? <SourceCard f={f} title={T.threeD.sourceTitle} sub={T.threeD.sourceSub} disabled={isGenerating} /> : <SourceCard f={f} disabled={isGenerating} />
+ ) : null}
+ {tool === '3d' && f.threeDWay === 'image' ? <ThreeDSidesCard f={f} disabled={isGenerating} /> : null}
+ {tool === '3d' && f.threeDWay === 'video' ? <ThreeDVideoCard f={f} disabled={isGenerating} /> : null}
+ {tool === '3d' ? <ThreeDDetailCard f={f} disabled={isGenerating} /> : null}
{tool === 'lipsync' && f.needsClip ? <VideoInputCard f={f} title={T.presenterClip} sub={T.presenterClipSub} disabled={isGenerating} testid="m-create-clip" /> : null}
{tool === 'lipsync' && f.needsPortrait ? <SourceCard f={f} title={T.presenter} sub={T.presenterSub} disabled={isGenerating} /> : null}
{tool === 'lipsync' && !f.needsClip && !f.needsPortrait ? (
@@ -413,7 +422,7 @@ function Stage({ f, onRetry, onCancel, onMakeVoice }: { f: CreateFacts; onRetry:
) : null}
{/* A tool without an input card says in one line what it wants. The tool row above names it, the cards say it for the others. */}
- {!showRunning && !showResult && HINT_TOOLS.includes(tool) ? (
+ {!showRunning && !showResult && (HINT_TOOLS.includes(tool) || (tool === '3d' && f.threeDWay === 'text')) ? (
<p className="m-k-hint" data-testid="m-create-empty">
<Icon icon={ToolGlyph} />
{text.empty}
diff --git a/src/mobile/screens/create/ItemViewerPage.tsx b/src/mobile/screens/create/ItemViewerPage.tsx
index a98252dc..15ebf3e5 100644
--- a/src/mobile/screens/create/ItemViewerPage.tsx
+++ b/src/mobile/screens/create/ItemViewerPage.tsx
@@ -8,6 +8,7 @@
* (opens the prompt, with Copy). Where the store rules ask for it there is
* "Report".
* The id "source" shows the current source image of K1 (K1.18).
+ * A 3D model (3.1.0) shows the 3D view: drag turns it, two fingers zoom.
*/
import { createContext, useCallback, useContext, useEffect, useRef, useState, type PointerEvent } from 'react'
import { ChevronLeft, ChevronRight, Download, Ellipsis, Flag, Share2, X, ZoomIn, ZoomOut } from 'lucide-react'
@@ -21,6 +22,7 @@ import { Button, IconButton } from '../../ui'
import { copyWithToast, saveWithToast, shareWithToast } from './parts/actions'
import { VIEW_START, clampView, pinchView, type Point, type Size, type View } from './parts/mask-strokes'
import { reportItem, shownCreateLabel, storePolicy } from './parts/policy'
+import { LazyModelViewer } from '../../../components/three/LazyModelViewer'
import { MediaStateBox, itemName, useGalleryItem, useItemMedia } from './parts/ui'
import { CheckerBoard, useChecker } from './parts/checker'
@@ -234,6 +236,12 @@ function ItemView({ item }: { item: GalleryItem }) {
</div>
) : item.type === 'image' ? (
<ZoomImage src={media.url} alt={name} view={view} setView={setView} onSwipe={go} onError={media.onError} />
+ ) : item.type === '3d' ? (
+ <div className="m-viewer-stage" data-testid="m-create-item-stage" data-el="K7.7" aria-label={name}>
+ <div className="m-k-viewer-3d" data-testid="m-create-item-3d">
+ <LazyModelViewer key={item.id} item={item} touch />
+ </div>
+ </div>
) : (
<div className="m-viewer-stage" data-testid="m-create-item-stage" data-el="K7.7">
{item.type === 'video' ? (
diff --git a/src/mobile/screens/create/PresetSheet.tsx b/src/mobile/screens/create/PresetSheet.tsx
index 0cccbdbb..3364631b 100644
--- a/src/mobile/screens/create/PresetSheet.tsx
+++ b/src/mobile/screens/create/PresetSheet.tsx
@@ -11,6 +11,7 @@
*/
import { memo, useRef } from 'react'
import { AudioLines, Box, Play } from 'lucide-react'
+import { ModelThumb } from '../../../components/three/ModelThumb'
import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
import { useContentPolicy } from '../../../hooks/useContentPolicy'
import { useSheet } from '../../nav'
@@ -41,7 +42,7 @@ 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}
+ {near && item.type === '3d' && media.state === 'ok' ? <ModelThumb item={item} small /> : null}
{media.state !== 'ok' ? <MediaStateBox state={media.state} compact /> : null}
</button>
{item.type !== 'image' && media.state === 'ok' ? (
diff --git a/src/mobile/screens/create/ShowcasePage.tsx b/src/mobile/screens/create/ShowcasePage.tsx
index 81ce2efa..031bd56a 100644
--- a/src/mobile/screens/create/ShowcasePage.tsx
+++ b/src/mobile/screens/create/ShowcasePage.tsx
@@ -13,6 +13,7 @@ import { Button, Icon, Page } from '../../ui'
import { useGate } from './parts/facts'
import { purchaseView } from './parts/policy'
import { TOOLS, type ToolId } from './parts/tools'
+import { toolProbe, useCatalogVersion } from './parts/catalog'
import { TOOL_ICON } from './parts/ui'
import './parts/create.css'
@@ -49,6 +50,7 @@ function Card({ tool, index }: { tool: ToolId; index: number }) {
export default function ShowcasePage() {
const { gate } = useGate()
+ useCatalogVersion()
const purchase = purchaseView().mode
const open = gate === 'open'
const first = gate === 'signed-out' || gate === 'checking' ? T.showcase.signIn : T.showcase.turnOn
@@ -85,7 +87,8 @@ export default function ShowcasePage() {
}
>
<p className="m-k-pad m-k-card-sub m-k-intro">{T.showcase.intro}</p>
- {TOOLS.map((tool, i) => (
+ {/* 3D (3.1.0) shows only once the catalog lists a 3D model: the page never names what LU Cloud cannot make. */}
+ {TOOLS.filter((tool) => tool.id !== '3d' || toolProbe()['3d']).map((tool, i) => (
<Card key={tool.id} tool={tool.id} index={i} />
))}
</Page>
diff --git a/src/mobile/screens/create/SourceSheet.tsx b/src/mobile/screens/create/SourceSheet.tsx
index 3dc84fde..1346a5f3 100644
--- a/src/mobile/screens/create/SourceSheet.tsx
+++ b/src/mobile/screens/create/SourceSheet.tsx
@@ -4,12 +4,13 @@
* K5.1 Take photo, K5.2 Photo library (several photos start a batch where
* the tool can run one), K5.3 File, K5.4 From gallery (opens K6 as a
* picker), K5.5 Saved characters (sub page), K5.6 Close is the close button
- * of the sheet.
+ * of the sheet. 3D (3.1.0) adds Video: LU reads still frames of it, the
+ * video itself stays on the phone.
* States: the photo is being prepared, the file is too large, the format
* cannot be read.
*/
import { useEffect, useState } from 'react'
-import { Camera, FolderOpen, Images, LayoutGrid, Trash2, UsersRound } from 'lucide-react'
+import { Camera, Film, FolderOpen, Images, LayoutGrid, Trash2, UsersRound } from 'lucide-react'
import { useCreateStore } from '../../../stores/createStore'
import { deleteSavedCharacter, listSavedCharacters, subscribeSavedCharacters, type SavedCharacter } from '../../../lib/saved-characters'
import { MAX_STORED_REFERENCES } from '../../../lib/edit-references'
@@ -22,7 +23,10 @@ import { CREATE_STRINGS as T } from '../../strings/create'
import { EmptyState, IconButton, ListGroup, Notice, Progress, Row, Sheet, SkeletonRows, toast } from '../../ui'
import { addSourceFiles, fileProblemText, takeImageAsSource } from './parts/actions'
import { loadPhoneImageFromBlob } from './parts/photos'
-import { toolFacts } from './parts/tools'
+import { toolFacts, toolTakesPhoto } from './parts/tools'
+import { pickVideoFor3d } from './parts/ThreeDCards'
+import { threeDModelFacts } from './parts/three-d'
+import { useCreateFacts } from './parts/facts'
function SavedCharacters({ onDone }: { onDone: () => void }) {
const [list, setList] = useState<SavedCharacter[] | null>(null)
@@ -99,7 +103,8 @@ export default function SourceSheet() {
const [busy, setBusy] = useState(false)
const [problem, setProblem] = useState<string | null>(null)
const facts = toolFacts(tool)
- const takesSource = facts.needsSource || tool === 'lipsync' || tool === 'motion'
+ const takesSource = toolTakesPhoto(tool)
+ const model = useCreateFacts().model
if (sub === 'saved') {
return (
@@ -124,6 +129,15 @@ export default function SourceSheet() {
close()
}
+ const takeVideo = async () => {
+ setBusy(true)
+ setProblem(null)
+ const out = await pickVideoFor3d(threeDModelFacts(model.studio ? model.id : undefined).maxViews)
+ setBusy(false)
+ if (out.status === 'failed') setProblem(out.message)
+ else if (out.status === 'ok') close()
+ }
+
return (
<Sheet title={T.source.title}>
{!takesSource ? <p className="m-cap m-k-pad">{T.source.switchesToEdit}</p> : null}
@@ -170,6 +184,9 @@ export default function SourceSheet() {
testid="m-create-source-file"
el="K5.3"
/>
+ {tool === '3d' ? (
+ <Row icon={Film} title={T.source.video} subtitle={T.source.videoSub} chevron={false} disabled={busy} onPress={() => void takeVideo()} risk="sensor" testid="m-create-source-video" />
+ ) : null}
<Row icon={LayoutGrid} title={T.source.fromGallery} subtitle={T.source.fromGallerySub} disabled={busy} onPress={() => openGalleryPicker('source')} testid="m-create-source-gallery" el="K5.4" />
<Row icon={UsersRound} title={T.source.saved} subtitle={T.source.savedSub} disabled={busy} onPress={() => pushSub('saved')} testid="m-create-source-saved" el="K5.5" />
</ListGroup>
diff --git a/src/mobile/screens/create/__tests__/fixtures/three-d-models.ts b/src/mobile/screens/create/__tests__/fixtures/three-d-models.ts
new file mode 100644
index 00000000..8f7a369f
--- /dev/null
+++ b/src/mobile/screens/create/__tests__/fixtures/three-d-models.ts
@@ -0,0 +1,72 @@
+/**
+ * Three cloud 3D models for the tests of the phone, one per way, after the
+ * first wave of the plan (C3D-PLAN 3.3). The real entries come with the
+ * studio registry later; until then a test adds these and takes them out
+ * again. Endpoints are stand ins, prices are only the shape of the real ones.
+ *
+ * Used by the unit tests here and by e2e/mobile/create.mobile.ts, which
+ * serves the same entries to the app in place of the registry files.
+ */
+import type { Schema, StudioModel } from '../../../../../lib/render/studio-contract'
+
+export const MESH_IMAGE = 'trellis-2'
+export const MESH_TEXT = 'hunyuan3d-3.1-rapid-text'
+export const MESH_VIEWS = 'tripo-h3.1-multiview'
+
+export const THREE_D_STUDIO: Record<string, StudioModel> = {
+ [MESH_IMAGE]: {
+ label: 'TRELLIS.2', endpoint: 'test/trellis-2/image-to-3d', kind: '3d', adult: false, tier: 'best', weights: 'open', typical_s: 40,
+ inputs: { image: 'source_path' }, defaults: {}, baselineUsd: 0.2,
+ price: { mode: 'flat', rates: { '512': 0.1, '1024': 0.2, '1536': 0.4 }, resolutionField: 'resolution' },
+ },
+ [MESH_TEXT]: {
+ label: 'Hunyuan3D 3.1 Rapid', endpoint: 'test/hunyuan-3d/text-to-3d', kind: '3d', adult: false, tier: 'standard', weights: 'open-family', typical_s: 110,
+ inputs: {}, defaults: {}, baselineUsd: 0.27,
+ price: { mode: 'flat', rates: { default: 0.27 } },
+ },
+ [MESH_VIEWS]: {
+ label: 'Tripo H3.1 Multiview', endpoint: 'test/tripo/multiview-to-3d', kind: '3d', adult: false, tier: 'standard', weights: 'closed', typical_s: 130,
+ inputs: { images: 'image_paths' }, defaults: {}, baselineUsd: 0.36,
+ price: { mode: 'flat', rates: { standard: 0.36, detailed: 0.48, extreme: 0.6 }, resolutionField: 'texture_quality', extraImage: 0 },
+ },
+}
+
+export const THREE_D_SCHEMAS: Record<string, Schema> = {
+ 'test/trellis-2/image-to-3d': {
+ type: 'object',
+ required: ['image'],
+ properties: {
+ image: { type: 'string', format: 'uri' },
+ resolution: { type: 'integer', enum: [512, 1024, 1536], default: 1024 },
+ seed: { type: 'integer', minimum: -1, maximum: 2147483647, default: -1 },
+ },
+ },
+ 'test/hunyuan-3d/text-to-3d': {
+ type: 'object',
+ required: ['prompt'],
+ properties: { prompt: { type: 'string' } },
+ },
+ 'test/tripo/multiview-to-3d': {
+ type: 'object',
+ required: ['images'],
+ properties: {
+ images: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 4 },
+ texture_quality: { type: 'string', enum: ['standard', 'detailed', 'extreme'], default: 'standard' },
+ },
+ },
+}
+
+/** The catalog entries the server sends for them (ops studio, the price confirmed by the server). */
+export function threeDCatalogEntries(): { id: string; label: string; kind: '3d'; adult: boolean; ops: string[]; quote_required: boolean; tier: string; weights: string }[] {
+ return Object.entries(THREE_D_STUDIO).map(([id, m]) => ({ id, label: m.label, kind: '3d', adult: m.adult, ops: ['studio'], quote_required: true, tier: m.tier, weights: m.weights }))
+}
+
+/** Put the three into the registry objects the app reads. Returns the undo. */
+export function installThreeDStudio(models: Record<string, StudioModel>, schemas: Record<string, Schema>): () => void {
+ Object.assign(models, THREE_D_STUDIO)
+ Object.assign(schemas, THREE_D_SCHEMAS)
+ return () => {
+ for (const id of Object.keys(THREE_D_STUDIO)) delete models[id]
+ for (const path of Object.keys(THREE_D_SCHEMAS)) delete schemas[path]
+ }
+}
diff --git a/src/mobile/screens/create/__tests__/three-d.test.ts b/src/mobile/screens/create/__tests__/three-d.test.ts
new file mode 100644
index 00000000..25b15870
--- /dev/null
+++ b/src/mobile/screens/create/__tests__/three-d.test.ts
@@ -0,0 +1,250 @@
+/**
+ * 3D on the phone (3.1.0, cloud only): the tool, its ways, the models of
+ * each way, the detail step, the still frames of a video, the refusal of
+ * "My computer", and the file a 3D result is saved and shared as.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const frames = vi.hoisted(() => ({ count: 8, fail: false }))
+vi.mock('../../../../lib/video-frames', async () => {
+ const actual = await vi.importActual<typeof import('../../../../lib/video-frames')>('../../../../lib/video-frames')
+ return {
+ ...actual,
+ framesAcrossVideo: vi.fn(async () => {
+ if (frames.fail) throw new Error('Could not load the video')
+ return Array.from({ length: frames.count }, (_, i) => new Blob([`frame-${i}`], { type: 'image/jpeg' }))
+ }),
+ }
+})
+vi.mock('../parts/photos', async () => {
+ const actual = await vi.importActual<typeof import('../parts/photos')>('../parts/photos')
+ return {
+ ...actual,
+ loadPhoneImageFromBlob: vi.fn(async (_b: Blob, name: string) => ({ filename: name, name, url: `data:image/jpeg;base64,${name}`, width: 64, height: 64 })),
+ }
+})
+
+import schemas from '../../../../lib/render/provider-schemas.json'
+import { STUDIO_MODELS, type Schema } from '../../../../lib/render/studio-contract'
+import { useCloudCatalogStore } from '../../../../stores/cloudCatalogStore'
+import { useCreateStore } from '../../../../stores/createStore'
+import { checkPromptSafety, SAFETY_BLOCK_MESSAGE } from '../../../../lib/render/safety'
+import { createRemoteCreateRunner, THREE_D_NOT_ON_COMPUTER, type RemoteCreateDeps, type RemoteCreateJob } from '../../../../lib/remote-create-runner'
+import { evenPick as desktopEvenPick } from '../../../../components/create/experimental/ThreeDControls'
+import { CREATE_STRINGS as T } from '../../../strings/create'
+import { runModel, toolModels, toolProbe } from '../parts/catalog'
+import { saveName, saveTarget } from '../parts/files'
+import { blockReason, type ReadyInput } from '../parts/run-state'
+import { applyPicks, clearVideo, evenPick, pickDetail, pickWay, readVideoFrames, shownDetail, tapFrame, threeDModelFacts, togglePick, useThreeDVideo } from '../parts/three-d'
+import { COMPUTER_TOOLS } from '../parts/computer-tools'
+import { TOOL_IDS, toolFacts, toolTakesPhoto } from '../parts/tools'
+import { MESH_IMAGE, MESH_TEXT, MESH_VIEWS, installThreeDStudio, threeDCatalogEntries } from './fixtures/three-d-models'
+
+const picks = { cloudImageModel: '', cloudVideoModel: '', cloudOpModel: '' }
+const fallbackCredits = { image: null, video: null, audio: null }
+
+let undo: () => void = () => {}
+let catalogBefore: ReturnType<typeof useCloudCatalogStore.getState>['models']
+
+beforeAll(() => {
+ undo = installThreeDStudio(STUDIO_MODELS, schemas as Record<string, Schema>)
+ catalogBefore = useCloudCatalogStore.getState().models
+})
+afterAll(() => {
+ undo()
+ useCloudCatalogStore.setState({ models: catalogBefore })
+})
+beforeEach(() => {
+ useCloudCatalogStore.setState({ models: [...catalogBefore, ...threeDCatalogEntries()] as typeof catalogBefore })
+ useCreateStore.getState().setIntent('3d')
+ useCreateStore.setState({ threeDWay: 'image', threeDViews: [], source: null, cloudStudioOptions: {}, cloudOpModel: '' })
+ useThreeDVideo.setState({ name: null, frames: [], picked: [], reading: false })
+ frames.count = 8
+ frames.fail = false
+})
+afterEach(() => vi.clearAllMocks())
+
+describe('the 3D tool', () => {
+ it('stands last in the row, so no other tool moves', () => {
+ expect(TOOL_IDS[TOOL_IDS.length - 1]).toBe('3d')
+ expect(TOOL_IDS.indexOf('motion')).toBe(TOOL_IDS.length - 2)
+ })
+
+ it('from words wants a prompt, from a photo or a video a picture and no prompt', () => {
+ expect(toolFacts('3d', 'text')).toMatchObject({ kind: '3d', needsSource: false, prompt: 'yes', batch: false, hasModels: true })
+ expect(toolFacts('3d', 'image')).toMatchObject({ needsSource: true, prompt: 'no' })
+ expect(toolFacts('3d', 'video')).toMatchObject({ needsSource: true, prompt: 'no' })
+ // Other tools do not read the way.
+ expect(toolFacts('edit', 'text')).toEqual(toolFacts('edit'))
+ })
+
+ it('keeps a photo the user adds, on every way', () => {
+ expect(toolTakesPhoto('3d')).toBe(true)
+ expect(toolTakesPhoto('image')).toBe(false)
+ })
+
+ it('is not a tool of "My computer" in v1', () => {
+ expect(COMPUTER_TOOLS as readonly string[]).not.toContain('3d')
+ })
+
+ it('has a text for every place the phone shows it', () => {
+ expect(T.tool['3d'].name).toBe('3D model')
+ expect(T.threeD.ways).toEqual({ text: 'Text', image: 'Image', video: 'Video' })
+ expect(T.block['no-3d-video']).toBeTruthy()
+ expect(T.gal.kind['3d']).toBe('3D model')
+ })
+})
+
+describe('the catalog decides', () => {
+ it('the tab is there as soon as the catalog lists a 3D model, and gone without one', () => {
+ expect(toolProbe()['3d']).toBe(true)
+ useCloudCatalogStore.setState({ models: catalogBefore })
+ expect(toolProbe()['3d']).toBe(false)
+ })
+
+ it('each way lists only the models of its way', () => {
+ const ids = (way: 'text' | 'image' | 'video') => toolModels('3d', { character: null, characterUse: false, musicSeconds: 0, fallbackCredits, threeDWay: way }).map((r) => r.id)
+ expect(ids('text')).toEqual([MESH_TEXT])
+ // The picker groups by tier like every other list; which one runs first is the run's matter (next test).
+ expect(ids('image').sort()).toEqual([MESH_IMAGE, MESH_VIEWS].sort())
+ expect(ids('video').sort()).toEqual([MESH_IMAGE, MESH_VIEWS].sort())
+ })
+
+ it('the run takes the model of the way, also with a pick left from another way', () => {
+ expect(runModel('3d', picks, null, false, 'text').id).toBe(MESH_TEXT)
+ expect(runModel('3d', picks, null, false, 'video').id).toBe(MESH_VIEWS)
+ expect(runModel('3d', { ...picks, cloudOpModel: MESH_TEXT }, null, false, 'image').id).toBe(MESH_IMAGE)
+ expect(runModel('3d', { ...picks, cloudOpModel: MESH_VIEWS }, null, false, 'image')).toMatchObject({ id: MESH_VIEWS, studio: true })
+ })
+
+ it('a model says how many pictures it takes and whether it has a detail step', () => {
+ expect(threeDModelFacts(MESH_VIEWS)).toEqual({ maxViews: 4, hasDetail: true })
+ expect(threeDModelFacts(MESH_IMAGE)).toEqual({ maxViews: 1, hasDetail: true })
+ expect(threeDModelFacts(MESH_TEXT)).toEqual({ maxViews: 1, hasDetail: false })
+ expect(threeDModelFacts(undefined)).toEqual({ maxViews: 1, hasDetail: false })
+ })
+})
+
+describe('the detail step', () => {
+ it('writes the model’s own field, where the price and the booking read it', () => {
+ expect(shownDetail(MESH_IMAGE, {}, 'standard')).toBe('standard')
+ pickDetail(MESH_IMAGE, 'fine')
+ expect(useCreateStore.getState().cloudStudioOptions).toEqual({ resolution: 1536 })
+ expect(shownDetail(MESH_IMAGE, useCreateStore.getState().cloudStudioOptions, 'standard')).toBe('fine')
+ pickDetail(MESH_VIEWS, 'draft')
+ expect(useCreateStore.getState().cloudStudioOptions).toMatchObject({ texture_quality: 'standard' })
+ })
+})
+
+describe('the still frames of a video', () => {
+ it('spread like on the desktop', () => {
+ for (const [n, want] of [[8, 4], [8, 1], [2, 4], [0, 4], [5, 3], [8, 2]]) expect(evenPick(n, want)).toEqual(desktopEvenPick(n, want))
+ })
+
+ it('a tap swaps a moment, never the last one, and keeps the order of the video', () => {
+ expect(togglePick([0, 2, 4, 5], 7, 4)).toEqual([2, 4, 5, 7])
+ expect(togglePick([0, 2], 5, 4)).toEqual([0, 2, 5])
+ expect(togglePick([0, 2], 2, 4)).toEqual([0])
+ expect(togglePick([3], 3, 4)).toEqual([3])
+ expect(togglePick([3], 6, 1)).toEqual([6])
+ })
+
+ it('the picked moments become the source and the further sides; the video is never kept', async () => {
+ const out = await readVideoFrames(new File(['x'], 'teapot.mp4', { type: 'video/mp4' }), 4)
+ expect(out).toEqual({ ok: true })
+ const st = useCreateStore.getState()
+ expect(st.threeDWay).toBe('video')
+ expect(st.source?.name).toBe('teapot-frame-1.jpg')
+ expect(st.threeDViews.map((v) => v.name)).toEqual(['teapot-frame-3.jpg', 'teapot-frame-5.jpg', 'teapot-frame-6.jpg'])
+ expect(useCreateStore.getState().videoInput).toBeNull()
+ tapFrame(7, 4)
+ expect(useCreateStore.getState().source?.name).toBe('teapot-frame-3.jpg')
+ expect(useCreateStore.getState().threeDViews).toHaveLength(3)
+ })
+
+ it('a model that takes one picture gets the middle moment only', async () => {
+ await readVideoFrames(new File(['x'], 'cup.mov', { type: 'video/quicktime' }), 1)
+ expect(useCreateStore.getState().source?.name).toBe('cup-frame-4.jpg')
+ expect(useCreateStore.getState().threeDViews).toEqual([])
+ })
+
+ it('back on the video way after a photo, the moments come back', async () => {
+ await readVideoFrames(new File(['x'], 'cup.webm', { type: 'video/webm' }), 4)
+ pickWay('image', 4)
+ expect(useCreateStore.getState().threeDViews).toEqual([])
+ pickWay('video', 4)
+ expect(useCreateStore.getState().threeDViews).toHaveLength(3)
+ clearVideo()
+ expect(useCreateStore.getState().source).toBeNull()
+ applyPicks(4)
+ expect(useCreateStore.getState().source).toBeNull()
+ })
+
+ it('a file that is no video, or a video that does not play, says so and keeps nothing', async () => {
+ expect(await readVideoFrames(new File(['x'], 'a.png', { type: 'image/png' }), 4)).toEqual({ ok: false, reason: 'wrong-kind' })
+ frames.fail = true
+ expect(await readVideoFrames(new File(['x'], 'a.mp4', { type: 'video/mp4' }), 4)).toEqual({ ok: false, reason: 'unreadable' })
+ expect(useThreeDVideo.getState().frames).toEqual([])
+ })
+
+ it('without a frame the run waits for a video, not for a photo', () => {
+ const base: ReadyInput = {
+ online: true, tool: '3d', promptNeeded: false, prompt: '', sourceNeeded: true, hasSource: false, maskNeeded: false, hasMask: false,
+ characterUse: false, hasCharacter: false, trainPhotos: 0, minTrainPhotos: 0, hasVoice: false, needsPortrait: false, needsClip: false,
+ hasVideo: false, hasExtendClip: false, hasModel: true, priceState: 'known', quotaKnown: true,
+ }
+ expect(blockReason({ ...base, threeDWay: 'video' })).toBe('no-3d-video')
+ expect(blockReason({ ...base, threeDWay: 'image' })).toBe('no-source')
+ expect(blockReason({ ...base, threeDWay: 'text', sourceNeeded: false, promptNeeded: true })).toBe('no-prompt')
+ })
+})
+
+describe('a 3D result leaves the phone as a GLB', () => {
+ it('is saved to Files with the ending .glb, whatever type the bytes carry', () => {
+ expect(saveTarget('3d')).toBe('files')
+ const { name, mime } = saveName('3d', 'application/octet-stream', Date.UTC(2026, 10, 13), 'res-abcdef')
+ expect(name).toMatch(/\.glb$/)
+ expect(mime).toBe('model/gltf-binary')
+ })
+})
+
+describe('"My computer" refuses 3D in v1, after the content gate', () => {
+ function rig(): { deps: RemoteCreateDeps; finished: { ok: boolean; error: string | null }[]; generated: number } {
+ const r = { finished: [] as { ok: boolean; error: string | null }[], generated: 0, deps: null as unknown as RemoteCreateDeps }
+ r.deps = {
+ tool: 'comfyui',
+ runLane: async () => { r.generated++; return '' },
+ galleryItems: () => [],
+ replyGallery: async () => null,
+ generate: async () => { r.generated++; return '' },
+ cancel: () => {},
+ listModels: async () => ({ kinds: {}, engine_ready: true }),
+ desktopBusy: () => false,
+ inputRef: () => undefined,
+ progress: async () => true,
+ finish: async (_id, ok, error) => { r.finished.push({ ok, error }) },
+ replyCapabilities: async () => null,
+ addToGallery: () => {},
+ }
+ return r
+ }
+ const job = (prompt: string): RemoteCreateJob => ({ id: 'j', kind: '3d' as RemoteCreateJob['kind'], prompt, negative: '', model: null, width: 0, height: 0, steps: null, seed: null, count: 1, conversation_id: 'remote-create:j' })
+
+ it('a harmless prompt gets the plain sentence and nothing runs', async () => {
+ const r = rig()
+ await createRemoteCreateRunner(r.deps).handle({ action: 'run', job: job('a clay teapot') })
+ expect(r.finished).toEqual([{ ok: false, error: THREE_D_NOT_ON_COMPUTER }])
+ expect(r.generated).toBe(0)
+ })
+
+ it('a refused prompt reads as refused, not as "not here"', async () => {
+ const prompt = 'nude schoolgirl'
+ expect(checkPromptSafety(prompt).blocked).toBe(true)
+ const r = rig()
+ await createRemoteCreateRunner(r.deps).handle({ action: 'run', job: job(prompt) })
+ expect(r.finished[0].ok).toBe(false)
+ expect(r.finished[0].error).not.toBe(THREE_D_NOT_ON_COMPUTER)
+ expect(r.finished[0].error).toBe(SAFETY_BLOCK_MESSAGE)
+ expect(r.generated).toBe(0)
+ })
+})
diff --git a/src/mobile/screens/create/parts/GalleryBody.tsx b/src/mobile/screens/create/parts/GalleryBody.tsx
index 2b7ba30a..091567f7 100644
--- a/src/mobile/screens/create/parts/GalleryBody.tsx
+++ b/src/mobile/screens/create/parts/GalleryBody.tsx
@@ -14,6 +14,7 @@
*/
import { memo, useMemo, useRef, useState } from 'react'
import { AudioLines, Box, Check, ListChecks, Play, X } from 'lucide-react'
+import { ModelThumb } from '../../../../components/three/ModelThumb'
import { useCreateStore, type GalleryItem } from '../../../../stores/createStore'
import { nav } from '../../../nav'
import { COMPUTER_STRINGS as C, CREATE_STRINGS as T } from '../../../strings/create'
@@ -22,10 +23,10 @@ import { ComputerGallery } from './ComputerGallery'
import { useComputerAvailability } from './computer-source'
import { deleteItems, saveWithToast, takeItemAsExtend, takeItemAsSource, takeItemAsVoice } from './actions'
import { saveItem } from './media-out'
-import { toolFacts } from './tools'
+import { toolTakesPhoto } from './tools'
import { MediaStateBox, itemName, useItemMedia, useNearViewport } from './ui'
-type Filter = 'all' | 'image' | 'video' | 'audio'
+type Filter = 'all' | 'image' | 'video' | 'audio' | '3d'
import type { PickPurpose } from './pick'
type Purpose = PickPurpose
@@ -61,7 +62,8 @@ 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}
+ {/* A 3D model shows the still the 3D view drew of it, or the cube with its name. */}
+ {near && item.type === '3d' && state === 'ok' ? <ModelThumb item={item} small /> : null}
{state !== 'ok' ? <MediaStateBox state={state} compact /> : null}
</button>
{item.type !== 'image' && state === 'ok' ? (
@@ -97,6 +99,7 @@ export function GalleryBody({ purpose }: { purpose: Purpose | null }) {
const onComputer = computerGallery && where === 'computer'
const kind = purpose ? PURPOSE_KIND[purpose] : filter === 'all' ? null : filter
+ const has3d = gallery.some((g) => g.type === '3d')
const items = useMemo(() => {
const list = kind ? gallery.filter((g) => g.type === kind) : gallery
// A picker only offers what can be handed over: a cloud result that still exists.
@@ -165,7 +168,7 @@ export function GalleryBody({ purpose }: { purpose: Purpose | null }) {
if (purpose === 'source') {
const st = useCreateStore.getState()
const tool = st.intent()
- ok = await takeItemAsSource(item, toolFacts(tool).needsSource || tool === 'lipsync' || tool === 'motion' ? tool : 'edit')
+ ok = await takeItemAsSource(item, toolTakesPhoto(tool) ? tool : 'edit')
} else if (purpose === 'extend') ok = takeItemAsExtend(item)
else ok = takeItemAsVoice(item)
setBusy(null)
@@ -238,9 +241,10 @@ export function GalleryBody({ purpose }: { purpose: Purpose | null }) {
{tabs}
{picking ? null : (
<ChipGroup label={T.gal.filters} testid="m-create-gallery-filters">
- {(['all', 'image', 'video', 'audio'] as const).map((id) => (
+ {/* The 3D chip only where there is a 3D model, so the row of everyone else stays as it was. */}
+ {(['all', 'image', 'video', 'audio', ...(has3d || filter === '3d' ? ['3d' as const] : [])] as const).map((id) => (
<Chip key={id} kind="filter" selected={filter === id} onPress={() => setFilter(id)} testid={`m-create-gallery-filter-${id}`} el="K6.1">
- {id === 'all' ? T.gal.all : id === 'image' ? T.gal.images : id === 'video' ? T.gal.video : T.gal.audio}
+ {id === 'all' ? T.gal.all : id === 'image' ? T.gal.images : id === 'video' ? T.gal.video : id === '3d' ? T.gal.threeD : T.gal.audio}
</Chip>
))}
</ChipGroup>
diff --git a/src/mobile/screens/create/parts/ThreeDCards.tsx b/src/mobile/screens/create/parts/ThreeDCards.tsx
new file mode 100644
index 00000000..b9cd62e5
--- /dev/null
+++ b/src/mobile/screens/create/parts/ThreeDCards.tsx
@@ -0,0 +1,207 @@
+/**
+ * The cards of the 3D tool on the stage of K1 (3.1.0, cloud only): the way
+ * (Text, Image, Video), the further sides of a model that takes several, the
+ * still frames of a video, and the detail step.
+ */
+import { useEffect, useState } from 'react'
+import { Plus, Video as VideoIcon } from 'lucide-react'
+import { useCreateStore, type ThreeDWay } from '../../../../stores/createStore'
+import { pickFiles, pickPhotos } from '../../../platform/files'
+import { Button, Icon, Notice, Progress, Segmented, riskProps, toast } from '../../../ui'
+import { CREATE_STRINGS as T } from '../../../strings/create'
+import { fileProblemText } from './actions'
+import type { CreateFacts } from './facts'
+import { loadPhoneImage } from './photos'
+import { DETAILS, clearVideo, fitPicks, pickDetail, pickWay, readVideoFrames, shownDetail, tapFrame, useThreeDVideo } from './three-d'
+import { THREE_D_WAYS } from './tools'
+import { RemoveX } from './ui'
+
+const S = T.threeD
+
+/** The switch at the top of the tool: from words, from a photo, from a video. */
+export function ThreeDWaySwitch({ f, disabled }: { f: CreateFacts; disabled: boolean }) {
+ const maxViews = f.threeD?.maxViews ?? 1
+ return (
+ <div className="m-k-sec" data-testid="m-create-3d-way-row">
+ <Segmented<ThreeDWay>
+ label={S.wayLabel}
+ value={f.threeDWay}
+ onChange={(way) => pickWay(way, maxViews)}
+ options={THREE_D_WAYS.map((way) => ({ value: way, label: S.ways[way], disabled, testid: `m-create-3d-way-${way}` }))}
+ testid="m-create-3d-way"
+ />
+ </div>
+ )
+}
+
+/** Left, Back, Right for a model that takes several pictures. Front is the source photo. */
+export function ThreeDSidesCard({ f, disabled }: { f: CreateFacts; disabled: boolean }) {
+ const [busy, setBusy] = useState(false)
+ const maxViews = f.threeD?.maxViews ?? 1
+ if (!f.source || maxViews <= 1) return null
+ const sides = S.sides.slice(1, maxViews)
+ const views = f.threeDViews.slice(0, sides.length)
+ const next = sides[views.length]
+ const add = async () => {
+ const [picked] = await pickPhotos({ multiple: false })
+ if (!picked) return
+ setBusy(true)
+ try {
+ const ref = await loadPhoneImage(picked.file)
+ const st = useCreateStore.getState()
+ st.setThreeDViews([...st.threeDViews.slice(0, sides.length), ref].slice(0, sides.length))
+ } catch (err) {
+ toast(fileProblemText(err), { tone: 'error', testid: 'create-3d-side-failed' })
+ } finally {
+ setBusy(false)
+ }
+ }
+ const remove = (i: number) => {
+ const st = useCreateStore.getState()
+ st.setThreeDViews(st.threeDViews.filter((_, k) => k !== i))
+ }
+ return (
+ <div className="m-k-card" data-testid="m-create-3d-sides" data-state={`${views.length}`}>
+ <span className="m-k-card-text">
+ <span className="m-k-card-title">{S.moreSides}</span>
+ <span className="m-k-card-sub">{S.moreSidesSub}</span>
+ </span>
+ <div className="m-k-refs">
+ {views.map((ref, i) => (
+ <span className="m-k-ref" key={`${i}-${ref.url.length}`}>
+ <span className="m-k-thumb" title={sides[i]}>
+ <img src={ref.url} alt={sides[i]} />
+ </span>
+ {disabled ? null : <RemoveX label={S.removeSide(sides[i])} testid="m-create-3d-side-remove" onPress={() => remove(i)} />}
+ </span>
+ ))}
+ {next ? (
+ <button type="button" className="m-k-addtile" aria-label={S.addSide(next)} aria-busy={busy || undefined} disabled={disabled || busy} data-testid="m-create-3d-side-add" {...riskProps('sensor')} onClick={() => void add()}>
+ {busy ? <span className="m-ring" aria-hidden="true" /> : <Icon icon={Plus} />}
+ </button>
+ ) : null}
+ </div>
+ </div>
+ )
+}
+
+export type VideoPick = { status: 'cancelled' } | { status: 'ok' } | { status: 'failed'; message: string }
+
+/** Pick a video from Files and read its still frames. Shared by the card and the source sheet. */
+export async function pickVideoFor3d(maxViews: number): Promise<VideoPick> {
+ const [picked] = await pickFiles({ accept: 'video/*' })
+ if (!picked) return { status: 'cancelled' }
+ const out = await readVideoFrames(picked.file, maxViews)
+ if (out.ok) return { status: 'ok' }
+ return { status: 'failed', message: out.reason === 'wrong-kind' ? T.file.wrongKind.video : out.reason === 'empty' ? T.file.empty : S.videoFailed }
+}
+
+/** The video of "From video": the moments LU read from it, and which of them go. The video stays on the phone. */
+export function ThreeDVideoCard({ f, disabled }: { f: CreateFacts; disabled: boolean }) {
+ const video = useThreeDVideo()
+ const [problem, setProblem] = useState<string | null>(null)
+ const maxViews = f.threeD?.maxViews ?? 1
+ const want = Math.max(1, Math.min(4, maxViews))
+ useEffect(() => {
+ // Another model may take more or fewer pictures: the picks follow it.
+ fitPicks(maxViews)
+ }, [maxViews])
+ const pick = async () => {
+ setProblem(null)
+ const out = await pickVideoFor3d(maxViews)
+ if (out.status === 'failed') setProblem(out.message)
+ }
+ const problemNote = problem ? (
+ <Notice variant="error" testid="m-create-3d-video-error">
+ {problem}
+ </Notice>
+ ) : null
+
+ if (video.reading) {
+ return (
+ <div className="m-k-card" data-testid="m-create-3d-video" data-state="reading">
+ <Progress label={S.reading} detail={video.name ?? S.reading} />
+ </div>
+ )
+ }
+ if (!video.frames.length) {
+ return (
+ <div className="m-k-card m-k-card--add" data-testid="m-create-3d-video" data-state="empty">
+ <button type="button" className="m-k-addcard" disabled={disabled} data-testid="m-create-3d-video-add" {...riskProps('sensor')} onClick={() => void pick()}>
+ <span className="m-k-thumb" aria-hidden="true">
+ <Icon icon={VideoIcon} />
+ </span>
+ <span className="m-k-card-text">
+ <span className="m-sr">{`${S.addVideo}. `}</span>
+ <span className="m-k-card-title">{S.videoTitle}</span>
+ <span className="m-k-card-sub">{S.videoSub}</span>
+ </span>
+ <span className="m-k-addcard-go" aria-hidden="true">
+ <Icon icon={Plus} small />
+ </span>
+ </button>
+ {problemNote}
+ </div>
+ )
+ }
+ const line = want === 1 ? S.framesOne : want === 4 && video.frames.length >= 4 ? S.framesMany : S.framesSome(Math.min(want, video.frames.length))
+ return (
+ <div className="m-k-card" data-testid="m-create-3d-video" data-state="ready" data-m-picked={video.picked.join(',')}>
+ <span className="m-k-card-text">
+ <span className="m-k-card-title">{video.name ?? S.videoTitle}</span>
+ <span className="m-k-card-sub">{line}</span>
+ </span>
+ <div className="m-k-frames" role="group" aria-label={line} data-testid="m-create-3d-frames">
+ {video.frames.map((frame, i) => {
+ const order = video.picked.indexOf(i)
+ return (
+ <button
+ key={frame.url.slice(-24) + i}
+ type="button"
+ className="m-k-frame"
+ aria-pressed={order >= 0}
+ aria-label={S.frame(i + 1, video.frames.length)}
+ disabled={disabled}
+ data-testid="m-create-3d-frame"
+ data-m-id={String(i)}
+ onClick={() => tapFrame(i, maxViews)}
+ >
+ <img src={frame.url} alt="" />
+ {order >= 0 && want > 1 ? <span className="m-k-frame-no" aria-hidden="true">{order + 1}</span> : null}
+ </button>
+ )
+ })}
+ </div>
+ <span className="m-k-card-sub">{S.honest}</span>
+ {problemNote}
+ <div className="m-k-card-actions">
+ <Button icon={Plus} onPress={() => void pick()} disabled={disabled} risk="sensor" testid="m-create-3d-video-add">
+ {S.otherVideo}
+ </Button>
+ <Button variant="quiet" onPress={clearVideo} disabled={disabled} testid="m-create-3d-video-remove">
+ {T.motionVideoRemove}
+ </Button>
+ </div>
+ </div>
+ )
+}
+
+/** Draft, Standard, Fine, where the model has a step. It writes the model's own field. */
+export function ThreeDDetailCard({ f, disabled }: { f: CreateFacts; disabled: boolean }) {
+ const options = useCreateStore((s) => s.cloudStudioOptions)
+ const stored = useCreateStore((s) => s.threeDDetail)
+ if (!f.threeD?.hasDetail || !f.model.studio) return null
+ const value = shownDetail(f.model.id, options, stored)
+ return (
+ <div className="m-k-card" data-testid="m-create-3d-detail-card">
+ <span className="m-k-card-title">{S.detail}</span>
+ <Segmented
+ label={S.detail}
+ value={value}
+ onChange={(d) => pickDetail(f.model.id, d)}
+ options={DETAILS.map((d) => ({ value: d, label: S.details[d], disabled, testid: `m-create-3d-detail-${d}` }))}
+ testid="m-create-3d-detail"
+ />
+ </div>
+ )
+}
diff --git a/src/mobile/screens/create/parts/actions.ts b/src/mobile/screens/create/parts/actions.ts
index 1249d87b..ce89f2f7 100644
--- a/src/mobile/screens/create/parts/actions.ts
+++ b/src/mobile/screens/create/parts/actions.ts
@@ -19,7 +19,7 @@ import { applyStyleText, type PromptStyle } from './styles'
import { aspectSize } from './params'
import { nav } from '../../../nav'
import { imageBaseLong } from './catalog'
-import { toolFacts, toolNeedsMask, type ToolId } from './tools'
+import { toolFacts, toolNeedsMask, toolTakesPhoto, type ToolId } from './tools'
import type { PickPurpose } from './pick'
const store = () => useCreateStore.getState()
@@ -51,8 +51,10 @@ export function fileProblemText(err: unknown, kind: MediaKind = 'image'): string
/** Make `ref` the source image. A tool without a source becomes Edit. */
export function takeImageAsSource(ref: ImageRef, tool?: ToolId): void {
const st = store()
- const want = tool ?? (toolFacts(st.intent()).needsSource || st.intent() === 'lipsync' || st.intent() === 'motion' ? st.intent() : 'edit')
+ const want = tool ?? (toolTakesPhoto(st.intent()) ? st.intent() : 'edit')
if (st.intent() !== want) st.setIntent(want)
+ // 3D: a photo is the way "From image". Words and a video have no photo of their own.
+ if (want === '3d' && store().threeDWay !== 'image') store().setThreeDWay('image')
const now = store()
if (now.batchSources.length) now.setBatchSources([])
now.setMask(null)
@@ -69,7 +71,7 @@ export async function addSourceFiles(files: readonly File[]): Promise<AddResult>
if (files.length === 0) return { ok: false, message: '' }
const st = store()
const intent = st.intent()
- const target: ToolId = toolFacts(intent).needsSource || intent === 'lipsync' || intent === 'motion' ? intent : 'edit'
+ const target: ToolId = toolTakesPhoto(intent) ? intent : 'edit'
const usable = files.filter((f) => checkFile(f, 'image') === null)
const skipped = files.length - usable.length
if (usable.length === 0) {
diff --git a/src/mobile/screens/create/parts/catalog.ts b/src/mobile/screens/create/parts/catalog.ts
index e8fe536d..159ae7fd 100644
--- a/src/mobile/screens/create/parts/catalog.ts
+++ b/src/mobile/screens/create/parts/catalog.ts
@@ -5,7 +5,7 @@
* the logic layer. The screens ask it three things: which tools can run,
* which models a tool has, and what the picked model is.
*/
-import { useCreateStore, MODEL_TYPE_DEFAULTS, type CharacterRef } from '../../../../stores/createStore'
+import { useCreateStore, MODEL_TYPE_DEFAULTS, type CharacterRef, type ThreeDWay } from '../../../../stores/createStore'
import {
useCloudCatalogStore,
animatePickerModels,
@@ -20,7 +20,7 @@ import {
videoPickerModels,
} from '../../../../stores/cloudCatalogStore'
import type { CloudModel } from '../../../../lib/render/cloud-models'
-import { createRunModel, createStudioCost, intentPickerModels, intentRoles, isStudioModel } from '../../../../lib/render/create-studio'
+import { createRunModel, createStudioCost, intentPickerModels, intentRoles, isStudioModel, studioIntentOf } from '../../../../lib/render/create-studio'
import { groupForPicker, tierMarks } from '../../../../lib/render/model-tier'
import { modelLabel } from '../../../../lib/render/preset-models'
import { effectiveVideoDurations } from '../../../../lib/render/video-duration'
@@ -63,6 +63,8 @@ export function toolProbe(): ToolProbe {
music: intentPickerModels('music').length > 0,
extend: intentPickerModels('extend').length > 0,
motion: intentPickerModels('motion').length > 0,
+ // The tab is there as soon as the catalog lists one 3D model, whatever its way.
+ '3d': intentPickerModels('3d').length > 0,
}
}
@@ -105,18 +107,20 @@ function rowCredits(id: string, tool: ToolId, musicSeconds: number, fallback: nu
}
/** The models of a tool, grouped and marked the way the desktop picker does it. */
-export function toolModels(tool: ToolId, opts: { character: CharacterRef | null; characterUse: boolean; musicSeconds: number; fallbackCredits: Record<'image' | 'video' | 'audio', number | null> }): ModelRow[] {
- const facts = toolFacts(tool)
+export function toolModels(tool: ToolId, opts: { character: CharacterRef | null; characterUse: boolean; musicSeconds: number; fallbackCredits: Record<'image' | 'video' | 'audio', number | null>; threeDWay?: ThreeDWay }): ModelRow[] {
+ const facts = toolFacts(tool, opts.threeDWay)
if (!facts.hasModels) return []
+ // 3D lists the models of its way: words, one photo, or the frames of a video.
+ const pickIntent = studioIntentOf(tool, opts.threeDWay)
let list: Listable[]
if (tool === 'character') {
list = opts.characterUse ? characterGenerationModels(opts.character?.family ?? '') : opPickerModels('lora-train')
- } else if (intentRoles(tool).length > 0) list = intentPickerModels(tool)
+ } else if (intentRoles(pickIntent).length > 0) list = intentPickerModels(pickIntent)
else if (tool === 'edit') list = editCapableModels()
else if (tool === 'animate') list = animatePickerModels()
else if (tool === 'video') list = videoPickerModels()
else list = imageModels()
- const fallback = opts.fallbackCredits[facts.kind]
+ const fallback = facts.kind === '3d' ? null : opts.fallbackCredits[facts.kind]
return groupForPicker(list).map(({ model, group }) => ({
id: model.id,
// The name and the head of the group as this build may show them: a store build writes no word it may not show.
@@ -161,10 +165,10 @@ export interface RunModel {
type Picks = { cloudImageModel: string; cloudVideoModel: string; cloudOpModel: string }
-/** The model a run of `tool` uses with the current picks. */
-export function runModel(tool: ToolId, picks: Picks, character: CharacterRef | null, characterUse: boolean): RunModel {
+/** The model a run of `tool` uses with the current picks. 3D runs the model of its way. */
+export function runModel(tool: ToolId, picks: Picks, character: CharacterRef | null, characterUse: boolean, threeDWay?: ThreeDWay): RunModel {
const id = createRunModel(
- tool,
+ studioIntentOf(tool, threeDWay),
{ image: picks.cloudImageModel, video: picks.cloudVideoModel, op: picks.cloudOpModel },
characterUse ? character?.family ?? '' : undefined,
)
diff --git a/src/mobile/screens/create/parts/create.css b/src/mobile/screens/create/parts/create.css
index 4338cc72..e68bf0ae 100644
--- a/src/mobile/screens/create/parts/create.css
+++ b/src/mobile/screens/create/parts/create.css
@@ -1234,3 +1234,53 @@
position: relative;
background: transparent;
}
+
+/* ---------- 3D (3.1.0) ---------- */
+/* The 3D view needs a height of its own: a canvas has none. */
+.m-app .m-k-media--3d {
+ height: min(56vh, 420px);
+ display: flex;
+}
+.m-app .m-k-viewer-3d {
+ width: 100%;
+ height: 100%;
+ display: flex;
+}
+.m-k-frames {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: var(--m-s2);
+}
+.m-app .m-k-frame {
+ position: relative;
+ aspect-ratio: 1 / 1;
+ min-height: 44px;
+ border-radius: var(--m-r-md);
+ overflow: hidden;
+ background: var(--m-fill);
+ border: 2px solid transparent;
+ padding: 0;
+}
+.m-app .m-k-frame[aria-pressed='true'] {
+ border-color: var(--m-accent);
+}
+.m-k-frame img {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.m-k-frame-no {
+ position: absolute;
+ right: 3px;
+ bottom: 3px;
+ min-width: 18px;
+ padding: 0 4px;
+ border-radius: 9px;
+ background: var(--m-accent);
+ color: var(--m-on-accent);
+ font-size: var(--m-text-label);
+ line-height: 18px;
+ text-align: center;
+}
diff --git a/src/mobile/screens/create/parts/facts.ts b/src/mobile/screens/create/parts/facts.ts
index 2bc23286..8869ba11 100644
--- a/src/mobile/screens/create/parts/facts.ts
+++ b/src/mobile/screens/create/parts/facts.ts
@@ -8,12 +8,12 @@
* so two open screens never ask the server twice.
*/
import { create } from 'zustand'
-import { useCreateStore, imageQualityLadder, type CharacterRef, type ImageRef, type MediaRef } from '../../../../stores/createStore'
+import { useCreateStore, imageQualityLadder, type CharacterRef, type ImageRef, type MediaRef, type ThreeDWay } from '../../../../stores/createStore'
import { useCloudAuthStore, deriveCloudAvailable } from '../../../../stores/cloudAuthStore'
import { useCloudCatalogStore, lengthPrice, runCredits } from '../../../../stores/cloudCatalogStore'
import { useSettingsStore } from '../../../../stores/settingsStore'
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 { createStudioCost, intentRequiredInputs, startImageCount, studioExtraPhotoSlots, studioIntentOf } from '../../../../lib/render/create-studio'
import { STUDIO_MODELS, studioFields } from '../../../../lib/render/studio-contract'
import { runImageCount } from '../../../../lib/render/image-count'
import { meterState, type MeterState } from '../../../../lib/render/credits-meter'
@@ -26,6 +26,7 @@ import { lengthUnit } from './length-price'
import { aspectKey, qualityKey, runParams, summaryParts, type AspectKey, type QualityKey, type RunParams } from './params'
import { blockReason, walletVerdict, type BlockReason, type WalletVerdict } from './run-state'
import { toolFacts, toolNeedsMask, type ToolFacts, type ToolId } from './tools'
+import { threeDModelFacts, type ThreeDModelFacts } from './three-d'
// ---------- the confirmed price, shared ----------
@@ -127,6 +128,11 @@ export interface CreateFacts {
videoInput: MediaRef | null
audioInput: MediaRef | null
online: boolean
+ /** 3D: the way of the tool, and what its model takes. Null for every other tool. */
+ threeDWay: ThreeDWay
+ threeD: ThreeDModelFacts | null
+ /** 3D: the further sides after the Front (or the further still frames). */
+ threeDViews: ImageRef[]
}
export function useCreateFacts(): CreateFacts {
@@ -163,11 +169,14 @@ export function useCreateFacts(): CreateFacts {
const voiceFromJob = useCreateStore((s) => s.voiceFromJob)
const videoInput = useCreateStore((s) => s.videoInput)
const extendSource = useCreateStore((s) => s.extendSource)
+ const threeDWay = useCreateStore((s) => s.threeDWay)
+ const threeDViews = useCreateStore((s) => s.threeDViews)
const price = usePriceStore()
- const facts = toolFacts(tool)
+ const facts = toolFacts(tool, threeDWay)
const characterUse = tool === 'character' && characterTab === 'use'
- const model = runModel(tool, { cloudImageModel, cloudVideoModel, cloudOpModel }, character, characterUse)
+ const model = runModel(tool, { cloudImageModel, cloudVideoModel, cloudOpModel }, character, characterUse, threeDWay)
+ const threeD = tool === '3d' ? threeDModelFacts(model.studio ? model.id : undefined) : null
let { kind, op } = intentToJob(tool)
if (characterUse) {
kind = 'image'
@@ -198,7 +207,7 @@ export function useCreateFacts(): CreateFacts {
// The price of one run, by the same rule the cloud hook books with.
const runSeconds = op === 'music' ? musicDuration : kind === 'video' && !model.studio && seconds !== null ? seconds : undefined
- const extraPhotos = tool === 'edit' || tool === 'animate' ? references.length : 0
+ const extraPhotos = tool === 'edit' || tool === 'animate' ? references.length : tool === '3d' && threeD ? Math.min(threeDViews.length, threeD.maxViews - 1) : 0
let unit: number | null = null
let priceState: CreateFacts['priceState'] = 'known'
if (model.studio) {
@@ -234,7 +243,7 @@ export function useCreateFacts(): CreateFacts {
const needsMask = toolNeedsMask(tool, model.maskless)
const promptShown = facts.prompt !== 'no' && (tool !== 'character' || characterUse)
const promptNeeded = promptShown && facts.prompt === 'yes'
- const studioNeeds = model.studio ? intentRequiredInputs(tool, model.id) : []
+ const studioNeeds = model.studio ? intentRequiredInputs(studioIntentOf(tool, threeDWay), model.id) : []
const needsClip = tool === 'lipsync' && (model.studio ? studioNeeds.includes('video_path') : model.lipsyncFromClip)
const needsPortrait = tool === 'lipsync' && !needsClip && (model.studio ? studioNeeds.includes('source_path') : true)
@@ -256,6 +265,7 @@ export function useCreateFacts(): CreateFacts {
needsClip,
hasVideo: !!videoInput,
hasExtendClip: !!extendSource,
+ threeDWay,
hasModel: !facts.hasModels || !!model.id,
priceState,
quotaKnown: quota !== null,
@@ -267,5 +277,6 @@ export function useCreateFacts(): CreateFacts {
source, mask, references,
referenceSlots: model.studio && (tool === 'edit' || tool === 'animate') ? studioExtraPhotoSlots(model.id) : 0,
needsPortrait, needsClip, videoInput, audioInput, online,
+ threeDWay, threeD, threeDViews,
}
}
diff --git a/src/mobile/screens/create/parts/run-state.ts b/src/mobile/screens/create/parts/run-state.ts
index 29b44737..608601be 100644
--- a/src/mobile/screens/create/parts/run-state.ts
+++ b/src/mobile/screens/create/parts/run-state.ts
@@ -137,6 +137,8 @@ export type BlockReason =
| 'no-portrait'
| 'no-clip'
| 'no-motion-video'
+ /** 3D from a video: no video read yet. */
+ | 'no-3d-video'
| 'no-model'
| 'price-unavailable'
| 'price-measuring'
@@ -163,6 +165,8 @@ export interface ReadyInput {
hasVideo: boolean
/** Extend. */
hasExtendClip: boolean
+ /** 3D: the way of the tool. Its source is a still frame on the video way. */
+ threeDWay?: 'text' | 'image' | 'video'
hasModel: boolean
/** A model whose price the server confirms. */
/** pending only changes the label, the server confirms again at the start. */
@@ -189,6 +193,7 @@ export function blockReason(i: ReadyInput): BlockReason | null {
if (!i.hasSource) return 'no-portrait'
if (!i.hasVideo) return 'no-motion-video'
}
+ if (i.tool === '3d' && i.threeDWay === 'video' && !i.hasSource) return 'no-3d-video'
if (i.sourceNeeded && !i.hasSource) return 'no-source'
if (i.maskNeeded && !i.hasMask) return 'no-mask'
if (i.promptNeeded && i.prompt.trim().length === 0) return 'no-prompt'
diff --git a/src/mobile/screens/create/parts/three-d.ts b/src/mobile/screens/create/parts/three-d.ts
new file mode 100644
index 00000000..3644bee2
--- /dev/null
+++ b/src/mobile/screens/create/parts/three-d.ts
@@ -0,0 +1,157 @@
+/**
+ * 3D on the phone (3.1.0, cloud only). What the picked model takes, the
+ * detail step, and the still frames of a video.
+ *
+ * The video never leaves the phone. LU reads still frames of it here; the
+ * picked moments in order become the source (the "Front") and the further
+ * sides of the create store, and from there "From video" runs exactly like
+ * "From image". Built after the desktop row (ThreeDControls.tsx), not taken
+ * from it.
+ */
+import { create } from 'zustand'
+import { useCreateStore, type ImageRef, type ThreeDDetail, type ThreeDWay } from '../../../../stores/createStore'
+import { cloudDetailOf, threeDControlFacts, threeDDetailField } from '../../../../lib/three/three-d-models'
+import { framesAcrossVideo } from '../../../../lib/video-frames'
+import { checkFileAgainst } from '../../../../lib/media-file'
+import { loadPhoneImageFromBlob } from './photos'
+
+/** How many moments of a video are offered to pick from. */
+export const FRAME_CHOICES = 8
+
+export const DETAILS: readonly ThreeDDetail[] = ['draft', 'standard', 'fine']
+
+export interface ThreeDModelFacts {
+ /** How many pictures the model takes: 1, or up to 4 sides. */
+ maxViews: number
+ /** The model has a detail step. */
+ hasDetail: boolean
+}
+
+/** What the cloud model `studioId` takes. A model the registry does not know takes one picture and no step. */
+export function threeDModelFacts(studioId: string | undefined): ThreeDModelFacts {
+ const f = threeDControlFacts('cloud', studioId)
+ return { maxViews: f.maxViews, hasDetail: f.hasDetail }
+}
+
+/** `want` indices spread evenly over `n` frames: 0, 2, 4, 5 of eight. Same rule as the desktop. */
+export function evenPick(n: number, want: number): number[] {
+ if (n <= 0) return []
+ const k = Math.min(want, n)
+ if (k === 1) return [Math.floor((n - 1) / 2)]
+ return Array.from({ length: k }, (_, i) => Math.round((i * (n - 1)) / k))
+}
+
+/**
+ * A tap on moment `i`. One picture: it becomes the one. Several: a picked
+ * moment goes (never the last one), a new one comes in and pushes out the
+ * oldest when the strip is full. Always in the order of the video.
+ */
+export function togglePick(picked: readonly number[], i: number, want: number): number[] {
+ if (want <= 1) return [i]
+ if (picked.includes(i)) return picked.length > 1 ? picked.filter((k) => k !== i) : [...picked]
+ return (picked.length >= want ? [...picked.slice(1), i] : [...picked, i]).sort((a, b) => a - b)
+}
+
+/** The step a cloud model stands on now. */
+export function shownDetail(studioId: string | undefined, options: Record<string, unknown>, stored: ThreeDDetail): ThreeDDetail {
+ const field = threeDDetailField(studioId)
+ return field ? cloudDetailOf(field, options[field.field], studioId) : stored
+}
+
+/** Pick a step: in the cloud the step is the model's own field, written where the price and the booking read it. */
+export function pickDetail(studioId: string | undefined, d: ThreeDDetail): void {
+ const st = useCreateStore.getState()
+ st.setThreeDDetail(d)
+ const field = threeDDetailField(studioId)
+ if (field) st.setCloudStudioOptions({ ...st.cloudStudioOptions, [field.field]: field.values[d] })
+}
+
+/** Switch the way. A video read before comes back with its picks. */
+export function pickWay(way: ThreeDWay, maxViews: number): void {
+ const st = useCreateStore.getState()
+ if (st.threeDWay === way) return
+ st.setThreeDWay(way)
+ if (way === 'video' && useThreeDVideo.getState().frames.length > 0) applyPicks(maxViews)
+}
+
+// ---------- the video ----------
+
+export interface ThreeDVideo {
+ /** File name of the video, null before one was picked. */
+ name: string | null
+ frames: ImageRef[]
+ picked: number[]
+ reading: boolean
+}
+
+const EMPTY: ThreeDVideo = { name: null, frames: [], picked: [], reading: false }
+
+export const useThreeDVideo = create<ThreeDVideo>()(() => ({ ...EMPTY }))
+
+/** Write the picked moments to the create store: the first is the source, the others the further sides. */
+export function applyPicks(maxViews: number): void {
+ const { frames, picked } = useThreeDVideo.getState()
+ if (!frames.length) return
+ const want = Math.max(1, Math.min(4, maxViews))
+ const chosen = picked.map((i) => frames[i]).filter((f): f is ImageRef => !!f).slice(0, want)
+ const st = useCreateStore.getState()
+ st.setSource(chosen[0] ?? null)
+ st.setThreeDViews(chosen.slice(1))
+}
+
+/** The user tapped moment `i`. */
+export function tapFrame(i: number, maxViews: number): void {
+ const want = Math.max(1, Math.min(4, maxViews))
+ useThreeDVideo.setState((s) => ({ picked: togglePick(s.picked, i, want) }))
+ applyPicks(maxViews)
+}
+
+/** The picked model changed: it may take more or fewer pictures now. */
+export function fitPicks(maxViews: number): void {
+ const { frames, picked } = useThreeDVideo.getState()
+ if (!frames.length) return
+ const want = Math.max(1, Math.min(4, maxViews))
+ if (picked.length !== Math.min(want, frames.length)) useThreeDVideo.setState({ picked: evenPick(frames.length, want) })
+ applyPicks(maxViews)
+}
+
+/** Forget the video and its frames. */
+export function clearVideo(): void {
+ useThreeDVideo.setState({ ...EMPTY })
+ const st = useCreateStore.getState()
+ st.setSource(null)
+ st.setThreeDViews([])
+}
+
+export type ReadVideoResult = { ok: true } | { ok: false; reason: 'empty' | 'wrong-kind' | 'unreadable' }
+
+/**
+ * Read still frames of `file`. The bytes stay in this phone's memory: an
+ * address of its own is made for the reading and dropped right after. No
+ * upload limit applies, because the video itself is never uploaded.
+ */
+export async function readVideoFrames(file: File, maxViews: number): Promise<ReadVideoResult> {
+ const bad = checkFileAgainst(file, 'video', Number.POSITIVE_INFINITY)
+ if (bad) return { ok: false, reason: bad.kind === 'empty' ? 'empty' : bad.kind === 'wrong-kind' ? 'wrong-kind' : 'unreadable' }
+ const st = useCreateStore.getState()
+ if (st.intent() !== '3d') st.setIntent('3d')
+ if (useCreateStore.getState().threeDWay !== 'video') useCreateStore.getState().setThreeDWay('video')
+ useThreeDVideo.setState({ reading: true, name: file.name })
+ const url = URL.createObjectURL(file)
+ try {
+ const blobs = await framesAcrossVideo(url, FRAME_CHOICES)
+ const base = file.name.replace(/\.[^.]+$/, '') || 'video'
+ const frames: ImageRef[] = []
+ for (const [i, b] of blobs.entries()) frames.push(await loadPhoneImageFromBlob(b, `${base}-frame-${i + 1}.jpg`))
+ if (!frames.length) throw new Error('no frames')
+ const want = Math.max(1, Math.min(4, maxViews))
+ useThreeDVideo.setState({ frames, picked: evenPick(frames.length, want), reading: false })
+ applyPicks(maxViews)
+ return { ok: true }
+ } catch {
+ useThreeDVideo.setState({ ...EMPTY })
+ return { ok: false, reason: 'unreadable' }
+ } finally {
+ URL.revokeObjectURL(url)
+ }
+}
diff --git a/src/mobile/screens/create/parts/tools.ts b/src/mobile/screens/create/parts/tools.ts
index 3611dece..5fa8042c 100644
--- a/src/mobile/screens/create/parts/tools.ts
+++ b/src/mobile/screens/create/parts/tools.ts
@@ -5,14 +5,14 @@
* image, a prompt, a painted area) is written down here once, so the page,
* the sheets and the tests read the same table.
*/
-import type { CreateIntent } from '../../../../stores/createStore'
+import type { CreateIntent, ThreeDWay } from '../../../../stores/createStore'
export type ToolId = CreateIntent
export interface ToolFacts {
id: ToolId
/** What the result is. */
- kind: 'image' | 'video' | 'audio'
+ kind: 'image' | 'video' | 'audio' | '3d'
/** The tool starts from an image the user brings. */
needsSource: boolean
/** yes: a prompt is required. optional: it may stay empty. no: there is no prompt field. */
@@ -40,8 +40,13 @@ export const TOOLS: readonly ToolFacts[] = [
{ id: 'music', kind: 'audio', needsSource: false, prompt: 'yes', mask: 'none', batch: false, styles: false, hasModels: true },
{ id: 'extend', kind: 'video', needsSource: false, prompt: 'yes', mask: 'none', batch: false, styles: false, hasModels: true },
{ id: 'motion', kind: 'video', needsSource: false, prompt: 'optional', mask: 'none', batch: false, styles: false, hasModels: true },
+ // 3D (3.1.0): last in the row, so no tool moves. Source and prompt follow the way (toolFacts).
+ { id: '3d', kind: '3d', needsSource: false, prompt: 'yes', mask: 'none', batch: false, styles: false, hasModels: true },
]
+/** The three ways of the 3D tool, in the order of its switch. */
+export const THREE_D_WAYS: readonly ThreeDWay[] = ['text', 'image', 'video']
+
export const TOOL_IDS: readonly ToolId[] = TOOLS.map((t) => t.id)
/**
@@ -58,8 +63,21 @@ export function toolChoiceRisk(id: ToolId): 'paid' | undefined {
return MARKED_TOOL_CHOICES.includes(id) ? 'paid' : undefined
}
-export function toolFacts(id: ToolId): ToolFacts {
- return TOOLS.find((t) => t.id === id) ?? TOOLS[0]
+/**
+ * The facts of a tool. 3D reads its way: from words it wants a prompt and no
+ * picture, from a photo or a video it wants a picture (a still frame of the
+ * video stands there) and no prompt.
+ */
+export function toolFacts(id: ToolId, threeDWay: ThreeDWay = 'image'): ToolFacts {
+ const facts = TOOLS.find((t) => t.id === id) ?? TOOLS[0]
+ if (facts.id !== '3d') return facts
+ const words = threeDWay === 'text'
+ return { ...facts, needsSource: !words, prompt: words ? 'yes' : 'no' }
+}
+
+/** Whether a photo the user adds stays with this tool. Every other tool hands it to Edit. */
+export function toolTakesPhoto(id: ToolId): boolean {
+ return id === '3d' || id === 'lipsync' || id === 'motion' || toolFacts(id).needsSource
}
/** Which tools the catalog can run right now. A missing answer counts as no. */
diff --git a/src/mobile/screens/create/parts/ui.tsx b/src/mobile/screens/create/parts/ui.tsx
index e305fb8f..e1752f8e 100644
--- a/src/mobile/screens/create/parts/ui.tsx
+++ b/src/mobile/screens/create/parts/ui.tsx
@@ -13,6 +13,7 @@ import {
} from 'lucide-react'
import { useCreateStore, type GalleryItem } from '../../../../stores/createStore'
import { galleryLabelShort } from '../../../../lib/render/gallery-label'
+import { LazyModelViewer } from '../../../../components/three/LazyModelViewer'
import { nav, useSheet } from '../../../nav'
import { Icon, type IconType } from '../../../ui'
import { useHeldScreenShape } from '../../../ui/screen-shape'
@@ -216,6 +217,14 @@ export function ResultMediaView({ item, openTestid, el }: { item: GalleryItem; o
</div>
)
}
+ if (item.type === '3d') {
+ // The 3D view turns right here. Its full screen is the result view (K7).
+ return (
+ <div className="m-k-media m-k-media--3d" data-testid="m-create-result-3d" data-el={el} aria-label={T.threeD.viewer}>
+ <LazyModelViewer item={item} touch onFullscreen={open} />
+ </div>
+ )
+ }
return (
<div className="m-k-media">
<audio src={media.url} controls preload="metadata" aria-label={itemName(item, 80)} onError={media.onError} />
diff --git a/src/mobile/strings/create.ts b/src/mobile/strings/create.ts
index ff198549..ab848b04 100644
--- a/src/mobile/strings/create.ts
+++ b/src/mobile/strings/create.ts
@@ -7,6 +7,7 @@
import type { CreateIntent } from '../../stores/createStore'
import { MIN_TRAIN_IMAGES, maxTrainImages } from '../../lib/train-image-cap'
import { UNFILTERED_MARK_LABEL } from '../../lib/unfiltered-mark'
+import { THREE_D_TEXT } from '../../lib/three/three-d-text'
import { priced } from '../policy/gates'
import { POLICY } from './policy'
@@ -244,6 +245,7 @@ export const CREATE_STRINGS = {
'no-portrait': 'Add a portrait first',
'no-clip': 'Pick a clip first',
'no-motion-video': 'Add a motion video first',
+ 'no-3d-video': 'Add a short video first',
'no-model': 'No model is available for this tool',
get 'price-unavailable'() {
return priced('Price could not be confirmed', 'Credits could not be confirmed')
@@ -503,6 +505,8 @@ export const CREATE_STRINGS = {
savedDeleteTitle: (name: string) => `Delete ${name}?`,
savedDeleteText: 'Its photos are removed from this phone.',
switchesToEdit: 'Adding a photo switches to Edit.',
+ video: 'Video',
+ videoSub: 'LU takes still frames. The video stays on this phone.',
batchStarted: (n: number) => `${n} images added to the batch`,
batchLeftOut: (n: number) => `Only the first ${n} were added. A batch takes up to 50 images.`,
},
@@ -517,6 +521,7 @@ export const CREATE_STRINGS = {
images: 'Images',
video: 'Video',
audio: 'Audio',
+ threeD: '3D',
select: 'Select',
done: 'Done',
selected: (n: number) => `${n} selected`,
@@ -957,6 +962,33 @@ export const CREATE_STRINGS = {
},
// ---------- store rules: report, consent, buying ----------
+ // ---------- 3D (3.1.0) ----------
+ threeD: {
+ wayLabel: 'How to make the model',
+ ways: THREE_D_TEXT.waysShort,
+ sourceTitle: 'Photo of one object',
+ sourceSub: 'One thing, fully in frame. A plain background works best.',
+ moreSides: THREE_D_TEXT.moreSides,
+ moreSidesSub: THREE_D_TEXT.moreSidesSub,
+ sides: THREE_D_TEXT.sides,
+ addSide: (side: string) => `Add the ${side.toLowerCase()} side`,
+ removeSide: (side: string) => `Remove the ${side.toLowerCase()} side`,
+ videoTitle: 'Video of one object',
+ videoSub: THREE_D_TEXT.dropVideoSub,
+ addVideo: 'Add a video',
+ otherVideo: 'Another video',
+ reading: THREE_D_TEXT.framesReading,
+ framesMany: THREE_D_TEXT.framesMany,
+ framesOne: THREE_D_TEXT.framesOne,
+ framesSome: (n: number) => `LU picked ${n} moments from your video. Swap any of them.`,
+ frame: (i: number, n: number) => `Moment ${i} of ${n}`,
+ honest: THREE_D_TEXT.videoHonest,
+ videoFailed: 'LU could not read this video. Try another one.',
+ detail: THREE_D_TEXT.detail,
+ details: THREE_D_TEXT.details,
+ viewer: 'Your 3D model',
+ },
+
policy: {
report: 'Report',
reportLabel: (name: string) => `Report ${name}`,