diff --git a/.docs/wiki/Studios.md b/.docs/wiki/Studios.md index 515a65c..fd0887a 100644 --- a/.docs/wiki/Studios.md +++ b/.docs/wiki/Studios.md @@ -29,7 +29,7 @@ Boards of pictures, videos, notes, colours and links in a fast grid with section ## Tools -Tools are single-purpose pages in the studio switcher: Angles (an orbit sphere for camera angles), Remove background, Remove region (paint a mask on an image or a video frame), Frame extractor, Background change (swap a video's background from a reference picture), Storyboard and Mesh tools (split, segment, clean and remesh a model). FBX files convert to GLB on upload. GLB, glTF and FBX open and can be placed in a scene. OBJ, STL, USDZ and DAE are stored in the library but cannot be previewed or placed yet. +Tools are single-purpose pages in the studio switcher: Angles (an orbit sphere for camera angles), Remove background, Remove region (paint a mask on an image or a video frame), Frame extractor, Background change (swap a video's background from a reference picture), Storyboard and Mesh tools (split, segment, clean and remesh a model). FBX files convert to GLB on upload. GLB, glTF, FBX, OBJ and STL open and can be placed in a scene. OBJ and STL are converted to GLB in the window and show in neutral grey, because the library keeps no material file beside them. USDZ and DAE are stored in the library but cannot be previewed or placed yet. ## Library diff --git a/CHANGELOG.md b/CHANGELOG.md index 997cc05..c314102 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,23 @@ Versions follow `v*.*.*` with dots. Dates are UTC. +## 0.9.4 · 2026-11-28 + +### Changed + +- OBJ and STL files open in the 3D viewer, show a preview and a cover, and can be placed in a scene. They are converted to GLB in the window, as FBX files are, and show in neutral grey, because the library keeps no material file beside them. Mesh tools preview them too. USDZ and DAE are still stored only. + +### Fixed + +- A private file restored from its backup copy is readable by you alone from the moment it is opened, as a newly written one already was. +- The library picker shows the "stored, cannot be previewed yet" note for 3D formats the viewer cannot show, as the library and the upload dialog do. + +### Checked + +- Type check, production build, 1186 frontend tests, 478 engine tests, the engine self-check, the version check, the skills check and the agents check pass on Linux. A small OBJ and a small STL were converted through the built app in a headless browser. +- Two assertions in the viewer's format test that said OBJ is unknown and cannot be previewed now expect the opposite. No test was added. +- Not run: the installer, the engine freeze, the desktop build, and a generation against a provider. + ## 0.9.3 · 2026-11-28 ### Changed diff --git a/LICENSES.md b/LICENSES.md index d543c30..bdde3df 100644 --- a/LICENSES.md +++ b/LICENSES.md @@ -1,6 +1,6 @@ # Third-party licences · formcraft -Version v0.9.3 · 2026-11-28 +Version v0.9.4 · 2026-11-28 formcraft is licensed under the Apache License, Version 2.0 (see `LICENSE`), Copyright 2026 NodeAgentc, Inc. This file lists every third-party item that ships with formcraft or is used to build it, with its version, licence, where it ships and what the licence asks of us. `NOTICE` carries the short list of obligations that travel with the app and points here. diff --git a/README.md b/README.md index 71326e6..39db627 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version v0.9.3 + version v0.9.4 TypeScript, Vite and Three.js Python and FastAPI macOS, Windows and Linux @@ -77,7 +77,7 @@

122 catalogued models

32 image · 43 video · 12 audio · 17 mesh · 5 world · 13 utility · each field, limit and price read from the provider

Studios and tools

Create · Canvas · Scene · Board · Edit · Angles · Remove background · Remove region · Frame extractor · Background change · Storyboard · Mesh tools -

Formats

Opens: PNG · JPEG · WEBP · GIF · MP4 · MOV · WEBM · MP3 · WAV · GLB · glTF · FBX · SPLAT · Native: .fcrft. OBJ, STL, USDZ and DAE are stored in the library but cannot be previewed or placed yet. Exports: MP4 · WebM · PNG · .fcrft; no GIF, image sequence or mesh export yet. +

Formats

Opens: PNG · JPEG · WEBP · GIF · MP4 · MOV · WEBM · MP3 · WAV · GLB · glTF · FBX · OBJ · STL · SPLAT · Native: .fcrft. GLB, glTF, FBX, OBJ and STL open and can be placed; OBJ and STL are converted to GLB in the window and show in neutral grey, because the library keeps no material file beside them. USDZ and DAE are stored in the library but cannot be previewed or placed yet. Exports: MP4 · WebM · PNG · .fcrft; no GIF, image sequence or mesh export yet. diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index a864c14..70b4453 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of comment content, explainers, rationale, TODOs and removed code for the engine side of the repo. Source files stay comment-free per the owner's hashout-log rule; what they would have said lives here, indexed. Read this first, then edit code surgically. -Current build version: v0.9.3 +Current build version: v0.9.4 Last updated: 2026-11-02 · v0.8.0 engine MCP (dual-era protocol, 44 tools, consent, token, bridge, engine.port, the stdio launcher and mcp mode), the export preview, and the D1 fixes (bridge disconnects and bye, approval keys, withdrawals, root checks before asking, frozen launcher). Before that, B3 v0.7.0 engine (kind edit, /api/edit capability and export sessions with a POST cancel alias, GET /api/media/{id}/probe, /api/sounds with an original synthesised set) and its F2 fix. Before that, A1 v0.6.0 catalogue (Meshy rigging and character models, pages rig and character); W1 v0.6.0 engine (a finished world keeps all its assets and `meta.world`, POST /api/media/{id}/world/complete, the starter pack routes and install job). Before that, 2026-11-01 · E1 v0.5.0 engine (canvas and board project kinds, POST /api/media/mask-video, GET /api/media/{id}/frame). Before that, F5 v0.4.0 fixes (ASCII FBX stored as a 3D model with a start-up correction of earlier items, the FBX original found from its GLB in both link directions, a visible import unhides an identical hidden item). Before that, S5 v0.4.0 engine for the Scene studio: scene projects (kind `scene`, cover upload, role and meta carried in `.fcrft`), media migration 4 (`role`, `meta`), the H.264 encoder probe and the engine encode sessions, library 3D items as mesh-tool inputs in the planner. Before that, F2 v0.3.0 fixes (the mask edit colour in the catalogue, hidden media import, a private copy of a character's image, the sog extension). Before that, v0.3.0 library and projects engine: folders, tags, favourite and hidden flags, covers for 3D objects and worlds, characters with an avatar job, prompt history read from the jobs, the .fcrft project store with its hardened reader (schema 3), the mesh-tools page key, and a window policy that lets the 3D viewers run. Before that (v0.2.0), generation: provider clients for fal and World Labs with a key check, the model catalogue and the planner (request to provider call and price), POST /api/generate with the gen.* job runners, and job lanes so long generation jobs cannot block imports and downloads. Before that (v0.1.0), E1 (Phase 3 gaps): `askLocation` setting, save-dialog downloads (`path`, `overwrite`), batch download (inline or as a `download` job), auto-download on job success, CSP on the served window. Before that, wave 2 (C6): ffmpeg found or fetched the family way, ffprobe fill-in of durations and sizes, video poster frames, `ffmpeg` in capabilities. Before that: engine core (Phase 1 skeleton, Phase 3 jobs, events, media, costs, keys) --- @@ -2240,7 +2240,7 @@ From VERIFY_v0.8.0_E2E.md. A closed page's long poll could take a queued call: t ## 2026-11-28 · v0.9.3 the key file, the Python lookup and the LGPL text {#keys-v093} -- **Key file (`services/secrets.py`).** The file is opened owner-only (600, folder 700) at creation. Before, each write made a temporary file with default permissions and narrowed it afterwards. The reported store is the one the last save used and is remembered per process, so a restart works it out again. On Windows POSIX modes mean nothing; the profile folder's own permissions are the only guard, and the engine says so. Open: `core/durable.py`'s restore-from-`.bak` path still narrows permissions after writing. +- **Key file (`services/secrets.py`).** The file is opened owner-only (600, folder 700) at creation. Before, each write made a temporary file with default permissions and narrowed it afterwards. The reported store is the one the last save used and is remembered per process, so a restart works it out again. On Windows POSIX modes mean nothing; the profile folder's own permissions are the only guard, and the engine says so. Closed in v0.9.4: `core/durable.py` opens private files and their `.bak` copies with `os.open(..., 0o600)` through one helper, the temporary file with `O_EXCL` and the `.bak` with `O_TRUNC` then `fchmod` where the platform has it, so neither a normal write nor a restore leaves a moment of wider permissions. An older, looser `.bak` is narrowed on the next write. Files that are not private are unchanged. - **Python lookup (`setup/lib.sh`, `setup/find_python.bat`).** Exactly 3.12 wins over a newer Python on PATH so an engine built from source matches what CI tests. The fallback line goes to stderr so `mcp` stdout stays clean. `fc_python` still echoes one command, so its callers are unchanged. - **LGPL text.** `licenses/LGPL-2.1.txt` is a byte copy of the system's `/usr/share/common-licenses/LGPL-2.1` and ships through `bundle.resources`. formcompiler's `tauri_config.py` does not touch that key. No written offer and no recorded library versions. - **Tool list check (`setup/agents.py`).** `WINDOW_TOOL_NAMES` is read from `services/agents.py` with `ast`, as `mcp_tools.py` already was, so the engine is never imported. diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 2064093..4f69433 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -3,7 +3,7 @@ from pathlib import Path APP_NAME = "formcraft" -VERSION = "0.9.3" +VERSION = "0.9.4" FRONTEND_PORT = 5290 BACKEND_PORT = 8290 SUBFOLDERS = ("library", "thumbs", "downloads", "db", "settings", "logs") diff --git a/backend/app/core/durable.py b/backend/app/core/durable.py index 847aaf4..465bf9d 100644 --- a/backend/app/core/durable.py +++ b/backend/app/core/durable.py @@ -19,6 +19,17 @@ def _say(text: str) -> None: print(f"formcraft: {text}", file=sys.__stderr__) +def _open_private(path: Path, flags: int): + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | flags, 0o600) + if hasattr(os, "fchmod"): + try: + os.fchmod(descriptor, 0o600) + except OSError: + os.close(descriptor) + raise + return descriptor + + def _parse(path: Path): return json.loads(path.read_text(encoding="utf-8")) @@ -52,15 +63,19 @@ def write_json(path: Path, data, *, private: bool = False, indent: int | None = path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") try: - temporary.write_text(json.dumps(data, indent=indent), encoding="utf-8") + text = json.dumps(data, indent=indent) if private: - with contextlib.suppress(OSError): - os.chmod(temporary, 0o600) + with os.fdopen(_open_private(temporary, os.O_EXCL), "w", encoding="utf-8") as handle: + handle.write(text) + else: + temporary.write_text(text, encoding="utf-8") if keep_backup and path.is_file(): with contextlib.suppress(OSError): - shutil.copyfile(path, _backup(path)) if private: - os.chmod(_backup(path), 0o600) + with open(path, "rb") as source, os.fdopen(_open_private(_backup(path), os.O_TRUNC), "wb") as target: + shutil.copyfileobj(source, target) + else: + shutil.copyfile(path, _backup(path)) os.replace(temporary, path) finally: temporary.unlink(missing_ok=True) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 321afaa..8c50a0b 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of comment content, explainers, rationale, TODOs and removed code for the frontend side of the repo. Source files stay comment-free per the owner's hashout-log rule; what they would have said lives here, anchored by file and symbol. Read the map and the table of contents first. -Current build version: v0.9.3 +Current build version: v0.9.4 Last updated: 2026-11-02 · v0.8.0 command metadata, live edit commands, the automation bridge and 30 window tools, approvals with withdrawal, the Agents and Updates panels, the bridge goodbye beacon, the new icon in the splash and favicon. Before that, v0.7.0 Edit studio (engine/edit, ui/edit: contract, store and operations, renderer, effects, masks and audio mix, preview and transport, timeline, properties and assets panels, studio shell, files and export), the shared media panel in Canvas, Board and Scene (ui/panels), Add to edit in the Scene strip, lightbox and library, and the F1 and F2 fixes. Before that, v0.6.0 Scene studio from scene to shot: worlds as the environment (ui/scene/world), light and materials (view/ibl.ts, view/contact.ts, models keep their materials), the prompt bar and shot results (ui/scene/shot, replacing the Generate panel), generate into the scene (ui/scene/make), the downloadable starter pack (ui/scene/pack). Before that, 2026-11-01 · v0.5.0 Canvas studio (engine/canvas, ui/canvas: stage and tools, files, generate, results, 3D model nodes), Board studio (engine/board, ui/board: shell, grid, inspector, Present, board canvas view), Background change and video region removal (ui/tools/background-change, remove-region video mode), the app.ts wiring and `maskVideo` in io/api.ts. Before that, v0.4.0 F5 fixes (FBX conversion, pooled model renderer, Coming later), v0.4.0 Scene studio (engine/scene, ui/scene: host and view, object builders, procedural starter kit, editor chrome and files, presets and placement, outliner and inspector, timeline, posing and animation library, capture and record with mediabunny, Generate box and preview), Mesh tools and FBX conversion (ui/tools/mesh-tools.ts, ui/viewers/fbx-convert.ts, io/api-media-meta.ts), the upload dialog's 3D review step, and the app.ts wiring (mounts, studio-aware drops, close guard). Before that, v0.3.0 F1 fixes (lightbox hand-offs to Remove background, 3D object and World, Open in Scene placeholders, batch groups in the Library studio and the picker, mask polarity from the catalogue, one-step hidden import, character dedupe by content), on top of v0.3.0 Library studio (virtual grid, folders, tags, favourites, hidden items, covers), characters and prompt history, tags and favourite in the lightbox, 3D object and Gaussian splat viewers with covers, the 3D object and World pages, the tool pages (Angles, Remove background, Remove a region, Frame extractor, Storyboard) and projects (New and Open, .fcrft files, Home project lists). Before that (v0.2.0) Create pages: window model store and labels, model picker and options bar, prompt box with the mention editor and the fullscreen editor, reference deck and library modal, generation feed, lightbox, audio player and upload dialog, the Image, Video and Audio pages with the prompt store and handoffs, Behavior and Generation preferences, and gen.* job names in the job toasts. Before that (v0.1.0), E2 gap closing (job toasts, downloads with Ask where to save, Home file selection and delete, studio restore prefs, About dialog, cheatsheet hold time and pin), on top of wave 2 (title bar and menus, status bar and Jobs list, Home and importer, Preferences and panels, shortcuts panel, cheatsheet, alert sounds) and the orchestrator's integration edits in app.ts, ui/dom.ts, ui/menus.ts and styles/home.css --- @@ -7148,6 +7148,6 @@ Checked in a real Chrome against the engine: a reload keeps the dock working (th ## 2026-11-28 · v0.9.3 unviewable models, the remember box and source maps {#models-v093} - **Unviewable models.** The upload dialog and the library tile ask `modelFormat` from `ui/viewers/kinds` at run time, so the note goes away for a format the moment the viewer learns it. The tile shows its sentence as a tooltip because the existing tile CSS has no text slot. Open: `ui/library/library-modal.ts` still asks for a cover for these formats and shows no note. -- **OBJ and STL.** A conversion to GLB in the window, made the way `fbx-convert.ts` converts FBX, exists and is held back: `tests/unit/ui/viewers/kinds.test.ts` asserts that OBJ is an unknown format that cannot be previewed, and the owner decides whether those two assertions change. The library keeps no file beside an OBJ, so its material file is never found and a converted model is neutral grey. +- **OBJ and STL (shipped in v0.9.4).** A conversion to GLB in the window, made the way `fbx-convert.ts` converts FBX, with `ui/viewers/library-glb.ts` keeping the converted file in the library for reuse. The owner approved changing the two assertions in `tests/unit/ui/viewers/kinds.test.ts` that said OBJ is unknown and cannot be previewed. `ui/tools/mesh-tools.ts` goes through the viewer's own conversion. `ui/canvas/model3d/render.ts` reads only glTF and has no FBX path either, so a model as a canvas layer needs a conversion before `renderModel` for FBX, OBJ and STL alike. `ui/library/library-modal.ts` now asks `modelFormat` like the grid tile. The library keeps no file beside an OBJ, so its material file is never found and a converted model is neutral grey. - **Remember box.** The approval dialog is built once and reused, so with no estimate the label stays in place with `visibility: hidden` and a disabled checkbox, and `finish` ignores a disabled box. Removing the label would shift the dialog. - **Source maps (`vite.config.ts`).** Production builds emit none; `npm run dev` still serves them. `setup/freeze_backend` rebuilds a `dist` that still has `.map` files and stops if any remain. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 7af3a5c..33f26ea 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formcraft-frontend", - "version": "0.9.3", + "version": "0.9.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formcraft-frontend", - "version": "0.9.3", + "version": "0.9.4", "license": "Apache-2.0", "dependencies": { "@fontsource/inter": "5.3.0", diff --git a/frontend/package.json b/frontend/package.json index 5e4975e..dfcf8dd 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formcraft-frontend", "private": true, - "version": "0.9.3", + "version": "0.9.4", "description": "formcraft frontend · the studio window", "license": "Apache-2.0", "type": "module", diff --git a/frontend/src/ui/library/library-modal.ts b/frontend/src/ui/library/library-modal.ts index 012c0f6..c41464d 100644 --- a/frontend/src/ui/library/library-modal.ts +++ b/frontend/src/ui/library/library-modal.ts @@ -8,6 +8,7 @@ import { t, tn } from '../i18n'; import { icon } from '../icons'; import { toast } from '../toasts'; import { coverKey, ensureCover, onCover } from '../viewers/cover'; +import { modelFormat } from '../viewers/kinds'; import { batchGroups, library, type Batch } from './library-store'; import { COL_MAX, COL_MIN, DRAG_PX, EDGE_PX, FADE_MS, FLUSH_MAX, FLUSH_MS, GLIDE_MS, KIND_ICON, MORE_MARGIN, NARROW_PX, PAGE, Pager, SCROLL_MAX, SEARCH_MS, WIDE_PX, @@ -690,7 +691,7 @@ class LibraryModal extends Dialog { const badge = q(n, '.fc-lib-badge'); const text = badgeText(m); setText(q(n, '.fc-lib-name'), m.name); - setTitle(n, m.name); + setTitle(n, m.kind === 'model' && modelFormat(m) === null ? t('Stored in the library and can be downloaded, but cannot be previewed or placed in a scene yet.') : m.name); setAttr(n, 'aria-label', m.name); setText(badge, text); setHidden(badge, !text); @@ -741,6 +742,7 @@ class LibraryModal extends Dialog { const id = node.dataset.key; if (!id || node.dataset.thumb) return; const m = this.byId.get(id)?.m; + if (m && m.kind === 'model' && modelFormat(m) === null) return; const solid = m !== undefined && (m.kind === 'model' || m.kind === 'splat'); const cover = m && solid ? coverKey(m) : ''; if (m && solid && !cover) { diff --git a/frontend/src/ui/scene/presets/place.ts b/frontend/src/ui/scene/presets/place.ts index a05a42d..b999257 100644 --- a/frontend/src/ui/scene/presets/place.ts +++ b/frontend/src/ui/scene/presets/place.ts @@ -5,6 +5,7 @@ import { isPackId } from '../pack/types'; import type { Media } from '../../../io/api'; import { roleOf } from '../../../io/api-media-meta'; import { t } from '../../i18n'; +import { modelFormat } from '../../viewers/kinds'; import type { SceneContext } from '../context'; import { isWorld, setEnvironment } from '../world'; import type { PresetCard } from './catalogue'; @@ -188,6 +189,18 @@ export function placeMedia(ctx: PlaceParts, media: Media, spot?: Spot): string | const asset = { $media: media.id }; const name = nameOf(media); if (media.kind === 'model') { + const format = modelFormat(media); + if (format === 'obj' || format === 'stl') { + const dismiss = ctx.toast(t('Loading the 3D model'), 'info', { key: 'scene-place', ms: 60000 }); + void import('../../viewers/library-glb') + .then(({ libraryGlb }) => libraryGlb(media, format)) + .then((glb) => { + dismiss(); + placeMedia(ctx, glb, at); + }) + .catch((err: unknown) => ctx.toast(err instanceof Error ? t(err.message) : t('Could not load this 3D model.'), 'error', { key: 'scene-place' })); + return null; + } const role = roleOf(media); if (role === 'animation') { ctx.toast(t('This file holds animations. Add it from the Animations library.'), 'warning', { key: 'scene-place' }); diff --git a/frontend/src/ui/tools/mesh-tools.ts b/frontend/src/ui/tools/mesh-tools.ts index 8cd5708..a49c07b 100644 --- a/frontend/src/ui/tools/mesh-tools.ts +++ b/frontend/src/ui/tools/mesh-tools.ts @@ -49,7 +49,7 @@ function acceptedExts(model: WindowModel): string[] | null { function viewKind(m: Pick): ModelKind | null { const ext = extOf(m.name); - return ext === 'glb' || ext === 'gltf' || ext === 'fbx' ? ext : null; + return ext === 'glb' || ext === 'gltf' || ext === 'fbx' || ext === 'obj' || ext === 'stl' ? ext : null; } function sizeText(n: number): string { diff --git a/frontend/src/ui/viewers/fbx-convert.ts b/frontend/src/ui/viewers/fbx-convert.ts index 084a6b7..9f45700 100644 --- a/frontend/src/ui/viewers/fbx-convert.ts +++ b/frontend/src/ui/viewers/fbx-convert.ts @@ -264,3 +264,113 @@ export async function fbxToGlb(input: Blob | ArrayBuffer | Uint8Array): Promise< release(group, blobs); } } + +const NEUTRAL = 0xb4b4b4; +const NEUTRAL_ROUGHNESS = 0.8; + +function neutral(three: Three, root: Object3D): void { + const made = new Map(); + const pick = (painted: boolean): Material => { + let m = made.get(painted); + if (!m) { + m = new three.MeshStandardMaterial({ color: painted ? 0xffffff : NEUTRAL, vertexColors: painted, roughness: NEUTRAL_ROUGHNESS, metalness: 0 }); + made.set(painted, m); + } + return m; + }; + root.traverse((node) => { + const mesh = node as Mesh; + if (mesh.isMesh) mesh.material = pick(mesh.geometry.hasAttribute('color')); + }); +} + +async function exportGlb(root: Object3D, fail: string): Promise { + const exporters = await import('three/addons/exporters/GLTFExporter.js'); + await wait(0); + let out: ArrayBuffer; + try { + out = (await new exporters.GLTFExporter().parseAsync(root, { binary: true, maxTextureSize: MAX_TEXTURE })) as ArrayBuffer; + } catch { + throw new Error(fail); + } + return new Blob([out], { type: 'model/gltf-binary' }); +} + +const still = (meshes: number): ModelProbe => ({ clips: [], skinned: false, meshes, humanoid: false, rig: 'none', bones: 0 }); + +export async function objToGlb(input: Blob | ArrayBuffer | Uint8Array, mtl: string | null = null): Promise { + const text = new TextDecoder().decode(await toBuffer(input)); + await wait(0); + const [three, loaders, materials] = await Promise.all([import('three'), import('three/addons/loaders/OBJLoader.js'), mtl === null ? null : import('three/addons/loaders/MTLLoader.js')]); + const blobs = new Set(); + let started = 0; + const manager = new three.LoadingManager(); + manager.setURLModifier((url) => { + started++; + if (url.startsWith('blob:')) blobs.add(url); + return url.startsWith('blob:') || url.startsWith('data:') ? url : DOT; + }); + const loader = new loaders.OBJLoader(manager); + let group: Group | null = null; + try { + let loaded: Promise; + try { + if (materials && mtl !== null) { + const creator = new materials.MTLLoader(manager).parse(mtl, ''); + creator.preload(); + loader.setMaterials(creator); + } + group = loader.parse(text); + loaded = textureWait(manager, () => started); + } catch { + throw new Error('This OBJ file could not be read.'); + } + const root = group; + let meshes = 0; + root.traverse((node) => { + if ((node as Mesh).isMesh) meshes++; + }); + if (meshes === 0) throw new Error('This OBJ file has no model in it.'); + await loaded; + keepLoaded(root); + if (mtl === null) neutral(three, root); + else standardise(three, root); + root.updateMatrixWorld(true); + for (const tex of texturesOf(root)) { + const src = sourceOf(tex); + if (src.startsWith('blob:')) blobs.add(src); + } + return { glb: await exportGlb(root, 'This OBJ file could not be converted to GLB.'), ...still(meshes) }; + } finally { + release(group, blobs); + } +} + +export async function stlToGlb(input: Blob | ArrayBuffer | Uint8Array): Promise { + const buffer = await toBuffer(input); + await wait(0); + const [three, loaders] = await Promise.all([import('three'), import('three/addons/loaders/STLLoader.js')]); + let group: Group | null = null; + try { + let geometry; + try { + geometry = new loaders.STLLoader().parse(buffer); + } catch { + throw new Error('This STL file could not be read.'); + } + group = new three.Group(); + group.add(new three.Mesh(geometry)); + if (!geometry.getAttribute('position')?.count) throw new Error('This STL file has no model in it.'); + neutral(three, group); + group.updateMatrixWorld(true); + return { glb: await exportGlb(group, 'This STL file could not be converted to GLB.'), ...still(1) }; + } finally { + release(group, new Set()); + } +} + +export type Convertible = 'fbx' | 'obj' | 'stl'; + +export function convertToGlb(input: Blob | ArrayBuffer | Uint8Array, format: Convertible): Promise { + return format === 'obj' ? objToGlb(input) : format === 'stl' ? stlToGlb(input) : fbxToGlb(input); +} diff --git a/frontend/src/ui/viewers/kinds.ts b/frontend/src/ui/viewers/kinds.ts index 02ecd31..c2a332c 100644 --- a/frontend/src/ui/viewers/kinds.ts +++ b/frontend/src/ui/viewers/kinds.ts @@ -1,6 +1,6 @@ import type { Media } from '../../io/api'; -export type ModelFormat = 'glb' | 'gltf' | 'fbx'; +export type ModelFormat = 'glb' | 'gltf' | 'fbx' | 'obj' | 'stl'; export type SplatFormat = 'spz' | 'ply' | 'splat' | 'ksplat' | 'sog'; const SPLATS: ReadonlySet = new Set(['spz', 'ply', 'splat', 'ksplat', 'sog']); @@ -12,9 +12,11 @@ const extOf = (name: string): string => { export function modelFormat(m: Pick): ModelFormat | null { const ext = extOf(m.name); - if (ext === 'glb' || ext === 'gltf' || ext === 'fbx') return ext; + if (ext === 'glb' || ext === 'gltf' || ext === 'fbx' || ext === 'obj' || ext === 'stl') return ext; if (m.mime === 'model/gltf-binary') return 'glb'; if (m.mime === 'model/gltf+json') return 'gltf'; + if (m.mime === 'model/obj') return 'obj'; + if (m.mime === 'model/stl') return 'stl'; return null; } diff --git a/frontend/src/ui/viewers/library-glb.ts b/frontend/src/ui/viewers/library-glb.ts new file mode 100644 index 0000000..d021693 --- /dev/null +++ b/frontend/src/ui/viewers/library-glb.ts @@ -0,0 +1,18 @@ +import { getMedia, mediaFileUrl, type Media } from '../../io/api'; +import { importModelFile, metaOf, patchMediaMeta, swapExt, type MetaMedia } from '../../io/api-media-meta'; +import { download } from './download'; +import { convertToGlb, type Convertible } from './fbx-convert'; + +export async function libraryGlb(media: Media, format: Convertible): Promise { + const known = metaOf(media as MetaMedia).glbId; + if (typeof known === 'string' && known !== '') { + const kept = await getMedia(known).catch(() => null); + if (kept && kept.kind === 'model') return kept as MetaMedia; + } + const bytes = await download(mediaFileUrl(media.id), () => undefined, new AbortController().signal); + const made = await convertToGlb(bytes, format); + const item = await importModelFile(made.glb, swapExt(media.name, 'glb'), { hidden: false }); + const saved = await patchMediaMeta(item.id, { meta: { sourceId: media.id, clips: made.clips, rig: made.rig } }).catch(() => item); + await patchMediaMeta(media.id, { meta: { ...metaOf(media as MetaMedia), glbId: saved.id } }).catch(() => undefined); + return saved; +} diff --git a/frontend/src/ui/viewers/model-viewer.ts b/frontend/src/ui/viewers/model-viewer.ts index df3992b..2cf4493 100644 --- a/frontend/src/ui/viewers/model-viewer.ts +++ b/frontend/src/ui/viewers/model-viewer.ts @@ -1,10 +1,12 @@ import { download } from './download'; -import { fbxToGlb } from './fbx-convert'; +import { convertToGlb, type Convertible } from './fbx-convert'; import type { ModelCore } from './model-core'; import { COVER_BACKGROUND, COVER_SIZE, ViewerShell, themeColors } from './viewer-shell'; export interface ViewerOptions { grid?: boolean; pace?: () => Promise } -export type ModelKind = 'glb' | 'gltf' | 'fbx'; +export type ModelKind = 'glb' | 'gltf' | Convertible; + +const CONVERTING: Record = { fbx: 'Converting the FBX file', obj: 'Converting the OBJ file', stl: 'Converting the STL file' }; const NO_WEBGL = 'The 3D view is not available on this device.'; @@ -82,9 +84,9 @@ export class ModelViewer { return this.opening; } - private async convert(url: string): Promise { + private async convert(url: string, kind: Convertible): Promise { const bytes = await download(url, (r) => this.shell.progress(r), new AbortController().signal); - const made = await fbxToGlb(bytes); + const made = await convertToGlb(bytes, kind); return URL.createObjectURL(made.glb); } @@ -92,19 +94,20 @@ export class ModelViewer { if (this.dead) return; const ticket = ++this.ticket; this.loaded = false; - if (kind !== 'glb' && kind !== 'gltf' && kind !== 'fbx') { + const convert = kind === 'glb' || kind === 'gltf' ? null : kind; + if (convert !== null && !(convert in CONVERTING)) { this.core?.clear(); this.shell.fail('There is no preview for this 3D format.'); throw new Error('unsupported'); } - this.shell.begin(kind === 'fbx' ? 'Converting the FBX file' : 'Loading 3D model'); + this.shell.begin(convert ? CONVERTING[convert] : 'Loading 3D model'); if (this.core) { this.core.clear(); this.core.stage.request(); } try { const core = await this.open(); - const from = kind === 'fbx' ? await this.convert(url) : url; + const from = convert ? await this.convert(url, convert) : url; let info; try { if (this.dead || ticket !== this.ticket) return; diff --git a/frontend/tests/unit/ui/viewers/kinds.test.ts b/frontend/tests/unit/ui/viewers/kinds.test.ts index 5fac56d..1617856 100644 --- a/frontend/tests/unit/ui/viewers/kinds.test.ts +++ b/frontend/tests/unit/ui/viewers/kinds.test.ts @@ -18,7 +18,7 @@ describe('modelFormat', () => { }); it('returns null for other formats and for names without an extension', () => { - expect(modelFormat({ name: 'x.obj', mime: 'model/obj' })).toBeNull(); + expect(modelFormat({ name: 'x.obj', mime: 'model/obj' })).toBe('obj'); expect(modelFormat({ name: 'glb', mime: '' })).toBeNull(); expect(modelFormat({ name: '.glb', mime: '' })).toBeNull(); expect(modelFormat({ name: 'trailing.', mime: '' })).toBeNull(); @@ -47,7 +47,7 @@ describe('previewable', () => { it('previews a model only when its format is known', () => { expect(previewable({ kind: 'model', name: 'a.glb', mime: '' })).toBe(true); - expect(previewable({ kind: 'model', name: 'a.obj', mime: '' })).toBe(false); + expect(previewable({ kind: 'model', name: 'a.obj', mime: '' })).toBe(true); }); it('does not preview other kinds even with a model extension', () => { diff --git a/setup/form-app.json b/setup/form-app.json index b68c3d9..dbb8f6d 100644 --- a/setup/form-app.json +++ b/setup/form-app.json @@ -4,7 +4,7 @@ "id": "formcraft", "app": "formcraft", "name": "FormCraft", - "version": "0.9.3", + "version": "0.9.4", "agents": { "mcp": { "available": true, diff --git a/setup/mcpb/manifest.json b/setup/mcpb/manifest.json index d364984..ff583da 100644 --- a/setup/mcpb/manifest.json +++ b/setup/mcpb/manifest.json @@ -2,7 +2,7 @@ "manifest_version": "0.3", "name": "formcraft", "display_name": "FormCraft", - "version": "0.9.3", + "version": "0.9.4", "description": "Drive the FormCraft studio from an agent: generate images, video, audio, 3D and worlds, search the library, manage projects and cut edits.", "long_description": "Starts the FormCraft engine in MCP mode over stdio. It attaches to a running FormCraft app when there is one and otherwise runs headless. Generation uses your own provider keys stored in FormCraft; agents must be allowed in FormCraft Preferences.", "author": { diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 263990b..428babf 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1073,7 +1073,7 @@ dependencies = [ [[package]] name = "formcraft" -version = "0.9.3" +version = "0.9.4" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 61016f5..e807ef6 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formcraft" -version = "0.9.3" +version = "0.9.4" description = "formcraft desktop shell" authors = ["NodeAgentc, Inc."] license = "Apache-2.0" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index f09fe08..cfb3231 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormCraft", - "version": "0.9.3", + "version": "0.9.4", "identifier": "ai.nodemode.formcraft", "build": { "frontendDist": "../frontend/dist"