diff --git a/.agents/skills/formcraft-driving/SKILL.md b/.agents/skills/formcraft-driving/SKILL.md index 83ab158..5dea0a2 100644 --- a/.agents/skills/formcraft-driving/SKILL.md +++ b/.agents/skills/formcraft-driving/SKILL.md @@ -9,7 +9,7 @@ metadata: # Driving formcraft through MCP -formcraft exposes one MCP server, started with `formcraft mcp` (stdio). The 44 engine-direct tools always work, with the app window closed; the 30 window tools work only while the app window is open. Use only the tool names listed in `references/tools-by-task.md`: the set is frozen and a name that is not there does not exist. If a tool you expect is missing from `tools/list`, say so; do not invent a substitute call. +formcraft exposes one MCP server, started with `formcraft mcp` (stdio). The 44 engine-direct tools always work, with the app window closed; the 49 window tools work only while the app window is open. Use only the tool names listed in `references/tools-by-task.md`: the set is frozen and a name that is not there does not exist. If a tool you expect is missing from `tools/list`, say so; do not invent a substitute call. ## Connect diff --git a/.agents/skills/formcraft-driving/references/tools-by-task.md b/.agents/skills/formcraft-driving/references/tools-by-task.md index 5b0ccf9..cb19440 100644 --- a/.agents/skills/formcraft-driving/references/tools-by-task.md +++ b/.agents/skills/formcraft-driving/references/tools-by-task.md @@ -58,7 +58,17 @@ Time is in ticks (120000 per second) or seconds as each tool description states; ## Scene -Needs the window. `scene_state` to read, `scene_add` to place objects, `scene_update` for transforms, pose, sky, sun, environment, active camera and prompt, `scene_capture` to return a shot as an image. To turn a shot into media, use `command_run` with the scene's generate-from-camera command found through `commands_list`. +Needs the window. No scene tool depends on a selection, an open panel or Build or Record mode; do not drive the scene through `command_run` shortcuts. Positions are metres, rotations degrees, times seconds. + +1. `scene_schema` once for the object, keyframe and `.fcrft` formats. Never read the app's code or edit an exported file to change a scene. +2. Read: `scene_list_objects` (ids, kinds, parents, transforms), `scene_state` (setup), `scene_timeline_get` (tracks and keys). +3. Build: `scene_add_many` for a whole set in one call (give a group a `ref`, then use that ref as `parent` of later items), `scene_add` for one object, `scene_update` to change one (including `parent`), `scene_delete`, `scene_group`, `scene_ungroup`, `scene_select`. +4. Cameras: `scene_camera` makes a camera active and sets its lens, position and look-at point or object. +5. Animate: `scene_keys_set` with a list of `{ objectId, time, position, rotation, scale, ease }` (one call for every key; `extendDuration` lengthens the timeline), `scene_keys_delete`, `scene_timeline_set` for duration, fps and playhead. +6. Output: `scene_capture` for a still; `scene_record_start` (switches to Record mode itself, options aspect, cameraId, durationSec), then `scene_record_status` with `waitSec` until `running` is false and `result.mediaId` is set; `scene_record_stop` to stop. +7. Keep it: `scene_save` (a name for the first save, `path` to also write a `.fcrft`), `scene_export`, `scene_open` (`saveFirst` or `discardChanges` when there are unsaved changes). + +To turn a shot into media, use `command_run` with the scene's generate-from-camera command found through `commands_list`. ## Canvas and board diff --git a/.agents/skills/formcraft-harness/references/engine-routes.md b/.agents/skills/formcraft-harness/references/engine-routes.md index f2d8c93..3f41a2d 100644 --- a/.agents/skills/formcraft-harness/references/engine-routes.md +++ b/.agents/skills/formcraft-harness/references/engine-routes.md @@ -24,7 +24,7 @@ All routes sit under `/api` (router files in `backend/app/routers/`, mounted in | `generate.py` | `POST /generate` (model, page, prompt, options, media, strategy, subscriberId, clientRequestId) | | `jobs.py` | `GET /jobs`, `POST /jobs`, `POST /jobs/dismiss-finished`, `GET /jobs/{id}`, `POST /jobs/{id}/cancel`, `POST /jobs/{id}/dismiss` | | `events.py` | `GET /events` (SSE, 15 s heartbeat) | -| `media.py` | `GET /media`, `POST /media/import`, `POST /media/download-batch`, `GET`, `PATCH`, `DELETE /media/{id}`, `PUT /media/{id}/tags`, `PUT`, `DELETE /media/{id}/cover`, `GET /media/{id}/file`, `GET /media/{id}/frame`, `GET /media/{id}/thumb`, `POST /media/{id}/world/complete`, `POST /media/mask-video`, `POST /media/{id}/download` | +| `media.py` | `GET /media`, `POST /media/import`, `POST /media/download-batch`, `GET`, `PATCH`, `DELETE /media/{id}`, `PUT /media/{id}/tags`, `PUT`, `DELETE /media/{id}/cover`, `GET /media/{id}/file`, `GET /media/{id}/frame`, `GET /media/{id}/thumb`, `POST /media/{id}/world/complete`, `POST /media/mask-video`, `POST /media/name-preview`, `POST /media/{id}/download` | | `edit.py` | `GET /edit/capability`, encode sessions `POST /edit/encode`, `PUT .../frames`, `PUT .../audio`, `POST .../finish`, `POST .../cancel`, `DELETE`; `GET /media/{id}/probe`; `GET /sounds`, `GET /sounds/{id}/file`, `POST /sounds/{id}/import` | | `scene.py` | scene recording encode sessions: `POST /scene/encode`, `PUT .../frames`, `POST .../finish`, `DELETE` | | `folders.py` | `GET`, `POST /folders`, `GET`, `PATCH`, `DELETE /folders/{id}`, `POST /folders/{id}/items` | @@ -33,6 +33,9 @@ All routes sit under `/api` (router files in `backend/app/routers/`, mounted in | `prompts.py` | `GET /prompts` | | `projects.py` | `GET`, `POST /projects`, `POST /projects/import`, `GET`, `PUT`, `PATCH`, `DELETE /projects/{id}`, `PUT /projects/{id}/cover`, `POST /projects/{id}/export` | | `pack.py` | `GET`, `DELETE /pack`, `POST /pack/install`, `GET /pack/file/{key}` | +| `render.py` | `GET /render/binaries`, `POST /render/binaries/check`, `GET /render/presets`, `POST /render`, `POST /render/{job_id}/cancel`, `GET /render/formencoder`, `POST /render/formencoder/send` | +| `starter.py` | `GET /starter`, `GET /starter/credits`, `GET /starter/packs/{pack_id}/licence`, `GET /starter/items/{pack_id}/{item_id}`, `GET .../file`, `GET`, `PUT .../thumb`, `POST .../add` | +| `demos.py` | `GET /demos`, `GET /demos/{demo_id}/cover`, `POST /demos/{demo_id}/open` | | `settings.py` | `GET`, `PUT /settings` | | `keys.py` | `GET /keys`, `PUT`, `DELETE /keys/{provider}`, `POST /keys/{provider}/check` | diff --git a/.agents/skills/formcraft-harness/references/tool-map.md b/.agents/skills/formcraft-harness/references/tool-map.md index 8b4b74c..877b982 100644 --- a/.agents/skills/formcraft-harness/references/tool-map.md +++ b/.agents/skills/formcraft-harness/references/tool-map.md @@ -11,13 +11,13 @@ ## Rules -There are 44 engine-direct tools (always available) and 30 window tools (available while the window is open), 74 in all, listed in `agents/manifest.json`. The tool names below are frozen from v0.8.0: never renamed, never reused for another meaning. A new capability gets a new name. Every tool carries `title`, a description and the four annotation hints (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`). Names are snake_case. +There are 44 engine-direct tools (always available) and 49 window tools (available while the window is open), 93 in all, listed in `agents/manifest.json`. The tool names below are frozen from v0.8.0: never renamed, never reused for another meaning. A new capability gets a new name. Every tool carries `title`, a description and the four annotation hints (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`). Names are snake_case. Hint letters in the tables: R reads only, W writes, D destructive (asks), $ spends money, N reaches a provider over the network. `agentsAllowed` (engine setting, off by default) is checked before any tool runs. The server is stateless JSON at `POST /mcp`, dual era: `2026-07-28` (`server/discover`, version in `_meta`) and `2025-11-25` (`initialize`, `notifications/initialized`, `ping`). Tools only, plus a few resources (`formcraft://models/{page}`, `library/{id}`, `project/{id}`, `jobs`) and prompts (`shot_workflow`, `edit_workflow`, `generate_safely`). -Tool failures answer `isError` with the engine `error.code`. A window tool with no window answers `window_required` within a few seconds after the window closes (bridge timeout 90 s, 900 s for `edit_export`, 180 s for `scene_capture`). Secrets never appear in results, resources, logs or errors. +Tool failures answer `isError` with the engine `error.code`. A window tool with no window answers `window_required` within a few seconds after the window closes (bridge timeout 90 s; 900 s for `edit_export` and `scene_export`; 180 s for `scene_capture`, `scene_save` and `scene_open`; 120 s for `scene_record_start`). Every failure says what was wrong and which tool to call instead. Secrets never appear in results, resources, logs or errors. ## Engine-direct tools @@ -92,10 +92,28 @@ These go through the bridge to the open window and are listed only when the wind | `edit_settings` | W | `setFps`, `setCanvas`, `setBackground` | | | `edit_undo`, `edit_redo` | W | `undo`, `redo` | | | `edit_export` | W | export through `ui/edit/export` | renders; 600 s timeout; overwriting asks | -| `scene_state` | R | `SceneStore` summary | | -| `scene_add` | W | `SceneStore.add` | | -| `scene_update` | W | `update`, `setTransform`, `setPose`, `setSkybox`, `setSun`, `setEnvironment`, `setActiveCamera`, `setPrompt` | | -| `scene_capture` | R | shot capture through `ui/scene/shot` | image block | +| `scene_state` | R | `SceneStore` summary | rotation in degrees | +| `scene_list_objects` | R | `SceneStore.doc.objects` | ids, kinds, parents, transforms, group children | +| `scene_add` | W | `SceneStore.create` | transform, colour, material, light, lens, parent in one call | +| `scene_add_many` | W | `newObject`, `SceneStore.add` | up to 500 in one undo step; `ref` lets later items parent to an earlier group | +| `scene_update` | W | `update`, `reparent`, `setAspect`, `setSkybox`, `setSun`, `setActiveCamera`, `setPrompt` | | +| `scene_delete` | D | `SceneStore.remove` | | +| `scene_select` | W | `SceneStore.select` | no other tool needs a selection | +| `scene_group`, `scene_ungroup` | W, D | `group`, `ungroup` | | +| `scene_camera` | W | `update`, `setActiveCamera`, `lookAtEuler` | active, lens, position, look-at | +| `scene_mode` | W | `EditorState.setMode` | keeps the selection | +| `scene_timeline_get` | R | `doc.timeline` | keys with ids, times, transforms, eases | +| `scene_keys_set` | W | `engine/scene/tl-batch.addKeys`, `commitTimeline` | batch, one undo step, any mode, no selection | +| `scene_keys_delete` | D | `tl-batch.removeKeys` | by key id, time range or all | +| `scene_timeline_set` | W | `setDuration`, `tl-batch.setRate`, `EditorState.setPlayhead` | duration, fps, playhead | +| `scene_capture` | W | `ui/scene/generate/frame.captureFrame` | keeps the still in the library unless `save` is false; image block | +| `scene_record_start` | W | command `scene.record` (`ui/scene/output/controller`) | switches to Record mode itself | +| `scene_record_status` | R | `EditorState.busy`, newest library video | `waitSec` up to 80 | +| `scene_record_stop` | W | command `scene.cancelOutput` | | +| `scene_save` | W | `SceneFiles.save`, `createProject` | `name` for a first save; `path` also exports | +| `scene_export` | W | `exportProject` | `.fcrft`; path checked against the write roots | +| `scene_open` | D | `SceneFiles.openId`, `importProjectPath` | `saveFirst` or `discardChanges` when unsaved | +| `scene_schema` | R | static | scene, object, key and `.fcrft` formats | | `canvas_state` | R | `CanvasStore` summary | | | `canvas_add_image` | W | `CanvasStore` node add | no raw strokes | | `board_state` | R | `BoardStore` summary | | diff --git a/.claude/skills/formcraft-driving/SKILL.md b/.claude/skills/formcraft-driving/SKILL.md index 83ab158..5dea0a2 100644 --- a/.claude/skills/formcraft-driving/SKILL.md +++ b/.claude/skills/formcraft-driving/SKILL.md @@ -9,7 +9,7 @@ metadata: # Driving formcraft through MCP -formcraft exposes one MCP server, started with `formcraft mcp` (stdio). The 44 engine-direct tools always work, with the app window closed; the 30 window tools work only while the app window is open. Use only the tool names listed in `references/tools-by-task.md`: the set is frozen and a name that is not there does not exist. If a tool you expect is missing from `tools/list`, say so; do not invent a substitute call. +formcraft exposes one MCP server, started with `formcraft mcp` (stdio). The 44 engine-direct tools always work, with the app window closed; the 49 window tools work only while the app window is open. Use only the tool names listed in `references/tools-by-task.md`: the set is frozen and a name that is not there does not exist. If a tool you expect is missing from `tools/list`, say so; do not invent a substitute call. ## Connect diff --git a/.claude/skills/formcraft-driving/references/tools-by-task.md b/.claude/skills/formcraft-driving/references/tools-by-task.md index 5b0ccf9..cb19440 100644 --- a/.claude/skills/formcraft-driving/references/tools-by-task.md +++ b/.claude/skills/formcraft-driving/references/tools-by-task.md @@ -58,7 +58,17 @@ Time is in ticks (120000 per second) or seconds as each tool description states; ## Scene -Needs the window. `scene_state` to read, `scene_add` to place objects, `scene_update` for transforms, pose, sky, sun, environment, active camera and prompt, `scene_capture` to return a shot as an image. To turn a shot into media, use `command_run` with the scene's generate-from-camera command found through `commands_list`. +Needs the window. No scene tool depends on a selection, an open panel or Build or Record mode; do not drive the scene through `command_run` shortcuts. Positions are metres, rotations degrees, times seconds. + +1. `scene_schema` once for the object, keyframe and `.fcrft` formats. Never read the app's code or edit an exported file to change a scene. +2. Read: `scene_list_objects` (ids, kinds, parents, transforms), `scene_state` (setup), `scene_timeline_get` (tracks and keys). +3. Build: `scene_add_many` for a whole set in one call (give a group a `ref`, then use that ref as `parent` of later items), `scene_add` for one object, `scene_update` to change one (including `parent`), `scene_delete`, `scene_group`, `scene_ungroup`, `scene_select`. +4. Cameras: `scene_camera` makes a camera active and sets its lens, position and look-at point or object. +5. Animate: `scene_keys_set` with a list of `{ objectId, time, position, rotation, scale, ease }` (one call for every key; `extendDuration` lengthens the timeline), `scene_keys_delete`, `scene_timeline_set` for duration, fps and playhead. +6. Output: `scene_capture` for a still; `scene_record_start` (switches to Record mode itself, options aspect, cameraId, durationSec), then `scene_record_status` with `waitSec` until `running` is false and `result.mediaId` is set; `scene_record_stop` to stop. +7. Keep it: `scene_save` (a name for the first save, `path` to also write a `.fcrft`), `scene_export`, `scene_open` (`saveFirst` or `discardChanges` when there are unsaved changes). + +To turn a shot into media, use `command_run` with the scene's generate-from-camera command found through `commands_list`. ## Canvas and board diff --git a/.claude/skills/formcraft-harness/references/engine-routes.md b/.claude/skills/formcraft-harness/references/engine-routes.md index f2d8c93..3f41a2d 100644 --- a/.claude/skills/formcraft-harness/references/engine-routes.md +++ b/.claude/skills/formcraft-harness/references/engine-routes.md @@ -24,7 +24,7 @@ All routes sit under `/api` (router files in `backend/app/routers/`, mounted in | `generate.py` | `POST /generate` (model, page, prompt, options, media, strategy, subscriberId, clientRequestId) | | `jobs.py` | `GET /jobs`, `POST /jobs`, `POST /jobs/dismiss-finished`, `GET /jobs/{id}`, `POST /jobs/{id}/cancel`, `POST /jobs/{id}/dismiss` | | `events.py` | `GET /events` (SSE, 15 s heartbeat) | -| `media.py` | `GET /media`, `POST /media/import`, `POST /media/download-batch`, `GET`, `PATCH`, `DELETE /media/{id}`, `PUT /media/{id}/tags`, `PUT`, `DELETE /media/{id}/cover`, `GET /media/{id}/file`, `GET /media/{id}/frame`, `GET /media/{id}/thumb`, `POST /media/{id}/world/complete`, `POST /media/mask-video`, `POST /media/{id}/download` | +| `media.py` | `GET /media`, `POST /media/import`, `POST /media/download-batch`, `GET`, `PATCH`, `DELETE /media/{id}`, `PUT /media/{id}/tags`, `PUT`, `DELETE /media/{id}/cover`, `GET /media/{id}/file`, `GET /media/{id}/frame`, `GET /media/{id}/thumb`, `POST /media/{id}/world/complete`, `POST /media/mask-video`, `POST /media/name-preview`, `POST /media/{id}/download` | | `edit.py` | `GET /edit/capability`, encode sessions `POST /edit/encode`, `PUT .../frames`, `PUT .../audio`, `POST .../finish`, `POST .../cancel`, `DELETE`; `GET /media/{id}/probe`; `GET /sounds`, `GET /sounds/{id}/file`, `POST /sounds/{id}/import` | | `scene.py` | scene recording encode sessions: `POST /scene/encode`, `PUT .../frames`, `POST .../finish`, `DELETE` | | `folders.py` | `GET`, `POST /folders`, `GET`, `PATCH`, `DELETE /folders/{id}`, `POST /folders/{id}/items` | @@ -33,6 +33,9 @@ All routes sit under `/api` (router files in `backend/app/routers/`, mounted in | `prompts.py` | `GET /prompts` | | `projects.py` | `GET`, `POST /projects`, `POST /projects/import`, `GET`, `PUT`, `PATCH`, `DELETE /projects/{id}`, `PUT /projects/{id}/cover`, `POST /projects/{id}/export` | | `pack.py` | `GET`, `DELETE /pack`, `POST /pack/install`, `GET /pack/file/{key}` | +| `render.py` | `GET /render/binaries`, `POST /render/binaries/check`, `GET /render/presets`, `POST /render`, `POST /render/{job_id}/cancel`, `GET /render/formencoder`, `POST /render/formencoder/send` | +| `starter.py` | `GET /starter`, `GET /starter/credits`, `GET /starter/packs/{pack_id}/licence`, `GET /starter/items/{pack_id}/{item_id}`, `GET .../file`, `GET`, `PUT .../thumb`, `POST .../add` | +| `demos.py` | `GET /demos`, `GET /demos/{demo_id}/cover`, `POST /demos/{demo_id}/open` | | `settings.py` | `GET`, `PUT /settings` | | `keys.py` | `GET /keys`, `PUT`, `DELETE /keys/{provider}`, `POST /keys/{provider}/check` | diff --git a/.claude/skills/formcraft-harness/references/tool-map.md b/.claude/skills/formcraft-harness/references/tool-map.md index 8b4b74c..877b982 100644 --- a/.claude/skills/formcraft-harness/references/tool-map.md +++ b/.claude/skills/formcraft-harness/references/tool-map.md @@ -11,13 +11,13 @@ ## Rules -There are 44 engine-direct tools (always available) and 30 window tools (available while the window is open), 74 in all, listed in `agents/manifest.json`. The tool names below are frozen from v0.8.0: never renamed, never reused for another meaning. A new capability gets a new name. Every tool carries `title`, a description and the four annotation hints (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`). Names are snake_case. +There are 44 engine-direct tools (always available) and 49 window tools (available while the window is open), 93 in all, listed in `agents/manifest.json`. The tool names below are frozen from v0.8.0: never renamed, never reused for another meaning. A new capability gets a new name. Every tool carries `title`, a description and the four annotation hints (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`). Names are snake_case. Hint letters in the tables: R reads only, W writes, D destructive (asks), $ spends money, N reaches a provider over the network. `agentsAllowed` (engine setting, off by default) is checked before any tool runs. The server is stateless JSON at `POST /mcp`, dual era: `2026-07-28` (`server/discover`, version in `_meta`) and `2025-11-25` (`initialize`, `notifications/initialized`, `ping`). Tools only, plus a few resources (`formcraft://models/{page}`, `library/{id}`, `project/{id}`, `jobs`) and prompts (`shot_workflow`, `edit_workflow`, `generate_safely`). -Tool failures answer `isError` with the engine `error.code`. A window tool with no window answers `window_required` within a few seconds after the window closes (bridge timeout 90 s, 900 s for `edit_export`, 180 s for `scene_capture`). Secrets never appear in results, resources, logs or errors. +Tool failures answer `isError` with the engine `error.code`. A window tool with no window answers `window_required` within a few seconds after the window closes (bridge timeout 90 s; 900 s for `edit_export` and `scene_export`; 180 s for `scene_capture`, `scene_save` and `scene_open`; 120 s for `scene_record_start`). Every failure says what was wrong and which tool to call instead. Secrets never appear in results, resources, logs or errors. ## Engine-direct tools @@ -92,10 +92,28 @@ These go through the bridge to the open window and are listed only when the wind | `edit_settings` | W | `setFps`, `setCanvas`, `setBackground` | | | `edit_undo`, `edit_redo` | W | `undo`, `redo` | | | `edit_export` | W | export through `ui/edit/export` | renders; 600 s timeout; overwriting asks | -| `scene_state` | R | `SceneStore` summary | | -| `scene_add` | W | `SceneStore.add` | | -| `scene_update` | W | `update`, `setTransform`, `setPose`, `setSkybox`, `setSun`, `setEnvironment`, `setActiveCamera`, `setPrompt` | | -| `scene_capture` | R | shot capture through `ui/scene/shot` | image block | +| `scene_state` | R | `SceneStore` summary | rotation in degrees | +| `scene_list_objects` | R | `SceneStore.doc.objects` | ids, kinds, parents, transforms, group children | +| `scene_add` | W | `SceneStore.create` | transform, colour, material, light, lens, parent in one call | +| `scene_add_many` | W | `newObject`, `SceneStore.add` | up to 500 in one undo step; `ref` lets later items parent to an earlier group | +| `scene_update` | W | `update`, `reparent`, `setAspect`, `setSkybox`, `setSun`, `setActiveCamera`, `setPrompt` | | +| `scene_delete` | D | `SceneStore.remove` | | +| `scene_select` | W | `SceneStore.select` | no other tool needs a selection | +| `scene_group`, `scene_ungroup` | W, D | `group`, `ungroup` | | +| `scene_camera` | W | `update`, `setActiveCamera`, `lookAtEuler` | active, lens, position, look-at | +| `scene_mode` | W | `EditorState.setMode` | keeps the selection | +| `scene_timeline_get` | R | `doc.timeline` | keys with ids, times, transforms, eases | +| `scene_keys_set` | W | `engine/scene/tl-batch.addKeys`, `commitTimeline` | batch, one undo step, any mode, no selection | +| `scene_keys_delete` | D | `tl-batch.removeKeys` | by key id, time range or all | +| `scene_timeline_set` | W | `setDuration`, `tl-batch.setRate`, `EditorState.setPlayhead` | duration, fps, playhead | +| `scene_capture` | W | `ui/scene/generate/frame.captureFrame` | keeps the still in the library unless `save` is false; image block | +| `scene_record_start` | W | command `scene.record` (`ui/scene/output/controller`) | switches to Record mode itself | +| `scene_record_status` | R | `EditorState.busy`, newest library video | `waitSec` up to 80 | +| `scene_record_stop` | W | command `scene.cancelOutput` | | +| `scene_save` | W | `SceneFiles.save`, `createProject` | `name` for a first save; `path` also exports | +| `scene_export` | W | `exportProject` | `.fcrft`; path checked against the write roots | +| `scene_open` | D | `SceneFiles.openId`, `importProjectPath` | `saveFirst` or `discardChanges` when unsaved | +| `scene_schema` | R | static | scene, object, key and `.fcrft` formats | | `canvas_state` | R | `CanvasStore` summary | | | `canvas_add_image` | W | `CanvasStore` node add | no raw strokes | | `board_state` | R | `BoardStore` summary | | diff --git a/.docs/wiki/Agents-and-MCP.md b/.docs/wiki/Agents-and-MCP.md index 38bad5e..ecddc12 100644 --- a/.docs/wiki/Agents-and-MCP.md +++ b/.docs/wiki/Agents-and-MCP.md @@ -14,7 +14,7 @@ The server speaks two protocol generations: the stateless `2026-07-28` revision ## Engine tools and window tools -Engine tools work with the window closed. Window tools need the app open and answer `window_required` when no window is polling, and within a few seconds after the window closes or reloads, instead of waiting out the call limit (90 seconds; longer for `edit_export` and `scene_capture`). Tool names are frozen. +Engine tools work with the window closed. Window tools need the app open and answer `window_required` when no window is polling, and within a few seconds after the window closes or reloads, instead of waiting out the call limit (90 seconds; longer for `edit_export`, `scene_capture`, `scene_save`, `scene_export`, `scene_open` and `scene_record_start`). Tool names are frozen. | Group | Tools | | --- | --- | @@ -25,9 +25,11 @@ Engine tools work with the window closed. Window tools need the app open and ans | Projects and packs | `projects_list`, `projects_get`, `projects_create`, `projects_update`, `projects_export`, `projects_import`, `projects_delete`, `sounds_list`, `sounds_import`, `starter_pack_status`, `starter_pack_install` | | Window: commands | `commands_list`, `command_describe`, `command_run`, `studio_state`, `studio_open` | | Window: Edit | `edit_state`, `edit_add_media`, `edit_add_text`, `edit_move`, `edit_trim`, `edit_split`, `edit_remove`, `edit_set_param`, `edit_toggle_key`, `edit_set_speed`, `edit_add_effect`, `edit_set_mask`, `edit_bookmark`, `edit_settings`, `edit_undo`, `edit_redo`, `edit_export` | -| Window: Scene, Canvas, Board | `scene_state`, `scene_add`, `scene_update`, `scene_capture`, `canvas_state`, `canvas_add_image`, `board_state`, `board_add_items` | +| Window: Scene build | `scene_schema`, `scene_state`, `scene_list_objects`, `scene_add`, `scene_add_many`, `scene_update`, `scene_delete`, `scene_select`, `scene_group`, `scene_ungroup`, `scene_camera` | +| Window: Scene animation and output | `scene_mode`, `scene_timeline_get`, `scene_keys_set`, `scene_keys_delete`, `scene_timeline_set`, `scene_capture`, `scene_record_start`, `scene_record_status`, `scene_record_stop`, `scene_save`, `scene_export`, `scene_open` | +| Window: Canvas, Board | `canvas_state`, `canvas_add_image`, `board_state`, `board_add_items` | -Every tool has a title, a description and the four annotation hints (read-only, destructive, idempotent, open-world). `commands_list` shows the same command catalogue the window uses, with a description, parameters, whether the command changes anything and whether it is risky. Prefer a command over a low-level tool when one exists. Window tools appear in `tools/list` once the window has mirrored them; a change fires `notifications/tools/list_changed`. +That is 44 engine tools and 49 window tools. Every tool has a title, a description and the four annotation hints (read-only, destructive, idempotent, open-world); a tool that writes anything, a library item included, is never marked read-only. `commands_list` shows the same command catalogue the window uses, with a description, parameters, whether the command changes anything and whether it is risky. Prefer a studio tool over a command: commands follow what is selected and open in the window, the tools do not. The scene tools need no selection, open panel or mode: `scene_keys_set` keys any object at any time in one batch, `scene_record_start` switches to Record mode by itself and keeps the selection, and `scene_schema` describes the scene, keyframe and `.fcrft` formats so an agent never has to read the app's code. Materials are arguments, not separate tools: `scene_add`, `scene_add_many` and `scene_update` take `metalness`, `roughness`, `opacity`, `emissive`, `emissiveStrength`, `tiling`, `colorMapId`, `normalMapId`, `roughnessMapId` and `materialMediaId` (a material from the starter library, by its library id), and `scene_update` also takes `envMapId`, `envIntensity`, `envRotation` and `envBackground` for the saved environment image. When a command cannot run, `command_describe` and `command_run` say which condition is missing and name the tool to call instead. Window tools appear in `tools/list` once the window has mirrored them; a change fires `notifications/tools/list_changed`. Never exposed: provider keys (reading, writing or testing them), engine settings, encode sessions, cover uploads and the agent routes themselves. @@ -35,14 +37,48 @@ Never exposed: provider keys (reading, writing or testing them), engine settings - Master switch: Preferences, Agents, "Let outside agents use formcraft". It is the engine setting `agentsAllowed` and is off by default. While it is off every agent call is refused. - Token: a random token in the file `agent.token` in the data folder, readable only by you. `formcraft mcp` reads it (or takes `FORMCRAFT_MCP_TOKEN`) and sends it as a bearer token to `/mcp`. Rotate it in Preferences, Agents; the token itself is never shown or returned. -- Policy per client: each client (by the name it reports when it connects) is set to allow, ask or deny. -- Ask: risky actions always ask in the window and wait up to 120 seconds. Risky means `generate`, `library_delete`, `projects_delete`, `library_import`, `starter_pack_install`, `library_save_copy` or `projects_export` with `overwrite`, and `command_run` for a command marked risky. With no window open a risky call is refused. If the agent gives up while the prompt is showing, the prompt closes by itself. +- Level per agent: each agent (by the name it reports when it connects) has one of four levels, set in Preferences, Agents, Clients, or from the request card. A fifth choice, Deny, refuses the agent at once with `client_denied`. A new agent starts at Ask every time. - Activity: Preferences, Agents lists the last 200 calls with client, tool, status and time, and a Stop button that cancels every pending bridged call. - Secrets never appear in results, resources, logs or errors. +### Levels + +| Level | What it does | +| --- | --- | +| Ask every time | every call that changes anything asks first | +| Ask once per session | the first time an agent uses a tool it asks, and after you allow it the same tool does not ask again until formcraft closes | +| Always allow in this project | changing calls do not ask while that project is the current one (the project you used last). It needs a project to exist, and is kept per project | +| Always allow everywhere | changing calls do not ask, in any project | + +Reading never asks, at any level: the tools marked read-only in `agents/manifest.json` just run. Two kinds of call ask whatever the level, because they spend money or can lose files: `generate`, and the risky calls (`library_delete`, `projects_delete`, `library_import`, `starter_pack_install`, `library_save_copy` or `projects_export` with `overwrite`, and `command_run` for a command marked risky). With no window open, a call that needs an answer is refused with `window_required`. + +### The request card + +A request for an ordinary tool shows as a card in the window. It does not take over the screen: you can keep working, and the studio stays usable underneath. The card names the agent and the action, shows the tool and its first arguments, and says which level is set now. Its buttons: + +| Button | Does | +| --- | --- | +| Allow (Enter) | allows this one call | +| Deny (Esc) | refuses this one call | +| Always allow in this project | allows this call and sets that level for this agent in the open project. Disabled, with the hint "Open or save a project first.", when there is no project yet | +| Stop asking for this session | allows this call and stops asking this agent for ordinary tools until formcraft closes | +| Allow all | appears when more than one request waits, and allows them all | + +When more than one request waits, the card counts them ("2 waiting") and shows the oldest first. The Agents button at the top right of the title bar shows a count of waiting requests and a mark while an agent is running. An unanswered request is refused after about two minutes, and a request the agent gave up on closes by itself. + +Spending and the risky calls above use a dialog instead of the card, because they cannot be granted for ever. The dialog shows the estimated cost when there is one and has a "Remember this choice" box where that is allowed. A remembered `generate` approval covers later generations up to the approved cost. + +### Spending + +Preferences, Agents, Allowed has a switch, "Allow spending without asking", and an amount, "Up to, in dollars per run" (from 0.01 to 1000). With the switch on, a `generate` call whose estimate is at or below the amount runs without asking. A call above the amount still asks. It is off by default. + +### The Allowed list + +Preferences, Agents, Allowed lists every standing permission: always allow everywhere, always allow in a project (with the project's name), remembered choices, and session permissions, each with a Revoke button. Revoke removes just that permission. "Nothing is allowed yet." shows when the list is empty. + ## The cost rule -`generate` costs money. It refuses unless the call carries `acceptCostUsd` at or above the estimate, so the agent must call `plan_generation` or `estimate_cost` first and pass the figure. A remembered generate approval covers later generates up to the approved cost. New agent programs start at Ask. The calls are idempotent by `clientRequestId`. A cancelled World Labs job may still be charged by the provider. +`generate` costs money. It refuses unless the call carries `acceptCostUsd` at or above the estimate, so the agent must call `plan_generation` or `estimate_cost` first and pass the figure. A remembered generate approval covers later generates up to the approved cost, and the spending switch in Preferences, Agents covers any generate up to the amount you set. Neither is turned on for a new agent program: it starts at Ask every time. The calls are idempotent by `clientRequestId`. A cancelled World Labs job may still be charged by the provider. ## Connect a client diff --git a/.docs/wiki/Edit-studio.md b/.docs/wiki/Edit-studio.md index 77e5084..acbd5cb 100644 --- a/.docs/wiki/Edit-studio.md +++ b/.docs/wiki/Edit-studio.md @@ -15,6 +15,11 @@ The Edit studio is a multi-track video editor. An edit is a project: it autosave Move, trim, split (at the playhead, or keeping only the left or right part), ripple, duplicate, extract and recover audio, mute, hide, and change speed with or without keeping pitch. Snapping, a marquee, bookmarks with notes and colours, and zoom are on the toolbar. Keyframe lanes and a curve editor have easing presets and saved curves. Every change undoes in one step. +- In and out points: press I and O to mark a range on the timeline. The status line shows In and Out. Alt+X clears them. Shift+L turns Loop on and off; with Loop on, playback goes back to the start of the range when it reaches the end. +- Fades: drag the grip at either end of a clip to fade in or out. The clip menu has Fade in and out, Dip to black at the cut before, and Remove fades. +- Cut: Mod+X copies the picked clips and removes them, so you can place them again with paste. +- Add media: the add button on the timeline opens a menu with From your files, From library and From starter library. + Default keys, all rebindable in Preferences, Keyboard: | Action | Keys | @@ -22,11 +27,22 @@ Default keys, all rebindable in Preferences, Keyboard: | Play or pause | Space, K | | Seek one second back or forward | J, L | | Next or previous frame | Right arrow, Left arrow | -| Split at the playhead | S | +| Set the in point, set the out point | I, O | +| Clear the in and out points | Alt+X | +| Loop playback on or off | Shift+L | +| Split at the playhead | S, Mod+B | | Split and remove the left or right part | Q, W | +| Cut | Mod+X | | Delete | Backspace, Delete | | Duplicate, undo, redo | Mod+D, Mod+Z, Mod+Shift+Z | | Snapping on or off | N | +| Bookmark | M | +| Zoom in, zoom out, zoom to fit | Equal, Minus, Shift+Z | +| Add or remove a keyframe | Shift+K | + +## Transitions and track controls + +Right-click a clip for Cross dissolve at the cut before or after (Ctrl+T) and Dip to black. A transition shows on the cut with its length, and dragging its edge changes the length. Every track has mute, solo, hide and lock buttons in its header: solo plays only the soloed tracks, and a locked track shows hatched and ignores edits until you unlock it. The Zoom menu under the preview has Full, Half and Quarter quality, which keeps playback smooth on long or heavy cuts and does not change the export. ## Effects and finishing @@ -34,7 +50,7 @@ Blur, nine mask kinds (with feather, invert and stroke), keyframes on any movabl ## Export -Export writes MP4 or WebM to disk and to the library. Exports today are MP4, WebM, PNG and the `.fcrft` project file; there is no GIF, image sequence or mesh export yet. The export panel checks what this computer can encode, in the window or in the engine, and says plainly what is missing. The studio is locked while it renders, Cancel always cleans up, and an export left running when the window closes is stopped. Linux builds need a webview or system ffmpeg with an H.264 encoder for MP4. +Export writes MP4 or WebM to disk and to the library, in the output folder from Preferences, Files and Output, and says "Export finished." when it is done. The format and quality it starts with come from Preferences, Rendering, and the render uses the ffmpeg described there. When FormEncoder is installed, Send to FormEncoder in the export panel and on library items hands the file to it with a preset of your choice. Exports today are MP4, WebM, PNG and the `.fcrft` project file; there is no GIF, image sequence or mesh export yet. The export panel checks what this computer can encode, in the window or in the engine, and says plainly what is missing. The studio is locked while it renders, Cancel always cleans up, and an export left running when the window closes is stopped. Every export also shows in Jobs in the title bar, with Open result when it is done. Linux builds need a webview or system ffmpeg with an H.264 encoder for MP4. ## Bringing media in diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index 7c14118..364f005 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -2,7 +2,7 @@ formcraft is the form family's scene and generation studio. It generates images, video, audio, 3D objects and explorable worlds from your own provider keys, stages them in a 2D canvas, a moodboard and a 3D scene, and cuts the results in a built-in multi-track video editor. Everything lives in a local library on your own computer. There is no account and there are no credits. -Version 0.9.x · Tauri 2 shell, vanilla TypeScript with Vite and Three.js, a Python FastAPI engine · macOS, Windows and Linux · built by two people and their coding agents. +Version 0.10.x · Tauri 2 shell, vanilla TypeScript with Vite and Three.js, a Python FastAPI engine · macOS, Windows and Linux · built by two people and their coding agents. The source of truth for this wiki is `.docs/wiki/` in the code repository. Edit it there, in the same change as the code it describes, and publish it to the GitHub wiki. Do not edit pages in the GitHub web interface: the next publish overwrites them. @@ -14,10 +14,12 @@ formcraft is released and still being actively developed and tested. The table s | --- | --- | --- | | Create (Image, Video, Audio, 3D object, World) | Built, in testing | Checked against the providers' published schemas and a mock of their services. No run against the real fal or World Labs services from the build environment | | Canvas, Board | Built, in testing | Checked in Chromium and against the engine | -| Scene studio | Built, in testing | Software rendering only. Recording to MP4 on Linux needs an H.264 encoder | +| Scene studio | Built, in testing | Software rendering only. The 0.10 docked layout, navigation, display modes and frame-by-frame recording have not been run on a real Mac or Windows PC. Recording needs an H.264 encoder | | Edit studio | Built, in testing | Checked in Chromium. Not yet on WebKitGTK, WKWebView or WebView2, or with real H.264 sources | | Library, projects (`.fcrft`) | Stable on Linux | Import is hardened and exports are atomic. Not yet run on a real Mac or Windows PC | -| Agents (MCP) | Released in 0.9.x, in testing | Checked with a protocol-level client. No run with a real Claude Code, Claude Desktop, Codex, Cursor or Antigravity session yet | +| Saving, autosave, keys in the system keyring | New in 0.10, in testing | The native Save dialog, Reveal, recovery after a crash and the Keychain and Credential Manager paths have not been run on a real Mac or Windows PC | +| Starter library and demos | New in 0.10, in testing | 31 CC0 packs and 6 demos are read by the engine. They have not been through a real installer yet | +| Agents (MCP) | Released in 0.9.x, in testing | Checked with a protocol-level client. No run with a real Claude Code, Claude Desktop, Codex, Cursor or Antigravity session yet. The 0.10 approval levels and the 93 tools are newly added | | In-app updater | Released in 0.9.x, not live | Needs the owner's signing key and a published update feed | | Installers and release | Contract written, not run | A release build has not been made on macOS or Windows. See [[Packaging-and-Release]] | @@ -27,7 +29,11 @@ formcraft is released and still being actively developed and tested. The table s | --- | --- | | Install and start formcraft | [[Install]] | | Know what each studio does | [[Studios]] | +| Stage, move around and record a 3D scene | [[Scene-studio]] | | Cut a video | [[Edit-studio]] | +| Start from a demo or the free CC0 starter library | [[Starter-library-and-demos]] | +| Find or change a keyboard shortcut | [[Keyboard-shortcuts]] | +| Set the output folder, file names, ffmpeg or FormEncoder | [[Preferences]] | | Let Claude Code, Claude Desktop, Codex, Cursor or Antigravity drive formcraft | [[Agents-and-MCP]] | | Save, move and open `.fcrft` project files | [[Projects-and-files]] | | Add fal and World Labs keys | [[Providers-and-keys]] | diff --git a/.docs/wiki/Install.md b/.docs/wiki/Install.md index 62c0d50..0d1efa4 100644 --- a/.docs/wiki/Install.md +++ b/.docs/wiki/Install.md @@ -6,7 +6,7 @@ There are two ways to get formcraft: install the desktop app that formcompiler b Installers are produced for macOS (dmg, macOS 14 or newer), Windows (NSIS, Windows 10 or newer) and Linux (AppImage and deb, glibc 2.35 or newer). FormPortal lists formcraft once a release exists, installs it, opens `.fcrft` files with it and can connect it to your coding agents (see [[Agents-and-MCP]]). No release has been published yet, so until then build it yourself. So far only the Linux build has been built and opened. The release pipeline produces the macOS and Windows builds, and they are newly tested. -On first start formcraft downloads the LGPL build of ffmpeg once and checks it file by file, unless another form app already installed one. +On first start formcraft downloads the LGPL build of ffmpeg once from the Form family's formai-binaries releases and checks it file by file, unless another form app already installed one. Preferences, Rendering shows which ffmpeg is in use and can check or download it again. The first window opens a three-step welcome, and the installer carries the starter library (about 43 MB) and the demo projects, see [[Starter-library-and-demos]]. ## Run from the repository @@ -55,6 +55,8 @@ The data folder holds `library`, `thumbs`, `downloads`, `db`, `settings` and `lo | `FORMCRAFT_PORT` | engine port (`0` picks a free one) | | `FORMCRAFT_DEV` | `1` runs the engine in dev mode with the dev window allowed | | `FORMCRAFT_FFMPEG_AUTO` | `1` lets a dev engine download ffmpeg; frozen builds download by default | +| `FORMCRAFT_FFMPEG_DIR` | a folder with ffmpeg to use before any other | +| `FORMCRAFT_STARTER_DIR`, `FORMCRAFT_DEMOS_DIR` | where the engine looks for the starter library and the demos, before the app's own folders | | `FORMCRAFT_BOOT_WAIT` | seconds `boot` waits for each server (default 60) | | `FORMCRAFT_LOG_LEVEL`, `FORMCRAFT_LOG_BYTES` | engine log level and rotation size | | `FORMCRAFT_PARENT_PID` | an engine exits when this process does (set by the shell and by `formcraft mcp`) | diff --git a/.docs/wiki/Keyboard-shortcuts.md b/.docs/wiki/Keyboard-shortcuts.md new file mode 100644 index 0000000..2f029bc --- /dev/null +++ b/.docs/wiki/Keyboard-shortcuts.md @@ -0,0 +1,117 @@ +# Keyboard shortcuts + +Every action in formcraft has a name, a group and, for most, a default key. Preferences, Keyboard lists them all. In these tables Mod means Ctrl on Windows and Linux and Command on a Mac. + +## Find a shortcut + +- Hold Ctrl (Command on a Mac) on its own for a moment and the cheatsheet appears. It lists the keys of the studio you are in, and in the Scene studio the keys of the mode you are in (Build or Record). Let go and it closes. The hold time is set in Preferences, Keyboard, from 1 to 5 seconds (1 by default). +- Press Keep open on the cheatsheet to leave it up until Esc. Change shortcuts opens Preferences, Keyboard. +- Help, Shortcut Cheatsheet opens it from the menu, and Help, Keyboard Shortcuts opens the settings. +- Search commands (the magnifier in the title bar) finds every action by name and shows its key. + +## Change a shortcut + +In Preferences, Keyboard: + +1. Search for the action by name or by key, or press the key combination to look for it. +2. Press Record next to the action and press the new keys. Esc cancels. +3. If another action already uses those keys, formcraft says which one. Choose Swap to exchange the keys, Rebind anyway to take them, or Cancel. + +Reset sets one action, one section or everything back to the preset. Changed from the preset marks the actions you changed. + +## Presets + +A preset is a starting set of keys. Choose it at the top of Preferences, Keyboard. Your own changes stay on top of the preset. + +| Preset | What it changes | +| --- | --- | +| FormCraft | the defaults: W A S D fly the Scene camera, T R G are the move, rotate and scale tools | +| Blender-like | G grabs with an axis lock, R rotates, S scales, Shift+A adds, X deletes, Z opens the display menu, Tab switches mode, N and T show panels, the numpad sets the view | +| Maya/Unity-like | W moves, E rotates, R scales, F frames the selection, Alt-drag orbits, the camera flies on the numpad | + +## Import and export + +Export writes your changes and the preset you chose to a small JSON file. Import reads such a file, replaces your changes with the ones in it, and says how many it took. A file that is not a formcraft shortcuts file is refused with a message and nothing changes. Use this to move your keys to another computer. + +## Everywhere + +| Action | Keys | +| --- | --- | +| Studios Create, Canvas, Scene, Board, Edit, Library | Mod+1 to Mod+6 | +| New project, Open project | Mod+N, Mod+O | +| Save, Save As | Mod+S, Mod+Shift+S | +| Close the project in the studio | Mod+W | +| Preferences | Mod+Comma | +| Show or hide Agents | Mod+Backquote | +| Show or hide the Scene panels | Mod+Backslash | +| Quit | Mod+Q | + +## Scene studio + +These are the FormCraft preset keys. Some act only in Build mode or only in Record mode. + +| Action | Keys | +| --- | --- | +| Fly the camera | W A S D, Q down, E up. Arrow keys look around | +| Move, rotate, scale tool | T, R, G | +| World or local space, pose mode, snapping | X, K, N | +| Frame the selection, frame everything | F | +| Reset the view | Home | +| Front, right, top view | 1, 3, 7 (number row or numpad) | +| Back, left, bottom view | Alt+1, Alt+3, Alt+7, or Mod+numpad 1, 3, 7 | +| Perspective or orthographic | 5 | +| Display menu, wireframe on or off | Z, Shift+Z | +| Show or hide the grid | H | +| Look through the camera, play or pause | Space | +| Add from presets | B | +| Undo, redo, copy, paste, duplicate | Mod+Z, Mod+Shift+Z, Mod+C, Mod+V, Mod+D | +| Group, ungroup | Mod+G, Mod+Shift+G | +| Delete | Delete, Backspace | +| Save, save a copy | Mod+S, Mod+Shift+S | +| Show or hide the timeline | Shift+T | +| Key the transform | I | +| Switch between Build and Record | Tab | +| Capture a still, record | C, R (Record mode) | +| Stop a capture or recording | Esc | + +## Edit studio + +| Action | Keys | +| --- | --- | +| Play or pause | Space, K | +| Seek one second back or forward | J, L | +| Next or previous frame | Right arrow, Left arrow | +| Set the in point, set the out point | I, O | +| Clear the in and out points | Alt+X | +| Loop playback on or off | Shift+L | +| Split at the playhead | S, Mod+B | +| Cut | Mod+X | +| Delete | Backspace, Delete | +| Duplicate, undo, redo | Mod+D, Mod+Z, Mod+Shift+Z | +| Snapping on or off | N | +| Bookmark | M | +| Zoom in, zoom out, zoom to fit | Equal, Minus, Shift+Z | +| Add or remove a keyframe | Shift+K | + +## Canvas and Board + +| Action | Keys | +| --- | --- | +| Canvas: fit to screen, zoom to 100 percent | Mod+0, Mod+1 | +| Canvas: export as PNG, copy the image | Mod+Shift+E, Mod+Shift+C | +| Board: undo, redo in the grid | Mod+Z, Mod+Shift+Z | +| Board: export the board as a picture (free canvas) | Mod+Shift+E | + +## Source map + +| Path | What lives there | +| --- | --- | +| `frontend/src/engine/shortcuts.ts` | the registry, overrides, import and export | +| `frontend/src/engine/shortcut-presets.ts` | the three presets | +| `frontend/src/ui/keybinds-panel.ts` | Preferences, Keyboard | +| `frontend/src/ui/cheatsheet.ts` | the cheatsheet | + +## Contract + +- An action is registered once, with its default keys. Presets and your changes only override keys, never add actions. +- The cheatsheet, Preferences and the agent command catalogue read the same registry. diff --git a/.docs/wiki/Packaging-and-Release.md b/.docs/wiki/Packaging-and-Release.md index cac8435..85e2fb4 100644 --- a/.docs/wiki/Packaging-and-Release.md +++ b/.docs/wiki/Packaging-and-Release.md @@ -47,7 +47,7 @@ Day-to-day work happens on `main`. A release is cut by pushing a branch named `c python3 setup/package_desktop.py linux-tar # a tarball of the deb's files, Linux only ``` -`desktop build` builds the window, freezes the engine with PyInstaller (it runs `--selfcheck` on the result), copies it beside the shell and runs `tauri build`. Installers are AppImage and deb on Linux (no rpm), dmg on macOS and NSIS on Windows. `LICENSE`, `NOTICE` and `LICENSES.md` ship inside the bundle. +`desktop build` builds the window, freezes the engine with PyInstaller (it runs `--selfcheck` on the result), copies it beside the shell and runs `tauri build`. Installers are AppImage and deb on Linux (no rpm), dmg on macOS and NSIS on Windows. `LICENSE`, `NOTICE` and `LICENSES.md` ship inside the bundle, and so do `assets/starter/` (as `starter/`, about 43 MB) and `assets/demos/` (as `demos/`), through `bundle.resources` in `src-tauri/tauri.conf.json`. On macOS a quit with the Command+Q key closes the window first, so the unsaved-changes question is asked. ## Notes and the MCP bundle diff --git a/.docs/wiki/Preferences.md b/.docs/wiki/Preferences.md new file mode 100644 index 0000000..6d70067 --- /dev/null +++ b/.docs/wiki/Preferences.md @@ -0,0 +1,47 @@ +# Preferences + +Open Preferences with Mod+Comma or the gear in the title bar. Settings are kept on this computer. The engine keeps the ones that change what it does (the output folder, agents, the file name template) and the window keeps the ones that change how it looks. + +| Section | What is in it | +| --- | --- | +| General | what shows at start (Home, or the studio you used last), how Enter works in prompt boxes, and Reset, which puts every preference back and keeps your library and projects | +| Interface | theme, accent and its intensity, light and dark choices, match the system appearance, language (English for now), interface scale, reduced motion | +| Workspace | keeps the page you last used in each studio | +| Generation | images per run, asking before a run that costs a dollar or more, what to do when a model does not offer a size or length, how the model picker lists models | +| Connections | the fal and World Labs keys, with Save or Replace, Test and Remove, and a line under each key that says where it is kept | +| Files and Output | the output folder and the file name template, see below | +| Library and Files | where the engine's data folder is (the library, thumbnails, jobs, logs) | +| Rendering | the ffmpeg in use, the default video format and quality, FormEncoder, see below | +| Performance | nothing to set yet | +| Keyboard | cheatsheet hold time, presets, your shortcuts, import and export, see [[Keyboard-shortcuts]] | +| Alerts and Sounds | short tones for events, off until you turn them on | +| Agents | the switch, the token, each agent's level, spending, the Allowed list, recent calls and setup, see [[Agents-and-MCP]] | +| Updates | the version, and updating when the build has an update feed | + +## Connections: where a key is kept + +Under each key a line says where it is stored: "Stored in macOS Keychain", "Stored in Windows Credential Manager", "Stored in your system keyring" (the Secret Service on Linux), "Stored in KWallet", or "Stored in a file only you can read" when the computer has no keyring. Before a key is saved the line says where it will go. If an older version left a key in the private file and the computer has a keyring, formcraft moves the key into the keyring the first time it reads it, without asking, and clears the file entry once the keyring returns the same key. If the keyring will not take it, the key stays in the file and keeps working. The key itself is never shown. See [[Providers-and-keys]]. + +## Files and Output + +- Output folder: where finished files are saved. Change opens a folder picker in the desktop app (in a browser, type the path). Open shows the folder in your file manager. Use default goes back to the standard folder. A file that already exists is never replaced: a number is added. +- Ask where to save each time: with it on, each file asks for its place. With it off, files go to the output folder. +- Save every finished result automatically: with it on, results are copied to the output folder as they finish. With it off, they stay in the library until you save them. +- File name template: type a name made of tokens, or click a token to insert it. The tokens are `{date}`, `{time}`, `{model}`, `{prompt}` (the first words), `{kind}`, `{project}`, `{seed}` and `{n}` (the number in a batch). The file type is added for you. Leave it empty for the standard name, model and date. A preview shows the name you would get, and a problem with the template is shown under it. Use standard name clears it. + +File, Open Output Folder opens the output folder from the menu. + +## Rendering + +- ffmpeg: formcraft runs ffmpeg as a separate program. It looks for a copy bundled with the app, then the Form family download (formai-binaries), then one installed on the computer, then one shared by another Form app. The section shows which one is in use, its version, its path and whether it matches the family record (Matches, Differs, or Not recorded). Check binaries looks again. Download ffmpeg fetches the family build and checks every file against the record. +- Output: the format (MP4 or WebM) and quality the Edit export starts with. You can still change them in the export panel. +- FormEncoder: turns on Send to FormEncoder in the Edit export and on library items. The section says whether FormEncoder is open, installed or missing. + +## Source map + +| Path | What lives there | +| --- | --- | +| `frontend/src/ui/prefs-dialog.ts` | the sections | +| `frontend/src/ui/panels/files-output.ts`, `output-files.ts` | Files and Output | +| `frontend/src/ui/rendering.ts` | Rendering and Send to FormEncoder | +| `backend/app/services/binaries.py`, `render.py`, `formencoder.py` | the ffmpeg lookup, the render job, the FormEncoder hand-off | diff --git a/.docs/wiki/Projects-and-files.md b/.docs/wiki/Projects-and-files.md index 659a486..e72a6ac 100644 --- a/.docs/wiki/Projects-and-files.md +++ b/.docs/wiki/Projects-and-files.md @@ -14,16 +14,42 @@ A `.fcrft` file is a zip archive. Export writes to a hidden `.part` file and then renames it, so a failed export never leaves a half-written project. Import is hardened: it checks the manifest, limits the number of entries, sizes and compression ratios, rejects paths that leave the archive, and keeps the id of media that is identical to media already in your library. A scene exported and opened on another computer keeps its characters' reference pictures. An export also writes `.preview.webp` beside the project (at most 256 KB, made from the cover) so FormPortal can show a preview. -## Open, save and move +## Open and move -- New Project and Open Project are in the File menu (Mod+N, Mod+O); the desktop app uses a native dialog. Home lists recent projects. +- New Project and Open Project are in the File menu (Mod+N, Mod+O); the desktop app uses a native dialog. Open Recent lists up to eight projects you opened last, and Home lists recent projects. - Double-click a `.fcrft` in your file manager, or drop it on the window. A second launch hands the file to the running window (single instance). -- Export from a studio's file menu to write a `.fcrft` anywhere. Save as copy never overwrites an existing file. -- Closing a window with unsaved work asks first. Boards and edits save themselves, and the close waits for the last save. + +## Save + +The File menu in the Scene, Canvas, Edit and Board studios has these entries, and the title bar has a label that says where the project stands. + +| Entry | Keys | What it does | +| --- | --- | --- | +| Save | Mod+S | writes the project to its `.fcrft` file. The first time, the desktop app opens a native Save dialog. After that it writes to the same file without asking | +| Save As... | Mod+Shift+S | asks for a new file and the project then belongs to it | +| Save a Copy... | | writes a copy to a file you choose and keeps working on the original | +| Export... | | in the Scene and Edit studios, goes to the video export. In Canvas and Board, saves a copy | +| Reveal in Finder, Show in Explorer, Show in Folder | | shows the saved file in your file manager. Disabled until the project has a file | +| Open Output Folder | | shows the folder where finished renders and downloads go | +| Close | Mod+W | closes the project in the studio, asking first if it has unsaved changes. Not in Board | + +- The title bar label reads Saved, Edited or Saving. Click it to show the file. Its tooltip is the path of the file, or "Not saved to a file yet". +- Save a Copy never changes which file the project belongs to. Save and Save As do. +- The dialog starts in the folder you saved to last, and adds `.fcrft` if you leave it off. A failed save says why and offers Try again. A project with nothing in it says to add something first. +- In a browser there is no native dialog. Save writes into the data folder, in `projects`, or next to the project's earlier file. +- A save no longer writes a file to your Downloads folder. + +## Autosave and crash recovery + +Scenes and canvases that have unsaved changes are copied to the data folder about four seconds after you stop changing them, and when the window loses focus or is hidden. A clean close, or a save, removes the copy. If formcraft closes any other way, the next start asks "Restore unsaved changes": Restore opens the work as a new project named "(recovered)", Discard throws the copy away, and closing the dialog keeps it for next time. Boards and edits save themselves as you work. + +## Closing + +Closing the window with unsaved work asks first: Save, Discard changes or Cancel. Cancel keeps the window open. On a Mac, Command+Q and Quit in the app menu go through the same question, so a quit cannot skip it. Boards and edits save themselves, and the close waits for the last save. ## Media -Imports and results go into one content-addressed library under the data folder, so the same file is stored once. Downloads and saved copies follow the naming scheme in Preferences, Library and Files and never overwrite. +Imports and results go into one content-addressed library under the data folder, so the same file is stored once. Downloads and saved copies follow the output folder and file name template in Preferences, Files and Output, and never overwrite. See [[Preferences]]. ## Agents @@ -34,7 +60,9 @@ Imports and results go into one content-addressed library under the data folder, | Path | What lives there | | --- | --- | | `backend/app/services/projects.py` | kinds, export, import, covers | -| `backend/app/routers/projects.py` | `/api/projects` routes | +| `backend/app/routers/projects.py` | `/api/projects` routes, and `/api/autosave` for the recovery copies | +| `frontend/src/ui/projects/file-commands.ts`, `disk.ts`, `autosave.ts` | the File menu commands, writing a file, the recovery copy | +| `frontend/src/ui/save-label.ts` | the Saved, Edited and Saving label in the title bar | | `backend/app/services/media.py`, `library.py` | the content-addressed library | | `src-tauri/src/opens.rs`, `instance.rs` | open by argument, single instance | | `src-tauri/linux/` | MIME type and desktop file for `.fcrft` | diff --git a/.docs/wiki/Providers-and-keys.md b/.docs/wiki/Providers-and-keys.md index ba43dad..86857ab 100644 --- a/.docs/wiki/Providers-and-keys.md +++ b/.docs/wiki/Providers-and-keys.md @@ -11,13 +11,15 @@ formcraft generates through two cloud services, using their official APIs and yo 1. Open Preferences (Mod+Comma), then Connections. 2. Paste the key for fal, and for World Labs if you want worlds, and save. -3. Press Test. formcraft asks the provider to confirm the key and says plainly if it was refused. +3. Press Test. formcraft asks the provider to confirm the key and says plainly if it was refused. Save becomes Replace once a key is set, and Remove deletes it. -The engine stores the key in the system password store (Keychain, Credential Manager or the Secret Service) under the service name `formcraft` when there is one. When there is none, it keeps the key in a private file that only your user can read. The window never holds a key after you save it, and a key is never written to a project, a log or an environment variable. Removing a key in Connections deletes it from the store. +You can also add a key without leaving your work. When you press Generate (the button reads Add key) and the model's provider has no key, a key sheet opens over the prompt box with a link to the provider's key page, a field with Paste, Test, and Save and generate, which saves the key and starts the run. Cancel or Esc closes it and keeps your prompt. + +The engine stores the key in the system password store (Keychain, Credential Manager or the Secret Service) under the service name `formcraft` when there is one. When there is none, it keeps the key in a private file that only your user can read. The window never holds a key after you save it, and a key is never written to a project, a log or an environment variable. Removing a key in Connections deletes it from the store. Under each key, Connections says where that key is kept ("Stored in macOS Keychain", "Stored in Windows Credential Manager", "Stored in your system keyring", "Stored in KWallet" or "Stored in a file only you can read"), and before you save one it says where the key will go. A key that an older version left in the private file moves into the system keyring the first time the engine reads it, with no prompt, and the file entry is cleared only after the keyring gives the same key back. If the keyring will not take it, the key stays in the file and keeps working. ## Cost -Every run shows a dollar estimate before it starts, labelled as an estimate. The provider sets the final charge. Preferences, Generation can ask before runs estimated at one dollar or more, and sets what happens when you ask for a size or length the model does not offer (upgrade, downgrade, or stop and tell you). Agents must pass the estimate back before `generate` runs, see [[Agents-and-MCP]]. +Every run shows a dollar estimate before it starts, labelled as an estimate. The provider sets the final charge. Preferences, Generation can ask before runs estimated at one dollar or more, and sets what happens when you ask for a size or length the model does not offer (upgrade, downgrade, or stop and tell you). Agents must pass the estimate back before `generate` runs, and `generate` asks you unless you set a spending limit for agents, see [[Agents-and-MCP]]. ## The model catalogue diff --git a/.docs/wiki/Scene-studio.md b/.docs/wiki/Scene-studio.md new file mode 100644 index 0000000..88da446 --- /dev/null +++ b/.docs/wiki/Scene-studio.md @@ -0,0 +1,112 @@ +# Scene studio + +The Scene studio is a 3D stage. You block out a shot with models, lights and cameras, then take a still or record the timeline to video. Agents can do all of it too, see [[Agents-and-MCP]]. + +## Layout + +The studio is docked. The outliner is on the left, the inspector is on the right, the viewport fills the middle, and the timeline and the media strip sit below it. Nothing floats over the viewport. + +| Part | What it does | +| --- | --- | +| Outliner (left) | the objects in the scene, with groups. Width 200 to 420 pixels, 260 by default | +| Inspector (right) | the settings of the selected object. When nothing is selected it shows a hint. Width 260 to 480 pixels, 300 by default | +| Grips | the thin bars between the columns and the viewport | +| Timeline and media strip | the keyframe timeline and the library strip under the viewport | + +To change the layout: + +- Drag a grip to resize a column. Focus a grip and press the left or right arrow keys to move it in steps of 16 pixels. +- Double-click a grip to put that column back to its default width. +- Click the small arrow on a grip to fold the column away, and again to bring it back. +- View, Show Panels (Mod+Backslash) hides or shows the panels at once. +- File menu of the scene, Reset layout, puts widths and folds back to the defaults. + +The layout is remembered on this computer, not in the project. In Record mode the grips are hidden and the controls for Capture and Record take the top of the viewport. + +## Moving around + +Navigation follows the common 3D editor conventions. The Navigation button (the question mark under the axis gizmo) lists them in the app and holds three settings: Trackpad mode, Invert zoom and Orbit speed. Trackpad mode is on by default on a Mac. + +| Action | Mouse | Keyboard | +| --- | --- | --- | +| Orbit | left drag on empty space, or middle drag | | +| Pan | Shift and middle drag, or hold Space and drag | in trackpad mode, two-finger scroll | +| Zoom | scroll wheel, toward the pointer | in trackpad mode, pinch | +| Zoom by drag | Ctrl or Command and middle drag | | +| Fly | hold the right button, then move the mouse to look | W A S D to move, Q and E for down and up. Scroll while flying to change speed | +| Frame the selection | double-click an object | F. With nothing selected, F frames everything | +| Reset the view | the Home button | Home | +| Select | click an object | | +| Look through the camera | | Space (Space plays and pauses while the timeline is in use) | + +In trackpad mode, hold Alt (Option on a Mac) and scroll to orbit. + +### View presets and orthographic + +The axis gizmo at the top right of the viewport shows where the view is pointing. Click an axis dot to snap to that side. + +| View | Keys | +| --- | --- | +| Front, Right, Top | 1, 3, 7 on the number row or the numpad | +| Back, Left, Bottom | Alt+1, Alt+3, Alt+7 (Option on a Mac), or Ctrl+numpad 1, 3, 7 (Command on a Mac) | +| Perspective or orthographic | 5, or the Persp button | + +View presets and Home are off while you look through a camera. The same actions are in the command search and can be rebound in Preferences, Keyboard, see [[Keyboard-shortcuts]]. + +## Display modes + +The Display button opens a menu, and Z opens it from the keyboard. Shift+Z switches wireframe on and off. + +| Group | Choices | +| --- | --- | +| Display | Solid, Wireframe, Solid with wire, Material preview (the default), Bounding box | +| Show | Grid, Axes, Light helpers, Camera helpers, Selection outline, Backface culling | +| Selected object displays as | Viewport setting, Wireframe, Bounding box, Hidden in render | + +The display mode and the overlays are for the viewport only, and they are saved with the scene so it opens the way you left it. "Hidden in render" is the one per-object choice that is meant for output: that object is left out of a still or a recording, but it stays in the scene and in the outliner. + +## Selecting several objects + +Shift or Cmd (Ctrl on Windows and Linux) click in the view or in the outliner adds an object to the selection or takes it out. Shift drag in the view selects everything inside the box, and the Edit menu has Select All and Invert Selection. The gizmo then moves, rotates or scales the whole selection, and the inspector edits the fields the selected objects have in common. Copy, Paste and Duplicate work for every kind of object, lights and cameras included. The snap button on the toolbar shows the current steps (0.1 m, 5 degrees and 0.1 scale to start with), and the arrow beside it changes them. + +## Camera view + +Record mode looks through the active camera. The frame shows the picture area, the title and action safe areas, a rule of thirds and the focal length. Align camera to view, in the camera menu, moves the active camera to where you are looking from. + +## Materials and environment + +Select a shape or a model and open Material in the inspector. You can set colour, metalness, roughness, opacity and glow, pick quick materials, and choose texture maps (colour, normal, roughness) from your library or from the starter library with a tiling control. Under Environment you can choose an HDRI or a panorama picture to light the scene and, if you want, to show as the background, with strength and turn. An environment picture is saved in the scene. A `.hdr` or `.exr` lights it correctly. A tone-mapped picture lights it only approximately. A placed world sets the light itself, so the environment picture applies when the world is removed. + +## Capture and record + +Switch to Record mode with Tab or the mode button. Capture (C) takes a still of the camera view. Record (R) renders the timeline to an MP4. + +- Recording renders each frame of the timeline in order and hands it to the engine's ffmpeg, so the video is exact and does not depend on how fast the window draws. If the engine has no usable encoder, formcraft falls back to the window's own encoder where it has one. +- The frame rate is the timeline's frame rate (1 to 120, 30 by default). The length is the timeline's length, up to 60 seconds. +- While it works, a cover shows Recording with a percentage. Stop is the Cancel button on the cover, or Esc. Stopping always returns: the cover says Stopping, the window waits at most about a second and a half, then you are back in the scene. No video is saved and the scene is as it was. Your playhead goes back to where it was. +- No single step waits for ever. If the engine does not start the encoder, a frame does not pose or draw, or the engine stops taking frames, the recording stops and says which step failed, with a Retry button. +- Also save depth and mask records two more videos beside the main one: a grey depth video and a black and white mask video. They need the engine encoder. If they cannot be made, the main video is still saved and a message says so. +- When it finishes, a review shows the result, and the video is in the library. A message says "Your recording is ready." + +A recording needs an H.264 encoder. On Linux the downloaded ffmpeg has none, so install a system ffmpeg that has one, see [[Troubleshooting]]. + +## Saving + +A scene is a project. File, Save (Mod+S), Save As and Save a Copy are described in [[Projects-and-files]]. The title bar shows Saved, Edited or Saving. A scene with unsaved changes is kept in a recovery copy, and formcraft offers to restore it the next time it starts. + +## Source map + +| Path | What lives there | +| --- | --- | +| `frontend/src/engine/scene/` | the DOM-free scene: `store.ts`, `actions.ts` (the key table), `viewport.ts` (display state), `material.ts`, `env-map.ts`, `tl-batch.ts` (keys in batches) | +| `frontend/src/ui/scene/panels/dock.ts` | the docked columns, grips and Reset layout | +| `frontend/src/ui/scene/view/` | the viewport, navigation, the axis gizmo (`navui.ts`) and the display menu (`display.ts`) | +| `frontend/src/ui/scene/output/` | Capture and Record, the cover, the review | +| `frontend/src/ui/scene/materials/` | the Material and Environment sections | +| `backend/app/services/encode_sessions.py` | the engine side of a recording | + +## Contract + +- A scene action goes through `SCENE_ACTIONS` with a label, group, keys and a gate, so Preferences, the cheatsheet and the agent catalogue see it. +- Display state is the viewport's, never the document's. +- Recording must always be stoppable: every wait has a limit and Stop returns within a moment. diff --git a/.docs/wiki/Starter-library-and-demos.md b/.docs/wiki/Starter-library-and-demos.md new file mode 100644 index 0000000..a93a713 --- /dev/null +++ b/.docs/wiki/Starter-library-and-demos.md @@ -0,0 +1,71 @@ +# Starter library and demos + +formcraft ships with things to start from: a library of free CC0 assets and six demo projects. Neither needs a key. + +## Demos + +Home lists the demos under Demos. Each card has a picture, the studio it opens in and a short description. Open demo makes a copy as a new project in your list, so you can change it and the original is never touched. The first time you start formcraft, the welcome offers Explore without a key, which opens a demo. + +| Demo | Studio | What it shows | +| --- | --- | --- | +| Scifi Corridor Walk | Scene | keyframes, cameras, lights, groups, lens | +| Product Turntable | Scene | keyframes, cameras, three-point lighting, materials | +| Stage the Cast | Scene | mannequins, animation clips, cameras | +| Night Drive Moodboard | Board | notes, colours, sections, ratings | +| Night Horizon Canvas | Canvas | layers, shapes, brush, mask | +| Night Drive Cut | Edit | three clips, an animated title, a crossfade, a fade to black, music | + +The demos are `.fcrft` files in `assets/demos/`, listed with their covers in `assets/demos/demos.json`. They are original to formcraft. A demo that cannot be found says "This demo could not be opened." + +## Starter library + +The starter library is a set of CC0 1.0 assets that ship inside the app. Everything in it is public domain: free for any use, with no credit needed. formcraft records the licence, author and source on every item you add anyway. + +| Kind | Files | What | +| --- | --- | --- | +| 3D models | 27 | Poly Haven models (furniture, props, tools, fruit) as GLB | +| Textures | 258 | 26 Poly Haven and 60 ambientCG PBR materials, shown as 86 materials with their maps | +| HDRI skies | 16 | Poly Haven, as real `.hdr` files with previews | +| Pictures | 176 | 117 works from the Metropolitan Museum of Art, the Cleveland Museum of Art and the Art Institute of Chicago, 10 photographs from Negative Space, 41 Cleveland photographs and 8 colour palettes derived from the textures | +| Video | 46 | 17 archival film clips from the Prelinger Archives and 29 clips generated for formcraft by NodeAgentc, Inc. | +| Audio | 130 | 101 field recordings and foley sounds and 10 music tracks published as CC0 by their creators on the Internet Archive, and 19 sounds generated for formcraft | + +That is 17 packs, 653 items and about 118 MB, which every installer carries. `assets/starter/CREDITS.md` names every pack, its author, its source, its licence evidence and the version it was taken from. + +### Where it comes from + +Every pack comes from its publisher's own website or API: Poly Haven, ambientCG, the Met, the Cleveland Museum of Art, the Art Institute of Chicago, Negative Space, the Prelinger Archives and CC0 audio on the Internet Archive. Nothing comes from a GitHub mirror, and nothing was fetched from a site whose `robots.txt` asks AI agents not to, which is why some earlier packs were taken out. Each licence was confirmed by two statements read on the publisher's site, normally the site-wide licence page and the item's own page or API record naming CC0 for that item. Both addresses and the date are kept in the pack's `pack.json` under `licence_evidence`, the statement as fetched is at the top of its `LICENSE.txt`, and About this asset links to them. The Prelinger clips carry the Creative Commons Public Domain Dedication and show "Public domain dedication"; everything else is CC0 1.0. + +### Using it + +- In the Library studio, choose Starter in the sidebar. In other studios, the Add media menus and the Material and Environment sections have From the starter library, and the command search has Starter library. +- Tabs filter by kind (All, 3D, Textures, HDRIs, Images, Video, Audio). Search by name or tag, and use the category chips. +- Add to library copies the file into your library and keeps the source on the item. Use in current studio places it where you are: a model, picture or clip into the Scene, a texture as the material of the selected object, an HDRI as the scene environment, a picture onto the Canvas, a picture or clip onto a Board, a clip, sound or picture onto the Edit timeline. About this asset shows the pack, author, licence and source. +- Textures that belong together show as one item, and Add to library adds every map. +- 3D models with no picture show a placeholder, then a picture drawn once in the window and kept, so it is instant next time. +- Help, About, Starter library credits lists every pack and its licence. + +If a pack has no CC0 licence text, or an item's file is missing, the engine skips it and writes the reason in its log, and the rest still load. A build with no starter folder says "No starter packs are in this build." + +The two agent tools `starter_pack_status` and `starter_pack_install` belong to the older optional download pack. They do not read the bundled starter library. + +## Source map + +| Path | What lives there | +| --- | --- | +| `assets/starter/` | the packs: `3d`, `2d`, `video`, `audio`, each pack with `pack.json` and `LICENSE.txt` | +| `assets/demos/` | the demo projects, covers and `demos.json` | +| `backend/app/services/starter.py`, `routers/starter.py` | reading the packs and the `/api/starter` routes | +| `backend/app/services/demos.py`, `routers/demos.py` | the `/api/demos` routes and making a copy | +| `frontend/src/ui/library/starter/` | the picker, credits, thumbnails and Use in current studio | +| `frontend/src/ui/home.ts`, `first-run.ts` | the Demos list and the welcome | +| `src-tauri/tauri.conf.json` | the resources that put both folders in the installer | + +## Where the engine looks + +The starter folder: `FORMCRAFT_STARTER_DIR` when set, then the app's resource folder `starter`, then `assets/starter` in a clone. The demos: `FORMCRAFT_DEMOS_DIR` when set, then the app's resource folder `demos`, then `assets/demos` in a clone. The starter folder is kept out of the frozen engine on purpose, because the Linux and Windows engines unpack their data on every start. + +## Contract + +- Only CC0 1.0 content goes into `assets/starter/`. A pack needs `pack.json`, `LICENSE.txt` and a source, and is recorded in `NOTICE` and `LICENSES.md`. +- A demo is original work, made for formcraft, and opens without a key. diff --git a/.docs/wiki/Studios.md b/.docs/wiki/Studios.md index fd0887a..104717a 100644 --- a/.docs/wiki/Studios.md +++ b/.docs/wiki/Studios.md @@ -13,19 +13,19 @@ The window is a set of studios you switch between from the studio switcher, the ## Create -Each page has a prompt box, a model picker, the options that the chosen model really has, references from your files or library, and a feed where runs appear at once and land as results. A dollar estimate shows before every run, and Preferences, Generation can ask before runs of one dollar or more. Characters saved from an image can be mentioned with `@` on the Image and Video pages. Recreate and Make video start a new run from a result. The model catalogue holds 122 models as data in `backend/app/catalogue/data`. +Each page has a prompt box, a model picker, the options that the chosen model really has, references from your files or library, and a feed where runs appear at once and land as results. When a page has many models, the model picker pins your favourites at the top (the star on a model), then the models you used most recently on that page, then the recommended one, then all models. Results in the feed, the lightbox and the library offer the same actions: Recreate, Variations, Edit image, Make video, Remove background, Upscale, Make 3D object, Make 3D world, Add to scene, canvas, board or edit timeline, Use as reference, Download, Show in folder, Copy and Delete, with the ones that fit the kind of file. A dollar estimate shows before every run, and Preferences, Generation can ask before runs of one dollar or more. Characters saved from an image can be mentioned with `@` on the Image and Video pages. Recreate and Make video start a new run from a result. The model catalogue holds 122 models as data in `backend/app/catalogue/data`. ## Canvas -Start from files, the library or a blank canvas in nine sizes. Paint, erase, draw shapes, place pictures and 3D models in layers, and paint an inpainting mask. Generate sends inpainting models the picture and the mask, and edit models the whole composition with your references. Results stay in a strip beside the canvas. +Start from files, the library or a blank canvas in nine sizes. Paint, erase, draw shapes, place pictures and 3D models in layers, and paint an inpainting mask. A docked side panel holds the Layers list (bring forward, send backward, duplicate, delete) and can be hidden, resized or put back with Reset layout. The tool rail also has Text (T), an Eyedropper, Crop and canvas size (C, which can extend the page past the picture), and Rectangle (M) and Lasso (L) selection; a selection bar offers Fill, Clear, Invert, Feather and Selection to mask. Layers have opacity, six blend modes (Normal, Multiply, Screen, Overlay, Darken, Lighten), groups, merge down and merge visible. Above the prompt box are three plain choices for generating: Change the whole image, Change only the masked area, and Extend the image. Generate sends the composed picture and, where it applies, the mask, with your references. A placeholder with Cancel sits over the area being changed, and a review card lets you step through, compare, accept or discard each result. Results stay in a strip beside the canvas. Export or copy the canvas as a PNG (Mod+Shift+E, Mod+Shift+C). ## Scene -Stand inside a World Labs world at true scale or on a set. Place rigged characters and props (generated from a prompt or picture in the scene, or from the CC0 starter pack), pose them, and add up to six cameras. Describe the shot in the prompt bar and Generate from the camera. Capture saves a PNG, Record renders an MP4 at 30 fps, and a still can become a clip. Recording on Linux needs an H.264 encoder in the webview or a system ffmpeg. +Stand inside a World Labs world at true scale or on a set. Place rigged characters and props (generated from a prompt or picture in the scene, or from the CC0 starter library), pose them, and add up to six cameras. Describe the shot in the prompt bar and Generate from the camera. Capture saves a PNG, Record renders an MP4 at the timeline's frame rate, and a still can become a clip. The studio is docked, with resizable columns and a Reset layout, you move around it with orbit, pan, zoom and fly controls and view presets, and objects can show as wireframe or bounding boxes. See [[Scene-studio]] for the controls, the display modes and recording. ## Board -Boards of pictures, videos, notes, colours and links in a fast grid with sections, ratings, tags, search and a palette. Present shows a board full screen, Use as reference sends items to a prompt. A free canvas view adds groups, snapping, Fit to grid, Pack collage and Auto-group. Boards save themselves. +Boards of pictures, videos, notes, colours and links in a fast grid with sections, ratings, tags, search and a palette. The grid has undo and redo. Present shows a board full screen, Use as reference sends items to a prompt, and Make prompt writes a prompt from the board. A free canvas view adds groups, snapping (hold Shift to skip it), Fit to grid, Pack collage and Auto-group. Its Align and arrange menu aligns edges, centres and middles, distributes, duplicates, locks, and draws an arrow between selected items (Shift+C) that follows them when they move; every step can be undone, and Export and send writes the board, the board at double size, or the selection as a picture. Boards save themselves. ## Tools @@ -33,7 +33,15 @@ Tools are single-purpose pages in the studio switcher: Angles (an orbit sphere f ## Library -Folders (nested, coloured, starred), tags, favourites, hidden items, characters, search, sort, marquee selection, a context menu and bulk actions over a grid that stays smooth at ten thousand items. Imports and results are stored by content with thumbnails and posters. Saved copies never overwrite a file. +Folders (nested, coloured, starred), tags, favourites, hidden items, characters, search, sort, marquee selection, a context menu and bulk actions over a grid that stays smooth at ten thousand items. Imports and results are stored by content with thumbnails and posters. Saved copies never overwrite a file. The Starter entry in the sidebar opens the bundled CC0 starter library, see [[Starter-library-and-demos]]. + +## Home, menus and notices + +Home asks "What do you want to make?" and lists Continue (your recent projects), Demos, the Starter library, every studio and tool, and recent files. Click the logo at the top left, from any studio, for one menu of every studio and tool with a line about each. The Agents button at the top right opens the agent dock, and the View menu has Show Agents, Show Panels (Scene), Show Terminal and a Claude Code terminal. The Jobs list in the status bar groups jobs as Running, Waiting, Done and Failed. + +The Jobs button in the title bar (Ctrl+Alt+J) shows a count of running and waiting jobs and opens a short list with Cancel, Retry, Edit prompt, Open result and Recreate; Scene recordings and Edit exports appear there too, and Open full list shows them all. When you press Generate and the model's provider has no key, a key sheet opens over the prompt box: paste the key, Test it and press Save and generate, and your prompt stays as it was if you press Esc. The Media button in Scene, Canvas and Board (or View, Show Library) opens a floating Library window with Library, Starter and Outputs tabs. Move it by its title and resize it from any edge; each studio remembers where you put it. Drag an item onto the studio, or double-click it, to use it there: a starter HDRI becomes the scene environment, a texture the material of the object under it. + +Each studio shows a short tour the first time it opens, one control at a time, and never covers the control it points at. Esc leaves it. Help has Tour This Studio, Getting Started, Open a Demo, What's New, Report a Problem and Show Logs Folder, and Preferences, General, Studio Tours has Show the Tours Again. Notices appear in a strip kept free at the bottom, above the status bar, at most three at a time, so they do not cover the studio. Hovering a notice keeps it up. Hover a button for a tooltip with its shortcut. Menus, tooltips and pop-ups place themselves inside the window, below the title bar and above the status bar, so they do not collide. ## Source map @@ -42,6 +50,8 @@ Folders (nested, coloured, starred), tags, favourites, hidden items, characters, | `frontend/src/app.ts` | the shell, the studio list and the base commands | | `frontend/src/engine/` | DOM-free stores and registries: `studios.ts`, `commands.ts`, `shortcuts.ts`, `scene/`, `canvas/`, `board/`, `edit/` | | `frontend/src/ui/create`, `canvas`, `scene`, `board`, `edit`, `tools`, `library` | the studios' interfaces | +| `frontend/src/ui/home.ts`, `tool-menu.ts`, `first-run.ts` | Home, the all-studios menu and the welcome | +| `frontend/src/ui/position.ts`, `tooltip.ts`, `toasts.ts` | the one placement helper for menus and pop-ups, the one tooltip, and notices | | `backend/app/routers/` | one router per area, for example `generate.py`, `media.py`, `projects.py` | ## Contract for a new studio diff --git a/.docs/wiki/Troubleshooting.md b/.docs/wiki/Troubleshooting.md index 1c8ab21..fc3745e 100644 --- a/.docs/wiki/Troubleshooting.md +++ b/.docs/wiki/Troubleshooting.md @@ -18,6 +18,7 @@ Start with the engine log: `logs/formcraft-engine.log` in the data folder (Prefe | Symptom | Cause and fix | | --- | --- | | Generate is disabled or says no key | add a key in Preferences, Connections and press Test. See [[Providers-and-keys]] | +| Connections says "Stored in a file only you can read" | the computer has no system keyring the engine can use. The key works, and moves to the keyring by itself once one is available | | A run fails with a balance or content message | the provider refused; the Jobs list in the status bar explains it in plain words | | Generate waits for a choice | the model does not offer the size or length you asked for and Preferences, Generation is set to Stop and tell me | | A job stays queued after a restart | jobs recover after a restart without being sent twice; check the status bar's Jobs list, then the log | @@ -27,6 +28,11 @@ Start with the engine log: `logs/formcraft-engine.log` in the data folder (Prefe | Symptom | Cause and fix | | --- | --- | | Export or Record says an encoder is missing | on Linux the bundled LGPL ffmpeg has no H.264 encoder. Install a system ffmpeg with one, or export WebM | +| A recording stops with a message about a step | the message names the step (the encoder, posing a frame, drawing a frame, or the engine taking frames) and offers Retry. Check Preferences, Rendering for the ffmpeg in use, and the engine log | +| A recording is stuck on Stopping | it should return within about two seconds with the scene as it was. If it does not, close and open the window, and send the engine log with the report | +| Also save depth and mask says only the main video was recorded | the depth and mask videos need the engine's encoder. Check Preferences, Rendering | +| Save does nothing, or says the file could not be written | the message says why. Choose another folder with Save As, or check that the folder exists and you may write to it. Save a Copy never changes the project's file | +| formcraft offers to restore unsaved changes at start | it closed without saving a scene or canvas. Restore opens the work as a new project named "(recovered)" | | ffmpeg is downloading at first start | expected once; it is checked file by file. A dev engine only downloads with `FORMCRAFT_FFMPEG_AUTO=1` | | An `.fcrft` will not open | the message names the problem, for example not a formcraft file or unsupported. Files from a newer formcraft may not open in an older one | | Another app's FBX looks wrong | FBX converts to GLB on upload; mark it as object, character, creature, set or animation | @@ -40,7 +46,9 @@ Start with the engine log: `logs/formcraft-engine.log` in the data folder (Prefe | The client shows no tools or a protocol error | something wrote to standard output. Only the launcher may; check that the path points at `formcraft`, not a wrapper script that prints | | A tool answers `window_required` | it needs the open app. Open formcraft and keep its window running | | `generate` refuses with a cost message | pass `acceptCostUsd` at or above the estimate from `plan_generation` | -| A tool waits and then says the call was not approved | the approval prompt in the window was denied or timed out after 120 seconds. A client set to deny is refused at once with `client_denied` | +| A tool waits and then says the call was not approved | the request card was denied or not answered for about two minutes. A client set to deny is refused at once with `client_denied` | +| Agent requests keep coming | set the agent's level in Preferences, Agents: Always allow in this project or Always allow everywhere. Spending and the risky calls (deleting, importing, overwriting) always ask. Turn on "Allow spending without asking" for `generate` up to an amount | +| "Always allow in this project" is greyed out | there is no project yet. Save or open a project first | | The client was rejected after rotating the token | restart the client so `formcraft mcp` reads the new token file | See [[Agents-and-MCP]] for the full setup. diff --git a/.docs/wiki/_Sidebar.md b/.docs/wiki/_Sidebar.md index d72a160..2bf9d10 100644 --- a/.docs/wiki/_Sidebar.md +++ b/.docs/wiki/_Sidebar.md @@ -7,9 +7,13 @@ **Use** - [[Studios]] +- [[Scene-studio]] - [[Edit-studio]] +- [[Starter-library-and-demos]] - [[Projects-and-files]] - [[Providers-and-keys]] +- [[Preferences]] +- [[Keyboard-shortcuts]] **Agents** diff --git a/AGENTS.md b/AGENTS.md index e4b8454..3e72a08 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,4 +2,4 @@ Read `CLAUDE.md` in this folder first. It holds the project summary, the clean-room rules, the build rules and the commit rules, and it applies to every coding agent (Claude Code, Codex, Cursor, Antigravity) working in this repository. -formcraft's MCP server runs over stdio with `./formcraft mcp` (it attaches to the running engine at http://127.0.0.1:8290, or starts a headless one). Configs: `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json`, and for Antigravity `~/.gemini/config/mcp_config.json`. Run `./formcraft agents install` to write them for your home folder and the folder you ran it from, and to install the skills. The skill packs live in `.agents/skills`: `formcraft-driving` (using the app) and `formcraft-harness` (changing this repository). Agents are off until the person turns them on in Preferences, Agents. +formcraft's MCP server runs over stdio with `./formcraft mcp` (it attaches to the running engine at http://127.0.0.1:8290, or starts a headless one). Configs: `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json`, and for Antigravity `~/.gemini/config/mcp_config.json`. Run `./formcraft agents install` to write them for your home folder and the folder you ran it from, and to install the skills. The skill packs live in `.agents/skills`: `formcraft-driving` (using the app) and `formcraft-harness` (changing this repository). Agents are off until the person turns them on in Preferences, Agents. There are 93 tools (44 that work without the window and 49 that need it open). Each agent then asks for approval at the level the person sets there; reading never asks, and spending and risky calls always ask. The scene tools (`scene_add_many`, `scene_keys_set`, `scene_record_start`, `scene_save` and the rest) need no selection or open panel, and `scene_schema` describes the scene and `.fcrft` formats. diff --git a/CHANGELOG.md b/CHANGELOG.md index c314102..f9fb896 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,113 @@ Versions follow `v*.*.*` with dots. Dates are UTC. +## 0.11.0 · 2026-11-29 + +Parity and polish on top of 0.10.0, with the starter library re-sourced from the publishers' own websites. + +### Added + +- Edit: cross dissolves between clips (button on the cut, Ctrl or Cmd+T, drag to change the length), rendered the same in preview and export; fades and dissolves also shape the sound. +- Edit: track lock, solo and drag-to-resize heights, saved with the project; Full, Half and Quarter preview quality; slip (Alt-drag) and slide (Alt+Shift-drag); ripple trim on both edges; play backwards; freeze frame; Lower third, Centred title and End card presets. +- Canvas: a Text tool, an Eyedropper, Crop and canvas size with extend for outpainting, Rectangle and Lasso selection (fill, clear, invert, feather, selection to mask), layer opacity and six blend modes, groups, merge down and merge visible, flip, and a tool rail that folds. +- Canvas: three plain choices for generating (change the whole image, only the masked area, or extend it), a placeholder with Cancel over the area being changed, a review card to step through, compare, accept or discard each result, and Send to Create, Scene, Board or Edit. +- Board: align and distribute, lock, Alt-drag duplicate, arrows that follow their items, extract a palette from a picture, drag to reorder in the grid, a resizable details column, Send to Canvas, Scene or Edit, and export all media of a board. +- Scene: select several objects (Shift or Cmd click, Shift drag, select all, invert), move them together, and edit their common fields at once; copy, paste and duplicate for every kind of object; snap steps shown on the toolbar and editable; safe-area guides in camera view and Align camera to view. Display settings are saved with the scene. +- A Jobs button in the title bar: running and waiting jobs with a count, Cancel, Retry, Edit prompt, Open result and Recreate. Scene recordings and Edit exports appear there too. +- A key sheet on the prompt box: when a model's provider has no key, paste it, test it and press Save and generate, without leaving what you were doing. Preferences, Generation has "Confirm before runs over" an amount. +- A floating Library window (Media button, View, Show Library): move it, resize it, and drag items onto Scene, Canvas, Board or Edit. +- Help: a short guided tour in each studio, Getting Started, Open a Demo, What's New, Report a Problem and Show Logs Folder. +- The full FormCraft icon set: a macOS icon, a document icon for `.fcrft` files, a favicon, a small mark, and the real icon in the title bar, the Home side panel, the welcome and About. +- Starter library: 16 HDRIs as real `.hdr` files, 26 materials and 27 models from Poly Haven; 60 materials from ambientCG; 117 photographs from the Metropolitan Museum of Art, the Cleveland Museum of Art and the Art Institute of Chicago; 10 photographs from Negative Space; 17 archival film clips from the Prelinger Archives; 101 field recordings and foley sounds and 10 music tracks published as CC0 by their creators on the Internet Archive. + +### Changed + +- Home and its side panel follow the Form family layout used by FormDeck: the real icon and "formcraft by nodemode-ai", Start, Recent, Library, Outputs, Demos and Starter library with counts, a Demos page with categories and search, and Local only, Preferences and About at the bottom. +- Every starter pack now comes from its publisher's own website. Each licence is confirmed by two statements read on that publisher's site (the site licence page and the item's own page or record), recorded in the pack with the date. Packs whose files came from GitHub mirrors (Kenney, KayKit, the Khronos samples) or from sites that ask AI agents not to fetch from them (OpenGameArt, Free Nature Stock, and itch.io download links, which removed the Quaternius packs) were taken out. +- The Prelinger clips carry the Creative Commons Public Domain Dedication, shown as "Public domain dedication"; everything else in the starter library is CC0 1.0. +- Snapping in Scene defaults to 0.1 m, 5 degrees and 0.1 scale. +- Board: Shift, not Alt, skips snapping while dragging. + +### Fixed + +- A restored project keeps its current name, not "Untitled scene (recovered)". +- Preferences, Agents shows a project grant under the project's current name after a rename. +- A Scene recording or a generated result identical to an earlier one gets its own library item. +- Keys are no longer read from the system keyring at start-up, which could show Keychain prompts on macOS. A small index of which providers have keys, and their last four characters, is kept instead. +- Download and install refuses while jobs are running. +- Dropped files that are programs or not media are named and left out. +- The Edit welcome card no longer covers the empty timeline. +- The Canvas prompt no longer keeps Generate off after you type a prompt. On short windows it folds to one line so the canvas stays usable. +- After a crop or extend, Canvas generation sends the composed picture and the mask, not the original picture. +- Opening an Edit project or demo no longer shows an empty timeline: the studio started blank while the project was still loading and kept the blank one. +- The Media button was unstyled in Scene, Canvas and Board, the shortcut cheatsheet cut off its right column, and "About this asset" showed broken evidence links. + +### 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. No test was added or changed. +- The built app was driven end to end in a headless browser against the engine at 1440x900 and 1100x700: the welcome and Home, the Demos page, all six demos, every studio's tour and empty state, Scene multi-select, copy and paste, camera view and a recording that showed in Jobs and the library, Canvas text, selection, blend, crop and the key sheet, Board align, arrows and undo, an Edit dissolve with lock, solo and preview quality and an engine MP4 export (H.264, 1280x720, 16 s), the Library window dropping an HDRI on Scene and a photo on Board, the starter browser, every Preferences section and the Help menu. +- Every starter pack validates (17 packs, 653 items, 118 MB): each file opens, sizes match, and each pack records two licence statements from its publisher's own site. Each source's robots.txt was read, and nothing was fetched from a site or path it closes to AI agents. +- A mechanical comparison of FormCraft's code and files with ArtCraft's (identical files, and every run of six normalised lines) found no identical file and no shared code. The one match is a provider's own list of voice names in the model catalogue, present since 0.2.0. Nobody who changed FormCraft read ArtCraft's source, and the source was deleted from the build machine. +- Not run: the macOS and Windows desktop builds and `cargo check` (no GTK here); native dialogs and Keychain; a generation against a provider; the Canvas extend round trip with a real key. +- Known: Esc on a new Board note with text deletes it; "Add and use" from the starter library puts a second Edit clip on a new track; Scene Record has no duration setting; the restore prompt can appear for a demo copy that was only opened; the cheatsheet's Display menu row shows no key. +- Esc closes the Jobs popover on the first press when a tour has run. + +## 0.10.0 · 2026-11-29 + +A usability release, made after the first day of real use on macOS. + +### Fixed + +- Scene, Record: a recording no longer stops at 1 or 2 percent. The window's own video encoder could wait for ever on an event the macOS webview may never send. Record now sends frames one by one to the engine's ffmpeg when it has one and uses the window encoder only as a fallback. Every wait has a time limit and fails with a plain message and Retry. +- Scene, Record: Stop returns you to the studio within about two seconds, puts the playhead pose back and says nothing was kept. A recording left open by a closed window no longer blocks new ones. +- Scene, Record: recordings use the timeline's frame rate and length instead of a fixed 30 frames a second. Entering Record no longer drops the selection. +- Agents: "Remember this choice" now covers every window action from that agent. It was saved per command, so each new command asked again. +- Agents: scene tools that said rotations were in degrees passed them through as radians. They are degrees now. +- Projects: an export with no path, including the agent export tool, no longer writes to the Downloads folder. It goes beside the project's saved file or into the app's projects folder, never replaces a file, and returns the path. +- Quit on macOS waits for the Save, Don't Save, Cancel question. +- The "Saved" toast, tooltips and menus no longer cover controls: toasts sit in a reserved strip above the status bar, and tooltips, menus and dropdowns stay between the title bar and the status bar. + +### Added + +- Projects: Save, Save As, Save a Copy, Open Recent, Export, Reveal and Close in the File menu of every studio, with a native save dialog that remembers the last folder. The title bar shows Saved, Edited or Saving. +- Projects: Scene and Canvas changes are autosaved to the app's own folder, and after a crash the next launch offers to restore them. +- Scene: orbit, pan and zoom toward the pointer with mouse or trackpad, fly with the right button and WASD, frame the selection with F, view presets, orthographic view, a corner axis gizmo and a navigation help card. +- Scene: display modes (Solid, Wireframe, Solid with wire, Material preview, Bounding box), viewport toggles, and "Display as" per object. Display modes never change a capture or a recording. +- Scene: materials with colour, normal and roughness maps, tiling, glow and opacity, and an environment image saved with the project. +- Scene, Record: with "Also save depth and mask" on, a recording also saves a depth video and a mask video. +- Agents: Ask every time, Ask once per session, Always allow in this project and Always allow everywhere, per agent program; a spending switch that is off by default; and a list of what is allowed, with Revoke. +- Agents: 19 scene tools, 93 tools in all: list, add many, delete, select, group, cameras, mode, timeline keys in batches, duration and frame rate, record start, status and stop, save, export, open, and `scene_schema`, which describes the formats. +- A title bar Agents button with a running dot and a waiting count, and View menu entries for agents and panels. +- Home opens on "What do you want to make?", with recent projects, demos and the starter library. A short welcome runs on first launch and can be skipped. The app icon opens a menu of every studio and tool. +- Six demo projects, one or more per studio, that open as unsaved copies and need no key. +- A starter library of CC0 content: 294 3D models, 40 materials, 10 environments, pictures, sprites, 29 video clips and 149 sounds, 43 MB in all. Each item keeps its licence, author and source. See `assets/starter/CREDITS.md`. +- Rendering: the engine finds ffmpeg through one resolver that follows formai-binaries, a render service for image sequences and joined clips, a Rendering section in Preferences, and "Send to FormEncoder". +- Preferences, Files and Output: output folder, ask where to save, save finished results automatically, and a file name template with a live preview. +- Keyboard: Blender-like and Maya/Unity-like presets, swap on conflict, import and export, search by pressing a key, and a cheatsheet on `?` or by holding Ctrl or Cmd. +- Edit: in and out points, loop, cut, fades with a dip to black, an add-media menu and a hint line. +- Canvas: a Layers panel, export as PNG, JPEG or WebP, and copy to the clipboard. +- Board: undo and redo in the grid, export the board as a picture, and "Make prompt" from the board's notes and tags. + +### Changed + +- Scene: the panels are docked and no longer float over the view: one toolbar row that never wraps, outliner on the left, inspector on the right, the shot box under the view, and a bottom strip that grows into the timeline. Columns resize, fold and are remembered. File has "Reset layout". +- Scene: the outliner scrolls, has a search box, a count and collapse all. +- Agents: an ordinary request shows as a small card at the top right that names the action in plain words and queues requests, instead of a dialog that blurs the window. The dialog is kept for spending and risky steps. +- Preferences, Connections: each key says where it is stored. Keys found in the fallback file move into the system keyring at start-up. +- Results: feed cards, the lightbox and the library offer the same actions in the same order. Pending cards show the cost; failed cards give the reason and Retry. The jobs list is grouped. +- Create: the model button shows the full name, the picker pins Favourites, Recently used and Recommended, Generate reads "Add key" when the model has none, and the page switch is a fixed bar. +- New project offers the things people make and opens the right place. +- Names: "3D object" is "3D model", the transform space "World" is "Global", the Board view "Canvas" is "Freeform". +- File names never replace a file: a second copy gets `_1`, `_2`. + +### 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. +- The built app was driven end to end in a headless browser against the engine: first launch, Home and the six demos, every studio at 1100x700 and 1440x900, Scene navigation and display modes on the corridor demo, a two second recording with depth and mask (60 frames at 30 a second, not black), Stop at 30 percent (usable in 1.2 s, no ffmpeg left running), the forced window-encoder stall (an error with Retry after 12 s), save and re-import, the close question, the restore prompt, the agent tools over MCP with the request card and a project grant, the starter library and all 17 Preferences sections. +- No test was added or changed. +- Not run: the macOS and Windows desktop builds and the macOS webview, where the recording fault was reported; native save and open dialogs; the system keyring on a real Mac or Windows PC; a real FormEncoder; a generation against a provider. Canvas, Board and Edit were opened and their new controls exercised by the agents that built them, but not in the final end to end pass. +- Known: a restored project can be named "Untitled scene (recovered)" when it had another name; a project grant keeps the project's old name after a rename; a recording identical to an earlier one is merged into the earlier library item. + ## 0.9.4 · 2026-11-28 ### Changed diff --git a/CLAUDE.md b/CLAUDE.md index ba37418..f0db22c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,7 +12,9 @@ Released. The owner approved `DEV_PLAN.md` on 2026-11-01; each build turn lands - `backend/` is the local engine (FastAPI on 127.0.0.1, 8290 in dev, port 0 when frozen). It owns jobs, events, the library, keys, settings and ffmpeg. The window never stores a key. - `src-tauri/` is the desktop shell. It starts the engine, shows the splash, loads the engine-served window and owns OS integration (single instance, open files, links, folder picker). - `setup/` holds the scripts the root `formcraft` command fans out to, including the engine freeze used by `desktop build`. -- `assets/` is repository art (the icon source), not runtime files; runtime files live in `frontend/public/` and `src-tauri/icons/`. +- `assets/` holds the icon source (`app-icon/`), which is repository art, and two folders that ship in the installer as Tauri resources: `assets/starter/` (the CC0 starter library, 31 packs, read by `backend/app/services/starter.py`; `CREDITS.md` and `README.md` there say what is in it) and `assets/demos/` (the demo `.fcrft` files, covers and `demos.json`, read by `services/demos.py`). Other runtime files live in `frontend/public/` and `src-tauri/icons/`. +- New in 0.10: `frontend/src/ui/library/starter/` (the starter picker), `frontend/src/ui/scene/materials/` (materials and the environment image), `frontend/src/ui/projects/` (Save, autosave, Open Recent) and `frontend/src/automation/tools-scene-*.ts` (the scene tools). Backend services `binaries.py` (the ffmpeg lookup through formai-binaries), `render.py` (render jobs), `formencoder.py` (Send to FormEncoder), `starter.py` and `demos.py`, with routers `render.py`, `starter.py` and `demos.py`. +- The MCP surface is 44 engine tools and 49 window tools, 93 in all, listed in `agents/manifest.json`. Agents ask for approval at a level the person sets in Preferences, Agents (Ask every time, Ask once per session, Always allow in this project, Always allow everywhere); spending and risky calls always ask. - Each side keeps its own `HASHOUT_LOG.md` beside its code; read it before editing that side. ## Skills diff --git a/LICENSES.md b/LICENSES.md index bdde3df..a55d25d 100644 --- a/LICENSES.md +++ b/LICENSES.md @@ -1,6 +1,6 @@ # Third-party licences · formcraft -Version v0.9.4 · 2026-11-28 +Version v0.11.0 · 2026-11-29 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. @@ -26,6 +26,7 @@ How to read the tables: the columns are item, version, licence, where it ships a 14. [Model catalogue data](#catalogue) 15. [Licence text: BSD 3-Clause (httpx and httpcore)](#bsd) 16. [Downloadable content: the starter pack](#downloadable) +17. [Bundled starter content](#bundled-starter) The Apache-2.0 text for third-party Apache-2.0 items is the repository's `LICENSE`; it is the same text. @@ -223,7 +224,7 @@ Not bundled in any installer. The engine downloads them at first run (see sectio ## 7. ffmpeg: the LGPL build downloaded at first run {#ffmpeg} -formcraft does not contain FFmpeg. When no ffmpeg is installed, formcraft downloads FFmpeg 7.1.5 (the LGPL build that the form family publishes at https://github.com/nodemode-dev/formcut-binaries/releases/tag/ffmpeg-7.1.5-2), checks every file against a SHA-256 recorded in formcraft (`backend/app/services/ffmpeg_record.py`), installs it in a per-person folder shared with the other form apps (`formcut-binaries/ffmpeg-7.1.5-2`), and runs it as a separate program. FFmpeg is licensed under the GNU Lesser General Public License, version 2.1 or later; this build is configured with `--disable-gpl --disable-nonfree`, and its libraries are shared and can be replaced by the person who installed it. The licence text, the third-party notices and the build record are installed beside the programs. libopus 1.6.1 and libvpx 1.17.0, compiled into the FFmpeg libraries, are licensed under the BSD 3-Clause licence; on Linux the download also carries libva 2.24.1 and libdrm 2.4.134 (MIT), and on Windows and Linux it carries MIT-licensed codec headers (nv-codec-headers, AMF) compiled in. +formcraft does not contain FFmpeg. When no ffmpeg is installed, formcraft downloads FFmpeg 7.1.5 (the LGPL build that the form family publishes at https://github.com/nodemode-dev/formai-binaries/releases/tag/ffmpeg-7.1.5-2), checks every file against a SHA-256 recorded in formcraft (`backend/app/services/ffmpeg_record.py`), installs it in a per-person folder shared with the other form apps (`formcut-binaries/ffmpeg-7.1.5-2`), and runs it as a separate program. FFmpeg is licensed under the GNU Lesser General Public License, version 2.1 or later; this build is configured with `--disable-gpl --disable-nonfree`, and its libraries are shared and can be replaced by the person who installed it. The licence text, the third-party notices and the build record are installed beside the programs. libopus 1.6.1 and libvpx 1.17.0, compiled into the FFmpeg libraries, are licensed under the BSD 3-Clause licence; on Linux the download also carries libva 2.24.1 and libdrm 2.4.134 (MIT), and on Windows and Linux it carries MIT-licensed codec headers (nv-codec-headers, AMF) compiled in. Source offer. The exact source of the FFmpeg, libopus and libvpx used (ffmpeg-7.1.5.tar.xz, libopus-1.6.1.tar.gz, libvpx-1.17.0.tar.gz, and for Linux libva-2.24.1.tar.bz2 and libdrm-2.4.134.tar.xz) is attached to the same release, beside the binaries, as the record requires; the record (`ffmpeg-licence.json`, installed with the programs) names every upstream download with its SHA-256 and the configure line of each target. @@ -661,3 +662,21 @@ Obligation: none (CC0); the credit lines are kept in the manifest. - Not in the manifest, so not recorded as shipped: the 100Avatars R1 VRM characters (Polygonal Mind, CC0) and seven 2K sky originals, which need hosts the engine does not allow. Each needs a row in this section before it is added to the manifest. - No new package entered v0.7.0 either: the Edit studio uses only packages already listed (mediabunny 1.61.6 for decoding and window-side export, unmodified and lazy; the bundled Inter and JetBrains Mono for the font picker). Its colour and gradient presets, shape stickers and the 24 sounds of the sounds library are formcraft's own, made in code (the sounds are synthesised by the engine on first use), so they carry no third-party licence. Engine-side export runs through the same ffmpeg already recorded; MP4 there uses whichever H.264 encoder that ffmpeg offers, and the family LGPL build has no libx264. - No new package entered v0.6.0 (section 3). The catalogue gained two Meshy entries (rigging and character); section 14 applies unchanged: facts only, no weights, no logo. + +## 17. Bundled starter content {#bundled-starter} + +New in v0.10.0, re-sourced in v0.11.0. The folder `assets/starter/` ships inside every installer (Tauri resource `starter/`, about 118 MB). It holds 17 packs and 653 items. Every file comes from the publisher's own website or the publisher's own upload, not from a GitHub mirror. 16 packs are CC0 1.0 Universal; one, Prelinger Archives, is under the legacy Creative Commons Public Domain Dedication. Both are public domain dedications: no obligation attaches, and the credit lines below are courtesy credits. Each pack folder carries a `pack.json` (author, source address, version, retrieval date, and two licence evidence URLs) and a `LICENSE.txt`; `assets/starter/CREDITS.md` lists all 17 packs. The engine loads a pack only when its `pack.json` names CC0-1.0 or a public domain dedication and the folder holds `LICENSE.txt`. This content is separate from the downloadable starter pack in section 16 and from the five bundled sets in `backend/app/pack/sets`. + +| Source and author | Packs and files | Source address | Evidence | +| --- | --- | --- | --- | +| Poly Haven artists (named per item) | 1 pack of 27 3D models, 1 pack of 26 PBR materials (78 maps), 1 pack of 16 HDRI skies with previews, 1K | https://polyhaven.com | https://polyhaven.com/license and the API record of each item, `LICENSE.txt` in each pack | +| ambientCG and its contributors | 1 pack of PBR textures (180 maps, 60 materials) | https://ambientcg.com | https://docs.ambientcg.com/license/ and each material's page, `LICENSE.txt` | +| Derived from ambientCG textures by the formcraft build | 1 pack of 8 colour palettes (images) | https://ambientcg.com | derivative data of CC0 works, `LICENSE.txt` | +| The Cleveland Museum of Art, The Metropolitan Museum of Art, The Art Institute of Chicago (open access) | 4 packs of reference pictures: Cleveland works (41) and photographs (41), Met photographs (33), Art Institute works (43) | https://www.clevelandart.org/open-access, https://www.metmuseum.org, https://www.artic.edu/open-access/open-access-images | each museum's open access statement and the CC0 status in each item's API record | +| Negative Space | 1 pack of 10 colour photographs (city and architecture) | https://negativespace.co | https://negativespace.co/license/ and each photo's page | +| Prelinger Archives (films by various original producers) | 1 pack of 17 film excerpts, audio removed, under the legacy Creative Commons Public Domain Dedication | https://archive.org/details/prelinger | each film's record and the collection statement, `LICENSE.txt` | +| graphite412 (Electronica 4 God netlabel) | 1 pack of 101 field recordings and foley sounds | the author's own uploads on https://archive.org (djt002, djt003, djt005) | the CC0 licence in each item's metadata record and the author's CC0 statement in each item's description, `LICENSE.txt` | +| Komiku (Monplaisir), WinAAA, ricohman | 3 packs of music: 3 Komiku tracks and 3 WinAAA loops (50 second excerpts), 4 short jingles | the publishers' own uploads on https://archive.org | the CC0 licence in each item's metadata record and the CC0 statement in each item's description, `LICENSE.txt` in each pack | +| NodeAgentc, Inc., generated for FormCraft | 2 packs: FormCraft Synth Audio (19 sounds) and FormCraft Generated Video (29 clips), made procedurally for this project and dedicated to the public domain under CC0 1.0 by NodeAgentc, Inc. | not applicable (generated) | `LICENSE.txt` in each pack | + +The demo projects in `assets/demos/` (six `.fcrft` files and their covers) are original to formcraft. diff --git a/NOTICE b/NOTICE index a7a7dcc..f3f089f 100644 --- a/NOTICE +++ b/NOTICE @@ -116,6 +116,17 @@ Augustin and contributors; the conditions and disclaimer printed above for httpx with this copyright line), ptyprocess 0.7.0 on macOS and Linux (ISC) and pywinpty 3.0.5 on Windows (MIT), all bundled unmodified in the frozen engine; LICENSES.md, section 2, lists them. +System password store. The engine keeps provider keys in macOS Keychain, Windows Credential +Manager or the Secret Service on Linux through keyring 25.7.0 (MIT) with jaraco.classes 3.4.0, +jaraco.context 6.1.2, jaraco.functools 4.6.0 and more-itertools 11.2.1 (MIT), jeepney 0.9.0 on +Linux (MIT), SecretStorage 3.5.0 on Linux (BSD 3-Clause, Copyright 2012-2025 Dmitry Shachnev; +the conditions and disclaimer printed above for httpx apply to it with this copyright line) and +pywin32-ctypes 0.2.3 on Windows (BSD 3-Clause), all bundled unmodified in the frozen engine. The +MIT permission notice printed above for three applies to each MIT package; their copyright lines +are those of their licence files (more-itertools: Copyright (c) 2012 Erik Rose; jeepney: +Copyright (c) 2017 Thomas Kluyver; keyring and the jaraco packages: their authors). +LICENSES.md, section 2, lists them. + The WebAssembly module inside Spark is built from Rust crates whose licences are all permissive (MIT, Apache-2.0, Zlib, BSD, ISC, CC0-1.0, Unicode-3.0 or a choice among them); LICENSES.md, section 11, lists the audit. @@ -221,6 +232,22 @@ for nothing; the credits below are courtesy credits. address, evidence and credit line of each item. Version 0.6.0 added no package to the window, the engine or the desktop shell. +Bundled starter content. The installer carries the starter library, assets/starter (118 MB, 17 +packs, 653 items), taken from each publisher's own website or own upload. 16 packs are CC0 1.0 +and one, Prelinger Archives, is under the legacy Creative Commons Public Domain Dedication: they +ask for nothing, and the credits are courtesy credits. Sources and authors: models, PBR +materials and HDRI skies from Poly Haven artists (named per item); PBR textures from ambientCG +and its contributors, with eight colour palettes derived from them by the formcraft build; +pictures from The Cleveland Museum of Art, The Metropolitan Museum of Art and The Art Institute +of Chicago open access; colour photographs from Negative Space; film excerpts from the +Prelinger Archives; field recordings and foley by graphite412 and music by Komiku, WinAAA and +ricohman, from their own uploads on the Internet Archive. Two packs, the +FormCraft Synth Audio sounds and the FormCraft Generated Video clips, were generated for +formcraft by NodeAgentc, Inc. and dedicated to the public domain under CC0 1.0 by NodeAgentc, +Inc. The demo projects in assets/demos are original to formcraft. Each pack folder holds its own +LICENSE.txt, and assets/starter/CREDITS.md and LICENSES.md, section 17, list every pack with its +source and version. + Everything else (MIT, BSD, ISC, Apache-2.0, Zlib, PSF and similar licences) asks that its copyright notice and licence text be kept. The installer carries LICENSE, NOTICE and LICENSES.md, which lists each item; the other licence texts are not yet collected into it diff --git a/README.md b/README.md index 39db627..1ec2118 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

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

The FormCraft Scene studio with a marble bust on a plinth, a treasure chest, an armchair, a rubber duck and a lantern in front of a sunset photo, with the outliner on the left and the prompt bar below
- The Scene studio: CC0 models staged in front of a photo backdrop, framed by a camera, ready for the prompt bar. + The Scene studio: CC0 models staged in front of a photo backdrop, framed by a camera, ready for the prompt bar. This picture was taken before 0.10, which docks the outliner and inspector as resizable columns.

@@ -38,6 +38,7 @@ Agents · Under the hood · Download · + Getting started · Run from source

@@ -48,7 +49,7 @@

Every medium

Generate images, video, music, sound, 3D meshes and explorable worlds from one prompt bar, with the options each model really has.

Stage the shot

Block out a 3D scene with props and cameras, then turn the camera's frame into a still and a still into a clip.

Your keys

Generation runs on your own provider keys, kept in the system password store. No account, no credits. -

Agent-ready

The same engine from the window and from an MCP server with 44 engine tools always available and 30 more when the window is open, for Claude Code, Codex, Cursor and Antigravity. +

Agent-ready

The same engine from the window and from an MCP server with 44 engine tools always available and 49 more when the window is open, for Claude Code, Codex, Cursor and Antigravity. @@ -59,15 +60,19 @@ +

Cut on a timeline

A multi-track editor with trim, split, ripple, snapping, in and out points, loop, fades, cross dissolves, keyframes and masks, with lock, solo, mute and hide on every track and a half or quarter quality preview for long cuts. Export to MP4 or WebM to disk and the library, or send the file to FormEncoder. +

Paint and compose

Layer pictures, shapes, text and 3D models in a Layers panel with opacity and blend modes, select with a rectangle or a lasso, crop or extend the page, paint a mask, then choose how to generate: change the whole image, only the masked area, or extend it. Review each result before you keep it. Export the canvas as a picture. +

Collect references

Boards of pictures, clips, notes, colours and links, with sections, ratings, tags, a palette and undo. Make a prompt from a board. +

Lay it out freely

Switch a board to a free canvas with groups, snapping, align and distribute, and arrows that follow their items, present it full screen, or export it as a picture. + + + +
The Edit studio with the library on the left, a Venice sunset clip in the preview, transform controls on the right and four tracks of clips, titles and music on the timeline
The Edit studio: four clips, titles, a music bed and drums on one timeline. -

Cut on a timeline

A multi-track editor with trim, split, ripple, snapping, keyframes and masks. Export to MP4 or WebM to disk and the library.
The Canvas studio with three photos, a white brush stroke, an orange circle and a blue triangle layered on a dark canvas, with a prompt box below
The Canvas studio: photos, shapes and a brush stroke in layers. -

Paint and compose

Layer pictures, shapes and 3D models, paint a mask, then send the mask or the whole composition to the right model.
A moodboard grid with five colour swatches, a note and a City section of photos, with tag filters above
A board in grid view with palette, note and sections. -

Collect references

Boards of pictures, clips, notes, colours and links, with sections, ratings, tags and a palette.
A free board canvas with eight photos laid out in rows and a text label reading Warm light
The same kind of board on a free canvas. -

Lay it out freely

Switch a board to a free canvas with groups, snapping and layout tools, and present it full screen.

Stage in 3D

The Scene studio has a docked layout: an outliner on the left, an inspector on the right, and a timeline below, all resizable, with Reset layout in the file menu. Move around with the usual 3D editor controls: orbit, pan, zoom, fly, snap to front, side and top views, switch to orthographic, and show the scene as wireframe or bounding boxes, or one object at a time. Select several objects and move or edit them together, copy and paste any object, and frame the shot in camera view with safe-area guides. Give shapes and models materials with texture maps, and light the scene with a saved environment image. Record renders the timeline to MP4, with optional depth and mask videos.

Start from something

Open one of 6 demo projects without a key. Browse the starter library: 653 CC0 and public domain items in 17 packs, 27 of them 3D models and 86 materials, plus HDRI skies, pictures, clips, sounds and music, free for any use, each taken from its publisher's own website. Drag them from the floating Library window onto any studio. Each studio has a short tour, and the Jobs button in the title bar shows what is running. Save a project to a .fcrft file with Save, Save As or Save a Copy; unsaved scenes and canvases are kept and offered back after a crash.
@@ -83,7 +88,7 @@ ## Built for agents -`./formcraft mcp` always serves 44 engine tools (generate, wait on jobs, search the library, manage projects) and adds 30 studio tools while the window is open. +`./formcraft mcp` always serves 44 engine tools (generate, wait on jobs, search the library, manage projects) and adds 49 studio tools while the window is open, 93 in all. An agent can build a scene, set keyframes, record, save and export it without a selection or an open panel. ```sh ./formcraft mcp --where # print the data folder and engine it would use @@ -92,15 +97,16 @@ claude mcp add --transport stdio formcraft -- "$PWD/formcraft" mcp # register ./formcraft agents install # writes .mcp.json, .codex/config.toml, .cursor/mcp.json and Antigravity's ~/.gemini/config/mcp_config.json, installs the skills ``` -Agents are off until you allow them in Preferences, Agents. `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json` are already wired in this repo. See [`AGENTS.md`](AGENTS.md). +Agents are off until you allow them in Preferences, Agents. A request shows as a card in the window that does not block it. Choose per agent: Ask every time, Ask once per session, Always allow in this project, or Always allow everywhere. Spending can be allowed up to a limit you set, and every grant is listed and can be removed. The Agents button at the top right opens the agent dock. `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json` are already wired in this repo. See [`AGENTS.md`](AGENTS.md). ## Under the hood - **Window:** vanilla TypeScript and Vite with Three.js, DOM-free engines under `frontend/src/engine/`. - **Engine:** Python and FastAPI on loopback only, with a job queue that survives a restart. -- **Providers:** fal and the World Labs API through their official APIs and your own keys. -- **Library:** imports and results stored by content, with thumbnails, posters and durations. -- **Projects:** `.fcrft` files that carry their media, saved atomically. +- **Providers:** fal and the World Labs API through their official APIs and your own keys. Preferences, Connections says where each key is kept, and a key found in an older private file moves into the system keyring on its own. +- **Library:** imports and results stored by content, with thumbnails, posters and durations, and a bundled CC0 starter library. +- **Projects:** `.fcrft` files that carry their media, saved atomically, with native Save dialogs and an autosave for scenes and canvases. +- **Rendering:** ffmpeg runs as a separate program, found through the Form family's formai-binaries; finished video can be sent to FormEncoder. - **CI:** typecheck, build, engine selfcheck, version agreement and a skills check. ## Download @@ -113,6 +119,16 @@ Agents are off until you allow them in Preferences, Agents. `.mcp.json`, `.codex All FormCraft builds are compiled and released from [FormCompiler](https://github.com/nodemode-dev/formcompiler); this repo holds the source. +## Getting started + +- **First run:** a three-step welcome says what formcraft is, offers to add a key or explore without one, and lets you pick a look. Search commands finds it again as Welcome tour. +- **Home:** it asks "What do you want to make?" and lists your recent projects, the demos and every studio and tool. Click the logo at the top left from anywhere to open the menu of all studios and tools. +- **Demos:** six ready-made projects (three Scene, one Canvas, one Board, one Edit) open from Home without a key. +- **Starter library:** Library, Starter (or Help, About, Starter library credits) holds 17 CC0 and public domain packs, 653 items, 118 MB: 27 3D models, 86 materials, 16 HDRI skies, 168 pictures, 8 palettes, 46 clips and 130 sounds and music tracks. Add to library keeps the source and licence with each item. +- **Add a key:** Preferences, Connections. The note under each key says where it is stored. +- **Save:** File, Save, Save As or Save a Copy writes a `.fcrft` file with a native dialog, and the title bar says Saved, Edited or Saving. Files and Output in Preferences sets the output folder and the file name template. +- **Agents:** the Agents button at the top right, or View, Show Agents. + ## Run it from source For anyone who wants the web UI in a browser or wants to contribute. @@ -137,7 +153,7 @@ On Windows use `formcraft_oc_install.bat` and `formcraft.bat boot`. The engine l | `FORMCRAFT_MCP_URL` | `formcraft mcp` attaches to the engine at this URL | > [!IMPORTANT] -> **Status:** released. All 24 planned phases have landed and only the Linux build has been built and opened so far. The release pipeline also produces macOS and Windows builds, which are newly tested. Generation was checked against the providers' published schemas and a mock, not against the live services. +> **Status:** released. All 24 planned phases have landed and only the Linux build has been built and opened so far. The release pipeline also produces macOS and Windows builds, which are newly tested. Generation was checked against the providers' published schemas and a mock, not against the live services. The 0.10 changes (docked Scene layout, native saving, agent approvals, recording) have not been tried on a real Mac or Windows PC yet. **Contributing:** branch from `main`, keep changes to source here, and leave packaging and releases to FormCompiler. See [`CONTRIBUTING.md`](CONTRIBUTING.md), [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md), [`.docs/BRANCHING.md`](.docs/BRANCHING.md) and [`AGENTS.md`](AGENTS.md). Report security issues privately as [`SECURITY.md`](SECURITY.md) describes. @@ -152,6 +168,8 @@ On Windows use `formcraft_oc_install.bat` and `formcraft.bat boot`. The engine l | `.claude/skills/` | skills for changing this repo and for driving the app over MCP | | `docs/images/` | README screenshots | | `assets/` | the icon master that `src-tauri/icons` is generated from | +| `assets/starter/` | the bundled CC0 starter library, with `CREDITS.md` and `README.md` | +| `assets/demos/` | the demo projects (`.fcrft`), their covers and `demos.json` | Docs: [`.docs/wiki`](.docs/wiki) · Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md) · Contributing: [`.docs/BRANCHING.md`](.docs/BRANCHING.md) diff --git a/agents/manifest.json b/agents/manifest.json index 78aa29a..afbbc6b 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -108,6 +108,25 @@ "edit_undo", "edit_redo", "edit_export", + "scene_list_objects", + "scene_add_many", + "scene_delete", + "scene_select", + "scene_group", + "scene_ungroup", + "scene_camera", + "scene_schema", + "scene_record_start", + "scene_record_status", + "scene_record_stop", + "scene_save", + "scene_export", + "scene_open", + "scene_mode", + "scene_timeline_get", + "scene_keys_set", + "scene_keys_delete", + "scene_timeline_set", "scene_state", "scene_add", "scene_update", diff --git a/assets/app-icon/formcraft-256.png b/assets/app-icon/formcraft-256.png index 5fcc679..805c2d9 100644 Binary files a/assets/app-icon/formcraft-256.png and b/assets/app-icon/formcraft-256.png differ diff --git a/assets/demos/covers/night-drive-cut.webp b/assets/demos/covers/night-drive-cut.webp new file mode 100644 index 0000000..e00bd58 Binary files /dev/null and b/assets/demos/covers/night-drive-cut.webp differ diff --git a/assets/demos/covers/night-drive-moodboard.webp b/assets/demos/covers/night-drive-moodboard.webp new file mode 100644 index 0000000..28a3769 Binary files /dev/null and b/assets/demos/covers/night-drive-moodboard.webp differ diff --git a/assets/demos/covers/night-horizon-canvas.webp b/assets/demos/covers/night-horizon-canvas.webp new file mode 100644 index 0000000..f264a66 Binary files /dev/null and b/assets/demos/covers/night-horizon-canvas.webp differ diff --git a/assets/demos/covers/product-turntable.webp b/assets/demos/covers/product-turntable.webp new file mode 100644 index 0000000..23b088a Binary files /dev/null and b/assets/demos/covers/product-turntable.webp differ diff --git a/assets/demos/covers/scifi-corridor-walk.webp b/assets/demos/covers/scifi-corridor-walk.webp new file mode 100644 index 0000000..44ddf84 Binary files /dev/null and b/assets/demos/covers/scifi-corridor-walk.webp differ diff --git a/assets/demos/covers/stage-the-cast.webp b/assets/demos/covers/stage-the-cast.webp new file mode 100644 index 0000000..f5576a3 Binary files /dev/null and b/assets/demos/covers/stage-the-cast.webp differ diff --git a/assets/demos/demos.json b/assets/demos/demos.json new file mode 100644 index 0000000..ad636fc --- /dev/null +++ b/assets/demos/demos.json @@ -0,0 +1,93 @@ +[ + { + "id": "scifi-corridor-walk", + "title": "Scifi Corridor Walk", + "blurb": "Two explorers walk a lit scifi corridor while a low dutch-angle camera tracks backward ahead of them.", + "studio": "scene", + "file": "scifi-corridor-walk.fcrft", + "cover": "covers/scifi-corridor-walk.webp", + "minutes": 2, + "shows": [ + "keyframes", + "cameras", + "lights", + "groups", + "lens" + ] + }, + { + "id": "product-turntable", + "title": "Product Turntable", + "blurb": "A Poly Haven vase spins on a pedestal lit by a studio HDRI and a key, fill and rim light while the camera orbits around it.", + "studio": "scene", + "file": "product-turntable.fcrft", + "cover": "covers/product-turntable.webp", + "minutes": 2, + "shows": [ + "keyframes", + "cameras", + "three-point lighting", + "HDRI" + ] + }, + { + "id": "stage-the-cast", + "title": "Stage the Cast", + "blurb": "Three built-in mannequins on marks, each playing its own animation clip, with three cameras to cut between.", + "studio": "scene", + "file": "stage-the-cast.fcrft", + "cover": "covers/stage-the-cast.webp", + "minutes": 2, + "shows": [ + "mannequins", + "animation clips", + "cameras" + ] + }, + { + "id": "night-drive-moodboard", + "title": "Night Drive Moodboard", + "blurb": "A moodboard with brief notes, a five-colour palette and rated motion references in sections.", + "studio": "board", + "file": "night-drive-moodboard.fcrft", + "cover": "covers/night-drive-moodboard.webp", + "minutes": 2, + "shows": [ + "notes", + "colours", + "sections", + "ratings" + ] + }, + { + "id": "night-horizon-canvas", + "title": "Night Horizon Canvas", + "blurb": "A layered poster made from shapes and brush strokes, with a painted mask ready for a fill.", + "studio": "canvas", + "file": "night-horizon-canvas.fcrft", + "cover": "covers/night-horizon-canvas.webp", + "minutes": 2, + "shows": [ + "layers", + "shapes", + "brush", + "mask" + ] + }, + { + "id": "night-drive-cut", + "title": "Night Drive Cut", + "blurb": "A thirteen-second cut with three clips, an animated title, a crossfade, a fade to black and music.", + "studio": "edit", + "file": "night-drive-cut.fcrft", + "cover": "covers/night-drive-cut.webp", + "minutes": 2, + "shows": [ + "clips", + "titles", + "transitions", + "keyframes", + "audio" + ] + } +] diff --git a/assets/demos/night-drive-cut.fcrft b/assets/demos/night-drive-cut.fcrft new file mode 100644 index 0000000..16832b2 Binary files /dev/null and b/assets/demos/night-drive-cut.fcrft differ diff --git a/assets/demos/night-drive-moodboard.fcrft b/assets/demos/night-drive-moodboard.fcrft new file mode 100644 index 0000000..d3fa90b Binary files /dev/null and b/assets/demos/night-drive-moodboard.fcrft differ diff --git a/assets/demos/night-horizon-canvas.fcrft b/assets/demos/night-horizon-canvas.fcrft new file mode 100644 index 0000000..b95282e Binary files /dev/null and b/assets/demos/night-horizon-canvas.fcrft differ diff --git a/assets/demos/product-turntable.fcrft b/assets/demos/product-turntable.fcrft new file mode 100644 index 0000000..0a7bc73 Binary files /dev/null and b/assets/demos/product-turntable.fcrft differ diff --git a/assets/demos/scifi-corridor-walk.fcrft b/assets/demos/scifi-corridor-walk.fcrft new file mode 100644 index 0000000..8ab3bd2 Binary files /dev/null and b/assets/demos/scifi-corridor-walk.fcrft differ diff --git a/assets/demos/stage-the-cast.fcrft b/assets/demos/stage-the-cast.fcrft new file mode 100644 index 0000000..0499fa9 Binary files /dev/null and b/assets/demos/stage-the-cast.fcrft differ diff --git a/assets/formcraft_document_icon.png b/assets/formcraft_document_icon.png new file mode 100644 index 0000000..493edf9 Binary files /dev/null and b/assets/formcraft_document_icon.png differ diff --git a/assets/formcraft_icon_full.png b/assets/formcraft_icon_full.png new file mode 100644 index 0000000..2ca3b2f Binary files /dev/null and b/assets/formcraft_icon_full.png differ diff --git a/assets/formcraft_icon_macos.png b/assets/formcraft_icon_macos.png new file mode 100644 index 0000000..2b0908d Binary files /dev/null and b/assets/formcraft_icon_macos.png differ diff --git a/assets/formcraft_mark.svg b/assets/formcraft_mark.svg new file mode 100644 index 0000000..9997c10 --- /dev/null +++ b/assets/formcraft_mark.svg @@ -0,0 +1 @@ + diff --git a/assets/icon_src/build.py b/assets/icon_src/build.py new file mode 100644 index 0000000..f3026d2 --- /dev/null +++ b/assets/icon_src/build.py @@ -0,0 +1,121 @@ +import io, os, struct, sys +from PIL import Image, ImageChops, ImageDraw, ImageFilter + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.abspath(os.path.join(HERE, '..', '..')) +SRC = Image.open(os.path.join(HERE, 'formcraft_icon_source.png')).convert('RGBA') +TILE = (100, 100, 924, 924) + + +def P(rel): + path = os.path.join(ROOT, rel) + os.makedirs(os.path.dirname(path), exist_ok=True) + return path + + +def _full_master(): + crop = SRC.crop(TILE) + a = crop.getchannel('A').point(lambda v: max(0, min(255, (v - 200) * 255 // 55))) + crop.putalpha(a) + return crop.resize((1024, 1024), Image.LANCZOS) + + +FULL = _full_master() + + +def mac(n): + return SRC.resize((n, n), Image.LANCZOS) + + +def full(n): + im = FULL.resize((n, n), Image.LANCZOS) + if n <= 64: + im = im.filter(ImageFilter.UnsharpMask(radius=0.6, percent=60, threshold=1)) + return im + + +def png(im): + b = io.BytesIO() + im.save(b, 'PNG', optimize=True) + return b.getvalue() + + +def ico(path, sizes, fn): + ims = [png(fn(n)) for n in sizes] + off = 6 + 16 * len(sizes) + ent = b'' + for n, d in zip(sizes, ims): + ent += struct.pack('I', 8 + len(d)) + d for t, n in ICNS_TYPES for d in [png(fn(n))]) + open(path, 'wb').write(b'icns' + struct.pack('>I', 8 + len(body)) + body) + + +def document(n=1024): + s = 4 + W = n * s + im = Image.new('RGBA', (W, W), (0, 0, 0, 0)) + pw, ph = 0.70 * W, 0.86 * W + x0, y0 = (W - pw) / 2, (W - ph) / 2 + x1, y1 = x0 + pw, y0 + ph + fold, r = 0.20 * W, 0.035 * W + page = [(x0 + r, y0), (x1 - fold, y0), (x1, y0 + fold), (x1, y1 - r), (x1 - r, y1), + (x0 + r, y1), (x0, y1 - r), (x0, y0 + r)] + sh = Image.new('RGBA', (W, W), (0, 0, 0, 0)) + ImageDraw.Draw(sh).polygon([(x + 0, y + 0.012 * W) for x, y in page], fill=(0, 0, 0, 120)) + sh = sh.filter(ImageFilter.GaussianBlur(0.012 * W)) + im.alpha_composite(sh) + d = ImageDraw.Draw(im) + d.polygon(page, fill=(244, 242, 248, 255), outline=(206, 202, 216, 255), width=max(1, W // 256)) + d.polygon([(x1 - fold, y0), (x1 - fold, y0 + fold - r), (x1 - fold + r, y0 + fold), (x1, y0 + fold)], + fill=(214, 208, 228, 255), outline=(190, 184, 206, 255), width=max(1, W // 256)) + ic = int(0.50 * W) + badge = FULL.resize((ic, ic), Image.LANCZOS) + im.alpha_composite(badge, (int((W - ic) / 2), int(y0 + 0.40 * ph - ic / 2 + 0.04 * W))) + bar_y = y1 - 0.14 * W + d.rounded_rectangle([x0 + 0.12 * W, bar_y, x1 - 0.12 * W, bar_y + 0.035 * W], radius=0.0175 * W, fill=(122, 100, 242, 255)) + d.rounded_rectangle([x0 + 0.12 * W, bar_y + 0.065 * W, x0 + 0.40 * W, bar_y + 0.09 * W], radius=0.0125 * W, fill=(176, 170, 192, 255)) + return im.resize((n, n), Image.LANCZOS) + + +def main(): + DOC = document(1024) + docn = lambda n: DOC.resize((n, n), Image.LANCZOS) + mac(1024).save(P('assets/formcraft_icon_macos.png')) + FULL.save(P('assets/formcraft_icon_full.png')) + DOC.save(P('assets/formcraft_document_icon.png')) + mac(256).save(P('assets/app-icon/formcraft-256.png')) + icns(P('src-tauri/icons/icon.icns'), mac) + ico(P('src-tauri/icons/icon.ico'), [16, 24, 32, 48, 64, 128, 256], full) + mac(1024).save(P('src-tauri/icons/icon.png')) + full(32).save(P('src-tauri/icons/32x32.png')) + mac(128).save(P('src-tauri/icons/128x128.png')) + mac(256).save(P('src-tauri/icons/128x128@2x.png')) + icns(P('src-tauri/icons/fcrft.icns'), docn) + ico(P('src-tauri/icons/fcrft.ico'), [16, 32, 48, 256], docn) + for n in (16, 32, 48, 64, 128, 256, 512): + docn(n).save(P(f'src-tauri/icons/mimetypes/{n}x{n}/application-x-formcraft-project.png')) + full(64).save(P('frontend/public/favicon.png')) + ico(P('frontend/public/favicon.ico'), [16, 32, 48], full) + mac(256).save(P('frontend/public/formcraft-256.png')) + full(192).save(P('frontend/public/icon-192.png')) + full(512).save(P('frontend/public/icon-512.png')) + at = Image.new('RGBA', (180, 180), (17, 17, 25, 255)) + at.alpha_composite(full(180)) + at.convert('RGB').save(P('frontend/public/apple-touch-icon.png')) + for n in (16, 20, 26, 28): + full(n).save(P(f'frontend/public/brand/formcraft-{n}.png')) + full(n * 2).save(P(f'frontend/public/brand/formcraft-{n}@2x.png')) + + +if __name__ == '__main__': + main() + sys.stdout.write('ok\n') diff --git a/assets/icon_src/formcraft_icon_source.png b/assets/icon_src/formcraft_icon_source.png new file mode 100644 index 0000000..69f02c7 Binary files /dev/null and b/assets/icon_src/formcraft_icon_source.png differ diff --git a/assets/starter/2d/images-artic-cc0/LICENSE.txt b/assets/starter/2d/images-artic-cc0/LICENSE.txt new file mode 100644 index 0000000..9b4c6c2 --- /dev/null +++ b/assets/starter/2d/images-artic-cc0/LICENSE.txt @@ -0,0 +1,52 @@ +Statement retrieved from https://www.artic.edu/open-access/open-access-images on 2026-11-29 (text of the page, markup removed) + +Open Access Images +Collection Information +  › +Open Access +Open Access Images +Public API +Open Source Code +Open Access Images +Share +The Art Institute of Chicago is pleased to offer free, unrestricted use of over 50,000 images of works in the collection believed to be in the public domain or to which the museum otherwise waives any copyright it might have. Such images are made available under +Creative Commons Zero (CC0) +designation and the +Terms and Conditions of this website +. +The museum requests that you include the following caption with reproductions of the images: Artist. Title, Date. The Art Institute of Chicago. This information, which is available on the object page for each work, is also made available under Creative Commons Zero (CC0). Additional data about artworks in the collection is available using our +public API +. +Searching for Public Domain Images +Keyword Search +On the the +Collection page +, you’ll find a search box. When you enter either “public domain” or “CC0,” the search engine will return +the full list of public domain images available from the Art Institute of Chicago +. +Filter Search +You can also access public domain images using the advanced search filters on the +Collection page +. Among the many filters is a checkbox to limit your search results to only public domain artworks. You can use this checkbox to view all public domain artworks, refine existing keyword searches, or combine it with other filters such as artist, date, and medium. +The public domain checkbox is located near the bottom of the advanced filter drawer. +Example Search +Imagine you are looking for a painting of a cat to post to Twitter. To find public domain artworks featuring cats, you should start your search with the keyword “cats” and then refine the results by selecting the public domain filter. Now you will have +over 1,800 cat-related public domain images +from the collection to choose from. And you are free to download and use these images however you see fit. +Downloading Public Domain Artworks +The Art Institute of Chicago offers image file downloads for artworks in the public domain. These are accessible on the individual artwork pages. Adjacent to the image will be action buttons allowing you to zoom in, download the image file, or share the artwork on social media. The download button is the one in the middle with the arrow pointing downward. +A download button is included on pages when the artwork image is in the public domain. +You are welcome to use any images with the label “CC0 Public Domain Designation” for any purpose, including commercial and noncommercial uses, free of charge and without additional permission from the museum. Although the museum is not aware of and does not believe that such images are subject to any copyright restrictions, it is the sole responsibility of the image user to identify and obtain any necessary third-party permissions. The Art Institute of Chicago makes no representations or warranties of any kind concerning the images. +For more information about how to request an image not designated as CC0 or otherwise unavailable on the website in the required resolution or format, please refer to +the image licensing page +. +Note: The Art Institute of Chicago has many artworks which are covered by a copyright. If an artwork page does not have a download button, assume the artwork is not in the public domain. +About IIIF +The +International Image Interoperability Framework (IIIF) +represents a set of open standards that enables rich access to digital media from libraries, archives, museums, and other cultural institutions around the world. +By offering images and metadata via IIIF APIs, institutions open a range of ways for users to interact with their collections. A growing number of tools and frameworks support IIIF standards. These tools allow exploration of high-resolution artwork images, support interactive storytelling, and facilitate scholarly collaboration across institutions. +Many of these tools require a manifest to display an object. A manifest is a file that contains essential information about an object, including details such as its title, artist name, and copyright. Manifests are provided by individual institutions. +We offer IIIF manifests for all of our public domain artworks. You can find the manifest URL alongside the metadata on each artwork’s webpage. + +Second statement: every item was checked against https://api.artic.edu/api/v1/artworks/{id} on 2026-11-29: is_public_domain=true, copyright_notice empty. The API response carries this licence note: The description field is CC-By 4.0; all other data is licensed under a Creative Commons Zero (CC0) 1.0 designation (https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/assets/starter/2d/images-artic-cc0/animals_189715.jpg b/assets/starter/2d/images-artic-cc0/animals_189715.jpg new file mode 100644 index 0000000..bdf7f48 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/animals_189715.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/architecture_103193.jpg b/assets/starter/2d/images-artic-cc0/architecture_103193.jpg new file mode 100644 index 0000000..46c5f83 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/architecture_103193.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/architecture_123632.jpg b/assets/starter/2d/images-artic-cc0/architecture_123632.jpg new file mode 100644 index 0000000..7919c5e Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/architecture_123632.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/architecture_123636.jpg b/assets/starter/2d/images-artic-cc0/architecture_123636.jpg new file mode 100644 index 0000000..811f95f Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/architecture_123636.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/architecture_123652.jpg b/assets/starter/2d/images-artic-cc0/architecture_123652.jpg new file mode 100644 index 0000000..7bd166d Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/architecture_123652.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/architecture_145957.jpg b/assets/starter/2d/images-artic-cc0/architecture_145957.jpg new file mode 100644 index 0000000..cb43ab1 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/architecture_145957.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/architecture_181557.jpg b/assets/starter/2d/images-artic-cc0/architecture_181557.jpg new file mode 100644 index 0000000..ef779e7 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/architecture_181557.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/architecture_181558.jpg b/assets/starter/2d/images-artic-cc0/architecture_181558.jpg new file mode 100644 index 0000000..7a69bc8 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/architecture_181558.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/architecture_18967.jpg b/assets/starter/2d/images-artic-cc0/architecture_18967.jpg new file mode 100644 index 0000000..0122d3c Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/architecture_18967.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/architecture_60079.jpg b/assets/starter/2d/images-artic-cc0/architecture_60079.jpg new file mode 100644 index 0000000..b3831a7 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/architecture_60079.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/architecture_66315.jpg b/assets/starter/2d/images-artic-cc0/architecture_66315.jpg new file mode 100644 index 0000000..020e626 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/architecture_66315.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/architecture_97328.jpg b/assets/starter/2d/images-artic-cc0/architecture_97328.jpg new file mode 100644 index 0000000..00f5036 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/architecture_97328.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/interior_43683.jpg b/assets/starter/2d/images-artic-cc0/interior_43683.jpg new file mode 100644 index 0000000..cbd1475 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/interior_43683.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/interior_43711.jpg b/assets/starter/2d/images-artic-cc0/interior_43711.jpg new file mode 100644 index 0000000..9cad0cf Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/interior_43711.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/interior_43714.jpg b/assets/starter/2d/images-artic-cc0/interior_43714.jpg new file mode 100644 index 0000000..a41b9e8 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/interior_43714.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/interior_43739.jpg b/assets/starter/2d/images-artic-cc0/interior_43739.jpg new file mode 100644 index 0000000..cde6f06 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/interior_43739.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/interior_45316.jpg b/assets/starter/2d/images-artic-cc0/interior_45316.jpg new file mode 100644 index 0000000..33e4c16 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/interior_45316.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/interior_45401.jpg b/assets/starter/2d/images-artic-cc0/interior_45401.jpg new file mode 100644 index 0000000..1c2dda2 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/interior_45401.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/landscape_105101.jpg b/assets/starter/2d/images-artic-cc0/landscape_105101.jpg new file mode 100644 index 0000000..3ccd3eb Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/landscape_105101.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/landscape_140416.jpg b/assets/starter/2d/images-artic-cc0/landscape_140416.jpg new file mode 100644 index 0000000..64be9a6 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/landscape_140416.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/landscape_150429.jpg b/assets/starter/2d/images-artic-cc0/landscape_150429.jpg new file mode 100644 index 0000000..f1ab84f Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/landscape_150429.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/landscape_152666.jpg b/assets/starter/2d/images-artic-cc0/landscape_152666.jpg new file mode 100644 index 0000000..12ee29e Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/landscape_152666.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/landscape_212135.jpg b/assets/starter/2d/images-artic-cc0/landscape_212135.jpg new file mode 100644 index 0000000..d0696b6 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/landscape_212135.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/landscape_63554.jpg b/assets/starter/2d/images-artic-cc0/landscape_63554.jpg new file mode 100644 index 0000000..a2a95d0 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/landscape_63554.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/nature_150434.jpg b/assets/starter/2d/images-artic-cc0/nature_150434.jpg new file mode 100644 index 0000000..504d9e2 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/nature_150434.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/object_108575.jpg b/assets/starter/2d/images-artic-cc0/object_108575.jpg new file mode 100644 index 0000000..6524194 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/object_108575.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/object_117093.jpg b/assets/starter/2d/images-artic-cc0/object_117093.jpg new file mode 100644 index 0000000..2928a4d Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/object_117093.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/pack.json b/assets/starter/2d/images-artic-cc0/pack.json new file mode 100644 index 0000000..d83c293 --- /dev/null +++ b/assets/starter/2d/images-artic-cc0/pack.json @@ -0,0 +1,658 @@ +{ + "id": "images-artic-cc0", + "name": "Reference photographs and objects (Art Institute of Chicago Open Access)", + "kind": "image", + "licence": "CC0-1.0", + "author": "The Art Institute of Chicago (public-domain works; CC0 per item, artist and reference number in tags)", + "source_url": "https://www.artic.edu/open-access/open-access-images", + "source_commit_or_version": "api.artic.edu artworks is_public_domain=true, image from the museum IIIF server at 843 px width (the server's own cap), retrieved 2026-11-29", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://www.artic.edu/open-access/open-access-images", + "https://api.artic.edu/api/v1/artworks/{id} (per item: is_public_domain=true, copyright_notice empty; response licence note: all data except description is CC0 1.0)" + ], + "items": [ + { + "id": "artic-105101", + "name": "First View of the Yosemite Valley from the Mariposa Trail", + "file": "landscape_105101.jpg", + "category": "landscape", + "tags": [ + "landscape", + "albumen silver print", + "accession:1986.22", + "artist:Carleton Watkins", + "date:1865/66" + ], + "bytes": 135302, + "source_page": "https://www.artic.edu/artworks/105101" + }, + { + "id": "artic-152666", + "name": "Landscape, Switzerland", + "file": "landscape_152666.jpg", + "category": "landscape", + "tags": [ + "landscape", + "albumen silver print", + "accession:1999.247.1-3", + "artist:Adolphe Braun", + "date:c. 1860" + ], + "bytes": 115703, + "source_page": "https://www.artic.edu/artworks/152666" + }, + { + "id": "artic-150429", + "name": "Landscape with Ruin", + "file": "landscape_150429.jpg", + "category": "landscape", + "tags": [ + "landscape", + "albumen silver print", + "accession:1998.20", + "artist:Félix Thiollier", + "date:c. 1870" + ], + "bytes": 168016, + "source_page": "https://www.artic.edu/artworks/150429" + }, + { + "id": "artic-212135", + "name": "Old Faithful", + "file": "landscape_212135.jpg", + "category": "landscape", + "tags": [ + "landscape", + "photograph", + "accession:2012.239", + "artist:William Henry Jackson", + "date:1871" + ], + "bytes": 123421, + "source_page": "https://www.artic.edu/artworks/212135" + }, + { + "id": "artic-140416", + "name": "Ancient Ruins in the Cañon de Chelle, N.M. In a niche 50 feet above present Cañon bed.", + "file": "landscape_140416.jpg", + "category": "landscape", + "tags": [ + "landscape", + "albumen silver print", + "accession:1959.615a", + "artist:Timothy O'Sullivan", + "date:1873" + ], + "bytes": 236621, + "source_page": "https://www.artic.edu/artworks/140416" + }, + { + "id": "artic-63554", + "name": "Big River, from the Rancherie, Mendocino, California", + "file": "landscape_63554.jpg", + "category": "landscape", + "tags": [ + "landscape", + "albumen silver print", + "accession:1981.649", + "artist:Carleton Watkins", + "date:1863" + ], + "bytes": 119343, + "source_page": "https://www.artic.edu/artworks/63554" + }, + { + "id": "artic-150434", + "name": "Forest and Rocks, Fontainebleau", + "file": "nature_150434.jpg", + "category": "nature", + "tags": [ + "nature", + "salted paper print", + "accession:1998.25", + "artist:Achille Quinet", + "date:1860s" + ], + "bytes": 136893, + "source_page": "https://www.artic.edu/artworks/150434" + }, + { + "id": "artic-68994", + "name": "Tree, Forest of Fontainebleau", + "file": "plants_68994.jpg", + "category": "plants", + "tags": [ + "plants", + "albumen silver print", + "accession:1987.54", + "artist:Gustave Le Gray", + "date:c. 1856" + ], + "bytes": 186955, + "source_page": "https://www.artic.edu/artworks/68994" + }, + { + "id": "artic-60482", + "name": "Olivier, Nice (Olive Tree, Nice)", + "file": "plants_60482.jpg", + "category": "plants", + "tags": [ + "plants", + "albumen silver print", + "accession:1980.351", + "artist:Jean-Eugène-Auguste Atget", + "date:c. 1900" + ], + "bytes": 249775, + "source_page": "https://www.artic.edu/artworks/60482" + }, + { + "id": "artic-66552", + "name": "The Dying Chestnut Tree-My Teacher", + "file": "plants_66552.jpg", + "category": "plants", + "tags": [ + "plants", + "gelatin silver (developing-out-paper) pr", + "accession:1949.781", + "artist:Alfred Stieglitz", + "date:1927" + ], + "bytes": 119835, + "source_page": "https://www.artic.edu/artworks/66552" + }, + { + "id": "artic-66526", + "name": "The Dancing Trees", + "file": "plants_66526.jpg", + "category": "plants", + "tags": [ + "plants", + "palladium print", + "accession:1949.772", + "artist:Alfred Stieglitz", + "date:1922" + ], + "bytes": 155362, + "source_page": "https://www.artic.edu/artworks/66526" + }, + { + "id": "artic-66385", + "name": "Tree Set 3", + "file": "plants_66385.jpg", + "category": "plants", + "tags": [ + "plants", + "gelatin silver (developing-out-paper) pr", + "accession:1949.731", + "artist:Alfred Stieglitz", + "date:c. 1924" + ], + "bytes": 81998, + "source_page": "https://www.artic.edu/artworks/66385" + }, + { + "id": "artic-38930", + "name": "Two Plant Specimens", + "file": "plants_38930.jpg", + "category": "plants", + "tags": [ + "plants", + "salted paper print", + "accession:1972.325", + "artist:William Henry Fox Talbot", + "date:1839" + ], + "bytes": 106655, + "source_page": "https://www.artic.edu/artworks/38930" + }, + { + "id": "artic-126485", + "name": "Cloudy Sky, Mediterranean Sea", + "file": "sky_126485.jpg", + "category": "sky", + "tags": [ + "sky", + "albumen silver print", + "accession:1971.577.2", + "artist:Gustave Le Gray", + "date:1857" + ], + "bytes": 67909, + "source_page": "https://www.artic.edu/artworks/126485" + }, + { + "id": "artic-126481", + "name": "Solar Effect in the Clouds-Ocean", + "file": "sky_126481.jpg", + "category": "sky", + "tags": [ + "sky", + "albumen silver print", + "accession:1971.577.14", + "artist:Gustave Le Gray", + "date:1856/57" + ], + "bytes": 76805, + "source_page": "https://www.artic.edu/artworks/126481" + }, + { + "id": "artic-66535", + "name": "Music - A Sequence of Ten Cloud Photographs, No. II", + "file": "sky_66535.jpg", + "category": "sky", + "tags": [ + "sky", + "gelatin silver (developing-out-paper) pr", + "accession:1949.775", + "artist:Alfred Stieglitz", + "date:1922" + ], + "bytes": 77588, + "source_page": "https://www.artic.edu/artworks/66535" + }, + { + "id": "artic-66625", + "name": "Equivalent", + "file": "sky_66625.jpg", + "category": "sky", + "tags": [ + "sky", + "gelatin silver print", + "accession:1949.805", + "artist:Alfred Stieglitz", + "date:1926" + ], + "bytes": 92434, + "source_page": "https://www.artic.edu/artworks/66625" + }, + { + "id": "artic-36848", + "name": "The Great Wave, Sète", + "file": "water_36848.jpg", + "category": "water", + "tags": [ + "water", + "albumen silver print", + "accession:1971.577.11", + "artist:Gustave Le Gray", + "date:1857" + ], + "bytes": 106540, + "source_page": "https://www.artic.edu/artworks/36848" + }, + { + "id": "artic-126479", + "name": "Brig on the Water", + "file": "vehicle_126479.jpg", + "category": "vehicle", + "tags": [ + "vehicle", + "albumen silver print", + "accession:1971.577.12", + "artist:Gustave Le Gray", + "date:1856" + ], + "bytes": 78309, + "source_page": "https://www.artic.edu/artworks/126479" + }, + { + "id": "artic-126487", + "name": "Ships in the Harbor at Sète", + "file": "vehicle_126487.jpg", + "category": "vehicle", + "tags": [ + "vehicle", + "albumen silver print", + "accession:1971.577.4", + "artist:Gustave Le Gray", + "date:1857" + ], + "bytes": 89016, + "source_page": "https://www.artic.edu/artworks/126487" + }, + { + "id": "artic-145957", + "name": "Rue des Grands Carmes, Vue prise de la Rue Ste. Marthe", + "file": "architecture_145957.jpg", + "category": "architecture", + "tags": [ + "architecture", + "albumen silver print", + "accession:1996.473", + "artist:Adolphe Terris", + "date:1862" + ], + "bytes": 180912, + "source_page": "https://www.artic.edu/artworks/145957" + }, + { + "id": "artic-181558", + "name": "Rue de la Montagne-Sainte-Geneviève near the Intersection of Rue LaPlace (Rue de la Montagne-Sainte-Geneviève prés de carrefour de la rue LaPlace)", + "file": "architecture_181558.jpg", + "category": "architecture", + "tags": [ + "architecture", + "albumen print from collodion negative", + "accession:2003.121", + "artist:Charles Marville", + "date:1865/69" + ], + "bytes": 168850, + "source_page": "https://www.artic.edu/artworks/181558" + }, + { + "id": "artic-181557", + "name": "Rue Chartière (impasse Chartière) de la rue de Reims", + "file": "architecture_181557.jpg", + "category": "architecture", + "tags": [ + "architecture", + "albumen print from collodion negative", + "accession:2003.120", + "artist:Charles Marville", + "date:1865/69" + ], + "bytes": 136484, + "source_page": "https://www.artic.edu/artworks/181557" + }, + { + "id": "artic-60079", + "name": "The Portal of Saint Ursinus at Bourges, rue du Vieux Poirier", + "file": "architecture_60079.jpg", + "category": "architecture", + "tags": [ + "architecture", + "albumen silver print", + "accession:1980.213", + "artist:Bisson Frères", + "date:1854" + ], + "bytes": 176996, + "source_page": "https://www.artic.edu/artworks/60079" + }, + { + "id": "artic-97328", + "name": "Tombeau de la chrétienne. Vue du côté nord. (Tomb of the Christian Woman. View of the North Side.)", + "file": "architecture_97328.jpg", + "category": "architecture", + "tags": [ + "architecture", + "albumen silver print", + "accession:1982.307", + "artist:John Beasley Greene", + "date:1855" + ], + "bytes": 70079, + "source_page": "https://www.artic.edu/artworks/97328" + }, + { + "id": "artic-123632", + "name": "Chartres Cathedral, West Facade; Royal Portal, Central Bay", + "file": "architecture_123632.jpg", + "category": "architecture", + "tags": [ + "architecture", + "albumen silver print", + "accession:1961.647", + "artist:Bisson Frères", + "date:1857, printed 1857" + ], + "bytes": 210448, + "source_page": "https://www.artic.edu/artworks/123632" + }, + { + "id": "artic-123636", + "name": "Bibliothèque Imperial du Louvre, Paris", + "file": "architecture_123636.jpg", + "category": "architecture", + "tags": [ + "architecture", + "albumen silver print", + "accession:1961.642", + "artist:Bisson Frères", + "date:1854" + ], + "bytes": 235831, + "source_page": "https://www.artic.edu/artworks/123636" + }, + { + "id": "artic-123652", + "name": "Arc de Septime Sévère, Rome", + "file": "architecture_123652.jpg", + "category": "architecture", + "tags": [ + "architecture", + "albumen silver print", + "accession:1961.663", + "artist:Bisson Frères", + "date:1854/55, printed 1855/65" + ], + "bytes": 147386, + "source_page": "https://www.artic.edu/artworks/123652" + }, + { + "id": "artic-66315", + "name": "The Flatiron", + "file": "architecture_66315.jpg", + "category": "architecture", + "tags": [ + "architecture", + "gelatin silver (developing-out-paper) pr", + "accession:1949.707", + "artist:Alfred Stieglitz", + "date:1903, printed 1920/39" + ], + "bytes": 206308, + "source_page": "https://www.artic.edu/artworks/66315" + }, + { + "id": "artic-103193", + "name": "Khalias Rock-Hewn Temple, Ellora", + "file": "architecture_103193.jpg", + "category": "architecture", + "tags": [ + "architecture", + "gelatin silver printing-out-paper print", + "accession:1984.1226", + "artist:Raja Deen Dayal", + "date:c. 1890" + ], + "bytes": 132233, + "source_page": "https://www.artic.edu/artworks/103193" + }, + { + "id": "artic-18967", + "name": "Versailles, Coin de Parc", + "file": "architecture_18967.jpg", + "category": "architecture", + "tags": [ + "architecture", + "albumen silver print", + "accession:1963.986", + "artist:Jean-Eugène-Auguste Atget", + "date:1904" + ], + "bytes": 208124, + "source_page": "https://www.artic.edu/artworks/18967" + }, + { + "id": "artic-43714", + "name": "E10: English Dining Room of the Georgian Period, 1770–90", + "file": "interior_43714.jpg", + "category": "interior", + "tags": [ + "interior", + "miniature", + "accession:1941.1195", + "artist:Narcissa Thorne", + "date:c. 1937" + ], + "bytes": 112934, + "source_page": "https://www.artic.edu/artworks/43714" + }, + { + "id": "artic-43711", + "name": "E9: English Drawing Room of the Georgian Period, 1770–1800", + "file": "interior_43711.jpg", + "category": "interior", + "tags": [ + "interior", + "miniature", + "accession:1941.1194", + "artist:Narcissa Thorne", + "date:c. 1937" + ], + "bytes": 106385, + "source_page": "https://www.artic.edu/artworks/43711" + }, + { + "id": "artic-43683", + "name": "E1: English Great Room of the Late Tudor Period, 1550–1603", + "file": "interior_43683.jpg", + "category": "interior", + "tags": [ + "interior", + "miniature", + "accession:1941.1186", + "artist:Narcissa Thorne", + "date:c. 1937" + ], + "bytes": 155013, + "source_page": "https://www.artic.edu/artworks/43683" + }, + { + "id": "artic-45316", + "name": "A1: Massachusetts Living Room and Kitchen, 1675–1700", + "file": "interior_45316.jpg", + "category": "interior", + "tags": [ + "interior", + "miniature", + "accession:1942.481", + "artist:Narcissa Thorne", + "date:c. 1940" + ], + "bytes": 80357, + "source_page": "https://www.artic.edu/artworks/45316" + }, + { + "id": "artic-45401", + "name": "A31: Tennessee Entrance Hall, 1835", + "file": "interior_45401.jpg", + "category": "interior", + "tags": [ + "interior", + "miniature", + "accession:1942.511", + "artist:Narcissa Thorne", + "date:c. 1940" + ], + "bytes": 122715, + "source_page": "https://www.artic.edu/artworks/45401" + }, + { + "id": "artic-43739", + "name": "E17: French Bedroom of the Henri IV Period, Late 16th Century", + "file": "interior_43739.jpg", + "category": "interior", + "tags": [ + "interior", + "miniature", + "accession:1941.1202", + "artist:Narcissa Thorne", + "date:c. 1937" + ], + "bytes": 129291, + "source_page": "https://www.artic.edu/artworks/43739" + }, + { + "id": "artic-79234", + "name": "Toothing Plane", + "file": "tools_79234.jpg", + "category": "tools", + "tags": [ + "tools", + "tool", + "accession:1953.104", + "date:c. 1720" + ], + "bytes": 54628, + "source_page": "https://www.artic.edu/artworks/79234" + }, + { + "id": "artic-79228", + "name": "Architect's Compass", + "file": "tools_79228.jpg", + "category": "tools", + "tags": [ + "tools", + "tool", + "accession:1953.101", + "date:17th century" + ], + "bytes": 34968, + "source_page": "https://www.artic.edu/artworks/79228" + }, + { + "id": "artic-117093", + "name": "Hand-and-a-Half Sword", + "file": "object_117093.jpg", + "category": "object", + "tags": [ + "object", + "edged weapon-sword", + "accession:1982.3367", + "date:c. 1520" + ], + "bytes": 37778, + "source_page": "https://www.artic.edu/artworks/117093" + }, + { + "id": "artic-189715", + "name": "King Vulture", + "file": "animals_189715.jpg", + "category": "animals", + "tags": [ + "animals", + "ceramics", + "accession:2007.105", + "artist:Johann Joachim Kändler", + "date:1734" + ], + "bytes": 112174, + "source_page": "https://www.artic.edu/artworks/189715" + }, + { + "id": "artic-108575", + "name": "Elephant Candelabrum Vase (Vase à Tête d'Eléphant)", + "file": "object_108575.jpg", + "category": "object", + "tags": [ + "object", + "vase", + "accession:1986.3446", + "artist:Manufacture nationale de Sèvres", + "date:1757–58" + ], + "bytes": 107002, + "source_page": "https://www.artic.edu/artworks/108575" + }, + { + "id": "artic-77333", + "name": "Under the Wave off Kanagawa (Kanagawa oki nami ura), also known as The Great Wave, from the series \"Thirty-Six Views of Mount Fuji (Fugaku sanjurokkei)\"", + "file": "water_77333.jpg", + "category": "water", + "tags": [ + "water", + "woodblock print", + "accession:1952.343", + "artist:Katsushika Hokusai", + "date:1830/33" + ], + "bytes": 124424, + "source_page": "https://www.artic.edu/artworks/77333" + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/images-artic-cc0/plants_38930.jpg b/assets/starter/2d/images-artic-cc0/plants_38930.jpg new file mode 100644 index 0000000..b571300 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/plants_38930.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/plants_60482.jpg b/assets/starter/2d/images-artic-cc0/plants_60482.jpg new file mode 100644 index 0000000..5e0dcbf Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/plants_60482.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/plants_66385.jpg b/assets/starter/2d/images-artic-cc0/plants_66385.jpg new file mode 100644 index 0000000..5115f45 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/plants_66385.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/plants_66526.jpg b/assets/starter/2d/images-artic-cc0/plants_66526.jpg new file mode 100644 index 0000000..421d04f Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/plants_66526.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/plants_66552.jpg b/assets/starter/2d/images-artic-cc0/plants_66552.jpg new file mode 100644 index 0000000..e5ee00d Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/plants_66552.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/plants_68994.jpg b/assets/starter/2d/images-artic-cc0/plants_68994.jpg new file mode 100644 index 0000000..3f6dba0 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/plants_68994.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/sky_126481.jpg b/assets/starter/2d/images-artic-cc0/sky_126481.jpg new file mode 100644 index 0000000..0936d8b Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/sky_126481.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/sky_126485.jpg b/assets/starter/2d/images-artic-cc0/sky_126485.jpg new file mode 100644 index 0000000..3fe7c6d Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/sky_126485.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/sky_66535.jpg b/assets/starter/2d/images-artic-cc0/sky_66535.jpg new file mode 100644 index 0000000..0a0056b Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/sky_66535.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/sky_66625.jpg b/assets/starter/2d/images-artic-cc0/sky_66625.jpg new file mode 100644 index 0000000..16c5877 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/sky_66625.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/tools_79228.jpg b/assets/starter/2d/images-artic-cc0/tools_79228.jpg new file mode 100644 index 0000000..17bc89f Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/tools_79228.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/tools_79234.jpg b/assets/starter/2d/images-artic-cc0/tools_79234.jpg new file mode 100644 index 0000000..76657d8 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/tools_79234.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/vehicle_126479.jpg b/assets/starter/2d/images-artic-cc0/vehicle_126479.jpg new file mode 100644 index 0000000..bd1ba60 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/vehicle_126479.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/vehicle_126487.jpg b/assets/starter/2d/images-artic-cc0/vehicle_126487.jpg new file mode 100644 index 0000000..d02e9cb Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/vehicle_126487.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/water_36848.jpg b/assets/starter/2d/images-artic-cc0/water_36848.jpg new file mode 100644 index 0000000..a619bc0 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/water_36848.jpg differ diff --git a/assets/starter/2d/images-artic-cc0/water_77333.jpg b/assets/starter/2d/images-artic-cc0/water_77333.jpg new file mode 100644 index 0000000..8c37a09 Binary files /dev/null and b/assets/starter/2d/images-artic-cc0/water_77333.jpg differ diff --git a/assets/starter/2d/images-cleveland-cc0/LICENSE.txt b/assets/starter/2d/images-cleveland-cc0/LICENSE.txt new file mode 100644 index 0000000..c75bdd5 --- /dev/null +++ b/assets/starter/2d/images-cleveland-cc0/LICENSE.txt @@ -0,0 +1,160 @@ +Licence statements fetched on 2026-11-29 (read by FormCraft build, agent 7 audit) + +1. https://www.clevelandart.org/open-access (Cleveland Museum of Art, site statement) + "High-resolution images and data related to the CMA's collection are made available under a Creative Commons Zero (CC0) designation." +2. https://openaccess-api.clevelandart.org/api/artworks/?accession_number=1984.59 (the museum's Open Access API, record of the first item; one such record was queried for each of the 41 items) + Each record returned share_license_status "CC0" and copyright null, with the same title and accession number as the pack entry (the pack replaces an em dash in one title with a hyphen; the page text below has its em dashes replaced by hyphens). + +File check (2026-11-29): each shipped WebP was compared with the record's web JPEG (images.web.url) resized to the same size; mean difference at most 6.3 of 255 (lossy re-encode), so each file is the museum image of that record. Title and accession tags match. + +----- Text shipped by the author with the files (verbatim, as originally copied) ----- + +Statement retrieved from https://www.clevelandart.org/open-access on 2026-11-28 (text of the page, markup removed) + +Open Access | Cleveland Museum of Art +Open Access +Video URL +The Cleveland Museum of Art is proud to be an open access institution, offering the public the ability to download, share, collaborate, remix, and reuse images of public-domain artworks from the museum’s collection, as well as metadata for the entire collection - all without asking permission. High-resolution images and data related to the CMA’s collection are made available under a +Creative Commons Zero +(opens in a new tab) +(CC0) designation. +What is open access? +Open access content (images, data, software, and documentation) is content that the CMA publishes digitally, free of charge, and without copyright and licensing restrictions. For more information about open access, visit the +Creative Commons +(opens in a new tab) +website for an overview. Images, data, software, and documentation offered with Creative Commons Zero can be used in any application, from art making, education, digital media projects, scholarly research, and publications to data science - all without fees or restriction. +Why open access? +Open access is a logical and exciting outgrowth of the CMA’s inclusive mission “to create transformative experiences through art, for the benefit of all the people forever.” The time is right to firmly bring our mission into the 21st century. With this move to open access, we have transformed not only access to the CMA’s collection but also its usability inside and outside the walls of our museum. By expanding access to the collection, we proudly contribute to best practices, both in the quality of images and the wealth of data we will release. +Read the full statement from the CMA’s director, William M. Griswold. +Read the Full Statement +Explore Open Access Artworks on CMA's Collection Online +Search Open Access Artworks +Ways to Access the Open Access Collection +Frequently Asked Questions +How many items are part of open access? +Our open access initiative includes more than half of the museum’s collection. The exact number changes frequently as new works enter the public domain, and we update our open access collection every January. Visit the museum’s +Collection Online +for a current count of open access works. +Do open access artworks require citations? +Works designated as Creative Commons (CC0) do not require attribution or citation. If you choose to cite images and data for a publication, you can use the following format: +Artist. Title. Date (year). Medium. Dimensions. The Cleveland Museum of Art. Credit Line. Accession Number. URL from +www.clevelandart.org/ +Consult the CMA Collection Online or metadata associated with an object via the +application programming interface +(API) or data from the +GitHub Repository +for information that can be used for citations. +Fine Print: +Citation of the CMA’s CC0 or restricted content does not imply endorsement by the CMA, nor does it grant permission to use the CMA’s trademarks without prior approval. Copyrighted content, content with proprietary rights, or content that is otherwise restricted for limited noncommercial, educational, and personal uses should be cited including the URL “ +www.clevelandart.org +” in addition to all copyright and other proprietary notices contained on the materials. +When are images and data not available through open access? +If the CMA has not yet created a digitized image or data of the artwork +If the artwork is under copyright or has other restrictions from the artist, donor, or lender +If the artwork is not fully owned by the CMA +How can I identify images designated as open access on the CMA’s website and affiliates? +Look for the icon with Creative Commons Zero (CC0) on CMA websites and affiliates, along with seeking out the designation embedded in the image or dataset as metadata. +When searching the CMA’s collection, you can filter for open access images: +CC0 designation on an exported CSV file from the CMA's Github Repository +How do I request images not available with CC0 on the CMA’s website, API, or affiliates, or if I need a version of an existing image with a color bar? +Use the Image Services +request form +to submit image requests for objects under copyright or with other restrictions. If images are available, a processing fee of $75 applies. Additional fees may also apply depending on the type and nature of the request. +How do I access CC0 artwork collection data? +Collection Online Art Detail Page +Images and metadata may be downloaded via the “download” button on the artwork page. Metadata is available for every object in the CMA’s collection through open access, image downloads are only available for CC0 artworks. +Image +Access CC0 metadata via the CMA’s public +application program interface +(API). No key or token is required for access. Documentation regarding fields, departments, and data types is available through the API as well. Portions of metadata are made available for all digital images of public domain artworks whose underlying work is in the public domain including a URL to corresponding image file. Artworks in the CMA’s collection which may have copyright or other restrictions have portions of metadata with CC0, but no image file is supplied by CMA. +Users can also access the CMA's collection data via a +GitHub Repository +. Detailed documentation is available here along with the data formatted in JSON and CSV. Please note that the CMA does not support pull requests. Data is refreshed at a weekly rate, so please check often for the latest revisions. +CC0 CMA collection data and images are also available from Internet +Archive, +Wikimedia Commons +, and +Wikidata +. +Can I get written confirmation or a license that I can use a CC0 images, data, software, and documentation in my project? +No. The CMA’s images, data, software, and documentation designated as CC0 will not be issued under separate or individual agreements. See our +Terms and Conditions +for more information. +Do I need to send a cost-free copy of the publication or link to a project in which I used CMA CC0 images or data? +The CMA would be grateful to receive a copy of your print publication reproducing open access images with +Creative Commons Zero +(CC0) images and data, but this is not a requirement. +Print copies can be mailed: +The Cleveland Museum of Art +Ingalls Library and Museum Archives +11150 East Boulevard +Cleveland, OH 44106 +Please send links to electronic resources or e-book information to +the Ingalls Library and Museum Archives +. +Open Access Experiments +Measuring Impact +Since launching our open access initiative, the CMA has been asking, “How is open access making an impact?” In May 2020, in collaboration with local data science firm +Pandata +(opens in a new tab) +, the CMA launched its Live Virtual Dashboards, which update daily. Click through the tabs to see different data sets! +View Live Virtual Dashboards +Half a Decade of Open Access +Five years ago, in January 2019, the CMA launched its open access initiative, which makes available to the public high-resolution images of more than half the artworks in our collection, completely free to view, use, remix, merchandize, and more. +Read More About Five Years of Open Access +Open Access in 3-D +The open access policy extends to three-dimensional (3-D) images of public domain artworks from the collection. +Open access works with available 3-D models +can be viewed in Collection Online. The model files are hosted on +Sketchfab +(opens in a new tab) +and can be downloaded there as well. +You can interact with the +Wade Cup with Animated Script +on the CMA’s Collection Online, on +Sketchfab +(opens in a new tab) +, or try it here! +CMA One Minute Guides +Google Arts and Culture worked with the CMA to create a special edition of their One Minute Guides using Google’s multimodal AI model Gemini and the +CMA’s Open Access API +. Explore personalized guides on sculpture or Chinese art and textiles for foodies, fun seekers, color enthusiasts, and more. +Explore the One Minute Guide +Testimonials +“It’s been especially exciting to watch as people from all over the globe discover and use these images in their own projects via the +Creative Commons Search tool +(opens in a new tab) +. Providing true access to digital knowledge and culture requires more than just publishing content online and calling it ‘open.’ The CMA has exhibited great leadership in this space.” +-Cable Green, Interim CEO and Director of Education, Creative Commons +Wikimedia +“It’s been great to see the impact that the Cleveland Museum of Art’s open access program has had on Wikipedia and other Wikimedia projects. [The] CMA’s open access program allows for new ways for the public to experience the breadth of the museum’s content on a truly global scale.” +5 out of 5 stars +-Kevin Payravi, Cofounder, Ohio Wikimedia Users Group +3-D Content +“The Cleveland Museum of Art’s contribution to open access cultural 3-D content cannot be understated - the quality of 3-D data being made available is matched by the transparency of messaging regarding how this data can be reused and built upon by artists and creators.” +5 out of 5 stars +-Thomas Flynn, Cultural Heritage Lead at Sketchfab +Global Leadership +“The CMA is committed to transparency and universal access, and we anticipate that other institutions around the world will undertake similar initiatives in order to engage new audiences and help bring art to life for all.” +-William Griswold, CMA Director +Awards +OHtec Best of Tech Awards +Winner: +(opens in a new tab) +Best Community Collaboration and Innovation, Open Access Initiative +Museums and the Web Awards +Finalist: +(opens in a new tab) +Behind the Scenes, Open Access Initiative +Media and Technology MUSE Awards +Bronze: +(opens in a new tab) +Research and Innovation, Open Access Initiative +Grands Prix Awards +Silver: +(opens in a new tab) +Cross-Institution Partnership, Launching Open Access: Tool Sets and Protocols for Best Practice +Special thanks to +BlueBridge Networks' +(opens in a new tab) +Tracy and Kevin Goodman whose love for art and culture and all things Cleveland contribute mightily to support the CMA's open access policy, helping us serve many by sharing our collection with the world, and extending our mission to create transformative experiences through art, "for the benefit of all the people forever" well into the twenty-first century. diff --git a/assets/starter/2d/images-cleveland-cc0/animals_1949_186.webp b/assets/starter/2d/images-cleveland-cc0/animals_1949_186.webp new file mode 100644 index 0000000..7e35e44 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/animals_1949_186.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/animals_1955_44.webp b/assets/starter/2d/images-cleveland-cc0/animals_1955_44.webp new file mode 100644 index 0000000..be9b5e8 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/animals_1955_44.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/animals_1964_351.webp b/assets/starter/2d/images-cleveland-cc0/animals_1964_351.webp new file mode 100644 index 0000000..4a0186c Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/animals_1964_351.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/animals_2013_319.webp b/assets/starter/2d/images-cleveland-cc0/animals_2013_319.webp new file mode 100644 index 0000000..9becf45 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/animals_2013_319.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/architecture_2001_152.webp b/assets/starter/2d/images-cleveland-cc0/architecture_2001_152.webp new file mode 100644 index 0000000..e956845 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/architecture_2001_152.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/architecture_2019_56.webp b/assets/starter/2d/images-cleveland-cc0/architecture_2019_56.webp new file mode 100644 index 0000000..b4411d2 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/architecture_2019_56.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/architecture_2020_209.webp b/assets/starter/2d/images-cleveland-cc0/architecture_2020_209.webp new file mode 100644 index 0000000..91017cc Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/architecture_2020_209.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/architecture_2020_213.webp b/assets/starter/2d/images-cleveland-cc0/architecture_2020_213.webp new file mode 100644 index 0000000..05352f0 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/architecture_2020_213.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/architecture_2021_62.webp b/assets/starter/2d/images-cleveland-cc0/architecture_2021_62.webp new file mode 100644 index 0000000..e8ab032 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/architecture_2021_62.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/architecture_2024_79.webp b/assets/starter/2d/images-cleveland-cc0/architecture_2024_79.webp new file mode 100644 index 0000000..bea1277 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/architecture_2024_79.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/ceramics_1918_823.webp b/assets/starter/2d/images-cleveland-cc0/ceramics_1918_823.webp new file mode 100644 index 0000000..350b76a Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/ceramics_1918_823.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/ceramics_1944_190.webp b/assets/starter/2d/images-cleveland-cc0/ceramics_1944_190.webp new file mode 100644 index 0000000..eac9673 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/ceramics_1944_190.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/ceramics_1966_233.webp b/assets/starter/2d/images-cleveland-cc0/ceramics_1966_233.webp new file mode 100644 index 0000000..8bfabdd Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/ceramics_1966_233.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/ceramics_1971_145.webp b/assets/starter/2d/images-cleveland-cc0/ceramics_1971_145.webp new file mode 100644 index 0000000..9f8e6af Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/ceramics_1971_145.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/ceramics_2017_208.webp b/assets/starter/2d/images-cleveland-cc0/ceramics_2017_208.webp new file mode 100644 index 0000000..865f5b3 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/ceramics_2017_208.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/ceramics_2022_224.webp b/assets/starter/2d/images-cleveland-cc0/ceramics_2022_224.webp new file mode 100644 index 0000000..bceb172 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/ceramics_2022_224.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/flowers_1935_233.webp b/assets/starter/2d/images-cleveland-cc0/flowers_1935_233.webp new file mode 100644 index 0000000..f2d8614 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/flowers_1935_233.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/flowers_1953_155.webp b/assets/starter/2d/images-cleveland-cc0/flowers_1953_155.webp new file mode 100644 index 0000000..428b4e9 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/flowers_1953_155.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/flowers_1960_108.webp b/assets/starter/2d/images-cleveland-cc0/flowers_1960_108.webp new file mode 100644 index 0000000..5dbd1b1 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/flowers_1960_108.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/flowers_1967_36.webp b/assets/starter/2d/images-cleveland-cc0/flowers_1967_36.webp new file mode 100644 index 0000000..3150289 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/flowers_1967_36.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/flowers_1987_40_1.webp b/assets/starter/2d/images-cleveland-cc0/flowers_1987_40_1.webp new file mode 100644 index 0000000..fecfebc Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/flowers_1987_40_1.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_1963_262.webp b/assets/starter/2d/images-cleveland-cc0/landscape_1963_262.webp new file mode 100644 index 0000000..844ed19 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_1963_262.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_1967_19.webp b/assets/starter/2d/images-cleveland-cc0/landscape_1967_19.webp new file mode 100644 index 0000000..2a40d11 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_1967_19.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_1967_63.webp b/assets/starter/2d/images-cleveland-cc0/landscape_1967_63.webp new file mode 100644 index 0000000..6c600e5 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_1967_63.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_1980_141.webp b/assets/starter/2d/images-cleveland-cc0/landscape_1980_141.webp new file mode 100644 index 0000000..9160af0 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_1980_141.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_1983_155.webp b/assets/starter/2d/images-cleveland-cc0/landscape_1983_155.webp new file mode 100644 index 0000000..e425577 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_1983_155.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_1983_206.webp b/assets/starter/2d/images-cleveland-cc0/landscape_1983_206.webp new file mode 100644 index 0000000..8023e36 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_1983_206.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_1984_59.webp b/assets/starter/2d/images-cleveland-cc0/landscape_1984_59.webp new file mode 100644 index 0000000..4201113 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_1984_59.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_1992_237.webp b/assets/starter/2d/images-cleveland-cc0/landscape_1992_237.webp new file mode 100644 index 0000000..f2461df Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_1992_237.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_1993_162.webp b/assets/starter/2d/images-cleveland-cc0/landscape_1993_162.webp new file mode 100644 index 0000000..3fa801e Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_1993_162.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_1993_28.webp b/assets/starter/2d/images-cleveland-cc0/landscape_1993_28.webp new file mode 100644 index 0000000..c83181e Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_1993_28.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_2014_12.webp b/assets/starter/2d/images-cleveland-cc0/landscape_2014_12.webp new file mode 100644 index 0000000..8ae8ee6 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_2014_12.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_2015_516.webp b/assets/starter/2d/images-cleveland-cc0/landscape_2015_516.webp new file mode 100644 index 0000000..ecf3bf4 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_2015_516.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_2020_235.webp b/assets/starter/2d/images-cleveland-cc0/landscape_2020_235.webp new file mode 100644 index 0000000..dd7e787 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_2020_235.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/landscape_2024_6_yy.webp b/assets/starter/2d/images-cleveland-cc0/landscape_2024_6_yy.webp new file mode 100644 index 0000000..f614f98 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/landscape_2024_6_yy.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/pack.json b/assets/starter/2d/images-cleveland-cc0/pack.json new file mode 100644 index 0000000..7eb8cbb --- /dev/null +++ b/assets/starter/2d/images-cleveland-cc0/pack.json @@ -0,0 +1,549 @@ +{ + "id": "images-cleveland-cc0", + "name": "Reference images (Cleveland Museum of Art Open Access)", + "kind": "image", + "licence": "CC0-1.0", + "author": "The Cleveland Museum of Art (public-domain works; CC0 per item, artist and accession in tags)", + "source_url": "https://www.clevelandart.org/open-access", + "source_commit_or_version": "openaccess-api.clevelandart.org snapshot, web-size JPEG resized to max 1024 px WebP, retrieved 2026-11-28", + "retrieved": "2026-11-28", + "licence_evidence": [ + "https://www.clevelandart.org/open-access", + "https://openaccess-api.clevelandart.org/api/artworks/?accession_number=1984.59" + ], + "items": [ + { + "id": "cma-1984-59", + "name": "Rocky, Wooded Landscape with a Dell and Weir", + "file": "landscape_1984_59.webp", + "category": "landscape", + "tags": [ + "painting", + "landscape", + "accession:1984.59", + "artist:Thomas Gainsborough (British, 1727–1788)" + ], + "bytes": 25692 + }, + { + "id": "cma-1983-155", + "name": "Prater Landscape", + "file": "landscape_1983_155.webp", + "category": "landscape", + "tags": [ + "painting", + "landscape", + "accession:1983.155", + "artist:Ferdinand Georg Waldmüller (Austrian, 1793–1865)" + ], + "bytes": 59570 + }, + { + "id": "cma-2014-12", + "name": "Vale of Kashmir", + "file": "landscape_2014_12.webp", + "category": "landscape", + "tags": [ + "painting", + "landscape", + "accession:2014.12", + "artist:Robert S. Duncanson (American, 1821–1872)" + ], + "bytes": 22340 + }, + { + "id": "cma-1963-262", + "name": "Landscape", + "file": "landscape_1963_262.webp", + "category": "landscape", + "tags": [ + "painting", + "landscape", + "accession:1963.262", + "artist:Sōami (Japanese, d. 1525)" + ], + "bytes": 56626 + }, + { + "id": "cma-2015-516", + "name": "Landscape with Fishermen", + "file": "landscape_2015_516.webp", + "category": "landscape", + "tags": [ + "painting", + "landscape", + "accession:2015.516", + "artist:Yi Bul-hae (Korean, active 1500s)" + ], + "bytes": 43120 + }, + { + "id": "cma-1967-19", + "name": "Landscape with a Windmill\r\n", + "file": "landscape_1967_19.webp", + "category": "landscape", + "tags": [ + "painting", + "landscape", + "accession:1967.19", + "artist:Jacob van Ruisdael (Dutch, 1628/29–1682)" + ], + "bytes": 39276 + }, + { + "id": "cma-1967-63", + "name": "Low Waterfall in a Wooded Landscape with a Dead Beech Tree", + "file": "landscape_1967_63.webp", + "category": "landscape", + "tags": [ + "painting", + "landscape", + "accession:1967.63", + "artist:Jacob van Ruisdael (Dutch, 1628/29–1682)" + ], + "bytes": 35198 + }, + { + "id": "cma-1993-162", + "name": "Landscape", + "file": "landscape_1993_162.webp", + "category": "landscape", + "tags": [ + "photograph", + "landscape", + "accession:1993.162", + "artist:Henry White (British, 1819–1903)" + ], + "bytes": 82940 + }, + { + "id": "cma-1993-28", + "name": "Untitled (Winter Landscape)", + "file": "landscape_1993_28.webp", + "category": "landscape", + "tags": [ + "photograph", + "landscape", + "accession:1993.28", + "artist:William B. Post (American, 1857–1925)" + ], + "bytes": 41530 + }, + { + "id": "cma-2024-6-yy", + "name": "Untitled (Landscape Scene)", + "file": "landscape_2024_6_yy.webp", + "category": "landscape", + "tags": [ + "photograph", + "landscape", + "accession:2024.6.yy", + "artist:John Burke (Irish, 1845–1915)" + ], + "bytes": 32316 + }, + { + "id": "cma-2020-235", + "name": "Untitled (River, Hong Kong or Macau, China)", + "file": "landscape_2020_235.webp", + "category": "landscape", + "tags": [ + "photograph", + "landscape", + "accession:2020.235", + "artist:William Pryor Floyd (British, 1834–c. 1900)" + ], + "bytes": 51880 + }, + { + "id": "cma-1980-141", + "name": "Winter Landscape", + "file": "landscape_1980_141.webp", + "category": "landscape", + "tags": [ + "photograph", + "landscape", + "accession:1980.141", + "artist:Clarence H. White (American, 1871–1925)" + ], + "bytes": 36564 + }, + { + "id": "cma-1983-206", + "name": "Rowing Home the Schoof-Stuff", + "file": "landscape_1983_206.webp", + "category": "landscape", + "tags": [ + "photograph", + "landscape", + "accession:1983.206", + "artist:Peter Henry Emerson (British, 1856–1936)" + ], + "bytes": 16310 + }, + { + "id": "cma-1992-237", + "name": "Switzerland. Grindelwald, Upper Glacier, Source of the Lutschine", + "file": "landscape_1992_237.webp", + "category": "landscape", + "tags": [ + "photograph", + "landscape", + "accession:1992.237", + "artist:Adolphe Braun (French, 1812–1877)" + ], + "bytes": 57470 + }, + { + "id": "cma-2020-209", + "name": "Perumal Temple Vimana from Corner of Court, Madurai", + "file": "architecture_2020_209.webp", + "category": "architecture", + "tags": [ + "photograph", + "architecture", + "accession:2020.209", + "artist:Captain Linnaeus Tripe (British, 1822–1902)" + ], + "bytes": 57742 + }, + { + "id": "cma-2021-62", + "name": "Kenilworth Castle, Warwickshire, England", + "file": "architecture_2021_62.webp", + "category": "architecture", + "tags": [ + "photograph", + "architecture", + "accession:2021.62", + "artist:Adolphe Braun (French, 1812–1877)" + ], + "bytes": 57228 + }, + { + "id": "cma-2001-152", + "name": "Hoyshaleshvara Temple Sculpture, Halebidu (Halebeedu)", + "file": "architecture_2001_152.webp", + "category": "architecture", + "tags": [ + "photograph", + "architecture", + "accession:2001.152", + "artist:Richard Banner Oakeley (British, 1834–1914)" + ], + "bytes": 76498 + }, + { + "id": "cma-2020-213", + "name": "South Façade of the Quadrangle of the Nayak Darbar Hall, Thanjavur", + "file": "architecture_2020_213.webp", + "category": "architecture", + "tags": [ + "photograph", + "architecture", + "accession:2020.213", + "artist:Captain Linnaeus Tripe (British, 1822–1902)" + ], + "bytes": 57856 + }, + { + "id": "cma-2019-56", + "name": "Nowshera, Kashmir (number 1000)", + "file": "architecture_2019_56.webp", + "category": "architecture", + "tags": [ + "photograph", + "architecture", + "accession:2019.56", + "artist:Samuel Bourne (British, 1834–1912)" + ], + "bytes": 44332 + }, + { + "id": "cma-2024-79", + "name": "Futtypore Sikri-Two of the Marbled Screens in the Tomb of Sheik Selim Chisti", + "file": "architecture_2024_79.webp", + "category": "architecture", + "tags": [ + "photograph", + "architecture", + "accession:2024.79", + "artist:Samuel Bourne (British, 1834–1912)" + ], + "bytes": 113580 + }, + { + "id": "cma-2013-319", + "name": "A floral fantasy of animals and birds (Waq-waq)", + "file": "animals_2013_319.webp", + "category": "animals", + "tags": [ + "painting", + "animals", + "accession:2013.319", + "artist:Unknown" + ], + "bytes": 59678 + }, + { + "id": "cma-1964-351", + "name": "Peregrine Falcons (Duck Hawks)", + "file": "animals_1964_351.webp", + "category": "animals", + "tags": [ + "painting", + "animals", + "accession:1964.351", + "artist:John James Audubon (American, born Haiti, 1785–185" + ], + "bytes": 57554 + }, + { + "id": "cma-1955-44", + "name": "The White Path Between Two Rivers", + "file": "animals_1955_44.webp", + "category": "animals", + "tags": [ + "painting", + "animals", + "accession:1955.44", + "artist:Unknown" + ], + "bytes": 29416 + }, + { + "id": "cma-1949-186", + "name": "Fight Between a Tiger and a Buffalo", + "file": "animals_1949_186.webp", + "category": "animals", + "tags": [ + "painting", + "animals", + "accession:1949.186", + "artist:Henri Rousseau (French, 1844–1910)" + ], + "bytes": 57446 + }, + { + "id": "cma-1974-1", + "name": "Still Life with Herrings", + "file": "still_life_1974_1.webp", + "category": "still life", + "tags": [ + "painting", + "still life", + "accession:1974.1", + "artist:Jean-Siméon Chardin (French, 1699–1779)" + ], + "bytes": 35560 + }, + { + "id": "cma-1980-6", + "name": "Still Life with Sweets", + "file": "still_life_1980_6.webp", + "category": "still life", + "tags": [ + "painting", + "still life", + "accession:1980.6", + "artist:Juan van der Hamen y Léon (Spanish, 1596–1631)" + ], + "bytes": 19616 + }, + { + "id": "cma-1983-97", + "name": "Still Life with Fish, Bread, and Kettle", + "file": "still_life_1983_97.webp", + "category": "still life", + "tags": [ + "painting", + "still life", + "accession:1983.97", + "artist:Luis Meléndez (Spanish, 1716–1780)" + ], + "bytes": 38924 + }, + { + "id": "cma-1980-284", + "name": "Still Life with Asparagus", + "file": "still_life_1980_284.webp", + "category": "still life", + "tags": [ + "painting", + "still life", + "accession:1980.284", + "artist:Philippe Rousseau (French, 1816–1887)" + ], + "bytes": 15018 + }, + { + "id": "cma-1944-190", + "name": "Amphora Vase", + "file": "ceramics_1944_190.webp", + "category": "ceramics", + "tags": [ + "ceramic", + "ceramics", + "accession:1944.190", + "artist:Unknown" + ], + "bytes": 10860 + }, + { + "id": "cma-2022-224", + "name": "Gu-Shaped Flower Vase", + "file": "ceramics_2022_224.webp", + "category": "ceramics", + "tags": [ + "ceramic", + "ceramics", + "accession:2022.224", + "artist:Seifū Yohei III (Japanese, 1851–1914)" + ], + "bytes": 8172 + }, + { + "id": "cma-1918-823", + "name": "Portland Vase", + "file": "ceramics_1918_823.webp", + "category": "ceramics", + "tags": [ + "ceramic", + "ceramics", + "accession:1918.823", + "artist:Josiah Wedgwood and Sons (Britain, Staffordshire, " + ], + "bytes": 16090 + }, + { + "id": "cma-1971-145", + "name": "Vase with Golden Pheasants", + "file": "ceramics_1971_145.webp", + "category": "ceramics", + "tags": [ + "ceramic", + "ceramics", + "accession:1971.145", + "artist:Unknown" + ], + "bytes": 13306 + }, + { + "id": "cma-2017-208", + "name": "Vase", + "file": "ceramics_2017_208.webp", + "category": "ceramics", + "tags": [ + "ceramic", + "ceramics", + "accession:2017.208", + "artist:Walter Crane (British, 1845–1915)" + ], + "bytes": 44478 + }, + { + "id": "cma-1966-233", + "name": "Potpourri Vase with Cover", + "file": "ceramics_1966_233.webp", + "category": "ceramics", + "tags": [ + "ceramic", + "ceramics", + "accession:1966.233", + "artist:Mennecy Factory (French)" + ], + "bytes": 15498 + }, + { + "id": "cma-1979-57", + "name": "Ruin by the Sea", + "file": "seascape_1979_57.webp", + "category": "seascape", + "tags": [ + "painting", + "seascape", + "accession:1979.57", + "artist:Arnold Böcklin (Swiss, 1827–1901)" + ], + "bytes": 18282 + }, + { + "id": "cma-1924-195", + "name": "Early Morning After a Storm at Sea", + "file": "seascape_1924_195.webp", + "category": "seascape", + "tags": [ + "painting", + "seascape", + "accession:1924.195", + "artist:Winslow Homer (American, 1836–1910)" + ], + "bytes": 34286 + }, + { + "id": "cma-1953-155", + "name": "Spring Flowers", + "file": "flowers_1953_155.webp", + "category": "flowers", + "tags": [ + "painting", + "flowers", + "accession:1953.155", + "artist:Claude Monet (French, 1840–1926)" + ], + "bytes": 50192 + }, + { + "id": "cma-1960-108", + "name": "Flowers in a Glass", + "file": "flowers_1960_108.webp", + "category": "flowers", + "tags": [ + "painting", + "flowers", + "accession:1960.108", + "artist:Ambrosius Bosschaert (Dutch, 1573–1621)" + ], + "bytes": 41998 + }, + { + "id": "cma-1935-233", + "name": "Vase of Flowers", + "file": "flowers_1935_233.webp", + "category": "flowers", + "tags": [ + "painting", + "flowers", + "accession:1935.233", + "artist:Odilon Redon (French, 1840–1916)" + ], + "bytes": 55086 + }, + { + "id": "cma-1967-36", + "name": "Ink Flowers", + "file": "flowers_1967_36.webp", + "category": "flowers", + "tags": [ + "painting", + "flowers", + "accession:1967.36", + "artist:Zhao Zhong (Chinese, second half of the 1300s)" + ], + "bytes": 7094 + }, + { + "id": "cma-1987-40-1", + "name": "Winter and Summer Flowers", + "file": "flowers_1987_40_1.webp", + "category": "flowers", + "tags": [ + "painting", + "flowers", + "accession:1987.40.1", + "artist:Kaihō Yūshō (Japanese, 1533–1615)" + ], + "bytes": 22838 + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/images-cleveland-cc0/seascape_1924_195.webp b/assets/starter/2d/images-cleveland-cc0/seascape_1924_195.webp new file mode 100644 index 0000000..c62c952 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/seascape_1924_195.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/seascape_1979_57.webp b/assets/starter/2d/images-cleveland-cc0/seascape_1979_57.webp new file mode 100644 index 0000000..05501b6 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/seascape_1979_57.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/still_life_1974_1.webp b/assets/starter/2d/images-cleveland-cc0/still_life_1974_1.webp new file mode 100644 index 0000000..740ce21 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/still_life_1974_1.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/still_life_1980_284.webp b/assets/starter/2d/images-cleveland-cc0/still_life_1980_284.webp new file mode 100644 index 0000000..88ad365 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/still_life_1980_284.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/still_life_1980_6.webp b/assets/starter/2d/images-cleveland-cc0/still_life_1980_6.webp new file mode 100644 index 0000000..a094eb8 Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/still_life_1980_6.webp differ diff --git a/assets/starter/2d/images-cleveland-cc0/still_life_1983_97.webp b/assets/starter/2d/images-cleveland-cc0/still_life_1983_97.webp new file mode 100644 index 0000000..d1e722f Binary files /dev/null and b/assets/starter/2d/images-cleveland-cc0/still_life_1983_97.webp differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/LICENSE.txt b/assets/starter/2d/images-cleveland-photos-cc0/LICENSE.txt new file mode 100644 index 0000000..6f7db2b --- /dev/null +++ b/assets/starter/2d/images-cleveland-photos-cc0/LICENSE.txt @@ -0,0 +1,161 @@ +Statement retrieved from https://www.clevelandart.org/open-access on 2026-11-28 (copy of the Cleveland pack statement; text of the page, markup removed). Each item was re-checked on 2026-11-29 against https://openaccess-api.clevelandart.org/api/artworks/{id}: share_license_status=CC0, copyright=null. + + +1. https://www.clevelandart.org/open-access (Cleveland Museum of Art, site statement) + "High-resolution images and data related to the CMA's collection are made available under a Creative Commons Zero (CC0) designation." +2. https://openaccess-api.clevelandart.org/api/artworks/?accession_number=1984.59 (the museum's Open Access API, record of the first item; one such record was queried for each of the 41 items) + Each record returned share_license_status "CC0" and copyright null, with the same title and accession number as the pack entry (the pack replaces an em dash in one title with a hyphen; the page text below has its em dashes replaced by hyphens). + +File check (2026-11-29): each shipped WebP was compared with the record's web JPEG (images.web.url) resized to the same size; mean difference at most 6.3 of 255 (lossy re-encode), so each file is the museum image of that record. Title and accession tags match. + +----- Text shipped by the author with the files (verbatim, as originally copied) ----- + +Statement retrieved from https://www.clevelandart.org/open-access on 2026-11-28 (text of the page, markup removed) + +Open Access | Cleveland Museum of Art +Open Access +Video URL +The Cleveland Museum of Art is proud to be an open access institution, offering the public the ability to download, share, collaborate, remix, and reuse images of public-domain artworks from the museum’s collection, as well as metadata for the entire collection - all without asking permission. High-resolution images and data related to the CMA’s collection are made available under a +Creative Commons Zero +(opens in a new tab) +(CC0) designation. +What is open access? +Open access content (images, data, software, and documentation) is content that the CMA publishes digitally, free of charge, and without copyright and licensing restrictions. For more information about open access, visit the +Creative Commons +(opens in a new tab) +website for an overview. Images, data, software, and documentation offered with Creative Commons Zero can be used in any application, from art making, education, digital media projects, scholarly research, and publications to data science - all without fees or restriction. +Why open access? +Open access is a logical and exciting outgrowth of the CMA’s inclusive mission “to create transformative experiences through art, for the benefit of all the people forever.” The time is right to firmly bring our mission into the 21st century. With this move to open access, we have transformed not only access to the CMA’s collection but also its usability inside and outside the walls of our museum. By expanding access to the collection, we proudly contribute to best practices, both in the quality of images and the wealth of data we will release. +Read the full statement from the CMA’s director, William M. Griswold. +Read the Full Statement +Explore Open Access Artworks on CMA's Collection Online +Search Open Access Artworks +Ways to Access the Open Access Collection +Frequently Asked Questions +How many items are part of open access? +Our open access initiative includes more than half of the museum’s collection. The exact number changes frequently as new works enter the public domain, and we update our open access collection every January. Visit the museum’s +Collection Online +for a current count of open access works. +Do open access artworks require citations? +Works designated as Creative Commons (CC0) do not require attribution or citation. If you choose to cite images and data for a publication, you can use the following format: +Artist. Title. Date (year). Medium. Dimensions. The Cleveland Museum of Art. Credit Line. Accession Number. URL from +www.clevelandart.org/ +Consult the CMA Collection Online or metadata associated with an object via the +application programming interface +(API) or data from the +GitHub Repository +for information that can be used for citations. +Fine Print: +Citation of the CMA’s CC0 or restricted content does not imply endorsement by the CMA, nor does it grant permission to use the CMA’s trademarks without prior approval. Copyrighted content, content with proprietary rights, or content that is otherwise restricted for limited noncommercial, educational, and personal uses should be cited including the URL “ +www.clevelandart.org +” in addition to all copyright and other proprietary notices contained on the materials. +When are images and data not available through open access? +If the CMA has not yet created a digitized image or data of the artwork +If the artwork is under copyright or has other restrictions from the artist, donor, or lender +If the artwork is not fully owned by the CMA +How can I identify images designated as open access on the CMA’s website and affiliates? +Look for the icon with Creative Commons Zero (CC0) on CMA websites and affiliates, along with seeking out the designation embedded in the image or dataset as metadata. +When searching the CMA’s collection, you can filter for open access images: +CC0 designation on an exported CSV file from the CMA's Github Repository +How do I request images not available with CC0 on the CMA’s website, API, or affiliates, or if I need a version of an existing image with a color bar? +Use the Image Services +request form +to submit image requests for objects under copyright or with other restrictions. If images are available, a processing fee of $75 applies. Additional fees may also apply depending on the type and nature of the request. +How do I access CC0 artwork collection data? +Collection Online Art Detail Page +Images and metadata may be downloaded via the “download” button on the artwork page. Metadata is available for every object in the CMA’s collection through open access, image downloads are only available for CC0 artworks. +Image +Access CC0 metadata via the CMA’s public +application program interface +(API). No key or token is required for access. Documentation regarding fields, departments, and data types is available through the API as well. Portions of metadata are made available for all digital images of public domain artworks whose underlying work is in the public domain including a URL to corresponding image file. Artworks in the CMA’s collection which may have copyright or other restrictions have portions of metadata with CC0, but no image file is supplied by CMA. +Users can also access the CMA's collection data via a +GitHub Repository +. Detailed documentation is available here along with the data formatted in JSON and CSV. Please note that the CMA does not support pull requests. Data is refreshed at a weekly rate, so please check often for the latest revisions. +CC0 CMA collection data and images are also available from Internet +Archive, +Wikimedia Commons +, and +Wikidata +. +Can I get written confirmation or a license that I can use a CC0 images, data, software, and documentation in my project? +No. The CMA’s images, data, software, and documentation designated as CC0 will not be issued under separate or individual agreements. See our +Terms and Conditions +for more information. +Do I need to send a cost-free copy of the publication or link to a project in which I used CMA CC0 images or data? +The CMA would be grateful to receive a copy of your print publication reproducing open access images with +Creative Commons Zero +(CC0) images and data, but this is not a requirement. +Print copies can be mailed: +The Cleveland Museum of Art +Ingalls Library and Museum Archives +11150 East Boulevard +Cleveland, OH 44106 +Please send links to electronic resources or e-book information to +the Ingalls Library and Museum Archives +. +Open Access Experiments +Measuring Impact +Since launching our open access initiative, the CMA has been asking, “How is open access making an impact?” In May 2020, in collaboration with local data science firm +Pandata +(opens in a new tab) +, the CMA launched its Live Virtual Dashboards, which update daily. Click through the tabs to see different data sets! +View Live Virtual Dashboards +Half a Decade of Open Access +Five years ago, in January 2019, the CMA launched its open access initiative, which makes available to the public high-resolution images of more than half the artworks in our collection, completely free to view, use, remix, merchandize, and more. +Read More About Five Years of Open Access +Open Access in 3-D +The open access policy extends to three-dimensional (3-D) images of public domain artworks from the collection. +Open access works with available 3-D models +can be viewed in Collection Online. The model files are hosted on +Sketchfab +(opens in a new tab) +and can be downloaded there as well. +You can interact with the +Wade Cup with Animated Script +on the CMA’s Collection Online, on +Sketchfab +(opens in a new tab) +, or try it here! +CMA One Minute Guides +Google Arts and Culture worked with the CMA to create a special edition of their One Minute Guides using Google’s multimodal AI model Gemini and the +CMA’s Open Access API +. Explore personalized guides on sculpture or Chinese art and textiles for foodies, fun seekers, color enthusiasts, and more. +Explore the One Minute Guide +Testimonials +“It’s been especially exciting to watch as people from all over the globe discover and use these images in their own projects via the +Creative Commons Search tool +(opens in a new tab) +. Providing true access to digital knowledge and culture requires more than just publishing content online and calling it ‘open.’ The CMA has exhibited great leadership in this space.” +-Cable Green, Interim CEO and Director of Education, Creative Commons +Wikimedia +“It’s been great to see the impact that the Cleveland Museum of Art’s open access program has had on Wikipedia and other Wikimedia projects. [The] CMA’s open access program allows for new ways for the public to experience the breadth of the museum’s content on a truly global scale.” +5 out of 5 stars +-Kevin Payravi, Cofounder, Ohio Wikimedia Users Group +3-D Content +“The Cleveland Museum of Art’s contribution to open access cultural 3-D content cannot be understated - the quality of 3-D data being made available is matched by the transparency of messaging regarding how this data can be reused and built upon by artists and creators.” +5 out of 5 stars +-Thomas Flynn, Cultural Heritage Lead at Sketchfab +Global Leadership +“The CMA is committed to transparency and universal access, and we anticipate that other institutions around the world will undertake similar initiatives in order to engage new audiences and help bring art to life for all.” +-William Griswold, CMA Director +Awards +OHtec Best of Tech Awards +Winner: +(opens in a new tab) +Best Community Collaboration and Innovation, Open Access Initiative +Museums and the Web Awards +Finalist: +(opens in a new tab) +Behind the Scenes, Open Access Initiative +Media and Technology MUSE Awards +Bronze: +(opens in a new tab) +Research and Innovation, Open Access Initiative +Grands Prix Awards +Silver: +(opens in a new tab) +Cross-Institution Partnership, Launching Open Access: Tool Sets and Protocols for Best Practice +Special thanks to +BlueBridge Networks' +(opens in a new tab) +Tracy and Kevin Goodman whose love for art and culture and all things Cleveland contribute mightily to support the CMA's open access policy, helping us serve many by sharing our collection with the world, and extending our mission to create transformative experiences through art, "for the benefit of all the people forever" well into the twenty-first century. diff --git a/assets/starter/2d/images-cleveland-photos-cc0/animals_2021_53.jpg b/assets/starter/2d/images-cleveland-photos-cc0/animals_2021_53.jpg new file mode 100644 index 0000000..586cf9c Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/animals_2021_53.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/animals_2023_121_22.jpg b/assets/starter/2d/images-cleveland-photos-cc0/animals_2023_121_22.jpg new file mode 100644 index 0000000..c3b1b56 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/animals_2023_121_22.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/architecture_1987_26.jpg b/assets/starter/2d/images-cleveland-photos-cc0/architecture_1987_26.jpg new file mode 100644 index 0000000..5c25c63 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/architecture_1987_26.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/architecture_1991_160.jpg b/assets/starter/2d/images-cleveland-photos-cc0/architecture_1991_160.jpg new file mode 100644 index 0000000..f6a428d Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/architecture_1991_160.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/architecture_1991_35.jpg b/assets/starter/2d/images-cleveland-photos-cc0/architecture_1991_35.jpg new file mode 100644 index 0000000..bb41ec6 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/architecture_1991_35.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/architecture_1992_120.jpg b/assets/starter/2d/images-cleveland-photos-cc0/architecture_1992_120.jpg new file mode 100644 index 0000000..0326658 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/architecture_1992_120.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/architecture_1992_234.jpg b/assets/starter/2d/images-cleveland-photos-cc0/architecture_1992_234.jpg new file mode 100644 index 0000000..b468ff9 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/architecture_1992_234.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/architecture_2021_55.jpg b/assets/starter/2d/images-cleveland-photos-cc0/architecture_2021_55.jpg new file mode 100644 index 0000000..7e2867b Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/architecture_2021_55.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/architecture_2021_56.jpg b/assets/starter/2d/images-cleveland-photos-cc0/architecture_2021_56.jpg new file mode 100644 index 0000000..53e65d1 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/architecture_2021_56.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/architecture_2022_33.jpg b/assets/starter/2d/images-cleveland-photos-cc0/architecture_2022_33.jpg new file mode 100644 index 0000000..61fa1c3 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/architecture_2022_33.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/architecture_2024_5_36.jpg b/assets/starter/2d/images-cleveland-photos-cc0/architecture_2024_5_36.jpg new file mode 100644 index 0000000..16315f5 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/architecture_2024_5_36.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/architecture_2024_5_40.jpg b/assets/starter/2d/images-cleveland-photos-cc0/architecture_2024_5_40.jpg new file mode 100644 index 0000000..1480d45 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/architecture_2024_5_40.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/interior_2024_5_28.jpg b/assets/starter/2d/images-cleveland-photos-cc0/interior_2024_5_28.jpg new file mode 100644 index 0000000..2110c32 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/interior_2024_5_28.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/landscape_1985_94.jpg b/assets/starter/2d/images-cleveland-photos-cc0/landscape_1985_94.jpg new file mode 100644 index 0000000..459b0be Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/landscape_1985_94.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/landscape_1992_12.jpg b/assets/starter/2d/images-cleveland-photos-cc0/landscape_1992_12.jpg new file mode 100644 index 0000000..38c55b6 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/landscape_1992_12.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/landscape_1992_238.jpg b/assets/starter/2d/images-cleveland-photos-cc0/landscape_1992_238.jpg new file mode 100644 index 0000000..123f87e Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/landscape_1992_238.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/landscape_1993_217.jpg b/assets/starter/2d/images-cleveland-photos-cc0/landscape_1993_217.jpg new file mode 100644 index 0000000..b1347ff Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/landscape_1993_217.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/landscape_1995_27.jpg b/assets/starter/2d/images-cleveland-photos-cc0/landscape_1995_27.jpg new file mode 100644 index 0000000..08c8876 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/landscape_1995_27.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/landscape_2002_45.jpg b/assets/starter/2d/images-cleveland-photos-cc0/landscape_2002_45.jpg new file mode 100644 index 0000000..8127e00 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/landscape_2002_45.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/landscape_2024_5_22.jpg b/assets/starter/2d/images-cleveland-photos-cc0/landscape_2024_5_22.jpg new file mode 100644 index 0000000..fa7763a Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/landscape_2024_5_22.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/landscape_2024_5_24.jpg b/assets/starter/2d/images-cleveland-photos-cc0/landscape_2024_5_24.jpg new file mode 100644 index 0000000..c5baa97 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/landscape_2024_5_24.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/nature_1992_242.jpg b/assets/starter/2d/images-cleveland-photos-cc0/nature_1992_242.jpg new file mode 100644 index 0000000..f0c8c1a Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/nature_1992_242.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/object_1990_116.jpg b/assets/starter/2d/images-cleveland-photos-cc0/object_1990_116.jpg new file mode 100644 index 0000000..c6132d6 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/object_1990_116.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/object_1992_121.jpg b/assets/starter/2d/images-cleveland-photos-cc0/object_1992_121.jpg new file mode 100644 index 0000000..7081fdf Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/object_1992_121.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/pack.json b/assets/starter/2d/images-cleveland-photos-cc0/pack.json new file mode 100644 index 0000000..c23d788 --- /dev/null +++ b/assets/starter/2d/images-cleveland-photos-cc0/pack.json @@ -0,0 +1,631 @@ +{ + "id": "images-cleveland-photos-cc0", + "name": "Reference photographs (Cleveland Museum of Art Open Access)", + "kind": "image", + "licence": "CC0-1.0", + "author": "The Cleveland Museum of Art (public-domain photographs; CC0 per item, photographer and accession in tags)", + "source_url": "https://www.clevelandart.org/open-access", + "source_commit_or_version": "openaccess-api.clevelandart.org artworks, cc0 filter, type Photograph, print JPEG resized to max 1400 px, retrieved 2026-11-29", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://www.clevelandart.org/open-access", + "https://openaccess-api.clevelandart.org/api/artworks/?cc0&type=Photograph (per item: share_license_status=CC0, copyright=null; record URL in source_page)" + ], + "items": [ + { + "id": "cma-ph-1992-12", + "name": "Bridal Veil, Yosemite", + "file": "landscape_1992_12.jpg", + "category": "landscape", + "tags": [ + "landscape", + "photograph", + "accession:1992.12", + "artist:Carleton E. Watkins (American, 1829–1916)", + "date:1865–66" + ], + "bytes": 241184, + "source_page": "https://clevelandart.org/art/1992.12" + }, + { + "id": "cma-ph-1985-94", + "name": "Mount Maudit, Savoy", + "file": "landscape_1985_94.jpg", + "category": "landscape", + "tags": [ + "landscape", + "photograph", + "accession:1985.94", + "artist:Auguste-Rosalie Bisson (French, 1826–1900)", + "date:1860" + ], + "bytes": 192415, + "source_page": "https://clevelandart.org/art/1985.94" + }, + { + "id": "cma-ph-1995-27", + "name": "Gorge at Eaux Chaudes, Pyrenees", + "file": "landscape_1995_27.jpg", + "category": "landscape", + "tags": [ + "landscape", + "photograph", + "accession:1995.27", + "artist:Jean-Jacques Heilmann (French, 1822–1859)", + "date:c. 1855" + ], + "bytes": 181510, + "source_page": "https://clevelandart.org/art/1995.27" + }, + { + "id": "cma-ph-2002-45", + "name": "Sand Dunes, Carson Desert, Nevada", + "file": "landscape_2002_45.jpg", + "category": "landscape", + "tags": [ + "landscape", + "photograph", + "accession:2002.45", + "artist:Timothy H. O'Sullivan (American, 1840–1882)", + "date:1867" + ], + "bytes": 195050, + "source_page": "https://clevelandart.org/art/2002.45" + }, + { + "id": "cma-ph-1992-238", + "name": "East Humboldt Mountains, Utah", + "file": "landscape_1992_238.jpg", + "category": "landscape", + "tags": [ + "landscape", + "photograph", + "accession:1992.238", + "artist:Timothy H. O'Sullivan (American, 1840–1882)", + "date:1868" + ], + "bytes": 246420, + "source_page": "https://clevelandart.org/art/1992.238" + }, + { + "id": "cma-ph-1992-242", + "name": "Hell's Half Acre, Prismatic Springs", + "file": "nature_1992_242.jpg", + "category": "nature", + "tags": [ + "nature", + "photograph", + "accession:1992.242", + "artist:Frank Jay Haynes (American, 1853–1921)", + "date:c. late 1880s" + ], + "bytes": 207556, + "source_page": "https://clevelandart.org/art/1992.242" + }, + { + "id": "cma-ph-2024-5-22", + "name": "The Upper Himmalayahs. View in the Buspa Valley from Sangla", + "file": "landscape_2024_5_22.jpg", + "category": "landscape", + "tags": [ + "landscape", + "photograph", + "accession:2024.5.22", + "artist:Samuel Bourne (British, 1834–1912)", + "date:1863–70" + ], + "bytes": 248651, + "source_page": "https://clevelandart.org/art/2024.5.22" + }, + { + "id": "cma-ph-2024-5-24", + "name": "The Upper Himmalayahs. View of the Mountain of Bunderpoonch with the Jumnootri Peak, 20,458 above the Level of the Sea", + "file": "landscape_2024_5_24.jpg", + "category": "landscape", + "tags": [ + "landscape", + "photograph", + "accession:2024.5.24", + "artist:Samuel Bourne (British, 1834–1912)", + "date:1863–70" + ], + "bytes": 246955, + "source_page": "https://clevelandart.org/art/2024.5.24" + }, + { + "id": "cma-ph-2024-5-25", + "name": "The Upper Himmalayahs. The Dodee Tal in Lake", + "file": "water_2024_5_25.jpg", + "category": "water", + "tags": [ + "water", + "photograph", + "accession:2024.5.25", + "artist:Samuel Bourne (British, 1834–1912)", + "date:1863–70" + ], + "bytes": 285786, + "source_page": "https://clevelandart.org/art/2024.5.25" + }, + { + "id": "cma-ph-2024-132", + "name": "Great Dismal Swamp, Virginia", + "file": "plants_2024_132.jpg", + "category": "plants", + "tags": [ + "plants", + "photograph", + "accession:2024.132", + "artist:Israel Cook Russell (American, 1852–1906)", + "date:c. 1872–90" + ], + "bytes": 276027, + "source_page": "https://clevelandart.org/art/2024.132" + }, + { + "id": "cma-ph-1988-88", + "name": "Bear Lake, LVRR", + "file": "water_1988_88.jpg", + "category": "water", + "tags": [ + "water", + "photograph", + "accession:1988.88", + "artist:William H. Rau (American, 1855–1920)", + "date:c. 1898–99" + ], + "bytes": 233567, + "source_page": "https://clevelandart.org/art/1988.88" + }, + { + "id": "cma-ph-1993-217", + "name": "Cinnabar Mountain, Devil Slide", + "file": "landscape_1993_217.jpg", + "category": "landscape", + "tags": [ + "landscape", + "photograph", + "accession:1993.217", + "artist:Frank Jay Haynes (American, 1853–1921)", + "date:1880s" + ], + "bytes": 225599, + "source_page": "https://clevelandart.org/art/1993.217" + }, + { + "id": "cma-ph-2024-6-gg", + "name": "The River Gorge", + "file": "water_2024_6_gg.jpg", + "category": "water", + "tags": [ + "water", + "photograph", + "accession:2024.6.gg", + "artist:John Burke (Irish, 1845–1915)", + "date:1878–80" + ], + "bytes": 245956, + "source_page": "https://clevelandart.org/art/2024.6.gg" + }, + { + "id": "cma-ph-1988-191", + "name": "Sky Study, Paris", + "file": "sky_1988_191.jpg", + "category": "sky", + "tags": [ + "sky", + "photograph", + "accession:1988.191", + "artist:Charles Marville (French, 1813–1879)", + "date:1856–57" + ], + "bytes": 243524, + "source_page": "https://clevelandart.org/art/1988.191" + }, + { + "id": "cma-ph-2025-17", + "name": "A Winter's Sunrise", + "file": "sky_2025_17.jpg", + "category": "sky", + "tags": [ + "sky", + "photograph", + "accession:2025.17", + "artist:Peter Henry Emerson (British, 1856–1936)", + "date:before 1891, published 1895" + ], + "bytes": 200376, + "source_page": "https://clevelandart.org/art/2025.17" + }, + { + "id": "cma-ph-2022-35", + "name": "View of Ste-Adrese Beach with the Dumont Baths", + "file": "water_2022_35.jpg", + "category": "water", + "tags": [ + "water", + "photograph", + "accession:2022.35", + "artist:Gustave Le Gray (French, 1820–1884)", + "date:1856" + ], + "bytes": 233713, + "source_page": "https://clevelandart.org/art/2022.35" + }, + { + "id": "cma-ph-2026-62", + "name": "Yuen Fu Rapids", + "file": "water_2026_62.jpg", + "category": "water", + "tags": [ + "water", + "photograph", + "accession:2026.62", + "artist:John Thomson (Scottish, 1837–1921)", + "date:1873" + ], + "bytes": 199252, + "source_page": "https://clevelandart.org/art/2026.62" + }, + { + "id": "cma-ph-2025-16", + "name": "Marsh Weeds", + "file": "plants_2025_16.jpg", + "category": "plants", + "tags": [ + "plants", + "photograph", + "accession:2025.16", + "artist:Peter Henry Emerson (British, 1856–1936)", + "date:before 1891, published 1895" + ], + "bytes": 202943, + "source_page": "https://clevelandart.org/art/2025.16" + }, + { + "id": "cma-ph-2024-5-15", + "name": "Hyree Lake. South End of the Lake", + "file": "water_2024_5_15.jpg", + "category": "water", + "tags": [ + "water", + "photograph", + "accession:2024.5.15", + "artist:Samuel Bourne (British, 1834–1912)", + "date:1863–70" + ], + "bytes": 252750, + "source_page": "https://clevelandart.org/art/2024.5.15" + }, + { + "id": "cma-ph-1989-29", + "name": "Road in the Forest", + "file": "plants_1989_29.jpg", + "category": "plants", + "tags": [ + "plants", + "photograph", + "accession:1989.29", + "artist:Eugène Cuvelier (French, 1837–1900)", + "date:1860–1863" + ], + "bytes": 235605, + "source_page": "https://clevelandart.org/art/1989.29" + }, + { + "id": "cma-ph-1988-64", + "name": "Pathway in the Forest of Fontainebleau", + "file": "plants_1988_64.jpg", + "category": "plants", + "tags": [ + "plants", + "photograph", + "accession:1988.64", + "artist:Gustave Le Gray (French, 1820–1884)", + "date:1849–52" + ], + "bytes": 234048, + "source_page": "https://clevelandart.org/art/1988.64" + }, + { + "id": "cma-ph-2006-4", + "name": "Winter Trees Reflected in a Pond", + "file": "plants_2006_4.jpg", + "category": "plants", + "tags": [ + "plants", + "photograph", + "accession:2006.4", + "artist:William Henry Fox Talbot (British, 1800–1877)", + "date:1841–42" + ], + "bytes": 239424, + "source_page": "https://clevelandart.org/art/2006.4" + }, + { + "id": "cma-ph-1988-239", + "name": "Scotch Firs, Hawkhurst", + "file": "plants_1988_239.jpg", + "category": "plants", + "tags": [ + "plants", + "photograph", + "accession:1988.239", + "artist:Benjamin Brecknell Turner (British, 1815–1894)", + "date:1853" + ], + "bytes": 237353, + "source_page": "https://clevelandart.org/art/1988.239" + }, + { + "id": "cma-ph-1994-93", + "name": "Study of a Birch Tree, Barbizon", + "file": "plants_1994_93.jpg", + "category": "plants", + "tags": [ + "plants", + "photograph", + "accession:1994.93", + "artist:Constant Alexandre Famin (French, 1827–1888)", + "date:1860s-1870s" + ], + "bytes": 240304, + "source_page": "https://clevelandart.org/art/1994.93" + }, + { + "id": "cma-ph-1988-86", + "name": "Floral Still Life (Bleeding Hearts)", + "file": "plants_1988_86.jpg", + "category": "plants", + "tags": [ + "plants", + "photograph", + "accession:1988.86", + "artist:Charles Aubry (French, 1811–1877)", + "date:c. 1865" + ], + "bytes": 210321, + "source_page": "https://clevelandart.org/art/1988.86" + }, + { + "id": "cma-ph-1991-35", + "name": "Notre-Dame, Paris", + "file": "architecture_1991_35.jpg", + "category": "architecture", + "tags": [ + "architecture", + "photograph", + "accession:1991.35", + "artist:Édouard Baldus (French, 1813–1889)", + "date:1852–53" + ], + "bytes": 187070, + "source_page": "https://clevelandart.org/art/1991.35" + }, + { + "id": "cma-ph-2021-56", + "name": "The Parthenon", + "file": "architecture_2021_56.jpg", + "category": "architecture", + "tags": [ + "architecture", + "photograph", + "accession:2021.56", + "artist:Frédéric Boissonnas (Swiss, 1858–1944)", + "date:c. 1907–20" + ], + "bytes": 219257, + "source_page": "https://clevelandart.org/art/2021.56" + }, + { + "id": "cma-ph-2022-33", + "name": "Lyon. Viaduc du Rhône", + "file": "architecture_2022_33.jpg", + "category": "architecture", + "tags": [ + "architecture", + "photograph", + "accession:2022.33", + "artist:Édouard Baldus (French, 1813–1889)", + "date:c. 1860" + ], + "bytes": 171744, + "source_page": "https://clevelandart.org/art/2022.33" + }, + { + "id": "cma-ph-2021-55", + "name": "Chemin de fer de Toulouse à Bayonne. Pont de l'Aran (en trois arches de 17m d'ouverture chacune). Situation des travaux au 21 juillet 1861", + "file": "architecture_2021_55.jpg", + "category": "architecture", + "tags": [ + "architecture", + "photograph", + "accession:2021.55", + "artist:Édouard Baldus (French, 1813–1889)", + "date:1861" + ], + "bytes": 168733, + "source_page": "https://clevelandart.org/art/2021.55" + }, + { + "id": "cma-ph-2024-5-40", + "name": "Agra. View of the Taj from the Garden", + "file": "architecture_2024_5_40.jpg", + "category": "architecture", + "tags": [ + "architecture", + "photograph", + "accession:2024.5.40", + "artist:Samuel Bourne (British, 1834–1912)", + "date:1863–70" + ], + "bytes": 271624, + "source_page": "https://clevelandart.org/art/2024.5.40" + }, + { + "id": "cma-ph-1991-160", + "name": "Pavilion Richelieu, Louvre, Paris", + "file": "architecture_1991_160.jpg", + "category": "architecture", + "tags": [ + "architecture", + "photograph", + "accession:1991.160", + "artist:Édouard Baldus (French, 1813–1889)", + "date:1856–57" + ], + "bytes": 247582, + "source_page": "https://clevelandart.org/art/1991.160" + }, + { + "id": "cma-ph-1992-120", + "name": "Church at Auvers", + "file": "architecture_1992_120.jpg", + "category": "architecture", + "tags": [ + "architecture", + "photograph", + "accession:1992.120", + "artist:Édouard Baldus (French, 1813–1889)", + "date:1855" + ], + "bytes": 224512, + "source_page": "https://clevelandart.org/art/1992.120" + }, + { + "id": "cma-ph-1987-26", + "name": "Chateau Montesquieu", + "file": "architecture_1987_26.jpg", + "category": "architecture", + "tags": [ + "architecture", + "photograph", + "accession:1987.26", + "artist:Frederick H. Evans (British, 1853–1943)", + "date:c. 1900" + ], + "bytes": 154228, + "source_page": "https://clevelandart.org/art/1987.26" + }, + { + "id": "cma-ph-2024-5-36", + "name": "Lucknow. The Great Emambara and Mosque", + "file": "architecture_2024_5_36.jpg", + "category": "architecture", + "tags": [ + "architecture", + "photograph", + "accession:2024.5.36", + "artist:Samuel Bourne (British, 1834–1912)", + "date:1863–70" + ], + "bytes": 230075, + "source_page": "https://clevelandart.org/art/2024.5.36" + }, + { + "id": "cma-ph-1992-234", + "name": "Large Speos - View taken from the Sand Slope (Temple of Ramesses II), Abu Simbel", + "file": "architecture_1992_234.jpg", + "category": "architecture", + "tags": [ + "architecture", + "photograph", + "accession:1992.234", + "artist:Félix Teynard (French, 1817–1892)", + "date:1851–52" + ], + "bytes": 185449, + "source_page": "https://clevelandart.org/art/1992.234" + }, + { + "id": "cma-ph-2024-5-28", + "name": "Delhi. The Emperor's Palace. Interior of Dewani in Private Hall", + "file": "interior_2024_5_28.jpg", + "category": "interior", + "tags": [ + "interior", + "photograph", + "accession:2024.5.28", + "artist:Samuel Bourne (British, 1834–1912)", + "date:1863–70" + ], + "bytes": 248617, + "source_page": "https://clevelandart.org/art/2024.5.28" + }, + { + "id": "cma-ph-1992-121", + "name": "Articles of Glass", + "file": "object_1992_121.jpg", + "category": "object", + "tags": [ + "object", + "photograph", + "accession:1992.121", + "artist:William Henry Fox Talbot (British, 1800–1877)", + "date:1844" + ], + "bytes": 228620, + "source_page": "https://clevelandart.org/art/1992.121" + }, + { + "id": "cma-ph-1990-116", + "name": "Ornamental Scupture", + "file": "object_1990_116.jpg", + "category": "object", + "tags": [ + "object", + "photograph", + "accession:1990.116", + "artist:Louis-Émile Durandelle (French, 1839–1917)", + "date:c. 1865–72" + ], + "bytes": 242712, + "source_page": "https://clevelandart.org/art/1990.116" + }, + { + "id": "cma-ph-2021-53", + "name": "Monkey on Branch", + "file": "animals_2021_53.jpg", + "category": "animals", + "tags": [ + "animals", + "photograph", + "accession:2021.53", + "artist:Louis Jules Duboscq-Soleil (French, 1817–1886)", + "date:c. 1855" + ], + "bytes": 177159, + "source_page": "https://clevelandart.org/art/2021.53" + }, + { + "id": "cma-ph-2023-121-22", + "name": "Lord William Beresford's horses", + "file": "animals_2023_121_22.jpg", + "category": "animals", + "tags": [ + "animals", + "photograph", + "accession:2023.121.22", + "artist:Raja Deen Dayal (Indian, 1844–1905)", + "date:c. 1882–87" + ], + "bytes": 227295, + "source_page": "https://clevelandart.org/art/2023.121.22" + }, + { + "id": "cma-ph-2024-5-49", + "name": "Calcutta. The Custom House Landing Place. Shipping in the River Hoogly", + "file": "vehicle_2024_5_49.jpg", + "category": "vehicle", + "tags": [ + "vehicle", + "photograph", + "accession:2024.5.49", + "artist:Samuel Bourne (British, 1834–1912)", + "date:1863–70" + ], + "bytes": 243876, + "source_page": "https://clevelandart.org/art/2024.5.49" + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/images-cleveland-photos-cc0/plants_1988_239.jpg b/assets/starter/2d/images-cleveland-photos-cc0/plants_1988_239.jpg new file mode 100644 index 0000000..5a4ed9b Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/plants_1988_239.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/plants_1988_64.jpg b/assets/starter/2d/images-cleveland-photos-cc0/plants_1988_64.jpg new file mode 100644 index 0000000..e300e04 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/plants_1988_64.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/plants_1988_86.jpg b/assets/starter/2d/images-cleveland-photos-cc0/plants_1988_86.jpg new file mode 100644 index 0000000..24fc7b3 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/plants_1988_86.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/plants_1989_29.jpg b/assets/starter/2d/images-cleveland-photos-cc0/plants_1989_29.jpg new file mode 100644 index 0000000..3b13f27 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/plants_1989_29.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/plants_1994_93.jpg b/assets/starter/2d/images-cleveland-photos-cc0/plants_1994_93.jpg new file mode 100644 index 0000000..a586b6a Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/plants_1994_93.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/plants_2006_4.jpg b/assets/starter/2d/images-cleveland-photos-cc0/plants_2006_4.jpg new file mode 100644 index 0000000..3238f12 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/plants_2006_4.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/plants_2024_132.jpg b/assets/starter/2d/images-cleveland-photos-cc0/plants_2024_132.jpg new file mode 100644 index 0000000..1d0f6fd Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/plants_2024_132.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/plants_2025_16.jpg b/assets/starter/2d/images-cleveland-photos-cc0/plants_2025_16.jpg new file mode 100644 index 0000000..bfb1f05 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/plants_2025_16.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/sky_1988_191.jpg b/assets/starter/2d/images-cleveland-photos-cc0/sky_1988_191.jpg new file mode 100644 index 0000000..0c9bd3c Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/sky_1988_191.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/sky_2025_17.jpg b/assets/starter/2d/images-cleveland-photos-cc0/sky_2025_17.jpg new file mode 100644 index 0000000..f470cb7 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/sky_2025_17.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/vehicle_2024_5_49.jpg b/assets/starter/2d/images-cleveland-photos-cc0/vehicle_2024_5_49.jpg new file mode 100644 index 0000000..36decbd Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/vehicle_2024_5_49.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/water_1988_88.jpg b/assets/starter/2d/images-cleveland-photos-cc0/water_1988_88.jpg new file mode 100644 index 0000000..1d9ea9f Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/water_1988_88.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/water_2022_35.jpg b/assets/starter/2d/images-cleveland-photos-cc0/water_2022_35.jpg new file mode 100644 index 0000000..33afcec Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/water_2022_35.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/water_2024_5_15.jpg b/assets/starter/2d/images-cleveland-photos-cc0/water_2024_5_15.jpg new file mode 100644 index 0000000..168498e Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/water_2024_5_15.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/water_2024_5_25.jpg b/assets/starter/2d/images-cleveland-photos-cc0/water_2024_5_25.jpg new file mode 100644 index 0000000..77cadd9 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/water_2024_5_25.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/water_2024_6_gg.jpg b/assets/starter/2d/images-cleveland-photos-cc0/water_2024_6_gg.jpg new file mode 100644 index 0000000..907f814 Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/water_2024_6_gg.jpg differ diff --git a/assets/starter/2d/images-cleveland-photos-cc0/water_2026_62.jpg b/assets/starter/2d/images-cleveland-photos-cc0/water_2026_62.jpg new file mode 100644 index 0000000..a11c5cf Binary files /dev/null and b/assets/starter/2d/images-cleveland-photos-cc0/water_2026_62.jpg differ diff --git a/assets/starter/2d/images-met-cc0/LICENSE.txt b/assets/starter/2d/images-met-cc0/LICENSE.txt new file mode 100644 index 0000000..8111445 --- /dev/null +++ b/assets/starter/2d/images-met-cc0/LICENSE.txt @@ -0,0 +1,13 @@ +Statements retrieved on 2026-11-29. + +1. The Met Open Access policy page, https://www.metmuseum.org/about-the-met/policies-and-documents/open-access +(The page refused the shell with HTTP 429, so it was read with the WebFetch tool, which returned these quotations.) + - Open Access "makes images of public-domain artworks and basic data on all accessioned works" in the collection "available for unrestricted use under Creative Commons Zero (CC0)." + - "Anyone can download, share, and remix images and data about artworks in The Met collection." + - Data and images are "available for free and unrestricted use." + - The API provides "high resolution images (JPEG format) that are in the public domain." + +2. The Met Collection API documentation, https://metmuseum.github.io/ (fetched directly): + "The Met's Open Access datasets are available through our API. The API (RESTful web service in JSON format) gives access to all of The Met's Open Access data and to corresponding high resolution images (JPEG format) that are in the public domain." + Field isPublicDomain: When "true" indicates an artwork in the Public Domain. + Every item in this pack was read from https://collectionapi.metmuseum.org/public/collection/v1/objects/{objectID} on 2026-11-29 and has isPublicDomain=true with a primaryImage URL (images.metmuseum.org). diff --git a/assets/starter/2d/images-met-cc0/animals_266656.jpg b/assets/starter/2d/images-met-cc0/animals_266656.jpg new file mode 100644 index 0000000..ad4d862 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/animals_266656.jpg differ diff --git a/assets/starter/2d/images-met-cc0/architecture_261809.jpg b/assets/starter/2d/images-met-cc0/architecture_261809.jpg new file mode 100644 index 0000000..cbedf29 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/architecture_261809.jpg differ diff --git a/assets/starter/2d/images-met-cc0/architecture_283069.jpg b/assets/starter/2d/images-met-cc0/architecture_283069.jpg new file mode 100644 index 0000000..e061972 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/architecture_283069.jpg differ diff --git a/assets/starter/2d/images-met-cc0/architecture_285452.jpg b/assets/starter/2d/images-met-cc0/architecture_285452.jpg new file mode 100644 index 0000000..09f1edc Binary files /dev/null and b/assets/starter/2d/images-met-cc0/architecture_285452.jpg differ diff --git a/assets/starter/2d/images-met-cc0/architecture_285983.jpg b/assets/starter/2d/images-met-cc0/architecture_285983.jpg new file mode 100644 index 0000000..9a16b68 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/architecture_285983.jpg differ diff --git a/assets/starter/2d/images-met-cc0/architecture_302645.jpg b/assets/starter/2d/images-met-cc0/architecture_302645.jpg new file mode 100644 index 0000000..e7dc439 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/architecture_302645.jpg differ diff --git a/assets/starter/2d/images-met-cc0/architecture_728358.jpg b/assets/starter/2d/images-met-cc0/architecture_728358.jpg new file mode 100644 index 0000000..aa4f82e Binary files /dev/null and b/assets/starter/2d/images-met-cc0/architecture_728358.jpg differ diff --git a/assets/starter/2d/images-met-cc0/interior_264540.jpg b/assets/starter/2d/images-met-cc0/interior_264540.jpg new file mode 100644 index 0000000..4cfeba7 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/interior_264540.jpg differ diff --git a/assets/starter/2d/images-met-cc0/interior_289717.jpg b/assets/starter/2d/images-met-cc0/interior_289717.jpg new file mode 100644 index 0000000..59903da Binary files /dev/null and b/assets/starter/2d/images-met-cc0/interior_289717.jpg differ diff --git a/assets/starter/2d/images-met-cc0/interior_290473.jpg b/assets/starter/2d/images-met-cc0/interior_290473.jpg new file mode 100644 index 0000000..e3f35c3 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/interior_290473.jpg differ diff --git a/assets/starter/2d/images-met-cc0/landscape_264530.jpg b/assets/starter/2d/images-met-cc0/landscape_264530.jpg new file mode 100644 index 0000000..d6813a9 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/landscape_264530.jpg differ diff --git a/assets/starter/2d/images-met-cc0/landscape_267087.jpg b/assets/starter/2d/images-met-cc0/landscape_267087.jpg new file mode 100644 index 0000000..c5a33b5 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/landscape_267087.jpg differ diff --git a/assets/starter/2d/images-met-cc0/landscape_283336.jpg b/assets/starter/2d/images-met-cc0/landscape_283336.jpg new file mode 100644 index 0000000..8c5b6bc Binary files /dev/null and b/assets/starter/2d/images-met-cc0/landscape_283336.jpg differ diff --git a/assets/starter/2d/images-met-cc0/landscape_285787.jpg b/assets/starter/2d/images-met-cc0/landscape_285787.jpg new file mode 100644 index 0000000..84cc9b1 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/landscape_285787.jpg differ diff --git a/assets/starter/2d/images-met-cc0/landscape_700108.jpg b/assets/starter/2d/images-met-cc0/landscape_700108.jpg new file mode 100644 index 0000000..07761c2 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/landscape_700108.jpg differ diff --git a/assets/starter/2d/images-met-cc0/nature_264901.jpg b/assets/starter/2d/images-met-cc0/nature_264901.jpg new file mode 100644 index 0000000..6188865 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/nature_264901.jpg differ diff --git a/assets/starter/2d/images-met-cc0/nature_264912.jpg b/assets/starter/2d/images-met-cc0/nature_264912.jpg new file mode 100644 index 0000000..ba78b2e Binary files /dev/null and b/assets/starter/2d/images-met-cc0/nature_264912.jpg differ diff --git a/assets/starter/2d/images-met-cc0/nature_265967.jpg b/assets/starter/2d/images-met-cc0/nature_265967.jpg new file mode 100644 index 0000000..d479007 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/nature_265967.jpg differ diff --git a/assets/starter/2d/images-met-cc0/object_265916.jpg b/assets/starter/2d/images-met-cc0/object_265916.jpg new file mode 100644 index 0000000..4641bcc Binary files /dev/null and b/assets/starter/2d/images-met-cc0/object_265916.jpg differ diff --git a/assets/starter/2d/images-met-cc0/object_283087.jpg b/assets/starter/2d/images-met-cc0/object_283087.jpg new file mode 100644 index 0000000..e468fcb Binary files /dev/null and b/assets/starter/2d/images-met-cc0/object_283087.jpg differ diff --git a/assets/starter/2d/images-met-cc0/object_286248.jpg b/assets/starter/2d/images-met-cc0/object_286248.jpg new file mode 100644 index 0000000..a75012f Binary files /dev/null and b/assets/starter/2d/images-met-cc0/object_286248.jpg differ diff --git a/assets/starter/2d/images-met-cc0/pack.json b/assets/starter/2d/images-met-cc0/pack.json new file mode 100644 index 0000000..2fca8fd --- /dev/null +++ b/assets/starter/2d/images-met-cc0/pack.json @@ -0,0 +1,511 @@ +{ + "id": "images-met-cc0", + "name": "Reference photographs and objects (The Met Open Access)", + "kind": "image", + "licence": "CC0-1.0", + "author": "The Metropolitan Museum of Art (public-domain works; CC0 per item, artist and accession in tags)", + "source_url": "https://www.metmuseum.org/about-the-met/policies-and-documents/open-access", + "source_commit_or_version": "collectionapi.metmuseum.org v1 objects, isPublicDomain=true, primaryImage JPEG resized to max 1400 px, retrieved 2026-11-29", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://www.metmuseum.org/about-the-met/policies-and-documents/open-access", + "https://metmuseum.github.io/" + ], + "items": [ + { + "id": "met-267087", + "name": "Landscape", + "file": "landscape_267087.jpg", + "category": "landscape", + "tags": [ + "landscape", + "Photographs", + "accession:1994.417", + "artist:Marie-Charles-Isidore Choiselat", + "date:1844" + ], + "bytes": 232256, + "source_page": "https://www.metmuseum.org/art/collection/search/267087" + }, + { + "id": "met-283336", + "name": "Wisconsin Landscape", + "file": "landscape_283336.jpg", + "category": "landscape", + "tags": [ + "landscape", + "Photographs", + "accession:1999.367.5", + "artist:Henry Hamilton Bennett", + "date:1889" + ], + "bytes": 238161, + "source_page": "https://www.metmuseum.org/art/collection/search/283336" + }, + { + "id": "met-285787", + "name": "Volcanic Ridge, Trinity Mountains, Nevada", + "file": "landscape_285787.jpg", + "category": "landscape", + "tags": [ + "landscape", + "Photographs", + "accession:2005.100.635", + "artist:Timothy H. O'Sullivan", + "date:1867" + ], + "bytes": 248421, + "source_page": "https://www.metmuseum.org/art/collection/search/285787" + }, + { + "id": "met-700108", + "name": "American Fork Canyon", + "file": "landscape_700108.jpg", + "category": "landscape", + "tags": [ + "landscape", + "Photographs", + "accession:2015.778.32", + "artist:Charles Roscoe Savage", + "date:ca. 1875" + ], + "bytes": 182064, + "source_page": "https://www.metmuseum.org/art/collection/search/700108" + }, + { + "id": "met-282040", + "name": "Landscape with Clouds", + "file": "sky_282040.jpg", + "category": "sky", + "tags": [ + "sky", + "Photographs", + "accession:1997.382.35", + "artist:Roger Fenton", + "date:probably 1856" + ], + "bytes": 179212, + "source_page": "https://www.metmuseum.org/art/collection/search/282040" + }, + { + "id": "met-264530", + "name": "Darjeeling", + "file": "landscape_264530.jpg", + "category": "landscape", + "tags": [ + "landscape", + "Photographs", + "accession:1985.1168.21", + "artist:Unknown", + "date:1860s–70s" + ], + "bytes": 176957, + "source_page": "https://www.metmuseum.org/art/collection/search/264530" + }, + { + "id": "met-261809", + "name": "Béni-Haçan, Architecture Hypogéene - Tombeau d'Amoneï", + "file": "architecture_261809.jpg", + "category": "architecture", + "tags": [ + "architecture", + "Photographs", + "accession:1976.607.13", + "artist:Félix Teynard", + "date:1851–52, printed 1853–54" + ], + "bytes": 230036, + "source_page": "https://www.metmuseum.org/art/collection/search/261809" + }, + { + "id": "met-285983", + "name": "Chartres Cathedral", + "file": "architecture_285983.jpg", + "category": "architecture", + "tags": [ + "architecture", + "Photographs", + "accession:2005.100.815", + "artist:Pierre Emile Joseph Pécarrère", + "date:1850–52" + ], + "bytes": 230503, + "source_page": "https://www.metmuseum.org/art/collection/search/285983" + }, + { + "id": "met-283069", + "name": "Hungerford Suspension Bridge", + "file": "architecture_283069.jpg", + "category": "architecture", + "tags": [ + "architecture", + "Photographs", + "accession:2005.100.608", + "artist:William Henry Fox Talbot", + "date:ca. 1845" + ], + "bytes": 241838, + "source_page": "https://www.metmuseum.org/art/collection/search/283069" + }, + { + "id": "met-302645", + "name": "Amerapoora: Wooden Bridge", + "file": "architecture_302645.jpg", + "category": "architecture", + "tags": [ + "architecture", + "Photographs", + "accession:2012.323.15", + "artist:Linnaeus Tripe", + "date:September 1–October 21, 1855" + ], + "bytes": 222412, + "source_page": "https://www.metmuseum.org/art/collection/search/302645" + }, + { + "id": "met-285452", + "name": "Nîmes, Tour Magne", + "file": "architecture_285452.jpg", + "category": "architecture", + "tags": [ + "architecture", + "Photographs", + "accession:2005.100.364.41", + "artist:Edouard Baldus", + "date:1853" + ], + "bytes": 238789, + "source_page": "https://www.metmuseum.org/art/collection/search/285452" + }, + { + "id": "met-728358", + "name": "Temple Ruins", + "file": "architecture_728358.jpg", + "category": "architecture", + "tags": [ + "architecture", + "Photographs", + "accession:2005.100.583 (108a)", + "artist:John Thomson", + "date:1865" + ], + "bytes": 228288, + "source_page": "https://www.metmuseum.org/art/collection/search/728358" + }, + { + "id": "met-290473", + "name": "Interior, Tintern", + "file": "interior_290473.jpg", + "category": "interior", + "tags": [ + "interior", + "Photographs", + "accession:2009.460.5", + "artist:Alfred Capel Cure", + "date:1857" + ], + "bytes": 236111, + "source_page": "https://www.metmuseum.org/art/collection/search/290473" + }, + { + "id": "met-289717", + "name": "Factory Interior", + "file": "interior_289717.jpg", + "category": "interior", + "tags": [ + "interior", + "Photographs", + "accession:2008.558.1", + "artist:Louis Lafon", + "date:ca. 1880" + ], + "bytes": 231579, + "source_page": "https://www.metmuseum.org/art/collection/search/289717" + }, + { + "id": "met-264540", + "name": "Interior of Taj Mahal, Agra", + "file": "interior_264540.jpg", + "category": "interior", + "tags": [ + "interior", + "Photographs", + "accession:1985.1168.30", + "artist:Unknown", + "date:1860s–70s" + ], + "bytes": 249380, + "source_page": "https://www.metmuseum.org/art/collection/search/264540" + }, + { + "id": "met-286248", + "name": "Still Life", + "file": "object_286248.jpg", + "category": "object", + "tags": [ + "object", + "Negatives", + "accession:2005.100.877", + "artist:Louis-Rémy Robert", + "date:1850" + ], + "bytes": 247926, + "source_page": "https://www.metmuseum.org/art/collection/search/286248" + }, + { + "id": "met-283087", + "name": "Still Life with Fruit", + "file": "object_283087.jpg", + "category": "object", + "tags": [ + "object", + "Photographs", + "accession:2005.100.15", + "artist:Roger Fenton", + "date:1860" + ], + "bytes": 169721, + "source_page": "https://www.metmuseum.org/art/collection/search/283087" + }, + { + "id": "met-265916", + "name": "Articles of Glass", + "file": "object_265916.jpg", + "category": "object", + "tags": [ + "object", + "Photographs", + "accession:1988.1047", + "artist:William Henry Fox Talbot", + "date:before June 1844" + ], + "bytes": 185609, + "source_page": "https://www.metmuseum.org/art/collection/search/265916" + }, + { + "id": "met-283089", + "name": "Tree", + "file": "plants_283089.jpg", + "category": "plants", + "tags": [ + "plants", + "Photographs", + "accession:2005.100.17", + "artist:Horatio Ross", + "date:ca. 1858" + ], + "bytes": 245831, + "source_page": "https://www.metmuseum.org/art/collection/search/283089" + }, + { + "id": "met-287851", + "name": "Banian Tree", + "file": "plants_287851.jpg", + "category": "plants", + "tags": [ + "plants", + "Photographs", + "accession:2005.100.948.2 (34)", + "artist:Captain R. B. Hill", + "date:1850s" + ], + "bytes": 241536, + "source_page": "https://www.metmuseum.org/art/collection/search/287851" + }, + { + "id": "met-269560", + "name": "Tree Study", + "file": "plants_269560.jpg", + "category": "plants", + "tags": [ + "plants", + "Photographs", + "accession:51.611.502", + "artist:Unknown", + "date:1880s–90s" + ], + "bytes": 233043, + "source_page": "https://www.metmuseum.org/art/collection/search/269560" + }, + { + "id": "met-286677", + "name": "Water-Lilies", + "file": "water_286677.jpg", + "category": "water", + "tags": [ + "water", + "Photographs", + "accession:2005.100.744", + "artist:Peter Henry Emerson", + "date:1886" + ], + "bytes": 188376, + "source_page": "https://www.metmuseum.org/art/collection/search/286677" + }, + { + "id": "met-283124", + "name": "Mediterranean Sea - Sète", + "file": "water_283124.jpg", + "category": "water", + "tags": [ + "water", + "Photographs", + "accession:2005.100.48", + "artist:Gustave Le Gray", + "date:1857" + ], + "bytes": 224377, + "source_page": "https://www.metmuseum.org/art/collection/search/283124" + }, + { + "id": "met-260060", + "name": "Rhyl, from the Sea", + "file": "water_260060.jpg", + "category": "water", + "tags": [ + "water", + "Photographs", + "accession:1972.567.13", + "artist:Francis Bedford", + "date:1870s" + ], + "bytes": 204605, + "source_page": "https://www.metmuseum.org/art/collection/search/260060" + }, + { + "id": "met-264925", + "name": "Merced River", + "file": "water_264925.jpg", + "category": "water", + "tags": [ + "water", + "Photographs", + "accession:1986.1189.34", + "artist:Carleton E. Watkins", + "date:ca. 1872, printed ca. 1876" + ], + "bytes": 233031, + "source_page": "https://www.metmuseum.org/art/collection/search/264925" + }, + { + "id": "met-282603", + "name": "Study of Clouds and Rooftops", + "file": "sky_282603.jpg", + "category": "sky", + "tags": [ + "sky", + "Photographs", + "accession:1998.339", + "artist:Franck-François-Genès Chauvassaignes", + "date:1856–59" + ], + "bytes": 156713, + "source_page": "https://www.metmuseum.org/art/collection/search/282603" + }, + { + "id": "met-268079", + "name": "Locomotive #133, U.S.M.R.R.", + "file": "vehicle_268079.jpg", + "category": "vehicle", + "tags": [ + "vehicle", + "Photographs", + "accession:33.65.280", + "artist:Andrew Joseph Russell", + "date:1861–65" + ], + "bytes": 232551, + "source_page": "https://www.metmuseum.org/art/collection/search/268079" + }, + { + "id": "met-285681", + "name": "Model of a P.L.M. Locomotive", + "file": "vehicle_285681.jpg", + "category": "vehicle", + "tags": [ + "vehicle", + "Negatives", + "accession:2005.100.892", + "artist:Dominique Roman", + "date:ca. 1855" + ], + "bytes": 211111, + "source_page": "https://www.metmuseum.org/art/collection/search/285681" + }, + { + "id": "met-266656", + "name": "Horse", + "file": "animals_266656.jpg", + "category": "animals", + "tags": [ + "animals", + "Photographs", + "accession:1992.5013", + "artist:Ottomar Anschütz", + "date:1884" + ], + "bytes": 215258, + "source_page": "https://www.metmuseum.org/art/collection/search/266656" + }, + { + "id": "met-264901", + "name": "Seal Rocks", + "file": "nature_264901.jpg", + "category": "nature", + "tags": [ + "nature", + "Photographs", + "accession:1986.1189.12", + "artist:Carleton E. Watkins", + "date:1868–69, printed ca. 1876" + ], + "bytes": 238560, + "source_page": "https://www.metmuseum.org/art/collection/search/264901" + }, + { + "id": "met-264912", + "name": "Cathedral Rocks, Yosemite", + "file": "nature_264912.jpg", + "category": "nature", + "tags": [ + "nature", + "Photographs", + "accession:1986.1189.22", + "artist:Carleton E. Watkins", + "date:ca. 1872, printed ca. 1876" + ], + "bytes": 226721, + "source_page": "https://www.metmuseum.org/art/collection/search/264912" + }, + { + "id": "met-265967", + "name": "Rocks in the Auvergne", + "file": "nature_265967.jpg", + "category": "nature", + "tags": [ + "nature", + "Photographs", + "accession:1988.1112.1", + "artist:Edouard Baldus", + "date:1854, printed 1979" + ], + "bytes": 232947, + "source_page": "https://www.metmuseum.org/art/collection/search/265967" + }, + { + "id": "met-631211", + "name": "Camera Obscura", + "file": "tools_631211.jpg", + "category": "tools", + "tags": [ + "tools", + "Photographic Equipment", + "accession:1989.1045.1", + "artist:Unknown", + "date:19th century" + ], + "bytes": 165873, + "source_page": "https://www.metmuseum.org/art/collection/search/631211" + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/images-met-cc0/plants_269560.jpg b/assets/starter/2d/images-met-cc0/plants_269560.jpg new file mode 100644 index 0000000..7d5c23c Binary files /dev/null and b/assets/starter/2d/images-met-cc0/plants_269560.jpg differ diff --git a/assets/starter/2d/images-met-cc0/plants_283089.jpg b/assets/starter/2d/images-met-cc0/plants_283089.jpg new file mode 100644 index 0000000..5887643 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/plants_283089.jpg differ diff --git a/assets/starter/2d/images-met-cc0/plants_287851.jpg b/assets/starter/2d/images-met-cc0/plants_287851.jpg new file mode 100644 index 0000000..4b3b4a0 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/plants_287851.jpg differ diff --git a/assets/starter/2d/images-met-cc0/sky_282040.jpg b/assets/starter/2d/images-met-cc0/sky_282040.jpg new file mode 100644 index 0000000..f0657e3 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/sky_282040.jpg differ diff --git a/assets/starter/2d/images-met-cc0/sky_282603.jpg b/assets/starter/2d/images-met-cc0/sky_282603.jpg new file mode 100644 index 0000000..9a33f4c Binary files /dev/null and b/assets/starter/2d/images-met-cc0/sky_282603.jpg differ diff --git a/assets/starter/2d/images-met-cc0/tools_631211.jpg b/assets/starter/2d/images-met-cc0/tools_631211.jpg new file mode 100644 index 0000000..2815747 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/tools_631211.jpg differ diff --git a/assets/starter/2d/images-met-cc0/vehicle_268079.jpg b/assets/starter/2d/images-met-cc0/vehicle_268079.jpg new file mode 100644 index 0000000..c4e48bb Binary files /dev/null and b/assets/starter/2d/images-met-cc0/vehicle_268079.jpg differ diff --git a/assets/starter/2d/images-met-cc0/vehicle_285681.jpg b/assets/starter/2d/images-met-cc0/vehicle_285681.jpg new file mode 100644 index 0000000..e78571a Binary files /dev/null and b/assets/starter/2d/images-met-cc0/vehicle_285681.jpg differ diff --git a/assets/starter/2d/images-met-cc0/water_260060.jpg b/assets/starter/2d/images-met-cc0/water_260060.jpg new file mode 100644 index 0000000..4e30a4f Binary files /dev/null and b/assets/starter/2d/images-met-cc0/water_260060.jpg differ diff --git a/assets/starter/2d/images-met-cc0/water_264925.jpg b/assets/starter/2d/images-met-cc0/water_264925.jpg new file mode 100644 index 0000000..3a8f98c Binary files /dev/null and b/assets/starter/2d/images-met-cc0/water_264925.jpg differ diff --git a/assets/starter/2d/images-met-cc0/water_283124.jpg b/assets/starter/2d/images-met-cc0/water_283124.jpg new file mode 100644 index 0000000..2aaafd3 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/water_283124.jpg differ diff --git a/assets/starter/2d/images-met-cc0/water_286677.jpg b/assets/starter/2d/images-met-cc0/water_286677.jpg new file mode 100644 index 0000000..e0176a0 Binary files /dev/null and b/assets/starter/2d/images-met-cc0/water_286677.jpg differ diff --git a/assets/starter/2d/palettes-derived/LICENSE.txt b/assets/starter/2d/palettes-derived/LICENSE.txt new file mode 100644 index 0000000..3b47ff5 --- /dev/null +++ b/assets/starter/2d/palettes-derived/LICENSE.txt @@ -0,0 +1,38 @@ +Licence statements fetched on 2026-11-29 (read by FormCraft build, agent 7 audit) + +1. https://docs.ambientcg.com/license/ (ambientCG, site-wide) + "All ambientCG assets are provided under the Creative Commons CC0 1.0 Universal License." "This applies to the downloadable asset files and the material preview renders shown for each asset on the site." +2. https://ambientcg.com/view?id=Wood049 (an asset page the palettes draw on) + "Yes. All assets are released under the Creative Commons CC0 license, making them free to use without attribution" + +What this pack is: 8 JSON files of five-colour palettes computed by FormCraft from the colour maps of 40 ambientCG materials (ids such as wood049, metal032). All 40 ids were looked up on 2026-11-29 in the ambientCG API (https://ambientcg.com/api/v2/full_json?id=...) and exist. The data is derived from CC0 works and is released under CC0 1.0. + +----- Text shipped by the author with the files (verbatim, as originally copied) ----- + +Statement retrieved from https://docs.ambientcg.com/license/ on 2026-11-28 (text of the page, markup removed) + +License information +¶ +All ambientCG assets are provided under the +Creative Commons CC0 1.0 Universal License +. +This applies to the downloadable asset files and the material preview renders shown for each asset on the site. +License Details +¶ +The Creative Commons CC0 license gives you near limitless freedom to use the materials, models and other assets: +Creative Commons CC0 License +You can copy, modify, distribute and perform the assets, even for commercial purposes, all without asking permission. +You can include the raw files in your project, for example a video game. +You can read the full text on the +Creative Commons website +. There you can also read the full license in many languages by using the dropdown menu in the top right corner. +Giving credit +¶ +You don't need to give credit but I would of course appreciate it, if you did it anyways. You can do so using this text: +Created using from ambientCG.com, +licensed under the Creative Commons CC0 1.0 Universal License. +Tip +You can use the short and neat URLs to link to assets on ambientCG, like this: +https://ambientcg.com/a/ +, for example +https://ambientcg.com/a/Pa diff --git a/assets/starter/2d/palettes-derived/pack.json b/assets/starter/2d/palettes-derived/pack.json new file mode 100644 index 0000000..79603a9 --- /dev/null +++ b/assets/starter/2d/palettes-derived/pack.json @@ -0,0 +1,120 @@ +{ + "id": "palettes-derived", + "name": "Colour palettes (derived from ambientCG textures)", + "kind": "image", + "licence": "CC0-1.0", + "author": "Derived by FormCraft build from ambientCG (ambientcg.com) CC0 textures; colours quantised from the colour maps", + "source_url": "https://ambientcg.com", + "source_commit_or_version": "Derived from the textures-ambientcg pack, 2026-11-28", + "retrieved": "2026-11-28", + "licence_evidence": [ + "https://docs.ambientcg.com/license/", + "https://ambientcg.com/view?id=Wood049" + ], + "items": [ + { + "id": "palette-wood", + "name": "Wood palettes", + "file": "palettes/wood.json", + "category": "palette", + "tags": [ + "palette", + "colour", + "json", + "wood" + ], + "bytes": 855 + }, + { + "id": "palette-metal", + "name": "Metal palettes", + "file": "palettes/metal.json", + "category": "palette", + "tags": [ + "palette", + "colour", + "json", + "metal" + ], + "bytes": 900 + }, + { + "id": "palette-concrete", + "name": "Concrete palettes", + "file": "palettes/concrete.json", + "category": "palette", + "tags": [ + "palette", + "colour", + "json", + "concrete" + ], + "bytes": 881 + }, + { + "id": "palette-fabric", + "name": "Fabric palettes", + "file": "palettes/fabric.json", + "category": "palette", + "tags": [ + "palette", + "colour", + "json", + "fabric" + ], + "bytes": 865 + }, + { + "id": "palette-stone", + "name": "Stone palettes", + "file": "palettes/stone.json", + "category": "palette", + "tags": [ + "palette", + "colour", + "json", + "stone" + ], + "bytes": 862 + }, + { + "id": "palette-ground", + "name": "Ground palettes", + "file": "palettes/ground.json", + "category": "palette", + "tags": [ + "palette", + "colour", + "json", + "ground" + ], + "bytes": 853 + }, + { + "id": "palette-tiles", + "name": "Tiles palettes", + "file": "palettes/tiles.json", + "category": "palette", + "tags": [ + "palette", + "colour", + "json", + "tiles" + ], + "bytes": 886 + }, + { + "id": "palette-sci-fi-panels", + "name": "Sci-fi panels palettes", + "file": "palettes/sci-fi-panels.json", + "category": "palette", + "tags": [ + "palette", + "colour", + "json", + "sci-fi panels" + ], + "bytes": 918 + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/palettes-derived/palettes/concrete.json b/assets/starter/2d/palettes-derived/palettes/concrete.json new file mode 100644 index 0000000..f0fc577 --- /dev/null +++ b/assets/starter/2d/palettes-derived/palettes/concrete.json @@ -0,0 +1,60 @@ +{ + "name": "Concrete palettes", + "palettes": [ + { + "name": "Concrete007", + "source": "ambientCG concrete007", + "colors": [ + "#79797a", + "#7b7b7d", + "#7f8183", + "#7d7d7f", + "#757575" + ] + }, + { + "name": "Concrete034", + "source": "ambientCG concrete034", + "colors": [ + "#b8b8b8", + "#b7b7b7", + "#bebebe", + "#b3b3b3", + "#bababa" + ] + }, + { + "name": "Concrete019", + "source": "ambientCG concrete019", + "colors": [ + "#7a807c", + "#89908b", + "#6d746f", + "#656b66", + "#727874" + ] + }, + { + "name": "Asphalt004", + "source": "ambientCG asphalt004", + "colors": [ + "#808080", + "#7d7d7d", + "#7e7e7e", + "#7c7c7c", + "#7b7b7b" + ] + }, + { + "name": "Plaster001", + "source": "ambientCG plaster001", + "colors": [ + "#dad7d3", + "#d5d1ce", + "#d8d4d1", + "#d4d0cd", + "#d4cfcc" + ] + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/palettes-derived/palettes/fabric.json b/assets/starter/2d/palettes-derived/palettes/fabric.json new file mode 100644 index 0000000..26add5e --- /dev/null +++ b/assets/starter/2d/palettes-derived/palettes/fabric.json @@ -0,0 +1,60 @@ +{ + "name": "Fabric palettes", + "palettes": [ + { + "name": "Fabric030", + "source": "ambientCG fabric030", + "colors": [ + "#5b5b5b", + "#5a5a5a", + "#5c5c5c", + "#5d5d5d", + "#5a5b5a" + ] + }, + { + "name": "Fabric045", + "source": "ambientCG fabric045", + "colors": [ + "#c2c1bf", + "#c4c4c1", + "#c6c5c3", + "#c8c8c5", + "#bebebc" + ] + }, + { + "name": "Carpet009", + "source": "ambientCG carpet009", + "colors": [ + "#beac88", + "#ccc6b0", + "#c1b290", + "#baa883", + "#bbab86" + ] + }, + { + "name": "Leather011", + "source": "ambientCG leather011", + "colors": [ + "#45100f", + "#420d0c", + "#461312", + "#461110", + "#3d0707" + ] + }, + { + "name": "Wicker001", + "source": "ambientCG wicker001", + "colors": [ + "#8b694f", + "#78482b", + "#8c6b51", + "#8d6d53", + "#876248" + ] + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/palettes-derived/palettes/ground.json b/assets/starter/2d/palettes-derived/palettes/ground.json new file mode 100644 index 0000000..2620a89 --- /dev/null +++ b/assets/starter/2d/palettes-derived/palettes/ground.json @@ -0,0 +1,60 @@ +{ + "name": "Ground palettes", + "palettes": [ + { + "name": "Ground037", + "source": "ambientCG ground037", + "colors": [ + "#97984d", + "#a09761", + "#918759", + "#969057", + "#a39f5c" + ] + }, + { + "name": "Gravel021", + "source": "ambientCG gravel021", + "colors": [ + "#2e2e27", + "#373730", + "#222119", + "#3f3f38", + "#4b4b44" + ] + }, + { + "name": "Grass004", + "source": "ambientCG grass004", + "colors": [ + "#5e6a2f", + "#626e31", + "#59642b", + "#657233", + "#687736" + ] + }, + { + "name": "Snow006", + "source": "ambientCG snow006", + "colors": [ + "#c6c8c8", + "#cbcdcd", + "#c8c9c9", + "#c9caca", + "#c4c5c5" + ] + }, + { + "name": "Moss001", + "source": "ambientCG moss001", + "colors": [ + "#727453", + "#827a5e", + "#85855e", + "#8b8d62", + "#95996a" + ] + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/palettes-derived/palettes/metal.json b/assets/starter/2d/palettes-derived/palettes/metal.json new file mode 100644 index 0000000..126a31d --- /dev/null +++ b/assets/starter/2d/palettes-derived/palettes/metal.json @@ -0,0 +1,60 @@ +{ + "name": "Metal palettes", + "palettes": [ + { + "name": "Metal032", + "source": "ambientCG metal032", + "colors": [ + "#7c8892", + "#7d8995", + "#808d99", + "#7a848f", + "#7f8a96" + ] + }, + { + "name": "Metal038", + "source": "ambientCG metal038", + "colors": [ + "#5d605f", + "#5f6161", + "#616362", + "#636665", + "#5b5e5d" + ] + }, + { + "name": "Paintedmetal007", + "source": "ambientCG paintedmetal007", + "colors": [ + "#192a87", + "#0b1b77", + "#172378", + "#4d364f", + "#312d64" + ] + }, + { + "name": "Corrugatedsteel005", + "source": "ambientCG corrugatedsteel005", + "colors": [ + "#959799", + "#9b9d9f", + "#8d8f91", + "#a1a3a5", + "#a9abad" + ] + }, + { + "name": "Diamondplate001", + "source": "ambientCG diamondplate001", + "colors": [ + "#747c7b", + "#787f80", + "#7c8384", + "#6f7775", + "#82898a" + ] + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/palettes-derived/palettes/sci-fi-panels.json b/assets/starter/2d/palettes-derived/palettes/sci-fi-panels.json new file mode 100644 index 0000000..5a84a32 --- /dev/null +++ b/assets/starter/2d/palettes-derived/palettes/sci-fi-panels.json @@ -0,0 +1,60 @@ +{ + "name": "Sci-fi panels palettes", + "palettes": [ + { + "name": "Metalplates001", + "source": "ambientCG metalplates001", + "colors": [ + "#858b91", + "#828a91", + "#707478", + "#81878e", + "#848a91" + ] + }, + { + "name": "Metalplates006", + "source": "ambientCG metalplates006", + "colors": [ + "#42484b", + "#494c4a", + "#4a4d4a", + "#414547", + "#454a4b" + ] + }, + { + "name": "Metalwalkway001", + "source": "ambientCG metalwalkway001", + "colors": [ + "#515053", + "#393939", + "#5f5d61", + "#504c4c", + "#434243" + ] + }, + { + "name": "Sheetmetal001", + "source": "ambientCG sheetmetal001", + "colors": [ + "#1d1c21", + "#201f24", + "#2b2a2f", + "#1c1b20", + "#1c1c20" + ] + }, + { + "name": "Solarpanel001", + "source": "ambientCG solarpanel001", + "colors": [ + "#33516a", + "#2d4761", + "#385971", + "#3d6179", + "#617b8b" + ] + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/palettes-derived/palettes/stone.json b/assets/starter/2d/palettes-derived/palettes/stone.json new file mode 100644 index 0000000..0a48593 --- /dev/null +++ b/assets/starter/2d/palettes-derived/palettes/stone.json @@ -0,0 +1,60 @@ +{ + "name": "Stone palettes", + "palettes": [ + { + "name": "Rock030", + "source": "ambientCG rock030", + "colors": [ + "#4c4941", + "#504e46", + "#535149", + "#46433c", + "#595750" + ] + }, + { + "name": "Rock035", + "source": "ambientCG rock035", + "colors": [ + "#0c1619", + "#101b1f", + "#081013", + "#152124", + "#1e2a2d" + ] + }, + { + "name": "Marble006", + "source": "ambientCG marble006", + "colors": [ + "#131414", + "#0c0d0e", + "#1a1a1a", + "#222221", + "#32312f" + ] + }, + { + "name": "Bricks059", + "source": "ambientCG bricks059", + "colors": [ + "#89543f", + "#a37e64", + "#956349", + "#af8b72", + "#c0a087" + ] + }, + { + "name": "Travertine001", + "source": "ambientCG travertine001", + "colors": [ + "#a1957d", + "#aa9d86", + "#afa48e", + "#93876f", + "#b8ac96" + ] + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/palettes-derived/palettes/tiles.json b/assets/starter/2d/palettes-derived/palettes/tiles.json new file mode 100644 index 0000000..ade81ac --- /dev/null +++ b/assets/starter/2d/palettes-derived/palettes/tiles.json @@ -0,0 +1,60 @@ +{ + "name": "Tiles palettes", + "palettes": [ + { + "name": "Tiles074", + "source": "ambientCG tiles074", + "colors": [ + "#0a0b0c", + "#9a8675", + "#21201f", + "#9e8b7a", + "#897767" + ] + }, + { + "name": "Tiles107", + "source": "ambientCG tiles107", + "colors": [ + "#fcfbfc", + "#f2f2f1", + "#fdfcfd", + "#f7f7f7", + "#fefdfe" + ] + }, + { + "name": "Terrazzo003", + "source": "ambientCG terrazzo003", + "colors": [ + "#3b3b3c", + "#3e3f42", + "#373637", + "#47484b", + "#6b6a6f" + ] + }, + { + "name": "Roofingtiles003", + "source": "ambientCG roofingtiles003", + "colors": [ + "#30322f", + "#353835", + "#292a29", + "#3b3e3b", + "#434643" + ] + }, + { + "name": "Pavingstones070", + "source": "ambientCG pavingstones070", + "colors": [ + "#9e9c9b", + "#918f88", + "#79786a", + "#8a857d", + "#818272" + ] + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/palettes-derived/palettes/wood.json b/assets/starter/2d/palettes-derived/palettes/wood.json new file mode 100644 index 0000000..0536246 --- /dev/null +++ b/assets/starter/2d/palettes-derived/palettes/wood.json @@ -0,0 +1,60 @@ +{ + "name": "Wood palettes", + "palettes": [ + { + "name": "Wood049", + "source": "ambientCG wood049", + "colors": [ + "#78614b", + "#7b634e", + "#7d654f", + "#745e48", + "#836a53" + ] + }, + { + "name": "Wood051", + "source": "ambientCG wood051", + "colors": [ + "#3f332c", + "#41342e", + "#43362f", + "#473932", + "#3b302a" + ] + }, + { + "name": "Woodfloor040", + "source": "ambientCG woodfloor040", + "colors": [ + "#b48653", + "#b78956", + "#ae804e", + "#ba8c59", + "#c2925e" + ] + }, + { + "name": "Planks012", + "source": "ambientCG planks012", + "colors": [ + "#524333", + "#584737", + "#493b2c", + "#5c4b39", + "#64513f" + ] + }, + { + "name": "Bark001", + "source": "ambientCG bark001", + "colors": [ + "#77766d", + "#898780", + "#525048", + "#93918b", + "#a09e9a" + ] + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/photos-negativespace-cc0/LICENSE.txt b/assets/starter/2d/photos-negativespace-cc0/LICENSE.txt new file mode 100644 index 0000000..dec127a --- /dev/null +++ b/assets/starter/2d/photos-negativespace-cc0/LICENSE.txt @@ -0,0 +1,15 @@ +Source: https://negativespace.co/license/ +Fetched: 2026-11-29 + +Statement 1 (site-wide licence page, "CC0 License"): +"all the photographs (and their raw image files) are made available under the Creative Commons CC0 license." +The CC0 license grants users the right to download any photo, use, copy, edit or share it, use it for personal or commercial purposes, and to do so without purchase, permission, or giving attribution to the creator of the work. +The page adds: "It is your responsibility to check the validity and safety of using any photos downloaded from this site." + +Statement 2 (each item page, listed as source_page per item in pack.json): +the page description reads "Download the free ... photo '' with a CC0 license and use the image however and wherever you like." and the page carries the licence link http://creativecommons.org/licenses/publicdomain/ + +No restriction on the files was found on the site (no terms page; licence, about and privacy pages only). robots.txt allows general access. + +Licence: CC0 1.0 Universal, https://creativecommons.org/publicdomain/zero/1.0/ +Files here are resized and recompressed copies of the originals. diff --git a/assets/starter/2d/photos-negativespace-cc0/city_church_building_perspective.jpg b/assets/starter/2d/photos-negativespace-cc0/city_church_building_perspective.jpg new file mode 100644 index 0000000..05631b1 Binary files /dev/null and b/assets/starter/2d/photos-negativespace-cc0/city_church_building_perspective.jpg differ diff --git a/assets/starter/2d/photos-negativespace-cc0/city_city_buildings_2.jpg b/assets/starter/2d/photos-negativespace-cc0/city_city_buildings_2.jpg new file mode 100644 index 0000000..b6b115c Binary files /dev/null and b/assets/starter/2d/photos-negativespace-cc0/city_city_buildings_2.jpg differ diff --git a/assets/starter/2d/photos-negativespace-cc0/city_city_buildings_3.jpg b/assets/starter/2d/photos-negativespace-cc0/city_city_buildings_3.jpg new file mode 100644 index 0000000..d2b77c5 Binary files /dev/null and b/assets/starter/2d/photos-negativespace-cc0/city_city_buildings_3.jpg differ diff --git a/assets/starter/2d/photos-negativespace-cc0/city_looking_up_at_skyscrapers.jpg b/assets/starter/2d/photos-negativespace-cc0/city_looking_up_at_skyscrapers.jpg new file mode 100644 index 0000000..a7339b6 Binary files /dev/null and b/assets/starter/2d/photos-negativespace-cc0/city_looking_up_at_skyscrapers.jpg differ diff --git a/assets/starter/2d/photos-negativespace-cc0/city_modern_building_abstract_exterior.jpg b/assets/starter/2d/photos-negativespace-cc0/city_modern_building_abstract_exterior.jpg new file mode 100644 index 0000000..49ae4d1 Binary files /dev/null and b/assets/starter/2d/photos-negativespace-cc0/city_modern_building_abstract_exterior.jpg differ diff --git a/assets/starter/2d/photos-negativespace-cc0/city_nyc_buildings.jpg b/assets/starter/2d/photos-negativespace-cc0/city_nyc_buildings.jpg new file mode 100644 index 0000000..a051757 Binary files /dev/null and b/assets/starter/2d/photos-negativespace-cc0/city_nyc_buildings.jpg differ diff --git a/assets/starter/2d/photos-negativespace-cc0/city_nyc_old_buildings.jpg b/assets/starter/2d/photos-negativespace-cc0/city_nyc_old_buildings.jpg new file mode 100644 index 0000000..e398f8d Binary files /dev/null and b/assets/starter/2d/photos-negativespace-cc0/city_nyc_old_buildings.jpg differ diff --git a/assets/starter/2d/photos-negativespace-cc0/city_office_building.jpg b/assets/starter/2d/photos-negativespace-cc0/city_office_building.jpg new file mode 100644 index 0000000..06d1110 Binary files /dev/null and b/assets/starter/2d/photos-negativespace-cc0/city_office_building.jpg differ diff --git a/assets/starter/2d/photos-negativespace-cc0/city_red_and_white_apartments.jpg b/assets/starter/2d/photos-negativespace-cc0/city_red_and_white_apartments.jpg new file mode 100644 index 0000000..e9e7a6f Binary files /dev/null and b/assets/starter/2d/photos-negativespace-cc0/city_red_and_white_apartments.jpg differ diff --git a/assets/starter/2d/photos-negativespace-cc0/pack.json b/assets/starter/2d/photos-negativespace-cc0/pack.json new file mode 100644 index 0000000..6c968ef --- /dev/null +++ b/assets/starter/2d/photos-negativespace-cc0/pack.json @@ -0,0 +1,156 @@ +{ + "id": "photos-negativespace-cc0", + "name": "City and architecture photographs in colour (NegativeSpace)", + "kind": "image", + "licence": "CC0-1.0", + "author": "NegativeSpace (negativespace.co)", + "source_url": "https://negativespace.co/", + "source_commit_or_version": "Original JPEGs downloaded from negativespace.co/wp-content/uploads (image_url per item) and resized to 2048 px longest side, JPEG quality 82, progressive; selected 2026-11-29.", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://negativespace.co/license/", + "Each item source_page: description \"Download the free ... photo ... with a CC0 license and use the image however and wherever you like.\" and license meta http://creativecommons.org/licenses/publicdomain/" + ], + "items": [ + { + "id": "ns-brick-wall-background", + "name": "Red Brick Wall", + "file": "texture_brick_wall_background.jpg", + "category": "texture", + "tags": [ + "texture", + "brick", + "wall" + ], + "bytes": 433388, + "source_page": "https://negativespace.co/brick-wall-background/", + "image_url": "https://negativespace.co/wp-content/uploads/2024/03/negative-space-red-brick-texture-modern.jpg" + }, + { + "id": "ns-church-building-perspective", + "name": "Church Tower from Below", + "file": "city_church_building_perspective.jpg", + "category": "city", + "tags": [ + "city", + "architecture", + "buildings" + ], + "bytes": 274742, + "source_page": "https://negativespace.co/church-building-perspective/", + "image_url": "https://negativespace.co/wp-content/uploads/2024/03/negative-space-church.jpg" + }, + { + "id": "ns-city-buildings-2", + "name": "City Buildings from Below", + "file": "city_city_buildings_2.jpg", + "category": "city", + "tags": [ + "city", + "architecture", + "buildings" + ], + "bytes": 201746, + "source_page": "https://negativespace.co/city-buildings-2/", + "image_url": "https://negativespace.co/wp-content/uploads/2025/02/negative-space-nyc-old-buildings-background.jpg" + }, + { + "id": "ns-city-buildings-3", + "name": "Old Apartment Building Facade", + "file": "city_city_buildings_3.jpg", + "category": "city", + "tags": [ + "city", + "architecture", + "buildings" + ], + "bytes": 235648, + "source_page": "https://negativespace.co/city-buildings-3/", + "image_url": "https://negativespace.co/wp-content/uploads/2025/02/negative-space-nice-buildings-aerial.jpg" + }, + { + "id": "ns-looking-up-at-skyscrapers", + "name": "Looking Up at Skyscrapers", + "file": "city_looking_up_at_skyscrapers.jpg", + "category": "city", + "tags": [ + "city", + "architecture", + "buildings" + ], + "bytes": 568895, + "source_page": "https://negativespace.co/looking-up-at-skyscrapers/", + "image_url": "https://negativespace.co/wp-content/uploads/2025/02/negative-space-looking-up-skyscrapers.jpg" + }, + { + "id": "ns-modern-building-abstract-exterior", + "name": "Modern Glass Building Exterior", + "file": "city_modern_building_abstract_exterior.jpg", + "category": "city", + "tags": [ + "city", + "architecture", + "buildings" + ], + "bytes": 355439, + "source_page": "https://negativespace.co/modern-building-abstract-exterior/", + "image_url": "https://negativespace.co/wp-content/uploads/2024/05/negative-space-abstract-building-pattern.jpg" + }, + { + "id": "ns-nyc-buildings", + "name": "NYC Brick Buildings", + "file": "city_nyc_buildings.jpg", + "category": "city", + "tags": [ + "city", + "architecture", + "buildings" + ], + "bytes": 372299, + "source_page": "https://negativespace.co/nyc-buildings/", + "image_url": "https://negativespace.co/wp-content/uploads/2025/01/negative-space-nyc-buildings-bg.jpg" + }, + { + "id": "ns-nyc-old-buildings", + "name": "NYC Old Brick Building", + "file": "city_nyc_old_buildings.jpg", + "category": "city", + "tags": [ + "city", + "architecture", + "buildings" + ], + "bytes": 336706, + "source_page": "https://negativespace.co/nyc-old-buildings/", + "image_url": "https://negativespace.co/wp-content/uploads/2025/02/negative-space-nyc-old-buildings-bg.jpg" + }, + { + "id": "ns-office-building", + "name": "Loft Building Facade", + "file": "city_office_building.jpg", + "category": "city", + "tags": [ + "city", + "architecture", + "buildings" + ], + "bytes": 520515, + "source_page": "https://negativespace.co/office-building/", + "image_url": "https://negativespace.co/wp-content/uploads/2024/11/negative-space-nyc-office-buildings-background.jpg" + }, + { + "id": "ns-red-and-white-apartments", + "name": "Red and White Apartments", + "file": "city_red_and_white_apartments.jpg", + "category": "city", + "tags": [ + "city", + "architecture", + "buildings" + ], + "bytes": 431157, + "source_page": "https://negativespace.co/red-and-white-apartments/", + "image_url": "https://negativespace.co/wp-content/uploads/2024/11/negative-space-nyc-red-white-apartments-real-estate-bg.jpg" + } + ] +} diff --git a/assets/starter/2d/photos-negativespace-cc0/texture_brick_wall_background.jpg b/assets/starter/2d/photos-negativespace-cc0/texture_brick_wall_background.jpg new file mode 100644 index 0000000..87acf2f Binary files /dev/null and b/assets/starter/2d/photos-negativespace-cc0/texture_brick_wall_background.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/LICENSE.txt b/assets/starter/2d/polyhaven-hdri/LICENSE.txt new file mode 100644 index 0000000..95df7f2 --- /dev/null +++ b/assets/starter/2d/polyhaven-hdri/LICENSE.txt @@ -0,0 +1,11 @@ +Source: https://polyhaven.com/license +Fetched: 2026-11-29 + +Asset License All assets ( HDRIs , textures and 3D models ) on this site are the original work of Poly Haven staff, or artists who willingly and directly donate/sell their work to Poly Haven. Our assets are all licensed as CC0 , which is effectively Public Domain even in jurisdictions that do not support the Public Domain. Here's an excerpt from the CC0 FAQ page to clarify: Once the creator or a subsequent owner of a work applies CC0 to a work, the work is no longer his or hers in any meaningful sense under copyright law. Anyone can then use the work in any way and for any purpose, including commercial purposes [...] Think of CC0 as the "no rights reserved" option. CC0 is a useful tool for clarifying that you do not claim copyright in a work anywhere in the world. In other words: You can use our assets for any purpose , including commercial work. You do not need to give credit or attribution when using them (although it is appreciated). You can redistribute them , share them around, include them when sharing your own work, or even in a product you sell. More info: CC0 summary , CC0 wiki , CC0 FAQ . + +[...] + +4. Intellectual Property 4.1. All content on this website, excluding the CC0 assets themselves, is protected by intellectual property laws. You may not reproduce, distribute, or otherwise use this content without prior written permission from the website or intellectual property owner. 4.2. Examples of such content includes but is not limited to: Logos User avatar images Asset example renders User submitted renders Text and copy + +Per-item confirmation: each asset page https://polyhaven.com/a/<id> names the licence CC0 (schema.org license http://creativecommons.org/publicdomain/zero/1.0/, "CC0 1.0 Universal - public domain dedication, no attribution required"). +Previews (<id>.jpg) are rendered by FormCraft tooling from the CC0 asset files; no Poly Haven example renders are included. diff --git a/assets/starter/2d/polyhaven-hdri/bismarckturm.jpg b/assets/starter/2d/polyhaven-hdri/bismarckturm.jpg new file mode 100644 index 0000000..69c6653 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/bismarckturm.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/bismarckturm_1k.hdr b/assets/starter/2d/polyhaven-hdri/bismarckturm_1k.hdr new file mode 100644 index 0000000..51567fa Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/bismarckturm_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/ferndale_studio_06.jpg b/assets/starter/2d/polyhaven-hdri/ferndale_studio_06.jpg new file mode 100644 index 0000000..5dd8021 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/ferndale_studio_06.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/ferndale_studio_06_1k.hdr b/assets/starter/2d/polyhaven-hdri/ferndale_studio_06_1k.hdr new file mode 100644 index 0000000..66d8aea Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/ferndale_studio_06_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/goegap.jpg b/assets/starter/2d/polyhaven-hdri/goegap.jpg new file mode 100644 index 0000000..e29fa6e Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/goegap.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/goegap_1k.hdr b/assets/starter/2d/polyhaven-hdri/goegap_1k.hdr new file mode 100644 index 0000000..4585716 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/goegap_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/golden_bay.jpg b/assets/starter/2d/polyhaven-hdri/golden_bay.jpg new file mode 100644 index 0000000..0496b04 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/golden_bay.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/golden_bay_1k.hdr b/assets/starter/2d/polyhaven-hdri/golden_bay_1k.hdr new file mode 100644 index 0000000..a8598e1 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/golden_bay_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/kloofendal_misty_morning_puresky.jpg b/assets/starter/2d/polyhaven-hdri/kloofendal_misty_morning_puresky.jpg new file mode 100644 index 0000000..55cb1bb Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/kloofendal_misty_morning_puresky.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/kloofendal_misty_morning_puresky_1k.hdr b/assets/starter/2d/polyhaven-hdri/kloofendal_misty_morning_puresky_1k.hdr new file mode 100644 index 0000000..e4f6d4b Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/kloofendal_misty_morning_puresky_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/kloppenheim_01_puresky.jpg b/assets/starter/2d/polyhaven-hdri/kloppenheim_01_puresky.jpg new file mode 100644 index 0000000..c636188 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/kloppenheim_01_puresky.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/kloppenheim_01_puresky_1k.hdr b/assets/starter/2d/polyhaven-hdri/kloppenheim_01_puresky_1k.hdr new file mode 100644 index 0000000..9b4e99e Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/kloppenheim_01_puresky_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/lakeside.jpg b/assets/starter/2d/polyhaven-hdri/lakeside.jpg new file mode 100644 index 0000000..c93f36d Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/lakeside.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/lakeside_1k.hdr b/assets/starter/2d/polyhaven-hdri/lakeside_1k.hdr new file mode 100644 index 0000000..74e6d86 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/lakeside_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/lebombo.jpg b/assets/starter/2d/polyhaven-hdri/lebombo.jpg new file mode 100644 index 0000000..81cd702 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/lebombo.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/lebombo_1k.hdr b/assets/starter/2d/polyhaven-hdri/lebombo_1k.hdr new file mode 100644 index 0000000..3aee193 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/lebombo_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/moonless_golf.jpg b/assets/starter/2d/polyhaven-hdri/moonless_golf.jpg new file mode 100644 index 0000000..8cf4b32 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/moonless_golf.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/moonless_golf_1k.hdr b/assets/starter/2d/polyhaven-hdri/moonless_golf_1k.hdr new file mode 100644 index 0000000..cc60dc8 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/moonless_golf_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/overcast_soil_puresky.jpg b/assets/starter/2d/polyhaven-hdri/overcast_soil_puresky.jpg new file mode 100644 index 0000000..2e9b061 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/overcast_soil_puresky.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/overcast_soil_puresky_1k.hdr b/assets/starter/2d/polyhaven-hdri/overcast_soil_puresky_1k.hdr new file mode 100644 index 0000000..fd2bfaf Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/overcast_soil_puresky_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/pack.json b/assets/starter/2d/polyhaven-hdri/pack.json new file mode 100644 index 0000000..8fb87bf --- /dev/null +++ b/assets/starter/2d/polyhaven-hdri/pack.json @@ -0,0 +1,468 @@ +{ + "id": "polyhaven-hdri", + "name": "HDRI environments (Poly Haven)", + "kind": "hdri", + "licence": "CC0-1.0", + "author": "Poly Haven (polyhaven.com) artists: Andreas Mischok, Dimitrios Savva, Greg Zaal, Grzegorz Wronkowski, Jarod Guest, Oliksiy Yakovlyev, Sergej Majboroda", + "source_url": "https://polyhaven.com/hdris", + "source_commit_or_version": "api.polyhaven.com snapshot, 1k Radiance .hdr (md5 checked against API) plus 512 px JPEG previews rendered by FormCraft tooling from the asset itself (Poly Haven example renders are excluded from CC0 by its ToS 4.2), retrieved 2026-11-29", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/<item id> (per item, see items[].licence_evidence)" + ], + "items": [ + { + "id": "bismarckturm", + "name": "Bismarckturm", + "file": "bismarckturm_1k.hdr", + "preview": "bismarckturm.jpg", + "category": "sunrise-sunset", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "nature", + "sunrise-sunset", + "partly cloudy", + "low contrast", + "natural light", + "tree", + "grass", + "by:Andreas Mischok" + ], + "bytes": 1304988, + "source_page": "https://polyhaven.com/a/bismarckturm", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/bismarckturm" + ] + }, + { + "id": "ferndale_studio_06", + "name": "Ferndale Studio 06", + "file": "ferndale_studio_06_1k.hdr", + "preview": "ferndale_studio_06.jpg", + "category": "studio", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "studio", + "indoor", + "artificial light", + "urban", + "high contrast", + "photo", + "lamp", + "infinity", + "by:Dimitrios Savva", + "by:Greg Zaal" + ], + "bytes": 1228415, + "source_page": "https://polyhaven.com/a/ferndale_studio_06", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/ferndale_studio_06" + ] + }, + { + "id": "goegap", + "name": "Goegap", + "file": "goegap_1k.hdr", + "preview": "goegap.jpg", + "category": "nature", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "nature", + "midday", + "clear", + "high contrast", + "natural light", + "sand", + "dirt", + "by:Greg Zaal" + ], + "bytes": 1361485, + "source_page": "https://polyhaven.com/a/goegap", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/goegap" + ] + }, + { + "id": "golden_bay", + "name": "Golden Bay", + "file": "golden_bay_1k.hdr", + "preview": "golden_bay.jpg", + "category": "night", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "night", + "urban", + "artificial light", + "high contrast", + "clear", + "lamp", + "pier", + "by:Greg Zaal" + ], + "bytes": 1411725, + "source_page": "https://polyhaven.com/a/golden_bay", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/golden_bay" + ] + }, + { + "id": "kloofendal_misty_morning_puresky", + "name": "Kloofendal Misty Morning (Pure Sky)", + "file": "kloofendal_misty_morning_puresky_1k.hdr", + "preview": "kloofendal_misty_morning_puresky.jpg", + "category": "nature", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "skies", + "natural light", + "nature", + "overcast", + "low contrast", + "morning-afternoon", + "pure skies", + "by:Greg Zaal" + ], + "bytes": 702293, + "source_page": "https://polyhaven.com/a/kloofendal_misty_morning_puresky", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/kloofendal_misty_morning_puresky" + ] + }, + { + "id": "kloppenheim_01_puresky", + "name": "Kloppenheim 01 (Pure Sky)", + "file": "kloppenheim_01_puresky_1k.hdr", + "preview": "kloppenheim_01_puresky.jpg", + "category": "sunrise-sunset", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "skies", + "nature", + "sunrise-sunset", + "overcast", + "low contrast", + "natural light", + "pure skies", + "by:Greg Zaal", + "by:Jarod Guest" + ], + "bytes": 861984, + "source_page": "https://polyhaven.com/a/kloppenheim_01_puresky", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/kloppenheim_01_puresky" + ] + }, + { + "id": "lakeside", + "name": "Lakeside", + "file": "lakeside_1k.hdr", + "preview": "lakeside.jpg", + "category": "nature", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "nature", + "morning-afternoon", + "clear", + "high contrast", + "natural light", + "sun", + "tree", + "by:Greg Zaal" + ], + "bytes": 1474514, + "source_page": "https://polyhaven.com/a/lakeside", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/lakeside" + ] + }, + { + "id": "small_harbour_sunset", + "name": "Small Harbour Sunset", + "file": "small_harbour_sunset_1k.hdr", + "preview": "small_harbour_sunset.jpg", + "category": "sunrise-sunset", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "skies", + "natural light", + "sunrise-sunset", + "nature", + "clear", + "medium contrast", + "sun", + "by:Greg Zaal", + "by:Jarod Guest" + ], + "bytes": 1499733, + "source_page": "https://polyhaven.com/a/small_harbour_sunset", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/small_harbour_sunset" + ] + }, + { + "id": "snowy_park_01", + "name": "Snowy Park 01", + "file": "snowy_park_01_1k.hdr", + "preview": "snowy_park_01.jpg", + "category": "nature", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "nature", + "midday", + "overcast", + "low contrast", + "natural light", + "snow", + "tree", + "by:Oliksiy Yakovlyev" + ], + "bytes": 1211017, + "source_page": "https://polyhaven.com/a/snowy_park_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/snowy_park_01" + ] + }, + { + "id": "white_studio_02", + "name": "White Studio 02", + "file": "white_studio_02_1k.hdr", + "preview": "white_studio_02.jpg", + "category": "studio", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "studio", + "indoor", + "artificial light", + "urban", + "low contrast", + "lamp", + "white", + "photo", + "by:Grzegorz Wronkowski" + ], + "bytes": 1312076, + "source_page": "https://polyhaven.com/a/white_studio_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/white_studio_02" + ] + }, + { + "id": "studio_small_09", + "name": "Studio Small 09", + "file": "studio_small_09_1k.hdr", + "preview": "studio_small_09.jpg", + "category": "studio", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "medium contrast", + "indoor", + "urban", + "artificial light", + "studio", + "umbrella", + "softbox", + "infinity", + "by:Sergej Majboroda" + ], + "bytes": 1615248, + "source_page": "https://polyhaven.com/a/studio_small_09", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/studio_small_09" + ] + }, + { + "id": "lebombo", + "name": "Lebombo", + "file": "lebombo_1k.hdr", + "preview": "lebombo.jpg", + "category": "indoor", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "indoor", + "urban", + "morning-afternoon", + "low contrast", + "natural light", + "artificial light", + "house", + "lamp", + "by:Greg Zaal" + ], + "bytes": 1476953, + "source_page": "https://polyhaven.com/a/lebombo", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/lebombo" + ] + }, + { + "id": "moonless_golf", + "name": "Moonless Golf", + "file": "moonless_golf_1k.hdr", + "preview": "moonless_golf.jpg", + "category": "night", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "skies", + "nature", + "night", + "clear", + "medium contrast", + "natural light", + "artificial light", + "by:Greg Zaal" + ], + "bytes": 1672754, + "source_page": "https://polyhaven.com/a/moonless_golf", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/moonless_golf" + ] + }, + { + "id": "potsdamer_platz", + "name": "Potsdamer Platz", + "file": "potsdamer_platz_1k.hdr", + "preview": "potsdamer_platz.jpg", + "category": "urban", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "urban", + "morning-afternoon", + "overcast", + "low contrast", + "natural light", + "europe", + "architecture", + "by:Greg Zaal" + ], + "bytes": 1540678, + "source_page": "https://polyhaven.com/a/potsdamer_platz", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/potsdamer_platz" + ] + }, + { + "id": "overcast_soil_puresky", + "name": "Overcast Soil (Pure Sky)", + "file": "overcast_soil_puresky_1k.hdr", + "preview": "overcast_soil_puresky.jpg", + "category": "nature", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "skies", + "natural light", + "nature", + "low contrast", + "overcast", + "morning-afternoon", + "pure skies", + "by:Jarod Guest", + "by:Sergej Majboroda" + ], + "bytes": 1195816, + "source_page": "https://polyhaven.com/a/overcast_soil_puresky", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/overcast_soil_puresky" + ] + }, + { + "id": "venice_sunset", + "name": "Venice Sunset", + "file": "venice_sunset_1k.hdr", + "preview": "venice_sunset.jpg", + "category": "sunrise-sunset", + "tags": [ + "hdri", + "equirect", + "1k", + "radiance", + "outdoor", + "skies", + "nature", + "urban", + "sunrise-sunset", + "clear", + "medium contrast", + "natural light", + "by:Greg Zaal" + ], + "bytes": 1440400, + "source_page": "https://polyhaven.com/a/venice_sunset", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/venice_sunset" + ] + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/polyhaven-hdri/potsdamer_platz.jpg b/assets/starter/2d/polyhaven-hdri/potsdamer_platz.jpg new file mode 100644 index 0000000..f5a5a6d Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/potsdamer_platz.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/potsdamer_platz_1k.hdr b/assets/starter/2d/polyhaven-hdri/potsdamer_platz_1k.hdr new file mode 100644 index 0000000..e3121c1 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/potsdamer_platz_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/small_harbour_sunset.jpg b/assets/starter/2d/polyhaven-hdri/small_harbour_sunset.jpg new file mode 100644 index 0000000..9f20f6a Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/small_harbour_sunset.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/small_harbour_sunset_1k.hdr b/assets/starter/2d/polyhaven-hdri/small_harbour_sunset_1k.hdr new file mode 100644 index 0000000..69d28ff Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/small_harbour_sunset_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/snowy_park_01.jpg b/assets/starter/2d/polyhaven-hdri/snowy_park_01.jpg new file mode 100644 index 0000000..bfbc89f Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/snowy_park_01.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/snowy_park_01_1k.hdr b/assets/starter/2d/polyhaven-hdri/snowy_park_01_1k.hdr new file mode 100644 index 0000000..c8208f2 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/snowy_park_01_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/studio_small_09.jpg b/assets/starter/2d/polyhaven-hdri/studio_small_09.jpg new file mode 100644 index 0000000..f8b8574 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/studio_small_09.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/studio_small_09_1k.hdr b/assets/starter/2d/polyhaven-hdri/studio_small_09_1k.hdr new file mode 100644 index 0000000..e9a2d22 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/studio_small_09_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/venice_sunset.jpg b/assets/starter/2d/polyhaven-hdri/venice_sunset.jpg new file mode 100644 index 0000000..da30f47 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/venice_sunset.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/venice_sunset_1k.hdr b/assets/starter/2d/polyhaven-hdri/venice_sunset_1k.hdr new file mode 100644 index 0000000..0e33781 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/venice_sunset_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-hdri/white_studio_02.jpg b/assets/starter/2d/polyhaven-hdri/white_studio_02.jpg new file mode 100644 index 0000000..418a52a Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/white_studio_02.jpg differ diff --git a/assets/starter/2d/polyhaven-hdri/white_studio_02_1k.hdr b/assets/starter/2d/polyhaven-hdri/white_studio_02_1k.hdr new file mode 100644 index 0000000..17ef0f6 Binary files /dev/null and b/assets/starter/2d/polyhaven-hdri/white_studio_02_1k.hdr differ diff --git a/assets/starter/2d/polyhaven-textures/LICENSE.txt b/assets/starter/2d/polyhaven-textures/LICENSE.txt new file mode 100644 index 0000000..95df7f2 --- /dev/null +++ b/assets/starter/2d/polyhaven-textures/LICENSE.txt @@ -0,0 +1,11 @@ +Source: https://polyhaven.com/license +Fetched: 2026-11-29 + +Asset License All assets ( HDRIs , textures and 3D models ) on this site are the original work of Poly Haven staff, or artists who willingly and directly donate/sell their work to Poly Haven. Our assets are all licensed as CC0 , which is effectively Public Domain even in jurisdictions that do not support the Public Domain. Here's an excerpt from the CC0 FAQ page to clarify: Once the creator or a subsequent owner of a work applies CC0 to a work, the work is no longer his or hers in any meaningful sense under copyright law. Anyone can then use the work in any way and for any purpose, including commercial purposes [...] Think of CC0 as the "no rights reserved" option. CC0 is a useful tool for clarifying that you do not claim copyright in a work anywhere in the world. In other words: You can use our assets for any purpose , including commercial work. You do not need to give credit or attribution when using them (although it is appreciated). You can redistribute them , share them around, include them when sharing your own work, or even in a product you sell. More info: CC0 summary , CC0 wiki , CC0 FAQ . + +[...] + +4. Intellectual Property 4.1. All content on this website, excluding the CC0 assets themselves, is protected by intellectual property laws. You may not reproduce, distribute, or otherwise use this content without prior written permission from the website or intellectual property owner. 4.2. Examples of such content includes but is not limited to: Logos User avatar images Asset example renders User submitted renders Text and copy + +Per-item confirmation: each asset page https://polyhaven.com/a/<id> names the licence CC0 (schema.org license http://creativecommons.org/publicdomain/zero/1.0/, "CC0 1.0 Universal - public domain dedication, no attribution required"). +Previews (<id>.jpg) are rendered by FormCraft tooling from the CC0 asset files; no Poly Haven example renders are included. diff --git a/assets/starter/2d/polyhaven-textures/asphalt_02/colour.webp b/assets/starter/2d/polyhaven-textures/asphalt_02/colour.webp new file mode 100644 index 0000000..ca2cf5f Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/asphalt_02/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/asphalt_02/normal.webp b/assets/starter/2d/polyhaven-textures/asphalt_02/normal.webp new file mode 100644 index 0000000..694f19a Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/asphalt_02/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/asphalt_02/roughness.webp b/assets/starter/2d/polyhaven-textures/asphalt_02/roughness.webp new file mode 100644 index 0000000..aae5afe Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/asphalt_02/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/blue_floor_tiles_01/colour.webp b/assets/starter/2d/polyhaven-textures/blue_floor_tiles_01/colour.webp new file mode 100644 index 0000000..d7a0baa Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/blue_floor_tiles_01/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/blue_floor_tiles_01/normal.webp b/assets/starter/2d/polyhaven-textures/blue_floor_tiles_01/normal.webp new file mode 100644 index 0000000..58bc58a Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/blue_floor_tiles_01/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/blue_floor_tiles_01/roughness.webp b/assets/starter/2d/polyhaven-textures/blue_floor_tiles_01/roughness.webp new file mode 100644 index 0000000..817123d Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/blue_floor_tiles_01/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/blue_metal_plate/colour.webp b/assets/starter/2d/polyhaven-textures/blue_metal_plate/colour.webp new file mode 100644 index 0000000..a132e9d Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/blue_metal_plate/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/blue_metal_plate/normal.webp b/assets/starter/2d/polyhaven-textures/blue_metal_plate/normal.webp new file mode 100644 index 0000000..f435b8c Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/blue_metal_plate/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/blue_metal_plate/roughness.webp b/assets/starter/2d/polyhaven-textures/blue_metal_plate/roughness.webp new file mode 100644 index 0000000..d02a04f Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/blue_metal_plate/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/brick_4/colour.webp b/assets/starter/2d/polyhaven-textures/brick_4/colour.webp new file mode 100644 index 0000000..6458f12 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/brick_4/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/brick_4/normal.webp b/assets/starter/2d/polyhaven-textures/brick_4/normal.webp new file mode 100644 index 0000000..20a5db2 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/brick_4/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/brick_4/roughness.webp b/assets/starter/2d/polyhaven-textures/brick_4/roughness.webp new file mode 100644 index 0000000..e7226ec Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/brick_4/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/brown_leather/colour.webp b/assets/starter/2d/polyhaven-textures/brown_leather/colour.webp new file mode 100644 index 0000000..8046e8c Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/brown_leather/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/brown_leather/normal.webp b/assets/starter/2d/polyhaven-textures/brown_leather/normal.webp new file mode 100644 index 0000000..98e76be Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/brown_leather/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/brown_leather/roughness.webp b/assets/starter/2d/polyhaven-textures/brown_leather/roughness.webp new file mode 100644 index 0000000..6b2ce88 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/brown_leather/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/brown_planks_03/colour.webp b/assets/starter/2d/polyhaven-textures/brown_planks_03/colour.webp new file mode 100644 index 0000000..f655792 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/brown_planks_03/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/brown_planks_03/normal.webp b/assets/starter/2d/polyhaven-textures/brown_planks_03/normal.webp new file mode 100644 index 0000000..86bc75b Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/brown_planks_03/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/brown_planks_03/roughness.webp b/assets/starter/2d/polyhaven-textures/brown_planks_03/roughness.webp new file mode 100644 index 0000000..ccf5f1d Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/brown_planks_03/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/coast_sand_01/colour.webp b/assets/starter/2d/polyhaven-textures/coast_sand_01/colour.webp new file mode 100644 index 0000000..e9b7f42 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/coast_sand_01/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/coast_sand_01/normal.webp b/assets/starter/2d/polyhaven-textures/coast_sand_01/normal.webp new file mode 100644 index 0000000..f161170 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/coast_sand_01/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/coast_sand_01/roughness.webp b/assets/starter/2d/polyhaven-textures/coast_sand_01/roughness.webp new file mode 100644 index 0000000..76cf737 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/coast_sand_01/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/cobblestone_floor_001/colour.webp b/assets/starter/2d/polyhaven-textures/cobblestone_floor_001/colour.webp new file mode 100644 index 0000000..6aa4bbd Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/cobblestone_floor_001/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/cobblestone_floor_001/normal.webp b/assets/starter/2d/polyhaven-textures/cobblestone_floor_001/normal.webp new file mode 100644 index 0000000..ad706cf Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/cobblestone_floor_001/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/cobblestone_floor_001/roughness.webp b/assets/starter/2d/polyhaven-textures/cobblestone_floor_001/roughness.webp new file mode 100644 index 0000000..1f8c0c1 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/cobblestone_floor_001/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/concrete_floor_02/colour.webp b/assets/starter/2d/polyhaven-textures/concrete_floor_02/colour.webp new file mode 100644 index 0000000..7766327 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/concrete_floor_02/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/concrete_floor_02/normal.webp b/assets/starter/2d/polyhaven-textures/concrete_floor_02/normal.webp new file mode 100644 index 0000000..ecb012e Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/concrete_floor_02/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/concrete_floor_02/roughness.webp b/assets/starter/2d/polyhaven-textures/concrete_floor_02/roughness.webp new file mode 100644 index 0000000..814867e Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/concrete_floor_02/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/denim_fabric/colour.webp b/assets/starter/2d/polyhaven-textures/denim_fabric/colour.webp new file mode 100644 index 0000000..f93ec14 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/denim_fabric/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/denim_fabric/normal.webp b/assets/starter/2d/polyhaven-textures/denim_fabric/normal.webp new file mode 100644 index 0000000..0d76b95 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/denim_fabric/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/denim_fabric/roughness.webp b/assets/starter/2d/polyhaven-textures/denim_fabric/roughness.webp new file mode 100644 index 0000000..bb1a517 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/denim_fabric/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/floor_tiles_06/colour.webp b/assets/starter/2d/polyhaven-textures/floor_tiles_06/colour.webp new file mode 100644 index 0000000..4dd8001 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/floor_tiles_06/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/floor_tiles_06/normal.webp b/assets/starter/2d/polyhaven-textures/floor_tiles_06/normal.webp new file mode 100644 index 0000000..57b7174 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/floor_tiles_06/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/floor_tiles_06/roughness.webp b/assets/starter/2d/polyhaven-textures/floor_tiles_06/roughness.webp new file mode 100644 index 0000000..739d9be Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/floor_tiles_06/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/forrest_ground_01/colour.webp b/assets/starter/2d/polyhaven-textures/forrest_ground_01/colour.webp new file mode 100644 index 0000000..a7cbb4c Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/forrest_ground_01/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/forrest_ground_01/normal.webp b/assets/starter/2d/polyhaven-textures/forrest_ground_01/normal.webp new file mode 100644 index 0000000..0a23571 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/forrest_ground_01/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/forrest_ground_01/roughness.webp b/assets/starter/2d/polyhaven-textures/forrest_ground_01/roughness.webp new file mode 100644 index 0000000..8ae216e Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/forrest_ground_01/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/grass_path_2/colour.webp b/assets/starter/2d/polyhaven-textures/grass_path_2/colour.webp new file mode 100644 index 0000000..d63d823 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/grass_path_2/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/grass_path_2/normal.webp b/assets/starter/2d/polyhaven-textures/grass_path_2/normal.webp new file mode 100644 index 0000000..7b627f5 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/grass_path_2/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/grass_path_2/roughness.webp b/assets/starter/2d/polyhaven-textures/grass_path_2/roughness.webp new file mode 100644 index 0000000..e17d7f6 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/grass_path_2/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/green_metal_rust/colour.webp b/assets/starter/2d/polyhaven-textures/green_metal_rust/colour.webp new file mode 100644 index 0000000..34b5052 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/green_metal_rust/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/green_metal_rust/normal.webp b/assets/starter/2d/polyhaven-textures/green_metal_rust/normal.webp new file mode 100644 index 0000000..7d84329 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/green_metal_rust/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/green_metal_rust/roughness.webp b/assets/starter/2d/polyhaven-textures/green_metal_rust/roughness.webp new file mode 100644 index 0000000..ff25836 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/green_metal_rust/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/grey_plaster/colour.webp b/assets/starter/2d/polyhaven-textures/grey_plaster/colour.webp new file mode 100644 index 0000000..c107d4d Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/grey_plaster/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/grey_plaster/normal.webp b/assets/starter/2d/polyhaven-textures/grey_plaster/normal.webp new file mode 100644 index 0000000..91032fe Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/grey_plaster/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/grey_plaster/roughness.webp b/assets/starter/2d/polyhaven-textures/grey_plaster/roughness.webp new file mode 100644 index 0000000..0319917 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/grey_plaster/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/marble_01/colour.webp b/assets/starter/2d/polyhaven-textures/marble_01/colour.webp new file mode 100644 index 0000000..1c50b1c Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/marble_01/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/marble_01/normal.webp b/assets/starter/2d/polyhaven-textures/marble_01/normal.webp new file mode 100644 index 0000000..fc3a3ab Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/marble_01/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/marble_01/roughness.webp b/assets/starter/2d/polyhaven-textures/marble_01/roughness.webp new file mode 100644 index 0000000..e9e1a3e Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/marble_01/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/marble_tiles/colour.webp b/assets/starter/2d/polyhaven-textures/marble_tiles/colour.webp new file mode 100644 index 0000000..1cb812f Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/marble_tiles/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/marble_tiles/normal.webp b/assets/starter/2d/polyhaven-textures/marble_tiles/normal.webp new file mode 100644 index 0000000..1e1015c Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/marble_tiles/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/marble_tiles/roughness.webp b/assets/starter/2d/polyhaven-textures/marble_tiles/roughness.webp new file mode 100644 index 0000000..cd921cc Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/marble_tiles/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/metal_plate/colour.webp b/assets/starter/2d/polyhaven-textures/metal_plate/colour.webp new file mode 100644 index 0000000..cf028d7 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/metal_plate/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/metal_plate/normal.webp b/assets/starter/2d/polyhaven-textures/metal_plate/normal.webp new file mode 100644 index 0000000..3de0488 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/metal_plate/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/metal_plate/roughness.webp b/assets/starter/2d/polyhaven-textures/metal_plate/roughness.webp new file mode 100644 index 0000000..e047ab5 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/metal_plate/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/pack.json b/assets/starter/2d/polyhaven-textures/pack.json new file mode 100644 index 0000000..d337c8a --- /dev/null +++ b/assets/starter/2d/polyhaven-textures/pack.json @@ -0,0 +1,2290 @@ +{ + "id": "polyhaven-textures", + "name": "PBR materials (Poly Haven)", + "kind": "texture", + "licence": "CC0-1.0", + "author": "Poly Haven (polyhaven.com) artists: Amal Kumar, Charlotte Baglioni, Dario Barresi, Dimitrios Savva, Rico Cilliers, Rob Tuytel", + "source_url": "https://polyhaven.com/textures", + "source_commit_or_version": "api.polyhaven.com snapshot, 1k JPG maps (Diffuse, nor_gl, Rough) re-encoded to WebP at 1024 px for size, retrieved 2026-11-29", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/<item id> (per item, see items[].licence_evidence)" + ], + "items": [ + { + "id": "wood_floor-colour", + "name": "Wood Floor colour", + "file": "wood_floor/colour.webp", + "material": "wood_floor", + "map": "colour", + "category": "floor", + "tags": [ + "pbr", + "1k", + "colour", + "material:wood_floor", + "seamless", + "floor", + "wood", + "man made", + "clean", + "wooden", + "wooden flooring ", + "grain", + "by:Dimitrios Savva" + ], + "bytes": 69886, + "source_page": "https://polyhaven.com/a/wood_floor", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/wood_floor" + ] + }, + { + "id": "wood_floor-normal", + "name": "Wood Floor normal", + "file": "wood_floor/normal.webp", + "material": "wood_floor", + "map": "normal", + "category": "floor", + "tags": [ + "pbr", + "1k", + "normal", + "material:wood_floor", + "seamless", + "floor", + "wood", + "man made", + "clean", + "wooden", + "wooden flooring ", + "grain", + "by:Dimitrios Savva" + ], + "bytes": 2748, + "source_page": "https://polyhaven.com/a/wood_floor", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/wood_floor" + ] + }, + { + "id": "wood_floor-roughness", + "name": "Wood Floor roughness", + "file": "wood_floor/roughness.webp", + "material": "wood_floor", + "map": "roughness", + "category": "floor", + "tags": [ + "pbr", + "1k", + "roughness", + "material:wood_floor", + "seamless", + "floor", + "wood", + "man made", + "clean", + "wooden", + "wooden flooring ", + "grain", + "by:Dimitrios Savva" + ], + "bytes": 26246, + "source_page": "https://polyhaven.com/a/wood_floor", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/wood_floor" + ] + }, + { + "id": "wood_floor_worn-colour", + "name": "Wood Floor Worn colour", + "file": "wood_floor_worn/colour.webp", + "material": "wood_floor_worn", + "map": "colour", + "category": "floor", + "tags": [ + "pbr", + "1k", + "colour", + "material:wood_floor_worn", + "seamless", + "floor", + "wood", + "man made", + "old", + "weathered", + "rough", + "worn", + "by:Dimitrios Savva" + ], + "bytes": 33890, + "source_page": "https://polyhaven.com/a/wood_floor_worn", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/wood_floor_worn" + ] + }, + { + "id": "wood_floor_worn-normal", + "name": "Wood Floor Worn normal", + "file": "wood_floor_worn/normal.webp", + "material": "wood_floor_worn", + "map": "normal", + "category": "floor", + "tags": [ + "pbr", + "1k", + "normal", + "material:wood_floor_worn", + "seamless", + "floor", + "wood", + "man made", + "old", + "weathered", + "rough", + "worn", + "by:Dimitrios Savva" + ], + "bytes": 23888, + "source_page": "https://polyhaven.com/a/wood_floor_worn", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/wood_floor_worn" + ] + }, + { + "id": "wood_floor_worn-roughness", + "name": "Wood Floor Worn roughness", + "file": "wood_floor_worn/roughness.webp", + "material": "wood_floor_worn", + "map": "roughness", + "category": "floor", + "tags": [ + "pbr", + "1k", + "roughness", + "material:wood_floor_worn", + "seamless", + "floor", + "wood", + "man made", + "old", + "weathered", + "rough", + "worn", + "by:Dimitrios Savva" + ], + "bytes": 4500, + "source_page": "https://polyhaven.com/a/wood_floor_worn", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/wood_floor_worn" + ] + }, + { + "id": "brown_planks_03-colour", + "name": "Brown Planks 03 colour", + "file": "brown_planks_03/colour.webp", + "material": "brown_planks_03", + "map": "colour", + "category": "wood", + "tags": [ + "pbr", + "1k", + "colour", + "material:brown_planks_03", + "seamless", + "wood", + "man made", + "indoor", + "outdoor", + "clean", + "wall", + "planks", + "by:Rob Tuytel" + ], + "bytes": 157126, + "source_page": "https://polyhaven.com/a/brown_planks_03", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/brown_planks_03" + ] + }, + { + "id": "brown_planks_03-normal", + "name": "Brown Planks 03 normal", + "file": "brown_planks_03/normal.webp", + "material": "brown_planks_03", + "map": "normal", + "category": "wood", + "tags": [ + "pbr", + "1k", + "normal", + "material:brown_planks_03", + "seamless", + "wood", + "man made", + "indoor", + "outdoor", + "clean", + "wall", + "planks", + "by:Rob Tuytel" + ], + "bytes": 27338, + "source_page": "https://polyhaven.com/a/brown_planks_03", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/brown_planks_03" + ] + }, + { + "id": "brown_planks_03-roughness", + "name": "Brown Planks 03 roughness", + "file": "brown_planks_03/roughness.webp", + "material": "brown_planks_03", + "map": "roughness", + "category": "wood", + "tags": [ + "pbr", + "1k", + "roughness", + "material:brown_planks_03", + "seamless", + "wood", + "man made", + "indoor", + "outdoor", + "clean", + "wall", + "planks", + "by:Rob Tuytel" + ], + "bytes": 15006, + "source_page": "https://polyhaven.com/a/brown_planks_03", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/brown_planks_03" + ] + }, + { + "id": "weathered_planks-colour", + "name": "Weathered Planks colour", + "file": "weathered_planks/colour.webp", + "material": "weathered_planks", + "map": "colour", + "category": "outdoor", + "tags": [ + "pbr", + "1k", + "colour", + "material:weathered_planks", + "seamless", + "outdoor", + "wood", + "man made", + "wall", + "floor", + "wooden", + "bridge", + "by:Dario Barresi", + "by:Dimitrios Savva" + ], + "bytes": 37326, + "source_page": "https://polyhaven.com/a/weathered_planks", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/weathered_planks" + ] + }, + { + "id": "weathered_planks-normal", + "name": "Weathered Planks normal", + "file": "weathered_planks/normal.webp", + "material": "weathered_planks", + "map": "normal", + "category": "outdoor", + "tags": [ + "pbr", + "1k", + "normal", + "material:weathered_planks", + "seamless", + "outdoor", + "wood", + "man made", + "wall", + "floor", + "wooden", + "bridge", + "by:Dario Barresi", + "by:Dimitrios Savva" + ], + "bytes": 29550, + "source_page": "https://polyhaven.com/a/weathered_planks", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/weathered_planks" + ] + }, + { + "id": "weathered_planks-roughness", + "name": "Weathered Planks roughness", + "file": "weathered_planks/roughness.webp", + "material": "weathered_planks", + "map": "roughness", + "category": "outdoor", + "tags": [ + "pbr", + "1k", + "roughness", + "material:weathered_planks", + "seamless", + "outdoor", + "wood", + "man made", + "wall", + "floor", + "wooden", + "bridge", + "by:Dario Barresi", + "by:Dimitrios Savva" + ], + "bytes": 2826, + "source_page": "https://polyhaven.com/a/weathered_planks", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/weathered_planks" + ] + }, + { + "id": "brick_4-colour", + "name": "Brick 4 colour", + "file": "brick_4/colour.webp", + "material": "brick_4", + "map": "colour", + "category": "wall", + "tags": [ + "pbr", + "1k", + "colour", + "material:brick_4", + "seamless", + "wall", + "man made", + "dirty", + "outdoor", + "brick", + "red", + "moss", + "by:Rob Tuytel" + ], + "bytes": 189290, + "source_page": "https://polyhaven.com/a/brick_4", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/brick_4" + ] + }, + { + "id": "brick_4-normal", + "name": "Brick 4 normal", + "file": "brick_4/normal.webp", + "material": "brick_4", + "map": "normal", + "category": "wall", + "tags": [ + "pbr", + "1k", + "normal", + "material:brick_4", + "seamless", + "wall", + "man made", + "dirty", + "outdoor", + "brick", + "red", + "moss", + "by:Rob Tuytel" + ], + "bytes": 188252, + "source_page": "https://polyhaven.com/a/brick_4", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/brick_4" + ] + }, + { + "id": "brick_4-roughness", + "name": "Brick 4 roughness", + "file": "brick_4/roughness.webp", + "material": "brick_4", + "map": "roughness", + "category": "wall", + "tags": [ + "pbr", + "1k", + "roughness", + "material:brick_4", + "seamless", + "wall", + "man made", + "dirty", + "outdoor", + "brick", + "red", + "moss", + "by:Rob Tuytel" + ], + "bytes": 174834, + "source_page": "https://polyhaven.com/a/brick_4", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/brick_4" + ] + }, + { + "id": "red_brick_03-colour", + "name": "Red Brick 03 colour", + "file": "red_brick_03/colour.webp", + "material": "red_brick_03", + "map": "colour", + "category": "outdoor", + "tags": [ + "pbr", + "1k", + "colour", + "material:red_brick_03", + "seamless", + "outdoor", + "wall", + "clean", + "man made", + "brick", + "red", + "industrial", + "by:Rob Tuytel" + ], + "bytes": 202132, + "source_page": "https://polyhaven.com/a/red_brick_03", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/red_brick_03" + ] + }, + { + "id": "red_brick_03-normal", + "name": "Red Brick 03 normal", + "file": "red_brick_03/normal.webp", + "material": "red_brick_03", + "map": "normal", + "category": "outdoor", + "tags": [ + "pbr", + "1k", + "normal", + "material:red_brick_03", + "seamless", + "outdoor", + "wall", + "clean", + "man made", + "brick", + "red", + "industrial", + "by:Rob Tuytel" + ], + "bytes": 140760, + "source_page": "https://polyhaven.com/a/red_brick_03", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/red_brick_03" + ] + }, + { + "id": "red_brick_03-roughness", + "name": "Red Brick 03 roughness", + "file": "red_brick_03/roughness.webp", + "material": "red_brick_03", + "map": "roughness", + "category": "outdoor", + "tags": [ + "pbr", + "1k", + "roughness", + "material:red_brick_03", + "seamless", + "outdoor", + "wall", + "clean", + "man made", + "brick", + "red", + "industrial", + "by:Rob Tuytel" + ], + "bytes": 26162, + "source_page": "https://polyhaven.com/a/red_brick_03", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/red_brick_03" + ] + }, + { + "id": "concrete_floor_02-colour", + "name": "Concrete Floor 02 colour", + "file": "concrete_floor_02/colour.webp", + "material": "concrete_floor_02", + "map": "colour", + "category": "concrete", + "tags": [ + "pbr", + "1k", + "colour", + "material:concrete_floor_02", + "seamless", + "concrete", + "plaster-concrete", + "dirty", + "man made", + "outdoor", + "indoor", + "wall", + "by:Rob Tuytel" + ], + "bytes": 302070, + "source_page": "https://polyhaven.com/a/concrete_floor_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/concrete_floor_02" + ] + }, + { + "id": "concrete_floor_02-normal", + "name": "Concrete Floor 02 normal", + "file": "concrete_floor_02/normal.webp", + "material": "concrete_floor_02", + "map": "normal", + "category": "concrete", + "tags": [ + "pbr", + "1k", + "normal", + "material:concrete_floor_02", + "seamless", + "concrete", + "plaster-concrete", + "dirty", + "man made", + "outdoor", + "indoor", + "wall", + "by:Rob Tuytel" + ], + "bytes": 59878, + "source_page": "https://polyhaven.com/a/concrete_floor_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/concrete_floor_02" + ] + }, + { + "id": "concrete_floor_02-roughness", + "name": "Concrete Floor 02 roughness", + "file": "concrete_floor_02/roughness.webp", + "material": "concrete_floor_02", + "map": "roughness", + "category": "concrete", + "tags": [ + "pbr", + "1k", + "roughness", + "material:concrete_floor_02", + "seamless", + "concrete", + "plaster-concrete", + "dirty", + "man made", + "outdoor", + "indoor", + "wall", + "by:Rob Tuytel" + ], + "bytes": 28296, + "source_page": "https://polyhaven.com/a/concrete_floor_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/concrete_floor_02" + ] + }, + { + "id": "grey_plaster-colour", + "name": "Grey Plaster colour", + "file": "grey_plaster/colour.webp", + "material": "grey_plaster", + "map": "colour", + "category": "plaster", + "tags": [ + "pbr", + "1k", + "colour", + "material:grey_plaster", + "seamless", + "plaster", + "outdoor", + "indoor", + "man made", + "wall", + "floor", + "plaster-concrete", + "by:Rob Tuytel" + ], + "bytes": 260100, + "source_page": "https://polyhaven.com/a/grey_plaster", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/grey_plaster" + ] + }, + { + "id": "grey_plaster-normal", + "name": "Grey Plaster normal", + "file": "grey_plaster/normal.webp", + "material": "grey_plaster", + "map": "normal", + "category": "plaster", + "tags": [ + "pbr", + "1k", + "normal", + "material:grey_plaster", + "seamless", + "plaster", + "outdoor", + "indoor", + "man made", + "wall", + "floor", + "plaster-concrete", + "by:Rob Tuytel" + ], + "bytes": 11908, + "source_page": "https://polyhaven.com/a/grey_plaster", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/grey_plaster" + ] + }, + { + "id": "grey_plaster-roughness", + "name": "Grey Plaster roughness", + "file": "grey_plaster/roughness.webp", + "material": "grey_plaster", + "map": "roughness", + "category": "plaster", + "tags": [ + "pbr", + "1k", + "roughness", + "material:grey_plaster", + "seamless", + "plaster", + "outdoor", + "indoor", + "man made", + "wall", + "floor", + "plaster-concrete", + "by:Rob Tuytel" + ], + "bytes": 242820, + "source_page": "https://polyhaven.com/a/grey_plaster", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/grey_plaster" + ] + }, + { + "id": "white_plaster_02-colour", + "name": "White Plaster 02 colour", + "file": "white_plaster_02/colour.webp", + "material": "white_plaster_02", + "map": "colour", + "category": "plaster-concrete", + "tags": [ + "pbr", + "1k", + "colour", + "material:white_plaster_02", + "seamless", + "plaster-concrete", + "wall", + "man made", + "outdoor", + "indoor", + "clean", + "floor", + "by:Rob Tuytel" + ], + "bytes": 136552, + "source_page": "https://polyhaven.com/a/white_plaster_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/white_plaster_02" + ] + }, + { + "id": "white_plaster_02-normal", + "name": "White Plaster 02 normal", + "file": "white_plaster_02/normal.webp", + "material": "white_plaster_02", + "map": "normal", + "category": "plaster-concrete", + "tags": [ + "pbr", + "1k", + "normal", + "material:white_plaster_02", + "seamless", + "plaster-concrete", + "wall", + "man made", + "outdoor", + "indoor", + "clean", + "floor", + "by:Rob Tuytel" + ], + "bytes": 54000, + "source_page": "https://polyhaven.com/a/white_plaster_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/white_plaster_02" + ] + }, + { + "id": "white_plaster_02-roughness", + "name": "White Plaster 02 roughness", + "file": "white_plaster_02/roughness.webp", + "material": "white_plaster_02", + "map": "roughness", + "category": "plaster-concrete", + "tags": [ + "pbr", + "1k", + "roughness", + "material:white_plaster_02", + "seamless", + "plaster-concrete", + "wall", + "man made", + "outdoor", + "indoor", + "clean", + "floor", + "by:Rob Tuytel" + ], + "bytes": 15416, + "source_page": "https://polyhaven.com/a/white_plaster_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/white_plaster_02" + ] + }, + { + "id": "metal_plate-colour", + "name": "Metal Plate colour", + "file": "metal_plate/colour.webp", + "material": "metal_plate", + "map": "colour", + "category": "metal", + "tags": [ + "pbr", + "1k", + "colour", + "material:metal_plate", + "seamless", + "metal", + "floor", + "man made", + "indoor", + "outdoor", + "dirty", + "bare", + "by:Rob Tuytel" + ], + "bytes": 52702, + "source_page": "https://polyhaven.com/a/metal_plate", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/metal_plate" + ] + }, + { + "id": "metal_plate-normal", + "name": "Metal Plate normal", + "file": "metal_plate/normal.webp", + "material": "metal_plate", + "map": "normal", + "category": "metal", + "tags": [ + "pbr", + "1k", + "normal", + "material:metal_plate", + "seamless", + "metal", + "floor", + "man made", + "indoor", + "outdoor", + "dirty", + "bare", + "by:Rob Tuytel" + ], + "bytes": 58606, + "source_page": "https://polyhaven.com/a/metal_plate", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/metal_plate" + ] + }, + { + "id": "metal_plate-roughness", + "name": "Metal Plate roughness", + "file": "metal_plate/roughness.webp", + "material": "metal_plate", + "map": "roughness", + "category": "metal", + "tags": [ + "pbr", + "1k", + "roughness", + "material:metal_plate", + "seamless", + "metal", + "floor", + "man made", + "indoor", + "outdoor", + "dirty", + "bare", + "by:Rob Tuytel" + ], + "bytes": 105896, + "source_page": "https://polyhaven.com/a/metal_plate", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/metal_plate" + ] + }, + { + "id": "blue_metal_plate-colour", + "name": "Blue Metal Plate colour", + "file": "blue_metal_plate/colour.webp", + "material": "blue_metal_plate", + "map": "colour", + "category": "metal", + "tags": [ + "pbr", + "1k", + "colour", + "material:blue_metal_plate", + "seamless", + "metal", + "industrial", + "scratched", + "metal sheet", + "painted", + "scratches", + "scuffed", + "by:Rob Tuytel" + ], + "bytes": 13500, + "source_page": "https://polyhaven.com/a/blue_metal_plate", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/blue_metal_plate" + ] + }, + { + "id": "blue_metal_plate-normal", + "name": "Blue Metal Plate normal", + "file": "blue_metal_plate/normal.webp", + "material": "blue_metal_plate", + "map": "normal", + "category": "metal", + "tags": [ + "pbr", + "1k", + "normal", + "material:blue_metal_plate", + "seamless", + "metal", + "industrial", + "scratched", + "metal sheet", + "painted", + "scratches", + "scuffed", + "by:Rob Tuytel" + ], + "bytes": 4984, + "source_page": "https://polyhaven.com/a/blue_metal_plate", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/blue_metal_plate" + ] + }, + { + "id": "blue_metal_plate-roughness", + "name": "Blue Metal Plate roughness", + "file": "blue_metal_plate/roughness.webp", + "material": "blue_metal_plate", + "map": "roughness", + "category": "metal", + "tags": [ + "pbr", + "1k", + "roughness", + "material:blue_metal_plate", + "seamless", + "metal", + "industrial", + "scratched", + "metal sheet", + "painted", + "scratches", + "scuffed", + "by:Rob Tuytel" + ], + "bytes": 15168, + "source_page": "https://polyhaven.com/a/blue_metal_plate", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/blue_metal_plate" + ] + }, + { + "id": "rust_coarse_01-colour", + "name": "Rust Coarse 01 colour", + "file": "rust_coarse_01/colour.webp", + "material": "rust_coarse_01", + "map": "colour", + "category": "metal", + "tags": [ + "pbr", + "1k", + "colour", + "material:rust_coarse_01", + "seamless", + "metal", + "outdoor", + "man made", + "dirty", + "wall", + "coarse", + "rusty", + "by:Dimitrios Savva", + "by:Rico Cilliers" + ], + "bytes": 95930, + "source_page": "https://polyhaven.com/a/rust_coarse_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/rust_coarse_01" + ] + }, + { + "id": "rust_coarse_01-normal", + "name": "Rust Coarse 01 normal", + "file": "rust_coarse_01/normal.webp", + "material": "rust_coarse_01", + "map": "normal", + "category": "metal", + "tags": [ + "pbr", + "1k", + "normal", + "material:rust_coarse_01", + "seamless", + "metal", + "outdoor", + "man made", + "dirty", + "wall", + "coarse", + "rusty", + "by:Dimitrios Savva", + "by:Rico Cilliers" + ], + "bytes": 33942, + "source_page": "https://polyhaven.com/a/rust_coarse_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/rust_coarse_01" + ] + }, + { + "id": "rust_coarse_01-roughness", + "name": "Rust Coarse 01 roughness", + "file": "rust_coarse_01/roughness.webp", + "material": "rust_coarse_01", + "map": "roughness", + "category": "metal", + "tags": [ + "pbr", + "1k", + "roughness", + "material:rust_coarse_01", + "seamless", + "metal", + "outdoor", + "man made", + "dirty", + "wall", + "coarse", + "rusty", + "by:Dimitrios Savva", + "by:Rico Cilliers" + ], + "bytes": 76290, + "source_page": "https://polyhaven.com/a/rust_coarse_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/rust_coarse_01" + ] + }, + { + "id": "green_metal_rust-colour", + "name": "Green Metal Rust colour", + "file": "green_metal_rust/colour.webp", + "material": "green_metal_rust", + "map": "colour", + "category": "metal", + "tags": [ + "pbr", + "1k", + "colour", + "material:green_metal_rust", + "seamless", + "metal", + "outdoor", + "indoor", + "man made", + "dirty", + "painted", + "ship", + "by:Rob Tuytel" + ], + "bytes": 13186, + "source_page": "https://polyhaven.com/a/green_metal_rust", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/green_metal_rust" + ] + }, + { + "id": "green_metal_rust-normal", + "name": "Green Metal Rust normal", + "file": "green_metal_rust/normal.webp", + "material": "green_metal_rust", + "map": "normal", + "category": "metal", + "tags": [ + "pbr", + "1k", + "normal", + "material:green_metal_rust", + "seamless", + "metal", + "outdoor", + "indoor", + "man made", + "dirty", + "painted", + "ship", + "by:Rob Tuytel" + ], + "bytes": 4410, + "source_page": "https://polyhaven.com/a/green_metal_rust", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/green_metal_rust" + ] + }, + { + "id": "green_metal_rust-roughness", + "name": "Green Metal Rust roughness", + "file": "green_metal_rust/roughness.webp", + "material": "green_metal_rust", + "map": "roughness", + "category": "metal", + "tags": [ + "pbr", + "1k", + "roughness", + "material:green_metal_rust", + "seamless", + "metal", + "outdoor", + "indoor", + "man made", + "dirty", + "painted", + "ship", + "by:Rob Tuytel" + ], + "bytes": 6394, + "source_page": "https://polyhaven.com/a/green_metal_rust", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/green_metal_rust" + ] + }, + { + "id": "blue_floor_tiles_01-colour", + "name": "Blue Floor Tiles 01 colour", + "file": "blue_floor_tiles_01/colour.webp", + "material": "blue_floor_tiles_01", + "map": "colour", + "category": "floor", + "tags": [ + "pbr", + "1k", + "colour", + "material:blue_floor_tiles_01", + "seamless", + "floor", + "man made", + "outdoor", + "dirty", + "brick", + "moss", + "damp", + "by:Rob Tuytel" + ], + "bytes": 114530, + "source_page": "https://polyhaven.com/a/blue_floor_tiles_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/blue_floor_tiles_01" + ] + }, + { + "id": "blue_floor_tiles_01-normal", + "name": "Blue Floor Tiles 01 normal", + "file": "blue_floor_tiles_01/normal.webp", + "material": "blue_floor_tiles_01", + "map": "normal", + "category": "floor", + "tags": [ + "pbr", + "1k", + "normal", + "material:blue_floor_tiles_01", + "seamless", + "floor", + "man made", + "outdoor", + "dirty", + "brick", + "moss", + "damp", + "by:Rob Tuytel" + ], + "bytes": 100228, + "source_page": "https://polyhaven.com/a/blue_floor_tiles_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/blue_floor_tiles_01" + ] + }, + { + "id": "blue_floor_tiles_01-roughness", + "name": "Blue Floor Tiles 01 roughness", + "file": "blue_floor_tiles_01/roughness.webp", + "material": "blue_floor_tiles_01", + "map": "roughness", + "category": "floor", + "tags": [ + "pbr", + "1k", + "roughness", + "material:blue_floor_tiles_01", + "seamless", + "floor", + "man made", + "outdoor", + "dirty", + "brick", + "moss", + "damp", + "by:Rob Tuytel" + ], + "bytes": 20904, + "source_page": "https://polyhaven.com/a/blue_floor_tiles_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/blue_floor_tiles_01" + ] + }, + { + "id": "floor_tiles_06-colour", + "name": "Floor Tiles 06 colour", + "file": "floor_tiles_06/colour.webp", + "material": "floor_tiles_06", + "map": "colour", + "category": "floor", + "tags": [ + "pbr", + "1k", + "colour", + "material:floor_tiles_06", + "seamless", + "floor", + "indoor", + "clean", + "man made", + "marble", + "tiles", + "checkerboard", + "by:Rob Tuytel" + ], + "bytes": 41412, + "source_page": "https://polyhaven.com/a/floor_tiles_06", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/floor_tiles_06" + ] + }, + { + "id": "floor_tiles_06-normal", + "name": "Floor Tiles 06 normal", + "file": "floor_tiles_06/normal.webp", + "material": "floor_tiles_06", + "map": "normal", + "category": "floor", + "tags": [ + "pbr", + "1k", + "normal", + "material:floor_tiles_06", + "seamless", + "floor", + "indoor", + "clean", + "man made", + "marble", + "tiles", + "checkerboard", + "by:Rob Tuytel" + ], + "bytes": 3992, + "source_page": "https://polyhaven.com/a/floor_tiles_06", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/floor_tiles_06" + ] + }, + { + "id": "floor_tiles_06-roughness", + "name": "Floor Tiles 06 roughness", + "file": "floor_tiles_06/roughness.webp", + "material": "floor_tiles_06", + "map": "roughness", + "category": "floor", + "tags": [ + "pbr", + "1k", + "roughness", + "material:floor_tiles_06", + "seamless", + "floor", + "indoor", + "clean", + "man made", + "marble", + "tiles", + "checkerboard", + "by:Rob Tuytel" + ], + "bytes": 6990, + "source_page": "https://polyhaven.com/a/floor_tiles_06", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/floor_tiles_06" + ] + }, + { + "id": "marble_tiles-colour", + "name": "Marble Tiles colour", + "file": "marble_tiles/colour.webp", + "material": "marble_tiles", + "map": "colour", + "category": "floor", + "tags": [ + "pbr", + "1k", + "colour", + "material:marble_tiles", + "seamless", + "floor", + "man made", + "outdoor", + "dirty", + "tiles", + "marble", + "ceramic", + "by:Charlotte Baglioni" + ], + "bytes": 179758, + "source_page": "https://polyhaven.com/a/marble_tiles", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/marble_tiles" + ] + }, + { + "id": "marble_tiles-normal", + "name": "Marble Tiles normal", + "file": "marble_tiles/normal.webp", + "material": "marble_tiles", + "map": "normal", + "category": "floor", + "tags": [ + "pbr", + "1k", + "normal", + "material:marble_tiles", + "seamless", + "floor", + "man made", + "outdoor", + "dirty", + "tiles", + "marble", + "ceramic", + "by:Charlotte Baglioni" + ], + "bytes": 28300, + "source_page": "https://polyhaven.com/a/marble_tiles", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/marble_tiles" + ] + }, + { + "id": "marble_tiles-roughness", + "name": "Marble Tiles roughness", + "file": "marble_tiles/roughness.webp", + "material": "marble_tiles", + "map": "roughness", + "category": "floor", + "tags": [ + "pbr", + "1k", + "roughness", + "material:marble_tiles", + "seamless", + "floor", + "man made", + "outdoor", + "dirty", + "tiles", + "marble", + "ceramic", + "by:Charlotte Baglioni" + ], + "bytes": 106566, + "source_page": "https://polyhaven.com/a/marble_tiles", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/marble_tiles" + ] + }, + { + "id": "denim_fabric-colour", + "name": "Denim Fabric colour", + "file": "denim_fabric/colour.webp", + "material": "denim_fabric", + "map": "colour", + "category": "fabric", + "tags": [ + "pbr", + "1k", + "colour", + "material:denim_fabric", + "seamless", + "fabric", + "denim", + "jeans", + "pants", + "cloth", + "clothing", + "stitching", + "by:Rob Tuytel" + ], + "bytes": 325118, + "source_page": "https://polyhaven.com/a/denim_fabric", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/denim_fabric" + ] + }, + { + "id": "denim_fabric-normal", + "name": "Denim Fabric normal", + "file": "denim_fabric/normal.webp", + "material": "denim_fabric", + "map": "normal", + "category": "fabric", + "tags": [ + "pbr", + "1k", + "normal", + "material:denim_fabric", + "seamless", + "fabric", + "denim", + "jeans", + "pants", + "cloth", + "clothing", + "stitching", + "by:Rob Tuytel" + ], + "bytes": 27662, + "source_page": "https://polyhaven.com/a/denim_fabric", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/denim_fabric" + ] + }, + { + "id": "denim_fabric-roughness", + "name": "Denim Fabric roughness", + "file": "denim_fabric/roughness.webp", + "material": "denim_fabric", + "map": "roughness", + "category": "fabric", + "tags": [ + "pbr", + "1k", + "roughness", + "material:denim_fabric", + "seamless", + "fabric", + "denim", + "jeans", + "pants", + "cloth", + "clothing", + "stitching", + "by:Rob Tuytel" + ], + "bytes": 110716, + "source_page": "https://polyhaven.com/a/denim_fabric", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/denim_fabric" + ] + }, + { + "id": "brown_leather-colour", + "name": "Brown Leather colour", + "file": "brown_leather/colour.webp", + "material": "brown_leather", + "map": "colour", + "category": "fabric", + "tags": [ + "pbr", + "1k", + "colour", + "material:brown_leather", + "seamless", + "fabric", + "leather", + "brown", + "chair", + "seat", + "upholstery", + "vintage", + "by:Rob Tuytel" + ], + "bytes": 86164, + "source_page": "https://polyhaven.com/a/brown_leather", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/brown_leather" + ] + }, + { + "id": "brown_leather-normal", + "name": "Brown Leather normal", + "file": "brown_leather/normal.webp", + "material": "brown_leather", + "map": "normal", + "category": "fabric", + "tags": [ + "pbr", + "1k", + "normal", + "material:brown_leather", + "seamless", + "fabric", + "leather", + "brown", + "chair", + "seat", + "upholstery", + "vintage", + "by:Rob Tuytel" + ], + "bytes": 119930, + "source_page": "https://polyhaven.com/a/brown_leather", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/brown_leather" + ] + }, + { + "id": "brown_leather-roughness", + "name": "Brown Leather roughness", + "file": "brown_leather/roughness.webp", + "material": "brown_leather", + "map": "roughness", + "category": "fabric", + "tags": [ + "pbr", + "1k", + "roughness", + "material:brown_leather", + "seamless", + "fabric", + "leather", + "brown", + "chair", + "seat", + "upholstery", + "vintage", + "by:Rob Tuytel" + ], + "bytes": 286170, + "source_page": "https://polyhaven.com/a/brown_leather", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/brown_leather" + ] + }, + { + "id": "asphalt_02-colour", + "name": "Asphalt 02 colour", + "file": "asphalt_02/colour.webp", + "material": "asphalt_02", + "map": "colour", + "category": "terrain", + "tags": [ + "pbr", + "1k", + "colour", + "material:asphalt_02", + "seamless", + "terrain", + "road", + "man made", + "outdoor", + "floor", + "asphalt", + "cracked", + "by:Rob Tuytel" + ], + "bytes": 296520, + "source_page": "https://polyhaven.com/a/asphalt_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/asphalt_02" + ] + }, + { + "id": "asphalt_02-normal", + "name": "Asphalt 02 normal", + "file": "asphalt_02/normal.webp", + "material": "asphalt_02", + "map": "normal", + "category": "terrain", + "tags": [ + "pbr", + "1k", + "normal", + "material:asphalt_02", + "seamless", + "terrain", + "road", + "man made", + "outdoor", + "floor", + "asphalt", + "cracked", + "by:Rob Tuytel" + ], + "bytes": 248682, + "source_page": "https://polyhaven.com/a/asphalt_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/asphalt_02" + ] + }, + { + "id": "asphalt_02-roughness", + "name": "Asphalt 02 roughness", + "file": "asphalt_02/roughness.webp", + "material": "asphalt_02", + "map": "roughness", + "category": "terrain", + "tags": [ + "pbr", + "1k", + "roughness", + "material:asphalt_02", + "seamless", + "terrain", + "road", + "man made", + "outdoor", + "floor", + "asphalt", + "cracked", + "by:Rob Tuytel" + ], + "bytes": 164514, + "source_page": "https://polyhaven.com/a/asphalt_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/asphalt_02" + ] + }, + { + "id": "forrest_ground_01-colour", + "name": "Forest Ground 01 colour", + "file": "forrest_ground_01/colour.webp", + "material": "forrest_ground_01", + "map": "colour", + "category": "terrain", + "tags": [ + "pbr", + "1k", + "colour", + "material:forrest_ground_01", + "seamless", + "terrain", + "outdoor", + "natural", + "grass", + "twigs", + "forest", + "leaves", + "by:Rob Tuytel" + ], + "bytes": 208588, + "source_page": "https://polyhaven.com/a/forrest_ground_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/forrest_ground_01" + ] + }, + { + "id": "forrest_ground_01-normal", + "name": "Forest Ground 01 normal", + "file": "forrest_ground_01/normal.webp", + "material": "forrest_ground_01", + "map": "normal", + "category": "terrain", + "tags": [ + "pbr", + "1k", + "normal", + "material:forrest_ground_01", + "seamless", + "terrain", + "outdoor", + "natural", + "grass", + "twigs", + "forest", + "leaves", + "by:Rob Tuytel" + ], + "bytes": 341056, + "source_page": "https://polyhaven.com/a/forrest_ground_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/forrest_ground_01" + ] + }, + { + "id": "forrest_ground_01-roughness", + "name": "Forest Ground 01 roughness", + "file": "forrest_ground_01/roughness.webp", + "material": "forrest_ground_01", + "map": "roughness", + "category": "terrain", + "tags": [ + "pbr", + "1k", + "roughness", + "material:forrest_ground_01", + "seamless", + "terrain", + "outdoor", + "natural", + "grass", + "twigs", + "forest", + "leaves", + "by:Rob Tuytel" + ], + "bytes": 32808, + "source_page": "https://polyhaven.com/a/forrest_ground_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/forrest_ground_01" + ] + }, + { + "id": "grass_path_2-colour", + "name": "Grass Path 2 colour", + "file": "grass_path_2/colour.webp", + "material": "grass_path_2", + "map": "colour", + "category": "terrain", + "tags": [ + "pbr", + "1k", + "colour", + "material:grass_path_2", + "seamless", + "terrain", + "natural", + "outdoor", + "grass", + "pathway", + "path", + "ground", + "by:Rob Tuytel" + ], + "bytes": 202746, + "source_page": "https://polyhaven.com/a/grass_path_2", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/grass_path_2" + ] + }, + { + "id": "grass_path_2-normal", + "name": "Grass Path 2 normal", + "file": "grass_path_2/normal.webp", + "material": "grass_path_2", + "map": "normal", + "category": "terrain", + "tags": [ + "pbr", + "1k", + "normal", + "material:grass_path_2", + "seamless", + "terrain", + "natural", + "outdoor", + "grass", + "pathway", + "path", + "ground", + "by:Rob Tuytel" + ], + "bytes": 157550, + "source_page": "https://polyhaven.com/a/grass_path_2", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/grass_path_2" + ] + }, + { + "id": "grass_path_2-roughness", + "name": "Grass Path 2 roughness", + "file": "grass_path_2/roughness.webp", + "material": "grass_path_2", + "map": "roughness", + "category": "terrain", + "tags": [ + "pbr", + "1k", + "roughness", + "material:grass_path_2", + "seamless", + "terrain", + "natural", + "outdoor", + "grass", + "pathway", + "path", + "ground", + "by:Rob Tuytel" + ], + "bytes": 49768, + "source_page": "https://polyhaven.com/a/grass_path_2", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/grass_path_2" + ] + }, + { + "id": "coast_sand_01-colour", + "name": "Coast Sand 01 colour", + "file": "coast_sand_01/colour.webp", + "material": "coast_sand_01", + "map": "colour", + "category": "outdoor", + "tags": [ + "pbr", + "1k", + "colour", + "material:coast_sand_01", + "seamless", + "outdoor", + "terrain", + "sand", + "natural", + "aerial", + "beach", + "costal", + "by:Rob Tuytel" + ], + "bytes": 180536, + "source_page": "https://polyhaven.com/a/coast_sand_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/coast_sand_01" + ] + }, + { + "id": "coast_sand_01-normal", + "name": "Coast Sand 01 normal", + "file": "coast_sand_01/normal.webp", + "material": "coast_sand_01", + "map": "normal", + "category": "outdoor", + "tags": [ + "pbr", + "1k", + "normal", + "material:coast_sand_01", + "seamless", + "outdoor", + "terrain", + "sand", + "natural", + "aerial", + "beach", + "costal", + "by:Rob Tuytel" + ], + "bytes": 200286, + "source_page": "https://polyhaven.com/a/coast_sand_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/coast_sand_01" + ] + }, + { + "id": "coast_sand_01-roughness", + "name": "Coast Sand 01 roughness", + "file": "coast_sand_01/roughness.webp", + "material": "coast_sand_01", + "map": "roughness", + "category": "outdoor", + "tags": [ + "pbr", + "1k", + "roughness", + "material:coast_sand_01", + "seamless", + "outdoor", + "terrain", + "sand", + "natural", + "aerial", + "beach", + "costal", + "by:Rob Tuytel" + ], + "bytes": 4356, + "source_page": "https://polyhaven.com/a/coast_sand_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/coast_sand_01" + ] + }, + { + "id": "rock_surface-colour", + "name": "Rock Surface colour", + "file": "rock_surface/colour.webp", + "material": "rock_surface", + "map": "colour", + "category": "natural", + "tags": [ + "pbr", + "1k", + "colour", + "material:rock_surface", + "seamless", + "natural", + "rock", + "rough", + "weathered", + "discolored", + "dirty", + "stone", + "by:Amal Kumar" + ], + "bytes": 122286, + "source_page": "https://polyhaven.com/a/rock_surface", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/rock_surface" + ] + }, + { + "id": "rock_surface-normal", + "name": "Rock Surface normal", + "file": "rock_surface/normal.webp", + "material": "rock_surface", + "map": "normal", + "category": "natural", + "tags": [ + "pbr", + "1k", + "normal", + "material:rock_surface", + "seamless", + "natural", + "rock", + "rough", + "weathered", + "discolored", + "dirty", + "stone", + "by:Amal Kumar" + ], + "bytes": 210120, + "source_page": "https://polyhaven.com/a/rock_surface", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/rock_surface" + ] + }, + { + "id": "rock_surface-roughness", + "name": "Rock Surface roughness", + "file": "rock_surface/roughness.webp", + "material": "rock_surface", + "map": "roughness", + "category": "natural", + "tags": [ + "pbr", + "1k", + "roughness", + "material:rock_surface", + "seamless", + "natural", + "rock", + "rough", + "weathered", + "discolored", + "dirty", + "stone", + "by:Amal Kumar" + ], + "bytes": 47820, + "source_page": "https://polyhaven.com/a/rock_surface", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/rock_surface" + ] + }, + { + "id": "marble_01-colour", + "name": "Marble 01 colour", + "file": "marble_01/colour.webp", + "material": "marble_01", + "map": "colour", + "category": "floor", + "tags": [ + "pbr", + "1k", + "colour", + "material:marble_01", + "seamless", + "floor", + "man made", + "indoor", + "clean", + "wall", + "marble", + "smooth", + "by:Rob Tuytel" + ], + "bytes": 28868, + "source_page": "https://polyhaven.com/a/marble_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/marble_01" + ] + }, + { + "id": "marble_01-normal", + "name": "Marble 01 normal", + "file": "marble_01/normal.webp", + "material": "marble_01", + "map": "normal", + "category": "floor", + "tags": [ + "pbr", + "1k", + "normal", + "material:marble_01", + "seamless", + "floor", + "man made", + "indoor", + "clean", + "wall", + "marble", + "smooth", + "by:Rob Tuytel" + ], + "bytes": 3898, + "source_page": "https://polyhaven.com/a/marble_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/marble_01" + ] + }, + { + "id": "marble_01-roughness", + "name": "Marble 01 roughness", + "file": "marble_01/roughness.webp", + "material": "marble_01", + "map": "roughness", + "category": "floor", + "tags": [ + "pbr", + "1k", + "roughness", + "material:marble_01", + "seamless", + "floor", + "man made", + "indoor", + "clean", + "wall", + "marble", + "smooth", + "by:Rob Tuytel" + ], + "bytes": 7708, + "source_page": "https://polyhaven.com/a/marble_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/marble_01" + ] + }, + { + "id": "cobblestone_floor_001-colour", + "name": "Cobblestone Floor 001 colour", + "file": "cobblestone_floor_001/colour.webp", + "material": "cobblestone_floor_001", + "map": "colour", + "category": "road", + "tags": [ + "pbr", + "1k", + "colour", + "material:cobblestone_floor_001", + "seamless", + "road", + "man made", + "outdoor", + "dirty", + "floor", + "cobblestone", + "mud", + "by:Rob Tuytel" + ], + "bytes": 150670, + "source_page": "https://polyhaven.com/a/cobblestone_floor_001", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/cobblestone_floor_001" + ] + }, + { + "id": "cobblestone_floor_001-normal", + "name": "Cobblestone Floor 001 normal", + "file": "cobblestone_floor_001/normal.webp", + "material": "cobblestone_floor_001", + "map": "normal", + "category": "road", + "tags": [ + "pbr", + "1k", + "normal", + "material:cobblestone_floor_001", + "seamless", + "road", + "man made", + "outdoor", + "dirty", + "floor", + "cobblestone", + "mud", + "by:Rob Tuytel" + ], + "bytes": 174026, + "source_page": "https://polyhaven.com/a/cobblestone_floor_001", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/cobblestone_floor_001" + ] + }, + { + "id": "cobblestone_floor_001-roughness", + "name": "Cobblestone Floor 001 roughness", + "file": "cobblestone_floor_001/roughness.webp", + "material": "cobblestone_floor_001", + "map": "roughness", + "category": "road", + "tags": [ + "pbr", + "1k", + "roughness", + "material:cobblestone_floor_001", + "seamless", + "road", + "man made", + "outdoor", + "dirty", + "floor", + "cobblestone", + "mud", + "by:Rob Tuytel" + ], + "bytes": 77122, + "source_page": "https://polyhaven.com/a/cobblestone_floor_001", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/cobblestone_floor_001" + ] + }, + { + "id": "painted_metal_shutter-colour", + "name": "Painted Metal Shutter colour", + "file": "painted_metal_shutter/colour.webp", + "material": "painted_metal_shutter", + "map": "colour", + "category": "man made", + "tags": [ + "pbr", + "1k", + "colour", + "material:painted_metal_shutter", + "seamless", + "man made", + "metal", + "weathered", + "worn", + "dirty", + "stained", + "scratched", + "by:Dario Barresi", + "by:Rico Cilliers", + "by:Charlotte Baglioni" + ], + "bytes": 42732, + "source_page": "https://polyhaven.com/a/painted_metal_shutter", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/painted_metal_shutter" + ] + }, + { + "id": "painted_metal_shutter-normal", + "name": "Painted Metal Shutter normal", + "file": "painted_metal_shutter/normal.webp", + "material": "painted_metal_shutter", + "map": "normal", + "category": "man made", + "tags": [ + "pbr", + "1k", + "normal", + "material:painted_metal_shutter", + "seamless", + "man made", + "metal", + "weathered", + "worn", + "dirty", + "stained", + "scratched", + "by:Dario Barresi", + "by:Rico Cilliers", + "by:Charlotte Baglioni" + ], + "bytes": 33230, + "source_page": "https://polyhaven.com/a/painted_metal_shutter", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/painted_metal_shutter" + ] + }, + { + "id": "painted_metal_shutter-roughness", + "name": "Painted Metal Shutter roughness", + "file": "painted_metal_shutter/roughness.webp", + "material": "painted_metal_shutter", + "map": "roughness", + "category": "man made", + "tags": [ + "pbr", + "1k", + "roughness", + "material:painted_metal_shutter", + "seamless", + "man made", + "metal", + "weathered", + "worn", + "dirty", + "stained", + "scratched", + "by:Dario Barresi", + "by:Rico Cilliers", + "by:Charlotte Baglioni" + ], + "bytes": 24606, + "source_page": "https://polyhaven.com/a/painted_metal_shutter", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/painted_metal_shutter" + ] + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/polyhaven-textures/painted_metal_shutter/colour.webp b/assets/starter/2d/polyhaven-textures/painted_metal_shutter/colour.webp new file mode 100644 index 0000000..fbf8385 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/painted_metal_shutter/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/painted_metal_shutter/normal.webp b/assets/starter/2d/polyhaven-textures/painted_metal_shutter/normal.webp new file mode 100644 index 0000000..399b91b Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/painted_metal_shutter/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/painted_metal_shutter/roughness.webp b/assets/starter/2d/polyhaven-textures/painted_metal_shutter/roughness.webp new file mode 100644 index 0000000..8079998 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/painted_metal_shutter/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/red_brick_03/colour.webp b/assets/starter/2d/polyhaven-textures/red_brick_03/colour.webp new file mode 100644 index 0000000..1b40109 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/red_brick_03/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/red_brick_03/normal.webp b/assets/starter/2d/polyhaven-textures/red_brick_03/normal.webp new file mode 100644 index 0000000..9529692 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/red_brick_03/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/red_brick_03/roughness.webp b/assets/starter/2d/polyhaven-textures/red_brick_03/roughness.webp new file mode 100644 index 0000000..73a35c2 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/red_brick_03/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/rock_surface/colour.webp b/assets/starter/2d/polyhaven-textures/rock_surface/colour.webp new file mode 100644 index 0000000..3342e2b Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/rock_surface/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/rock_surface/normal.webp b/assets/starter/2d/polyhaven-textures/rock_surface/normal.webp new file mode 100644 index 0000000..0db7a49 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/rock_surface/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/rock_surface/roughness.webp b/assets/starter/2d/polyhaven-textures/rock_surface/roughness.webp new file mode 100644 index 0000000..a5fe856 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/rock_surface/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/rust_coarse_01/colour.webp b/assets/starter/2d/polyhaven-textures/rust_coarse_01/colour.webp new file mode 100644 index 0000000..122c09f Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/rust_coarse_01/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/rust_coarse_01/normal.webp b/assets/starter/2d/polyhaven-textures/rust_coarse_01/normal.webp new file mode 100644 index 0000000..63a95ba Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/rust_coarse_01/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/rust_coarse_01/roughness.webp b/assets/starter/2d/polyhaven-textures/rust_coarse_01/roughness.webp new file mode 100644 index 0000000..ca06e08 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/rust_coarse_01/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/weathered_planks/colour.webp b/assets/starter/2d/polyhaven-textures/weathered_planks/colour.webp new file mode 100644 index 0000000..edd757a Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/weathered_planks/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/weathered_planks/normal.webp b/assets/starter/2d/polyhaven-textures/weathered_planks/normal.webp new file mode 100644 index 0000000..6d0746a Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/weathered_planks/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/weathered_planks/roughness.webp b/assets/starter/2d/polyhaven-textures/weathered_planks/roughness.webp new file mode 100644 index 0000000..412b894 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/weathered_planks/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/white_plaster_02/colour.webp b/assets/starter/2d/polyhaven-textures/white_plaster_02/colour.webp new file mode 100644 index 0000000..1bd40df Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/white_plaster_02/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/white_plaster_02/normal.webp b/assets/starter/2d/polyhaven-textures/white_plaster_02/normal.webp new file mode 100644 index 0000000..26859da Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/white_plaster_02/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/white_plaster_02/roughness.webp b/assets/starter/2d/polyhaven-textures/white_plaster_02/roughness.webp new file mode 100644 index 0000000..1f243ca Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/white_plaster_02/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/wood_floor/colour.webp b/assets/starter/2d/polyhaven-textures/wood_floor/colour.webp new file mode 100644 index 0000000..54e8a04 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/wood_floor/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/wood_floor/normal.webp b/assets/starter/2d/polyhaven-textures/wood_floor/normal.webp new file mode 100644 index 0000000..e9aa702 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/wood_floor/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/wood_floor/roughness.webp b/assets/starter/2d/polyhaven-textures/wood_floor/roughness.webp new file mode 100644 index 0000000..fd955b5 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/wood_floor/roughness.webp differ diff --git a/assets/starter/2d/polyhaven-textures/wood_floor_worn/colour.webp b/assets/starter/2d/polyhaven-textures/wood_floor_worn/colour.webp new file mode 100644 index 0000000..9931a4e Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/wood_floor_worn/colour.webp differ diff --git a/assets/starter/2d/polyhaven-textures/wood_floor_worn/normal.webp b/assets/starter/2d/polyhaven-textures/wood_floor_worn/normal.webp new file mode 100644 index 0000000..b39cb9f Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/wood_floor_worn/normal.webp differ diff --git a/assets/starter/2d/polyhaven-textures/wood_floor_worn/roughness.webp b/assets/starter/2d/polyhaven-textures/wood_floor_worn/roughness.webp new file mode 100644 index 0000000..3d84381 Binary files /dev/null and b/assets/starter/2d/polyhaven-textures/wood_floor_worn/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/LICENSE.txt b/assets/starter/2d/textures-ambientcg/LICENSE.txt new file mode 100644 index 0000000..79d6ef6 --- /dev/null +++ b/assets/starter/2d/textures-ambientcg/LICENSE.txt @@ -0,0 +1,35 @@ +Licence statement fetched from https://ambientcg.com/license (redirects to https://docs.ambientcg.com/license/) on 2026-11-29. Page text, markup and navigation removed. +Each item's own page is linked in pack.json as source_page; the item pages repeat that all assets are CC0. + +License information +¶ +All ambientCG assets are provided under the +Creative Commons CC0 1.0 Universal License +. +This applies to the downloadable asset files and the material preview renders shown for each asset on the site. +License Details +¶ +The Creative Commons CC0 license gives you near limitless freedom to use the materials, models and other assets: +Creative Commons CC0 License +You can copy, modify, distribute and perform the assets, even for commercial purposes, all without asking permission. +You can include the raw files in your project, for example a video game. +You can read the full text on the +Creative Commons website +. There you can also read the full license in many languages by using the dropdown menu in the top right corner. +Giving credit +¶ +You don't need to give credit but I would of course appreciate it, if you did it anyways. You can do so using this text: +Created using <asset name> from ambientCG.com, +licensed under the Creative Commons CC0 1.0 Universal License. +Tip +You can use the short and neat URLs to link to assets on ambientCG, like this: +https://ambientcg.com/a/<id> +, for example +https://ambientcg.com/a/PavingStones036 +. +Previous +Home +Next +Asset Types +Made with +Material for MkDocs diff --git a/assets/starter/2d/textures-ambientcg/carpet/carpet004/color.webp b/assets/starter/2d/textures-ambientcg/carpet/carpet004/color.webp new file mode 100644 index 0000000..851bdc0 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/carpet/carpet004/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/carpet/carpet004/normal.webp b/assets/starter/2d/textures-ambientcg/carpet/carpet004/normal.webp new file mode 100644 index 0000000..ece3850 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/carpet/carpet004/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/carpet/carpet004/roughness.webp b/assets/starter/2d/textures-ambientcg/carpet/carpet004/roughness.webp new file mode 100644 index 0000000..4372fcb Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/carpet/carpet004/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/carpet/carpet012/color.webp b/assets/starter/2d/textures-ambientcg/carpet/carpet012/color.webp new file mode 100644 index 0000000..1f6e465 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/carpet/carpet012/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/carpet/carpet012/normal.webp b/assets/starter/2d/textures-ambientcg/carpet/carpet012/normal.webp new file mode 100644 index 0000000..157aad6 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/carpet/carpet012/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/carpet/carpet012/roughness.webp b/assets/starter/2d/textures-ambientcg/carpet/carpet012/roughness.webp new file mode 100644 index 0000000..4f726f9 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/carpet/carpet012/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/asphalt004/color.webp b/assets/starter/2d/textures-ambientcg/concrete/asphalt004/color.webp new file mode 100644 index 0000000..d58bb36 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/asphalt004/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/asphalt004/normal.webp b/assets/starter/2d/textures-ambientcg/concrete/asphalt004/normal.webp new file mode 100644 index 0000000..f15af2a Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/asphalt004/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/asphalt004/roughness.webp b/assets/starter/2d/textures-ambientcg/concrete/asphalt004/roughness.webp new file mode 100644 index 0000000..0e54bd5 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/asphalt004/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/concrete007/color.webp b/assets/starter/2d/textures-ambientcg/concrete/concrete007/color.webp new file mode 100644 index 0000000..b295042 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/concrete007/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/concrete007/normal.webp b/assets/starter/2d/textures-ambientcg/concrete/concrete007/normal.webp new file mode 100644 index 0000000..2280b2e Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/concrete007/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/concrete007/roughness.webp b/assets/starter/2d/textures-ambientcg/concrete/concrete007/roughness.webp new file mode 100644 index 0000000..f94bb89 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/concrete007/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/concrete019/color.webp b/assets/starter/2d/textures-ambientcg/concrete/concrete019/color.webp new file mode 100644 index 0000000..6a85f54 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/concrete019/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/concrete019/normal.webp b/assets/starter/2d/textures-ambientcg/concrete/concrete019/normal.webp new file mode 100644 index 0000000..27938f5 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/concrete019/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/concrete019/roughness.webp b/assets/starter/2d/textures-ambientcg/concrete/concrete019/roughness.webp new file mode 100644 index 0000000..5b8de44 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/concrete019/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/concrete034/color.webp b/assets/starter/2d/textures-ambientcg/concrete/concrete034/color.webp new file mode 100644 index 0000000..6a7f0db Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/concrete034/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/concrete034/normal.webp b/assets/starter/2d/textures-ambientcg/concrete/concrete034/normal.webp new file mode 100644 index 0000000..611bc63 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/concrete034/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/concrete034/roughness.webp b/assets/starter/2d/textures-ambientcg/concrete/concrete034/roughness.webp new file mode 100644 index 0000000..f825444 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/concrete034/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/plaster001/color.webp b/assets/starter/2d/textures-ambientcg/concrete/plaster001/color.webp new file mode 100644 index 0000000..2aa43c0 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/plaster001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/plaster001/normal.webp b/assets/starter/2d/textures-ambientcg/concrete/plaster001/normal.webp new file mode 100644 index 0000000..1c3a3f1 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/plaster001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/concrete/plaster001/roughness.webp b/assets/starter/2d/textures-ambientcg/concrete/plaster001/roughness.webp new file mode 100644 index 0000000..a8baeff Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/concrete/plaster001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/carpet009/color.webp b/assets/starter/2d/textures-ambientcg/fabric/carpet009/color.webp new file mode 100644 index 0000000..ea2eaf1 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/carpet009/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/carpet009/normal.webp b/assets/starter/2d/textures-ambientcg/fabric/carpet009/normal.webp new file mode 100644 index 0000000..cb4c359 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/carpet009/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/carpet009/roughness.webp b/assets/starter/2d/textures-ambientcg/fabric/carpet009/roughness.webp new file mode 100644 index 0000000..02bf5bd Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/carpet009/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric026/color.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric026/color.webp new file mode 100644 index 0000000..9500d74 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric026/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric026/normal.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric026/normal.webp new file mode 100644 index 0000000..159ddf9 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric026/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric026/roughness.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric026/roughness.webp new file mode 100644 index 0000000..ae4d0e1 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric026/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric030/color.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric030/color.webp new file mode 100644 index 0000000..ce24967 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric030/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric030/normal.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric030/normal.webp new file mode 100644 index 0000000..aaacb18 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric030/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric030/roughness.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric030/roughness.webp new file mode 100644 index 0000000..2c5efad Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric030/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric045/color.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric045/color.webp new file mode 100644 index 0000000..8dd0e59 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric045/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric045/normal.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric045/normal.webp new file mode 100644 index 0000000..a8a435a Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric045/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric045/roughness.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric045/roughness.webp new file mode 100644 index 0000000..0361190 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric045/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric062/color.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric062/color.webp new file mode 100644 index 0000000..1174f2f Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric062/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric062/normal.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric062/normal.webp new file mode 100644 index 0000000..26fc78f Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric062/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/fabric062/roughness.webp b/assets/starter/2d/textures-ambientcg/fabric/fabric062/roughness.webp new file mode 100644 index 0000000..595b38f Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/fabric062/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/leather011/color.webp b/assets/starter/2d/textures-ambientcg/fabric/leather011/color.webp new file mode 100644 index 0000000..55ec644 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/leather011/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/leather011/normal.webp b/assets/starter/2d/textures-ambientcg/fabric/leather011/normal.webp new file mode 100644 index 0000000..465478a Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/leather011/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/leather011/roughness.webp b/assets/starter/2d/textures-ambientcg/fabric/leather011/roughness.webp new file mode 100644 index 0000000..ac1f399 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/leather011/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/wicker001/color.webp b/assets/starter/2d/textures-ambientcg/fabric/wicker001/color.webp new file mode 100644 index 0000000..8bcb7c4 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/wicker001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/wicker001/normal.webp b/assets/starter/2d/textures-ambientcg/fabric/wicker001/normal.webp new file mode 100644 index 0000000..672d534 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/wicker001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/fabric/wicker001/roughness.webp b/assets/starter/2d/textures-ambientcg/fabric/wicker001/roughness.webp new file mode 100644 index 0000000..33f87f7 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/fabric/wicker001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/foam/foam001/color.webp b/assets/starter/2d/textures-ambientcg/foam/foam001/color.webp new file mode 100644 index 0000000..c9ad4b1 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/foam/foam001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/foam/foam001/normal.webp b/assets/starter/2d/textures-ambientcg/foam/foam001/normal.webp new file mode 100644 index 0000000..38596b3 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/foam/foam001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/foam/foam001/roughness.webp b/assets/starter/2d/textures-ambientcg/foam/foam001/roughness.webp new file mode 100644 index 0000000..757fbcd Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/foam/foam001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/grass004/color.webp b/assets/starter/2d/textures-ambientcg/ground/grass004/color.webp new file mode 100644 index 0000000..eb25b8d Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/grass004/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/grass004/normal.webp b/assets/starter/2d/textures-ambientcg/ground/grass004/normal.webp new file mode 100644 index 0000000..768d4a9 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/grass004/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/grass004/roughness.webp b/assets/starter/2d/textures-ambientcg/ground/grass004/roughness.webp new file mode 100644 index 0000000..96f6a91 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/grass004/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/gravel021/color.webp b/assets/starter/2d/textures-ambientcg/ground/gravel021/color.webp new file mode 100644 index 0000000..12dd654 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/gravel021/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/gravel021/normal.webp b/assets/starter/2d/textures-ambientcg/ground/gravel021/normal.webp new file mode 100644 index 0000000..247adc8 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/gravel021/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/gravel021/roughness.webp b/assets/starter/2d/textures-ambientcg/ground/gravel021/roughness.webp new file mode 100644 index 0000000..70eac8b Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/gravel021/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/ground037/color.webp b/assets/starter/2d/textures-ambientcg/ground/ground037/color.webp new file mode 100644 index 0000000..acd3c80 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/ground037/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/ground037/normal.webp b/assets/starter/2d/textures-ambientcg/ground/ground037/normal.webp new file mode 100644 index 0000000..7c7eb06 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/ground037/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/ground037/roughness.webp b/assets/starter/2d/textures-ambientcg/ground/ground037/roughness.webp new file mode 100644 index 0000000..6359da0 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/ground037/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/moss001/color.webp b/assets/starter/2d/textures-ambientcg/ground/moss001/color.webp new file mode 100644 index 0000000..dd2f9f6 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/moss001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/moss001/normal.webp b/assets/starter/2d/textures-ambientcg/ground/moss001/normal.webp new file mode 100644 index 0000000..2c13ef6 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/moss001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/moss001/roughness.webp b/assets/starter/2d/textures-ambientcg/ground/moss001/roughness.webp new file mode 100644 index 0000000..0cde25e Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/moss001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/snow006/color.webp b/assets/starter/2d/textures-ambientcg/ground/snow006/color.webp new file mode 100644 index 0000000..4baae74 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/snow006/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/snow006/normal.webp b/assets/starter/2d/textures-ambientcg/ground/snow006/normal.webp new file mode 100644 index 0000000..af5441c Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/snow006/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/ground/snow006/roughness.webp b/assets/starter/2d/textures-ambientcg/ground/snow006/roughness.webp new file mode 100644 index 0000000..cf734b9 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/ground/snow006/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/leather/leather026/color.webp b/assets/starter/2d/textures-ambientcg/leather/leather026/color.webp new file mode 100644 index 0000000..f103bba Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/leather/leather026/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/leather/leather026/normal.webp b/assets/starter/2d/textures-ambientcg/leather/leather026/normal.webp new file mode 100644 index 0000000..e401a54 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/leather/leather026/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/leather/leather026/roughness.webp b/assets/starter/2d/textures-ambientcg/leather/leather026/roughness.webp new file mode 100644 index 0000000..a22607d Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/leather/leather026/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/marble/marble003/color.webp b/assets/starter/2d/textures-ambientcg/marble/marble003/color.webp new file mode 100644 index 0000000..fd29c51 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/marble/marble003/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/marble/marble003/normal.webp b/assets/starter/2d/textures-ambientcg/marble/marble003/normal.webp new file mode 100644 index 0000000..ab1dd9f Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/marble/marble003/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/marble/marble003/roughness.webp b/assets/starter/2d/textures-ambientcg/marble/marble003/roughness.webp new file mode 100644 index 0000000..bf53bd8 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/marble/marble003/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/marble/marble012/color.webp b/assets/starter/2d/textures-ambientcg/marble/marble012/color.webp new file mode 100644 index 0000000..49af999 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/marble/marble012/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/marble/marble012/normal.webp b/assets/starter/2d/textures-ambientcg/marble/marble012/normal.webp new file mode 100644 index 0000000..db86471 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/marble/marble012/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/marble/marble012/roughness.webp b/assets/starter/2d/textures-ambientcg/marble/marble012/roughness.webp new file mode 100644 index 0000000..e0fe5fc Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/marble/marble012/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/corrugatedsteel005/color.webp b/assets/starter/2d/textures-ambientcg/metal/corrugatedsteel005/color.webp new file mode 100644 index 0000000..a210367 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/corrugatedsteel005/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/corrugatedsteel005/normal.webp b/assets/starter/2d/textures-ambientcg/metal/corrugatedsteel005/normal.webp new file mode 100644 index 0000000..ba73f9d Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/corrugatedsteel005/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/corrugatedsteel005/roughness.webp b/assets/starter/2d/textures-ambientcg/metal/corrugatedsteel005/roughness.webp new file mode 100644 index 0000000..c8c0a55 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/corrugatedsteel005/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/diamondplate001/color.webp b/assets/starter/2d/textures-ambientcg/metal/diamondplate001/color.webp new file mode 100644 index 0000000..a2b3e84 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/diamondplate001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/diamondplate001/normal.webp b/assets/starter/2d/textures-ambientcg/metal/diamondplate001/normal.webp new file mode 100644 index 0000000..5da7410 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/diamondplate001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/diamondplate001/roughness.webp b/assets/starter/2d/textures-ambientcg/metal/diamondplate001/roughness.webp new file mode 100644 index 0000000..1718ad5 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/diamondplate001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/grate002/color.webp b/assets/starter/2d/textures-ambientcg/metal/grate002/color.webp new file mode 100644 index 0000000..488c431 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/grate002/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/grate002/normal.webp b/assets/starter/2d/textures-ambientcg/metal/grate002/normal.webp new file mode 100644 index 0000000..e0f63ee Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/grate002/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/grate002/roughness.webp b/assets/starter/2d/textures-ambientcg/metal/grate002/roughness.webp new file mode 100644 index 0000000..cfb3508 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/grate002/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/metal032/color.webp b/assets/starter/2d/textures-ambientcg/metal/metal032/color.webp new file mode 100644 index 0000000..bfc2ad5 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/metal032/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/metal032/normal.webp b/assets/starter/2d/textures-ambientcg/metal/metal032/normal.webp new file mode 100644 index 0000000..00e81ea Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/metal032/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/metal032/roughness.webp b/assets/starter/2d/textures-ambientcg/metal/metal032/roughness.webp new file mode 100644 index 0000000..87dde1b Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/metal032/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/metal038/color.webp b/assets/starter/2d/textures-ambientcg/metal/metal038/color.webp new file mode 100644 index 0000000..b105172 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/metal038/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/metal038/normal.webp b/assets/starter/2d/textures-ambientcg/metal/metal038/normal.webp new file mode 100644 index 0000000..ca9e843 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/metal038/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/metal038/roughness.webp b/assets/starter/2d/textures-ambientcg/metal/metal038/roughness.webp new file mode 100644 index 0000000..4ecd3cb Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/metal038/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/metal055a/color.webp b/assets/starter/2d/textures-ambientcg/metal/metal055a/color.webp new file mode 100644 index 0000000..fda375c Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/metal055a/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/metal055a/normal.webp b/assets/starter/2d/textures-ambientcg/metal/metal055a/normal.webp new file mode 100644 index 0000000..48ff8a5 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/metal055a/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/metal055a/roughness.webp b/assets/starter/2d/textures-ambientcg/metal/metal055a/roughness.webp new file mode 100644 index 0000000..69c2a49 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/metal055a/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/paintedmetal007/color.webp b/assets/starter/2d/textures-ambientcg/metal/paintedmetal007/color.webp new file mode 100644 index 0000000..d9ee778 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/paintedmetal007/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/paintedmetal007/normal.webp b/assets/starter/2d/textures-ambientcg/metal/paintedmetal007/normal.webp new file mode 100644 index 0000000..1778736 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/paintedmetal007/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/metal/paintedmetal007/roughness.webp b/assets/starter/2d/textures-ambientcg/metal/paintedmetal007/roughness.webp new file mode 100644 index 0000000..d58d302 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/metal/paintedmetal007/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/pack.json b/assets/starter/2d/textures-ambientcg/pack.json new file mode 100644 index 0000000..70a7f55 --- /dev/null +++ b/assets/starter/2d/textures-ambientcg/pack.json @@ -0,0 +1,3523 @@ +{ + "id": "textures-ambientcg", + "name": "PBR textures (ambientCG)", + "kind": "texture", + "licence": "CC0-1.0", + "author": "ambientCG (ambientcg.com) and its contributors", + "source_url": "https://ambientcg.com", + "source_commit_or_version": "ambientCG API v2 (full_json), 1K-JPG downloads via /get?file=<AssetID>_1K-JPG.zip, retrieved 2026-11-29", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://docs.ambientcg.com/license/ (site-wide licence page, reached from https://ambientcg.com/license; states all ambientCG assets are CC0 1.0 Universal, fetched 2026-11-29)", + "https://ambientcg.com/view?id=<AssetID> (each item's own page, listed per item as source_page; its FAQ states all assets are released under CC0; the API record https://ambientcg.com/api/v2/full_json?id=<AssetID>&include=downloadData confirmed each asset exists as a Material with a 1K-JPG download; fetched 2026-11-29)" + ], + "items": [ + { + "id": "wood049-color", + "name": "Wood049 Color", + "file": "wood/wood049/color.webp", + "category": "wood", + "tags": [ + "brown", + "furniture", + "grain", + "horizontal", + "interior", + "modern", + "color", + "material:wood049", + "seamless" + ], + "bytes": 69512, + "material": "wood049", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Wood049" + }, + { + "id": "wood049-normal", + "name": "Wood049 Normal", + "file": "wood/wood049/normal.webp", + "category": "wood", + "tags": [ + "brown", + "furniture", + "grain", + "horizontal", + "interior", + "modern", + "normal", + "material:wood049", + "seamless" + ], + "bytes": 18968, + "material": "wood049", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Wood049" + }, + { + "id": "wood049-roughness", + "name": "Wood049 Roughness", + "file": "wood/wood049/roughness.webp", + "category": "wood", + "tags": [ + "brown", + "furniture", + "grain", + "horizontal", + "interior", + "modern", + "roughness", + "material:wood049", + "seamless" + ], + "bytes": 21016, + "material": "wood049", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Wood049" + }, + { + "id": "wood051-color", + "name": "Wood051 Color", + "file": "wood/wood051/color.webp", + "category": "wood", + "tags": [ + "brown", + "dark", + "elegant", + "espresso", + "flooring", + "furniture", + "color", + "material:wood051", + "seamless" + ], + "bytes": 44100, + "material": "wood051", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Wood051" + }, + { + "id": "wood051-normal", + "name": "Wood051 Normal", + "file": "wood/wood051/normal.webp", + "category": "wood", + "tags": [ + "brown", + "dark", + "elegant", + "espresso", + "flooring", + "furniture", + "normal", + "material:wood051", + "seamless" + ], + "bytes": 21304, + "material": "wood051", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Wood051" + }, + { + "id": "wood051-roughness", + "name": "Wood051 Roughness", + "file": "wood/wood051/roughness.webp", + "category": "wood", + "tags": [ + "brown", + "dark", + "elegant", + "espresso", + "flooring", + "furniture", + "roughness", + "material:wood051", + "seamless" + ], + "bytes": 20686, + "material": "wood051", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Wood051" + }, + { + "id": "woodfloor040-color", + "name": "Woodfloor040 Color", + "file": "wood/woodfloor040/color.webp", + "category": "wood", + "tags": [ + "floor", + "parquet", + "planks", + "wood", + "color", + "material:woodfloor040", + "seamless" + ], + "bytes": 71202, + "material": "woodfloor040", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=WoodFloor040" + }, + { + "id": "woodfloor040-normal", + "name": "Woodfloor040 Normal", + "file": "wood/woodfloor040/normal.webp", + "category": "wood", + "tags": [ + "floor", + "parquet", + "planks", + "wood", + "normal", + "material:woodfloor040", + "seamless" + ], + "bytes": 2752, + "material": "woodfloor040", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=WoodFloor040" + }, + { + "id": "woodfloor040-roughness", + "name": "Woodfloor040 Roughness", + "file": "wood/woodfloor040/roughness.webp", + "category": "wood", + "tags": [ + "floor", + "parquet", + "planks", + "wood", + "roughness", + "material:woodfloor040", + "seamless" + ], + "bytes": 2778, + "material": "woodfloor040", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=WoodFloor040" + }, + { + "id": "planks012-color", + "name": "Planks012 Color", + "file": "wood/planks012/color.webp", + "category": "wood", + "tags": [ + "nailed", + "nails", + "planks", + "rough", + "wood", + "color", + "material:planks012", + "seamless" + ], + "bytes": 74584, + "material": "planks012", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Planks012" + }, + { + "id": "planks012-normal", + "name": "Planks012 Normal", + "file": "wood/planks012/normal.webp", + "category": "wood", + "tags": [ + "nailed", + "nails", + "planks", + "rough", + "wood", + "normal", + "material:planks012", + "seamless" + ], + "bytes": 21894, + "material": "planks012", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Planks012" + }, + { + "id": "planks012-roughness", + "name": "Planks012 Roughness", + "file": "wood/planks012/roughness.webp", + "category": "wood", + "tags": [ + "nailed", + "nails", + "planks", + "rough", + "wood", + "roughness", + "material:planks012", + "seamless" + ], + "bytes": 23570, + "material": "planks012", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Planks012" + }, + { + "id": "bark001-color", + "name": "Bark001 Color", + "file": "wood/bark001/color.webp", + "category": "wood", + "tags": [ + "bark", + "forest", + "tree", + "wood", + "color", + "material:bark001", + "seamless" + ], + "bytes": 80936, + "material": "bark001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Bark001" + }, + { + "id": "bark001-normal", + "name": "Bark001 Normal", + "file": "wood/bark001/normal.webp", + "category": "wood", + "tags": [ + "bark", + "forest", + "tree", + "wood", + "normal", + "material:bark001", + "seamless" + ], + "bytes": 129020, + "material": "bark001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Bark001" + }, + { + "id": "bark001-roughness", + "name": "Bark001 Roughness", + "file": "wood/bark001/roughness.webp", + "category": "wood", + "tags": [ + "bark", + "forest", + "tree", + "wood", + "roughness", + "material:bark001", + "seamless" + ], + "bytes": 59838, + "material": "bark001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Bark001" + }, + { + "id": "metal032-color", + "name": "Metal032 Color", + "file": "metal/metal032/color.webp", + "category": "metal", + "tags": [ + "grey", + "metal", + "smooth", + "color", + "material:metal032", + "seamless" + ], + "bytes": 4658, + "material": "metal032", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Metal032" + }, + { + "id": "metal032-normal", + "name": "Metal032 Normal", + "file": "metal/metal032/normal.webp", + "category": "metal", + "tags": [ + "grey", + "metal", + "smooth", + "normal", + "material:metal032", + "seamless" + ], + "bytes": 550, + "material": "metal032", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Metal032" + }, + { + "id": "metal032-roughness", + "name": "Metal032 Roughness", + "file": "metal/metal032/roughness.webp", + "category": "metal", + "tags": [ + "grey", + "metal", + "smooth", + "roughness", + "material:metal032", + "seamless" + ], + "bytes": 938, + "material": "metal032", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Metal032" + }, + { + "id": "metal038-color", + "name": "Metal038 Color", + "file": "metal/metal038/color.webp", + "category": "metal", + "tags": [ + "metal", + "scratched", + "steel", + "color", + "material:metal038", + "seamless" + ], + "bytes": 18896, + "material": "metal038", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Metal038" + }, + { + "id": "metal038-normal", + "name": "Metal038 Normal", + "file": "metal/metal038/normal.webp", + "category": "metal", + "tags": [ + "metal", + "scratched", + "steel", + "normal", + "material:metal038", + "seamless" + ], + "bytes": 1276, + "material": "metal038", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Metal038" + }, + { + "id": "metal038-roughness", + "name": "Metal038 Roughness", + "file": "metal/metal038/roughness.webp", + "category": "metal", + "tags": [ + "metal", + "scratched", + "steel", + "roughness", + "material:metal038", + "seamless" + ], + "bytes": 4692, + "material": "metal038", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Metal038" + }, + { + "id": "paintedmetal007-color", + "name": "Paintedmetal007 Color", + "file": "metal/paintedmetal007/color.webp", + "category": "metal", + "tags": [ + "blue", + "metal", + "painted", + "rust", + "color", + "material:paintedmetal007", + "seamless" + ], + "bytes": 54944, + "material": "paintedmetal007", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=PaintedMetal007" + }, + { + "id": "paintedmetal007-normal", + "name": "Paintedmetal007 Normal", + "file": "metal/paintedmetal007/normal.webp", + "category": "metal", + "tags": [ + "blue", + "metal", + "painted", + "rust", + "normal", + "material:paintedmetal007", + "seamless" + ], + "bytes": 17214, + "material": "paintedmetal007", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=PaintedMetal007" + }, + { + "id": "paintedmetal007-roughness", + "name": "Paintedmetal007 Roughness", + "file": "metal/paintedmetal007/roughness.webp", + "category": "metal", + "tags": [ + "blue", + "metal", + "painted", + "rust", + "roughness", + "material:paintedmetal007", + "seamless" + ], + "bytes": 21338, + "material": "paintedmetal007", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=PaintedMetal007" + }, + { + "id": "corrugatedsteel005-color", + "name": "Corrugatedsteel005 Color", + "file": "metal/corrugatedsteel005/color.webp", + "category": "metal", + "tags": [ + "bare", + "corrugated", + "metal", + "painted", + "steel", + "color", + "material:corrugatedsteel005", + "seamless" + ], + "bytes": 53956, + "material": "corrugatedsteel005", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=CorrugatedSteel005" + }, + { + "id": "corrugatedsteel005-normal", + "name": "Corrugatedsteel005 Normal", + "file": "metal/corrugatedsteel005/normal.webp", + "category": "metal", + "tags": [ + "bare", + "corrugated", + "metal", + "painted", + "steel", + "normal", + "material:corrugatedsteel005", + "seamless" + ], + "bytes": 4618, + "material": "corrugatedsteel005", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=CorrugatedSteel005" + }, + { + "id": "corrugatedsteel005-roughness", + "name": "Corrugatedsteel005 Roughness", + "file": "metal/corrugatedsteel005/roughness.webp", + "category": "metal", + "tags": [ + "bare", + "corrugated", + "metal", + "painted", + "steel", + "roughness", + "material:corrugatedsteel005", + "seamless" + ], + "bytes": 20310, + "material": "corrugatedsteel005", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=CorrugatedSteel005" + }, + { + "id": "diamondplate001-color", + "name": "Diamondplate001 Color", + "file": "metal/diamondplate001/color.webp", + "category": "metal", + "tags": [ + "diamond", + "floor", + "industrial", + "metal", + "pattern", + "plate", + "color", + "material:diamondplate001", + "seamless" + ], + "bytes": 42210, + "material": "diamondplate001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=DiamondPlate001" + }, + { + "id": "diamondplate001-normal", + "name": "Diamondplate001 Normal", + "file": "metal/diamondplate001/normal.webp", + "category": "metal", + "tags": [ + "diamond", + "floor", + "industrial", + "metal", + "pattern", + "plate", + "normal", + "material:diamondplate001", + "seamless" + ], + "bytes": 21968, + "material": "diamondplate001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=DiamondPlate001" + }, + { + "id": "diamondplate001-roughness", + "name": "Diamondplate001 Roughness", + "file": "metal/diamondplate001/roughness.webp", + "category": "metal", + "tags": [ + "diamond", + "floor", + "industrial", + "metal", + "pattern", + "plate", + "roughness", + "material:diamondplate001", + "seamless" + ], + "bytes": 28658, + "material": "diamondplate001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=DiamondPlate001" + }, + { + "id": "concrete007-color", + "name": "Concrete007 Color", + "file": "concrete/concrete007/color.webp", + "category": "concrete", + "tags": [ + "concrete", + "flat", + "pattern", + "smooth", + "tiles", + "color", + "material:concrete007", + "seamless" + ], + "bytes": 36250, + "material": "concrete007", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Concrete007" + }, + { + "id": "concrete007-normal", + "name": "Concrete007 Normal", + "file": "concrete/concrete007/normal.webp", + "category": "concrete", + "tags": [ + "concrete", + "flat", + "pattern", + "smooth", + "tiles", + "normal", + "material:concrete007", + "seamless" + ], + "bytes": 2910, + "material": "concrete007", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Concrete007" + }, + { + "id": "concrete007-roughness", + "name": "Concrete007 Roughness", + "file": "concrete/concrete007/roughness.webp", + "category": "concrete", + "tags": [ + "concrete", + "flat", + "pattern", + "smooth", + "tiles", + "roughness", + "material:concrete007", + "seamless" + ], + "bytes": 26804, + "material": "concrete007", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Concrete007" + }, + { + "id": "concrete034-color", + "name": "Concrete034 Color", + "file": "concrete/concrete034/color.webp", + "category": "concrete", + "tags": [ + "concrete", + "grey", + "light", + "plaster", + "smooth", + "color", + "material:concrete034", + "seamless" + ], + "bytes": 23438, + "material": "concrete034", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Concrete034" + }, + { + "id": "concrete034-normal", + "name": "Concrete034 Normal", + "file": "concrete/concrete034/normal.webp", + "category": "concrete", + "tags": [ + "concrete", + "grey", + "light", + "plaster", + "smooth", + "normal", + "material:concrete034", + "seamless" + ], + "bytes": 11320, + "material": "concrete034", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Concrete034" + }, + { + "id": "concrete034-roughness", + "name": "Concrete034 Roughness", + "file": "concrete/concrete034/roughness.webp", + "category": "concrete", + "tags": [ + "concrete", + "grey", + "light", + "plaster", + "smooth", + "roughness", + "material:concrete034", + "seamless" + ], + "bytes": 4996, + "material": "concrete034", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Concrete034" + }, + { + "id": "concrete019-color", + "name": "Concrete019 Color", + "file": "concrete/concrete019/color.webp", + "category": "concrete", + "tags": [ + "concrete", + "patches", + "plaster", + "uniform", + "color", + "material:concrete019", + "seamless" + ], + "bytes": 74092, + "material": "concrete019", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Concrete019" + }, + { + "id": "concrete019-normal", + "name": "Concrete019 Normal", + "file": "concrete/concrete019/normal.webp", + "category": "concrete", + "tags": [ + "concrete", + "patches", + "plaster", + "uniform", + "normal", + "material:concrete019", + "seamless" + ], + "bytes": 21072, + "material": "concrete019", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Concrete019" + }, + { + "id": "concrete019-roughness", + "name": "Concrete019 Roughness", + "file": "concrete/concrete019/roughness.webp", + "category": "concrete", + "tags": [ + "concrete", + "patches", + "plaster", + "uniform", + "roughness", + "material:concrete019", + "seamless" + ], + "bytes": 19932, + "material": "concrete019", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Concrete019" + }, + { + "id": "asphalt004-color", + "name": "Asphalt004 Color", + "file": "concrete/asphalt004/color.webp", + "category": "concrete", + "tags": [ + "asphalt", + "grey", + "light", + "rough", + "color", + "material:asphalt004", + "seamless" + ], + "bytes": 68412, + "material": "asphalt004", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Asphalt004" + }, + { + "id": "asphalt004-normal", + "name": "Asphalt004 Normal", + "file": "concrete/asphalt004/normal.webp", + "category": "concrete", + "tags": [ + "asphalt", + "grey", + "light", + "rough", + "normal", + "material:asphalt004", + "seamless" + ], + "bytes": 73890, + "material": "asphalt004", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Asphalt004" + }, + { + "id": "asphalt004-roughness", + "name": "Asphalt004 Roughness", + "file": "concrete/asphalt004/roughness.webp", + "category": "concrete", + "tags": [ + "asphalt", + "grey", + "light", + "rough", + "roughness", + "material:asphalt004", + "seamless" + ], + "bytes": 21786, + "material": "asphalt004", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Asphalt004" + }, + { + "id": "plaster001-color", + "name": "Plaster001 Color", + "file": "concrete/plaster001/color.webp", + "category": "concrete", + "tags": [ + "clean", + "matte", + "modern", + "outdoor", + "plaster", + "rough", + "color", + "material:plaster001", + "seamless" + ], + "bytes": 46400, + "material": "plaster001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Plaster001" + }, + { + "id": "plaster001-normal", + "name": "Plaster001 Normal", + "file": "concrete/plaster001/normal.webp", + "category": "concrete", + "tags": [ + "clean", + "matte", + "modern", + "outdoor", + "plaster", + "rough", + "normal", + "material:plaster001", + "seamless" + ], + "bytes": 19226, + "material": "plaster001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Plaster001" + }, + { + "id": "plaster001-roughness", + "name": "Plaster001 Roughness", + "file": "concrete/plaster001/roughness.webp", + "category": "concrete", + "tags": [ + "clean", + "matte", + "modern", + "outdoor", + "plaster", + "rough", + "roughness", + "material:plaster001", + "seamless" + ], + "bytes": 3884, + "material": "plaster001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Plaster001" + }, + { + "id": "fabric030-color", + "name": "Fabric030 Color", + "file": "fabric/fabric030/color.webp", + "category": "fabric", + "tags": [ + "cloth", + "fabric", + "grey", + "color", + "material:fabric030", + "seamless" + ], + "bytes": 194076, + "material": "fabric030", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Fabric030" + }, + { + "id": "fabric030-normal", + "name": "Fabric030 Normal", + "file": "fabric/fabric030/normal.webp", + "category": "fabric", + "tags": [ + "cloth", + "fabric", + "grey", + "normal", + "material:fabric030", + "seamless" + ], + "bytes": 59750, + "material": "fabric030", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Fabric030" + }, + { + "id": "fabric030-roughness", + "name": "Fabric030 Roughness", + "file": "fabric/fabric030/roughness.webp", + "category": "fabric", + "tags": [ + "cloth", + "fabric", + "grey", + "roughness", + "material:fabric030", + "seamless" + ], + "bytes": 51472, + "material": "fabric030", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Fabric030" + }, + { + "id": "fabric045-color", + "name": "Fabric045 Color", + "file": "fabric/fabric045/color.webp", + "category": "fabric", + "tags": [ + "fabric", + "grey", + "rough", + "rug", + "white", + "color", + "material:fabric045", + "seamless" + ], + "bytes": 80160, + "material": "fabric045", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Fabric045" + }, + { + "id": "fabric045-normal", + "name": "Fabric045 Normal", + "file": "fabric/fabric045/normal.webp", + "category": "fabric", + "tags": [ + "fabric", + "grey", + "rough", + "rug", + "white", + "normal", + "material:fabric045", + "seamless" + ], + "bytes": 48808, + "material": "fabric045", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Fabric045" + }, + { + "id": "fabric045-roughness", + "name": "Fabric045 Roughness", + "file": "fabric/fabric045/roughness.webp", + "category": "fabric", + "tags": [ + "fabric", + "grey", + "rough", + "rug", + "white", + "roughness", + "material:fabric045", + "seamless" + ], + "bytes": 21476, + "material": "fabric045", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Fabric045" + }, + { + "id": "carpet009-color", + "name": "Carpet009 Color", + "file": "fabric/carpet009/color.webp", + "category": "fabric", + "tags": [ + "carpet", + "pattern", + "small", + "sqare", + "color", + "material:carpet009", + "seamless" + ], + "bytes": 133082, + "material": "carpet009", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Carpet009" + }, + { + "id": "carpet009-normal", + "name": "Carpet009 Normal", + "file": "fabric/carpet009/normal.webp", + "category": "fabric", + "tags": [ + "carpet", + "pattern", + "small", + "sqare", + "normal", + "material:carpet009", + "seamless" + ], + "bytes": 36004, + "material": "carpet009", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Carpet009" + }, + { + "id": "carpet009-roughness", + "name": "Carpet009 Roughness", + "file": "fabric/carpet009/roughness.webp", + "category": "fabric", + "tags": [ + "carpet", + "pattern", + "small", + "sqare", + "roughness", + "material:carpet009", + "seamless" + ], + "bytes": 1954, + "material": "carpet009", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Carpet009" + }, + { + "id": "leather011-color", + "name": "Leather011 Color", + "file": "fabric/leather011/color.webp", + "category": "fabric", + "tags": [ + "couch", + "leather", + "red", + "sofa", + "color", + "material:leather011", + "seamless" + ], + "bytes": 19894, + "material": "leather011", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Leather011" + }, + { + "id": "leather011-normal", + "name": "Leather011 Normal", + "file": "fabric/leather011/normal.webp", + "category": "fabric", + "tags": [ + "couch", + "leather", + "red", + "sofa", + "normal", + "material:leather011", + "seamless" + ], + "bytes": 19908, + "material": "leather011", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Leather011" + }, + { + "id": "leather011-roughness", + "name": "Leather011 Roughness", + "file": "fabric/leather011/roughness.webp", + "category": "fabric", + "tags": [ + "couch", + "leather", + "red", + "sofa", + "roughness", + "material:leather011", + "seamless" + ], + "bytes": 13722, + "material": "leather011", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Leather011" + }, + { + "id": "wicker001-color", + "name": "Wicker001 Color", + "file": "fabric/wicker001/color.webp", + "category": "fabric", + "tags": [ + "fabric", + "pattern", + "wicker", + "wood", + "color", + "material:wicker001", + "seamless" + ], + "bytes": 73994, + "material": "wicker001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Wicker001" + }, + { + "id": "wicker001-normal", + "name": "Wicker001 Normal", + "file": "fabric/wicker001/normal.webp", + "category": "fabric", + "tags": [ + "fabric", + "pattern", + "wicker", + "wood", + "normal", + "material:wicker001", + "seamless" + ], + "bytes": 21218, + "material": "wicker001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Wicker001" + }, + { + "id": "wicker001-roughness", + "name": "Wicker001 Roughness", + "file": "fabric/wicker001/roughness.webp", + "category": "fabric", + "tags": [ + "fabric", + "pattern", + "wicker", + "wood", + "roughness", + "material:wicker001", + "seamless" + ], + "bytes": 20392, + "material": "wicker001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Wicker001" + }, + { + "id": "rock030-color", + "name": "Rock030 Color", + "file": "stone/rock030/color.webp", + "category": "stone", + "tags": [ + "cliff", + "grey", + "rock", + "stone", + "wall", + "color", + "material:rock030", + "seamless" + ], + "bytes": 112610, + "material": "rock030", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Rock030" + }, + { + "id": "rock030-normal", + "name": "Rock030 Normal", + "file": "stone/rock030/normal.webp", + "category": "stone", + "tags": [ + "cliff", + "grey", + "rock", + "stone", + "wall", + "normal", + "material:rock030", + "seamless" + ], + "bytes": 53158, + "material": "rock030", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Rock030" + }, + { + "id": "rock030-roughness", + "name": "Rock030 Roughness", + "file": "stone/rock030/roughness.webp", + "category": "stone", + "tags": [ + "cliff", + "grey", + "rock", + "stone", + "wall", + "roughness", + "material:rock030", + "seamless" + ], + "bytes": 21210, + "material": "rock030", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Rock030" + }, + { + "id": "rock035-color", + "name": "Rock035 Color", + "file": "stone/rock035/color.webp", + "category": "stone", + "tags": [ + "black", + "cave", + "cliff", + "grey", + "rock", + "stone", + "color", + "material:rock035", + "seamless" + ], + "bytes": 68048, + "material": "rock035", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Rock035" + }, + { + "id": "rock035-normal", + "name": "Rock035 Normal", + "file": "stone/rock035/normal.webp", + "category": "stone", + "tags": [ + "black", + "cave", + "cliff", + "grey", + "rock", + "stone", + "normal", + "material:rock035", + "seamless" + ], + "bytes": 53342, + "material": "rock035", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Rock035" + }, + { + "id": "rock035-roughness", + "name": "Rock035 Roughness", + "file": "stone/rock035/roughness.webp", + "category": "stone", + "tags": [ + "black", + "cave", + "cliff", + "grey", + "rock", + "stone", + "roughness", + "material:rock035", + "seamless" + ], + "bytes": 19988, + "material": "rock035", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Rock035" + }, + { + "id": "marble006-color", + "name": "Marble006 Color", + "file": "stone/marble006/color.webp", + "category": "stone", + "tags": [ + "black", + "dark", + "gray", + "grey", + "marble", + "stone", + "color", + "material:marble006", + "seamless" + ], + "bytes": 83470, + "material": "marble006", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Marble006" + }, + { + "id": "marble006-normal", + "name": "Marble006 Normal", + "file": "stone/marble006/normal.webp", + "category": "stone", + "tags": [ + "black", + "dark", + "gray", + "grey", + "marble", + "stone", + "normal", + "material:marble006", + "seamless" + ], + "bytes": 550, + "material": "marble006", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Marble006" + }, + { + "id": "marble006-roughness", + "name": "Marble006 Roughness", + "file": "stone/marble006/roughness.webp", + "category": "stone", + "tags": [ + "black", + "dark", + "gray", + "grey", + "marble", + "stone", + "roughness", + "material:marble006", + "seamless" + ], + "bytes": 9238, + "material": "marble006", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Marble006" + }, + { + "id": "bricks059-color", + "name": "Bricks059 Color", + "file": "stone/bricks059/color.webp", + "category": "stone", + "tags": [ + "bricks", + "red", + "wall", + "color", + "material:bricks059", + "seamless" + ], + "bytes": 72480, + "material": "bricks059", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Bricks059" + }, + { + "id": "bricks059-normal", + "name": "Bricks059 Normal", + "file": "stone/bricks059/normal.webp", + "category": "stone", + "tags": [ + "bricks", + "red", + "wall", + "normal", + "material:bricks059", + "seamless" + ], + "bytes": 21862, + "material": "bricks059", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Bricks059" + }, + { + "id": "bricks059-roughness", + "name": "Bricks059 Roughness", + "file": "stone/bricks059/roughness.webp", + "category": "stone", + "tags": [ + "bricks", + "red", + "wall", + "roughness", + "material:bricks059", + "seamless" + ], + "bytes": 21520, + "material": "bricks059", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Bricks059" + }, + { + "id": "travertine001-color", + "name": "Travertine001 Color", + "file": "stone/travertine001/color.webp", + "category": "stone", + "tags": [ + "beige", + "marble", + "stone", + "travertine", + "color", + "material:travertine001", + "seamless" + ], + "bytes": 72150, + "material": "travertine001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Travertine001" + }, + { + "id": "travertine001-normal", + "name": "Travertine001 Normal", + "file": "stone/travertine001/normal.webp", + "category": "stone", + "tags": [ + "beige", + "marble", + "stone", + "travertine", + "normal", + "material:travertine001", + "seamless" + ], + "bytes": 550, + "material": "travertine001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Travertine001" + }, + { + "id": "travertine001-roughness", + "name": "Travertine001 Roughness", + "file": "stone/travertine001/roughness.webp", + "category": "stone", + "tags": [ + "beige", + "marble", + "stone", + "travertine", + "roughness", + "material:travertine001", + "seamless" + ], + "bytes": 2792, + "material": "travertine001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Travertine001" + }, + { + "id": "ground037-color", + "name": "Ground037 Color", + "file": "ground/ground037/color.webp", + "category": "ground", + "tags": [ + "damp", + "earth", + "forest", + "grass", + "green", + "ground", + "color", + "material:ground037", + "seamless" + ], + "bytes": 237326, + "material": "ground037", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Ground037" + }, + { + "id": "ground037-normal", + "name": "Ground037 Normal", + "file": "ground/ground037/normal.webp", + "category": "ground", + "tags": [ + "damp", + "earth", + "forest", + "grass", + "green", + "ground", + "normal", + "material:ground037", + "seamless" + ], + "bytes": 29950, + "material": "ground037", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Ground037" + }, + { + "id": "ground037-roughness", + "name": "Ground037 Roughness", + "file": "ground/ground037/roughness.webp", + "category": "ground", + "tags": [ + "damp", + "earth", + "forest", + "grass", + "green", + "ground", + "roughness", + "material:ground037", + "seamless" + ], + "bytes": 21128, + "material": "ground037", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Ground037" + }, + { + "id": "gravel021-color", + "name": "Gravel021 Color", + "file": "ground/gravel021/color.webp", + "category": "ground", + "tags": [ + "gravel", + "ground", + "pebbles", + "river", + "rocks", + "color", + "material:gravel021", + "seamless" + ], + "bytes": 74364, + "material": "gravel021", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Gravel021" + }, + { + "id": "gravel021-normal", + "name": "Gravel021 Normal", + "file": "ground/gravel021/normal.webp", + "category": "ground", + "tags": [ + "gravel", + "ground", + "pebbles", + "river", + "rocks", + "normal", + "material:gravel021", + "seamless" + ], + "bytes": 48898, + "material": "gravel021", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Gravel021" + }, + { + "id": "gravel021-roughness", + "name": "Gravel021 Roughness", + "file": "ground/gravel021/roughness.webp", + "category": "ground", + "tags": [ + "gravel", + "ground", + "pebbles", + "river", + "rocks", + "roughness", + "material:gravel021", + "seamless" + ], + "bytes": 21964, + "material": "gravel021", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Gravel021" + }, + { + "id": "grass004-color", + "name": "Grass004 Color", + "file": "ground/grass004/color.webp", + "category": "ground", + "tags": [ + "dense", + "garden", + "grass", + "grass004", + "green", + "ground", + "color", + "material:grass004", + "seamless" + ], + "bytes": 138546, + "material": "grass004", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Grass004" + }, + { + "id": "grass004-normal", + "name": "Grass004 Normal", + "file": "ground/grass004/normal.webp", + "category": "ground", + "tags": [ + "dense", + "garden", + "grass", + "grass004", + "green", + "ground", + "normal", + "material:grass004", + "seamless" + ], + "bytes": 31020, + "material": "grass004", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Grass004" + }, + { + "id": "grass004-roughness", + "name": "Grass004 Roughness", + "file": "ground/grass004/roughness.webp", + "category": "ground", + "tags": [ + "dense", + "garden", + "grass", + "grass004", + "green", + "ground", + "roughness", + "material:grass004", + "seamless" + ], + "bytes": 37238, + "material": "grass004", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Grass004" + }, + { + "id": "snow006-color", + "name": "Snow006 Color", + "file": "ground/snow006/color.webp", + "category": "ground", + "tags": [ + "cold", + "flat", + "ice", + "snow", + "steps", + "stomped", + "color", + "material:snow006", + "seamless" + ], + "bytes": 19564, + "material": "snow006", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Snow006" + }, + { + "id": "snow006-normal", + "name": "Snow006 Normal", + "file": "ground/snow006/normal.webp", + "category": "ground", + "tags": [ + "cold", + "flat", + "ice", + "snow", + "steps", + "stomped", + "normal", + "material:snow006", + "seamless" + ], + "bytes": 20772, + "material": "snow006", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Snow006" + }, + { + "id": "snow006-roughness", + "name": "Snow006 Roughness", + "file": "ground/snow006/roughness.webp", + "category": "ground", + "tags": [ + "cold", + "flat", + "ice", + "snow", + "steps", + "stomped", + "roughness", + "material:snow006", + "seamless" + ], + "bytes": 5406, + "material": "snow006", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Snow006" + }, + { + "id": "moss001-color", + "name": "Moss001 Color", + "file": "ground/moss001/color.webp", + "category": "ground", + "tags": [ + "ground", + "moss", + "mossy", + "color", + "material:moss001", + "seamless" + ], + "bytes": 224534, + "material": "moss001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Moss001" + }, + { + "id": "moss001-normal", + "name": "Moss001 Normal", + "file": "ground/moss001/normal.webp", + "category": "ground", + "tags": [ + "ground", + "moss", + "mossy", + "normal", + "material:moss001", + "seamless" + ], + "bytes": 55022, + "material": "moss001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Moss001" + }, + { + "id": "moss001-roughness", + "name": "Moss001 Roughness", + "file": "ground/moss001/roughness.webp", + "category": "ground", + "tags": [ + "ground", + "moss", + "mossy", + "roughness", + "material:moss001", + "seamless" + ], + "bytes": 34444, + "material": "moss001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Moss001" + }, + { + "id": "tiles074-color", + "name": "Tiles074 Color", + "file": "tiles/tiles074/color.webp", + "category": "tiles", + "tags": [ + "floor", + "marble", + "stone", + "tiled", + "tiles", + "tiling", + "color", + "material:tiles074", + "seamless" + ], + "bytes": 74684, + "material": "tiles074", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Tiles074" + }, + { + "id": "tiles074-normal", + "name": "Tiles074 Normal", + "file": "tiles/tiles074/normal.webp", + "category": "tiles", + "tags": [ + "floor", + "marble", + "stone", + "tiled", + "tiles", + "tiling", + "normal", + "material:tiles074", + "seamless" + ], + "bytes": 630, + "material": "tiles074", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Tiles074" + }, + { + "id": "tiles074-roughness", + "name": "Tiles074 Roughness", + "file": "tiles/tiles074/roughness.webp", + "category": "tiles", + "tags": [ + "floor", + "marble", + "stone", + "tiled", + "tiles", + "tiling", + "roughness", + "material:tiles074", + "seamless" + ], + "bytes": 7000, + "material": "tiles074", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Tiles074" + }, + { + "id": "tiles107-color", + "name": "Tiles107 Color", + "file": "tiles/tiles107/color.webp", + "category": "tiles", + "tags": [ + "tiles", + "white", + "color", + "material:tiles107", + "seamless" + ], + "bytes": 10922, + "material": "tiles107", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Tiles107" + }, + { + "id": "tiles107-normal", + "name": "Tiles107 Normal", + "file": "tiles/tiles107/normal.webp", + "category": "tiles", + "tags": [ + "tiles", + "white", + "normal", + "material:tiles107", + "seamless" + ], + "bytes": 9238, + "material": "tiles107", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Tiles107" + }, + { + "id": "tiles107-roughness", + "name": "Tiles107 Roughness", + "file": "tiles/tiles107/roughness.webp", + "category": "tiles", + "tags": [ + "tiles", + "white", + "roughness", + "material:tiles107", + "seamless" + ], + "bytes": 5282, + "material": "tiles107", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Tiles107" + }, + { + "id": "terrazzo003-color", + "name": "Terrazzo003 Color", + "file": "tiles/terrazzo003/color.webp", + "category": "tiles", + "tags": [ + "antique", + "black", + "clean", + "floor", + "stone", + "terrazzo", + "color", + "material:terrazzo003", + "seamless" + ], + "bytes": 71180, + "material": "terrazzo003", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Terrazzo003" + }, + { + "id": "terrazzo003-normal", + "name": "Terrazzo003 Normal", + "file": "tiles/terrazzo003/normal.webp", + "category": "tiles", + "tags": [ + "antique", + "black", + "clean", + "floor", + "stone", + "terrazzo", + "normal", + "material:terrazzo003", + "seamless" + ], + "bytes": 2834, + "material": "terrazzo003", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Terrazzo003" + }, + { + "id": "terrazzo003-roughness", + "name": "Terrazzo003 Roughness", + "file": "tiles/terrazzo003/roughness.webp", + "category": "tiles", + "tags": [ + "antique", + "black", + "clean", + "floor", + "stone", + "terrazzo", + "roughness", + "material:terrazzo003", + "seamless" + ], + "bytes": 13560, + "material": "terrazzo003", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Terrazzo003" + }, + { + "id": "roofingtiles003-color", + "name": "Roofingtiles003 Color", + "file": "tiles/roofingtiles003/color.webp", + "category": "tiles", + "tags": [ + "clean", + "roofing", + "slate", + "square", + "tiles", + "color", + "material:roofingtiles003", + "seamless" + ], + "bytes": 69866, + "material": "roofingtiles003", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=RoofingTiles003" + }, + { + "id": "roofingtiles003-normal", + "name": "Roofingtiles003 Normal", + "file": "tiles/roofingtiles003/normal.webp", + "category": "tiles", + "tags": [ + "clean", + "roofing", + "slate", + "square", + "tiles", + "normal", + "material:roofingtiles003", + "seamless" + ], + "bytes": 21756, + "material": "roofingtiles003", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=RoofingTiles003" + }, + { + "id": "roofingtiles003-roughness", + "name": "Roofingtiles003 Roughness", + "file": "tiles/roofingtiles003/roughness.webp", + "category": "tiles", + "tags": [ + "clean", + "roofing", + "slate", + "square", + "tiles", + "roughness", + "material:roofingtiles003", + "seamless" + ], + "bytes": 42882, + "material": "roofingtiles003", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=RoofingTiles003" + }, + { + "id": "pavingstones070-color", + "name": "Pavingstones070 Color", + "file": "tiles/pavingstones070/color.webp", + "category": "tiles", + "tags": [ + "cobble", + "old", + "pavement", + "paving", + "stones", + "color", + "material:pavingstones070", + "seamless" + ], + "bytes": 157750, + "material": "pavingstones070", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=PavingStones070" + }, + { + "id": "pavingstones070-normal", + "name": "Pavingstones070 Normal", + "file": "tiles/pavingstones070/normal.webp", + "category": "tiles", + "tags": [ + "cobble", + "old", + "pavement", + "paving", + "stones", + "normal", + "material:pavingstones070", + "seamless" + ], + "bytes": 25156, + "material": "pavingstones070", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=PavingStones070" + }, + { + "id": "pavingstones070-roughness", + "name": "Pavingstones070 Roughness", + "file": "tiles/pavingstones070/roughness.webp", + "category": "tiles", + "tags": [ + "cobble", + "old", + "pavement", + "paving", + "stones", + "roughness", + "material:pavingstones070", + "seamless" + ], + "bytes": 12498, + "material": "pavingstones070", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=PavingStones070" + }, + { + "id": "metalplates001-color", + "name": "Metalplates001 Color", + "file": "sci-fi-panels/metalplates001/color.webp", + "category": "sci-fi panels", + "tags": [ + "brushed", + "bumpy", + "metal", + "plates", + "scratches", + "silver", + "color", + "material:metalplates001", + "seamless" + ], + "bytes": 16362, + "material": "metalplates001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=MetalPlates001" + }, + { + "id": "metalplates001-normal", + "name": "Metalplates001 Normal", + "file": "sci-fi-panels/metalplates001/normal.webp", + "category": "sci-fi panels", + "tags": [ + "brushed", + "bumpy", + "metal", + "plates", + "scratches", + "silver", + "normal", + "material:metalplates001", + "seamless" + ], + "bytes": 9776, + "material": "metalplates001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=MetalPlates001" + }, + { + "id": "metalplates001-roughness", + "name": "Metalplates001 Roughness", + "file": "sci-fi-panels/metalplates001/roughness.webp", + "category": "sci-fi panels", + "tags": [ + "brushed", + "bumpy", + "metal", + "plates", + "scratches", + "silver", + "roughness", + "material:metalplates001", + "seamless" + ], + "bytes": 6780, + "material": "metalplates001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=MetalPlates001" + }, + { + "id": "metalplates006-color", + "name": "Metalplates006 Color", + "file": "sci-fi-panels/metalplates006/color.webp", + "category": "sci-fi panels", + "tags": [ + "decoration", + "design", + "metal", + "plates", + "color", + "material:metalplates006", + "seamless" + ], + "bytes": 35714, + "material": "metalplates006", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=MetalPlates006" + }, + { + "id": "metalplates006-normal", + "name": "Metalplates006 Normal", + "file": "sci-fi-panels/metalplates006/normal.webp", + "category": "sci-fi panels", + "tags": [ + "decoration", + "design", + "metal", + "plates", + "normal", + "material:metalplates006", + "seamless" + ], + "bytes": 19602, + "material": "metalplates006", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=MetalPlates006" + }, + { + "id": "metalplates006-roughness", + "name": "Metalplates006 Roughness", + "file": "sci-fi-panels/metalplates006/roughness.webp", + "category": "sci-fi panels", + "tags": [ + "decoration", + "design", + "metal", + "plates", + "roughness", + "material:metalplates006", + "seamless" + ], + "bytes": 14902, + "material": "metalplates006", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=MetalPlates006" + }, + { + "id": "metalwalkway001-color", + "name": "Metalwalkway001 Color", + "file": "sci-fi-panels/metalwalkway001/color.webp", + "category": "sci-fi panels", + "tags": [ + "metal", + "steel", + "walkway", + "color", + "material:metalwalkway001", + "seamless" + ], + "bytes": 66458, + "material": "metalwalkway001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=MetalWalkway001" + }, + { + "id": "metalwalkway001-normal", + "name": "Metalwalkway001 Normal", + "file": "sci-fi-panels/metalwalkway001/normal.webp", + "category": "sci-fi panels", + "tags": [ + "metal", + "steel", + "walkway", + "normal", + "material:metalwalkway001", + "seamless" + ], + "bytes": 21564, + "material": "metalwalkway001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=MetalWalkway001" + }, + { + "id": "metalwalkway001-roughness", + "name": "Metalwalkway001 Roughness", + "file": "sci-fi-panels/metalwalkway001/roughness.webp", + "category": "sci-fi panels", + "tags": [ + "metal", + "steel", + "walkway", + "roughness", + "material:metalwalkway001", + "seamless" + ], + "bytes": 41364, + "material": "metalwalkway001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=MetalWalkway001" + }, + { + "id": "sheetmetal001-color", + "name": "Sheetmetal001 Color", + "file": "sci-fi-panels/sheetmetal001/color.webp", + "category": "sci-fi panels", + "tags": [ + "hole", + "holes", + "metal", + "pattern", + "perforated", + "sheet", + "color", + "material:sheetmetal001", + "seamless" + ], + "bytes": 68072, + "material": "sheetmetal001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=SheetMetal001" + }, + { + "id": "sheetmetal001-normal", + "name": "Sheetmetal001 Normal", + "file": "sci-fi-panels/sheetmetal001/normal.webp", + "category": "sci-fi panels", + "tags": [ + "hole", + "holes", + "metal", + "pattern", + "perforated", + "sheet", + "normal", + "material:sheetmetal001", + "seamless" + ], + "bytes": 32068, + "material": "sheetmetal001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=SheetMetal001" + }, + { + "id": "sheetmetal001-roughness", + "name": "Sheetmetal001 Roughness", + "file": "sci-fi-panels/sheetmetal001/roughness.webp", + "category": "sci-fi panels", + "tags": [ + "hole", + "holes", + "metal", + "pattern", + "perforated", + "sheet", + "roughness", + "material:sheetmetal001", + "seamless" + ], + "bytes": 21098, + "material": "sheetmetal001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=SheetMetal001" + }, + { + "id": "solarpanel001-color", + "name": "Solarpanel001 Color", + "file": "sci-fi-panels/solarpanel001/color.webp", + "category": "sci-fi panels", + "tags": [ + "cell", + "panel", + "solar", + "sun", + "color", + "material:solarpanel001", + "seamless" + ], + "bytes": 74396, + "material": "solarpanel001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=SolarPanel001" + }, + { + "id": "solarpanel001-normal", + "name": "Solarpanel001 Normal", + "file": "sci-fi-panels/solarpanel001/normal.webp", + "category": "sci-fi panels", + "tags": [ + "cell", + "panel", + "solar", + "sun", + "normal", + "material:solarpanel001", + "seamless" + ], + "bytes": 1678, + "material": "solarpanel001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=SolarPanel001" + }, + { + "id": "solarpanel001-roughness", + "name": "Solarpanel001 Roughness", + "file": "sci-fi-panels/solarpanel001/roughness.webp", + "category": "sci-fi panels", + "tags": [ + "cell", + "panel", + "solar", + "sun", + "roughness", + "material:solarpanel001", + "seamless" + ], + "bytes": 20834, + "material": "solarpanel001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=SolarPanel001" + }, + { + "id": "tiles093-color", + "name": "Tiles093 Color", + "file": "tiles/tiles093/color.webp", + "category": "tiles", + "tags": [ + "black", + "dark", + "old", + "random", + "tiles", + "color", + "material:tiles093", + "seamless" + ], + "bytes": 103506, + "material": "tiles093", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Tiles093" + }, + { + "id": "tiles093-normal", + "name": "Tiles093 Normal", + "file": "tiles/tiles093/normal.webp", + "category": "tiles", + "tags": [ + "black", + "dark", + "old", + "random", + "tiles", + "normal", + "material:tiles093", + "seamless" + ], + "bytes": 71480, + "material": "tiles093", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Tiles093" + }, + { + "id": "tiles093-roughness", + "name": "Tiles093 Roughness", + "file": "tiles/tiles093/roughness.webp", + "category": "tiles", + "tags": [ + "black", + "dark", + "old", + "random", + "tiles", + "roughness", + "material:tiles093", + "seamless" + ], + "bytes": 52026, + "material": "tiles093", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Tiles093" + }, + { + "id": "tiles101-color", + "name": "Tiles101 Color", + "file": "tiles/tiles101/color.webp", + "category": "tiles", + "tags": [ + "clean", + "painted", + "pattern", + "tiles", + "color", + "material:tiles101", + "seamless" + ], + "bytes": 292530, + "material": "tiles101", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Tiles101" + }, + { + "id": "tiles101-normal", + "name": "Tiles101 Normal", + "file": "tiles/tiles101/normal.webp", + "category": "tiles", + "tags": [ + "clean", + "painted", + "pattern", + "tiles", + "normal", + "material:tiles101", + "seamless" + ], + "bytes": 10582, + "material": "tiles101", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Tiles101" + }, + { + "id": "tiles101-roughness", + "name": "Tiles101 Roughness", + "file": "tiles/tiles101/roughness.webp", + "category": "tiles", + "tags": [ + "clean", + "painted", + "pattern", + "tiles", + "roughness", + "material:tiles101", + "seamless" + ], + "bytes": 34732, + "material": "tiles101", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Tiles101" + }, + { + "id": "plaster003-color", + "name": "Plaster003 Color", + "file": "plaster/plaster003/color.webp", + "category": "plaster", + "tags": [ + "clean", + "plaster", + "rough", + "wall", + "white", + "color", + "material:plaster003", + "seamless" + ], + "bytes": 313460, + "material": "plaster003", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Plaster003" + }, + { + "id": "plaster003-normal", + "name": "Plaster003 Normal", + "file": "plaster/plaster003/normal.webp", + "category": "plaster", + "tags": [ + "clean", + "plaster", + "rough", + "wall", + "white", + "normal", + "material:plaster003", + "seamless" + ], + "bytes": 60470, + "material": "plaster003", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Plaster003" + }, + { + "id": "plaster003-roughness", + "name": "Plaster003 Roughness", + "file": "plaster/plaster003/roughness.webp", + "category": "plaster", + "tags": [ + "clean", + "plaster", + "rough", + "wall", + "white", + "roughness", + "material:plaster003", + "seamless" + ], + "bytes": 4502, + "material": "plaster003", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Plaster003" + }, + { + "id": "plaster006-color", + "name": "Plaster006 Color", + "file": "plaster/plaster006/color.webp", + "category": "plaster", + "tags": [ + "plaster", + "wall", + "white", + "color", + "material:plaster006", + "seamless" + ], + "bytes": 51900, + "material": "plaster006", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Plaster006" + }, + { + "id": "plaster006-normal", + "name": "Plaster006 Normal", + "file": "plaster/plaster006/normal.webp", + "category": "plaster", + "tags": [ + "plaster", + "wall", + "white", + "normal", + "material:plaster006", + "seamless" + ], + "bytes": 71404, + "material": "plaster006", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Plaster006" + }, + { + "id": "plaster006-roughness", + "name": "Plaster006 Roughness", + "file": "plaster/plaster006/roughness.webp", + "category": "plaster", + "tags": [ + "plaster", + "wall", + "white", + "roughness", + "material:plaster006", + "seamless" + ], + "bytes": 35404, + "material": "plaster006", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Plaster006" + }, + { + "id": "marble003-color", + "name": "Marble003 Color", + "file": "marble/marble003/color.webp", + "category": "marble", + "tags": [ + "clean", + "grey", + "marble", + "white", + "color", + "material:marble003", + "seamless" + ], + "bytes": 67306, + "material": "marble003", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Marble003" + }, + { + "id": "marble003-normal", + "name": "Marble003 Normal", + "file": "marble/marble003/normal.webp", + "category": "marble", + "tags": [ + "clean", + "grey", + "marble", + "white", + "normal", + "material:marble003", + "seamless" + ], + "bytes": 5144, + "material": "marble003", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Marble003" + }, + { + "id": "marble003-roughness", + "name": "Marble003 Roughness", + "file": "marble/marble003/roughness.webp", + "category": "marble", + "tags": [ + "clean", + "grey", + "marble", + "white", + "roughness", + "material:marble003", + "seamless" + ], + "bytes": 51716, + "material": "marble003", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Marble003" + }, + { + "id": "marble012-color", + "name": "Marble012 Color", + "file": "marble/marble012/color.webp", + "category": "marble", + "tags": [ + "bathroom", + "elegant", + "glossy", + "gray", + "grey", + "kitchen", + "color", + "material:marble012", + "seamless" + ], + "bytes": 212898, + "material": "marble012", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Marble012" + }, + { + "id": "marble012-normal", + "name": "Marble012 Normal", + "file": "marble/marble012/normal.webp", + "category": "marble", + "tags": [ + "bathroom", + "elegant", + "glossy", + "gray", + "grey", + "kitchen", + "normal", + "material:marble012", + "seamless" + ], + "bytes": 546, + "material": "marble012", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Marble012" + }, + { + "id": "marble012-roughness", + "name": "Marble012 Roughness", + "file": "marble/marble012/roughness.webp", + "category": "marble", + "tags": [ + "bathroom", + "elegant", + "glossy", + "gray", + "grey", + "kitchen", + "roughness", + "material:marble012", + "seamless" + ], + "bytes": 23344, + "material": "marble012", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Marble012" + }, + { + "id": "fabric026-color", + "name": "Fabric026 Color", + "file": "fabric/fabric026/color.webp", + "category": "fabric", + "tags": [ + "carpet", + "cloth", + "fabric", + "floor", + "red", + "tiled", + "color", + "material:fabric026", + "seamless" + ], + "bytes": 186562, + "material": "fabric026", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Fabric026" + }, + { + "id": "fabric026-normal", + "name": "Fabric026 Normal", + "file": "fabric/fabric026/normal.webp", + "category": "fabric", + "tags": [ + "carpet", + "cloth", + "fabric", + "floor", + "red", + "tiled", + "normal", + "material:fabric026", + "seamless" + ], + "bytes": 47044, + "material": "fabric026", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Fabric026" + }, + { + "id": "fabric026-roughness", + "name": "Fabric026 Roughness", + "file": "fabric/fabric026/roughness.webp", + "category": "fabric", + "tags": [ + "carpet", + "cloth", + "fabric", + "floor", + "red", + "tiled", + "roughness", + "material:fabric026", + "seamless" + ], + "bytes": 39442, + "material": "fabric026", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Fabric026" + }, + { + "id": "fabric062-color", + "name": "Fabric062 Color", + "file": "fabric/fabric062/color.webp", + "category": "fabric", + "tags": [ + "fabric", + "rough", + "color", + "material:fabric062", + "seamless" + ], + "bytes": 201646, + "material": "fabric062", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Fabric062" + }, + { + "id": "fabric062-normal", + "name": "Fabric062 Normal", + "file": "fabric/fabric062/normal.webp", + "category": "fabric", + "tags": [ + "fabric", + "rough", + "normal", + "material:fabric062", + "seamless" + ], + "bytes": 49922, + "material": "fabric062", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Fabric062" + }, + { + "id": "fabric062-roughness", + "name": "Fabric062 Roughness", + "file": "fabric/fabric062/roughness.webp", + "category": "fabric", + "tags": [ + "fabric", + "rough", + "roughness", + "material:fabric062", + "seamless" + ], + "bytes": 29936, + "material": "fabric062", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Fabric062" + }, + { + "id": "leather026-color", + "name": "Leather026 Color", + "file": "leather/leather026/color.webp", + "category": "leather", + "tags": [ + "black", + "dark", + "leather", + "smooth", + "color", + "material:leather026", + "seamless" + ], + "bytes": 22666, + "material": "leather026", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Leather026" + }, + { + "id": "leather026-normal", + "name": "Leather026 Normal", + "file": "leather/leather026/normal.webp", + "category": "leather", + "tags": [ + "black", + "dark", + "leather", + "smooth", + "normal", + "material:leather026", + "seamless" + ], + "bytes": 17986, + "material": "leather026", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Leather026" + }, + { + "id": "leather026-roughness", + "name": "Leather026 Roughness", + "file": "leather/leather026/roughness.webp", + "category": "leather", + "tags": [ + "black", + "dark", + "leather", + "smooth", + "roughness", + "material:leather026", + "seamless" + ], + "bytes": 19870, + "material": "leather026", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Leather026" + }, + { + "id": "carpet012-color", + "name": "Carpet012 Color", + "file": "carpet/carpet012/color.webp", + "category": "carpet", + "tags": [ + "blue", + "carpet", + "dark", + "plain", + "color", + "material:carpet012", + "seamless" + ], + "bytes": 399468, + "material": "carpet012", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Carpet012" + }, + { + "id": "carpet012-normal", + "name": "Carpet012 Normal", + "file": "carpet/carpet012/normal.webp", + "category": "carpet", + "tags": [ + "blue", + "carpet", + "dark", + "plain", + "normal", + "material:carpet012", + "seamless" + ], + "bytes": 128334, + "material": "carpet012", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Carpet012" + }, + { + "id": "carpet012-roughness", + "name": "Carpet012 Roughness", + "file": "carpet/carpet012/roughness.webp", + "category": "carpet", + "tags": [ + "blue", + "carpet", + "dark", + "plain", + "roughness", + "material:carpet012", + "seamless" + ], + "bytes": 40046, + "material": "carpet012", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Carpet012" + }, + { + "id": "carpet004-color", + "name": "Carpet004 Color", + "file": "carpet/carpet004/color.webp", + "category": "carpet", + "tags": [ + "carpet", + "dark", + "fabric", + "floor", + "grey", + "mat", + "color", + "material:carpet004", + "seamless" + ], + "bytes": 332748, + "material": "carpet004", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Carpet004" + }, + { + "id": "carpet004-normal", + "name": "Carpet004 Normal", + "file": "carpet/carpet004/normal.webp", + "category": "carpet", + "tags": [ + "carpet", + "dark", + "fabric", + "floor", + "grey", + "mat", + "normal", + "material:carpet004", + "seamless" + ], + "bytes": 73856, + "material": "carpet004", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Carpet004" + }, + { + "id": "carpet004-roughness", + "name": "Carpet004 Roughness", + "file": "carpet/carpet004/roughness.webp", + "category": "carpet", + "tags": [ + "carpet", + "dark", + "fabric", + "floor", + "grey", + "mat", + "roughness", + "material:carpet004", + "seamless" + ], + "bytes": 10890, + "material": "carpet004", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Carpet004" + }, + { + "id": "roofingtiles010-color", + "name": "RoofingTiles010 Color", + "file": "roof/roofingtiles010/color.webp", + "category": "roof", + "tags": [ + "grey", + "modern", + "roofing", + "tiles", + "white", + "color", + "material:roofingtiles010", + "seamless" + ], + "bytes": 28728, + "material": "roofingtiles010", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=RoofingTiles010" + }, + { + "id": "roofingtiles010-normal", + "name": "RoofingTiles010 Normal", + "file": "roof/roofingtiles010/normal.webp", + "category": "roof", + "tags": [ + "grey", + "modern", + "roofing", + "tiles", + "white", + "normal", + "material:roofingtiles010", + "seamless" + ], + "bytes": 35440, + "material": "roofingtiles010", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=RoofingTiles010" + }, + { + "id": "roofingtiles010-roughness", + "name": "RoofingTiles010 Roughness", + "file": "roof/roofingtiles010/roughness.webp", + "category": "roof", + "tags": [ + "grey", + "modern", + "roofing", + "tiles", + "white", + "roughness", + "material:roofingtiles010", + "seamless" + ], + "bytes": 41016, + "material": "roofingtiles010", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=RoofingTiles010" + }, + { + "id": "pavingstones092-color", + "name": "PavingStones092 Color", + "file": "paving/pavingstones092/color.webp", + "category": "paving", + "tags": [ + "floor", + "pavement", + "paving", + "red", + "stone", + "stones", + "color", + "material:pavingstones092", + "seamless" + ], + "bytes": 181040, + "material": "pavingstones092", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=PavingStones092" + }, + { + "id": "pavingstones092-normal", + "name": "PavingStones092 Normal", + "file": "paving/pavingstones092/normal.webp", + "category": "paving", + "tags": [ + "floor", + "pavement", + "paving", + "red", + "stone", + "stones", + "normal", + "material:pavingstones092", + "seamless" + ], + "bytes": 72166, + "material": "pavingstones092", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=PavingStones092" + }, + { + "id": "pavingstones092-roughness", + "name": "PavingStones092 Roughness", + "file": "paving/pavingstones092/roughness.webp", + "category": "paving", + "tags": [ + "floor", + "pavement", + "paving", + "red", + "stone", + "stones", + "roughness", + "material:pavingstones092", + "seamless" + ], + "bytes": 11022, + "material": "pavingstones092", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=PavingStones092" + }, + { + "id": "grate002-color", + "name": "Grate002 Color", + "file": "metal/grate002/color.webp", + "category": "metal", + "tags": [ + "grate", + "gutter", + "manhole", + "color", + "material:grate002", + "seamless" + ], + "bytes": 70572, + "material": "grate002", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Grate002" + }, + { + "id": "grate002-normal", + "name": "Grate002 Normal", + "file": "metal/grate002/normal.webp", + "category": "metal", + "tags": [ + "grate", + "gutter", + "manhole", + "normal", + "material:grate002", + "seamless" + ], + "bytes": 19016, + "material": "grate002", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Grate002" + }, + { + "id": "grate002-roughness", + "name": "Grate002 Roughness", + "file": "metal/grate002/roughness.webp", + "category": "metal", + "tags": [ + "grate", + "gutter", + "manhole", + "roughness", + "material:grate002", + "seamless" + ], + "bytes": 17972, + "material": "grate002", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Grate002" + }, + { + "id": "foam001-color", + "name": "Foam001 Color", + "file": "foam/foam001/color.webp", + "category": "foam", + "tags": [ + "foam", + "ocean", + "sea", + "soap", + "color", + "material:foam001", + "seamless" + ], + "bytes": 220538, + "material": "foam001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Foam001" + }, + { + "id": "foam001-normal", + "name": "Foam001 Normal", + "file": "foam/foam001/normal.webp", + "category": "foam", + "tags": [ + "foam", + "ocean", + "sea", + "soap", + "normal", + "material:foam001", + "seamless" + ], + "bytes": 49564, + "material": "foam001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Foam001" + }, + { + "id": "foam001-roughness", + "name": "Foam001 Roughness", + "file": "foam/foam001/roughness.webp", + "category": "foam", + "tags": [ + "foam", + "ocean", + "sea", + "soap", + "roughness", + "material:foam001", + "seamless" + ], + "bytes": 48962, + "material": "foam001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Foam001" + }, + { + "id": "paper001-color", + "name": "Paper001 Color", + "file": "paper/paper001/color.webp", + "category": "paper", + "tags": [ + "paper", + "white", + "color", + "material:paper001", + "seamless" + ], + "bytes": 25500, + "material": "paper001", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Paper001" + }, + { + "id": "paper001-normal", + "name": "Paper001 Normal", + "file": "paper/paper001/normal.webp", + "category": "paper", + "tags": [ + "paper", + "white", + "normal", + "material:paper001", + "seamless" + ], + "bytes": 62778, + "material": "paper001", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Paper001" + }, + { + "id": "paper001-roughness", + "name": "Paper001 Roughness", + "file": "paper/paper001/roughness.webp", + "category": "paper", + "tags": [ + "paper", + "white", + "roughness", + "material:paper001", + "seamless" + ], + "bytes": 74072, + "material": "paper001", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Paper001" + }, + { + "id": "plastic010-color", + "name": "Plastic010 Color", + "file": "plastic/plastic010/color.webp", + "category": "plastic", + "tags": [ + "plastic", + "smooth", + "white", + "color", + "material:plastic010", + "seamless" + ], + "bytes": 2314, + "material": "plastic010", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Plastic010" + }, + { + "id": "plastic010-normal", + "name": "Plastic010 Normal", + "file": "plastic/plastic010/normal.webp", + "category": "plastic", + "tags": [ + "plastic", + "smooth", + "white", + "normal", + "material:plastic010", + "seamless" + ], + "bytes": 618, + "material": "plastic010", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Plastic010" + }, + { + "id": "plastic010-roughness", + "name": "Plastic010 Roughness", + "file": "plastic/plastic010/roughness.webp", + "category": "plastic", + "tags": [ + "plastic", + "smooth", + "white", + "roughness", + "material:plastic010", + "seamless" + ], + "bytes": 19010, + "material": "plastic010", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Plastic010" + }, + { + "id": "plastic006-color", + "name": "Plastic006 Color", + "file": "plastic/plastic006/color.webp", + "category": "plastic", + "tags": [ + "black", + "plastic", + "shiny", + "smooth", + "color", + "material:plastic006", + "seamless" + ], + "bytes": 16078, + "material": "plastic006", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Plastic006" + }, + { + "id": "plastic006-normal", + "name": "Plastic006 Normal", + "file": "plastic/plastic006/normal.webp", + "category": "plastic", + "tags": [ + "black", + "plastic", + "shiny", + "smooth", + "normal", + "material:plastic006", + "seamless" + ], + "bytes": 584, + "material": "plastic006", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Plastic006" + }, + { + "id": "plastic006-roughness", + "name": "Plastic006 Roughness", + "file": "plastic/plastic006/roughness.webp", + "category": "plastic", + "tags": [ + "black", + "plastic", + "shiny", + "smooth", + "roughness", + "material:plastic006", + "seamless" + ], + "bytes": 22186, + "material": "plastic006", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Plastic006" + }, + { + "id": "rubber004-color", + "name": "Rubber004 Color", + "file": "plastic/rubber004/color.webp", + "category": "plastic", + "tags": [ + "black", + "floor", + "gym", + "rubber", + "color", + "material:rubber004", + "seamless" + ], + "bytes": 106032, + "material": "rubber004", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Rubber004" + }, + { + "id": "rubber004-normal", + "name": "Rubber004 Normal", + "file": "plastic/rubber004/normal.webp", + "category": "plastic", + "tags": [ + "black", + "floor", + "gym", + "rubber", + "normal", + "material:rubber004", + "seamless" + ], + "bytes": 55290, + "material": "rubber004", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Rubber004" + }, + { + "id": "rubber004-roughness", + "name": "Rubber004 Roughness", + "file": "plastic/rubber004/roughness.webp", + "category": "plastic", + "tags": [ + "black", + "floor", + "gym", + "rubber", + "roughness", + "material:rubber004", + "seamless" + ], + "bytes": 57320, + "material": "rubber004", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Rubber004" + }, + { + "id": "metal055a-color", + "name": "Metal055A Color", + "file": "metal/metal055a/color.webp", + "category": "metal", + "tags": [ + "iron", + "metal", + "color", + "material:metal055a", + "seamless" + ], + "bytes": 35172, + "material": "metal055a", + "map": "colour", + "source_page": "https://ambientcg.com/view?id=Metal055A" + }, + { + "id": "metal055a-normal", + "name": "Metal055A Normal", + "file": "metal/metal055a/normal.webp", + "category": "metal", + "tags": [ + "iron", + "metal", + "normal", + "material:metal055a", + "seamless" + ], + "bytes": 882, + "material": "metal055a", + "map": "normal", + "source_page": "https://ambientcg.com/view?id=Metal055A" + }, + { + "id": "metal055a-roughness", + "name": "Metal055A Roughness", + "file": "metal/metal055a/roughness.webp", + "category": "metal", + "tags": [ + "iron", + "metal", + "roughness", + "material:metal055a", + "seamless" + ], + "bytes": 21808, + "material": "metal055a", + "map": "roughness", + "source_page": "https://ambientcg.com/view?id=Metal055A" + } + ] +} \ No newline at end of file diff --git a/assets/starter/2d/textures-ambientcg/paper/paper001/color.webp b/assets/starter/2d/textures-ambientcg/paper/paper001/color.webp new file mode 100644 index 0000000..006d573 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/paper/paper001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/paper/paper001/normal.webp b/assets/starter/2d/textures-ambientcg/paper/paper001/normal.webp new file mode 100644 index 0000000..4d240e5 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/paper/paper001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/paper/paper001/roughness.webp b/assets/starter/2d/textures-ambientcg/paper/paper001/roughness.webp new file mode 100644 index 0000000..f5d850a Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/paper/paper001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/paving/pavingstones092/color.webp b/assets/starter/2d/textures-ambientcg/paving/pavingstones092/color.webp new file mode 100644 index 0000000..08808fd Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/paving/pavingstones092/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/paving/pavingstones092/normal.webp b/assets/starter/2d/textures-ambientcg/paving/pavingstones092/normal.webp new file mode 100644 index 0000000..eeb5b80 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/paving/pavingstones092/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/paving/pavingstones092/roughness.webp b/assets/starter/2d/textures-ambientcg/paving/pavingstones092/roughness.webp new file mode 100644 index 0000000..cc5c398 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/paving/pavingstones092/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plaster/plaster003/color.webp b/assets/starter/2d/textures-ambientcg/plaster/plaster003/color.webp new file mode 100644 index 0000000..f9be472 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plaster/plaster003/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plaster/plaster003/normal.webp b/assets/starter/2d/textures-ambientcg/plaster/plaster003/normal.webp new file mode 100644 index 0000000..cb075b8 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plaster/plaster003/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plaster/plaster003/roughness.webp b/assets/starter/2d/textures-ambientcg/plaster/plaster003/roughness.webp new file mode 100644 index 0000000..65e8a1c Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plaster/plaster003/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plaster/plaster006/color.webp b/assets/starter/2d/textures-ambientcg/plaster/plaster006/color.webp new file mode 100644 index 0000000..0076a67 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plaster/plaster006/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plaster/plaster006/normal.webp b/assets/starter/2d/textures-ambientcg/plaster/plaster006/normal.webp new file mode 100644 index 0000000..f67af7c Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plaster/plaster006/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plaster/plaster006/roughness.webp b/assets/starter/2d/textures-ambientcg/plaster/plaster006/roughness.webp new file mode 100644 index 0000000..2aa961b Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plaster/plaster006/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plastic/plastic006/color.webp b/assets/starter/2d/textures-ambientcg/plastic/plastic006/color.webp new file mode 100644 index 0000000..20f9b4f Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plastic/plastic006/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plastic/plastic006/normal.webp b/assets/starter/2d/textures-ambientcg/plastic/plastic006/normal.webp new file mode 100644 index 0000000..2c28a0f Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plastic/plastic006/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plastic/plastic006/roughness.webp b/assets/starter/2d/textures-ambientcg/plastic/plastic006/roughness.webp new file mode 100644 index 0000000..35bab18 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plastic/plastic006/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plastic/plastic010/color.webp b/assets/starter/2d/textures-ambientcg/plastic/plastic010/color.webp new file mode 100644 index 0000000..3c73a18 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plastic/plastic010/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plastic/plastic010/normal.webp b/assets/starter/2d/textures-ambientcg/plastic/plastic010/normal.webp new file mode 100644 index 0000000..25865b6 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plastic/plastic010/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plastic/plastic010/roughness.webp b/assets/starter/2d/textures-ambientcg/plastic/plastic010/roughness.webp new file mode 100644 index 0000000..f9de1f8 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plastic/plastic010/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plastic/rubber004/color.webp b/assets/starter/2d/textures-ambientcg/plastic/rubber004/color.webp new file mode 100644 index 0000000..bde2450 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plastic/rubber004/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plastic/rubber004/normal.webp b/assets/starter/2d/textures-ambientcg/plastic/rubber004/normal.webp new file mode 100644 index 0000000..11afb0d Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plastic/rubber004/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/plastic/rubber004/roughness.webp b/assets/starter/2d/textures-ambientcg/plastic/rubber004/roughness.webp new file mode 100644 index 0000000..0f7fd64 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/plastic/rubber004/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/roof/roofingtiles010/color.webp b/assets/starter/2d/textures-ambientcg/roof/roofingtiles010/color.webp new file mode 100644 index 0000000..5c1eed0 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/roof/roofingtiles010/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/roof/roofingtiles010/normal.webp b/assets/starter/2d/textures-ambientcg/roof/roofingtiles010/normal.webp new file mode 100644 index 0000000..88191e6 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/roof/roofingtiles010/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/roof/roofingtiles010/roughness.webp b/assets/starter/2d/textures-ambientcg/roof/roofingtiles010/roughness.webp new file mode 100644 index 0000000..dda0964 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/roof/roofingtiles010/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates001/color.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates001/color.webp new file mode 100644 index 0000000..4d92488 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates001/normal.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates001/normal.webp new file mode 100644 index 0000000..d9d3cfd Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates001/roughness.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates001/roughness.webp new file mode 100644 index 0000000..6f549b9 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates006/color.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates006/color.webp new file mode 100644 index 0000000..aecd976 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates006/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates006/normal.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates006/normal.webp new file mode 100644 index 0000000..f9cd07d Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates006/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates006/roughness.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates006/roughness.webp new file mode 100644 index 0000000..46041a8 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalplates006/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalwalkway001/color.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalwalkway001/color.webp new file mode 100644 index 0000000..04ac46e Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalwalkway001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalwalkway001/normal.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalwalkway001/normal.webp new file mode 100644 index 0000000..009a389 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalwalkway001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalwalkway001/roughness.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalwalkway001/roughness.webp new file mode 100644 index 0000000..4ff4bee Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/metalwalkway001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/sheetmetal001/color.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/sheetmetal001/color.webp new file mode 100644 index 0000000..d30b64b Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/sheetmetal001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/sheetmetal001/normal.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/sheetmetal001/normal.webp new file mode 100644 index 0000000..392bee7 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/sheetmetal001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/sheetmetal001/roughness.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/sheetmetal001/roughness.webp new file mode 100644 index 0000000..12983d3 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/sheetmetal001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/solarpanel001/color.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/solarpanel001/color.webp new file mode 100644 index 0000000..623cc22 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/solarpanel001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/solarpanel001/normal.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/solarpanel001/normal.webp new file mode 100644 index 0000000..6a7db91 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/solarpanel001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/sci-fi-panels/solarpanel001/roughness.webp b/assets/starter/2d/textures-ambientcg/sci-fi-panels/solarpanel001/roughness.webp new file mode 100644 index 0000000..695aab2 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/sci-fi-panels/solarpanel001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/bricks059/color.webp b/assets/starter/2d/textures-ambientcg/stone/bricks059/color.webp new file mode 100644 index 0000000..71f9271 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/bricks059/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/bricks059/normal.webp b/assets/starter/2d/textures-ambientcg/stone/bricks059/normal.webp new file mode 100644 index 0000000..3b48791 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/bricks059/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/bricks059/roughness.webp b/assets/starter/2d/textures-ambientcg/stone/bricks059/roughness.webp new file mode 100644 index 0000000..1f98dcc Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/bricks059/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/marble006/color.webp b/assets/starter/2d/textures-ambientcg/stone/marble006/color.webp new file mode 100644 index 0000000..52dd6b9 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/marble006/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/marble006/normal.webp b/assets/starter/2d/textures-ambientcg/stone/marble006/normal.webp new file mode 100644 index 0000000..00e81ea Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/marble006/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/marble006/roughness.webp b/assets/starter/2d/textures-ambientcg/stone/marble006/roughness.webp new file mode 100644 index 0000000..cd63ea7 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/marble006/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/rock030/color.webp b/assets/starter/2d/textures-ambientcg/stone/rock030/color.webp new file mode 100644 index 0000000..9e3d4b1 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/rock030/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/rock030/normal.webp b/assets/starter/2d/textures-ambientcg/stone/rock030/normal.webp new file mode 100644 index 0000000..5478749 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/rock030/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/rock030/roughness.webp b/assets/starter/2d/textures-ambientcg/stone/rock030/roughness.webp new file mode 100644 index 0000000..ace5cea Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/rock030/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/rock035/color.webp b/assets/starter/2d/textures-ambientcg/stone/rock035/color.webp new file mode 100644 index 0000000..87dbc05 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/rock035/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/rock035/normal.webp b/assets/starter/2d/textures-ambientcg/stone/rock035/normal.webp new file mode 100644 index 0000000..e6b9100 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/rock035/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/rock035/roughness.webp b/assets/starter/2d/textures-ambientcg/stone/rock035/roughness.webp new file mode 100644 index 0000000..5c4ec57 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/rock035/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/travertine001/color.webp b/assets/starter/2d/textures-ambientcg/stone/travertine001/color.webp new file mode 100644 index 0000000..5c6785c Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/travertine001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/travertine001/normal.webp b/assets/starter/2d/textures-ambientcg/stone/travertine001/normal.webp new file mode 100644 index 0000000..00e81ea Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/travertine001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/stone/travertine001/roughness.webp b/assets/starter/2d/textures-ambientcg/stone/travertine001/roughness.webp new file mode 100644 index 0000000..6903004 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/stone/travertine001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/pavingstones070/color.webp b/assets/starter/2d/textures-ambientcg/tiles/pavingstones070/color.webp new file mode 100644 index 0000000..32d4f09 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/pavingstones070/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/pavingstones070/normal.webp b/assets/starter/2d/textures-ambientcg/tiles/pavingstones070/normal.webp new file mode 100644 index 0000000..d5d3aad Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/pavingstones070/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/pavingstones070/roughness.webp b/assets/starter/2d/textures-ambientcg/tiles/pavingstones070/roughness.webp new file mode 100644 index 0000000..5ef5aa7 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/pavingstones070/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/roofingtiles003/color.webp b/assets/starter/2d/textures-ambientcg/tiles/roofingtiles003/color.webp new file mode 100644 index 0000000..decd8ab Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/roofingtiles003/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/roofingtiles003/normal.webp b/assets/starter/2d/textures-ambientcg/tiles/roofingtiles003/normal.webp new file mode 100644 index 0000000..9d78192 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/roofingtiles003/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/roofingtiles003/roughness.webp b/assets/starter/2d/textures-ambientcg/tiles/roofingtiles003/roughness.webp new file mode 100644 index 0000000..768f9e0 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/roofingtiles003/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/terrazzo003/color.webp b/assets/starter/2d/textures-ambientcg/tiles/terrazzo003/color.webp new file mode 100644 index 0000000..ba743a7 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/terrazzo003/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/terrazzo003/normal.webp b/assets/starter/2d/textures-ambientcg/tiles/terrazzo003/normal.webp new file mode 100644 index 0000000..afa9fa0 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/terrazzo003/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/terrazzo003/roughness.webp b/assets/starter/2d/textures-ambientcg/tiles/terrazzo003/roughness.webp new file mode 100644 index 0000000..94ead99 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/terrazzo003/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles074/color.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles074/color.webp new file mode 100644 index 0000000..5bdf9ce Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles074/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles074/normal.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles074/normal.webp new file mode 100644 index 0000000..d7b5259 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles074/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles074/roughness.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles074/roughness.webp new file mode 100644 index 0000000..ef77ec6 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles074/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles093/color.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles093/color.webp new file mode 100644 index 0000000..217fb41 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles093/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles093/normal.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles093/normal.webp new file mode 100644 index 0000000..ae916fa Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles093/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles093/roughness.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles093/roughness.webp new file mode 100644 index 0000000..21f9236 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles093/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles101/color.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles101/color.webp new file mode 100644 index 0000000..9f50eb7 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles101/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles101/normal.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles101/normal.webp new file mode 100644 index 0000000..46fea8a Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles101/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles101/roughness.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles101/roughness.webp new file mode 100644 index 0000000..bfd27ea Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles101/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles107/color.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles107/color.webp new file mode 100644 index 0000000..3c4e42b Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles107/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles107/normal.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles107/normal.webp new file mode 100644 index 0000000..cfd9db5 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles107/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/tiles/tiles107/roughness.webp b/assets/starter/2d/textures-ambientcg/tiles/tiles107/roughness.webp new file mode 100644 index 0000000..af17b5b Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/tiles/tiles107/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/bark001/color.webp b/assets/starter/2d/textures-ambientcg/wood/bark001/color.webp new file mode 100644 index 0000000..b9c3d44 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/bark001/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/bark001/normal.webp b/assets/starter/2d/textures-ambientcg/wood/bark001/normal.webp new file mode 100644 index 0000000..c6fdaf1 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/bark001/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/bark001/roughness.webp b/assets/starter/2d/textures-ambientcg/wood/bark001/roughness.webp new file mode 100644 index 0000000..052fa82 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/bark001/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/planks012/color.webp b/assets/starter/2d/textures-ambientcg/wood/planks012/color.webp new file mode 100644 index 0000000..071c8b3 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/planks012/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/planks012/normal.webp b/assets/starter/2d/textures-ambientcg/wood/planks012/normal.webp new file mode 100644 index 0000000..4091a7b Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/planks012/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/planks012/roughness.webp b/assets/starter/2d/textures-ambientcg/wood/planks012/roughness.webp new file mode 100644 index 0000000..a72cbda Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/planks012/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/wood049/color.webp b/assets/starter/2d/textures-ambientcg/wood/wood049/color.webp new file mode 100644 index 0000000..05dd974 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/wood049/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/wood049/normal.webp b/assets/starter/2d/textures-ambientcg/wood/wood049/normal.webp new file mode 100644 index 0000000..550a709 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/wood049/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/wood049/roughness.webp b/assets/starter/2d/textures-ambientcg/wood/wood049/roughness.webp new file mode 100644 index 0000000..a8bcbf5 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/wood049/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/wood051/color.webp b/assets/starter/2d/textures-ambientcg/wood/wood051/color.webp new file mode 100644 index 0000000..10e71bc Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/wood051/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/wood051/normal.webp b/assets/starter/2d/textures-ambientcg/wood/wood051/normal.webp new file mode 100644 index 0000000..92f611b Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/wood051/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/wood051/roughness.webp b/assets/starter/2d/textures-ambientcg/wood/wood051/roughness.webp new file mode 100644 index 0000000..0aa6a16 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/wood051/roughness.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/woodfloor040/color.webp b/assets/starter/2d/textures-ambientcg/wood/woodfloor040/color.webp new file mode 100644 index 0000000..4b9f1aa Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/woodfloor040/color.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/woodfloor040/normal.webp b/assets/starter/2d/textures-ambientcg/wood/woodfloor040/normal.webp new file mode 100644 index 0000000..d9bbf6c Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/woodfloor040/normal.webp differ diff --git a/assets/starter/2d/textures-ambientcg/wood/woodfloor040/roughness.webp b/assets/starter/2d/textures-ambientcg/wood/woodfloor040/roughness.webp new file mode 100644 index 0000000..950fbe5 Binary files /dev/null and b/assets/starter/2d/textures-ambientcg/wood/woodfloor040/roughness.webp differ diff --git a/assets/starter/3d/polyhaven-models/ArmChair_01.glb b/assets/starter/3d/polyhaven-models/ArmChair_01.glb new file mode 100644 index 0000000..be62628 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/ArmChair_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/ArmChair_01.jpg b/assets/starter/3d/polyhaven-models/ArmChair_01.jpg new file mode 100644 index 0000000..67de7ce Binary files /dev/null and b/assets/starter/3d/polyhaven-models/ArmChair_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/Barrel_02.glb b/assets/starter/3d/polyhaven-models/Barrel_02.glb new file mode 100644 index 0000000..2ab3d7d Binary files /dev/null and b/assets/starter/3d/polyhaven-models/Barrel_02.glb differ diff --git a/assets/starter/3d/polyhaven-models/Barrel_02.jpg b/assets/starter/3d/polyhaven-models/Barrel_02.jpg new file mode 100644 index 0000000..c4affd7 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/Barrel_02.jpg differ diff --git a/assets/starter/3d/polyhaven-models/ClassicNightstand_01.glb b/assets/starter/3d/polyhaven-models/ClassicNightstand_01.glb new file mode 100644 index 0000000..386f632 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/ClassicNightstand_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/ClassicNightstand_01.jpg b/assets/starter/3d/polyhaven-models/ClassicNightstand_01.jpg new file mode 100644 index 0000000..664a7a3 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/ClassicNightstand_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/Drill_01.glb b/assets/starter/3d/polyhaven-models/Drill_01.glb new file mode 100644 index 0000000..ffad908 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/Drill_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/Drill_01.jpg b/assets/starter/3d/polyhaven-models/Drill_01.jpg new file mode 100644 index 0000000..3ce8932 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/Drill_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/LICENSE.txt b/assets/starter/3d/polyhaven-models/LICENSE.txt new file mode 100644 index 0000000..95df7f2 --- /dev/null +++ b/assets/starter/3d/polyhaven-models/LICENSE.txt @@ -0,0 +1,11 @@ +Source: https://polyhaven.com/license +Fetched: 2026-11-29 + +Asset License All assets ( HDRIs , textures and 3D models ) on this site are the original work of Poly Haven staff, or artists who willingly and directly donate/sell their work to Poly Haven. Our assets are all licensed as CC0 , which is effectively Public Domain even in jurisdictions that do not support the Public Domain. Here's an excerpt from the CC0 FAQ page to clarify: Once the creator or a subsequent owner of a work applies CC0 to a work, the work is no longer his or hers in any meaningful sense under copyright law. Anyone can then use the work in any way and for any purpose, including commercial purposes [...] Think of CC0 as the "no rights reserved" option. CC0 is a useful tool for clarifying that you do not claim copyright in a work anywhere in the world. In other words: You can use our assets for any purpose , including commercial work. You do not need to give credit or attribution when using them (although it is appreciated). You can redistribute them , share them around, include them when sharing your own work, or even in a product you sell. More info: CC0 summary , CC0 wiki , CC0 FAQ . + +[...] + +4. Intellectual Property 4.1. All content on this website, excluding the CC0 assets themselves, is protected by intellectual property laws. You may not reproduce, distribute, or otherwise use this content without prior written permission from the website or intellectual property owner. 4.2. Examples of such content includes but is not limited to: Logos User avatar images Asset example renders User submitted renders Text and copy + +Per-item confirmation: each asset page https://polyhaven.com/a/<id> names the licence CC0 (schema.org license http://creativecommons.org/publicdomain/zero/1.0/, "CC0 1.0 Universal - public domain dedication, no attribution required"). +Previews (<id>.jpg) are rendered by FormCraft tooling from the CC0 asset files; no Poly Haven example renders are included. diff --git a/assets/starter/3d/polyhaven-models/Megaphone_01.glb b/assets/starter/3d/polyhaven-models/Megaphone_01.glb new file mode 100644 index 0000000..70b57e6 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/Megaphone_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/Megaphone_01.jpg b/assets/starter/3d/polyhaven-models/Megaphone_01.jpg new file mode 100644 index 0000000..85f9e5b Binary files /dev/null and b/assets/starter/3d/polyhaven-models/Megaphone_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/SchoolChair_01.glb b/assets/starter/3d/polyhaven-models/SchoolChair_01.glb new file mode 100644 index 0000000..409b6e5 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/SchoolChair_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/SchoolChair_01.jpg b/assets/starter/3d/polyhaven-models/SchoolChair_01.jpg new file mode 100644 index 0000000..7ea9abd Binary files /dev/null and b/assets/starter/3d/polyhaven-models/SchoolChair_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/SchoolDesk_01.glb b/assets/starter/3d/polyhaven-models/SchoolDesk_01.glb new file mode 100644 index 0000000..4583fc2 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/SchoolDesk_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/SchoolDesk_01.jpg b/assets/starter/3d/polyhaven-models/SchoolDesk_01.jpg new file mode 100644 index 0000000..7479364 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/SchoolDesk_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/Television_01.glb b/assets/starter/3d/polyhaven-models/Television_01.glb new file mode 100644 index 0000000..8b33a51 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/Television_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/Television_01.jpg b/assets/starter/3d/polyhaven-models/Television_01.jpg new file mode 100644 index 0000000..1b93b96 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/Television_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/WetFloorSign_01.glb b/assets/starter/3d/polyhaven-models/WetFloorSign_01.glb new file mode 100644 index 0000000..ef9fffd Binary files /dev/null and b/assets/starter/3d/polyhaven-models/WetFloorSign_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/WetFloorSign_01.jpg b/assets/starter/3d/polyhaven-models/WetFloorSign_01.jpg new file mode 100644 index 0000000..79bb458 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/WetFloorSign_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/brass_vase_04.glb b/assets/starter/3d/polyhaven-models/brass_vase_04.glb new file mode 100644 index 0000000..77958dc Binary files /dev/null and b/assets/starter/3d/polyhaven-models/brass_vase_04.glb differ diff --git a/assets/starter/3d/polyhaven-models/brass_vase_04.jpg b/assets/starter/3d/polyhaven-models/brass_vase_04.jpg new file mode 100644 index 0000000..8b566bf Binary files /dev/null and b/assets/starter/3d/polyhaven-models/brass_vase_04.jpg differ diff --git a/assets/starter/3d/polyhaven-models/ceramic_vase_01.glb b/assets/starter/3d/polyhaven-models/ceramic_vase_01.glb new file mode 100644 index 0000000..862e0d1 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/ceramic_vase_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/ceramic_vase_01.jpg b/assets/starter/3d/polyhaven-models/ceramic_vase_01.jpg new file mode 100644 index 0000000..73119dc Binary files /dev/null and b/assets/starter/3d/polyhaven-models/ceramic_vase_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/flower_empodium.glb b/assets/starter/3d/polyhaven-models/flower_empodium.glb new file mode 100644 index 0000000..e4c4aee Binary files /dev/null and b/assets/starter/3d/polyhaven-models/flower_empodium.glb differ diff --git a/assets/starter/3d/polyhaven-models/flower_empodium.jpg b/assets/starter/3d/polyhaven-models/flower_empodium.jpg new file mode 100644 index 0000000..4265bb9 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/flower_empodium.jpg differ diff --git a/assets/starter/3d/polyhaven-models/food_apple_01.glb b/assets/starter/3d/polyhaven-models/food_apple_01.glb new file mode 100644 index 0000000..71f2a76 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/food_apple_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/food_apple_01.jpg b/assets/starter/3d/polyhaven-models/food_apple_01.jpg new file mode 100644 index 0000000..35e782b Binary files /dev/null and b/assets/starter/3d/polyhaven-models/food_apple_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/food_avocado_01.glb b/assets/starter/3d/polyhaven-models/food_avocado_01.glb new file mode 100644 index 0000000..830908d Binary files /dev/null and b/assets/starter/3d/polyhaven-models/food_avocado_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/food_avocado_01.jpg b/assets/starter/3d/polyhaven-models/food_avocado_01.jpg new file mode 100644 index 0000000..8d1515b Binary files /dev/null and b/assets/starter/3d/polyhaven-models/food_avocado_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/food_lime_01.glb b/assets/starter/3d/polyhaven-models/food_lime_01.glb new file mode 100644 index 0000000..8ceabb6 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/food_lime_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/food_lime_01.jpg b/assets/starter/3d/polyhaven-models/food_lime_01.jpg new file mode 100644 index 0000000..664f875 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/food_lime_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/food_pomegranate_01.glb b/assets/starter/3d/polyhaven-models/food_pomegranate_01.glb new file mode 100644 index 0000000..adf430c Binary files /dev/null and b/assets/starter/3d/polyhaven-models/food_pomegranate_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/food_pomegranate_01.jpg b/assets/starter/3d/polyhaven-models/food_pomegranate_01.jpg new file mode 100644 index 0000000..987bb20 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/food_pomegranate_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/grass_medium_02.glb b/assets/starter/3d/polyhaven-models/grass_medium_02.glb new file mode 100644 index 0000000..deaceb1 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/grass_medium_02.glb differ diff --git a/assets/starter/3d/polyhaven-models/grass_medium_02.jpg b/assets/starter/3d/polyhaven-models/grass_medium_02.jpg new file mode 100644 index 0000000..08e1913 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/grass_medium_02.jpg differ diff --git a/assets/starter/3d/polyhaven-models/hanging_picture_frame_01.glb b/assets/starter/3d/polyhaven-models/hanging_picture_frame_01.glb new file mode 100644 index 0000000..2663de6 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/hanging_picture_frame_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/hanging_picture_frame_01.jpg b/assets/starter/3d/polyhaven-models/hanging_picture_frame_01.jpg new file mode 100644 index 0000000..8d20b83 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/hanging_picture_frame_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/magnifying_glass_01.glb b/assets/starter/3d/polyhaven-models/magnifying_glass_01.glb new file mode 100644 index 0000000..bef6fa5 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/magnifying_glass_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/magnifying_glass_01.jpg b/assets/starter/3d/polyhaven-models/magnifying_glass_01.jpg new file mode 100644 index 0000000..7c10ca1 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/magnifying_glass_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/measuring_tape_01.glb b/assets/starter/3d/polyhaven-models/measuring_tape_01.glb new file mode 100644 index 0000000..14b747e Binary files /dev/null and b/assets/starter/3d/polyhaven-models/measuring_tape_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/measuring_tape_01.jpg b/assets/starter/3d/polyhaven-models/measuring_tape_01.jpg new file mode 100644 index 0000000..c28563b Binary files /dev/null and b/assets/starter/3d/polyhaven-models/measuring_tape_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/modern_ceiling_lamp_01.glb b/assets/starter/3d/polyhaven-models/modern_ceiling_lamp_01.glb new file mode 100644 index 0000000..32772e5 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/modern_ceiling_lamp_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/modern_ceiling_lamp_01.jpg b/assets/starter/3d/polyhaven-models/modern_ceiling_lamp_01.jpg new file mode 100644 index 0000000..5303f23 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/modern_ceiling_lamp_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/moss_01.glb b/assets/starter/3d/polyhaven-models/moss_01.glb new file mode 100644 index 0000000..0f37e02 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/moss_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/moss_01.jpg b/assets/starter/3d/polyhaven-models/moss_01.jpg new file mode 100644 index 0000000..452f036 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/moss_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/pack.json b/assets/starter/3d/polyhaven-models/pack.json new file mode 100644 index 0000000..1759c60 --- /dev/null +++ b/assets/starter/3d/polyhaven-models/pack.json @@ -0,0 +1,761 @@ +{ + "id": "polyhaven-models", + "name": "3D models (Poly Haven)", + "kind": "model", + "licence": "CC0-1.0", + "author": "Poly Haven (polyhaven.com) artists: Ethan Place, Ethan Simon-Law, Fernando Quinn, Fran Calvente, Gabriel Radi\u0107, James Ray Cock, Jenelle van Heerden, Jorge Camacho, Kirill Sannikov, Kuutti Siitonen, Nazar Borodavka, Oliver Harries, Plat251, Rico Cilliers, Rob Tuytel, Ulan Cabanilla", + "source_url": "https://polyhaven.com/models", + "source_commit_or_version": "api.polyhaven.com snapshot, 1k glTF packed to single GLB (buffers and JPEG textures embedded byte for byte) plus 512 px JPEG previews rendered by FormCraft tooling from the asset itself (Poly Haven example renders are excluded from CC0 by its ToS 4.2), retrieved 2026-11-29", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/<item id> (per item, see items[].licence_evidence)" + ], + "items": [ + { + "id": "WetFloorSign_01", + "name": "Wet Floor Sign 01", + "file": "WetFloorSign_01.glb", + "preview": "WetFloorSign_01.jpg", + "category": "props", + "tags": [ + "glb", + "pbr", + "1k", + "props", + "industrial", + "office", + "prop", + "plastic", + "sign", + "safety", + "caution", + "warning", + "by:Fran Calvente" + ], + "bytes": 265468, + "source_page": "https://polyhaven.com/a/WetFloorSign_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/WetFloorSign_01" + ] + }, + { + "id": "brass_vase_04", + "name": "Brass Vase 04", + "file": "brass_vase_04.glb", + "preview": "brass_vase_04.jpg", + "category": "containers", + "tags": [ + "glb", + "pbr", + "1k", + "containers", + "props", + "vases", + "dishes", + "vintage", + "fancy", + "metal", + "brass", + "copper", + "by:Rico Cilliers" + ], + "bytes": 393412, + "source_page": "https://polyhaven.com/a/brass_vase_04", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/brass_vase_04" + ] + }, + { + "id": "hanging_picture_frame_01", + "name": "Hanging Picture Frame 01", + "file": "hanging_picture_frame_01.glb", + "preview": "hanging_picture_frame_01.jpg", + "category": "decorative", + "tags": [ + "glb", + "pbr", + "1k", + "decorative", + "wall decoration", + "modern", + "minimalist", + "clean", + "frame", + "simple", + "art", + "by:James Ray Cock" + ], + "bytes": 483420, + "source_page": "https://polyhaven.com/a/hanging_picture_frame_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/hanging_picture_frame_01" + ] + }, + { + "id": "small_wooden_table_01", + "name": "Small Wooden Table 01", + "file": "small_wooden_table_01.glb", + "preview": "small_wooden_table_01.jpg", + "category": "furniture", + "tags": [ + "glb", + "pbr", + "1k", + "furniture", + "table", + "vintage", + "wood", + "small", + "wooden", + "by:Ulan Cabanilla" + ], + "bytes": 413764, + "source_page": "https://polyhaven.com/a/small_wooden_table_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/small_wooden_table_01" + ] + }, + { + "id": "ceramic_vase_01", + "name": "Ceramic Vase 01", + "file": "ceramic_vase_01.glb", + "preview": "ceramic_vase_01.jpg", + "category": "vases", + "tags": [ + "glb", + "pbr", + "1k", + "vases", + "containers", + "decorative", + "pot", + "clean", + "tall", + "modern", + "fancy", + "decor", + "by:James Ray Cock" + ], + "bytes": 417476, + "source_page": "https://polyhaven.com/a/ceramic_vase_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/ceramic_vase_01" + ] + }, + { + "id": "Barrel_02", + "name": "Barrel 02", + "file": "Barrel_02.glb", + "preview": "Barrel_02.jpg", + "category": "industrial", + "tags": [ + "glb", + "pbr", + "1k", + "industrial", + "containers", + "barrel", + "water", + "plastic", + "garage", + "warehouse", + "storage", + "drums", + "by:Jorge Camacho" + ], + "bytes": 420564, + "source_page": "https://polyhaven.com/a/Barrel_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/Barrel_02" + ] + }, + { + "id": "SchoolDesk_01", + "name": "School Desk 01", + "file": "SchoolDesk_01.glb", + "preview": "SchoolDesk_01.jpg", + "category": "furniture", + "tags": [ + "glb", + "pbr", + "1k", + "furniture", + "table", + "school", + "desk", + "wood", + "metal", + "classroom", + "student", + "single-seat", + "by:Ethan Place" + ], + "bytes": 420656, + "source_page": "https://polyhaven.com/a/SchoolDesk_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/SchoolDesk_01" + ] + }, + { + "id": "sofa_02", + "name": "Sofa 02", + "file": "sofa_02.glb", + "preview": "sofa_02.jpg", + "category": "furniture", + "tags": [ + "glb", + "pbr", + "1k", + "furniture", + "seating", + "wood", + "chair", + "prop", + "couch", + "leather", + "fabric", + "by:Kirill Sannikov" + ], + "bytes": 425580, + "source_page": "https://polyhaven.com/a/sofa_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/sofa_02" + ] + }, + { + "id": "modern_ceiling_lamp_01", + "name": "Modern Ceiling Lamp 01", + "file": "modern_ceiling_lamp_01.glb", + "preview": "modern_ceiling_lamp_01.jpg", + "category": "lighting", + "tags": [ + "glb", + "pbr", + "1k", + "lighting", + "light", + "modern", + "glass", + "round", + "hanging", + "hanging lamp", + "ceiling lamp", + "decorative lighting", + "by:James Ray Cock" + ], + "bytes": 433620, + "source_page": "https://polyhaven.com/a/modern_ceiling_lamp_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/modern_ceiling_lamp_01" + ] + }, + { + "id": "ClassicNightstand_01", + "name": "Classic Nightstand 01", + "file": "ClassicNightstand_01.glb", + "preview": "ClassicNightstand_01.jpg", + "category": "furniture", + "tags": [ + "glb", + "pbr", + "1k", + "furniture", + "table", + "wood", + "vintage", + "gothic", + "victorian", + "decorative", + "by:Kirill Sannikov" + ], + "bytes": 443948, + "source_page": "https://polyhaven.com/a/ClassicNightstand_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/ClassicNightstand_01" + ] + }, + { + "id": "measuring_tape_01", + "name": "Measuring Tape 01", + "file": "measuring_tape_01.glb", + "preview": "measuring_tape_01.jpg", + "category": "industrial", + "tags": [ + "glb", + "pbr", + "1k", + "industrial", + "tools", + "props", + "tape", + "ruler", + "measure", + "tool", + "toolbox", + "woodwork", + "by:Kuutti Siitonen" + ], + "bytes": 445000, + "source_page": "https://polyhaven.com/a/measuring_tape_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/measuring_tape_01" + ] + }, + { + "id": "magnifying_glass_01", + "name": "Magnifying Glass 01", + "file": "magnifying_glass_01.glb", + "preview": "magnifying_glass_01.jpg", + "category": "props", + "tags": [ + "glb", + "pbr", + "1k", + "props", + "tools", + "eye", + "focal", + "lense", + "magnifier", + "magnifying lens", + "inspection", + "optical tool", + "by:Nazar Borodavka" + ], + "bytes": 486476, + "source_page": "https://polyhaven.com/a/magnifying_glass_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/magnifying_glass_01" + ] + }, + { + "id": "wooden_display_shelves_01", + "name": "Wooden Display Shelves 01", + "file": "wooden_display_shelves_01.glb", + "preview": "wooden_display_shelves_01.jpg", + "category": "furniture", + "tags": [ + "glb", + "pbr", + "1k", + "furniture", + "shelves", + "modern", + "wood", + "pine", + "square", + "display", + "shelf", + "bookshelf", + "by:James Ray Cock" + ], + "bytes": 468428, + "source_page": "https://polyhaven.com/a/wooden_display_shelves_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/wooden_display_shelves_01" + ] + }, + { + "id": "food_apple_01", + "name": "Food Apple 01", + "file": "food_apple_01.glb", + "preview": "food_apple_01.jpg", + "category": "food", + "tags": [ + "glb", + "pbr", + "1k", + "food", + "nature", + "fruit", + "apple", + "fruitbowl", + "red", + "ripe", + "fresh", + "organic", + "by:Oliver Harries" + ], + "bytes": 472828, + "source_page": "https://polyhaven.com/a/food_apple_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/food_apple_01" + ] + }, + { + "id": "SchoolChair_01", + "name": "School Chair 01", + "file": "SchoolChair_01.glb", + "preview": "SchoolChair_01.jpg", + "category": "furniture", + "tags": [ + "glb", + "pbr", + "1k", + "furniture", + "seating", + "prop", + "metal", + "plastic", + "chair", + "school", + "by:Ethan Place" + ], + "bytes": 483748, + "source_page": "https://polyhaven.com/a/SchoolChair_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/SchoolChair_01" + ] + }, + { + "id": "painted_wooden_chair_01", + "name": "Painted Wooden Chair 01", + "file": "painted_wooden_chair_01.glb", + "preview": "painted_wooden_chair_01.jpg", + "category": "furniture", + "tags": [ + "glb", + "pbr", + "1k", + "furniture", + "seating", + "chair", + "wood", + "painted", + "farmhouse", + "dining", + "diner", + "american", + "by:Kuutti Siitonen" + ], + "bytes": 491540, + "source_page": "https://polyhaven.com/a/painted_wooden_chair_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/painted_wooden_chair_01" + ] + }, + { + "id": "Drill_01", + "name": "Drill 01", + "file": "Drill_01.glb", + "preview": "Drill_01.jpg", + "category": "props", + "tags": [ + "glb", + "pbr", + "1k", + "props", + "tools", + "electronics", + "metal", + "plastic", + "tool", + "drill", + "prop", + "by:Fernando Quinn" + ], + "bytes": 500116, + "source_page": "https://polyhaven.com/a/Drill_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/Drill_01" + ] + }, + { + "id": "Television_01", + "name": "Television 01", + "file": "Television_01.glb", + "preview": "Television_01.jpg", + "category": "props", + "tags": [ + "glb", + "pbr", + "1k", + "props", + "electronics", + "vintage", + "prop", + "furniture", + "metal", + "wood", + "tv", + "television", + "by:Gabriel Radi\u0107" + ], + "bytes": 530224, + "source_page": "https://polyhaven.com/a/Television_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/Television_01" + ] + }, + { + "id": "food_avocado_01", + "name": "Food Avocado 01", + "file": "food_avocado_01.glb", + "preview": "food_avocado_01.jpg", + "category": "food", + "tags": [ + "glb", + "pbr", + "1k", + "food", + "nature", + "fruit", + "fruitbowl", + "avo", + "dark", + "ripe", + "by:Oliver Harries" + ], + "bytes": 584180, + "source_page": "https://polyhaven.com/a/food_avocado_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/food_avocado_01" + ] + }, + { + "id": "food_lime_01", + "name": "Food Lime 01", + "file": "food_lime_01.glb", + "preview": "food_lime_01.jpg", + "category": "food", + "tags": [ + "glb", + "pbr", + "1k", + "food", + "nature", + "fruit", + "fruitbowl", + "lemon", + "lime", + "citrus", + "green", + "fresh", + "by:Oliver Harries" + ], + "bytes": 578324, + "source_page": "https://polyhaven.com/a/food_lime_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/food_lime_01" + ] + }, + { + "id": "food_pomegranate_01", + "name": "Food Pomegranate 01", + "file": "food_pomegranate_01.glb", + "preview": "food_pomegranate_01.jpg", + "category": "food", + "tags": [ + "glb", + "pbr", + "1k", + "food", + "nature", + "fruit", + "fruitbowl", + "red", + "pomegranite", + "produce", + "fresh fruit", + "ripe", + "by:Oliver Harries" + ], + "bytes": 609840, + "source_page": "https://polyhaven.com/a/food_pomegranate_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/food_pomegranate_01" + ] + }, + { + "id": "rubber_duck_toy", + "name": "Rubber Duck Toy", + "file": "rubber_duck_toy.glb", + "preview": "rubber_duck_toy.jpg", + "category": "props", + "tags": [ + "glb", + "pbr", + "1k", + "props", + "decorative", + "shed", + "toy", + "bathroom", + "child", + "home", + "fun", + "kids", + "by:Plat251" + ], + "bytes": 733900, + "source_page": "https://polyhaven.com/a/rubber_duck_toy", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/rubber_duck_toy" + ] + }, + { + "id": "ArmChair_01", + "name": "Arm Chair 01", + "file": "ArmChair_01.glb", + "preview": "ArmChair_01.jpg", + "category": "furniture", + "tags": [ + "glb", + "pbr", + "1k", + "furniture", + "seating", + "gothic", + "vintage", + "chair", + "victorian", + "couch", + "wood", + "varnished", + "by:Kirill Sannikov" + ], + "bytes": 768184, + "source_page": "https://polyhaven.com/a/ArmChair_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/ArmChair_01" + ] + }, + { + "id": "Megaphone_01", + "name": "Megaphone 01", + "file": "Megaphone_01.glb", + "preview": "Megaphone_01.jpg", + "category": "props", + "tags": [ + "glb", + "pbr", + "1k", + "props", + "electronics", + "tools", + "plastic", + "megaphone", + "device", + "audio", + "amplifier", + "loudspeaker", + "by:Ethan Simon-Law" + ], + "bytes": 775196, + "source_page": "https://polyhaven.com/a/Megaphone_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/Megaphone_01" + ] + }, + { + "id": "grass_medium_02", + "name": "Grass Medium 02", + "file": "grass_medium_02.glb", + "preview": "grass_medium_02.jpg", + "category": "nature", + "tags": [ + "glb", + "pbr", + "1k", + "nature", + "ground cover", + "grass", + "plants", + "field", + "meadow", + "shrub", + "small", + "green", + "by:Rico Cilliers" + ], + "bytes": 797904, + "source_page": "https://polyhaven.com/a/grass_medium_02", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/grass_medium_02" + ] + }, + { + "id": "flower_empodium", + "name": "Flower Empodium", + "file": "flower_empodium.glb", + "preview": "flower_empodium.jpg", + "category": "nature", + "tags": [ + "glb", + "pbr", + "1k", + "nature", + "plants", + "flowers", + "ground cover", + "karoo", + "field", + "yellow", + "floral", + "wildflower", + "by:Jenelle van Heerden", + "by:Rico Cilliers" + ], + "bytes": 894656, + "source_page": "https://polyhaven.com/a/flower_empodium", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/flower_empodium" + ] + }, + { + "id": "moss_01", + "name": "Moss 01", + "file": "moss_01.glb", + "preview": "moss_01.jpg", + "category": "nature", + "tags": [ + "glb", + "pbr", + "1k", + "nature", + "plants", + "ground cover", + "moss", + "forest", + "woodland", + "foliage", + "plant", + "natural", + "by:Rob Tuytel" + ], + "bytes": 913380, + "source_page": "https://polyhaven.com/a/moss_01", + "licence_evidence": [ + "https://polyhaven.com/license", + "https://polyhaven.com/a/moss_01" + ] + } + ] +} \ No newline at end of file diff --git a/assets/starter/3d/polyhaven-models/painted_wooden_chair_01.glb b/assets/starter/3d/polyhaven-models/painted_wooden_chair_01.glb new file mode 100644 index 0000000..63b4bed Binary files /dev/null and b/assets/starter/3d/polyhaven-models/painted_wooden_chair_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/painted_wooden_chair_01.jpg b/assets/starter/3d/polyhaven-models/painted_wooden_chair_01.jpg new file mode 100644 index 0000000..52c4981 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/painted_wooden_chair_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/rubber_duck_toy.glb b/assets/starter/3d/polyhaven-models/rubber_duck_toy.glb new file mode 100644 index 0000000..7fdbc9b Binary files /dev/null and b/assets/starter/3d/polyhaven-models/rubber_duck_toy.glb differ diff --git a/assets/starter/3d/polyhaven-models/rubber_duck_toy.jpg b/assets/starter/3d/polyhaven-models/rubber_duck_toy.jpg new file mode 100644 index 0000000..a27abbe Binary files /dev/null and b/assets/starter/3d/polyhaven-models/rubber_duck_toy.jpg differ diff --git a/assets/starter/3d/polyhaven-models/small_wooden_table_01.glb b/assets/starter/3d/polyhaven-models/small_wooden_table_01.glb new file mode 100644 index 0000000..ffb0c2d Binary files /dev/null and b/assets/starter/3d/polyhaven-models/small_wooden_table_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/small_wooden_table_01.jpg b/assets/starter/3d/polyhaven-models/small_wooden_table_01.jpg new file mode 100644 index 0000000..dea2aba Binary files /dev/null and b/assets/starter/3d/polyhaven-models/small_wooden_table_01.jpg differ diff --git a/assets/starter/3d/polyhaven-models/sofa_02.glb b/assets/starter/3d/polyhaven-models/sofa_02.glb new file mode 100644 index 0000000..fbd467c Binary files /dev/null and b/assets/starter/3d/polyhaven-models/sofa_02.glb differ diff --git a/assets/starter/3d/polyhaven-models/sofa_02.jpg b/assets/starter/3d/polyhaven-models/sofa_02.jpg new file mode 100644 index 0000000..570133a Binary files /dev/null and b/assets/starter/3d/polyhaven-models/sofa_02.jpg differ diff --git a/assets/starter/3d/polyhaven-models/wooden_display_shelves_01.glb b/assets/starter/3d/polyhaven-models/wooden_display_shelves_01.glb new file mode 100644 index 0000000..4029103 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/wooden_display_shelves_01.glb differ diff --git a/assets/starter/3d/polyhaven-models/wooden_display_shelves_01.jpg b/assets/starter/3d/polyhaven-models/wooden_display_shelves_01.jpg new file mode 100644 index 0000000..0939241 Binary files /dev/null and b/assets/starter/3d/polyhaven-models/wooden_display_shelves_01.jpg differ diff --git a/assets/starter/CREDITS.md b/assets/starter/CREDITS.md new file mode 100644 index 0000000..063cccb --- /dev/null +++ b/assets/starter/CREDITS.md @@ -0,0 +1,25 @@ +# Starter library credits + +All starter content bundled with formcraft is released under **CC0 1.0 Universal** (public domain dedication). You may copy, change and use it for any purpose, commercial or not, without asking and without credit. formcraft credits the sources here anyway, and records the licence, author and source on each library item you add from the starter library. + +This file is written by a small script from the 17 `pack.json` files in `assets/starter/` (653 items, 115.0 MB on disk). Each pack folder holds its own `LICENSE.txt`, which starts with the licence statements as fetched from the publisher, their URLs and the date. "Evidence" lists the two (or more) independent pages that state the licence; "Items" counts the entries in `pack.json`; "Size" is the whole pack folder. + +| Pack | Folder | Kind | Author | Licence | Source | Evidence | Items | Size | Retrieved | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| Reference photographs and objects (Art Institute of Chicago Open Access) | `2d/images-artic-cc0` | image | The Art Institute of Chicago (public-domain works; CC0 per item, artist and reference number in tags) | CC0-1.0 | https://www.artic.edu/open-access/open-access-images | https://www.artic.edu/open-access/open-access-images; https://api.artic.edu/api/v1/artworks/{id} (per item: is_public_domain=true, copyright_notice empty; response licence note: all data except description is CC0 1.0) | 43 | 5.3 MB | 2026-11-29 | +| Reference images (Cleveland Museum of Art Open Access) | `2d/images-cleveland-cc0` | image | The Cleveland Museum of Art (public-domain works; CC0 per item, artist and accession in tags) | CC0-1.0 | https://www.clevelandart.org/open-access | https://www.clevelandart.org/open-access; https://openaccess-api.clevelandart.org/api/artworks/?accession_number=1984.59 | 41 | 1.6 MB | 2026-11-28 | +| Reference photographs (Cleveland Museum of Art Open Access) | `2d/images-cleveland-photos-cc0` | image | The Cleveland Museum of Art (public-domain photographs; CC0 per item, photographer and accession in tags) | CC0-1.0 | https://www.clevelandart.org/open-access | https://www.clevelandart.org/open-access; https://openaccess-api.clevelandart.org/api/artworks/?cc0&type=Photograph (per item: share_license_status=CC0, copyright=null; record URL in source_page) | 41 | 8.8 MB | 2026-11-29 | +| Reference photographs and objects (The Met Open Access) | `2d/images-met-cc0` | image | The Metropolitan Museum of Art (public-domain works; CC0 per item, artist and accession in tags) | CC0-1.0 | https://www.metmuseum.org/about-the-met/policies-and-documents/open-access | https://www.metmuseum.org/about-the-met/policies-and-documents/open-access; https://metmuseum.github.io/ | 33 | 6.9 MB | 2026-11-29 | +| Colour palettes (derived from ambientCG textures) | `2d/palettes-derived` | image | Derived by FormCraft build from ambientCG (ambientcg.com) CC0 textures; colours quantised from the colour maps | CC0-1.0 | https://ambientcg.com | https://docs.ambientcg.com/license/; https://ambientcg.com/view?id=Wood049 | 8 | 12 KB | 2026-11-28 | +| City and architecture photographs in colour (NegativeSpace) | `2d/photos-negativespace-cc0` | image | NegativeSpace (negativespace.co) | CC0-1.0 | https://negativespace.co/ | https://negativespace.co/license/; Each item source_page: description "Download the free ... photo ... with a CC0 license and use the image however and wherever you like." and license meta http://creativecommons.org/licenses/publicdomain/ | 10 | 3.6 MB | 2026-11-29 | +| HDRI environments (Poly Haven) | `2d/polyhaven-hdri` | hdri | Poly Haven (polyhaven.com) artists: Andreas Mischok, Dimitrios Savva, Greg Zaal, Grzegorz Wronkowski, Jarod Guest, Oliksiy Yakovlyev, Sergej Majboroda | CC0-1.0 | https://polyhaven.com/hdris | https://polyhaven.com/license; https://polyhaven.com/a/<item id> (per item, see items[].licence_evidence) | 16 | 20.6 MB | 2026-11-29 | +| PBR materials (Poly Haven) | `2d/polyhaven-textures` | texture | Poly Haven (polyhaven.com) artists: Amal Kumar, Charlotte Baglioni, Dario Barresi, Dimitrios Savva, Rico Cilliers, Rob Tuytel | CC0-1.0 | https://polyhaven.com/textures | https://polyhaven.com/license; https://polyhaven.com/a/<item id> (per item, see items[].licence_evidence) | 78 | 7.2 MB | 2026-11-29 | +| PBR textures (ambientCG) | `2d/textures-ambientcg` | texture | ambientCG (ambientcg.com) and its contributors | CC0-1.0 | https://ambientcg.com | https://docs.ambientcg.com/license/ (site-wide licence page, reached from https://ambientcg.com/license; states all ambientCG assets are CC0 1.0 Universal, fetched 2026-11-29); https://ambientcg.com/view?id=<AssetID> (each item's own page, listed per item as source_page; its FAQ states all assets are released under CC0; the API record https://ambientcg.com/api/v2/full_json?id=<AssetID>&include=downloadData confirmed each asset exists as a Material with a 1K-JPG download; fetched 2026-11-29) | 180 | 8.8 MB | 2026-11-29 | +| 3D models (Poly Haven) | `3d/polyhaven-models` | model | Poly Haven (polyhaven.com) artists: Ethan Place, Ethan Simon-Law, Fernando Quinn, Fran Calvente, Gabriel Radić, James Ray Cock, Jenelle van Heerden, Jorge Camacho, Kirill Sannikov, Kuutti Siitonen, Nazar Borodavka, Oliver Harries, Plat251, Rico Cilliers, Rob Tuytel, Ulan Cabanilla | CC0-1.0 | https://polyhaven.com/models | https://polyhaven.com/license; https://polyhaven.com/a/<item id> (per item, see items[].licence_evidence) | 27 | 14.4 MB | 2026-11-29 | +| FormCraft Synth Audio (original) | `audio/formcraft-synth-audio` | audio | NodeAgentc, Inc. (FormCraft) | CC0-1.0 | generated | https://creativecommons.org/publicdomain/zero/1.0/legalcode; https://creativecommons.org/publicdomain/zero/1.0/ | 19 | 819 KB | 2026-11-28 | +| graphite412 Foley and Field Recordings (CC0) | `audio/graphite412-foley-cc0` | audio | graphite412 (Electronica 4 God netlabel) | CC0-1.0 | https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools | https://archive.org/metadata/Djt002-Graphite412FoleyAndProductionTools; https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools; https://archive.org/metadata/Djt003-Graphite412FoleyAndProductionTools2; https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2; https://archive.org/metadata/Djt005-Graphite412Samplepack03; https://archive.org/details/Djt005-Graphite412Samplepack03 | 101 | 7.2 MB | 2026-11-29 | +| Komiku: It's time for adventure vol. 3 (CC0, excerpts) | `audio/komiku-childhood-scene-cc0` | audio | Komiku (Monplaisir), via the Hi Fidelity netlabel | CC0-1.0 | https://archive.org/details/Komiku01ChildhoodScene | https://archive.org/metadata/Komiku01ChildhoodScene; https://archive.org/details/Komiku01ChildhoodScene | 3 | 2.1 MB | 2026-11-29 | +| Jingles and Ditties (CC0) | `audio/ricohman-jingles-ditties-cc0` | audio | ricohman (made with Chaos von Eschenbach, 2000-2001) | CC0-1.0 | https://archive.org/details/jingles-ditties | https://archive.org/metadata/jingles-ditties; https://archive.org/details/jingles-ditties | 4 | 1.1 MB | 2026-11-29 | +| WinAAA BGM loops (CC0, excerpts) | `audio/winaaa-bgm-cc0` | audio | WinAAA | CC0-1.0 | https://archive.org/details/winaaa-bgm-cc0 | https://archive.org/metadata/winaaa-bgm-cc0; https://archive.org/details/winaaa-bgm-cc0 | 3 | 1.9 MB | 2026-11-29 | +| FormCraft Generated Video (original) | `video/formcraft-generated-video` | video | NodeAgentc, Inc. (FormCraft) | CC0-1.0 | generated | https://creativecommons.org/publicdomain/zero/1.0/legalcode; https://creativecommons.org/publicdomain/zero/1.0/ | 29 | 10.4 MB | 2026-11-28 | +| Prelinger Archives (public domain dedication, archival film excerpts) | `video/prelinger-archives-pd` | video | Prelinger Archives (films by various original producers; excerpts, audio removed) | CC-PD-Dedication-1.0-legacy | https://archive.org/details/prelinger | https://www.panix.com/~footage/prelarch.html; https://archive.org/metadata/prelinger/metadata | 17 | 14.3 MB | 2026-11-29 | diff --git a/assets/starter/README.md b/assets/starter/README.md new file mode 100644 index 0000000..ab9721c --- /dev/null +++ b/assets/starter/README.md @@ -0,0 +1,50 @@ +# Starter library + +Bundled CC0 1.0 assets that ship inside the desktop app and show in the Library under **Starter**. Everything here is public domain: free for any use, credit not required. + +## Layout + +``` +assets/starter/<section>/<pack>/ + pack.json facts about the pack and its items + LICENSE.txt the CC0 1.0 text or the source's own CC0 statement + <files> the assets, referenced from pack.json by a path inside the pack folder +``` + +Sections: `3d`, `2d`, `video`, `audio`. + +## pack.json + +``` +{"id", "name", "kind": "3d" | "texture" | "hdri" | "image" | "sprite" | "video" | "audio", + "licence": "CC0-1.0", "author", "source_url", "source_commit_or_version", "retrieved", "licence_evidence", + "items": [{"id", "name", "file", "category", "tags": [], "bytes", "seconds"?}]} +``` + +The engine (`backend/app/services/starter.py`) reads every `*/*/pack.json` at run time and skips, with a logged reason, any pack that is not CC0-1.0, lacks a field or a `LICENSE.txt`, and any item whose file is missing or outside its pack folder. A picture beside a file with the same stem (`.webp`, `.png` or `.jpg`) is used as its thumbnail; 3D files and HDRIs without one show a neutral placeholder. + +## Where it is found + +1. `FORMCRAFT_STARTER_DIR`, when set. +2. In the packaged app, the Tauri resource folder `starter/` (bundled by `bundle.resources` in `src-tauri/tauri.conf.json`): `Contents/Resources/starter` on macOS, beside the app on Windows, `/usr/lib/FormCraft/starter` on Linux. +3. From source, this folder. + +It is kept out of the PyInstaller engine on purpose: the Linux and Windows engines are one-file binaries that unpack their data on every start. + +## Size + +The folder is copied as is, so it adds its own size to every installer: run `du -sh assets/starter`. At the time of writing (17 packs, 653 items) that is 118 MB: 15 MB 3D, 65 MB 2D, 25 MB video, 14 MB audio. Installers compress it a little, as GLB, WebP, MP4 and OGG files are already compressed. + +## Grouping + +Texture files that share a `material:<name>` tag show as one item (the colour map), with the other maps listed under About this asset; Add to library adds every map and links them on the colour map's `meta.credit.maps`. A JPG that sits beside an `.hdr` or `.exr` of the same name is used as that HDRI's thumbnail and is not listed on its own. + +## 3D thumbnails + +A 3D item with no picture beside it is rendered once in the window (off screen, with the app's model viewer, paced to idle time), sent to `PUT /api/starter/items/{pack}/{item}/thumb` and kept in the app data folder under `thumbs/starter/`, so it is instant next time. Until then it shows a neutral placeholder. + +## Routes + +`GET /api/starter` (catalogue: `kind`, `category`, `pack`, `q`, `offset`, `limit`), `GET /api/starter/credits`, `GET /api/starter/items/{pack}/{item}` with `/file` (range requests) and `/thumb?w=`, `GET /api/starter/packs/{pack}/licence`, `POST /api/starter/items/{pack}/{item}/add` (copies the file into the library and records licence, author and source under `meta.credit` on the library item). + +Credits for each pack are in `CREDITS.md` and in the app under Help, About, Starter library credits. diff --git a/assets/starter/audio/formcraft-synth-audio/LICENSE.txt b/assets/starter/audio/formcraft-synth-audio/LICENSE.txt new file mode 100644 index 0000000..c89b5c3 --- /dev/null +++ b/assets/starter/audio/formcraft-synth-audio/LICENSE.txt @@ -0,0 +1,140 @@ +CC0 1.0 Universal (Public Domain Dedication) + +To the extent possible under law, NodeAgentc, Inc. (FormCraft) has waived all +copyright and related or neighboring rights to the files in this folder. +The files are original works generated procedurally for the FormCraft project. +They contain no third-party material and no recorded or sampled source files. + +You can copy, modify, distribute and use the works, even for commercial +purposes, all without asking permission. + +Author and dedicator: NodeAgentc, Inc. (FormCraft) +Generating script: gen_audio.py (Python, numpy and ffmpeg libvorbis only; seed 20261128; kept in the FormCraft build tooling, not shipped) +Each sound is synthesised from oscillators, noise and envelopes in numpy, written to a temporary WAV and encoded to OGG; no input audio files are read. +Dedication confirmed and legal code fetched 2026-11-29 from +https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt +Deed: https://creativecommons.org/publicdomain/zero/1.0/ + +===== Full text of the CC0 1.0 Universal legal code (as fetched) ===== + +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/assets/starter/audio/formcraft-synth-audio/ambience/hum-electrical.ogg b/assets/starter/audio/formcraft-synth-audio/ambience/hum-electrical.ogg new file mode 100644 index 0000000..e53779f Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/ambience/hum-electrical.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/ambience/rain-soft.ogg b/assets/starter/audio/formcraft-synth-audio/ambience/rain-soft.ogg new file mode 100644 index 0000000..8448ee9 Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/ambience/rain-soft.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/ambience/room-tone.ogg b/assets/starter/audio/formcraft-synth-audio/ambience/room-tone.ogg new file mode 100644 index 0000000..8b21ddc Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/ambience/room-tone.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/ambience/wind-soft.ogg b/assets/starter/audio/formcraft-synth-audio/ambience/wind-soft.ogg new file mode 100644 index 0000000..7fcb14d Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/ambience/wind-soft.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/hits/boom-cinematic.ogg b/assets/starter/audio/formcraft-synth-audio/hits/boom-cinematic.ogg new file mode 100644 index 0000000..b155ff3 Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/hits/boom-cinematic.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/hits/sub-drop.ogg b/assets/starter/audio/formcraft-synth-audio/hits/sub-drop.ogg new file mode 100644 index 0000000..478a03b Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/hits/sub-drop.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/music/arp-pluck.ogg b/assets/starter/audio/formcraft-synth-audio/music/arp-pluck.ogg new file mode 100644 index 0000000..767d42f Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/music/arp-pluck.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/music/pad-dark-drone.ogg b/assets/starter/audio/formcraft-synth-audio/music/pad-dark-drone.ogg new file mode 100644 index 0000000..81e2a84 Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/music/pad-dark-drone.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/music/pad-warm.ogg b/assets/starter/audio/formcraft-synth-audio/music/pad-warm.ogg new file mode 100644 index 0000000..2ffbbe7 Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/music/pad-warm.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/music/pulse-heartbeat.ogg b/assets/starter/audio/formcraft-synth-audio/music/pulse-heartbeat.ogg new file mode 100644 index 0000000..fb861fe Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/music/pulse-heartbeat.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/pack.json b/assets/starter/audio/formcraft-synth-audio/pack.json new file mode 100644 index 0000000..2b58d63 --- /dev/null +++ b/assets/starter/audio/formcraft-synth-audio/pack.json @@ -0,0 +1,292 @@ +{ + "id": "formcraft-synth-audio", + "name": "FormCraft Synth Audio (original)", + "kind": "audio", + "licence": "CC0-1.0", + "author": "NodeAgentc, Inc. (FormCraft)", + "source_url": "generated", + "source_commit_or_version": "gen_audio.py, numpy + ffmpeg libvorbis, seed 20261128", + "retrieved": "2026-11-28", + "licence_evidence": [ + "https://creativecommons.org/publicdomain/zero/1.0/legalcode", + "https://creativecommons.org/publicdomain/zero/1.0/" + ], + "items": [ + { + "id": "formcraft-synth-whoosh-fast", + "name": "Whoosh Fast", + "file": "whooshes/whoosh-fast.ogg", + "category": "whooshes", + "tags": [ + "sweep", + "synth", + "transition", + "whoosh" + ], + "bytes": 14284, + "seconds": 1.2 + }, + { + "id": "formcraft-synth-whoosh-slow", + "name": "Whoosh Slow", + "file": "whooshes/whoosh-slow.ogg", + "category": "whooshes", + "tags": [ + "sweep", + "synth", + "transition", + "whoosh" + ], + "bytes": 25251, + "seconds": 2.6 + }, + { + "id": "formcraft-synth-whoosh-low", + "name": "Whoosh Low Sweep", + "file": "whooshes/whoosh-low.ogg", + "category": "whooshes", + "tags": [ + "sweep", + "synth", + "transition", + "whoosh" + ], + "bytes": 18626, + "seconds": 2.0 + }, + { + "id": "formcraft-synth-riser-noise", + "name": "Riser Noise 4s", + "file": "risers/riser-noise.ogg", + "category": "risers", + "tags": [ + "build", + "riser", + "synth", + "transition" + ], + "bytes": 38172, + "seconds": 4.0 + }, + { + "id": "formcraft-synth-riser-tone", + "name": "Riser Tone 6s", + "file": "risers/riser-tone.ogg", + "category": "risers", + "tags": [ + "build", + "riser", + "synth", + "tension" + ], + "bytes": 28703, + "seconds": 6.0 + }, + { + "id": "formcraft-synth-boom-cinematic", + "name": "Boom Cinematic", + "file": "hits/boom-cinematic.ogg", + "category": "hits", + "tags": [ + "boom", + "cinematic", + "impact", + "synth" + ], + "bytes": 28382, + "seconds": 3.0 + }, + { + "id": "formcraft-synth-sub-drop", + "name": "Sub Drop", + "file": "hits/sub-drop.ogg", + "category": "hits", + "tags": [ + "bass", + "drop", + "sub", + "synth" + ], + "bytes": 10410, + "seconds": 2.5 + }, + { + "id": "formcraft-synth-tape-stop", + "name": "Tape Stop", + "file": "transitions/tape-stop.ogg", + "category": "transitions", + "tags": [ + "slowdown", + "stop", + "synth", + "tape" + ], + "bytes": 23902, + "seconds": 1.8 + }, + { + "id": "formcraft-synth-sparkle", + "name": "Sparkle Chimes", + "file": "transitions/sparkle.ogg", + "category": "transitions", + "tags": [ + "chime", + "magic", + "sparkle", + "synth" + ], + "bytes": 19921, + "seconds": 2.5 + }, + { + "id": "formcraft-synth-countdown-beeps", + "name": "Countdown Beeps", + "file": "tones/countdown-beeps.ogg", + "category": "tones", + "tags": [ + "beep", + "countdown", + "leader", + "synth" + ], + "bytes": 8434, + "seconds": 5.0 + }, + { + "id": "formcraft-synth-sync-pop", + "name": "Sync Pop (two-pop)", + "file": "tones/sync-pop.ogg", + "category": "tones", + "tags": [ + "beep", + "leader", + "sync", + "synth" + ], + "bytes": 5001, + "seconds": 1.0 + }, + { + "id": "formcraft-synth-room-tone", + "name": "Room Tone", + "file": "ambience/room-tone.ogg", + "category": "ambience", + "tags": [ + "loop", + "quiet", + "room", + "synth", + "tone" + ], + "bytes": 100131, + "seconds": 11.0 + }, + { + "id": "formcraft-synth-wind-soft", + "name": "Wind Soft", + "file": "ambience/wind-soft.ogg", + "category": "ambience", + "tags": [ + "air", + "loop", + "outdoor", + "synth", + "wind" + ], + "bytes": 97362, + "seconds": 11.0 + }, + { + "id": "formcraft-synth-rain-soft", + "name": "Rain Soft", + "file": "ambience/rain-soft.ogg", + "category": "ambience", + "tags": [ + "loop", + "outdoor", + "rain", + "synth", + "weather" + ], + "bytes": 110861, + "seconds": 11.0 + }, + { + "id": "formcraft-synth-hum-electrical", + "name": "Electrical Hum 60 Hz", + "file": "ambience/hum-electrical.ogg", + "category": "ambience", + "tags": [ + "drone", + "electrical", + "hum", + "loop", + "synth" + ], + "bytes": 111347, + "seconds": 12.0 + }, + { + "id": "formcraft-synth-pad-warm", + "name": "Pad Warm A minor", + "file": "music/pad-warm.ogg", + "category": "music", + "tags": [ + "ambient", + "chord", + "loop", + "pad", + "synth", + "warm" + ], + "bytes": 57507, + "seconds": 12.0 + }, + { + "id": "formcraft-synth-pad-dark-drone", + "name": "Drone Dark", + "file": "music/pad-dark-drone.ogg", + "category": "music", + "tags": [ + "ambient", + "dark", + "drone", + "loop", + "synth", + "tension" + ], + "bytes": 45821, + "seconds": 12.0 + }, + { + "id": "formcraft-synth-pulse-heartbeat", + "name": "Pulse Heartbeat 120 bpm", + "file": "music/pulse-heartbeat.ogg", + "category": "music", + "tags": [ + "bass", + "heartbeat", + "loop", + "pulse", + "synth" + ], + "bytes": 35803, + "seconds": 8.0 + }, + { + "id": "formcraft-synth-arp-pluck", + "name": "Arp Pluck Loop 120 bpm", + "file": "music/arp-pluck.ogg", + "category": "music", + "tags": [ + "arp", + "loop", + "melodic", + "pluck", + "synth" + ], + "bytes": 44733, + "seconds": 8.0 + } + ] +} \ No newline at end of file diff --git a/assets/starter/audio/formcraft-synth-audio/risers/riser-noise.ogg b/assets/starter/audio/formcraft-synth-audio/risers/riser-noise.ogg new file mode 100644 index 0000000..6065b8f Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/risers/riser-noise.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/risers/riser-tone.ogg b/assets/starter/audio/formcraft-synth-audio/risers/riser-tone.ogg new file mode 100644 index 0000000..e4d8559 Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/risers/riser-tone.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/tones/countdown-beeps.ogg b/assets/starter/audio/formcraft-synth-audio/tones/countdown-beeps.ogg new file mode 100644 index 0000000..aa99d98 Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/tones/countdown-beeps.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/tones/sync-pop.ogg b/assets/starter/audio/formcraft-synth-audio/tones/sync-pop.ogg new file mode 100644 index 0000000..8892868 Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/tones/sync-pop.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/transitions/sparkle.ogg b/assets/starter/audio/formcraft-synth-audio/transitions/sparkle.ogg new file mode 100644 index 0000000..725e6a4 Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/transitions/sparkle.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/transitions/tape-stop.ogg b/assets/starter/audio/formcraft-synth-audio/transitions/tape-stop.ogg new file mode 100644 index 0000000..0945a00 Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/transitions/tape-stop.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/whooshes/whoosh-fast.ogg b/assets/starter/audio/formcraft-synth-audio/whooshes/whoosh-fast.ogg new file mode 100644 index 0000000..bd4437f Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/whooshes/whoosh-fast.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/whooshes/whoosh-low.ogg b/assets/starter/audio/formcraft-synth-audio/whooshes/whoosh-low.ogg new file mode 100644 index 0000000..344c69d Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/whooshes/whoosh-low.ogg differ diff --git a/assets/starter/audio/formcraft-synth-audio/whooshes/whoosh-slow.ogg b/assets/starter/audio/formcraft-synth-audio/whooshes/whoosh-slow.ogg new file mode 100644 index 0000000..7d5a2fa Binary files /dev/null and b/assets/starter/audio/formcraft-synth-audio/whooshes/whoosh-slow.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/LICENSE.txt b/assets/starter/audio/graphite412-foley-cc0/LICENSE.txt new file mode 100644 index 0000000..44006ab --- /dev/null +++ b/assets/starter/audio/graphite412-foley-cc0/LICENSE.txt @@ -0,0 +1,16 @@ +Source: archive.org items Djt002-Graphite412FoleyAndProductionTools, Djt003-Graphite412FoleyAndProductionTools2, Djt005-Graphite412Samplepack03 +Fetched: 2026-11-29 + +https://archive.org/metadata/Djt002-Graphite412FoleyAndProductionTools licenseurl: http://creativecommons.org/publicdomain/zero/1.0/ +https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools uploader's description says: + djt002- graphite412: foley and production tools These foley and production files include various sounds and ambient noises that have been personally recorded by graphite412. Many of these sounds have been used in his tracks to create soundscapes and textures and have been a major part of his ambient works. Feel free to use these samples royalty free in your own music or dj sets. Many of these files are in mono, but stereo files are also included. License- Creative Common CC0 1.0 Universal + +https://archive.org/metadata/Djt003-Graphite412FoleyAndProductionTools2 licenseurl: http://creativecommons.org/publicdomain/zero/1.0/ +https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2 uploader's description says: + This is the second set of samples offered by graphite412. These files include various sounds and ambient noises. There are also a number of percussive and scraping noises as well. The highlights include natural soundscapes and long textures created by using granular synthesis on recorded .wav files. Most of these files are in mono but stereo files are also included. License- Creative Common CC0 1.0 Universal + +https://archive.org/metadata/Djt005-Graphite412Samplepack03 licenseurl: http://creativecommons.org/publicdomain/zero/1.0/ +https://archive.org/details/Djt005-Graphite412Samplepack03 uploader's description says: + This is my third samplepack that I'm releasing for free. This samplepack is recorded and edited by myself and is created from original recordings. It contains percussive hits, soundscapes, and a variety of other sounds. It could be useful for IDM, ambient music, or any genre using unusual samples from soundscapes. I am putting these files into the public domain under a CC0 1.0 Universal license. + +CC0 1.0 Universal legal code: https://creativecommons.org/publicdomain/zero/1.0/legalcode diff --git a/assets/starter/audio/graphite412-foley-cc0/city/car-start01.ogg b/assets/starter/audio/graphite412-foley-cc0/city/car-start01.ogg new file mode 100644 index 0000000..3bae223 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/city/car-start01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/city/city-night.ogg b/assets/starter/audio/graphite412-foley-cc0/city/city-night.ogg new file mode 100644 index 0000000..e26665b Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/city/city-night.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/city/city-soundscape-night-01.ogg b/assets/starter/audio/graphite412-foley-cc0/city/city-soundscape-night-01.ogg new file mode 100644 index 0000000..a9a78c8 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/city/city-soundscape-night-01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/city/city-soundscape-night-04.ogg b/assets/starter/audio/graphite412-foley-cc0/city/city-soundscape-night-04.ogg new file mode 100644 index 0000000..25b8f00 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/city/city-soundscape-night-04.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/city/train01.ogg b/assets/starter/audio/graphite412-foley-cc0/city/train01.ogg new file mode 100644 index 0000000..8fd41c7 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/city/train01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/door01.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/door01.ogg new file mode 100644 index 0000000..9698b6d Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/door01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/door02.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/door02.ogg new file mode 100644 index 0000000..b6d7e17 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/door02.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/door03.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/door03.ogg new file mode 100644 index 0000000..4ba1b7e Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/door03.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/door04.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/door04.ogg new file mode 100644 index 0000000..bf46f5f Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/door04.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/door05.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/door05.ogg new file mode 100644 index 0000000..ebb3975 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/door05.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/door06.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/door06.ogg new file mode 100644 index 0000000..068e031 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/door06.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/door07.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/door07.ogg new file mode 100644 index 0000000..2ea3f09 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/door07.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/door08.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/door08.ogg new file mode 100644 index 0000000..6a8f8d4 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/door08.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/door09.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/door09.ogg new file mode 100644 index 0000000..0fb5d1e Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/door09.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/door10.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/door10.ogg new file mode 100644 index 0000000..1c0d530 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/door10.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/knock01.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/knock01.ogg new file mode 100644 index 0000000..39f369f Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/knock01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/doors/small-guard-door.ogg b/assets/starter/audio/graphite412-foley-cc0/doors/small-guard-door.ogg new file mode 100644 index 0000000..48f4cf2 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/doors/small-guard-door.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/foley/analysis-wrapper-1.ogg b/assets/starter/audio/graphite412-foley-cc0/foley/analysis-wrapper-1.ogg new file mode 100644 index 0000000..0ec90db Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/foley/analysis-wrapper-1.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/foley/lat-inhale.ogg b/assets/starter/audio/graphite412-foley-cc0/foley/lat-inhale.ogg new file mode 100644 index 0000000..fdb5b2e Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/foley/lat-inhale.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/foley/pages01.ogg b/assets/starter/audio/graphite412-foley-cc0/foley/pages01.ogg new file mode 100644 index 0000000..97101ec Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/foley/pages01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/foley/squeak-chair-01.ogg b/assets/starter/audio/graphite412-foley-cc0/foley/squeak-chair-01.ogg new file mode 100644 index 0000000..562229d Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/foley/squeak-chair-01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/footsteps/crunch01.ogg b/assets/starter/audio/graphite412-foley-cc0/footsteps/crunch01.ogg new file mode 100644 index 0000000..3404042 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/footsteps/crunch01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-concrete.ogg b/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-concrete.ogg new file mode 100644 index 0000000..57dd029 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-concrete.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-gravel01.ogg b/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-gravel01.ogg new file mode 100644 index 0000000..375fd3d Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-gravel01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-gravel02.ogg b/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-gravel02.ogg new file mode 100644 index 0000000..44b4789 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-gravel02.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-gravel03.ogg b/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-gravel03.ogg new file mode 100644 index 0000000..d2a3015 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-gravel03.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-snow.ogg b/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-snow.ogg new file mode 100644 index 0000000..d255337 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/footsteps/walking-on-snow.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/ambient-crash.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/ambient-crash.ogg new file mode 100644 index 0000000..615fe19 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/ambient-crash.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/ambient-reverse-crash.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/ambient-reverse-crash.ogg new file mode 100644 index 0000000..6c39608 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/ambient-reverse-crash.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/glass-ringing-01.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/glass-ringing-01.ogg new file mode 100644 index 0000000..96df0db Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/glass-ringing-01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/low-g-harmonic2.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/low-g-harmonic2.ogg new file mode 100644 index 0000000..d02328d Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/low-g-harmonic2.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/low-rumble01.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/low-rumble01.ogg new file mode 100644 index 0000000..f9a4ec1 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/low-rumble01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/noise01.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/noise01.ogg new file mode 100644 index 0000000..0b78717 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/noise01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape-time-frequency-stretch.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape-time-frequency-stretch.ogg new file mode 100644 index 0000000..32e7a48 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape-time-frequency-stretch.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape01.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape01.ogg new file mode 100644 index 0000000..184072a Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape02.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape02.ogg new file mode 100644 index 0000000..7bb7adb Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape02.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape03.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape03.ogg new file mode 100644 index 0000000..ac5b252 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape03.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape04.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape04.ogg new file mode 100644 index 0000000..26b4712 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape04.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape05.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape05.ogg new file mode 100644 index 0000000..2520924 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape05.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape06.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape06.ogg new file mode 100644 index 0000000..08dfc37 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape06.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape07.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape07.ogg new file mode 100644 index 0000000..9bc9396 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape07.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape08.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape08.ogg new file mode 100644 index 0000000..d660050 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape08.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape09.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape09.ogg new file mode 100644 index 0000000..8bfb98f Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape09.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape10.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape10.ogg new file mode 100644 index 0000000..708ad32 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape10.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape11.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape11.ogg new file mode 100644 index 0000000..47a2376 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape11.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape12.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape12.ogg new file mode 100644 index 0000000..b08fb61 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape12.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape13.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape13.ogg new file mode 100644 index 0000000..6ad231c Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape13.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape14.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape14.ogg new file mode 100644 index 0000000..a5209a8 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape14.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape15.ogg b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape15.ogg new file mode 100644 index 0000000..2994845 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/impacts-and-textures/scrape15.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/mechanical/clock01.ogg b/assets/starter/audio/graphite412-foley-cc0/mechanical/clock01.ogg new file mode 100644 index 0000000..9513d6e Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/mechanical/clock01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/mechanical/light01.ogg b/assets/starter/audio/graphite412-foley-cc0/mechanical/light01.ogg new file mode 100644 index 0000000..11e1868 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/mechanical/light01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/mechanical/mechanical03.ogg b/assets/starter/audio/graphite412-foley-cc0/mechanical/mechanical03.ogg new file mode 100644 index 0000000..e0fc753 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/mechanical/mechanical03.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/mechanical/tape-hiss-dbb-portable.ogg b/assets/starter/audio/graphite412-foley-cc0/mechanical/tape-hiss-dbb-portable.ogg new file mode 100644 index 0000000..b6281e4 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/mechanical/tape-hiss-dbb-portable.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/mechanical/taps01.ogg b/assets/starter/audio/graphite412-foley-cc0/mechanical/taps01.ogg new file mode 100644 index 0000000..5d217c3 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/mechanical/taps01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/mechanical/taps02.ogg b/assets/starter/audio/graphite412-foley-cc0/mechanical/taps02.ogg new file mode 100644 index 0000000..86dd6eb Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/mechanical/taps02.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/mechanical/taps03.ogg b/assets/starter/audio/graphite412-foley-cc0/mechanical/taps03.ogg new file mode 100644 index 0000000..39b7508 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/mechanical/taps03.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/mechanical/taps04.ogg b/assets/starter/audio/graphite412-foley-cc0/mechanical/taps04.ogg new file mode 100644 index 0000000..a01f155 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/mechanical/taps04.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/mechanical/taps05.ogg b/assets/starter/audio/graphite412-foley-cc0/mechanical/taps05.ogg new file mode 100644 index 0000000..caa6f49 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/mechanical/taps05.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/nature/bird-calls01.ogg b/assets/starter/audio/graphite412-foley-cc0/nature/bird-calls01.ogg new file mode 100644 index 0000000..2010bea Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/nature/bird-calls01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/nature/cicada-wings-08.ogg b/assets/starter/audio/graphite412-foley-cc0/nature/cicada-wings-08.ogg new file mode 100644 index 0000000..f0e17fd Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/nature/cicada-wings-08.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/nature/cicada01.ogg b/assets/starter/audio/graphite412-foley-cc0/nature/cicada01.ogg new file mode 100644 index 0000000..2dbad1a Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/nature/cicada01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/nature/geese02.ogg b/assets/starter/audio/graphite412-foley-cc0/nature/geese02.ogg new file mode 100644 index 0000000..b5b2d15 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/nature/geese02.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/nature/insect-noises-1.ogg b/assets/starter/audio/graphite412-foley-cc0/nature/insect-noises-1.ogg new file mode 100644 index 0000000..57896f2 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/nature/insect-noises-1.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/nature/nature-sounds01.ogg b/assets/starter/audio/graphite412-foley-cc0/nature/nature-sounds01.ogg new file mode 100644 index 0000000..e3fdda8 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/nature/nature-sounds01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/nature/nature-sounds04.ogg b/assets/starter/audio/graphite412-foley-cc0/nature/nature-sounds04.ogg new file mode 100644 index 0000000..bb4be93 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/nature/nature-sounds04.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/nature/owl-call.ogg b/assets/starter/audio/graphite412-foley-cc0/nature/owl-call.ogg new file mode 100644 index 0000000..5a7f327 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/nature/owl-call.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/nature/thunder1.ogg b/assets/starter/audio/graphite412-foley-cc0/nature/thunder1.ogg new file mode 100644 index 0000000..ab99512 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/nature/thunder1.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/nature/windchime-bamboo-02.ogg b/assets/starter/audio/graphite412-foley-cc0/nature/windchime-bamboo-02.ogg new file mode 100644 index 0000000..fa84f11 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/nature/windchime-bamboo-02.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/nature/windchime-metal-01.ogg b/assets/starter/audio/graphite412-foley-cc0/nature/windchime-metal-01.ogg new file mode 100644 index 0000000..6bb584f Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/nature/windchime-metal-01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/pack.json b/assets/starter/audio/graphite412-foley-cc0/pack.json new file mode 100644 index 0000000..8fd1395 --- /dev/null +++ b/assets/starter/audio/graphite412-foley-cc0/pack.json @@ -0,0 +1,1588 @@ +{ + "id": "graphite412-foley-cc0", + "name": "graphite412 Foley and Field Recordings (CC0)", + "kind": "audio", + "licence": "CC0-1.0", + "author": "graphite412 (Electronica 4 God netlabel)", + "source_url": "https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools", + "source_commit_or_version": "archive.org item originals as of 2026-11-29; encoded to OGG Vorbis q5 (ffmpeg libvorbis), metadata stripped; long files are excerpts from the start with a 2 s fade", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://archive.org/metadata/Djt002-Graphite412FoleyAndProductionTools", + "https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools", + "https://archive.org/metadata/Djt003-Graphite412FoleyAndProductionTools2", + "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2", + "https://archive.org/metadata/Djt005-Graphite412Samplepack03", + "https://archive.org/details/Djt005-Graphite412Samplepack03" + ], + "items": [ + { + "id": "g412-car-start01", + "name": "Car start01", + "file": "city/car-start01.ogg", + "category": "city", + "tags": [ + "car", + "city", + "field-recording", + "graphite412", + "start01" + ], + "bytes": 73463, + "seconds": 6.22, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-city-night", + "name": "City night (excerpt)", + "file": "city/city-night.ogg", + "category": "city", + "tags": [ + "city", + "field-recording", + "graphite412", + "night" + ], + "bytes": 187158, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools" + }, + { + "id": "g412-city-soundscape-night-01", + "name": "City soundscape night 01 (excerpt)", + "file": "city/city-soundscape-night-01.ogg", + "category": "city", + "tags": [ + "city", + "field-recording", + "graphite412", + "night", + "soundscape" + ], + "bytes": 173463, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-city-soundscape-night-04", + "name": "City soundscape night 04 (excerpt)", + "file": "city/city-soundscape-night-04.ogg", + "category": "city", + "tags": [ + "city", + "field-recording", + "graphite412", + "night", + "soundscape" + ], + "bytes": 173933, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-train01", + "name": "Train01 (excerpt)", + "file": "city/train01.ogg", + "category": "city", + "tags": [ + "city", + "field-recording", + "graphite412", + "train01" + ], + "bytes": 131609, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-door01", + "name": "Door01", + "file": "doors/door01.ogg", + "category": "doors", + "tags": [ + "door01", + "doors", + "field-recording", + "graphite412" + ], + "bytes": 10934, + "seconds": 0.67, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-door02", + "name": "Door02", + "file": "doors/door02.ogg", + "category": "doors", + "tags": [ + "door02", + "doors", + "field-recording", + "graphite412" + ], + "bytes": 21331, + "seconds": 1.68, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-door03", + "name": "Door03", + "file": "doors/door03.ogg", + "category": "doors", + "tags": [ + "door03", + "doors", + "field-recording", + "graphite412" + ], + "bytes": 70951, + "seconds": 5.98, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-door04", + "name": "Door04", + "file": "doors/door04.ogg", + "category": "doors", + "tags": [ + "door04", + "doors", + "field-recording", + "graphite412" + ], + "bytes": 28516, + "seconds": 2.43, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-door05", + "name": "Door05", + "file": "doors/door05.ogg", + "category": "doors", + "tags": [ + "door05", + "doors", + "field-recording", + "graphite412" + ], + "bytes": 109118, + "seconds": 10.33, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-door06", + "name": "Door06", + "file": "doors/door06.ogg", + "category": "doors", + "tags": [ + "door06", + "doors", + "field-recording", + "graphite412" + ], + "bytes": 130094, + "seconds": 12.23, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-door07", + "name": "Door07", + "file": "doors/door07.ogg", + "category": "doors", + "tags": [ + "door07", + "doors", + "field-recording", + "graphite412" + ], + "bytes": 96775, + "seconds": 8.76, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-door08", + "name": "Door08", + "file": "doors/door08.ogg", + "category": "doors", + "tags": [ + "door08", + "doors", + "field-recording", + "graphite412" + ], + "bytes": 155710, + "seconds": 14.53, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-door09", + "name": "Door09", + "file": "doors/door09.ogg", + "category": "doors", + "tags": [ + "door09", + "doors", + "field-recording", + "graphite412" + ], + "bytes": 144954, + "seconds": 13.22, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-door10", + "name": "Door10", + "file": "doors/door10.ogg", + "category": "doors", + "tags": [ + "door10", + "doors", + "field-recording", + "graphite412" + ], + "bytes": 86156, + "seconds": 8.04, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-knock01", + "name": "Knock01", + "file": "doors/knock01.ogg", + "category": "doors", + "tags": [ + "doors", + "field-recording", + "graphite412", + "knock01" + ], + "bytes": 7199, + "seconds": 0.41, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-small-guard-door", + "name": "Small guard door (excerpt)", + "file": "doors/small-guard-door.ogg", + "category": "doors", + "tags": [ + "door", + "doors", + "field-recording", + "graphite412", + "guard", + "small" + ], + "bytes": 203250, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools" + }, + { + "id": "g412-analysis-wrapper-1", + "name": "Analysis Wrapper 1", + "file": "foley/analysis-wrapper-1.ogg", + "category": "foley", + "tags": [ + "1", + "analysis", + "field-recording", + "foley", + "graphite412", + "wrapper" + ], + "bytes": 22794, + "seconds": 1.9, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-lat-inhale", + "name": "LAT inhale", + "file": "foley/lat-inhale.ogg", + "category": "foley", + "tags": [ + "field-recording", + "foley", + "graphite412", + "inhale", + "lat" + ], + "bytes": 35938, + "seconds": 3.18, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-pages01", + "name": "Pages01 (excerpt)", + "file": "foley/pages01.ogg", + "category": "foley", + "tags": [ + "field-recording", + "foley", + "graphite412", + "pages01" + ], + "bytes": 168851, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-squeak-chair-01", + "name": "Squeak chair 01", + "file": "foley/squeak-chair-01.ogg", + "category": "foley", + "tags": [ + "01", + "chair", + "field-recording", + "foley", + "graphite412", + "squeak" + ], + "bytes": 129697, + "seconds": 13.48, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-crunch01", + "name": "Crunch01", + "file": "footsteps/crunch01.ogg", + "category": "footsteps", + "tags": [ + "crunch01", + "field-recording", + "footsteps", + "graphite412" + ], + "bytes": 12714, + "seconds": 0.4, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-walking-on-concrete", + "name": "Walking on concrete", + "file": "footsteps/walking-on-concrete.ogg", + "category": "footsteps", + "tags": [ + "concrete", + "field-recording", + "footsteps", + "graphite412", + "on", + "walking" + ], + "bytes": 95364, + "seconds": 8.25, + "source_page": "https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools" + }, + { + "id": "g412-walking-on-gravel01", + "name": "Walking on gravel01 (excerpt)", + "file": "footsteps/walking-on-gravel01.ogg", + "category": "footsteps", + "tags": [ + "field-recording", + "footsteps", + "graphite412", + "gravel01", + "on", + "walking" + ], + "bytes": 220762, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-walking-on-gravel02", + "name": "Walking on gravel02", + "file": "footsteps/walking-on-gravel02.ogg", + "category": "footsteps", + "tags": [ + "field-recording", + "footsteps", + "graphite412", + "gravel02", + "on", + "walking" + ], + "bytes": 87989, + "seconds": 7.0, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-walking-on-gravel03", + "name": "Walking on gravel03 (excerpt)", + "file": "footsteps/walking-on-gravel03.ogg", + "category": "footsteps", + "tags": [ + "field-recording", + "footsteps", + "graphite412", + "gravel03", + "on", + "walking" + ], + "bytes": 222738, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-walking-on-snow", + "name": "Walking on snow (excerpt)", + "file": "footsteps/walking-on-snow.ogg", + "category": "footsteps", + "tags": [ + "field-recording", + "footsteps", + "graphite412", + "on", + "snow", + "walking" + ], + "bytes": 208072, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools" + }, + { + "id": "g412-ambient-crash", + "name": "Ambient crash", + "file": "impacts-and-textures/ambient-crash.ogg", + "category": "impacts-and-textures", + "tags": [ + "ambient", + "crash", + "field-recording", + "graphite412", + "impacts-and-textures" + ], + "bytes": 43179, + "seconds": 4.14, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-ambient-reverse-crash", + "name": "Ambient reverse crash", + "file": "impacts-and-textures/ambient-reverse-crash.ogg", + "category": "impacts-and-textures", + "tags": [ + "ambient", + "crash", + "field-recording", + "graphite412", + "impacts-and-textures", + "reverse" + ], + "bytes": 31726, + "seconds": 2.42, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-glass-ringing-01", + "name": "Glass ringing 01", + "file": "impacts-and-textures/glass-ringing-01.ogg", + "category": "impacts-and-textures", + "tags": [ + "01", + "field-recording", + "glass", + "graphite412", + "impacts-and-textures", + "ringing" + ], + "bytes": 24624, + "seconds": 2.59, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-low-g-harmonic2", + "name": "Low g harmonic2", + "file": "impacts-and-textures/low-g-harmonic2.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "g", + "graphite412", + "harmonic2", + "impacts-and-textures", + "low" + ], + "bytes": 54097, + "seconds": 5.58, + "source_page": "https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools" + }, + { + "id": "g412-low-rumble01", + "name": "Low rumble01", + "file": "impacts-and-textures/low-rumble01.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "low", + "rumble01" + ], + "bytes": 76089, + "seconds": 17.82, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-noise01", + "name": "Noise01", + "file": "impacts-and-textures/noise01.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "noise01" + ], + "bytes": 56345, + "seconds": 4.69, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape-time-frequency-stretch", + "name": "Scrape time frequency stretch", + "file": "impacts-and-textures/scrape-time-frequency-stretch.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "frequency", + "graphite412", + "impacts-and-textures", + "scrape", + "time" + ], + "bytes": 10992, + "seconds": 0.68, + "source_page": "https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools" + }, + { + "id": "g412-scrape01", + "name": "Scrape01", + "file": "impacts-and-textures/scrape01.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape01" + ], + "bytes": 6146, + "seconds": 0.15, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape02", + "name": "Scrape02", + "file": "impacts-and-textures/scrape02.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape02" + ], + "bytes": 20239, + "seconds": 1.5, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape03", + "name": "Scrape03", + "file": "impacts-and-textures/scrape03.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape03" + ], + "bytes": 47741, + "seconds": 3.92, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape04", + "name": "Scrape04", + "file": "impacts-and-textures/scrape04.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape04" + ], + "bytes": 13121, + "seconds": 0.82, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape05", + "name": "Scrape05", + "file": "impacts-and-textures/scrape05.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape05" + ], + "bytes": 17983, + "seconds": 1.28, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape06", + "name": "Scrape06", + "file": "impacts-and-textures/scrape06.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape06" + ], + "bytes": 29832, + "seconds": 2.34, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape07", + "name": "Scrape07", + "file": "impacts-and-textures/scrape07.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape07" + ], + "bytes": 12174, + "seconds": 0.75, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape08", + "name": "Scrape08", + "file": "impacts-and-textures/scrape08.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape08" + ], + "bytes": 13288, + "seconds": 0.84, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape09", + "name": "Scrape09", + "file": "impacts-and-textures/scrape09.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape09" + ], + "bytes": 39396, + "seconds": 3.28, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape10", + "name": "Scrape10", + "file": "impacts-and-textures/scrape10.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape10" + ], + "bytes": 13897, + "seconds": 0.89, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape11", + "name": "Scrape11", + "file": "impacts-and-textures/scrape11.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape11" + ], + "bytes": 7692, + "seconds": 0.23, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape12", + "name": "Scrape12", + "file": "impacts-and-textures/scrape12.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape12" + ], + "bytes": 5133, + "seconds": 0.07, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape13", + "name": "Scrape13", + "file": "impacts-and-textures/scrape13.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape13" + ], + "bytes": 156033, + "seconds": 13.18, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape14", + "name": "Scrape14", + "file": "impacts-and-textures/scrape14.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape14" + ], + "bytes": 40254, + "seconds": 3.25, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-scrape15", + "name": "Scrape15", + "file": "impacts-and-textures/scrape15.ogg", + "category": "impacts-and-textures", + "tags": [ + "field-recording", + "graphite412", + "impacts-and-textures", + "scrape15" + ], + "bytes": 17035, + "seconds": 1.2, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-clock01", + "name": "Clock01", + "file": "mechanical/clock01.ogg", + "category": "mechanical", + "tags": [ + "clock01", + "field-recording", + "graphite412", + "mechanical" + ], + "bytes": 152338, + "seconds": 13.59, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-light01", + "name": "Light01", + "file": "mechanical/light01.ogg", + "category": "mechanical", + "tags": [ + "field-recording", + "graphite412", + "light01", + "mechanical" + ], + "bytes": 78092, + "seconds": 6.36, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-mechanical03", + "name": "Mechanical03", + "file": "mechanical/mechanical03.ogg", + "category": "mechanical", + "tags": [ + "field-recording", + "graphite412", + "mechanical", + "mechanical03" + ], + "bytes": 44965, + "seconds": 4.06, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-tape-hiss-dbb-portable", + "name": "Tape hiss dbb portable (excerpt)", + "file": "mechanical/tape-hiss-dbb-portable.ogg", + "category": "mechanical", + "tags": [ + "dbb", + "field-recording", + "graphite412", + "hiss", + "mechanical", + "tape" + ], + "bytes": 362535, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-taps01", + "name": "Taps01", + "file": "mechanical/taps01.ogg", + "category": "mechanical", + "tags": [ + "field-recording", + "graphite412", + "mechanical", + "taps01" + ], + "bytes": 35879, + "seconds": 3.03, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-taps02", + "name": "Taps02", + "file": "mechanical/taps02.ogg", + "category": "mechanical", + "tags": [ + "field-recording", + "graphite412", + "mechanical", + "taps02" + ], + "bytes": 37576, + "seconds": 3.2, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-taps03", + "name": "Taps03", + "file": "mechanical/taps03.ogg", + "category": "mechanical", + "tags": [ + "field-recording", + "graphite412", + "mechanical", + "taps03" + ], + "bytes": 21809, + "seconds": 1.57, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-taps04", + "name": "Taps04", + "file": "mechanical/taps04.ogg", + "category": "mechanical", + "tags": [ + "field-recording", + "graphite412", + "mechanical", + "taps04" + ], + "bytes": 119708, + "seconds": 10.5, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-taps05", + "name": "Taps05", + "file": "mechanical/taps05.ogg", + "category": "mechanical", + "tags": [ + "field-recording", + "graphite412", + "mechanical", + "taps05" + ], + "bytes": 61670, + "seconds": 5.42, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-bird-calls01", + "name": "Bird calls01 (excerpt)", + "file": "nature/bird-calls01.ogg", + "category": "nature", + "tags": [ + "bird", + "calls01", + "field-recording", + "graphite412", + "nature" + ], + "bytes": 207525, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-cicada-wings-08", + "name": "Cicada wings 08", + "file": "nature/cicada-wings-08.ogg", + "category": "nature", + "tags": [ + "08", + "cicada", + "field-recording", + "graphite412", + "nature", + "wings" + ], + "bytes": 80529, + "seconds": 7.03, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-cicada01", + "name": "Cicada01", + "file": "nature/cicada01.ogg", + "category": "nature", + "tags": [ + "cicada01", + "field-recording", + "graphite412", + "nature" + ], + "bytes": 41014, + "seconds": 2.66, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-geese02", + "name": "Geese02", + "file": "nature/geese02.ogg", + "category": "nature", + "tags": [ + "field-recording", + "geese02", + "graphite412", + "nature" + ], + "bytes": 135164, + "seconds": 11.89, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-insect-noises-1", + "name": "Insect Noises 1", + "file": "nature/insect-noises-1.ogg", + "category": "nature", + "tags": [ + "1", + "field-recording", + "graphite412", + "insect", + "nature", + "noises" + ], + "bytes": 152340, + "seconds": 14.24, + "source_page": "https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools" + }, + { + "id": "g412-nature-sounds01", + "name": "Nature sounds01 (excerpt)", + "file": "nature/nature-sounds01.ogg", + "category": "nature", + "tags": [ + "field-recording", + "graphite412", + "nature", + "sounds01" + ], + "bytes": 217357, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-nature-sounds04", + "name": "Nature sounds04 (excerpt)", + "file": "nature/nature-sounds04.ogg", + "category": "nature", + "tags": [ + "field-recording", + "graphite412", + "nature", + "sounds04" + ], + "bytes": 205860, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-owl-call", + "name": "Owl call", + "file": "nature/owl-call.ogg", + "category": "nature", + "tags": [ + "call", + "field-recording", + "graphite412", + "nature", + "owl" + ], + "bytes": 16143, + "seconds": 1.18, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-thunder1", + "name": "Thunder1", + "file": "nature/thunder1.ogg", + "category": "nature", + "tags": [ + "field-recording", + "graphite412", + "nature", + "thunder1" + ], + "bytes": 62299, + "seconds": 6.42, + "source_page": "https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools" + }, + { + "id": "g412-windchime-bamboo-02", + "name": "Windchime bamboo 02", + "file": "nature/windchime-bamboo-02.ogg", + "category": "nature", + "tags": [ + "02", + "bamboo", + "field-recording", + "graphite412", + "nature", + "windchime" + ], + "bytes": 130668, + "seconds": 16.51, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-windchime-metal-01", + "name": "Windchime metal 01 (excerpt)", + "file": "nature/windchime-metal-01.ogg", + "category": "nature", + "tags": [ + "01", + "field-recording", + "graphite412", + "metal", + "nature", + "windchime" + ], + "bytes": 206975, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-clap-01", + "name": "Clap 01", + "file": "ui-and-hits/clap-01.ogg", + "category": "ui-and-hits", + "tags": [ + "01", + "clap", + "field-recording", + "graphite412", + "ui-and-hits" + ], + "bytes": 6249, + "seconds": 0.26, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-clap-05", + "name": "Clap 05", + "file": "ui-and-hits/clap-05.ogg", + "category": "ui-and-hits", + "tags": [ + "05", + "clap", + "field-recording", + "graphite412", + "ui-and-hits" + ], + "bytes": 6389, + "seconds": 0.26, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-clap-11", + "name": "Clap 11", + "file": "ui-and-hits/clap-11.ogg", + "category": "ui-and-hits", + "tags": [ + "11", + "clap", + "field-recording", + "graphite412", + "ui-and-hits" + ], + "bytes": 5999, + "seconds": 0.21, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-efx02", + "name": "EFX02", + "file": "ui-and-hits/efx02.ogg", + "category": "ui-and-hits", + "tags": [ + "efx02", + "field-recording", + "graphite412", + "ui-and-hits" + ], + "bytes": 7189, + "seconds": 0.42, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-handdrum-01", + "name": "Handdrum 01", + "file": "ui-and-hits/handdrum-01.ogg", + "category": "ui-and-hits", + "tags": [ + "01", + "field-recording", + "graphite412", + "handdrum", + "ui-and-hits" + ], + "bytes": 9381, + "seconds": 0.68, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-ping01", + "name": "Ping01", + "file": "ui-and-hits/ping01.ogg", + "category": "ui-and-hits", + "tags": [ + "field-recording", + "graphite412", + "ping01", + "ui-and-hits" + ], + "bytes": 7901, + "seconds": 0.37, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-ping02", + "name": "Ping02", + "file": "ui-and-hits/ping02.ogg", + "category": "ui-and-hits", + "tags": [ + "field-recording", + "graphite412", + "ping02", + "ui-and-hits" + ], + "bytes": 24760, + "seconds": 2.15, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-snap-03", + "name": "Snap 03", + "file": "ui-and-hits/snap-03.ogg", + "category": "ui-and-hits", + "tags": [ + "03", + "field-recording", + "graphite412", + "snap", + "ui-and-hits" + ], + "bytes": 7738, + "seconds": 0.31, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-snap-04", + "name": "Snap 04", + "file": "ui-and-hits/snap-04.ogg", + "category": "ui-and-hits", + "tags": [ + "04", + "field-recording", + "graphite412", + "snap", + "ui-and-hits" + ], + "bytes": 7007, + "seconds": 0.29, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-snap-07", + "name": "Snap 07", + "file": "ui-and-hits/snap-07.ogg", + "category": "ui-and-hits", + "tags": [ + "07", + "field-recording", + "graphite412", + "snap", + "ui-and-hits" + ], + "bytes": 7215, + "seconds": 0.31, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-tump-04", + "name": "Tump 04", + "file": "ui-and-hits/tump-04.ogg", + "category": "ui-and-hits", + "tags": [ + "04", + "field-recording", + "graphite412", + "tump", + "ui-and-hits" + ], + "bytes": 6237, + "seconds": 0.24, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-tump-08", + "name": "Tump 08", + "file": "ui-and-hits/tump-08.ogg", + "category": "ui-and-hits", + "tags": [ + "08", + "field-recording", + "graphite412", + "tump", + "ui-and-hits" + ], + "bytes": 6066, + "seconds": 0.24, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-tump-14", + "name": "Tump 14", + "file": "ui-and-hits/tump-14.ogg", + "category": "ui-and-hits", + "tags": [ + "14", + "field-recording", + "graphite412", + "tump", + "ui-and-hits" + ], + "bytes": 6304, + "seconds": 0.26, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-tump-22", + "name": "Tump 22", + "file": "ui-and-hits/tump-22.ogg", + "category": "ui-and-hits", + "tags": [ + "22", + "field-recording", + "graphite412", + "tump", + "ui-and-hits" + ], + "bytes": 5983, + "seconds": 0.21, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-bailer", + "name": "Bailer (excerpt)", + "file": "water/bailer.ogg", + "category": "water", + "tags": [ + "bailer", + "field-recording", + "graphite412", + "water" + ], + "bytes": 220621, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt002-Graphite412FoleyAndProductionTools" + }, + { + "id": "g412-creek01", + "name": "Creek01", + "file": "water/creek01.ogg", + "category": "water", + "tags": [ + "creek01", + "field-recording", + "graphite412", + "water" + ], + "bytes": 12468, + "seconds": 0.77, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek02", + "name": "Creek02", + "file": "water/creek02.ogg", + "category": "water", + "tags": [ + "creek02", + "field-recording", + "graphite412", + "water" + ], + "bytes": 21765, + "seconds": 1.59, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek03", + "name": "Creek03", + "file": "water/creek03.ogg", + "category": "water", + "tags": [ + "creek03", + "field-recording", + "graphite412", + "water" + ], + "bytes": 24704, + "seconds": 1.82, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek04", + "name": "Creek04", + "file": "water/creek04.ogg", + "category": "water", + "tags": [ + "creek04", + "field-recording", + "graphite412", + "water" + ], + "bytes": 23555, + "seconds": 1.76, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek05", + "name": "Creek05", + "file": "water/creek05.ogg", + "category": "water", + "tags": [ + "creek05", + "field-recording", + "graphite412", + "water" + ], + "bytes": 45698, + "seconds": 3.56, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek06", + "name": "Creek06", + "file": "water/creek06.ogg", + "category": "water", + "tags": [ + "creek06", + "field-recording", + "graphite412", + "water" + ], + "bytes": 20530, + "seconds": 1.36, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek07", + "name": "Creek07", + "file": "water/creek07.ogg", + "category": "water", + "tags": [ + "creek07", + "field-recording", + "graphite412", + "water" + ], + "bytes": 18473, + "seconds": 1.22, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek08", + "name": "Creek08", + "file": "water/creek08.ogg", + "category": "water", + "tags": [ + "creek08", + "field-recording", + "graphite412", + "water" + ], + "bytes": 12298, + "seconds": 0.72, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek09", + "name": "Creek09", + "file": "water/creek09.ogg", + "category": "water", + "tags": [ + "creek09", + "field-recording", + "graphite412", + "water" + ], + "bytes": 13051, + "seconds": 0.73, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek10", + "name": "Creek10", + "file": "water/creek10.ogg", + "category": "water", + "tags": [ + "creek10", + "field-recording", + "graphite412", + "water" + ], + "bytes": 25170, + "seconds": 1.85, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek11", + "name": "Creek11", + "file": "water/creek11.ogg", + "category": "water", + "tags": [ + "creek11", + "field-recording", + "graphite412", + "water" + ], + "bytes": 13034, + "seconds": 0.77, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek12", + "name": "Creek12", + "file": "water/creek12.ogg", + "category": "water", + "tags": [ + "creek12", + "field-recording", + "graphite412", + "water" + ], + "bytes": 11642, + "seconds": 0.63, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-creek13", + "name": "Creek13", + "file": "water/creek13.ogg", + "category": "water", + "tags": [ + "creek13", + "field-recording", + "graphite412", + "water" + ], + "bytes": 12880, + "seconds": 0.83, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-rain01", + "name": "Rain01", + "file": "water/rain01.ogg", + "category": "water", + "tags": [ + "field-recording", + "graphite412", + "rain01", + "water" + ], + "bytes": 42836, + "seconds": 2.99, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + }, + { + "id": "g412-rain02", + "name": "Rain02 (excerpt)", + "file": "water/rain02.ogg", + "category": "water", + "tags": [ + "field-recording", + "graphite412", + "rain02", + "water" + ], + "bytes": 232793, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-rain04", + "name": "Rain04 (excerpt)", + "file": "water/rain04.ogg", + "category": "water", + "tags": [ + "field-recording", + "graphite412", + "rain04", + "water" + ], + "bytes": 186048, + "seconds": 20.0, + "source_page": "https://archive.org/details/Djt005-Graphite412Samplepack03" + }, + { + "id": "g412-stream02", + "name": "Stream02", + "file": "water/stream02.ogg", + "category": "water", + "tags": [ + "field-recording", + "graphite412", + "stream02", + "water" + ], + "bytes": 291119, + "seconds": 15.63, + "source_page": "https://archive.org/details/Djt003-Graphite412FoleyAndProductionTools2" + } + ] +} diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/clap-01.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/clap-01.ogg new file mode 100644 index 0000000..408f36f Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/clap-01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/clap-05.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/clap-05.ogg new file mode 100644 index 0000000..8078300 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/clap-05.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/clap-11.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/clap-11.ogg new file mode 100644 index 0000000..3174dc6 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/clap-11.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/efx02.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/efx02.ogg new file mode 100644 index 0000000..0ca1d4f Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/efx02.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/handdrum-01.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/handdrum-01.ogg new file mode 100644 index 0000000..8771412 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/handdrum-01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/ping01.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/ping01.ogg new file mode 100644 index 0000000..f19ddde Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/ping01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/ping02.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/ping02.ogg new file mode 100644 index 0000000..28fa003 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/ping02.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/snap-03.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/snap-03.ogg new file mode 100644 index 0000000..4b9871d Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/snap-03.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/snap-04.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/snap-04.ogg new file mode 100644 index 0000000..a51d619 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/snap-04.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/snap-07.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/snap-07.ogg new file mode 100644 index 0000000..874e13c Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/snap-07.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-04.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-04.ogg new file mode 100644 index 0000000..a2105bb Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-04.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-08.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-08.ogg new file mode 100644 index 0000000..7b9c128 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-08.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-14.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-14.ogg new file mode 100644 index 0000000..07b512b Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-14.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-22.ogg b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-22.ogg new file mode 100644 index 0000000..a63fa2c Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/ui-and-hits/tump-22.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/bailer.ogg b/assets/starter/audio/graphite412-foley-cc0/water/bailer.ogg new file mode 100644 index 0000000..a4234cd Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/bailer.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek01.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek01.ogg new file mode 100644 index 0000000..87672b0 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek02.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek02.ogg new file mode 100644 index 0000000..f932c5d Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek02.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek03.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek03.ogg new file mode 100644 index 0000000..a058727 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek03.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek04.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek04.ogg new file mode 100644 index 0000000..86c4d1b Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek04.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek05.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek05.ogg new file mode 100644 index 0000000..9f9998d Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek05.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek06.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek06.ogg new file mode 100644 index 0000000..f03e2e0 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek06.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek07.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek07.ogg new file mode 100644 index 0000000..9540282 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek07.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek08.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek08.ogg new file mode 100644 index 0000000..165a2c0 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek08.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek09.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek09.ogg new file mode 100644 index 0000000..56bb727 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek09.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek10.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek10.ogg new file mode 100644 index 0000000..a0405e2 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek10.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek11.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek11.ogg new file mode 100644 index 0000000..1deda76 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek11.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek12.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek12.ogg new file mode 100644 index 0000000..8797e29 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek12.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/creek13.ogg b/assets/starter/audio/graphite412-foley-cc0/water/creek13.ogg new file mode 100644 index 0000000..a5db7ca Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/creek13.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/rain01.ogg b/assets/starter/audio/graphite412-foley-cc0/water/rain01.ogg new file mode 100644 index 0000000..f56fe01 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/rain01.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/rain02.ogg b/assets/starter/audio/graphite412-foley-cc0/water/rain02.ogg new file mode 100644 index 0000000..c110daf Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/rain02.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/rain04.ogg b/assets/starter/audio/graphite412-foley-cc0/water/rain04.ogg new file mode 100644 index 0000000..1e8ce25 Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/rain04.ogg differ diff --git a/assets/starter/audio/graphite412-foley-cc0/water/stream02.ogg b/assets/starter/audio/graphite412-foley-cc0/water/stream02.ogg new file mode 100644 index 0000000..dd918fc Binary files /dev/null and b/assets/starter/audio/graphite412-foley-cc0/water/stream02.ogg differ diff --git a/assets/starter/audio/komiku-childhood-scene-cc0/LICENSE.txt b/assets/starter/audio/komiku-childhood-scene-cc0/LICENSE.txt new file mode 100644 index 0000000..202d2c2 --- /dev/null +++ b/assets/starter/audio/komiku-childhood-scene-cc0/LICENSE.txt @@ -0,0 +1,8 @@ +Source: archive.org items Komiku01ChildhoodScene +Fetched: 2026-11-29 + +https://archive.org/metadata/Komiku01ChildhoodScene licenseurl: http://creativecommons.org/publicdomain/zero/1.0/ +https://archive.org/details/Komiku01ChildhoodScene uploader's description says: + Third in a series of CC0 soundtracks by Monplaisir. http://freemusicarchive.org/music/Komiku/ + +CC0 1.0 Universal legal code: https://creativecommons.org/publicdomain/zero/1.0/legalcode diff --git a/assets/starter/audio/komiku-childhood-scene-cc0/music/childhood-scene.ogg b/assets/starter/audio/komiku-childhood-scene-cc0/music/childhood-scene.ogg new file mode 100644 index 0000000..9d74c60 Binary files /dev/null and b/assets/starter/audio/komiku-childhood-scene-cc0/music/childhood-scene.ogg differ diff --git a/assets/starter/audio/komiku-childhood-scene-cc0/music/decisive-battle.ogg b/assets/starter/audio/komiku-childhood-scene-cc0/music/decisive-battle.ogg new file mode 100644 index 0000000..7d48cca Binary files /dev/null and b/assets/starter/audio/komiku-childhood-scene-cc0/music/decisive-battle.ogg differ diff --git a/assets/starter/audio/komiku-childhood-scene-cc0/music/save-me-from-my-prison.ogg b/assets/starter/audio/komiku-childhood-scene-cc0/music/save-me-from-my-prison.ogg new file mode 100644 index 0000000..466cbcb Binary files /dev/null and b/assets/starter/audio/komiku-childhood-scene-cc0/music/save-me-from-my-prison.ogg differ diff --git a/assets/starter/audio/komiku-childhood-scene-cc0/pack.json b/assets/starter/audio/komiku-childhood-scene-cc0/pack.json new file mode 100644 index 0000000..f16d882 --- /dev/null +++ b/assets/starter/audio/komiku-childhood-scene-cc0/pack.json @@ -0,0 +1,58 @@ +{ + "id": "komiku-childhood-scene-cc0", + "name": "Komiku: It's time for adventure vol. 3 (CC0, excerpts)", + "kind": "audio", + "licence": "CC0-1.0", + "author": "Komiku (Monplaisir), via the Hi Fidelity netlabel", + "source_url": "https://archive.org/details/Komiku01ChildhoodScene", + "source_commit_or_version": "archive.org item originals as of 2026-11-29; encoded to OGG Vorbis q5 (ffmpeg libvorbis), metadata stripped; long files are excerpts from the start with a 2 s fade", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://archive.org/metadata/Komiku01ChildhoodScene", + "https://archive.org/details/Komiku01ChildhoodScene" + ], + "items": [ + { + "id": "komiku-childhood-scene", + "name": "Childhood Scene (excerpt)", + "file": "music/childhood-scene.ogg", + "category": "music", + "tags": [ + "calm", + "komiku", + "music" + ], + "bytes": 670538, + "seconds": 50.0, + "source_page": "https://archive.org/details/Komiku01ChildhoodScene" + }, + { + "id": "komiku-save-me-from-my-prison", + "name": "Save Me From My Prison (excerpt)", + "file": "music/save-me-from-my-prison.ogg", + "category": "music", + "tags": [ + "cinematic", + "komiku", + "music" + ], + "bytes": 822257, + "seconds": 50.0, + "source_page": "https://archive.org/details/Komiku01ChildhoodScene" + }, + { + "id": "komiku-decisive-battle", + "name": "Decisive Battle (excerpt)", + "file": "music/decisive-battle.ogg", + "category": "music", + "tags": [ + "cinematic", + "komiku", + "music" + ], + "bytes": 751206, + "seconds": 50.0, + "source_page": "https://archive.org/details/Komiku01ChildhoodScene" + } + ] +} diff --git a/assets/starter/audio/ricohman-jingles-ditties-cc0/LICENSE.txt b/assets/starter/audio/ricohman-jingles-ditties-cc0/LICENSE.txt new file mode 100644 index 0000000..04fbd7a --- /dev/null +++ b/assets/starter/audio/ricohman-jingles-ditties-cc0/LICENSE.txt @@ -0,0 +1,8 @@ +Source: archive.org items jingles-ditties +Fetched: 2026-11-29 + +https://archive.org/metadata/jingles-ditties licenseurl: http://creativecommons.org/publicdomain/zero/1.0/ +https://archive.org/details/jingles-ditties uploader's description says: + Here are some short songs (jingles, ditties and intros) made with Chaos von Eschenbach (CvE) in 2000-2001, using various scales and rhythms. Using these, I hope you that sell lots of toothpaste, repel some rodents, or that you even have fun listening to these bits of noise. cc0: no rights reserved + +CC0 1.0 Universal legal code: https://creativecommons.org/publicdomain/zero/1.0/legalcode diff --git a/assets/starter/audio/ricohman-jingles-ditties-cc0/music/chr-swing.ogg b/assets/starter/audio/ricohman-jingles-ditties-cc0/music/chr-swing.ogg new file mode 100644 index 0000000..dcbf74d Binary files /dev/null and b/assets/starter/audio/ricohman-jingles-ditties-cc0/music/chr-swing.ogg differ diff --git a/assets/starter/audio/ricohman-jingles-ditties-cc0/music/intro.ogg b/assets/starter/audio/ricohman-jingles-ditties-cc0/music/intro.ogg new file mode 100644 index 0000000..e2a6f53 Binary files /dev/null and b/assets/starter/audio/ricohman-jingles-ditties-cc0/music/intro.ogg differ diff --git a/assets/starter/audio/ricohman-jingles-ditties-cc0/music/phrygia.ogg b/assets/starter/audio/ricohman-jingles-ditties-cc0/music/phrygia.ogg new file mode 100644 index 0000000..0a17eac Binary files /dev/null and b/assets/starter/audio/ricohman-jingles-ditties-cc0/music/phrygia.ogg differ diff --git a/assets/starter/audio/ricohman-jingles-ditties-cc0/music/welcome.ogg b/assets/starter/audio/ricohman-jingles-ditties-cc0/music/welcome.ogg new file mode 100644 index 0000000..356f6b6 Binary files /dev/null and b/assets/starter/audio/ricohman-jingles-ditties-cc0/music/welcome.ogg differ diff --git a/assets/starter/audio/ricohman-jingles-ditties-cc0/pack.json b/assets/starter/audio/ricohman-jingles-ditties-cc0/pack.json new file mode 100644 index 0000000..d77d2ab --- /dev/null +++ b/assets/starter/audio/ricohman-jingles-ditties-cc0/pack.json @@ -0,0 +1,72 @@ +{ + "id": "ricohman-jingles-ditties-cc0", + "name": "Jingles and Ditties (CC0)", + "kind": "audio", + "licence": "CC0-1.0", + "author": "ricohman (made with Chaos von Eschenbach, 2000-2001)", + "source_url": "https://archive.org/details/jingles-ditties", + "source_commit_or_version": "archive.org item originals as of 2026-11-29; encoded to OGG Vorbis q5 (ffmpeg libvorbis), metadata stripped; long files are excerpts from the start with a 2 s fade", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://archive.org/metadata/jingles-ditties", + "https://archive.org/details/jingles-ditties" + ], + "items": [ + { + "id": "ricohman-welcome", + "name": "Welcome", + "file": "music/welcome.ogg", + "category": "music", + "tags": [ + "music", + "ricohman", + "upbeat" + ], + "bytes": 555211, + "seconds": 36.83, + "source_page": "https://archive.org/details/jingles-ditties" + }, + { + "id": "ricohman-chr-swing", + "name": "Chr Swing", + "file": "music/chr-swing.ogg", + "category": "music", + "tags": [ + "music", + "ricohman", + "upbeat" + ], + "bytes": 206354, + "seconds": 16.0, + "source_page": "https://archive.org/details/jingles-ditties" + }, + { + "id": "ricohman-phrygia", + "name": "Phrygia", + "file": "music/phrygia.ogg", + "category": "music", + "tags": [ + "cinematic", + "music", + "ricohman" + ], + "bytes": 258354, + "seconds": 18.75, + "source_page": "https://archive.org/details/jingles-ditties" + }, + { + "id": "ricohman-intro", + "name": "Intro", + "file": "music/intro.ogg", + "category": "music", + "tags": [ + "music", + "ricohman", + "upbeat" + ], + "bytes": 144109, + "seconds": 10.58, + "source_page": "https://archive.org/details/jingles-ditties" + } + ] +} diff --git a/assets/starter/audio/winaaa-bgm-cc0/LICENSE.txt b/assets/starter/audio/winaaa-bgm-cc0/LICENSE.txt new file mode 100644 index 0000000..43a0bb8 --- /dev/null +++ b/assets/starter/audio/winaaa-bgm-cc0/LICENSE.txt @@ -0,0 +1,8 @@ +Source: archive.org items winaaa-bgm-cc0 +Fetched: 2026-11-29 + +https://archive.org/metadata/winaaa-bgm-cc0 licenseurl: http://creativecommons.org/publicdomain/zero/1.0/ +https://archive.org/details/winaaa-bgm-cc0 uploader's description says: + Background music to sit under a speaking voice — explainers, reviews, vlogs, talk, game commentary — in any language. Every file is a seamless loop. CC0 1.0 (public domain dedication): free for any use including monetised YouTube videos and commercial work, no credit required , edit and remix freely. Not registered with Content ID; please do not register these tracks (or videos that only add them) either. How to use: loop to any length; put the music 12–20 LU below the voice (about 15–20 dB quieter). WAV 44.1 kHz stereo and MP3 of the same audio. Tracks (18): calm 1 — Calm piano and pad, no drums (84 BPM, B minor) calm 2 — Slow fingerpicked guitar and soft pad, no drums (76 BPM, F# minor) ca + +CC0 1.0 Universal legal code: https://creativecommons.org/publicdomain/zero/1.0/legalcode diff --git a/assets/starter/audio/winaaa-bgm-cc0/music/alluring-3-dark-piano.ogg b/assets/starter/audio/winaaa-bgm-cc0/music/alluring-3-dark-piano.ogg new file mode 100644 index 0000000..20e4bec Binary files /dev/null and b/assets/starter/audio/winaaa-bgm-cc0/music/alluring-3-dark-piano.ogg differ diff --git a/assets/starter/audio/winaaa-bgm-cc0/music/bright-2-piano-house.ogg b/assets/starter/audio/winaaa-bgm-cc0/music/bright-2-piano-house.ogg new file mode 100644 index 0000000..ec65536 Binary files /dev/null and b/assets/starter/audio/winaaa-bgm-cc0/music/bright-2-piano-house.ogg differ diff --git a/assets/starter/audio/winaaa-bgm-cc0/music/calm-1-piano-and-pad.ogg b/assets/starter/audio/winaaa-bgm-cc0/music/calm-1-piano-and-pad.ogg new file mode 100644 index 0000000..5ba55e4 Binary files /dev/null and b/assets/starter/audio/winaaa-bgm-cc0/music/calm-1-piano-and-pad.ogg differ diff --git a/assets/starter/audio/winaaa-bgm-cc0/pack.json b/assets/starter/audio/winaaa-bgm-cc0/pack.json new file mode 100644 index 0000000..77a21c3 --- /dev/null +++ b/assets/starter/audio/winaaa-bgm-cc0/pack.json @@ -0,0 +1,59 @@ +{ + "id": "winaaa-bgm-cc0", + "name": "WinAAA BGM loops (CC0, excerpts)", + "kind": "audio", + "licence": "CC0-1.0", + "author": "WinAAA", + "source_url": "https://archive.org/details/winaaa-bgm-cc0", + "source_commit_or_version": "archive.org item originals as of 2026-11-29; encoded to OGG Vorbis q5 (ffmpeg libvorbis), metadata stripped; long files are excerpts from the start with a 2 s fade", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://archive.org/metadata/winaaa-bgm-cc0", + "https://archive.org/details/winaaa-bgm-cc0" + ], + "items": [ + { + "id": "winaaa-calm-1-piano-and-pad", + "name": "Calm 1 (piano and pad) (excerpt)", + "file": "music/calm-1-piano-and-pad.ogg", + "category": "music", + "tags": [ + "calm", + "music", + "winaaa" + ], + "bytes": 796187, + "seconds": 50.0, + "source_page": "https://archive.org/details/winaaa-bgm-cc0" + }, + { + "id": "winaaa-bright-2-piano-house", + "name": "Bright 2 (piano house) (excerpt)", + "file": "music/bright-2-piano-house.ogg", + "category": "music", + "tags": [ + "music", + "upbeat", + "winaaa" + ], + "bytes": 711086, + "seconds": 50.0, + "source_page": "https://archive.org/details/winaaa-bgm-cc0" + }, + { + "id": "winaaa-alluring-3-dark-piano", + "name": "Alluring 3 (dark piano) (excerpt)", + "file": "music/alluring-3-dark-piano.ogg", + "category": "music", + "tags": [ + "cinematic", + "music", + "winaaa" + ], + "bytes": 529001, + "seconds": 50.0, + "source_page": "https://archive.org/details/winaaa-bgm-cc0" + } + ], + "caveat": "The publisher says the tracks were made with its own composition code and FreePats instruments dedicated to CC0." +} diff --git a/assets/starter/video/formcraft-generated-video/LICENSE.txt b/assets/starter/video/formcraft-generated-video/LICENSE.txt new file mode 100644 index 0000000..4748cea --- /dev/null +++ b/assets/starter/video/formcraft-generated-video/LICENSE.txt @@ -0,0 +1,140 @@ +CC0 1.0 Universal (Public Domain Dedication) + +To the extent possible under law, NodeAgentc, Inc. (FormCraft) has waived all +copyright and related or neighboring rights to the files in this folder. +The files are original works generated procedurally for the FormCraft project. +They contain no third-party material and no recorded or sampled source files. + +You can copy, modify, distribute and use the works, even for commercial +purposes, all without asking permission. + +Author and dedicator: NodeAgentc, Inc. (FormCraft) +Generating script: gen_video.py (Python, numpy and ffmpeg libx264 only; seed 20261128; kept in the FormCraft build tooling, not shipped) +Each clip is rendered frame by frame from numpy formulas (gradients, noise, shapes) at 640x360 and scaled to 1280x720 by ffmpeg; no input video or image files are read. +Dedication confirmed and legal code fetched 2026-11-29 from +https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt +Deed: https://creativecommons.org/publicdomain/zero/1.0/ + +===== Full text of the CC0 1.0 Universal legal code (as fetched) ===== + +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/assets/starter/video/formcraft-generated-video/abstract/checker-motion.mp4 b/assets/starter/video/formcraft-generated-video/abstract/checker-motion.mp4 new file mode 100644 index 0000000..0bc61de Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/abstract/checker-motion.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/abstract/iris-rings.mp4 b/assets/starter/video/formcraft-generated-video/abstract/iris-rings.mp4 new file mode 100644 index 0000000..bc54546 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/abstract/iris-rings.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/abstract/lava-blobs.mp4 b/assets/starter/video/formcraft-generated-video/abstract/lava-blobs.mp4 new file mode 100644 index 0000000..809da26 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/abstract/lava-blobs.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/abstract/plasma-cool.mp4 b/assets/starter/video/formcraft-generated-video/abstract/plasma-cool.mp4 new file mode 100644 index 0000000..2aaadec Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/abstract/plasma-cool.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/abstract/plasma-hot.mp4 b/assets/starter/video/formcraft-generated-video/abstract/plasma-hot.mp4 new file mode 100644 index 0000000..f342db7 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/abstract/plasma-hot.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/abstract/radial-burst.mp4 b/assets/starter/video/formcraft-generated-video/abstract/radial-burst.mp4 new file mode 100644 index 0000000..3ee9d2f Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/abstract/radial-burst.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/abstract/retro-grid.mp4 b/assets/starter/video/formcraft-generated-video/abstract/retro-grid.mp4 new file mode 100644 index 0000000..9924a62 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/abstract/retro-grid.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/abstract/spectrum-bars.mp4 b/assets/starter/video/formcraft-generated-video/abstract/spectrum-bars.mp4 new file mode 100644 index 0000000..fa4cc1c Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/abstract/spectrum-bars.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/abstract/tunnel.mp4 b/assets/starter/video/formcraft-generated-video/abstract/tunnel.mp4 new file mode 100644 index 0000000..5608207 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/abstract/tunnel.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/abstract/wave-lines.mp4 b/assets/starter/video/formcraft-generated-video/abstract/wave-lines.mp4 new file mode 100644 index 0000000..5256371 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/abstract/wave-lines.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/backgrounds/aurora.mp4 b/assets/starter/video/formcraft-generated-video/backgrounds/aurora.mp4 new file mode 100644 index 0000000..223ead2 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/backgrounds/aurora.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/backgrounds/gradient-mono.mp4 b/assets/starter/video/formcraft-generated-video/backgrounds/gradient-mono.mp4 new file mode 100644 index 0000000..310fc60 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/backgrounds/gradient-mono.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/backgrounds/gradient-ocean.mp4 b/assets/starter/video/formcraft-generated-video/backgrounds/gradient-ocean.mp4 new file mode 100644 index 0000000..64da452 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/backgrounds/gradient-ocean.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/backgrounds/gradient-sunset.mp4 b/assets/starter/video/formcraft-generated-video/backgrounds/gradient-sunset.mp4 new file mode 100644 index 0000000..dd1c5de Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/backgrounds/gradient-sunset.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/leaders/colour-bars.mp4 b/assets/starter/video/formcraft-generated-video/leaders/colour-bars.mp4 new file mode 100644 index 0000000..a963944 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/leaders/colour-bars.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/leaders/countdown-leader.mp4 b/assets/starter/video/formcraft-generated-video/leaders/countdown-leader.mp4 new file mode 100644 index 0000000..b1f87e8 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/leaders/countdown-leader.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/overlays/bokeh-lights.mp4 b/assets/starter/video/formcraft-generated-video/overlays/bokeh-lights.mp4 new file mode 100644 index 0000000..a22b5b8 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/overlays/bokeh-lights.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/overlays/film-grain.mp4 b/assets/starter/video/formcraft-generated-video/overlays/film-grain.mp4 new file mode 100644 index 0000000..33845ca Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/overlays/film-grain.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/overlays/light-leak-amber.mp4 b/assets/starter/video/formcraft-generated-video/overlays/light-leak-amber.mp4 new file mode 100644 index 0000000..deb02fd Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/overlays/light-leak-amber.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/overlays/light-leak-magenta.mp4 b/assets/starter/video/formcraft-generated-video/overlays/light-leak-magenta.mp4 new file mode 100644 index 0000000..4b54b78 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/overlays/light-leak-magenta.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/overlays/vhs-slate.mp4 b/assets/starter/video/formcraft-generated-video/overlays/vhs-slate.mp4 new file mode 100644 index 0000000..37a9d00 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/overlays/vhs-slate.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/overlays/vignette-pulse.mp4 b/assets/starter/video/formcraft-generated-video/overlays/vignette-pulse.mp4 new file mode 100644 index 0000000..29a243b Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/overlays/vignette-pulse.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/pack.json b/assets/starter/video/formcraft-generated-video/pack.json new file mode 100644 index 0000000..38ffb8f --- /dev/null +++ b/assets/starter/video/formcraft-generated-video/pack.json @@ -0,0 +1,450 @@ +{ + "id": "formcraft-generated-video", + "name": "FormCraft Generated Video (original)", + "kind": "video", + "licence": "CC0-1.0", + "author": "NodeAgentc, Inc. (FormCraft)", + "source_url": "generated", + "source_commit_or_version": "gen_video.py, numpy + ffmpeg libx264, seed 20261128", + "retrieved": "2026-11-28", + "licence_evidence": [ + "https://creativecommons.org/publicdomain/zero/1.0/legalcode", + "https://creativecommons.org/publicdomain/zero/1.0/" + ], + "items": [ + { + "id": "formcraft-gen-gradient-ocean", + "name": "Gradient Ocean Drift", + "file": "backgrounds/gradient-ocean.mp4", + "category": "backgrounds", + "tags": [ + "blue", + "calm", + "generated", + "gradient", + "loop" + ], + "bytes": 282893, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-gradient-sunset", + "name": "Gradient Sunset Drift", + "file": "backgrounds/gradient-sunset.mp4", + "category": "backgrounds", + "tags": [ + "generated", + "gradient", + "loop", + "orange", + "warm" + ], + "bytes": 284976, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-gradient-mono", + "name": "Gradient Slate Drift", + "file": "backgrounds/gradient-mono.mp4", + "category": "backgrounds", + "tags": [ + "generated", + "gradient", + "grey", + "loop", + "neutral" + ], + "bytes": 214245, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-aurora", + "name": "Aurora Bands", + "file": "backgrounds/aurora.mp4", + "category": "backgrounds", + "tags": [ + "aurora", + "generated", + "green", + "loop", + "night" + ], + "bytes": 321873, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-plasma-cool", + "name": "Plasma Cool", + "file": "abstract/plasma-cool.mp4", + "category": "abstract", + "tags": [ + "blue", + "generated", + "loop", + "plasma", + "teal" + ], + "bytes": 342245, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-plasma-hot", + "name": "Plasma Hot", + "file": "abstract/plasma-hot.mp4", + "category": "abstract", + "tags": [ + "generated", + "loop", + "magenta", + "orange", + "plasma" + ], + "bytes": 335067, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-lava-blobs", + "name": "Lava Blobs", + "file": "abstract/lava-blobs.mp4", + "category": "abstract", + "tags": [ + "blobs", + "generated", + "loop", + "organic", + "warm" + ], + "bytes": 381495, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-wave-lines", + "name": "Wave Lines", + "file": "abstract/wave-lines.mp4", + "category": "abstract", + "tags": [ + "generated", + "lines", + "loop", + "neon", + "waves" + ], + "bytes": 940777, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-iris-rings", + "name": "Iris Rings", + "file": "abstract/iris-rings.mp4", + "category": "abstract", + "tags": [ + "generated", + "hypnotic", + "loop", + "rings", + "teal" + ], + "bytes": 604373, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-spectrum-bars", + "name": "Spectrum Bars", + "file": "abstract/spectrum-bars.mp4", + "category": "abstract", + "tags": [ + "audio", + "bars", + "generated", + "loop", + "neon" + ], + "bytes": 245065, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-checker-motion", + "name": "Checker Motion", + "file": "abstract/checker-motion.mp4", + "category": "abstract", + "tags": [ + "checker", + "generated", + "geometric", + "green", + "loop" + ], + "bytes": 874318, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-radial-burst", + "name": "Radial Burst", + "file": "abstract/radial-burst.mp4", + "category": "abstract", + "tags": [ + "burst", + "generated", + "loop", + "pink", + "rays" + ], + "bytes": 361281, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-retro-grid", + "name": "Retro Grid Run", + "file": "abstract/retro-grid.mp4", + "category": "abstract", + "tags": [ + "generated", + "grid", + "loop", + "perspective", + "synthwave" + ], + "bytes": 230696, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-tunnel", + "name": "Tunnel Flight", + "file": "abstract/tunnel.mp4", + "category": "abstract", + "tags": [ + "blue", + "depth", + "generated", + "loop", + "tunnel" + ], + "bytes": 567287, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-dust-motes", + "name": "Dust Motes Rising", + "file": "particles/dust-motes.mp4", + "category": "particles", + "tags": [ + "dust", + "generated", + "loop", + "particles", + "warm" + ], + "bytes": 440816, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-snow-fall", + "name": "Snow Fall", + "file": "particles/snow-fall.mp4", + "category": "particles", + "tags": [ + "generated", + "loop", + "particles", + "snow", + "winter" + ], + "bytes": 489092, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-embers-rise", + "name": "Embers Rising", + "file": "particles/embers-rise.mp4", + "category": "particles", + "tags": [ + "embers", + "fire", + "generated", + "loop", + "particles" + ], + "bytes": 441413, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-starfield-flight", + "name": "Starfield Flight", + "file": "particles/starfield-flight.mp4", + "category": "particles", + "tags": [ + "forward", + "generated", + "loop", + "space", + "stars" + ], + "bytes": 467774, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-rain-streaks", + "name": "Rain Streaks", + "file": "particles/rain-streaks.mp4", + "category": "particles", + "tags": [ + "generated", + "loop", + "night", + "rain", + "weather" + ], + "bytes": 778278, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-fog-clouds", + "name": "Fog and Clouds", + "file": "textures/fog-clouds.mp4", + "category": "textures", + "tags": [ + "clouds", + "fog", + "generated", + "loop", + "soft" + ], + "bytes": 376212, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-smoke-flow", + "name": "Smoke Flow", + "file": "textures/smoke-flow.mp4", + "category": "textures", + "tags": [ + "dark", + "flow", + "generated", + "loop", + "smoke" + ], + "bytes": 341879, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-bokeh-lights", + "name": "Bokeh Lights", + "file": "overlays/bokeh-lights.mp4", + "category": "overlays", + "tags": [ + "bokeh", + "generated", + "lights", + "loop", + "soft" + ], + "bytes": 314464, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-light-leak-amber", + "name": "Light Leak Amber", + "file": "overlays/light-leak-amber.mp4", + "category": "overlays", + "tags": [ + "amber", + "film", + "generated", + "light-leak", + "loop" + ], + "bytes": 240106, + "seconds": 6.0 + }, + { + "id": "formcraft-gen-light-leak-magenta", + "name": "Light Leak Magenta", + "file": "overlays/light-leak-magenta.mp4", + "category": "overlays", + "tags": [ + "film", + "generated", + "light-leak", + "loop", + "magenta" + ], + "bytes": 235740, + "seconds": 6.0 + }, + { + "id": "formcraft-gen-film-grain", + "name": "Film Grain Dark", + "file": "overlays/film-grain.mp4", + "category": "overlays", + "tags": [ + "film", + "generated", + "grain", + "loop", + "texture" + ], + "bytes": 164677, + "seconds": 6.0 + }, + { + "id": "formcraft-gen-vignette-pulse", + "name": "Vignette Pulse", + "file": "overlays/vignette-pulse.mp4", + "category": "overlays", + "tags": [ + "generated", + "grey", + "loop", + "pulse", + "vignette" + ], + "bytes": 88416, + "seconds": 6.0 + }, + { + "id": "formcraft-gen-vhs-slate", + "name": "VHS Slate Noise", + "file": "overlays/vhs-slate.mp4", + "category": "overlays", + "tags": [ + "generated", + "loop", + "noise", + "retro", + "vhs" + ], + "bytes": 191071, + "seconds": 6.0 + }, + { + "id": "formcraft-gen-countdown-leader", + "name": "Countdown Leader 8 to 1", + "file": "leaders/countdown-leader.mp4", + "category": "leaders", + "tags": [ + "countdown", + "film", + "generated", + "leader" + ], + "bytes": 257651, + "seconds": 8.0 + }, + { + "id": "formcraft-gen-colour-bars", + "name": "Colour Bars", + "file": "leaders/colour-bars.mp4", + "category": "leaders", + "tags": [ + "bars", + "generated", + "loop", + "smpte-style", + "test" + ], + "bytes": 37082, + "seconds": 6.0 + } + ] +} \ No newline at end of file diff --git a/assets/starter/video/formcraft-generated-video/particles/dust-motes.mp4 b/assets/starter/video/formcraft-generated-video/particles/dust-motes.mp4 new file mode 100644 index 0000000..3e0287c Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/particles/dust-motes.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/particles/embers-rise.mp4 b/assets/starter/video/formcraft-generated-video/particles/embers-rise.mp4 new file mode 100644 index 0000000..5a28bfc Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/particles/embers-rise.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/particles/rain-streaks.mp4 b/assets/starter/video/formcraft-generated-video/particles/rain-streaks.mp4 new file mode 100644 index 0000000..e4b8042 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/particles/rain-streaks.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/particles/snow-fall.mp4 b/assets/starter/video/formcraft-generated-video/particles/snow-fall.mp4 new file mode 100644 index 0000000..8d6c6b4 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/particles/snow-fall.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/particles/starfield-flight.mp4 b/assets/starter/video/formcraft-generated-video/particles/starfield-flight.mp4 new file mode 100644 index 0000000..164dfb9 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/particles/starfield-flight.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/textures/fog-clouds.mp4 b/assets/starter/video/formcraft-generated-video/textures/fog-clouds.mp4 new file mode 100644 index 0000000..2fae806 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/textures/fog-clouds.mp4 differ diff --git a/assets/starter/video/formcraft-generated-video/textures/smoke-flow.mp4 b/assets/starter/video/formcraft-generated-video/textures/smoke-flow.mp4 new file mode 100644 index 0000000..7efa6c3 Binary files /dev/null and b/assets/starter/video/formcraft-generated-video/textures/smoke-flow.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/LICENSE.txt b/assets/starter/video/prelinger-archives-pd/LICENSE.txt new file mode 100644 index 0000000..fd38658 --- /dev/null +++ b/assets/starter/video/prelinger-archives-pd/LICENSE.txt @@ -0,0 +1,54 @@ +Source: https://www.panix.com/~footage/prelarch.html (Prelinger Archives: Licensing, Access, Collections; revised May 27, 2026) +Fetched: 2026-11-29 +Second statement: each item's own record at https://archive.org/metadata/<identifier>/metadata/licenseurl returns http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication). + +The publisher's statement as fetched (plain text of the page): + +Prelinger Archives: Licensing, Access, Collections +Prelinger Archives FAQ: Usage, Access, Collections(revised May 27, 2026) +IF YOU NEED ARCHIVAL OR STOCK FOOTAGE, PLEASE READ THIS ENTIRE PAGE BEFORE CONTACTING US. +PLEASE NOTE: +Many people believe that all Prelinger Archives films are in the public domain. Some are. Many are not. DO NOT ASSUME that all Prelinger Archives films are in the public domain, or that all of them carry Creative Commons licenses. +We would appreciate your reading questions 4, 5, 6 and 7 below for further information. +1. How can I access films or footage from Prelinger Archives? +DATABASE: A searchable database of films available online at Internet Archive is here. +DOWNLOADING: +You can freely download digital files from the Prelinger Collection at Internet Archive. Many files are available under the Creative Commons Public Domain Dedication, which means you can use them according to the terms of the license, generally without cost or restriction. If a film does not carry a Creative Commons license, you may wish to search for other occurrences of the same film at Internet Archive that do carry the license. If after searching you do not find a version with a Creative Commons license and still wish to reuse the film, you may contact us at prelingerclips@gmail.com for information. If you wish a written usage agreement, contact us at prelingerclips@gmail.com. We are unfortunately not able to provide written usage agreements for free. +Please note: While Creative Commons has "retired" their Public Domain Dedication and no longer recommends its use, it does not expire, and our dedication of materials to the public domain still stands. +CLIP LICENSING: Getty Images maintains a searchable database offering over 19,000 archival clips from our collection (many in 4K and HD) that are available for fee-based licensing. Getty Images furnishes written license agreements. +If the material you wish to use is not in the Getty Images database, or if you have further questions, please contact us at prelingerclips@gmail.com for further information. +The rest of this FAQ gives more detail about these two ways to access our collection. Please read this entire page before contacting us with questions. +2. How do I license stock footage and get a written license agreement? +Getty Images has a searchable database with over 19,000 archival clips from our collection (many in 4K and HD) that are available for fee-based licensing. Getty Images furnishes written license agreements and offers rapid access to all available material. They can research the collection for specific topics and deliver highest-quality material very quickly in all formats. +If you are in need of stock footage that is not shown in Getty's clip database, please contact Getty as follows: +Getty Images Customer Support +If the material you wish to use is not in the Getty Images database, or if you have further questions, please contact us at prelingerclips@gmail.com for further information. +3. How can I get access to films or stock footage for free? +Most key items in our collection are also available for free viewing and downloading through Internet Archive. This site hosts digital video files representing approximately 10,300 key films from the Prelinger collection. We anticipate that the films on this site will satisfy most research requests. +Online Prelinger films at Internet Archive fall into two categories: +New films (beginning 2023). These films have been scanned in 5K or 4K (ProRes 4444HQ), sometimes 2K (ProRes 422HQ) and occasionally HD (ProRes 422HQ) on a Lasergraphics ScanStation. Typically we offer them, with some exceptions, as h.264 mp4 files at 12Mbps bitrate. With a few exceptions, these are the highest-quality films we offer for free viewing and download. You can find newly uploaded films by sorting by "Date Archived." To see what files are available to download for a specific film, please follow the SHOW ALL link on the film's detail page, and you will be taken to a directory showing the available films. +Older films (2000-2022). These films were transferred to NTSC video using telecine equipment that in its time was state of the art but is now obsolete. They are available in MPEG-2 and MPEG-4 files that are high-quality but compressed, and thus lack some of the detail, resolution and fluidity of today's broadcast-quality video. They are, however, excellent for research, screening, teaching and low-end production use. Many of our older online films are offered under the Creative Commons Public Domain Dedication. +4. Aren't all Prelinger films in the public domain? How can I find out the copyright status of a specific film? +Many people have been led to believe that all films in Prelinger Archives are in the public domain. This is not true. While some Prelinger films are in the public domain, many are not. Many Prelinger films carry a Creative Commons Public Domain Dedication. Others do not. For films without a Creative Commons Public Domain dedication, please contact us at prelingerclips@gmail.com for information on how to reuse them. +The copyright status of films in our online collection varies. Some are in public domain. We own the copyright to some items. Others are orphan works, meaning that they may be in copyright but the copyright holder is unknown or unable to be located. Copyright is a complex set of laws, regulations and practices, and it is not possible to make simple generalizations about the copyright status of a specific work. +Prelinger Archives cannot make informal representations as to the copyright status of a work. Doing so may constitute a legal commitment, and we can only specify copyright status as part of a written use agreement (for information on these, please see question 6 below). You are, of course, welcome to do your own copyright research. Two useful resources that may be helpful if you begin researching copyright status are Cornell University's page on Copyright Term and the Public Domain and Glen Secor's excellent book The Public Domain, available from Nolo Press. +5. Why don't all online Prelinger films carry a Creative Commons license? +Prelinger Archives used the Creative Commons Public Domain Dedication for many years. After some time it became clear that this license did not work well with many films in our archives and we stopped using it. Please note that this Public Domain dedication still governs films to which it has been affixed. For films without a Creative Commons license, please contact us at prelingerclips@gmail.com for information on how to reuse them. Please note: While Creative Commons has "retired" the Public Domain Dedication and no longer recommends its use, it does not expire, and our dedication of materials to the public domain still stands. +6. How can I get a written license agreement for Prelinger films? How can I get a written guarantee that material is free to use? +If you require a written license agreement, please contact us at prelingerclips@gmail.com. We are unfortunately not able to provide written usage agreements for free. The Internet Archive does NOT furnish written license agreements nor make any warranties or representations as to the footage other than what may be stated on its website. In addition, please be aware that the Internet Archive hosts other collections besides Prelinger Archives on its site, and some of these collections may carry certain restrictions that differ from the Prelinger Archives. The Internet Archive does NOT furnish copies of these films on film, videotape, DVD, hard drives or other physical media. +Please note that Internet Archive holds millions of video files from sources other than Prelinger Archives. We cannot offer additional information about, or provide rights clearances for non-Prelinger films. +7. Do I need further permission to use digital files of Prelinger Collection films? +You can freely download digital files from the Prelinger Collection at Internet Archive. Many files are available under the Creative Commons Public Domain Dedication, which means you can use them according to the terms of the license, generally without cost or restriction. If a film does not carry a Creative Commons license, you may wish to search for other occurrences of the same film at Internet Archive that do carry the license. If after searching you do not find a version with a Creative Commons license and still wish to reuse the film, you may contact us for information. If you wish a written usage agreement, please contact us at prelingerclips@gmail.com. We are unfortunately not able to provide written usage agreements for free. +Please be aware that public domain materials may occasionally incorporate copyrighted elements (such as music, images and archival footage) that might not be free to use outside the context of the original film. We urge you to seek legal advice if you are in doubt regarding the materials you wish to use. +8. Can I get access to physical film materials in Prelinger Archives? +The original Prelinger Archives film collection (1983-2002) was acquired by the Library of Congress in August 2002. The Library is in the process of accessioning this collection and cannot currently fulfill any research requests. However, Prelinger Archives holds approximately 15,000 titles in video and digital formats, which are available through Getty Images and Prelinger Archives. In addition, films acquired subsequent to 2002 are often held in physical form and are sometimes available for screening at venues qualified to present archival films. +9. How can I get Internet Archive technical support? +If you need technical support regarding the Internet Archive, you may address questions and issues to Archive Support at info@archive.org. +10. Do I need to credit Prelinger Archives or Internet Archive when I use your material? +We would be delighted if you credit Prelinger Archives and Internet Archive (www.archive.org/details/prelinger) for films or footage that you use, but we do not require that you do so. We'd love to see what you've made using our footage if you are interested in sending us a copy (postal address here), but this is your choice. +11. Can I license complete films from Prelinger Archives for use in programming? +Prelinger Archives can provide films in their entirety or for use as programming. Please contact us at prelingerclips@gmail.com to discuss your need for archival films as program content in all media and markets. +12. Is there other access to Prelinger Archives? +We provide access to researchers, scholars, noncommercial users and interested members of the public, subject to certain time and resource limitations. We prefer to fulfill as many research needs as possible through the facilities of the Internet Archive (see above). If you wish to access our archives for other purposes, please contact Rick Prelinger at prelingerclips@gmail.com. +May 27, 2026 +Home diff --git a/assets/starter/video/prelinger-archives-pd/city/manhattan-skyline-bridge.mp4 b/assets/starter/video/prelinger-archives-pd/city/manhattan-skyline-bridge.mp4 new file mode 100644 index 0000000..45e2856 Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/city/manhattan-skyline-bridge.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/city/manhattan-skyline-harbor.mp4 b/assets/starter/video/prelinger-archives-pd/city/manhattan-skyline-harbor.mp4 new file mode 100644 index 0000000..cb65334 Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/city/manhattan-skyline-harbor.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/city/street-traffic-trams.mp4 b/assets/starter/video/prelinger-archives-pd/city/street-traffic-trams.mp4 new file mode 100644 index 0000000..a705768 Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/city/street-traffic-trams.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/city/suspension-bridge-span.mp4 b/assets/starter/video/prelinger-archives-pd/city/suspension-bridge-span.mp4 new file mode 100644 index 0000000..6f291d5 Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/city/suspension-bridge-span.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/industrial/glowing-steel-slab.mp4 b/assets/starter/video/prelinger-archives-pd/industrial/glowing-steel-slab.mp4 new file mode 100644 index 0000000..2718169 Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/industrial/glowing-steel-slab.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/industrial/iron-stream.mp4 b/assets/starter/video/prelinger-archives-pd/industrial/iron-stream.mp4 new file mode 100644 index 0000000..e3bf36b Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/industrial/iron-stream.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/industrial/molten-steel-pour.mp4 b/assets/starter/video/prelinger-archives-pd/industrial/molten-steel-pour.mp4 new file mode 100644 index 0000000..dc1e443 Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/industrial/molten-steel-pour.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/pack.json b/assets/starter/video/prelinger-archives-pd/pack.json new file mode 100644 index 0000000..89a6a53 --- /dev/null +++ b/assets/starter/video/prelinger-archives-pd/pack.json @@ -0,0 +1,509 @@ +{ + "id": "prelinger-archives-pd", + "name": "Prelinger Archives (public domain dedication, archival film excerpts)", + "kind": "video", + "licence": "CC-PD-Dedication-1.0-legacy", + "licence_note": "Creative Commons Public Domain Dedication (the retired predecessor of CC0). Prelinger Archives states the dedication still stands. Not literally CC0-1.0: orchestrator to accept or reject.", + "author": "Prelinger Archives (films by various original producers; excerpts, audio removed)", + "source_url": "https://archive.org/details/prelinger", + "source_commit_or_version": "archive.org item MP4 derivatives as of 2026-11-29; FAQ revised May 27, 2026", + "retrieved": "2026-11-29", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/prelinger/metadata" + ], + "caveat": "Publisher FAQ: public domain materials may occasionally incorporate copyrighted elements (music, images, archival footage). All audio removed; excerpts are picture only. Only items whose own record carries the dedication were used.", + "items": [ + { + "id": "prelinger-earth-globe-model", + "name": "Earth globe model (from \"Heavenly Bodies\")", + "file": "space/earth-globe-model.mp4", + "category": "space", + "tags": [ + "1920", + "animation", + "archival", + "earth", + "prelinger", + "space" + ], + "bytes": 759123, + "seconds": 8.0, + "source_page": "https://archive.org/details/Heavenly1920", + "original_title": "Heavenly Bodies", + "archive_org_identifier": "Heavenly1920", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "1920s", + "original_publisher": "Unknown", + "excerpt_start_seconds": 86.17, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/Heavenly1920/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-moon-crescent", + "name": "Crescent moon model (from \"Heavenly Bodies\")", + "file": "space/moon-crescent.mp4", + "category": "space", + "tags": [ + "archival", + "crescent", + "moon", + "prelinger", + "space" + ], + "bytes": 836337, + "seconds": 8.0, + "source_page": "https://archive.org/details/Heavenly1920", + "original_title": "Heavenly Bodies", + "archive_org_identifier": "Heavenly1920", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "1920s", + "original_publisher": "Unknown", + "excerpt_start_seconds": 333.25, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/Heavenly1920/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-cumulus-over-pines", + "name": "Cumulus cloud over pines (from \"River, The (Part I)\")", + "file": "sky/cumulus-over-pines.mp4", + "category": "sky", + "tags": [ + "archival", + "bw", + "clouds", + "prelinger", + "sky", + "trees" + ], + "bytes": 376002, + "seconds": 6.88, + "source_page": "https://archive.org/details/RiverThe1937", + "original_title": "River, The (Part I)", + "archive_org_identifier": "RiverThe1937", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "1937", + "original_publisher": "U.S. Department of Agriculture, Resettlement Administration", + "excerpt_start_seconds": 499.88, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/RiverThe1937/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-cloud-bank", + "name": "Cloud bank over hills (from \"River, The (Part I)\")", + "file": "sky/cloud-bank.mp4", + "category": "sky", + "tags": [ + "archival", + "bw", + "clouds", + "prelinger", + "sky" + ], + "bytes": 709949, + "seconds": 8.0, + "source_page": "https://archive.org/details/RiverThe1937", + "original_title": "River, The (Part I)", + "archive_org_identifier": "RiverThe1937", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "1937", + "original_publisher": "U.S. Department of Agriculture, Resettlement Administration", + "excerpt_start_seconds": 507.26, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/RiverThe1937/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-dam-spillway", + "name": "Dam spillway (from \"Mighty Columbia River, The\")", + "file": "water/dam-spillway.mp4", + "category": "water", + "tags": [ + "archival", + "color", + "dam", + "prelinger", + "river", + "water" + ], + "bytes": 565219, + "seconds": 5.61, + "source_page": "https://archive.org/details/MightyCo1947", + "original_title": "Mighty Columbia River, The", + "archive_org_identifier": "MightyCo1947", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "1947", + "original_publisher": "Coronet Instructional Films", + "excerpt_start_seconds": 87.5, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/MightyCo1947/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-river-rapids", + "name": "River rapids (from \"Mighty Columbia River, The\")", + "file": "water/river-rapids.mp4", + "category": "water", + "tags": [ + "archival", + "color", + "prelinger", + "rapids", + "river", + "water" + ], + "bytes": 991879, + "seconds": 5.67, + "source_page": "https://archive.org/details/MightyCo1947", + "original_title": "Mighty Columbia River, The", + "archive_org_identifier": "MightyCo1947", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "1947", + "original_publisher": "Coronet Instructional Films", + "excerpt_start_seconds": 183.2, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/MightyCo1947/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-rapids-and-fishway", + "name": "Rapids beside a fishway (from \"Mighty Columbia River, The\")", + "file": "water/rapids-and-fishway.mp4", + "category": "water", + "tags": [ + "archival", + "color", + "prelinger", + "rapids", + "water" + ], + "bytes": 643047, + "seconds": 8.0, + "source_page": "https://archive.org/details/MightyCo1947", + "original_title": "Mighty Columbia River, The", + "archive_org_identifier": "MightyCo1947", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "1947", + "original_publisher": "Coronet Instructional Films", + "excerpt_start_seconds": 196.88, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/MightyCo1947/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-niagara-horseshoe-falls", + "name": "Horseshoe Falls (from \"[Amateur Film: Wathen Collection: Niagara Falls and Austin, Texas]\")", + "file": "water/niagara-horseshoe-falls.mp4", + "category": "water", + "tags": [ + "archival", + "color", + "prelinger", + "silent", + "water", + "waterfall" + ], + "bytes": 461885, + "seconds": 5.44, + "source_page": "https://archive.org/details/WathenCo48", + "original_title": "[Amateur Film: Wathen Collection: Niagara Falls and Austin, Texas]", + "archive_org_identifier": "WathenCo48", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "ca. 1947 - 48", + "original_publisher": "Unknown", + "excerpt_start_seconds": 117.17, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/WathenCo48/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-niagara-rainbow-falls", + "name": "Falls with rainbow (from \"[Amateur Film: Wathen Collection: Niagara Falls and Austin, Texas]\")", + "file": "water/niagara-rainbow-falls.mp4", + "category": "water", + "tags": [ + "archival", + "color", + "prelinger", + "rainbow", + "silent", + "water", + "waterfall" + ], + "bytes": 1618472, + "seconds": 8.0, + "source_page": "https://archive.org/details/WathenCo48", + "original_title": "[Amateur Film: Wathen Collection: Niagara Falls and Austin, Texas]", + "archive_org_identifier": "WathenCo48", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "ca. 1947 - 48", + "original_publisher": "Unknown", + "excerpt_start_seconds": 150.33, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/WathenCo48/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-coast-surf-rocks", + "name": "Surf on coastal rocks (from \"Golden Gate City\")", + "file": "water/coast-surf-rocks.mp4", + "category": "water", + "tags": [ + "archival", + "bw", + "coast", + "prelinger", + "rocks", + "water", + "waves" + ], + "bytes": 1206885, + "seconds": 5.27, + "source_page": "https://archive.org/details/golden_gate_city", + "original_title": "Golden Gate City", + "archive_org_identifier": "golden_gate_city", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "", + "original_publisher": "Castle Films", + "excerpt_start_seconds": 538.35, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/golden_gate_city/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-manhattan-skyline-harbor", + "name": "Skyline from the harbor (from \"Manhattan Waterfront\")", + "file": "city/manhattan-skyline-harbor.mp4", + "category": "city", + "tags": [ + "archival", + "bw", + "city", + "harbor", + "prelinger", + "skyline" + ], + "bytes": 1376564, + "seconds": 8.0, + "source_page": "https://archive.org/details/ManhattanWat", + "original_title": "Manhattan Waterfront", + "archive_org_identifier": "ManhattanWat", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "", + "original_publisher": "", + "excerpt_start_seconds": 24.84, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/ManhattanWat/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-manhattan-skyline-bridge", + "name": "Skyline and bridge (from \"Manhattan Waterfront\")", + "file": "city/manhattan-skyline-bridge.mp4", + "category": "city", + "tags": [ + "archival", + "bridge", + "bw", + "city", + "prelinger", + "skyline" + ], + "bytes": 1046722, + "seconds": 8.0, + "source_page": "https://archive.org/details/ManhattanWat", + "original_title": "Manhattan Waterfront", + "archive_org_identifier": "ManhattanWat", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "", + "original_publisher": "", + "excerpt_start_seconds": 245.33, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/ManhattanWat/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-suspension-bridge-span", + "name": "Suspension bridge (from \"Manhattan Waterfront\")", + "file": "city/suspension-bridge-span.mp4", + "category": "city", + "tags": [ + "archival", + "bridge", + "bw", + "city", + "prelinger" + ], + "bytes": 1106663, + "seconds": 8.0, + "source_page": "https://archive.org/details/ManhattanWat", + "original_title": "Manhattan Waterfront", + "archive_org_identifier": "ManhattanWat", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "", + "original_publisher": "", + "excerpt_start_seconds": 502.99, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/ManhattanWat/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-street-traffic-trams", + "name": "Busy street with trams and cars (from \"Golden Gate City\")", + "file": "city/street-traffic-trams.mp4", + "category": "city", + "tags": [ + "archival", + "bw", + "city", + "prelinger", + "street", + "traffic" + ], + "bytes": 1184665, + "seconds": 5.44, + "source_page": "https://archive.org/details/golden_gate_city", + "original_title": "Golden Gate City", + "archive_org_identifier": "golden_gate_city", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "", + "original_publisher": "Castle Films", + "excerpt_start_seconds": 123.37, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/golden_gate_city/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-molten-steel-pour", + "name": "Molten steel (from \"Steel: A Symphony of Industry\")", + "file": "industrial/molten-steel-pour.mp4", + "category": "industrial", + "tags": [ + "archival", + "bw", + "glow", + "industrial", + "prelinger", + "steel" + ], + "bytes": 871550, + "seconds": 8.0, + "source_page": "https://archive.org/details/SteelASy1936", + "original_title": "Steel: A Symphony of Industry", + "archive_org_identifier": "SteelASy1936", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "1936", + "original_publisher": "Audio Productions", + "excerpt_start_seconds": 726.94, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/SteelASy1936/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-glowing-steel-slab", + "name": "Glowing steel slab (from \"Steel: A Symphony of Industry\")", + "file": "industrial/glowing-steel-slab.mp4", + "category": "industrial", + "tags": [ + "archival", + "bw", + "glow", + "industrial", + "prelinger", + "steel" + ], + "bytes": 751912, + "seconds": 8.0, + "source_page": "https://archive.org/details/SteelASy1936", + "original_title": "Steel: A Symphony of Industry", + "archive_org_identifier": "SteelASy1936", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "1936", + "original_publisher": "Audio Productions", + "excerpt_start_seconds": 870.49, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/SteelASy1936/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + }, + { + "id": "prelinger-iron-stream", + "name": "Iron stream (from \"Industries of the United States: Steel - The Hardest Metal in the World\")", + "file": "industrial/iron-stream.mp4", + "category": "industrial", + "tags": [ + "archival", + "bw", + "industrial", + "prelinger", + "sparks", + "steel" + ], + "bytes": 438359, + "seconds": 8.0, + "source_page": "https://archive.org/details/steel_the_hardest_metal", + "original_title": "Industries of the United States: Steel - The Hardest Metal in the World", + "archive_org_identifier": "steel_the_hardest_metal", + "item_licenseurl": "http://creativecommons.org/licenses/publicdomain/", + "original_date": "", + "original_publisher": "", + "excerpt_start_seconds": 122.81, + "audio": "removed", + "licence_evidence": [ + "https://www.panix.com/~footage/prelarch.html", + "https://archive.org/metadata/steel_the_hardest_metal/metadata/licenseurl" + ], + "licence_statement": "Item record licenseurl = http://creativecommons.org/licenses/publicdomain/ (Creative Commons Public Domain Dedication)" + } + ] +} \ No newline at end of file diff --git a/assets/starter/video/prelinger-archives-pd/sky/cloud-bank.mp4 b/assets/starter/video/prelinger-archives-pd/sky/cloud-bank.mp4 new file mode 100644 index 0000000..422ce09 Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/sky/cloud-bank.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/sky/cumulus-over-pines.mp4 b/assets/starter/video/prelinger-archives-pd/sky/cumulus-over-pines.mp4 new file mode 100644 index 0000000..182323e Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/sky/cumulus-over-pines.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/space/earth-globe-model.mp4 b/assets/starter/video/prelinger-archives-pd/space/earth-globe-model.mp4 new file mode 100644 index 0000000..7963d0d Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/space/earth-globe-model.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/space/moon-crescent.mp4 b/assets/starter/video/prelinger-archives-pd/space/moon-crescent.mp4 new file mode 100644 index 0000000..21c1857 Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/space/moon-crescent.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/water/coast-surf-rocks.mp4 b/assets/starter/video/prelinger-archives-pd/water/coast-surf-rocks.mp4 new file mode 100644 index 0000000..a4cd110 Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/water/coast-surf-rocks.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/water/dam-spillway.mp4 b/assets/starter/video/prelinger-archives-pd/water/dam-spillway.mp4 new file mode 100644 index 0000000..248149c Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/water/dam-spillway.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/water/niagara-horseshoe-falls.mp4 b/assets/starter/video/prelinger-archives-pd/water/niagara-horseshoe-falls.mp4 new file mode 100644 index 0000000..421028f Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/water/niagara-horseshoe-falls.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/water/niagara-rainbow-falls.mp4 b/assets/starter/video/prelinger-archives-pd/water/niagara-rainbow-falls.mp4 new file mode 100644 index 0000000..29940cc Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/water/niagara-rainbow-falls.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/water/rapids-and-fishway.mp4 b/assets/starter/video/prelinger-archives-pd/water/rapids-and-fishway.mp4 new file mode 100644 index 0000000..6585cf7 Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/water/rapids-and-fishway.mp4 differ diff --git a/assets/starter/video/prelinger-archives-pd/water/river-rapids.mp4 b/assets/starter/video/prelinger-archives-pd/water/river-rapids.mp4 new file mode 100644 index 0000000..63c2608 Binary files /dev/null and b/assets/starter/video/prelinger-archives-pd/water/river-rapids.mp4 differ diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 70b4453..acff4bd 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2246,3 +2246,24 @@ From VERIFY_v0.8.0_E2E.md. A closed page's long poll could take a queued call: t - **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. - **CI.** The `install` job runs `./formcraft install` and the self-check. `install-desktop`, the freeze and the desktop build still run in no job. - Removed code: none. + +## 2026-11-29 · v0.10.0 the usability round {#usable-v0100} + +- **Binaries (`services/binaries.py`).** One resolver for ffmpeg and ffprobe that follows the formai-binaries record; `ffmpeg_fetch.locate()`, `encoders.selected()` and `encode_sessions.py` go through it. The old formcut-binaries address stays as the fallback, and the shared install folder keeps its name. Adapted from formcut `backend/app/tools.py` and `ffmpeg_fetch.py` and formencoder `backend/app/ffmpeg_fetch.py` (Apache-2.0). +- **Render (`services/render.py`, `routers/render.py`).** Image sequences and joined clips to MP4 or WebM as a cancellable job with progress read from ffmpeg and a hard time limit. The Scene recorder still uses `encode_sessions.py`; up to six sessions so a recording with depth and mask fits. +- **FormEncoder (`services/formencoder.py`).** Detection and the hand-off call follow formencoder `core/discovery.py` and `engine/family.py`. Tested against a stand-in server only. +- **Approvals (`services/agents.py`).** A remembered Allow was stored under the tool plus the exact command id, so each new command asked again. Grants are per risk class now; waiting requests of the same class clear when one is allowed. Project grants are stored with the project id in `agents.json`, not inside the `.fcrft`. A client set to "allow" before 0.10.0 is asked before generating. +- **Projects.** An export with no path went to `media.resolve_dir(None)`, the Downloads folder. It now goes beside the saved file or into the app's projects folder. Uploading a cover no longer bumps `updated_at`, and the engine accepts its own saved path on a second save. +- **Keys (`services/secrets.py`).** Keys in the fallback file move into the keyring at start-up. Keys are still read from the keyring at start-up; formvis avoids that read with a last-four index, which is open here. +- **Starter and demos (`services/starter.py`, `services/demos.py`).** Read-only catalogues over `assets/starter` and `assets/demos`, found from source and from the packaged app (Tauri resources `starter/` and `demos/`). The packaged lookup is written but no desktop build was run. +- **Names (`services/naming.py`).** A second copy gets `_1`, `_2`, not `(1)`; names that look executable are refused. +- Removed code: none. + +## 2026-11-29 · v0.11.0 keys, library ids and the starter rules {#parity-v0110} + +- **Key index (`services/secrets.py`).** `settings/key-index.json` holds provider names and last four characters, never a key. Status and the key list read it; the keyring is read only for a run or a test. A key saved before 0.11 with no index entry is found by one ask per session at the run gate. Adapted from formvis `backend/app/services/secrets.py` (Apache-2.0). +- **Library ids (`services/media.py`).** Ids are content hashes, so identical recordings and generated results merged. Those ids are now salted with the job or recording session id; a retry of the same job still lands on one item, and plain imports still dedupe. +- **Agent grants.** A project grant stores the id and looks the name up when listed. +- **Starter (`services/starter.py`).** `licence_evidence` may be a string or a list; licences accepted are CC0-1.0 and the public-domain labels; packs carry `material` and `map`, `rigged` and `animations`, `source_page`. +- **Starter sourcing rule.** Files come from the publisher's own website, two licence statements read there, and never from a site or path whose robots.txt closes it to AI agents (OpenGameArt, Free Nature Stock, itch.io download links). The older scene pack in `app/pack` (KayKit pieces from GitHub, 0.6.0) is not covered by this round and is left as it was. +- Removed code: none. diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 4f69433..713378a 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.4" +VERSION = "0.11.0" FRONTEND_PORT = 5290 BACKEND_PORT = 8290 SUBFOLDERS = ("library", "thumbs", "downloads", "db", "settings", "logs") diff --git a/backend/app/main.py b/backend/app/main.py index 201cde0..88873ab 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -78,6 +78,12 @@ async def lifespan(_: FastAPI): app.include_router(agents_router.router, prefix="/api") app.include_router(mcp_router.router) app.include_router(terminal_router.router, prefix="/api") +from app.routers import render as render_router # noqa: E402 +app.include_router(render_router.router, prefix="/api") +from app.routers import starter as starter_router # noqa: E402 +app.include_router(starter_router.router, prefix="/api") +from app.routers import demos as demos_router # noqa: E402 +app.include_router(demos_router.router, prefix="/api") app.add_middleware(claude_code.TabBearer) _dist = config.dist_dir() diff --git a/backend/app/routers/agents.py b/backend/app/routers/agents.py index 12d58e1..ec02103 100644 --- a/backend/app/routers/agents.py +++ b/backend/app/routers/agents.py @@ -1,3 +1,5 @@ +from typing import Literal + from fastapi import APIRouter, Body, Query, Request, Response from pydantic import BaseModel, StrictBool @@ -10,6 +12,8 @@ class Decision(BaseModel): allow: StrictBool remember: StrictBool = False + scope: Literal["once", "session", "project", "allow"] = "once" + project: str | None = None @router.post("/agents/catalogue") @@ -18,7 +22,9 @@ def post_catalogue(body: dict = Body(...)): @router.get("/agents/bridge/next") -async def bridge_next(request: Request, wait: float = Query(25, ge=0, le=30)): +async def bridge_next(request: Request, wait: float = Query(25, ge=0, le=30), project: str | None = Query(None, max_length=200)): + if project is not None: + agents.set_window_project(project) item = await agents.bridge.next_item(wait, request.is_disconnected) if item is None: return Response(status_code=204) @@ -43,7 +49,9 @@ def bridge_result(item_id: str, body: dict = Body(...)): @router.post("/agents/approvals/{item_id}") def approval(item_id: str, body: Decision): - if not agents.bridge.decide(item_id, body.allow, body.remember): + if body.project is not None: + agents.set_window_project(body.project) + if not agents.bridge.decide(item_id, body.allow, body.remember, body.scope): raise ApiError(404, "approval_not_found", "No pending approval with that id.") return {"ok": True} diff --git a/backend/app/routers/demos.py b/backend/app/routers/demos.py new file mode 100644 index 0000000..55a809f --- /dev/null +++ b/backend/app/routers/demos.py @@ -0,0 +1,25 @@ +from fastapi import APIRouter +from fastapi.concurrency import run_in_threadpool +from fastapi.responses import FileResponse + +from app.services import demos + +router = APIRouter() + +COVER_HEADERS = {"X-Content-Type-Options": "nosniff", "Cache-Control": "private, max-age=3600"} + + +@router.get("/demos") +def list_demos(): + return demos.catalogue() + + +@router.get("/demos/{demo_id}/cover") +def read_cover(demo_id: str): + path, mime = demos.cover(demo_id) + return FileResponse(path, media_type=mime, headers=COVER_HEADERS) + + +@router.post("/demos/{demo_id}/open") +async def open_demo(demo_id: str): + return await run_in_threadpool(demos.open_copy, demo_id) diff --git a/backend/app/routers/media.py b/backend/app/routers/media.py index 196727b..fc525e5 100644 --- a/backend/app/routers/media.py +++ b/backend/app/routers/media.py @@ -26,6 +26,15 @@ class DownloadBody(BaseModel): dir: str | None = None path: str | None = None overwrite: StrictBool = False + project: str | None = Field(default=None, max_length=200) + name: str | None = Field(default=None, max_length=200) + + +class NamePreviewBody(BaseModel): + scheme: str = Field(default="", max_length=400) + mediaId: str | None = Field(default=None, max_length=100) + ext: str = Field(default="png", max_length=12) + project: str | None = Field(default=None, max_length=200) class MediaPatch(BaseModel): @@ -53,6 +62,7 @@ class TagsBody(BaseModel): class BatchBody(BaseModel): ids: list[str] = Field(min_length=1, max_length=MAX_BATCH) dir: str | None = None + project: str | None = Field(default=None, max_length=200) def _found(media_id: str): @@ -152,12 +162,12 @@ async def import_media(request: Request, hidden: bool = False): raise ApiError(415, "unsupported_media_type", "Send multipart form data with a file field, or JSON with a paths list.") -def _download_inline(ids: list[str], folder: str) -> dict: +def _download_inline(ids: list[str], folder: str, project: str | None = None) -> dict: saved: list[dict] = [] failed: list[dict] = [] for index, media_id in enumerate(ids, 1): try: - saved.append({"id": media_id, "path": str(media.download(media_id, folder, index, len(ids)))}) + saved.append({"id": media_id, "path": str(media.download(media_id, folder, index, len(ids), project=project))}) except ApiError as err: failed.append({"id": media_id, "message": err.message}) return {"saved": saved, "failed": failed} @@ -170,9 +180,14 @@ async def download_batch(body: BatchBody): ids = list(dict.fromkeys(body.ids)) folder = await run_in_threadpool(media.resolve_dir, body.dir) if len(body.ids) > INLINE_BATCH: - job = jobs.create(kind="download", title=f"Save {len(ids)} files", provider=None, model=None, subscriber_id=None, payload={"ids": ids, "dir": folder}, timeout_sec=None) - return {"jobId": job["id"]} - return await run_in_threadpool(_download_inline, ids, folder) + job = jobs.create(kind="download", title=f"Save {len(ids)} files", provider=None, model=None, subscriber_id=None, payload={"ids": ids, "dir": folder, "project": body.project}, timeout_sec=None) + return {"jobId": job["id"], "dir": folder} + return {**await run_in_threadpool(_download_inline, ids, folder, body.project), "dir": folder} + + +@router.post("/media/name-preview") +def name_preview(body: NamePreviewBody): + return media.preview_name(body.scheme, body.ext, body.project, body.mediaId) @router.get("/media/{media_id}") @@ -269,4 +284,4 @@ def delete_media(media_id: str): @router.post("/media/{media_id}/download") def download_media(media_id: str, body: DownloadBody = DownloadBody()): - return {"path": str(media.download(media_id, body.dir, path=body.path, overwrite=body.overwrite))} + return {"path": str(media.download(media_id, body.dir, path=body.path, overwrite=body.overwrite, project=body.project, stem=body.name))} diff --git a/backend/app/routers/projects.py b/backend/app/routers/projects.py index b253454..be9ca9b 100644 --- a/backend/app/routers/projects.py +++ b/backend/app/routers/projects.py @@ -32,6 +32,28 @@ class ProjectPatch(BaseModel): class ExportBody(BaseModel): path: str | None = None overwrite: StrictBool = False + remember: StrictBool = True + + +class AutosaveBody(BaseModel): + name: str = "" + projectId: str | None = None + doc: dict + + +@router.get("/autosave") +def list_autosaves(): + return projects.autosave_list() + + +@router.put("/autosave/{kind}") +def put_autosave(kind: str, body: AutosaveBody): + return projects.autosave_put(kind, body.name, body.projectId, body.doc) + + +@router.delete("/autosave/{kind}") +def drop_autosave(kind: str): + return projects.autosave_drop(kind) @router.get("/projects") @@ -120,4 +142,4 @@ def delete_project(project_id: str): @router.post("/projects/{project_id}/export") def export_project(project_id: str, body: ExportBody = ExportBody()): - return projects.export(project_id, body.path, body.overwrite) + return projects.export(project_id, body.path, body.overwrite, body.remember) diff --git a/backend/app/routers/render.py b/backend/app/routers/render.py new file mode 100644 index 0000000..1738db0 --- /dev/null +++ b/backend/app/routers/render.py @@ -0,0 +1,94 @@ +import urllib.error + +from fastapi import APIRouter +from fastapi.concurrency import run_in_threadpool +from pydantic import BaseModel, Field, StrictBool + +from app.core.errors import ApiError +from app.services import binaries, formencoder, jobs, media, render + +router = APIRouter() +render.register() + + +class RenderStart(BaseModel): + type: str + preset: str | None = None + format: str | None = None + quality: str | None = None + fps: float | dict | None = None + width: int | None = None + height: int | None = None + framesDir: str | None = Field(default=None, max_length=4000) + mediaIds: list[str] | None = None + paths: list[str] | None = None + audioMediaId: str | None = None + audioPath: str | None = Field(default=None, max_length=4000) + name: str | None = Field(default=None, max_length=200) + timeoutSec: int | None = Field(default=None, ge=10, le=render.MAX_TIMEOUT) + + +class BinariesCheck(BaseModel): + fetch: StrictBool = False + + +class EncoderSend(BaseModel): + mediaId: str = Field(min_length=1, max_length=200) + preset: str | None = Field(default=None, max_length=120) + start: StrictBool = False + + +@router.get("/render/binaries") +def read_binaries(): + return binaries.status() + + +@router.post("/render/binaries/check") +async def check_binaries(body: BinariesCheck): + binaries.recheck() + started = body.fetch and binaries.start_fetch() + found = await run_in_threadpool(binaries.status) + caps = await run_in_threadpool(render.capability) if found["available"] else None + return {**found, "fetching": bool(started), "encoders": caps} + + +@router.get("/render/presets") +def read_presets(): + return {"presets": render.presets(), "formats": list(render.FORMATS), "qualities": list(render.QUALITIES)} + + +@router.post("/render") +def start_render(body: RenderStart): + spec = body.model_dump(exclude_none=True) + if binaries.locate() is None: + raise ApiError(409, "no_ffmpeg", "formcraft has no ffmpeg to render with yet. Open Preferences, Rendering, and press Check binaries.") + return render.submit(spec, title=f"Render {spec.get('name') or spec['type']}") + + +@router.post("/render/{job_id}/cancel") +async def cancel_render(job_id: str): + job = jobs.get(job_id) + if job is None or job["kind"] != render.KIND: + raise ApiError(404, "job_not_found", "No render job with that id.") + return await jobs.manager.cancel(job_id) + + +@router.get("/render/formencoder") +async def read_formencoder(): + return await run_in_threadpool(formencoder.state) + + +@router.post("/render/formencoder/send") +async def send_formencoder(body: EncoderSend): + row = media.live_row(body.mediaId) + if row is None: + raise ApiError(404, "media_not_found", "No library item with that id.") + path = media.file_path(row) + if not path.is_file(): + raise ApiError(404, "file_missing", "The file for this item is missing from the library.") + try: + return await run_in_threadpool(formencoder.send, path, body.preset, body.start) + except ValueError as err: + raise ApiError(422, "formencoder_refused", f"FormEncoder did not take the file: {err}") from None + except (urllib.error.URLError, OSError) as err: + raise ApiError(502, "formencoder_unreachable", f"FormEncoder could not be reached: {err}") from None diff --git a/backend/app/routers/starter.py b/backend/app/routers/starter.py new file mode 100644 index 0000000..07dae04 --- /dev/null +++ b/backend/app/routers/starter.py @@ -0,0 +1,66 @@ +from fastapi import APIRouter, Query, Request +from fastapi.concurrency import run_in_threadpool +from fastapi.responses import FileResponse, Response + +from app.services import starter, thumbs + +router = APIRouter() + +IMMUTABLE = "private, max-age=31536000, immutable" +BRIEF = "private, max-age=300" +FILE_HEADERS = {"X-Content-Type-Options": "nosniff", "Content-Security-Policy": "sandbox", "Cache-Control": "private, max-age=3600"} + + +@router.get("/starter") +def read_catalogue( + kind: list[str] = Query(default=[]), + category: str | None = None, + pack: str | None = None, + q: str | None = Query(default=None, max_length=200), + offset: int = Query(0, ge=0), + limit: int = Query(100, ge=1, le=starter.MAX_LIMIT), +): + kinds = [part for raw in kind for part in raw.split(",") if part] + return starter.catalogue(kinds, category or None, pack or None, q, offset, limit) + + +@router.get("/starter/credits") +def read_credits(): + return starter.credits() + + +@router.get("/starter/packs/{pack_id}/licence") +def read_licence(pack_id: str): + return FileResponse(starter.licence_text(pack_id), media_type="text/plain; charset=utf-8", headers=FILE_HEADERS) + + +@router.get("/starter/items/{pack_id}/{item_id}") +def read_item(pack_id: str, item_id: str): + item = starter.find(pack_id, item_id) + return {**starter.item_view(item), "credit": starter.credit_for(item)} + + +@router.get("/starter/items/{pack_id}/{item_id}/file") +def read_file(pack_id: str, item_id: str): + item = starter.find(pack_id, item_id) + return FileResponse(item["path"], media_type=item["mime"], filename=item["path"].name, content_disposition_type="inline", headers=FILE_HEADERS) + + +@router.get("/starter/items/{pack_id}/{item_id}/thumb") +def read_thumb(pack_id: str, item_id: str, w: int = Query(thumbs.DEFAULT_WIDTH)): + result, cache = starter.thumbnail(pack_id, item_id, w) + headers = {"Cache-Control": IMMUTABLE if cache == "forever" else BRIEF, "X-Content-Type-Options": "nosniff"} + if isinstance(result, bytes): + return Response(result, media_type="image/webp", headers=headers) + return FileResponse(result, media_type="image/webp", headers=headers) + + +@router.put("/starter/items/{pack_id}/{item_id}/thumb") +async def put_thumb(pack_id: str, item_id: str, request: Request): + data = await request.body() + return await run_in_threadpool(starter.store_render, pack_id, item_id, data) + + +@router.post("/starter/items/{pack_id}/{item_id}/add") +async def add_item(pack_id: str, item_id: str): + return await run_in_threadpool(starter.add_to_library, pack_id, item_id) diff --git a/backend/app/services/agents.py b/backend/app/services/agents.py index d3066ee..3c79b3f 100644 --- a/backend/app/services/agents.py +++ b/backend/app/services/agents.py @@ -23,13 +23,18 @@ GRACE_SEC = 2.0 APPROVAL_SEC = 120 CALL_SEC = 90 -POLICIES = ("allow", "ask", "deny") +POLICIES = ("allow", "session", "ask", "deny") +LEVELS = ("ask", "session", "project", "allow", "deny") DEFAULT_POLICY = "ask" PRICED_KEY = "generate<=" +RISK_KEY = "risk:" +WINDOW_KEY = "window" +SCOPES = ("once", "session", "project", "allow") +SPEND_MAX = 1000.0 ACTIVITY_MAX = 200 NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,128}$") BLOCKED_PREFIXES = ("keys_", "key_", "settings_", "encode_", "cover_", "agents_", "agent_") -LONG_CALLS = {"edit_export": 900, "scene_capture": 180} +LONG_CALLS = {"edit_export": 900, "scene_capture": 180, "scene_export": 900, "scene_save": 180, "scene_open": 180, "scene_record_start": 120} _lock = threading.RLock() @@ -98,7 +103,17 @@ def _load() -> dict: data = {} policies = {k: v for k, v in (data.get("policies") or {}).items() if isinstance(k, str) and v in POLICIES} if isinstance(data.get("policies"), dict) else {} remembered = {k: [t for t in v if isinstance(t, str)] for k, v in (data.get("remembered") or {}).items() if isinstance(v, list)} if isinstance(data.get("remembered"), dict) else {} - return {"policies": policies, "remembered": remembered} + projects: dict[str, dict] = {} + for pid, raw in (data.get("projects") or {}).items() if isinstance(data.get("projects"), dict) else (): + if isinstance(pid, str) and isinstance(raw, dict) and isinstance(raw.get("clients"), list): + clients = [c for c in raw["clients"] if isinstance(c, str)] + if clients: + projects[pid] = {"name": str(raw.get("name") or "")[:200], "clients": clients} + raw_spend = data.get("spend") if isinstance(data.get("spend"), dict) else {} + limit = raw_spend.get("limitUsd") + limit = float(limit) if isinstance(limit, (int, float)) and not isinstance(limit, bool) and 0 <= limit <= SPEND_MAX else 0.0 + spend = {"on": raw_spend.get("on") is True and limit > 0, "limitUsd": limit} + return {"policies": policies, "remembered": remembered, "projects": projects, "spend": spend} def _save(state: dict) -> None: @@ -106,15 +121,48 @@ def _save(state: dict) -> None: _seen: dict[str, float] = {} +_session_all: set[str] = set() +_session_keys: dict[str, set[str]] = {} def touch_client(name: str) -> None: _seen[name] = time.time() +_window_project: dict = {} + + +def set_window_project(project_id: str | None) -> None: + _window_project["id"] = (project_id or "").strip() or None + + +def current_project() -> dict | None: + from app.services import projects + + try: + if "id" in _window_project: + pid = _window_project["id"] + return {"id": pid, "name": projects.get_summary(pid)["name"]} if pid else None + items = projects.list_projects(None) + except Exception: + log.debug("current project lookup failed", exc_info=True) + return None + return {"id": items[0]["id"], "name": items[0]["name"]} if items else None + + +def level_for(client: str, state: dict | None = None, project: dict | None = None) -> str: + state = state if state is not None else _load() + policy = state["policies"].get(client, DEFAULT_POLICY) + if policy in ("deny", "allow"): + return policy + if project is not None and client in state["projects"].get(project["id"], {}).get("clients", ()): + return "project" + return policy + + def policy_for(client: str) -> str: with _lock: - return _load()["policies"].get(client, DEFAULT_POLICY) + return "deny" if _load()["policies"].get(client) == "deny" else "ask" def _bound(item: str) -> float | None: @@ -132,27 +180,56 @@ def priced_key(key: str, cost) -> str: return f"{PRICED_KEY}{float(cost)!r}" +def risk_of(key: str) -> str: + if key == "generate" or _bound(key) is not None: + return "spend" + return "risky" if key.startswith(RISK_KEY) else "normal" + + +def _keepable(key: str) -> bool: + risk = risk_of(key) + return (risk == "spend" and key != "generate") or risk == "normal" or key.startswith(f"{RISK_KEY}command_run:") + + def remembered(client: str, tool: str) -> bool: + project = current_project() with _lock: - items = _load()["remembered"].get(client, []) - bound = _bound(tool) - if bound is not None: + state = _load() + items = [*state["remembered"].get(client, []), *_session_keys.get(client, ())] + level = level_for(client, state, project) + spend = state["spend"] + everyone = client in _session_all + risk = risk_of(tool) + if risk == "spend": + bound = _bound(tool) + if bound is None: + return False + if spend["on"] and bound <= spend["limitUsd"] + 1e-9: + return True return any(b is not None and bound <= b + 1e-9 for b in map(_bound, items)) - return tool != "generate" and tool in items + if risk == "risky": + return _keepable(tool) and tool in items + return tool in items or everyone or level in ("allow", "project") def approval_key(tool: str, args: dict) -> str: from app.services import mcp_tools - if tool == "command_run": - return f"{tool}:{args.get('id')}" - if callable(mcp_tools.TOOLS.get(tool, {}).get("risky")): - return f"{tool}:{args.get('path') or args.get('dir') or ''}" + if mcp_tools.get(tool) is None: + if tool == "command_run" and window_risky(tool, args): + return f"{RISK_KEY}command_run:{args.get('id')}" + return WINDOW_KEY + if tool == "generate": + return tool + if mcp_tools.is_risky(tool, args): + if callable(mcp_tools.TOOLS.get(tool, {}).get("risky")): + return f"{RISK_KEY}{tool}:{args.get('path') or args.get('dir') or ''}" + return f"{RISK_KEY}{tool}" return tool def remember(client: str, tool: str) -> None: - if tool == "generate": + if not _keepable(tool): return with _lock: state = _load() @@ -162,17 +239,153 @@ def remember(client: str, tool: str) -> None: _save(state) +def grant(client: str, key: str, scope: str) -> None: + risk = risk_of(key) + with _lock: + if scope == "session": + if risk == "normal": + _session_all.add(client) + elif _keepable(key): + _session_keys.setdefault(client, set()).add(key) + return + if scope == "once": + state = _load() + if risk == "normal" and level_for(client, state) == "session": + _session_keys.setdefault(client, set()).add(key) + return + if risk != "normal": + return + if scope == "project": + project = current_project() + if project is None: + return + with _lock: + state = _load() + entry = state["projects"].setdefault(project["id"], {"name": project["name"], "clients": []}) + entry["name"] = project["name"] + if client not in entry["clients"]: + entry["clients"].append(client) + _save(state) + elif scope == "allow": + with _lock: + state = _load() + state["policies"][client] = "allow" + _save(state) + + +def key_label(key: str) -> str: + if key == WINDOW_KEY: + return "Window actions" + bound = _bound(key) + if bound is not None: + return f"Generations up to ${bound:.2f}" + if key.startswith(f"{RISK_KEY}command_run:"): + command = key[len(f"{RISK_KEY}command_run:"):] + return next((str(c.get("label") or command) for c in catalogue.commands if c.get("id") == command), command) + from app.services import mcp_tools + + found = mcp_tools.get(key) + return str(found.get("title") or key) if found else key + + +def _project_name(pid: str, stored: str) -> str: + from app.services import projects + + try: + return projects.get_summary(pid)["name"] + except Exception: + return stored + + +def _grants(state: dict) -> list[dict]: + out: list[dict] = [] + for client, policy in sorted(state["policies"].items()): + if policy == "allow": + out.append({"client": client, "scope": "allow", "key": "*", "label": "Always allow everywhere"}) + for pid, entry in sorted(state["projects"].items()): + for client in entry["clients"]: + out.append({"client": client, "scope": "project", "key": pid, "label": "Always allow in this project", "project": _project_name(pid, entry["name"])}) + for client, items in sorted(state["remembered"].items()): + for key in items: + if _keepable(key): + out.append({"client": client, "scope": "remembered", "key": key, "label": key_label(key)}) + for client in sorted(_session_all): + out.append({"client": client, "scope": "session", "key": "*", "label": "Not asking for this session"}) + for client, keys in sorted(_session_keys.items()): + for key in sorted(keys): + out.append({"client": client, "scope": "session", "key": key, "label": key_label(key)}) + return out + + +def revoke(body: dict) -> None: + client, scope, key = body.get("client"), body.get("scope"), body.get("key") + if not isinstance(client, str) or not isinstance(key, str): + return + with _lock: + if scope == "session": + if key == "*": + _session_all.discard(client) + else: + _session_keys.get(client, set()).discard(key) + return + state = _load() + if scope == "allow" and state["policies"].get(client) == "allow": + state["policies"][client] = DEFAULT_POLICY + elif scope == "project" and key in state["projects"]: + entry = state["projects"][key] + entry["clients"] = [c for c in entry["clients"] if c != client] + if not entry["clients"]: + del state["projects"][key] + elif scope == "remembered": + state["remembered"][client] = [k for k in state["remembered"].get(client, []) if k != key] + if not state["remembered"][client]: + del state["remembered"][client] + else: + return + _save(state) + + +def set_level(client: str, level: str) -> None: + project = current_project() + with _lock: + state = _load() + if level == "project": + if project is None: + return + if state["policies"].get(client) == "allow": + state["policies"][client] = DEFAULT_POLICY + entry = state["projects"].setdefault(project["id"], {"name": project["name"], "clients": []}) + if client not in entry["clients"]: + entry["clients"].append(client) + else: + state["policies"][client] = level + if project is not None and project["id"] in state["projects"]: + entry = state["projects"][project["id"]] + entry["clients"] = [c for c in entry["clients"] if c != client] + if not entry["clients"]: + del state["projects"][project["id"]] + if level in ("ask", "deny"): + _session_all.discard(client) + _session_keys.pop(client, None) + _save(state) + + def public_state() -> dict: from app.services import settings + project = current_project() with _lock: state = _load() - names = sorted(set(state["policies"]) | set(_seen)) - clients = [{"name": n, "policy": state["policies"].get(n, DEFAULT_POLICY), "lastSeen": _seen.get(n), "remembered": state["remembered"].get(n, [])} for n in names] + names = sorted(set(state["policies"]) | set(_seen) | {c for e in state["projects"].values() for c in e["clients"]}) + clients = [{"name": n, "policy": state["policies"].get(n, DEFAULT_POLICY), "level": level_for(n, state, project), "lastSeen": _seen.get(n), "remembered": state["remembered"].get(n, [])} for n in names] + grants = _grants(state) return { "allowed": settings.agents_allowed(), "policies": state["policies"], "clients": clients, + "grants": grants, + "spend": state["spend"], + "project": project, "windowConnected": bridge.connected(), "tokenPath": str(token_path()), "defaultPolicy": DEFAULT_POLICY, @@ -192,7 +405,7 @@ def put_state(body: dict) -> dict: if "policies" in body: policies = body["policies"] if not isinstance(policies, dict) or not all(isinstance(k, str) and 0 < len(k) <= 100 and v in POLICIES for k, v in policies.items()): - raise ApiError(400, "invalid_setting", "policies must map a client name to allow, ask or deny.") + raise ApiError(400, "invalid_setting", "policies must map a client name to allow, session, ask or deny.") with _lock: state = _load() state["policies"] = dict(policies) @@ -204,6 +417,26 @@ def put_state(body: dict) -> dict: state = _load() state["remembered"] = {} _save(state) + if "level" in body: + level = body["level"] + if not isinstance(level, dict) or not isinstance(level.get("client"), str) or not 0 < len(level["client"]) <= 100 or level.get("level") not in LEVELS: + raise ApiError(400, "invalid_setting", "level must name a client and one of ask, session, project, allow or deny.") + if level["level"] == "project" and current_project() is None: + raise ApiError(409, "no_project", "Open or save a project first, then allow it for this project.") + set_level(level["client"], level["level"]) + if "spend" in body: + spend = body["spend"] + limit = spend.get("limitUsd") if isinstance(spend, dict) else None + if not isinstance(spend, dict) or not isinstance(spend.get("on"), bool) or isinstance(limit, bool) or not isinstance(limit, (int, float)) or not 0 <= limit <= SPEND_MAX: + raise ApiError(400, "invalid_setting", f"spend needs on (true or false) and limitUsd from 0 to {SPEND_MAX:g}.") + with _lock: + state = _load() + state["spend"] = {"on": spend["on"] and limit > 0, "limitUsd": float(limit)} + _save(state) + if "revoke" in body: + if not isinstance(body["revoke"], dict): + raise ApiError(400, "invalid_setting", "revoke must be an object.") + revoke(body["revoke"]) return public_state() @@ -347,8 +580,12 @@ async def ask(self, client: str, tool: str, args: dict, cost, ctx=None) -> None: raise ToolError("window_required", f"{tool} needs your approval in the FormCraft window and the window is not open. Open FormCraft, then call again.") item_id = uuid.uuid4().hex future = asyncio.get_running_loop().create_future() - self.approvals[item_id] = (future, client, priced_key(approval_key(tool, args), cost)) - item = {"kind": "approval", "id": item_id, "tool": tool, "args": args, "client": client} + key = priced_key(approval_key(tool, args), cost) + self.approvals[item_id] = (future, client, key) + project = current_project() + with _lock: + level = level_for(client, _load(), project) + item = {"kind": "approval", "id": item_id, "tool": tool, "args": args, "client": client, "title": action_title(tool, args), "risk": risk_of(key), "keepable": _keepable(key), "level": level, "project": project} if cost is not None: item["costUsd"] = cost self._put(item) @@ -373,15 +610,29 @@ async def ask(self, client: str, tool: str, args: dict, cost, ctx=None) -> None: if not allowed: raise ToolError("approval_denied", f"The owner declined {tool}.") - def decide(self, item_id: str, allow: bool, remember_it: bool) -> bool: + def decide(self, item_id: str, allow: bool, remember_it: bool, scope: str = "once") -> bool: entry = self.approvals.get(item_id) if entry is None or entry[0].done(): return False if allow and remember_it: remember(entry[1], entry[2]) + if allow: + grant(entry[1], entry[2], scope if scope in SCOPES else "once") entry[0].set_result(bool(allow)) + if allow: + self._sweep(entry[1]) return True + def _sweep(self, client: str) -> None: + for other_id, (future, who, key) in list(self.approvals.items()): + if who != client or future.done() or not remembered(who, key): + continue + future.set_result(True) + if any(i.get("id") == other_id for i in self.queue): + self._drop(other_id) + else: + self._put({"kind": "withdraw", "id": other_id}) + def stop(self) -> int: count = 0 self.epoch += 1 @@ -473,6 +724,9 @@ def window_tools() -> list[dict]: "studio_state", "studio_open", "edit_state", "edit_add_media", "edit_add_text", "edit_move", "edit_trim", "edit_split", "edit_remove", "edit_set_param", "edit_toggle_key", "edit_set_speed", "edit_add_effect", "edit_set_mask", "edit_bookmark", "edit_settings", "edit_undo", "edit_redo", "edit_export", "scene_state", "scene_add", "scene_update", "scene_capture", + "scene_list_objects", "scene_add_many", "scene_delete", "scene_select", "scene_group", "scene_ungroup", "scene_camera", + "scene_mode", "scene_timeline_get", "scene_keys_set", "scene_keys_delete", "scene_timeline_set", + "scene_schema", "scene_record_start", "scene_record_status", "scene_record_stop", "scene_save", "scene_export", "scene_open", )) @@ -480,6 +734,18 @@ def window_tool(name: str) -> dict | None: return catalogue.tools.get(name) +def action_title(name: str, args: dict) -> str: + from app.services import mcp_tools + + if name == "command_run": + for command in catalogue.commands: + if command.get("id") == args.get("id"): + return str(command.get("label") or args.get("id"))[:120] + return str(args.get("id") or name)[:120] + found = mcp_tools.get(name) or catalogue.tools.get(name) or {} + return str(found.get("title") or name)[:120] + + def window_risky(name: str, args: dict) -> bool: if name != "command_run": return False diff --git a/backend/app/services/binaries.py b/backend/app/services/binaries.py new file mode 100644 index 0000000..9c5ae5c --- /dev/null +++ b/backend/app/services/binaries.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +import hashlib +import logging +import os +import sys +import tempfile +import threading +from pathlib import Path +from typing import NamedTuple + +from app.core import config +from app.services import ffmpeg_fetch +from app.services.ffmpeg_record import FILES, RELEASE + +log = logging.getLogger("formcraft.binaries") + +RELEASES = ( + "https://github.com/nodemode-dev/formai-binaries/releases/download", + "https://github.com/nodemode-dev/formcut-binaries/releases/download", +) +MIRRORS = ("FORMCRAFT_FFMPEG_RELEASE", "FORMCUT_FFMPEG_RELEASE") +DIR_ENV = "FORMCRAFT_FFMPEG_DIR" +DOCUMENTS = ("LGPL-2.1.txt", "THIRD-PARTY-NOTICES.txt") + +_guard = threading.Lock() +_digests: dict[tuple, str] = {} +_last_error: dict[str, str | None] = {"fetch": None} + + +class Resolved(NamedTuple): + found: ffmpeg_fetch.Found + folder: Path + origin: str + verified: bool | None + documents: bool + + +def bundled_folders() -> list[Path]: + places: list[Path] = [] + explicit = os.environ.get(DIR_ENV, "").strip() + if explicit: + places.append(Path(explicit)) + if getattr(sys, "frozen", False): + here = Path(sys.executable).resolve().parent + places += [here, here / "binaries", here / "ffmpeg", here.parent / "Resources" / "binaries", here.parent / "Resources" / "ffmpeg", here.parent / "lib" / "formcraft" / "ffmpeg"] + places.append(config.REPO_DIR / "src-tauri" / "binaries") + return places + + +def _candidates() -> list[tuple[str, Path | None]]: + out: list[tuple[str, Path | None]] = [("bundled", f) for f in bundled_folders()] + out += [("shared", f) for f in ffmpeg_fetch._family_folders()] + out.append(("system", None)) + out += [("sibling", ffmpeg_fetch.base_dir() / name / "ffmpeg") for name in ffmpeg_fetch.SIBLINGS] + return out + + +def _digest(path: Path) -> str | None: + try: + info = path.stat() + except OSError: + return None + key = (str(path), info.st_mtime_ns, info.st_size) + with _guard: + if key in _digests: + return _digests[key] + h = hashlib.sha256() + try: + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1 << 20), b""): + h.update(block) + except OSError: + return None + value = h.hexdigest() + with _guard: + _digests[key] = value + return value + + +def verify(folder: Path) -> bool | None: + pins = FILES.get(ffmpeg_fetch.host_triple()) + if not pins: + return None + named = [(folder / path, digest) for path, digest in pins] + if not named[0][0].is_file(): + return None + return all(path.is_file() and _digest(path) == digest for path, digest in named) + + +def _in(folder: Path, origin: str) -> Resolved | None: + found = ffmpeg_fetch._in_folder(folder) + if found is None: + return None + found = found._replace(source=origin) + return Resolved(found, folder, origin, verify(folder), all((folder / d).is_file() for d in DOCUMENTS)) + + +def resolve() -> Resolved | None: + for origin, folder in _candidates(): + if folder is None: + found = ffmpeg_fetch._on_path() + if found: + return Resolved(found._replace(source="system"), found.ffmpeg.parent, "system", None, False) + continue + hit = _in(folder, origin) + if hit: + if hit.verified is False: + log.info("ffmpeg in %s differs from the family record; it is used as the person placed it", folder) + return hit + return None + + +def locate() -> ffmpeg_fetch.Found | None: + hit = resolve() + if hit is None: + return None + return hit.found._replace(source="shared" if hit.verified else hit.origin) + + +def sources() -> list[str]: + triple = ffmpeg_fetch.host_triple() + mirror = next((os.environ[name] for name in MIRRORS if os.environ.get(name, "").strip()), "") + bases = [mirror] if mirror else [f"{base}/ffmpeg-{RELEASE}" for base in RELEASES] + return [f"{base.rstrip('/')}/ffmpeg-lgpl-{RELEASE}-{triple}.tar.gz" for base in bases] + + +def fetch() -> Path: + pins = FILES.get(ffmpeg_fetch.host_triple()) + if not pins: + raise ValueError(f"no ffmpeg build is recorded for {ffmpeg_fetch.host_triple()}") + where = ffmpeg_fetch.shared_folder() + failures: list[str] = [] + for url in sources(): + try: + with tempfile.TemporaryDirectory() as scratch: + archive = Path(scratch) / "ffmpeg.tar.gz" + ffmpeg_fetch._download(url, archive) + ffmpeg_fetch._install(archive, pins, where) + except (OSError, ValueError) as error: + failures.append(f"{url} ({error})") + continue + ffmpeg_fetch._plain_names(where) + return where + raise ValueError("ffmpeg could not be installed from " + "; ".join(failures)) + + +def _fetch_thread() -> None: + try: + fetch() + _last_error["fetch"] = None + except Exception as error: + _last_error["fetch"] = str(error)[:400] + log.warning("ffmpeg fetch failed: %s", error) + finally: + ffmpeg_fetch._downloading.clear() + + +def start_fetch() -> bool: + if resolve() is not None: + return False + with ffmpeg_fetch._guard: + if ffmpeg_fetch._downloading.is_set(): + return True + ffmpeg_fetch._downloading.set() + threading.Thread(target=_fetch_thread, name="binaries-fetch", daemon=True).start() + return True + + +def recheck() -> None: + with _guard: + _digests.clear() + with ffmpeg_fetch._guard: + ffmpeg_fetch._checked.clear() + + +def status() -> dict: + hit = resolve() + base = { + "release": RELEASE, + "triple": ffmpeg_fetch.host_triple(), + "downloading": ffmpeg_fetch.downloading(), + "downloadFrom": sources(), + "lastError": _last_error["fetch"], + } + if hit is None: + return {**base, "available": False, "source": "none", "version": None, "ffmpeg": None, "ffprobe": None, "verified": None, "licenceTexts": False} + return { + **base, + "available": True, + "source": hit.origin, + "version": hit.found.version, + "ffmpeg": str(hit.found.ffmpeg), + "ffprobe": str(hit.found.ffprobe) if hit.found.ffprobe else None, + "folder": str(hit.folder), + "verified": hit.verified, + "licenceTexts": hit.documents, + } diff --git a/backend/app/services/builtin_runners.py b/backend/app/services/builtin_runners.py index caa7ab5..aa115a7 100644 --- a/backend/app/services/builtin_runners.py +++ b/backend/app/services/builtin_runners.py @@ -93,7 +93,7 @@ async def run(self, ctx: jobs.JobContext) -> None: if media_id in handled: continue try: - path = await asyncio.to_thread(media.download, media_id, folder, index, len(ids), cancel=ctx.cancel_flag) + path = await asyncio.to_thread(media.download, media_id, folder, index, len(ids), cancel=ctx.cancel_flag, project=ctx.payload.get("project")) except media.ImportCancelled: raise asyncio.CancelledError() from None except ApiError as err: diff --git a/backend/app/services/demos.py b/backend/app/services/demos.py new file mode 100644 index 0000000..841874d --- /dev/null +++ b/backend/app/services/demos.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import json +import os +import re +import sys +from pathlib import Path + +from app.core import config +from app.core.errors import ApiError +from app.services import projects + +STUDIOS = ("scene", "canvas", "board", "edit") +ID_PATTERN = re.compile(r"[a-z0-9][a-z0-9-]{0,63}") +COVER_TYPES = {".webp": "image/webp", ".png": "image/png"} +MAX_INDEX_BYTES = 1 << 20 + + +def _candidates() -> list[Path]: + found: list[Path] = [] + raw = os.environ.get("FORMCRAFT_DEMOS_DIR", "").strip() + if raw: + found.append(Path(raw).expanduser()) + if getattr(sys, "frozen", False): + bundled = getattr(sys, "_MEIPASS", "") + if bundled: + found.append(Path(bundled) / "demos") + exe = Path(sys.executable).resolve().parent + found += [exe.parent / "demos", exe.parent / "Resources" / "demos", exe / "demos", exe.parent / "lib" / "FormCraft" / "demos", exe.parent / "lib" / "formcraft" / "demos"] + found.append(config.REPO_DIR / "assets" / "demos") + return found + + +def root() -> Path | None: + for path in _candidates(): + if (path / "demos.json").is_file(): + return path + return None + + +def _inside(base: Path, rel) -> Path | None: + if not isinstance(rel, str) or not rel or rel.startswith(("/", "\\")) or "\\" in rel: + return None + try: + target = (base / rel).resolve() + target.relative_to(base.resolve()) + except (ValueError, OSError): + return None + return target if target.is_file() else None + + +def _entries() -> list[tuple[dict, Path, Path | None]]: + base = root() + if base is None: + return [] + index = base / "demos.json" + try: + if index.stat().st_size > MAX_INDEX_BYTES: + return [] + raw = json.loads(index.read_text(encoding="utf-8")) + except (OSError, ValueError): + return [] + out: list[tuple[dict, Path, Path | None]] = [] + for item in raw if isinstance(raw, list) else []: + if not isinstance(item, dict) or not isinstance(item.get("id"), str) or not ID_PATTERN.fullmatch(item["id"]) or item.get("studio") not in STUDIOS: + continue + file = _inside(base, item.get("file")) + if file is None or file.suffix.lower() != projects.EXTENSION: + continue + cover = _inside(base, item.get("cover")) + if cover is not None and cover.suffix.lower() not in COVER_TYPES: + cover = None + shows = [s for s in item.get("shows", []) if isinstance(s, str)] if isinstance(item.get("shows"), list) else [] + minutes = item.get("minutes") if isinstance(item.get("minutes"), int) and item["minutes"] > 0 else 2 + view = { + "id": item["id"], + "title": str(item.get("title") or item["id"])[:120], + "blurb": str(item.get("blurb") or "")[:300], + "studio": item["studio"], + "minutes": minutes, + "shows": shows[:12], + "cover": f"/api/demos/{item['id']}/cover" if cover is not None else None, + } + out.append((view, file, cover)) + return out + + +def _find(demo_id: str) -> tuple[dict, Path, Path | None]: + for entry in _entries(): + if entry[0]["id"] == demo_id: + return entry + raise ApiError(404, "demo_not_found", "No demo with that id.") + + +def catalogue() -> dict: + return {"demos": [view for view, _, _ in _entries()]} + + +def cover(demo_id: str) -> tuple[Path, str]: + _, _, path = _find(demo_id) + if path is None: + raise ApiError(404, "cover_not_found", "This demo has no cover.") + return path, COVER_TYPES[path.suffix.lower()] + + +def open_copy(demo_id: str) -> dict: + view, file, _ = _find(demo_id) + try: + stream = open(file, "rb") + except OSError: + raise ApiError(500, "demo_unreadable", f"formcraft cannot read the {view['title']} demo.") from None + with stream: + made = projects.import_stream(stream, origin=None, fallback=view["title"]) + return {**made, "demo": view["id"]} diff --git a/backend/app/services/edit_encode.py b/backend/app/services/edit_encode.py index 2c8f097..14c84df 100644 --- a/backend/app/services/edit_encode.py +++ b/backend/app/services/edit_encode.py @@ -478,7 +478,7 @@ def finish(session_id: str) -> dict: _run_mux(session) _verify(session) with open(session.output, "rb") as stream: - item, _ = media.ingest(stream, session.name) + item, _ = media.ingest(stream, session.name, salt=session.id) return media.fresh(item["id"]) except ApiError: raise diff --git a/backend/app/services/encode_sessions.py b/backend/app/services/encode_sessions.py index 2721ff2..d651d24 100644 --- a/backend/app/services/encode_sessions.py +++ b/backend/app/services/encode_sessions.py @@ -12,12 +12,13 @@ from typing import AsyncIterator from app.core.errors import ApiError -from app.services import encoders, ffmpeg_fetch, ffmpeg_run, media +from app.services import binaries, encoders, ffmpeg_fetch, ffmpeg_run, media log = logging.getLogger("formcraft.encode") -MAX_SESSIONS = 2 +MAX_SESSIONS = 6 IDLE_SECONDS = 600.0 +STALE_SECONDS = 90.0 SWEEP_SECONDS = 15.0 FINISH_SECONDS = 300 MIN_EDGE = 64 @@ -178,12 +179,21 @@ def open_session(width: int, height: int, fps: int, frames: int, name: str | Non raise ApiError(400, "invalid_frames", f"frames must be a whole number from 1 to {MAX_FRAMES}.") choice = encoders.selected() if choice is None: - why = "formcraft has no ffmpeg to encode with yet." if ffmpeg_fetch.locate() is None else "The ffmpeg formcraft found has no H.264 encoder that works on this computer." + why = "formcraft has no ffmpeg to encode with yet." if binaries.locate() is None else "The ffmpeg formcraft found has no H.264 encoder that works on this computer." raise ApiError(409, "no_video_encoder", f"{why} Video recording from the engine is not available.") found, profile = choice + with _lock: + now = time.monotonic() + stale = [s for s in _sessions.values() if now - s.touched > STALE_SECONDS and not s._busy] + for old in stale: + _sessions.pop(old.id, None) + for old in stale: + old.reason = "expired" + old.kill() + log.info("recording session %s closed: no frames for %.0f s and a new recording started", old.id, STALE_SECONDS) with _lock: if len(_sessions) >= MAX_SESSIONS: - raise ApiError(429, "encode_busy", f"{MAX_SESSIONS} recordings are already being encoded. Finish or cancel one first.") + raise ApiError(429, "encode_busy", "Too many recordings are being encoded at once. Finish or cancel one first.") try: session = Session("enc_" + uuid.uuid4().hex[:16], width, height, fps, frames, _title(name), found, profile) except OSError as exc: @@ -246,7 +256,7 @@ async def feed(session_id: str, declared: str | None, chunks: AsyncIterator[byte def _verify(session: Session) -> None: - found = ffmpeg_fetch.locate() + found = binaries.locate() if found is None or found.ffprobe is None: if session.part.stat().st_size == 0: raise ApiError(500, "encode_failed", "The encoder wrote an empty file.") @@ -288,7 +298,7 @@ def finish(session_id: str) -> dict: raise ApiError(500, "encode_failed", session.failure("The encoder stopped before it finished")) _verify(session) with open(session.part, "rb") as stream: - item, _ = media.ingest(stream, session.name) + item, _ = media.ingest(stream, session.name, salt=session.id) return media.fresh(item["id"]) except ApiError: raise diff --git a/backend/app/services/encoders.py b/backend/app/services/encoders.py index 9d6c183..2739215 100644 --- a/backend/app/services/encoders.py +++ b/backend/app/services/encoders.py @@ -7,7 +7,7 @@ from pathlib import Path from typing import NamedTuple -from app.services import ffmpeg_fetch +from app.services import binaries, ffmpeg_fetch log = logging.getLogger("formcraft.encode") @@ -113,7 +113,7 @@ def _probe(found: ffmpeg_fetch.Found) -> Profile | None: def selected() -> tuple[ffmpeg_fetch.Found, Profile] | None: - found = ffmpeg_fetch.locate() + found = binaries.locate() if found is None: return None key = _key(found) diff --git a/backend/app/services/ffmpeg_fetch.py b/backend/app/services/ffmpeg_fetch.py index bc2ec0f..2bcaa2a 100644 --- a/backend/app/services/ffmpeg_fetch.py +++ b/backend/app/services/ffmpeg_fetch.py @@ -156,6 +156,12 @@ def _family_folders() -> list[Path]: def locate() -> Found | None: + from app.services import binaries + + return binaries.locate() + + +def _locate_family() -> Found | None: for folder in _family_folders(): found = _in_folder(folder) if found: @@ -303,7 +309,9 @@ def _tell(ready: Callable[[], None] | None) -> None: def _run(ready: Callable[[], None] | None) -> None: done = False try: - where = fetch() + from app.services import binaries + + where = binaries.fetch() log.info("ffmpeg %s ready in %s", RELEASE, where) done = True except Exception as error: diff --git a/backend/app/services/formencoder.py b/backend/app/services/formencoder.py new file mode 100644 index 0000000..42f858f --- /dev/null +++ b/backend/app/services/formencoder.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +import urllib.error +import urllib.request +from pathlib import Path + +PAGE = "https://formencoder.formai.studio/" +DEFAULT_PORT = 8270 +LOCAL_HEADER = "x-formencoder-local" +SOURCE_HEADER = "x-formencoder-source" +SOURCE = "formcraft" +HEALTH_SECONDS = 1.0 +SEND_SECONDS = 60.0 +PRESETS = ( + ("system/match-source-high", "Match source, high quality (MP4)"), + ("system/webm-vp9-1080p", "WebM VP9 1080p"), + ("system/youtube-1080p", "YouTube 1080p"), + ("system/instagram-reels", "Instagram Reels"), + ("system/tiktok", "TikTok"), + ("system/prores-422", "ProRes 422"), + ("system/gif-720", "GIF 720"), +) + + +def data_dir() -> Path: + raw = os.environ.get("FORMENCODER_DATA_DIR", "").strip() + return Path(raw).expanduser() if raw else Path.home() / "Formencoder" + + +def _health(url: str) -> dict | None: + try: + with urllib.request.urlopen(urllib.request.Request(f"{url}/api/health", headers={LOCAL_HEADER: "1"}), timeout=HEALTH_SECONDS) as r: + body = json.loads(r.read().decode() or "null") + except (urllib.error.URLError, OSError, ValueError): + return None + return body if isinstance(body, dict) and body.get("name") == "formencoder" and body.get("status") == "ok" else None + + +def running() -> tuple[str, dict] | None: + seen: list[str] = [] + env = os.environ.get("FORMENCODER_URL", "").strip().rstrip("/") + if env: + seen.append(env) + try: + url = json.loads((data_dir() / "engine.json").read_text(encoding="utf-8")).get("url") + if isinstance(url, str) and url.startswith("http://127.0.0.1:"): + seen.append(url.rstrip("/")) + except (OSError, ValueError, AttributeError): + pass + seen.append(f"http://127.0.0.1:{os.environ.get('FORMENCODER_PORT', '') or DEFAULT_PORT}") + for url in dict.fromkeys(seen): + health = _health(url) + if health: + return url, health + return None + + +def installed() -> str | None: + exe = shutil.which("formencoder") + if exe: + return exe + places: list[Path] = [] + if sys.platform == "darwin": + for root in (Path("/Applications"), Path.home() / "Applications"): + places += [root / "FormEncoder.app", root / "formencoder.app"] + elif os.name == "nt": + for base in (os.environ.get("LOCALAPPDATA"), os.environ.get("ProgramFiles")): + if base: + places += [Path(base) / "FormEncoder" / "formencoder.exe", Path(base) / "Programs" / "FormEncoder" / "formencoder.exe", Path(base) / "formencoder" / "formencoder.exe"] + else: + places += [Path("/usr/bin/formencoder"), Path("/opt/FormEncoder/formencoder"), Path.home() / "Applications" / "FormEncoder.AppImage"] + return next((str(p) for p in places if p.exists()), None) + + +def state() -> dict: + live = running() + app = installed() + base = {"page": PAGE, "presets": [{"id": i, "label": label} for i, label in PRESETS]} + if live: + return {**base, "installed": True, "running": True, "url": live[0], "version": live[1].get("version"), "app": app} + return {**base, "installed": app is not None, "running": False, "url": None, "version": None, "app": app} + + +def _rpc(url: str, command: str, params: dict) -> dict: + body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "command.execute", "params": {"command": command, "params": params}}).encode() + req = urllib.request.Request(f"{url}/api/rpc", data=body, method="POST", headers={LOCAL_HEADER: "1", SOURCE_HEADER: SOURCE, "content-type": "application/json"}) + with urllib.request.urlopen(req, timeout=SEND_SECONDS) as r: + reply = json.loads(r.read().decode() or "null") + if isinstance(reply, dict) and reply.get("error"): + err = reply["error"] + raise ValueError(err.get("message") if isinstance(err, dict) else str(err)) + return reply.get("result") if isinstance(reply, dict) else {} + + +def _launch(app: str, path: Path) -> None: + if sys.platform == "darwin" and app.endswith(".app"): + args = ["open", "-a", app, "--args", str(path)] + else: + args = [app, str(path)] + flags = 0x00000008 | 0x00000200 if os.name == "nt" else 0 + subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=flags, start_new_session=os.name != "nt") + + +def send(path: Path, preset: str | None, start: bool) -> dict: + if preset is not None and not (isinstance(preset, str) and preset.startswith(("system/", "user/")) and len(preset) <= 120): + raise ValueError("That is not a FormEncoder preset id.") + live = running() + if live: + params: dict = {"paths": [str(path)], "start": bool(start)} + if preset: + params["preset"] = preset + result = _rpc(live[0], "queue.addSource", params) + return {"sent": True, "how": "queue", "url": live[0], "preset": preset, "result": result} + app = installed() + if not app: + return {"sent": False, "how": "missing", "page": PAGE} + _launch(app, path) + return {"sent": True, "how": "opened", "app": app, "preset": None} diff --git a/backend/app/services/mcp_protocol.py b/backend/app/services/mcp_protocol.py index 14394b8..fa487a1 100644 --- a/backend/app/services/mcp_protocol.py +++ b/backend/app/services/mcp_protocol.py @@ -28,7 +28,9 @@ "formcraft engine tools. Agents are off until the owner turns them on in FormCraft, Preferences, Agents; until then every tool call answers an error that says so.\n" "Call plan_generation before generate. generate spends money and needs acceptCostUsd at or above the plan estimate.\n" "Studio tools (commands, edit, scene, canvas, board) run in the open FormCraft window and answer window_required when it is closed.\n" - "Prefer command_run for anything the app already has a command for. Library ids come from library_search.\n" + "Prefer a studio tool over command_run: menu commands depend on what is selected and open in the window, the tools do not. Library ids come from library_search.\n" + "3D scenes: scene_schema gives the scene, object and keyframe formats; build with scene_add_many, animate with scene_keys_set (no mode or selection needed), " + "render with scene_capture or scene_record_start and scene_record_status, keep it with scene_save. Never edit exported .fcrft files to change a scene.\n" "Jobs finish on their own time: use job_wait or job_get, never assume a result." ) @@ -202,8 +204,7 @@ async def _call(rid, params: dict, ctx: Ctx, modern: bool) -> dict: if problem: status = "error" raise ToolError("invalid_arguments", problem) - if not studio: - await mcp_tools.precheck(name, args, ctx) + await mcp_tools.precheck(name, args, ctx) try: await _gate(ctx, name, args, tool, studio) except ToolError: diff --git a/backend/app/services/mcp_tools.py b/backend/app/services/mcp_tools.py index eeca524..291f9c9 100644 --- a/backend/app/services/mcp_tools.py +++ b/backend/app/services/mcp_tools.py @@ -169,7 +169,7 @@ def validate(schema: dict, value, path: str = "arguments") -> str | None: if problem: return problem elif schema.get("additionalProperties") is False: - return f"{path}.{key} is not a known argument." + return f"{path}.{key} is not a known argument. The arguments are: {', '.join(props) or 'none'}." return None @@ -220,6 +220,10 @@ async def precheck(name: str, args: dict, ctx=None) -> None: _check_write(args.get("path"), ctx) elif name == "projects_import": _check_read([args["path"]], ctx) + elif name in ("scene_save", "scene_export"): + _check_write(args.get("path"), ctx) + elif name == "scene_open" and isinstance(args.get("path"), str): + _check_read([args["path"]], ctx) def _model(cls, **kw): @@ -661,7 +665,7 @@ async def projects_update(a, ctx): return await _t(svc.projects.update, a["id"], changes) -@tool("projects_export", "Export a project", "Write a project and its media to a .fcrft file. Replacing an existing file asks the owner.", {"id": _s("Project id."), "path": _s("Full file path; default the download folder."), "overwrite": _b("Replace an existing file.")}, ("id",), hint="A", risky=lambda a: bool(a.get("overwrite"))) +@tool("projects_export", "Export a project", "Write a project and its media to a .fcrft file. Replacing an existing file asks the owner.", {"id": _s("Project id."), "path": _s("Full file path; default beside the saved file, or the app's projects folder."), "overwrite": _b("Replace an existing file.")}, ("id",), hint="A", risky=lambda a: bool(a.get("overwrite"))) async def projects_export(a, ctx): _check_write(a.get("path"), ctx) return await _t(svc.projects.export, a["id"], a.get("path"), bool(a.get("overwrite"))) diff --git a/backend/app/services/media.py b/backend/app/services/media.py index f302eba..198a080 100644 --- a/backend/app/services/media.py +++ b/backend/app/services/media.py @@ -468,7 +468,7 @@ def _place(tmp: Path, media_id: str, name: str, size: int, source: str, job_id: return to_media(db.one("SELECT * FROM media WHERE id = ?", (media_id,))), True -def ingest(stream: BinaryIO, name: str | None, *, source: str = "import", job_id: str | None = None, prompt: str | None = None, cancel: threading.Event | None = None, hidden: bool = False) -> tuple[dict, bool]: +def ingest(stream: BinaryIO, name: str | None, *, source: str = "import", job_id: str | None = None, prompt: str | None = None, cancel: threading.Event | None = None, hidden: bool = False, salt: str | None = None) -> tuple[dict, bool]: tmp = _tmp_path() digest = hashlib.sha256() size = 0 @@ -487,6 +487,8 @@ def ingest(stream: BinaryIO, name: str | None, *, source: str = "import", job_id out.write(chunk) if size == 0: raise ApiError(400, "empty_file", "That file is empty.") + if salt: + digest.update(b"\0" + salt.encode("utf-8")) return _place(tmp, digest.hexdigest()[:32], clean_name(name), size, source, job_id, prompt, hidden) except OSError as exc: raise ApiError(500, "storage_failed", f"Could not copy the file into the library: {exc.strerror or 'disk error'}.") from None @@ -519,10 +521,11 @@ def import_upload(stream: BinaryIO, filename: str | None, cancel: threading.Even def add_generated(source: bytes | Path, name: str, *, job_id: str | None = None, prompt: str | None = None, cancel: threading.Event | None = None, hidden: bool = False) -> tuple[dict, bool]: + salt = job_id or uuid.uuid4().hex if isinstance(source, (bytes, bytearray)): - return ingest(io.BytesIO(source), name, source="generated", job_id=job_id, prompt=prompt, cancel=cancel, hidden=hidden) + return ingest(io.BytesIO(source), name, source="generated", job_id=job_id, prompt=prompt, cancel=cancel, hidden=hidden, salt=salt) with open(source, "rb") as stream: - return ingest(stream, name, source="generated", job_id=job_id, prompt=prompt, cancel=cancel, hidden=hidden) + return ingest(stream, name, source="generated", job_id=job_id, prompt=prompt, cancel=cancel, hidden=hidden, salt=salt) def warn_failed(name: str, err: Exception) -> None: @@ -728,7 +731,7 @@ def _save_unique(source: Path, folder: Path, stem: str, ext: str, cancel: thread try: _copy_to(source, partial, cancel) for number in range(0, MAX_SUFFIX + 1): - name = f"{stem}.{ext}" if number == 0 else f"{stem} ({number}).{ext}" + name = f"{stem}.{ext}" if number == 0 else f"{stem}_{number}.{ext}" final = folder / name try: os.link(partial, final) @@ -800,7 +803,42 @@ def _save_exact(source: Path, final: Path, overwrite: bool, cancel: threading.Ev partial.unlink(missing_ok=True) -def download(media_id: str, directory: str | None, index: int = 1, count: int = 1, *, path: str | None = None, overwrite: bool = False, cancel: threading.Event | None = None) -> Path: +def _name_context(row) -> dict: + model = seed = None + if row["job_id"]: + job = db.one("SELECT model, payload FROM jobs WHERE id = ?", (row["job_id"],)) + if job: + model = job["model"] + try: + request = (json.loads(job["payload"] or "{}").get("request") or {}) + except ValueError: + request = {} + params = request.get("params") if isinstance(request.get("params"), dict) else {} + seed = request.get("seed", params.get("seed")) + return {"model": model, "name": Path(row["name"]).stem, "prompt": row["prompt"], "kind": row["kind"], "seed": seed} + + +def preview_name(scheme: str, ext: str, project: str | None = None, media_id: str | None = None) -> dict: + try: + checked = naming.validate_scheme(scheme or settings.naming_scheme()) + except naming.SchemeError as err: + return {"ok": False, "message": str(err), "name": ""} + row = live_row(media_id) if media_id else None + if row is not None: + stem = naming.render(checked, moment=datetime.now(), project=project, **_name_context(row)) + ext = row["ext"] + else: + stem = naming.render( + checked, model="flux-pro", name="sunset", moment=datetime.now(), index=1, count=1, + prompt="A red fox at dawn, soft light", kind="image", project=project or "My project", seed=42, + ) + safe = ext.strip(".").lower() + if not safe.isalnum() or safe in mediatypes.UNSAFE_EXTENSIONS: + safe = "png" + return {"ok": True, "message": "", "name": f"{stem}.{safe}"} + + +def download(media_id: str, directory: str | None, index: int = 1, count: int = 1, *, path: str | None = None, overwrite: bool = False, cancel: threading.Event | None = None, project: str | None = None, stem: str | None = None) -> Path: row = live_row(media_id) if row is None: raise ApiError(404, "media_not_found", "No library item with that id.") @@ -813,9 +851,9 @@ def download(media_id: str, directory: str | None, index: int = 1, count: int = if path is not None: return _save_exact(source, _exact_target(path), overwrite, cancel) folder = _target_dir(directory) - model = None - if row["job_id"]: - job = db.one("SELECT model FROM jobs WHERE id = ?", (row["job_id"],)) - model = job["model"] if job else None - stem = naming.render(settings.naming_scheme(), model=model, name=Path(row["name"]).stem, moment=datetime.now(), index=index, count=count) - return _save_unique(source, folder, stem, ext, cancel) + if stem and stem.strip(): + name = naming.clean(stem.strip().rsplit(".", 1)[0] if stem.strip().lower().endswith("." + ext) else stem.strip()) + name = naming.defang(name) or "formcraft" + else: + name = naming.render(settings.naming_scheme(), moment=datetime.now(), index=index, count=count, project=project, **_name_context(row)) + return _save_unique(source, folder, name, ext, cancel) diff --git a/backend/app/services/naming.py b/backend/app/services/naming.py index 8c81032..a9301ce 100644 --- a/backend/app/services/naming.py +++ b/backend/app/services/naming.py @@ -3,10 +3,14 @@ import re from datetime import datetime +from app.services import mediatypes + DEFAULT_SCHEME = "default" DEFAULT_TEMPLATE = "{model}_{YYYY}-{MM}-{DD}-{HH}-{mm}-{SS}" -TOKENS = ("model", "name", "date", "YYYY", "YY", "MM", "DD", "HH", "mm", "SS", "batch_index") +TOKENS = ("model", "name", "date", "time", "prompt", "kind", "project", "seed", "n", "YYYY", "YY", "MM", "DD", "HH", "mm", "SS", "batch_index") MAX_STEM = 200 +PROMPT_WORDS = 6 +PROMPT_CHARS = 40 MAX_TEMPLATE = 200 TOKEN_PATTERN = re.compile(r"\{([A-Za-z_]+)\}") UNSAFE = re.compile(r"[\\/:*?\"<>|`%'\x00-\x1f\x7f]") @@ -38,6 +42,8 @@ def validate_scheme(raw: str) -> str: sample = render(scheme, model="sample", name="sample", moment=datetime(2026, 1, 2, 3, 4, 5), index=1, count=1) if not sample.strip("._ "): raise SchemeError("The naming scheme would produce an empty file name.") + if any(part.lower() in mediatypes.UNSAFE_EXTENSIONS for part in leftover.split(".")[1:]): + raise SchemeError("The naming scheme cannot make a name that looks like a program or script.") return scheme @@ -59,12 +65,40 @@ def clean(text: str) -> str: return text -def render(scheme: str, *, model: str | None, name: str | None, moment: datetime, index: int = 1, count: int = 1) -> str: +def prompt_words(text: str | None) -> str: + words = re.sub(r"[^a-z0-9]+", " ", (text or "").lower()).split()[:PROMPT_WORDS] + return "-".join(words)[:PROMPT_CHARS].strip("-") + + +def defang(text: str) -> str: + head, *rest = text.split(".") + return head + "".join(("_" if part.lower() in mediatypes.UNSAFE_EXTENSIONS else ".") + part for part in rest) + + +def render( + scheme: str, + *, + model: str | None, + name: str | None, + moment: datetime, + index: int = 1, + count: int = 1, + prompt: str | None = None, + kind: str | None = None, + project: str | None = None, + seed: int | str | None = None, +) -> str: template = DEFAULT_TEMPLATE if scheme == DEFAULT_SCHEME else scheme stem = slug(name) values = { "model": slug(model) or stem or "formcraft", "name": stem or "formcraft", + "prompt": prompt_words(prompt), + "kind": slug(kind), + "project": slug(project), + "seed": re.sub(r"[^0-9]", "", str(seed if seed is not None else ""))[:12], + "n": str(index), + "time": moment.strftime("%H-%M-%S"), "date": moment.strftime("%Y-%m-%d"), "YYYY": moment.strftime("%Y"), "YY": moment.strftime("%y"), @@ -76,6 +110,8 @@ def render(scheme: str, *, model: str | None, name: str | None, moment: datetime "batch_index": str(index), } text = TOKEN_PATTERN.sub(lambda m: values.get(m.group(1), ""), template) - if count > 1 and "{batch_index}" not in template: + if count > 1 and "{batch_index}" not in template and "{n}" not in template: text = f"{text}_{index}" - return clean(text) or "formcraft" + if any(not values.get(token, "x") for token in TOKEN_PATTERN.findall(template)): + text = re.sub(r"([_-])[_-]+", r"\1", text).strip("_-") + return defang(clean(text)) or "formcraft" diff --git a/backend/app/services/projects.py b/backend/app/services/projects.py index 30e6c83..b29220b 100644 --- a/backend/app/services/projects.py +++ b/backend/app/services/projects.py @@ -214,7 +214,7 @@ def set_cover_upload(project_id: str, stream: BinaryIO) -> dict: data, ext = media.clean_cover(stream, MAX_COVER_BYTES) cover, _ = media.ingest(io.BytesIO(data), f"{_stem(row['name'])} cover.{ext}", hidden=True) before = db.one("SELECT cover_media_id FROM projects WHERE id = ?", (project_id,)) - if not db.run("UPDATE projects SET cover_media_id = ?, updated_at = ? WHERE id = ?", (cover["id"], db.now_iso(), project_id)): + if not db.run("UPDATE projects SET cover_media_id = ? WHERE id = ?", (cover["id"], project_id)): raise ApiError(404, "project_not_found", "No project with that id.") announce("changed", project_id) if before is not None and before["cover_media_id"] and before["cover_media_id"] != cover["id"]: @@ -432,7 +432,60 @@ def _write_preview(final: Path, cover_id) -> None: partial.unlink(missing_ok=True) -def export(project_id: str, path: str | None, overwrite: bool = False) -> dict: +def _default_export_dir(saved: str | None) -> Path: + if saved: + parent = Path(saved).parent + if parent.is_dir() and os.access(parent, os.W_OK): + return parent + return config.subdir("projects") + + +AUTOSAVE_KINDS = ("scene", "canvas", "board", "edit") + + +def _autosave_file(kind: str) -> Path: + if kind not in AUTOSAVE_KINDS: + raise ApiError(400, "invalid_kind", f"Autosave keeps {', '.join(AUTOSAVE_KINDS)} projects only.") + return config.subdir("autosave") / f"{kind}.json" + + +def autosave_put(kind: str, name: str, project_id: str | None, doc) -> dict: + final = _autosave_file(kind) + entry = {"kind": kind, "name": (name or "").strip()[:MAX_NAME], "projectId": project_id, "savedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + text = '{"entry":' + json.dumps(entry, ensure_ascii=False) + ',"doc":' + encode_doc(doc) + "}" + partial = final.with_name(f".{uuid.uuid4().hex}.part") + try: + partial.write_text(text, encoding="utf-8") + os.replace(partial, final) + except OSError as exc: + raise ApiError(500, "autosave_failed", f"Could not write the autosave: {exc.strerror or 'disk error'}.") from None + finally: + partial.unlink(missing_ok=True) + return entry + + +def autosave_list() -> dict: + found = [] + for kind in AUTOSAVE_KINDS: + path = config.subdir("autosave") / f"{kind}.json" + try: + held = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError: + continue + except (OSError, ValueError): + path.unlink(missing_ok=True) + continue + if isinstance(held, dict) and isinstance(held.get("entry"), dict) and isinstance(held.get("doc"), dict): + found.append({**held["entry"], "kind": kind, "doc": held["doc"]}) + return {"autosaves": found} + + +def autosave_drop(kind: str) -> dict: + _autosave_file(kind).unlink(missing_ok=True) + return {"deleted": True} + + +def export(project_id: str, path: str | None, overwrite: bool = False, remember: bool = True) -> dict: row = _row(project_id, doc=True) parsed = _parse_doc(row) refs = media_refs(parsed) @@ -465,8 +518,9 @@ def export(project_id: str, path: str | None, overwrite: bool = False) -> dict: "coverId": row["cover"] if any(item["id"] == row["cover"] for item in rows) else None, "media": [_index_entry(item, budget) for item in rows], } - target = None if path is None else _export_target(path, overwrite) - folder = Path(media.resolve_dir(None)) if target is None else target.parent + own = bool(path and overwrite and row["file_path"] and path.strip() == row["file_path"]) + target = None if path is None else Path(row["file_path"]) if own else _export_target(path, overwrite) + folder = _default_export_dir(row["file_path"]) if target is None else target.parent partial = folder / f".{uuid.uuid4().hex}.part" try: _write_archive(partial, manifest, row["doc"], rows) @@ -476,8 +530,9 @@ def export(project_id: str, path: str | None, overwrite: bool = False) -> dict: finally: partial.unlink(missing_ok=True) _write_preview(final, manifest["coverId"]) - db.run("UPDATE projects SET file_path = ? WHERE id = ?", (str(final), project_id)) - announce("changed", project_id) + if remember: + db.run("UPDATE projects SET file_path = ? WHERE id = ?", (str(final), project_id)) + announce("changed", project_id) if missing: events.warn(f"{row['name']} was exported without {_plural(len(missing), 'file')} that {'is' if len(missing) == 1 else 'are'} missing from the library.") return {"path": str(final), "media": len(rows), "missing": missing} diff --git a/backend/app/services/render.py b/backend/app/services/render.py new file mode 100644 index 0000000..2704116 --- /dev/null +++ b/backend/app/services/render.py @@ -0,0 +1,485 @@ +from __future__ import annotations + +import asyncio +import collections +import contextlib +import json +import logging +import os +import re +import shutil +import subprocess +import tempfile +import threading +import time +from fractions import Fraction +from pathlib import Path +from typing import Callable + +from app.services import binaries, encoders, ffmpeg_fetch, ffmpeg_run, jobs, media + +log = logging.getLogger("formcraft.render") + +KIND = "render" +FORMATS = ("mp4", "webm") +QUALITIES = ("low", "medium", "high", "veryhigh") +IMAGE_CODECS = {".png": "png", ".jpg": "mjpeg", ".jpeg": "mjpeg", ".webp": "webp"} +MAX_FRAMES = 200_000 +MAX_CLIPS = 200 +MIN_EDGE, MAX_EDGE = 16, 8192 +MAX_FPS = 240 +PROBE_SECONDS = 20 +CLEANUP_SECONDS = 8 +MIN_TIMEOUT, MAX_TIMEOUT = 120, 6 * 3600 +RATE_SCALE = {"low": 0.35, "medium": 0.6, "high": 1.0, "veryhigh": 1.6} +X264_CRF = {"low": "28", "medium": "23", "high": "19", "veryhigh": "16"} +VP9_CRF = {"low": "42", "medium": "36", "high": "31", "veryhigh": "24"} +AAC_RATE = {"low": "96k", "medium": "128k", "high": "192k", "veryhigh": "256k"} +OPUS_RATE = {"low": "64k", "medium": "96k", "high": "128k", "veryhigh": "160k"} +PRESETS = { + "mp4-web": {"label": "MP4 for the web", "format": "mp4", "quality": "high", "maxEdge": 1920}, + "mp4-master": {"label": "MP4 master", "format": "mp4", "quality": "veryhigh", "maxEdge": None}, + "mp4-small": {"label": "MP4 small", "format": "mp4", "quality": "low", "maxEdge": 1280}, + "webm-web": {"label": "WebM for the web", "format": "webm", "quality": "high", "maxEdge": 1920}, + "webm-small": {"label": "WebM small", "format": "webm", "quality": "medium", "maxEdge": 1280}, +} +NATURAL = re.compile(r"(\d+)") + +_guard = threading.Lock() +_h264: dict[tuple, encoders.Profile | None] = {} + + +class RenderError(jobs.JobError): + pass + + +class Cancelled(Exception): + pass + + +def presets() -> list[dict]: + return [{"id": key, **value} for key, value in PRESETS.items()] + + +def _natural(path: Path) -> list: + return [int(p) if p.isdigit() else p.lower() for p in NATURAL.split(path.name)] + + +def _even(n: float) -> int: + return max(2, int(n) // 2 * 2) + + +def _rate(raw) -> Fraction: + try: + if isinstance(raw, dict): + value = Fraction(int(raw["num"]), int(raw["den"])) + else: + value = Fraction(str(raw)).limit_denominator(1001) + except (KeyError, TypeError, ValueError, ZeroDivisionError): + raise RenderError("invalid_input", "fps must be a number or {num, den}.") from None + if not 0 < value <= MAX_FPS: + raise RenderError("invalid_input", f"fps must be above 0 and at most {MAX_FPS}.") + return value + + +def _media_path(media_id) -> Path: + if not isinstance(media_id, str) or not media_id: + raise RenderError("invalid_input", "Every media id must be a non-empty string.") + row = media.live_row(media_id) + if row is None: + raise RenderError("invalid_input", f"No library item with the id {media_id[:40]}.") + path = media.file_path(row) + if not path.is_file(): + raise RenderError("invalid_input", f"The file for library item {media_id[:40]} is missing.") + return path + + +def _file(raw) -> Path: + if not isinstance(raw, str) or not raw.strip() or not os.path.isabs(raw): + raise RenderError("invalid_input", "Every path must be an absolute file path.") + path = Path(raw) + if not path.is_file(): + raise RenderError("invalid_input", f"{path.name} does not exist or is not a file.") + return path + + +def _frames(spec: dict) -> list[Path]: + if spec.get("framesDir"): + folder = Path(str(spec["framesDir"])) + if not folder.is_absolute() or not folder.is_dir(): + raise RenderError("invalid_input", "framesDir must be an absolute folder path.") + found = [p for p in folder.iterdir() if p.is_file() and p.suffix.lower() in IMAGE_CODECS] + if not found: + raise RenderError("invalid_input", "framesDir holds no PNG, JPEG or WebP frames.") + counts = collections.Counter(IMAGE_CODECS[p.suffix.lower()] for p in found) + codec = counts.most_common(1)[0][0] + frames = sorted((p for p in found if IMAGE_CODECS[p.suffix.lower()] == codec), key=_natural) + else: + ids = spec.get("mediaIds") + if not isinstance(ids, list) or not ids: + raise RenderError("invalid_input", "A sequence needs framesDir or a list of image mediaIds.") + frames = [_media_path(i) for i in ids] + if len({IMAGE_CODECS.get(p.suffix.lower()) for p in frames}) != 1 or IMAGE_CODECS.get(frames[0].suffix.lower()) is None: + raise RenderError("invalid_input", "Every frame of a sequence must be the same kind of image: PNG, JPEG or WebP.") + if len(frames) > MAX_FRAMES: + raise RenderError("invalid_input", f"A sequence can hold at most {MAX_FRAMES} frames.") + return frames + + +def _clips(spec: dict) -> list[Path]: + paths = [_media_path(i) for i in spec.get("mediaIds") or []] + [_file(p) for p in spec.get("paths") or []] + if not paths: + raise RenderError("invalid_input", "A concat needs mediaIds or paths of video clips.") + if len(paths) > MAX_CLIPS: + raise RenderError("invalid_input", f"A concat can join at most {MAX_CLIPS} clips.") + return paths + + +def _audio(spec: dict) -> Path | None: + if spec.get("audioMediaId"): + return _media_path(spec["audioMediaId"]) + if spec.get("audioPath"): + return _file(spec["audioPath"]) + return None + + +def options(spec: dict) -> dict: + preset = spec.get("preset") + if preset is not None and preset not in PRESETS: + raise RenderError("invalid_input", f"Unknown preset. Use one of: {', '.join(PRESETS)}.") + base = PRESETS.get(preset or "", {}) + fmt = spec.get("format") or base.get("format") or "mp4" + quality = spec.get("quality") or base.get("quality") or "high" + if fmt not in FORMATS: + raise RenderError("invalid_input", "format must be mp4 or webm.") + if quality not in QUALITIES: + raise RenderError("invalid_input", f"quality must be one of {', '.join(QUALITIES)}.") + size = [] + for key in ("width", "height"): + value = spec.get(key) + if value is not None and (isinstance(value, bool) or not isinstance(value, int) or not MIN_EDGE <= value <= MAX_EDGE): + raise RenderError("invalid_input", f"{key} must be a whole number from {MIN_EDGE} to {MAX_EDGE}.") + size.append(value) + if spec.get("type") not in ("sequence", "concat"): + raise RenderError("invalid_input", "type must be sequence or concat.") + return {"format": fmt, "quality": quality, "maxEdge": base.get("maxEdge"), "width": size[0], "height": size[1]} + + +def _env(found: ffmpeg_fetch.Found): + return ffmpeg_fetch.run_env(found.libs) + + +def _probe(found: ffmpeg_fetch.Found, path: Path) -> dict: + if found.ffprobe is None: + raise RenderError("no_ffprobe", "formcraft has no ffprobe to read the clips with.") + try: + done = subprocess.run( + [str(found.ffprobe), "-v", "error", "-hide_banner", "-show_format", "-show_streams", "-of", "json", str(path)], + capture_output=True, timeout=PROBE_SECONDS, stdin=subprocess.DEVNULL, env=_env(found), creationflags=ffmpeg_fetch.NO_WINDOW, check=False, + ) + info = ffmpeg_run.summarise(json.loads(done.stdout)) if done.returncode == 0 else None + except (OSError, subprocess.SubprocessError, ValueError): + info = None + if not info or not info.get("width") or not info.get("durationSec"): + raise RenderError("invalid_input", f"{path.name} could not be read as a video clip.") + return info + + +def _image_size(found: ffmpeg_fetch.Found, path: Path) -> tuple[int, int]: + if found.ffprobe is not None: + with contextlib.suppress(OSError, subprocess.SubprocessError, ValueError): + done = subprocess.run( + [str(found.ffprobe), "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "json", str(path)], + capture_output=True, timeout=PROBE_SECONDS, stdin=subprocess.DEVNULL, env=_env(found), creationflags=ffmpeg_fetch.NO_WINDOW, check=False, + ) + stream = json.loads(done.stdout)["streams"][0] + return int(stream["width"]), int(stream["height"]) + raise RenderError("invalid_input", f"The size of {path.name} could not be read.") + + +def h264(found: ffmpeg_fetch.Found) -> encoders.Profile | None: + try: + info = found.ffmpeg.stat() + except OSError: + return None + key = (str(found.ffmpeg), info.st_mtime_ns, info.st_size, found.source) + with _guard: + if key in _h264: + return _h264[key] + listed = encoders._listed(found) + chosen = None + for profile in encoders.PROFILES: + if profile.name == "libx264" and found.source == "shared": + continue + if profile.name in listed and encoders._works(found, profile): + chosen = profile + break + with _guard: + _h264[key] = chosen + return chosen + + +def _target(opts: dict, width: int, height: int) -> tuple[int, int]: + w, h = opts["width"], opts["height"] + if w and h: + return _even(w), _even(h) + if w: + return _even(w), _even(w * height / width) + if h: + return _even(h * width / height), _even(h) + edge = opts["maxEdge"] + if edge and max(width, height) > edge: + scale = edge / max(width, height) + return _even(width * scale), _even(height * scale) + return _even(width), _even(height) + + +def _video_codec(found: ffmpeg_fetch.Found, opts: dict, width: int, height: int, fps: Fraction) -> tuple[list[str], list[str], str, str]: + quality = opts["quality"] + if opts["format"] == "webm": + return [], ["-c:v", "libvpx-vp9", "-row-mt", "1", "-deadline", "good", "-cpu-used", "4", "-b:v", "0", "-crf", VP9_CRF[quality]], "libvpx-vp9", encoders.VP9_CHAIN + profile = h264(found) + if profile is None: + raise RenderError("no_encoder", "The ffmpeg formcraft found has no H.264 encoder that works on this computer. Choose WebM, or check the binaries in Preferences, Rendering.") + codec = list(profile.codec) + if profile.by_rate: + rate = int(encoders.bitrate(width, height, max(1, round(float(fps)))) * RATE_SCALE[quality]) + codec += ["-b:v", str(rate)] + else: + codec += ["-crf", X264_CRF[quality]] + return list(profile.before), codec, profile.name, profile.chain + + +def _audio_codec(opts: dict) -> list[str]: + if opts["format"] == "webm": + return ["-c:a", "libopus", "-ar", "48000", "-b:a", OPUS_RATE[opts["quality"]]] + return ["-c:a", "aac", "-b:a", AAC_RATE[opts["quality"]]] + + +def _fit(width: int, height: int) -> str: + return f"scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1" + + +def build(spec: dict, output: Path, found: ffmpeg_fetch.Found, cancel: threading.Event | None = None) -> dict: + opts = options(spec) + kind = spec["type"] + audio = _audio(spec) + head = [str(found.ffmpeg), "-hide_banner", "-loglevel", "error", "-nostdin", "-nostats", "-progress", "pipe:1", "-y"] + tail = ["-movflags", "+faststart"] if opts["format"] == "mp4" else [] + if kind == "sequence": + frames = _frames(spec) + fps = _rate(spec.get("fps") or 30) + width, height = _target(opts, *_image_size(found, frames[0])) + before, codec, name, chain = _video_codec(found, opts, width, height, fps) + args = [*head, *before, "-f", "image2pipe", "-framerate", f"{fps.numerator}/{fps.denominator}", "-c:v", IMAGE_CODECS[frames[0].suffix.lower()], "-i", "pipe:0"] + if audio: + args += ["-i", str(audio)] + args += ["-map", "0:v:0", "-vf", f"{_fit(width, height)},{encoders.TO_VIDEO_RANGE},{chain}", *codec, *encoders.TAGS] + args += ["-map", "1:a:0", *_audio_codec(opts), "-shortest"] if audio else ["-an"] + seconds = len(frames) / float(fps) + return {"args": [*args, *tail, str(output)], "frames": frames, "total": seconds, "count": len(frames), "width": width, "height": height, + "fps": float(fps), "format": opts["format"], "quality": opts["quality"], "video": name, "audio": bool(audio)} + clips = _clips(spec) + infos = [] + for p in clips: + if cancel is not None and cancel.is_set(): + raise Cancelled() + infos.append(_probe(found, p)) + first = infos[0] + fps = _rate(spec.get("fps") or first.get("fps") or 30) + width, height = _target(opts, first["width"], first["height"]) + before, codec, name, chain = _video_codec(found, opts, width, height, fps) + sound = audio is None and any(i["hasAudio"] for i in infos) + args = [*head, *before] + for p in clips: + args += ["-i", str(p)] + if audio: + args += ["-i", str(audio)] + parts, joined = [], "" + for n, info in enumerate(infos): + parts.append(f"[{n}:v:0]{_fit(width, height)},fps={fps.numerator}/{fps.denominator},format=yuv420p[v{n}]") + joined += f"[v{n}]" + if sound: + d = f"{info['durationSec']:.3f}" + if info["hasAudio"]: + parts.append(f"[{n}:a:0]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,apad,atrim=duration={d}[a{n}]") + else: + parts.append(f"anullsrc=r=48000:cl=stereo,atrim=duration={d}[a{n}]") + joined += f"[a{n}]" + parts.append(f"{joined}concat=n={len(clips)}:v=1:a={1 if sound else 0}[cv]{'[ca]' if sound else ''}") + parts.append(f"[cv]{encoders.TO_VIDEO_RANGE},{chain}[v]") + args += ["-filter_complex", ";".join(parts), "-map", "[v]", *codec, *encoders.TAGS] + if sound: + args += ["-map", "[ca]", *_audio_codec(opts)] + elif audio: + args += ["-map", f"{len(clips)}:a:0", *_audio_codec(opts), "-shortest"] + else: + args += ["-an"] + seconds = sum(i["durationSec"] for i in infos) + return {"args": [*args, *tail, str(output)], "frames": None, "total": seconds, "count": len(clips), "width": width, "height": height, + "fps": float(fps), "format": opts["format"], "quality": opts["quality"], "video": name, "audio": sound or bool(audio)} + + +def timeout_for(seconds: float) -> int: + return int(min(MAX_TIMEOUT, max(MIN_TIMEOUT, 120 + seconds * 20))) + + +def _feed(proc: subprocess.Popen, frames: list[Path], stop: threading.Event) -> None: + try: + for frame in frames: + if stop.is_set(): + break + proc.stdin.write(frame.read_bytes()) + except (OSError, ValueError): + pass + finally: + with contextlib.suppress(OSError, ValueError): + proc.stdin.close() + + +def _progress(proc: subprocess.Popen, plan: dict, report: Callable[[float], None]) -> None: + total = plan["total"] or 0 + count = plan["count"] if plan["frames"] else 0 + for raw in proc.stdout: + key, _, value = raw.decode("utf-8", "replace").strip().partition("=") + try: + if key == "frame" and count: + report(min(0.99, int(value) / count)) + elif key == "out_time_us" and total and not count: + report(min(0.99, max(0, int(value)) / 1e6 / total)) + except ValueError: + continue + + +def _drain(stream, tail: collections.deque) -> None: + for raw in stream: + line = raw.decode("utf-8", "replace").strip() + if line: + tail.append(line[-300:]) + + +def _kill(proc: subprocess.Popen) -> None: + if proc.poll() is None: + with contextlib.suppress(OSError): + proc.kill() + with contextlib.suppress(subprocess.SubprocessError, OSError): + proc.wait(timeout=5) + + +def encode(spec: dict, output: Path, report: Callable[[float], None] | None = None, cancel: threading.Event | None = None, timeout: float | None = None) -> dict: + found = binaries.locate() + if found is None: + raise RenderError("no_ffmpeg", "formcraft has no ffmpeg to render with yet. Open Preferences, Rendering, and press Check binaries.") + cancel = cancel or threading.Event() + report = report or (lambda _v: None) + output.parent.mkdir(parents=True, exist_ok=True) + scratch = Path(tempfile.mkdtemp(prefix="render-", dir=output.parent)) + partial = scratch / f"out.{options(spec)['format']}" + stop = threading.Event() + proc = None + try: + report(0.0) + plan = build(spec, partial, found, cancel) + limit = timeout if timeout else timeout_for(plan["total"]) + deadline = time.monotonic() + limit + proc = subprocess.Popen( + plan["args"], stdin=subprocess.PIPE if plan["frames"] else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=_env(found), creationflags=ffmpeg_fetch.NO_WINDOW, + ) + tail: collections.deque = collections.deque(maxlen=8) + helpers = [threading.Thread(target=_progress, args=(proc, plan, report), daemon=True), threading.Thread(target=_drain, args=(proc.stderr, tail), daemon=True)] + if plan["frames"]: + helpers.append(threading.Thread(target=_feed, args=(proc, plan["frames"], stop), daemon=True)) + for t in helpers: + t.start() + while proc.poll() is None: + if cancel.is_set(): + raise Cancelled() + if time.monotonic() > deadline: + raise RenderError("timeout", f"The render did not finish within {int(limit)} seconds and was stopped.") + time.sleep(0.1) + for t in helpers: + t.join(timeout=2) + if cancel.is_set(): + raise Cancelled() + if proc.returncode != 0 or not partial.is_file() or partial.stat().st_size == 0: + why = tail[-1] if tail else f"ffmpeg exited with code {proc.returncode}" + raise RenderError("encode_failed", f"The render stopped before it finished: {why}") + os.replace(partial, output) + report(1.0) + return {"path": str(output), "format": plan["format"], "quality": plan["quality"], "width": plan["width"], "height": plan["height"], "fps": plan["fps"], + "seconds": round(plan["total"], 3), "items": plan["count"], "video": plan["video"], "audio": plan["audio"], "ffmpeg": found.version, "source": found.source} + finally: + stop.set() + if proc is not None: + _kill(proc) + shutil.rmtree(scratch, ignore_errors=True) + + +def _name(spec: dict, fmt: str) -> str: + raw = media.clean_name(spec.get("name") or "") if spec.get("name") else "" + stem = Path(raw).stem if raw else "render" + return f"{stem}.{fmt}" + + +class RenderRunner(jobs.Runner): + kind = KIND + auto_download = False + + def validate(self, payload: dict) -> None: + options(payload) + if payload["type"] == "sequence": + _frames(payload) + _rate(payload.get("fps") or 30) + else: + _clips(payload) + _audio(payload) + + async def run(self, ctx: jobs.JobContext) -> None: + loop = asyncio.get_running_loop() + fmt = options(ctx.payload)["format"] + output = media.library_dir() / ".tmp" / f"{ctx.job_id}.{fmt}" + + def report(value: float) -> None: + loop.call_soon_threadsafe(ctx.progress, value) + + work = asyncio.ensure_future(asyncio.to_thread(encode, ctx.payload, output, report, ctx.cancel_flag, ctx.payload.get("timeoutSec"))) + try: + result = await asyncio.shield(work) + except asyncio.CancelledError: + ctx.cancel_flag.set() + await asyncio.wait({work}, timeout=CLEANUP_SECONDS) + with contextlib.suppress(OSError): + output.unlink() + raise + except Cancelled: + raise asyncio.CancelledError() from None + try: + item, _ = await asyncio.to_thread(media.add_generated, output, _name(ctx.payload, fmt), job_id=ctx.job_id) + finally: + with contextlib.suppress(OSError): + output.unlink() + ctx.add_result(item["id"]) + ctx.record("output", {**result, "path": None, "mediaId": item["id"]}) + + +def submit(spec: dict, title: str | None = None) -> dict: + seconds = 0.0 + with contextlib.suppress(jobs.JobError, ValueError, TypeError): + if spec.get("type") == "sequence": + seconds = len(_frames(spec)) / float(_rate(spec.get("fps") or 30)) + limit = int(spec.get("timeoutSec") or timeout_for(seconds if seconds else 600)) + return jobs.create(kind=KIND, title=title or "Render", provider=None, model=None, subscriber_id=None, payload=spec, timeout_sec=min(MAX_TIMEOUT, max(1, limit))) + + +def register() -> None: + jobs.register(RenderRunner()) + + +def capability() -> dict: + found = binaries.locate() + if found is None: + return {"available": False, "mp4": False, "webm": False, "h264": None} + listed = encoders._listed(found) + profile = h264(found) + return {"available": True, "mp4": profile is not None and "aac" in listed, "webm": "libvpx-vp9" in listed and "libopus" in listed, "h264": profile.name if profile else None} diff --git a/backend/app/services/secrets.py b/backend/app/services/secrets.py index 0708217..08a6e70 100644 --- a/backend/app/services/secrets.py +++ b/backend/app/services/secrets.py @@ -1,7 +1,12 @@ +"""API keys. The system keyring is read only when a key is needed for a run or a test; the key list and status come +from key-index.json, which names the providers kept there and their last four characters, never a key. The index +approach is adapted from FormVis (backend/app/services/secrets.py, Apache-2.0).""" + from __future__ import annotations import json import os +import sys import threading import uuid from pathlib import Path @@ -15,6 +20,8 @@ _lock = threading.RLock() _status: dict | None = None _last: tuple[Path, str] | None = None +_held: dict[str, str] = {} +_asked: set[str] = set() def _store(): @@ -66,6 +73,32 @@ def _file_clear(name: str) -> None: _file_save(data) +def _index_file() -> Path: + return config.subdir("settings") / "key-index.json" + + +def _index() -> dict: + data = durable.read_json(_index_file(), {}, private=True) + return {k: v for k, v in data.items() if isinstance(v, dict)} if isinstance(data, dict) else {} + + +def _index_set(name: str, value: str) -> None: + global _status + entry = {"last4": value[-4:] if len(value) >= MIN_LENGTH else None} + data = _index() + if data.get(name) != entry: + _status = None + durable.write_json(_index_file(), {**data, name: entry}, private=True, keep_backup=False) + + +def _index_drop(name: str) -> None: + global _status + data = _index() + if name in data: + _status = None + durable.write_json(_index_file(), {k: v for k, v in data.items() if k != name}, private=True, keep_backup=False) + + def where() -> dict: kr = _store() if kr: @@ -84,26 +117,60 @@ def store_name() -> str: return "system" -def get(name: str) -> str | None: +def system_name() -> str | None: + kr = _store() + if not kr: + return None + if "kwallet" in type(kr).__module__.lower(): + return "kwallet" + if sys.platform == "darwin": + return "keychain" + if os.name == "nt": + return "credential-manager" + return "secret-service" + + +def _lookup(name: str) -> tuple[str | None, str | None]: with _lock: kr = _store() if not kr: - return _file_all().get(name) + value = _file_all().get(name) + return value, "file" if value else None + if name in _held: + return _held[name], "system" + legacy = _file_all().get(name) + indexed = name in _index() + if not indexed and not legacy and name in _asked: + return None, None + answered = True try: value = kr.get_password(SERVICE, name) except Exception: - value = None + value, answered = None, False if value: - return value - legacy = _file_all().get(name) - if legacy: - try: - kr.set_password(SERVICE, name, legacy) - if kr.get_password(SERVICE, name) == legacy: - _file_clear(name) - except Exception: - pass - return legacy + _held[name] = value + _index_set(name, value) + return value, "system" + if indexed and answered: + _index_drop(name) + if not legacy: + if answered: + _asked.add(name) + return None, None + try: + kr.set_password(SERVICE, name, legacy) + if kr.get_password(SERVICE, name) == legacy: + _held[name] = legacy + _index_set(name, legacy) + _file_clear(name) + return legacy, "system" + except Exception: + pass + return legacy, "file" + + +def get(name: str) -> str | None: + return _lookup(name)[0] def put(name: str, value: str) -> str: @@ -116,11 +183,16 @@ def put(name: str, value: str) -> str: try: kr.set_password(SERVICE, name, value) if kr.get_password(SERVICE, name) == value: + _held[name] = value + _asked.discard(name) + _index_set(name, value) _file_clear(name) _last = (_file(), "system") return "system" except Exception: pass + _held.pop(name, None) + _index_drop(name) _file_write(name, value) _last = (_file(), "file") return "file" @@ -137,11 +209,16 @@ def delete(name: str) -> None: kr.delete_password(SERVICE, name) except Exception: pass + _held.pop(name, None) + _asked.discard(name) + _index_drop(name) _file_clear(name) def configured(name: str) -> bool: - return bool(status()[name]["set"]) + if status()[name]["set"]: + return True + return bool(_lookup(name)[0]) and bool(status()[name]["set"]) def status() -> dict: @@ -149,11 +226,18 @@ def status() -> dict: with _lock: if _status is None: fresh: dict = {} + stores: dict = {} + index = _index() if _store() else {} for name in PROVIDERS: - value = get(name) + if name in index: + stores[name] = "system" + fresh[name] = {"set": True, "last4": index[name].get("last4") or None} + continue + value = _file_all().get(name) + stores[name] = "file" if value else None fresh[name] = {"set": bool(value), "last4": value[-4:] if value and len(value) >= MIN_LENGTH else None} - _status = fresh - return {**{k: dict(v) for k, v in _status.items()}, "store": store_name()} + _status = {**fresh, "stores": stores} + return {**{k: dict(v) for k, v in _status.items()}, "store": store_name(), "system": system_name()} def warm() -> None: diff --git a/backend/app/services/starter.py b/backend/app/services/starter.py new file mode 100644 index 0000000..4027dfd --- /dev/null +++ b/backend/app/services/starter.py @@ -0,0 +1,449 @@ +from __future__ import annotations + +import hashlib +import json +import logging +import mimetypes +import os +import sys +import threading +import uuid +from pathlib import Path + +from app.core import config +from app.core.errors import ApiError +from app.services import media, thumbs + +log = logging.getLogger("formcraft.starter") + +SECTIONS = ("3d", "2d", "video", "audio") +KINDS = ("3d", "texture", "hdri", "image", "sprite", "video", "audio") +LICENCE = "CC0-1.0" +LICENCES = (LICENCE, "CC-PD-Dedication-1.0-legacy", "public-domain", "public-domain-us") +KIND_ALIAS = {"model": "3d", "models": "3d"} +MEDIA_KIND = {"3d": "model", "texture": "image", "hdri": "image", "image": "image", "sprite": "image", "video": "video", "audio": "audio"} +PACK_TEXT = ("id", "name", "kind", "licence", "author", "source_url", "source_commit_or_version", "retrieved", "licence_evidence") +ITEM_TEXT = ("id", "name", "file", "category") +MAX_LIMIT = 500 +MAX_PACK_BYTES = 4 << 20 +MAX_RENDER_BYTES = 4 << 20 +RENDER_EDGE = 512 +PREVIEW_EXT = (".webp", ".png", ".jpg", ".jpeg") +STILL_EXT = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tif", ".tiff", ".tga"} +TYPES = { + ".glb": "model/gltf-binary", ".gltf": "model/gltf+json", ".obj": "model/obj", ".stl": "model/stl", ".fbx": "application/octet-stream", + ".hdr": "image/vnd.radiance", ".exr": "image/x-exr", ".webp": "image/webp", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", + ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".m4v": "video/mp4", + ".mp3": "audio/mpeg", ".wav": "audio/wav", ".ogg": "audio/ogg", ".oga": "audio/ogg", ".opus": "audio/ogg", ".flac": "audio/flac", ".m4a": "audio/mp4", + ".bin": "application/octet-stream", ".ktx2": "image/ktx2", +} + +_lock = threading.Lock() +_cache: dict = {"key": None, "data": None} + + +def _candidates() -> list[Path]: + found: list[Path] = [] + raw = os.environ.get("FORMCRAFT_STARTER_DIR", "").strip() + if raw: + found.append(Path(raw).expanduser()) + if getattr(sys, "frozen", False): + bundled = getattr(sys, "_MEIPASS", "") + if bundled: + found.append(Path(bundled) / "starter") + exe = Path(sys.executable).resolve().parent + found += [exe.parent / "starter", exe.parent / "Resources" / "starter", exe / "starter", exe.parent / "lib" / "FormCraft" / "starter", exe.parent / "lib" / "formcraft" / "starter"] + found.append(config.REPO_DIR / "assets" / "starter") + return found + + +def root() -> Path | None: + for path in _candidates(): + if path.is_dir(): + return path + return None + + +def _text(value) -> bool: + return isinstance(value, str) and bool(value.strip()) + + +def _evidence(value) -> list[str]: + if isinstance(value, list): + return [v.strip() for v in value if _text(v)] + return [value.strip()] if _text(value) else [] + + +def _inside(base: Path, rel: str) -> Path | None: + if not _text(rel) or rel.startswith(("/", "\\")) or "\\" in rel: + return None + try: + target = (base / rel).resolve() + target.relative_to(base.resolve()) + except (ValueError, OSError): + return None + return target if target.is_file() else None + + +def _kind_of(name: str) -> str: + ext = Path(name).suffix.lower() + return TYPES.get(ext) or mimetypes.guess_type(name)[0] or "application/octet-stream" + + +def _preview(file: Path) -> Path | None: + for ext in PREVIEW_EXT: + side = file.with_suffix(ext) + if side != file and side.is_file(): + return side + return None + + +MAP_ROLES = ("color", "normal", "roughness", "metalness", "ao", "displacement", "height", "opacity", "emission") +COLOR_ALIASES = {"color", "colour", "albedo", "basecolor", "diffuse"} +HDR_EXT = {".hdr", ".exr"} + + +def _role(item: dict) -> str: + if item.get("map"): + named = item["map"] + return "color" if named in COLOR_ALIASES else {"metallic": "metalness", "rough": "roughness", "disp": "displacement", "occlusion": "ao"}.get(named, named) + stem = item["path"].stem.lower().rsplit("_", 1)[-1].rsplit("-", 1)[-1] + if stem in COLOR_ALIASES or "color" in item["tags"]: + return "color" + for role in MAP_ROLES: + if role == stem or role in item["tags"]: + return role + return stem + + +def _group(items: list[dict]) -> None: + materials: dict[str, list[dict]] = {} + for item in items: + key = item.get("material") or next((tag[9:] for tag in item["tags"] if tag.startswith("material:")), "") + if key and item["kind"] == "texture": + materials.setdefault(key, []).append(item) + for parts in materials.values(): + if len(parts) < 2: + continue + roles = {_role(p): p for p in parts} + lead = roles.get("color") or parts[0] + lead["maps"] = {role: p["uid"] for role, p in roles.items()} + for p in parts: + if p is not lead: + p["hidden"] = True + for suffix in (" Color", " Colour", " color", " colour", " Albedo", " Basecolor"): + if lead["name"].endswith(suffix): + lead["name"] = lead["name"][: -len(suffix)] + lead["tags"] = [t for t in lead["tags"] if t not in MAP_ROLES and t not in COLOR_ALIASES and not t.startswith("material:")] + ["material"] + lead["bytes"] = sum(p["bytes"] for p in parts) + radiance = {(i["path"].parent, i["path"].stem) for i in items if i["path"].suffix.lower() in HDR_EXT} + for item in items: + if item["path"].suffix.lower() not in HDR_EXT and (item["path"].parent, item["path"].stem) in radiance: + item["hidden"] = True + + +def _load_pack(section: str, folder: Path, manifest: Path) -> tuple[dict | None, list[str]]: + where = f"{section}/{folder.name}" + try: + if manifest.stat().st_size > MAX_PACK_BYTES: + return None, [f"{where}: pack.json is larger than 4 MB"] + raw = json.loads(manifest.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + return None, [f"{where}: pack.json could not be read ({exc.__class__.__name__})"] + if not isinstance(raw, dict): + return None, [f"{where}: pack.json is not an object"] + if raw.get("kind") in KIND_ALIAS: + raw["kind"] = KIND_ALIAS[raw["kind"]] + evidence = _evidence(raw.get("licence_evidence")) + problems = [f"{where}: {key} is missing" for key in PACK_TEXT if key != "licence_evidence" and not _text(raw.get(key))] + if not evidence: + problems.append(f"{where}: licence_evidence is missing") + if raw.get("kind") not in KINDS: + problems.append(f"{where}: kind must be one of {', '.join(KINDS)}") + if raw.get("licence") not in LICENCES: + problems.append(f"{where}: licence must be one of {', '.join(LICENCES)}") + if not isinstance(raw.get("items"), list): + problems.append(f"{where}: items must be a list") + if problems: + return None, problems + pack_id = str(raw["id"]).strip() + items: list[dict] = [] + seen: set[str] = set() + for index, entry in enumerate(raw["items"]): + label = f"{where} item {index + 1}" + if not isinstance(entry, dict) or not all(_text(entry.get(key)) for key in ITEM_TEXT): + problems.append(f"{label}: id, name, file and category are required") + continue + item_id = str(entry["id"]).strip() + if item_id in seen or "/" in item_id: + problems.append(f"{label}: id {item_id} is repeated or holds a slash") + continue + file = _inside(folder, entry["file"]) + if file is None: + problems.append(f"{label}: {entry['file']} is not in the pack folder") + continue + kind = entry.get("kind") if entry.get("kind") in KINDS else raw["kind"] + mime = _kind_of(file.name) + shown = MEDIA_KIND[kind] if mime.startswith(("image/", "video/", "audio/", "model/")) or kind == "3d" else "other" + tags = [str(tag).strip() for tag in entry.get("tags") or [] if _text(tag)] if isinstance(entry.get("tags"), list) else [] + seconds = entry.get("seconds") + seen.add(item_id) + items.append({ + "uid": f"{pack_id}/{item_id}", + "id": item_id, + "pack": pack_id, + "name": str(entry["name"]).strip(), + "file": entry["file"], + "path": file, + "kind": kind, + "mediaKind": shown, + "mime": mime, + "category": str(entry["category"]).strip(), + "tags": tags, + "bytes": entry["bytes"] if isinstance(entry.get("bytes"), int) and entry["bytes"] >= 0 else file.stat().st_size, + "seconds": seconds if isinstance(seconds, (int, float)) and seconds >= 0 else None, + "preview": (_inside(folder, entry["preview"]) if _text(entry.get("preview")) else None) or _preview(file), + "maps": {}, + "hidden": False, + "material": str(entry["material"]).strip() if _text(entry.get("material")) else "", + "map": str(entry["map"]).strip().lower() if _text(entry.get("map")) else "", + "rigged": entry.get("rigged") is True, + "animations": [str(a).strip() for a in entry["animations"] if _text(a)] if isinstance(entry.get("animations"), list) else [], + "sourcePage": str(entry["source_page"]).strip() if _text(entry.get("source_page")) and str(entry["source_page"]).strip().startswith(("https://", "http://")) else "", + }) + _group(items) + licence_file = folder / "LICENSE.txt" + if not licence_file.is_file(): + problems.append(f"{where}: LICENSE.txt is missing") + pack = { + "id": pack_id, + "name": str(raw["name"]).strip(), + "kind": raw["kind"], + "section": section, + "licence": raw["licence"], + "author": str(raw["author"]).strip(), + "sourceUrl": str(raw["source_url"]).strip(), + "version": str(raw["source_commit_or_version"]).strip(), + "retrieved": str(raw["retrieved"]).strip(), + "licenceEvidence": ", ".join(evidence), + "folder": folder, + "items": items, + } + return pack, problems + + +def _signature(base: Path) -> tuple: + marks = [] + for manifest in sorted(base.glob("*/*/pack.json")): + try: + marks.append((str(manifest), manifest.stat().st_mtime_ns)) + except OSError: + continue + return (str(base), tuple(marks)) + + +def load() -> dict: + base = root() + key = _signature(base) if base else None + with _lock: + if _cache["data"] is not None and _cache["key"] == key: + return _cache["data"] + packs: list[dict] = [] + problems: list[str] = [] + if base is not None: + for section in SECTIONS: + holder = base / section + if not holder.is_dir(): + continue + for folder in sorted(p for p in holder.iterdir() if p.is_dir()): + manifest = folder / "pack.json" + if not manifest.is_file(): + continue + pack, found = _load_pack(section, folder, manifest) + problems += found + if pack is None: + continue + if any(p["id"] == pack["id"] for p in packs): + problems.append(f"{section}/{folder.name}: pack id {pack['id']} is used twice") + continue + packs.append(pack) + if problems: + log.warning("starter library: %s", "; ".join(problems[:20])) + data = {"root": base, "packs": packs, "items": {i["uid"]: i for p in packs for i in p["items"]}, "problems": problems} + with _lock: + _cache.update(key=key, data=data) + return data + + +def pack_view(pack: dict) -> dict: + return {key: pack[key] for key in ("id", "name", "kind", "section", "licence", "author", "sourceUrl", "version", "retrieved", "licenceEvidence")} | { + "count": sum(1 for i in pack["items"] if not i["hidden"]), + "files": len(pack["items"]), + "bytes": sum(i["path"].stat().st_size for i in pack["items"] if i["path"].is_file()), + } + + +def item_view(item: dict) -> dict: + return { + "uid": item["uid"], "id": item["id"], "pack": item["pack"], "name": item["name"], "file": Path(item["file"]).name, + "kind": item["kind"], "mediaKind": item["mediaKind"], "mime": item["mime"], "category": item["category"], + "tags": item["tags"], "bytes": item["bytes"], "seconds": item["seconds"], "maps": item["maps"], + "material": item["material"], "map": item["map"], "rigged": item["rigged"], "animations": item["animations"], "sourcePage": item["sourcePage"], + "thumb": item["mediaKind"] != "model" or item["preview"] is not None or _rendered(item).is_file(), + } + + +def _counted(values) -> list[dict]: + counts: dict[str, int] = {} + for value in values: + counts[value] = counts.get(value, 0) + 1 + return [{"name": name, "count": n} for name, n in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0].casefold()))] + + +def catalogue(kinds: list[str], category: str | None, pack: str | None, q: str | None, offset: int, limit: int) -> dict: + data = load() + wanted = [k for k in kinds if k] + bad = [k for k in wanted if k not in KINDS] + if bad: + raise ApiError(400, "invalid_kind", f"kind must be one of {', '.join(KINDS)}.") + every = [i for p in data["packs"] for i in p["items"] if not i["hidden"]] + scoped = [i for i in every if (not wanted or i["kind"] in wanted) and (not pack or i["pack"] == pack)] + words = [w for w in (q or "").casefold().split() if w] + + def hit(item: dict) -> bool: + hay = " ".join([item["name"], item["category"], item["kind"], item["pack"], *item["tags"]]).casefold() + return all(w in hay for w in words) + + searched = [i for i in scoped if hit(i)] + shown = [i for i in searched if not category or i["category"].casefold() == category.casefold()] + page = shown[offset : offset + min(max(limit, 1), MAX_LIMIT)] + return { + "available": data["root"] is not None, + "packs": [pack_view(p) for p in data["packs"]], + "kinds": _counted(i["kind"] for i in every), + "categories": _counted(i["category"] for i in searched), + "items": [item_view(i) for i in page], + "total": len(shown), + "problems": data["problems"], + } + + +def credits() -> dict: + data = load() + return {"packs": [pack_view(p) for p in data["packs"]], "problems": data["problems"]} + + +def find(pack_id: str, item_id: str) -> dict: + item = load()["items"].get(f"{pack_id}/{item_id}") + if item is None or not item["path"].is_file(): + raise ApiError(404, "starter_item_not_found", "That starter item is not in this build.") + return item + + +def _pack(pack_id: str) -> dict: + for pack in load()["packs"]: + if pack["id"] == pack_id: + return pack + raise ApiError(404, "starter_pack_not_found", "That starter pack is not in this build.") + + +def licence_text(pack_id: str) -> Path: + path = _pack(pack_id)["folder"] / "LICENSE.txt" + if not path.is_file(): + raise ApiError(404, "licence_missing", "This pack has no LICENSE.txt.") + return path + + +def _thumb_dir() -> Path: + path = media.thumbs_dir() / "starter" + path.mkdir(parents=True, exist_ok=True) + return path + + +def _stem(item: dict) -> str: + stamp = item["path"].stat().st_mtime_ns + return hashlib.sha256(f"{item['uid']}|{stamp}".encode()).hexdigest()[:24] + + +def _rendered(item: dict) -> Path: + return _thumb_dir() / f"{_stem(item)}_model.webp" + + +def store_render(pack_id: str, item_id: str, data: bytes) -> dict: + item = find(pack_id, item_id) + if item["mediaKind"] != "model": + raise ApiError(400, "not_a_model", "Only 3D starter items take a rendered thumbnail.") + if not data or len(data) > MAX_RENDER_BYTES: + raise ApiError(413, "render_too_large", "A rendered thumbnail can be up to 4 MB.") + target = _rendered(item) + temporary = target.with_name(f".{target.name}.{uuid.uuid4().hex}.tmp") + try: + temporary.write_bytes(data) + try: + clean = thumbs.make(temporary, RENDER_EDGE) + except Exception: + raise ApiError(400, "invalid_image", "The rendered thumbnail is not a readable image.") from None + temporary.write_bytes(clean) + os.replace(temporary, target) + finally: + temporary.unlink(missing_ok=True) + return {"thumb": True} + + +def thumbnail(pack_id: str, item_id: str, width: int) -> tuple[Path | bytes, str]: + item = find(pack_id, item_id) + bucket = thumbs.bucket_for(width) + source = item["preview"] + if source is None and item["mediaKind"] == "model" and _rendered(item).is_file(): + source = _rendered(item) + still = source is not None or (item["mediaKind"] == "image" and item["path"].suffix.lower() in STILL_EXT) + if source is None and still: + source = item["path"] + if not still and item["mediaKind"] != "video": + return thumbs.placeholder(item["mediaKind"], bucket), media.BRIEF + cached = _thumb_dir() / f"{_stem(item)}_{bucket}.webp" + if cached.is_file() and cached.stat().st_size > 0: + return cached, media.FOREVER + try: + data = thumbs.make(source, bucket) if still else thumbs.poster(item["path"], item["seconds"], bucket) + except Exception as exc: + log.warning("starter thumbnail for %s could not be made (%s)", item["uid"], exc) + data = None + if data is None: + return thumbs.placeholder(item["mediaKind"], bucket), media.BRIEF + temporary = cached.with_name(f".{cached.name}.{uuid.uuid4().hex}.tmp") + try: + temporary.write_bytes(data) + os.replace(temporary, cached) + except OSError: + return data, media.BRIEF + finally: + temporary.unlink(missing_ok=True) + return cached, media.FOREVER + + +def credit_for(item: dict) -> dict: + pack = _pack(item["pack"]) + return { + "licence": pack["licence"], "author": pack["author"], "sourceUrl": pack["sourceUrl"], "version": pack["version"], + "retrieved": pack["retrieved"], "licenceEvidence": pack["licenceEvidence"], "pack": pack["id"], "packName": pack["name"], + "item": item["id"], "itemName": item["name"], "from": "formcraft starter library", + **({"sourcePage": item["sourcePage"]} if item["sourcePage"] else {}), + } + + +def _import_credited(item: dict, extra: dict | None = None) -> dict: + added, _ = media.import_path(item["path"]) + current = (media.get(added["id"]) or added).get("meta") or {} + credit = credit_for(item) | (extra or {}) + return media.update(added["id"], meta={**current, "credit": credit}) + + +def add_to_library(pack_id: str, item_id: str) -> dict: + item = find(pack_id, item_id) + maps: dict[str, str] = {} + for role, uid in item["maps"].items(): + part = load()["items"].get(uid) + if part is not None and part is not item and part["path"].is_file(): + maps[role] = _import_credited(part, {"material": item["name"], "map": role})["id"] + return _import_credited(item, {"material": item["name"], "map": "color", "maps": maps} if maps else None) diff --git a/backend/formcraft_engine.py b/backend/formcraft_engine.py index f53c7b8..5cd1557 100644 --- a/backend/formcraft_engine.py +++ b/backend/formcraft_engine.py @@ -15,6 +15,12 @@ def selfcheck() -> int: info[name.lower()] = getattr(module, "__version__", "ok") except Exception as exc: info[name.lower()] = f"missing: {exc}" + try: + import keyring.backend + + info["keyring_backends"] = sorted(type(k).__module__.rsplit(".", 1)[-1] for k in keyring.backend.get_all_keyring()) + except Exception as exc: + info["keyring_backends"] = f"missing: {exc}" try: import io import sqlite3 diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 8c50a0b..11c98ee 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -7151,3 +7151,31 @@ Checked in a real Chrome against the engine: a reload keeps the dock working (th - **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. + +## 2026-11-29 · v0.10.0 the usability round {#usable-v0100} + +- **Why Record hung.** `ui/scene/output` tried the window's WebCodecs encoder first. Its `add` waits for a `dequeue` event once four frames are queued and that wait has no time limit; the macOS webview may never send the event, and Stop only set a flag the stuck loop never read. The engine sink is now first, the window sink is the fallback, and every wait has a limit. Reproduced in headless Chrome by dropping `dequeue` events. Not run on a Mac. +- **Scene dock (`ui/scene/panels/dock.ts`, `styles/scene-dock.css`).** Panels are grid areas, not absolutely placed boxes that measured each other. `panels/column.ts` is gone. The view keeps its own resize observer; the renderer is never recreated. `view/framing.ts` no longer reserves space for floating chrome. +- **Viewport state (`engine/scene/viewport.ts`).** Display modes, orthographic and per-object "Display as" are editor state. They are not saved with the project and never reach a capture or a recording, except "Hidden in render". +- **Materials and environment.** New optional fields in the scene document (`engine/scene/material.ts`, `env-map.ts`); a 0.9 document parses unchanged and an older reader ignores them. The engine packs every library file a document refers to, so `.fcrft` needed no change. +- **Saving (`ui/projects/disk.ts`, `file-commands.ts`, `autosave.ts`).** Save writes the library copy and a file the user chose. Autosave goes to the app data `autosave` folder only. Edit and Board already save on their own and are not autosaved. +- **Approvals (`automation/approvals.ts`).** A grant is kept per risk class, not per command id. The window sends the open project's id on each poll so a project grant follows the open project. The blurring dialog stays for spending and risky steps. +- **Agent tools.** `tools-scene-build.ts`, `tools-scene-time.ts`, `tools-scene-io.ts`, `tools-scene-material.ts`. Keying needs no mode, selection or open timeline (`engine/scene/tl-batch.ts`). +- **Shared primitives.** `ui/position.ts` (`placeFloating`), `ui/tooltip.ts`, and the toast strip (`--cv-toast-strip-h`, 32px less stage height; set it to 0 to undo). `--fs-9` and `--fs-10` are 11px. +- **Renames.** "3D object" is "3D model", transform space "World" is "Global", Board view "Canvas" is "Freeform". Command ids did not change. +- **Adapted from the family (Apache-2.0).** Title bar order and look from formvis `ui/titlebar-tools.ts` and `styles/shell.css`; the segmented switcher from formvis `styles/panels.css`; the key store wording from formvis `ui/panels/connection-settings.ts`. +- **Open.** A true cross dissolve, track lock, solo and heights in Edit; a text tool, crop and lasso in Canvas; align, lock and arrows in Board; 3D thumbnails render in page order; `?` is the cheatsheet and `scene.navHelp` has no key. +- Removed code: `ui/scene/panels/column.ts`; the Home "Examples" block; the Downloads and File names groups in "Library and Files" (their code is still in `panels/library-files.ts`). + +## 2026-11-29 · v0.11.0 parity, the family shell and the re-sourced starter library {#parity-v0110} + +- **No ArtCraft code.** Behaviour came from notes kept outside the repo; nobody who wrote code here read ArtCraft's source. A comparison of six-line runs and whole-file hashes against ArtCraft found one match only: the fal voice enum in `backend/app/catalogue/data/audio.json` (fal's own API data, here since 0.2.0). +- **Home and brand.** Layout and count chips follow formdeck `frontend/src/ui/home.ts` and `styles/shell.css` (Apache-2.0). Brand images live in `public/brand/` and `public/brand-*.png`; `assets/icon_src/build.py` regenerates every icon from `formcraft_icon_source.png` and is adapted from formdeck `assets/icon_src/build.py`. +- **One key flow.** `ui/prompt/key-sheet.ts` is the only place a key is added from a run; `ui/key-setup.ts` was removed. Preferences stays the place to manage keys. +- **Jobs.** Window-side work (Scene Record, Edit export) reports through `engine/local-jobs.ts` so the Jobs popover shows it beside engine jobs. +- **Canvas extend.** One path grows the canvas (`ui/canvas/tools/crop.ts`); "Extend the image" uses it, and Accept adds a full-frame layer so undo covers it. Generation sends the baked composite from `ui/canvas/stage/bake.ts`. +- **Edit transitions.** `engine/edit/transitions.ts`; the shared renderer draws them, so preview and export match. +- **Scene editor prefs.** Display mode, orthographic, overlays and snap are an optional `editorPrefs` field; changing them does not mark the scene edited. +- **Tours.** `ui/help/tour.ts` takes Esc only while its card is visible. +- **Edit open.** `activeProjectId()` must not start a studio; it did, and the Edit opener kept the blank studio. +- Removed code: `ui/key-setup.ts`, `ui/canvas/generate/extend.ts`, the Media pop-up panel in `ui/panels/media-drawer.ts`, `.fc-ed-dots` and `.fc-ed-ob-actions`. diff --git a/frontend/index.html b/frontend/index.html index 5f7b661..068fcef 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -5,7 +5,9 @@ <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="color-scheme" content="dark light"> <title>FormCraft + + diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 33f26ea..37332fd 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formcraft-frontend", - "version": "0.9.4", + "version": "0.11.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formcraft-frontend", - "version": "0.9.4", + "version": "0.11.0", "license": "Apache-2.0", "dependencies": { "@fontsource/inter": "5.3.0", diff --git a/frontend/package.json b/frontend/package.json index dfcf8dd..ebf882f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formcraft-frontend", "private": true, - "version": "0.9.4", + "version": "0.11.0", "description": "formcraft frontend · the studio window", "license": "Apache-2.0", "type": "module", diff --git a/frontend/public/apple-touch-icon.png b/frontend/public/apple-touch-icon.png new file mode 100644 index 0000000..2c2c1a5 Binary files /dev/null and b/frontend/public/apple-touch-icon.png differ diff --git a/frontend/public/brand-128.png b/frontend/public/brand-128.png new file mode 100644 index 0000000..758df6e Binary files /dev/null and b/frontend/public/brand-128.png differ diff --git a/frontend/public/brand-32.png b/frontend/public/brand-32.png new file mode 100644 index 0000000..f6011df Binary files /dev/null and b/frontend/public/brand-32.png differ diff --git a/frontend/public/brand-64.png b/frontend/public/brand-64.png new file mode 100644 index 0000000..f4c4a64 Binary files /dev/null and b/frontend/public/brand-64.png differ diff --git a/frontend/public/brand/formcraft-16.png b/frontend/public/brand/formcraft-16.png new file mode 100644 index 0000000..8af9f28 Binary files /dev/null and b/frontend/public/brand/formcraft-16.png differ diff --git a/frontend/public/brand/formcraft-16@2x.png b/frontend/public/brand/formcraft-16@2x.png new file mode 100644 index 0000000..11e66b9 Binary files /dev/null and b/frontend/public/brand/formcraft-16@2x.png differ diff --git a/frontend/public/brand/formcraft-20.png b/frontend/public/brand/formcraft-20.png new file mode 100644 index 0000000..c1a9db1 Binary files /dev/null and b/frontend/public/brand/formcraft-20.png differ diff --git a/frontend/public/brand/formcraft-20@2x.png b/frontend/public/brand/formcraft-20@2x.png new file mode 100644 index 0000000..b29a8b5 Binary files /dev/null and b/frontend/public/brand/formcraft-20@2x.png differ diff --git a/frontend/public/brand/formcraft-26.png b/frontend/public/brand/formcraft-26.png new file mode 100644 index 0000000..5a81c72 Binary files /dev/null and b/frontend/public/brand/formcraft-26.png differ diff --git a/frontend/public/brand/formcraft-26@2x.png b/frontend/public/brand/formcraft-26@2x.png new file mode 100644 index 0000000..2f04cd4 Binary files /dev/null and b/frontend/public/brand/formcraft-26@2x.png differ diff --git a/frontend/public/brand/formcraft-28.png b/frontend/public/brand/formcraft-28.png new file mode 100644 index 0000000..dd00809 Binary files /dev/null and b/frontend/public/brand/formcraft-28.png differ diff --git a/frontend/public/brand/formcraft-28@2x.png b/frontend/public/brand/formcraft-28@2x.png new file mode 100644 index 0000000..a69533e Binary files /dev/null and b/frontend/public/brand/formcraft-28@2x.png differ diff --git a/frontend/public/favicon.ico b/frontend/public/favicon.ico new file mode 100644 index 0000000..1cf6183 Binary files /dev/null and b/frontend/public/favicon.ico differ diff --git a/frontend/public/favicon.png b/frontend/public/favicon.png index afdc730..8eeb9c4 100644 Binary files a/frontend/public/favicon.png and b/frontend/public/favicon.png differ diff --git a/frontend/public/formcraft-256.png b/frontend/public/formcraft-256.png index 5fcc679..805c2d9 100644 Binary files a/frontend/public/formcraft-256.png and b/frontend/public/formcraft-256.png differ diff --git a/frontend/public/icon-192.png b/frontend/public/icon-192.png new file mode 100644 index 0000000..37e9ee2 Binary files /dev/null and b/frontend/public/icon-192.png differ diff --git a/frontend/public/icon-512.png b/frontend/public/icon-512.png new file mode 100644 index 0000000..99a0792 Binary files /dev/null and b/frontend/public/icon-512.png differ diff --git a/frontend/src/app.ts b/frontend/src/app.ts index 09cc758..022b042 100644 --- a/frontend/src/app.ts +++ b/frontend/src/app.ts @@ -1,5 +1,5 @@ import { Dock } from './dock/dock'; -import { formcraftDock, reserveDock } from './dock-adapter'; +import { AGENTS_ID, formcraftDock, reserveDock } from './dock-adapter'; import { commands, type Command } from './engine/commands'; import { Emitter } from './engine/emitter'; import { jobs } from './engine/jobs'; @@ -19,6 +19,7 @@ import { loadPrefs } from './ui/prefs'; import { mountPreferences } from './ui/prefs-dialog'; import { wireSounds } from './ui/sounds'; import { mountStatusBar } from './ui/status'; +import { installTooltips } from './ui/tooltip'; import { applyTheme, isLightTheme, readChoice, setTheme } from './ui/themes'; import { mountTitleBar } from './ui/titlebar'; import { mountCreatePages } from './ui/create'; @@ -40,6 +41,7 @@ import { canvasReadyToClose } from './ui/canvas/base/bridge'; import { dropFilesInScene, sceneReadyToClose } from './ui/scene/bridge'; import { openUploadDialog } from './ui/upload/upload-dialog'; import { toast } from './ui/toasts'; +import './ui/library/starter/starter-picker'; import { APP_NAME } from './version'; const STUDIO_KEY = 'formcraft.studio'; @@ -49,7 +51,7 @@ const STUDIO_LIST: Studio[] = [ { id: 'image', label: 'Image', icon: 'image', kind: 'studio', parent: 'create' }, { id: 'video', label: 'Video', icon: 'video', kind: 'studio', parent: 'create' }, { id: 'audio', label: 'Audio', icon: 'audio', kind: 'studio', parent: 'create' }, - { id: 'object', label: '3D object', icon: 'cube', kind: 'studio', parent: 'create' }, + { id: 'object', label: '3D model', icon: 'cube', kind: 'studio', parent: 'create' }, { id: 'world', label: 'World', icon: 'globe', kind: 'studio', parent: 'create' }, { id: 'canvas', label: 'Canvas', icon: 'canvas', kind: 'studio' }, { id: 'scene', label: 'Scene', icon: 'scene', kind: 'studio' }, @@ -154,7 +156,7 @@ function shellHtml(): string { `` + `
` + `
` + - `
${icon('brand', 20)}
` + + `
` + `
` + `` + `
` + @@ -356,6 +358,7 @@ async function guardClose(): Promise { let ready = true; try { ready = (await sceneReadyToClose()) && (await canvasReadyToClose()) && (await boardReadyToClose()) && (await editReadyToClose()); + if (ready) await (await import('./ui/projects/autosave')).clearAutosaves(); } catch { ready = true; } @@ -402,6 +405,7 @@ export function startApp(): void { mountTitleBar(m); mountStatusBar(m); + installTooltips(); const home = mountHome(m); const prefs = mountPreferences(); hooks.showHome = () => home.show(); @@ -414,9 +418,22 @@ export function startApp(): void { firstRun: () => !homeOpen() && !anyDialogOpen(), })); dock.onChange = () => commands.refresh(); + dock.onTab = () => commands.refresh(); dock.mount(m.root, m.status); + const PANELS_KEY = 'formcraft.panels'; + const panelsShown = (): boolean => document.documentElement.getAttribute('data-fc-panels') !== 'hidden'; + const showPanels = (on: boolean): void => { + if (on) document.documentElement.removeAttribute('data-fc-panels'); + else document.documentElement.setAttribute('data-fc-panels', 'hidden'); + commands.refresh(); + try { localStorage.setItem(PANELS_KEY, on ? 'shown' : 'hidden'); } catch { return; } + }; + const savedPanels = ((): string | null => { try { return localStorage.getItem(PANELS_KEY); } catch { return null; } })(); + if (savedPanels === 'hidden') document.documentElement.setAttribute('data-fc-panels', 'hidden'); commands.register([ - { id: 'view-terminal', label: 'Terminal', group: 'View', keys: ['Mod+Backquote'], checked: () => dock.isOpen(), run: () => dock.toggle() }, + { id: AGENTS_ID, label: 'Show Agents', group: 'View', keys: ['Mod+Backquote'], checked: () => dock.isOpen(), run: () => dock.toggle() }, + { id: 'view-terminal', label: 'Show Terminal', group: 'View', checked: () => dock.isShowing('shell'), run: () => void dock.toggleKind('shell') }, + { id: 'view-panels', label: 'Show Panels', group: 'View', keys: ['Mod+Backslash'], enabled: () => studios.activeRoot === 'scene', checked: () => panelsShown(), run: () => showPanels(!panelsShown()) }, { id: 'new-terminal', label: 'New Terminal', group: 'View', run: () => void dock.newTerminal() }, { id: 'claude-code', label: 'Claude Code', group: 'View', keys: ['Shift+Mod+Backquote'], run: () => void dock.show('claude') }, ]); @@ -451,11 +468,11 @@ export function startApp(): void { if (!c.keys?.length && !shortcuts.has(c.id)) shortcuts.define({ action: c.id, keys: [], group: c.group }); } - m.brand.addEventListener('click', () => void commands.run('home')); + m.brand.addEventListener('click', () => void commands.run('tool-menu')); m.brand.addEventListener('keydown', (e) => { if (e.key !== 'Enter' && e.key !== ' ') return; e.preventDefault(); - void commands.run('home'); + void commands.run('tool-menu'); }); m.studioSwitcher.addEventListener('click', (e) => { const b = (e.target as Element).closest('.fc-sw'); diff --git a/frontend/src/automation/approvals.ts b/frontend/src/automation/approvals.ts index a22d31e..542e0e1 100644 --- a/frontend/src/automation/approvals.ts +++ b/frontend/src/automation/approvals.ts @@ -1,16 +1,27 @@ import '../styles/agents.css'; -import { answerApproval, type BridgeApproval } from '../io/api-agents'; -import { Dialog } from '../ui/dialogs'; -import { el, q, setDisabled, setHidden, setText } from '../ui/dom'; -import { t } from '../ui/i18n'; +import { answerApproval, type AgentLevel, type ApprovalScope, type BridgeApproval } from '../io/api-agents'; +import { Dialog, anyDialogOpen } from '../ui/dialogs'; +import { el, q, setDisabled, setHidden, setText, setTitle } from '../ui/dom'; +import { relabel, t } from '../ui/i18n'; +import { activeProjectId } from '../ui/projects/file-commands'; const WAIT_MS = 115000; const LINE_MAX = 160; const LINES_MAX = 8; +const CARD_LINES = 2; + +export const LEVEL_LABEL: Record = { + ask: 'Ask every time', + session: 'Ask once per session', + project: 'Always allow in this project', + allow: 'Always allow everywhere', + deny: 'Deny', +}; interface Decision { allow: boolean; remember: boolean; + scope?: ApprovalScope; withdrawn?: boolean; } @@ -93,16 +104,16 @@ class ApprovalDialog extends Dialog { if (!w) return; this.current = w; const { item } = w; - setText(this.lead, t('An outside agent wants to run a tool in this window. It waits until you answer.')); + setText(this.lead, `${t('An outside agent wants to run a tool in this window. It waits until you answer.')} ${t('Now: {level}').replace('{level}', t(LEVEL_LABEL[item.level ?? 'ask']))}`); setText(this.client, item.client); - setText(this.tool, item.tool); + setText(this.tool, item.title && item.title !== item.tool ? `${item.title} (${item.tool})` : item.tool); setText(this.args, summarise(item.args)); const priced = typeof item.costUsd === 'number'; setHidden(this.costRow, !priced); const price = priced ? `$${(item.costUsd as number).toFixed(2)}` : ''; if (priced) setText(q(this.costRow, '.fc-ag-val'), price); this.remember.checked = false; - const offered = priced || item.tool !== 'generate'; + const offered = item.keepable ?? (priced || item.tool !== 'generate'); this.keep.style.visibility = offered ? '' : 'hidden'; setDisabled(this.remember, !offered); setText(this.rememberText, t(priced ? 'Remember this choice for {client} up to {cost}' : 'Remember this choice for {client}').replace('{client}', item.client).replace('{cost}', price)); @@ -123,18 +134,139 @@ class ApprovalDialog extends Dialog { } } +interface Queued extends Waiting { + timer: number; +} + +const editable = (node: Element | null): boolean => + !!node && (node instanceof HTMLInputElement || node instanceof HTMLTextAreaElement || node instanceof HTMLSelectElement || (node instanceof HTMLElement && node.isContentEditable)); + +function cardButton(english: string, kind: string, run: () => void): HTMLButtonElement { + const b = el(``); + b.dataset.en = english; + setText(b, t(english)); + b.addEventListener('click', run); + return b; +} + +class RequestCard { + private readonly root = el(''); + private readonly heading = el(''); + private readonly count = el(''); + private readonly what = el('

'); + private readonly detail = el('
');
+  private readonly level = el('

'); + private readonly all = cardButton('Allow all', 'ghost', () => this.allowAll()); + private readonly project = cardButton('Always allow in this project', 'ghost', () => this.finish(true, 'project')); + private readonly session = cardButton('Stop asking for this session', 'ghost', () => this.finish(true, 'session')); + private readonly deny = cardButton('Deny', 'ghost', () => this.finish(false)); + private readonly allow = cardButton('Allow', 'primary', () => this.finish(true)); + private readonly queue: Queued[] = []; + + constructor() { + setText(this.heading, t('Agent request')); + const head = el('
'); + head.append(this.heading, this.count, this.all); + const main = el('
'); + main.append(this.deny, this.project, this.allow); + const more = el('
'); + more.append(this.session); + this.root.append(head, this.what, this.detail, this.level, main, more); + setTitle(this.allow, t('Enter')); + setTitle(this.deny, t('Esc')); + document.getElementById('overlay-root')?.appendChild(this.root); + document.addEventListener('keydown', (e) => this.onKey(e), true); + } + + ask(item: BridgeApproval): Promise { + return new Promise((resolve) => { + const w: Queued = { item, settle: resolve, timer: 0 }; + w.timer = window.setTimeout(() => this.settle(w, { allow: false, remember: false }), WAIT_MS); + this.queue.push(w); + this.paint(); + }); + } + + withdraw(id: string): boolean { + const w = this.queue.find((x) => x.item.id === id); + if (!w) return false; + this.settle(w, { allow: false, remember: false, withdrawn: true }); + return true; + } + + private settle(w: Queued, d: Decision): void { + const at = this.queue.indexOf(w); + if (at < 0) return; + this.queue.splice(at, 1); + window.clearTimeout(w.timer); + w.settle(d); + this.paint(); + } + + private finish(allow: boolean, scope: ApprovalScope = 'once'): void { + const w = this.queue[0]; + if (w) this.settle(w, { allow, remember: false, scope }); + } + + private allowAll(): void { + for (const w of this.queue.slice()) this.settle(w, { allow: true, remember: false }); + } + + private onKey(e: KeyboardEvent): void { + if (this.root.hidden || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey || (e.key !== 'Enter' && e.key !== 'Escape')) return; + const inside = this.root.contains(document.activeElement); + if (!inside && (anyDialogOpen() || editable(document.activeElement))) return; + if (inside && e.key === 'Enter' && document.activeElement instanceof HTMLButtonElement) return; + e.preventDefault(); + e.stopPropagation(); + this.finish(e.key === 'Enter'); + } + + private paint(): void { + const w = this.queue[0]; + if (!w) { + if (this.root.contains(document.activeElement)) (document.activeElement as HTMLElement).blur(); + this.root.hidden = true; + return; + } + const { item } = w; + const many = this.queue.length > 1; + setText(this.count, many ? t('{n} waiting').replace('{n}', String(this.queue.length)) : ''); + setHidden(this.all, !many); + setText(this.what, t('{client} wants to: {action}').replace('{client}', item.client).replace('{action}', item.title || item.tool)); + setText(this.detail, [item.tool, ...summarise(item.args).split('\n')].slice(0, CARD_LINES + 1).join('\n')); + const level = item.level ?? 'ask'; + setText(this.level, t('Now: {level}').replace('{level}', t(LEVEL_LABEL[level]))); + setDisabled(this.project, !item.project); + setTitle(this.project, item.project ? t('Project: {name}').replace('{name}', item.project.name) : t('Open or save a project first.')); + if (this.root.hidden) { + relabel(this.root); + this.root.hidden = false; + } + } +} + let dialog: ApprovalDialog | null = null; +let card: RequestCard | null = null; export function withdrawApproval(id: string): void { + if (card?.withdraw(id)) return; dialog?.withdraw(id); } export async function handleApproval(item: BridgeApproval): Promise { - dialog ??= new ApprovalDialog(); - const decision = await dialog.ask(item); + let decision: Decision; + if ((item.risk ?? 'normal') === 'normal' && typeof item.costUsd !== 'number') { + card ??= new RequestCard(); + decision = await card.ask(item); + } else { + dialog ??= new ApprovalDialog(); + decision = await dialog.ask(item); + } if (decision.withdrawn) return; try { - await answerApproval(item.id, decision.allow, decision.remember); + const scope = decision.allow ? decision.scope : 'once'; + await answerApproval(item.id, decision.allow, decision.remember, scope, scope === 'project' ? await activeProjectId() : undefined); } catch (err) { console.error('[agents] approval answer', err); } diff --git a/frontend/src/automation/bridge.ts b/frontend/src/automation/bridge.ts index 030feec..22fffc5 100644 --- a/frontend/src/automation/bridge.ts +++ b/frontend/src/automation/bridge.ts @@ -1,9 +1,11 @@ import { ApiError } from '../io/api'; import { answerBridge, nextBridge, type BridgeAnswer, type BridgeCall, type BridgeItem } from '../io/api-agents'; +import { activeProjectId } from '../ui/projects/file-commands'; import { handleApproval, withdrawApproval } from './approvals'; import { ToolError, asArgs, getTool, validate } from './tool'; const WAIT_SECONDS = 25; +const PROJECT_CHECK_MS = 1000; const BACKOFF_MS = [1000, 2000, 4000, 8000, 15000]; const TEXT_MAX = 200000; @@ -76,7 +78,8 @@ export function startBridge(): () => void { while (!stopped && gen === generation) { ctrl = new AbortController(); try { - const item = await nextBridge(WAIT_SECONDS, { signal: ctrl.signal }); + sent = await activeProjectId(); + const item = await nextBridge(WAIT_SECONDS, { signal: ctrl.signal }, sent); failures = 0; if (item && !stopped && gen === generation) dispatch(item); } catch (err) { @@ -87,6 +90,15 @@ export function startBridge(): () => void { } }; + let sent: string | null = null; + const watch = window.setInterval(() => { + if (stopped || !ctrl) return; + const polling = ctrl; + void activeProjectId().then((id) => { + if (id !== sent && polling === ctrl) polling.abort(); + }); + }, PROJECT_CHECK_MS); + const start = (): void => { stopped = false; generation += 1; @@ -112,6 +124,7 @@ export function startBridge(): () => void { return () => { window.removeEventListener('pagehide', leave); window.removeEventListener('pageshow', back); + window.clearInterval(watch); stop(); }; } diff --git a/frontend/src/automation/index.ts b/frontend/src/automation/index.ts index d609126..a1773b3 100644 --- a/frontend/src/automation/index.ts +++ b/frontend/src/automation/index.ts @@ -5,6 +5,9 @@ import { registerCanvasTools } from './tools-canvas'; import { registerCoreTools } from './tools-core'; import { registerEditTools } from './tools-edit'; import { registerSceneTools } from './tools-scene'; +import { registerSceneBuildTools } from './tools-scene-build'; +import { registerSceneOutputTools } from './tools-scene-io'; +import { registerSceneTimeTools } from './tools-scene-time'; let running = false; @@ -14,6 +17,9 @@ export function startAutomation(): void { registerCoreTools(); registerEditTools(); registerSceneTools(); + registerSceneBuildTools(); + registerSceneTimeTools(); + registerSceneOutputTools(); registerCanvasTools(); registerBoardTools(); startCatalogue(); diff --git a/frontend/src/automation/tool.ts b/frontend/src/automation/tool.ts index c5c4b12..e852565 100644 --- a/frontend/src/automation/tool.ts +++ b/frontend/src/automation/tool.ts @@ -139,7 +139,7 @@ export function validate(schema: Schema, value: unknown, path = 'arguments'): st if (v === undefined) continue; const sub = props[key]; if (!sub) { - if (schema.additionalProperties === false) return `${path}.${key} is not a known field.`; + if (schema.additionalProperties === false) return `${path}.${key} is not a known field. The fields are: ${Object.keys(props).join(', ') || 'none'}.`; continue; } const bad = validate(sub, v, `${path}.${key}`); diff --git a/frontend/src/automation/tools-core.ts b/frontend/src/automation/tools-core.ts index f7a910d..b57926f 100644 --- a/frontend/src/automation/tools-core.ts +++ b/frontend/src/automation/tools-core.ts @@ -7,7 +7,8 @@ import { canvasLoaded, canvasUnsaved } from '../ui/canvas/base/bridge'; import { editLoaded, editUnsaved } from '../ui/edit/bridge'; import { sceneLoaded, sceneUnsaved } from '../ui/scene/bridge'; import { showProject } from '../ui/projects'; -import { mounted } from './access'; +import { gateFacts, gateOpen, sceneAction } from '../engine/scene/actions'; +import { mounted, sceneHandle } from './access'; import { CHANGES, READ_ONLY, ToolError, bool, defineTools, int, json, obj, oneOf, str, type Args } from './tool'; function describeCommand(id: string): Record { @@ -40,6 +41,66 @@ function disabledHint(studio: string): string { return open ? 'Its conditions are not met right now (nothing selected, a busy state, or a tool already active).' : `The ${root} studio is not the active studio. Call studio_open with studio "${root}", then try again.`; } +const GATE_WORDS: Record = { + build: 'the Scene studio is in Record mode and this needs Build mode', + record: 'this needs Record mode', + selection: 'nothing is selected', + 'timeline-open': 'the timeline panel is closed', + 'timeline-selection': 'no key or clip is picked on the timeline', + 'not-busy': 'a capture or recording is running', + busy: 'nothing is rendering', + 'playback-context': 'the timeline is closed and nothing is playing', + pose: 'pose mode is off', + 'camera-view': 'the view is not looking through the camera', + '!timeline-open': 'the timeline panel is open', + '!pose': 'pose mode is on', + '!camera-view': 'the view is looking through the camera', + '!playback-context': 'the timeline is open or playing', + '!timeline-selection': 'a key or clip is picked on the timeline', +}; + +const INSTEAD: Record = { + 'scene.keyframe': 'scene_keys_set (keys any object at any time; no mode, selection or open timeline needed)', + 'scene.timelineDelete': 'scene_keys_delete', + 'scene.record': 'scene_record_start (switches to Record mode by itself)', + 'scene.capture': 'scene_capture', + 'scene.cancelOutput': 'scene_record_stop', + 'scene.mode': 'scene_mode (keeps the selection)', + 'scene.save': 'scene_save', + 'scene.delete': 'scene_delete', + 'scene.group': 'scene_group', + 'scene.ungroup': 'scene_ungroup', + 'scene.duplicate': 'scene_add_many', + 'scene.deselect': 'scene_select with id null', + 'scene.cameraView': 'scene_camera', + 'scene.timelineStart': 'scene_timeline_set with playheadSec 0', + 'scene.timelineEnd': 'scene_timeline_set with playheadSec', + 'scene.stepBack': 'scene_timeline_set with playheadFrame', + 'scene.stepForward': 'scene_timeline_set with playheadFrame', +}; + +async function sceneReason(id: string): Promise { + if (!id.startsWith('scene.') || !mounted('scene')) return null; + const ctx = await sceneHandle(); + const def = sceneAction(id); + const facts = gateFacts(ctx.store, ctx.editor); + const failing = def ? def.gate.filter((term) => !gateOpen(term, facts)).map((term) => GATE_WORDS[term] ?? term) : []; + return failing.length ? `It cannot run because ${failing.join(', and ')}.` : 'Its own condition is not met (the recorder is not ready, or there is nothing to act on).'; +} + +async function describeFull(id: string): Promise> { + const info = describeCommand(id); + if (!info.enabled) { + const why = await sceneReason(id); + if (why) info.disabledBecause = why; + } + if (INSTEAD[id]) { + info.preferTool = INSTEAD[id]; + if (!info.enabled) info.disabledBecause = `${String(info.disabledBecause ?? '')} Call ${INSTEAD[id]} instead.`.trim(); + } + return info; +} + function listCommands(args: Args): Record { const studio = typeof args.studio === 'string' ? args.studio : ''; const group = typeof args.group === 'string' ? args.group.toLowerCase() : ''; @@ -124,7 +185,7 @@ export function registerCoreTools(): void { inputSchema: obj({ id: str('The command id from commands_list.') }, ['id']), annotations: READ_ONLY, studio: 'core', - run: async (args) => json(describeCommand(String(args.id))), + run: async (args) => json(await describeFull(String(args.id))), }, { name: 'command_run', @@ -136,7 +197,7 @@ export function registerCoreTools(): void { studio: 'core', run: async (args) => { const id = String(args.id); - const info = describeCommand(id); + const info = await describeFull(id); if (!info.enabled) throw new ToolError('command_disabled', `Command "${id}" cannot run right now. ${String(info.disabledBecause ?? '')}`.trim()); let failure: unknown = null; const off = commands.on('error', (failed, err) => { diff --git a/frontend/src/automation/tools-scene-build.ts b/frontend/src/automation/tools-scene-build.ts new file mode 100644 index 0000000..873a680 --- /dev/null +++ b/frontend/src/automation/tools-scene-build.ts @@ -0,0 +1,264 @@ +import { lookAtEuler } from '../engine/scene/matrix'; +import { OBJECT_KINDS, SHAPE_KEYS, newObject, type NewObjectOptions, type ObjectPatch } from '../engine/scene/objects'; +import type { SceneStore } from '../engine/scene/store'; +import { worldMatrix } from '../engine/scene/tree'; +import { MAX_CAMERAS, type ObjectKind, type SceneObject, type ShapeKey, type Vec3 } from '../engine/scene/types'; +import { getMedia, type Media } from '../io/api'; +import { sceneHandle } from './access'; +import { ADDS, CHANGES, DESTROYS, READ_ONLY, ToolError, arr, asArgs, bool, defineTools, json, num, obj, oneOf, str, type Args } from './tool'; +import { readVec, row, vec } from './tools-scene'; +import { MATERIAL_PROPS, materialArgs } from './tools-scene-material'; + +const NEEDS_MEDIA: readonly ObjectKind[] = ['image', 'video', 'model', 'splat']; +const BATCH_MAX = 500; +type Ref = { id: string; group: boolean }; +const ids = (description: string): Record => arr({ type: 'string' }, description, { minItems: 1, maxItems: BATCH_MAX }); + +const ITEM = obj( + { + ref: str('Your own short label for this item, so later items in the same call can use it as parent.', { maxLength: 80 }), + kind: oneOf(OBJECT_KINDS, 'What to add.'), + shape: oneOf(SHAPE_KEYS, 'For kind shape: which primitive (default cube).'), + mediaId: str('Library item id, required for image, video, model and splat.'), + name: str('Name for the object.', { maxLength: 80 }), + position: vec('[x, y, z] in metres.'), + rotation: vec('[x, y, z] in degrees.'), + scale: vec('[x, y, z] factors.'), + color: str('Hex colour such as #ffaa00.'), + parent: str('Id of a group already in the scene, or the ref of a group earlier in this list.'), + ...MATERIAL_PROPS, + lightIntensity: num('For kind light: intensity (default 1).', { minimum: 0, maximum: 1000 }), + lightDistance: num('For kind light: reach in metres (default 100).', { minimum: 0, maximum: 10000 }), + focalMm: num('For kind camera: focal length in mm, 10 to 200.', { minimum: 10, maximum: 200 }), + visible: bool('Show the object (default true).'), + locked: bool('Lock the object (default false).'), + }, + ['kind'], +); + +function mediaFits(kind: ObjectKind, media: Media): boolean { + return kind === 'image' ? media.kind === 'image' : kind === 'video' ? media.kind === 'video' : kind === 'model' ? media.kind === 'model' : media.kind === 'splat'; +} + +async function buildItem(store: SceneStore, a: Args, at: string, refs: Map, names: Set, media: Map): Promise { + const kind = a.kind as ObjectKind; + const opts: NewObjectOptions = { names }; + if (typeof a.name === 'string') opts.name = a.name; + if (typeof a.color === 'string') opts.color = a.color; + if (kind === 'shape') opts.shape = (a.shape as ShapeKey | undefined) ?? 'cube'; + if (typeof a.visible === 'boolean') opts.visible = a.visible; + if (typeof a.locked === 'boolean') opts.locked = a.locked; + const material = await materialArgs(a); + if (material) opts.material = material; + if (typeof a.lightIntensity === 'number' || typeof a.lightDistance === 'number') opts.light = { ...(typeof a.lightIntensity === 'number' ? { intensity: a.lightIntensity } : {}), ...(typeof a.lightDistance === 'number' ? { distance: a.lightDistance } : {}) }; + if (typeof a.focalMm === 'number') opts.camera = { focal: a.focalMm }; + if (typeof a.parent === 'string') { + const ref = refs.get(a.parent); + const id = ref ? ref.id : a.parent; + if (ref ? !ref.group : store.object(id)?.kind !== 'group') throw new ToolError('invalid_arguments', `${at}.parent "${a.parent}" is neither the id of a group in the scene nor the ref of a group earlier in this list.`); + if (kind === 'camera') throw new ToolError('invalid_arguments', `${at}: a camera stays at the top level, so it takes no parent.`); + opts.parent = id; + } + const position = readVec(a, 'position'); + const rotation = readVec(a, 'rotation'); + const scale = readVec(a, 'scale'); + if (position || rotation || scale) opts.transform = { ...(position ? { position } : {}), ...(rotation ? { rotation } : {}), ...(scale ? { scale } : {}) }; + else if (kind === 'camera') opts.transform = { position: [...store.doc.view.position], rotation: [...store.doc.view.rotation], scale: [1, 1, 1] }; + if (NEEDS_MEDIA.includes(kind)) { + if (typeof a.mediaId !== 'string') throw new ToolError('invalid_arguments', `${at}: a ${kind} object needs mediaId from the library (library_search).`); + let item = media.get(a.mediaId); + if (!item) { + try { + item = await getMedia(a.mediaId); + } catch { + throw new ToolError('not_found', `${at}: no library item with id "${a.mediaId}". Use library_search for ids.`); + } + media.set(a.mediaId, item); + } + if (!mediaFits(kind, item)) throw new ToolError('invalid_arguments', `${at}: a ${kind} object needs a library item of that kind, but "${a.mediaId}" is ${item.kind}.`); + opts.asset = { $media: item.id }; + } + const made = newObject(kind, opts); + names.add(made.name); + if (typeof a.ref === 'string') { + if (refs.has(a.ref)) throw new ToolError('invalid_arguments', `${at}.ref "${a.ref}" is used twice in this list.`); + refs.set(a.ref, { id: made.id, group: kind === 'group' }); + } + return made; +} + +function worldPosition(store: SceneStore, id: string): Vec3 { + const m = worldMatrix((i) => store.object(i), id); + return [m[12], m[13], m[14]]; +} + +function listObjects(store: SceneStore, a: Args): Record { + const kind = typeof a.kind === 'string' ? a.kind : ''; + const parent = typeof a.parent === 'string' ? a.parent : undefined; + const query = typeof a.query === 'string' ? a.query.toLowerCase() : ''; + const rows = []; + for (const o of store.doc.objects) { + if (kind && o.kind !== kind) continue; + if (parent !== undefined && (parent === 'root' ? o.parent !== null : o.parent !== parent)) continue; + if (query && !o.name.toLowerCase().includes(query)) continue; + const r = row(o); + if (o.kind === 'group') r.children = store.children(o.id).map((c) => c.id); + if (store.tl.hasKeys(o.id)) r.keyed = true; + rows.push(r); + } + return { total: rows.length, objects: rows, selected: store.selected, activeCamera: store.doc.activeCamera }; +} + +export function registerSceneBuildTools(): void { + defineTools([ + { + name: 'scene_list_objects', + title: 'List scene objects', + description: + 'List the objects of the open 3D scene with id, name, kind, parent, position (metres), rotation (degrees), scale, colour, material, the children of each group and whether it has keyframes. Filter by kind, parent ("root" for the top level) or name. Opens the Scene studio when it is not open.', + inputSchema: obj({ + kind: oneOf(OBJECT_KINDS, 'Only objects of this kind.'), + parent: str('Only the direct children of this group id, or "root" for the top level.'), + query: str('Only objects whose name contains this text.'), + }), + annotations: READ_ONLY, + studio: 'scene', + run: async (args) => { + const { store } = await sceneHandle(); + return json(listObjects(store, args)); + }, + }, + { + name: 'scene_add_many', + title: 'Add many objects to the scene', + description: `Add up to ${BATCH_MAX} objects in one call and one undo step, each with the same fields as scene_add (kind, shape, mediaId, name, position, rotation in degrees, scale, colour, material, light and camera settings). Give a group a ref and later items can use that ref as their parent, so a whole set (for example a corridor of walls, lights and props inside one group) is one call. Nothing is added when any item is wrong; the error names the item. The selection does not change.`, + inputSchema: obj({ objects: arr(ITEM, 'The objects to add, in order.', { minItems: 1, maxItems: BATCH_MAX }) }, ['objects']), + annotations: ADDS, + studio: 'scene', + run: async (args) => { + const { store } = await sceneHandle(); + const items = (args.objects as unknown[]).map(asArgs); + const cameras = items.filter((a) => a.kind === 'camera').length; + if (store.cameras.length + cameras > MAX_CAMERAS) throw new ToolError('too_many_cameras', `A scene holds at most ${MAX_CAMERAS} cameras; it has ${store.cameras.length} and this list adds ${cameras}.`); + const refs = new Map(); + const names = new Set(store.names()); + const media = new Map(); + const made: SceneObject[] = []; + for (let i = 0; i < items.length; i++) made.push(await buildItem(store, items[i], `objects[${i}]`, refs, names, media)); + const added = store.add(made, 'user', { select: false, label: made.length === 1 ? `Add ${made[0].name}` : `Add ${made.length} objects` }); + if (added.length !== made.length) throw new ToolError('not_added', `Only ${added.length} of ${made.length} objects could be added. Call scene_list_objects to see the scene.`); + return json( + { count: added.length, added: made.map((o, i) => ({ ...(typeof items[i].ref === 'string' ? { ref: items[i].ref } : {}), id: added[i], name: o.name, kind: o.kind, ...(o.parent ? { parent: o.parent } : {}) })) }, + `Added ${added.length} objects.`, + ); + }, + }, + { + name: 'scene_delete', + title: 'Delete scene objects', + description: 'Delete objects by id, with everything inside a deleted group and their keyframes, in one undo step. The first camera cannot be deleted.', + inputSchema: obj({ ids: ids('Ids from scene_list_objects.') }, ['ids']), + annotations: DESTROYS, + studio: 'scene', + run: async (args) => { + const { store } = await sceneHandle(); + const asked = args.ids as string[]; + const missing = asked.filter((id) => !store.object(id)); + if (missing.length) throw new ToolError('unknown_object', `No object with id ${missing.map((m) => `"${m}"`).join(', ')}. Call scene_list_objects for the ids.`); + const removed = store.remove(asked); + if (!removed.length) throw new ToolError('not_deleted', 'Nothing was deleted: the first camera of a scene always stays.'); + return json({ deleted: removed }, `Deleted ${removed.length} objects.`); + }, + }, + { + name: 'scene_select', + title: 'Select a scene object', + description: 'Select one object (as if it were clicked in the outliner), or clear the selection with id null. No other scene tool needs a selection; this is for showing the person something.', + inputSchema: obj({ id: { type: ['string', 'null'], description: 'Object id, or null to clear.' } }, ['id']), + annotations: CHANGES, + studio: 'scene', + run: async (args) => { + const { store } = await sceneHandle(); + const id = typeof args.id === 'string' ? args.id : null; + if (id && !store.object(id)) throw new ToolError('unknown_object', `No object with id "${id}". Call scene_list_objects for the ids.`); + store.select(id); + return json({ selected: store.selected }); + }, + }, + { + name: 'scene_group', + title: 'Group scene objects', + description: 'Put objects into a new group placed at their centre, keeping where they are in the world. Cameras are left out. One undo step. Returns the group id.', + inputSchema: obj({ ids: ids('Ids of the objects to group.'), name: str('Name for the group.', { maxLength: 80 }) }, ['ids']), + annotations: ADDS, + studio: 'scene', + run: async (args) => { + const { store } = await sceneHandle(); + const asked = args.ids as string[]; + const missing = asked.filter((id) => !store.object(id)); + if (missing.length) throw new ToolError('unknown_object', `No object with id ${missing.map((m) => `"${m}"`).join(', ')}. Call scene_list_objects for the ids.`); + const group = store.group(asked); + if (!group) throw new ToolError('not_grouped', 'Nothing could be grouped: cameras cannot go in a group.'); + if (typeof args.name === 'string' && args.name.trim()) store.rename(group, args.name); + const made = store.object(group); + return json({ group: made ? row(made) : group, members: store.children(group).map((c) => c.id) }); + }, + }, + { + name: 'scene_ungroup', + title: 'Ungroup', + description: 'Dissolve a group: its children move to the group\'s parent and keep their place in the world. One undo step.', + inputSchema: obj({ id: str('Group id.') }, ['id']), + annotations: DESTROYS, + studio: 'scene', + run: async (args) => { + const { store } = await sceneHandle(); + const id = String(args.id); + if (store.object(id)?.kind !== 'group') throw new ToolError('invalid_arguments', `"${id}" is not a group. Call scene_list_objects with kind group for the ids.`); + const freed = store.ungroup(id); + if (!freed) throw new ToolError('not_changed', 'The group could not be dissolved.'); + return json({ freed }); + }, + }, + { + name: 'scene_camera', + title: 'Set up a camera', + description: + 'Aim and set up a camera in one call: make it the active camera (the one stills and recordings look through), set its focal length, move it, and point it at a point or at an object. Leave out id for the active camera. To animate a camera, key it with scene_keys_set like any object.', + inputSchema: obj({ + id: str('Camera id. Default: the active camera.'), + active: bool('Make this camera the active one.'), + focalMm: num('Focal length in mm, 10 to 200 (lower is wider).', { minimum: 10, maximum: 200 }), + position: vec('[x, y, z] in metres.'), + rotation: vec('[x, y, z] in degrees. Ignored when lookAt or lookAtObject is given.'), + lookAt: vec('Point the camera at this [x, y, z] in metres.'), + lookAtObject: str('Point the camera at the centre of this object.'), + }), + annotations: CHANGES, + studio: 'scene', + run: async (args) => { + const { store } = await sceneHandle(); + const id = typeof args.id === 'string' ? args.id : store.doc.activeCamera; + const cam = store.object(id); + if (!cam || cam.kind !== 'camera') throw new ToolError('invalid_arguments', `"${id}" is not a camera. Call scene_list_objects with kind camera for the ids.`); + if (args.lookAt !== undefined && args.lookAtObject !== undefined) throw new ToolError('invalid_arguments', 'Give lookAt or lookAtObject, not both.'); + const position = readVec(args, 'position'); + let rotation = readVec(args, 'rotation'); + let target = readVec(args, 'lookAt'); + if (typeof args.lookAtObject === 'string') { + if (!store.object(args.lookAtObject)) throw new ToolError('unknown_object', `No object with id "${args.lookAtObject}". Call scene_list_objects for the ids.`); + target = worldPosition(store, args.lookAtObject); + } + if (target) rotation = lookAtEuler(position ?? cam.transform.position, target); + const patch: ObjectPatch = {}; + if (position || rotation) patch.transform = { ...(position ? { position } : {}), ...(rotation ? { rotation } : {}) }; + if (typeof args.focalMm === 'number') patch.camera = { focal: args.focalMm }; + const changed: string[] = []; + if (Object.keys(patch).length && store.update(id, patch, { label: 'Edit camera' })) changed.push('camera'); + if (args.active === true && store.doc.activeCamera !== id && store.setActiveCamera(id)) changed.push('activeCamera'); + const now = store.object(id); + return json({ changed, camera: now ? row(now) : null, active: store.doc.activeCamera === id }); + }, + }, + ]); +} diff --git a/frontend/src/automation/tools-scene-io.ts b/frontend/src/automation/tools-scene-io.ts new file mode 100644 index 0000000..9c97434 --- /dev/null +++ b/frontend/src/automation/tools-scene-io.ts @@ -0,0 +1,287 @@ +import { commands } from '../engine/commands'; +import { EASE, MAX_CAMERAS, MAX_DURATION, MAX_FOCAL_MM, MIN_DURATION, MIN_FOCAL_MM, SCENE_FPS, ASPECTS, SKYBOXES, OUTPUT_SIZES, type AspectId } from '../engine/scene/types'; +import { OBJECT_KINDS, SHAPE_KEYS, MODEL_ROLES } from '../engine/scene/objects'; +import { ApiError, listMedia } from '../io/api'; +import { createProject, exportProject, getProject, importProjectPath, type ProjectDoc } from '../io/api-projects'; +import { t } from '../ui/i18n'; +import { projectStore } from '../ui/projects/store'; +import { filesFor } from '../ui/scene/chrome'; +import { DEFAULT_NAME } from '../ui/scene/chrome/files'; +import type { SceneContext } from '../ui/scene/context'; +import { findSupport, unavailableReason, usable } from '../ui/scene/output/support'; +import { shotIds } from '../ui/scene/shot'; +import { sceneHandle } from './access'; +import { ADDS, CHANGES, READ_ONLY, ToolError, bool, defineTools, json, num, obj, oneOf, round, str } from './tool'; +import { switchMode } from './tools-scene-time'; + +const START_WAIT_MS = 20000; +const STOP_WAIT_MS = 10000; +const WAIT_MAX_SEC = 80; +const NAME_MAX = 120; + +let recording: { at: number; durationSec: number } | null = null; + +const sleep = (ms: number): Promise => new Promise((resolve) => window.setTimeout(resolve, ms)); + +const outputRunning = (): boolean => { + const cmd = commands.get('scene.cancelOutput'); + return !!cmd && commands.enabled(cmd); +}; + +async function lastRecording(): Promise | null> { + if (!recording) return null; + try { + const page = await listMedia({ kind: 'video', sort: 'new', limit: 5 }); + const hit = page.items.find((m) => Date.parse(m.createdAt) >= recording!.at - 2000 && !/-(depth|mask)\.mp4$/i.test(m.name)); + return hit ? { mediaId: hit.id, name: hit.name, createdAt: hit.createdAt } : null; + } catch { + return null; + } +} + +async function recordStatus(ctx: SceneContext): Promise> { + const running = ctx.editor.busy && outputRunning(); + const out: Record = { running, mode: ctx.editor.mode, busy: ctx.editor.busy }; + if (recording) { + out.startedAt = new Date(recording.at).toISOString(); + out.elapsedSec = round((Date.now() - recording.at) / 1000, 1); + out.timelineSec = recording.durationSec; + if (!running) out.result = await lastRecording(); + } + if (!running && recording && !out.result) out.note = 'The last recording did not reach the library: it was stopped, or it failed (the window shows why).'; + return out; +} + +async function saveScene(ctx: SceneContext, name?: string): Promise<{ projectId: string; name: string }> { + const files = filesFor(ctx); + if (files.busy || ctx.editor.busy) throw new ToolError('busy', 'The scene is busy (saving, opening, capturing or recording). Wait with scene_record_status, then call again.'); + const wanted = name?.trim().slice(0, NAME_MAX) || ''; + if (files.id === null) { + const untitled = files.name === DEFAULT_NAME || files.name === t(DEFAULT_NAME); + const chosen = wanted || (untitled ? '' : files.name); + if (!chosen) throw new ToolError('name_required', 'This scene has never been saved, so it needs a name. Call scene_save again with name.'); + const doc = { ...ctx.store.snapshot(), shots: shotIds(ctx) } as unknown as ProjectDoc; + const project = await createProject({ kind: 'scene', name: chosen, doc }); + projectStore.upsert(project); + files.id = project.id; + files.name = project.name || chosen; + } else if (wanted && wanted !== files.name && !(await files.rename(wanted))) { + throw new ToolError('save_failed', 'The scene could not be renamed. The window shows why.'); + } + if (!(await files.save())) throw new ToolError('save_failed', 'The scene could not be saved. The window shows why; call scene_save again once it is fixed.'); + return { projectId: files.id as string, name: files.name }; +} + +async function exportScene(ctx: SceneContext, path: string | null, name?: string): Promise { + const files = filesFor(ctx); + const id = files.id === null || ctx.store.dirty ? (await saveScene(ctx, name)).projectId : files.id; + try { + return (await exportProject(id, path, false)).path; + } catch (err) { + const why = err instanceof ApiError && err.message ? err.message : 'The scene could not be exported.'; + throw new ToolError('export_failed', `${why} Give another path, or call projects_export with id ${id} and overwrite true to replace a file (the owner is asked).`); + } +} + +const SCHEMA = { + units: { position: 'metres, [x, y, z], y is up', rotationInTools: 'degrees, [x, y, z] Euler order XYZ', rotationInDocument: 'radians (project.json and .fcrft store radians; the tools convert)', scale: 'factors', time: 'seconds; frame = round(time * fps)' }, + object: { + fields: { + id: 'string, made by the app', + kind: OBJECT_KINDS, + name: 'string, at most 80 characters, unique in the scene', + parent: 'id of a group, or null for the top level; transforms are relative to the parent', + transform: '{ position: [x,y,z], rotation: [x,y,z], scale: [x,y,z] }', + color: '#rrggbb', + visible: 'boolean', + locked: 'boolean; a locked object only takes name, visible and locked changes', + asset: '{ $media: libraryId } for image, video, model and splat; null otherwise', + shape: `for kind shape: ${SHAPE_KEYS.join(', ')}`, + material: 'for shape and model: { metalness 0..1, roughness 0..1, and optional colorMap, normalMap, roughnessMap { $media: library id }, repeat [x, y] 0.01..100, emissive hex with emissiveStrength 0..20, opacity 0..1 }; tool fields: colorMapId, normalMapId, roughnessMapId (null clears), materialMediaId (a starter material sets all three), tiling, emissive, emissiveStrength, opacity', + light: 'for kind light: { intensity 0..1000, distance 0..10000 metres }', + camera: `for kind camera: { focal ${MIN_FOCAL_MM}..${MAX_FOCAL_MM} mm }; a camera is always top level, at most ${MAX_CAMERAS} per scene, the first one cannot be deleted`, + role: `for kind model: ${MODEL_ROLES.join(', ')}`, + }, + }, + timeline: { + fields: { duration: `seconds, ${MIN_DURATION} to ${MAX_DURATION}`, fps: `whole number 1 to 120, default ${SCENE_FPS}`, tracks: 'one per keyed object: { objectId, keys: [Keyframe] }', strips: 'animation clips on models: { id, objectId, source, name, start, length, loop, fitted, blend }' }, + keyframe: { id: 'string', time: 'seconds', transform: 'the whole transform at that time', ease: 'cubic bezier [x1, y1, x2, y2] from this key to the next' }, + eases: EASE, + rules: [ + 'Between two keys every transform field is interpolated with the first key\'s ease; before the first key and after the last the object holds still.', + 'Two keys of one object closer than 1 ms are one key: setting a key there replaces it.', + 'Keys past the duration are dropped when the timeline gets shorter.', + ], + }, + scene: { fields: { format: 1, objects: '[Object] in outliner order', activeCamera: 'camera id used by stills and recordings', aspect: ASPECTS, skybox: `${SKYBOXES.join(', ')} or pack:`, sun: '{ direction [x,y,z], color, intensity }', prompt: 'text used when generating from the frame', environment: 'a placed world or null', envMap: 'optional saved environment image { image { $media }, name, hdr, intensity 0..10, rotation degrees, background }; .hdr and .exr light correctly, tone-mapped images light approximately; set with scene_update envMapId, envIntensity, envRotation, envBackground', view: 'the editor viewpoint { position, rotation }', timeline: 'Timeline', shots: 'library ids of the shot strip' } }, + outputSizes: OUTPUT_SIZES, + recording: { fps: SCENE_FPS, covers: 'the whole timeline from 0 to duration through the active camera, at the aspect size in outputSizes.video', result: 'a video in the library; scene_record_status gives its mediaId' }, + file: { extension: '.fcrft', layout: 'a zip holding manifest.json ({ format: "fcrft", version, app, appVersion, kind, name, createdAt, updatedAt, coverId, media: [{ id, name, source, hidden }] }), project.json (the scene document above) and media/.' }, + tools: { + read: ['scene_list_objects', 'scene_state', 'scene_timeline_get', 'scene_record_status', 'scene_schema'], + build: ['scene_add', 'scene_add_many', 'scene_update', 'scene_delete', 'scene_select', 'scene_group', 'scene_ungroup', 'scene_camera'], + animate: ['scene_keys_set', 'scene_keys_delete', 'scene_timeline_set', 'scene_mode'], + output: ['scene_capture', 'scene_record_start', 'scene_record_status', 'scene_record_stop'], + files: ['scene_save', 'scene_export', 'scene_open'], + note: 'No scene tool needs a selection, an open panel or a mode: edit through these tools instead of editing exported files.', + }, +}; + +export function registerSceneOutputTools(): void { + defineTools([ + { + name: 'scene_schema', + title: 'Scene and keyframe formats', + description: 'The 3D scene document, object, timeline and keyframe formats, units, limits, the .fcrft file layout and which scene tool does what. Read this instead of the app\'s code.', + inputSchema: obj({}), + annotations: READ_ONLY, + studio: 'scene', + run: async () => { + const { editor } = await sceneHandle(); + return json({ ...SCHEMA, recording: { ...SCHEMA.recording, fps: editor.fps || SCENE_FPS, note: 'the recorder uses the timeline fps' } }); + }, + }, + { + name: 'scene_record_start', + title: 'Start recording the timeline', + description: + 'Record the scene timeline to a video through the active camera, the same as the Record button. Switches to Record mode by itself (the selection is kept). Optionally sets the aspect, the camera and the timeline length first. Returns once the recording has started; follow it with scene_record_status (waitSec) and stop it with scene_record_stop. The finished video lands in the library.', + inputSchema: obj({ + aspect: oneOf(ASPECTS, 'Frame aspect to record at.'), + cameraId: str('Camera to record through; becomes the active camera.'), + durationSec: num('Set the timeline length first (a shorter one drops keys past the end).', { minimum: MIN_DURATION, maximum: MAX_DURATION }), + }), + annotations: ADDS, + studio: 'scene', + run: async (args) => { + const ctx = await sceneHandle(); + const { store, editor, view } = ctx; + if (editor.busy) throw new ToolError('busy', 'A capture or recording is already running. Call scene_record_status, or scene_record_stop to end it.'); + if (typeof args.cameraId === 'string') { + if (store.object(args.cameraId)?.kind !== 'camera') throw new ToolError('invalid_arguments', `"${args.cameraId}" is not a camera. Call scene_list_objects with kind camera.`); + if (store.doc.activeCamera !== args.cameraId) store.setActiveCamera(args.cameraId); + } + if (typeof args.aspect === 'string') store.setAspect(args.aspect as AspectId); + if (typeof args.durationSec === 'number' && args.durationSec !== store.doc.timeline.duration) store.tl.setDuration(args.durationSec); + await switchMode(ctx, 'record'); + const cmd = commands.get('scene.record'); + if (!cmd) throw new ToolError('recorder_unavailable', 'The recorder is not loaded in this window. Call studio_open with studio "scene", then try again.'); + const until = Date.now() + START_WAIT_MS; + while (!commands.enabled(cmd) && Date.now() < until) await sleep(100); + if (!commands.enabled(cmd)) throw new ToolError('recorder_busy', 'The recorder is not ready (another output is running, or the window is still preparing it). Call scene_record_status, then try again.'); + recording = { at: Date.now(), durationSec: store.doc.timeline.duration }; + await commands.run('scene.record'); + while (!editor.busy && Date.now() < until) { + await sleep(100); + if (!editor.busy && commands.enabled(cmd)) break; + } + if (!editor.busy) { + recording = null; + const [w, h] = view.videoSize(); + const support = await findSupport(w, h, editor.fps || SCENE_FPS).catch(() => null); + const why = support && !usable(support) ? unavailableReason(support) : 'The window did not start it; a message there says why.'; + throw new ToolError('record_failed', `The recording did not start. ${why} A still works without an encoder: call scene_capture.`); + } + return json({ started: true, ...(await recordStatus(ctx)) }, 'Recording started.'); + }, + }, + { + name: 'scene_record_status', + title: 'Recording status', + description: `Whether a recording or capture is running, how long it has run and, once it is done, the library id of the video. Give waitSec (up to ${WAIT_MAX_SEC}) to wait for it to finish.`, + inputSchema: obj({ waitSec: num('Wait up to this many seconds for the recording to finish.', { minimum: 0, maximum: WAIT_MAX_SEC }) }), + annotations: READ_ONLY, + studio: 'scene', + run: async (args) => { + const ctx = await sceneHandle(); + const until = Date.now() + (typeof args.waitSec === 'number' ? args.waitSec * 1000 : 0); + while (ctx.editor.busy && Date.now() < until) await sleep(250); + return json(await recordStatus(ctx)); + }, + }, + { + name: 'scene_record_stop', + title: 'Stop the recording', + description: 'Stop the running recording or capture, the same as pressing Escape. What was recorded so far is discarded.', + inputSchema: obj({}), + annotations: CHANGES, + studio: 'scene', + run: async () => { + const ctx = await sceneHandle(); + if (!outputRunning()) throw new ToolError('not_running', 'Nothing is recording. Call scene_record_start to start.'); + await commands.run('scene.cancelOutput'); + const until = Date.now() + STOP_WAIT_MS; + while (ctx.editor.busy && Date.now() < until) await sleep(100); + return json({ stopped: !ctx.editor.busy, ...(ctx.editor.busy ? { note: 'Still stopping. Call scene_record_status with waitSec.' } : {}) }); + }, + }, + { + name: 'scene_save', + title: 'Save the scene', + description: + 'Save the open scene as a project (the same as File, Save). A scene that was never saved needs name; giving name to a saved scene renames it. Give path to also write a .fcrft file there (inside the folders agents may write to). Returns the project id.', + inputSchema: obj({ name: str('Project name.', { maxLength: NAME_MAX }), path: str('Also export a .fcrft file to this full path.') }), + annotations: CHANGES, + studio: 'scene', + run: async (args) => { + const ctx = await sceneHandle(); + const saved = await saveScene(ctx, typeof args.name === 'string' ? args.name : undefined); + const exported = typeof args.path === 'string' ? await exportScene(ctx, args.path) : null; + return json({ ...saved, unsaved: ctx.store.dirty, ...(exported ? { exportedTo: exported } : {}) }, `Saved "${saved.name}".`); + }, + }, + { + name: 'scene_export', + title: 'Export the scene to .fcrft', + description: + 'Write the open scene and its media to a .fcrft file, saving it first when it has changes. Without path it goes beside the saved file, or the app\'s projects folder. A path must be inside the folders agents may write to; an existing file is not replaced (use projects_export with overwrite for that).', + inputSchema: obj({ path: str('Full file path ending in .fcrft.'), name: str('Project name, needed when the scene was never saved.', { maxLength: NAME_MAX }) }), + annotations: ADDS, + studio: 'scene', + run: async (args) => { + const ctx = await sceneHandle(); + const path = await exportScene(ctx, typeof args.path === 'string' ? args.path : null, typeof args.name === 'string' ? args.name : undefined); + return json({ path, projectId: filesFor(ctx).id }, `Exported to ${path}.`); + }, + }, + { + name: 'scene_open', + title: 'Open a scene project', + description: + 'Open a saved scene project by id (projects_list), or import a .fcrft file from a full path and open it, in the Scene studio. When the open scene has unsaved changes, pass saveFirst or discardChanges.', + inputSchema: obj({ + projectId: str('Project id of a scene.'), + path: str('Full path of a .fcrft file to import and open.'), + saveFirst: bool('Save the open scene first.'), + discardChanges: bool('Drop the open scene\'s unsaved changes.'), + }), + annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }, + studio: 'scene', + run: async (args) => { + if ((typeof args.projectId === 'string') === (typeof args.path === 'string')) throw new ToolError('invalid_arguments', 'Give projectId or path, one of them.'); + const ctx = await sceneHandle(); + const files = filesFor(ctx); + let id = typeof args.projectId === 'string' ? args.projectId : ''; + if (typeof args.path === 'string') { + const project = await importProjectPath(args.path); + projectStore.upsert(project); + id = project.id; + } + let kind: string; + try { + kind = (await getProject(id)).kind; + } catch { + throw new ToolError('not_found', `No project with id "${id}". Call projects_list with kind scene.`); + } + if (kind !== 'scene') throw new ToolError('invalid_arguments', `That project is a ${kind}, not a scene. Use studio_open with projectId for other kinds.`); + if (ctx.store.dirty && files.id !== id) { + if (args.saveFirst === true) await saveScene(ctx); + else if (args.discardChanges === true) ctx.store.markSaved(); + else throw new ToolError('unsaved_changes', 'The open scene has unsaved changes. Call scene_open again with saveFirst true (or call scene_save first), or with discardChanges true.'); + } + if (!(await files.openId(id, true))) throw new ToolError('open_failed', 'The scene could not be opened. The window shows why.'); + return json({ opened: id, name: files.name, objects: ctx.store.doc.objects.length }, `Opened "${files.name}".`); + }, + }, + ]); +} diff --git a/frontend/src/automation/tools-scene-material.ts b/frontend/src/automation/tools-scene-material.ts new file mode 100644 index 0000000..1d4abd8 --- /dev/null +++ b/frontend/src/automation/tools-scene-material.ts @@ -0,0 +1,89 @@ +import type { MaterialPatch } from '../engine/scene/material'; +import { MAX_ENV_INTENSITY } from '../engine/scene/env-map'; +import type { SceneContext } from '../ui/scene/context'; +import { ToolError, arr, bool, num, str, type Args } from './tool'; + +const mapArg = (what: string): Record => ({ type: ['string', 'null'], description: `Library image id for the ${what} map (library_search), or null to clear it.` }); + +export const MATERIAL_PROPS: Record> = { + metalness: num('Shape or model material metalness, 0 to 1.', { minimum: 0, maximum: 1 }), + roughness: num('Shape or model material roughness, 0 to 1 (multiplies a roughness map).', { minimum: 0, maximum: 1 }), + colorMapId: mapArg('colour (albedo)'), + normalMapId: mapArg('normal'), + roughnessMapId: mapArg('roughness'), + materialMediaId: str('Library id of a material added from the starter library: sets its colour, normal and roughness maps together.'), + tiling: arr({ type: 'number' }, 'Map repeat [x, y], 0.01 to 100 (default [1, 1]).', { minItems: 2, maxItems: 2 }), + emissive: str('Glow colour as hex.'), + emissiveStrength: num('Glow strength, 0 (off) to 20.', { minimum: 0, maximum: 20 }), + opacity: num('Material opacity, 0 to 1 (default 1).', { minimum: 0, maximum: 1 }), +}; + +export const ENV_MAP_PROPS: Record> = { + envMapId: { type: ['string', 'null'], description: 'Library id of an HDRI (.hdr or .exr lights correctly) or an equirectangular image (tone-mapped, lights approximately) to use as the saved scene environment, or null to remove it.' }, + envIntensity: num(`Environment light strength, 0 to ${MAX_ENV_INTENSITY} (default 1).`, { minimum: 0, maximum: MAX_ENV_INTENSITY }), + envRotation: num('Environment turn in degrees, 0 to 360.', { minimum: -360, maximum: 360 }), + envBackground: bool('Show the environment image as the background (default true); false keeps the skybox and only lights with it.'), +}; + +const mapRef = (v: unknown, key: string): { $media: string } | null | undefined => { + if (v === undefined) return undefined; + if (v === null) return null; + if (typeof v !== 'string' || !v) throw new ToolError('invalid_arguments', `${key} must be a library id or null.`); + return { $media: v }; +}; + +export async function applyEnvMapArgs(ctx: SceneContext, a: Args): Promise { + const env = await import('../ui/scene/materials/env-map'); + let changed = false; + if (a.envMapId === null) changed = ctx.store.setEnvMap(null); + else if (typeof a.envMapId === 'string') { + const { getMedia } = await import('../io/api'); + let m; + try { + m = await getMedia(a.envMapId); + } catch { + throw new ToolError('not_found', `No library item with id "${a.envMapId}". Use library_search for ids.`); + } + const before = JSON.stringify(ctx.store.doc.envMap ?? null); + await env.setSceneEnvMap(ctx, m.id, m.name); + changed = JSON.stringify(ctx.store.doc.envMap ?? null) !== before; + } + const patch: { intensity?: number; rotation?: number; background?: boolean } = {}; + if (typeof a.envIntensity === 'number') patch.intensity = a.envIntensity; + if (typeof a.envRotation === 'number') patch.rotation = a.envRotation; + if (typeof a.envBackground === 'boolean') patch.background = a.envBackground; + if (Object.keys(patch).length) { + if (!ctx.store.doc.envMap) throw new ToolError('invalid_arguments', 'envIntensity, envRotation and envBackground need an environment image: give envMapId first.'); + if (env.patchSceneEnvMap(ctx, patch)) changed = true; + } + return changed; +} + +export async function materialArgs(a: Args): Promise { + const out: MaterialPatch = {}; + if (typeof a.materialMediaId === 'string') { + const { getMedia } = await import('../io/api'); + const { mapsOfMedia } = await import('../ui/scene/materials/use'); + let m; + try { + m = await getMedia(a.materialMediaId); + } catch { + throw new ToolError('not_found', `No library item with id "${a.materialMediaId}". Use library_search for ids.`); + } + Object.assign(out, { colorMap: null, normalMap: null, roughnessMap: null }, mapsOfMedia(m)); + } + for (const [key, role] of [['colorMapId', 'colorMap'], ['normalMapId', 'normalMap'], ['roughnessMapId', 'roughnessMap']] as const) { + const ref = mapRef(a[key], key); + if (ref !== undefined) out[role] = ref; + } + if (typeof a.metalness === 'number') out.metalness = a.metalness; + if (typeof a.roughness === 'number') out.roughness = a.roughness; + if (Array.isArray(a.tiling)) { + if (a.tiling.length !== 2 || a.tiling.some((n) => typeof n !== 'number' || !Number.isFinite(n))) throw new ToolError('invalid_arguments', 'tiling must be two numbers [x, y].'); + out.repeat = [a.tiling[0] as number, a.tiling[1] as number]; + } + if (typeof a.emissive === 'string') out.emissive = a.emissive; + if (typeof a.emissiveStrength === 'number') out.emissiveStrength = a.emissiveStrength; + if (typeof a.opacity === 'number') out.opacity = a.opacity; + return Object.keys(out).length ? out : null; +} diff --git a/frontend/src/automation/tools-scene-time.ts b/frontend/src/automation/tools-scene-time.ts new file mode 100644 index 0000000..917a131 --- /dev/null +++ b/frontend/src/automation/tools-scene-time.ts @@ -0,0 +1,240 @@ +import { easeNameOf } from '../engine/scene/ease'; +import { addKeys, removeKeys, setRate, type KeyRange, type KeySpec } from '../engine/scene/tl-batch'; +import { frameTime, totalFrames } from '../engine/scene/tl-core'; +import { sampleAt } from '../engine/scene/tl-keys'; +import { setDuration } from '../engine/scene/timeline'; +import { EASE, MAX_DURATION, MIN_DURATION, type Bezier, type SceneMode, type Timeline, type Transform } from '../engine/scene/types'; +import type { SceneContext } from '../ui/scene/context'; +import { sceneHandle } from './access'; +import { CHANGES, DESTROYS, READ_ONLY, ToolError, arr, asArgs, bool, defineTools, int, json, num, obj, oneOf, round, str, type Args } from './tool'; +import { readVec, toDegrees, vec } from './tools-scene'; + +const EASES = Object.keys(EASE); +const KEYS_MAX = 5000; + +export async function switchMode(ctx: SceneContext, mode: SceneMode): Promise { + const { store, editor } = ctx; + if (editor.mode === mode) return false; + if (editor.busy) throw new ToolError('busy', 'A capture or recording is running, so the mode cannot change. Wait with scene_record_status (waitSec), or stop it with scene_record_stop.'); + const keep = store.selected; + if (!editor.setMode(mode)) throw new ToolError('not_changed', `The Scene studio could not switch to ${mode === 'record' ? 'Record' : 'Build'} mode.`); + if (keep && store.selected !== keep && store.object(keep)) store.select(keep); + ctx.commands.refresh(); + return true; +} + +const keyRow = (k: { id: string; time: number; transform: Transform; ease: Bezier }): Record => ({ + id: k.id, + time: round(k.time, 4), + position: k.transform.position.map((n) => round(n)), + rotation: toDegrees(k.transform.rotation), + scale: k.transform.scale.map((n) => round(n)), + ease: easeNameOf(k.ease) ?? k.ease, +}); + +function timelineInfo(ctx: SceneContext, a: Args): Record { + const { store, editor } = ctx; + const tl = store.doc.timeline; + const only = typeof a.objectId === 'string' ? a.objectId : null; + const withKeys = a.includeKeys !== false; + return { + durationSec: tl.duration, + fps: tl.fps, + frames: totalFrames(tl), + playheadSec: round(editor.playhead, 4), + playing: editor.playing, + mode: editor.mode, + unsavedTimelineEdits: store.tl.modified, + tracks: tl.tracks + .filter((t) => !only || t.objectId === only) + .map((t) => ({ objectId: t.objectId, name: store.object(t.objectId)?.name ?? null, keyCount: t.keys.length, ...(withKeys ? { keys: t.keys.map(keyRow) } : {}) })), + strips: tl.strips.filter((s) => !only || s.objectId === only).map((s) => ({ id: s.id, objectId: s.objectId, name: s.name, start: s.start, length: s.length, loop: s.loop })), + }; +} + +function readEase(v: unknown, at: string): Bezier | string | undefined { + if (v === undefined) return undefined; + if (typeof v === 'string') { + if (!EASES.includes(v)) throw new ToolError('invalid_arguments', `${at}.ease must be one of ${EASES.join(', ')}, or four numbers [x1, y1, x2, y2].`); + return v; + } + if (Array.isArray(v) && v.length === 4 && v.every((n) => typeof n === 'number' && Number.isFinite(n))) return [v[0], v[1], v[2], v[3]] as Bezier; + throw new ToolError('invalid_arguments', `${at}.ease must be one of ${EASES.join(', ')}, or four numbers [x1, y1, x2, y2].`); +} + +function readTimeOf(a: Args, tl: Timeline, at: string): number { + if (typeof a.time === 'number' && typeof a.frame === 'number') throw new ToolError('invalid_arguments', `${at}: give time or frame, not both.`); + if (typeof a.frame === 'number') return a.frame / (tl.fps || 30); + if (typeof a.time === 'number') return a.time; + throw new ToolError('invalid_arguments', `${at} needs time (seconds) or frame.`); +} + +function commitTimeline(ctx: SceneContext, label: string, next: Timeline): boolean { + const { store } = ctx; + const clean = !store.tl.modified; + store.begin(label); + const changed = store.commitTimeline(label, next); + if (clean) store.saveBaseline(); + store.commit(); + return changed; +} + +const KEY_ITEM = obj( + { + objectId: str('Object id from scene_list_objects. Any object can be keyed, cameras included.'), + time: num('Time in seconds from the start.', { minimum: 0 }), + frame: int('Frame number instead of time.', { minimum: 0 }), + position: vec('[x, y, z] in metres.'), + rotation: vec('[x, y, z] in degrees.'), + scale: vec('[x, y, z] factors.'), + ease: { type: ['string', 'array'], description: `Easing from this key to the next: ${EASES.join(', ')} (default inOut), or a cubic bezier [x1, y1, x2, y2].` }, + }, + ['objectId'], +); + +const RANGE_ITEM = obj( + { + objectId: str('Object id.'), + keyIds: arr({ type: 'string' }, 'Only these key ids (from scene_timeline_get).'), + fromSec: num('Only keys at or after this time.', { minimum: 0 }), + toSec: num('Only keys at or before this time.', { minimum: 0 }), + }, + ['objectId'], +); + +export function registerSceneTimeTools(): void { + defineTools([ + { + name: 'scene_mode', + title: 'Switch Build or Record mode', + description: + 'Switch the Scene studio between Build (edit) and Record (look through the active camera). The selection is kept. No scene tool needs a particular mode: keying works in either, and scene_record_start switches to Record by itself.', + inputSchema: obj({ mode: oneOf(['build', 'record'], 'The mode to switch to.') }, ['mode']), + annotations: CHANGES, + studio: 'scene', + run: async (args) => { + const ctx = await sceneHandle(); + const changed = await switchMode(ctx, args.mode as SceneMode); + return json({ mode: ctx.editor.mode, changed, selected: ctx.store.selected }); + }, + }, + { + name: 'scene_timeline_get', + title: 'Read the scene timeline', + description: + 'Read the animation timeline of the 3D scene: duration, fps, frame count, playhead, mode, and every track with its keys (id, time in seconds, position, rotation in degrees, scale, ease) and animation clips. Filter to one object with objectId.', + inputSchema: obj({ objectId: str('Only this object.'), includeKeys: bool('Include each key (default true); false gives key counts only.') }), + annotations: READ_ONLY, + studio: 'scene', + run: async (args) => json(timelineInfo(await sceneHandle(), args)), + }, + { + name: 'scene_keys_set', + title: 'Set keyframes', + description: + `Set up to ${KEYS_MAX} transform keyframes in one call and one undo step, for any objects and times. Needs no mode, no selection and no open timeline. A key on a frame that already has one replaces it. Fields left out of a key come from the object's animated value at that time before this call (or its current transform when it has no keys). Times snap to whole frames. A key past the end of the timeline is refused unless extendDuration is true (up to ${MAX_DURATION} seconds).`, + inputSchema: obj({ keys: arr(KEY_ITEM, 'The keys to set.', { minItems: 1, maxItems: KEYS_MAX }), extendDuration: bool('Lengthen the timeline to fit the last key.') }, ['keys']), + annotations: CHANGES, + studio: 'scene', + run: async (args) => { + const ctx = await sceneHandle(); + const { store } = ctx; + let tl = store.doc.timeline; + const items = (args.keys as unknown[]).map(asArgs); + const times = items.map((a, i) => readTimeOf(a, tl, `keys[${i}]`)); + const last = Math.max(...times); + if (last > tl.duration + 1e-6) { + if (args.extendDuration !== true) throw new ToolError('past_end', `A key at ${round(last, 3)} s is past the end of the timeline (${tl.duration} s). Call again with extendDuration true, or set durationSec with scene_timeline_set first.`); + if (last > MAX_DURATION) throw new ToolError('past_end', `A key at ${round(last, 3)} s is past the longest timeline (${MAX_DURATION} s).`); + const longer = setDuration(tl, Math.max(MIN_DURATION, last)); + if (!longer.ok) throw new ToolError('invalid_arguments', longer.reason); + tl = longer.timeline; + } + const specs: KeySpec[] = items.map((a, i) => { + const at = `keys[${i}]`; + const o = store.object(String(a.objectId)); + if (!o) throw new ToolError('unknown_object', `${at}: no object with id "${String(a.objectId)}". Call scene_list_objects for the ids.`); + const time = frameTime(tl, times[i]); + const base = sampleAt(store.doc.timeline, o.id, time) ?? o.transform; + const transform: Transform = { + position: readVec(a, 'position') ?? [...base.position], + rotation: readVec(a, 'rotation') ?? [...base.rotation], + scale: o.kind === 'camera' ? [1, 1, 1] : (readVec(a, 'scale') ?? [...base.scale]), + }; + return { objectId: o.id, time, transform, ease: readEase(a.ease, at) }; + }); + const out = addKeys(tl, specs); + if (!out.ok) throw new ToolError('invalid_arguments', out.reason); + commitTimeline(ctx, specs.length === 1 ? 'Add keyframe' : `Add ${specs.length} keyframes`, out.timeline); + return json( + { set: specs.length, replaced: out.replaced, durationSec: store.doc.timeline.duration, keys: specs.map((s, i) => ({ objectId: s.objectId, id: out.ids[i], time: round(s.time, 4) })) }, + `Set ${specs.length} keyframes.`, + ); + }, + }, + { + name: 'scene_keys_delete', + title: 'Delete keyframes', + description: 'Delete keyframes in one undo step: for each object, the listed key ids, the keys between fromSec and toSec, or all of its keys when neither is given.', + inputSchema: obj({ items: arr(RANGE_ITEM, 'Which keys to delete.', { minItems: 1, maxItems: KEYS_MAX }) }, ['items']), + annotations: DESTROYS, + studio: 'scene', + run: async (args) => { + const ctx = await sceneHandle(); + const ranges: KeyRange[] = (args.items as unknown[]).map(asArgs).map((a) => ({ + objectId: String(a.objectId), + ...(Array.isArray(a.keyIds) ? { keyIds: a.keyIds as string[] } : {}), + ...(typeof a.fromSec === 'number' ? { from: a.fromSec } : {}), + ...(typeof a.toSec === 'number' ? { to: a.toSec } : {}), + })); + const out = removeKeys(ctx.store.doc.timeline, ranges); + if (!out.removed.length) throw new ToolError('not_found', 'No keys matched. Call scene_timeline_get for the key ids and times.'); + commitTimeline(ctx, out.removed.length === 1 ? 'Delete keyframe' : `Delete ${out.removed.length} keyframes`, out.timeline); + return json({ deleted: out.removed.length, keyIds: out.removed }); + }, + }, + { + name: 'scene_timeline_set', + title: 'Set timeline length, fps or playhead', + description: `Set the timeline duration (${MIN_DURATION} to ${MAX_DURATION} seconds; a shorter timeline drops the keys past the new end), its frames per second (1 to 120), and/or move the playhead, which poses every keyed object at that time. Playback stops when the playhead moves.`, + inputSchema: obj({ + durationSec: num('Timeline length in seconds.', { minimum: MIN_DURATION, maximum: MAX_DURATION }), + fps: int('Frames per second.', { minimum: 1, maximum: 120 }), + playheadSec: num('Move the playhead to this time in seconds.', { minimum: 0 }), + playheadFrame: int('Move the playhead to this frame instead.', { minimum: 0 }), + }), + annotations: CHANGES, + studio: 'scene', + run: async (args) => { + const ctx = await sceneHandle(); + const { store, editor } = ctx; + const changed: string[] = []; + let tl = store.doc.timeline; + const keysBefore = tl.tracks.reduce((n, t) => n + t.keys.length, 0); + if (typeof args.durationSec === 'number' && args.durationSec !== tl.duration) { + const out = setDuration(tl, args.durationSec); + if (!out.ok) throw new ToolError('invalid_arguments', out.reason); + tl = out.timeline; + changed.push('duration'); + } + if (typeof args.fps === 'number' && args.fps !== tl.fps) { + const out = setRate(tl, args.fps); + if (!out.ok) throw new ToolError('invalid_arguments', 'fps must be a whole number from 1 to 120.'); + tl = out.timeline; + changed.push('fps'); + } + if (tl !== store.doc.timeline) commitTimeline(ctx, 'Set timeline', tl); + if (typeof args.playheadSec === 'number' && typeof args.playheadFrame === 'number') throw new ToolError('invalid_arguments', 'Give playheadSec or playheadFrame, not both.'); + const head = typeof args.playheadFrame === 'number' ? args.playheadFrame / store.doc.timeline.fps : typeof args.playheadSec === 'number' ? args.playheadSec : null; + if (head !== null) { + editor.setPlaying(false); + editor.setPlayhead(head); + changed.push('playhead'); + } + if (!changed.length) throw new ToolError('not_changed', 'Nothing changed: give durationSec, fps, playheadSec or playheadFrame with a new value.'); + const keysAfter = store.doc.timeline.tracks.reduce((n, t) => n + t.keys.length, 0); + return json({ changed, durationSec: store.doc.timeline.duration, fps: store.doc.timeline.fps, playheadSec: round(editor.playhead, 4), ...(keysAfter < keysBefore ? { keysDropped: keysBefore - keysAfter } : {}) }); + }, + }, + ]); +} diff --git a/frontend/src/automation/tools-scene.ts b/frontend/src/automation/tools-scene.ts index 20e2af7..894e9d3 100644 --- a/frontend/src/automation/tools-scene.ts +++ b/frontend/src/automation/tools-scene.ts @@ -4,27 +4,33 @@ import { getMedia } from '../io/api'; import { importBlob } from '../ui/tools/hidden-import'; import { captureFrame, frameName } from '../ui/scene/generate/frame'; import { sceneHandle } from './access'; +import { ENV_MAP_PROPS, MATERIAL_PROPS, applyEnvMapArgs, materialArgs } from './tools-scene-material'; import { ADDS, CHANGES, READ_ONLY, ToolError, arr, bool, defineTools, json, num, obj, oneOf, result, round, str, type Args } from './tool'; const NEEDS_MEDIA: readonly ObjectKind[] = ['image', 'video', 'model', 'splat']; const MAX_IMAGE_EDGE = 1024; -const vec = (description: string): Record => arr({ type: 'number' }, description, { minItems: 3, maxItems: 3 }); +export const vec = (description: string): Record => arr({ type: 'number' }, description, { minItems: 3, maxItems: 3 }); -function readVec(args: Args, key: string): Vec3 | undefined { +const DEG = 180 / Math.PI; + +export const toDegrees = (v: readonly number[]): Vec3 => [round(v[0] * DEG), round(v[1] * DEG), round(v[2] * DEG)]; + +export function readVec(args: Args, key: string): Vec3 | undefined { const v = args[key]; if (v === undefined) return undefined; if (!Array.isArray(v) || v.length !== 3 || v.some((n) => typeof n !== 'number' || !Number.isFinite(n))) throw new ToolError('invalid_arguments', `${key} must be three numbers [x, y, z].`); - return [v[0], v[1], v[2]] as Vec3; + const out = [v[0], v[1], v[2]] as Vec3; + return key === 'rotation' ? [out[0] / DEG, out[1] / DEG, out[2] / DEG] : out; } -function row(o: Readonly): Record { +export function row(o: Readonly): Record { const out: Record = { id: o.id, kind: o.kind, name: o.name, position: o.transform.position.map((n) => round(n)), - rotation: o.transform.rotation.map((n) => round(n)), + rotation: toDegrees(o.transform.rotation), scale: o.transform.scale.map((n) => round(n)), color: o.color, }; @@ -33,6 +39,7 @@ function row(o: Readonly): Record { if (o.locked) out.locked = true; if (o.asset) out.asset = o.asset; if (o.kind === 'shape') out.shape = o.shape; + if (o.material) out.material = o.material; if (o.kind === 'model') out.role = o.role; if (o.kind === 'light' && o.light) out.light = o.light; if (o.kind === 'camera' && o.camera) out.focalMm = o.camera.focal; @@ -79,6 +86,7 @@ export function registerSceneTools(): void { sun: d.sun, prompt: d.prompt, environment: d.environment ? d.environment.name : null, + envMap: d.envMap ?? null, timeline: { durationSec: d.timeline.duration, fps: d.timeline.fps, tracks: d.timeline.tracks.length, strips: d.timeline.strips.length }, unsaved: store.dirty, canUndo: store.canUndo, @@ -90,7 +98,7 @@ export function registerSceneTools(): void { name: 'scene_add', title: 'Add an object to the scene', description: - 'Add an object to the 3D scene: a primitive shape, a point light, water, a group, another camera (up to six), or a library item placed as an image or video plane, a 3D model or a world splat (give mediaId). Units are metres, rotation is degrees. The new object is selected. One undo step.', + 'Add one object to the 3D scene: a primitive shape, a point light, water, a group, another camera (up to six), or a library item placed as an image or video plane, a 3D model or a world splat (give mediaId), with its transform, colour, material and parent in the same call. Units are metres, rotation is degrees. The new object is selected. One undo step. For many objects use scene_add_many.', inputSchema: obj( { kind: oneOf(OBJECT_KINDS, 'What to add.'), @@ -102,6 +110,10 @@ export function registerSceneTools(): void { scale: vec('[x, y, z] factors.'), color: str('Hex colour such as #ffaa00.'), parent: str('Id of a group to put it in.'), + ...MATERIAL_PROPS, + lightIntensity: num('For kind light: intensity (default 1).', { minimum: 0, maximum: 1000 }), + lightDistance: num('For kind light: reach in metres (default 100).', { minimum: 0, maximum: 10000 }), + focalMm: num('For kind camera: focal length in mm, 10 to 200.', { minimum: 10, maximum: 200 }), }, ['kind'], ), @@ -112,8 +124,12 @@ export function registerSceneTools(): void { const kind = args.kind as ObjectKind; const opts: NewObjectOptions = { name: typeof args.name === 'string' ? args.name : undefined, color: typeof args.color === 'string' ? args.color : undefined }; if (kind === 'shape') opts.shape = (args.shape as ShapeKey | undefined) ?? 'cube'; + const material = await materialArgs(args); + if (material) opts.material = material; + if (typeof args.lightIntensity === 'number' || typeof args.lightDistance === 'number') opts.light = { ...(typeof args.lightIntensity === 'number' ? { intensity: args.lightIntensity } : {}), ...(typeof args.lightDistance === 'number' ? { distance: args.lightDistance } : {}) }; + if (typeof args.focalMm === 'number') opts.camera = { focal: args.focalMm }; if (typeof args.parent === 'string') { - if (store.object(args.parent)?.kind !== 'group') throw new ToolError('invalid_arguments', 'parent must be the id of a group in the scene.'); + if (store.object(args.parent)?.kind !== 'group') throw new ToolError('invalid_arguments', 'parent must be the id of a group in the scene. Make one with scene_add kind group or scene_group, and read ids with scene_list_objects.'); opts.parent = args.parent; } const transform: NonNullable = {}; @@ -145,7 +161,7 @@ export function registerSceneTools(): void { name: 'scene_update', title: 'Change an object or the scene setup', description: - 'Change one object (name, colour, visibility, lock, position, rotation in degrees, scale, light intensity, camera focal length in mm) with one undo step, and/or the scene setup (aspect, skybox, sun, prompt, active camera). Only the fields given change. A locked object only accepts name, visible and locked changes.', + 'Change one object (name, colour, visibility, lock, position, rotation in degrees, scale, light intensity, camera focal length in mm, and for shapes and models the material: metalness, roughness, colour, normal and roughness maps from the library, tiling, glow and opacity) with one undo step, and/or the scene setup (aspect, skybox, sun, prompt, active camera, and the saved environment image with its light strength, turn and background setting). Only the fields given change. A locked object only accepts name, visible and locked changes.', inputSchema: obj({ id: str('Object id from scene_state. Leave out to change only the scene setup.'), name: str('New name.', { maxLength: 80 }), @@ -157,6 +173,9 @@ export function registerSceneTools(): void { scale: vec('[x, y, z] factors.'), lightIntensity: num('Point light intensity.', { minimum: 0 }), focalMm: num('Camera focal length in mm, 10 to 200.', { minimum: 10, maximum: 200 }), + ...MATERIAL_PROPS, + ...ENV_MAP_PROPS, + parent: { type: ['string', 'null'], description: 'Id of a group to move the object into, or null for the top level. The object keeps its place in the world.' }, aspect: oneOf(ASPECTS, 'Frame aspect ratio of the scene.'), skybox: str(`Skybox: ${SKYBOXES.join(', ')} or a pack sky id like pack:name.`), sunIntensity: num('Sun intensity.', { minimum: 0 }), @@ -186,6 +205,17 @@ export function registerSceneTools(): void { if (o.kind !== 'camera') throw new ToolError('invalid_arguments', 'focalMm applies to cameras only.'); patch.camera = { focal: args.focalMm }; } + const material = await materialArgs(args); + if (material) { + if (o.kind !== 'shape' && o.kind !== 'model') throw new ToolError('invalid_arguments', 'Material fields apply to shapes and models only.'); + patch.material = material; + } + if (args.parent !== undefined && (args.parent ?? null) !== o.parent) { + const to = typeof args.parent === 'string' ? args.parent : null; + if (to !== null && store.object(to)?.kind !== 'group') throw new ToolError('invalid_arguments', 'parent must be the id of a group, or null. Read ids with scene_list_objects.'); + if (!store.reparent(args.id, to)) throw new ToolError('not_changed', 'The object could not move there (a camera stays at the top level, and a group cannot go inside itself).'); + changed.push('parent'); + } if (Object.keys(patch).length) { if (!store.update(args.id, patch, { label: 'Edit' })) throw new ToolError('not_changed', o.locked ? 'The object is locked, so only name, visible and locked can change.' : 'Nothing changed: the values already match, or they were not valid.'); changed.push('object'); @@ -195,6 +225,7 @@ export function registerSceneTools(): void { if (typeof args.skybox === 'string' && store.setSkybox(args.skybox as (typeof SKYBOXES)[number])) changed.push('skybox'); if ((typeof args.sunIntensity === 'number' || typeof args.sunColor === 'string') && store.setSun({ ...(typeof args.sunIntensity === 'number' ? { intensity: args.sunIntensity } : {}), ...(typeof args.sunColor === 'string' ? { color: args.sunColor } : {}) })) changed.push('sun'); if (typeof args.prompt === 'string' && store.setPrompt(args.prompt)) changed.push('prompt'); + if (await applyEnvMapArgs(await sceneHandle(), args)) changed.push('envMap'); if (typeof args.activeCamera === 'string') { if (!store.setActiveCamera(args.activeCamera)) throw new ToolError('invalid_arguments', 'activeCamera must be the id of a camera that is not already active.'); changed.push('activeCamera'); diff --git a/frontend/src/dock-adapter.ts b/frontend/src/dock-adapter.ts index 124d65f..2630848 100644 --- a/frontend/src/dock-adapter.ts +++ b/frontend/src/dock-adapter.ts @@ -1,9 +1,41 @@ import type { DockAdapter, DockAgentStatus, DockChannel, DockProgram, DockState, DockTerminal, PtyKind } from './dock/adapter'; +import { Emitter } from './engine/emitter'; +import { shortcuts } from './engine/shortcuts'; import { ApiError, request } from './io/api'; import { HEADER, ensureWindowKey, streamTicket, windowKey } from './io/window-key'; import { isMac } from './ui/dom'; import { t } from './ui/i18n'; +export const AGENTS_ID = 'view-agents'; +export interface AgentActivity { running: boolean; requests: number } +const activity = new Emitter<{ change: [] }>(); +const alive = new Set(); +let requests = 0; +let working = 0; + +export const agentActivity = (): AgentActivity => ({ running: alive.size > 0 || working > 0, requests }); +export const onAgentActivity = (fn: () => void): (() => void) => activity.on('change', fn); + +export function setAgentRequests(count: number): void { + const n = Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0; + if (n === requests) return; + requests = n; + activity.emit('change'); +} + +export function setAgentWorking(on: boolean): void { + const was = working > 0; + working = Math.max(0, working + (on ? 1 : -1)); + if (was !== working > 0) activity.emit('change'); +} + +function mark(id: string, on: boolean): void { + if (alive.has(id) === on) return; + if (on) alive.add(id); + else alive.delete(id); + activity.emit('change'); +} + export const DOCK_KEY = 'formcraft.dock'; export const DOCK_SIZES = { minHeight: 140, maxHeightShare: 0.7, defaultHeight: 280, minWidth: 460, maxWidthShare: 0.6, defaultWidth: 460, keepWidth: 440 }; const RIGHT_FROM = 900; @@ -45,16 +77,16 @@ export function reserveDock(none: boolean): void { const text = (v: unknown): string => (typeof v === 'string' ? v : ''); -function socketChannel(socket: WebSocket): DockChannel { +function socketChannel(socket: WebSocket, ended: () => void = () => undefined): DockChannel { let data = (_chunk: string | Uint8Array): void => undefined; let exit = (): void => undefined; let closed = (): void => undefined; socket.binaryType = 'arraybuffer'; socket.addEventListener('message', (msg) => { if (typeof msg.data === 'string') { data(msg.data); return; } - try { if ((JSON.parse(new TextDecoder().decode(msg.data as ArrayBuffer)) as { type?: string }).type === 'exit') exit(); } catch { return; } + try { if ((JSON.parse(new TextDecoder().decode(msg.data as ArrayBuffer)) as { type?: string }).type === 'exit') { ended(); exit(); } } catch { return; } }); - socket.addEventListener('close', () => closed()); + socket.addEventListener('close', () => { ended(); closed(); }); const send = (frame: string): void => { if (socket.readyState === WebSocket.OPEN) socket.send(frame); else if (socket.readyState === WebSocket.CONNECTING) socket.addEventListener('open', () => socket.send(frame), { once: true }); @@ -70,11 +102,20 @@ function socketChannel(socket: WebSocket): DockChannel { } interface EngineTerminal { id: string; title: string; kind?: string; alive?: boolean; tip?: unknown; status?: unknown } -const record = (x: EngineTerminal): DockTerminal => ({ - id: x.id, title: x.title, alive: x.alive !== false, kind: KINDS.find((k) => k === x.kind) ?? 'shell', - ...(text(x.tip) ? { tip: text(x.tip) } : {}), ...(text(x.status) ? { status: text(x.status) } : {}), -}); +const record = (x: EngineTerminal): DockTerminal => { + const out: DockTerminal = { + id: x.id, title: x.title, alive: x.alive !== false, kind: KINDS.find((k) => k === x.kind) ?? 'shell', + ...(text(x.tip) ? { tip: text(x.tip) } : {}), ...(text(x.status) ? { status: text(x.status) } : {}), + }; + mark(out.id, out.alive && out.kind !== 'shell'); + return out; +}; const mod = (e: KeyboardEvent): boolean => (isMac ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey); +const agentsChord = (e: KeyboardEvent): boolean => { + if (!shortcuts.has(AGENTS_ID)) return mod(e) && !e.altKey && !e.shiftKey && e.code === 'Backquote'; + const b = shortcuts.parse(e); + return !!b && shortcuts.bindings(AGENTS_ID).includes(b); +}; const inDock = (e: KeyboardEvent): boolean => e.target instanceof Element && e.target.closest('.ft-dock') !== null; const path = (id: string): string => `/terminal/${encodeURIComponent(id)}`; @@ -93,8 +134,8 @@ export function formcraftDock(host: DockHost): DockAdapter { sizes: DOCK_SIZES, canDockRight: () => window.innerWidth >= RIGHT_FROM, }, - isDockChord: (e) => mod(e) && !e.altKey && !e.shiftKey && e.code === 'Backquote' && !(host.layerOpen() && !inDock(e)), - chordLabel: () => `${isMac ? 'Cmd' : 'Ctrl'}+\``, + isDockChord: (e) => agentsChord(e) && !(host.layerOpen() && !inDock(e)), + chordLabel: () => (shortcuts.has(AGENTS_ID) ? shortcuts.label(AGENTS_ID) : `${isMac ? 'Cmd' : 'Ctrl'}+\``), passKey: (e) => mod(e) && e.shiftKey && !e.altKey && e.code === 'Backquote', tabs: () => ({ builtin: ['shell', 'claude', 'codex', 'cursor', 'antigravity'] }), classes: { iconButton: 'cv-tt-btn', button: 'cv-btn', primaryButton: 'cv-btn-primary', input: 'cv-input', select: 'cv-input', note: 'cv-note' }, @@ -119,7 +160,11 @@ export function formcraftDock(host: DockHost): DockAdapter { }, firstRun: () => host.firstRun(), terminal: { - list: async () => (await call<{ terminals: EngineTerminal[] }>('/terminal')).terminals.map(record), + list: async () => { + const out = (await call<{ terminals: EngineTerminal[] }>('/terminal')).terminals.map(record); + for (const id of Array.from(alive)) if (!out.some((x) => x.id === id)) mark(id, false); + return out; + }, open: async (kind, o) => { const size = { cols: o.cols, rows: o.rows }; if (kind === 'shell') return record(await call('/terminal', 'POST', size)); @@ -129,12 +174,12 @@ export function formcraftDock(host: DockHost): DockAdapter { return record(await call('/agent/claude/open', 'POST', { ...size, ...(prompt ? { prompt } : {}), ...(o.resume ? { resume: o.resume } : {}) })); }, restart: async (id) => { await call(`${path(id)}/restart`, 'POST', {}); }, - close: async (id) => { await call<{ ok: boolean }>(path(id), 'DELETE'); }, + close: async (id) => { await call<{ ok: boolean }>(path(id), 'DELETE'); mark(id, false); }, channel: async (id) => { await ensureWindowKey(); const ticket = await streamTicket(); const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'; - return socketChannel(new WebSocket(`${proto}//${location.host}/api${path(id)}/stream?ticket=${encodeURIComponent(ticket)}`)); + return socketChannel(new WebSocket(`${proto}//${location.host}/api${path(id)}/stream?ticket=${encodeURIComponent(ticket)}`), () => mark(id, false)); }, }, agentStatus: async () => { diff --git a/frontend/src/engine/board/actions.ts b/frontend/src/engine/board/actions.ts index 022a9be..5853e19 100644 --- a/frontend/src/engine/board/actions.ts +++ b/frontend/src/engine/board/actions.ts @@ -84,6 +84,12 @@ export const BOARD_ACTIONS: readonly BoardAction[] = [ act('addNote', 'Add a note', 'Edit', ['Shift+KeyN'], GRID), act('newSection', 'New section', 'Edit', [], GRID), act('useReference', 'Use the selected images as references', 'Edit', ['Shift+KeyR'], SEL), + act('undo', 'Undo', 'Edit', ['Mod+KeyZ'], [...GRID, 'can-undo']), + act('redo', 'Redo', 'Edit', ['Mod+Shift+KeyZ', 'Mod+KeyY'], [...GRID, 'can-redo']), + act('makePrompt', 'Make a prompt from the board', 'Edit', [], ['!viewer']), + act('canvasExport', 'Export the board as a picture', 'Edit', ['Mod+Shift+KeyE'], CANVAS), + act('canvasExport2x', 'Export the board at double size', 'Edit', [], CANVAS), + act('canvasExportSelection', 'Export the selection as a picture', 'Edit', [], [...CANVAS, 'node-selection']), act('canvasSelect', 'Select tool', 'Tools', ['KeyV'], CANVAS), act('canvasLasso', 'Lasso tool', 'Tools', ['KeyL'], CANVAS), act('canvasText', 'Text tool', 'Tools', ['KeyT'], CANVAS), @@ -96,6 +102,23 @@ export const BOARD_ACTIONS: readonly BoardAction[] = [ act('canvasReset', 'Reset zoom and pan', 'View', ['Mod+Digit0'], CANVAS), act('canvasUndo', 'Undo', 'Edit', ['Mod+KeyZ'], [...CANVAS, 'can-undo']), act('canvasRedo', 'Redo', 'Edit', ['Mod+Shift+KeyZ', 'Mod+KeyY'], [...CANVAS, 'can-redo']), + act('canvasAlignLeft', 'Align left edges', 'Arrange', ['Alt+KeyA'], [...CANVAS, 'node-selection']), + act('canvasAlignCentre', 'Align centres', 'Arrange', ['Alt+KeyH'], [...CANVAS, 'node-selection']), + act('canvasAlignRight', 'Align right edges', 'Arrange', ['Alt+KeyD'], [...CANVAS, 'node-selection']), + act('canvasAlignTop', 'Align top edges', 'Arrange', ['Alt+KeyW'], [...CANVAS, 'node-selection']), + act('canvasAlignMiddle', 'Align middles', 'Arrange', ['Alt+KeyV'], [...CANVAS, 'node-selection']), + act('canvasAlignBottom', 'Align bottom edges', 'Arrange', ['Alt+KeyS'], [...CANVAS, 'node-selection']), + act('canvasDistributeH', 'Distribute horizontally', 'Arrange', ['Alt+Shift+KeyH'], [...CANVAS, 'node-selection']), + act('canvasDistributeV', 'Distribute vertically', 'Arrange', ['Alt+Shift+KeyV'], [...CANVAS, 'node-selection']), + act('canvasLock', 'Lock or unlock the selection', 'Arrange', ['Mod+KeyL'], [...CANVAS, 'node-selection']), + act('canvasUnlockAll', 'Unlock everything', 'Arrange', [], CANVAS), + act('canvasConnect', 'Connect with an arrow', 'Arrange', ['Shift+KeyC'], [...CANVAS, 'node-selection']), + act('canvasDuplicate', 'Duplicate', 'Edit', ['Mod+KeyD'], [...CANVAS, 'node-selection'], { blender: ['Shift+KeyD'] }), + act('extractPalette', 'Extract palette', 'Edit', [], ['!viewer']), + act('sendCanvas', 'Send to Canvas', 'Edit', [], ['!viewer']), + act('sendScene', 'Send to Scene', 'Edit', [], ['!viewer']), + act('sendEdit', 'Send to Edit', 'Edit', [], ['!viewer']), + act('exportMedia', 'Export all media to a folder', 'Edit', [], ['!viewer']), ]; const BY_ID = new Map(BOARD_ACTIONS.map((a) => [a.id, a])); diff --git a/frontend/src/engine/board/doc.ts b/frontend/src/engine/board/doc.ts index e2167aa..ee812e3 100644 --- a/frontend/src/engine/board/doc.ts +++ b/frontend/src/engine/board/doc.ts @@ -21,7 +21,7 @@ export const RATING_MAX = 5; export const NAME_MAX = 80; const ITEM_KINDS: readonly ItemKind[] = ['image', 'video', 'note', 'link', 'colour']; -const NODE_KINDS: readonly NodeKind[] = ['image', 'video', 'text', 'group']; +const NODE_KINDS: readonly NodeKind[] = ['image', 'video', 'text', 'group', 'arrow']; const VIEWS: readonly BoardView[] = ['grid', 'canvas']; const DENSITIES: readonly Density[] = ['compact', 'cozy', 'comfortable']; const HEX = /^#[0-9a-fA-F]{6}$/; @@ -133,7 +133,7 @@ function parseNodes(raw: unknown, issues: string[]): BoardNode[] { let id = validId(o.id) ? o.id : newId(); if (seen.has(id)) id = newId(); seen.add(id); - out.push({ + const node: BoardNode = { id, kind, asset, @@ -143,8 +143,20 @@ function parseNodes(raw: unknown, issues: string[]): BoardNode[] { width: Math.max(1, num(o.width, 200)), height: Math.max(1, num(o.height, 200)), rotation: num(o.rotation, 0), - parent: typeof o.parent === 'string' ? o.parent : null, - }); + parent: kind === 'arrow' ? null : typeof o.parent === 'string' ? o.parent : null, + }; + if (o.locked === true) node.locked = true; + if (kind === 'arrow') { + if (!validId(o.from) || !validId(o.to) || o.from === o.to) continue; + node.from = o.from; + node.to = o.to; + } + out.push(node); + } + const ends = new Set(out.filter((n) => n.kind !== 'arrow').map((n) => n.id)); + for (let i = out.length - 1; i >= 0; i--) { + const n = out[i]; + if (n.kind === 'arrow' && !(ends.has(n.from ?? '') && ends.has(n.to ?? ''))) out.splice(i, 1); } const groups = new Set(out.filter((n) => n.kind === 'group').map((n) => n.id)); const byId = new Map(out.map((n) => [n.id, n])); @@ -214,7 +226,8 @@ export function sameNodes(a: readonly BoardNode[], b: readonly BoardNode[]): boo const y = b[i]; if ( x.id !== y.id || x.kind !== y.kind || x.text !== y.text || x.x !== y.x || x.y !== y.y || x.width !== y.width || - x.height !== y.height || x.rotation !== y.rotation || x.parent !== y.parent || (x.asset?.$media ?? null) !== (y.asset?.$media ?? null) + x.height !== y.height || x.rotation !== y.rotation || x.parent !== y.parent || (x.asset?.$media ?? null) !== (y.asset?.$media ?? null) || + !!x.locked !== !!y.locked || x.from !== y.from || x.to !== y.to ) { return false; } diff --git a/frontend/src/engine/board/store.ts b/frontend/src/engine/board/store.ts index 1280d77..581144e 100644 --- a/frontend/src/engine/board/store.ts +++ b/frontend/src/engine/board/store.ts @@ -20,6 +20,10 @@ export type NewItem = Partial & { kind: ItemKind }; const same = (a: ReadonlySet, b: ReadonlySet): boolean => a.size === b.size && Array.from(a).every((x) => b.has(x)); +interface Snap { nodes?: BoardNode[]; items?: Item[]; sections?: Section[] } +type Part = keyof Snap; +const deep = (v: T): T => JSON.parse(JSON.stringify(v)) as T; + export class BoardStore { private doc_: BoardDoc; private index = new Map(); @@ -29,8 +33,8 @@ export class BoardStore { private hay = new WeakMap(); private visible_: Item[] | null = null; private tags_: string[] | null = null; - private past: BoardNode[][] = []; - private future: BoardNode[][] = []; + private past: Snap[] = []; + private future: Snap[] = []; private gesture: BoardNode[] | null = null; private rev_ = 0; private dirty_ = false; @@ -135,6 +139,49 @@ export class BoardStore { } } + private snap(parts: readonly Part[]): Snap { + const s: Snap = {}; + for (const p of parts) (s as Record)[p] = deep(this.doc_[p]); + return s; + } + + private remember(s: Snap): void { + this.past.push(s); + if (this.past.length > BOARD_HISTORY_LIMIT) this.past.splice(0, this.past.length - BOARD_HISTORY_LIMIT); + this.future = []; + this.emitter.emit('history'); + } + + private restore(s: Snap): Snap { + const inverse = this.snap(Object.keys(s) as Part[]); + if (s.nodes) this.doc_.nodes = s.nodes; + if (s.sections) this.doc_.sections = s.sections; + if (s.items) { + for (const i of s.items) { + const now = this.index.get(i.id); + if (now?.asset && !i.asset) { + i.asset = now.asset; + i.aspect = now.aspect; + } + } + this.doc_.items = s.items; + this.reindex(); + const kept = new Set(Array.from(this.selected_).filter((id) => this.index.has(id))); + if (kept.size !== this.selected_.size) { + this.selected_ = kept; + this.emitter.emit('selection'); + } + } + this.touch(); + if (s.nodes) { + this.pruneNodeSelection(); + this.emitter.emit('nodes'); + } + if (s.sections) this.emitter.emit('sections'); + if (s.items || s.sections) this.emitter.emit('items'); + return inverse; + } + markSaved(rev: number): void { if (rev !== this.rev_ || !this.dirty_) return; this.dirty_ = false; @@ -169,6 +216,7 @@ export class BoardStore { addItems(list: readonly NewItem[], silent = false): Item[] { const made = list.map((init) => newItem(init.kind, init)); if (!made.length) return made; + this.remember(this.snap(['items'])); this.doc_.items.push(...made); for (const i of made) this.index.set(i.id, i); this.visible_ = null; @@ -185,11 +233,14 @@ export class BoardStore { updateItem(id: string, patch: Partial>): boolean { const item = this.index.get(id); if (!item) return false; + const before = this.snap(['items']); let changed = false; + let meaningful = false; const set = (k: K, v: Item[K]): void => { if (JSON.stringify(item[k]) !== JSON.stringify(v)) { item[k] = v; changed = true; + if (k !== 'asset' && k !== 'aspect') meaningful = true; } }; if (patch.text !== undefined) set('text', patch.text.slice(0, 20000)); @@ -203,6 +254,7 @@ export class BoardStore { if (patch.aspect !== undefined && patch.aspect > 0 && Number.isFinite(patch.aspect)) set('aspect', Math.min(patch.aspect, 20)); if (patch.tags !== undefined) set('tags', Array.from(new Set(patch.tags.map(cleanTag).filter(Boolean)))); if (!changed) return false; + if (meaningful) this.remember(before); this.hay.delete(item); this.visible_ = null; this.tags_ = null; @@ -214,6 +266,7 @@ export class BoardStore { removeItems(ids: Iterable): number { const gone = new Set(Array.from(ids).filter((id) => this.index.has(id))); if (!gone.size) return 0; + this.remember(this.snap(['items'])); this.doc_.items = this.doc_.items.filter((i) => !gone.has(i.id)); this.reindex(); let sel = false; @@ -226,6 +279,7 @@ export class BoardStore { setRating(ids: Iterable, rating: number): number { const r = clampRating(rating); + const before = this.snap(['items']); let n = 0; let any = false; for (const id of ids) { @@ -238,6 +292,7 @@ export class BoardStore { } } if (any) { + this.remember(before); this.visible_ = null; this.touch(); this.emitter.emit('items'); @@ -260,6 +315,7 @@ export class BoardStore { addSection(name: string = DEFAULT_SECTION): Section { const s: Section = { id: newId(), name: name.trim().slice(0, NAME_MAX) || DEFAULT_SECTION, collapsed: false }; + this.remember(this.snap(['sections'])); this.doc_.sections.push(s); this.touch(); this.emitter.emit('sections'); @@ -271,6 +327,7 @@ export class BoardStore { const s = this.section(id); const next = name.trim().slice(0, NAME_MAX); if (!s || !next || s.name === next) return false; + this.remember(this.snap(['sections'])); s.name = next; this.touch(); this.emitter.emit('sections'); @@ -288,6 +345,7 @@ export class BoardStore { removeSection(id: string): boolean { if (!this.section(id)) return false; + this.remember(this.snap(['sections', 'items'])); this.doc_.sections = this.doc_.sections.filter((s) => s.id !== id); for (const i of this.doc_.items) if (i.section === id) i.section = null; this.visible_ = null; @@ -299,13 +357,17 @@ export class BoardStore { moveToSection(ids: Iterable, section: string | null): number { if (section !== null && !this.section(section)) return 0; + const before = this.snap(['items']); let n = 0; + let moved = false; for (const id of ids) { const item = this.index.get(id); if (!item) continue; n++; + moved = moved || item.section !== section; item.section = section; } + if (moved) this.remember(before); if (n) { this.visible_ = null; this.touch(); @@ -314,6 +376,33 @@ export class BoardStore { return n; } + reorderItems(ids: Iterable, before: string | null, section: string | null): boolean { + if (section !== null && !this.section(section)) return false; + const want = new Set(Array.from(ids).filter((id) => this.index.has(id))); + if (!want.size || (before !== null && want.has(before))) return false; + const snap = this.snap(['items']); + const moving = this.doc_.items.filter((i) => want.has(i.id)); + const rest = this.doc_.items.filter((i) => !want.has(i.id)); + let at = before === null ? -1 : rest.findIndex((i) => i.id === before); + if (at < 0) { + at = rest.length; + for (let k = rest.length - 1; k >= 0; k--) if (rest[k].section === section) { + at = k + 1; + break; + } + } + const next = [...rest.slice(0, at), ...moving, ...rest.slice(at)]; + const changed = next.some((i, k) => i !== this.doc_.items[k]) || moving.some((i) => i.section !== section); + if (!changed) return false; + this.remember(snap); + for (const i of moving) i.section = section; + this.doc_.items = next; + this.visible_ = null; + this.touch(); + this.emitter.emit('items'); + return true; + } + setView(view: BoardView): void { if (this.doc_.view === view) return; this.doc_.view = view; @@ -418,15 +507,10 @@ export class BoardStore { private commitNodes(next: BoardNode[], before: BoardNode[], history: boolean): void { this.doc_.nodes = next; - if (history) { - this.past.push(before); - if (this.past.length > BOARD_HISTORY_LIMIT) this.past.splice(0, this.past.length - BOARD_HISTORY_LIMIT); - this.future = []; - } + if (history) this.remember({ nodes: before }); this.touch(); this.pruneNodeSelection(); this.emitter.emit('nodes'); - if (history) this.emitter.emit('history'); } private pruneNodeSelection(): void { @@ -465,11 +549,8 @@ export class BoardStore { const before = this.gesture; this.gesture = null; if (!before || sameNodes(before, this.doc_.nodes)) return false; - this.past.push(before); - if (this.past.length > BOARD_HISTORY_LIMIT) this.past.splice(0, this.past.length - BOARD_HISTORY_LIMIT); - this.future = []; this.touch(); - this.emitter.emit('history'); + this.remember({ nodes: before }); return true; } @@ -486,11 +567,7 @@ export class BoardStore { this.commitGesture(); const prev = this.past.pop(); if (!prev) return false; - this.future.push(cloneNodes(this.doc_.nodes)); - this.doc_.nodes = prev; - this.touch(); - this.pruneNodeSelection(); - this.emitter.emit('nodes'); + this.future.push(this.restore(prev)); this.emitter.emit('history'); return true; } @@ -498,11 +575,7 @@ export class BoardStore { redo(): boolean { const next = this.future.pop(); if (!next) return false; - this.past.push(cloneNodes(this.doc_.nodes)); - this.doc_.nodes = next; - this.touch(); - this.pruneNodeSelection(); - this.emitter.emit('nodes'); + this.past.push(this.restore(next)); this.emitter.emit('history'); return true; } diff --git a/frontend/src/engine/board/types.ts b/frontend/src/engine/board/types.ts index 3b80fa1..73597a4 100644 --- a/frontend/src/engine/board/types.ts +++ b/frontend/src/engine/board/types.ts @@ -35,7 +35,7 @@ export interface Section { collapsed: boolean; } -export type NodeKind = 'image' | 'video' | 'text' | 'group'; +export type NodeKind = 'image' | 'video' | 'text' | 'group' | 'arrow'; export interface BoardNode { id: string; @@ -48,6 +48,9 @@ export interface BoardNode { height: number; rotation: number; parent: string | null; + locked?: boolean; + from?: string; + to?: string; } export interface Viewport { diff --git a/frontend/src/engine/canvas/actions.ts b/frontend/src/engine/canvas/actions.ts index 15a7441..2737e63 100644 --- a/frontend/src/engine/canvas/actions.ts +++ b/frontend/src/engine/canvas/actions.ts @@ -1,7 +1,7 @@ import type { ShortcutDef } from '../shortcuts'; import type { CanvasTool } from './types'; -export type CanvasGate = 'editor' | 'selection' | 'can-undo' | 'can-redo' | 'mask-model' | 'sized-tool' | 'edit3d' | 'not-busy'; +export type CanvasGate = 'editor' | 'selection' | 'can-undo' | 'can-redo' | 'mask-model' | 'sized-tool' | 'edit3d' | 'not-busy' | 'region' | 'crop'; export type CanvasGateTerm = CanvasGate | `!${CanvasGate}`; export type CanvasGroup = 'Tools' | 'Edit' | 'View'; @@ -25,6 +25,7 @@ export interface CanvasGateFacts { tool: CanvasTool; edit3dOpen: boolean; busy: boolean; + region?: boolean; } export interface CanvasGateSource { @@ -39,6 +40,7 @@ export interface CanvasUiFacts { tool: CanvasTool; edit3dOpen: boolean; busy: boolean; + region?: boolean; } export function canvasFacts(store: CanvasGateSource, ui: CanvasUiFacts): CanvasGateFacts { @@ -63,6 +65,10 @@ function holds(gate: CanvasGate, f: CanvasGateFacts): boolean { return f.edit3dOpen; case 'not-busy': return !f.busy; + case 'region': + return f.region === true; + case 'crop': + return f.tool === 'crop'; } } @@ -91,6 +97,29 @@ export const CANVAS_ACTIONS: readonly CanvasAction[] = [ act('undo', 'Undo', 'Edit', ['Mod+KeyZ'], [...EDIT, 'can-undo']), act('redo', 'Redo', 'Edit', ['Mod+Shift+KeyZ', 'Mod+KeyY'], [...EDIT, 'can-redo']), act('commit3d', 'Commit Edit 3D', 'View', ['Escape'], ['editor', 'edit3d'], { allowWhileTyping: true }), + act('fit', 'Fit canvas to screen', 'View', ['Mod+Digit0', 'Mod+Numpad0'], ['editor']), + act('zoom100', 'Zoom to 100 percent', 'View', ['Mod+Digit1', 'Mod+Numpad1'], ['editor']), + act('exportPng', 'Export as PNG', 'Edit', ['Mod+Shift+KeyE'], EDIT), + act('copyImage', 'Copy canvas image', 'Edit', ['Mod+Shift+KeyC'], EDIT), + act('toolText', 'Text tool', 'Tools', ['KeyT'], EDIT, { tool: 'text' }), + act('toolEyedropper', 'Eyedropper', 'Tools', ['KeyI'], EDIT, { tool: 'eyedropper' }), + act('toolCrop', 'Crop and canvas size', 'Tools', ['KeyC'], EDIT, { tool: 'crop' }), + act('toolMarquee', 'Rectangle selection', 'Tools', ['KeyM'], EDIT, { tool: 'marquee' }), + act('toolLasso', 'Lasso selection', 'Tools', ['KeyL'], EDIT, { tool: 'lasso' }), + act('cropApply', 'Apply crop', 'Edit', ['Enter', 'NumpadEnter'], [...EDIT, 'crop', '!edit3d']), + act('cropCancel', 'Cancel crop', 'Edit', ['Escape'], [...EDIT, 'crop', '!edit3d']), + act('regionFill', 'Fill the selection', 'Edit', ['Alt+Backspace', 'Alt+Delete'], [...EDIT, 'region']), + act('regionClear', 'Clear the selection', 'Edit', ['Shift+Backspace', 'Shift+Delete'], [...EDIT, 'region']), + act('regionInvert', 'Invert the selection', 'Edit', ['Mod+Shift+KeyI'], EDIT), + act('regionMask', 'Selection to mask', 'Edit', ['KeyQ'], [...EDIT, 'region']), + act('regionNone', 'Deselect', 'Edit', ['Mod+KeyD'], [...EDIT, 'region']), + act('group', 'Group', 'Edit', ['Mod+KeyG'], [...EDIT, 'selection']), + act('ungroup', 'Ungroup', 'Edit', ['Mod+Shift+KeyG'], [...EDIT, 'selection']), + act('mergeDown', 'Merge down', 'Edit', ['Mod+KeyE'], [...EDIT, 'selection']), + act('mergeVisible', 'Merge visible', 'Edit', ['Mod+Alt+KeyE'], EDIT), + act('flipH', 'Flip horizontal', 'Edit', ['Shift+KeyH'], [...EDIT, 'selection']), + act('flipV', 'Flip vertical', 'Edit', ['Shift+KeyV'], [...EDIT, 'selection']), + act('toggleRail', 'Show or hide the tool rail', 'View', ['Mod+Backslash'], ['editor']), ]; const BY_ID = new Map(CANVAS_ACTIONS.map((a) => [a.id, a])); @@ -102,6 +131,10 @@ export function canvasActionOpen(action: CanvasAction | string, facts: CanvasGat return !!def && def.gate.every((t) => canvasGateOpen(t, facts)); } +export function canvasExclusive(a: readonly CanvasGateTerm[], b: readonly CanvasGateTerm[]): boolean { + return a.some((x) => b.some((y) => x === `!${y}` || y === `!${x}`)); +} + export function canvasBindings(action: CanvasAction, preset: 'standard' | 'blender'): readonly string[] { return preset === 'blender' && action.blender && action.blender.length ? action.blender : action.keys; } diff --git a/frontend/src/engine/canvas/doc.ts b/frontend/src/engine/canvas/doc.ts index 9a0cc28..b2af7cb 100644 --- a/frontend/src/engine/canvas/doc.ts +++ b/frontend/src/engine/canvas/doc.ts @@ -1,6 +1,6 @@ import { - BLANK_SIZES, CANVAS_FORMAT, SHAPE_COLOUR, - type CanvasAspect, type CanvasBase, type CanvasDoc, type CanvasNode, type CanvasScene, type MaskStroke, type ModelView, type ResultBundle, type ShapeKind, + BLANK_SIZES, BLEND_MODES, CANVAS_FORMAT, FEATHER_MAX, SHAPE_COLOUR, TEXT_FONTS, TEXT_SIZE, + type BlendMode, type CanvasAspect, type CanvasBase, type CanvasDoc, type CanvasFrame, type CanvasNode, type CanvasScene, type MaskStroke, type ModelView, type ResultBundle, type ShapeKind, type TextAlign, } from './types'; import { newId, validId } from '../scene/ids'; @@ -27,7 +27,9 @@ export const ASPECT_SIZES: Readonly): CanvasNode | null { scaleX: scaleOf(raw.scaleX), scaleY: scaleOf(raw.scaleY), locked: raw.locked === true, + ...(raw.hidden === true ? { hidden: true } : {}), + ...(typeof raw.name === 'string' && raw.name.trim() ? { name: raw.name.trim().slice(0, 80) } : {}), + ...(typeof raw.alpha === 'number' && Number.isFinite(raw.alpha) && raw.alpha < 1 ? { alpha: num(raw.alpha, 1, 0, 1) } : {}), + ...(BLEND_MODES.includes(raw.blend as BlendMode) && raw.blend !== 'normal' ? { blend: raw.blend as BlendMode } : {}), + ...(validId(raw.group) ? { group: raw.group } : {}), }; let node: CanvasNode | null = null; if (raw.kind === 'image') { @@ -152,6 +159,27 @@ export function cleanNode(raw: unknown, seen: Set): CanvasNode | null { ...common, kind: 'shape', shape: raw.shape as ShapeKind, width: num(raw.width, 100, 0, MAX_DIM), height: num(raw.height, 100, 0, MAX_DIM), fill: colour(raw.fill, SHAPE_COLOUR), }; + if (raw.shape === 'polygon') { + const points = cleanPoints(raw.points); + if (points.length < 6) node = null; + else { + node.points = points; + const feather = num(raw.feather, 0, 0, FEATHER_MAX); + if (feather > 0) node.feather = feather; + if (raw.invert === true) node.invert = true; + if (raw.erase === true) node.erase = true; + } + } + } + } else if (raw.kind === 'text') { + if (typeof raw.text === 'string') { + const font = TEXT_FONTS.includes(raw.font as string) ? (raw.font as string) : TEXT_FONTS[0]; + node = { + ...common, kind: 'text', text: raw.text.slice(0, MAX_TEXT), font, size: num(raw.size, TEXT_SIZE.initial, TEXT_SIZE.min, TEXT_SIZE.max), + weight: Math.round(num(raw.weight, 400, 100, 900) / 100) * 100, colour: colour(raw.colour, '#000000'), + align: ALIGNS.includes(raw.align as TextAlign) ? (raw.align as TextAlign) : 'left', lineHeight: num(raw.lineHeight, 1.2, 0.5, 4), + width: num(raw.width, 1, 0, MAX_DIM), height: num(raw.height, 1, 0, MAX_DIM), + }; } } else if (raw.kind === 'model') { const model = mediaRef(raw.model); @@ -171,7 +199,24 @@ function cleanMaskStroke(raw: unknown, seen: Set): MaskStroke | null { let id = validId(raw.id) ? raw.id : newId(); while (seen.has(id)) id = newId(); seen.add(id); - return { id, points, size: num(raw.size, 30, 1, 100), mode: raw.mode === 'erase' ? 'erase' : 'add' }; + const out: MaskStroke = { id, points, size: num(raw.size, 30, 1, 100), mode: raw.mode === 'erase' ? 'erase' : 'add' }; + if (raw.fill === true && points.length >= 6) { + out.fill = true; + if (raw.invert === true) out.invert = true; + const feather = num(raw.feather, 0, 0, FEATHER_MAX); + if (feather > 0) out.feather = feather; + } + return out; +} + +function cleanFrame(raw: unknown): CanvasFrame | undefined { + if (!isRecord(raw) || !isRecord(raw.content)) return undefined; + const c = raw.content; + return { + width: dim(raw.width, 1024), + height: dim(raw.height, 1024), + content: { x: num(c.x, 0), y: num(c.y, 0), width: num(c.width, 1, 1, MAX_DIM), height: num(c.height, 1, 1, MAX_DIM) }, + }; } export function cleanScene(raw: unknown): CanvasScene { @@ -194,7 +239,18 @@ export function cleanScene(raw: unknown): CanvasScene { if (s) mask.push(s); } } - return { nodes, mask }; + const frame = cleanFrame(r.frame); + return frame ? { nodes, mask, frame } : { nodes, mask }; +} + +export function sceneSize(base: Readonly | null, aspect: CanvasAspect, scene: Readonly | undefined): { width: number; height: number } { + return scene?.frame ? { width: scene.frame.width, height: scene.frame.height } : canvasSizeOf(base, aspect); +} + +export function sceneContent(base: Readonly | null, aspect: CanvasAspect, scene: Readonly | undefined): { x: number; y: number; width: number; height: number } { + if (scene?.frame) return { ...scene.frame.content }; + const s = canvasSizeOf(base, aspect); + return { x: 0, y: 0, width: s.width, height: s.height }; } function cleanBase(raw: unknown): CanvasBase | null { @@ -238,7 +294,7 @@ function cleanBundle(raw: unknown, seen: Set): ResultBundle | null { } export function sceneIsEmpty(s: Readonly): boolean { - return s.nodes.length === 0 && s.mask.length === 0; + return s.nodes.length === 0 && s.mask.length === 0 && !s.frame; } export function parseCanvas(input: unknown): CanvasDoc { diff --git a/frontend/src/engine/canvas/geometry.ts b/frontend/src/engine/canvas/geometry.ts index 9d8eb98..cdd03eb 100644 --- a/frontend/src/engine/canvas/geometry.ts +++ b/frontend/src/engine/canvas/geometry.ts @@ -134,7 +134,7 @@ export function hitNode(node: Readonly, wx: number, wy: number, tole } export function hitTest(nodes: ReadonlyArray>, wx: number, wy: number, tolerance = 0): Readonly | null { - for (let i = nodes.length - 1; i >= 0; i--) if (hitNode(nodes[i], wx, wy, tolerance)) return nodes[i]; + for (let i = nodes.length - 1; i >= 0; i--) if (!nodes[i].hidden && hitNode(nodes[i], wx, wy, tolerance)) return nodes[i]; return null; } diff --git a/frontend/src/engine/canvas/nodes.ts b/frontend/src/engine/canvas/nodes.ts index 24341b1..97208a4 100644 --- a/frontend/src/engine/canvas/nodes.ts +++ b/frontend/src/engine/canvas/nodes.ts @@ -1,4 +1,4 @@ -import { SHAPE_COLOUR, type ImageNode, type LineNode, type MaskStroke, type ModelNode, type ModelView, type ShapeKind, type ShapeNode } from './types'; +import { SHAPE_COLOUR, type ImageNode, type LineNode, type MaskStroke, type ModelNode, type ModelView, type ShapeKind, type ShapeNode, type TextNode } from './types'; import { DEFAULT_MODEL_VIEW } from './doc'; import { newId } from '../scene/ids'; import type { Rect } from './geometry'; @@ -24,3 +24,27 @@ export function newModelNode(model: string, render: string, rect: Rect, view: Mo export function newMaskStroke(points: number[], size: number, mode: 'add' | 'erase'): MaskStroke { return { id: newId(), points: [...points], size, mode }; } + +export function newTextNode(at: Pick, style: Pick): TextNode { + return { ...common(at), kind: 'text', text: '', ...style, width: 1, height: style.size * style.lineHeight }; +} + +export function newRegionNode(points: readonly number[], style: { fill: string; feather?: number; invert?: boolean; erase?: boolean }): ShapeNode | null { + let x0 = Infinity; + let y0 = Infinity; + let x1 = -Infinity; + let y1 = -Infinity; + for (let i = 0; i + 1 < points.length; i += 2) { + x0 = Math.min(x0, points[i]); + x1 = Math.max(x1, points[i]); + y0 = Math.min(y0, points[i + 1]); + y1 = Math.max(y1, points[i + 1]); + } + if (points.length < 6 || !Number.isFinite(x0)) return null; + const local = points.map((v, i) => (i % 2 ? v - y0 : v - x0)); + const node: ShapeNode = { ...common({ x: x0, y: y0 }), kind: 'shape', shape: 'polygon', width: x1 - x0, height: y1 - y0, fill: style.fill, points: local }; + if (style.feather && style.feather > 0) node.feather = style.feather; + if (style.invert) node.invert = true; + if (style.erase) node.erase = true; + return node; +} diff --git a/frontend/src/engine/canvas/store.ts b/frontend/src/engine/canvas/store.ts index da101e3..acf1c81 100644 --- a/frontend/src/engine/canvas/store.ts +++ b/frontend/src/engine/canvas/store.ts @@ -2,21 +2,23 @@ import { Emitter, type Unsubscribe } from '../emitter'; import { newId } from '../scene/ids'; import { CANVAS_FORMAT, PASTE_OFFSET_PX, - type CanvasAspect, type CanvasBase, type CanvasDoc, type CanvasEvents, type CanvasNode, type CanvasScene, type MaskStroke, type ResultBundle, + type BlendMode, type CanvasAspect, type CanvasBase, type CanvasDoc, type CanvasEvents, type CanvasFrame, type CanvasNode, type CanvasRect, type CanvasScene, type MaskStroke, type ResultBundle, type TextAlign, } from './types'; import { MAX_BUNDLES, MAX_MASK_STROKES, MAX_NODES, MAX_PROMPT, NO_BASE_KEY, - baseKey, blankCanvas, canvasSize, cleanNode, cloneNode, cloneScene, colour, contentSignature, emptyScene, parseCanvas, sceneIsEmpty, serializeCanvas, + baseKey, blankCanvas, cleanNode, sceneContent, sceneSize, cloneNode, cloneScene, colour, contentSignature, emptyScene, parseCanvas, sceneIsEmpty, serializeCanvas, } from './doc'; import { SnapshotHistory } from './history'; import { nodeBounds, rectsIntersect, type Rect } from './geometry'; import { newMaskStroke } from './nodes'; export type NodePatch = Partial<{ - x: number; y: number; rotation: number; scaleX: number; scaleY: number; locked: boolean; width: number; height: number; + x: number; y: number; rotation: number; scaleX: number; scaleY: number; locked: boolean; hidden: boolean; name: string; width: number; height: number; fill: string; colour: string; size: number; opacity: number; points: number[]; asset: { $media: string }; model: { $media: string }; render: { $media: string }; view: { scale: number; yaw: number; pitch: number; fov: number }; + text: string; font: string; weight: number; align: TextAlign; lineHeight: number; + alpha: number; blend: BlendMode; group: string; feather: number; invert: boolean; }>; export type TransformPatch = { id: string } & Partial>; @@ -66,7 +68,22 @@ export class CanvasStore { } get size(): { width: number; height: number } { - return canvasSize(this.doc_); + return sceneSize(this.doc_.base, this.doc_.aspect, this.doc_.scenes[this.baseKey]); + } + + get content(): CanvasRect { + return sceneContent(this.doc_.base, this.doc_.aspect, this.doc_.scenes[this.baseKey]); + } + + get extended(): boolean { + const s = this.size; + const c = this.content; + return c.x > 0 || c.y > 0 || c.x + c.width < s.width || c.y + c.height < s.height; + } + + groupMembers(id: string): string[] { + const g = this.node(id)?.group; + return g ? this.liveScene().nodes.filter((n) => n.group === g).map((n) => n.id) : [id]; } get background(): string { @@ -413,6 +430,21 @@ export class CanvasStore { }); } + moveTo(ids: readonly string[], index: number): boolean { + return this.edit('Reorder layers', (s) => { + const pick = new Set(ids); + const sel = s.nodes.filter((n) => pick.has(n.id)); + if (!sel.length) return false; + const before = s.nodes.map((n) => n.id); + const below = s.nodes.slice(0, Math.max(0, Math.min(s.nodes.length, index))).filter((n) => !pick.has(n.id)); + const above = s.nodes.slice(Math.max(0, Math.min(s.nodes.length, index))).filter((n) => !pick.has(n.id)); + s.nodes = [...below, ...sel, ...above]; + const changed = !sameJson(before, s.nodes.map((n) => n.id)); + if (changed) this.touch(); + return changed; + }); + } + lock(ids: readonly string[] = this.selected_): number { return this.setLocked(ids, true); } @@ -479,12 +511,109 @@ export class CanvasStore { }); } + groupNodes(ids: readonly string[] = this.selected_): string | null { + const gid = newId(); + const done = this.edit('Group', (s) => { + const pick = new Set(ids); + const sel = s.nodes.filter((n) => pick.has(n.id)); + if (sel.length < 2) return false; + const top = s.nodes.findIndex((n) => n.id === sel[sel.length - 1].id); + const below = s.nodes.slice(0, top + 1).filter((n) => !pick.has(n.id)); + const above = s.nodes.slice(top + 1).filter((n) => !pick.has(n.id)); + for (const n of sel) n.group = gid; + s.nodes = [...below, ...sel, ...above]; + this.touch(); + return true; + }); + return done ? gid : null; + } + + ungroup(ids: readonly string[] = this.selected_): number { + return this.edit('Ungroup', (s) => { + const pick = new Set(ids); + const groups = new Set(s.nodes.filter((n) => pick.has(n.id) && n.group).map((n) => n.group)); + let n = 0; + for (const node of s.nodes) { + if (node.group && groups.has(node.group)) { + delete node.group; + n++; + } + } + if (n) this.touch(); + return n; + }); + } + + flip(axis: 'x' | 'y', ids: readonly string[] = this.selected_): number { + const nodes = this.liveScene().nodes.filter((n) => ids.includes(n.id) && !n.locked); + if (!nodes.length) return 0; + let lo = Infinity; + let hi = -Infinity; + for (const n of nodes) { + const b = nodeBounds(n); + lo = Math.min(lo, axis === 'x' ? b.x : b.y); + hi = Math.max(hi, axis === 'x' ? b.x + b.width : b.y + b.height); + } + const mid = lo + hi; + return this.updateNodes( + nodes.map((n) => ({ + id: n.id, + patch: axis === 'x' ? { x: mid - n.x, rotation: -n.rotation, scaleX: -n.scaleX } : { y: mid - n.y, rotation: -n.rotation, scaleY: -n.scaleY }, + })), + axis === 'x' ? 'Flip horizontal' : 'Flip vertical', + ); + } + + replaceNodes(ids: readonly string[], node: CanvasNode, label: string): CanvasNode | null { + const out = this.edit(label, (s) => { + const pick = new Set(ids); + const at = s.nodes.findIndex((n) => pick.has(n.id)); + if (at < 0) return null; + const keep = s.nodes.filter((n) => !pick.has(n.id)); + const seen = new Set(keep.map((n) => n.id)); + const clean = cleanNode(node, seen); + if (!clean) return null; + const index = s.nodes.slice(0, at).filter((n) => !pick.has(n.id)).length; + keep.splice(index, 0, clean); + s.nodes = keep; + this.touch(); + return clean; + }); + if (out) this.setSelection([out.id]); + return out; + } + + setFrame(rect: CanvasRect, label = 'Crop'): boolean { + const w = Math.round(rect.width); + const h = Math.round(rect.height); + if (!this.doc_.base || w < 1 || h < 1 || w > 16384 || h > 16384) return false; + const dx = Math.round(rect.x); + const dy = Math.round(rect.y); + const was = this.content; + const cur = this.size; + if (!dx && !dy && w === cur.width && h === cur.height) return false; + return this.edit(label, (s) => { + for (const n of s.nodes) { + n.x -= dx; + n.y -= dy; + } + for (const m of s.mask) for (let i = 0; i + 1 < m.points.length; i += 2) { + m.points[i] -= dx; + m.points[i + 1] -= dy; + } + const frame: CanvasFrame = { width: w, height: h, content: { x: was.x - dx, y: was.y - dy, width: was.width, height: was.height } }; + s.frame = frame; + this.touch(); + return true; + }); + } + // ---- mask addMaskStroke(stroke: Omit & { id?: string }): MaskStroke | null { return this.edit('Mask', (s) => { if (s.mask.length >= MAX_MASK_STROKES) return null; - const cleaned = parseCanvas({ scenes: { k: { mask: [{ ...newMaskStroke(stroke.points, stroke.size, stroke.mode), ...(stroke.id ? { id: stroke.id } : {}) }] } } }).scenes.k.mask[0]; + const cleaned = parseCanvas({ scenes: { k: { mask: [{ ...newMaskStroke(stroke.points, stroke.size, stroke.mode), fill: stroke.fill, invert: stroke.invert, feather: stroke.feather, ...(stroke.id ? { id: stroke.id } : {}) }] } } }).scenes.k.mask[0]; if (!cleaned) return null; if (s.mask.some((m) => m.id === cleaned.id)) cleaned.id = newId(); s.mask.push(cleaned); @@ -524,6 +653,7 @@ export class CanvasStore { if (sceneIsEmpty(s)) return false; s.nodes = []; s.mask = []; + delete s.frame; this.touch(); return true; }); @@ -667,9 +797,10 @@ export class CanvasStore { if (i < 0) return false; const cur = s.nodes[i]; const merged: Record = { ...cur }; - const allowed = new Set(['x', 'y', 'rotation', 'scaleX', 'scaleY', 'locked']); + const allowed = new Set(['x', 'y', 'rotation', 'scaleX', 'scaleY', 'locked', 'hidden', 'name', 'alpha', 'blend', 'group']); if (cur.kind === 'image') ['width', 'height', 'asset'].forEach((k) => allowed.add(k)); - else if (cur.kind === 'shape') ['width', 'height', 'fill'].forEach((k) => allowed.add(k)); + else if (cur.kind === 'shape') ['width', 'height', 'fill', 'points', 'feather', 'invert'].forEach((k) => allowed.add(k)); + else if (cur.kind === 'text') ['width', 'height', 'text', 'font', 'size', 'weight', 'colour', 'align', 'lineHeight'].forEach((k) => allowed.add(k)); else if (cur.kind === 'line') ['colour', 'size', 'opacity', 'points'].forEach((k) => allowed.add(k)); else ['width', 'height', 'model', 'render', 'view'].forEach((k) => allowed.add(k)); for (const [k, v] of Object.entries(patch)) if (allowed.has(k) && v !== undefined) merged[k] = v; diff --git a/frontend/src/engine/canvas/types.ts b/frontend/src/engine/canvas/types.ts index 1a3840b..3caa035 100644 --- a/frontend/src/engine/canvas/types.ts +++ b/frontend/src/engine/canvas/types.ts @@ -14,9 +14,29 @@ export const BLANK_SIZES: ReadonlyArray = [ [720, 1280], [1080, 1920], ]; -export type CanvasTool = 'select' | 'shape' | 'brush' | 'mask' | 'eraser'; -export type ShapeKind = 'rect' | 'circle' | 'triangle'; +export type CanvasTool = 'select' | 'shape' | 'brush' | 'mask' | 'eraser' | 'text' | 'eyedropper' | 'crop' | 'marquee' | 'lasso'; +export type ShapeKind = 'rect' | 'circle' | 'triangle' | 'polygon'; export type CanvasAspect = '3:2' | '2:3' | '1:1'; +export type BlendMode = 'normal' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten'; +export const BLEND_MODES: readonly BlendMode[] = ['normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten']; +export type TextAlign = 'left' | 'center' | 'right'; +export const TEXT_FONTS: readonly string[] = ['Inter', 'JetBrains Mono']; +export const TEXT_WEIGHTS: Readonly> = { Inter: [400, 500, 600], 'JetBrains Mono': [400, 700] }; +export const TEXT_SIZE = { min: 6, max: 512, initial: 48 } as const; +export const FEATHER_MAX = 200; + +export interface CanvasRect { + x: number; + y: number; + width: number; + height: number; +} + +export interface CanvasFrame { + width: number; + height: number; + content: CanvasRect; +} export type CanvasBase = | { kind: 'media'; $media: string; width: number; height: number } @@ -30,6 +50,11 @@ interface NodeCommon { scaleX: number; scaleY: number; locked: boolean; + hidden?: boolean; + name?: string; + alpha?: number; + blend?: BlendMode; + group?: string; } export interface ImageNode extends NodeCommon { @@ -54,6 +79,23 @@ export interface ShapeNode extends NodeCommon { width: number; height: number; fill: string; + points?: number[]; + feather?: number; + invert?: boolean; + erase?: boolean; +} + +export interface TextNode extends NodeCommon { + kind: 'text'; + text: string; + font: string; + size: number; + weight: number; + colour: string; + align: TextAlign; + lineHeight: number; + width: number; + height: number; } export interface ModelView { @@ -72,18 +114,22 @@ export interface ModelNode extends NodeCommon { height: number; } -export type CanvasNode = ImageNode | LineNode | ShapeNode | ModelNode; +export type CanvasNode = ImageNode | LineNode | ShapeNode | ModelNode | TextNode; export interface MaskStroke { id: string; points: number[]; size: number; mode: 'add' | 'erase'; + fill?: boolean; + invert?: boolean; + feather?: number; } export interface CanvasScene { nodes: CanvasNode[]; mask: MaskStroke[]; + frame?: CanvasFrame; } export interface ResultBundle { diff --git a/frontend/src/engine/edit/actions.ts b/frontend/src/engine/edit/actions.ts index 1270ad7..7f0094c 100644 --- a/frontend/src/engine/edit/actions.ts +++ b/frontend/src/engine/edit/actions.ts @@ -22,29 +22,38 @@ export const EDIT_ACTIONS: readonly EditAction[] = [ act('jumpBack', 'Jump back 5 seconds', 'Navigate', ['Shift+ArrowLeft']), act('seekStart', 'Go to the start', 'Navigate', ['Home', 'Enter']), act('seekEnd', 'Go to the end', 'Navigate', ['End']), - act('split', 'Split at the playhead', 'Edit', ['KeyS']), + act('markIn', 'Set the in point', 'Playback', ['KeyI']), + act('markOut', 'Set the out point', 'Playback', ['KeyO']), + act('clearInOut', 'Clear the in and out points', 'Playback', ['Alt+KeyX']), + act('loop', 'Turn loop playback on or off', 'Playback', ['Shift+KeyL']), + act('split', 'Split at the playhead', 'Edit', ['KeyS', 'Mod+KeyB']), act('splitLeft', 'Split and remove the left part', 'Edit', ['KeyQ']), act('splitRight', 'Split and remove the right part', 'Edit', ['KeyW']), act('delete', 'Delete', 'Edit', ['Backspace', 'Delete']), act('duplicate', 'Duplicate', 'Edit', ['Mod+KeyD']), act('undo', 'Undo', 'Edit', ['Mod+KeyZ']), act('redo', 'Redo', 'Edit', ['Mod+Shift+KeyZ', 'Mod+KeyY']), + act('dissolve', 'Add or remove a cross dissolve at the nearest cut', 'Edit', ['Mod+KeyT']), + act('freeze', 'Freeze the frame at the playhead', 'Edit', ['Shift+KeyF']), + act('reverse', 'Play the selected clips backwards', 'Edit'), + act('lockTrack', 'Lock or unlock the tracks of the selected clips', 'Timeline'), act('extractAudio', 'Extract audio', 'Edit'), act('recoverAudio', 'Recover audio', 'Edit'), act('mute', 'Mute or unmute', 'Edit'), act('hide', 'Hide or show', 'Edit'), + act('cut', 'Cut', 'Clipboard', ['Mod+KeyX']), act('copy', 'Copy', 'Clipboard', ['Mod+KeyC']), act('paste', 'Paste', 'Clipboard', ['Mod+KeyV']), act('selectAll', 'Select all', 'Selection', ['Mod+KeyA']), act('deselect', 'Deselect all', 'Selection'), act('cancel', 'Cancel or clear the selection', 'Selection', ['Escape']), act('snapping', 'Turn snapping on or off', 'Timeline', ['KeyN']), - act('ripple', 'Turn ripple on or off', 'Timeline'), - act('bookmark', 'Add or remove a bookmark', 'Timeline'), - act('zoomIn', 'Zoom in', 'Timeline'), - act('zoomOut', 'Zoom out', 'Timeline'), - act('zoomFit', 'Zoom to fit', 'Timeline'), - act('toggleKey', 'Add or remove a keyframe', 'Keyframes'), + act('ripple', 'Turn ripple on or off', 'Timeline', ['Shift+KeyR']), + act('bookmark', 'Add or remove a bookmark', 'Timeline', ['KeyM']), + act('zoomIn', 'Zoom in', 'Timeline', ['Equal']), + act('zoomOut', 'Zoom out', 'Timeline', ['Minus']), + act('zoomFit', 'Zoom to fit', 'Timeline', ['Shift+KeyZ']), + act('toggleKey', 'Add or remove a keyframe', 'Keyframes', ['Shift+KeyK']), act('graph', 'Open the graph editor', 'Keyframes'), ]; diff --git a/frontend/src/engine/edit/audio/mix.ts b/frontend/src/engine/edit/audio/mix.ts index 642f708..4c4a03d 100644 --- a/frontend/src/engine/edit/audio/mix.ts +++ b/frontend/src/engine/edit/audio/mix.ts @@ -1,6 +1,8 @@ import { evalProp } from '../keyframes'; -import { TICKS_PER_SECOND, type EditDoc, type EditElement, type EditScene, type Tick } from '../types'; -import { timeStretch } from './stretch'; +import { trackAudible } from '../tracks'; +import { shownSpan, soundGain, soundShaped } from '../transitions'; +import { TICKS_PER_SECOND, type EditDoc, type EditElement, type EditScene, type EditTrack, type Tick } from '../types'; +import { needsShaping, shapeClip } from './shape'; export const SLICE_SECONDS = 60; export const OUTPUT_GAIN = 0.98; @@ -64,13 +66,18 @@ export class Limiter { } } -function audible(scene: EditScene): EditElement[] { - const out: EditElement[] = []; +interface Heard { + el: EditElement; + track: EditTrack; +} + +function audible(scene: EditScene): Heard[] { + const out: Heard[] = []; for (const track of scene.tracks) { - if (track.muted) continue; + if (!trackAudible(scene, track)) continue; for (const el of track.elements) { if (el.muted) continue; - if (el.kind === 'audio' || (el.kind === 'video' && el.hasAudio && !el.audioExtracted)) out.push(el); + if (el.kind === 'audio' || (el.kind === 'video' && el.hasAudio && !el.audioExtracted && !el.freeze)) out.push({ el, track }); } } return out; @@ -86,26 +93,34 @@ function offlineCtor(): OfflineCtor { return ctor; } -function gainSamples(el: EditElement & { volumeDb: number }, a: Tick, b: Tick): Float32Array { +export function gainSamples(el: EditElement & { volumeDb: number }, a: Tick, b: Tick, track?: EditTrack): Float32Array { const seconds = (b - a) / TICKS_PER_SECOND; const n = Math.max(2, Math.ceil(seconds * 200) + 1); const values = new Float32Array(n); for (let i = 0; i < n; i++) { const t = a + ((b - a) * i) / (n - 1); - values[i] = dbToGain(evalProp(el, 'volumeDb', t - el.start, el.volumeDb)); + const local = Math.min(el.duration, Math.max(0, t - el.start)); + values[i] = dbToGain(evalProp(el, 'volumeDb', local, el.volumeDb)) * (track ? soundGain(track, el, t) : 1); } return values; } +export function soundWindow(track: EditTrack, el: EditElement & { trimStart: Tick; speed: number }, shaped: boolean): { from: Tick; to: Tick } { + if (shaped) return { from: el.start, to: el.start + el.duration }; + const span = shownSpan(track, el); + return { from: Math.max(span.from, el.start - Math.floor(el.trimStart / (el.speed > 0 ? el.speed : 1))), to: span.to }; +} + interface Prepared { - el: EditElement & { volumeDb: number; speed: number; trimStart: Tick; keepPitch: boolean }; + el: EditElement & { volumeDb: number; speed: number; trimStart: Tick; keepPitch: boolean; reverse?: boolean }; + track: EditTrack; buffer: AudioBuffer; stretched: Float32Array[] | null; } -async function prepare(decode: DecodeFn, cache: Map>, els: EditElement[]): Promise { +async function prepare(decode: DecodeFn, cache: Map>, heard: Heard[]): Promise { const out: Prepared[] = []; - for (const raw of els) { + for (const { el: raw, track } of heard) { if (raw.kind !== 'audio' && raw.kind !== 'video') continue; const el = raw as Prepared['el']; const id = raw.media.$media; @@ -120,16 +135,8 @@ async function prepare(decode: DecodeFn, cache: Map } catch { continue; } - let stretched: Float32Array[] | null = null; - if (el.keepPitch && Math.abs(el.speed - 1) > 1e-4) { - const sr = buffer.sampleRate; - const from = Math.max(0, Math.floor((el.trimStart / TICKS_PER_SECOND) * sr)); - const to = Math.min(buffer.length, Math.ceil(((el.trimStart + el.duration * el.speed) / TICKS_PER_SECOND) * sr)); - const parts: Float32Array[] = []; - for (let c = 0; c < buffer.numberOfChannels; c++) parts.push(buffer.getChannelData(c).subarray(from, Math.max(from, to))); - stretched = timeStretch(parts, sr, el.speed); - } - out.push({ el, buffer, stretched }); + const stretched = needsShaping(el) ? shapeClip(buffer, el) : null; + out.push({ el, track, buffer, stretched }); } return out; } @@ -138,9 +145,10 @@ async function renderSlice(items: Prepared[], s0: number, samples: number, sr: n const Ctor = offlineCtor(); const ctx = new Ctor(nch, samples, sr); const s1 = s0 + (samples / sr) * TICKS_PER_SECOND; - for (const { el, buffer, stretched } of items) { - const a = Math.max(el.start, s0); - const b = Math.min(el.start + el.duration, s1); + for (const { el, track, buffer, stretched } of items) { + const win = soundWindow(track, el, !!stretched); + const a = Math.max(win.from, s0); + const b = Math.min(win.to, s1); if (!(b > a)) continue; const when = (a - s0) / TICKS_PER_SECOND; const node = ctx.createBufferSource(); @@ -161,8 +169,8 @@ async function renderSlice(items: Prepared[], s0: number, samples: number, sr: n const offset = Math.max(0, (el.trimStart + (a - el.start) * el.speed) / TICKS_PER_SECOND); node.start(when, offset, ((b - a) / TICKS_PER_SECOND) * el.speed); } - const animated = el.anim?.volumeDb?.keys.length; - if (animated) gain.gain.setValueCurveAtTime(gainSamples(el, a, b), when, (b - a) / TICKS_PER_SECOND); + const animated = el.anim?.volumeDb?.keys.length || soundShaped(track, el); + if (animated) gain.gain.setValueCurveAtTime(gainSamples(el, a, b, track), when, (b - a) / TICKS_PER_SECOND); else gain.gain.value = dbToGain(el.volumeDb); node.connect(gain); gain.connect(ctx.destination); @@ -179,7 +187,10 @@ export async function* mixAudioSlices(doc: EditDoc, scene: EditScene, decode: De const nch = opts.channels ?? 2; const total = Math.max(0, Math.floor(((opts.to - opts.from) / TICKS_PER_SECOND) * sr)); const step = SLICE_SECONDS * sr; - const els = audible(scene).filter((e) => e.start < opts.to && e.start + e.duration > opts.from); + const els = audible(scene).filter(({ el, track }) => { + const s = shownSpan(track, el); + return s.from < opts.to && s.to > opts.from; + }); const cache = new Map>(); const items = els.length ? await prepare(decode, cache, els) : []; const limiter = new Limiter(sr); diff --git a/frontend/src/engine/edit/audio/shape.ts b/frontend/src/engine/edit/audio/shape.ts new file mode 100644 index 0000000..a83e1db --- /dev/null +++ b/frontend/src/engine/edit/audio/shape.ts @@ -0,0 +1,50 @@ +import { TICKS_PER_SECOND, type Tick } from '../types'; +import { timeStretch } from './stretch'; + +export interface ShapeSource { + sampleRate: number; + length: number; + numberOfChannels: number; + getChannelData(channel: number): Float32Array; +} + +export interface ShapeClip { + trimStart: Tick; + duration: Tick; + speed: number; + keepPitch: boolean; + reverse?: boolean; +} + +export const needsShaping = (el: ShapeClip): boolean => !!el.reverse || (el.keepPitch && Math.abs(el.speed - 1) > 1e-4); + +export const shapeKey = (id: string, el: ShapeClip): string => `${id}|${el.trimStart}|${el.duration}|${el.speed}|${el.keepPitch ? 1 : 0}|${el.reverse ? 1 : 0}`; + +function resample(c: Float32Array, rate: number): Float32Array { + const n = Math.max(1, Math.round(c.length / rate)); + const out = new Float32Array(n); + for (let i = 0; i < n; i++) { + const x = i * rate; + const j = Math.floor(x); + const f = x - j; + const a = c[Math.min(c.length - 1, j)] ?? 0; + const b = c[Math.min(c.length - 1, j + 1)] ?? 0; + out[i] = a + (b - a) * f; + } + return out; +} + +export function shapeClip(src: ShapeSource, el: ShapeClip): Float32Array[] { + const sr = src.sampleRate; + const from = Math.max(0, Math.floor((el.trimStart / TICKS_PER_SECOND) * sr)); + const to = Math.min(src.length, Math.ceil(((el.trimStart + el.duration * el.speed) / TICKS_PER_SECOND) * sr)); + let parts: Float32Array[] = []; + for (let c = 0; c < src.numberOfChannels; c++) { + const raw = src.getChannelData(c).subarray(from, Math.max(from, to)); + parts.push(el.reverse ? raw.slice().reverse() : raw); + } + if (Math.abs(el.speed - 1) <= 1e-4) return parts.map((p) => (el.reverse ? p : p.slice())); + if (el.keepPitch) return timeStretch(parts, sr, el.speed); + parts = parts.map((p) => resample(p, el.speed)); + return parts; +} diff --git a/frontend/src/engine/edit/doc.ts b/frontend/src/engine/edit/doc.ts index 314536a..22e01d8 100644 --- a/frontend/src/engine/edit/doc.ts +++ b/frontend/src/engine/edit/doc.ts @@ -2,7 +2,7 @@ import { newId, validId } from '../scene/ids'; import { defaultGraphic, defaultMask, defaultText, defaultTransform, DEFAULT_CLIP_TICKS } from './elements'; import { clampSpeed } from './speed'; import { DEFAULT_FPS, normaliseFps } from './time'; -import { makeTrack, trackAccepts } from './tracks'; +import { makeTrack, trackAccepts, TRACK_H_MAX, TRACK_H_MIN } from './tracks'; import { EDIT_DOC_VERSION, type AnimCurve, @@ -190,7 +190,10 @@ function normElement(raw: unknown, ids: Ids): EditElement | null { effects: normEffects(raw.effects, ids), mask: normMask(raw.mask), }; - const size = { width: intOr(raw.width, 1, 1), height: intOr(raw.height, 1, 1) }; + if (isNum(raw.fadeIn) && raw.fadeIn > 0) base.fadeIn = Math.round(raw.fadeIn); + if (isNum(raw.fadeOut) && raw.fadeOut > 0) base.fadeOut = Math.round(raw.fadeOut); + if (isNum(raw.dissolveIn) && raw.dissolveIn > 0) base.dissolveIn = Math.round(raw.dissolveIn); + const size ={ width: intOr(raw.width, 1, 1), height: intOr(raw.height, 1, 1) }; switch (kind) { case 'video': case 'audio': { @@ -205,6 +208,7 @@ function normElement(raw: unknown, ids: Ids): EditElement | null { keepPitch: boolOr(raw.keepPitch, true), volumeDb: numOr(raw.volumeDb, 0, -100, 20), ...size, + ...(raw.reverse === true ? { reverse: true } : {}), }; if (kind === 'audio') { fields.width = intOr(raw.width, 0); @@ -212,7 +216,7 @@ function normElement(raw: unknown, ids: Ids): EditElement | null { const extractedFrom = typeof raw.extractedFrom === 'string' && raw.extractedFrom ? raw.extractedFrom : undefined; return { ...base, kind, ...fields, ...(extractedFrom ? { extractedFrom } : {}) }; } - return { ...base, kind, ...fields, hasAudio: boolOr(raw.hasAudio, true), audioExtracted: boolOr(raw.audioExtracted, false) }; + return { ...base, kind, ...fields, hasAudio: boolOr(raw.hasAudio, true), audioExtracted: boolOr(raw.audioExtracted, false), ...(raw.freeze === true ? { freeze: true } : {}) }; } case 'image': { const media = mediaRef(raw.media); @@ -249,6 +253,9 @@ function normTrack(raw: unknown, ids: Ids): EditTrack | null { hidden: boolOr(raw.hidden, false), elements: [], }; + if (raw.locked === true) track.locked = true; + if (raw.solo === true) track.solo = true; + if (isNum(raw.height)) track.height = Math.round(Math.min(TRACK_H_MAX, Math.max(TRACK_H_MIN, raw.height))); const list = Array.isArray(raw.elements) ? raw.elements : []; for (const r of list) { const el = normElement(r, ids); @@ -366,6 +373,8 @@ export function normaliseEdit(input: unknown): LoadResult { snapping: boolOr(v.snapping, true), ripple: boolOr(v.ripple, false), playhead: intOr(v.playhead, 0), + markIn: isNum(v.markIn) && v.markIn >= 0 ? Math.round(v.markIn) : undefined, + markOut: isNum(v.markOut) && v.markOut >= 0 ? Math.round(v.markOut) : undefined, }, }; return { doc }; diff --git a/frontend/src/engine/edit/index.ts b/frontend/src/engine/edit/index.ts index 48b92a6..addcece 100644 --- a/frontend/src/engine/edit/index.ts +++ b/frontend/src/engine/edit/index.ts @@ -14,5 +14,7 @@ export * from './snap'; export * from './ops-clip'; export * from './ops-key'; export * from './ops-misc'; +export * from './ops-time'; +export * from './transitions'; export * from './actions'; export * from './store'; diff --git a/frontend/src/engine/edit/keyframes.ts b/frontend/src/engine/edit/keyframes.ts index f61b157..c42b703 100644 --- a/frontend/src/engine/edit/keyframes.ts +++ b/frontend/src/engine/edit/keyframes.ts @@ -134,6 +134,13 @@ export function resolveTransform(el: EditElement, localTick: Tick): Transform2D }; } +export function fadeFactor(el: EditElement, localTick: Tick): number { + let f = 1; + if (el.fadeIn && el.fadeIn > 0) f *= Math.min(1, Math.max(0, localTick / el.fadeIn)); + if (el.fadeOut && el.fadeOut > 0) f *= Math.min(1, Math.max(0, (el.duration - localTick) / el.fadeOut)); + return f; +} + export function resolveColour(el: EditElement, prop: string, localTick: Tick, fallback: string): string { if (!isColourProp(prop)) return fallback; const base = readBase(el, prop); diff --git a/frontend/src/engine/edit/ops-clip.ts b/frontend/src/engine/edit/ops-clip.ts index 1622818..fc5177c 100644 --- a/frontend/src/engine/edit/ops-clip.ts +++ b/frontend/src/engine/edit/ops-clip.ts @@ -158,8 +158,8 @@ function cut(el: EditElement, at: Tick, fps: Rational): { left: EditElement; rig const clone = cloneElement(el); let right: EditElement = { ...clone, start: at, duration: rightDur, anim: cropAnim(clone.anim, leftDur, el.duration) }; if (hasSource(left) && hasSource(right)) { - left = withTrimEnd(left, leftDur); - right = withTrimStart(right, rightDur); + left = left.reverse ? withTrimStart(left, leftDur) : withTrimEnd(left, leftDur); + right = right.reverse ? withTrimEnd(right, rightDur) : withTrimStart(right, rightDur); } return { left, right }; } @@ -173,7 +173,8 @@ export function splitOp(doc: EditDoc, ids: readonly string[] | null, at: Tick, s let touched = false; const elements: EditElement[] = []; for (const e of tr.elements) { - const pieces = !set || set.has(e.id) ? cut(e, t, doc.fps) : null; + const cutPieces = !set || set.has(e.id) ? cut(e, t, doc.fps) : null; + const pieces = cutPieces && { left: { ...cutPieces.left, fadeOut: undefined }, right: { ...cutPieces.right, fadeIn: undefined, dissolveIn: undefined } }; if (!pieces) { elements.push(e); continue; @@ -196,22 +197,24 @@ export function trimOp(doc: EditDoc, ids: readonly string[], edge: 'start' | 'en const min = minDuration(doc.fps); let lo = -Infinity; let hi = Infinity; + const ripple = doc.view.ripple; const targets: { el: EditElement; trackId: string }[] = []; for (const tr of scene.tracks) { for (const e of tr.elements) { if (!set.has(e.id)) continue; targets.push({ el: e, trackId: tr.id }); const others = tr.elements.filter((o) => o !== e); + const rev = hasSource(e) && !!e.reverse; if (edge === 'start') { const prevEnd = others.filter((o) => elementEnd(o) <= e.start).reduce((m, o) => Math.max(m, elementEnd(o)), 0); - let l = -(e.start - prevEnd); - if (hasSource(e)) l = Math.max(l, -Math.floor(e.trimStart / e.speed)); + let l = ripple ? -Infinity : -(e.start - prevEnd); + if (hasSource(e)) l = Math.max(l, -Math.floor((rev ? e.trimEnd : e.trimStart) / e.speed)); lo = Math.max(lo, l); hi = Math.min(hi, e.duration - min); } else { const nextStart = others.filter((o) => o.start >= elementEnd(e)).reduce((m, o) => Math.min(m, o.start), Infinity); - let h = nextStart - elementEnd(e); - if (hasSource(e)) h = Math.min(h, Math.floor((e.sourceDuration - e.trimStart) / e.speed) - e.duration); + let h = ripple ? Infinity : nextStart - elementEnd(e); + if (hasSource(e)) h = Math.min(h, rev ? Math.floor(e.trimStart / e.speed) : Math.floor((e.sourceDuration - e.trimStart) / e.speed) - e.duration); lo = Math.max(lo, -(e.duration - min)); hi = Math.min(hi, h); } @@ -225,19 +228,20 @@ export function trimOp(doc: EditDoc, ids: readonly string[], edge: 'start' | 'en const shift = edge === 'start' ? delta : 0; const duration = edge === 'start' ? el.duration - delta : el.duration + delta; const anim = Object.keys(el.anim).length ? cropAnim(el.anim, shift, shift + duration) : el.anim; - let next: EditElement = { ...el, start: edge === 'start' ? el.start + delta : el.start, duration, anim }; - if (hasSource(next)) next = edge === 'start' ? withTrimStart(next, duration) : withTrimEnd(next, duration); + let next: EditElement = { ...el, start: edge === 'start' && !ripple ? el.start + delta : el.start, duration, anim }; + if (hasSource(next)) next = (edge === 'start') !== !!next.reverse ? withTrimStart(next, duration) : withTrimEnd(next, duration); replaced.set(el.id, next); } let tracks = scene.tracks.map((tr) => (tr.elements.some((e) => replaced.has(e.id)) ? { ...tr, elements: tr.elements.map((e) => replaced.get(e.id) ?? e) } : tr)); - if (doc.view.ripple && edge === 'end' && delta < 0) { + if (ripple) { + const move = edge === 'start' ? -delta : delta; const ends = new Map(targets.map((x) => [x.el.id, elementEnd(x.el)])); tracks = tracks.map((tr) => { const mine = tr.elements.filter((e) => ends.has(e.id)).sort((a, b) => (ends.get(b.id) ?? 0) - (ends.get(a.id) ?? 0)); let elements = tr.elements; for (const m of mine) { const end = ends.get(m.id) ?? 0; - elements = elements.map((e) => (e.id !== m.id && e.start >= end ? { ...e, start: e.start + delta } : e)); + elements = elements.map((e) => (e.id !== m.id && e.start >= end ? { ...e, start: e.start + move } : e)); } return elements === tr.elements ? tr : { ...tr, elements }; }); @@ -280,7 +284,7 @@ export function moveOp(doc: EditDoc, ids: readonly string[], dt: Tick, dTrack: n const moved = u.els.map((e) => ({ ...e, start: e.start + delta })); const raw = u.idx + shift; const target = raw >= 0 && raw < origIds.length ? work.find((t) => t.id === origIds[raw]) : undefined; - const ok = target && moved.every((e) => trackAccepts(target, e) && !overlaps(target, e.start, elementEnd(e))); + const ok = target && !target.locked && moved.every((e) => trackAccepts(target, e) && !overlaps(target, e.start, elementEnd(e))); if (ok && target) { const lead = moved.reduce((m, e) => Math.min(m, e.start), Infinity); const pinned = @@ -431,7 +435,7 @@ export function recoverAudioOp(doc: EditDoc, id: string, force = false): EditDoc export function speedOp(doc: EditDoc, id: string, speed: number, keepPitch?: boolean): EditDoc { const scene = currentScene(doc); const found = findElement(scene, id); - if (!found || !hasSource(found.el)) return doc; + if (!found || !hasSource(found.el) || (found.el.kind === 'video' && found.el.freeze)) return doc; const el: SourceElement = found.el; const s = clampSpeed(speed); const duration = frameDuration(Math.round(sourceSpan(el) / s), doc.fps); diff --git a/frontend/src/engine/edit/ops-misc.ts b/frontend/src/engine/edit/ops-misc.ts index 548e282..9ed7a4f 100644 --- a/frontend/src/engine/edit/ops-misc.ts +++ b/frontend/src/engine/edit/ops-misc.ts @@ -208,6 +208,8 @@ export function setViewOp(doc: EditDoc, patch: Partial): EditDoc { snapping: typeof patch.snapping === 'boolean' ? patch.snapping : v.snapping, ripple: typeof patch.ripple === 'boolean' ? patch.ripple : v.ripple, playhead: patch.playhead === undefined || !Number.isFinite(patch.playhead) ? v.playhead : Math.max(0, Math.round(patch.playhead)), + markIn: patch.markIn === undefined || !Number.isFinite(patch.markIn) ? v.markIn : patch.markIn < 0 ? undefined : Math.round(patch.markIn), + markOut: patch.markOut === undefined || !Number.isFinite(patch.markOut) ? v.markOut : patch.markOut < 0 ? undefined : Math.round(patch.markOut), }; const same = (Object.keys(next) as (keyof TimelineView)[]).every((k) => next[k] === v[k]); return same ? doc : { ...doc, view: next }; diff --git a/frontend/src/engine/edit/ops-time.ts b/frontend/src/engine/edit/ops-time.ts new file mode 100644 index 0000000..3b96359 --- /dev/null +++ b/frontend/src/engine/edit/ops-time.ts @@ -0,0 +1,155 @@ +import { cloneElement } from './elements'; +import { cropAnim } from './curves'; +import { sourceTickOf } from './render/frame'; +import { hasSource, minDuration, SPEED_MIN, withTrimEnd, withTrimStart } from './speed'; +import { snapToFrame } from './time'; +import { currentScene, elementEnd, findElement, sortedElements, withScene } from './tracks'; +import type { EditDoc, EditElement, Tick, VideoElement } from './types'; + +export function slipRange(el: EditElement): { lo: Tick; hi: Tick } | null { + if (!hasSource(el) || (el.kind === 'video' && el.freeze)) return null; + const sign = el.reverse ? -1 : 1; + const a = -el.trimStart * sign; + const b = el.trimEnd * sign; + return { lo: Math.min(a, b), hi: Math.max(a, b) }; +} + +export function slipOp(doc: EditDoc, id: string, dSource: Tick): EditDoc { + const scene = currentScene(doc); + const found = findElement(scene, id); + if (!found || found.track.locked) return doc; + const el = found.el; + const range = slipRange(el); + if (!range || !hasSource(el)) return doc; + const d = Math.round(Math.min(range.hi, Math.max(range.lo, dSource))); + if (d === 0) return doc; + const move = el.reverse ? -d : d; + const next = { ...el, trimStart: el.trimStart + move, trimEnd: el.trimEnd - move } as EditElement; + const tracks = scene.tracks.map((t) => (t === found.track ? { ...t, elements: t.elements.map((e) => (e.id === id ? next : e)) } : t)); + return withScene(doc, { ...scene, tracks }); +} + +function resizeEnd(el: EditElement, duration: Tick): EditElement { + const anim = Object.keys(el.anim).length ? cropAnim(el.anim, 0, duration) : el.anim; + let next: EditElement = { ...el, duration, anim }; + if (hasSource(next)) next = next.reverse ? withTrimStart(next, duration) : withTrimEnd(next, duration); + return next; +} + +function resizeStart(el: EditElement, delta: Tick): EditElement { + const duration = el.duration - delta; + const anim = Object.keys(el.anim).length ? cropAnim(el.anim, delta, delta + duration) : el.anim; + let next: EditElement = { ...el, start: el.start + delta, duration, anim }; + if (hasSource(next)) next = next.reverse ? withTrimEnd(next, duration) : withTrimStart(next, duration); + return next; +} + +const growLimit = (el: EditElement, atEnd: boolean): Tick => { + if (!hasSource(el)) return Infinity; + const room = atEnd !== !!el.reverse ? el.trimEnd : el.trimStart; + return Math.floor(room / el.speed); +}; + +export function slideRange(doc: EditDoc, id: string): { lo: Tick; hi: Tick } | null { + const scene = currentScene(doc); + const found = findElement(scene, id); + if (!found || found.track.locked) return null; + const { el, track } = found; + const min = minDuration(doc.fps); + const others = track.elements.filter((o) => o.id !== id); + const prev = others.find((o) => elementEnd(o) === el.start); + const next = others.find((o) => o.start === elementEnd(el)); + const prevEnd = others.filter((o) => elementEnd(o) <= el.start).reduce((m, o) => Math.max(m, elementEnd(o)), 0); + const nextStart = others.filter((o) => o.start >= elementEnd(el)).reduce((m, o) => Math.min(m, o.start), Infinity); + let lo = -el.start; + let hi = Infinity; + if (prev) { + lo = Math.max(lo, -(prev.duration - min)); + hi = Math.min(hi, growLimit(prev, true)); + } else lo = Math.max(lo, prevEnd - el.start); + if (next) { + hi = Math.min(hi, next.duration - min); + lo = Math.max(lo, -growLimit(next, false)); + } else hi = Math.min(hi, nextStart - elementEnd(el)); + if (track.group === 'main' && el.start === 0) return null; + return lo <= hi ? { lo, hi } : null; +} + +export function slideOp(doc: EditDoc, id: string, dt: Tick): EditDoc { + const range = slideRange(doc, id); + if (!range) return doc; + const delta = Math.min(range.hi, Math.max(range.lo, snapToFrame(dt, doc.fps))); + if (delta === 0) return doc; + const scene = currentScene(doc); + const found = findElement(scene, id); + if (!found) return doc; + const { el, track } = found; + const end = elementEnd(el); + const elements = track.elements.map((o) => { + if (o.id === id) return { ...o, start: o.start + delta }; + if (elementEnd(o) === el.start) return resizeEnd(o, o.duration + delta); + if (o.start === end) return resizeStart(o, delta); + return o; + }); + const tracks = scene.tracks.map((t) => (t === track ? { ...t, elements: sortedElements(elements) } : t)); + return withScene(doc, { ...scene, tracks }); +} + +export function freezeFrameOp(doc: EditDoc, id: string, at: Tick, hold: Tick): { doc: EditDoc; id: string | null } { + const scene = currentScene(doc); + const found = findElement(scene, id); + if (!found || found.track.locked || found.el.kind !== 'video' || found.el.freeze) return { doc, id: null }; + const el = found.el; + const t = Math.min(elementEnd(el) - minDuration(doc.fps), Math.max(el.start, snapToFrame(at, doc.fps))); + if (t < el.start) return { doc, id: null }; + const len = Math.max(minDuration(doc.fps), snapToFrame(hold, doc.fps)); + const frame = sourceTickOf(el, t); + const still = cloneElement(el) as VideoElement; + let freeze: VideoElement = { + ...still, + name: `${el.name} (freeze)`, + start: t, + duration: len, + trimStart: frame, + speed: SPEED_MIN, + reverse: undefined, + freeze: true, + hasAudio: false, + anim: {}, + fadeIn: undefined, + fadeOut: undefined, + dissolveIn: undefined, + }; + freeze = withTrimEnd(freeze, len) as VideoElement; + const elements: EditElement[] = []; + for (const o of found.track.elements) { + if (o.id !== id) { + elements.push(o.start >= t ? { ...o, start: o.start + len } : o); + continue; + } + if (t === el.start) { + elements.push({ ...o, start: o.start + len, dissolveIn: undefined }); + continue; + } + const left = resizeEnd({ ...o, fadeOut: undefined }, t - o.start); + const rightRaw = cloneElement(o); + const right = resizeStart({ ...rightRaw, fadeIn: undefined, dissolveIn: undefined }, t - o.start); + elements.push(left, { ...right, start: right.start + len }); + } + elements.push(freeze); + const tracks = scene.tracks.map((tr) => (tr === found.track ? { ...tr, elements: sortedElements(elements) } : tr)); + return { doc: withScene(doc, { ...scene, tracks }), id: freeze.id }; +} + +export function reverseOp(doc: EditDoc, ids: readonly string[]): EditDoc { + const scene = currentScene(doc); + const set = new Set(ids); + const pool = scene.tracks.filter((t) => !t.locked).flatMap((t) => t.elements.filter((e) => set.has(e.id) && hasSource(e) && !(e.kind === 'video' && e.freeze))); + if (!pool.length) return doc; + const value = pool.some((e) => hasSource(e) && !e.reverse); + const tracks = scene.tracks.map((t) => { + if (t.locked || !t.elements.some((e) => pool.includes(e))) return t; + return { ...t, elements: t.elements.map((e) => (pool.includes(e) ? ({ ...e, reverse: value || undefined } as EditElement) : e)) }; + }); + return withScene(doc, { ...scene, tracks }); +} diff --git a/frontend/src/engine/edit/placement.ts b/frontend/src/engine/edit/placement.ts index 01b8c0d..ea9084d 100644 --- a/frontend/src/engine/edit/placement.ts +++ b/frontend/src/engine/edit/placement.ts @@ -15,14 +15,14 @@ export interface Placed { } function fits(track: EditTrack, el: EditElement): boolean { - return trackAccepts(track, el) && !overlaps(track, el.start, el.start + el.duration); + return !track.locked && trackAccepts(track, el) && !overlaps(track, el.start, el.start + el.duration); } function nearestFirst(scene: EditScene, el: EditElement): EditTrack[] { const main = mainIndex(scene); return scene.tracks .map((t, i) => ({ t, i })) - .filter(({ t }) => trackAccepts(t, el)) + .filter(({ t }) => !t.locked && trackAccepts(t, el)) .sort((a, b) => Math.abs(a.i - main) - Math.abs(b.i - main) || a.i - b.i) .map(({ t }) => t); } diff --git a/frontend/src/engine/edit/render/frame.ts b/frontend/src/engine/edit/render/frame.ts index 12e16d8..33dd2bb 100644 --- a/frontend/src/engine/edit/render/frame.ts +++ b/frontend/src/engine/edit/render/frame.ts @@ -1,10 +1,11 @@ import { applyEffects, surfaceScale } from '../effects'; import { paintGradient } from '../gradient'; -import { evalProp, readBase, resolveColour, resolveTransform, type LinearRgba } from '../keyframes'; +import { evalProp, fadeFactor, readBase, resolveColour, resolveTransform, type LinearRgba } from '../keyframes'; import { applyMask, composeMat, maskActive, type Mat } from '../masks'; import { clearSurface, type Ctx2D } from '../raster'; import { stickerRaster } from '../stickers'; import { sortedElements } from '../tracks'; +import { dissolveIn, shownAt } from '../transitions'; import type { EditDoc, EditElement, @@ -40,7 +41,10 @@ export function activeAt(el: EditElement, t: Tick): boolean { export function sourceTickOf(el: EditElement, t: Tick): Tick { if (el.kind !== 'video') return 0; - return el.trimStart + Math.round((t - el.start) * el.speed); + if (el.freeze) return el.trimStart; + const span = Math.round((t - el.start) * el.speed); + const raw = el.reverse ? el.trimStart + Math.max(0, Math.round(el.duration * el.speed) - 1) - span : el.trimStart + span; + return Math.min(Math.max(0, el.sourceDuration - 1), Math.max(0, raw)); } export function sourceSize(src: CanvasImageSource): { w: number; h: number } | null { @@ -78,7 +82,7 @@ export function placeElement(doc: EditDoc, el: EditElement, t: Tick, surfaceW: n } if (!(bw > 0 && bh > 0)) return null; const m = composeMat(surfaceW / 2 + tr.x * k, surfaceH / 2 + tr.y * k, tr.rotation, tr.scale * tr.scaleX, tr.scale * tr.scaleY); - return { bw, bh, m, opacity: tr.opacity }; + return { bw, bh, m, opacity: tr.opacity * fadeFactor(el, local) }; } function animatedText(el: EditElement & { kind: 'text' }, local: Tick): TextStyle { @@ -139,14 +143,14 @@ interface Drawable { place: Placement; } -function drawableFor(doc: EditDoc, el: EditElement, t: Tick, surface: RenderSurface, media: MediaResolver): Drawable | null { +function drawableFor(doc: EditDoc, el: EditElement, t: Tick, surface: RenderSurface, media: MediaResolver, srcT: Tick): Drawable | null { const local = t - el.start; const sw = surface.width; const sh = surface.height; switch (el.kind) { case 'video': case 'image': { - const src = el.kind === 'video' ? media.videoFrame(el.media.$media, sourceTickOf(el, t)) : media.image(el.media.$media); + const src = el.kind === 'video' ? media.videoFrame(el.media.$media, sourceTickOf(el, srcT)) : media.image(el.media.$media); if (!src) return null; const natural = sourceSize(src) ?? (el.width > 0 && el.height > 0 ? { w: el.width, h: el.height } : null); const place = placeElement(doc, el, t, sw, sh, natural); @@ -195,14 +199,15 @@ function resetState(ctx: Ctx2D): void { ctx.filter = 'none'; } -function drawElement(doc: EditDoc, el: EditElement, t: Tick, surface: RenderSurface, media: MediaResolver): void { +function drawElement(doc: EditDoc, el: EditElement, at: Tick, surface: RenderSurface, media: MediaResolver, mix = 1): void { const ctx = surface.ctx; + const t = Math.min(el.start + el.duration - 1, Math.max(el.start, at)); const local = t - el.start; const scale = surfaceScale(surface.width, surface.height); if (el.kind === 'effect') { const fx = animatedEffects(el, local); if (!fx.some((f) => f.enabled)) return; - const opacity = resolveTransform(el, local).opacity; + const opacity = resolveTransform(el, local).opacity * fadeFactor(el, local) * mix; if (opacity <= 0) return; const layer = surface.scratch(surface.width, surface.height); clearSurface(layer); @@ -215,8 +220,9 @@ function drawElement(doc: EditDoc, el: EditElement, t: Tick, surface: RenderSurf return; } if (el.kind === 'audio') return; - const d = drawableFor(doc, el, t, surface, media); + const d = drawableFor(doc, el, t, surface, media, at); if (!d) return; + if (mix !== 1) d.place.opacity *= mix; const fx = animatedEffects(el, local).filter((f) => f.enabled); const maskable = el.kind === 'video' || el.kind === 'image' || el.kind === 'graphic'; const mask = maskable && maskActive(el.mask) ? el.mask : null; @@ -288,8 +294,8 @@ export function renderFrame(doc: EditDoc, scene: EditScene, t: Tick, surface: Re for (const track of order) { if (track.hidden) continue; for (const el of sortedElements(track.elements)) { - if (el.hidden || !activeAt(el, t)) continue; - drawElement(doc, el, t, surface, media); + if (el.hidden || !shownAt(track, el, t)) continue; + drawElement(doc, el, t, surface, media, dissolveIn(track, el, t)); } } resetState(ctx); diff --git a/frontend/src/engine/edit/tracks.ts b/frontend/src/engine/edit/tracks.ts index af3b8f4..b3143ba 100644 --- a/frontend/src/engine/edit/tracks.ts +++ b/frontend/src/engine/edit/tracks.ts @@ -3,6 +3,17 @@ import type { EditDoc, EditElement, EditScene, EditTrack, ElementKind, Tick, Tra export const elementEnd = (el: EditElement): Tick => el.start + el.duration; +export const TRACK_H_MIN = 25; +export const TRACK_H_MAX = 200; + +export const soundTrack = (t: EditTrack): boolean => t.type === 'audio' || t.type === 'video'; + +export function trackAudible(scene: EditScene, track: EditTrack): boolean { + if (track.muted) return false; + const solo = scene.tracks.some((t) => t.solo && soundTrack(t)); + return !solo || !!track.solo; +} + export function trackTypeOf(kind: ElementKind): TrackType { switch (kind) { case 'video': diff --git a/frontend/src/engine/edit/transitions.ts b/frontend/src/engine/edit/transitions.ts new file mode 100644 index 0000000..b9c795d --- /dev/null +++ b/frontend/src/engine/edit/transitions.ts @@ -0,0 +1,147 @@ +import { needsShaping } from './audio/shape'; +import { fadeFactor } from './keyframes'; +import { hasSource, minDuration } from './speed'; +import { snapToFrame } from './time'; +import { currentScene, elementEnd, findElement, patchById, withScene } from './tracks'; +import { TICKS_PER_SECOND, type EditDoc, type EditElement, type EditScene, type EditTrack, type Tick } from './types'; + +export const DISSOLVE_DEFAULT: Tick = TICKS_PER_SECOND; + +export interface Span { + from: Tick; + to: Tick; +} + +export function previousAt(track: EditTrack, el: EditElement): EditElement | null { + return track.elements.find((o) => o.id !== el.id && elementEnd(o) === el.start) ?? null; +} + +export function nextAt(track: EditTrack, el: EditElement): EditElement | null { + const end = elementEnd(el); + return track.elements.find((o) => o.id !== el.id && o.start === end) ?? null; +} + +export function dissolveRoom(a: EditElement, b: EditElement): Tick { + return Math.min(a.duration, b.duration); +} + +export function dissolveLength(track: EditTrack, el: EditElement): Tick { + if (!el.dissolveIn || el.dissolveIn <= 0) return 0; + const prev = previousAt(track, el); + return prev ? Math.min(el.dissolveIn, dissolveRoom(prev, el)) : 0; +} + +export function shownSpan(track: EditTrack, el: EditElement): Span { + const lead = dissolveLength(track, el); + const next = nextAt(track, el); + const tail = next ? dissolveLength(track, next) : 0; + return { from: el.start - Math.floor(lead / 2), to: elementEnd(el) + Math.ceil(tail / 2) }; +} + +export function shownAt(track: EditTrack, el: EditElement, t: Tick): boolean { + if (el.start <= t && t < elementEnd(el)) return true; + if (!el.dissolveIn && !track.elements.some((o) => o.dissolveIn && o.start === elementEnd(el))) return false; + const s = shownSpan(track, el); + return s.from <= t && t < s.to; +} + +const progress = (t: Tick, cut: Tick, len: Tick): number => Math.min(1, Math.max(0, (t - (cut - Math.floor(len / 2))) / len)); + +export function dissolveIn(track: EditTrack, el: EditElement, t: Tick): number { + const len = dissolveLength(track, el); + return len > 0 ? progress(t, el.start, len) : 1; +} + +function room(el: EditElement, tail: boolean): Tick { + if (!hasSource(el) || needsShaping(el)) return 0; + return Math.floor((tail ? el.trimEnd : el.trimStart) / (el.speed > 0 ? el.speed : 1)); +} + +const ramp = (t: Tick, a: Tick, b: Tick): number => (b > a ? Math.min(1, Math.max(0, (t - a) / (b - a))) : t >= b ? 1 : 0); + +export function crossGain(track: EditTrack, el: EditElement, t: Tick): number { + let g = 1; + const len = dissolveLength(track, el); + if (len > 0) { + const half = Math.floor(len / 2); + g *= Math.sin((ramp(t, el.start - Math.min(half, room(el, false)), el.start + (len - half)) * Math.PI) / 2); + } + const next = nextAt(track, el); + const out = next ? dissolveLength(track, next) : 0; + if (out > 0) { + const half = Math.floor(out / 2); + const end = elementEnd(el); + g *= Math.cos((ramp(t, end - half, end + Math.min(out - half, room(el, true))) * Math.PI) / 2); + } + return g; +} + +export function soundGain(track: EditTrack, el: EditElement, t: Tick): number { + const local = Math.min(el.duration, Math.max(0, t - el.start)); + return fadeFactor(el, local) * crossGain(track, el, t); +} + +export function soundShaped(track: EditTrack, el: EditElement): boolean { + if (el.fadeIn || el.fadeOut || dissolveLength(track, el) > 0) return true; + const next = nextAt(track, el); + return !!next && dissolveLength(track, next) > 0; +} + +export interface Cut { + a: EditElement; + b: EditElement; + at: Tick; +} + +export function cutsOf(track: EditTrack): Cut[] { + const out: Cut[] = []; + for (const b of track.elements) { + const a = previousAt(track, b); + if (a) out.push({ a, b, at: b.start }); + } + return out; +} + +function partner(scene: EditScene, videoId: string): { el: EditElement; track: EditTrack } | null { + for (const t of scene.tracks) for (const e of t.elements) if (e.kind === 'audio' && e.extractedFrom === videoId) return { el: e, track: t }; + return null; +} + +export function setDissolveOp(doc: EditDoc, id: string, length: Tick | undefined): EditDoc { + const scene = currentScene(doc); + const found = findElement(scene, id); + if (!found) return doc; + const prev = previousAt(found.track, found.el); + if (length !== undefined && !prev) return doc; + const value = + length === undefined || !prev + ? undefined + : Math.max(minDuration(doc.fps) * 2, Math.min(dissolveRoom(prev, found.el), snapToFrame(length, doc.fps))); + if (value === found.el.dissolveIn) return doc; + let next = patchById(scene, id, (e) => ({ ...e, dissolveIn: value })); + if (found.el.kind === 'video' && prev && prev.kind === 'video') { + const pa = partner(next, prev.id); + const pb = partner(next, found.el.id); + if (pa && pb && pa.track.id === pb.track.id && elementEnd(pa.el) === pb.el.start) { + next = patchById(next, pb.el.id, (e) => ({ ...e, dissolveIn: value === undefined ? undefined : Math.min(value, dissolveRoom(pa.el, pb.el)) })); + } + } + return withScene(doc, next); +} + +export function cutNear(scene: EditScene, at: Tick, prefer: readonly string[], within: Tick): Cut | null { + const picked = new Set(prefer); + let best: Cut | null = null; + let bestD = Infinity; + for (const track of scene.tracks) { + if (track.locked) continue; + for (const c of cutsOf(track)) { + const d = Math.abs(c.at - at) - (picked.has(c.a.id) || picked.has(c.b.id) ? within : 0); + if (d < bestD && Math.abs(c.at - at) <= within) { + bestD = d; + best = c; + } + } + } + return best; +} diff --git a/frontend/src/engine/edit/types.ts b/frontend/src/engine/edit/types.ts index 5be3538..b897443 100644 --- a/frontend/src/engine/edit/types.ts +++ b/frontend/src/engine/edit/types.ts @@ -159,6 +159,9 @@ export interface ElementBase { anim: AnimMap; effects: EffectInstance[]; mask: Mask | null; + fadeIn?: Tick; + fadeOut?: Tick; + dissolveIn?: Tick; } export interface MediaElementFields { @@ -171,12 +174,14 @@ export interface MediaElementFields { volumeDb: number; width: number; height: number; + reverse?: boolean; } export interface VideoElement extends ElementBase, MediaElementFields { kind: 'video'; hasAudio: boolean; audioExtracted: boolean; + freeze?: boolean; } export interface ImageElement extends ElementBase { @@ -230,6 +235,9 @@ export interface EditTrack { name: string; muted: boolean; hidden: boolean; + locked?: boolean; + solo?: boolean; + height?: number; elements: EditElement[]; } @@ -283,6 +291,8 @@ export interface TimelineView { snapping: boolean; ripple: boolean; playhead: Tick; + markIn?: Tick; + markOut?: Tick; } export interface EditDoc { diff --git a/frontend/src/engine/local-jobs.ts b/frontend/src/engine/local-jobs.ts new file mode 100644 index 0000000..ab955df --- /dev/null +++ b/frontend/src/engine/local-jobs.ts @@ -0,0 +1,105 @@ +import { Emitter } from './emitter'; +import type { Job, JobStatus } from '../io/api'; + +/** Work that runs in this window rather than in the engine (Scene Record, Edit export). It is shaped like an engine + * job so the Jobs popover can list both together. Ids start with "local:" and never reach the engine. */ +export interface LocalHandle { + progress(value: number | null): void; + done(results?: readonly string[]): void; + fail(message: string): void; + cancelled(): void; +} + +type Events = { change: [] }; + +const KEEP_FINISHED = 20; + +class LocalJobs { + private readonly byId = new Map(); + private readonly stops = new Map void>(); + private readonly emitter = new Emitter(); + private seq = 0; + + start(kind: string, title: string, cancel: () => void): LocalHandle { + const now = new Date().toISOString(); + const id = `local:${Date.now().toString(36)}-${++this.seq}`; + this.byId.set(id, { + id, kind, title, status: 'running', provider: null, model: null, progress: null, attempts: 1, + createdAt: now, updatedAt: now, startedAt: now, finishedAt: null, timeoutAt: null, error: null, + subscriberId: null, payload: { local: true }, results: [], dismissed: false, + }); + this.stops.set(id, cancel); + this.emit(); + const end = (status: JobStatus, extra: Partial = {}): void => { + const job = this.byId.get(id); + if (!job || job.status !== 'running') return; + const at = new Date().toISOString(); + this.byId.set(id, { ...job, ...extra, status, updatedAt: at, finishedAt: at }); + this.stops.delete(id); + this.trim(); + this.emit(); + }; + return { + progress: (value) => { + const job = this.byId.get(id); + if (!job || job.status !== 'running') return; + const v = typeof value === 'number' && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : null; + if (v !== null && job.progress !== null && Math.abs(v - job.progress) < 0.005) return; + this.byId.set(id, { ...job, progress: v, updatedAt: new Date().toISOString() }); + this.emit(); + }, + done: (results = []) => end('succeeded', { progress: 1, results: [...results] }), + fail: (message) => end('failed', { error: { category: 'local', message } }), + cancelled: () => end('cancelled'), + }; + } + + list(): Job[] { + return Array.from(this.byId.values()); + } + + get(id: string): Job | undefined { + return this.byId.get(id); + } + + cancel(id: string): boolean { + const stop = this.stops.get(id); + if (!stop) return false; + stop(); + return true; + } + + dismiss(id: string): void { + const job = this.byId.get(id); + if (!job || job.status === 'running') return; + this.byId.delete(id); + this.emit(); + } + + dismissFinished(): number { + let n = 0; + for (const [id, job] of this.byId) { + if (job.status === 'running') continue; + this.byId.delete(id); + n++; + } + if (n) this.emit(); + return n; + } + + on(fn: () => void): () => void { + return this.emitter.on('change', fn); + } + + private trim(): void { + const done = this.list().filter((j) => j.status !== 'running'); + for (const j of done.slice(0, Math.max(0, done.length - KEEP_FINISHED))) this.byId.delete(j.id); + } + + private emit(): void { + this.emitter.emit('change'); + } +} + +export const localJobs = new LocalJobs(); +export const isLocalJob = (id: string): boolean => id.startsWith('local:'); diff --git a/frontend/src/engine/scene/actions.ts b/frontend/src/engine/scene/actions.ts index 681a6a8..8abf961 100644 --- a/frontend/src/engine/scene/actions.ts +++ b/frontend/src/engine/scene/actions.ts @@ -114,7 +114,7 @@ export const SCENE_ACTIONS: readonly SceneAction[] = [ act('camLeft', 'Fly left', 'Camera', ['KeyA'], BUILD, { blender: ['Numpad4', 'Digit4'], held: true }), act('camRight', 'Fly right', 'Camera', ['KeyD'], BUILD, { blender: ['Numpad6', 'Digit6'], held: true }), act('camUp', 'Fly up', 'Camera', ['KeyE'], BUILD, { blender: ['Numpad9', 'Digit9'], held: true }), - act('camDown', 'Fly down', 'Camera', ['KeyQ'], BUILD, { blender: ['Numpad3', 'Digit3'], held: true }), + act('camDown', 'Fly down', 'Camera', ['KeyQ'], BUILD, { blender: ['Digit3'], held: true }), act('lookUp', 'Look up', 'Camera', ['ArrowUp'], [...BUILD, '!timeline-open'], { held: true }), act('lookDown', 'Look down', 'Camera', ['ArrowDown'], [...BUILD, '!timeline-open'], { held: true }), act('lookLeft', 'Look left', 'Camera', ['ArrowLeft'], [...BUILD, '!timeline-open'], { held: true }), @@ -139,9 +139,38 @@ export const SCENE_ACTIONS: readonly SceneAction[] = [ act('togglePlay', 'Play or pause', 'View', ['Space'], ['playback-context', 'not-busy']), act('stats', 'Performance overlay', 'View', ['Backquote'], []), act('grid', 'Show or hide the grid', 'View', ['KeyH'], ['not-busy']), + act('frameAll', 'Frame everything', 'View', ['KeyF'], [...BUILD, '!selection', '!camera-view']), + act('viewHome', 'Reset the view', 'View', ['Home'], [...BUILD, '!playback-context', '!camera-view']), + act('viewFront', 'Front view', 'View', ['Numpad1', 'Digit1'], [...BUILD, '!camera-view'], { blender: ['Numpad1'] }), + act('viewBack', 'Back view', 'View', ['Mod+Numpad1', 'Alt+Digit1'], [...BUILD, '!camera-view'], { blender: ['Mod+Numpad1'] }), + act('viewRight', 'Right view', 'View', ['Numpad3', 'Digit3'], [...BUILD, '!camera-view'], { blender: ['Numpad3'] }), + act('viewLeft', 'Left view', 'View', ['Mod+Numpad3', 'Alt+Digit3'], [...BUILD, '!camera-view'], { blender: ['Mod+Numpad3'] }), + act('viewTop', 'Top view', 'View', ['Numpad7', 'Digit7'], [...BUILD, '!camera-view'], { blender: ['Numpad7'] }), + act('viewBottom', 'Bottom view', 'View', ['Mod+Numpad7', 'Alt+Digit7'], [...BUILD, '!camera-view'], { blender: ['Mod+Numpad7'] }), + act('viewOrtho', 'Switch between perspective and orthographic', 'View', ['Numpad5', 'Digit5'], [...BUILD, '!camera-view'], { blender: ['Numpad5'] }), + act('navHelp', 'Navigation help', 'View', [], []), + act('displayMenu', 'Display menu', 'View', ['KeyZ'], []), + act('displayWireToggle', 'Switch wireframe on or off', 'View', ['Shift+KeyZ'], []), + act('displaySolid', 'Display solid', 'View', [], []), + act('displayWire', 'Display wireframe', 'View', [], []), + act('displaySolidWire', 'Display solid with wire', 'View', [], []), + act('displayMaterial', 'Display material preview', 'View', [], []), + act('displayBounds', 'Display bounding boxes', 'View', [], []), + act('overlayAxes', 'Show or hide the axes', 'View', [], []), + act('overlayLights', 'Show or hide light helpers', 'View', [], []), + act('overlayCameras', 'Show or hide camera helpers', 'View', [], []), + act('overlayOutline', 'Show or hide the selection outline', 'View', [], []), + act('overlayBackface', 'Backface culling', 'View', [], []), + act('displayAsInherit', 'Display as the viewport setting', 'View', [], ['build', 'selection']), + act('displayAsWire', 'Display as wireframe', 'View', [], ['build', 'selection']), + act('displayAsBounds', 'Display as bounding box', 'View', [], ['build', 'selection']), + act('displayAsNoRender', 'Hide in render', 'View', [], ['build', 'selection']), act('escape', 'Back out one step', 'Selection', ['Escape'], ['not-busy']), act('deselect', 'Clear the selection', 'Selection', ['Mod+Alt+KeyA'], SEL, { blender: ['Alt+KeyA'] }), + act('selectAll', 'Select all', 'Selection', ['Mod+KeyA'], BUILD, { blender: ['KeyA'] }), + act('invertSelection', 'Invert the selection', 'Selection', ['Mod+KeyI'], BUILD, { blender: ['Mod+KeyI'] }), + act('alignCamera', 'Align camera to view', 'View', ['Mod+Alt+Numpad0'], [...BUILD, '!camera-view'], { blender: ['Mod+Alt+Numpad0'] }), act('undo', 'Undo', 'Edit', ['Mod+KeyZ'], BUILD), act('redo', 'Redo', 'Edit', ['Mod+Shift+KeyZ', 'Mod+KeyY'], BUILD), diff --git a/frontend/src/engine/scene/doc.ts b/frontend/src/engine/scene/doc.ts index afcf2ad..fee8549 100644 --- a/frontend/src/engine/scene/doc.ts +++ b/frontend/src/engine/scene/doc.ts @@ -1,9 +1,10 @@ -import { ASPECTS, MAX_CAMERAS, SCENE_FORMAT, SKYBOXES, isPackSky, type PackSkyId, type AspectId, type SceneDoc, type SceneEnvironment, type SceneObject, type SkyboxId, type Sun, type Vec3, type ViewPose } from './types'; +import { ASPECTS, MAX_CAMERAS, SCENE_FORMAT, SKYBOXES, isPackSky, type PackSkyId, type AspectId, type SceneDoc, type SceneEditorPrefs, type SceneEnvironment, type SceneObject, type SkyboxId, type SnapSteps, type Sun, type Vec3, type ViewPose } from './types'; import { newId, validId } from './ids'; import { lookAtEuler } from './matrix'; import { blankTimeline } from './tl-core'; import { parseTimeline } from './timeline'; import { normaliseColor, normaliseObject, newObject } from './objects'; +import { cleanEnvMap } from './env-map'; export const MAX_OBJECTS = 2000; export const MAX_PROMPT = 4000; @@ -177,9 +178,46 @@ function readScene(input: unknown): ParseResult { prompt: typeof raw.prompt === 'string' ? raw.prompt.slice(0, MAX_PROMPT) : '', environment: cleanEnvironment(raw.environment), }; + const envMap = cleanEnvMap(raw.envMap); + if (envMap) doc.envMap = envMap; + const prefs = cleanEditorPrefs(raw.editorPrefs); + if (prefs) doc.editorPrefs = prefs; return { doc, issues }; } +const clampStep = (v: unknown, lo: number, hi: number, fallback: number): number => { + const n = Number(v); + return Number.isFinite(n) && n > 0 ? Math.min(hi, Math.max(lo, n)) : fallback; +}; + +export const DEFAULT_SNAP: SnapSteps = { move: 0.1, rotate: 5, scale: 0.1, grid: false }; + +export function cleanSnap(v: unknown): SnapSteps { + const r = v && typeof v === 'object' ? (v as Record) : {}; + return { + move: clampStep(r.move, 0.001, 100, DEFAULT_SNAP.move), + rotate: clampStep(r.rotate, 0.1, 180, DEFAULT_SNAP.rotate), + scale: clampStep(r.scale, 0.001, 10, DEFAULT_SNAP.scale), + grid: r.grid === true, + }; +} + +export function cleanEditorPrefs(v: unknown): SceneEditorPrefs | null { + if (!v || typeof v !== 'object') return null; + const r = v as Record; + const out: SceneEditorPrefs = {}; + if (typeof r.display === 'string' && r.display.length < 32) out.display = r.display; + if (typeof r.ortho === 'boolean') out.ortho = r.ortho; + if (typeof r.snapping === 'boolean') out.snapping = r.snapping; + if (r.overlays && typeof r.overlays === 'object') { + const o: Record = {}; + for (const [k, val] of Object.entries(r.overlays as Record).slice(0, 16)) if (typeof val === 'boolean' && k.length < 32) o[k] = val; + out.overlays = o; + } + if (r.snap !== undefined) out.snap = cleanSnap(r.snap); + return Object.keys(out).length ? out : null; +} + export function sceneToPlain(doc: Readonly): SceneDoc { const objects: SceneObject[] = []; for (const o of doc.objects) { @@ -188,7 +226,11 @@ export function sceneToPlain(doc: Readonly): SceneDoc { } const ids = new Set(objects.map((o) => o.id)); const camera = objects.find((o) => o.id === doc.activeCamera && o.kind === 'camera') ?? objects.find((o) => o.kind === 'camera'); + const envMap = cleanEnvMap(doc.envMap); + const editorPrefs = cleanEditorPrefs(doc.editorPrefs); return { + ...(editorPrefs ? { editorPrefs } : {}), + ...(envMap ? { envMap } : {}), format: SCENE_FORMAT, objects, activeCamera: camera ? camera.id : doc.activeCamera, @@ -217,5 +259,6 @@ export function contentSignature(doc: Readonly): string { doc.timeline, doc.prompt, doc.environment, + doc.envMap ?? null, ]); } diff --git a/frontend/src/engine/scene/editor-state.ts b/frontend/src/engine/scene/editor-state.ts index d78a6e9..bf140a3 100644 --- a/frontend/src/engine/scene/editor-state.ts +++ b/frontend/src/engine/scene/editor-state.ts @@ -2,6 +2,9 @@ import { Emitter } from '../emitter'; import type { EditorEvent, EditorEvents, EditorSource, GizmoMode, GizmoSpace, SceneMode, SceneSource } from './types'; import { SCENE_FPS } from './types'; import { EPS, clamp } from './tl-core'; +import { ViewportState } from './viewport'; +import { DEFAULT_SNAP, cleanSnap } from './doc'; +import type { SnapSteps } from './types'; export type EscapeLayer = 'camera-view' | 'pose' | 'selection'; @@ -17,6 +20,7 @@ export interface TimelinePick { } export class EditorState implements EditorSource { + readonly viewport = new ViewportState(); private readonly emitter = new Emitter(); private readonly rigged = new Set(); private mode_: SceneMode = 'build'; @@ -28,6 +32,7 @@ export class EditorState implements EditorSource { private gizmoMode_: GizmoMode = 'move'; private space_: GizmoSpace = 'world'; private snapping_ = true; + private snap_: SnapSteps = { ...DEFAULT_SNAP }; private outliner_ = true; private timeline_ = false; private busy_ = false; @@ -41,6 +46,7 @@ export class EditorState implements EditorSource { }); scene.on('removed', (id) => { this.rigged.delete(id); + this.viewport.forget(id); if (this.pose_ === id) this.setPoseTarget(null); if (this.pick_ && this.pick_.objectId === id) this.setTimelinePick(null); }); @@ -259,6 +265,18 @@ export class EditorState implements EditorSource { return this.setGizmoSpace(this.space_ === 'world' ? 'local' : 'world'); } + get snapSteps(): Readonly { + return this.snap_; + } + + setSnapSteps(next: Partial): boolean { + const clean = cleanSnap({ ...this.snap_, ...next }); + if (JSON.stringify(clean) === JSON.stringify(this.snap_)) return false; + this.snap_ = clean; + this.emitter.emit('gizmo'); + return true; + } + setSnapping(on: boolean): boolean { if (on === this.snapping_) return false; this.snapping_ = on; @@ -337,6 +355,7 @@ export class EditorState implements EditorSource { private resetForScene(): void { this.rigged.clear(); + this.viewport.forget(); this.pick_ = null; if (this.playing_) this.setPlaying(false); this.setPlayhead(0); diff --git a/frontend/src/engine/scene/env-map.ts b/frontend/src/engine/scene/env-map.ts new file mode 100644 index 0000000..93819fa --- /dev/null +++ b/frontend/src/engine/scene/env-map.ts @@ -0,0 +1,27 @@ +import { mediaRef, type MediaRef } from './material'; + +export interface SceneEnvMap { + image: MediaRef; + name: string; + hdr: boolean; + intensity: number; + rotation: number; + background: boolean; +} + +export const MAX_ENV_INTENSITY = 10; + +const isRecord = (v: unknown): v is Record => typeof v === 'object' && v !== null && !Array.isArray(v); + +export const isRadianceName = (name: string): boolean => /\.(hdr|exr)$/i.test(name.trim()); + +export function cleanEnvMap(v: unknown): SceneEnvMap | null { + if (!isRecord(v)) return null; + const image = mediaRef(v.image); + if (!image) return null; + const name = typeof v.name === 'string' && v.name.trim() ? v.name.trim().slice(0, 120) : 'Environment'; + const intensity = typeof v.intensity === 'number' && Number.isFinite(v.intensity) ? Math.min(MAX_ENV_INTENSITY, Math.max(0, v.intensity)) : 1; + let rotation = typeof v.rotation === 'number' && Number.isFinite(v.rotation) ? v.rotation % 360 : 0; + if (rotation < 0) rotation += 360; + return { image, name, hdr: v.hdr === true, intensity, rotation: Math.round(rotation * 100) / 100, background: v.background !== false }; +} diff --git a/frontend/src/engine/scene/material.ts b/frontend/src/engine/scene/material.ts new file mode 100644 index 0000000..253898b --- /dev/null +++ b/frontend/src/engine/scene/material.ts @@ -0,0 +1,66 @@ +export interface MediaRef { $media: string } + +export type MapRole = 'colorMap' | 'normalMap' | 'roughnessMap'; +export const MAP_ROLES: readonly MapRole[] = ['colorMap', 'normalMap', 'roughnessMap']; + +export interface ObjectMaterial { + metalness: number; + roughness: number; + colorMap?: MediaRef; + normalMap?: MediaRef; + roughnessMap?: MediaRef; + repeat?: [number, number]; + emissive?: string; + emissiveStrength?: number; + opacity?: number; +} + +export type MaterialPatch = Partial> & Partial>; + +export const MAX_REPEAT = 100; +export const MAX_EMISSIVE = 20; + +const isRecord = (v: unknown): v is Record => typeof v === 'object' && v !== null && !Array.isArray(v); + +const num = (v: unknown, fallback: number, lo: number, hi: number): number => + typeof v === 'number' && Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : fallback; + +export function mediaRef(v: unknown): MediaRef | null { + return isRecord(v) && typeof v.$media === 'string' && v.$media && v.$media.length <= 200 ? { $media: v.$media } : null; +} + +function hex(v: unknown): string | null { + if (typeof v !== 'string') return null; + const m = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.exec(v.trim()); + if (!m) return null; + const h = m[1].length === 3 ? m[1].split('').map((c) => c + c).join('') : m[1]; + return `#${h.toLowerCase()}`; +} + +export function cleanMaterial(v: unknown): ObjectMaterial { + const m = isRecord(v) ? v : {}; + const out: ObjectMaterial = { metalness: num(m.metalness, 0, 0, 1), roughness: num(m.roughness, 1, 0, 1) }; + for (const role of MAP_ROLES) { + const ref = mediaRef(m[role]); + if (ref) out[role] = ref; + } + if (Array.isArray(m.repeat) && m.repeat.length === 2) { + const x = num(m.repeat[0], 1, 0.01, MAX_REPEAT); + const y = num(m.repeat[1], 1, 0.01, MAX_REPEAT); + if (x !== 1 || y !== 1) out.repeat = [x, y]; + } + const emissive = hex(m.emissive); + const strength = num(m.emissiveStrength, 0, 0, MAX_EMISSIVE); + if (emissive && emissive !== '#000000' && strength > 0) { + out.emissive = emissive; + out.emissiveStrength = strength; + } + const opacity = num(m.opacity, 1, 0, 1); + if (opacity < 1) out.opacity = opacity; + return out; +} + +export function materialMedia(m: Readonly | undefined): string[] { + if (!m) return []; + return MAP_ROLES.map((r) => m[r]?.$media).filter((id): id is string => !!id); +} diff --git a/frontend/src/engine/scene/objects.ts b/frontend/src/engine/scene/objects.ts index e22376e..c8a5177 100644 --- a/frontend/src/engine/scene/objects.ts +++ b/frontend/src/engine/scene/objects.ts @@ -4,6 +4,7 @@ import { } from './types'; import { newId, validId } from './ids'; import { cleanTransform } from './timeline'; +import { cleanMaterial, type MaterialPatch } from './material'; export const OBJECT_KINDS: readonly ObjectKind[] = ['shape', 'water', 'light', 'image', 'video', 'model', 'splat', 'group', 'camera']; export const SHAPE_KEYS: readonly ShapeKey[] = ['cube', 'sphere', 'cylinder', 'torus', 'cone', 'capsule']; @@ -27,7 +28,7 @@ export type ObjectPatch = Partial>; light?: Partial>; plane?: Partial; - material?: Partial>; + material?: MaterialPatch; data?: Record; }; @@ -47,7 +48,7 @@ export interface NewObjectOptions { light?: Partial>; plane?: Partial; camera?: Partial>; - material?: Partial>; + material?: MaterialPatch; data?: Record; names?: Iterable; } @@ -169,14 +170,13 @@ export function normaliseObject(raw: unknown): SceneObject | null { }; if (kind === 'shape') { out.shape = shape; - const m = isRecord(raw.material) ? raw.material : {}; - out.material = { metalness: num(m.metalness, 0, 0, 1), roughness: num(m.roughness, 1, 0, 1) }; + out.material = cleanMaterial(raw.material); } if (kind === 'model') { out.role = role; out.skeleton = raw.skeleton === true; out.pose = cleanPose(raw.pose); - if (isRecord(raw.material)) out.material = { metalness: num(raw.material.metalness, 0, 0, 1), roughness: num(raw.material.roughness, 1, 0, 1) }; + if (isRecord(raw.material)) out.material = cleanMaterial(raw.material); } if (kind === 'light') { const l = isRecord(raw.light) ? raw.light : {}; diff --git a/frontend/src/engine/scene/store.ts b/frontend/src/engine/scene/store.ts index 5924dba..fcf958f 100644 --- a/frontend/src/engine/scene/store.ts +++ b/frontend/src/engine/scene/store.ts @@ -1,9 +1,10 @@ import { ASPECTS, MAX_CAMERAS, MAX_FOCAL_MM, MIN_FOCAL_MM, PASTE_OFFSET, SKYBOXES, isPackSky, type PackSkyId, - type AspectId, type ChangeReason, type ObjectKind, type SceneDoc, type SceneEnvironment, type SceneObject, type SkyboxId, type Sun, type Timeline, type Transform, type ViewPose, + type AspectId, type ChangeReason, type ObjectKind, type SceneDoc, type SceneEditorPrefs, type SceneEnvironment, type SceneObject, type SkyboxId, type Sun, type Timeline, type Transform, type ViewPose, } from './types'; -import { cleanEnvironment, cleanSun, cleanView, sceneToPlain, serializeScene } from './doc'; +import { cleanEditorPrefs, cleanEnvironment, cleanSun, cleanView, sceneToPlain, serializeScene } from './doc'; import { newId } from './ids'; +import { cleanEnvMap } from './env-map'; import { invertAffine, pointThrough, reframe } from './matrix'; import { applyPatch, assignObject, changedKeys, cloneObject, newObject, normaliseColor, normaliseObject, uniqueName, @@ -34,7 +35,9 @@ const sameVec = (a: readonly number[], b: readonly number[]): boolean => a[0] == export class SceneStore extends StoreBase implements TimelineHost { readonly tl: TimelineEditor; - private clip: SceneObject[] | null = null; + private clip: SceneObject[][] | null = null; + private multi_: string[] = []; + private multiFor_: string | null = null; constructor(initial?: unknown) { super(initial); @@ -74,7 +77,51 @@ export class SceneStore extends StoreBase implements TimelineHost { } canCopy(id: string): boolean { - return this.canRemove(id); + const o = this.index.get(id); + return !!o && (o.kind !== 'camera' || this.cameras.length < MAX_CAMERAS); + } + + get selection(): string[] { + const p = this.selected_; + if (!p) return []; + if (this.multiFor_ !== p) return [p]; + const out = this.multi_.filter((id) => this.index.has(id)); + return out.includes(p) ? out : [p]; + } + + setSelection(ids: readonly string[], primary?: string | null): boolean { + const list = [...new Set(ids.filter((id) => this.index.has(id)))]; + const main = primary && list.includes(primary) ? primary : (list[list.length - 1] ?? null); + const before = this.selection.join('|'); + this.multi_ = list; + this.multiFor_ = main; + const moved = main !== this.selected_; + this.selected_ = main; + if (!moved && before === this.selection.join('|')) return false; + this.emit('selection', main); + return true; + } + + toggleSelected(id: string): boolean { + const now = this.selection; + return now.includes(id) ? this.setSelection(now.filter((x) => x !== id)) : this.setSelection([...now, id], id); + } + + selectAll(): boolean { + return this.setSelection(this.doc_.objects.filter((o) => !o.parent).map((o) => o.id), this.selected_); + } + + invertSelection(): boolean { + const now = new Set(this.selection); + return this.setSelection(this.doc_.objects.filter((o) => !o.parent && !now.has(o.id)).map((o) => o.id)); + } + + setEditorPrefs(next: SceneEditorPrefs): boolean { + const clean = cleanEditorPrefs({ ...(this.doc_.editorPrefs ?? {}), ...next }); + if (JSON.stringify(clean) === JSON.stringify(this.doc_.editorPrefs ?? null)) return false; + if (clean) this.doc_.editorPrefs = clean; + else delete this.doc_.editorPrefs; + return true; } names(): string[] { @@ -142,7 +189,7 @@ export class SceneStore extends StoreBase implements TimelineHost { } remove(input?: string | readonly string[]): string[] { - const asked = input === undefined ? (this.selected_ ? [this.selected_] : []) : typeof input === 'string' ? [input] : input; + const asked = input === undefined ? this.selection : typeof input === 'string' ? [input] : input; const first = this.firstCameraId; const set = new Set(); for (const id of asked) { @@ -178,7 +225,10 @@ export class SceneStore extends StoreBase implements TimelineHost { select(id: string | null): boolean { const next = id && this.index.has(id) ? id : null; - if (next === this.selected_) return false; + const wasMany = this.selection.length > 1; + this.multi_ = []; + this.multiFor_ = null; + if (next === this.selected_ && !wasMany) return false; this.selected_ = next; this.emit('selection', next); return true; @@ -238,6 +288,17 @@ export class SceneStore extends StoreBase implements TimelineHost { return this.tl.autoKey(objectId, time).ok; } + autoKeyMany(ids: readonly string[], time: number): boolean { + let next = this.doc_.timeline; + for (const id of ids) { + const o = this.index.get(id); + if (!o || !hasKeys(next, id)) continue; + const r = autoKey(next, id, cleanTransform(o.transform), time); + if (r.ok) next = r.timeline; + } + return this.commitTimeline('Update keyframe', next); + } + setTransform(id: string, transform: Partial, opts: UpdateOptions = {}): boolean { return this.update(id, { transform }, { label: 'Transform', ...opts }); } @@ -306,6 +367,16 @@ export class SceneStore extends StoreBase implements TimelineHost { return true; } + setEnvMap(next: unknown): boolean { + const clean = cleanEnvMap(next); + if (JSON.stringify(clean) === JSON.stringify(this.doc_.envMap ?? null)) return false; + if (clean) this.doc_.envMap = clean; + else delete this.doc_.envMap; + this.emit('env', ['envMap']); + this.checkDirty(); + return true; + } + setView(pose: ViewPose): void { this.doc_.view = cleanView(pose); this.emit('env', ['view']); @@ -425,7 +496,7 @@ export class SceneStore extends StoreBase implements TimelineHost { } group(ids?: readonly string[]): string | null { - const want = ids ?? (this.selected_ ? [this.selected_] : []); + const want = ids ?? this.selection; const usable = topMost(this.doc_.objects, want.filter((id) => (this.index.get(id)?.kind ?? 'camera') !== 'camera')); const members = this.doc_.objects.filter((o) => usable.includes(o.id)); if (!members.length) return null; @@ -492,10 +563,15 @@ export class SceneStore extends StoreBase implements TimelineHost { return [cloneObject(root), ...descendantsOf(this.doc_.objects, id).map((o) => cloneObject(o))]; } + private copyRoots(id?: string): string[] { + const asked = id ? [id] : this.selection; + return topMost(this.doc_.objects, asked.filter((x) => this.index.has(x))); + } + copy(id?: string): boolean { - const target = id ?? this.selected_; - if (!target || !this.canCopy(target)) return false; - this.clip = this.subtree(target); + const roots = this.copyRoots(id).filter((r) => this.canCopy(r) || this.index.get(r)?.kind === 'camera'); + if (!roots.length) return false; + this.clip = roots.map((r) => this.subtree(r)); return true; } @@ -503,36 +579,51 @@ export class SceneStore extends StoreBase implements TimelineHost { if (!this.clip) return null; const root = this.insertCopy(this.clip, 'Paste'); if (root) { - const p = this.clip[0].transform.position; - this.clip[0].transform.position = [p[0] + PASTE_OFFSET[0], p[1] + PASTE_OFFSET[1], p[2] + PASTE_OFFSET[2]]; + for (const tree of this.clip) { + const p = tree[0].transform.position; + tree[0].transform.position = [p[0] + PASTE_OFFSET[0], p[1] + PASTE_OFFSET[1], p[2] + PASTE_OFFSET[2]]; + } } return root; } duplicate(id?: string): string | null { - const target = id ?? this.selected_; - if (!target || !this.canCopy(target)) return null; - return this.insertCopy(this.subtree(target), 'Duplicate'); + const roots = this.copyRoots(id).filter((r) => this.canCopy(r)); + if (!roots.length) return null; + return this.insertCopy(roots.map((r) => this.subtree(r)), 'Duplicate'); } - private insertCopy(src: readonly SceneObject[], verb: string): string | null { - const root = src[0]; - if (root.kind === 'camera' && this.cameras.length >= MAX_CAMERAS) return null; - const ids = new Map(src.map((o) => [o.id, newId()])); + private insertCopy(trees: readonly (readonly SceneObject[])[], verb: string): string | null { + let room = MAX_CAMERAS - this.cameras.length; const taken = new Set(this.names()); - const copies = src.map((o, i) => { - const c = cloneObject(o); - c.id = ids.get(o.id) as string; - c.name = uniqueName(o.name, taken); - taken.add(c.name); - if (i === 0) { - c.parent = root.parent && this.index.get(root.parent)?.kind === 'group' ? root.parent : null; - c.transform.position = [o.transform.position[0] + PASTE_OFFSET[0], o.transform.position[1] + PASTE_OFFSET[1], o.transform.position[2] + PASTE_OFFSET[2]]; - } else c.parent = (o.parent && ids.get(o.parent)) || null; - return c; - }); - const added = this.add(copies, 'paste', { select: copies[0].id, label: `${verb} ${copies[0].name}` }); - return added.length ? added[0] : null; + const copies: SceneObject[] = []; + const roots: string[] = []; + for (const src of trees) { + const root = src[0]; + if (root.kind === 'camera') { + if (room <= 0) continue; + room--; + } + const ids = new Map(src.map((o) => [o.id, newId()])); + src.forEach((o, i) => { + const c = cloneObject(o); + c.id = ids.get(o.id) as string; + c.name = uniqueName(o.name, taken); + taken.add(c.name); + if (i === 0) { + c.parent = root.parent && this.index.get(root.parent)?.kind === 'group' ? root.parent : null; + c.transform.position = [o.transform.position[0] + PASTE_OFFSET[0], o.transform.position[1] + PASTE_OFFSET[1], o.transform.position[2] + PASTE_OFFSET[2]]; + roots.push(c.id); + } else c.parent = (o.parent && ids.get(o.parent)) || null; + copies.push(c); + }); + } + if (!copies.length) return null; + const label = roots.length === 1 ? `${verb} ${copies[0].name}` : `${verb} ${roots.length} objects`; + const added = this.add(copies, 'paste', { select: roots[0], label }); + if (!added.length) return null; + if (roots.length > 1) this.setSelection(roots, roots[0]); + return added[0]; } applyTimeline(time: number): string[] { diff --git a/frontend/src/engine/scene/tl-batch.ts b/frontend/src/engine/scene/tl-batch.ts new file mode 100644 index 0000000..2d3e632 --- /dev/null +++ b/frontend/src/engine/scene/tl-batch.ts @@ -0,0 +1,56 @@ +import type { Bezier, Timeline, Transform } from './types'; +import { addKey } from './tl-keys'; +import { EPS, cloneTimeline, fail, type Outcome } from './tl-core'; + +export interface KeySpec { + objectId: string; + time: number; + transform: Transform; + ease?: Bezier | string; +} + +export interface KeyRange { + objectId: string; + keyIds?: readonly string[]; + from?: number; + to?: number; +} + +export function addKeys(tl: Timeline, specs: readonly KeySpec[]): Outcome<{ timeline: Timeline; ids: string[]; replaced: number }> { + let next = tl; + const ids: string[] = []; + let replaced = 0; + for (const spec of specs) { + const out = addKey(next, spec.objectId, spec.transform, spec.time, spec.ease); + if (!out.ok) return out; + next = out.timeline; + ids.push(out.id ?? ''); + if (out.replaced) replaced++; + } + return { ok: true, timeline: next === tl ? cloneTimeline(tl) : next, ids, replaced }; +} + +export function removeKeys(tl: Timeline, ranges: readonly KeyRange[]): { timeline: Timeline; removed: string[] } { + const next = cloneTimeline(tl); + const removed: string[] = []; + for (const range of ranges) { + const track = next.tracks.find((t) => t.objectId === range.objectId); + if (!track) continue; + const lo = range.from ?? -Infinity; + const hi = range.to ?? Infinity; + track.keys = track.keys.filter((k) => { + const hit = range.keyIds ? range.keyIds.includes(k.id) : k.time >= lo - EPS && k.time <= hi + EPS; + if (hit) removed.push(k.id); + return !hit; + }); + } + next.tracks = next.tracks.filter((t) => t.keys.length > 0); + return { timeline: next, removed }; +} + +export function setRate(tl: Timeline, fps: number): Outcome<{ timeline: Timeline }> { + if (!Number.isInteger(fps) || fps < 1 || fps > 120) return fail('invalid'); + const next = cloneTimeline(tl); + next.fps = fps; + return { ok: true, timeline: next }; +} diff --git a/frontend/src/engine/scene/types.ts b/frontend/src/engine/scene/types.ts index e83a3e1..0a6f1d7 100644 --- a/frontend/src/engine/scene/types.ts +++ b/frontend/src/engine/scene/types.ts @@ -1,3 +1,6 @@ +import type { ObjectMaterial } from './material'; +import type { SceneEnvMap } from './env-map'; + export type Vec3 = [number, number, number]; export type Quat = [number, number, number, number]; export type Bezier = [number, number, number, number]; @@ -66,7 +69,7 @@ export interface SceneObject { light?: { intensity: number; distance: number }; plane?: PlaneOptions; camera?: { focal: number }; - material?: { metalness: number; roughness: number }; + material?: ObjectMaterial; data?: Record; } @@ -139,7 +142,23 @@ export interface SceneEnvironment { name: string; } +export interface SnapSteps { + move: number; + rotate: number; + scale: number; + grid: boolean; +} + +export interface SceneEditorPrefs { + display?: string; + ortho?: boolean; + overlays?: Record; + snapping?: boolean; + snap?: SnapSteps; +} + export interface SceneDoc { + editorPrefs?: SceneEditorPrefs; format: typeof SCENE_FORMAT; objects: SceneObject[]; activeCamera: string; @@ -150,10 +169,11 @@ export interface SceneDoc { timeline: Timeline; prompt: string; environment: SceneEnvironment | null; + envMap?: SceneEnvMap | null; } export type ChangeReason = 'user' | 'undo' | 'redo' | 'load' | 'timeline' | 'paste'; -export type EnvKey = 'aspect' | 'skybox' | 'sun' | 'view' | 'activeCamera' | 'prompt' | 'environment'; +export type EnvKey = 'aspect' | 'skybox' | 'sun' | 'view' | 'activeCamera' | 'prompt' | 'environment' | 'envMap'; export type SceneEvents = { reset: []; diff --git a/frontend/src/engine/scene/viewport.ts b/frontend/src/engine/scene/viewport.ts new file mode 100644 index 0000000..86a6389 --- /dev/null +++ b/frontend/src/engine/scene/viewport.ts @@ -0,0 +1,209 @@ +import { Emitter } from '../emitter'; + +export type DisplayMode = 'solid' | 'wire' | 'solid-wire' | 'material' | 'bounds'; +export type ObjectDisplay = 'inherit' | 'wire' | 'bounds' | 'no-render'; +export type Overlay = 'axes' | 'lights' | 'cameras' | 'outline' | 'backface'; +export type ViewPreset = 'front' | 'back' | 'left' | 'right' | 'top' | 'bottom'; + +export const DISPLAY_MODES: ReadonlyArray<{ id: DisplayMode; label: string }> = [ + { id: 'solid', label: 'Solid' }, + { id: 'wire', label: 'Wireframe' }, + { id: 'solid-wire', label: 'Solid with wire' }, + { id: 'material', label: 'Material preview' }, + { id: 'bounds', label: 'Bounding box' }, +]; + +export const OBJECT_DISPLAYS: ReadonlyArray<{ id: ObjectDisplay; label: string }> = [ + { id: 'inherit', label: 'Viewport setting' }, + { id: 'wire', label: 'Wireframe' }, + { id: 'bounds', label: 'Bounding box' }, + { id: 'no-render', label: 'Hidden in render' }, +]; + +export const OVERLAYS: ReadonlyArray<{ id: Overlay; label: string }> = [ + { id: 'axes', label: 'Axes' }, + { id: 'lights', label: 'Light helpers' }, + { id: 'cameras', label: 'Camera helpers' }, + { id: 'outline', label: 'Selection outline' }, + { id: 'backface', label: 'Backface culling' }, +]; + +export const VIEW_PRESETS: Readonly> = { + front: { yaw: 0, pitch: 0, label: 'Front' }, + back: { yaw: Math.PI, pitch: 0, label: 'Back' }, + right: { yaw: Math.PI / 2, pitch: 0, label: 'Right' }, + left: { yaw: -Math.PI / 2, pitch: 0, label: 'Left' }, + top: { yaw: 0, pitch: -Math.PI / 2, label: 'Top' }, + bottom: { yaw: 0, pitch: Math.PI / 2, label: 'Bottom' }, +}; + +export interface NavPrefs { + invertZoom: boolean; + orbitSpeed: number; + trackpad: boolean; +} + +export const NAV_STORAGE_KEY = 'formcraft.scene.nav'; +export const ORBIT_SPEED_MIN = 0.25; +export const ORBIT_SPEED_MAX = 3; + +type ViewportEvents = { display: []; prefs: []; object: [id: string] }; + +const DEFAULT_OVERLAYS: Readonly> = { axes: true, lights: true, cameras: true, outline: true, backface: false }; + +function detectMac(): boolean { + try { + return typeof navigator !== 'undefined' && /Mac/.test(navigator.platform || navigator.userAgent); + } catch { + return false; + } +} + +export class ViewportState { + private readonly emitter = new Emitter(); + private mode_: DisplayMode = 'material'; + private ortho_ = false; + private readonly overlays: Record = { ...DEFAULT_OVERLAYS }; + private readonly objects = new Map(); + private prefs_: NavPrefs = { invertZoom: false, orbitSpeed: 1, trackpad: detectMac() }; + + constructor() { + this.load(); + } + + on(event: E, fn: (...args: ViewportEvents[E]) => void): () => void { + return this.emitter.on(event, fn); + } + + get mode(): DisplayMode { + return this.mode_; + } + + get ortho(): boolean { + return this.ortho_; + } + + get prefs(): Readonly { + return this.prefs_; + } + + setMode(mode: DisplayMode): boolean { + if (mode === this.mode_ || !DISPLAY_MODES.some((m) => m.id === mode)) return false; + this.mode_ = mode; + this.emitter.emit('display'); + return true; + } + + cycleMode(): DisplayMode { + const i = DISPLAY_MODES.findIndex((m) => m.id === this.mode_); + this.setMode(DISPLAY_MODES[(i + 1) % DISPLAY_MODES.length].id); + return this.mode_; + } + + toggleWire(): boolean { + return this.setMode(this.mode_ === 'wire' ? 'material' : 'wire'); + } + + setOrtho(on: boolean): boolean { + if (on === this.ortho_) return false; + this.ortho_ = on; + this.emitter.emit('display'); + return true; + } + + overlay(id: Overlay): boolean { + return this.overlays[id]; + } + + setOverlay(id: Overlay, on: boolean): boolean { + if (!(id in this.overlays) || this.overlays[id] === on) return false; + this.overlays[id] = on; + this.emitter.emit('display'); + return true; + } + + toggleOverlay(id: Overlay): boolean { + return this.setOverlay(id, !this.overlays[id]); + } + + objectDisplay(id: string): ObjectDisplay { + return this.objects.get(id) ?? 'inherit'; + } + + hasObjectDisplays(): boolean { + return this.objects.size > 0; + } + + objectEntries(): IterableIterator<[string, ObjectDisplay]> { + return this.objects.entries(); + } + + setObjectDisplay(id: string, display: ObjectDisplay): boolean { + if (!OBJECT_DISPLAYS.some((d) => d.id === display) || this.objectDisplay(id) === display) return false; + if (display === 'inherit') this.objects.delete(id); + else this.objects.set(id, display); + this.emitter.emit('object', id); + this.emitter.emit('display'); + return true; + } + + forget(id?: string): void { + if (id === undefined) { + if (this.objects.size === 0) return; + this.objects.clear(); + } else if (!this.objects.delete(id)) return; + this.emitter.emit('display'); + } + + saved(): { display: DisplayMode; ortho: boolean; overlays: Record } { + return { display: this.mode_, ortho: this.ortho_, overlays: { ...this.overlays } }; + } + + restore(p: { display?: string; ortho?: boolean; overlays?: Record }): void { + let changed = false; + const mode = DISPLAY_MODES.find((m) => m.id === p.display)?.id; + if (mode && mode !== this.mode_) { + this.mode_ = mode; + changed = true; + } + if (typeof p.ortho === 'boolean' && p.ortho !== this.ortho_) { + this.ortho_ = p.ortho; + changed = true; + } + for (const id of Object.keys(this.overlays) as Overlay[]) { + const want = p.overlays?.[id]; + if (typeof want === 'boolean' && want !== this.overlays[id]) { + this.overlays[id] = want; + changed = true; + } + } + if (changed) this.emitter.emit('display'); + } + + setPrefs(next: Partial): void { + const merged: NavPrefs = { ...this.prefs_, ...next }; + merged.orbitSpeed = Math.min(ORBIT_SPEED_MAX, Math.max(ORBIT_SPEED_MIN, Number(merged.orbitSpeed) || 1)); + this.prefs_ = merged; + try { + localStorage.setItem(NAV_STORAGE_KEY, JSON.stringify(merged)); + } catch { + return void this.emitter.emit('prefs'); + } + this.emitter.emit('prefs'); + } + + private load(): void { + try { + const raw = localStorage.getItem(NAV_STORAGE_KEY); + if (!raw) return; + const saved = JSON.parse(raw) as Partial; + this.prefs_ = { + invertZoom: saved.invertZoom === true, + orbitSpeed: Math.min(ORBIT_SPEED_MAX, Math.max(ORBIT_SPEED_MIN, Number(saved.orbitSpeed) || 1)), + trackpad: typeof saved.trackpad === 'boolean' ? saved.trackpad : this.prefs_.trackpad, + }; + } catch { + return; + } + } +} diff --git a/frontend/src/engine/shortcut-presets.ts b/frontend/src/engine/shortcut-presets.ts new file mode 100644 index 0000000..a9eb02c --- /dev/null +++ b/frontend/src/engine/shortcut-presets.ts @@ -0,0 +1,62 @@ +export type PresetId = 'standard' | 'blender' | 'maya'; + +export interface PresetInfo { + id: PresetId; + label: string; + note: string; +} + +export const PRESETS: ReadonlyArray = [ + { id: 'standard', label: 'FormCraft', note: 'The default keys: W A S D fly, T R G for the tools.' }, + { + id: 'blender', + label: 'Blender-like', + note: 'G grabs with X, Y, Z axis lock, R rotates, S scales, Shift+A adds, X deletes, Z opens the display menu, Tab switches mode, N and T show panels, numpad sets the view.', + }, + { + id: 'maya', + label: 'Maya/Unity-like', + note: 'W moves, E rotates, R scales, F frames the selection, Alt-drag orbits, the camera flies on the numpad.', + }, +]; + +const FLY: Record = { + 'scene.camForward': ['Numpad8', 'Digit8'], + 'scene.camBack': ['Numpad2', 'Digit2'], + 'scene.camLeft': ['Numpad4', 'Digit4'], + 'scene.camRight': ['Numpad6', 'Digit6'], + 'scene.camUp': ['Numpad9', 'Digit9'], + 'scene.camDown': ['Digit3'], +}; + +export const PRESET_KEYS: Readonly, Readonly>>> = { + blender: { + 'scene.grab': ['KeyG'], + 'scene.gizmoMove': ['Shift+KeyG'], + 'scene.gizmoRotate': ['KeyR'], + 'scene.gizmoScale': ['KeyS'], + 'scene.delete': ['KeyX', 'Delete', 'Backspace'], + 'scene.toggleSpace': ['Backslash'], + 'scene.presets': ['Shift+KeyA'], + 'scene.displayMenu': ['KeyZ'], + 'scene.displayWireToggle': ['Shift+KeyZ'], + 'scene.mode': ['Tab'], + 'scene.outliner': ['KeyN'], + 'scene.timelineToggle': ['KeyT'], + 'scene.toggleSnapping': ['Shift+Tab'], + 'scene.focus': ['NumpadDecimal', 'KeyF'], + }, + maya: { + ...FLY, + 'scene.gizmoMove': ['KeyW'], + 'scene.gizmoRotate': ['KeyE'], + 'scene.gizmoScale': ['KeyR'], + 'scene.focus': ['KeyF'], + 'scene.frameAll': ['KeyA'], + }, +}; + +export function presetKeys(preset: PresetId, action: string): readonly string[] | undefined { + if (preset === 'standard') return undefined; + return PRESET_KEYS[preset][action]; +} diff --git a/frontend/src/engine/shortcuts.ts b/frontend/src/engine/shortcuts.ts index bfa6749..46c96fd 100644 --- a/frontend/src/engine/shortcuts.ts +++ b/frontend/src/engine/shortcuts.ts @@ -1,13 +1,10 @@ import { Emitter } from './emitter'; +import { PRESETS, presetKeys, type PresetId } from './shortcut-presets'; export type Surface = 'global' | 'create' | 'canvas' | 'scene' | 'board' | 'edit'; -export type PresetId = 'standard' | 'blender'; +export { PRESETS, type PresetId }; export const SURFACES: readonly Surface[] = ['global', 'create', 'canvas', 'scene', 'board', 'edit']; -export const PRESETS: ReadonlyArray<{ id: PresetId; label: string }> = [ - { id: 'standard', label: 'Standard' }, - { id: 'blender', label: 'Blender-like' }, -]; export const STORAGE_KEY = 'formcraft.shortcuts'; @@ -180,9 +177,48 @@ class Shortcuts { defaults(action: string): string[] { const d = this.defs.get(action); if (!d) return []; + const table = presetKeys(this.presetId, action); + if (table) return table.map((k) => this.normalize(k)); return this.presetId === 'blender' && d.blender.length ? [...d.blender] : [...d.keys]; } + overrideCount(): number { + let n = 0; + for (const action of Object.keys(this.overrides)) if (this.defs.has(action) && this.isCustomised(action)) n++; + return n; + } + + exportJson(): string { + const overrides: Record = {}; + for (const [action, list] of Object.entries(this.overrides)) overrides[action] = [...list]; + return JSON.stringify({ app: 'formcraft', kind: 'shortcuts', version: 1, preset: this.presetId, overrides }, null, 2); + } + + importJson(text: string): number { + let data: unknown; + try { + data = JSON.parse(text); + } catch { + throw new Error('not json'); + } + const src = data as { preset?: unknown; overrides?: unknown } | null; + if (!src || typeof src !== 'object' || !src.overrides || typeof src.overrides !== 'object' || Array.isArray(src.overrides)) throw new Error('no bindings'); + const next: Record = {}; + for (const [action, list] of Object.entries(src.overrides as Record)) { + if (!Array.isArray(list) || !list.every((x) => typeof x === 'string')) continue; + try { + next[action] = (list as string[]).map((b) => this.normalize(b)); + } catch { + continue; + } + } + if (PRESETS.some((p) => p.id === src.preset)) this.presetId = src.preset as PresetId; + this.overrides = next; + this.save(); + this.emitter.emit('change'); + return this.overrideCount(); + } + bindings(action: string): string[] { const o = this.overrides[action]; return o ? [...o] : this.defaults(action); @@ -321,7 +357,7 @@ class Shortcuts { const raw = localStorage.getItem(STORAGE_KEY); if (!raw) return; const saved = JSON.parse(raw) as Partial; - if (saved.preset === 'standard' || saved.preset === 'blender') this.presetId = saved.preset; + if (PRESETS.some((p) => p.id === saved.preset)) this.presetId = saved.preset as PresetId; if (saved.overrides && typeof saved.overrides === 'object') { for (const [action, list] of Object.entries(saved.overrides)) { if (!Array.isArray(list) || !list.every((x) => typeof x === 'string')) continue; diff --git a/frontend/src/io/api-agents.ts b/frontend/src/io/api-agents.ts index 07d3c72..5e0b6a2 100644 --- a/frontend/src/io/api-agents.ts +++ b/frontend/src/io/api-agents.ts @@ -1,6 +1,27 @@ import { request, type RequestOptions } from './api'; -export type AgentPolicy = 'allow' | 'ask' | 'deny'; +export type AgentPolicy = 'allow' | 'session' | 'ask' | 'deny'; +export type AgentLevel = AgentPolicy | 'project'; +export type ApprovalScope = 'once' | 'session' | 'project' | 'allow'; +export type ApprovalRisk = 'normal' | 'spend' | 'risky'; + +export interface AgentGrant { + client: string; + scope: 'allow' | 'project' | 'remembered' | 'session'; + key: string; + label: string; + project?: string; +} + +export interface AgentProject { + id: string; + name: string; +} + +export interface AgentSpend { + on: boolean; + limitUsd: number; +} export interface ToolAnnotations { readOnlyHint: boolean; @@ -50,6 +71,11 @@ export interface BridgeApproval { args: Record; client: string; costUsd?: number; + title?: string; + risk?: ApprovalRisk; + keepable?: boolean; + level?: AgentLevel; + project?: AgentProject | null; } export interface BridgeWithdraw { @@ -75,6 +101,7 @@ export type BridgeAnswer = { ok: true; result: ToolResult } | { ok: false; error export interface AgentClient { name: string; policy?: AgentPolicy; + level?: AgentLevel; lastSeen?: string | number | null; calls?: number; } @@ -86,6 +113,17 @@ export interface AgentsState { windowConnected: boolean; tokenPath: string; defaultPolicy?: AgentPolicy; + grants?: AgentGrant[]; + spend?: AgentSpend; + project?: AgentProject | null; +} + +export interface AgentsPatch { + allowed?: boolean; + policies?: Record; + level?: { client: string; level: AgentLevel }; + spend?: AgentSpend; + revoke?: { client: string; scope: AgentGrant['scope']; key: string }; } export interface AgentActivity { @@ -99,18 +137,18 @@ export interface AgentActivity { export const postCatalogue = (body: Catalogue, opts?: RequestOptions): Promise => request('POST', '/agents/catalogue', body, opts); -export const nextBridge = (wait: number, opts?: RequestOptions): Promise => - request('GET', `/agents/bridge/next?wait=${wait}`, undefined, opts); +export const nextBridge = (wait: number, opts?: RequestOptions, project?: string | null): Promise => + request('GET', `/agents/bridge/next?wait=${wait}${project === undefined ? '' : `&project=${encodeURIComponent(project ?? '')}`}`, undefined, opts); export const answerBridge = (id: string, body: BridgeAnswer, opts?: RequestOptions): Promise => request('POST', `/agents/bridge/${encodeURIComponent(id)}/result`, body, opts); -export const answerApproval = (id: string, allow: boolean, remember = false): Promise => - request('POST', `/agents/approvals/${encodeURIComponent(id)}`, remember ? { allow, remember } : { allow }); +export const answerApproval = (id: string, allow: boolean, remember = false, scope: ApprovalScope = 'once', project?: string | null): Promise => + request('POST', `/agents/approvals/${encodeURIComponent(id)}`, { allow, ...(remember ? { remember } : {}), ...(scope !== 'once' ? { scope } : {}), ...(project === undefined ? {} : { project: project ?? '' }) }); export const getAgentsState = (opts?: RequestOptions): Promise => request('GET', '/agents/state', undefined, opts); -export const putAgentsState = (patch: { allowed?: boolean; policies?: Record }): Promise => +export const putAgentsState = (patch: AgentsPatch): Promise => request('PUT', '/agents/state', patch); export const rotateAgentToken = (): Promise<{ tokenPath: string }> => request('POST', '/agents/token/rotate'); diff --git a/frontend/src/io/api-projects.ts b/frontend/src/io/api-projects.ts index fe5d582..818a19b 100644 --- a/frontend/src/io/api-projects.ts +++ b/frontend/src/io/api-projects.ts @@ -39,8 +39,8 @@ export const patchProject = (id: string, patch: ProjectPatch): P export const deleteProject = (id: string): Promise<{ deleted: boolean }> => request('DELETE', `/projects/${encodeURIComponent(id)}`); -export const exportProject = (id: string, path: string | null = null, overwrite = false): Promise<{ path: string }> => - request('POST', `/projects/${encodeURIComponent(id)}/export`, { path, overwrite }); +export const exportProject = (id: string, path: string | null = null, overwrite = false, remember = true): Promise<{ path: string }> => + request('POST', `/projects/${encodeURIComponent(id)}/export`, { path, overwrite, remember }); export const importProjectFile = (file: File): Promise => { const form = new FormData(); diff --git a/frontend/src/io/api.ts b/frontend/src/io/api.ts index 3ded413..9d1df8f 100644 --- a/frontend/src/io/api.ts +++ b/frontend/src/io/api.ts @@ -19,7 +19,12 @@ export type Strategy = 'upgrade' | 'downgrade' | 'strict'; export interface Settings { downloadDir: string; namingScheme: string; autoDownload: boolean; askLocation: boolean; strategy: Strategy } export interface KeyStatus { set: boolean; last4: string | null } -export type KeysState = Record & { store: KeyStore }; +export type SystemStore = 'keychain' | 'credential-manager' | 'secret-service' | 'kwallet'; +export type KeysState = Record & { + store: KeyStore; + stores?: Partial>; + system?: SystemStore | null; +}; export interface JobError { category: string; message: string } @@ -91,10 +96,11 @@ export interface MediaQuery { } export interface MediaPage { items: Media[]; total: number } -export interface DownloadOptions { dir?: string | null; path?: string | null; overwrite?: boolean } +export interface DownloadOptions { dir?: string | null; path?: string | null; overwrite?: boolean; project?: string | null; name?: string | null } +export interface NamePreview { ok: boolean; message: string; name: string } export interface SavedFile { id: string; path: string } export interface FailedFile { id: string; message: string } -export type BatchDownload = { saved: SavedFile[]; failed: FailedFile[]; jobId?: undefined } | { jobId: string; saved?: undefined; failed?: undefined }; +export type BatchDownload = { dir?: string; saved: SavedFile[]; failed: FailedFile[]; jobId?: undefined } | { dir?: string; jobId: string; saved?: undefined; failed?: undefined }; export interface CostRequest { provider: string; model: string; kind: string; options?: Record } export interface Cost { usd: number | null; exact: boolean; basis: string; perJob: number | null } @@ -341,17 +347,19 @@ export const listMedia = (q: MediaQuery = {}, opts?: RequestOptions): Promise): Promise<{ items: Media[] }> => { +export const importMediaFiles = (files: Iterable, hidden = false): Promise<{ items: Media[] }> => { const form = new FormData(); for (const f of files) form.append('file', f, f.name); - return request('POST', '/media/import', form); + return request('POST', `/media/import${hidden ? '?hidden=true' : ''}`, form); }; export const importMediaPaths = (paths: string[]): Promise<{ items: Media[] }> => request('POST', '/media/import', { paths }); export const getMedia = (id: string): Promise => request('GET', `/media/${encodeURIComponent(id)}`); export const deleteMedia = (id: string): Promise<{ deleted: boolean }> => request('DELETE', `/media/${encodeURIComponent(id)}`); export const downloadMedia = (id: string, opts: DownloadOptions = {}): Promise<{ path: string }> => - request('POST', `/media/${encodeURIComponent(id)}/download`, { dir: opts.dir ?? null, path: opts.path ?? null, overwrite: opts.overwrite === true }); -export const downloadBatch = (ids: string[], dir: string | null = null): Promise => request('POST', '/media/download-batch', { ids, dir }); + request('POST', `/media/${encodeURIComponent(id)}/download`, { dir: opts.dir ?? null, path: opts.path ?? null, overwrite: opts.overwrite === true, project: opts.project ?? null, name: opts.name ?? null }); +export const downloadBatch = (ids: string[], dir: string | null = null, project: string | null = null): Promise => request('POST', '/media/download-batch', { ids, dir, project }); +export const previewFileName = (scheme: string, ext: string, mediaId: string | null = null, project: string | null = null): Promise => + request('POST', '/media/name-preview', { scheme, ext, mediaId, project }); export const mediaFileUrl = (id: string): string => `${BASE}/media/${encodeURIComponent(id)}/file`; export const mediaThumbUrl = (id: string, width = 256): string => `${BASE}/media/${encodeURIComponent(id)}/thumb${query({ w: width })}`; diff --git a/frontend/src/styles/about.css b/frontend/src/styles/about.css index 0999f39..534ba82 100644 --- a/frontend/src/styles/about.css +++ b/frontend/src/styles/about.css @@ -3,4 +3,7 @@ .fc-about-row dt { color: var(--text-muted); } .fc-about-val { min-height: 1.45em; margin: 0; color: var(--text-primary); overflow-wrap: anywhere; user-select: text; font-variant-numeric: tabular-nums; } .fc-about-val.is-missing { color: var(--text-muted); } +.fc-about-head { display: flex; align-items: center; gap: var(--space-3); } +.fc-about-mark { flex: none; width: 48px; height: 48px; border-radius: var(--radius-lg); } +.fc-about-by { color: var(--text-muted); font-size: var(--fs-12); } .fc-about-row.is-tall .fc-about-val { display: -webkit-box; height: 2.9em; overflow: hidden; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; } diff --git a/frontend/src/styles/agents.css b/frontend/src/styles/agents.css index 393cdea..01962e9 100644 --- a/frontend/src/styles/agents.css +++ b/frontend/src/styles/agents.css @@ -31,4 +31,18 @@ .fc-ag-tabs { display: flex; flex-wrap: wrap; gap: var(--space-1); } .fc-ag-tab { height: var(--ctl-md); padding: 0 var(--space-3); border: 1px solid var(--border-light); border-radius: var(--radius); background: transparent; color: var(--text-secondary); font-size: var(--fs-12); cursor: pointer; } .fc-ag-tab.is-on { border-color: var(--accent-line); background: var(--accent-soft); color: var(--text-primary); } +.fc-ag-card { position: fixed; top: calc(var(--cv-titlebar-h) + var(--space-3)); right: var(--space-4); z-index: var(--z-raised); display: flex; flex-direction: column; gap: var(--space-2); width: min(360px, calc(100vw - 2 * var(--space-4))); padding: var(--space-3); border: 1px solid var(--accent-line); border-radius: var(--radius-md); background: var(--bg-secondary); box-shadow: var(--shadow-lg); color: var(--text-primary); font-size: var(--fs-12); } +.fc-ag-card[hidden] { display: none; } +.fc-ag-card:focus { outline: none; } +.fc-ag-card-head { display: flex; align-items: center; gap: var(--space-2); min-height: var(--ctl); } +.fc-ag-card-title { font-size: var(--fs-13); font-weight: 600; } +.fc-ag-card-count { flex: 1 1 auto; color: var(--text-muted); font-variant-numeric: tabular-nums; } +.fc-ag-card-head .cv-btn[hidden] { display: inline-flex; visibility: hidden; } +.fc-ag-card-what { margin: 0; overflow-wrap: anywhere; color: var(--text-primary); font-size: var(--fs-13); } +.fc-ag-card-args { margin: 0; height: calc(3 * 1.45em); overflow: hidden; color: var(--text-muted); font-family: var(--font-mono); font-size: var(--fs-11); line-height: 1.45; white-space: pre; text-overflow: ellipsis; } +.fc-ag-card-level { margin: 0; color: var(--text-secondary); } +.fc-ag-card-bar { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: var(--space-2); } +.fc-ag-card-more { justify-content: flex-start; } +.fc-ag-grant { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: var(--space-3); padding: var(--space-2) 0; } +.fc-ag-grant + .fc-ag-grant { border-top: 1px solid var(--border-soft); } .fc-ag-snippet { margin: 0; min-height: 120px; padding: var(--space-3); overflow: auto; border: 1px solid var(--border-soft); border-radius: var(--radius); background: var(--bg-input); color: var(--text-secondary); font-family: var(--font-mono); font-size: var(--fs-11); line-height: 1.5; white-space: pre; user-select: text; } diff --git a/frontend/src/styles/board-grid.css b/frontend/src/styles/board-grid.css index 0048bfc..eec94b2 100644 --- a/frontend/src/styles/board-grid.css +++ b/frontend/src/styles/board-grid.css @@ -50,6 +50,12 @@ .fc-bg-badge { position: absolute; left: var(--space-2); top: var(--space-2); display: grid; place-items: center; width: 22px; height: 22px; border-radius: 50%; background: var(--bg-scrim); color: var(--text-on-accent); pointer-events: none; } .fc-bg-note { position: absolute; inset: 0; padding: var(--space-3); overflow: hidden; background: var(--surface-2); color: var(--text-primary); } .fc-bg-note-text { margin: 0; font-size: var(--fs-13); line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; } +.fc-bg-note-text:empty::before { content: attr(data-placeholder); color: var(--text-muted); font-style: italic; } +.fc-bd-gridhost > .fc-bg-bar { width: auto; } +.fc-bg-drop { position: absolute; top: 0; left: 0; height: 3px; border-radius: var(--radius-pill); background: var(--accent-color); pointer-events: none; } +.fc-bg-drop[hidden] { display: none; } +.fc-bg-card.is-dragging { opacity: 0.4; } +.fc-bg-pane.is-reordering .fc-bg-card { cursor: grabbing; } .fc-bg-note-edit { position: absolute; inset: 0; box-sizing: border-box; width: 100%; height: 100%; padding: var(--space-3); border: 0; background: var(--surface-2); color: var(--text-primary); font: inherit; font-size: var(--fs-13); line-height: 1.45; resize: none; outline: 2px solid var(--accent-color); outline-offset: -2px; user-select: text; } .fc-bg-card.is-editing { cursor: text; } .fc-bg-link { position: absolute; inset: 0; display: flex; flex-direction: column; justify-content: center; gap: var(--space-1); padding: var(--space-3); background: var(--surface-2); } diff --git a/frontend/src/styles/board.css b/frontend/src/styles/board.css index d1bdfad..3130c83 100644 --- a/frontend/src/styles/board.css +++ b/frontend/src/styles/board.css @@ -72,7 +72,13 @@ .fc-bi-tool { display: grid; place-items: center; width: var(--ctl-md); height: var(--ctl-md); border: 0; border-radius: var(--radius-md); background: transparent; color: var(--text-secondary); cursor: pointer; } .fc-bi-tool:hover:not(:disabled) { background: var(--bg-hover); color: var(--text-primary); } .fc-bi-tool:disabled { opacity: 0.35; cursor: default; } -.fc-bi-body { display: grid; grid-template-columns: minmax(0, 1fr) 280px; min-height: 0; } +.fc-bi-tool.is-on { color: var(--accent-color); } +.fc-bi-body { display: grid; grid-template-columns: minmax(0, 1fr) 6px var(--fc-bi-side-w, 280px); min-height: 0; } +.fc-bi.is-side-hidden .fc-bi-body { grid-template-columns: minmax(0, 1fr) 0 0; } +.fc-bi.is-side-hidden .fc-bi-side, .fc-bi.is-side-hidden .fc-bi-split { visibility: hidden; overflow: hidden; padding: 0; border: 0; } +.fc-bi-split { position: relative; cursor: col-resize; touch-action: none; outline: none; } +.fc-bi-split::after { content: ''; position: absolute; top: 0; bottom: 0; left: 2px; width: 2px; border-radius: var(--radius-pill); background: transparent; } +.fc-bi-split:hover::after, .fc-bi-split:focus-visible::after, .fc-bi-split.is-drag::after { background: var(--accent-color); } .fc-bi-media { position: relative; display: grid; place-items: center; min-width: 0; min-height: 0; padding: var(--space-4); overflow: hidden; background: var(--canvas-bg); } .fc-bi-img { max-width: 100%; max-height: 100%; width: auto; height: auto; object-fit: contain; border-radius: var(--radius-md); } .fc-bi-note { max-width: 640px; max-height: 100%; overflow: auto; padding: var(--space-6); border: 1px solid var(--line-2); border-radius: var(--radius-lg); background: var(--surface-1); font-size: var(--fs-18); line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; } @@ -102,7 +108,7 @@ .fc-bi-actions { display: flex; flex-wrap: wrap; gap: var(--space-2); margin-top: auto; } .fc-bi-grip { position: absolute; right: 0; bottom: 0; width: 18px; height: 18px; cursor: nwse-resize; touch-action: none; background: linear-gradient(135deg, transparent 50%, var(--line-3) 50%, var(--line-3) 58%, transparent 58%, transparent 72%, var(--line-3) 72%, var(--line-3) 80%, transparent 80%); } .fc-bi.is-expanded .fc-bi-grip { display: none; } -@container fc-board (max-width: 720px) { .fc-bi-body { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) minmax(0, 40%); } .fc-bi-side { border-left: 0; border-top: 1px solid var(--line-1); } } +@container fc-board (max-width: 720px) { .fc-bi-body { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) 0 minmax(0, 40%); } .fc-bi.is-side-hidden .fc-bi-body { grid-template-rows: minmax(0, 1fr) 0 0; } .fc-bi-split { display: none; } .fc-bi-side { border-left: 0; border-top: 1px solid var(--line-1); } } .fc-bp { position: fixed; inset: 0; z-index: var(--z-modal); display: grid; place-items: center; background: #000; color: var(--text-on-accent); outline: none; } .fc-bp[hidden] { display: none; } diff --git a/frontend/src/styles/canvas-generate.css b/frontend/src/styles/canvas-generate.css index bed891e..8a7081f 100644 --- a/frontend/src/styles/canvas-generate.css +++ b/frontend/src/styles/canvas-generate.css @@ -36,6 +36,12 @@ .fc-cg-gen .fc-pb-deck:not(:empty) { padding: var(--space-2) var(--space-3) 0; } .fc-cg-gen .fc-pb-toolbar { flex-wrap: wrap; gap: var(--space-1); padding: 0 var(--space-3) var(--space-1); } .fc-cg-gen .fc-mp-pill { --fc-mp-w: 10rem; } +.fc-cv > [data-slot="right"] .fc-cg-hist { width: 100%; flex: 0 1 auto; min-height: 0; border-radius: var(--radius-md); box-shadow: none; } +.fc-cv > [data-slot="right"] .fc-cg-hist-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(72px, 1fr)); } +@media (max-height: 800px) { + .fc-cg-gen .fc-deck-note { display: none; } + .fc-cg-gen .fc-pb-deck:not(:empty) { padding-top: var(--space-1); } +} .fc-cg-note { margin: var(--space-1) 0 0; color: var(--text-muted); font-size: var(--fs-11); line-height: 1.4; } .fc-cg-note[hidden] { display: none; } @@ -100,3 +106,8 @@ .fc-cg-pk-card.is-selected .fc-cg-pk-tick { display: grid; } .fc-cg-pk-note { margin: 0; } .fc-cg-pk-note[hidden] { display: none; } +@media (max-height: 820px) { + .fc-cg-gen:not(:focus-within) .fc-cg-what, .fc-cg-gen:not(:focus-within) .fc-pb:not(.is-expanded) .fc-pb-deck, .fc-cg-gen:not(:focus-within) .fc-pb:not(.is-expanded) .fc-pb-foot { display: none; } + .fc-cg-gen:not(:focus-within) .fc-pb:not(.is-expanded) .fc-pb-main { padding-top: var(--space-2); } + .fc-cg-gen:not(:focus-within) .fc-pb:not(.is-expanded) .fc-ed { min-height: var(--fc-pb-line); max-height: var(--fc-pb-line); overflow: hidden; } +} diff --git a/frontend/src/styles/canvas-review.css b/frontend/src/styles/canvas-review.css new file mode 100644 index 0000000..62cc776 --- /dev/null +++ b/frontend/src/styles/canvas-review.css @@ -0,0 +1,36 @@ +.fc-cg-modes { display: flex; flex-direction: column; gap: var(--space-1); padding: 0 0 var(--space-2); } +.fc-cg-mode-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); } +.fc-cg-mode-group { display: inline-flex; flex-wrap: wrap; gap: var(--space-1); } +.fc-cg-mode { height: var(--ctl-sm); padding: 0 var(--space-3); border: 1px solid var(--line-2); border-radius: var(--radius-pill); background: var(--surface-field); color: var(--text-secondary); font: inherit; font-size: var(--fs-12); cursor: pointer; transition: background var(--transition-fast), border-color var(--transition-fast), color var(--transition-fast); } +.fc-cg-mode:hover { background: var(--bg-hover); color: var(--text-primary); } +.fc-cg-mode.is-on { border-color: var(--accent-line); background: var(--accent-soft); color: var(--accent-ink); } +.fc-cg-mode:focus-visible, .fc-cg-sel:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 2px; } +.fc-cg-ext { display: inline-flex; gap: var(--space-1); } +.fc-cg-ext[data-on="false"] { visibility: hidden; } +.fc-cg-sel { height: var(--ctl-sm); padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--bg-input); color: var(--text-primary); font: inherit; font-size: var(--fs-12); } +.fc-cg-what { margin: 0; min-height: 1.4em; overflow: hidden; color: var(--text-secondary); font-size: var(--fs-12); line-height: 1.4; white-space: nowrap; text-overflow: ellipsis; } + +.fc-cv-slot > .fc-cg-pend-layer { position: absolute; inset: 0; pointer-events: none; overflow: hidden; } +.fc-cg-pend { position: absolute; box-sizing: border-box; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--space-2); border: 2px dashed var(--accent-line); border-radius: var(--radius-sm); background: var(--accent-wash); color: var(--text-primary); font-size: var(--fs-12); pointer-events: none; } +.fc-cg-pend-spin { display: inline-flex; color: var(--accent-ink); } +.fc-cg-pend-spin svg { animation: fc-cg-spin 1s linear infinite; } +.fc-cg-pend-text { padding: var(--space-1) var(--space-2); border-radius: var(--radius-sm); background: var(--glass-bg); font-variant-numeric: tabular-nums; } +.fc-cg-pend-cancel { pointer-events: auto; } +@keyframes fc-cg-spin { to { transform: rotate(360deg); } } +@media (prefers-reduced-motion: reduce) { .fc-cg-pend-spin svg { animation: none; } } + +.fc-cv-slot > .fc-cg-rev-preview { position: absolute; pointer-events: none; object-fit: fill; } +.fc-cv-slot > .fc-cg-rev-preview[hidden] { display: none; } +.fc-cv-slot > .fc-cg-rev { position: absolute; top: var(--space-2); right: var(--space-2); display: flex; flex-direction: column; gap: var(--space-2); width: 12rem; padding: var(--space-2); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); background: var(--glass-bg); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); font-size: var(--fs-12); } +.fc-cv-slot > .fc-cg-rev[hidden] { display: none; } +.fc-cg-rev-head { display: flex; justify-content: space-between; gap: var(--space-2); } +.fc-cg-rev-title { font-weight: 600; } +.fc-cg-rev-count { color: var(--text-secondary); font-variant-numeric: tabular-nums; } +.fc-cg-rev-step { display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: var(--space-1); } +.fc-cg-rev-thumb { width: 100%; aspect-ratio: 1; object-fit: contain; border-radius: var(--radius-sm); background: var(--surface-0); } +.fc-cg-rev-btn { display: inline-grid; place-items: center; width: var(--ctl-sm); height: var(--ctl-sm); padding: 0; } +.fc-cg-rev-compare, .fc-cg-rev-accept, .fc-cg-rev-discard { display: inline-flex; align-items: center; justify-content: center; gap: var(--space-1); width: 100%; touch-action: none; } +.fc-cg-rev.is-before .fc-cg-rev-compare { border-color: var(--accent-line); background: var(--accent-soft); } +.fc-cg-rev-acts { display: flex; flex-direction: column; gap: var(--space-1); } +.fc-cg-rev-accept { border: 1px solid var(--cta-bg); background: var(--cta-bg); color: var(--cta-text); } +.fc-cg-rev-accept:hover:not(:disabled) { background: var(--cta-bg-hover); } diff --git a/frontend/src/styles/canvas-tools.css b/frontend/src/styles/canvas-tools.css index f9a8c30..1b4f6ed 100644 --- a/frontend/src/styles/canvas-tools.css +++ b/frontend/src/styles/canvas-tools.css @@ -40,3 +40,17 @@ .fc-cvt-mini { display: grid; place-items: center; width: var(--ctl-md); height: var(--ctl-md); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-secondary); cursor: pointer; } .fc-cvt-mini:hover { background: var(--bg-hover); color: var(--text-primary); } .fc-cvt-mini:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -2px; } + +.fc-cvt-select, .fc-cvt-num { height: var(--ctl-md); min-width: 0; padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--surface-field); color: var(--text-primary); font: inherit; font-size: var(--fs-12); } +.fc-cvt-num { width: 72px; font-family: var(--font-mono); font-variant-numeric: tabular-nums; } +.fc-cvt-row:has(> .fc-cvt-select), .fc-cvt-row:has(> .fc-cvt-num) { grid-template-columns: 76px minmax(0, 1fr); } +.fc-cvt-select:focus-visible, .fc-cvt-num:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -1px; } +.fc-cvt-cropbar, .fc-cvt-regionbar { width: auto; white-space: nowrap; } +.fc-cvt-regionbar .fc-cvt-range { flex: 0 0 96px; } +.fc-cvt-note { font-size: var(--fs-11); color: var(--text-muted); min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.fc-cvt-railbtn { flex: 0 0 auto; color: var(--text-muted); } +.fc-cv[data-rail="closed"] .fc-cvt-strip, .fc-cv[data-rail="closed"] .fc-cvt-reset, .fc-cv[data-rail="closed"] .fc-cvt-pop, .fc-cv[data-rail="closed"] .fc-cvt-shapecolour { display: none; } +.fc-cv[data-rail="closed"] > [data-slot="left"] { padding: var(--space-1); } +.fc-cv[data-rail="closed"] .fc-cvt-railbtn { color: var(--accent-ink); } + +.fc-cv-textedit { position: absolute; left: 0; top: 0; z-index: var(--z-raised); margin: 0; padding: 0; border: 0; outline: 1px dashed var(--accent-color); outline-offset: 2px; background: transparent; resize: none; overflow: hidden; white-space: pre; transform-origin: 0 0; caret-color: var(--accent-color); } diff --git a/frontend/src/styles/canvas.css b/frontend/src/styles/canvas.css index 505f404..ab1c2b0 100644 --- a/frontend/src/styles/canvas.css +++ b/frontend/src/styles/canvas.css @@ -1,4 +1,6 @@ -.fc-cv { position: relative; flex: 1 1 auto; min-width: 0; min-height: 0; overflow: hidden; isolation: isolate; background: var(--canvas-bg); color: var(--text-primary); } +.fc-cv { --cv-right-w: 264px; position: relative; flex: 1 1 auto; min-width: 0; min-height: 0; overflow: hidden; isolation: isolate; background: var(--canvas-bg); color: var(--text-primary); display: grid; grid-template-columns: auto minmax(0, 1fr) var(--cv-right-w); grid-template-rows: auto minmax(0, 1fr) auto auto; grid-template-areas: "left top right" "left stage right" "left bottom right" "left status right"; } +.fc-cv[data-right="closed"] { grid-template-columns: auto minmax(0, 1fr) var(--ctl-md); } +.fc-cv[data-empty="true"] { grid-template-columns: 0 minmax(0, 1fr) 0; } .fc-cv [hidden] { display: none; } .fc-cv-boot { position: absolute; inset: 0; z-index: var(--z-temp); display: grid; place-content: center; justify-items: center; gap: var(--space-2); padding: var(--space-6); text-align: center; pointer-events: none; } @@ -9,20 +11,36 @@ .fc-cv-retry:hover { background: var(--bg-hover); } .fc-cv-retry:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 2px; } -.fc-cv-stage { position: absolute; inset: 0; z-index: var(--z-base); overflow: hidden; background: var(--canvas-bg); } +.fc-cv-stage { position: relative; grid-area: stage; min-width: 0; min-height: 0; z-index: var(--z-base); overflow: hidden; background: var(--canvas-bg); } .fc-cv-view { position: absolute; inset: 0; display: block; width: 100%; height: 100%; outline: none; touch-action: none; user-select: none; -webkit-user-select: none; } .fc-cv[data-empty="true"] .fc-cv-view, .fc-cv[data-empty="true"] .fc-cv-zoom, .fc-cv[data-empty="true"] .fc-cv-ring { display: none; } .fc-cv-slot { pointer-events: none; } .fc-cv-slot > * { pointer-events: auto; } -.fc-cv > .fc-cv-slot, .fc-cv-stage > .fc-cv-slot { position: absolute; } +.fc-cv-stage > .fc-cv-slot, .fc-cv > [data-slot="modal"] { position: absolute; } .fc-cv-stage > [data-slot="overlay"] { inset: 0; z-index: var(--z-selected); } -.fc-cv > [data-slot="left"] { z-index: var(--z-rail); left: var(--space-3); top: 50%; translate: 0 -50%; display: flex; flex-direction: column; max-height: calc(100% - 2 * var(--space-8)); } -.fc-cv > [data-slot="right"] { z-index: var(--z-rail); right: var(--space-3); top: 50%; translate: 0 -50%; display: flex; flex-direction: column; max-height: calc(100% - 2 * var(--space-8)); } -.fc-cv > [data-slot="top"] { z-index: var(--z-rail); top: var(--space-3); left: 50%; translate: -50% 0; display: flex; flex-direction: column; align-items: center; gap: var(--space-2); max-width: calc(100% - 2 * var(--space-8)); } -.fc-cv > [data-slot="bottom"] { z-index: var(--z-rail); left: 50%; bottom: var(--space-3); translate: -50% 0; display: flex; flex-direction: column; align-items: center; gap: var(--space-2); width: min(90%, 48rem); } +.fc-cv > .fc-cv-slot:not([data-slot="modal"]) { position: relative; z-index: var(--z-rail); min-width: 0; min-height: 0; } +.fc-cv > [data-slot="left"] { grid-area: left; display: flex; flex-direction: column; justify-content: flex-start; padding: var(--space-2); border-right: 1px solid var(--line-1); background: var(--bg-secondary); overflow: auto; } +.fc-cv > [data-slot="right"] { grid-area: right; display: flex; flex-direction: column; gap: var(--space-2); padding: var(--space-2); border-left: 1px solid var(--line-1); background: var(--bg-secondary); overflow: auto; } +.fc-cv > [data-slot="top"] { grid-area: top; display: flex; flex-direction: column; align-items: center; gap: var(--space-2); padding: var(--space-2); border-bottom: 1px solid var(--line-1); background: var(--bg-secondary); } +.fc-cv > [data-slot="bottom"] { grid-area: bottom; display: flex; flex-direction: column; align-items: center; gap: var(--space-2); padding: var(--space-2); border-top: 1px solid var(--line-1); background: var(--bg-secondary); } +.fc-cv > [data-slot="bottom"] > * { width: min(100%, 48rem); } .fc-cv > [data-slot="modal"] { z-index: var(--z-chrome); inset: 0; } -.fc-cv[data-empty="true"] > [data-slot="left"], .fc-cv[data-empty="true"] > [data-slot="top"] { visibility: hidden; } +.fc-cv[data-empty="true"] > [data-slot="left"], .fc-cv[data-empty="true"] > [data-slot="top"], .fc-cv[data-empty="true"] > [data-slot="right"] { display: none; } +.fc-cv[data-right="closed"] > [data-slot="right"] > :not(.fc-cv-colbar) { display: none; } +.fc-cv-colbar { display: flex; align-items: center; gap: var(--space-1); } +.fc-cv-colbar-title { flex: 1 1 auto; font-size: var(--fs-12); font-weight: 600; color: var(--text-secondary); } +.fc-cv[data-right="closed"] .fc-cv-colbar { flex-direction: column; } +.fc-cv[data-right="closed"] .fc-cv-colbar-title, .fc-cv[data-right="closed"] .fc-cv-colbar [data-act="reset"] { display: none; } +.fc-cv[data-right="closed"] > [data-slot="right"] { padding: var(--space-1); } +.fc-cv-grip { position: absolute; left: -3px; top: 0; bottom: 0; width: 6px; cursor: col-resize; z-index: var(--z-raised); } +.fc-cv-grip:hover, .fc-cv-grip.is-drag { background: var(--accent-line); } +.fc-cv[data-right="closed"] .fc-cv-grip { display: none; } +.fc-cv-status { grid-area: status; display: flex; align-items: center; gap: var(--space-3); min-height: var(--ctl-md); padding: 0 var(--space-3); border-top: 1px solid var(--line-1); background: var(--bg-secondary); font-size: var(--fs-11); color: var(--text-muted); white-space: nowrap; overflow: hidden; } +.fc-cv-status b { font-weight: 600; color: var(--text-secondary); } +.fc-cv[data-empty="true"] .fc-cv-status, .fc-cv > [data-slot="bottom"]:not(:has(> :not([hidden]))) { display: none; } +.fc-cv-status-nav { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.fc-cv-stage[data-space="true"] .fc-cv-view { cursor: grab; } .fc-cv-zoom { position: absolute; left: var(--space-3); bottom: var(--space-3); z-index: var(--z-rail); display: flex; align-items: center; gap: 2px; padding: 2px; border: 1px solid var(--glass-border); border-radius: var(--radius-lg); background: var(--glass-bg); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); } .fc-cv-zbtn, .fc-cv-zval { height: var(--ctl-md); min-width: var(--ctl-md); padding: 0 var(--space-2); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-secondary); font-size: var(--fs-12); font-variant-numeric: tabular-nums; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; } @@ -35,3 +53,28 @@ .fc-cv-ring[data-tool="eraser"] { border-color: var(--bg-primary); background: color-mix(in srgb, var(--text-primary) 28%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--text-primary) 55%, transparent); } .fc-cv-menu { min-width: 220px; } + +.fc-cv > .fc-md { grid-area: stage; } +.fc-cv-layers { display: flex; flex-direction: column; gap: var(--space-1); min-height: 0; flex: 0 1 auto; } +.fc-cv-layer-list { display: flex; flex-direction: column; gap: 2px; max-height: 40vh; overflow: auto; outline: none; } +.fc-cv-layer-empty { margin: 0; padding: var(--space-2); font-size: var(--fs-12); color: var(--text-muted); } +.fc-cv-layer { display: flex; align-items: center; gap: var(--space-2); min-height: var(--ctl); padding: 2px var(--space-1); border: 1px solid transparent; border-radius: var(--radius); font-size: var(--fs-12); color: var(--text-secondary); cursor: default; user-select: none; } +.fc-cv-layer:hover { background: var(--bg-hover); } +.fc-cv-layer.is-on { background: var(--accent-tint); border-color: var(--accent-line); color: var(--text-primary); } +.fc-cv-layer.is-hidden .fc-cv-layer-thumb, .fc-cv-layer.is-hidden .fc-cv-layer-name { opacity: 0.45; } +.fc-cv-layer-thumb { flex: 0 0 auto; display: grid; place-items: center; width: 28px; height: 28px; overflow: hidden; border: 1px solid var(--line-1); border-radius: var(--radius-sm); background: var(--surface-field); color: var(--text-secondary); } +.fc-cv-layer-thumb img { width: 100%; height: 100%; object-fit: cover; } +.fc-cv-layer-name { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; outline: none; } +.fc-cv-layer-name[contenteditable="plaintext-only"] { padding: 0 2px; background: var(--bg-input); box-shadow: 0 0 0 1px var(--accent-color); text-overflow: clip; } +.fc-cv-layer-btn { flex: 0 0 auto; display: grid; place-items: center; width: var(--ctl-sm); height: var(--ctl-sm); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-muted); cursor: pointer; } +.fc-cv-layer-btn:hover { background: var(--bg-hover); color: var(--text-primary); } +.fc-cv-layer-btn[data-act="eye"][data-on="false"], .fc-cv-layer-btn[data-act="lock"][data-on="true"] { color: var(--accent-color); } +.fc-cv-layer-btn:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -2px; } +.fc-cv-layer-acts { display: flex; flex-wrap: wrap; gap: 2px; justify-content: flex-end; } +.fc-cv-layer.is-grouped { margin-left: var(--space-3); box-shadow: inset 2px 0 0 var(--accent-line); } +.fc-cv-layer-props { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) 36px; align-items: center; gap: var(--space-2); } +.fc-cv-layer-blend { height: var(--ctl-md); min-width: 0; padding: 0 var(--space-1); border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--surface-field); color: var(--text-primary); font: inherit; font-size: var(--fs-12); } +.fc-cv-layer-blend:disabled, .fc-cv-layer-alpha:disabled { opacity: 0.4; } +.fc-cv-layer-alpha { width: 100%; min-width: 0; accent-color: var(--accent-color); } +.fc-cv-layer-alphaval { font-family: var(--font-mono); font-size: var(--fs-11); color: var(--text-secondary); text-align: right; } +.fc-cv-layer-acts button:disabled { opacity: 0.4; cursor: default; } diff --git a/frontend/src/styles/create.css b/frontend/src/styles/create.css index fce7244..eb0a233 100644 --- a/frontend/src/styles/create.css +++ b/frontend/src/styles/create.css @@ -24,6 +24,12 @@ .fc-cr-mark { display: grid; place-items: center; width: 48px; height: 48px; margin-bottom: var(--space-2); border: 1px solid var(--accent-line); border-radius: var(--radius-xl); background: var(--accent-wash); color: var(--accent-color); } .fc-cr-title { margin: 0; color: var(--text-primary); font-size: var(--fs-24); font-weight: 600; letter-spacing: -0.01em; } .fc-cr-sub { max-width: 440px; margin: 0; color: var(--text-muted); font-size: var(--fs-14); line-height: 1.5; } +.fc-cr-key { display: flex; flex-direction: column; align-items: center; gap: var(--space-2); max-width: 460px; margin-top: var(--space-3); padding: var(--space-3) var(--space-4); border: 1px solid var(--border-soft); border-radius: var(--radius-xl); background: var(--surface-raised); pointer-events: auto; } +.fc-cr-key[hidden] { display: none; } +.fc-cr-key-t { margin: 0; color: var(--text-secondary); font-size: var(--fs-13); line-height: 1.5; } +.fc-cr-key-a { display: flex; flex-wrap: wrap; justify-content: center; gap: var(--space-2); } +.fc-cr-key-get { text-decoration: none; } +.fc-cr .fc-pb-toolbar .fc-mp-pill { width: auto; min-width: var(--fc-mp-w, 184px); max-width: min(100%, 28rem); } .fc-cr-feed { position: absolute; inset: 0; min-width: 0; min-height: 0; } @@ -57,19 +63,25 @@ .fc-cr-note { margin: var(--space-1) 0 0; color: var(--text-muted); font-size: var(--fs-11); line-height: 1.4; } .fc-cr-note[hidden] { display: none; } +.fc-cr { --fc-cr-top-h: calc(var(--ctl-md) + 2 * var(--space-2) + 1px); } +.fc-cr-feed, .fc-cr-head { top: var(--fc-cr-top-h); } +.fc-cr-head:has(.fc-cr-key:not([hidden])) > .fc-demo-link { visibility: hidden; } .fc-cr-pages { + position: absolute; + top: 0; + right: 0; + left: 0; + z-index: var(--z-rail); display: flex; - flex-wrap: wrap; + flex-wrap: nowrap; justify-content: center; + align-items: center; gap: 2px; - max-width: 100%; - padding: 3px; - border: 1px solid var(--glass-border); - border-radius: var(--radius-pill); - background: var(--glass-bg); - box-shadow: var(--shadow-sm); - -webkit-backdrop-filter: var(--glass-filter); - backdrop-filter: var(--glass-filter); + height: var(--fc-cr-top-h); + padding: 0 var(--space-3); + overflow-x: auto; + border-bottom: 1px solid var(--border-color); + background: var(--bg-secondary); } .fc-cr-pg { display: inline-flex; align-items: center; gap: var(--space-2); height: var(--ctl-md); padding: 0 var(--space-3); border: 0; border-radius: var(--radius-pill); background: transparent; color: var(--text-secondary); font: inherit; font-size: var(--fs-12); white-space: nowrap; cursor: pointer; transition: color var(--transition-fast), background var(--transition-fast); } .fc-cr-pg:hover { background: var(--bg-hover); color: var(--text-primary); } @@ -114,6 +126,10 @@ body.theme-light .fc-cost-warn { color: color-mix(in srgb, var(--warn) 42%, var(--text-primary)); } +@media (max-height: 800px) { + .fc-cr-mark { display: none; } +} + @media (max-width: 900px) { .fc-cr-row { display: flex; flex-wrap: wrap; justify-content: center; gap: var(--space-2); } } diff --git a/frontend/src/styles/dialogs.css b/frontend/src/styles/dialogs.css index acfb53a..52eb242 100644 --- a/frontend/src/styles/dialogs.css +++ b/frontend/src/styles/dialogs.css @@ -58,17 +58,17 @@ select.cv-input { padding-right: var(--space-1); } .cv-theme-swatch { width: 28px; height: 28px; padding: 0; border: 2px solid var(--border-color); border-radius: var(--radius-pill); cursor: pointer; } .cv-theme-swatch.is-active { border-width: 2px; } -.cv-toast { display: grid; grid-template-columns: 16px minmax(0, 1fr) auto 18px; align-items: start; column-gap: var(--space-2); max-width: 380px; padding: var(--space-2) var(--space-2) var(--space-2) var(--space-3); border: 1px solid var(--border-light); border-radius: var(--radius-md); background: var(--bg-secondary); box-shadow: var(--shadow-lg); color: var(--text-primary); font-size: var(--fs-12); pointer-events: auto; transition: opacity 160ms ease; } +.cv-toast { display: grid; grid-template-columns: 16px minmax(0, 1fr) auto 18px; align-items: center; column-gap: var(--space-2); flex: 0 1 auto; min-width: 0; max-width: 480px; padding: var(--space-1) var(--space-2) var(--space-1) var(--space-3); border: 1px solid var(--border-light); border-radius: var(--radius-md); background: var(--bg-secondary); box-shadow: var(--shadow-lg); color: var(--text-primary); font-size: var(--fs-12); pointer-events: auto; transition: opacity 160ms ease; } .cv-toast.is-leaving { opacity: 0; pointer-events: none; } .cv-toast-icon { display: grid; place-items: center; height: 18px; color: var(--text-secondary); } .cv-toast[data-kind="success"] .cv-toast-icon { color: var(--ok); } .cv-toast[data-kind="warning"] .cv-toast-icon { color: var(--warn); } .cv-toast[data-kind="error"] { border-color: var(--danger-fill); } .cv-toast[data-kind="error"] .cv-toast-icon { color: var(--danger-soft); } -.cv-toast-text { min-width: 0; padding-top: 2px; overflow-wrap: anywhere; white-space: pre-line; line-height: 1.4; } +.cv-toast-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1.4; } .cv-toast-actions { display: flex; gap: var(--space-1); } .cv-toast-actions:empty { display: none; } -.cv-toast-action { height: 22px; padding: 0 var(--space-2); border: 1px solid var(--border-light); border-radius: var(--radius-sm); background: var(--bg-tertiary); color: var(--text-primary); font: inherit; font-size: var(--fs-11); cursor: pointer; } +.cv-toast-action { height: 20px; padding: 0 var(--space-2); border: 1px solid var(--border-light); border-radius: var(--radius-sm); background: var(--bg-tertiary); color: var(--text-primary); font: inherit; font-size: var(--fs-11); cursor: pointer; } .cv-toast-action:hover { background: var(--bg-hover); } .cv-toast-close { display: grid; place-items: center; width: 18px; height: 18px; padding: 0; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-muted); cursor: pointer; } .cv-toast-close:hover { background: var(--bg-hover); color: var(--text-primary); } diff --git a/frontend/src/styles/edit-panels.css b/frontend/src/styles/edit-panels.css index 30e9904..d98efda 100644 --- a/frontend/src/styles/edit-panels.css +++ b/frontend/src/styles/edit-panels.css @@ -167,6 +167,9 @@ textarea.fc-ep-text { width: 100%; } .fc-ea-sample { width: 100%; height: 100%; background: linear-gradient(135deg, var(--fc-mn-image-1), var(--fc-mn-image-4) 55%, var(--fc-mn-video-3)); } .fc-ea-sample::after { content: ''; display: block; width: 46%; height: 46%; margin: 27% auto 0; border: 3px solid var(--text-primary); border-radius: 50%; } .fc-ea-textart { padding: var(--space-1); max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: var(--fs-14); line-height: 1.1; } +.fc-ea-tpl[data-tpl="lower-third"] { place-items: end start; padding: 0 0 12% 8%; } +.fc-ea-tpl[data-tpl="lower-third"] .fc-ea-textart { font-size: var(--fs-11); } +.fc-ea-tpl[data-tpl="end-card"] .fc-ea-textart { font-size: var(--fs-12); } .fc-ea-block { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); padding: var(--space-1) 0; } .fc-ea-block .fc-ea-chip { height: var(--ctl-sm); } diff --git a/frontend/src/styles/edit-preview.css b/frontend/src/styles/edit-preview.css index c1b8d7e..e0bc88c 100644 --- a/frontend/src/styles/edit-preview.css +++ b/frontend/src/styles/edit-preview.css @@ -54,6 +54,9 @@ .fc-pv-menu[hidden] { display: none; } .fc-pv-item { display: block; width: 100%; height: var(--ctl-md); padding: 0 var(--space-3); border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-primary); font: inherit; text-align: left; cursor: pointer; } .fc-pv-item:hover, .fc-pv-item:focus-visible { background: var(--bg-hover); outline: none; } +.fc-pv-item[aria-checked="true"] { color: var(--accent-color); } +.fc-pv-menu-sep { height: 1px; margin: var(--space-1) 0; background: var(--line-1); } +.fc-pv-menu-head { padding: var(--space-1) var(--space-3); color: var(--text-muted); font-size: var(--fs-11); white-space: nowrap; } .fc-pv-bar { container-type: inline-size; } @container (max-width: 560px) { diff --git a/frontend/src/styles/edit-timeline.css b/frontend/src/styles/edit-timeline.css index 3df044f..75069f5 100644 --- a/frontend/src/styles/edit-timeline.css +++ b/frontend/src/styles/edit-timeline.css @@ -8,6 +8,21 @@ .fc-etl-tb-sep { width: 1px; height: 16px; margin: 0 6px; background: var(--line-2); } .fc-etl-tb-fill { flex: 1; } .fc-etl-zoom { width: 120px; margin: 0 var(--space-1); accent-color: var(--accent-color); } +.fc-etl-tb-fill { display: flex; min-width: 0; } +.fc-etl-hint { flex: 1; min-width: 0; padding: 0 var(--space-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-11); color: var(--text-muted); } +.fc-etl-range { position: absolute; left: 0; top: 0; height: 22px; width: 0; background: var(--accent-wash); box-shadow: inset 2px 0 0 var(--accent-color), inset -2px 0 0 var(--accent-color); pointer-events: none; will-change: transform; } +.fc-etl-range[hidden], .fc-etl-empty[hidden] { display: none; } +.fc-etl-empty { grid-column: 2; grid-row: 2; align-self: start; justify-self: center; position: relative; z-index: var(--z-raised); display: flex; align-items: center; gap: var(--space-3); margin-top: var(--space-4); padding: var(--space-2) var(--space-3); border: 1px dashed var(--line-2); border-radius: var(--radius-lg); background: var(--surface-1); color: var(--text-secondary); pointer-events: none; } +.fc-etl-empty p { margin: 0; } +.fc-etl-empty .cv-btn { pointer-events: auto; } +.fc-etl-fadeband { position: absolute; top: 0; bottom: 0; pointer-events: none; background: color-mix(in srgb, var(--surface-0) 55%, transparent); } +.fc-etl-fadeband.is-in { left: 0; width: var(--fi, 0px); clip-path: polygon(0 0, 0 100%, 100% 0); } +.fc-etl-fadeband.is-out { right: 0; width: var(--fo, 0px); clip-path: polygon(0 0, 100% 0, 100% 100%); } +.fc-etl-fade { position: absolute; top: -3px; z-index: var(--z-raised); width: 10px; height: 10px; margin-left: -5px; border-radius: 50%; border: 1px solid var(--surface-0); background: var(--text-primary); cursor: ew-resize; visibility: hidden; } +.fc-etl-fade.is-in { left: calc(var(--fi, 0px) + 8px); } +.fc-etl-fade.is-out { left: calc(100% - var(--fo, 0px) - 8px); } +.fc-etl-clip:hover .fc-etl-fade, .fc-etl-clip.is-selected .fc-etl-fade { visibility: visible; } +.fc-etl-clip.is-narrow .fc-etl-fade { display: none; } .fc-etl-body { position: relative; display: grid; flex: 1; min-height: 0; grid-template-columns: 112px minmax(0, 1fr); grid-template-rows: 38px minmax(0, 1fr); align-content: start; } .fc-etl-corner { grid-column: 1; grid-row: 1; border-right: 1px solid var(--line-1); border-bottom: 1px solid var(--line-1); } @@ -24,6 +39,10 @@ .fc-etl-labels-in { position: relative; width: 100%; will-change: transform; } .fc-etl-label { position: absolute; left: 0; right: 0; display: flex; align-items: flex-start; gap: 2px; padding: max(0px, calc((var(--base) - 22px) / 2)) 4px 0 2px; } .fc-etl-label.is-off .fc-etl-lname { color: var(--text-muted); } +.fc-etl-label[data-tall="true"] { flex-wrap: wrap; align-content: flex-start; row-gap: 2px; padding-top: max(0px, calc((var(--base) - 46px) / 2)); } +.fc-etl-label[data-tall="true"] .fc-etl-lname { flex: 1 0 calc(100% - 26px); } +.fc-etl-lgrip { position: absolute; left: 0; right: 0; bottom: -4px; height: 7px; cursor: ns-resize; } +.fc-etl-lgrip:hover { background: color-mix(in srgb, var(--accent-color) 40%, transparent); } .fc-etl-lname { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 22px; color: var(--text-secondary); } .fc-etl-lbtn { display: inline-flex; align-items: center; justify-content: center; flex: none; width: 22px; height: 22px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-muted); cursor: default; } .fc-etl-lbtn[hidden] { display: none; } @@ -39,6 +58,20 @@ .fc-etl-lane { position: absolute; left: 0; width: 100%; background: color-mix(in srgb, var(--surface-2) 60%, transparent); border-radius: var(--radius-sm); } .fc-etl-lane.is-drop { background: var(--accent-wash); box-shadow: inset 0 0 0 1px var(--accent-line); } .fc-etl-krows { position: absolute; left: 0; right: 0; top: var(--base); } +.fc-etl-lane.is-locked { background-image: repeating-linear-gradient(135deg, transparent 0 6px, color-mix(in srgb, var(--line-2) 55%, transparent) 6px 7px); } +.fc-etl-lane.is-locked .fc-etl-clip .fc-etl-handle, .fc-etl-lane.is-locked .fc-etl-clip .fc-etl-fade { display: none; } +.fc-etl-cuts { position: absolute; left: 0; top: 0; width: 0; height: var(--base); z-index: var(--z-raised); pointer-events: none; } +.fc-etl-xd { position: absolute; top: 0; width: 0; height: 100%; } +.fc-etl-xd-add { position: absolute; left: -8px; top: 2px; display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; padding: 0; border: 1px solid var(--line-2); border-radius: var(--radius-pill); background: var(--surface-raised); color: var(--text-secondary); visibility: hidden; pointer-events: auto; cursor: default; } +.fc-etl-xd-add:hover { color: var(--accent-ink); border-color: var(--accent-line); } +.fc-etl-lane:hover .fc-etl-xd-add { visibility: visible; } +.fc-etl-xd.is-on .fc-etl-xd-add { display: none; } +.fc-etl-xd-band { position: absolute; top: calc(50% - 8px); left: calc(var(--xw, 0px) / -2); display: none; width: var(--xw, 0px); height: 16px; overflow: visible; border: 1px solid var(--accent-line); border-radius: var(--radius-sm); background: color-mix(in srgb, var(--accent-color) 30%, var(--surface-2)); background-image: linear-gradient(to top right, transparent calc(50% - 1px), var(--accent-ink) 50%, transparent calc(50% + 1px)), linear-gradient(to bottom right, transparent calc(50% - 1px), var(--accent-ink) 50%, transparent calc(50% + 1px)); pointer-events: auto; } +.fc-etl-xd.is-on .fc-etl-xd-band { display: block; } +.fc-etl-xd-grip { position: absolute; top: -2px; bottom: -2px; width: 6px; border-radius: var(--radius-xs); background: var(--accent-color); cursor: ew-resize; } +.fc-etl-xd-grip.is-l { left: -3px; } +.fc-etl-xd-grip.is-r { right: -3px; } +.fc-etl-xd-label { position: absolute; left: 50%; bottom: calc(100% + 1px); transform: translateX(-50%); color: var(--text-primary); font-size: var(--fs-10); white-space: nowrap; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.7); pointer-events: none; } .fc-etl-krow { position: relative; height: 20px; border-top: 1px dashed var(--line-1); } .fc-etl-clip { --c: var(--fc-mn-video-1); --wave: var(--fc-mn-audio-1); position: absolute; top: 0; height: var(--base); border-radius: var(--radius-sm); box-shadow: 0 0 0 0 transparent; } diff --git a/frontend/src/styles/edit.css b/frontend/src/styles/edit.css index 047ace0..6a74720 100644 --- a/frontend/src/styles/edit.css +++ b/frontend/src/styles/edit.css @@ -47,10 +47,5 @@ .fc-ed-lock-note { min-height: 1.5em; font-variant-numeric: tabular-nums; } .fc-ed-bar { align-self: stretch; height: 4px; overflow: hidden; border-radius: var(--radius-pill); background: var(--line-1); } .fc-ed-bar-fill { display: block; width: 100%; height: 100%; background: var(--accent-color); transform: scaleX(0); transform-origin: left center; } -.fc-ed-dots { display: flex; gap: var(--space-2); } -.fc-ed-dots span { width: 6px; height: 6px; border-radius: var(--radius-pill); background: var(--line-3); } -.fc-ed-dots span.is-on { background: var(--accent-color); } .fc-ed-card-title + p { min-height: 4.5em; } -.fc-ed-ob-actions { display: flex; justify-content: flex-end; gap: var(--space-2); align-self: stretch; } -.fc-ed-ob-actions [data-act="ob-skip"] { margin-right: auto; } @media (prefers-reduced-motion: reduce) { .fc-ed-boot { transition: none; } } diff --git a/frontend/src/styles/feed.css b/frontend/src/styles/feed.css index 0b0ad05..8df270d 100644 --- a/frontend/src/styles/feed.css +++ b/frontend/src/styles/feed.css @@ -7,7 +7,8 @@ .fc-top { position: sticky; top: 0; z-index: var(--z-selected); height: 0; max-width: var(--fc-feed-max); margin: 0 auto; pointer-events: none; } .fc-top-row { position: absolute; top: var(--space-2); right: var(--space-4); left: var(--space-4); display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: center; gap: var(--space-2); } .fc-top-row > * { pointer-events: auto; } -.fc-selbar { grid-column: 1; justify-self: start; } +.fc-selwrap { position: sticky; bottom: calc(var(--fc-feed-clear, 220px) - var(--space-4)); z-index: var(--z-selected); display: flex; justify-content: center; height: 0; pointer-events: none; } +.fc-selbar { flex: none; height: max-content; transform: translateY(-100%); pointer-events: auto; } .fc-newbtn { grid-column: 2; } .fc-tools { grid-column: 3; justify-self: end; } .fc-tools, .fc-selbar { display: flex; align-items: center; gap: 2px; padding: 3px; border: 1px solid var(--glass-border); border-radius: var(--radius-lg); background: var(--glass-bg); box-shadow: var(--shadow-sm); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); } @@ -67,6 +68,8 @@ .fc-card[data-state='pending'] .fc-bad, .fc-card[data-state='failed'] .fc-spin { display: none; } .fc-card[data-state='failed'] .fc-mark { color: var(--danger-soft); } .fc-stage { min-height: 1.3em; color: var(--text-primary); font-size: var(--fs-12); font-weight: 500; } +.fc-cost { color: var(--text-muted); font-size: var(--fs-11); font-variant-numeric: tabular-nums; } +.fc-card[data-state='failed'] .fc-cost, .fc-card[data-state='media'] .fc-cost { display: none; } .fc-clock, .fc-pct { min-height: 1.3em; color: var(--text-muted); font-size: var(--fs-11); font-variant-numeric: tabular-nums; } .fc-pct { color: var(--text-secondary); font-family: var(--font-mono); } .fc-feed[data-view='grid'] .fc-stage, .fc-feed[data-view='grid'] .fc-clock, .fc-feed[data-view='grid'] .fc-pct { align-self: stretch; } diff --git a/frontend/src/styles/home.css b/frontend/src/styles/home.css index 277cc6b..ebdce20 100644 --- a/frontend/src/styles/home.css +++ b/frontend/src/styles/home.css @@ -33,19 +33,23 @@ .cv-home-open-list { display: flex; flex-direction: column; gap: 2px; } .cv-home-ver { flex: none; color: var(--text-muted); font-size: var(--fs-11); font-variant-numeric: tabular-nums; } -.cv-home-nav { display: flex; flex-direction: column; gap: 2px; min-height: 0; padding: var(--space-4) var(--space-3) var(--space-3); background: var(--surface-0); border-right: 1px solid var(--line-0); overflow-y: auto; } -.cv-home-brand { display: flex; align-items: center; gap: var(--space-2); flex: none; height: var(--ctl-lg); margin-bottom: var(--space-3); padding: var(--space-2) var(--space-2) 0; color: var(--text-primary); font-size: var(--fs-16); font-weight: 600; letter-spacing: -0.005em; } -.cv-home-brand span { color: var(--text-muted); font-size: var(--fs-12); font-weight: 400; letter-spacing: 0; } +.cv-home-nav { display: flex; flex-direction: column; gap: 2px; min-height: 0; padding: 14px 10px var(--space-3); background: var(--surface-0); border-right: 1px solid var(--line-0); overflow-y: auto; } +.cv-home-brand { display: flex; align-items: center; gap: var(--space-3); flex: none; height: var(--ctl-lg); margin-bottom: var(--space-3); padding: 0 var(--space-2); color: var(--text-primary); font-size: 15px; font-weight: 600; letter-spacing: -0.005em; } +.cv-home-brand-mark { flex: none; width: 26px; height: 26px; border-radius: var(--radius); } +.cv-home-brand-name { flex: none; } +.cv-brand-mark { display: block; flex: none; width: 20px; height: 20px; border-radius: var(--radius-sm); transition: filter var(--transition-fast); } +.cv-brand[role="button"]:hover .cv-brand-mark { filter: brightness(1.12); } +.cv-home-brand-by { min-width: 0; color: var(--text-muted); font-size: var(--fs-12); font-weight: 400; line-height: 1.25; letter-spacing: 0; } .cv-home-nav-title { padding: var(--space-3) var(--space-3) var(--space-2); color: var(--text-muted); font-size: var(--fs-11); font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; } -.cv-home-nav-item { display: flex; align-items: center; gap: var(--space-3); flex: none; height: var(--ctl-lg); padding: 0 var(--space-3); border: 1px solid transparent; border-radius: var(--radius-md); background: transparent; color: var(--text-secondary); font: inherit; font-size: var(--fs-13); text-align: left; cursor: pointer; } +.cv-home-nav-item { display: flex; align-items: center; gap: 10px; flex: none; height: 34px; padding: 0 10px; border: 1px solid transparent; border-radius: var(--radius-md); background: transparent; color: var(--text-secondary); font: inherit; font-size: var(--fs-13); text-align: left; cursor: pointer; } .cv-home-nav-item[hidden] { display: none; } .cv-home-nav-item:hover { background: var(--surface-1); color: var(--text-primary); } -.cv-home-nav-item.is-active { border-color: var(--line-2); background: var(--surface-2); color: var(--text-primary); } -.cv-home-nav-item.is-active .icon { color: var(--accent-color); } +.cv-home-nav-item.is-active { border-color: var(--line-3); background: var(--surface-raised); color: var(--text-primary); box-shadow: inset 0 1px 0 var(--glass-highlight); } +.cv-home-nav-item.is-active .icon { color: var(--accent-ink); } .cv-home-nav-item:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } .cv-home-nav-item > .icon, .cv-home-hero-icon > .icon { flex: none; } .cv-home-nav-item > span:not(.cv-home-count):not(.cv-home-ver):not(.icon) { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.cv-home-count { min-width: 28px; padding: 1px 6px; border-radius: var(--radius-pill); background: var(--surface-1); color: var(--text-muted); font-size: var(--fs-11); font-variant-numeric: tabular-nums; text-align: center; } +.cv-home-count { display: inline-flex; align-items: center; justify-content: center; flex: none; min-width: 30px; height: 18px; padding: 0 5px; border: 1px solid var(--line-2); border-radius: var(--radius-pill); background: var(--surface-raised); color: var(--text-secondary); font-family: var(--font-mono); font-size: var(--fs-11); line-height: 1; font-variant-numeric: tabular-nums; } .cv-home-nav-sep { flex: none; height: 1px; margin: var(--space-3) var(--space-2); background: var(--line-1); } .cv-home-nav-foot { display: flex; flex-direction: column; gap: 2px; margin-top: auto; padding-top: var(--space-3); } @@ -80,8 +84,20 @@ .cv-home-action.is-primary .cv-key { background: var(--text-primary); color: var(--cta-text); } .cv-home-section { margin-top: calc(var(--space-8) + var(--space-1)); } -.cv-home-section-head { display: flex; align-items: center; gap: var(--space-3); margin-bottom: var(--space-1); } -.cv-home-section-title { margin: 0 auto 0 0; color: var(--text-primary); font-size: var(--fs-16); font-weight: 600; } +.cv-home-section-head { display: flex; align-items: center; flex-wrap: wrap; gap: 10px var(--space-3); margin-bottom: var(--space-1); } +.cv-home-section-title { margin: 0 6px 0 0; color: var(--text-primary); font-size: 15px; font-weight: 600; } +.fc-home-tools { margin-bottom: var(--space-4); } +.fc-home-chip { display: inline-flex; align-items: center; gap: 6px; flex: none; height: var(--ctl-md); padding: 0 var(--space-3); border: 1px solid var(--line-2); border-radius: var(--radius-pill); background: transparent; color: var(--text-secondary); font: inherit; font-size: var(--fs-12); white-space: nowrap; cursor: pointer; } +.fc-home-chip:hover { border-color: var(--line-3); color: var(--text-primary); } +.fc-home-chip.is-active { border-color: var(--line-3); background: var(--surface-raised); color: var(--text-primary); font-weight: 500; box-shadow: inset 0 1px 0 var(--glass-highlight); } +.fc-home-chip:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fc-home-chip-count { display: inline-block; min-width: 2ch; color: var(--text-muted); font-size: var(--fs-11); font-variant-numeric: tabular-nums; text-align: right; } +.fc-home-chip.is-active .fc-home-chip-count { color: var(--text-secondary); } +.fc-home-search { display: flex; align-items: center; gap: 6px; width: 240px; min-width: 0; height: 30px; margin-left: auto; padding: 0 10px; border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-field); color: var(--text-muted); } +.fc-home-search:focus-within { border-color: var(--accent-color); } +.fc-home-search-input { flex: 1; min-width: 0; height: 100%; border: 0; outline: 0; background: transparent; color: var(--text-primary); font: inherit; font-size: var(--fs-13); } +.fc-home-search-input::placeholder { color: var(--text-muted); } +.fc-home-search-input::-webkit-search-cancel-button { appearance: none; } .fc-home-tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(var(--cv-home-tile), 1fr)); gap: var(--space-3); padding-top: var(--space-3); } .fc-home-tiles.is-studios { grid-template-columns: repeat(auto-fill, minmax(var(--cv-home-studio), 1fr)); } @@ -200,6 +216,81 @@ .cv-home-narrow { display: flex; gap: var(--space-1); margin-bottom: var(--space-4); overflow-x: auto; } .cv-home-main { padding: var(--space-5) var(--space-4) calc(var(--space-8) + var(--space-2)); } .cv-home-hero { grid-template-columns: minmax(0, 1fr); padding: var(--space-5); } + .fc-home-search { width: 100%; margin-left: 0; } .cv-hf-bar { flex-wrap: wrap; } .cv-hf-input { width: 140px; } } + +.fc-home-ask { color: var(--text-primary); font-size: var(--fs-16); font-weight: 500; } +.fc-make-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: var(--space-3); } +@media (max-width: 760px) { .fc-make-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +.fc-make, .fc-home-starter { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto; align-items: start; gap: var(--space-2) var(--space-3); min-height: 108px; padding: var(--space-4); border: 1px solid var(--line-1); border-radius: var(--radius-xl); background: var(--surface-2); color: var(--text-primary); font: inherit; text-align: left; cursor: pointer; transition: border-color var(--transition-fast), background-color var(--transition-fast); } +.fc-make:hover, .fc-home-starter:hover { border-color: var(--accent-color); background: var(--accent-tint); } +.fc-make:focus-visible, .fc-home-starter:focus-visible, .fc-demo-open:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 2px; } +.fc-make-icon { display: grid; place-items: center; width: 44px; height: 44px; border: 1px solid var(--accent-line); border-radius: var(--radius-md); background: var(--accent-wash); color: var(--accent-color); } +.fc-make-text { display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.fc-make-title { color: var(--text-primary); font-size: var(--fs-16); font-weight: 600; } +.fc-make-line { color: var(--text-secondary); font-size: var(--fs-12); line-height: 1.4; } +.fc-make-where { grid-column: 1 / -1; color: var(--text-muted); font-size: var(--fs-11); } +.fc-make-where b { color: var(--text-secondary); font-weight: 600; } +.fc-home-starter { grid-template-columns: auto minmax(0, 1fr) auto; grid-template-rows: auto; align-items: center; width: 100%; min-height: 76px; } +.fc-home-starter > .icon { color: var(--text-muted); } +.fc-make { display: flex; flex-direction: column; gap: var(--space-2); min-height: 150px; } +.fc-make .fc-make-where { margin-top: auto; } +.fc-home-demos:not([hidden]) { animation: fc-home-in var(--transition-normal) both; } +.fc-demo { position: relative; } +.fc-demo-head { display: flex; align-items: center; gap: var(--space-2); min-width: 0; } +.fc-demo-head .cv-home-card-name { flex: 1; } +.fc-demo-open { align-self: flex-start; margin-top: var(--space-2); } +.fc-demo .cv-home-card-preview > img { animation: fc-home-in var(--transition-fast) both; } +.fc-demo .cv-home-card-preview > img[hidden] { display: none; } +@keyframes fc-home-in { from { opacity: 0; } to { opacity: 1; } } + +.fc-tm { position: fixed; z-index: var(--z-context); display: flex; flex-direction: column; gap: var(--space-2); width: min(720px, calc(100vw - 16px)); max-height: calc(100vh - 64px); overflow-y: auto; padding: var(--space-3); border-radius: var(--radius-lg); background: var(--glass-bg); border: 1px solid var(--glass-border); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); } +.fc-tm[hidden] { display: none; } +.fc-tm:focus { outline: none; } +.fc-tm-top { display: flex; align-items: center; gap: var(--space-3); padding-bottom: var(--space-2); border-bottom: 1px solid var(--line-1); } +.fc-tm-home { display: inline-flex; align-items: center; gap: var(--space-2); height: var(--ctl-md); padding: 0 var(--space-3); border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-1); color: var(--text-primary); font: inherit; font-size: var(--fs-13); } +.fc-tm-home:hover, .fc-tm-home:focus-visible { border-color: var(--accent-color); outline: none; } +.fc-tm-hint { color: var(--text-muted); font-size: var(--fs-12); } +.fc-tm-cols { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--space-3); } +.fc-tm-col { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.fc-tm-head { padding: var(--space-1) var(--space-2); color: var(--text-muted); font-size: var(--fs-11); font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; } +.fc-tm-item { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: var(--space-3); min-height: 44px; padding: var(--space-1) var(--space-2); border: 1px solid transparent; border-radius: var(--radius-md); background: transparent; color: var(--text-primary); font: inherit; text-align: left; } +.fc-tm-item:hover, .fc-tm-item:focus-visible { background: var(--surface-1); outline: none; border-color: var(--line-2); } +.fc-tm-item.is-active { border-color: var(--accent-line); background: var(--accent-wash); } +.fc-tm-icon { display: grid; place-items: center; width: 30px; height: 30px; border-radius: var(--radius); background: var(--surface-1); color: var(--accent-color); } +.fc-tm-text { display: flex; flex-direction: column; min-width: 0; } +.fc-tm-name { font-size: var(--fs-13); font-weight: 600; } +.fc-tm-line { overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +@media (max-width: 640px) { .fc-tm-cols { grid-template-columns: minmax(0, 1fr); } } + +.fc-wl { display: flex; flex-direction: column; gap: var(--space-3); min-height: 260px; } +.fc-wl-dots { display: flex; gap: 6px; margin: 0; padding: 0; list-style: none; } +.fc-wl-dots li { width: 28px; height: 4px; border-radius: var(--radius-pill); background: var(--line-2); } +.fc-wl-dots li.is-on { background: var(--accent-color); } +.fc-wl-step { display: flex; flex-direction: column; gap: var(--space-3); color: var(--text-secondary); } +.fc-wl-step[hidden] { display: none; } +.fc-wl-step > .fc-wl-mark { display: block; width: 36px; height: 36px; flex: none; } +.fc-wl-lead { margin: 0; color: var(--text-primary); font-size: var(--fs-16); font-weight: 600; line-height: 1.35; } +.fc-wl-body { margin: 0; font-size: var(--fs-13); line-height: 1.5; } +.fc-wl-state { min-height: 1.4em; margin: 0; color: var(--text-muted); font-size: var(--fs-12); } +.fc-wl-choices { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--space-3); } +.fc-wl-choice { display: flex; align-items: flex-start; gap: var(--space-3); padding: var(--space-4); border: 1px solid var(--line-2); border-radius: var(--radius-lg); background: var(--surface-1); color: var(--text-primary); font: inherit; text-align: left; } +.fc-wl-choice.is-primary { border-color: var(--accent-color); background: var(--accent-wash); } +.fc-wl-choice:hover, .fc-wl-choice:focus-visible { border-color: var(--accent-color); outline: none; } +.fc-wl-choice > span { display: flex; flex-direction: column; gap: 4px; } +.fc-wl-choice small { color: var(--text-muted); font-size: var(--fs-12); } +.fc-wl-themes { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--space-2); } +.fc-wl-theme { display: flex; align-items: center; gap: var(--space-2); height: var(--ctl-lg); padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-1); color: var(--text-primary); font: inherit; font-size: var(--fs-12); } +.fc-wl-theme[aria-pressed="true"] { border-color: var(--accent-color); } +.fc-wl-swatch { flex: none; width: 22px; height: 22px; border: 1px solid var(--line-2); border-radius: var(--radius); } + +.fc-empty-acts { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: var(--space-3); margin-top: var(--space-2); pointer-events: auto; } +.fc-empty-acts[hidden] { display: none; } +.fc-demo-link { padding: 0; border: 0; background: transparent; color: var(--accent-ink); font: inherit; font-size: var(--fs-12); text-decoration: underline; text-underline-offset: 3px; cursor: pointer; pointer-events: auto; } +.fc-demo-link:hover { color: var(--text-primary); } +.fc-demo-link:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 2px; border-radius: var(--radius-xs); } +.fc-rp-save { overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fc-rp-card[data-save="saved"] .fc-rp-save { color: var(--ok); } +.fc-rp-card[data-save="edited"] .fc-rp-save { color: var(--warn); } diff --git a/frontend/src/styles/jobs-popover.css b/frontend/src/styles/jobs-popover.css new file mode 100644 index 0000000..ad08c67 --- /dev/null +++ b/frontend/src/styles/jobs-popover.css @@ -0,0 +1,45 @@ +.cv-tt-jobs { position: relative; } +.cv-tt-ring { position: absolute; right: 2px; bottom: 2px; width: 8px; height: 8px; box-sizing: border-box; border: 1.5px solid var(--accent-soft); border-top-color: var(--accent-color); border-radius: var(--radius-pill); opacity: 0; transition: opacity 160ms ease; pointer-events: none; } +.cv-tt-jobs.is-running .cv-tt-ring { opacity: 1; animation: cv-jp-spin 0.9s linear infinite; } +@keyframes cv-jp-spin { to { transform: rotate(360deg); } } +@media (prefers-reduced-motion: reduce) { .cv-tt-jobs.is-running .cv-tt-ring { animation: none; border-color: var(--accent-color); } } + +.cv-jp-pop { position: fixed; display: flex; flex-direction: column; box-sizing: border-box; width: min(380px, calc(100vw - 16px)); padding: var(--space-2); border-radius: var(--radius-xl); background: var(--glass-bg); border: 1px solid var(--glass-border); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); user-select: none; -webkit-user-select: none; } +.cv-jp-pop[hidden] { display: none; } +.cv-jp-head { display: flex; align-items: center; height: var(--ctl); padding: 0 var(--space-2); } +.cv-jp-heading { color: var(--text-primary); font-size: var(--fs-13); font-weight: 600; } +.cv-jp-list { display: flex; flex-direction: column; gap: 2px; min-height: 0; margin: 0; padding: 0; overflow-y: auto; list-style: none; } +.cv-jp-group { display: flex; align-items: center; justify-content: space-between; padding: var(--space-2) var(--space-2) 2px; color: var(--text-muted); font-size: var(--fs-11); font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; } +.cv-jp-group[data-group="failed"] .cv-jp-gname { color: var(--danger); } +.cv-jp-gcount { font-variant-numeric: tabular-nums; } +.cv-jp-row { display: flex; gap: var(--space-2); padding: var(--space-2); border-radius: var(--radius); color: var(--text-secondary); outline: 0; cursor: default; } +.cv-jp-row:hover { background: var(--surface-raised); } +.cv-jp-row.is-picked { background: var(--accent-soft); color: var(--text-primary); } +.cv-jp-row:focus-visible { box-shadow: inset 0 0 0 2px var(--accent-color); } +.cv-jp-thumb { display: grid; place-items: center; flex: none; width: 40px; height: 40px; overflow: hidden; border-radius: var(--radius); background: var(--surface-1); color: var(--text-muted); } +.cv-jp-thumb img { width: 100%; height: 100%; object-fit: cover; } +.cv-jp-thumb img[hidden], .cv-jp-glyph[hidden] { display: none; } +.cv-jp-glyph { display: grid; place-items: center; } +.cv-jp-row[data-group="running"] .cv-jp-glyph { color: var(--accent-color); } +.cv-jp-row[data-group="failed"] .cv-jp-glyph { color: var(--danger); } +.cv-jp-main { display: flex; flex-direction: column; gap: 2px; flex: 1; min-width: 0; } +.cv-jp-line { display: flex; align-items: baseline; gap: var(--space-2); } +.cv-jp-title { flex: 1; min-width: 0; overflow: hidden; color: var(--text-primary); font-size: var(--fs-12); text-overflow: ellipsis; white-space: nowrap; } +.cv-jp-time { flex: none; color: var(--text-muted); font-size: var(--fs-11); font-variant-numeric: tabular-nums; } +.cv-jp-meta { min-height: 1.3em; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.cv-jp-row[data-group="failed"] .cv-jp-meta { color: var(--danger); } +.cv-jp-bar { position: relative; display: block; height: 3px; overflow: hidden; border-radius: var(--radius-pill); background: var(--line-2); } +.cv-jp-bar[hidden] { display: none; } +.cv-jp-bar i { position: absolute; inset: 0; background: var(--accent-color); transform-origin: left center; transform: scaleX(var(--p, 0)); transition: transform 200ms linear; } +.cv-jp-bar.is-indeterminate i { width: 30%; transform: none; animation: cv-jp-slide 1.2s ease-in-out infinite; } +@keyframes cv-jp-slide { from { left: -30%; } to { left: 100%; } } +.cv-jp-acts { display: flex; flex-wrap: wrap; gap: var(--space-1); } +.cv-jp-acts:empty, .cv-jp-act[hidden] { display: none; } +.cv-jp-act, .cv-jp-foot-btn { height: 22px; padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: var(--surface-1); color: var(--text-secondary); font: inherit; font-size: var(--fs-11); cursor: pointer; } +.cv-jp-act:hover, .cv-jp-foot-btn:hover { color: var(--text-primary); background: var(--surface-raised); } +.cv-jp-act:focus-visible, .cv-jp-foot-btn:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.cv-jp-act[aria-disabled="true"], .cv-jp-foot-btn[aria-disabled="true"] { opacity: 0.45; cursor: default; } +.cv-jp-empty { margin: 0; padding: var(--space-3) var(--space-2); color: var(--text-muted); font-size: var(--fs-12); } +.cv-jp-empty[hidden] { display: none; } +.cv-jp-foot { display: flex; justify-content: space-between; gap: var(--space-2); margin-top: var(--space-2); padding: var(--space-2) var(--space-1) 0; border-top: 1px solid var(--line-1); } +.cv-jp-foot-btn { height: var(--ctl-sm); font-size: var(--fs-12); } diff --git a/frontend/src/styles/key-sheet.css b/frontend/src/styles/key-sheet.css new file mode 100644 index 0000000..d162fd1 --- /dev/null +++ b/frontend/src/styles/key-sheet.css @@ -0,0 +1,14 @@ +/* Key sheet: opens above a prompt box when the chosen model's provider has no key. */ +.fc-shot-bar:has(> .fc-ks) { position: relative; } +.fc-ks { position: absolute; z-index: var(--z-menu); left: 50%; bottom: calc(100% + var(--space-2)); translate: -50% 0; box-sizing: border-box; display: flex; flex-direction: column; gap: var(--space-2); width: min(380px, calc(100vw - 2 * var(--space-4))); padding: var(--space-3); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); background: var(--bg-secondary); box-shadow: var(--shadow-lg); color: var(--text-primary); font-size: var(--fs-12); pointer-events: auto; text-align: left; } +.fc-ks-head { display: flex; align-items: center; gap: var(--space-2); } +.fc-ks-i { display: grid; place-items: center; color: var(--accent-color); } +.fc-ks-t { flex: 1; min-width: 0; font-size: var(--fs-14); font-weight: 600; } +.fc-ks .cv-note { margin: 0; } +.fc-ks-first { padding: var(--space-2); border-radius: var(--radius-md); background: var(--surface-2); color: var(--text-secondary); } +.fc-ks-link { color: var(--accent-color); text-decoration: underline; text-underline-offset: 2px; overflow-wrap: anywhere; } +.fc-ks-field { display: flex; align-items: flex-end; gap: var(--space-2); } +.fc-ks-field > .cv-field { flex: 1; min-width: 0; } +.fc-ks-where { min-height: 1.4em; color: var(--text-muted); } +.fc-ks-msg { min-height: 1.4em; color: var(--text-secondary); } +.fc-ks-bar { display: flex; justify-content: flex-end; gap: var(--space-2); } diff --git a/frontend/src/styles/keybinds-more.css b/frontend/src/styles/keybinds-more.css new file mode 100644 index 0000000..cb356b1 --- /dev/null +++ b/frontend/src/styles/keybinds-more.css @@ -0,0 +1,19 @@ +.fc-kb-io { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); } +.fc-kb-io .fc-kb-preset-note { flex: 1 1 auto; min-width: 0; margin: 0; } +.fc-kb-io-tools { display: flex; flex: none; gap: var(--space-2); } +.fc-kb-io-tools .cv-btn { gap: var(--space-1); height: var(--ctl-sm); padding: 0 var(--space-2); font-size: var(--fs-11); } +.fc-kb-find .fc-kb-keysearch { position: absolute; right: var(--space-1); width: var(--ctl-sm); height: var(--ctl-sm); } +.fc-kb-find .fc-kb-keysearch.is-active { border-color: var(--accent-line); background: var(--accent-soft); color: var(--text-primary); } +.fc-kb-find .cv-input { padding-right: calc(var(--ctl-sm) + var(--space-2)); } +.fc-kb-ctx { flex: none; padding: 0 var(--space-1); border: 1px solid var(--line-1); border-radius: var(--radius-sm); color: var(--text-muted); font-size: var(--fs-11); white-space: nowrap; } +.fc-kb-note-tools .cv-btn[hidden] { display: none; } + +.fc-sheet-find { position: relative; display: flex; align-items: center; flex: 1 1 auto; max-width: 280px; min-width: 120px; } +.fc-sheet-find > .icon { position: absolute; left: var(--space-2); color: var(--text-muted); pointer-events: none; } +.fc-sheet-find .cv-input { width: 100%; height: var(--ctl-sm); padding-left: var(--space-6); } +.fc-sheet-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); margin-top: var(--space-4); color: var(--text-muted); font-size: var(--fs-11); } +.fc-sheet-custom { height: var(--ctl-sm); padding: 0 var(--space-2); font-size: var(--fs-11); } + +@media (max-width: 719px) { + .fc-kb-io { flex-wrap: wrap; } +} diff --git a/frontend/src/styles/keybinds.css b/frontend/src/styles/keybinds.css index 5414f68..0651ec7 100644 --- a/frontend/src/styles/keybinds.css +++ b/frontend/src/styles/keybinds.css @@ -84,7 +84,7 @@ .fc-sheet-pin:not(.is-on) .fc-sheet-pin-text > span:last-child, .fc-sheet-pin.is-on .fc-sheet-pin-text > span:first-child { visibility: hidden; } .fc-sheet-groups { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: var(--space-5) var(--space-6); align-items: start; } .fc-sheet-group-title { margin-bottom: var(--space-1); color: var(--text-muted); font-size: var(--fs-11); font-weight: 600; letter-spacing: 0.02em; } -.fc-sheet-list { display: grid; list-style: none; } +.fc-sheet-list { display: grid; grid-template-columns: minmax(0, 1fr); list-style: none; } .fc-sheet-row { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); min-height: var(--ctl-md); font-size: var(--fs-12); } .fc-sheet-row.is-off { opacity: 0.45; } .fc-sheet-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } diff --git a/frontend/src/styles/legibility.css b/frontend/src/styles/legibility.css new file mode 100644 index 0000000..d0e73a3 --- /dev/null +++ b/frontend/src/styles/legibility.css @@ -0,0 +1,13 @@ +:root .fc-cr-sub, :root .fc-deck-addtext, :root .fc-deck-note, :root .fc-ed-ph, :root .fc-pill-pre, :root .fc-pb-count, :root .fc-pb-clear, +:root .fc-pb-clear.is-disabled:hover, :root .fc-cg-hist-empty, :root .fc-bg-chips-hint, :root .fc-bg-empty-text, :root .fc-bd-boot-note, +:root .fc-etl-hint, :root .fc-mp-note, :root .fc-mp-count, :root .fc-ep-hint, +:root .fc-sw-sub, :root .fc-sp-sub, :root .fc-sp-empty, :root .fc-sw-env.is-empty .fc-sw-kind, :root .fc-sw-env.is-empty .fc-sw-name, +:root .fc-scc-unit, :root .fc-scc-sheet-meta, :root .fc-scc-sheet-gt, :root .fc-scc-item-keys, :root .fc-scp-when, +:root .fc-so-meta, :root .fc-so-pass figcaption, +:root .fc-gen-deck-note, :root .fc-gen-foot-note, :root .fc-gen-cam-focal, :root .fc-gen-cam-foot, :root .fc-gen-mp-note, +:root .fc-tl-of, :root .fc-tl-mark b, :root .fc-tl-name.is-sub, :root .fc-tl-hint, :root .fc-tl-empty, :root .fc-tl-tip, :root .fc-tl-pop-note, :root .fc-tl-pick-len, +:root .fc-sc-hint, :root .fc-shot-an-note, :root .fc-sc-boot-note, :root .cv-jobs-note { color: var(--text-secondary); } +:root .fc-ed-ph, :root .fc-shot-prompt::placeholder { color: var(--text-secondary); } +:root .fc-pb-count.is-over { color: var(--danger); } +:root .fc-sw.is-active { color: var(--text-primary); } +:root .fc-so-opt { color: var(--text-primary); } diff --git a/frontend/src/styles/media-panel.css b/frontend/src/styles/media-panel.css index c242fe3..a45b5f6 100644 --- a/frontend/src/styles/media-panel.css +++ b/frontend/src/styles/media-panel.css @@ -38,7 +38,7 @@ .fc-mp-plus { display: inline-flex; align-items: center; justify-content: center; width: var(--ctl-sm); height: var(--ctl-sm); border: 0; border-radius: var(--radius-pill); background: var(--cta-bg); color: var(--cta-text); cursor: pointer; opacity: 0; transition: opacity var(--transition-fast); } .fc-mp[data-view="grid"] .fc-mp-plus { position: absolute; right: var(--space-2); top: var(--space-2); } .fc-mp-item:hover .fc-mp-plus, .fc-mp-item.is-selected .fc-mp-plus, .fc-mp-plus:focus-visible { opacity: 1; } -.fc-mp-note { padding: var(--space-6) var(--space-3); text-align: center; color: var(--text-muted); } +.fc-mp-note { padding: var(--space-3); text-align: center; color: var(--text-muted); line-height: 1.4; } .fc-mp-note[hidden], .fc-mp-retry[hidden] { display: none; } .fc-mp-foot { display: flex; flex: none; align-items: center; justify-content: space-between; gap: var(--space-2); min-height: var(--ctl-md); padding: 0 var(--space-3); border-top: 1px solid var(--line-1); color: var(--text-muted); font-size: var(--fs-11); } .fc-mp-retry { height: var(--ctl-sm); padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius); background: transparent; cursor: pointer; } @@ -53,3 +53,11 @@ .fc-md-panel { display: flex; flex-direction: column; width: 300px; height: min(520px, calc(100vh - 220px)); min-height: 240px; border: 1px solid var(--glass-border); border-radius: var(--radius-lg); background: var(--glass-bg); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); overflow: hidden; } .fc-md-panel[hidden] { display: none; } .fc-md.is-drop-target .fc-md-panel { box-shadow: 0 0 0 2px var(--accent-color); } +.fc-md[data-dock] { position: relative; right: auto; bottom: auto; z-index: auto; } +.fc-md[data-dock] > .fc-md-toggle { height: var(--ctl-md); border-color: var(--line-2); border-radius: var(--radius-md); background: transparent; box-shadow: none; -webkit-backdrop-filter: none; backdrop-filter: none; } +.fc-md[data-dock] > .fc-md-toggle:hover { background: var(--bg-hover); } +.fc-md[data-dock="board"] { flex: none; } +.fc-md[data-dock="board"] > .fc-md-panel { position: absolute; top: calc(100% + var(--space-2)); right: 0; z-index: var(--z-menu); } +.fc-md[data-dock="canvas"] { order: 99; flex: none; margin-top: auto; align-items: stretch; } +.fc-md[data-dock="canvas"] > .fc-md-toggle { justify-content: center; } +.fc-md[data-dock="canvas"] > .fc-md-panel { width: 100%; height: min(420px, 50vh); background: var(--surface-1); box-shadow: none; -webkit-backdrop-filter: none; backdrop-filter: none; } diff --git a/frontend/src/styles/picker.css b/frontend/src/styles/picker.css index 820370b..ade2ed2 100644 --- a/frontend/src/styles/picker.css +++ b/frontend/src/styles/picker.css @@ -58,20 +58,28 @@ .fc-mp-list { flex: 1 1 auto; min-height: 0; padding: var(--space-2); overflow-y: auto; overscroll-behavior: contain; outline: none; } .fc-mp-head { padding: var(--space-2) var(--space-2) var(--space-1); color: var(--text-muted); font-size: var(--fs-10); font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; } .fc-mp-head[hidden] { display: none; } -.fc-mp-row { display: grid; grid-template-columns: 28px minmax(0, 1fr) 14px; align-items: center; column-gap: var(--space-2); min-height: 50px; padding: var(--space-1) var(--space-2); border-radius: var(--radius-lg); cursor: pointer; } +.fc-mp-row { display: grid; grid-template-columns: 28px minmax(0, 1fr) 22px 14px; align-items: center; column-gap: var(--space-2); min-height: 50px; padding: var(--space-1) var(--space-2); border-radius: var(--radius-lg); cursor: pointer; } .fc-mp-row[hidden] { display: none; } .fc-mp-row.is-picked { background: var(--accent-soft); } .fc-mp-tile { display: grid; place-items: center; width: 28px; height: 28px; border-radius: var(--radius-md); background: var(--bg-hover); color: var(--text-secondary); } .fc-mp-row.is-chosen .fc-mp-tile { background: var(--accent-wash); color: var(--accent-ink); } .fc-mp-main { display: grid; gap: 2px; min-width: 0; } .fc-mp-line { display: flex; align-items: center; gap: var(--space-2); min-width: 0; } -.fc-mp-name { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-primary); font-size: var(--fs-13); font-weight: 500; } +.fc-mp-name { flex: 0 0 auto; max-width: 100%; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-primary); font-size: var(--fs-13); font-weight: 500; } .fc-mp-maker { flex: 1 1 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-muted); font-size: var(--fs-11); } .fc-mp-price { flex: none; color: var(--text-muted); font-size: var(--fs-11); font-variant-numeric: tabular-nums; white-space: nowrap; } .fc-mp-price[hidden] { display: none; } .fc-mp-blurb { flex: 1 1 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-secondary); font-size: var(--fs-11); } .fc-mp-badges { display: inline-flex; flex: none; gap: 2px; color: var(--text-muted); } .fc-mp-badge { display: inline-flex; } +.fc-mp-tags { display: inline-flex; flex: none; gap: 2px; } +.fc-mp-tags:empty { display: none; } +.fc-mp-tag { padding: 0 var(--space-1); border: 1px solid var(--border-soft); border-radius: var(--radius-pill); color: var(--text-secondary); font-size: var(--fs-11); line-height: 16px; white-space: nowrap; } +.fc-mp-tag[data-tag="recommended"] { border-color: var(--accent-line); background: var(--accent-wash); color: var(--accent-ink); } +.fc-mp-fav { display: inline-grid; place-items: center; width: 22px; height: 22px; padding: 0; border: 0; border-radius: var(--radius-pill); background: transparent; color: var(--text-muted); opacity: 0; cursor: pointer; transition: opacity var(--transition-fast), color var(--transition-fast); } +.fc-mp-row:hover .fc-mp-fav, .fc-mp-row.is-picked .fc-mp-fav, .fc-mp-fav.is-on, .fc-mp-fav:focus-visible { opacity: 1; } +.fc-mp-fav:hover, .fc-mp-fav.is-on { color: var(--accent-color); } +.fc-mp-fav:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } .fc-mp-tick { display: inline-flex; visibility: hidden; color: var(--accent-ink); } .fc-mp-row.is-chosen .fc-mp-tick { visibility: visible; } .fc-mp-row.is-off .fc-mp-tile, .fc-mp-row.is-off .fc-mp-name, .fc-mp-row.is-off .fc-mp-maker, .fc-mp-row.is-off .fc-mp-blurb, .fc-mp-row.is-off .fc-mp-badges { opacity: 0.5; } diff --git a/frontend/src/styles/prefs-output.css b/frontend/src/styles/prefs-output.css new file mode 100644 index 0000000..e47c2c2 --- /dev/null +++ b/frontend/src/styles/prefs-output.css @@ -0,0 +1,5 @@ +.fc-out-path { min-height: calc(1.45em + 2px); overflow-wrap: anywhere; user-select: text; color: var(--text-secondary); } +.fc-out-chips { display: flex; flex-wrap: wrap; gap: var(--space-1); } +.fc-out-preview { min-height: calc(1.45em + 2px); overflow-wrap: anywhere; user-select: text; } +.fc-out-error { min-height: calc(2.9em + 2px); } +.fc-output.is-pending, .fc-template.is-pending { opacity: 0.7; } diff --git a/frontend/src/styles/projects.css b/frontend/src/styles/projects.css index 9579187..6bafe68 100644 --- a/frontend/src/styles/projects.css +++ b/frontend/src/styles/projects.css @@ -20,7 +20,8 @@ .fc-home-first { margin-top: 0; } -.fc-np-kinds { display: grid; gap: var(--space-2); } +.fc-np-kinds { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--space-2); } +@media (max-width: 680px) { .fc-np-kinds { grid-template-columns: minmax(0, 1fr); } } .fc-np-kind { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: var(--space-3); padding: var(--space-3); border: 1px solid var(--line-1); border-radius: var(--radius-md); background: var(--surface-1); color: var(--text-secondary); font: inherit; text-align: left; cursor: pointer; } .fc-np-kind:hover:not(:disabled) { border-color: var(--accent-color); } .fc-np-kind.is-selected { border-color: var(--accent-color); background: var(--accent-wash); } diff --git a/frontend/src/styles/prompt.css b/frontend/src/styles/prompt.css index 1d815c5..016aa28 100644 --- a/frontend/src/styles/prompt.css +++ b/frontend/src/styles/prompt.css @@ -53,7 +53,12 @@ .fc-pb-cost:not(:empty):hover, .fc-pb-cost.is-open { background: var(--bg-hover); color: var(--text-primary); } .fc-pb-cost:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } -.fc-pb-gen { flex: none; display: grid; place-items: center; width: var(--ctl-lg); height: var(--ctl-lg); padding: 0; border: 0; border-radius: var(--radius-pill); background: var(--cta-bg); color: var(--cta-text); cursor: pointer; transition: background var(--transition-fast), color var(--transition-fast); } +.fc-pb-gen-a { grid-auto-flow: column; gap: var(--space-2); } +.fc-pb-gen-l { display: grid; font-size: var(--fs-13); font-weight: 600; white-space: nowrap; } +.fc-pb-gen-l > span { grid-area: 1 / 1; text-align: center; } +.fc-pb-gen-l > [data-l="key"], .fc-pb-gen.is-key .fc-pb-gen-l > [data-l="gen"] { visibility: hidden; } +.fc-pb-gen.is-key .fc-pb-gen-l > [data-l="key"] { visibility: visible; } +.fc-pb-gen { flex: none; display: grid; place-items: center; min-width: var(--ctl-lg); height: var(--ctl-lg); padding: 0 var(--space-4) 0 var(--space-3); border: 0; border-radius: var(--radius-pill); background: var(--cta-bg); color: var(--cta-text); cursor: pointer; transition: background var(--transition-fast), color var(--transition-fast); } .fc-pb-gen:hover { background: var(--cta-bg-hover); } .fc-pb-gen:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 2px; } .fc-pb-gen.is-disabled { background: var(--surface-raised); color: var(--text-muted); cursor: default; } diff --git a/frontend/src/styles/scene-dock.css b/frontend/src/styles/scene-dock.css new file mode 100644 index 0000000..c6394df --- /dev/null +++ b/frontend/src/styles/scene-dock.css @@ -0,0 +1,55 @@ +.fc-sc-grip { position: relative; z-index: var(--z-raised); display: flex; align-items: center; justify-content: center; min-width: 0; cursor: col-resize; touch-action: none; outline: none; } +.fc-sc-grip[data-side="left"] { grid-area: lgrip; } +.fc-sc-grip[data-side="right"] { grid-area: rgrip; } +.fc-sc-grip::before { content: ''; position: absolute; top: 0; bottom: var(--space-2); left: 50%; width: 2px; translate: -50% 0; border-radius: var(--radius-pill); background: transparent; transition: background var(--transition-fast); } +.fc-sc-grip:hover::before, .fc-sc-grip.is-dragging::before, .fc-sc-grip:focus-visible::before { background: var(--accent-line); } +.fc-sc[data-left="off"] > .fc-sc-grip[data-side="left"], .fc-sc[data-right="off"] > .fc-sc-grip[data-side="right"] { cursor: default; } +.fc-sc[data-left="off"] > .fc-sc-grip[data-side="left"]::before, .fc-sc[data-right="off"] > .fc-sc-grip[data-side="right"]::before { background: transparent; } +.fc-sc[data-sc-mode="record"] > .fc-sc-grip { display: none; } +.fc-sc-fold { position: absolute; top: var(--space-2); left: 50%; translate: -50% 0; display: grid; place-items: center; width: var(--space-4); height: var(--ctl-md); padding: 0; border: 1px solid var(--line-2); border-radius: var(--radius-pill); background: var(--surface-raised); color: var(--text-muted); cursor: pointer; } +.fc-sc-fold:hover { color: var(--text-primary); background: var(--bg-hover); } +.fc-sc-fold:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fc-sc-fold [hidden] { display: none; } + +.fc-sc-strip { grid-area: strip; display: flex; align-items: flex-end; gap: var(--space-2); min-width: 0; padding: 0 var(--space-2) var(--space-2); } +.fc-sc-strip > [data-slot="bottom"] { position: relative; flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; } +.fc-sc-strip > .fc-md { position: relative; flex: none; display: block; z-index: auto; right: auto; bottom: auto; } +.fc-sc-strip > .fc-md > .fc-md-toggle { height: var(--ctl-xl); } +.fc-sc-strip > .fc-md > .fc-md-panel { position: absolute; right: 0; bottom: calc(100% + var(--space-2)); z-index: var(--z-menu); } + +.fc-sc > [data-slot="left"] > .fc-sp-outliner { width: auto; height: auto; flex: 1 1 auto; min-height: 0; max-height: none; } +.fc-sc > [data-slot="bottom-right"] > .fc-sp-inspector { width: auto; max-width: none; max-height: none; flex: 0 1 auto; min-height: 0; } +.fc-sc-hint { flex: none; margin: 0; padding: var(--space-3); color: var(--text-muted); font-size: var(--fs-12); line-height: 1.4; } +.fc-sc-hint[hidden], .fc-sc-hint [hidden] { display: none; } +.fc-sc-top .fc-pr-hint { display: none; } + +.fc-sc > .fc-shot { grid-area: shot; position: relative; left: auto; bottom: auto; width: auto; height: auto; min-width: 0; padding: var(--space-2) 0 0; visibility: visible; } +.fc-sc > .fc-shot[hidden] { display: none; } +.fc-shot-bar { position: relative; } +.fc-shot-fold { display: grid; place-items: center; flex: none; align-self: flex-start; width: var(--ctl-md); height: var(--ctl-md); padding: 0; border: 0; border-radius: var(--radius-pill); background: transparent; color: var(--text-muted); cursor: pointer; pointer-events: auto; } +.fc-shot-fold:hover { background: var(--bg-hover); color: var(--text-primary); } +.fc-shot-fold:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -2px; } +.fc-shot-fold [hidden] { display: none; } +.fc-shot.is-small .fc-shot-float { display: none; } +.fc-shot.is-small .fc-shot-bar { flex-wrap: nowrap; align-items: center; padding: var(--space-1) var(--space-2); } +.fc-shot.is-small .fc-shot-fold { align-self: center; } +.fc-shot.is-small .fc-shot-prompt { flex: 1 1 auto; height: var(--ctl-md); padding-top: var(--space-1); padding-bottom: var(--space-1); overflow: hidden; white-space: nowrap; } +.fc-shot.is-small .fc-shot-ctl { flex: none; margin-left: 0; } +.fc-shot.is-small .fc-shot-ctl > :not(.fc-shot-go) { display: none; } + +.fc-sc-strip .fc-tl { align-self: stretch; width: 100%; translate: none; } +.fc-sc-strip .fc-tl.is-open { height: auto; } +.fc-sc-strip .fc-tl.is-open > .fc-tl-ed { position: relative; inset: auto; } + +.fc-sc-top .fc-so-opt { position: static; } +.fc-sc[data-sc-mode="record"] .fc-sc-top > .fc-sc-slot > [hidden] { display: none; } +.fc-sc-top > [data-slot="top-centre"] > .fc-so-bar { grid-area: 1 / 2 / 2 / 5; } +.fc-sc-top:not(.is-sq2) .fc-scc-morebar, .fc-sc[data-sc-mode="record"] .fc-scc-morebar { display: none; } +.fc-scc-morebar { order: 4; } +.fc-sc-top.is-sq1 .fc-scc-file .fc-scc-btn:not(.fc-scc-file-btn) .fc-scc-text, .fc-sc-top.is-sq1 .fc-scc-space .fc-scc-text, .fc-sc-top.is-sq1 .fc-scc-camname { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } +.fc-sc-top.is-sq1 .fc-scc-file .fc-scc-btn:not(.fc-scc-file-btn) { width: var(--ctl-md); padding: 0; } +.fc-sc-top.is-sq2 .fc-scc-tools > .fc-scc-div, .fc-sc-top.is-sq2 .fc-scc-space, .fc-sc-top.is-sq2 .fc-scc-tools > .fc-scc-tool:last-child, .fc-sc-top.is-sq2 [data-slot="top-centre"] > .fc-scc-wand, .fc-sc-top.is-sq2 .fc-scc-file > .fc-scc-btn:last-child { display: none; } +.fc-sc-top.is-sq3 .fc-scc-aspect .fc-scc-text, .fc-sc-top.is-sq3 .fc-scc-focalbtn .fc-scc-text { display: none; } +.fc-sc-top.is-sq4 .fc-scc-file > .fc-scc-btn:nth-child(2) { display: none; } + +@media (prefers-reduced-motion: reduce) { .fc-sc-grip::before { transition: none; } } diff --git a/frontend/src/styles/scene-output.css b/frontend/src/styles/scene-output.css index ae1ad6d..94f1174 100644 --- a/frontend/src/styles/scene-output.css +++ b/frontend/src/styles/scene-output.css @@ -41,7 +41,7 @@ .fc-so-passes { display: grid; grid-template-columns: repeat(2, minmax(0, 11rem)); justify-content: start; gap: var(--space-3); min-width: 0; } .fc-so-passes[hidden] { display: none; } .fc-so-pass { display: grid; gap: var(--space-1); min-width: 0; margin: 0; } -.fc-so-pass img { display: block; width: 100%; aspect-ratio: var(--fc-so-ratio, 1.7778); object-fit: contain; border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--canvas-bg); } +.fc-so-pass img, .fc-so-pass video { display: block; width: 100%; aspect-ratio: var(--fc-so-ratio, 1.7778); object-fit: contain; border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--canvas-bg); } .fc-so-pass figcaption { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-2); min-height: 1.3em; font-size: var(--fs-12); color: var(--text-muted); } .fc-so-pass-name { color: var(--text-secondary); font-weight: 600; } .fc-so-pass-state { font-variant-numeric: tabular-nums; } diff --git a/frontend/src/styles/scene-panels.css b/frontend/src/styles/scene-panels.css index 7aa0926..a596165 100644 --- a/frontend/src/styles/scene-panels.css +++ b/frontend/src/styles/scene-panels.css @@ -1,6 +1,5 @@ .fc-sp-panel { display: flex; flex-direction: column; min-height: 0; color: var(--text-primary); font-size: var(--fs-12); background: var(--glass-bg); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); } .fc-sp-panel[hidden] { display: none; } -.fc-sc > .fc-sc-slot[data-slot="bottom-right"] { max-height: var(--sc-br-room, none); translate: 0 calc(var(--sc-br-lift, 0px) * -1); transition: translate var(--transition-normal); } .fc-sp-panel[inert] { opacity: 0.6; } .fc-sp-panel button, .fc-sp-panel input { font: inherit; } .fc-sp-panel button { color: inherit; } @@ -16,6 +15,12 @@ .fc-sp-iconbtn { display: inline-flex; flex: none; align-items: center; justify-content: center; width: var(--ctl-sm); height: var(--ctl-sm); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-muted); cursor: pointer; } .fc-sp-iconbtn:hover { background: var(--bg-hover); color: var(--text-primary); } +.fc-sp-count { flex: none; min-width: 3ch; font-size: var(--fs-11); font-variant-numeric: tabular-nums; color: var(--text-muted); text-align: right; } +.fc-sp-count:empty { display: none; } +.fc-sp-find { display: flex; flex: none; align-items: center; gap: var(--space-1); padding: var(--space-1) var(--space-2); border-bottom: 1px solid var(--line-1); } +.fc-sp-search { flex: 1 1 auto; min-width: 0; height: var(--ctl-sm); padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--surface-field); color: var(--text-primary); font-size: var(--fs-12); outline: none; } +.fc-sp-search::placeholder { color: var(--text-muted); } +.fc-sp-search:focus { border-color: var(--accent-color); } .fc-sp-scroll { position: relative; flex: 1 1 auto; min-height: 0; overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; padding: var(--space-1); } .fc-sp-scroll.is-dragging { cursor: grabbing; user-select: none; -webkit-user-select: none; } .fc-sp-list { display: block; } @@ -114,5 +119,5 @@ .fc-sp-danger:hover:not(:disabled) { background: color-mix(in srgb, var(--danger) 16%, transparent); } @media (prefers-reduced-motion: reduce) { - .fc-sp-switch-track, .fc-sp-switch-track::after, .fc-sc > .fc-sc-slot[data-slot="bottom-right"] { transition: none; } + .fc-sp-switch-track, .fc-sp-switch-track::after { transition: none; } } diff --git a/frontend/src/styles/scene-shot.css b/frontend/src/styles/scene-shot.css index eb21fc2..1155b26 100644 --- a/frontend/src/styles/scene-shot.css +++ b/frontend/src/styles/scene-shot.css @@ -1,6 +1,5 @@ .fc-shot { position: absolute; left: var(--fc-shot-x, var(--space-3)); bottom: var(--fc-shot-lift, var(--space-3)); width: var(--fc-shot-w, 40rem); height: 0; display: flex; flex-direction: column; justify-content: flex-end; gap: var(--space-2); pointer-events: none; color: var(--text-primary); } .fc-shot[hidden], .fc-shot [hidden] { display: none; } -.fc-shot:not([data-settled]) { visibility: hidden; } .fc-shot-float { display: flex; flex-direction: column; gap: var(--space-1); min-width: 0; } .fc-shot-float > * { pointer-events: auto; } diff --git a/frontend/src/styles/scene.css b/frontend/src/styles/scene.css index 9823b08..5d09715 100644 --- a/frontend/src/styles/scene.css +++ b/frontend/src/styles/scene.css @@ -1,7 +1,10 @@ -.fc-sc { position: relative; flex: 1 1 auto; min-width: 0; min-height: 0; overflow: hidden; isolation: isolate; container: fc-scene / inline-size; background: var(--canvas-bg); color: var(--text-primary); } +.fc-sc { --sc-grip: var(--space-2); position: relative; flex: 1 1 auto; min-width: 0; min-height: 0; overflow: hidden; isolation: isolate; container: fc-scene / inline-size; display: grid; grid-template-columns: var(--sc-left-cell) var(--sc-grip) minmax(0, 1fr) var(--sc-grip) var(--sc-right-cell); grid-template-rows: auto minmax(0, 1fr) auto auto; grid-template-areas: "top top top top top" "left lgrip stage rgrip right" "left lgrip shot rgrip right" "strip strip strip strip strip"; --sc-left-cell: var(--sc-left-w, 260px); --sc-right-cell: var(--sc-right-w, 300px); background: var(--canvas-bg); color: var(--text-primary); } +.fc-sc[data-left="off"] { --sc-left-cell: 0px; } +.fc-sc[data-right="off"] { --sc-right-cell: 0px; } +.fc-sc[data-sc-mode="record"] { --sc-left-cell: 0px; --sc-right-cell: 0px; --sc-grip: 0px; } .fc-sc [hidden] { display: none; } -.fc-sc-stage { position: absolute; inset: 0; z-index: var(--z-base); overflow: hidden; background: var(--canvas-bg); } +.fc-sc-stage { grid-area: stage; position: relative; min-width: 0; min-height: 0; z-index: var(--z-base); overflow: hidden; background: var(--canvas-bg); } .fc-sc-canvas { position: absolute; inset: 0; display: block; width: 100%; height: 100%; opacity: 0; outline: none; touch-action: none; cursor: default; transition: opacity var(--transition-fast); } .fc-sc-stage.is-ready .fc-sc-canvas { opacity: 1; } .fc-sc-canvas.is-drag, .fc-sc-canvas.is-gizmo { cursor: grabbing; } @@ -14,23 +17,15 @@ .fc-sc-stage > .fc-sc-slot { position: absolute; inset: 0; } .fc-sc-stage > [data-slot="frame"] { z-index: var(--z-raised); } .fc-sc-stage > [data-slot="overlay"] { z-index: var(--z-selected); } -.fc-sc > .fc-sc-slot { position: absolute; z-index: var(--z-rail); } -.fc-sc > [data-slot="left"] { left: var(--space-3); top: 50%; translate: 0 -50%; display: flex; flex-direction: column; max-height: calc(100% - 2 * var(--space-8)); } -.fc-sc > [data-slot="bottom"] { left: 50%; bottom: var(--space-3); translate: -50% 0; display: flex; flex-direction: column; align-items: center; gap: var(--space-2); width: min(90%, 64rem); } -.fc-sc > [data-slot="bottom-right"] { right: var(--space-3); bottom: var(--space-3); display: flex; flex-direction: column; align-items: flex-end; gap: var(--space-2); } -.fc-sc > [data-slot="modal"] { inset: 0; z-index: var(--z-chrome); } +.fc-sc > .fc-sc-slot { position: relative; min-width: 0; min-height: 0; } +.fc-sc > [data-slot="left"] { grid-area: left; display: flex; flex-direction: column; padding: 0 0 var(--space-2) var(--space-2); overflow: hidden; } +.fc-sc > [data-slot="bottom-right"] { grid-area: right; display: flex; flex-direction: column; gap: var(--space-2); padding: 0 var(--space-2) var(--space-2) 0; overflow: hidden; } +.fc-sc[data-left="off"] > [data-slot="left"], .fc-sc[data-right="off"] > [data-slot="bottom-right"], .fc-sc[data-sc-mode="record"] > [data-slot="left"], .fc-sc[data-sc-mode="record"] > [data-slot="bottom-right"] { visibility: hidden; padding: 0; } +.fc-sc > [data-slot="bottom"] { grid-area: strip; } +.fc-sc > [data-slot="modal"] { position: absolute; inset: 0; z-index: var(--z-chrome); } -.fc-sc-top { position: absolute; top: var(--space-3); left: var(--space-3); right: var(--space-3); z-index: var(--z-rail); display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: start; gap: var(--space-2) var(--space-3); pointer-events: none; } -.fc-sc-top > .fc-sc-slot { position: static; display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); min-width: 0; max-width: 100%; } -.fc-sc-top > [data-slot="top-left"] { grid-column: 1; justify-content: flex-start; } -.fc-sc-top > [data-slot="top-centre"] { grid-column: 2; justify-content: center; } -.fc-sc-top > [data-slot="top-right"] { grid-column: 3; justify-content: flex-end; } -@container fc-scene (max-width: 899px) { - .fc-sc-top { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } - .fc-sc-top > [data-slot="top-left"] { grid-column: 1; grid-row: 1; } - .fc-sc-top > [data-slot="top-right"] { grid-column: 2; grid-row: 1; } - .fc-sc-top > [data-slot="top-centre"] { grid-column: 1 / -1; grid-row: 2; } -} +.fc-sc-top { grid-area: top; position: relative; z-index: var(--z-rail); display: flex; flex-wrap: nowrap; align-items: center; justify-content: space-between; gap: var(--space-3); min-width: 0; padding: var(--space-2) var(--space-2); pointer-events: none; } +.fc-sc-top > .fc-sc-slot { position: static; display: flex; flex: none; flex-wrap: nowrap; align-items: center; gap: var(--space-2); min-width: 0; } .fc-sc-frame { position: absolute; inset: 0; overflow: hidden; pointer-events: none; } .fc-sc-frame-box { position: absolute; top: 0; left: 0; box-sizing: border-box; border: 1px solid var(--scene-frame-line); box-shadow: 0 0 0 100vmax var(--scene-matte); background: linear-gradient(var(--scene-frame-guide), var(--scene-frame-guide)) 33.3333% 0 / 1px 100% no-repeat, linear-gradient(var(--scene-frame-guide), var(--scene-frame-guide)) 66.6667% 0 / 1px 100% no-repeat, linear-gradient(var(--scene-frame-guide), var(--scene-frame-guide)) 0 33.3333% / 100% 1px no-repeat, linear-gradient(var(--scene-frame-guide), var(--scene-frame-guide)) 0 66.6667% / 100% 1px no-repeat; } diff --git a/frontend/src/styles/shell.css b/frontend/src/styles/shell.css index ee5c3fb..8417723 100644 --- a/frontend/src/styles/shell.css +++ b/frontend/src/styles/shell.css @@ -3,11 +3,10 @@ body { font-size: var(--fs-12); line-height: 1.35; } #app { height: 100%; } #overlay-root { position: fixed; inset: 0; z-index: var(--z-menu); pointer-events: none; } #overlay-root > * { pointer-events: auto; } -#toast-root { position: fixed; right: var(--space-4); bottom: calc(var(--cv-status-h) + var(--space-3)); z-index: var(--z-toast); display: flex; flex-direction: column; align-items: flex-end; gap: var(--space-2); pointer-events: none; transition: translate var(--transition-normal); } -:root.has-jobs-open #toast-root { translate: calc(-1 * (var(--cv-jobs-w) + var(--space-2))) 0; } -@media (max-width: 899px) { - :root.has-jobs-open #toast-root { top: calc(var(--cv-titlebar-h) + var(--space-3)); bottom: auto; translate: none; } -} +:root { --cv-toast-strip-h: var(--space-8); } +#toast-root { position: fixed; left: 50%; bottom: calc(var(--cv-status-h) + var(--space-1)); z-index: var(--z-toast); display: flex; flex-direction: row; align-items: flex-end; justify-content: center; gap: var(--space-2); width: max-content; max-width: calc(100vw - 2 * var(--space-4)); translate: -50% 0; pointer-events: none; transition: left var(--transition-normal); } +:root.has-jobs-open #toast-root { left: calc((100vw - var(--cv-jobs-w) - var(--space-2)) / 2); } +.cv-main { padding-bottom: var(--cv-toast-strip-h); } :root.has-overlay-titlebar { --cv-titlebar-h: 38px; } @@ -40,12 +39,13 @@ body { font-size: var(--fs-12); line-height: 1.35; } .cv-brand:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -2px; } .cv-tabs { display: flex; align-items: flex-end; flex: 1 1 auto; gap: 2px; min-width: 0; height: 100%; } .cv-tab-strip { display: flex; align-items: flex-end; gap: 2px; min-width: 0; overflow-x: auto; } -.fc-switcher { display: flex; align-items: center; flex: none; align-self: center; gap: 2px; margin-left: auto; } -.fc-sw { display: inline-flex; align-items: center; gap: var(--space-1); height: var(--ctl-md); padding: 0 var(--space-3); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-muted); font-size: var(--fs-12); cursor: pointer; } -.fc-sw:hover { background: var(--bg-tertiary); color: var(--text-primary); } -.fc-sw.is-active { background: var(--bg-tertiary); color: var(--accent-color); } -.fc-sw:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } -@media (max-width: 899px) { .fc-sw-label { display: none; } .fc-sw { padding: 0 var(--space-2); } } +.fc-switcher { display: flex; align-items: center; flex: none; align-self: center; gap: 2px; margin-left: auto; padding: 2px; border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-1); } +.fc-sw { display: inline-flex; align-items: center; gap: var(--space-1); height: var(--ctl-sm); padding: 0 var(--space-3); border: 1px solid transparent; border-radius: var(--radius); background: transparent; color: var(--text-secondary); font-size: var(--fs-12); font-weight: 500; white-space: nowrap; cursor: pointer; } +.fc-sw:hover { background: var(--surface-raised); color: var(--text-primary); } +.fc-sw.is-active { border-color: var(--accent-line); background: var(--accent-soft); color: var(--accent-color); } +.fc-sw:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -2px; } +@media (max-width: 1023px) { .fc-sw { padding: 0 var(--space-2); } } +@media (max-width: 899px) { .fc-sw-label { display: none; } } .cv-stage { position: relative; min-width: 0; min-height: 0; overflow: hidden; background: var(--canvas-bg); } .fc-host { position: absolute; inset: 0; display: flex; min-width: 0; min-height: 0; } diff --git a/frontend/src/styles/status.css b/frontend/src/styles/status.css index 52394eb..4afdd24 100644 --- a/frontend/src/styles/status.css +++ b/frontend/src/styles/status.css @@ -91,6 +91,10 @@ .cv-jobs-pct { flex: none; width: 32px; text-align: right; font-variant-numeric: tabular-nums; } .cv-jobs-err { height: calc(var(--fs-11) * 1.4); margin-top: var(--space-1); overflow: hidden; color: var(--danger-text); font-size: var(--fs-11); line-height: 1.4; text-overflow: ellipsis; white-space: nowrap; } .cv-jobs-row[data-status="queued"] .cv-jobs-err { color: var(--text-secondary); } +.cv-jobs-group { display: flex; align-items: center; justify-content: space-between; height: 28px; padding: 0 var(--space-3); border-bottom: 1px solid var(--line-1); background: var(--surface-1); color: var(--text-muted); font-size: var(--fs-11); font-weight: 600; } +.cv-jobs-gcount { font-variant-numeric: tabular-nums; font-weight: 400; } +.cv-jobs-acts { display: grid; gap: var(--space-1); } +.cv-jobs-act2 { width: 84px; height: var(--ctl-sm); padding: 0; overflow: hidden; font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } .cv-jobs-act { width: 84px; height: var(--ctl-sm); padding: 0; overflow: hidden; font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } .cv-jobs [aria-disabled="true"] { opacity: 0.45; cursor: default; } diff --git a/frontend/src/styles/terminal.css b/frontend/src/styles/terminal.css index d52c436..c4bb26d 100644 --- a/frontend/src/styles/terminal.css +++ b/frontend/src/styles/terminal.css @@ -8,4 +8,4 @@ :root[data-ft-dock-side="right"] .cv-app > .ft-dock { grid-area: 2 / 2 / 3 / 3; } :root .cv-app > .cv-status { grid-area: 4 / 1 / 5 / -1; } :root[data-ft-dock="open"] .cv-home { bottom: calc(var(--cv-status-h) + var(--ft-dock-h)); right: var(--ft-dock-w); } -:root[data-ft-dock="open"] #toast-root { bottom: calc(var(--cv-status-h) + var(--ft-dock-h) + var(--space-3)); right: calc(var(--ft-dock-w) + var(--space-4)); } +:root[data-ft-dock="open"] #toast-root { bottom: calc(var(--cv-status-h) + var(--ft-dock-h) + var(--space-1)); left: calc((100vw - var(--ft-dock-w)) / 2); } diff --git a/frontend/src/styles/titlebar.css b/frontend/src/styles/titlebar.css index 5bffb07..d519788 100644 --- a/frontend/src/styles/titlebar.css +++ b/frontend/src/styles/titlebar.css @@ -1,8 +1,25 @@ +.cv-app .cv-titlebar { grid-template-columns: auto fit-content(40%) auto minmax(0, 1fr) auto; } +.cv-app .cv-titlebar > .cv-tb-save { grid-column: 3; } +.cv-app .cv-titlebar > .cv-title-tools { grid-column: 5; } +.cv-tb-save { box-sizing: content-box; width: 8ch; padding: 0 var(--space-2); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-secondary); font: inherit; font-size: var(--fs-12); text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; } +.cv-tb-save:hover { color: var(--text-primary); background: var(--surface-raised); } +.cv-tb-save:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.cv-tb-save.is-saved { color: var(--text-secondary); } +.cv-tb-save:not(.is-saved):not(.is-saving) { color: var(--accent-color); } +@media (max-width: 1259px) { .cv-titlebar .cv-tb-save { display: none; } } .cv-tt-btn { display: inline-grid; place-items: center; flex: none; width: var(--ctl-md); height: var(--ctl-md); padding: 0; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--surface-1); color: var(--text-secondary); cursor: pointer; } .cv-tt-btn:hover { color: var(--text-primary); background: var(--surface-raised); } .cv-tt-btn:disabled { opacity: 0.4; cursor: default; } .cv-tt-btn:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } -.cv-tt-btn[aria-expanded="true"] { border-color: var(--accent-line); background: var(--accent-soft); color: var(--accent-color); } +.cv-tt-btn[aria-expanded="true"], .cv-tt-btn.is-on { border-color: var(--accent-line); background: var(--accent-soft); color: var(--accent-color); } +.cv-tt-agents { position: relative; } +.cv-tt-run { position: absolute; right: 3px; bottom: 3px; width: 6px; height: 6px; border-radius: var(--radius-pill); background: var(--accent-color); box-shadow: 0 0 0 1.5px var(--surface-1); opacity: 0; transition: opacity 160ms ease; pointer-events: none; } +.cv-tt-agents.is-running .cv-tt-run { opacity: 1; animation: cv-tt-pulse 1.6s ease-in-out infinite; } +@keyframes cv-tt-pulse { 50% { opacity: 0.4; } } +@media (prefers-reduced-motion: reduce) { .cv-tt-agents.is-running .cv-tt-run { animation: none; } } +.cv-tt-badge { position: absolute; top: -5px; right: -5px; min-width: 15px; height: 15px; padding: 0 3px; border-radius: var(--radius-pill); background: var(--accent-color); color: var(--text-on-accent); font-size: var(--fs-10); font-weight: 600; line-height: 15px; text-align: center; box-shadow: 0 0 0 2px var(--surface-1); pointer-events: none; } +.cv-tt-badge[hidden] { display: none; } +:root[data-fc-panels="hidden"] .fc-host[data-host="scene"] .fc-sp-panel { display: none; } .cv-tt-sun, .cv-tt-moon { display: grid; place-items: center; } .cv-tt-sun[hidden], .cv-tt-moon[hidden] { display: none; } diff --git a/frontend/src/styles/tokens.css b/frontend/src/styles/tokens.css index a19d916..c3f2d1c 100644 --- a/frontend/src/styles/tokens.css +++ b/frontend/src/styles/tokens.css @@ -48,8 +48,8 @@ --font-ui: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Inter', 'Segoe UI', system-ui, sans-serif; --font-mono: ui-monospace, 'SF Mono', SFMono-Regular, Menlo, 'JetBrains Mono', monospace; - --fs-9: 9px; - --fs-10: 10px; + --fs-9: 11px; + --fs-10: 11px; --fs-11: 11px; --fs-12: 12px; --fs-13: 13px; @@ -131,6 +131,11 @@ --scene-frame-line: rgba(255, 255, 255, 0.85); --scene-frame-guide: rgba(255, 255, 255, 0.15); --scene-light-sky: #f5f6f8; + --scene-axis-x: #f05a6a; + --scene-axis-y: #8bd450; + --scene-axis-z: #4f9cf7; + --scene-solid: #b8bcc4; + --scene-wire: #e6e8ec; --fc-board-guide: #f43f5e; --cv-mask-rgb: 39, 187, 245; diff --git a/frontend/src/styles/tools.css b/frontend/src/styles/tools.css index 1d2ad14..6dafd7f 100644 --- a/frontend/src/styles/tools.css +++ b/frontend/src/styles/tools.css @@ -138,14 +138,14 @@ body.theme-light .fc-rb-hint[data-kind="warning"] { color: color-mix(in srgb, va .fc-bg-veil[hidden] { display: none; } .fc-bg-veil .icon { color: var(--accent-color); } -.fc-bg-bar { display: flex; align-items: center; gap: var(--space-3); width: min(720px, 100%); min-height: var(--ctl-lg); } -.fc-bg-note { flex: 1 1 auto; min-width: 0; margin: 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-12); line-height: 1.35; overflow-wrap: anywhere; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; } -.fc-bg-note[data-kind="ok"] { color: var(--ok-soft); } -.fc-bg-note[data-kind="warning"] { color: var(--warn); } -.fc-bg-note[data-kind="error"] { color: var(--danger-text); } -body.theme-light .fc-bg-note[data-kind="ok"] { color: color-mix(in srgb, var(--ok) 55%, var(--text-primary)); } -body.theme-light .fc-bg-note[data-kind="warning"] { color: color-mix(in srgb, var(--warn) 42%, var(--text-primary)); } -body.theme-light .fc-bg-note[data-kind="error"] { color: color-mix(in srgb, var(--danger) 55%, var(--text-primary)); } -.fc-bg-retry { flex: none; } -.fc-bg-retry[hidden] { display: none; } -.fc-bg-bar .fc-rb-cost { flex: none; } +.fc-rmbg-bar { display: flex; align-items: center; gap: var(--space-3); width: min(720px, 100%); min-height: var(--ctl-lg); } +.fc-rmbg-note { flex: 1 1 auto; min-width: 0; margin: 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-12); line-height: 1.35; overflow-wrap: anywhere; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; } +.fc-rmbg-note[data-kind="ok"] { color: var(--ok-soft); } +.fc-rmbg-note[data-kind="warning"] { color: var(--warn); } +.fc-rmbg-note[data-kind="error"] { color: var(--danger-text); } +body.theme-light .fc-rmbg-note[data-kind="ok"] { color: color-mix(in srgb, var(--ok) 55%, var(--text-primary)); } +body.theme-light .fc-rmbg-note[data-kind="warning"] { color: color-mix(in srgb, var(--warn) 42%, var(--text-primary)); } +body.theme-light .fc-rmbg-note[data-kind="error"] { color: color-mix(in srgb, var(--danger) 55%, var(--text-primary)); } +.fc-rmbg-retry { flex: none; } +.fc-rmbg-retry[hidden] { display: none; } +.fc-rmbg-bar .fc-rb-cost { flex: none; } diff --git a/frontend/src/styles/tooltip.css b/frontend/src/styles/tooltip.css new file mode 100644 index 0000000..45e869b --- /dev/null +++ b/frontend/src/styles/tooltip.css @@ -0,0 +1,6 @@ +.cv-tip { position: fixed; z-index: var(--z-context); display: flex; align-items: center; gap: var(--space-2); max-width: min(280px, calc(100vw - 2 * var(--space-2))); padding: var(--space-1) var(--space-2); border: 1px solid var(--border-light); border-radius: var(--radius-sm); background: var(--bg-tertiary); box-shadow: var(--shadow-md); color: var(--text-primary); font-size: var(--fs-11); line-height: 1.4; pointer-events: none; user-select: none; -webkit-user-select: none; } +.cv-tip[hidden] { display: none; } +.cv-tip-text { min-width: 0; overflow-wrap: anywhere; } +.cv-tip-keys { flex: none; min-width: 18px; padding: 0 var(--space-1); border: 1px solid var(--border-light); border-radius: var(--radius-sm); background: var(--bg-primary); color: var(--text-secondary); font: inherit; font-family: var(--font-mono); font-size: var(--fs-11); line-height: 16px; text-align: center; } +.cv-tip-keys[hidden] { display: none; } +.cv-sr-only { position: fixed; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; } diff --git a/frontend/src/styles/tour.css b/frontend/src/styles/tour.css new file mode 100644 index 0000000..c22e4f9 --- /dev/null +++ b/frontend/src/styles/tour.css @@ -0,0 +1,16 @@ +.fc-tour[hidden] { display: none; } +.fc-tour-ring { position: fixed; z-index: var(--z-context); border: 2px solid var(--accent-color); border-radius: var(--radius-md); box-shadow: 0 0 0 4px var(--accent-color-dim); pointer-events: none; } +.fc-tour-card { position: fixed; z-index: var(--z-context); left: 0; top: 0; box-sizing: border-box; width: 300px; max-width: calc(100vw - 16px); display: grid; gap: var(--space-2); padding: var(--space-3) var(--space-4); border: 1px solid var(--accent-line); border-radius: var(--radius-lg); background: var(--surface-2); color: var(--text-primary); box-shadow: var(--shadow-lg); outline: none; } +.fc-tour-title { margin: 0; font-size: var(--fs-14); font-weight: 600; } +.fc-tour-body { margin: 0; color: var(--text-secondary); font-size: var(--fs-13); line-height: 1.45; } +.fc-tour-foot { display: flex; align-items: center; gap: var(--space-2); margin-top: var(--space-1); } +.fc-tour-foot [hidden] { display: none; } +.fc-tour-dots { display: flex; gap: 5px; margin-right: auto; } +.fc-tour-dots i { width: 6px; height: 6px; border-radius: var(--radius-pill); background: var(--line-3); } +.fc-tour-dots i.is-on { background: var(--accent-color); } +.fc-tour-arrow { position: absolute; width: 12px; height: 12px; background: var(--surface-2); border: 1px solid var(--accent-line); transform: translate(-50%, -50%) rotate(45deg); pointer-events: none; } +.fc-tour-card[data-side="bottom"] .fc-tour-arrow { top: 0; border-right: 0; border-bottom: 0; } +.fc-tour-card[data-side="top"] .fc-tour-arrow { top: 100%; border-left: 0; border-top: 0; } +.fc-tour-card[data-side="right"] .fc-tour-arrow { left: 0; border-top: 0; border-right: 0; } +.fc-tour-card[data-side="left"] .fc-tour-arrow { left: 100%; border-bottom: 0; border-left: 0; } +.fc-whats-new { display: grid; gap: var(--space-2); margin: 0; padding: 0 0 0 var(--space-5); color: var(--text-secondary); font-size: var(--fs-13); line-height: 1.45; } diff --git a/frontend/src/ui/about.ts b/frontend/src/ui/about.ts index b1d1476..24a468a 100644 --- a/frontend/src/ui/about.ts +++ b/frontend/src/ui/about.ts @@ -60,11 +60,12 @@ function build(): Dialog { grid.append(node); } d.body.append( - el(`

${APP_NAME} v${VERSION}

`), - line('A studio for images, video, audio, 3D objects and worlds, with a local library.', 'cv-dialog-note'), + el(`

${APP_NAME} v${VERSION}
by nodemode-ai

`), + line('A studio for images, video, audio, 3D models and worlds, with a local library.', 'cv-dialog-note'), grid, line('Apache-2.0 · Copyright 2026 NodeAgentc, Inc.', 'cv-note'), ); + d.button('Starter library credits', 'ghost', () => void import('./library/starter/starter-credits').then((m) => m.showStarterCredits())); d.button('OK', 'primary', () => d.close()); put('address', location.origin); put('window', `v${VERSION}`); diff --git a/frontend/src/ui/board/canvas/arrange.ts b/frontend/src/ui/board/canvas/arrange.ts new file mode 100644 index 0000000..a566534 --- /dev/null +++ b/frontend/src/ui/board/canvas/arrange.ts @@ -0,0 +1,174 @@ +import type { BoardNode } from '../../../engine/board/types'; +import { Tree, unionRects, type Pt, type Rect } from './geom'; +import { newId } from './ids'; +import type { Guide } from './snap'; + +export type Align = 'left' | 'centre' | 'right' | 'top' | 'middle' | 'bottom'; +export type Axis = 'h' | 'v'; + +const HORIZONTAL: ReadonlySet = new Set(['left', 'centre', 'right']); + +function movable(tree: Tree, ids: readonly string[]): BoardNode[] { + return ids.map((id) => tree.byId.get(id)).filter((n): n is BoardNode => !!n && !n.parent && !n.locked); +} + +function shifted(nodes: readonly BoardNode[], moves: ReadonlyMap): BoardNode[] { + return nodes.map((n) => { + const d = moves.get(n.id); + return d && (d.x || d.y) ? { ...n, x: n.x + d.x, y: n.y + d.y } : n; + }); +} + +const edge = (b: Rect, how: Align): number => + how === 'left' ? b.x : how === 'centre' ? b.x + b.w / 2 : how === 'right' ? b.x + b.w : how === 'top' ? b.y : how === 'middle' ? b.y + b.h / 2 : b.y + b.h; + +export function alignNodes(nodes: readonly BoardNode[], ids: readonly string[], how: Align): { nodes: BoardNode[]; guides: Guide[] } | null { + const tree = new Tree(nodes); + const list = movable(tree, ids); + if (list.length < 2) return null; + const boxes = list.map((n) => [n.id, tree.bounds(n)] as const); + const all = unionRects(boxes.map((b) => b[1])); + if (!all) return null; + const target = edge(all, how); + const horiz = HORIZONTAL.has(how); + const moves = new Map(); + for (const [id, b] of boxes) { + const d = target - edge(b, how); + moves.set(id, horiz ? { x: d, y: 0 } : { x: 0, y: d }); + } + const guide: Guide = horiz ? { axis: 'x', at: target, from: all.y, to: all.y + all.h } : { axis: 'y', at: target, from: all.x, to: all.x + all.w }; + return { nodes: shifted(nodes, moves), guides: [guide] }; +} + +export function distributeNodes(nodes: readonly BoardNode[], ids: readonly string[], axis: Axis): BoardNode[] | null { + const tree = new Tree(nodes); + const list = movable(tree, ids); + if (list.length < 3) return null; + const h = axis === 'h'; + const boxes = list + .map((n) => ({ id: n.id, b: tree.bounds(n) })) + .sort((p, q) => (h ? p.b.x + p.b.w / 2 - (q.b.x + q.b.w / 2) : p.b.y + p.b.h / 2 - (q.b.y + q.b.h / 2))); + const lo = Math.min(...boxes.map((x) => (h ? x.b.x : x.b.y))); + const hi = Math.max(...boxes.map((x) => (h ? x.b.x + x.b.w : x.b.y + x.b.h))); + const used = boxes.reduce((s, x) => s + (h ? x.b.w : x.b.h), 0); + const gap = (hi - lo - used) / (boxes.length - 1); + const moves = new Map(); + let at = lo; + for (const x of boxes) { + const d = at - (h ? x.b.x : x.b.y); + moves.set(x.id, h ? { x: d, y: 0 } : { x: 0, y: d }); + at += (h ? x.b.w : x.b.h) + gap; + } + return shifted(nodes, moves); +} + +export function duplicateNodes(nodes: readonly BoardNode[], roots: readonly string[], offset: Pt): { added: BoardNode[]; roots: string[] } { + const tree = new Tree(nodes); + const map = new Map(); + const walk = (n: BoardNode): void => { + map.set(n.id, newId()); + for (const c of tree.children(n.id)) walk(c); + }; + for (const id of roots) { + const n = tree.byId.get(id); + if (n && !n.parent) walk(n); + } + const added: BoardNode[] = []; + for (const n of nodes) { + if (n.kind === 'arrow') { + const a = map.get(n.from ?? ''); + const b = map.get(n.to ?? ''); + if (a && b) added.push({ ...n, id: newId(), from: a, to: b }); + continue; + } + const id = map.get(n.id); + if (!id) continue; + const root = !n.parent; + const copy: BoardNode = { ...n, id, asset: n.asset ? { ...n.asset } : null, parent: n.parent ? map.get(n.parent) ?? null : null }; + delete copy.locked; + if (root) { + copy.x += offset.x; + copy.y += offset.y; + } + added.push(copy); + } + return { added, roots: roots.map((id) => map.get(id)).filter((x): x is string => !!x) }; +} + +export function connectNodes(nodes: readonly BoardNode[], ids: readonly string[]): BoardNode[] | null { + const tree = new Tree(nodes); + const ends = ids.filter((id) => tree.byId.has(id)); + if (ends.length < 2) return null; + const have = new Set(nodes.filter((n) => n.kind === 'arrow').map((n) => `${n.from}>${n.to}`)); + const made: BoardNode[] = []; + for (let i = 0; i + 1 < ends.length; i++) { + const key = `${ends[i]}>${ends[i + 1]}`; + if (have.has(key)) continue; + have.add(key); + made.push({ id: newId(), kind: 'arrow', asset: null, text: '', x: 0, y: 0, width: 1, height: 1, rotation: 0, parent: null, from: ends[i], to: ends[i + 1] }); + } + return made.length ? [...nodes, ...made] : null; +} + +export function toggleLock(nodes: readonly BoardNode[], ids: readonly string[]): { nodes: BoardNode[]; locked: boolean } | null { + const want = new Set(ids); + const list = nodes.filter((n) => want.has(n.id) && n.kind !== 'arrow'); + if (!list.length) return null; + const lock = list.some((n) => !n.locked); + return { + locked: lock, + nodes: nodes.map((n) => { + if (!want.has(n.id) || n.kind === 'arrow') return n; + const copy = { ...n }; + if (lock) copy.locked = true; + else delete copy.locked; + return copy; + }), + }; +} + +export function unlockAll(nodes: readonly BoardNode[]): BoardNode[] | null { + if (!nodes.some((n) => n.locked)) return null; + return nodes.map((n) => { + if (!n.locked) return n; + const copy = { ...n }; + delete copy.locked; + return copy; + }); +} + +function clipToBox(from: Pt, to: Pt, b: Rect): Pt { + const dx = to.x - from.x; + const dy = to.y - from.y; + const hw = b.w / 2; + const hh = b.h / 2; + const k = Math.min(dx ? hw / Math.abs(dx) : Infinity, dy ? hh / Math.abs(dy) : Infinity); + return k < 1 ? { x: from.x + dx * k, y: from.y + dy * k } : from; +} + +export function arrowEnds(tree: Tree, n: BoardNode): { a: Pt; b: Pt } | null { + const p = tree.byId.get(n.from ?? ''); + const q = tree.byId.get(n.to ?? ''); + if (!p || !q) return null; + const bp = tree.bounds(p); + const bq = tree.bounds(q); + const cp = { x: bp.x + bp.w / 2, y: bp.y + bp.h / 2 }; + const cq = { x: bq.x + bq.w / 2, y: bq.y + bq.h / 2 }; + if (Math.hypot(cq.x - cp.x, cq.y - cp.y) < 1) return null; + return { a: clipToBox(cp, cq, bp), b: clipToBox(cq, cp, bq) }; +} + +export function arrowAt(tree: Tree, p: Pt, tolerance: number): BoardNode | null { + for (let i = tree.nodes.length - 1; i >= 0; i--) { + const n = tree.nodes[i]; + if (n.kind !== 'arrow') continue; + const e = arrowEnds(tree, n); + if (!e) continue; + const vx = e.b.x - e.a.x; + const vy = e.b.y - e.a.y; + const len = vx * vx + vy * vy || 1; + const k = Math.max(0, Math.min(1, ((p.x - e.a.x) * vx + (p.y - e.a.y) * vy) / len)); + if (Math.hypot(e.a.x + vx * k - p.x, e.a.y + vy * k - p.y) <= tolerance) return n; + } + return null; +} diff --git a/frontend/src/ui/board/canvas/export.ts b/frontend/src/ui/board/canvas/export.ts new file mode 100644 index 0000000..3b64c6e --- /dev/null +++ b/frontend/src/ui/board/canvas/export.ts @@ -0,0 +1,69 @@ +import type { BoardNode } from '../../../engine/board/types'; +import { t } from '../../i18n'; +import { saveBlob } from '../../save-media'; +import { toast } from '../../toasts'; +import { Tree } from './geom'; +import { MediaCache } from './media'; +import { worldBox } from './ops'; +import { Renderer } from './render'; +import type { CanvasView } from './view'; + +const PAD = 32; +const MAX_SIDE = 8192; +const WAIT_MS = 12000; + +function subtree(nodes: readonly BoardNode[], roots: readonly string[]): BoardNode[] { + const keep = new Set(roots); + let grew = true; + while (grew) { + grew = false; + for (const n of nodes) if (n.parent && keep.has(n.parent) && !keep.has(n.id)) { + keep.add(n.id); + grew = true; + } + } + return nodes.filter((n) => keep.has(n.id)).map((n) => (roots.includes(n.id) ? { ...n, parent: null } : n)); +} + +export async function renderBoard(nodes: readonly BoardNode[], scale: number): Promise { + const tree = new Tree(nodes); + const box = worldBox(tree, tree.top.map((n) => n.id)); + if (!box || !(box.w > 0) || !(box.h > 0)) return null; + const w = box.w + PAD * 2; + const h = box.h + PAD * 2; + const s = Math.max(0.05, Math.min(scale, MAX_SIDE / w, MAX_SIDE / h)); + const canvas = document.createElement('canvas'); + let changed = (): void => undefined; + const media = new MediaCache(() => changed()); + const r = new Renderer(canvas, media); + r.resize(w, h, s); + const state = { tree, vp: { x: PAD - box.x, y: PAD - box.y, zoom: 1 }, selection: new Set(), hover: null, box: null, guides: [], marquee: null, lasso: null, editing: null, videos: new Map(), plain: true }; + const pending = (): boolean => + nodes.some((n) => (n.kind === 'image' || n.kind === 'video') && n.asset && media.get(n.asset.$media, n.kind === 'video', Math.max(n.width, n.height) * s) === null); + const until = Date.now() + WAIT_MS; + while (pending() && Date.now() < until) await new Promise((done) => { + changed = done; + window.setTimeout(done, 250); + }); + r.draw(state); + media.dispose(); + return new Promise((done) => canvas.toBlob((b) => done(b), 'image/png')); +} + +export async function exportBoard(view: CanvasView, scale: number, selectionOnly: boolean): Promise { + const all = view.nodes(); + const nodes = selectionOnly ? subtree(all, view.topSelection()) : all; + if (!nodes.length) { + toast(t('There is nothing on the board to export.'), 'info', { key: 'board-export' }); + return; + } + toast(t('Preparing the picture...'), 'info', { key: 'board-export' }); + try { + const blob = await renderBoard(nodes, scale); + if (!blob) throw new Error('empty'); + await saveBlob(blob, selectionOnly ? 'board-selection.png' : 'board.png', 'Export the board'); + } catch (err) { + console.error('[board] export', err); + toast(t('The picture could not be made.'), 'error', { key: 'board-export' }); + } +} diff --git a/frontend/src/ui/board/canvas/geom.ts b/frontend/src/ui/board/canvas/geom.ts index b3edf76..b3e6b02 100644 --- a/frontend/src/ui/board/canvas/geom.ts +++ b/frontend/src/ui/board/canvas/geom.ts @@ -46,8 +46,9 @@ export class Tree { private readonly mats = new Map(); constructor(readonly nodes: readonly BoardNode[]) { - for (const n of nodes) this.byId.set(n.id, n); + for (const n of nodes) if (n.kind !== 'arrow') this.byId.set(n.id, n); for (const n of nodes) { + if (n.kind === 'arrow') continue; const parent = n.parent && this.byId.has(n.parent) ? n.parent : null; const list = this.kids.get(parent); if (list) list.push(n); diff --git a/frontend/src/ui/board/canvas/icons.ts b/frontend/src/ui/board/canvas/icons.ts index 04fa291..44b45e9 100644 --- a/frontend/src/ui/board/canvas/icons.ts +++ b/frontend/src/ui/board/canvas/icons.ts @@ -13,5 +13,6 @@ Object.assign(ICONS, { bcPack: wrap(''), bcCluster: wrap(''), bcMagnet: wrap(''), - bcPlay: wrap(''), + bcAlign: wrap(''), + bcPlay:wrap(''), }); diff --git a/frontend/src/ui/board/canvas/keys.ts b/frontend/src/ui/board/canvas/keys.ts index d6b86bf..2217437 100644 --- a/frontend/src/ui/board/canvas/keys.ts +++ b/frontend/src/ui/board/canvas/keys.ts @@ -3,6 +3,7 @@ import type { BoardStore } from '../../../engine/board/store'; import { commands, type Command } from '../../../engine/commands'; import { shortcuts } from '../../../engine/shortcuts'; import { pickLibrary, pickUpload } from './add'; +import { exportBoard } from './export'; import type { CanvasView } from './view'; export const CMD = { @@ -24,6 +25,21 @@ export const CMD = { pack: 'board.canvasPack', autoGroup: 'board.canvasAutoGroup', snapping: 'board.canvasSnapping', + exportBoard: 'board.canvasExport', + exportBoard2x: 'board.canvasExport2x', + exportSelection: 'board.canvasExportSelection', + alignLeft: 'board.canvasAlignLeft', + alignCentre: 'board.canvasAlignCentre', + alignRight: 'board.canvasAlignRight', + alignTop: 'board.canvasAlignTop', + alignMiddle: 'board.canvasAlignMiddle', + alignBottom: 'board.canvasAlignBottom', + distributeH: 'board.canvasDistributeH', + distributeV: 'board.canvasDistributeV', + lock: 'board.canvasLock', + unlockAll: 'board.canvasUnlockAll', + connect: 'board.canvasConnect', + duplicate: 'board.canvasDuplicate', } as const; interface Active { view: CanvasView; host: HTMLElement; store: BoardStore } @@ -64,8 +80,25 @@ const RUN: Record void> = { [CMD.pack]: (v) => v.pack(), [CMD.autoGroup]: (v) => v.autoGroup(), [CMD.snapping]: (v) => v.toggleSnapping(), + [CMD.exportBoard]: (v) => void exportBoard(v, 1, false), + [CMD.exportBoard2x]: (v) => void exportBoard(v, 2, false), + [CMD.exportSelection]: (v) => void exportBoard(v, 2, true), + [CMD.alignLeft]: (v) => v.align('left'), + [CMD.alignCentre]: (v) => v.align('centre'), + [CMD.alignRight]: (v) => v.align('right'), + [CMD.alignTop]: (v) => v.align('top'), + [CMD.alignMiddle]: (v) => v.align('middle'), + [CMD.alignBottom]: (v) => v.align('bottom'), + [CMD.distributeH]: (v) => v.distribute('h'), + [CMD.distributeV]: (v) => v.distribute('v'), + [CMD.lock]: (v) => v.toggleLock(), + [CMD.unlockAll]: (v) => v.unlockAll(), + [CMD.connect]: (v) => v.connect(), + [CMD.duplicate]: (v) => v.duplicate(), }; +const ALIGNS: readonly string[] = [CMD.alignLeft, CMD.alignCentre, CMD.alignRight, CMD.alignTop, CMD.alignMiddle, CMD.alignBottom]; + const EXTRA: Record boolean; ready?: (v: CanvasView) => boolean }> = { [CMD.upload]: { label: 'Upload pictures or videos' }, [CMD.library]: { label: 'Pick from the library' }, @@ -73,11 +106,20 @@ const EXTRA: Record boolea [CMD.pack]: { label: 'Pack as a collage', ready: (v) => v.layoutReady() }, [CMD.autoGroup]: { label: 'Group nearby items', ready: (v) => v.layoutReady() }, [CMD.snapping]: { label: 'Snapping', checked: (v) => v.port.snapping() }, + [CMD.exportBoard]: { label: 'Export the board as a picture', ready: (v) => v.nodes().length > 0 }, + [CMD.exportBoard2x]: { label: 'Export the board at double size', ready: (v) => v.nodes().length > 0 }, }; const READY: Record boolean> = { [CMD.group]: (v) => v.canGroup(), [CMD.ungroup]: (v) => v.canUngroup(), + ...Object.fromEntries(ALIGNS.map((id) => [id, (v: CanvasView) => v.topSelection().length >= 2])), + [CMD.distributeH]: (v) => v.topSelection().length >= 3, + [CMD.distributeV]: (v) => v.topSelection().length >= 3, + [CMD.connect]: (v) => v.topSelection().length >= 2, + [CMD.lock]: (v) => v.topSelection().length > 0, + [CMD.duplicate]: (v) => v.topSelection().length > 0, + [CMD.unlockAll]: (v) => v.hasLocked(), }; export function registerCanvasCommands(): void { diff --git a/frontend/src/ui/board/canvas/layout.ts b/frontend/src/ui/board/canvas/layout.ts index 72067a4..6cafacc 100644 --- a/frontend/src/ui/board/canvas/layout.ts +++ b/frontend/src/ui/board/canvas/layout.ts @@ -9,8 +9,9 @@ const MIN_ROW_WIDTH = ROW_HEIGHT * 2; export function pickTargets(nodes: readonly BoardNode[], selected: ReadonlySet): string[] { const tree = new Tree(nodes); - const chosen = tree.top.filter((n) => selected.has(n.id)); - return (chosen.length >= 2 ? chosen : tree.top).map((n) => n.id); + const free = tree.top.filter((n) => !n.locked); + const chosen = free.filter((n) => selected.has(n.id)); + return (chosen.length >= 2 ? chosen : free).map((n) => n.id); } export function packCollage(nodes: readonly BoardNode[], targets: readonly string[]): BoardNode[] | null { diff --git a/frontend/src/ui/board/canvas/ops.ts b/frontend/src/ui/board/canvas/ops.ts index ce669ff..4eefefa 100644 --- a/frontend/src/ui/board/canvas/ops.ts +++ b/frontend/src/ui/board/canvas/ops.ts @@ -43,7 +43,7 @@ export function removeWithDescendants(nodes: readonly BoardNode[], ids: Readonly gone.add(id); for (const d of tree.descendants(id)) gone.add(d.id); } - return nodes.filter((n) => !gone.has(n.id)); + return nodes.filter((n) => !gone.has(n.id) && !(n.kind === 'arrow' && (gone.has(n.from ?? '') || gone.has(n.to ?? '')))); } export function applyBox(nodes: readonly BoardNode[], id: string, box: Partial>): BoardNode[] { @@ -137,7 +137,7 @@ export function fitToGrid(nodes: readonly BoardNode[], ids: ReadonlySet) const all = ids.size === 0; const topIds = new Set(tree.top.map((n) => n.id)); return nodes.map((n) => { - if (!topIds.has(n.id) || (!all && !ids.has(n.id))) return n; + if (!topIds.has(n.id) || n.locked || (!all && !ids.has(n.id))) return n; return { ...n, x: Math.round(n.x / GRID_STEP) * GRID_STEP, y: Math.round(n.y / GRID_STEP) * GRID_STEP }; }); } diff --git a/frontend/src/ui/board/canvas/pointer.ts b/frontend/src/ui/board/canvas/pointer.ts index e4d79d7..e2acd24 100644 --- a/frontend/src/ui/board/canvas/pointer.ts +++ b/frontend/src/ui/board/canvas/pointer.ts @@ -2,12 +2,14 @@ import type { BoardNode } from '../../../engine/board/types'; import { Tree, apply, invert, type Pt, type Rect } from './geom'; import { axes, handleAt, handleSign, oppositeOf, pickHandle, type HandleId, type TransformBox } from './handles'; import { MIN_SIZE, applyBox, normaliseAngle, worldBox } from './ops'; +import { arrowAt, duplicateNodes } from './arrange'; import { snapMove } from './snap'; import { fitHeight } from './text'; import type { CanvasView } from './view'; export const DRAG_PX = 4; const VIDEO_BADGE_PX = 16; +const ARROW_HIT_PX = 6; const CURSORS: Record = { nw: 'nwse-resize', se: 'nwse-resize', ne: 'nesw-resize', sw: 'nesw-resize', n: 'ns-resize', s: 'ns-resize', e: 'ew-resize', w: 'ew-resize', rot: 'grab', @@ -15,7 +17,7 @@ const CURSORS: Record = { type Gesture = | { kind: 'pan'; id: number; x: number; y: number } - | { kind: 'move'; id: number; sx: number; sy: number; base: BoardNode[]; tree: Tree; ids: Set; box: Rect; others: Rect[]; moved: boolean; toggleOff: string | null; narrow: string | null } + | { kind: 'move'; id: number; sx: number; sy: number; base: BoardNode[]; tree: Tree; ids: Set; box: Rect; others: Rect[]; moved: boolean; toggleOff: string | null; narrow: string | null; dup: boolean; copies: string[] | null } | { kind: 'resize'; id: number; handle: Exclude; base: BoardNode[]; tree: Tree; ids: string[]; box: TransformBox; changed: boolean } | { kind: 'rotate'; id: number; base: BoardNode[]; tree: Tree; ids: string[]; box: TransformBox; a0: number; changed: boolean } | { kind: 'marquee'; id: number; sx: number; sy: number; start: Pt; began: boolean; additive: boolean; keep: Set } @@ -126,10 +128,16 @@ export class PointerInput { } else if (v.selection.size > 1) { narrow = hit.id; } - const ids = new Set(v.topSelection()); + const dup = e.altKey; + const ids = new Set(v.topSelection().filter((id) => dup || !tree.byId.get(id)?.locked)); const rect = worldBox(tree, ids) ?? { x: 0, y: 0, w: 0, h: 0 }; - const others = tree.top.filter((n) => !ids.has(n.id)).map((n) => tree.bounds(n)); - this.begin(e, { kind: 'move', id: e.pointerId, sx: e.clientX, sy: e.clientY, base: v.nodes().slice(), tree, ids, box: rect, others, moved: false, toggleOff, narrow }); + const others = tree.top.filter((n) => dup || !ids.has(n.id)).map((n) => tree.bounds(n)); + this.begin(e, { kind: 'move', id: e.pointerId, sx: e.clientX, sy: e.clientY, base: v.nodes().slice(), tree, ids, box: rect, others, moved: false, toggleOff, narrow, dup, copies: null }); + return; + } + const arrow = arrowAt(tree, p, ARROW_HIT_PX / v.vp.zoom); + if (arrow) { + v.select(e.shiftKey ? [...v.selection, arrow.id] : [arrow.id]); return; } const keep = new Set(e.shiftKey ? v.selection : []); @@ -237,12 +245,19 @@ export class PointerInput { g.moved = true; g.toggleOff = null; g.narrow = null; + if (g.dup && g.ids.size) { + const res = duplicateNodes(g.base, Array.from(g.ids), { x: 0, y: 0 }); + g.base = [...g.base, ...res.added]; + g.ids = new Set(res.roots); + g.copies = res.roots; + } } + if (!g.ids.size) return; const z = v.vp.zoom; let dx = (e.clientX - g.sx) / z; let dy = (e.clientY - g.sy) / z; v.guides = []; - if (v.port.snapping() && !e.altKey) { + if (v.port.snapping() && !e.shiftKey) { const s = snapMove({ x: g.box.x + dx, y: g.box.y + dy, w: g.box.w, h: g.box.h }, g.others, z); dx += s.dx; dy += s.dy; @@ -334,8 +349,10 @@ export class PointerInput { break; case 'move': { v.guides = []; - if (ok && g.moved && v.draft) v.commit(v.draft); - else { + if (ok && g.moved && v.draft) { + v.commit(v.draft); + if (g.copies) v.select(g.copies); + } else { v.draft = null; if (ok && g.toggleOff) v.select([...v.selection].filter((id) => id !== g.toggleOff)); else if (ok && g.narrow) v.select([g.narrow]); diff --git a/frontend/src/ui/board/canvas/render.ts b/frontend/src/ui/board/canvas/render.ts index 3d73281..c00733e 100644 --- a/frontend/src/ui/board/canvas/render.ts +++ b/frontend/src/ui/board/canvas/render.ts @@ -1,5 +1,6 @@ import type { BoardNode, Viewport } from '../../../engine/board/types'; import { GRID_STEP } from '../../../engine/board/types'; +import { arrowEnds } from './arrange'; import { Tree, localMat, type Pt, type Rect, rectsIntersect } from './geom'; import { HANDLE_PX, RESIZE_HANDLES, boxCorners, handleAt, type TransformBox } from './handles'; import type { MediaCache } from './media'; @@ -20,6 +21,7 @@ export interface DrawState { lasso: readonly Pt[] | null; editing: string | null; videos: ReadonlyMap; + plain?: boolean; } interface Palette { @@ -94,8 +96,8 @@ export class Renderer { return this.pal; } - resize(w: number, h: number): void { - const dpr = Math.min(2, window.devicePixelRatio || 1); + resize(w: number, h: number, scale?: number): void { + const dpr = scale ?? Math.min(2, window.devicePixelRatio || 1); if (w === this.w && h === this.h && dpr === this.dpr) return; this.w = w; this.h = h; @@ -109,7 +111,7 @@ export class Renderer { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.fillStyle = pal.bg; ctx.fillRect(0, 0, this.w, this.h); - this.dots(s.vp); + if (!s.plain) this.dots(s.vp); const z = s.vp.zoom; ctx.setTransform(dpr * z, 0, 0, dpr * z, dpr * s.vp.x, dpr * s.vp.y); ctx.imageSmoothingEnabled = true; @@ -119,10 +121,64 @@ export class Renderer { if (!rectsIntersect(s.tree.bounds(n), view)) continue; this.node(n, s, z); } + this.arrows(s, z); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + if (!s.plain) this.locks(s); this.overlay(s); } + private arrows(s: DrawState, z: number): void { + const { ctx, pal } = this; + for (const n of s.tree.nodes) { + if (n.kind !== 'arrow') continue; + const e = arrowEnds(s.tree, n); + if (!e) continue; + const on = s.selection.has(n.id); + const colour = on ? pal.accent : pal.muted; + const head = Math.min(12 / z, Math.hypot(e.b.x - e.a.x, e.b.y - e.a.y) / 2); + const ang = Math.atan2(e.b.y - e.a.y, e.b.x - e.a.x); + ctx.strokeStyle = colour; + ctx.fillStyle = colour; + ctx.lineWidth = (on ? 2.5 : 2) / z; + ctx.lineCap = 'round'; + ctx.beginPath(); + ctx.moveTo(e.a.x, e.a.y); + ctx.lineTo(e.b.x - Math.cos(ang) * head * 0.8, e.b.y - Math.sin(ang) * head * 0.8); + ctx.stroke(); + ctx.beginPath(); + ctx.moveTo(e.b.x, e.b.y); + ctx.lineTo(e.b.x - Math.cos(ang - 0.45) * head, e.b.y - Math.sin(ang - 0.45) * head); + ctx.lineTo(e.b.x - Math.cos(ang + 0.45) * head, e.b.y - Math.sin(ang + 0.45) * head); + ctx.closePath(); + ctx.fill(); + } + } + + private locks(s: DrawState): void { + const { ctx, pal } = this; + for (const n of s.tree.top) { + if (!n.locked) continue; + const b = s.tree.bounds(n); + if (Math.min(b.w, b.h) * s.vp.zoom < 32) continue; + const p = this.toScreen({ x: b.x + b.w, y: b.y }, s.vp); + const x = p.x - 20; + const y = p.y + 6; + ctx.fillStyle = pal.card; + ctx.globalAlpha = 0.85; + ctx.beginPath(); + ctx.arc(x + 7, y + 7, 10, 0, Math.PI * 2); + ctx.fill(); + ctx.globalAlpha = 1; + ctx.strokeStyle = pal.text; + ctx.fillStyle = pal.text; + ctx.lineWidth = 1.4; + ctx.beginPath(); + ctx.arc(x + 7, y + 5, 2.6, Math.PI, 0); + ctx.stroke(); + ctx.fillRect(x + 3.5, y + 5.5, 7, 5.5); + } + } + private dots(vp: Viewport): void { const { ctx, pal } = this; const step = dotStep(vp.zoom); diff --git a/frontend/src/ui/board/canvas/toolbar.ts b/frontend/src/ui/board/canvas/toolbar.ts index 20828a6..4e41786 100644 --- a/frontend/src/ui/board/canvas/toolbar.ts +++ b/frontend/src/ui/board/canvas/toolbar.ts @@ -28,6 +28,8 @@ export function mountToolbar(root: HTMLElement, view: CanvasView, onHint: () => `', ); const zoom = el( @@ -50,10 +52,41 @@ export function mountToolbar(root: HTMLElement, view: CanvasView, onHint: () => menu.openAt(r.left, r.bottom + 6); setAttr(add, 'aria-expanded', 'true'); }); + const outMenu = new PopupMenu(null, true); + outMenu.setItems([CMD.exportBoard, CMD.exportBoard2x, CMD.exportSelection, 'board.makePrompt', '-', 'board.extractPalette', 'board.sendCanvas', 'board.sendScene', 'board.sendEdit', '-', 'board.exportMedia']); + const out = q(bar, '[data-out]'); + outMenu.onClose = () => setAttr(out, 'aria-expanded', 'false'); + out.addEventListener('click', () => { + if (outMenu.isOpen) { + outMenu.close(); + return; + } + const r = out.getBoundingClientRect(); + outMenu.openAt(r.left, r.bottom + 6); + setAttr(out, 'aria-expanded', 'true'); + }); + const arrMenu = new PopupMenu(null, true); + arrMenu.setItems([ + CMD.alignLeft, CMD.alignCentre, CMD.alignRight, '-', CMD.alignTop, CMD.alignMiddle, CMD.alignBottom, '-', + CMD.distributeH, CMD.distributeV, '-', CMD.duplicate, CMD.connect, '-', CMD.lock, CMD.unlockAll, + ]); + const arr = q(bar, '[data-arrange]'); + arrMenu.onClose = () => setAttr(arr, 'aria-expanded', 'false'); + arr.addEventListener('click', () => { + if (arrMenu.isOpen) { + arrMenu.close(); + return; + } + const r = arr.getBoundingClientRect(); + arrMenu.openAt(r.left, r.bottom + 6); + setAttr(arr, 'aria-expanded', 'true'); + }); const onKey = (e: KeyboardEvent): void => { - if (e.key === 'Escape' && menu.isOpen) { + if (e.key === 'Escape' && (menu.isOpen || outMenu.isOpen || arrMenu.isOpen)) { e.stopPropagation(); menu.close(); + outMenu.close(); + arrMenu.close(); } }; window.addEventListener('keydown', onKey, true); @@ -84,6 +117,8 @@ export function mountToolbar(root: HTMLElement, view: CanvasView, onHint: () => } setText(pct, `${Math.round(view.vp.zoom * 100)}%`); menu.refresh(); + outMenu.refresh(); + arrMenu.refresh(); }; const offCommands = commands.on('change', refresh); const offKeys = shortcuts.on('change', refresh); @@ -96,6 +131,10 @@ export function mountToolbar(root: HTMLElement, view: CanvasView, onHint: () => window.removeEventListener('keydown', onKey, true); menu.close(); menu.panel.remove(); + outMenu.close(); + outMenu.panel.remove(); + arrMenu.close(); + arrMenu.panel.remove(); bar.remove(); zoom.remove(); hint.remove(); diff --git a/frontend/src/ui/board/canvas/view.ts b/frontend/src/ui/board/canvas/view.ts index 3851bbb..e623c84 100644 --- a/frontend/src/ui/board/canvas/view.ts +++ b/frontend/src/ui/board/canvas/view.ts @@ -2,6 +2,7 @@ import type { BoardNode, Viewport } from '../../../engine/board/types'; import { Emitter } from '../../../engine/emitter'; import { toast } from '../../toasts'; import { t } from '../../i18n'; +import { alignNodes, connectNodes, distributeNodes, duplicateNodes, toggleLock, unlockAll, type Align, type Axis } from './arrange'; import { TextEditor } from './editor'; import { Tree, clamp, pointInPoly, polyHitsRect, rectsIntersect, type Pt, type Rect } from './geom'; import { boxOfRect, type TransformBox } from './handles'; @@ -20,6 +21,7 @@ export const ZOOM_MAX = 8; export const ZOOM_STEP = 1.1; export const FIT_PAD = 48; const SAVE_VIEW_MS = 220; +const FLASH_MS = 700; export class CanvasView { readonly events = new Emitter<{ change: []; tool: []; live: [] }>(); @@ -38,6 +40,7 @@ export class CanvasView { private treeFor: readonly BoardNode[] | null = null; private raf = 0; private saveTimer = 0; + private flashTimer = 0; private disposed = false; private offscreenShown = false; frames = 0; @@ -121,7 +124,7 @@ export class CanvasView { transformBox(tree: Tree): TransformBox | null { const ids = this.topSelection(tree); - if (!ids.length) return null; + if (!ids.length || ids.some((id) => tree.byId.get(id)?.locked)) return null; if (ids.length === 1) { const n = tree.byId.get(ids[0]); if (!n) return null; @@ -243,10 +246,79 @@ export class CanvasView { } deleteSelection(): void { - const ids = this.topSelection(); - if (!ids.length) return; + const tree = this.tree(); + const ids = this.topSelection(tree).filter((id) => !tree.byId.get(id)?.locked); + const arrows = new Set(this.port.nodes().filter((n) => n.kind === 'arrow' && this.selection.has(n.id)).map((n) => n.id)); + if (!ids.length && !arrows.size) { + if (this.selection.size) toast(t('Locked items cannot be deleted. Unlock them first.'), 'info', { key: 'bc-locked' }); + return; + } this.select([]); - this.commit(removeWithDescendants(this.port.nodes(), new Set(ids))); + this.commit(removeWithDescendants(this.port.nodes(), new Set(ids)).filter((n) => !arrows.has(n.id))); + } + + private flash(guides: Guide[]): void { + this.guides = guides; + this.invalidate(); + window.clearTimeout(this.flashTimer); + this.flashTimer = window.setTimeout(() => { + this.guides = []; + this.invalidate(); + }, FLASH_MS); + } + + align(how: Align): void { + const res = alignNodes(this.port.nodes(), this.topSelection(), how); + if (!res) { + toast(t('Select two or more unlocked items to align them.'), 'info', { key: 'bc-align' }); + return; + } + this.commit(res.nodes); + this.flash(res.guides); + } + + distribute(axis: Axis): void { + const next = distributeNodes(this.port.nodes(), this.topSelection(), axis); + if (!next) { + toast(t('Select three or more unlocked items to space them evenly.'), 'info', { key: 'bc-align' }); + return; + } + this.commit(next); + } + + toggleLock(): void { + const res = toggleLock(this.port.nodes(), this.topSelection()); + if (!res) return; + this.commit(res.nodes); + toast(res.locked ? t('Locked. Locked items cannot be moved or deleted.') : t('Unlocked.'), 'info', { key: 'bc-lock' }); + } + + unlockAll(): void { + const next = unlockAll(this.port.nodes()); + if (next) this.commit(next); + } + + hasLocked(): boolean { + return this.port.nodes().some((n) => n.locked); + } + + connect(): void { + const tree = this.tree(); + const ids = Array.from(this.selection).filter((id) => tree.byId.has(id) && !tree.byId.get(id)?.parent); + const next = connectNodes(this.port.nodes(), ids); + if (!next) { + toast(t('Select two or more items to connect them with arrows.'), 'info', { key: 'bc-connect' }); + return; + } + this.commit(next); + } + + duplicate(): void { + const roots = this.topSelection(); + if (!roots.length) return; + const res = duplicateNodes(this.port.nodes(), roots, { x: 24, y: 24 }); + this.commit([...this.port.nodes(), ...res.added]); + this.select(res.roots); } group(): void { @@ -469,6 +541,7 @@ export class CanvasView { dispose(): void { this.disposed = true; cancelAnimationFrame(this.raf); + window.clearTimeout(this.flashTimer); this.flushViewport(); this.editor.dispose(); for (const v of this.videos.values()) v.pause(); @@ -486,6 +559,7 @@ export class CanvasView { const tree = this.tree(); const hits: string[] = []; for (const n of tree.top) { + if (n.locked) continue; const quad = tree.corners(n); if (polyHitsRect(poly, quad) || quad.some((c) => pointInPoly(c, poly))) hits.push(n.id); } @@ -494,6 +568,6 @@ export class CanvasView { insideRect(r: Rect): string[] { const tree = this.tree(); - return tree.top.filter((n) => rectsIntersect(tree.bounds(n), r)).map((n) => n.id); + return tree.top.filter((n) => !n.locked && rectsIntersect(tree.bounds(n), r)).map((n) => n.id); } } diff --git a/frontend/src/ui/board/grid/card.ts b/frontend/src/ui/board/grid/card.ts index 0d263c6..6eec323 100644 --- a/frontend/src/ui/board/grid/card.ts +++ b/frontend/src/ui/board/grid/card.ts @@ -69,7 +69,7 @@ export function rebind(node: CardNode, id: string): CardNode { node.focused = false; node.editing = false; node.face.replaceChildren(); - node.el.classList.remove('is-selected', 'is-editing', 'is-loaded', 'is-broken', 'is-rated'); + node.el.classList.remove('is-selected', 'is-editing', 'is-loaded', 'is-broken', 'is-rated', 'is-dragging'); node.el.setAttribute('aria-selected', 'false'); return node; } @@ -85,7 +85,7 @@ function buildFace(item: Item, width: number): string { `${icon('video', 12)}` ); case 'note': - return '

'; + return `

`; case 'link': return ``; case 'colour': diff --git a/frontend/src/ui/board/grid/grid.ts b/frontend/src/ui/board/grid/grid.ts index 2045a7b..a77292b 100644 --- a/frontend/src/ui/board/grid/grid.ts +++ b/frontend/src/ui/board/grid/grid.ts @@ -1,5 +1,5 @@ import type { Item } from '../../../engine/board/doc'; -import { layoutBoard, nearestCard, PAD, type CardBox, type Layout, type LaneInput } from '../../../engine/board/layout'; +import { HEADER_H, layoutBoard, nearestCard, PAD, type CardBox, type Layout, type LaneInput } from '../../../engine/board/layout'; import { filtering } from '../../../engine/board/search'; import { el, q, setAttr, setClass, setHidden, setText } from '../../dom'; import { t } from '../../i18n'; @@ -39,6 +39,10 @@ export class GridView { readonly scroller: HTMLElement; private readonly sizer: HTMLElement; private readonly marquee: HTMLElement; + private readonly dropLine: HTMLElement; + private dropTarget: { before: string | null; section: string | null } | null = null; + private dragIds: Set | null = null; + private suppressClick = false; private readonly empty: HTMLElement; private readonly emptyText: HTMLElement; private readonly cards = new Map(); @@ -62,14 +66,23 @@ export class GridView { constructor(private readonly o: GridOptions) { this.root = el( `
` + - `
` + - `
`, + `
` + + ``, ); this.scroller = q(this.root, '.fc-bg-scroll'); this.sizer = q(this.root, '.fc-bg-sizer'); this.marquee = q(this.root, '.fc-bg-marquee'); + this.dropLine = q(this.root, '.fc-bg-drop'); this.empty = q(this.root, '.fc-bg-empty'); this.emptyText = q(this.root, '.fc-bg-empty-text'); + q(this.root, '.fc-empty-acts .cv-btn').addEventListener('click', () => this.o.adder.chooseFiles()); + q(this.root, '[data-empty="library"]').addEventListener('click', () => void this.o.adder.fromLibrary()); + q(this.root, '[data-empty="clear"]').addEventListener('click', () => this.store.clearFilters()); this.wire(); } @@ -196,6 +209,8 @@ export class GridView { const hide = !(none && (total === 0 || filtering(this.store.filters))); setHidden(this.empty, hide); if (!hide) setText(this.emptyText, total === 0 ? t('Nothing on this board yet. Add pictures, notes, colours or links.') : t('No items match your search.')); + if (!hide) setHidden(q(this.empty, '.fc-empty-acts'), total !== 0); + if (!hide) setHidden(q(this.empty, '[data-empty-filter]'), total === 0); this.syncHeads(layout, sectioned); } @@ -364,6 +379,10 @@ export class GridView { } private onClick(e: MouseEvent): void { + if (this.suppressClick) { + this.suppressClick = false; + return; + } if (this.drag?.on) return; const t0 = e.target as Element; const headBtn = t0.closest('.fc-bg-head [data-act]'); @@ -470,7 +489,12 @@ export class GridView { private onDown(e: PointerEvent): void { if (e.button !== 0) return; const t0 = e.target as Element; - if (t0.closest('.fc-bg-card, .fc-bg-head')) return; + const card = t0.closest('.fc-bg-card'); + if (card) { + this.startCardDrag(e, card); + return; + } + if (t0.closest('.fc-bg-head')) return; const r = this.scroller.getBoundingClientRect(); if (e.clientX > r.left + this.scroller.clientWidth || e.clientY > r.top + this.scroller.clientHeight) return; if (this.editor) this.commitEdit(); @@ -528,6 +552,89 @@ export class GridView { this.marqueeTo(e.clientX, e.clientY); } + private startCardDrag(e: PointerEvent, card: HTMLElement): void { + const id = card.dataset.id ?? ''; + if (!id || (e.target as Element).closest('[data-act], textarea') || this.editor?.id === id) return; + const sx = e.clientX; + const sy = e.clientY; + const pid = e.pointerId; + let on = false; + const move = (ev: PointerEvent): void => { + if (ev.pointerId !== pid) return; + if (!on) { + if (Math.hypot(ev.clientX - sx, ev.clientY - sy) < DRAG_PX) return; + on = true; + const sel = this.store.selection; + this.dragIds = new Set(sel.has(id) ? Array.from(sel) : [id]); + for (const [cid, node] of this.cards) setClass(node.el, 'is-dragging', this.dragIds.has(cid)); + setClass(this.root, 'is-reordering', true); + } + const r = this.scroller.getBoundingClientRect(); + if (ev.clientY < r.top + EDGE) this.scroller.scrollTop -= SCROLL_STEP; + else if (ev.clientY > r.bottom - EDGE) this.scroller.scrollTop += SCROLL_STEP; + this.dropAt(ev.clientX, ev.clientY); + }; + const up = (ev: PointerEvent): void => { + if (ev.pointerId !== pid) return; + window.removeEventListener('pointermove', move); + window.removeEventListener('pointerup', up); + window.removeEventListener('pointercancel', up); + if (!on) return; + this.suppressClick = ev.type === 'pointerup'; + window.setTimeout(() => { + this.suppressClick = false; + }, 0); + const ids = this.dragIds; + const target = this.dropTarget; + this.dragIds = null; + this.dropTarget = null; + setHidden(this.dropLine, true); + setClass(this.root, 'is-reordering', false); + for (const node of this.cards.values()) setClass(node.el, 'is-dragging', false); + if (ev.type === 'pointerup' && ids && target) this.store.reorderItems(ids, target.before, target.section); + }; + window.addEventListener('pointermove', move); + window.addEventListener('pointerup', up); + window.addEventListener('pointercancel', up); + } + + private dropAt(cx: number, cy: number): void { + const layout = this.layout; + const ids = this.dragIds; + if (!layout || !ids) return; + const r = this.scroller.getBoundingClientRect(); + const x = cx - r.left + this.scroller.scrollLeft; + const y = cy - r.top + this.scroller.scrollTop; + let target: { before: string | null; section: string | null } | null = null; + let line: { x: number; y: number; w: number } | null = null; + const head = layout.headers.find((h) => y >= h.y && y <= h.y + HEADER_H); + if (head) { + target = { before: null, section: head.id }; + line = { x: PAD, y: head.y + HEADER_H, w: layout.width - PAD * 2 }; + } else { + const c = layout.cards.find((b) => !ids.has(b.id) && x >= b.x && x <= b.x + b.w && y >= b.y && y <= b.y + b.h); + const item = c ? this.store.item(c.id) : undefined; + if (c && item) { + const upper = y < c.y + c.h / 2; + let before: string | null = c.id; + if (!upper) { + const all = this.store.items; + const at = all.findIndex((i) => i.id === c.id); + before = all.slice(at + 1).find((i) => !ids.has(i.id) && i.section === item.section)?.id ?? null; + } + target = { before, section: item.section }; + line = { x: c.x, y: upper ? c.y - layout.gap / 2 : c.y + c.h + layout.gap / 2, w: c.w }; + } + } + this.dropTarget = target; + setHidden(this.dropLine, !line); + if (line) { + const st = this.dropLine.style; + st.transform = `translate3d(${line.x}px, ${Math.round(line.y - 1.5)}px, 0)`; + st.width = `${line.w}px`; + } + } + private marqueeTo(cx: number, cy: number): void { const d = this.drag; if (!d || !this.layout) return; diff --git a/frontend/src/ui/board/grid/selbar.ts b/frontend/src/ui/board/grid/selbar.ts index 41357c8..4ca51f3 100644 --- a/frontend/src/ui/board/grid/selbar.ts +++ b/frontend/src/ui/board/grid/selbar.ts @@ -11,6 +11,9 @@ export class SelectionBar { private readonly useBtn: HTMLButtonElement; private readonly moveBtn: HTMLButtonElement; private readonly menu = new Popover({ className: 'fc-bg-move-pop' }); + private readonly sendMenu = new Popover({ className: 'fc-bg-move-pop' }); + private readonly sendBtn: HTMLButtonElement; + private readonly palBtn: HTMLButtonElement; private shown = false; constructor(private readonly ctx: BoardContext) { @@ -19,12 +22,25 @@ export class SelectionBar { `${t('Press 1 to 5 to rate, 0 to clear.')}` + `` + `` + + `` + + `` + `` + ``, ); this.count = q(this.root, '.fc-bg-selbar-count'); this.useBtn = q(this.root, '[data-act="ref"]'); this.moveBtn = q(this.root, '[data-act="move"]'); + this.sendBtn = q(this.root, '[data-act="send"]'); + this.palBtn = q(this.root, '[data-act="palette"]'); + this.sendMenu.panel.innerHTML = (['Canvas', 'Scene', 'Edit'] as const) + .map((n) => ``) + .join(''); + this.sendMenu.panel.addEventListener('click', (e) => { + const b = (e.target as Element).closest('[data-send]'); + if (!b) return; + this.sendMenu.close(); + void ctx.commands.run(b.dataset.send ?? ''); + }); this.root.addEventListener('click', (e) => { const b = (e.target as Element).closest('[data-act]'); if (!b) return; @@ -34,6 +50,13 @@ export class SelectionBar { if (this.menu.isOpen) this.menu.close(); else this.openMenu(); break; + case 'send': + if (this.sendMenu.isOpen) this.sendMenu.close(); + else this.sendMenu.open(this.sendBtn); + break; + case 'palette': + void ctx.commands.run('board.extractPalette'); + break; case 'ref': useAsReference(Array.from(s.selection, (id) => s.item(id)).filter((x): x is NonNullable => !!x)); break; @@ -62,6 +85,7 @@ export class SelectionBar { ctx.store.on('selection', () => this.sync()); ctx.store.on('items', () => this.sync()); ctx.store.on('reset', () => this.sync()); + ctx.store.on('view', () => this.sync()); } private openMenu(): void { @@ -81,15 +105,20 @@ export class SelectionBar { sync(): void { const s = this.ctx.store; const n = s.selection.size; - const show = n > 0; + const show = n > 0 && s.view === 'grid'; if (show !== this.shown) { this.shown = show; setHidden(this.root, !show); - if (!show) this.menu.close(); + if (!show) { + this.menu.close(); + this.sendMenu.close(); + } } if (!show) return; setText(this.count, tn(n, '{n} selected', '{n} selected')); const items = Array.from(s.selection, (id) => s.item(id)).filter((x): x is NonNullable => !!x); setHidden(this.useBtn, eligible(items).length === 0); + setHidden(this.sendBtn, !items.some((i) => !!i.asset)); + setHidden(this.palBtn, !items.some((i) => i.kind === 'image' && !!i.asset)); } } diff --git a/frontend/src/ui/board/grid/toolbar.ts b/frontend/src/ui/board/grid/toolbar.ts index ff8b109..e37c8fa 100644 --- a/frontend/src/ui/board/grid/toolbar.ts +++ b/frontend/src/ui/board/grid/toolbar.ts @@ -49,7 +49,10 @@ export class GridToolbar { `` + `
${btn('upload', 'upload', 'Upload')}${btn('library', 'library', 'From library')}${btn('note', 'bdNote', 'Add note')}` + `` + - `${btn('section', 'bdSection', 'New section')}
` + + `${btn('section', 'bdSection', 'New section')}${btn('prompt', 'scWand', 'Make prompt')}` + + `` + + `` + + `` + `
` + DENSITIES.map((d) => ``).join('') + `
` + @@ -111,8 +114,26 @@ export class GridToolbar { case 'rating': s.setFilters({ minRating: (s.filters.minRating + 1) % RATING_STEPS.length }); break; + case 'prompt': + void this.ctx.commands.run('board.makePrompt'); + break; + case 'export-media': + void this.ctx.commands.run('board.exportMedia'); + break; + case 'undo': + s.undo(); + break; + case 'redo': + s.redo(); + break; } }); + const undoBtn = q(this.bar, '[data-act="undo"]'); + const redoBtn = q(this.bar, '[data-act="redo"]'); + s.on('history', () => { + undoBtn.disabled = !s.canUndo; + redoBtn.disabled = !s.canRedo; + }); this.colourPop.panel.addEventListener('click', (e) => { if (!(e.target as Element).closest('[data-act="add-colour"]')) return; this.adder.addColour(normaliseHex(this.colourHex.value, this.colourPick.value)); diff --git a/frontend/src/ui/board/inspector/inspector.ts b/frontend/src/ui/board/inspector/inspector.ts index 2287d2d..31d3b3c 100644 --- a/frontend/src/ui/board/inspector/inspector.ts +++ b/frontend/src/ui/board/inspector/inspector.ts @@ -16,12 +16,19 @@ const DEFAULT_H = 760; const MARGIN = 16; const KIND_LABEL: Record = { image: 'Picture', video: 'Clip', note: 'Note', link: 'Link', colour: 'Colour' }; +const SIDE_MIN = 220; +const SIDE_MAX = 520; +const SIDE_DEFAULT = 280; +const SIDE_STEP = 16; + interface Geo { x: number; y: number; w: number; h: number; expanded: boolean; + side: number; + sideHidden: boolean; } export class Inspector { @@ -43,7 +50,7 @@ export class Inspector { private readonly palAdd: HTMLButtonElement; private readonly fields: Record<'caption' | 'text' | 'title' | 'url' | 'colour', HTMLElement>; private readonly useBtn: HTMLButtonElement; - private geo: Geo = { x: 0, y: 0, w: DEFAULT_W, h: DEFAULT_H, expanded: false }; + private geo: Geo = { x: 0, y: 0, w: DEFAULT_W, h: DEFAULT_H, expanded: false, side: SIDE_DEFAULT, sideHidden: false }; private id: string | null = null; private mediaKey = ''; private run = 0; @@ -56,9 +63,11 @@ export class Inspector { `
` + `` + `` + + `` + `` + `
` + - `
` + `
` + diff --git a/frontend/src/ui/board/shell/zip.ts b/frontend/src/ui/board/shell/zip.ts new file mode 100644 index 0000000..1ea5834 --- /dev/null +++ b/frontend/src/ui/board/shell/zip.ts @@ -0,0 +1,66 @@ +let table: Uint32Array | null = null; + +function crc32(data: Uint8Array): number { + if (!table) { + table = new Uint32Array(256); + for (let n = 0; n < 256; n++) { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + table[n] = c >>> 0; + } + } + let crc = 0xffffffff; + for (let i = 0; i < data.length; i++) crc = table[(crc ^ data[i]) & 0xff] ^ (crc >>> 8); + return (crc ^ 0xffffffff) >>> 0; +} + +export interface ZipEntry { name: string; data: Uint8Array } + +export function storeZip(entries: readonly ZipEntry[], when: Date = new Date()): Blob { + const enc = new TextEncoder(); + const time = (when.getHours() << 11) | (when.getMinutes() << 5) | Math.floor(when.getSeconds() / 2); + const date = ((Math.max(1980, when.getFullYear()) - 1980) << 9) | ((when.getMonth() + 1) << 5) | when.getDate(); + const parts: BlobPart[] = []; + const central: Uint8Array[] = []; + let offset = 0; + for (const e of entries) { + const name = new Uint8Array(enc.encode(e.name)); + const crc = crc32(e.data); + const head = new DataView(new ArrayBuffer(30)); + head.setUint32(0, 0x04034b50, true); + head.setUint16(4, 20, true); + head.setUint16(6, 0x0800, true); + head.setUint16(10, time, true); + head.setUint16(12, date, true); + head.setUint32(14, crc, true); + head.setUint32(18, e.data.length, true); + head.setUint32(22, e.data.length, true); + head.setUint16(26, name.length, true); + parts.push(head.buffer, name, e.data); + const dir = new DataView(new ArrayBuffer(46)); + dir.setUint32(0, 0x02014b50, true); + dir.setUint16(4, 20, true); + dir.setUint16(6, 20, true); + dir.setUint16(8, 0x0800, true); + dir.setUint16(12, time, true); + dir.setUint16(14, date, true); + dir.setUint32(16, crc, true); + dir.setUint32(20, e.data.length, true); + dir.setUint32(24, e.data.length, true); + dir.setUint16(28, name.length, true); + dir.setUint32(42, offset, true); + const row = new Uint8Array(46 + name.length); + row.set(new Uint8Array(dir.buffer), 0); + row.set(name, 46); + central.push(row); + offset += 30 + name.length + e.data.length; + } + const size = central.reduce((s, r) => s + r.length, 0); + const end = new DataView(new ArrayBuffer(22)); + end.setUint32(0, 0x06054b50, true); + end.setUint16(8, entries.length, true); + end.setUint16(10, entries.length, true); + end.setUint32(12, size, true); + end.setUint32(16, offset, true); + return new Blob([...parts, ...central, end.buffer], { type: 'application/zip' }); +} diff --git a/frontend/src/ui/canvas/base/empty-state.ts b/frontend/src/ui/canvas/base/empty-state.ts index 9ed40ac..6a4f16c 100644 --- a/frontend/src/ui/canvas/base/empty-state.ts +++ b/frontend/src/ui/canvas/base/empty-state.ts @@ -18,6 +18,8 @@ const SHELL = `` + `` + `
` + + `` + + `` + ``; export function mountEmptyState(ctx: CanvasContext): { el: HTMLElement; pickFiles(): void } { diff --git a/frontend/src/ui/canvas/context.ts b/frontend/src/ui/canvas/context.ts index c505806..a3b99d9 100644 --- a/frontend/src/ui/canvas/context.ts +++ b/frontend/src/ui/canvas/context.ts @@ -4,6 +4,9 @@ import type { toast } from '../toasts'; import type { BakeOptions, BakeResult } from './stage/bake'; import type { CanvasStage } from './stage/stage'; import type { ToolState } from './tools/state'; +import type { TextController } from './tools/text'; +import type { RegionController } from './tools/region'; +import type { CropController } from './tools/crop'; export const SLOT_NAMES = ['left', 'right', 'bottom', 'top', 'modal', 'overlay'] as const; @@ -30,4 +33,11 @@ export interface CanvasContext { removeBackground?: (nodeId: string) => void | Promise; uploadImages?: () => void; resetCanvas?: () => void; + edit?: EditTools; +} + +export interface EditTools { + readonly text: TextController; + readonly region: RegionController; + readonly crop: CropController; } diff --git a/frontend/src/ui/canvas/files/commands.ts b/frontend/src/ui/canvas/files/commands.ts index 58316c7..44997d3 100644 --- a/frontend/src/ui/canvas/files/commands.ts +++ b/frontend/src/ui/canvas/files/commands.ts @@ -6,7 +6,7 @@ import { addFromLibrary, pickAndAdd } from '../base/place'; import type { CanvasContext } from '../context'; import type { CanvasFiles } from './files'; -export const FILE_ROWS: readonly string[] = ['canvas.new', 'canvas.open', '-', 'canvas.save', 'canvas.saveCopy', 'canvas.revert', '-', 'canvas.export', '-', 'canvas.addFromLibrary', 'canvas.resetCanvas']; +export const FILE_ROWS: readonly string[] = ['canvas.new', 'canvas.open', '-', 'canvas.save', 'saveAs', 'canvas.saveCopy', 'canvas.revert', '-', 'canvas.export', 'revealProject', '-', 'canvas.addFromLibrary', 'canvas.addFromStarter', 'canvas.resetCanvas']; export async function resetCanvasAsk(ctx: CanvasContext): Promise { if (!ctx.store.base) return false; @@ -24,8 +24,8 @@ export function registerFileCommands(ctx: CanvasContext, files: CanvasFiles): vo const list: Command[] = [ own('canvas.new', 'New canvas', 'File', () => void files.newCanvas(), []), own('canvas.open', 'Open a canvas...', 'File', () => void files.openCanvas(), []), - own('canvas.save', 'Save canvas', 'File', () => void files.save(), ['Mod+KeyS'], { typing: true }), - own('canvas.saveCopy', 'Save a copy', 'File', () => void files.saveCopy(), ['Mod+Shift+KeyS'], { typing: true }), + own('canvas.save', 'Save canvas', 'File', () => void commands.run('save'), ['Mod+KeyS'], { typing: true }), + own('canvas.saveCopy', 'Save a copy', 'File', () => void commands.run('saveCopy'), []), own('canvas.revert', 'Revert to saved', 'File', () => void files.revert(), [], { enabled: () => files.revertible }), own('canvas.export', 'Export as .fcrft...', 'File', () => void files.exportFile(), []), own('canvas.addFromLibrary', 'Add from library...', 'Edit', () => void addFromLibrary(ctx), [], { enabled: () => ctx.store.base !== null }), diff --git a/frontend/src/ui/canvas/files/files.ts b/frontend/src/ui/canvas/files/files.ts index de7b2bb..3bdd36c 100644 --- a/frontend/src/ui/canvas/files/files.ts +++ b/frontend/src/ui/canvas/files/files.ts @@ -1,10 +1,9 @@ import { Emitter } from '../../../engine/emitter'; import { contentSignature, blankCanvas } from '../../../engine/canvas/doc'; import { studios } from '../../../engine/studios'; -import { ApiError, getSettings, type Media } from '../../../io/api'; +import { ApiError, type Media } from '../../../io/api'; import { createProject, - exportProject, getProject, listProjects, patchProject, @@ -16,9 +15,8 @@ import { } from '../../../io/api-projects'; import { confirmAction, promptName } from '../../dialogs'; import { t } from '../../i18n'; -import { inDesktop } from '../../prefs'; +import { writeProjectFile } from '../../projects/disk'; import { projectStore } from '../../projects/store'; -import { pickSavePath } from '../../save-media'; import { setBaseMedia } from '../base/base-image'; import { downscale } from '../base/util'; import type { CanvasContext } from '../context'; @@ -32,7 +30,6 @@ const COPY_TRIES = 9999; const COVER_EDGE = 512; const reasonOf = (err: unknown, fallback: string): string => (err instanceof ApiError && err.message ? err.message : fallback); -const fileSafe = (name: string): string => name.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').replace(/^[ .]+|[ .]+$/g, '').slice(0, 80) || 'canvas'; export function copyName(name: string, taken: ReadonlySet): string { const match = /^(.*?)(?: \((\d+)\))?$/.exec(name.trim()); @@ -240,22 +237,7 @@ export class CanvasFiles { if ((this.id === null || this.ctx.store.dirty) && !(await this.save())) return false; const id = this.id; if (id === null) return false; - return this.track(async () => { - try { - let path: string | null = null; - const settings = await getSettings().catch(() => null); - if (settings?.askLocation === true && inDesktop()) { - path = await pickSavePath(t('Export canvas'), `${fileSafe(this.name)}.fcrft`); - if (!path) return false; - } - const written = await exportProject(id, path, path !== null); - this.ctx.toast(t('Exported to {path}').replace('{path}', () => written.path), 'success', { key: 'canvas-export' }); - return true; - } catch (err) { - this.ctx.toast(reasonOf(err, t('The canvas could not be exported.')), 'error', { key: 'canvas-export' }); - return false; - } - }); + return this.track(async () => (await writeProjectFile(id, this.name, 'copy')) !== null); } async rename(raw: string): Promise { diff --git a/frontend/src/ui/canvas/files/menu.ts b/frontend/src/ui/canvas/files/menu.ts index 75ba63c..d809ca3 100644 --- a/frontend/src/ui/canvas/files/menu.ts +++ b/frontend/src/ui/canvas/files/menu.ts @@ -2,6 +2,7 @@ import { commands } from '../../../engine/commands'; import { shortcuts } from '../../../engine/shortcuts'; import { el, escapeHtml, setAttr, setDisabled, setHidden, setText, setTitle } from '../../dom'; import { onLanguage, relabel, t } from '../../i18n'; +import { filePathOf, onSaveState, saveStateOf } from '../../projects/disk'; import { Popover } from '../../scene/chrome/popover'; import { chromeButton, keepFocus, ownTab } from '../../scene/chrome/widgets'; import type { CanvasContext } from '../context'; @@ -52,9 +53,12 @@ export function mountFileMenu(ctx: CanvasContext, files: CanvasFiles): HTMLEleme setAttr(root, 'aria-label', t('Canvas file')); setTitle(file, t('File commands')); const keys = shortcuts.label('canvas.save'); - setTitle(save, keys ? `${t('Save')} (${keys})` : t('Save')); - setHidden(dot, !ctx.store.dirty); - setAttr(save, 'aria-label', ctx.store.dirty ? t('Save (unsaved changes)') : t('Save')); + const state = saveStateOf(files.id, ctx.store.dirty); + const path = filePathOf(files.id); + const word = t(state === 'saving' ? 'Saving' : state === 'saved' ? 'Saved' : 'Edited'); + setTitle(save, `${keys ? `${t('Save')} (${keys})` : t('Save')} · ${word}${path ? ` · ${path}` : ''}`); + setHidden(dot, state === 'saved'); + setAttr(save, 'aria-label', state === 'saved' ? t('Save') : t('Save (unsaved changes)')); setDisabled(save, files.busy); if (pop.isOpen) paintMenu(); }; @@ -78,6 +82,7 @@ export function mountFileMenu(ctx: CanvasContext, files: CanvasFiles): HTMLEleme }); ctx.store.on('dirty', paint); files.on(paint); + onSaveState(paint); commands.on('change', () => { if (pop.isOpen) paintMenu(); }); diff --git a/frontend/src/ui/canvas/files/title.ts b/frontend/src/ui/canvas/files/title.ts index cfe7608..ebf653e 100644 --- a/frontend/src/ui/canvas/files/title.ts +++ b/frontend/src/ui/canvas/files/title.ts @@ -1,5 +1,6 @@ import { studios } from '../../../engine/studios'; import { onLanguage } from '../../i18n'; +import { onSaveState, saveStateOf } from '../../projects/disk'; import { titleBar } from '../../titlebar'; import type { CanvasContext } from '../context'; import type { CanvasFiles } from './files'; @@ -10,7 +11,7 @@ export function bindTitle(ctx: CanvasContext, files: CanvasFiles): void { const paint = (): void => { const bar = titleBar(); if (!bar || !inCanvas()) return; - bar.setDocument(files.name, ctx.store.dirty); + bar.setDocument(files.name, saveStateOf(files.id, ctx.store.dirty) !== 'saved'); bar.setRenamer((name) => files.rename(name)); }; const release = (): void => { @@ -21,6 +22,7 @@ export function bindTitle(ctx: CanvasContext, files: CanvasFiles): void { }; ctx.store.on('dirty', paint); files.on(paint); + onSaveState(paint); onLanguage(paint); studios.on('active', (id, previous) => { const now = studios.rootOf(id) === 'canvas'; diff --git a/frontend/src/ui/canvas/generate/index.ts b/frontend/src/ui/canvas/generate/index.ts new file mode 100644 index 0000000..3d0d303 --- /dev/null +++ b/frontend/src/ui/canvas/generate/index.ts @@ -0,0 +1,26 @@ +import { shortcuts } from '../../../engine/shortcuts'; +import { t } from '../../i18n'; +import { addCentred } from '../base/place'; +import type { CanvasContext } from '../context'; + +export { mountPending } from './pending'; + +export function mountStarterEntry(ctx: CanvasContext): void { + const id = 'canvas.addFromStarter'; + if (ctx.commands.get(id)) return; + if (!shortcuts.has(id)) shortcuts.define({ action: id, surface: 'canvas', keys: [], group: 'Edit', allowWhileTyping: false }); + ctx.commands.register([ + { + id, + label: () => t('Add from the starter library...'), + group: 'Edit', + enabled: () => ctx.store.base !== null && !ctx.busy(), + run: () => + void (async () => { + const { openStarterPicker } = await import('../../library/starter/starter-picker'); + const picked = await openStarterPicker({ kinds: ['image', 'texture', 'sprite'], pick: true, max: 12, title: 'Add to the canvas' }); + if (picked.length) await addCentred(ctx, picked); + })(), + }, + ]); +} diff --git a/frontend/src/ui/canvas/generate/modes.ts b/frontend/src/ui/canvas/generate/modes.ts new file mode 100644 index 0000000..fe4e9e4 --- /dev/null +++ b/frontend/src/ui/canvas/generate/modes.ts @@ -0,0 +1,94 @@ +import { el, q, setAttr, setClass, setText } from '../../dom'; +import { relabel, t } from '../../i18n'; +import type { Mode, Side } from './session'; +import '../../../styles/canvas-review.css'; + +const MODES: ReadonlyArray<{ id: Mode; text: string }> = [ + { id: 'whole', text: 'Change the whole image' }, + { id: 'mask', text: 'Change only the masked area' }, + { id: 'extend', text: 'Extend the image' }, +]; + +const SIDES: ReadonlyArray<{ id: Side; text: string }> = [ + { id: 'auto', text: 'Fill the transparent area' }, + { id: 'left', text: 'Left' }, + { id: 'right', text: 'Right' }, + { id: 'top', text: 'Top' }, + { id: 'bottom', text: 'Bottom' }, + { id: 'all', text: 'All sides' }, +]; + +const AMOUNTS = [25, 50, 100] as const; + +export interface ModeState { + mode: Mode; + side: Side; + amount: number; +} + +export class ModeBar { + readonly el: HTMLElement; + private readonly what: HTMLElement; + private readonly side: HTMLSelectElement; + private readonly amount: HTMLSelectElement; + private state: ModeState = { mode: 'whole', side: 'auto', amount: 25 }; + + constructor(private readonly onChange: (s: ModeState) => void) { + const chips = MODES.map( + (m) => ``, + ).join(''); + const sides = SIDES.map((s) => ``).join(''); + const amounts = AMOUNTS.map((n) => ``).join(''); + this.el = el( + `
` + + `
${chips}
` + + `` + + `
` + + `

`, + ); + this.what = q(this.el, '.fc-cg-what'); + this.side = q(this.el, '[data-k="side"]'); + this.amount = q(this.el, '[data-k="amount"]'); + q(this.el, '.fc-cg-mode-group').addEventListener('click', (e) => { + const b = e.target instanceof Element ? e.target.closest('[data-mode]') : null; + if (b && !b.hasAttribute('aria-disabled')) this.set({ mode: b.dataset.mode as Mode }); + }); + this.side.addEventListener('change', () => this.set({ side: this.side.value as Side })); + this.amount.addEventListener('change', () => this.set({ amount: Number(this.amount.value) || 25 })); + this.paint(); + } + + get value(): ModeState { + return this.state; + } + + set(patch: Partial): void { + this.state = { ...this.state, ...patch }; + this.paint(); + this.onChange(this.state); + } + + describe(text: string): void { + setText(this.what, text); + setAttr(this.what, 'title', text); + } + + relabel(): void { + relabel(this.el); + } + + private paint(): void { + for (const b of this.el.querySelectorAll('[data-mode]')) { + const on = b.dataset.mode === this.state.mode; + setAttr(b, 'aria-checked', on ? 'true' : 'false'); + setClass(b, 'is-on', on); + } + const ext = q(this.el, '.fc-cg-ext'); + const on = this.state.mode === 'extend'; + if (ext.dataset.on !== String(on)) ext.dataset.on = String(on); + this.side.disabled = !on; + this.amount.disabled = !on || this.state.side === 'auto'; + if (this.side.value !== this.state.side) this.side.value = this.state.side; + if (this.amount.value !== String(this.state.amount)) this.amount.value = String(this.state.amount); + } +} diff --git a/frontend/src/ui/canvas/generate/panel.ts b/frontend/src/ui/canvas/generate/panel.ts index 8c5fe0d..42daa9c 100644 --- a/frontend/src/ui/canvas/generate/panel.ts +++ b/frontend/src/ui/canvas/generate/panel.ts @@ -11,6 +11,7 @@ import { el, q, setAttr, setHidden, setText } from '../../dom'; import { onLanguage, relabel, t } from '../../i18n'; import { icon } from '../../icons'; import { openLightbox } from '../../lightbox/lightbox'; +import { openKeySheet } from '../../prompt/key-sheet'; import { OptionsBar } from '../../prompt/options-bar'; import { PromptBox, type HintKind, type Mention } from '../../prompt/prompt-box'; import { ReferenceDeck } from '../../prompt/reference-deck'; @@ -20,8 +21,10 @@ import { ModelPick } from '../../scene/generate/model-pick'; import { PlanLoop, runGenerate } from '../../tools/tool-shell'; import { reason } from '../base/util'; import type { CanvasContext } from '../context'; -import { inpaintCapable, prepare, requestFor, type Refs } from './paths'; +import { ModeBar, type ModeState } from './modes'; +import { fits, inpaintCapable, modelFor, prepare, prepareExtend, requestFor, type Refs } from './paths'; import { readSaved, writeSaved } from './saved'; +import { maskBounds, padFor, runs, type Rect } from './session'; import '../../../styles/picker.css'; import '../../../styles/scene-generate.css'; @@ -45,6 +48,10 @@ export class CanvasGenerate { private countTouched = false; private blankOk = false; private busy = false; + private readonly modes: ModeBar; + private transparent: boolean | null = null; + private seeTimer = 0; + private hadMask = false; constructor(private readonly ctx: CanvasContext) { const saved = readSaved(); @@ -59,7 +66,10 @@ export class CanvasGenerate { accepts: (kinds) => this.deck.accepts(kinds), onCostClick: (anchor) => this.cost.toggle(anchor, this.model, this.loop.plan), onPreviewMention: (m) => void this.previewMention(m), + onAddKey: () => this.askKey(), }); + this.modes = new ModeBar((s) => this.onMode(s)); + this.box.on('input', () => this.loop.schedule()); this.picker = new ModelPick({ modelId: saved.modelId, onChange: (m) => this.onModel(m) }); this.bar = new OptionsBar({ onChange: (values) => this.onOptions(values) }); this.loop = new PlanLoop( @@ -73,16 +83,24 @@ export class CanvasGenerate { this.box.toolbar.append(this.picker.el, new SceneHistory({ onPick: (entry) => this.fromHistory(entry) }).el, this.bar.el, fit); this.box.deckSlot.append(this.deck.el, this.note); q(this.el, '.fc-cg-gen-box').append(this.box.el); + q(this.el, '.fc-cg-gen-box').before(this.modes.el); ctx.maskCapable = () => inpaintCapable(this.model); ctx.store.on('base', () => this.onBase()); ctx.store.on('reset', () => this.onBase()); this.paintShown(); - ctx.store.on('scene', () => this.paintState()); + ctx.store.on('scene', () => { + const has = ctx.store.mask.length > 0; + if (has && !this.hadMask && this.modes.value.mode === 'whole') this.modes.set({ mode: 'mask' }); + this.hadMask = has; + this.look(); + this.paintState(); + }); models.on('change', () => this.sync()); onLanguage(() => { relabel(this.el); setAttr(this.el, 'aria-label', t('Generate on the canvas')); + this.modes.relabel(); this.paintNote(); this.paintState(); }); @@ -98,6 +116,54 @@ export class CanvasGenerate { return this.model; } + private onMode(s: ModeState): void { + const next = modelFor(s.mode, this.model); + if (next && next.id !== this.model?.id) { + this.picker.set(next.id); + this.configure(next); + } + this.transparent = null; + this.look(); + this.paintState(); + } + + private look(): void { + window.clearTimeout(this.seeTimer); + const s = this.modes.value; + if (s.mode !== 'extend' || s.side !== 'auto' || !this.ctx.store.base) return; + this.seeTimer = window.setTimeout(() => { + this.transparent = this.ctx.store.extended; + this.paintState(); + }, 400); + } + + private modeGate(model: WindowModel): string | null { + const s = this.modes.value; + if (!fits(s.mode, model)) return s.mode === 'whole' ? t('No image model takes a picture to work from.') : t('Pick a model that can fill a masked area.'); + if (s.mode === 'mask' && this.ctx.store.mask.length === 0) return t('Paint the area to change with the Mask tool first.'); + if (s.mode === 'extend' && s.side === 'auto' && this.transparent === false) return t('The canvas has no transparent area. Pick a side to extend.'); + return null; + } + + private describeMode(): void { + const s = this.modes.value; + let text: string; + if (s.mode === 'whole') text = t('Sends the flattened picture, the base with every layer. Any part may change.'); + else if (s.mode === 'mask') text = t('Sends the flattened picture and your mask. Only the masked area changes.'); + else if (s.side === 'auto') text = t('Sends the flattened picture and a mask over its transparent area.'); + else text = t('Sends the picture with {n} percent of new space added, and a mask over the new space.').replace('{n}', String(s.amount)); + this.modes.describe(text); + } + + private affected(): Rect { + const { width, height } = this.ctx.store.size; + const s = this.modes.value; + if (s.mode === 'mask') return maskBounds(this.ctx.store.mask, width, height); + const pad = s.mode === 'extend' ? padFor(s.side, s.amount, width, height) : null; + if (!pad) return { x: 0, y: 0, width, height }; + return { x: -pad.l, y: -pad.t, width: width + pad.l + pad.r, height: height + pad.t + pad.b }; + } + private paintShown(): void { setHidden(this.el, this.ctx.store.base === null); } @@ -126,6 +192,7 @@ export class CanvasGenerate { private onModel(model: WindowModel): void { writeSaved({ modelId: model.id }); this.configure(model); + if (!fits(this.modes.value.mode, model)) this.modes.set({ mode: 'whole' }); } private configure(model: WindowModel | null): void { @@ -233,10 +300,15 @@ export class CanvasGenerate { if (!model) { const none = models.ready && frameModels().length === 0; const why = models.failed ? t('The model list could not be loaded.') : none ? t('No image model takes a picture to work from.') : t('The models are still loading.'); + this.box.setNeedsKey(false); this.box.setCanSubmit(false, why); this.box.setHint(models.failed || none ? why : null, 'warning'); + this.describeMode(); return; } + this.describeMode(); + this.box.setNeedsKey(models.ready && !models.configured(model.provider)); + const modeGate = this.modeGate(model); const missing = this.bar.missing(); const plan = this.loop.plan; const errors = this.blocking(plan ? plan.errors : []); @@ -246,6 +318,9 @@ export class CanvasGenerate { const hasMask = this.ctx.store.mask.length > 0; if (!this.ctx.store.base) { gate = t('Choose a picture or a blank canvas first.'); + } else if (modeGate) { + text = modeGate; + gate = modeGate; } else if (this.deck.uploading) { text = t('Uploading references'); gate = t('Wait for the references to finish uploading.'); @@ -259,9 +334,8 @@ export class CanvasGenerate { } else if (missing.length) { text = t('Choose {options} before generating.').replace('{options}', missing.map((k) => t(optionLabel(k))).join(', ')); kind = 'warning'; - } else if (hasMask && !inpaintCapable(model)) { - text = t('This model does not take a mask, so your mask is not used.'); - kind = 'warning'; + } else if (hasMask && this.modes.value.mode !== 'mask') { + text = t('Your mask is not used in this mode.'); } else if (hasMask && Object.values(this.deck.value()).some((v) => (Array.isArray(v) ? v.length > 0 : !!v))) { text = t('With a mask, only the picture and the mask are sent. References are not used.'); } else if (plan && plan.warnings.length) { @@ -279,11 +353,20 @@ export class CanvasGenerate { this.box.setBusy(on); } + /** Opens the key sheet on the canvas prompt box; saving it runs this generation. */ + private askKey(): void { + if (this.model) openKeySheet(this.box.el, this.model.provider, { onSaved: () => void this.run() }); + } + private async run(): Promise { const { ctx } = this; if (this.busy) return; const model = this.model; if (!model || !ctx.store.base) return; + if (!models.configured(model.provider)) { + this.askKey(); + return; + } const missing = this.bar.missing(); if (missing.length) { this.bar.reveal(); @@ -298,20 +381,37 @@ export class CanvasGenerate { try { const prompt = this.box.text; const options = this.bar.values(); + const gate = this.modeGate(model); + if (gate) { + ctx.toast(gate, 'warning', { key: 'canvas-gen-mode' }); + return; + } + const s = this.modes.value; + const { width, height } = ctx.store.size; + const pad = s.mode === 'extend' ? padFor(s.side, s.amount, width, height) : null; + let rect = this.affected(); + const baseKey = ctx.store.baseKey; let prepared; try { - prepared = await prepare(ctx, model, this.deck.value()); + prepared = s.mode === 'extend' ? await prepareExtend(ctx, model, pad) : await prepare(ctx, model, s.mode === 'mask' ? {} : this.deck.value(), s.mode === 'mask'); + if (s.mode === 'extend') rect = { x: 0, y: 0, ...ctx.store.size }; } catch (err) { ctx.toast(reason(err, t('The canvas could not be prepared.')), 'error', { key: 'canvas-gen-prepare' }); return; } - if (!prepared) return; + if (!prepared) { + if (s.mode === 'extend') ctx.toast(t('The canvas has no transparent area. Pick a side to extend.'), 'warning', { key: 'canvas-gen-mode' }); + return; + } const req = requestFor(model, prompt, options, prepared.media); const created = await runGenerate(model, req, null); if (!created) return; const asked = Math.max(1, Math.round(Number(options.count) || 1)); const each = Math.max(1, Math.round(asked / Math.max(1, created.length))); - for (const job of created) ctx.store.addPending(job.id, each, prompt); + for (const job of created) { + runs.set(job.id, { mode: s.mode, rect, pad, startedAt: Date.now(), baseKey }); + ctx.store.addPending(job.id, each, prompt); + } window.setTimeout(() => { if (created.some((j) => !jobStore.get(j.id))) void jobStore.resync(); }, 400); diff --git a/frontend/src/ui/canvas/generate/paths.ts b/frontend/src/ui/canvas/generate/paths.ts index d524f3a..7f651ac 100644 --- a/frontend/src/ui/canvas/generate/paths.ts +++ b/frontend/src/ui/canvas/generate/paths.ts @@ -1,4 +1,6 @@ -import { frameMedia, frameSlot } from '../../scene/generate/frame-models'; +import { models } from '../../../engine/models'; +import { frameMedia, frameModels, frameSlot } from '../../scene/generate/frame-models'; +import type { Mode, Pad } from './session'; import type { GenerateRequest, WindowModel } from '../../../io/api'; import { importBlob } from '../../tools/hidden-import'; import { stamp } from '../base/util'; @@ -21,15 +23,17 @@ export function requestFor(model: WindowModel, prompt: string, options: Record { +export async function prepare(ctx: CanvasContext, model: WindowModel, refs: Refs, allowMask = true): Promise { const base = ctx.store.base; if (!base) return null; const baked = await ctx.bake({ maskEdit: maskEdit(model) }); - const useMask = inpaintCapable(model) && ctx.store.mask.length > 0 && baked.mask !== null; + const useMask = allowMask && inpaintCapable(model) && ctx.store.mask.length > 0 && baked.mask !== null; const slot = frameSlot(model); if (!slot) return null; if (useMask && baked.mask) { - const plain = ctx.store.nodes.length === 0 && base.kind === 'media'; + const c = ctx.store.content; + const s = ctx.store.size; + const plain = ctx.store.nodes.length === 0 && base.kind === 'media' && c.x === 0 && c.y === 0 && c.width === s.width && c.height === s.height; const image = plain ? base.$media : (await importBlob(baked.composite, `canvas-${stamp()}.png`, { hidden: true })).id; const maskMedia = await importBlob(baked.mask,`canvas-mask-${stamp()}.png`, { hidden: true }); const media: Refs = { mask: maskMedia.id }; @@ -41,3 +45,33 @@ export async function prepare(ctx: CanvasContext, model: WindowModel, refs: Refs const composite = await importBlob(baked.composite, `canvas-${stamp()}.png`, { hidden: true }); return { path: 'edit', media: frameMedia(model, composite.id, refs), dropped: false }; } + +export async function prepareExtend(ctx: CanvasContext, model: WindowModel, pad: Pad | null): Promise { + const slot = frameSlot(model); + if (!ctx.store.base || !slot || !inpaintCapable(model)) return null; + if (pad) { + const { width, height } = ctx.store.size; + ctx.store.setFrame({ x: -pad.l, y: -pad.t, width: width + pad.l + pad.r, height: height + pad.t + pad.b }, 'Extend canvas'); + } + if (!ctx.store.extended) return null; + const baked = await ctx.bake({ maskEdit: maskEdit(model) }); + if (!baked.mask) return null; + const image = await importBlob(baked.composite, `canvas-extend-${stamp()}.png`, { hidden: true }); + const mask = await importBlob(baked.mask, `canvas-extend-mask-${stamp()}.png`, { hidden: true }); + const media: Refs = { mask: mask.id }; + if (slot === 'sourceImage') media.sourceImage = image.id; + else media.referenceImages = [image.id]; + return { path: 'inpaint', media, dropped: false }; +} + +export function fits(mode: Mode, m: WindowModel): boolean { + if (frameSlot(m) === null) return false; + return mode === 'whole' ? true : inpaintCapable(m); +} + +export function modelFor(mode: Mode, current: WindowModel | null): WindowModel | null { + if (current && fits(mode, current)) return current; + const list = frameModels().filter((m) => fits(mode, m)); + const rank = (m: WindowModel): number => (models.configured(m.provider) ? 0 : 2) + (m.available ? 0 : 1); + return list.slice().sort((a, b) => rank(a) - rank(b))[0] ?? null; +} diff --git a/frontend/src/ui/canvas/generate/pending.ts b/frontend/src/ui/canvas/generate/pending.ts new file mode 100644 index 0000000..4b8f609 --- /dev/null +++ b/frontend/src/ui/canvas/generate/pending.ts @@ -0,0 +1,88 @@ +import type { ResultBundle } from '../../../engine/canvas/types'; +import { jobs } from '../../../engine/jobs'; +import { el, patchList, q, setAttr, setText } from '../../dom'; +import { onLanguage, relabel, t } from '../../i18n'; +import { icon } from '../../icons'; +import { reason } from '../base/util'; +import type { CanvasContext } from '../context'; +import { runs } from './session'; +import '../../../styles/canvas-review.css'; + +const clock = (ms: number): string => { + const s = Math.max(0, Math.floor(ms / 1000)); + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; +}; + +export function mountPending(ctx: CanvasContext): HTMLElement { + const layer = el('
'); + ctx.slots.overlay.append(layer); + let timer = 0; + + const live = (): Array> => ctx.store.pending.filter((b) => !!runs.get(b.jobId) && runs.get(b.jobId)?.baseKey === ctx.store.baseKey); + + const make = (b: Readonly): HTMLElement => { + const node = el( + `
${icon('loading', 18)}` + + `${t('Generating')} 0:00` + + `
`, + ); + node.dataset.job = b.jobId; + place(node, b); + return node; + }; + + const place = (node: HTMLElement, b: Readonly): void => { + const meta = runs.get(b.jobId); + if (!meta) return; + const a = ctx.stage.canvasToView(meta.rect.x, meta.rect.y); + const z = ctx.stage.canvasToView(meta.rect.x + meta.rect.width, meta.rect.y + meta.rect.height); + const s = node.style; + s.left = `${Math.round(a.x)}px`; + s.top = `${Math.round(a.y)}px`; + s.width = `${Math.max(1, Math.round(z.x - a.x))}px`; + s.height = `${Math.max(1, Math.round(z.y - a.y))}px`; + setText(q(node, '.fc-cg-pend-time'), clock(Date.now() - meta.startedAt)); + setAttr(q(node, '.fc-cg-pend-cancel'), 'aria-label', `${t('Cancel')}: ${b.prompt || t('Generating')}`); + }; + + const render = (): void => { + const items = live(); + patchList(layer, items, { key: (b) => b.id, create: make, update: place }); + if (items.length && !timer) timer = window.setInterval(render, 1000); + if (!items.length && timer) { + window.clearInterval(timer); + timer = 0; + } + }; + + layer.addEventListener('click', (e) => { + const btn = e.target instanceof Element ? e.target.closest('.fc-cg-pend-cancel') : null; + const node = btn?.closest('.fc-cg-pend'); + const jobId = node?.dataset.job; + if (!btn || !jobId || btn.disabled) return; + btn.disabled = true; + void jobs.cancel(jobId).then( + () => { + const b = ctx.store.bundleByJob(jobId); + if (b && b.status !== 'done') ctx.store.removeBundle(b.id); + ctx.toast(t('Generation cancelled.'), 'info', { key: 'canvas-gen-cancel' }); + }, + (err: unknown) => { + btn.disabled = false; + ctx.toast(reason(err, t('The generation could not be cancelled.')), 'error', { key: 'canvas-gen-cancel' }); + }, + ); + }); + + ctx.store.on('results', render); + ctx.store.on('base', render); + ctx.store.on('reset', render); + ctx.stage.on('view', render); + runs.on(render); + onLanguage(() => { + relabel(layer); + render(); + }); + render(); + return layer; +} diff --git a/frontend/src/ui/canvas/generate/session.ts b/frontend/src/ui/canvas/generate/session.ts new file mode 100644 index 0000000..6d62a1b --- /dev/null +++ b/frontend/src/ui/canvas/generate/session.ts @@ -0,0 +1,65 @@ +import type { MaskStroke } from '../../../engine/canvas/types'; + +export type Mode = 'whole' | 'mask' | 'extend'; +export type Side = 'auto' | 'left' | 'right' | 'top' | 'bottom' | 'all'; + +export interface Rect { x: number; y: number; width: number; height: number } +export interface Pad { l: number; t: number; r: number; b: number } + +export interface RunMeta { + mode: Mode; + rect: Rect; + pad: Pad | null; + startedAt: number; + baseKey: string; +} + +const metas = new Map(); +const listeners = new Set<() => void>(); + +export const runs = { + set(jobId: string, meta: RunMeta): void { + metas.set(jobId, meta); + for (const fn of listeners) fn(); + }, + get: (jobId: string): RunMeta | undefined => metas.get(jobId), + on(fn: () => void): () => void { + listeners.add(fn); + return () => listeners.delete(fn); + }, +}; + +export function padFor(side: Side, percent: number, width: number, height: number): Pad | null { + if (side === 'auto') return null; + const dx = Math.round((width * percent) / 100); + const dy = Math.round((height * percent) / 100); + return { + l: side === 'left' || side === 'all' ? dx : 0, + r: side === 'right' || side === 'all' ? dx : 0, + t: side === 'top' || side === 'all' ? dy : 0, + b: side === 'bottom' || side === 'all' ? dy : 0, + }; +} + +export function maskBounds(mask: ReadonlyArray>, width: number, height: number): Rect { + let x0 = Infinity; + let y0 = Infinity; + let x1 = -Infinity; + let y1 = -Infinity; + for (const s of mask) { + if (s.mode !== 'add') continue; + const r = s.size / 2; + for (let i = 0; i + 1 < s.points.length; i += 2) { + x0 = Math.min(x0, s.points[i] - r); + y0 = Math.min(y0, s.points[i + 1] - r); + x1 = Math.max(x1, s.points[i] + r); + y1 = Math.max(y1, s.points[i + 1] + r); + } + } + if (!Number.isFinite(x0)) return { x: 0, y: 0, width, height }; + x0 = Math.max(0, x0); + y0 = Math.max(0, y0); + x1 = Math.min(width, x1); + y1 = Math.min(height, y1); + return { x: x0, y: y0, width: Math.max(1, x1 - x0), height: Math.max(1, y1 - y0) }; +} diff --git a/frontend/src/ui/canvas/layers/index.ts b/frontend/src/ui/canvas/layers/index.ts new file mode 100644 index 0000000..3078ea2 --- /dev/null +++ b/frontend/src/ui/canvas/layers/index.ts @@ -0,0 +1,369 @@ +import { BLEND_MODES, type BlendMode, type CanvasNode } from '../../../engine/canvas/types'; +import '../tools/icons'; +import { mediaThumbUrl } from '../../../io/api'; +import { el, patchList, q, setAttr, setClass, setText } from '../../dom'; +import { t } from '../../i18n'; +import { icon } from '../../icons'; +import { PopupMenu } from '../../menu'; +import type { CanvasContext } from '../context'; +import { EXPORT_ITEMS } from '../tools/menu'; + +const LAYOUT_KEY = 'formcraft.canvas.layout'; +const WIDTH = { min: 200, max: 420, initial: 264 } as const; + +interface Layout { + width: number; + open: boolean; +} + +function readLayout(): Layout { + try { + const raw = JSON.parse(localStorage.getItem(LAYOUT_KEY) ?? '{}') as Partial; + const w = typeof raw.width === 'number' ? raw.width : WIDTH.initial; + return { width: Math.min(WIDTH.max, Math.max(WIDTH.min, w)), open: raw.open !== false }; + } catch { + return { width: WIDTH.initial, open: true }; + } +} + +function writeLayout(l: Layout): void { + try { + localStorage.setItem(LAYOUT_KEY, JSON.stringify(l)); + } catch { + return; + } +} + +const KIND_LABEL: Record = { image: 'Image', line: 'Stroke', shape: 'Shape', model: '3D model', text: 'Text' }; +const BLEND_LABEL: Record = { normal: 'Normal', multiply: 'Multiply', screen: 'Screen', overlay: 'Overlay', darken: 'Darken', lighten: 'Lighten' }; + +export const layerName = (n: Readonly, index: number): string => n.name ?? `${t(KIND_LABEL[n.kind])} ${index + 1}`; + +function thumb(n: Readonly): string { + if (n.kind === 'image') return ``; + if (n.kind === 'model') return ``; + if (n.kind === 'line') return n.erase ? icon('minus', 14) : icon('pencil', 14); + if (n.kind === 'text') return icon('cvText', 14); + if (n.shape === 'polygon') return n.erase ? icon('minus', 14) : icon('cvLasso', 14); + const shape = n.shape === 'circle' ? '' : n.shape === 'triangle' ? '' : ''; + return ``; +} + +const STATUS_TOOL: Record = { + select: 'Select and move: drag to move, drag a handle to resize, Shift keeps proportions.', + shape: 'Shape: drag to draw, Shift for a square or circle. Press 2 again for the next shape.', + brush: 'Brush: paint on the canvas. Use Cmd or Ctrl with + and - to change the size.', + eraser: 'Eraser: erase strokes and shapes. Use Cmd or Ctrl with + and - to change the size.', + mask: 'Mask: paint the area the model may change. Only the masked area is sent as a mask.', + text: 'Text: click to place, type, then click outside or press Esc. Double-click text to edit it.', + eyedropper: 'Eyedropper: click to pick a colour from the canvas for the brush, shapes and text.', + crop: 'Crop: drag the handles, or past the edge to extend. Alt resizes from the centre. Enter applies.', + marquee: 'Rectangle selection: drag to select, Shift for a square. Then fill, clear, invert or make a mask.', + lasso: 'Lasso selection: drag around an area. Then fill, clear, invert or make a mask.', +}; + +function mountStatus(ctx: CanvasContext): void { + const bar = el(`
`); + const tool = q(bar, '.fc-cv-status-tool'); + const hint = q(bar, '.fc-cv-status-hint'); + const nav = q(bar, '.fc-cv-status-nav'); + setText(nav, t('Space-drag or scroll to pan, Cmd or Ctrl with scroll to zoom, Cmd or Ctrl+0 to fit.')); + const paint = (): void => { + const name = ctx.tools.tool; + setText(tool, ctx.tools.tool === 'mask' ? t('Mask mode') : t(name.charAt(0).toUpperCase() + name.slice(1))); + setText(hint, t(STATUS_TOOL[name] ?? '')); + }; + ctx.tools.on('change', paint); + paint(); + ctx.root.append(bar); +} + +export function mountLayers(ctx: CanvasContext): void { + const { store, root } = ctx; + const right = ctx.slots.right; + let layout = readLayout(); + const apply = (): void => { + root.style.setProperty('--cv-right-w', `${layout.width}px`); + root.dataset.right = layout.open ? 'open' : 'closed'; + }; + apply(); + + const bar = el( + `
${t('Layers')}` + + `` + + `` + + `
`, + ); + const grip = el(``); + const panel = el( + `
` + + `
` + + `` + + `` + + `
` + + `
` + + `

${t('Paint, add a shape or drop a picture to make a layer.')}

` + + `
` + + `` + + `` + + `` + + `` + + `` + + `` + + `` + + `` + + `` + + `` + + `
`, + ); + right.prepend(bar, panel); + right.append(grip); + const list = q(panel, '.fc-cv-layer-list'); + const empty = q(panel, '.fc-cv-layer-empty'); + const blend = q(panel, '[data-input="blend"]'); + const alpha = q(panel, '[data-input="alpha"]'); + const alphaVal = q(panel, '.fc-cv-layer-alphaval'); + let sliding = false; + blend.addEventListener('change', () => { + store.updateNodes(store.selected.map((id) => ({ id, patch: { blend: blend.value as BlendMode } })), 'Blend mode'); + }); + alpha.addEventListener('input', () => { + if (!sliding) { + sliding = true; + store.begin('Layer opacity'); + } + const v = Number(alpha.value) / 100; + setText(alphaVal, `${alpha.value}%`); + store.updateNodes(store.selected.map((id) => ({ id, patch: { alpha: v } })), 'Layer opacity'); + }); + const endSlide = (): void => { + if (!sliding) return; + sliding = false; + store.commit(); + paint(); + }; + alpha.addEventListener('change', endSlide); + alpha.addEventListener('pointerup', endSlide); + alpha.addEventListener('blur', endSlide); + const toggle = q(bar, '[data-act="toggle"]'); + let exportMenu: PopupMenu | null = null; + + bar.addEventListener('click', (e) => { + const b = e.target instanceof Element ? e.target.closest('[data-act]') : null; + if (!b) return; + if (b.dataset.act === 'export') { + exportMenu ??= new PopupMenu(null, true); + exportMenu.panel.classList.add('fc-cv-menu'); + exportMenu.setItems(EXPORT_ITEMS); + const r = b.getBoundingClientRect(); + exportMenu.openAt(r.left, r.bottom + 4); + return; + } + if (b.dataset.act === 'toggle') layout = { ...layout, open: !layout.open }; + else layout = { width: WIDTH.initial, open: true }; + setAttr(toggle, 'aria-expanded', String(layout.open)); + writeLayout(layout); + apply(); + }); + + grip.addEventListener('pointerdown', (e) => { + e.preventDefault(); + grip.setPointerCapture(e.pointerId); + grip.classList.add('is-drag'); + const startX = e.clientX; + const startW = layout.width; + const move = (m: PointerEvent): void => { + layout = { ...layout, width: Math.min(WIDTH.max, Math.max(WIDTH.min, startW + (startX - m.clientX))) }; + apply(); + }; + const up = (): void => { + grip.classList.remove('is-drag'); + grip.removeEventListener('pointermove', move); + writeLayout(layout); + }; + grip.addEventListener('pointermove', move); + grip.addEventListener('pointerup', up, { once: true }); + grip.addEventListener('pointercancel', up, { once: true }); + }); + + const row = (): HTMLElement => + el( + `
` + + `
`, + ); + + const update = (node: HTMLElement, n: Readonly): void => { + const i = store.nodes.indexOf(n); + const sig = n.kind === 'image' ? n.asset.$media : n.kind === 'model' ? n.render.$media : n.kind === 'shape' ? `${n.shape}:${n.fill}` : `${n.kind}:${n.kind === 'line' && n.erase}`; + const th = q(node, '.fc-cv-layer-thumb'); + if (th.dataset.sig !== sig) { + th.dataset.sig = sig; + th.innerHTML = thumb(n); + if (n.kind === 'shape') th.style.color = n.fill; + } + const name = q(node, '.fc-cv-layer-name'); + if (!name.isContentEditable) setText(name, layerName(n, i)); + setClass(node, 'is-on', store.isSelected(n.id)); + setAttr(node, 'aria-selected', String(store.isSelected(n.id))); + setClass(node, 'is-hidden', !!n.hidden); + setClass(node, 'is-grouped', !!n.group); + if (node.dataset.group !== (n.group ?? '')) node.dataset.group = n.group ?? ''; + const eye = q(node, '[data-act="eye"]'); + const lock = q(node, '[data-act="lock"]'); + if (eye.dataset.on !== String(!n.hidden)) { + eye.dataset.on = String(!n.hidden); + eye.innerHTML = icon('eye', 14); + setAttr(eye, 'title', t(n.hidden ? 'Show layer' : 'Hide layer')); + setAttr(eye, 'aria-label', t(n.hidden ? 'Show layer' : 'Hide layer')); + } + if (lock.dataset.on !== String(n.locked)) { + lock.dataset.on = String(n.locked); + lock.innerHTML = icon(n.locked ? 'lock' : 'unlock', 14); + setAttr(lock, 'title', t(n.locked ? 'Unlock' : 'Lock')); + setAttr(lock, 'aria-label', t(n.locked ? 'Unlock' : 'Lock')); + } + }; + + const paint = (): void => { + const items = [...store.nodes].reverse(); + patchList(list, items, { + key: (n) => n.id, + create: (n) => { + const node = row(); + update(node, n); + return node; + }, + update, + }); + empty.hidden = items.length > 0; + const picked = store.hasSelection; + for (const b of Array.from(panel.querySelectorAll('.fc-cv-layer-acts button'))) b.disabled = b.dataset.always ? items.length < 2 : !picked; + const sel = store.selectedNodes(); + const first = sel[0]; + blend.disabled = !first; + alpha.disabled = !first; + if (first && !sliding) { + const a = Math.round((first.alpha ?? 1) * 100); + if (document.activeElement !== alpha) alpha.value = String(a); + setText(alphaVal, `${a}%`); + if (document.activeElement !== blend) blend.value = first.blend ?? 'normal'; + } else if (!first) setText(alphaVal, ''); + }; + store.on('scene', paint); + store.on('selection', paint); + store.on('reset', paint); + store.on('base', paint); + paint(); + + const idOf = (e: Event): string | null => { + const r = e.target instanceof Element ? e.target.closest('.fc-cv-layer') : null; + return r?.dataset.key ?? null; + }; + let anchor: string | null = null; + + list.addEventListener('click', (e) => { + const id = idOf(e); + if (!id) return; + const n = store.node(id); + if (!n) return; + const act = e.target instanceof Element ? e.target.closest('[data-act]')?.dataset.act : undefined; + if (act === 'eye') { + store.updateNode(id, { hidden: !n.hidden }); + return; + } + if (act === 'lock') { + if (n.locked) store.unlock([id]); + else store.lock([id]); + return; + } + if (e.shiftKey && anchor) { + const ids = [...store.nodes].reverse().map((x) => x.id); + const a = ids.indexOf(anchor); + const b = ids.indexOf(id); + if (a >= 0 && b >= 0) store.select(ids.slice(Math.min(a, b), Math.max(a, b) + 1)); + return; + } + if (e.metaKey || e.ctrlKey) store.toggleSelection(id); + else store.select([id]); + anchor = id; + }); + + list.addEventListener('dblclick', (e) => { + const id = idOf(e); + const name = e.target instanceof Element ? e.target.closest('.fc-cv-layer-name') : null; + if (!id || !name) return; + name.contentEditable = 'plaintext-only'; + name.focus(); + getSelection()?.selectAllChildren(name); + const done = (keep: boolean): void => { + name.contentEditable = 'false'; + const value = (name.textContent ?? '').trim(); + if (keep) store.updateNode(id, { name: value }); + paint(); + }; + name.addEventListener('keydown', function key(k) { + if (k.key === 'Enter' || k.key === 'Escape') { + k.preventDefault(); + k.stopPropagation(); + name.removeEventListener('keydown', key); + name.blur(); + done(k.key === 'Enter'); + } + }); + name.addEventListener('blur', () => { + if (name.isContentEditable) done(true); + }, { once: true }); + }); + + list.addEventListener('contextmenu', (e) => { + const id = idOf(e); + if (!id) return; + e.preventDefault(); + if (!store.isSelected(id)) store.select([id]); + ctx.stage.view.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: e.clientX, clientY: e.clientY })); + }); + + let dragging: string | null = null; + list.addEventListener('dragstart', (e) => { + dragging = idOf(e); + if (dragging && !store.isSelected(dragging)) store.select([dragging]); + e.dataTransfer?.setData('text/plain', ''); + }); + list.addEventListener('dragover', (e) => { + if (!dragging) return; + e.preventDefault(); + }); + list.addEventListener('drop', (e) => { + if (!dragging) return; + e.preventDefault(); + const target = idOf(e); + dragging = null; + if (!target) return; + const r = (e.target as Element).closest('.fc-cv-layer'); + const box = r?.getBoundingClientRect(); + const below = box ? e.clientY > box.top + box.height / 2 : false; + const idx = store.nodes.findIndex((n) => n.id === target); + store.moveTo(store.selected, below ? idx : idx + 1); + }); + list.addEventListener('dragend', () => { + dragging = null; + }); + + panel.addEventListener('click', (e) => { + const b = e.target instanceof Element ? e.target.closest('.fc-cv-layer-acts [data-act]') : null; + if (!b) return; + const act = b.dataset.act; + if (act === 'dup') store.duplicate(); + else if (act === 'up') store.moveUp(); + else if (act === 'down') store.moveDown(); + else if (act === 'del') store.delete(); + else if (act === 'group') void ctx.commands.run('canvas.group'); + else if (act === 'ungroup') void ctx.commands.run('canvas.ungroup'); + else if (act === 'merge') void ctx.commands.run('canvas.mergeDown'); + else if (act === 'mergeAll') void ctx.commands.run('canvas.mergeVisible'); + else if (act === 'flipH') store.flip('x'); + else if (act === 'flipV') store.flip('y'); + }); + + mountStatus(ctx); +} diff --git a/frontend/src/ui/canvas/results/index.ts b/frontend/src/ui/canvas/results/index.ts new file mode 100644 index 0000000..eadf459 --- /dev/null +++ b/frontend/src/ui/canvas/results/index.ts @@ -0,0 +1,7 @@ +import type { CanvasContext } from '../context'; +import { mountSendTo } from './send'; +import { mountVersions } from './versions'; + +export function mountReview(ctx: CanvasContext): void { + mountSendTo(ctx, mountVersions(ctx)); +} diff --git a/frontend/src/ui/canvas/results/send.ts b/frontend/src/ui/canvas/results/send.ts new file mode 100644 index 0000000..47b955d --- /dev/null +++ b/frontend/src/ui/canvas/results/send.ts @@ -0,0 +1,86 @@ +import { getMedia, type Media } from '../../../io/api'; +import { el, setAttr, setDisabled, setTitle } from '../../dom'; +import { onLanguage, relabel, t } from '../../i18n'; +import { icon } from '../../icons'; +import { Popover } from '../../scene/chrome/popover'; +import { chromeButton, keepFocus, ownTab } from '../../scene/chrome/widgets'; +import { importBlob } from '../../tools/hidden-import'; +import { reason, stamp } from '../base/util'; +import type { CanvasContext } from '../context'; +import type { Review } from './versions'; +import '../../../styles/scene-chrome.css'; + +type Target = 'use-reference' | 'open-scene' | 'add-to-board' | 'add-to-edit'; + +const ROWS: ReadonlyArray<{ id: Target; text: string; icon: string }> = [ + { id: 'use-reference', text: 'Create, as a reference', icon: 'create' }, + { id: 'open-scene', text: 'Scene, as an image plane', icon: 'scene' }, + { id: 'add-to-board', text: 'Board', icon: 'board' }, + { id: 'add-to-edit', text: 'Edit, as a still clip', icon: 'edit' }, +]; + +export function mountSendTo(ctx: CanvasContext, review: Review): HTMLElement { + const root = el(''); + const btn = chromeButton({ icon: 'external', english: 'Send to', chevron: true }); + setAttr(btn, 'aria-haspopup', 'menu'); + setAttr(btn, 'aria-expanded', 'false'); + root.append(btn); + ctx.slots.top.append(root); + keepFocus(root); + ownTab(root); + const pop = new Popover(ctx.slots.modal, { label: t('Send to'), role: 'menu', align: 'start' }); + pop.panel.classList.add('fc-scc-menu'); + keepFocus(pop.panel); + ownTab(pop.panel); + for (const r of ROWS) { + pop.panel.append( + el(``), + ); + } + let busy = false; + + const paint = (): void => { + setDisabled(btn, !ctx.store.base || busy); + setTitle(btn, review.shown ? t('Send the result you are reviewing to another studio') : t('Send the flattened canvas to another studio')); + }; + + const source = async (): Promise => { + const v = review.shown; + if (v && v.meta.baseKey === ctx.store.baseKey) return getMedia(v.media); + const baked = await ctx.bake(); + return importBlob(baked.composite, `canvas-${stamp()}.png`, { hidden: false }); + }; + + btn.addEventListener('click', (e) => pop.toggle(btn, e.detail === 0)); + pop.panel.addEventListener('click', (e) => { + const row = e.target instanceof Element ? e.target.closest('.fc-scc-item') : null; + const id = row?.dataset.id as Target | undefined; + if (!id || busy) return; + pop.close(false); + busy = true; + paint(); + void (async () => { + try { + const m = await source(); + const { runResultAction } = await import('../../feed/result-actions'); + await runResultAction(id, m); + } catch (err) { + ctx.toast(reason(err, t('The canvas could not be sent.')), 'error', { key: 'canvas-send' }); + } finally { + busy = false; + paint(); + } + })(); + }); + + ctx.store.on('base', paint); + ctx.store.on('reset', paint); + ctx.store.on('results', paint); + onLanguage(() => { + relabel(root); + relabel(pop.panel); + paint(); + }); + paint(); + return root; +} diff --git a/frontend/src/ui/canvas/results/versions.ts b/frontend/src/ui/canvas/results/versions.ts new file mode 100644 index 0000000..ca54411 --- /dev/null +++ b/frontend/src/ui/canvas/results/versions.ts @@ -0,0 +1,196 @@ +import { newImageNode } from '../../../engine/canvas/nodes'; +import { mediaFileUrl, mediaThumbUrl } from '../../../io/api'; +import { el, q, setAttr, setClass, setDisabled, setHidden, setText } from '../../dom'; +import { onLanguage, relabel, t } from '../../i18n'; +import { icon } from '../../icons'; +import type { CanvasContext } from '../context'; +import { runs, type RunMeta } from '../generate/session'; +import '../../../styles/canvas-review.css'; + +export interface Version { + media: string; + jobId: string; + prompt: string; + meta: RunMeta; +} + +const SHELL = + `
` + + `
${t('New result')}
` + + `
` + + `` + + `` + + `
` + + `` + + `
` + + `` + + `` + + `
`; + +const typing = (target: EventTarget | null): boolean => + target instanceof HTMLElement && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)); + +export interface Review { + readonly shown: Version | null; +} + +export function mountVersions(ctx: CanvasContext): Review { + const root = el(SHELL); + const preview = el(''); + ctx.slots.overlay.append(preview, root); + const thumb = q(root, '.fc-cg-rev-thumb'); + const count = q(root, '.fc-cg-rev-count'); + const accept = q(root, '.fc-cg-rev-accept'); + const stack: Version[] = []; + const seen = new Set(); + let at = 0; + let before = false; + let working = false; + + const shown = (): Version | null => stack[at] ?? null; + + const place = (): void => { + const v = shown(); + const show = !!v && !before && v.meta.baseKey === ctx.store.baseKey; + setHidden(preview, !show); + if (!v || !show) return; + const src = mediaFileUrl(v.media); + if (preview.dataset.src !== src) { + preview.dataset.src = src; + preview.src = src; + } + const r = v.meta.rect; + const box = v.meta.mode === 'mask' ? { x: 0, y: 0, width: ctx.store.size.width, height: ctx.store.size.height } : r; + const a = ctx.stage.canvasToView(box.x, box.y); + const z = ctx.stage.canvasToView(box.x + box.width, box.y + box.height); + const s = preview.style; + s.left = `${Math.round(a.x)}px`; + s.top = `${Math.round(a.y)}px`; + s.width = `${Math.max(1, Math.round(z.x - a.x))}px`; + s.height = `${Math.max(1, Math.round(z.y - a.y))}px`; + }; + + const paint = (): void => { + const v = shown(); + setHidden(root, !v); + setClass(root, 'is-before', before); + if (v) { + const src = mediaThumbUrl(v.media, 160); + if (thumb.dataset.src !== src) { + thumb.dataset.src = src; + thumb.src = src; + } + setAttr(thumb, 'title', v.prompt); + setText(count, t('{n} of {total}').replace('{n}', String(at + 1)).replace('{total}', String(stack.length))); + const label = v.meta.mode === 'mask' ? 'Accept into the masked area' : 'Accept as a new layer'; + setText(q(accept, '.fc-cg-rev-accept-t'), t(label)); + } + setDisabled(q(root, '[data-act="prev"]'), at <= 0); + setDisabled(q(root, '[data-act="next"]'), at >= stack.length - 1); + setDisabled(accept, working); + place(); + }; + + const step = (d: number): void => { + const next = Math.max(0, Math.min(stack.length - 1, at + d)); + if (next === at) return; + at = next; + paint(); + }; + + const drop = (): void => { + stack.splice(at, 1); + at = Math.min(at, Math.max(0, stack.length - 1)); + before = false; + paint(); + }; + + const take = async (): Promise => { + const v = shown(); + if (!v || working) return; + working = true; + paint(); + try { + const { width, height } = ctx.store.size; + const node = { ...newImageNode(v.media, { x: 0, y: 0, width, height }), name: t('Generated result') }; + ctx.store.addNodes([node], true); + ctx.toast(t('Added as a new layer. Undo removes it.'), 'success', { key: 'canvas-accept' }); + drop(); + } finally { + working = false; + paint(); + } + }; + + const collect = (): void => { + let added = false; + for (const b of ctx.store.results) { + if (b.status !== 'done' || seen.has(b.id)) continue; + const meta = runs.get(b.jobId); + if (!meta) continue; + seen.add(b.id); + for (const m of b.media) stack.push({ media: m, jobId: b.jobId, prompt: b.prompt, meta }); + added = true; + } + if (added) at = stack.length - 1; + paint(); + }; + + root.addEventListener('click', (e) => { + const b = e.target instanceof Element ? e.target.closest('[data-act]') : null; + const act = b?.dataset.act; + if (act === 'prev') step(-1); + else if (act === 'next') step(1); + else if (act === 'accept') void take(); + else if (act === 'discard') drop(); + }); + const compare = q(root, '[data-act="compare"]'); + const hold = (on: boolean): void => { + if (before === on) return; + before = on; + paint(); + }; + compare.addEventListener('pointerdown', (e) => { + compare.setPointerCapture(e.pointerId); + hold(true); + }); + for (const ev of ['pointerup', 'pointercancel', 'lostpointercapture'] as const) compare.addEventListener(ev, () => hold(false)); + compare.addEventListener('keydown', (e) => { + if (e.key === ' ' || e.key === 'Enter') { + e.preventDefault(); + hold(true); + } + }); + compare.addEventListener('keyup', () => hold(false)); + compare.addEventListener('blur', () => hold(false)); + + window.addEventListener( + 'keydown', + (e) => { + if (!shown() || !ctx.root.isConnected || ctx.root.offsetParent === null || typing(e.target) || e.altKey || e.ctrlKey || e.metaKey) return; + const inside = e.target instanceof Node && root.contains(e.target); + if (!inside && ctx.store.hasSelection) return; + const d = e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : 0; + if (!d) return; + e.preventDefault(); + e.stopImmediatePropagation(); + step(d); + }, + true, + ); + + ctx.store.on('results', collect); + ctx.store.on('base', place); + ctx.store.on('reset', () => { + stack.length = 0; + at = 0; + paint(); + }); + ctx.stage.on('view', place); + onLanguage(() => { + relabel(root); + paint(); + }); + collect(); + return { get shown() { return shown(); } }; +} diff --git a/frontend/src/ui/canvas/stage/bake.ts b/frontend/src/ui/canvas/stage/bake.ts index c6e6b1d..adcf0a0 100644 --- a/frontend/src/ui/canvas/stage/bake.ts +++ b/frontend/src/ui/canvas/stage/bake.ts @@ -1,5 +1,5 @@ import type { CanvasStore } from '../../../engine/canvas/store'; -import { drawMaskStrokes, drawNodes, mediaIds } from './render'; +import { composeNodes, drawMaskStrokes, drawOutpaint, fontsReady, mediaIds } from './render'; import type { ImageCache } from './images'; export const BAKE_DELAY_MS = 300; @@ -127,14 +127,17 @@ export class Baker { const base = store.base; if (!base) return null; const { width, height } = store.size; + const content = store.content; + const extended = store.extended; const nodes = store.nodes.slice(); const strokes = store.mask.slice(); const fill = store.background; const want = mediaIds(nodes); if (base.kind === 'media') want.push(base.$media); - await this.images.ready(want); + await Promise.all([this.images.ready(want), fontsReady(nodes)]); if (version !== this.version) return null; const surfaces: HTMLCanvasElement[] = []; + const area = { width, height }; try { const out = make(width, height); surfaces.push(out.c); @@ -143,20 +146,23 @@ export class Baker { g.imageSmoothingQuality = 'high'; if (base.kind === 'media') { const img = this.images.image(base.$media); - if (img) g.drawImage(img, 0, 0, width, height); + if (img) g.drawImage(img, content.x, content.y, content.width, content.height); } else { g.fillStyle = HONOUR_BACKGROUND_ON_BLANK ? fill : '#ffffff'; - g.fillRect(0, 0, width, height); + g.fillRect(content.x, content.y, content.width, content.height); } const draw = make(width, height); surfaces.push(draw.c); - drawNodes(draw.g, nodes, this.images, null); - g.drawImage(draw.c, 0, 0); + composeNodes(g, { + g: draw.g, + flush: () => g.drawImage(draw.c, 0, 0), + clear: () => draw.g.clearRect(0, 0, width, height), + }, nodes, this.images, null, area); release(draw.c); const composite = await blobOf(out.c); release(out.c); let mask: Blob | null = null; - if (strokes.length) { + if (strokes.length || extended) { const m = make(width, height); surfaces.push(m.c); const ink = edit === 'white' ? '#ffffff' : '#000000'; @@ -165,7 +171,8 @@ export class Baker { m.g.fillRect(0, 0, width, height); const strokeLayer = make(width, height); surfaces.push(strokeLayer.c); - drawMaskStrokes(strokeLayer.g, strokes, ink); + if (extended) drawOutpaint(strokeLayer.g, area, content, ink); + drawMaskStrokes(strokeLayer.g, strokes, ink, area); m.g.drawImage(strokeLayer.c, 0, 0); release(strokeLayer.c); mask = await blobOf(m.c); diff --git a/frontend/src/ui/canvas/stage/render.ts b/frontend/src/ui/canvas/stage/render.ts index 7a11def..14ce4e3 100644 --- a/frontend/src/ui/canvas/stage/render.ts +++ b/frontend/src/ui/canvas/stage/render.ts @@ -1,4 +1,4 @@ -import type { CanvasNode, LineNode, MaskStroke, ShapeNode } from '../../../engine/canvas/types'; +import type { CanvasNode, LineNode, MaskStroke, ShapeNode, TextNode } from '../../../engine/canvas/types'; export type Surface2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D; @@ -46,13 +46,113 @@ function strokeLine(g: Surface2D, n: LineNode): void { g.globalAlpha = 1; g.strokeStyle = '#000000'; } else { - g.globalAlpha = n.opacity; + g.globalAlpha = n.opacity * g.globalAlpha; g.strokeStyle = n.colour; } g.stroke(); } -function fillShape(g: Surface2D, n: ShapeNode): void { +export interface Area { + width: number; + height: number; +} + +function polyPath(points: readonly number[]): Path2D { + const p = new Path2D(); + p.moveTo(points[0], points[1]); + for (let i = 2; i + 1 < points.length; i += 2) p.lineTo(points[i], points[i + 1]); + p.closePath(); + return p; +} + +export function fillFeathered(g: Surface2D, path: Path2D, rule: CanvasFillRule, feather: number, span: number): void { + if (!(feather > 0)) { + g.fill(path, rule); + return; + } + const m = g.getTransform(); + const scale = Math.sqrt(Math.abs(m.a * m.d - m.b * m.c)); + const d = span + feather * 8; + g.save(); + g.shadowColor = typeof g.fillStyle === 'string' ? g.fillStyle : '#000000'; + g.shadowBlur = feather * scale; + g.shadowOffsetX = m.a * d; + g.shadowOffsetY = m.b * d; + g.translate(-d, 0); + g.fill(path, rule); + g.restore(); +} + +function regionPath(points: readonly number[], invert: boolean, around: { x: number; y: number; w: number; h: number }): Path2D { + const p = new Path2D(); + if (invert) p.rect(around.x, around.y, around.w, around.h); + p.addPath(polyPath(points)); + return p; +} + +function fillRegion(g: Surface2D, n: ShapeNode, area: Area | null): void { + const pts = n.points ?? []; + if (pts.length < 6) return; + const f = n.feather ?? 0; + const pad = f * 3 + 2; + const w = area?.width ?? n.width; + const h = area?.height ?? n.height; + const around = { x: -n.x - pad, y: -n.y - pad, w: w + pad * 2, h: h + pad * 2 }; + if (n.erase) { + g.globalCompositeOperation = 'destination-out'; + g.globalAlpha = 1; + g.fillStyle = '#000000'; + } else g.fillStyle = n.fill; + fillFeathered(g, regionPath(pts, n.invert === true, around), 'evenodd', f, Math.abs(n.x) + Math.abs(n.y) + w + h + pad * 4); +} + +const TEXT_MEASURE: { g: CanvasRenderingContext2D | null } = { g: null }; + +export const fontOf = (n: Pick): string => `${n.weight} ${n.size}px "${n.font}"`; + +export function textLines(text: string): string[] { + return text.split(/\r?\n/); +} + +export function measureText(n: Pick): { width: number; height: number } { + TEXT_MEASURE.g ??= document.createElement('canvas').getContext('2d'); + const g = TEXT_MEASURE.g; + const lines = textLines(n.text); + let width = 0; + if (g) { + g.font = fontOf(n); + for (const line of lines) width = Math.max(width, g.measureText(line).width); + } + return { width: Math.max(1, Math.ceil(width)), height: Math.max(1, lines.length * n.size * n.lineHeight) }; +} + +function fillText(g: Surface2D, n: TextNode): void { + g.font = fontOf(n); + g.fillStyle = n.colour; + g.textBaseline = 'middle'; + g.textAlign = n.align; + const x = n.align === 'center' ? n.width / 2 : n.align === 'right' ? n.width : 0; + const step = n.size * n.lineHeight; + textLines(n.text).forEach((line, i) => g.fillText(line, x, (i + 0.5) * step)); +} + +export function fontsOf(nodes: readonly CanvasNode[]): string[] { + const out = new Set(); + for (const n of nodes) if (n.kind === 'text') out.add(fontOf({ weight: n.weight, size: 16, font: n.font })); + return Array.from(out); +} + +export async function fontsReady(nodes: readonly CanvasNode[]): Promise { + const specs = fontsOf(nodes); + if (!specs.length || typeof document === 'undefined' || !document.fonts) return; + await Promise.all(specs.map((s) => document.fonts.load(s).catch(() => []))); +} + +function fillShape(g: Surface2D, n: ShapeNode, area: Area | null = null): void { + if (n.shape === 'polygon') { + fillRegion(g, n, area); + return; + } g.fillStyle = n.fill; g.beginPath(); if (n.shape === 'circle') g.ellipse(n.width / 2, n.height / 2, Math.max(0, n.width / 2), Math.max(0, n.height / 2), 0, 0, Math.PI * 2); @@ -65,13 +165,16 @@ function fillShape(g: Surface2D, n: ShapeNode): void { g.fill(); } -export function drawNode(g: Surface2D, node: CanvasNode, images: ImageLookup): void { +export function drawNode(g: Surface2D, node: CanvasNode, images: ImageLookup, area: Area | null = null): void { g.save(); g.translate(node.x, node.y); if (node.rotation) g.rotate(node.rotation * RAD); g.scale(node.scaleX, node.scaleY); + g.globalAlpha = node.alpha ?? 1; + if (node.blend && node.blend !== 'normal') g.globalCompositeOperation = node.blend; if (node.kind === 'line') strokeLine(g, node); - else if (node.kind === 'shape') fillShape(g, node); + else if (node.kind === 'shape') fillShape(g, node, area); + else if (node.kind === 'text') fillText(g, node); else { const src = images.image(node.kind === 'image' ? node.asset.$media : node.render.$media); if (src) g.drawImage(src, 0, 0, node.width, node.height); @@ -79,18 +182,50 @@ export function drawNode(g: Surface2D, node: CanvasNode, images: ImageLookup): v g.restore(); } -export function drawNodes(g: Surface2D, nodes: readonly CanvasNode[], images: ImageLookup, over: Overrides | null = null): void { +export function drawNodes(g: Surface2D, nodes: readonly CanvasNode[], images: ImageLookup, over: Overrides | null = null, area: Area | null = null): void { g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high'; - for (const n of nodes) drawNode(g, applied(n, over), images); + for (const n of nodes) if (!n.hidden) drawNode(g, applied(n, over), images, area); +} + +export interface PaintLayer { + g: Surface2D; + flush(): void; + clear(): void; +} + +export const blended = (n: Readonly): boolean => !!n.blend && n.blend !== 'normal'; + +export function composeNodes(g: Surface2D, layer: PaintLayer, nodes: readonly CanvasNode[], images: ImageLookup, over: Overrides | null, area: Area | null): void { + g.imageSmoothingEnabled = true; + g.imageSmoothingQuality = 'high'; + layer.g.imageSmoothingEnabled = true; + layer.g.imageSmoothingQuality = 'high'; + let dirty = false; + for (const raw of nodes) { + if (raw.hidden) continue; + const n = applied(raw, over); + if (blended(n)) { + if (dirty) { + layer.flush(); + layer.clear(); + dirty = false; + } + drawNode(g, n, images, area); + } else { + drawNode(layer.g, n, images, area); + dirty = true; + } + } + if (dirty) layer.flush(); } export function hasErase(nodes: readonly CanvasNode[]): boolean { - for (const n of nodes) if (n.kind === 'line' && n.erase) return true; + for (const n of nodes) if ((n.kind === 'line' || n.kind === 'shape') && n.erase) return true; return false; } -export function drawMaskStrokes(g: Surface2D, strokes: readonly MaskStroke[], colour = '#ffffff'): void { +export function drawMaskStrokes(g: Surface2D, strokes: readonly MaskStroke[], colour = '#ffffff', area: Area | null = null): void { g.lineCap = 'round'; g.lineJoin = 'round'; for (const s of strokes) { @@ -100,12 +235,31 @@ export function drawMaskStrokes(g: Surface2D, strokes: readonly MaskStroke[], co g.globalAlpha = 1; g.globalCompositeOperation = s.mode === 'erase' ? 'destination-out' : 'source-over'; g.strokeStyle = colour; - strokePath(g, s.points); - g.stroke(); + g.fillStyle = colour; + if (s.fill) { + const f = s.feather ?? 0; + const pad = f * 3 + 2; + const w = area?.width ?? 0; + const h = area?.height ?? 0; + fillFeathered(g, regionPath(s.points, s.invert === true, { x: -pad, y: -pad, w: w + pad * 2, h: h + pad * 2 }), 'evenodd', f, w + h + pad * 4); + } else { + strokePath(g, s.points); + g.stroke(); + } g.restore(); } } +export function drawOutpaint(g: Surface2D, area: Area, content: { x: number; y: number; width: number; height: number }, colour: string): void { + const p = new Path2D(); + p.rect(0, 0, area.width, area.height); + p.rect(content.x, content.y, content.width, content.height); + g.save(); + g.fillStyle = colour; + g.fill(p, 'evenodd'); + g.restore(); +} + export function mediaIds(nodes: readonly CanvasNode[]): string[] { const out = new Set(); for (const n of nodes) { diff --git a/frontend/src/ui/canvas/stage/stage.ts b/frontend/src/ui/canvas/stage/stage.ts index 2503c05..760c3bd 100644 --- a/frontend/src/ui/canvas/stage/stage.ts +++ b/frontend/src/ui/canvas/stage/stage.ts @@ -2,9 +2,8 @@ import { Emitter } from '../../../engine/emitter'; import type { CanvasStore } from '../../../engine/canvas/store'; import { fitView, type Point } from '../../../engine/canvas/geometry'; import { MAX_ZOOM, MIN_ZOOM, type CanvasNode, type MaskStroke } from '../../../engine/canvas/types'; -import { isMac } from '../../dom'; import { ImageCache } from './images'; -import { MASK_ALPHA, MASK_RGB, drawMaskStrokes, drawNodes, hasErase, mediaIds, type Overrides } from './render'; +import { MASK_ALPHA, MASK_RGB, composeNodes, drawMaskStrokes, drawOutpaint, fontsOf, fontsReady, mediaIds, type Overrides } from './render'; export interface Insets { left: number; @@ -19,6 +18,7 @@ export interface Palette { handle: string; handleLine: string; guide: string; + scrim: string; } export type ClippedPainter = (g: CanvasRenderingContext2D, zoom: number) => void; @@ -111,6 +111,14 @@ export class CanvasStage { this.invalidate(); } + private skipId: string | null = null; + + setSkip(id: string | null): void { + if (id === this.skipId) return; + this.skipId = id; + this.invalidate(); + } + setOverrides(over: Overrides | null): void { this.overrides = over; this.invalidate(); @@ -164,6 +172,7 @@ export class CanvasStage { handle: pick('--text-primary', '#f7f7f7'), handleLine: pick('--accent-color', '#7a64f2'), guide: pick('--text-secondary', '#a4a4a4'), + scrim: pick('--bg-scrim', 'rgba(0, 0, 0, 0.6)'), }; return this.colours; } @@ -268,8 +277,11 @@ export class CanvasStage { this.zoomAt(this.zoom * Math.max(0.1, 1 - dy * 0.2 * 0.01), v.x, v.y); return; } - if (isMac && Math.abs(dy) <= 10) return; - this.zoomAt(this.zoom * Math.exp(-dy * 0.0005), v.x, v.y); + let dx = e.deltaX; + if (e.deltaMode === 1) dx *= 16; + else if (e.deltaMode === 2) dx *= 100; + if (e.shiftKey && dx === 0) [dx, dy] = [dy, 0]; + this.panBy(-dx, -dy); } private onScene(): void { @@ -282,6 +294,29 @@ export class CanvasStage { } this.prune(); this.invalidate(); + const fonts = fontsOf(this.store.nodes); + if (fonts.some((f) => !this.fontsSeen.has(f))) { + for (const f of fonts) this.fontsSeen.add(f); + void fontsReady(this.store.nodes).then(() => this.invalidate()); + } + } + + private readonly fontsSeen = new Set(); + private checkerOf: { colour: string; pattern: CanvasPattern | null } | null = null; + + private checker(g: CanvasRenderingContext2D, colour: string): CanvasPattern | string { + if (this.checkerOf?.colour === colour && this.checkerOf.pattern) return this.checkerOf.pattern; + const c = document.createElement('canvas'); + c.width = 16; + c.height = 16; + const t = c.getContext('2d'); + if (!t) return colour; + t.fillStyle = colour; + t.fillRect(0, 0, 8, 8); + t.fillRect(8, 8, 8, 8); + const pattern = g.createPattern(c, 'repeat'); + this.checkerOf = { colour, pattern }; + return pattern ?? colour; } private requestFit(): void { @@ -347,41 +382,49 @@ export class CanvasStage { if (!this.store.base) return; const { width, height } = this.store.size; const base = this.store.base; - const nodes = this.preview?.node ? [...this.store.nodes, this.preview.node] : this.store.nodes; + const live = this.skipId ? this.store.nodes.filter((n) => n.id !== this.skipId) : this.store.nodes; + const nodes = this.preview?.node ? [...live, this.preview.node] : live; const strokes = this.preview?.mask ? [...this.store.mask, this.preview.mask] : this.store.mask; g.save(); g.setTransform(k, 0, 0, k, this.panX * dpr, this.panY * dpr); g.beginPath(); g.rect(0, 0, width, height); g.clip(); + const content = this.store.content; + const area = { width, height }; + if (this.store.extended) { + g.fillStyle = this.checker(g, pal.edge); + g.fillRect(0, 0, width, height); + } g.fillStyle = this.store.background; - g.fillRect(0, 0, width, height); + g.fillRect(content.x, content.y, content.width, content.height); g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high'; if (base.kind === 'media') { const img = this.images.image(base.$media); - if (img) g.drawImage(img, 0, 0, width, height); + if (img) g.drawImage(img, content.x, content.y, content.width, content.height); } - if (hasErase(nodes)) { - const lg = this.lg; + const lg = this.lg; + const clearLayer = (): void => { lg.setTransform(1, 0, 0, 1, 0, 0); lg.clearRect(0, 0, this.layer.width, this.layer.height); lg.setTransform(k, 0, 0, k, this.panX * dpr, this.panY * dpr); - drawNodes(lg, nodes, this.images, this.overrides); - lg.setTransform(1, 0, 0, 1, 0, 0); - const keep = g.getTransform(); - g.setTransform(1, 0, 0, 1, 0, 0); - g.drawImage(this.layer, 0, 0); - g.setTransform(keep); - } else { - drawNodes(g, nodes, this.images, this.overrides); - } - if ((this.maskVisible() || this.preview?.mask) && strokes.length) { - const lg = this.lg; - lg.setTransform(1, 0, 0, 1, 0, 0); - lg.clearRect(0, 0, this.layer.width, this.layer.height); - lg.setTransform(k, 0, 0, k, this.panX * dpr, this.panY * dpr); - drawMaskStrokes(lg, strokes, `rgb(${MASK_RGB})`); + }; + clearLayer(); + composeNodes(g, { + g: lg, + clear: clearLayer, + flush: () => { + const keep = g.getTransform(); + g.setTransform(1, 0, 0, 1, 0, 0); + g.drawImage(this.layer, 0, 0); + g.setTransform(keep); + }, + }, nodes, this.images, this.overrides, area); + if ((this.maskVisible() || this.preview?.mask) && (strokes.length || this.store.extended)) { + clearLayer(); + if (this.store.extended) drawOutpaint(lg, area, content, `rgb(${MASK_RGB})`); + drawMaskStrokes(lg, strokes, `rgb(${MASK_RGB})`, area); lg.setTransform(1, 0, 0, 1, 0, 0); const keep = g.getTransform(); g.setTransform(1, 0, 0, 1, 0, 0); diff --git a/frontend/src/ui/canvas/studio.ts b/frontend/src/ui/canvas/studio.ts index e90fefb..80af5fd 100644 --- a/frontend/src/ui/canvas/studio.ts +++ b/frontend/src/ui/canvas/studio.ts @@ -37,7 +37,7 @@ function insetsOf(root: HTMLElement, slots: Slots): Insets { } const PARTS = import.meta.glob>( - ['./base/index.ts', './files/index.ts', './generate/index.ts', './model3d/index.ts', './results/index.ts'], + ['./base/index.ts', './files/index.ts', './generate/index.ts', './model3d/index.ts', './results/index.ts', './layers/index.ts'], { eager: true }, ); @@ -70,7 +70,7 @@ export function startStudio(shell: CanvasShell): CanvasContext { }; stage.setMaskVisible(() => ctx.maskCapable()); - stage.setInsets(() => insetsOf(root, slots)); + stage.setInsets(() => insetsOf(stageEl, slots)); tools.bindMask( () => ctx.maskCapable(), () => toast(t('The mask tool needs a model that can inpaint. Pick one in the prompt box.'), 'info', { key: 'canvas-mask-model' }), @@ -99,7 +99,8 @@ export function startStudio(shell: CanvasShell): CanvasContext { }); registerCanvasCommands(ctx); - wireInput(stageEl, stage, store, tools, createContextMenu(ctx), () => store.base !== null); + const input = wireInput(stageEl, stage, store, tools, createContextMenu(ctx), () => store.base !== null); + ctx.edit = { text: input.text, region: input.region, crop: input.crop }; mountToolbar(ctx); for (const [path, mod] of Object.entries(PARTS)) { diff --git a/frontend/src/ui/canvas/tools/commands.ts b/frontend/src/ui/canvas/tools/commands.ts index eafeab4..169fe6b 100644 --- a/frontend/src/ui/canvas/tools/commands.ts +++ b/frontend/src/ui/canvas/tools/commands.ts @@ -1,11 +1,14 @@ import { canvasActionOpen, canvasFacts, CANVAS_ACTIONS, type CanvasAction } from '../../../engine/canvas/actions'; import { commands, type Command } from '../../../engine/commands'; import type { CanvasContext } from '../context'; +import { copyCanvas, exportCanvas } from './export'; +import { mergeDown, mergeVisible } from './merge'; +import { t } from '../../i18n'; export function registerCanvasCommands(ctx: CanvasContext): () => void { const { store, tools, stage } = ctx; const facts = () => - canvasFacts(store, { editor: store.base !== null, maskModel: ctx.maskCapable(), tool: tools.tool, edit3dOpen: ctx.edit3dOpen(), busy: ctx.busy() }); + canvasFacts(store, { editor: store.base !== null, maskModel: ctx.maskCapable(), tool: tools.tool, edit3dOpen: ctx.edit3dOpen(), busy: ctx.busy(), region: ctx.edit?.region.active ?? false }); const open = (a: CanvasAction) => (): boolean => canvasActionOpen(a, facts()); const editor = (): boolean => store.base !== null && !ctx.busy(); const run: Record void> = { @@ -22,6 +25,36 @@ export function registerCanvasCommands(ctx: CanvasContext): () => void { 'canvas.undo': () => void store.undo(), 'canvas.redo': () => void store.redo(), 'canvas.commit3d': () => ctx.commit3d?.(), + 'canvas.fit': () => stage.fit(), + 'canvas.zoom100': () => stage.setZoom(1), + 'canvas.exportPng': () => void exportCanvas(ctx, 'png'), + 'canvas.copyImage': () => void copyCanvas(ctx), + 'canvas.toolText': () => void tools.setTool('text'), + 'canvas.toolEyedropper': () => void tools.setTool('eyedropper'), + 'canvas.toolCrop': () => void tools.setTool('crop'), + 'canvas.toolMarquee': () => void tools.setTool('marquee'), + 'canvas.toolLasso': () => void tools.setTool('lasso'), + 'canvas.cropApply': () => { + ctx.edit?.crop.apply(); + tools.setTool('select'); + }, + 'canvas.cropCancel': () => void tools.setTool('select'), + 'canvas.regionFill': () => void ctx.edit?.region.fill(tools.brushColour), + 'canvas.regionClear': () => void ctx.edit?.region.erase(), + 'canvas.regionInvert': () => ctx.edit?.region.invert(), + 'canvas.regionMask': () => { + if (ctx.edit?.region.toMask() && !ctx.maskCapable()) { + ctx.toast(t('Added to the mask. Pick a model that can inpaint to see and use it.'), 'info', { key: 'canvas-mask-model' }); + } + }, + 'canvas.regionNone': () => ctx.edit?.region.clear(), + 'canvas.group': () => void store.groupNodes(), + 'canvas.ungroup': () => void store.ungroup(), + 'canvas.mergeDown': () => void mergeDown(ctx), + 'canvas.mergeVisible': () => void mergeVisible(ctx), + 'canvas.flipH': () => void store.flip('x'), + 'canvas.flipV': () => void store.flip('y'), + 'canvas.toggleRail': () => tools.setRail(!tools.railOpen), }; const list: Command[] = CANVAS_ACTIONS.map((a) => { const base: Command = { id: a.id, label: a.label, group: a.group, enabled: open(a), run: run[a.id] ?? (() => undefined) }; @@ -54,11 +87,20 @@ export function registerCanvasCommands(ctx: CanvasContext): () => void { { id: 'canvas.moveDown', label: 'Send backward', group: 'Edit', enabled: picked, run: () => void store.moveDown() }, { id: 'canvas.toBack', label: 'Send to back', group: 'Edit', enabled: picked, run: () => void store.toBack() }, { id: 'canvas.duplicate', label: 'Duplicate', group: 'Edit', enabled: picked, run: () => void store.duplicate() }, - { id: 'canvas.fit', label: 'Fit canvas to screen', group: 'View', enabled: () => store.base !== null, run: () => stage.fit() }, + { id: 'canvas.exportJpeg', label: 'Export as JPEG', group: 'Edit', enabled: editor, run: () => void exportCanvas(ctx, 'jpeg') }, + { id: 'canvas.exportWebp', label: 'Export as WebP', group: 'Edit', enabled: editor, run: () => void exportCanvas(ctx, 'webp') }, + { id: 'canvas.exportPng2x', label: 'Export as PNG at double size', group: 'Edit', enabled: editor, run: () => void exportCanvas(ctx, 'png', { scale: 2 }) }, + { id: 'canvas.exportPngHalf', label: 'Export as PNG at half size', group: 'Edit', enabled: editor, run: () => void exportCanvas(ctx, 'png', { scale: 0.5 }) }, + { id: 'canvas.exportSelection', label: 'Export the selection as PNG', group: 'Edit', enabled: picked, run: () => void exportCanvas(ctx, 'png', { selection: true }) }, + { id: 'canvas.copySelection', label: 'Copy the selection as a picture', group: 'Edit', enabled: picked, run: () => void copyCanvas(ctx, { selection: true }) }, ); const off = commands.register(list); const refresh = (): void => commands.refresh(); const subs = [store.on('selection', refresh), store.on('history', refresh), tools.on('change', refresh)]; + queueMicrotask(() => { + const off2 = ctx.edit?.region.on(refresh); + if (off2) subs.push(off2); + }); return () => { off(); for (const s of subs) s(); diff --git a/frontend/src/ui/canvas/tools/crop.ts b/frontend/src/ui/canvas/tools/crop.ts new file mode 100644 index 0000000..28e6f5d --- /dev/null +++ b/frontend/src/ui/canvas/tools/crop.ts @@ -0,0 +1,240 @@ +import { Emitter } from '../../../engine/emitter'; +import type { Point } from '../../../engine/canvas/geometry'; +import type { CanvasStore } from '../../../engine/canvas/store'; +import type { CanvasRect } from '../../../engine/canvas/types'; +import type { CanvasStage } from '../stage/stage'; +import type { Drag } from './drag'; + +export type CropHandle = 'tl' | 't' | 'tr' | 'r' | 'br' | 'b' | 'bl' | 'l' | 'move'; + +export const CROP_ASPECTS: ReadonlyArray<{ id: string; label: string; ratio: number | null | 'original' }> = [ + { id: 'free', label: 'Free', ratio: null }, + { id: 'original', label: 'Original', ratio: 'original' }, + { id: '1:1', label: '1:1', ratio: 1 }, + { id: '4:3', label: '4:3', ratio: 4 / 3 }, + { id: '3:2', label: '3:2', ratio: 3 / 2 }, + { id: '16:9', label: '16:9', ratio: 16 / 9 }, + { id: '3:4', label: '3:4', ratio: 3 / 4 }, + { id: '2:3', label: '2:3', ratio: 2 / 3 }, + { id: '9:16', label: '9:16', ratio: 9 / 16 }, +]; + +const DIRS: Record, readonly [number, number]> = { + tl: [-1, -1], t: [0, -1], tr: [1, -1], r: [1, 0], br: [1, 1], b: [0, 1], bl: [-1, 1], l: [-1, 0], +}; +const HIT_PX = 9; +const MIN = 8; +const MAX = 16384; + +export class CropController { + rect: CanvasRect | null = null; + aspect = 'free'; + private readonly emitter = new Emitter<{ change: [] }>(); + + constructor(private readonly store: CanvasStore, private readonly stage: CanvasStage) { + store.on('base', () => this.reset()); + store.on('reset', () => this.reset()); + } + + on(fn: () => void): () => void { + return this.emitter.on('change', fn); + } + + private changed(): void { + this.stage.invalidate(); + this.emitter.emit('change'); + } + + reset(): void { + const s = this.store.size; + this.rect = { x: 0, y: 0, width: s.width, height: s.height }; + this.aspect = 'free'; + this.changed(); + } + + private ratio(): number | null { + const a = CROP_ASPECTS.find((x) => x.id === this.aspect)?.ratio ?? null; + if (a === 'original') { + const c = this.store.content; + return c.width / Math.max(1, c.height); + } + return a; + } + + setAspect(id: string): void { + if (!CROP_ASPECTS.some((a) => a.id === id)) return; + this.aspect = id; + const r = this.ratio(); + if (r && this.rect) { + const cx = this.rect.x + this.rect.width / 2; + const cy = this.rect.y + this.rect.height / 2; + let w = this.rect.width; + let h = w / r; + if (h > this.rect.height) { + h = this.rect.height; + w = h * r; + } + this.rect = this.round({ x: cx - w / 2, y: cy - h / 2, width: w, height: h }); + } + this.changed(); + } + + setSize(width: number, height: number): void { + if (!this.rect) this.reset(); + const r = this.rect!; + const w = Math.min(MAX, Math.max(MIN, Math.round(width) || r.width)); + const h = Math.min(MAX, Math.max(MIN, Math.round(height) || r.height)); + const cx = r.x + r.width / 2; + const cy = r.y + r.height / 2; + this.rect = this.round({ x: cx - w / 2, y: cy - h / 2, width: w, height: h }); + this.changed(); + } + + apply(): boolean { + const r = this.rect; + if (!r) return false; + const s = this.store.size; + const grows = r.x < 0 || r.y < 0 || r.x + r.width > s.width || r.y + r.height > s.height; + const ok = this.store.setFrame(r, grows ? 'Extend canvas' : 'Crop'); + this.reset(); + return ok; + } + + private round(r: CanvasRect): CanvasRect { + return { x: Math.round(r.x), y: Math.round(r.y), width: Math.max(MIN, Math.round(r.width)), height: Math.max(MIN, Math.round(r.height)) }; + } + + private handlePoint(h: Exclude, r: CanvasRect): Point { + const [sx, sy] = DIRS[h]; + return { x: r.x + ((sx + 1) / 2) * r.width, y: r.y + ((sy + 1) / 2) * r.height }; + } + + hit(p: Point): CropHandle | null { + const r = this.rect; + if (!r) return null; + for (const h of Object.keys(DIRS) as Array>) { + const q = this.handlePoint(h, r); + if (Math.hypot(q.x - p.x, q.y - p.y) * this.stage.zoom <= HIT_PX) return h; + } + return p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height ? 'move' : null; + } + + cursor(p: Point): string { + const h = this.hit(p); + if (!h) return 'crosshair'; + if (h === 'move') return 'move'; + return h === 't' || h === 'b' ? 'ns-resize' : h === 'l' || h === 'r' ? 'ew-resize' : h === 'tl' || h === 'br' ? 'nwse-resize' : 'nesw-resize'; + } + + down(p: Point): Drag { + if (!this.rect) this.reset(); + const start = { ...this.rect! }; + const h = this.hit(p); + let dead = false; + this.stage.setGesture(true); + const done = (): void => this.stage.setGesture(false); + return { + move: (e) => { + if (dead) return; + const q = this.stage.clientToCanvas(e.clientX, e.clientY); + const dx = q.x - p.x; + const dy = q.y - p.y; + if (h === 'move') this.rect = this.round({ ...start, x: start.x + dx, y: start.y + dy }); + else if (h) this.rect = this.resize(start, h, q, e.altKey, e.shiftKey); + else this.rect = this.resize({ x: p.x, y: p.y, width: 0, height: 0 }, 'br', q, e.altKey, e.shiftKey); + this.changed(); + }, + up: () => { + dead = true; + done(); + }, + cancel: () => { + dead = true; + this.rect = start; + done(); + this.changed(); + }, + }; + } + + private resize(r: CanvasRect, h: Exclude, q: Point, centre: boolean, square: boolean): CanvasRect { + const [sx, sy] = DIRS[h]; + let x0 = r.x; + let y0 = r.y; + let x1 = r.x + r.width; + let y1 = r.y + r.height; + const cx = (x0 + x1) / 2; + const cy = (y0 + y1) / 2; + if (sx < 0) x0 = q.x; + if (sx > 0) x1 = q.x; + if (sy < 0) y0 = q.y; + if (sy > 0) y1 = q.y; + if (centre) { + if (sx) { + const half = Math.abs(q.x - cx); + x0 = cx - half; + x1 = cx + half; + } + if (sy) { + const half = Math.abs(q.y - cy); + y0 = cy - half; + y1 = cy + half; + } + } + let w = Math.max(MIN, Math.abs(x1 - x0)); + let hh = Math.max(MIN, Math.abs(y1 - y0)); + const ratio = this.ratio() ?? (square ? 1 : null); + if (ratio) { + if (sx && sy) { + if (w / hh > ratio) hh = w / ratio; + else w = hh * ratio; + } else if (sx) hh = w / ratio; + else w = hh * ratio; + } + const left = centre ? cx - w / 2 : sx < 0 ? Math.min(x1, r.x + r.width) - w : sx > 0 ? r.x : cx - w / 2; + const top = centre ? cy - hh / 2 : sy < 0 ? Math.min(y1, r.y + r.height) - hh : sy > 0 ? r.y : cy - hh / 2; + return this.round({ x: left, y: top, width: Math.min(MAX, w), height: Math.min(MAX, hh) }); + } + + paintTop(g: CanvasRenderingContext2D): void { + const r = this.rect; + if (!r) return; + const pal = this.stage.palette(); + const s = this.store.size; + const a = this.stage.canvasToView(r.x, r.y); + const b = this.stage.canvasToView(r.x + r.width, r.y + r.height); + const ca = this.stage.canvasToView(0, 0); + const cb = this.stage.canvasToView(s.width, s.height); + const shade = new Path2D(); + shade.rect(Math.min(a.x, ca.x) - 4000, Math.min(a.y, ca.y) - 4000, 8000 + Math.max(b.x, cb.x), 8000 + Math.max(b.y, cb.y)); + shade.rect(a.x, a.y, b.x - a.x, b.y - a.y); + g.fillStyle = pal.scrim; + g.fill(shade, 'evenodd'); + g.strokeStyle = pal.handle; + g.lineWidth = 1; + g.strokeRect(a.x + 0.5, a.y + 0.5, b.x - a.x, b.y - a.y); + g.setLineDash([2, 4]); + g.strokeStyle = pal.guide; + for (let i = 1; i < 3; i++) { + const x = a.x + ((b.x - a.x) * i) / 3; + const y = a.y + ((b.y - a.y) * i) / 3; + g.beginPath(); + g.moveTo(x, a.y); + g.lineTo(x, b.y); + g.moveTo(a.x, y); + g.lineTo(b.x, y); + g.stroke(); + } + g.setLineDash([]); + g.fillStyle = pal.handle; + g.strokeStyle = pal.accent; + for (const h of Object.keys(DIRS) as Array>) { + const q = this.handlePoint(h, r); + const v = this.stage.canvasToView(q.x, q.y); + g.beginPath(); + g.rect(v.x - 4, v.y - 4, 8, 8); + g.fill(); + g.stroke(); + } + } +} diff --git a/frontend/src/ui/canvas/tools/export.ts b/frontend/src/ui/canvas/tools/export.ts new file mode 100644 index 0000000..2f929f2 --- /dev/null +++ b/frontend/src/ui/canvas/tools/export.ts @@ -0,0 +1,79 @@ +import { clampRectToCanvas, unionBounds, type Rect } from '../../../engine/canvas/geometry'; +import { t } from '../../i18n'; +import { saveBlob } from '../../save-media'; +import type { CanvasContext } from '../context'; + +export type ExportFormat = 'png' | 'jpeg' | 'webp'; + +export interface ExportOptions { + scale?: number; + selection?: boolean; +} + +const MIME: Record = { png: 'image/png', jpeg: 'image/jpeg', webp: 'image/webp' }; +const EXT: Record = { png: 'png', jpeg: 'jpg', webp: 'webp' }; +const KEY = 'canvas-export'; + +function selectionRect(ctx: CanvasContext): Rect | null { + const box = unionBounds(ctx.store.selectedNodes()); + if (!box) return null; + const s = ctx.store.size; + const r = clampRectToCanvas(box, s.width, s.height); + return r.width >= 1 && r.height >= 1 ? r : null; +} + +export async function renderCanvas(ctx: CanvasContext, format: ExportFormat, opts: ExportOptions = {}): Promise { + const { composite } = await ctx.bake(); + const bitmap = await createImageBitmap(composite); + try { + const crop = opts.selection ? selectionRect(ctx) : null; + const src = crop ?? { x: 0, y: 0, width: bitmap.width, height: bitmap.height }; + const scale = Math.max(0.05, Math.min(4, opts.scale ?? 1)); + const w = Math.max(1, Math.round(src.width * scale)); + const h = Math.max(1, Math.round(src.height * scale)); + if (format === 'png' && scale === 1 && !crop) return composite; + const c = document.createElement('canvas'); + c.width = w; + c.height = h; + const g = c.getContext('2d'); + if (!g) throw new Error(t('The canvas could not be encoded.')); + if (format === 'jpeg') { + g.fillStyle = ctx.store.background || '#ffffff'; + g.fillRect(0, 0, w, h); + } + g.imageSmoothingQuality = 'high'; + g.drawImage(bitmap, src.x, src.y, src.width, src.height, 0, 0, w, h); + const blob = await new Promise((resolve) => c.toBlob(resolve, MIME[format], 0.92)); + c.width = 0; + c.height = 0; + if (!blob) throw new Error(t('The canvas could not be encoded.')); + return blob; + } finally { + bitmap.close(); + } +} + +export async function exportCanvas(ctx: CanvasContext, format: ExportFormat, opts: ExportOptions = {}): Promise { + if (!ctx.store.base) return; + if (opts.selection && !selectionRect(ctx)) { + ctx.toast(t('Select something on the canvas first.'), 'info', { key: KEY }); + return; + } + try { + const blob = await renderCanvas(ctx, format, opts); + await saveBlob(blob, `canvas.${EXT[format]}`, 'Export canvas'); + } catch (err) { + ctx.toast(err instanceof Error && err.message ? err.message : t('The canvas could not be exported.'), 'error', { key: KEY }); + } +} + +export async function copyCanvas(ctx: CanvasContext, opts: ExportOptions = {}): Promise { + if (!ctx.store.base) return; + try { + const blob = await renderCanvas(ctx, 'png', opts); + await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]); + ctx.toast(t('Copied the canvas as a picture.'), 'success', { key: KEY }); + } catch { + ctx.toast(t('The picture could not be copied.'), 'error', { key: KEY }); + } +} diff --git a/frontend/src/ui/canvas/tools/eyedropper.ts b/frontend/src/ui/canvas/tools/eyedropper.ts new file mode 100644 index 0000000..f5b4b1a --- /dev/null +++ b/frontend/src/ui/canvas/tools/eyedropper.ts @@ -0,0 +1,55 @@ +import type { Point } from '../../../engine/canvas/geometry'; +import type { CanvasStore } from '../../../engine/canvas/store'; +import type { ImageCache } from '../stage/images'; +import { composeNodes, fontsReady, mediaIds } from '../stage/render'; + +const hex2 = (n: number): string => n.toString(16).padStart(2, '0'); + +function surface(): { c: HTMLCanvasElement; g: CanvasRenderingContext2D } | null { + const c = document.createElement('canvas'); + c.width = 1; + c.height = 1; + const g = c.getContext('2d', { willReadFrequently: true }); + return g ? { c, g } : null; +} + +export async function sampleCanvas(store: CanvasStore, images: ImageCache, p: Point): Promise { + const base = store.base; + const size = store.size; + if (!base || p.x < 0 || p.y < 0 || p.x >= size.width || p.y >= size.height) return null; + const nodes = store.nodes.slice(); + const want = mediaIds(nodes); + if (base.kind === 'media') want.push(base.$media); + await Promise.all([images.ready(want), fontsReady(nodes)]); + const out = surface(); + const layer = surface(); + if (!out || !layer) return null; + const x = Math.floor(p.x); + const y = Math.floor(p.y); + const content = store.content; + for (const s of [out.g, layer.g]) s.setTransform(1, 0, 0, 1, -x, -y); + out.g.fillStyle = store.background; + out.g.fillRect(content.x, content.y, content.width, content.height); + if (base.kind === 'media') { + const img = images.image(base.$media); + if (img) out.g.drawImage(img, content.x, content.y, content.width, content.height); + } + composeNodes(out.g, { + g: layer.g, + flush: () => { + out.g.save(); + out.g.setTransform(1, 0, 0, 1, 0, 0); + out.g.drawImage(layer.c, 0, 0); + out.g.restore(); + }, + clear: () => { + layer.g.save(); + layer.g.setTransform(1, 0, 0, 1, 0, 0); + layer.g.clearRect(0, 0, 1, 1); + layer.g.restore(); + }, + }, nodes, images, null, size); + const d = out.g.getImageData(0, 0, 1, 1).data; + if (d[3] === 0) return null; + return `#${hex2(d[0])}${hex2(d[1])}${hex2(d[2])}`; +} diff --git a/frontend/src/ui/canvas/tools/icons.ts b/frontend/src/ui/canvas/tools/icons.ts index 2d7937f..17ea219 100644 --- a/frontend/src/ui/canvas/tools/icons.ts +++ b/frontend/src/ui/canvas/tools/icons.ts @@ -14,5 +14,15 @@ Object.assign(ICONS, { cvForward: wrap(''), cvBackward: wrap(''), cvBack: wrap(''), - cvReset: wrap(''), + cvText: wrap(''), + cvEyedropper: wrap(''), + cvCrop: wrap(''), + cvMarquee: wrap(''), + cvLasso: wrap(''), + cvRail: wrap(''), + cvFlipH: wrap(''), + cvFlipV: wrap(''), + cvGroup: wrap(''), + cvMerge: wrap(''), + cvReset:wrap(''), }); diff --git a/frontend/src/ui/canvas/tools/input.ts b/frontend/src/ui/canvas/tools/input.ts index 5b3b7b0..039e2bf 100644 --- a/frontend/src/ui/canvas/tools/input.ts +++ b/frontend/src/ui/canvas/tools/input.ts @@ -5,12 +5,19 @@ import { DrawController } from './draw'; import type { Drag } from './drag'; import { SelectController } from './select'; import type { ToolState } from './state'; +import { TextController } from './text'; +import { RegionController } from './region'; +import { CropController } from './crop'; +import { sampleCanvas } from './eyedropper'; const PAN_MOVED_PX = 4; export interface InputParts { readonly select: SelectController; readonly draw: DrawController; + readonly text: TextController; + readonly region: RegionController; + readonly crop: CropController; dispose(): void; } @@ -24,6 +31,9 @@ export function wireInput( ): InputParts { const select = new SelectController(store, stage); const draw = new DrawController(store, stage, tools); + const text = new TextController(host, store, stage, tools); + const region = new RegionController(store, stage); + const crop = new CropController(store, stage); const view = stage.view; const ring = document.createElement('div'); ring.className = 'fc-cv-ring'; @@ -36,9 +46,31 @@ export function wireInput( let suppressMenu = false; const touches = new Map(); let pinch: { dist: number; cx: number; cy: number } | null = null; + let spaceHeld = false; + const typing = (t: EventTarget | null): boolean => + t instanceof HTMLElement && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)); + const onKey = (e: KeyboardEvent): void => { + if (e.code !== 'Space' || typing(e.target) || !enabled() || !host.isConnected || host.offsetParent === null) return; + const down = e.type === 'keydown'; + if (down) e.preventDefault(); + if (spaceHeld === down) return; + spaceHeld = down; + host.dataset.space = String(down); + if (!panning) stage.setCursor(down ? 'grab' : 'default'); + }; + window.addEventListener('keydown', onKey); + window.addEventListener('keyup', onKey); + window.addEventListener('blur', () => { + spaceHeld = false; + host.dataset.space = 'false'; + }); const off1 = stage.addPainter('top', (g) => select.paintTop(g)); const off2 = stage.addPainter('clipped', (g, zoom) => draw.paintClipped(g, zoom)); + const off3 = stage.addPainter('top', (g) => region.paintTop(g)); + const off4 = stage.addPainter('top', (g) => { + if (tools.tool === 'crop') crop.paintTop(g); + }); const ringSize = (): number => (tools.tool === 'brush' ? tools.brushSize : tools.tool === 'eraser' ? tools.eraserSize : tools.maskSize); const ringOn = (): boolean => tools.tool === 'brush' || tools.tool === 'eraser' || tools.tool === 'mask'; @@ -68,9 +100,13 @@ export function wireInput( const s = store.size; const inside = insideCanvas(p, s.width, s.height); let cursor = 'default'; - if (tools.tool === 'select') cursor = select.hoverCursor(p); + if (spaceHeld) cursor = 'grab'; + else if (tools.tool === 'select') cursor = select.hoverCursor(p); + else if (tools.tool === 'crop') cursor = crop.cursor(p); + else if (tools.tool === 'marquee' || tools.tool === 'lasso') cursor = 'crosshair'; else if (!inside) cursor = 'grab'; - else cursor = tools.tool === 'shape' ? 'crosshair' : 'none'; + else if (tools.tool === 'text') cursor = text.textAt(p) ? 'text' : 'crosshair'; + else cursor = tools.tool === 'shape' || tools.tool === 'eyedropper' ? 'crosshair' : 'none'; stage.setCursor(cursor); placeRing(clientX, clientY); }; @@ -103,7 +139,7 @@ export function wireInput( } if (drag || panning) return; const p = stage.clientToCanvas(e.clientX, e.clientY); - if (e.button === 1) { + if (e.button === 1 || (e.button === 0 && spaceHeld)) { e.preventDefault(); view.setPointerCapture(e.pointerId); startPan(e); @@ -124,10 +160,25 @@ export function wireInput( const s = store.size; const inside = insideCanvas(p, s.width, s.height); let started: Drag | 'pan' | null = null; - if (tools.tool === 'select') started = select.down(e, p); + const tool = tools.tool; + if (tool === 'select') started = select.down(e, p); + else if (tool === 'crop') started = crop.down(p); + else if (tool === 'marquee' || tool === 'lasso') started = region.down(tool, p); else if (!inside) started = 'pan'; - else if (tools.tool === 'shape') started = draw.shapeDrag(p); - else started = draw.stroke(tools.tool, p); + else if (tool === 'shape') started = draw.shapeDrag(p); + else if (tool === 'text') { + text.down(p); + started = null; + } else if (tool === 'eyedropper') { + void sampleCanvas(store, stage.images, p).then((c) => { + if (c) tools.setColour(c); + }); + started = null; + } else started = draw.stroke(tool, p); + if (started === null) { + if (view.hasPointerCapture(e.pointerId)) view.releasePointerCapture(e.pointerId); + return; + } if (started === 'pan') startPan(e); else drag = started; }; @@ -217,7 +268,14 @@ export function wireInput( view.addEventListener('lostpointercapture', (e) => { if ((drag && e.pointerId === activeId) || (panning && e.pointerId === panning.id)) stopAll(); }); + view.addEventListener('dblclick', (e) => { + if (!enabled() || tools.tool !== 'select') return; + const hit = text.textAt(stage.clientToCanvas(e.clientX, e.clientY)); + if (hit) text.edit(hit.id); + }); const offTool = tools.on('tool', () => { + text.commit(); + if (tools.tool === 'crop') crop.reset(); stopAll(); if (tools.tool !== 'select') select.marquee = null; ring.hidden = true; @@ -231,11 +289,18 @@ export function wireInput( return { select, draw, + text, + region, + crop, dispose: () => { off1(); off2(); + off3(); + off4(); offTool(); offChange(); + window.removeEventListener('keydown', onKey); + window.removeEventListener('keyup', onKey); ring.remove(); }, }; diff --git a/frontend/src/ui/canvas/tools/menu.ts b/frontend/src/ui/canvas/tools/menu.ts index 5d4c78b..2929b2d 100644 --- a/frontend/src/ui/canvas/tools/menu.ts +++ b/frontend/src/ui/canvas/tools/menu.ts @@ -13,6 +13,28 @@ const FULL = [ '-', 'canvas.duplicate', 'canvas.delete', + '-', + 'canvas.group', + 'canvas.ungroup', + 'canvas.mergeDown', + 'canvas.flipH', + 'canvas.flipV', + '-', + 'canvas.exportSelection', + 'canvas.copySelection', +]; + +export const EXPORT_ITEMS = [ + 'canvas.exportPng', + 'canvas.exportJpeg', + 'canvas.exportWebp', + '-', + 'canvas.exportPngHalf', + 'canvas.exportPng2x', + 'canvas.exportSelection', + '-', + 'canvas.copyImage', + 'canvas.copySelection', ]; export function createContextMenu(ctx: CanvasContext): (x: number, y: number) => void { diff --git a/frontend/src/ui/canvas/tools/merge.ts b/frontend/src/ui/canvas/tools/merge.ts new file mode 100644 index 0000000..32e1fa9 --- /dev/null +++ b/frontend/src/ui/canvas/tools/merge.ts @@ -0,0 +1,98 @@ +import { unionBounds } from '../../../engine/canvas/geometry'; +import { newImageNode } from '../../../engine/canvas/nodes'; +import type { CanvasNode } from '../../../engine/canvas/types'; +import { importMediaFiles } from '../../../io/api'; +import { t } from '../../i18n'; +import { reason } from '../base/util'; +import type { CanvasContext } from '../context'; +import { composeNodes, fontsReady, mediaIds } from '../stage/render'; + +const KEY = 'canvas-merge'; +const MAX_SIDE = 8192; + +async function rasterise(ctx: CanvasContext, nodes: readonly CanvasNode[], name: string, label: string): Promise { + const box = unionBounds(nodes); + if (!box || box.width < 1 || box.height < 1) return false; + const x0 = Math.floor(box.x); + const y0 = Math.floor(box.y); + const w = Math.min(MAX_SIDE, Math.ceil(box.x + box.width) - x0); + const h = Math.min(MAX_SIDE, Math.ceil(box.y + box.height) - y0); + const images = ctx.stage.images; + await Promise.all([images.ready(mediaIds(nodes as CanvasNode[])), fontsReady(nodes)]); + const make = (): { c: HTMLCanvasElement; g: CanvasRenderingContext2D } => { + const c = document.createElement('canvas'); + c.width = w; + c.height = h; + const g = c.getContext('2d'); + if (!g) throw new Error(t('The canvas could not be encoded.')); + g.setTransform(1, 0, 0, 1, -x0, -y0); + return { c, g }; + }; + const out = make(); + const layer = make(); + const plain = nodes.map((n) => ({ ...n, blend: undefined }) as CanvasNode); + composeNodes(out.g, { + g: layer.g, + flush: () => { + out.g.save(); + out.g.setTransform(1, 0, 0, 1, 0, 0); + out.g.drawImage(layer.c, 0, 0); + out.g.restore(); + }, + clear: () => { + layer.g.save(); + layer.g.setTransform(1, 0, 0, 1, 0, 0); + layer.g.clearRect(0, 0, w, h); + layer.g.restore(); + }, + }, plain, images, null, ctx.store.size); + const blob = await new Promise((resolve) => out.c.toBlob(resolve, 'image/png')); + out.c.width = 0; + layer.c.width = 0; + if (!blob) throw new Error(t('The canvas could not be encoded.')); + const res = await importMediaFiles([new File([blob], `${name}.png`, { type: 'image/png' })]); + const media = res.items[0]; + if (!media) throw new Error(t('Upload failed. Please try again.')); + const ids = nodes.map((n) => n.id); + if (ids.some((id) => !ctx.store.node(id))) { + ctx.toast(t('The layers changed while they were being merged, so nothing was merged.'), 'warning', { key: KEY }); + return false; + } + const node = newImageNode(media.id, { x: x0, y: y0, width: w, height: h }); + return !!ctx.store.replaceNodes(ids, { ...node, name }, label); +} + +export async function mergeDown(ctx: CanvasContext): Promise { + const store = ctx.store; + const sel = store.selectedNodes(); + if (!sel.length) return; + const all = store.nodes; + const top = sel.length === 1 ? all.indexOf(sel[0]) : -1; + const pick = sel.length > 1 ? sel : top > 0 ? [all[top - 1], all[top]] : []; + if (pick.length < 2) { + ctx.toast(t('There is no layer below to merge into.'), 'info', { key: KEY }); + return; + } + if (pick.some((n) => n.locked)) { + ctx.toast(t('Unlock the layers first.'), 'info', { key: KEY }); + return; + } + try { + await rasterise(ctx, pick as CanvasNode[], t('Merged'), 'Merge down'); + } catch (err) { + ctx.toast(reason(err, t('The layers could not be merged.')), 'error', { key: KEY }); + } +} + +export async function mergeVisible(ctx: CanvasContext): Promise { + const pick = ctx.store.nodes.filter((n) => !n.hidden && !n.locked); + if (pick.length < 2) { + ctx.toast(t('There is nothing to merge yet.'), 'info', { key: KEY }); + return; + } + try { + await rasterise(ctx, pick as CanvasNode[], t('Merged'), 'Merge visible'); + } catch (err) { + ctx.toast(reason(err, t('The layers could not be merged.')), 'error', { key: KEY }); + } +} diff --git a/frontend/src/ui/canvas/tools/region.ts b/frontend/src/ui/canvas/tools/region.ts new file mode 100644 index 0000000..8129742 --- /dev/null +++ b/frontend/src/ui/canvas/tools/region.ts @@ -0,0 +1,164 @@ +import { Emitter } from '../../../engine/emitter'; +import type { Point } from '../../../engine/canvas/geometry'; +import { newRegionNode } from '../../../engine/canvas/nodes'; +import type { CanvasStore } from '../../../engine/canvas/store'; +import { FEATHER_MAX } from '../../../engine/canvas/types'; +import type { CanvasStage } from '../stage/stage'; +import type { Drag } from './drag'; + +const MIN_DRAG_PX = 3; + +export class RegionController { + points: number[] | null = null; + inverted = false; + feather = 0; + private draft: number[] | null = null; + private readonly emitter = new Emitter<{ change: [] }>(); + + constructor(private readonly store: CanvasStore, private readonly stage: CanvasStage) { + const drop = (): void => this.clear(); + store.on('base', drop); + store.on('reset', drop); + } + + on(fn: () => void): () => void { + return this.emitter.on('change', fn); + } + + get active(): boolean { + return this.points !== null; + } + + private changed(): void { + this.stage.invalidate(); + this.emitter.emit('change'); + } + + clear(): void { + if (!this.points && !this.draft) return; + this.points = null; + this.draft = null; + this.inverted = false; + this.changed(); + } + + invert(): void { + if (!this.points) { + const s = this.store.size; + this.points = [0, 0, s.width, 0, s.width, s.height, 0, s.height]; + this.inverted = false; + } else this.inverted = !this.inverted; + this.changed(); + } + + setFeather(v: number): void { + const f = Math.min(FEATHER_MAX, Math.max(0, Math.round(Number.isFinite(v) ? v : 0))); + if (f === this.feather) return; + this.feather = f; + this.emitter.emit('change'); + } + + selectAll(): void { + const s = this.store.size; + this.points = [0, 0, s.width, 0, s.width, s.height, 0, s.height]; + this.inverted = false; + this.changed(); + } + + down(kind: 'marquee' | 'lasso', start: Point): Drag { + const pts: number[] = [start.x, start.y]; + let end = start; + let began = false; + let dead = false; + this.stage.setGesture(true); + const rect = (a: Point, b: Point): number[] => [a.x, a.y, b.x, a.y, b.x, b.y, a.x, b.y]; + const finish = (): void => { + this.draft = null; + this.stage.setGesture(false); + }; + return { + move: (e) => { + if (dead) return; + const p = this.stage.clientToCanvas(e.clientX, e.clientY); + if (!began && Math.hypot(p.x - start.x, p.y - start.y) * this.stage.zoom < MIN_DRAG_PX) return; + began = true; + if (kind === 'marquee') { + end = e.shiftKey ? { x: start.x + Math.sign(p.x - start.x) * Math.max(Math.abs(p.x - start.x), Math.abs(p.y - start.y)), y: start.y + Math.sign(p.y - start.y) * Math.max(Math.abs(p.x - start.x), Math.abs(p.y - start.y)) } : p; + this.draft = rect(start, end); + } else { + const lx = pts[pts.length - 2]; + const ly = pts[pts.length - 1]; + if (Math.hypot(p.x - lx, p.y - ly) * this.stage.zoom >= 2) pts.push(p.x, p.y); + this.draft = pts.slice(); + } + this.stage.invalidate(); + }, + up: () => { + if (dead) return; + dead = true; + const shape = this.draft; + finish(); + if (!began || !shape || shape.length < 6) { + this.clear(); + return; + } + this.points = shape; + this.inverted = false; + this.changed(); + }, + cancel: () => { + dead = true; + finish(); + this.stage.invalidate(); + }, + }; + } + + fill(colour: string): boolean { + if (!this.points) return false; + const node = newRegionNode(this.points, { fill: colour, feather: this.feather, invert: this.inverted }); + return !!(node && this.store.addNode({ ...node, name: 'Fill' })); + } + + erase(): boolean { + if (!this.points) return false; + const node = newRegionNode(this.points, { fill: '#000000', feather: this.feather, invert: this.inverted, erase: true }); + return !!(node && this.store.addNode({ ...node, name: 'Clear' })); + } + + toMask(): boolean { + if (!this.points) return false; + return !!this.store.addMaskStroke({ points: this.points.slice(), size: 1, mode: 'add', fill: true, invert: this.inverted, feather: this.feather }); + } + + paintTop(g: CanvasRenderingContext2D): void { + const pts = this.draft ?? this.points; + if (!pts || pts.length < 4) return; + const pal = this.stage.palette(); + g.beginPath(); + for (let i = 0; i + 1 < pts.length; i += 2) { + const v = this.stage.canvasToView(pts[i], pts[i + 1]); + if (i === 0) g.moveTo(v.x, v.y); + else g.lineTo(v.x, v.y); + } + g.closePath(); + if (this.inverted && !this.draft) { + const s = this.store.size; + const a = this.stage.canvasToView(0, 0); + const b = this.stage.canvasToView(s.width, s.height); + g.rect(a.x, a.y, b.x - a.x, b.y - a.y); + } + g.lineWidth = 1; + g.setLineDash([]); + g.strokeStyle = pal.handle; + g.stroke(); + g.setLineDash([5, 4]); + g.strokeStyle = pal.accent; + g.stroke(); + g.setLineDash([]); + g.globalAlpha = 0.08; + g.fillStyle = pal.accent; + if (!this.draft) g.fill('evenodd'); + g.globalAlpha = 1; + } +} diff --git a/frontend/src/ui/canvas/tools/select.ts b/frontend/src/ui/canvas/tools/select.ts index eaa189e..50f1d64 100644 --- a/frontend/src/ui/canvas/tools/select.ts +++ b/frontend/src/ui/canvas/tools/select.ts @@ -53,12 +53,14 @@ export class SelectController { const additive = e.ctrlKey || e.metaKey || e.shiftKey; const hit = hitTest(this.store.nodes, p.x, p.y, HIT_TOLERANCE_PX / zoom); if (hit) { + const members = e.altKey ? [hit.id] : this.store.groupMembers(hit.id); if (additive) { const was = this.store.isSelected(hit.id); - this.store.toggleSelection(hit.id); + if (was) this.store.select(this.store.selected.filter((id) => !members.includes(id))); + else this.store.addToSelection(members); if (was) return this.idle(); } else if (!this.store.isSelected(hit.id)) { - this.store.select([hit.id]); + this.store.select(members); } return this.move(p, additive ? null : hit.id); } @@ -117,7 +119,7 @@ export class SelectController { this.clear(); return; } - if (collapseTo && this.store.selected.length > 1) this.store.select([collapseTo]); + if (collapseTo && this.store.selected.length > 1) this.store.select(this.store.groupMembers(collapseTo)); }, cancel: () => { dead = true; @@ -140,7 +142,7 @@ export class SelectController { if (handle === 'rot') last = rotateGesture(nodes, frame, start, p, ev.shiftKey); else { const lock = free ? false : single ? !ev.shiftKey : true; - last = scaleGesture(nodes, frame, handle, p, lock); + last = scaleGesture(nodes, frame, handle, p, lock, ev.altKey); } this.live(last); }, diff --git a/frontend/src/ui/canvas/tools/state.ts b/frontend/src/ui/canvas/tools/state.ts index a9b5263..5c5ef11 100644 --- a/frontend/src/ui/canvas/tools/state.ts +++ b/frontend/src/ui/canvas/tools/state.ts @@ -1,8 +1,9 @@ import { Emitter } from '../../../engine/emitter'; import { cycleShape, isSizedTool, sizeRange, stepSize, type SizedTool } from '../../../engine/canvas/geometry'; -import { BRUSH_SIZE, ERASER_SIZE, MASK_SIZE, SHAPE_COLOUR, type CanvasTool, type ShapeKind } from '../../../engine/canvas/types'; +import { BRUSH_SIZE, ERASER_SIZE, MASK_SIZE, SHAPE_COLOUR, TEXT_FONTS, TEXT_SIZE, TEXT_WEIGHTS, type CanvasTool, type ShapeKind, type TextNode } from '../../../engine/canvas/types'; export type MaskMode = 'add' | 'erase'; +export type TextStyle = Pick; type ToolEvents = { tool: [tool: CanvasTool, previous: CanvasTool]; @@ -19,6 +20,32 @@ export class ToolState { maskSize: number = MASK_SIZE.initial; maskMode: MaskMode = 'add'; shapeColour: string = SHAPE_COLOUR; + text: TextStyle = { font: TEXT_FONTS[0], size: TEXT_SIZE.initial, weight: 400, colour: '#000000', align: 'left', lineHeight: 1.2 }; + railOpen = true; + + setTextStyle(patch: Partial): void { + const next = { ...this.text, ...patch }; + const weights = TEXT_WEIGHTS[next.font] ?? [400]; + if (!weights.includes(next.weight)) next.weight = weights.reduce((a, b) => (Math.abs(b - next.weight) < Math.abs(a - next.weight) ? b : a)); + next.size = Math.min(TEXT_SIZE.max, Math.max(TEXT_SIZE.min, Math.round(next.size) || TEXT_SIZE.initial)); + next.lineHeight = Math.min(4, Math.max(0.5, next.lineHeight || 1.2)); + if (JSON.stringify(next) === JSON.stringify(this.text)) return; + this.text = next; + this.emitter.emit('change'); + } + + setColour(colour: string): void { + this.brushColour = colour; + this.shapeColour = colour; + this.text = { ...this.text, colour }; + this.emitter.emit('change'); + } + + setRail(open: boolean): void { + if (open === this.railOpen) return; + this.railOpen = open; + this.emitter.emit('change'); + } private readonly emitter = new Emitter(); private canMask: () => boolean = () => false; diff --git a/frontend/src/ui/canvas/tools/text.ts b/frontend/src/ui/canvas/tools/text.ts new file mode 100644 index 0000000..0a66a20 --- /dev/null +++ b/frontend/src/ui/canvas/tools/text.ts @@ -0,0 +1,167 @@ +import { hitTest, type Point } from '../../../engine/canvas/geometry'; +import { newTextNode } from '../../../engine/canvas/nodes'; +import type { CanvasStore, NodePatch } from '../../../engine/canvas/store'; +import type { TextNode } from '../../../engine/canvas/types'; +import type { CanvasStage } from '../stage/stage'; +import { fontsReady, measureText } from '../stage/render'; +import type { ToolState, TextStyle } from './state'; +import { t } from '../../i18n'; + +interface Session { + id: string | null; + at: Point; + node: TextNode; +} + +export class TextController { + private readonly box: HTMLTextAreaElement; + private session: Session | null = null; + private closedAt = 0; + + constructor( + host: HTMLElement, + private readonly store: CanvasStore, + private readonly stage: CanvasStage, + private readonly tools: ToolState, + ) { + const box = document.createElement('textarea'); + box.className = 'fc-cv-textedit'; + box.hidden = true; + box.spellcheck = false; + box.setAttribute('aria-label', t('Text')); + box.setAttribute('wrap', 'off'); + host.appendChild(box); + this.box = box; + box.addEventListener('input', () => this.layout()); + box.addEventListener('keydown', (e) => { + if (e.key === 'Escape' || (e.key === 'Enter' && (e.metaKey || e.ctrlKey))) { + e.preventDefault(); + e.stopPropagation(); + this.commit(); + } + e.stopPropagation(); + }); + box.addEventListener('blur', () => this.commit()); + stage.on('view', () => this.layout()); + tools.on('change', () => this.restyle()); + store.on('reset', () => this.cancel()); + store.on('base', () => this.cancel()); + } + + get editing(): boolean { + return this.session !== null; + } + + textAt(p: Point): Readonly | null { + const hit = hitTest(this.store.nodes, p.x, p.y, 4 / this.stage.zoom); + return hit && hit.kind === 'text' && !hit.locked ? hit : null; + } + + down(p: Point): void { + if (performance.now() - this.closedAt < 250) return; + if (this.session) { + this.commit(); + return; + } + const hit = this.textAt(p); + if (hit) this.edit(hit.id); + else this.start(p); + } + + start(p: Point): void { + const node = newTextNode(p, this.tools.text); + node.y -= (node.size * node.lineHeight) / 2; + this.open({ id: null, at: p, node }); + } + + edit(id: string): void { + const n = this.store.node(id); + if (!n || n.kind !== 'text' || n.locked) return; + this.tools.setTextStyle({ font: n.font, size: n.size, weight: n.weight, colour: n.colour, align: n.align, lineHeight: n.lineHeight }); + this.open({ id, at: { x: n.x, y: n.y }, node: { ...n } }); + } + + private open(s: Session): void { + this.session = s; + this.stage.setSkip(s.id); + this.box.value = s.node.text; + this.box.hidden = false; + this.restyle(); + void fontsReady([s.node]).then(() => this.layout()); + requestAnimationFrame(() => { + this.box.focus({ preventScroll: true }); + this.box.select(); + }); + } + + private restyle(): void { + const s = this.session; + if (!s) return; + const st: TextStyle = this.tools.text; + s.node = { ...s.node, ...st }; + const b = this.box.style; + b.fontFamily = `"${st.font}"`; + b.fontWeight = String(st.weight); + b.fontSize = `${st.size}px`; + b.lineHeight = `${st.size * st.lineHeight}px`; + b.color = st.colour; + b.textAlign = st.align; + this.layout(); + } + + private layout(): void { + const s = this.session; + if (!s) return; + s.node.text = this.box.value; + const m = measureText({ ...s.node, text: s.node.text || ' ' }); + const n = s.node; + const v = this.stage.canvasToView(n.x, n.y); + const b = this.box.style; + b.width = `${m.width + n.size * 0.6}px`; + b.height = `${m.height}px`; + b.transform = `translate(${v.x}px, ${v.y}px) rotate(${n.rotation}deg) scale(${n.scaleX * this.stage.zoom}, ${n.scaleY * this.stage.zoom})`; + } + + commit(): void { + const s = this.session; + if (!s) return; + this.session = null; + this.closedAt = performance.now(); + this.box.hidden = true; + this.stage.setSkip(null); + const text =this.box.value.replace(/\s+$/u, ''); + const m = measureText({ ...s.node, text: text || ' ' }); + if (s.id) { + if (!text) this.store.delete([s.id]); + else { + const st = this.tools.text; + const patch: NodePatch = { text, width: m.width, height: m.height, font: st.font, size: st.size, weight: st.weight, colour: st.colour, align: st.align, lineHeight: st.lineHeight }; + this.store.updateNodes([{ id: s.id, patch }], 'Edit text'); + this.store.select([s.id]); + } + } else if (text) { + this.store.addNode({ ...s.node, text, width: m.width, height: m.height }, true); + } + this.stage.view.focus({ preventScroll: true }); + } + + cancel(): void { + if (!this.session) return; + this.session = null; + this.box.hidden = true; + this.stage.setSkip(null); + } + + applyToSelection(patch: Partial): void { + const ids = this.store.selectedNodes().filter((n) => n.kind === 'text' && !n.locked); + if (!ids.length || this.session) return; + this.store.updateNodes( + ids.map((n) => { + const next = { ...(n as TextNode), ...patch }; + const m = measureText(next); + return { id: n.id, patch: { ...patch, width: m.width, height: m.height } }; + }), + 'Text style', + ); + } +} diff --git a/frontend/src/ui/canvas/tools/toolbar.ts b/frontend/src/ui/canvas/tools/toolbar.ts index 81193ca..f1196c8 100644 --- a/frontend/src/ui/canvas/tools/toolbar.ts +++ b/frontend/src/ui/canvas/tools/toolbar.ts @@ -1,15 +1,69 @@ import './icons'; import { shortcuts } from '../../../engine/shortcuts'; -import { BRUSH_SIZE, ERASER_SIZE, MASK_SIZE, type ShapeKind } from '../../../engine/canvas/types'; +import { BRUSH_SIZE, ERASER_SIZE, MASK_SIZE, TEXT_FONTS, TEXT_SIZE, TEXT_WEIGHTS, type ShapeKind, type TextAlign } from '../../../engine/canvas/types'; +import { CROP_ASPECTS } from './crop'; import { el, q, setAttr, setClass, setHidden, setHtml, setText, setTitle } from '../../dom'; import { icon } from '../../icons'; import { t } from '../../i18n'; import type { CanvasContext } from '../context'; -type PopName = 'shape' | 'brush' | 'eraser' | 'bg'; +type PopName = 'shape' | 'brush' | 'eraser' | 'bg' | 'text'; -const SHAPE_ICON: Record = { rect: 'cvRect', circle: 'cvCircle', triangle: 'cvTriangle' }; -const SHAPE_LABEL: Record = { rect: 'Rectangle', circle: 'Circle', triangle: 'Triangle' }; +const SHAPE_ICON: Record = { rect: 'cvRect', circle: 'cvCircle', triangle: 'cvTriangle', polygon: 'cvLasso' }; +const SHAPE_LABEL: Record = { rect: 'Rectangle', circle: 'Circle', triangle: 'Triangle', polygon: 'Fill' }; +const RAIL_KEY = 'formcraft.canvas.rail'; +const TOOL_NAMES = ['select', 'shape', 'text', 'brush', 'mask', 'eraser', 'eyedropper', 'marquee', 'lasso', 'crop'] as const; +const TOOL_LABEL: Record = { + select: 'Select', text: 'Text', brush: 'Brush', mask: 'Mask', eraser: 'Eraser', eyedropper: 'Eyedropper', + marquee: 'Rectangle selection', lasso: 'Lasso selection', crop: 'Crop and canvas size', +}; + +function textPop(): string { + const fonts = TEXT_FONTS.map((f) => ``).join(''); + const aligns = (['left', 'center', 'right'] as const) + .map((a) => ``) + .join(''); + return ( + '' + ); +} + +function cropBar(): string { + const opts = CROP_ASPECTS.map((a) => ``).join(''); + return ( + '' + ); +} + +function regionBar(): string { + return ( + '' + ); +} const hex2 = (n: number): string => Math.round(Math.min(255, Math.max(0, n))).toString(16).padStart(2, '0'); @@ -42,15 +96,22 @@ function skeleton(): string { .join(''); return ( '' ); @@ -92,8 +154,15 @@ export function mountToolbar(ctx: CanvasContext): () => void { const { store, tools } = ctx; const root = el(skeleton()); const bar = el(maskBar()); + const crop = el(cropBar()); + const region = el(regionBar()); ctx.slots.left.appendChild(root); - ctx.slots.top.appendChild(bar); + ctx.slots.top.append(bar, crop, region); + try { + tools.setRail(localStorage.getItem(RAIL_KEY) !== 'closed'); + } catch { + tools.setRail(true); + } const btn = (act: string): HTMLButtonElement => q(root, `[data-act="${act}"]`); const input = (name: string, scope: ParentNode = root): HTMLInputElement => q(scope, `[data-input="${name}"]`); @@ -102,14 +171,18 @@ export function mountToolbar(ctx: CanvasContext): () => void { brush: q(root, '[data-pop="brush"]'), eraser: q(root, '[data-pop="eraser"]'), bg: q(root, '[data-pop="bg"]'), + text: q(root, '[data-pop="text"]'), } as const; const shapeColourBox = q(root, '.fc-cvt-shapecolour'); let openPop: PopName | null = null; let leaveTimer = 0; let recolouring = false; - const TOOL_OF: Record = { select: 'canvas.toolSelect', shape: 'canvas.toolShape', brush: 'canvas.toolBrush', mask: 'canvas.toolMask', eraser: 'canvas.toolEraser' }; - const POP_OF: Record = { shape: 'shape', brush: 'brush', eraser: 'eraser', bg: 'bg' }; + const TOOL_OF: Record = { + select: 'canvas.toolSelect', shape: 'canvas.toolShape', brush: 'canvas.toolBrush', mask: 'canvas.toolMask', eraser: 'canvas.toolEraser', + text: 'canvas.toolText', eyedropper: 'canvas.toolEyedropper', marquee: 'canvas.toolMarquee', lasso: 'canvas.toolLasso', crop: 'canvas.toolCrop', + }; + const POP_OF: Record = { shape: 'shape', brush: 'brush', eraser: 'eraser', bg: 'bg', text: 'text' }; const closePop = (): void => { if (!openPop) return; @@ -131,14 +204,14 @@ export function mountToolbar(ctx: CanvasContext): () => void { const sync = (): void => { const tool = tools.tool; - for (const name of ['select', 'shape', 'brush', 'mask', 'eraser'] as const) { + for (const name of TOOL_NAMES) { const b = btn(name); setClass(b, 'is-active', tool === name); setAttr(b, 'aria-pressed', String(tool === name)); const id = TOOL_OF[name]; const keys = shortcuts.label(id); setText(q(b, '.fc-cvt-key'), keys); - const label = name === 'select' ? 'Select' : name === 'shape' ? SHAPE_LABEL[tools.shape] : name === 'brush' ? 'Brush' : name === 'mask' ? 'Mask' : 'Eraser'; + const label = name === 'shape' ? SHAPE_LABEL[tools.shape] : TOOL_LABEL[name]; const off = name === 'mask' && !tools.maskAllowed; setClass(b, 'is-off', off); setAttr(b, 'aria-disabled', off ? 'true' : null); @@ -190,9 +263,53 @@ export function mountToolbar(ctx: CanvasContext): () => void { if (openPop === 'brush' && tool !== 'brush') closePop(); if (openPop === 'eraser' && tool !== 'eraser') closePop(); if (openPop === 'shape' && tool !== 'shape') closePop(); + const editingText = ctx.edit?.text.editing ?? false; + const textSel = store.selectedNodes().some((n) => n.kind === 'text'); + if (openPop === 'text' && tool !== 'text' && !textSel && !editingText) closePop(); + const ts = tools.text; + syncInput(input('text-font') as unknown as HTMLInputElement, ts.font); + const wsel = q(root, '[data-input="text-weight"]'); + const weights = TEXT_WEIGHTS[ts.font] ?? [400]; + const wsig = weights.join(','); + if (wsel.dataset.sig !== wsig) { + wsel.dataset.sig = wsig; + wsel.innerHTML = weights.map((w) => ``).join(''); + } + syncInput(wsel as unknown as HTMLInputElement, String(ts.weight)); + syncInput(input('text-size'), String(ts.size)); + syncInput(input('text-line'), String(ts.lineHeight)); + syncInput(input('text-colour'), split(ts.colour).hex); + for (const seg of root.querySelectorAll('[data-align]')) { + const on = seg.dataset.align === ts.align; + setClass(seg, 'is-active', on); + setAttr(seg, 'aria-checked', String(on)); + } + const rail = btn('rail'); + setAttr(rail, 'aria-expanded', String(tools.railOpen)); + setTitle(rail, `${t('Show or hide the tool rail')}${shortcuts.label('canvas.toggleRail') ? ` (${shortcuts.label('canvas.toggleRail')})` : ''}`); + if (ctx.root.dataset.rail !== (tools.railOpen ? 'open' : 'closed')) ctx.root.dataset.rail = tools.railOpen ? 'open' : 'closed'; + const cropOn = tool === 'crop'; + setHidden(crop, !cropOn); + const cr = ctx.edit?.crop; + if (cropOn && cr?.rect) { + syncInput(q(crop, '[data-input="crop-w"]'), String(cr.rect.width)); + syncInput(q(crop, '[data-input="crop-h"]'), String(cr.rect.height)); + syncInput(q(crop, '[data-input="crop-aspect"]') as unknown as HTMLInputElement, cr.aspect); + const s = store.size; + const r = cr.rect; + const grows = r.x < 0 || r.y < 0 || r.x + r.width > s.width || r.y + r.height > s.height; + setText(q(crop, '[data-val="crop-note"]'), grows ? t('New area is left clear for outpainting') : ''); + } + const rg = ctx.edit?.region; + setHidden(region, !rg?.active || tool === 'mask' || cropOn); + if (rg) { + syncInput(q(region, '[data-input="feather"]'), String(rg.feather)); + setText(q(region, '[data-val="feather"]'), `${rg.feather}px`); + setClass(q(region, '[data-region="invert"]'), 'is-active', rg.inverted); + } }; - const syncInput = (node: HTMLInputElement, value: string): void => { + const syncInput = (node: HTMLInputElement | HTMLSelectElement, value: string): void => { if (node.value !== value && document.activeElement !== node) node.value = value; }; @@ -204,6 +321,11 @@ export function mountToolbar(ctx: CanvasContext): () => void { tools.setShape(chip.dataset.shape as ShapeKind); return; } + const align = target.closest('[data-align]'); + if (align) { + setTextStyle({ align: align.dataset.align as TextAlign }); + return; + } const b = target.closest('[data-act]'); if (!b || b.disabled) return; const act = b.dataset.act ?? ''; @@ -211,6 +333,10 @@ export function mountToolbar(ctx: CanvasContext): () => void { ctx.toast(t('The mask tool needs a model that can inpaint. Pick one in the prompt box.'), 'info', { key: 'canvas-mask-model' }); return; } + if (act === 'rail') { + void ctx.commands.run('canvas.toggleRail'); + return; + } if (act === 'upload') ctx.uploadImages?.(); else if (act === 'reset') ctx.resetCanvas?.(); else if (act === 'undo') store.undo(); @@ -226,7 +352,7 @@ export function mountToolbar(ctx: CanvasContext): () => void { return; } void ctx.commands.run(TOOL_OF[act]); - if (act === 'shape') showPop('shape'); + if (act === 'shape' || act === 'text') showPop(act); else if (was && POP_OF[act]) { if (openPop === POP_OF[act]) closePop(); else showPop(POP_OF[act]); @@ -239,7 +365,7 @@ export function mountToolbar(ctx: CanvasContext): () => void { window.clearTimeout(leaveTimer); if (!b) return; const act = b.dataset.act ?? ''; - if ((act === 'brush' || act === 'eraser' || act === 'shape') && tools.tool === act) showPop(act); + if ((act === 'brush' || act === 'eraser' || act === 'shape' || act === 'text') && tools.tool === act) showPop(act); }); root.addEventListener('pointerleave', () => { window.clearTimeout(leaveTimer); @@ -248,6 +374,58 @@ export function mountToolbar(ctx: CanvasContext): () => void { }, 320); }); + const setTextStyle = (patch: Partial): void => { + tools.setTextStyle(patch); + const applied = { ...patch, weight: tools.text.weight }; + ctx.edit?.text.applyToSelection(patch.font ? applied : patch); + }; + + root.addEventListener('change', (e) => { + const node = e.target instanceof HTMLSelectElement || e.target instanceof HTMLInputElement ? e.target : null; + const name = node?.dataset.input; + if (!node || !name?.startsWith('text-')) return; + if (name === 'text-font') setTextStyle({ font: node.value }); + else if (name === 'text-weight') setTextStyle({ weight: Number(node.value) }); + else if (name === 'text-size') setTextStyle({ size: Number(node.value) }); + else if (name === 'text-line') setTextStyle({ lineHeight: Number(node.value) }); + else if (name === 'text-colour') setTextStyle({ colour: node.value }); + }); + + crop.addEventListener('click', (e) => { + const b = e.target instanceof Element ? e.target.closest('[data-crop]') : null; + if (!b) return; + const act = b.dataset.crop; + if (act === 'apply') void ctx.commands.run('canvas.cropApply'); + else if (act === 'cancel') void ctx.commands.run('canvas.cropCancel'); + else ctx.edit?.crop.reset(); + }); + crop.addEventListener('change', (e) => { + const node = e.target instanceof HTMLSelectElement || e.target instanceof HTMLInputElement ? e.target : null; + const cr = ctx.edit?.crop; + if (!node || !cr) return; + if (node.dataset.input === 'crop-aspect') cr.setAspect(node.value); + else if (node.dataset.input === 'crop-w') cr.setSize(Number(node.value), cr.rect?.height ?? 0); + else if (node.dataset.input === 'crop-h') cr.setSize(cr.rect?.width ?? 0, Number(node.value)); + }); + crop.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + (e.target as HTMLElement).blur(); + void ctx.commands.run('canvas.cropApply'); + } + }); + + region.addEventListener('click', (e) => { + const b = e.target instanceof Element ? e.target.closest('[data-region]') : null; + if (!b) return; + const map: Record = { fill: 'canvas.regionFill', clear: 'canvas.regionClear', invert: 'canvas.regionInvert', mask: 'canvas.regionMask', none: 'canvas.regionNone' }; + const id = map[b.dataset.region ?? '']; + if (id) void ctx.commands.run(id); + }); + region.addEventListener('input', (e) => { + const node = e.target instanceof HTMLInputElement ? e.target : null; + if (node?.dataset.input === 'feather') ctx.edit?.region.setFeather(Number(node.value)); + }); + root.addEventListener('input', (e) => { const node = e.target instanceof HTMLInputElement ? e.target : null; const name = node?.dataset.input; @@ -317,7 +495,21 @@ export function mountToolbar(ctx: CanvasContext): () => void { store.on('scene', sync), store.on('reset', sync), shortcuts.on('change', sync), + tools.on('change', () => { + try { + localStorage.setItem(RAIL_KEY, tools.railOpen ? 'open' : 'closed'); + } catch { + return; + } + }), ]; + queueMicrotask(() => { + const a = ctx.edit?.crop.on(sync); + const b = ctx.edit?.region.on(sync); + if (a) subs.push(a); + if (b) subs.push(b); + sync(); + }); sync(); return () => { for (const s of subs) s(); @@ -325,5 +517,7 @@ export function mountToolbar(ctx: CanvasContext): () => void { document.removeEventListener('keydown', esc); root.remove(); bar.remove(); + crop.remove(); + region.remove(); }; } diff --git a/frontend/src/ui/canvas/tools/transform.ts b/frontend/src/ui/canvas/tools/transform.ts index e43854b..4ee2d84 100644 --- a/frontend/src/ui/canvas/tools/transform.ts +++ b/frontend/src/ui/canvas/tools/transform.ts @@ -135,7 +135,7 @@ export function cursorFor(h: HandleId, angle: number): string { return 'nesw-resize'; } -const RECTLIKE = (n: CanvasNode): boolean => n.kind !== 'line'; +const RECTLIKE = (n: CanvasNode): boolean => n.kind !== 'line' && n.kind !== 'text'; function place(n: CanvasNode, pos: Point, rotation: number, fx: number, fy: number): Override { const sx = n.scaleX * fx; @@ -173,13 +173,13 @@ export function rotateGesture(nodes: ReadonlyArray>, frame: return { overrides, frame: { ...frame, angle: frame.angle + d } }; } -export function scaleGesture(nodes: ReadonlyArray>, frame: Frame, handle: ScaleHandle, p: Point, lock: boolean): Gesture { +export function scaleGesture(nodes: ReadonlyArray>, frame: Frame, handle: ScaleHandle, p: Point, lock: boolean, fromCentre = false): Gesture { const [sx, sy] = DIRS[handle]; const { u: pu, v: pv } = toFrame(frame, p.x, p.y); const hw = frame.w / 2; const hh = frame.h / 2; - let nw = sx !== 0 ? sx * pu + hw : frame.w; - let nh = sy !== 0 ? sy * pv + hh : frame.h; + let nw = sx !== 0 ? (fromCentre ? 2 * sx * pu : sx * pu + hw) : frame.w; + let nh = sy !== 0 ? (fromCentre ? 2 * sy * pv : sy * pv + hh) : frame.h; if (lock && frame.w > 0 && frame.h > 0) { let k = sx !== 0 && sy !== 0 ? Math.max(nw / frame.w, nh / frame.h) : sx !== 0 ? nw / frame.w : nh / frame.h; k = Math.max(k, MIN_FRAME / Math.min(frame.w, frame.h)); @@ -191,9 +191,9 @@ export function scaleGesture(nodes: ReadonlyArray>, frame: } const fx = frame.w > 0 ? nw / frame.w : 1; const fy = frame.h > 0 ? nh / frame.h : 1; - const ax = sx !== 0 ? -sx * hw : 0; - const ay = sy !== 0 ? -sy * hh : 0; - const centre = fromFrame(frame, sx !== 0 ? ax + (sx * nw) / 2 : 0, sy !== 0 ? ay + (sy * nh) / 2 : 0); + const ax = sx !== 0 && !fromCentre ? -sx * hw : 0; + const ay = sy !== 0 && !fromCentre ? -sy * hh : 0; + const centre = fromFrame(frame, sx !== 0 && !fromCentre ? ax + (sx * nw) / 2 : 0, sy !== 0 && !fromCentre ? ay + (sy * nh) / 2 : 0); const overrides = new Map(); for (const n of nodes) { const q = toFrame(frame, n.x, n.y); diff --git a/frontend/src/ui/cheatsheet.ts b/frontend/src/ui/cheatsheet.ts index c6eae8d..0ddb2ba 100644 --- a/frontend/src/ui/cheatsheet.ts +++ b/frontend/src/ui/cheatsheet.ts @@ -1,5 +1,7 @@ import '../styles/keybinds.css'; +import '../styles/keybinds-more.css'; import { commands } from '../engine/commands'; +import { sceneAction } from '../engine/scene/actions'; import { PRESETS, shortcuts } from '../engine/shortcuts'; import { el, patchList, q, setAttr, setClass, setHidden, setHtml, setText } from './dom'; import { ICONS, icon } from './icons'; @@ -30,16 +32,39 @@ interface SheetGroup { let mounted = false; -function collect(): SheetGroup[] { +function recording(): boolean { + const cmd = commands.get('scene.mode'); + return cmd !== undefined && commands.checked(cmd); +} + +function typingNow(): boolean { + const a = document.activeElement; + if (!(a instanceof HTMLElement)) return false; + if (a.isContentEditable) return true; + if (a instanceof HTMLTextAreaElement || a instanceof HTMLSelectElement) return true; + return a instanceof HTMLInputElement && !/^(button|checkbox|radio|range|color|file|submit|reset|image)$/.test(a.type); +} + +function collect(query: string): SheetGroup[] { const surface = activeSurface(); const order = surface === 'global' ? ['global' as const] : [surface, 'global' as const]; const groups = new Map(); + const words = query.toLowerCase().split(/\s+/).filter(Boolean); + const record = surface === 'scene' && recording(); for (const s of order) { for (const a of liveActions(s)) { if (!a.bindings.length) continue; const cmd = commands.get(a.action); const label = liveLabel(a.action); if (!cmd || label === null) continue; + if (s === 'scene' && !words.length) { + const gate = sceneAction(a.action)?.gate ?? []; + if ((record && gate.includes('build')) || (!record && gate.includes('record'))) continue; + } + if (words.length) { + const hay = [label, a.group, ...a.bindings.map((b) => shortcuts.format(b))].join(' ').toLowerCase(); + if (!words.every((w) => hay.includes(w))) continue; + } const name = a.group || 'Other'; let g = groups.get(name); if (!g) { @@ -63,11 +88,14 @@ export function mountCheatsheet(): void { const root = el( ``, ); host.appendChild(root); @@ -76,10 +104,13 @@ export function mountCheatsheet(): void { const pin = q(root, '.fc-sheet-pin'); const groupsEl = q(root, '.fc-sheet-groups'); const empty = q(root, '.fc-sheet-empty'); + const find = q(root, '.fc-sheet-find input'); let timer: number | null = null; let shown = false; let pinned = false; + let dragging = false; + let returnTo: HTMLElement | null = null; const renderRow = (node: HTMLElement, row: SheetRow): void => { setText(q(node, '.fc-sheet-name'), row.label); @@ -100,9 +131,10 @@ export function mountCheatsheet(): void { }; const render = (): void => { - const groups = collect(); + const groups = collect(find.value.trim()); const preset = PRESETS.find((p) => p.id === shortcuts.preset)?.label ?? ''; - setText(meta, `${surfaceTitle(activeSurface())} · ${t(preset)}`); + const mode = activeSurface() === 'scene' ? ` · ${t(recording() ? 'Record mode' : 'Build mode')}` : ''; + setText(meta, `${surfaceTitle(activeSurface())}${mode} · ${t(preset)}`); setHidden(empty, groups.length > 0); patchList(groupsEl, groups, { key: (g) => g.key, @@ -118,6 +150,7 @@ export function mountCheatsheet(): void { const show = (): void => { if (shown) return; shown = true; + find.value = ''; render(); setHidden(root, false); requestAnimationFrame(() => { @@ -152,18 +185,42 @@ export function mountCheatsheet(): void { setClass(pin, 'is-on', on); setAttr(pin, 'aria-pressed', String(on)); setAttr(root, 'aria-hidden', on ? 'false' : 'true'); - if (on) show(); - else hide(); + if (on) { + const at = document.activeElement; + returnTo = at instanceof HTMLElement && at !== document.body ? at : null; + show(); + find.focus({ preventScroll: true }); + } else { + hide(); + if (returnTo?.isConnected) returnTo.focus({ preventScroll: true }); + returnTo = null; + } }; + const blocked = (): boolean => isHoldSuspended() || dragging || typingNow(); + const arm = (): void => { - if (timer !== null || shown || isHoldSuspended()) return; + if (timer !== null || shown || blocked()) return; timer = window.setTimeout(() => { timer = null; - if (!isHoldSuspended()) show(); + if (!blocked()) show(); }, holdMs()); }; + find.addEventListener('input', render); + q(root, '.fc-sheet-custom').addEventListener('click', () => { + setPinned(false); + void commands.run('shortcuts'); + }); + commands.register({ + id: 'cheatsheet', + label: () => t('Shortcut Cheatsheet'), + group: 'Help', + keys: ['Shift+Slash'], + description: 'Show the shortcuts that work in the open studio and mode. Press Esc to close it.', + run: () => setPinned(!pinned), + }); + const isModKey = (e: KeyboardEvent): boolean => (shortcuts.isMac ? MOD_CODES_MAC : MOD_CODES_PLAIN).has(e.code); const modHeld = (e: KeyboardEvent): boolean => (shortcuts.isMac ? e.metaKey : e.ctrlKey); const alone = (e: KeyboardEvent): boolean => !e.altKey && !e.shiftKey && !(shortcuts.isMac ? e.ctrlKey : e.metaKey); @@ -198,7 +255,27 @@ export function mountCheatsheet(): void { }, true, ); - window.addEventListener('blur', cancel); + window.addEventListener( + 'pointerdown', + (e) => { + if (e.buttons !== 0 && !(e.target instanceof Node && card.contains(e.target))) dragging = true; + }, + { capture: true, passive: true }, + ); + window.addEventListener( + 'pointermove', + (e) => { + if (dragging && e.buttons === 0) dragging = false; + }, + { capture: true, passive: true }, + ); + for (const type of ['pointerup', 'pointercancel', 'dragend'] as const) { + window.addEventListener(type, () => (dragging = false), { capture: true, passive: true }); + } + window.addEventListener('blur', () => { + dragging = false; + cancel(); + }); document.addEventListener('visibilitychange', () => { if (document.hidden) cancel(); }); diff --git a/frontend/src/ui/create/cost-confirm.ts b/frontend/src/ui/create/cost-confirm.ts new file mode 100644 index 0000000..df2d09b --- /dev/null +++ b/frontend/src/ui/create/cost-confirm.ts @@ -0,0 +1,33 @@ +import { confirmAction } from '../dialogs'; +import { t } from '../i18n'; +import { loadPrefs, updatePrefs } from '../prefs'; + +const STEPS = [0.25, 0.5, 1, 2, 5, 10, 20, 50, 100] as const; +const DEFAULT_LINE = 1; + +export const formatUsd = (usd: number): string => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(usd); + +/** The next round amount above this run, offered as the new "ask from" line. */ +export function nextLine(usd: number): number { + return STEPS.find((s) => s > usd) ?? STEPS[STEPS.length - 1]; +} + +/** True when this estimate is at or over the line set in Preferences, Generation. */ +export function spendAsks(usd: number | null): boolean { + const p = loadPrefs(); + return p.confirmCostly && usd !== null && usd >= (p.costlyUsd ?? DEFAULT_LINE); +} + +/** True when the run may go ahead. Asks, with the existing confirm, only when spendAsks(usd). */ +export async function confirmSpend(usd: number | null, basis: string): Promise { + if (usd === null || !spendAsks(usd)) return true; + const line = nextLine(usd); + return confirmAction( + 'Confirm a costly run', + `${t('This run is estimated at about {amount}.').replace('{amount}', formatUsd(usd))} ${basis ? `${basis}. ` : ''}${t('The final charge is set by the provider. You can change this check in Preferences, Generation.')}`, + 'Generate', + false, + 'Cancel', + { label: t("Don't ask again for runs under {amount}").replace('{amount}', formatUsd(line)), onChecked: () => void updatePrefs({ costlyUsd: line }) }, + ); +} diff --git a/frontend/src/ui/create/defs.ts b/frontend/src/ui/create/defs.ts index e2ec846..4485de6 100644 --- a/frontend/src/ui/create/defs.ts +++ b/frontend/src/ui/create/defs.ts @@ -58,7 +58,7 @@ export const DEFS: Record = { jobKind: 'gen.mesh', mediaKind: 'model', icon: 'cube', - title: 'Create 3D objects', + title: 'Create 3D models', subtitle: 'Describe an object or start from a picture, choose a model and press Generate. Every result is saved to your library.', placeholder: 'Describe the object you want, or add a picture of it', deck: 'images', @@ -81,5 +81,4 @@ export const DEFS: Record = { export const PROVIDER_NAME: Record = { fal: 'fal', worldlabs: 'World Labs' }; -export const COSTLY_USD = 1; export const PLAN_DELAY_MS = 250; diff --git a/frontend/src/ui/create/page.ts b/frontend/src/ui/create/page.ts index e36c6da..4f2241b 100644 --- a/frontend/src/ui/create/page.ts +++ b/frontend/src/ui/create/page.ts @@ -7,16 +7,16 @@ import { models } from '../../engine/models'; import { promptStore, type CreatePageId, type InputMode, type MediaValue, type StateKey } from '../../engine/prompt-store'; import { studios } from '../../engine/studios'; import { ApiError, generate, getJob, getMedia, mediaFileUrl, planRequest, type GenerateRequest, type Job, type Media, type Plan, type PlanError, type WindowModel } from '../../io/api'; -import { characterAvatarUrl } from '../../io/api-characters'; +import { characterAvatarUrl, listPrompts } from '../../io/api-characters'; import { confirmAndDelete } from '../delete-media'; -import { confirmAction } from '../dialogs'; import { el, escapeHtml, q, setAttr, setClass, setHidden, setStyleVar, setText, setTitle } from '../dom'; import { icon } from '../icons'; import { onLanguage, t } from '../i18n'; import { openCharacters } from '../library/characters'; import { openLightbox } from '../lightbox/lightbox'; -import { loadPrefs, onPrefs } from '../prefs'; +import { inDesktop, invokeHost, loadPrefs, onPrefs } from '../prefs'; import { saveMedia } from '../save-media'; +import { openKeySheet } from '../prompt/key-sheet'; import { toast } from '../toasts'; import { Feed, type FeedAction, type FeedItem } from '../feed/feed'; import { mentioned } from '../prompt/editor'; @@ -26,7 +26,8 @@ import { OptionsBar } from '../prompt/options-bar'; import { PromptBox, type HintKind, type Mention } from '../prompt/prompt-box'; import { ReferenceDeck, type DeckMode } from '../prompt/reference-deck'; import { CostView } from './cost-view'; -import { COSTLY_USD, DEFS, PLAN_DELAY_MS, PROVIDER_NAME, type PageDef } from './defs'; +import { confirmSpend, spendAsks } from './cost-confirm'; +import { DEFS, PLAN_DELAY_MS, PROVIDER_NAME, type PageDef } from './defs'; import { DockTools } from './dock-tools'; import { coverJob, sweepCovers } from './covers'; import { ModeSwitch } from './mode-switch'; @@ -39,12 +40,30 @@ const BOX_GAP = 16; const FEED_AIR = 24; const REPLAY_MS = 400; const SETTLE_MS = 1500; +const SPEND_KEY = 'formcraft.create.spendNoted'; +const KEY_URL: Record = { fal: 'https://fal.ai/dashboard/keys', worldlabs: 'https://platform.worldlabs.ai/api-keys' }; const MENTION_KEYS: Record = { Image: ['referenceImages', 'sourceImage'], Video: ['referenceVideos'], Audio: ['referenceAudios', 'sourceAudio'], }; +function spendNoted(): boolean { + try { + return localStorage.getItem(SPEND_KEY) === '1'; + } catch { + return true; + } +} + +function markSpendNoted(): void { + try { + localStorage.setItem(SPEND_KEY, '1'); + } catch { + return; + } +} + function uuid(): string { if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID(); const b = new Uint8Array(16); @@ -70,7 +89,13 @@ function shell(def: PageDef): string { `
` + `
${icon(def.icon, 22)}` + `

${escapeHtml(t(def.title))}

` + - `

${escapeHtml(t(def.subtitle))}

` + + `

${escapeHtml(t(def.subtitle))}

` + + `` + + `` + + `
` + `
` + `` + `
` + @@ -113,6 +138,8 @@ export class CreatePage { private pending: { sig: string; id: string } | null = null; private readonly origin = new Map(); private readonly asked = new Set(); + private switchNote = ''; + private recallAt = 0; constructor(page: CreatePageId) { this.page = page; @@ -133,6 +160,9 @@ export class CreatePage { accepts: (kinds) => this.deck.accepts(kinds), onCostClick: (anchor) => this.cost.toggle(anchor, this.model, this.plan), onPreviewMention: (m) => void this.previewMention(m), + onBlocked: (reason) => this.onBlocked(reason), + onRecall: () => void this.recall(), + onAddKey: () => this.askKey(), }); this.picker = new ModelPicker({ page, onChange: () => undefined }); this.bar = new OptionsBar({ onChange: (values) => this.onOptions(values) }); @@ -147,8 +177,16 @@ export class CreatePage { this.dock = q(this.root, '.fc-cr-box'); const row = el('
'); if (this.def.mediaKind !== 'audio') row.append(new SceneNote().el); - row.append(new PageSwitcher().el, new DockTools(page).el); + row.append(new DockTools(page).el); this.dock.append(this.box.el, row); + this.root.prepend(new PageSwitcher().el); + q(this.root, '.fc-cr-key-add').addEventListener('click', () => this.askKey()); + q(this.root, '.fc-cr-key-demo').addEventListener('click', () => hooks.showHome?.()); + q(this.root, '.fc-cr-key-get').addEventListener('click', (e) => { + if (!inDesktop()) return; + e.preventDefault(); + void invokeHost('open_url', { url: (e.currentTarget as HTMLAnchorElement).href }).catch(() => undefined); + }); this.wire(); this.applyStore(ALL_KEYS, false); @@ -295,12 +333,44 @@ export class CreatePage { } private configure(model: WindowModel | null): void { + const prev = this.model; + const before = { ...this.options }; this.model = model; if (!model) { this.shape = ''; this.paintState(); return; } + if (prev && prev.id !== model.id && !this.applying) { + this.switchNote = ''; + this.configureCore(model); + this.switchNote = this.describeSwitch(prev, model, before); + this.paintState(); + return; + } + this.configureCore(model); + } + + private describeSwitch(prev: WindowModel, next: WindowModel, before: Record): string { + const after = this.options; + const nextKeys = new Set(next.options.map((o) => o.key)); + const reset: string[] = []; + const dropped: string[] = []; + for (const [k, v] of Object.entries(before)) { + if (!prev.options.some((o) => o.key === k)) continue; + if (!nextKeys.has(k)) dropped.push(k); + else if (JSON.stringify(after[k]) !== JSON.stringify(v)) reset.push(k); + } + const names = (keys: string[]): string => keys.map((k) => t(optionLabel(k)).toLowerCase()).join(', '); + const parts: string[] = []; + if (reset.length) parts.push(t('{options} set to the defaults for this model').replace('{options}', names(reset))); + if (dropped.length) parts.push(t('{options} not offered here').replace('{options}', names(dropped))); + const head = t('Switched to {model}.').replace('{model}', next.label); + const tail = parts.join('; '); + return tail ? `${head} ${tail.charAt(0).toUpperCase()}${tail.slice(1)}.` : `${head} ${t('Your settings were kept.')}`; + } + + private configureCore(model: WindowModel): void { this.shape = shapeOf(model); if (this.seg) { const modes = models.inputModes(model); @@ -345,6 +415,7 @@ export class CreatePage { private onOptions(values: Record): void { if (values.count !== this.options.count) this.countTouched = true; this.options = values; + this.switchNote = ''; promptStore.patch(this.page, { options: values }, 'ui'); this.paintState(); this.schedulePlan(); @@ -573,6 +644,7 @@ export class CreatePage { } else if (!models.configured(model.provider)) { text = t('Add your {provider} key in Preferences, Connections to generate with this model.').replace('{provider}', PROVIDER_NAME[model.provider]); kind = 'warning'; + gate = t('Add your {provider} key to generate with {model}.').replace('{provider}', PROVIDER_NAME[model.provider]).replace('{model}', model.label); } else if (missing.length) { text = t('Choose {options} before generating.').replace('{options}', missing.map((k) => t(optionLabel(k))).join(', ')); kind = 'warning'; @@ -586,17 +658,61 @@ export class CreatePage { kind = 'error'; } else if (mention) { text = mention.text; + } else if (this.switchNote) { + text = this.switchNote; + } else if (!spendNoted()) { + text = t('Each run is charged by {provider} to your own key. The estimate beside Generate shows the expected cost.').replace('{provider}', PROVIDER_NAME[model.provider]); } this.box.setHint(text, kind); this.box.setCanSubmit(gate === null, gate ?? undefined); + this.box.setNeedsKey(models.ready && !models.configured(model.provider)); + this.paintKey(model); } - private needKey(model: WindowModel, message?: string): void { + private paintKey(model: WindowModel | null): void { + const panel = q(this.root, '.fc-cr-key'); + const show = !!model && models.ready && !models.configured(model.provider); + setHidden(panel, !show); + if (!show || !model) return; const name = PROVIDER_NAME[model.provider]; - toast(message ?? t('Add your {provider} key to generate with {model}.').replace('{provider}', name).replace('{model}', model.label), 'warning', { - key: 'create-key', - actions: [{ label: t('Open Preferences'), run: () => hooks.openPreferences?.('connections') }], - }); + setText(q(panel, '.fc-cr-key-t'), t('A key is a private code from {provider} that lets formcraft run models on your account; you pay {provider} for what you make. Add one to start, or open a demo project that needs no key.').replace(/\{provider\}/g, name)); + const link = q(panel, '.fc-cr-key-get'); + const url = KEY_URL[model.provider] ?? KEY_URL.fal; + if (link.getAttribute('href') !== url) link.setAttribute('href', url); + setText(link, t('Get a {provider} key').replace('{provider}', name)); + } + + private onBlocked(reason: string): void { + const model = this.model; + if (model && !models.configured(model.provider)) this.askKey(); + else toast(reason, 'info', { key: 'prompt-blocked' }); + } + + private async recall(): Promise { + const seq = ++this.recallAt; + try { + const res = await listPrompts({ page: this.page, limit: 1 }); + const last = res.items[0]?.prompt ?? ''; + if (seq !== this.recallAt || !last || this.box.text !== '') return; + this.box.setText(last); + promptStore.patch(this.page, { text: last }, 'ui'); + this.paintState(); + this.schedulePlan(); + } catch { + return; + } + } + + private needKey(model: WindowModel, message?: string): void { + if (message) toast(message, 'warning', { key: 'create-key' }); + openKeySheet(this.box.el, model.provider, { onSaved: () => void this.submit() }); + } + + /** Opens the key sheet on this page's prompt box; saving it runs the generation that was asked for. */ + private askKey(): void { + const model = this.model; + if (!model) return; + openKeySheet(this.box.el, model.provider, { onSaved: () => void this.submit() }); } private requestId(sig: string): string { @@ -612,7 +728,7 @@ export class CreatePage { return; } if (!models.configured(model.provider)) { - this.needKey(model); + this.askKey(); return; } const missing = this.bar.missing(); @@ -641,20 +757,18 @@ export class CreatePage { return; } const usd = plan.cost.usd; - if (loadPrefs().confirmCostly && usd !== null && usd >= COSTLY_USD) { + if (spendAsks(usd)) { this.box.setBusy(false); - const amount = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(usd); - const ok = await confirmAction( - 'Confirm a costly run', - `${t('This run is estimated at about {amount}.').replace('{amount}', amount)} ${plan.cost.basis}. ${t('The final charge is set by the provider. You can turn this check off in Preferences, Generation.')}`, - 'Generate', - ); - if (!ok) return; + if (!(await confirmSpend(usd, plan.cost.basis))) return; this.box.setBusy(true); } const res = await generate({ ...req, clientRequestId: this.requestId(sig) }); this.pending = null; + markSpendNoted(); + this.switchNote = ''; this.afterGenerate(res.jobs, res.warnings, plan); + this.paintState(); + if (this.active()) this.box.focus(); } catch (err) { this.failed(err, model); } finally { @@ -689,6 +803,11 @@ export class CreatePage { if (action === 'open' && item.media) this.open(item.media); else if (action === 'recreate') void this.recreate(item.job, item.media); else if (action === 'make-video' && item.media && item.media.kind === 'image') makeVideo(item.media.id); + else if (action === 'add-key') { + const asked = item.job?.payload.request as Partial | undefined; + const provider = (typeof asked?.model === 'string' ? models.get(asked.model)?.provider : undefined) ?? this.model?.provider ?? 'fal'; + openKeySheet(this.box.el, provider, { onSaved: () => undefined }); + } } private async recreate(job?: Job, media?: Media): Promise { diff --git a/frontend/src/ui/dialogs.ts b/frontend/src/ui/dialogs.ts index acb6d66..5e3dcb5 100644 --- a/frontend/src/ui/dialogs.ts +++ b/frontend/src/ui/dialogs.ts @@ -182,21 +182,30 @@ export class Dialog { class Confirm extends Dialog { private readonly note = el('

'); + private readonly check = el(''); + private readonly box = q(this.check, 'input'); private readonly ok: HTMLButtonElement; private readonly cancel: HTMLButtonElement; private resolve: ((v: boolean) => void) | null = null; constructor() { super('Confirm', 400); - this.body.appendChild(this.note); + this.body.append(this.note, this.check); this.cancel = this.button('Cancel', 'ghost', () => this.finish(false)); this.ok = this.button('OK', 'primary', () => this.finish(true)); this.onClose = () => this.finish(false); } - ask(title: string, text: string, okLabel: string, danger: boolean, cancelLabel: string): Promise { + get checked(): boolean { + return !this.check.hidden && this.box.checked; + } + + ask(title: string, text: string, okLabel: string, danger: boolean, cancelLabel: string, checkLabel = ''): Promise { this.setTitle(title); setText(this.note, text); + setText(q(this.check, 'span'), checkLabel); + this.box.checked = false; + this.check.hidden = !checkLabel; this.ok.dataset.en = okLabel; this.cancel.dataset.en = cancelLabel; setText(this.ok, t(okLabel)); @@ -260,11 +269,19 @@ let promptDlg: Prompt | null = null; const hasOverlayRoot = (): boolean => !!document.getElementById('overlay-root'); -export function confirmAction(title: string, text: string, okLabel = 'OK', danger = false, cancelLabel = 'Cancel'): Promise { +/** An optional tick box under the text; onChecked runs only when the person confirms with it ticked. */ +export interface ConfirmCheck { label: string; onChecked(): void } + +export function confirmAction(title: string, text: string, okLabel = 'OK', danger = false, cancelLabel = 'Cancel', check?: ConfirmCheck): Promise { try { if (!hasOverlayRoot()) throw new Error('no overlay root'); - confirmDlg ??= new Confirm(); - return confirmDlg.ask(title, text, okLabel, danger, cancelLabel); + const dlg = (confirmDlg ??= new Confirm()); + const asked = dlg.ask(title, text, okLabel, danger, cancelLabel, check?.label ?? ''); + if (!check) return asked; + return asked.then((ok) => { + if (ok && dlg.checked) check.onChecked(); + return ok; + }); } catch { return Promise.resolve(window.confirm(`${title}\n\n${text}`)); } diff --git a/frontend/src/ui/drop-check.ts b/frontend/src/ui/drop-check.ts new file mode 100644 index 0000000..3af27d4 --- /dev/null +++ b/frontend/src/ui/drop-check.ts @@ -0,0 +1,48 @@ +import { t } from './i18n'; +import { toast } from './toasts'; + +// File types the library can show and use. Mirrors backend/app/services/mediatypes.py MIMES. +const KNOWN = new Set([ + 'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'ico', 'avif', 'heic', + 'mp4', 'mov', 'webm', 'mkv', 'avi', 'mpg', 'mpeg', 'flv', 'wmv', '3gp', 'ogv', 'm4v', + 'mp3', 'wav', 'flac', 'ogg', 'm4a', 'aac', 'aif', 'aiff', 'amr', + 'glb', 'gltf', 'obj', 'stl', 'usdz', 'fbx', 'ply', 'dae', 'usd', 'usda', + 'splat', 'spz', 'ksplat', 'sog', +]); +// Program and installer files are never taken in. Mirrors UNSAFE_EXTENSIONS on the engine. +const PROGRAMS = new Set([ + 'exe', 'dll', 'so', 'dylib', 'bat', 'cmd', 'com', 'scr', 'msi', 'app', 'sh', 'command', 'ps1', 'vbs', 'jar', 'apk', 'dmg', 'pkg', 'lnk', 'reg', 'pif', 'cpl', +]); +const LISTED = 3; + +const extOf = (name: string): string => { + const dot = name.lastIndexOf('.'); + return dot > 0 ? name.slice(dot + 1).toLowerCase() : ''; +}; + +const kindByType = (type: string): boolean => /^(image|video|audio|model)\//.test(type); + +function names(files: File[]): string { + const shown = files.slice(0, LISTED).map((f) => f.name).join(', '); + return files.length > LISTED ? `${shown} ${t('and {n} more').replace('{n}', String(files.length - LISTED))}` : shown; +} + +/** Splits dropped or picked files into those the library can take and those it cannot, and says plainly why the rest were left out. */ +export function screenFiles(files: File[]): File[] { + const ok: File[] = []; + const programs: File[] = []; + const unknown: File[] = []; + for (const f of files) { + const ext = extOf(f.name); + if (PROGRAMS.has(ext)) programs.push(f); + else if (KNOWN.has(ext) || kindByType(f.type)) ok.push(f); + else unknown.push(f); + } + if (programs.length) { + toast(`${t('Program files are never added:')} ${names(programs)}`, 'error', { key: 'drop-programs' }); + } + if (unknown.length) { + toast(`${t('Not an image, video, sound or 3D file, so it was left out:')} ${names(unknown)}`, 'warning', { key: 'drop-unknown' }); + } + return ok; +} diff --git a/frontend/src/ui/edit/assets/tab-media.ts b/frontend/src/ui/edit/assets/tab-media.ts index b980717..3eba90e 100644 --- a/frontend/src/ui/edit/assets/tab-media.ts +++ b/frontend/src/ui/edit/assets/tab-media.ts @@ -9,5 +9,6 @@ export const buildMedia: TabBuild = (page, ctx) => { onAdd: (items) => void ctx.addMedia(items.map((m) => m.id)), }); page.appendChild(panel.el); + page.insertAdjacentHTML('beforeend', '
'); return { show: () => panel.activate() }; }; diff --git a/frontend/src/ui/edit/assets/tab-text.ts b/frontend/src/ui/edit/assets/tab-text.ts index 5183361..6393ac9 100644 --- a/frontend/src/ui/edit/assets/tab-text.ts +++ b/frontend/src/ui/edit/assets/tab-text.ts @@ -1,5 +1,5 @@ import { makeText } from '../../../engine/edit/elements'; -import type { TextStyle } from '../../../engine/edit/types'; +import { TICKS_PER_SECOND, type TextStyle } from '../../../engine/edit/types'; import { el } from '../../dom'; import { t } from '../../i18n'; import type { TabBuild } from './util'; @@ -22,10 +22,61 @@ const PRESETS: readonly Preset[] = [ { id: 'mono', name: 'Typewriter', content: 'typed note', style: { fontFamily: 'JetBrains Mono', fontSize: 5, fontWeight: 500, letterSpacing: 1, color: '#9cf0b4' } }, ]; +interface Template { + id: string; + name: string; + content: string; + style: Partial; + x: number; + y: number; + fade: number; + atEnd?: boolean; +} + +const TEMPLATES: readonly Template[] = [ + { id: 'lower-third', name: 'Lower third', content: 'Your Name\nTitle or role', style: { fontSize: 4, fontWeight: 600, align: 'left', plate: true, plateColor: '#000000b3', plateRadius: 6 }, x: -0.28, y: 0.32, fade: 0.3 }, + { id: 'centred-title', name: 'Centred title', content: 'Your title', style: { fontSize: 10, fontWeight: 800, shadow: true }, x: 0, y: 0, fade: 0.5 }, + { id: 'end-card', name: 'End card', content: 'Thanks for watching\nSee you next time', style: { fontSize: 6, fontWeight: 700, lineHeight: 1.3, shadow: true }, x: 0, y: 0, fade: 0.5, atEnd: true }, +]; + +const CARD_SECONDS = 5; + export const buildText: TabBuild = (page, ctx) => { page.innerHTML = - `
${t('Text styles')}
`; - const grid = page.querySelector('.fc-ea-grid') as HTMLElement; + `
${t('Title templates')}
${t('Text styles')}
`; + const grid = page.querySelector('[data-grid="styles"]') as HTMLElement; + const tgrid = page.querySelector('[data-grid="templates"]') as HTMLElement; + for (const p of TEMPLATES) { + const tile = el( + ``, + ); + const sample = tile.querySelector('.fc-ea-textart') as HTMLElement; + sample.textContent = p.content.split('\n')[0]; + sample.style.fontWeight = String(p.style.fontWeight ?? 600); + if (p.style.plate) { + sample.style.background = p.style.plateColor ?? '#000'; + sample.style.borderRadius = '4px'; + } + (tile.querySelector('.fc-ea-tile-name') as HTMLElement).textContent = t(p.name); + tgrid.appendChild(tile); + } + tgrid.addEventListener('click', (e) => { + const tile = (e.target as Element).closest('.fc-ea-tile'); + const p = TEMPLATES.find((x) => x.id === tile?.dataset.id); + if (!p) return; + const { store, transport } = ctx; + const len = CARD_SECONDS * TICKS_PER_SECOND; + const clip = makeText(p.content, len); + const fade = Math.round(p.fade * TICKS_PER_SECOND); + clip.name = t(p.name); + clip.text = { ...clip.text, ...p.style }; + clip.transform = { ...clip.transform, x: Math.round(p.x * store.doc.canvas.width), y: Math.round(p.y * store.doc.canvas.height) }; + clip.fadeIn = fade; + clip.fadeOut = fade; + const at = p.atEnd && store.duration() > 0 ? Math.max(0, store.duration() - len) : transport.playhead; + const id = store.addElement(clip, at, 'first-available'); + store.select([id]); + }); for (const p of PRESETS) { const tile = el( ``, diff --git a/frontend/src/ui/edit/context.ts b/frontend/src/ui/edit/context.ts index a80be75..57e8218 100644 --- a/frontend/src/ui/edit/context.ts +++ b/frontend/src/ui/edit/context.ts @@ -9,6 +9,11 @@ export interface Transport { toggle(): void; seek(t: Tick): void; onTick(fn: (t: Tick) => void): () => void; + readonly range: { in: Tick | null; out: Tick | null }; + readonly looping: boolean; + setRange(inPoint: Tick | null, outPoint: Tick | null): void; + setLoop(on: boolean): void; + onState(fn: () => void): () => void; } export interface PreviewApi { diff --git a/frontend/src/ui/edit/export/index.ts b/frontend/src/ui/edit/export/index.ts index 4f1211f..1221447 100644 --- a/frontend/src/ui/edit/export/index.ts +++ b/frontend/src/ui/edit/export/index.ts @@ -8,9 +8,13 @@ import { el, escapeHtml, q, setAttr, setDisabled, setHidden, setHtml, setText, s import { t } from '../../i18n'; import { icon } from '../../icons'; import { inDesktop } from '../../prefs'; +import { browserSave } from '../../output-files'; +import { announceOutput } from '../../projects/outputs'; import { pickSavePath } from '../../save-media'; import { toast } from '../../toasts'; import { appState, handoffLabel, sendToApp, type FamilyApp, FAMILY_APPS } from '../handoff'; +import { localJobs } from '../../../engine/local-jobs'; +import { encoderOffered, readRenderingPrefs, sendToFormEncoder } from '../../rendering'; import { createAudioFeed, hasSound } from './audio'; import { mountLock, type ExportLock } from './lock'; import { exportFileName } from './names'; @@ -45,7 +49,10 @@ const DEFAULTS: ExportSettings = { format: 'mp4', quality: 'high', audio: true, function readSettings(): ExportSettings { try { const raw = JSON.parse(localStorage.getItem(KEY) ?? 'null') as Partial | null; - if (!raw || typeof raw !== 'object') return { ...DEFAULTS }; + if (!raw || typeof raw !== 'object') { + const chosen = readRenderingPrefs(); + return { ...DEFAULTS, format: chosen.format, quality: chosen.quality }; + } return { format: raw.format === 'webm' ? 'webm' : 'mp4', quality: QUALITIES.some(([id]) => id === raw.quality) ? (raw.quality as EditQuality) : 'high', @@ -373,10 +380,13 @@ class ExportPanel extends Dialog implements ExportApi { } const controller = new AbortController(); this.controller = controller; + this.outcome = null; + const local =localJobs.start('edit.export', t('Edit export'), () => controller.abort()); this.deps.beforeStart(); this.lock.set(true); this.setView('run'); const show = (p: Progress): void => { + local.progress(p.percent / 100); this.lock.progress(p); this.fill.style.transform = `scaleX(${Math.max(0, Math.min(1, p.percent / 100))})`; setText(this.percent, `${Math.floor(p.percent)}%`); @@ -403,6 +413,9 @@ class ExportPanel extends Dialog implements ExportApi { this.controller = null; this.lock.set(false); this.deps.afterEnd(); + if (this.outcome?.ok) local.done(this.outcome.mediaId ? [this.outcome.mediaId] : []); + else if (controller.signal.aborted) local.cancelled(); + else local.fail(this.outcome?.message || t('The export could not be finished.')); } } @@ -498,13 +511,7 @@ class ExportPanel extends Dialog implements ExportApi { if (!inDesktop()) { const url = blob ? URL.createObjectURL(blob) : media ? mediaFileUrl(media.id) : ''; if (!url) return { mark: 'bad', text: t('The file could not be saved to disk.') }; - const link = document.createElement('a'); - link.href = url; - link.download = plan.name; - link.hidden = true; - document.body.append(link); - link.click(); - link.remove(); + browserSave(url, plan.name); if (blob) window.setTimeout(() => URL.revokeObjectURL(url), 60000); return { mark: 'ok', text: t('Your browser is downloading {name}').replace('{name}', plan.name) }; } @@ -515,7 +522,7 @@ class ExportPanel extends Dialog implements ExportApi { path = await pickSavePath(t('Export video'), plan.name); if (!path) return { mark: 'skip', text: t('Not saved to disk: no location was chosen.') }; } - const saved = await downloadMedia(media.id, path ? { path, overwrite: true } : {}); + const saved = await downloadMedia(media.id, path ? { path, overwrite: true } : { name: plan.name }); return { mark: 'ok', text: t('Saved to {path}').replace('{path}', saved.path) }; } catch (err) { const why = err instanceof ApiError && err.message ? err.message : typeof err === 'string' ? err : t('The file could not be saved to disk.'); @@ -540,6 +547,7 @@ class ExportPanel extends Dialog implements ExportApi { this.paintHandoff(); this.setView('done'); if (!this.isOpen) this.open_(); + if (this.resultMedia) announceOutput([this.resultMedia.id], t('Export finished.'), 'edit-export-done'); } private paintHandoff(): void { @@ -554,8 +562,16 @@ class ExportPanel extends Dialog implements ExportApi { }); this.handoffRow.append(b); } + const enc = el(''); + enc.dataset.en = 'Send to FormEncoder'; + setText(enc, t('Send to FormEncoder')); + enc.addEventListener('click', () => { + if (this.resultMedia) void sendToFormEncoder(this.resultMedia.id); + }); + this.handoffRow.append(enc); } - for (const b of Array.from(this.handoffRow.querySelectorAll('button'))) { + setHidden(q(this.handoffRow, '[data-encoder]'), !encoderOffered()); + for (const b of Array.from(this.handoffRow.querySelectorAll('button[data-app]'))) { const app = b.dataset.app as FamilyApp; const state = appState(app); setText(b, handoffLabel(app)); diff --git a/frontend/src/ui/edit/export/run.ts b/frontend/src/ui/edit/export/run.ts index 7c83431..ad736f4 100644 --- a/frontend/src/ui/edit/export/run.ts +++ b/frontend/src/ui/edit/export/run.ts @@ -1,4 +1,5 @@ -import { renderFrame, activeAt, sourceTickOf } from '../../../engine/edit/render/frame'; +import { renderFrame, sourceTickOf } from '../../../engine/edit/render/frame'; +import { shownAt } from '../../../engine/edit/transitions'; import type { EditStore } from '../../../engine/edit/store'; import { frameStart } from '../../../engine/edit/time'; import type { EditScene } from '../../../engine/edit/types'; @@ -91,7 +92,7 @@ export async function runExport(args: RunArgs): Promise { for (const track of scene.tracks) { if (track.hidden) continue; for (const el of track.elements) { - if (el.hidden || !activeAt(el, at)) continue; + if (el.hidden || !shownAt(track, el, at)) continue; if (el.kind === 'video') waits.push(media.frameAsync(el.media.$media, sourceTickOf(el, at))); else if (el.kind === 'image') waits.push(media.imageAsync(el.media.$media)); } diff --git a/frontend/src/ui/edit/files.ts b/frontend/src/ui/edit/files.ts index feaab4a..2df7aa1 100644 --- a/frontend/src/ui/edit/files.ts +++ b/frontend/src/ui/edit/files.ts @@ -3,10 +3,9 @@ import { blankEdit } from '../../engine/edit/doc'; import { EditStore } from '../../engine/edit/store'; import type { EditDoc } from '../../engine/edit/types'; import { studios } from '../../engine/studios'; -import { ApiError, getSettings } from '../../io/api'; +import { ApiError } from '../../io/api'; import { createProject, - exportProject, getProject, patchProject, putProjectCover, @@ -17,9 +16,8 @@ import { } from '../../io/api-projects'; import { confirmAction } from '../dialogs'; import { t } from '../i18n'; -import { inDesktop } from '../prefs'; +import { writeProjectFile } from '../projects/disk'; import { projectStore } from '../projects/store'; -import { pickSavePath } from '../save-media'; import { toast } from '../toasts'; import { askUnsaved, type UnsavedReason } from './unsaved'; @@ -31,7 +29,6 @@ const COVER_DELAY_MS = 3000; const COVER_EDGE = 512; const reason = (err: unknown, fallback: string): string => (err instanceof ApiError && err.message ? err.message : fallback); -const fileSafe = (name: string): string => name.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').replace(/^[ .]+|[ .]+$/g, '').slice(0, 80) || 'edit'; export interface FilesHost { store(): EditStore; @@ -301,22 +298,7 @@ export class EditFiles { if (!(await this.flush())) return false; const id = this.id; if (id === null) return false; - return this.track(async () => { - try { - let path: string | null = null; - const settings = await getSettings().catch(() => null); - if (settings?.askLocation === true && inDesktop()) { - path = await pickSavePath(t('Export edit'), `${fileSafe(this.name)}.fcrft`); - if (!path) return false; - } - const written = await exportProject(id, path, path !== null); - toast(t('Exported to {path}').replace('{path}', () => written.path), 'success', { key: 'edit-export-file' }); - return true; - } catch (err) { - toast(reason(err, t('The edit could not be exported.')), 'error', { key: 'edit-export-file' }); - return false; - } - }); + return this.track(async () => (await writeProjectFile(id, this.name, 'copy')) !== null); } async rename(raw: string): Promise { diff --git a/frontend/src/ui/edit/index.ts b/frontend/src/ui/edit/index.ts index 2d76db3..f84b705 100644 --- a/frontend/src/ui/edit/index.ts +++ b/frontend/src/ui/edit/index.ts @@ -128,8 +128,8 @@ export function mountEdit(host: HTMLElement): void { registerProjectOpener('edit', async (summary) => { claimed++; try { - if (!pending) { - const project = await getProject(summary.id); + const project = pending ? null : await getProject(summary.id); + if (project && !pending) { await load(project); } else { const studio = await editApi(); diff --git a/frontend/src/ui/edit/intro.ts b/frontend/src/ui/edit/intro.ts index a356e84..18da72e 100644 --- a/frontend/src/ui/edit/intro.ts +++ b/frontend/src/ui/edit/intro.ts @@ -1,108 +1,27 @@ -import { studios } from '../../engine/studios'; -import { q, setHidden, setText } from '../dom'; -import { t } from '../i18n'; +import { q, setHidden } from '../dom'; import type { EditShell } from './skeleton'; -const SEEN_KEY = 'formcraft.edit.onboarded'; const MIN_WIDTH = 1024; -const STEPS: readonly (readonly [string, string])[] = [ - ['Bring in your media', 'Add video, pictures and sound from the Media tab, or drop files onto the window. Everything you add also lands in the library.'], - ['Arrange it on the timeline', 'Drag clips onto tracks, pull their ends to trim, and press S to cut at the playhead. Every change can be undone.'], - ['Finish and export', 'Press Export to make an MP4 or WebM file. Save it to disk, add it to the library, or do both.'], -]; - -function seen(): boolean { - try { - return localStorage.getItem(SEEN_KEY) === '1'; - } catch { - return false; - } -} - -function markSeen(): void { - try { - localStorage.setItem(SEEN_KEY, '1'); - } catch { - return; - } -} - export function mountIntro(shell: EditShell): { ready(): void } { const { root } = shell; const gate = q(root, '.fc-ed-gate'); - const board = q(root, '.fc-ed-onboard'); - const title = q(board, '.fc-ed-card-title'); - const text = q(board, '.fc-ed-ob-text'); - const dots = Array.from(board.querySelectorAll('.fc-ed-dots span')); - const back = q(board, '[data-act="ob-back"]'); - const next = q(board, '[data-act="ob-next"]'); - const skip = q(board, '[data-act="ob-skip"]'); - let waived = false; - let loaded = false; - let done = seen(); - let step = 0; const narrow = (): boolean => root.clientWidth > 0 && root.clientWidth < MIN_WIDTH; - const active = (): boolean => studios.rootOf(studios.active) === 'edit'; - - const paintStep = (): void => { - const [head, body] = STEPS[step]; - setText(title, t(head)); - setText(text, t(body)); - dots.forEach((d, i) => d.classList.toggle('is-on', i === step)); - setHidden(back, step === 0); - setText(next, t(step === STEPS.length - 1 ? 'Done' : 'Next')); - setHidden(skip, step === STEPS.length - 1); - }; const paint = (): void => { - const blocked = !waived && narrow(); - setHidden(gate, !blocked); - const showBoard = loaded && !done && !blocked && active(); - if (showBoard && board.hidden) { - step = 0; - paintStep(); - } - setHidden(board, !showBoard); - if (showBoard && !board.contains(document.activeElement)) next.focus({ preventScroll: true }); - }; - - const finish = (): void => { - done = true; - markSeen(); - paint(); + setHidden(gate, waived || !narrow()); }; q(gate, '[data-act="gate-continue"]').addEventListener('click', () => { waived = true; paint(); }); - next.addEventListener('click', () => { - if (step >= STEPS.length - 1) { - finish(); - return; - } - step++; - paintStep(); - }); - back.addEventListener('click', () => { - step = Math.max(0, step - 1); - paintStep(); - }); - skip.addEventListener('click', finish); - board.addEventListener('keydown', (e) => { - if (e.key !== 'Escape') return; - e.stopPropagation(); - finish(); - }); new ResizeObserver(paint).observe(root); - studios.on('active', paint); return { ready(): void { - loaded = true; paint(); }, }; diff --git a/frontend/src/ui/edit/library-drop.ts b/frontend/src/ui/edit/library-drop.ts new file mode 100644 index 0000000..c390bb3 --- /dev/null +++ b/frontend/src/ui/edit/library-drop.ts @@ -0,0 +1,46 @@ +import { DEFAULT_CLIP_SECONDS } from '../../engine/edit/elements'; +import { secondsToTicks, snapToFrame } from '../../engine/edit/time'; +import type { Media } from '../../io/api'; +import { probeMedia } from '../../io/api-edit'; +import { editApi } from './bridge'; +import { timelineDropAt } from './timeline'; + +export function editTrackAt(clientX: number, clientY: number): string | null { + for (const lane of document.querySelectorAll('.fc-etl-lane[data-track]')) { + const r = lane.getBoundingClientRect(); + if (clientX >= r.left && clientX <= r.right && clientY >= r.top && clientY < r.bottom) return lane.dataset.track ?? null; + } + return null; +} + +export async function dropMediaInEdit(items: readonly Media[], clientX: number, clientY: number): Promise { + const studio = await editApi(); + if (studio.exporting()) return 0; + const { store, transport } = studio.ctx(); + const track = editTrackAt(clientX, clientY) ?? undefined; + let at = snapToFrame(Math.max(0, timelineDropAt(clientX, clientY)?.at ?? transport.playhead), store.doc.fps); + let added = 0; + for (const m of items) { + if (m.kind !== 'video' && m.kind !== 'image' && m.kind !== 'audio') continue; + const probe = m.kind === 'image' ? null : await probeMedia(m.id).catch(() => null); + const seconds = m.kind === 'image' ? null : (probe?.durationSec ?? m.durationSec ?? null); + store.addMediaClip( + { + mediaId: m.id, + kind: m.kind, + durationSec: seconds, + width: probe?.width ?? m.width ?? 0, + height: probe?.height ?? m.height ?? 0, + hasAudio: m.kind === 'audio' ? true : probe?.hasAudio === true, + fps: m.kind === 'video' && probe?.fps ? probe.fps.num / probe.fps.den : undefined, + name: m.name, + }, + at, + track ? 'preferred-index' : undefined, + track, + ); + added++; + at += secondsToTicks(seconds && seconds > 0 ? seconds : DEFAULT_CLIP_SECONDS); + } + return added; +} diff --git a/frontend/src/ui/edit/preview/playback-audio.ts b/frontend/src/ui/edit/preview/playback-audio.ts index ce25455..b43d5ca 100644 --- a/frontend/src/ui/edit/preview/playback-audio.ts +++ b/frontend/src/ui/edit/preview/playback-audio.ts @@ -1,6 +1,8 @@ -import { timeStretch } from '../../../engine/edit/audio/stretch'; -import { evalProp } from '../../../engine/edit/keyframes'; +import { gainSamples, soundWindow } from '../../../engine/edit/audio/mix'; +import { needsShaping, shapeClip, shapeKey } from '../../../engine/edit/audio/shape'; import type { EditStore } from '../../../engine/edit/store'; +import { trackAudible } from '../../../engine/edit/tracks'; +import { soundShaped } from '../../../engine/edit/transitions'; import { TICKS_PER_SECOND, type EditElement, type Tick } from '../../../engine/edit/types'; import type { PreviewMedia } from './media'; @@ -11,20 +13,11 @@ interface Live { const RAMP = 0.01; const STRETCH_KEEP = 12; -const CURVE_PER_SECOND = 200; -type Sound = EditElement & { volumeDb: number; speed: number; trimStart: Tick; keepPitch: boolean }; +type Sound = EditElement & { volumeDb: number; speed: number; trimStart: Tick; keepPitch: boolean; reverse?: boolean }; -const stretchKey = (id: string, el: Sound): string => `${id}|${el.trimStart}|${el.duration}|${el.speed}`; const dbGain = (db: number): number => Math.pow(10, db / 20); -function gainCurve(el: Sound, a: Tick, b: Tick): Float32Array { - const n = Math.max(2, Math.ceil(((b - a) / TICKS_PER_SECOND) * CURVE_PER_SECOND) + 1); - const out = new Float32Array(n); - for (let i = 0; i < n; i += 1) out[i] = dbGain(evalProp(el, 'volumeDb', a + ((b - a) * i) / (n - 1) - el.start, el.volumeDb)); - return out; -} - function mediaOf(el: EditElement): string | null { if (el.kind === 'video') return el.hasAudio && !el.audioExtracted ? el.media.$media : null; if (el.kind === 'audio') return el.media.$media; @@ -116,40 +109,41 @@ export class PlaybackAudio { private schedule(ctx: AudioContext, from: Tick): void { const scene = this.store.scene; for (const track of scene.tracks) { - if (track.muted) continue; + if (!trackAudible(scene, track)) continue; for (const el of track.elements) { - if (el.muted || (el.kind !== 'video' && el.kind !== 'audio')) continue; + if (el.muted || (el.kind !== 'video' && el.kind !== 'audio') || (el.kind === 'video' && el.freeze)) continue; const id = mediaOf(el); if (!id) continue; - const end = el.start + el.duration; + const sound = el as Sound; + const pitched = needsShaping(sound); + const win = soundWindow(track, sound, pitched); + const end = win.to; if (end <= from) continue; const buffer = this.buffers.get(id); if (!buffer) { this.request(id); continue; } - const at = Math.max(from, el.start); - const sound = el as Sound; - const pitched = sound.keepPitch && Math.abs(sound.speed - 1) > 1e-4; + const at = Math.max(from, win.from); const fixed = pitched ? this.stretchedFor(id, sound, buffer) : null; if (pitched && !fixed) continue; const src = ctx.createBufferSource(); const gain = ctx.createGain(); - const when = ctx.currentTime + Math.max(0, (el.start - from) / TICKS_PER_SECOND); + const when = ctx.currentTime + Math.max(0, (at - from) / TICKS_PER_SECOND); if (fixed) { const offset = (at - el.start) / TICKS_PER_SECOND; if (offset >= fixed.duration) continue; src.buffer = fixed; src.start(when, offset, Math.min((end - at) / TICKS_PER_SECOND, fixed.duration - offset)); } else { - const offset = (el.trimStart + (at - el.start) * el.speed) / TICKS_PER_SECOND; + const offset = Math.max(0, (el.trimStart + (at - el.start) * el.speed) / TICKS_PER_SECOND); const length = ((end - at) * el.speed) / TICKS_PER_SECOND; if (offset >= buffer.duration) continue; src.buffer = buffer; src.playbackRate.value = el.speed > 0 ? el.speed : 1; src.start(when, offset, Math.min(length, buffer.duration - offset)); } - if (sound.anim?.volumeDb?.keys.length) gain.gain.setValueCurveAtTime(gainCurve(sound, at, end), when, (end - at) / TICKS_PER_SECOND); + if (sound.anim?.volumeDb?.keys.length || soundShaped(track, el)) gain.gain.setValueCurveAtTime(gainSamples(sound, at, end, track), when, (end - at) / TICKS_PER_SECOND); else gain.gain.value = dbGain(sound.volumeDb); src.connect(gain); gain.connect(this.master as GainNode); @@ -165,20 +159,16 @@ export class PlaybackAudio { } private stretchedFor(id: string, el: Sound, buffer: AudioBuffer): AudioBuffer | null { - const key = stretchKey(id, el); + const key = shapeKey(id, el); const hit = this.stretched.get(key); if (hit) return hit; if (this.stretching.has(key)) return null; this.stretching.add(key); - const { trimStart, duration, speed } = el; + const clip = { trimStart: el.trimStart, duration: el.duration, speed: el.speed, keepPitch: el.keepPitch, reverse: el.reverse }; window.setTimeout(() => { this.stretching.delete(key); const sr = buffer.sampleRate; - const from = Math.max(0, Math.floor((trimStart / TICKS_PER_SECOND) * sr)); - const to = Math.min(buffer.length, Math.ceil(((trimStart + duration * speed) / TICKS_PER_SECOND) * sr)); - const parts: Float32Array[] = []; - for (let c = 0; c < buffer.numberOfChannels; c += 1) parts.push(buffer.getChannelData(c).subarray(from, Math.max(from, to))); - const out = timeStretch(parts, sr, speed); + const out = shapeClip(buffer, clip); const len = out[0]?.length ?? 0; if (!len || !this.ctx) return; const made = this.ctx.createBuffer(out.length, len, sr); diff --git a/frontend/src/ui/edit/preview/stage.ts b/frontend/src/ui/edit/preview/stage.ts index 0e7ace3..1ea0187 100644 --- a/frontend/src/ui/edit/preview/stage.ts +++ b/frontend/src/ui/edit/preview/stage.ts @@ -1,4 +1,5 @@ -import { renderFrame } from '../../../engine/edit/render/frame'; +import { renderFrame, sourceTickOf } from '../../../engine/edit/render/frame'; +import { shownAt } from '../../../engine/edit/transitions'; import type { EditStore } from '../../../engine/edit/store'; import type { RenderSurface } from '../../../engine/edit/types'; import { el, q, setClass, setHidden, setText } from '../../dom'; @@ -16,6 +17,19 @@ const KEEP_VISIBLE = 48; export const evenSize = (n: number): number => Math.max(2, Math.round(n / 2) * 2); +export type PreviewQuality = 1 | 0.5 | 0.25; + +const QUALITY_KEY = 'formcraft.edit.previewQuality'; + +function readQuality(): PreviewQuality { + try { + const v = Number(localStorage.getItem(QUALITY_KEY)); + return v === 0.5 || v === 0.25 ? v : 1; + } catch { + return 1; + } +} + class Surface implements RenderSurface { constructor( readonly canvas: Surf, @@ -92,6 +106,7 @@ export class Stage { private broken = false; private panning = false; private lastTransform = ''; + private q = readQuality(); private viewFns = new Set<() => void>(); private renderFns = new Set<() => void>(); private offs: Array<() => void> = []; @@ -296,11 +311,13 @@ export class Stage { const doc = this.store.doc; const w = evenSize(doc.canvas.width); const h = evenSize(doc.canvas.height); - if (w === this.cw && h === this.ch && this.canvas.width === w && this.canvas.height === h) return false; + const pw = evenSize(w * this.q); + const ph = evenSize(h * this.q); + if (w === this.cw && h === this.ch && this.canvas.width === pw && this.canvas.height === ph) return false; this.cw = w; this.ch = h; - this.canvas.width = w; - this.canvas.height = h; + this.canvas.width = pw; + this.canvas.height = ph; this.board.style.width = `${w}px`; this.board.style.height = `${h}px`; this.surface = null; @@ -393,15 +410,38 @@ export class Stage { for (const track of scene.tracks) { if (track.hidden) continue; for (const e of track.elements) { - if (e.hidden || t < e.start || t >= e.start + e.duration) continue; - if (e.kind === 'video') waits.push(this.media.frameAsync(e.media.$media, e.trimStart + (t - e.start) * e.speed)); + if (e.hidden || !shownAt(track, e, t)) continue; + if (e.kind === 'video') waits.push(this.media.frameAsync(e.media.$media, sourceTickOf(e, t))); else if (e.kind === 'image') waits.push(this.media.imageAsync(e.media.$media)); } } await Promise.all(waits); - await this.renderNow(); - if (this.broken) return null; - return new Promise((resolve) => this.canvas.toBlob((b) => resolve(b), 'image/png')); + const keep = this.q; + this.q = 1; + try { + await this.renderNow(); + if (this.broken) return null; + return await new Promise((resolve) => this.canvas.toBlob((b) => resolve(b), 'image/png')); + } finally { + this.q = keep; + if (keep !== 1) this.request(); + } + } + + get quality(): PreviewQuality { + return this.q; + } + + setQuality(q: PreviewQuality): void { + if (q === this.q) return; + this.q = q; + try { + localStorage.setItem(QUALITY_KEY, String(q)); + } catch { + void 0; + } + this.request(); + this.emitView(); } dispose(): void { diff --git a/frontend/src/ui/edit/preview/toolbar.ts b/frontend/src/ui/edit/preview/toolbar.ts index 8733507..976eb33 100644 --- a/frontend/src/ui/edit/preview/toolbar.ts +++ b/frontend/src/ui/edit/preview/toolbar.ts @@ -3,10 +3,11 @@ import { formatTimecode, frameStart, frameTicks, parseTimecode } from '../../../ import type { Tick } from '../../../engine/edit/types'; import { el, q, setAttr, setClass, setDisabled, setText, setTitle, setValue } from '../../dom'; import { toast } from '../../toasts'; +import { saveBlob } from '../../save-media'; import type { PreviewApi } from '../context'; import { pvIcon } from './icons'; import type { Overlay } from './overlay'; -import type { Stage } from './stage'; +import type { PreviewQuality, Stage } from './stage'; import type { PlayTransport } from './transport'; const PRESETS: ReadonlyArray<{ label: string; percent: number }> = [ @@ -16,6 +17,12 @@ const PRESETS: ReadonlyArray<{ label: string; percent: number }> = [ { label: '200%', percent: 200 }, ]; +const QUALITY: ReadonlyArray<{ label: string; q: PreviewQuality }> = [ + { label: 'Full', q: 1 }, + { label: 'Half', q: 0.5 }, + { label: 'Quarter', q: 0.25 }, +]; + const btn = (cls: string, icon: string, label: string): string => ``; @@ -62,7 +69,10 @@ export class Toolbar { `` + '' + + '' + + '
Preview quality
' + + QUALITY.map((p) => ``).join('') + + '' + btn('fc-pv-snap', 'camera', 'Save a picture of this frame') + btn('fc-pv-full', 'expand', 'Full screen') + '', @@ -89,6 +99,9 @@ export class Toolbar { } private wire(): void { + this.play.dataset.tipKeys = 'edit.playPause'; + this.back.dataset.tipKeys = 'edit.stepBack'; + this.fwd.dataset.tipKeys = 'edit.stepForward'; this.play.addEventListener('click', () => this.transport.toggle()); this.back.addEventListener('click', () => this.step(-1)); this.fwd.addEventListener('click', () => this.step(1)); @@ -101,7 +114,8 @@ export class Toolbar { this.menu.addEventListener('click', (e) => { const item = (e.target as Element).closest('.fc-pv-item'); if (!item) return; - if (item.dataset.fit) this.stage.fit(); + if (item.dataset.quality) this.stage.setQuality(Number(item.dataset.quality) as PreviewQuality); + else if (item.dataset.fit) this.stage.fit(); else this.stage.setPercent(Number(item.dataset.percent)); this.setMenu(false); }); @@ -185,12 +199,7 @@ export class Toolbar { toast('The picture could not be saved.', 'error', { key: 'edit-snapshot' }); return; } - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `frame-${formatTimecode(this.transport.playhead, this.fps()).replace(/:/g, '-')}.png`; - a.click(); - window.setTimeout(() => URL.revokeObjectURL(url), 4000); + await saveBlob(blob, `frame-${formatTimecode(this.transport.playhead, this.fps()).replace(/:/g, '-')}.png`, 'Save frame'); } private async toggleFull(): Promise { @@ -241,6 +250,9 @@ export class Toolbar { private patchZoom(): void { setText(q(this.zoom, '.fc-pv-zoom-label'), this.stage.label()); + const now = String(this.stage.quality); + for (const item of this.menu.querySelectorAll('[data-quality]')) setAttr(item, 'aria-checked', item.dataset.quality === now ? 'true' : 'false'); + setTitle(this.zoom, this.stage.quality === 1 ? 'Zoom' : `Zoom, preview at ${this.stage.quality === 0.5 ? 'half' : 'quarter'} quality`); } private patchFull(): void { diff --git a/frontend/src/ui/edit/preview/transport.ts b/frontend/src/ui/edit/preview/transport.ts index 3beb74b..f4c312f 100644 --- a/frontend/src/ui/edit/preview/transport.ts +++ b/frontend/src/ui/edit/preview/transport.ts @@ -75,6 +75,44 @@ export class PlayTransport implements Transport { return this.dur; } + private loopOn = false; + + private get span(): { in: Tick | null; out: Tick | null } { + const v = this.store.doc.view; + return { in: v.markIn ?? null, out: v.markOut ?? null }; + } + + get range(): { in: Tick | null; out: Tick | null } { + return this.span; + } + + get looping(): boolean { + return this.loopOn; + } + + setRange(inPoint: Tick | null, outPoint: Tick | null): void { + let a = inPoint === null ? null : this.clamp(inPoint); + let b = outPoint === null ? null : this.clamp(outPoint); + if (a !== null && b !== null && b <= a) { + if (inPoint !== this.span.in) b = null; + else a = null; + } + this.store.setView({ markIn: a ?? -1, markOut: b ?? -1 }); + this.notifyState(); + } + + setLoop(on: boolean): void { + if (this.loopOn === on) return; + this.loopOn = on; + this.notifyState(); + } + + private bounds(): { start: Tick; end: Tick } { + const start = this.span.in ?? 0; + const end = this.span.out !== null && this.span.out > start ? Math.min(this.span.out, this.dur) : this.dur; + return { start, end }; + } + renderTime(): Tick { const fps = this.store.doc.fps; const last = frameStart(Math.max(0, frameCount(this.dur, fps) - 1), fps); @@ -118,9 +156,11 @@ export class PlayTransport implements Transport { this.dur = this.store.duration(); if (this.dur <= 0) return; const fps = this.store.doc.fps; - const last = frameStart(Math.max(0, frameCount(this.dur, fps) - 1), fps); - if (this.head >= last) { - this.head = 0; + const { start, end } = this.bounds(); + const last = frameStart(Math.max(0, frameCount(end, fps) - 1), fps); + const ranged = this.span.in !== null || this.span.out !== null; + if (this.head >= last || (ranged && this.head < start)) { + this.head = start; this.commitHead(); this.notify(); } @@ -168,8 +208,18 @@ export class PlayTransport implements Transport { if (!this.on) return; const fps = this.store.doc.fps; const cand = this.exactTime(); - if (cand >= this.dur) { - this.head = this.dur; + const { start, end } = this.bounds(); + if (cand >= end && this.loopOn && end > start) { + this.head = start; + this.anchorWall = performance.now(); + this.anchorTick = start; + this.audio.start(start); + this.notify(); + this.raf = requestAnimationFrame(this.loop); + return; + } + if (cand >= end) { + this.head = end; this.on = false; this.audio.stop(); this.commitHead(); diff --git a/frontend/src/ui/edit/props/fields.ts b/frontend/src/ui/edit/props/fields.ts index 53f5ca3..18ef25d 100644 --- a/frontend/src/ui/edit/props/fields.ts +++ b/frontend/src/ui/edit/props/fields.ts @@ -26,6 +26,14 @@ export interface Writer { commit(v: T): void; } +let lastProp: { id: string; prop: string } | null = null; + +export const lastKeyProp = (): { id: string; prop: string } | null => lastProp; + +const noteProp = (id: string | null, prop: string): void => { + if (id) lastProp = { id, prop }; +}; + export function paramWriter(env: Env, prop: string): Writer { return { preview(g, v) { @@ -34,6 +42,7 @@ export function paramWriter(env: Env, prop: string): Writer { }, commit(v) { const id = env.id(); + noteProp(id, prop); const kv = keyValueOf(v); if (id && kv !== null) env.store.setParam(id, prop, kv, env.playhead()); }, @@ -177,12 +186,16 @@ export function numberRow(env: Env, o: NumberOpts): Row { input.value = String(Number((base + (e.key === 'ArrowUp' ? 1 : -1) * o.step * mul * (e.shiftKey ? 10 : 1)).toFixed(dec))); } }); - input.addEventListener('focus', () => input.select()); + input.addEventListener('focus', () => { + input.select(); + if (o.prop) noteProp(env.id(), o.prop); + }); if (keyBtn && o.prop) { const prop = o.prop; keyBtn.addEventListener('click', () => { const id = env.id(); + noteProp(id, prop); if (id) env.store.toggleKey(id, prop, env.playhead()); }); } diff --git a/frontend/src/ui/edit/props/panes.ts b/frontend/src/ui/edit/props/panes.ts index cf0d89f..5cd876a 100644 --- a/frontend/src/ui/edit/props/panes.ts +++ b/frontend/src/ui/edit/props/panes.ts @@ -234,8 +234,8 @@ export function audioPane(env: Env, kind: ElementKind): Pane { export function speedPane(env: Env): Pane { const speed = numberRow(env, { label: 'Speed', - min: 0.01, - max: 5, + min: 0.25, + max: 4, step: 0.01, unit: 'x', live: false, @@ -254,7 +254,12 @@ export function speedPane(env: Env): Pane { const cur = env.cur(); if (id && (cur?.kind === 'video' || cur?.kind === 'audio')) env.store.setSpeed(id, cur.speed, !on); }); - return stack([section('Playback speed'), speed, pitch, note1()]); + const backwards = toggleRow('Play backwards', (e) => (e.kind === 'video' || e.kind === 'audio') && !!e.reverse, (on) => { + const id = env.id(); + const cur = env.cur(); + if (id && (cur?.kind === 'video' || cur?.kind === 'audio') && !(cur.kind === 'video' && cur.freeze)) env.store.patchElement(id, { reverse: on || undefined }); + }); + return stack([section('Playback speed'), speed, pitch, backwards, note1()]); } function note1(): HTMLElement { diff --git a/frontend/src/ui/edit/skeleton.ts b/frontend/src/ui/edit/skeleton.ts index 8a95b46..17203f0 100644 --- a/frontend/src/ui/edit/skeleton.ts +++ b/frontend/src/ui/edit/skeleton.ts @@ -77,15 +77,6 @@ export function skeleton(): string { `
${edIcon('desktop', 24)}

` + `

` + `

` + - '' + '
`; function labelOf(el: EditElement): string { return el.kind === 'text' ? el.text.content || el.name : el.name; @@ -91,9 +92,12 @@ export class Clips { if (view.width !== width) setStyleVar(view.node, 'width', `${width}px`); view.left = left; view.width = width; - const lbl = labelOf(el) + (isMedia(el) && el.speed !== 1 ? ` ${+el.speed.toFixed(2)}x` : ''); + const frozen = el.kind === 'video' && !!el.freeze; + const lbl = labelOf(el) + (isMedia(el) && el.speed !== 1 && !frozen ? ` ${+el.speed.toFixed(2)}x` : '') + (isMedia(el) && el.reverse ? ` ${t('backwards')}` : ''); setText(view.label, lbl); setClass(view.node, 'is-narrow', width < 24); + setStyleVar(view.node, '--fi', `${Math.min(width, Math.round((el.fadeIn ?? 0) * geo.ppt))}px`); + setStyleVar(view.node, '--fo', `${Math.min(width, Math.round((el.fadeOut ?? 0) * geo.ppt))}px`); } setClass(view.node, 'is-selected', selected); setClass(view.node, 'is-off', off); diff --git a/frontend/src/ui/edit/timeline/core.ts b/frontend/src/ui/edit/timeline/core.ts index 635c816..402c2ef 100644 --- a/frontend/src/ui/edit/timeline/core.ts +++ b/frontend/src/ui/edit/timeline/core.ts @@ -1,5 +1,6 @@ import type { EditStore } from '../../../engine/edit/store'; import type { EditElement, Tick } from '../../../engine/edit/types'; +import { placeFloating } from '../../position'; import type { EditContext } from '../context'; import type { Geo, Row } from './model'; @@ -117,15 +118,7 @@ export function openPopover(node: HTMLElement, anchor: Anchor, onClose: () => vo node.classList.add('fc-etl-pop'); node.style.visibility = 'hidden'; (document.getElementById('overlay-root') ?? document.body).appendChild(node); - const w = node.offsetWidth; - const h = node.offsetHeight; - const ax = anchor.x; - const ay = anchor.y; - const below = anchor.bottom !== undefined ? anchor.bottom + 6 : ay; - const above = ay - h - 6; - const top = below + h <= window.innerHeight - 4 ? below : Math.max(4, above); - node.style.left = `${Math.round(Math.max(4, Math.min(ax, window.innerWidth - w - 4)))}px`; - node.style.top = `${Math.round(Math.max(4, top))}px`; + placeFloating(node, { left: anchor.x, right: anchor.x, top: anchor.y, bottom: anchor.bottom ?? anchor.y }, { side: 'bottom', align: 'start' }); node.style.visibility = ''; let closed = false; const down = (e: PointerEvent): void => { diff --git a/frontend/src/ui/edit/timeline/cuts.ts b/frontend/src/ui/edit/timeline/cuts.ts new file mode 100644 index 0000000..2eacb32 --- /dev/null +++ b/frontend/src/ui/edit/timeline/cuts.ts @@ -0,0 +1,48 @@ +import { cutsOf, dissolveLength } from '../../../engine/edit/transitions'; +import { TICKS_PER_SECOND, type Tick } from '../../../engine/edit/types'; +import { el as html, setClass, setStyleVar, setText } from '../../dom'; +import { t } from '../../i18n'; +import type { Core } from './core'; +import { tlIcon } from './icons'; +import { patchKeyed } from './keyed'; +import type { Row } from './model'; + +interface CutItem { + id: string; + at: Tick; + len: Tick; +} + +const TEMPLATE = (): string => + `
`; + +export const cutHost = (lane: HTMLElement): HTMLElement | null => lane.querySelector(':scope > .fc-etl-cuts'); + +export function syncCuts(core: Core, rows: readonly Row[], lanes: ReadonlyMap, x0: number, x1: number): void { + const ppt = core.geo.ppt; + for (const row of rows) { + const lane = lanes.get(row.id); + const host = lane ? cutHost(lane) : null; + if (!host) continue; + const items: CutItem[] = []; + if (!row.track.locked) { + for (const c of cutsOf(row.track)) { + const x = c.at * ppt; + if (x < x0 || x > x1) continue; + items.push({ id: c.b.id, at: c.at, len: dissolveLength(row.track, c.b) }); + } + } + patchKeyed(host, items, { + key: (i) => i.id, + create: () => html(TEMPLATE()), + update: (node, i) => { + node.dataset.id = i.id; + node.dataset.at = String(i.at); + setStyleVar(node, 'left', `${Math.round(i.at * ppt)}px`); + setStyleVar(node, '--xw', `${Math.max(6, Math.round(i.len * ppt))}px`); + setClass(node, 'is-on', i.len > 0); + setText(node.querySelector('.fc-etl-xd-label'), i.len > 0 ? `${(i.len / TICKS_PER_SECOND).toFixed(1)}s` : ''); + }, + }); + } +} diff --git a/frontend/src/ui/edit/timeline/gestures.ts b/frontend/src/ui/edit/timeline/gestures.ts index fcba282..843745e 100644 --- a/frontend/src/ui/edit/timeline/gestures.ts +++ b/frontend/src/ui/edit/timeline/gestures.ts @@ -1,3 +1,6 @@ +import { patchElementOp, trimOp } from '../../../engine/edit/ops-clip'; +import { slideOp, slideRange, slipOp, slipRange } from '../../../engine/edit/ops-time'; +import { DISSOLVE_DEFAULT, setDissolveOp } from '../../../engine/edit/transitions'; import { frameTicks, snapToFrame } from '../../../engine/edit/time'; import { currentScene, trackAccepts } from '../../../engine/edit/tracks'; import type { EditElement, Tick } from '../../../engine/edit/types'; @@ -48,8 +51,10 @@ export function attachGestures(core: Core, ruler: HTMLElement): void { return out; }; + const unlocked = (): string[] => store.selection.clips.filter((x) => !store.elementById(x)?.track.locked); + const move = (e: PointerEvent, primaryId: string): void => { - const ids = store.selection.clips.slice(); + const ids = unlocked(); const items = infoOf(ids); const primary = items.find((i) => i.el.id === primaryId); if (!primary) return; @@ -84,7 +89,7 @@ export function attachGestures(core: Core, ruler: HTMLElement): void { const map = new Map(); for (const i of items) { const target = rows0[i.index + dTrack]?.track; - map.set(i.el.id, { start: Math.max(0, i.el.start + dt), trackId: target && trackAccepts(target, i.el) ? target.id : undefined }); + map.set(i.el.id, { start: Math.max(0, i.el.start + dt), trackId: target && !target.locked && trackAccepts(target, i.el) ? target.id : undefined }); } g?.preview((d) => placeAbsolute(d, map)); }; @@ -113,9 +118,38 @@ export function attachGestures(core: Core, ruler: HTMLElement): void { }); }; + const fade = (e: PointerEvent, id: string, key: 'fadeIn' | 'fadeOut'): void => { + const found = store.elementById(id); + if (!found) return; + const el = found.el; + const base = el[key] ?? 0; + const x0 = e.clientX; + const g = store.begin(key === 'fadeIn' ? 'Fade in' : 'Fade out'); + core.keep.add(id); + let next = base; + trackPointer(core, e, { + move(ev) { + const raw = ((ev.clientX - x0) / core.geo.ppt) * (key === 'fadeIn' ? 1 : -1); + next = clamp(snapToFrame(base + raw, store.doc.fps), 0, el.duration); + g.preview((d) => patchElementOp(d, id, { [key]: next > 0 ? next : undefined })); + }, + end() { + core.keep.delete(id); + g.abort(); + if (next !== base) store.patchElement(id, { [key]: next > 0 ? next : undefined }); + core.sync(); + }, + cancel() { + core.keep.delete(id); + g.abort(); + core.sync(); + }, + }, false); + }; + const trim = (e: PointerEvent, id: string, edge: 'start' | 'end'): void => { if (!store.selection.clips.includes(id)) store.select([id], 'replace'); - const ids = store.selection.clips.slice(); + const ids = unlocked(); const items = infoOf(ids); const primary = items.find((i) => i.el.id === id); if (!primary) return; @@ -126,14 +160,16 @@ export function attachGestures(core: Core, ruler: HTMLElement): void { const pos = (el: EditElement): Tick => (edge === 'start' ? el.start : el.start + el.duration); let lo = -Infinity; let hi = Infinity; + const ripple = store.doc.view.ripple; for (const { el } of items) { const sp = isMedia(el) ? el.speed : 1; + const room = (atStart: boolean): number => (isMedia(el) ? Math.floor((atStart !== !!el.reverse ? el.trimStart : el.trimEnd) / sp) : Infinity); if (edge === 'start') { hi = Math.min(hi, el.duration - frame); - lo = Math.max(lo, -el.start, isMedia(el) ? -Math.floor(el.trimStart / sp) : -Infinity); + lo = Math.max(lo, ripple ? -Infinity : -el.start, -room(true)); } else { lo = Math.max(lo, -(el.duration - frame)); - hi = Math.min(hi, isMedia(el) ? Math.floor(el.trimEnd / sp) : Infinity); + hi = Math.min(hi, room(false)); } } const g = store.begin('Trim clips'); @@ -157,14 +193,7 @@ export function attachGestures(core: Core, ruler: HTMLElement): void { } dt = clamp(dt, lo, hi); core.showSnap(at); - const map = new Map(); - for (const { el } of items) { - const sp = isMedia(el) ? el.speed : 1; - const src = Math.round(dt * sp); - if (edge === 'start') map.set(el.id, { start: el.start + dt, duration: el.duration - dt, trimStart: isMedia(el) ? el.trimStart + src : undefined }); - else map.set(el.id, { duration: el.duration + dt, trimEnd: isMedia(el) ? el.trimEnd - src : undefined }); - } - g.preview((d) => placeAbsolute(d, map)); + g.preview((d) => trimOp(d, ids, edge, dt)); }, end() { finish(); @@ -180,6 +209,81 @@ export function attachGestures(core: Core, ruler: HTMLElement): void { }); }; + const dissolveDrag = (e: PointerEvent, id: string, cut: Tick): void => { + const g = store.begin('Cross dissolve length'); + let len = store.elementById(id)?.el.dissolveIn ?? 0; + const base = len; + trackPointer(core, e, { + move(ev) { + len = Math.round(2 * Math.abs(core.geo.t(core.point(ev).x) - cut)); + g.preview((d) => setDissolveOp(d, id, len)); + }, + end() { + g.abort(); + if (len !== base) store.transact('Cross dissolve length', (d) => setDissolveOp(d, id, len)); + core.sync(); + }, + cancel() { + g.abort(); + core.sync(); + }, + }, false); + }; + + const slip = (e: PointerEvent, id: string): void => { + const found = store.elementById(id); + if (!found || !isMedia(found.el) || !slipRange(found.el)) return; + const el = found.el; + const x0 = e.clientX; + const g = store.begin('Slip clip'); + core.keep.add(id); + let src = 0; + trackPointer(core, e, { + move(ev) { + src = Math.round(((x0 - ev.clientX) / core.geo.ppt) * el.speed); + src = snapToFrame(src, store.doc.fps); + g.preview((d) => slipOp(d, id, src)); + }, + end() { + core.keep.delete(id); + g.abort(); + if (src !== 0) store.transact('Slip clip', (d) => slipOp(d, id, src)); + core.sync(); + }, + cancel() { + core.keep.delete(id); + g.abort(); + core.sync(); + }, + }, false); + }; + + const slide = (e: PointerEvent, id: string): void => { + if (!slideRange(store.doc, id)) return; + const x0 = e.clientX; + const origin = core.scrollX(); + const g = store.begin('Slide clip'); + core.keep.add(id); + let dt = 0; + trackPointer(core, e, { + move(ev) { + dt = snapToFrame((ev.clientX - x0 + (core.scrollX() - origin)) / core.geo.ppt, store.doc.fps); + g.preview((d) => slideOp(d, id, dt)); + }, + end() { + core.keep.delete(id); + g.abort(); + if (dt !== 0) store.transact('Slide clip', (d) => slideOp(d, id, dt)); + core.sync(); + }, + cancel() { + core.keep.delete(id); + g.abort(); + core.sync(); + }, + }); + }; + const keysAt = (clipId: string, t: Tick): KeyRef[] => { const f = store.elementById(clipId); if (!f) return []; @@ -318,6 +422,35 @@ export function attachGestures(core: Core, ruler: HTMLElement): void { else if (dia.dataset.element) dragKeys(e, [{ element: dia.dataset.element, prop: dia.dataset.prop as string, key: dia.dataset.kid as string }]); return; } + const xd = target.closest('.fc-etl-xd'); + if (xd) { + e.preventDefault(); + const part = target.closest('[data-xd]')?.dataset.xd; + if (part === 'add') store.transact('Add cross dissolve', (d) => setDissolveOp(d, xd.dataset.id as string, DISSOLVE_DEFAULT)); + else if (part === 'grip') dissolveDrag(e, xd.dataset.id as string, Number(xd.dataset.at)); + return; + } + const lockedClip = clip ? !!store.elementById(clip.dataset.id as string)?.track.locked : false; + if (clip && lockedClip) { + e.preventDefault(); + const id = clip.dataset.id as string; + store.select([id], additive(e) ? 'toggle' : 'replace'); + return; + } + if (clip && e.altKey && !handle && !target.closest('.fc-etl-fade')) { + e.preventDefault(); + const id = clip.dataset.id as string; + if (!store.selection.clips.includes(id)) store.select([id], 'replace'); + if (e.shiftKey) slide(e, id); + else slip(e, id); + return; + } + const fadeGrip = target.closest('.fc-etl-fade'); + if (clip && fadeGrip) { + e.preventDefault(); + fade(e, clip.dataset.id as string, fadeGrip.dataset.fade === 'in' ? 'fadeIn' : 'fadeOut'); + return; + } if (clip && handle) { e.preventDefault(); trim(e, clip.dataset.id as string, handle.dataset.edge === 'start' ? 'start' : 'end'); diff --git a/frontend/src/ui/edit/timeline/icons.ts b/frontend/src/ui/edit/timeline/icons.ts index d10a688..d7b3680 100644 --- a/frontend/src/ui/edit/timeline/icons.ts +++ b/frontend/src/ui/edit/timeline/icons.ts @@ -29,6 +29,13 @@ export const TL_ICONS: Record = { speed: wrap(''), close: wrap(''), plus: wrap(''), + dissolve: wrap(''), + freeze: wrap(''), + reverse: wrap(''), + lock: wrap(''), + unlock: wrap(''), + solo: wrap(''), + loop: wrap(''), }; export function tlIcon(name: string, size = 16): string { diff --git a/frontend/src/ui/edit/timeline/index.ts b/frontend/src/ui/edit/timeline/index.ts index 9eef591..d434008 100644 --- a/frontend/src/ui/edit/timeline/index.ts +++ b/frontend/src/ui/edit/timeline/index.ts @@ -1,18 +1,23 @@ import '../../../styles/edit-timeline.css'; import { TICKS_PER_SECOND, type Tick } from '../../../engine/edit/types'; -import { mountOnce, setClass, setHidden, setStyleVar } from '../../dom'; +import { mountOnce, setClass, setHidden, setStyleVar, setText } from '../../dom'; +import { t } from '../../i18n'; import type { SlotMount } from '../context'; import { createActions } from './actions'; +import { openAddMenu } from './add'; import { createBookmarks } from './bookmarks'; import { Clips } from './clips'; -import { closePopover, type Core } from './core'; +import { closePopover, trackPointer, type Core } from './core'; +import { syncCuts } from './cuts'; +import { setTrack } from './ops'; +import { setDissolveOp } from '../../../engine/edit/transitions'; import { attachDrops, dropTimeAt } from './drops'; import { attachGestures } from './gestures'; import { openGraph } from './graph'; import { attachKeys } from './keys'; import { Lanes } from './lanes'; -import { closeMenu, openMenu } from './menu'; -import { BOOK_H, Geo, PX_PER_SEC, RULER_H, SCROLL_DEBOUNCE, buildRows, clamp, zoomBounds, zoomToSlider } from './model'; +import { closeMenu, openList, openMenu } from './menu'; +import { BOOK_H, Geo, LANE_MAX, LANE_MIN, PX_PER_SEC, RULER_H, SCROLL_DEBOUNCE, buildRows, clamp, formatClock, zoomBounds, zoomToSlider } from './model'; import { createRuler } from './ruler'; import { openSpeed } from './speed'; import { createToolbar } from './toolbar'; @@ -23,9 +28,10 @@ const TEMPLATE = `
-
+
+
`; @@ -55,6 +61,8 @@ export const mountTimeline: SlotMount = (slot, ctx) => { const head = q('.fc-etl-head'); const snapLine = q('.fc-etl-snap'); const dropLine = q('.fc-etl-drop'); + const rangeBand = q('.fc-etl-range'); + const empty = q('.fc-etl-empty'); const { store } = ctx; const geo = new Geo(); geo.set(store.doc.view.zoom || 1); @@ -166,7 +174,36 @@ export const mountTimeline: SlotMount = (slot, ctx) => { setStyleVar(head, 'transform', `translateX(${x}px)`); } + let held = ''; + function paintHint(): void { + const node = bar.querySelector('.fc-etl-hint'); + const { in: a, out: b } = ctx.transport.range; + let text: string; + if (held === 'alt') text = t('Alt: drag inside a clip to slip its footage. Add Shift to slide the clip between its neighbours.'); + else if (held === 'shift') text = t('Shift: snapping is off while you drag. Shift-click adds to the selection.'); + else if (held === 'mod') text = t('Ctrl or Cmd: click adds to the selection, the wheel zooms around the pointer.'); + else text = t('Drag clips to move, drag their edges to trim, Alt-drag to slip. Hold Shift to skip snapping. Drag on empty space to box-select.'); + if (a !== null || b !== null) text = `${t('In')} ${a === null ? '-' : formatClock(a / TICKS_PER_SECOND)} ${t('Out')} ${b === null ? '-' : formatClock(b / TICKS_PER_SECOND)}${ctx.transport.looping ? ` ${t('Looping')}` : ''} · ${text}`; + setText(node, text); + } + + function paintRange(): void { + const { in: a, out: b } = ctx.transport.range; + if (a === null && b === null) { + setHidden(rangeBand, true); + return; + } + const sx = scroll.scrollLeft; + const x0 = Math.round(geo.x(a ?? 0) - sx); + const x1 = Math.round(geo.x(b ?? store.duration()) - sx); + setHidden(rangeBand, false); + setStyleVar(rangeBand, 'transform', `translateX(${x0}px)`); + setStyleVar(rangeBand, 'width', `${Math.max(2, x1 - x0)}px`); + } + function paintOver(): void { + paintRange(); + setHidden(empty, store.scene.tracks.some((tr) => tr.elements.length > 0)); const sx = scroll.scrollLeft; const sy = scroll.scrollTop; const header = RULER_H + BOOK_H; @@ -200,6 +237,7 @@ export const mountTimeline: SlotMount = (slot, ctx) => { const x0 = sx - 300; const x1 = sx + vw + 300; clips.sync(built.rows, lanes.lanes, x0, x1, selected, keySel, { geo: geo.version, keys: selStamp }, core.keep); + syncCuts(core, built.rows, lanes.lanes, x0, x1); lanes.keyRows(built.rows, x0, x1, keySel); const key = `${sx}|${vw}|${geo.zoom}|${store.doc.fps.num}/${store.doc.fps.den}`; if (key !== rulerKey) { @@ -248,6 +286,7 @@ export const mountTimeline: SlotMount = (slot, ctx) => { if (Math.abs(scroll.scrollLeft - v.scrollX) > 1) scroll.scrollLeft = v.scrollX; if (Math.abs(scroll.scrollTop - v.scrollY) > 1) scroll.scrollTop = v.scrollY; sync(); + paintHint(); }; const offs = [ @@ -258,7 +297,35 @@ export const mountTimeline: SlotMount = (slot, ctx) => { }), store.on('view', applyView), store.on('history', () => toolbar.paint()), + ctx.transport.onState(() => { + paintRange(); + paintHint(); + toolbar.paint(); + }), ]; + const modKeys = (e: KeyboardEvent): void => { + const next = e.altKey ? 'alt' : e.shiftKey ? 'shift' : e.ctrlKey || e.metaKey ? 'mod' : ''; + if (next === held) return; + held = next; + paintHint(); + }; + const blurKeys = (): void => { + if (!held) return; + held = ''; + paintHint(); + }; + window.addEventListener('keydown', modKeys); + window.addEventListener('keyup', modKeys); + window.addEventListener('blur', blurKeys); + offs.push(() => { + window.removeEventListener('keydown', modKeys); + window.removeEventListener('keyup', modKeys); + window.removeEventListener('blur', blurKeys); + }); + empty.addEventListener('click', (e) => { + if ((e.target as HTMLElement).closest('[data-act="add-media"]')) openAddMenu(core, e.target as HTMLElement); + }); + paintHint(); let lastBar = 0; offs.push(ctx.transport.onTick(() => { paintPlayhead(); @@ -297,9 +364,56 @@ export const mountTimeline: SlotMount = (slot, ctx) => { sync(); } else if (b.dataset.act === 'mute') actions.trackFlag(id, 'muted'); else if (b.dataset.act === 'hide') actions.trackFlag(id, 'hidden'); + else if (b.dataset.act === 'solo') actions.trackFlag(id, 'solo'); + else if (b.dataset.act === 'lock') actions.trackFlag(id, 'locked'); + }); + + labels.addEventListener('pointerdown', (e) => { + const grip = (e.target as HTMLElement).closest('.fc-etl-lgrip'); + const label = grip?.closest('.fc-etl-label'); + const row = label ? core.rows.find((r) => r.id === label.dataset.track) : null; + if (e.button !== 0 || !grip || !row) return; + e.preventDefault(); + const id = row.id; + const y0 = e.clientY; + const h0 = row.base; + const lo = LANE_MIN[row.track.type]; + const g = store.begin('Track height'); + let h = h0; + trackPointer(core, e, { + move(ev) { + h = Math.round(clamp(h0 + ev.clientY - y0, lo, LANE_MAX)); + g.preview((d) => setTrack(d, id, { height: h })); + }, + end() { + g.abort(); + if (h !== h0) store.transact('Track height', (d) => setTrack(d, id, { height: h })); + }, + cancel() { + g.abort(); + }, + }, false); }); scroll.addEventListener('contextmenu', (e) => { + const xd = (e.target as HTMLElement).closest('.fc-etl-xd.is-on'); + if (xd) { + e.preventDefault(); + const id = xd.dataset.id as string; + const set = (len: Tick | undefined) => (): void => store.transact(len === undefined ? 'Remove cross dissolve' : 'Cross dissolve length', (d) => setDissolveOp(d, id, len)); + openList( + [ + { label: t('Half a second'), run: set(TICKS_PER_SECOND / 2) }, + { label: t('One second'), run: set(TICKS_PER_SECOND) }, + { label: t('Two seconds'), run: set(2 * TICKS_PER_SECOND) }, + '-', + { label: t('Remove cross dissolve'), danger: true, run: set(undefined) }, + ], + e.clientX, + e.clientY, + ); + return; + } const clip = (e.target as HTMLElement).closest('.fc-etl-clip'); if (!clip) return; e.preventDefault(); diff --git a/frontend/src/ui/edit/timeline/keys.ts b/frontend/src/ui/edit/timeline/keys.ts index 96452fc..7bfc129 100644 --- a/frontend/src/ui/edit/timeline/keys.ts +++ b/frontend/src/ui/edit/timeline/keys.ts @@ -3,6 +3,9 @@ import { TICKS_PER_SECOND } from '../../../engine/edit/types'; import { shortcuts } from '../../../engine/shortcuts'; import { studios } from '../../../engine/studios'; import { anyDialogOpen } from '../../dialogs'; +import { t } from '../../i18n'; +import { toast } from '../../toasts'; +import { lastKeyProp } from '../props/fields'; import { keysValidity, type Actions } from './actions'; import type { Core } from './core'; import { clamp } from './model'; @@ -42,10 +45,25 @@ export function attachKeys(core: Core, actions: Actions): () => void { 'edit.duplicate': () => actions.duplicate(), 'edit.undo': () => store.undo(), 'edit.redo': () => store.redo(), + 'edit.dissolve': () => actions.dissolve(), + 'edit.freeze': () => actions.freeze(), + 'edit.reverse': () => actions.reverse(), + 'edit.lockTrack': () => actions.lockTracks(), 'edit.extractAudio': () => actions.extract(), 'edit.recoverAudio': () => actions.recover(), 'edit.mute': () => actions.mute(), 'edit.hide': () => actions.hide(), + 'edit.markIn': () => ctx.transport.setRange(core.playhead(), ctx.transport.range.out), + 'edit.markOut': () => ctx.transport.setRange(ctx.transport.range.in, core.playhead()), + 'edit.clearInOut': () => ctx.transport.setRange(null, null), + 'edit.loop': () => ctx.transport.setLoop(!ctx.transport.looping), + 'edit.cut': () => actions.cut(), + 'edit.toggleKey': () => { + const last = lastKeyProp(); + const sel = store.selection.clips; + if (last && sel.length === 1 && sel[0] === last.id && store.elementById(last.id)) store.toggleKey(last.id, last.prop, core.playhead()); + else toast(t('Click a property of the selected clip first, then press the key again.'), 'info', { key: 'edit-toggle-key' }); + }, 'edit.copy': () => actions.copy(), 'edit.paste': () => actions.paste(), 'edit.selectAll': () => actions.selectAll(), diff --git a/frontend/src/ui/edit/timeline/lanes.ts b/frontend/src/ui/edit/timeline/lanes.ts index 0e4dc29..a70fb70 100644 --- a/frontend/src/ui/edit/timeline/lanes.ts +++ b/frontend/src/ui/edit/timeline/lanes.ts @@ -6,10 +6,10 @@ import { tlIcon } from './icons'; import { patchKeyed } from './keyed'; import { DIAMOND, KEY_ROW_H, type Row } from './model'; -const LANE = '
'; +const LANE = '
'; const LABEL = (): string => - `
`; + `
`; interface Dia { element: string; @@ -81,12 +81,21 @@ export class Lanes { const mute = label.querySelector('[data-act="mute"]') as HTMLElement; const hide = label.querySelector('[data-act="hide"]') as HTMLElement; const expand = label.querySelector('[data-act="expand"]') as HTMLElement; + const solo = label.querySelector('[data-act="solo"]') as HTMLElement; + const lock = label.querySelector('[data-act="lock"]') as HTMLElement; setHidden(mute, !(audio || tr.type === 'video')); + setHidden(solo, !(audio || tr.type === 'video')); setHidden(hide, audio); setClass(mute, 'is-on', tr.muted); + setClass(solo, 'is-on', !!tr.solo); setClass(hide, 'is-on', tr.hidden); + setClass(lock, 'is-on', !!tr.locked); setTitle(mute, tr.muted ? t('Unmute track') : t('Mute track')); + setTitle(solo, tr.solo ? t('Stop solo') : t('Solo: hear only this track')); setTitle(hide, tr.hidden ? t('Show track') : t('Hide track')); + setTitle(lock, tr.locked ? t('Unlock track') : t('Lock track')); + setClass(lane, 'is-locked', !!tr.locked); + setAttr(label, 'data-tall', String(row.base >= 46)); setHidden(expand, row.props.length === 0); setClass(expand, 'is-open', row.open); setAttr(expand, 'aria-expanded', String(row.open)); diff --git a/frontend/src/ui/edit/timeline/menu.ts b/frontend/src/ui/edit/timeline/menu.ts index 823cbf0..ada2663 100644 --- a/frontend/src/ui/edit/timeline/menu.ts +++ b/frontend/src/ui/edit/timeline/menu.ts @@ -1,6 +1,10 @@ +import { patchElementOp } from '../../../engine/edit/ops-clip'; +import { DISSOLVE_DEFAULT, nextAt, setDissolveOp } from '../../../engine/edit/transitions'; +import { TICKS_PER_SECOND } from '../../../engine/edit/types'; import { shortcuts } from '../../../engine/shortcuts'; import { el as html, setText } from '../../dom'; import { t } from '../../i18n'; +import { placeFloating, pointTarget } from '../../position'; import { selectedElements, splitTargets, type Actions } from './actions'; import type { Core } from './core'; import { isMedia } from './model'; @@ -29,6 +33,10 @@ function build(core: Core, actions: Actions, clipId: string): (Item | '-')[] { { label: t('Delete'), hint: key('edit.delete'), run: () => actions.remove(), danger: true }, { label: t('Duplicate'), hint: key('edit.duplicate'), run: () => actions.duplicate() }, '-', + { label: t('Cut'), hint: key('edit.cut'), run: () => actions.cut() }, + { label: t('Copy'), hint: key('edit.copy'), run: () => actions.copy() }, + { label: t('Paste'), hint: key('edit.paste'), run: () => actions.paste() }, + '-', ]; if (sel.some((e) => e.kind === 'video' && e.hasAudio && !e.audioExtracted)) items.push({ label: t('Extract audio'), hint: key('edit.extractAudio'), run: () => actions.extract() }); if (sel.some((e) => e.kind === 'video' && e.audioExtracted)) items.push({ label: t('Recover audio'), hint: key('edit.recoverAudio'), run: () => actions.recover() }); @@ -36,9 +44,38 @@ function build(core: Core, actions: Actions, clipId: string): (Item | '-')[] { const allHidden = sel.length > 0 && sel.every((e) => e.hidden); items.push({ label: allMuted ? t('Unmute') : t('Mute'), hint: key('edit.mute'), run: () => actions.mute() }); items.push({ label: allHidden ? t('Show') : t('Hide'), hint: key('edit.hide'), run: () => actions.hide() }); + if (one) { + const half = Math.round(TICKS_PER_SECOND / 2); + const lane = core.store.elementById(one.id)?.track.elements ?? []; + const prev = lane.find((e) => e.id !== one.id && e.start + e.duration === one.start); + items.push('-'); + items.push({ label: t('Fade in and out'), run: () => core.store.transact('Fade in and out', (d) => patchElementOp(d, one.id, { fadeIn: Math.min(half, Math.floor(one.duration / 2)), fadeOut: Math.min(half, Math.floor(one.duration / 2)) })) }); + if (prev) { + items.push({ + label: t('Dip to black at the cut before'), + run: () => core.store.transact('Dip to black', (d) => patchElementOp(patchElementOp(d, prev.id, { fadeOut: Math.min(half, prev.duration) }), one.id, { fadeIn: Math.min(half, one.duration) })), + }); + } + if (one.fadeIn || one.fadeOut) items.push({ label: t('Remove fades'), run: () => core.store.transact('Remove fades', (d) => patchElementOp(d, one.id, { fadeIn: undefined, fadeOut: undefined })) }); + const track = core.store.elementById(one.id)?.track; + const next = track ? nextAt(track, one) : null; + if (prev && one.dissolveIn) items.push({ label: t('Remove cross dissolve before'), run: () => core.store.transact('Remove cross dissolve', (d) => setDissolveOp(d, one.id, undefined)) }); + else if (prev) items.push({ label: t('Cross dissolve at the cut before'), hint: key('edit.dissolve'), run: () => core.store.transact('Add cross dissolve', (d) => setDissolveOp(d, one.id, DISSOLVE_DEFAULT)) }); + if (next && next.dissolveIn) items.push({ label: t('Remove cross dissolve after'), run: () => core.store.transact('Remove cross dissolve', (d) => setDissolveOp(d, next.id, undefined)) }); + else if (next) items.push({ label: t('Cross dissolve at the cut after'), hint: key('edit.dissolve'), run: () => core.store.transact('Add cross dissolve', (d) => setDissolveOp(d, next.id, DISSOLVE_DEFAULT)) }); + } if (one && isMedia(one)) { items.push('-'); - items.push({ label: t('Speed'), run: () => core.openSpeed(one.id, { x: lastX, y: lastY }) }); + const frozen = one.kind === 'video' && !!one.freeze; + if (!frozen) items.push({ label: t('Speed'), run: () => core.openSpeed(one.id, { x: lastX, y: lastY }) }); + if (!frozen) items.push({ label: one.reverse ? t('Play forwards') : t('Play backwards'), run: () => actions.reverse() }); + const at = core.playhead(); + if (one.kind === 'video' && !frozen) items.push({ label: t('Freeze frame'), hint: key('edit.freeze'), off: !(one.start <= at && at < one.start + one.duration), run: () => actions.freeze() }); + } + if (one) { + const locked = !!core.store.elementById(one.id)?.track.locked; + items.push('-'); + items.push({ label: locked ? t('Unlock track') : t('Lock track'), run: () => actions.lockTracks() }); } if (sel.some((e) => 'media' in e)) { items.push('-'); @@ -54,7 +91,20 @@ export function openMenu(core: Core, actions: Actions, clipId: string, x: number closeMenu(); lastX = x; lastY = y; - const list = build(core, actions, clipId); + openList(build(core, actions, clipId), x, y); +} + +export interface ListItem { + label: string; + hint?: string; + run: () => void; + off?: boolean; + danger?: boolean; + attrs?: Record; +} + +export function openList(list: readonly (ListItem | '-')[], x: number, y: number): void { + closeMenu(); const node = html(''); for (const it of list) { if (it === '-') { @@ -65,6 +115,7 @@ export function openMenu(core: Core, actions: Actions, clipId: string, x: number setText(b.querySelector('.cv-menu-label'), it.label); setText(b.querySelector('.cv-menu-keys'), it.hint ?? ''); if (it.danger) b.classList.add('is-danger'); + for (const [k, v] of Object.entries(it.attrs ?? {})) b.setAttribute(k, v); b.disabled = !!it.off; b.addEventListener('click', () => { done(); @@ -75,10 +126,7 @@ export function openMenu(core: Core, actions: Actions, clipId: string, x: number node.addEventListener('contextmenu', (e) => e.preventDefault()); node.addEventListener('pointerdown', (e) => e.preventDefault()); (document.getElementById('overlay-root') ?? document.body).appendChild(node); - const w = node.offsetWidth; - const h = node.offsetHeight; - node.style.left = `${Math.round(Math.max(4, Math.min(x, window.innerWidth - w - 4)))}px`; - node.style.top = `${Math.round(Math.max(4, Math.min(y, window.innerHeight - h - 4)))}px`; + placeFloating(node, pointTarget(x, y), { side: 'bottom', align: 'start' }); panel = node; const off = (e: Event): void => { if (e.target instanceof Node && node.contains(e.target)) return; diff --git a/frontend/src/ui/edit/timeline/model.ts b/frontend/src/ui/edit/timeline/model.ts index 997f1b6..a999d73 100644 --- a/frontend/src/ui/edit/timeline/model.ts +++ b/frontend/src/ui/edit/timeline/model.ts @@ -7,6 +7,14 @@ export const BOOK_H = 16; export const GAP = 6; export const KEY_ROW_H = 20; export const LANE_H: Record = { video: 65, audio: 50, text: 25, graphic: 25, effect: 25 }; +export const LANE_MIN: Record = { video: 46, audio: 46, text: 25, graphic: 25, effect: 25 }; +export const LANE_MAX = 200; + +export function laneHeight(track: EditTrack): number { + const h = track.height; + return h === undefined ? LANE_H[track.type] : Math.round(clamp(h, LANE_MIN[track.type], LANE_MAX)); +} + export const PX_PER_SEC = 50; export const ZOOM_MAX = 100; export const ZOOM_STEP = 1.7; @@ -92,7 +100,7 @@ export function buildRows(tracks: readonly EditTrack[], open: ReadonlySet { const props = animatedProps(track); const isOpen = open.has(track.id) && props.length > 0; - const base = LANE_H[track.type]; + const base = laneHeight(track); const height = base + (isOpen ? props.length * KEY_ROW_H : 0); rows.push({ id: track.id, track, index, top, base, props, open: isOpen, height }); top += height + GAP; diff --git a/frontend/src/ui/edit/timeline/ops.ts b/frontend/src/ui/edit/timeline/ops.ts index a9adc9e..44f671f 100644 --- a/frontend/src/ui/edit/timeline/ops.ts +++ b/frontend/src/ui/edit/timeline/ops.ts @@ -40,7 +40,7 @@ export function placeAbsolute(doc: EditDoc, items: ReadonlyMap): return withScene(doc, { ...scene, tracks }); } -export function setTrack(doc: EditDoc, trackId: string, patch: Partial>): EditDoc { +export function setTrack(doc: EditDoc, trackId: string, patch: Partial>): EditDoc { const scene = currentScene(doc); return withScene(doc, { ...scene, tracks: scene.tracks.map((t) => (t.id === trackId ? { ...t, ...patch } : t)) }); } diff --git a/frontend/src/ui/edit/timeline/speed.ts b/frontend/src/ui/edit/timeline/speed.ts index d08a0fa..993e621 100644 --- a/frontend/src/ui/edit/timeline/speed.ts +++ b/frontend/src/ui/edit/timeline/speed.ts @@ -4,8 +4,8 @@ import { t } from '../../i18n'; import { openPopover, type Core } from './core'; import { clamp, isMedia } from './model'; -const MIN = 0.01; -const MAX = 5; +const MIN = 0.25; +const MAX = 4; export function openSpeed(core: Core, id: string, at: { x: number; y: number }): void { const found = core.store.elementById(id); diff --git a/frontend/src/ui/edit/timeline/toolbar.ts b/frontend/src/ui/edit/timeline/toolbar.ts index a37da1a..52deded 100644 --- a/frontend/src/ui/edit/timeline/toolbar.ts +++ b/frontend/src/ui/edit/timeline/toolbar.ts @@ -1,7 +1,11 @@ +import { allElements, currentScene } from '../../../engine/edit/tracks'; +import { cutNear } from '../../../engine/edit/transitions'; +import { TICKS_PER_SECOND } from '../../../engine/edit/types'; import { el as html, setAttr, setClass, setDisabled, setTitle } from '../../dom'; import { t } from '../../i18n'; import { keysValidity, splitTargets, type Actions } from './actions'; import type { Core } from './core'; +import { openAddMenu } from './add'; import { tlIcon } from './icons'; import { ZOOM_STEP, sliderToZoom, zoomBounds, zoomToSlider } from './model'; @@ -13,17 +17,21 @@ interface Btn { } const GROUPS: Btn[][] = [ + [{ act: 'addMedia', icon: 'plus', label: 'Add media' }], [ { act: 'split', icon: 'split', label: 'Split at the playhead' }, { act: 'splitLeft', icon: 'splitLeft', label: 'Split and remove the left part' }, { act: 'splitRight', icon: 'splitRight', label: 'Split and remove the right part' }, { act: 'remove', icon: 'trash', label: 'Delete' }, { act: 'duplicate', icon: 'duplicate', label: 'Duplicate' }, + { act: 'dissolve', icon: 'dissolve', label: 'Cross dissolve at the nearest cut' }, + { act: 'freeze', icon: 'freeze', label: 'Freeze the frame at the playhead' }, ], [ { act: 'ripple', icon: 'ripple', label: 'Ripple edit', toggle: true }, { act: 'snapping', icon: 'magnet', label: 'Snapping', toggle: true }, { act: 'bookmark', icon: 'bookmark', label: 'Bookmark at the playhead' }, + { act: 'loop', icon: 'loop', label: 'Loop playback', toggle: true }, ], ]; @@ -44,7 +52,7 @@ export function createToolbar(core: Core, host: HTMLElement, actions: Actions): if (i) host.appendChild(html('')); for (const b of group) host.appendChild(button(b)); }); - host.appendChild(html('')); + host.appendChild(html('')); const graph = button({ act: 'graph', icon: 'graph', label: 'Curve editor' }); host.appendChild(graph); host.appendChild(html('')); @@ -63,9 +71,13 @@ export function createToolbar(core: Core, host: HTMLElement, actions: Actions): case 'splitRight': return actions.split('right'); case 'remove': return actions.remove(); case 'duplicate': return actions.duplicate(); + case 'dissolve': return actions.dissolve(); + case 'freeze': return actions.freeze(); case 'ripple': return actions.ripple(); case 'snapping': return actions.snapping(); case 'bookmark': return actions.bookmark(); + case 'loop': return core.ctx.transport.setLoop(!core.ctx.transport.looping); + case 'addMedia': return openAddMenu(core, b); case 'graph': return core.openGraph(graph); case 'zoomOut': return core.zoomTo(core.geo.zoom / ZOOM_STEP); case 'zoomIn': return core.zoomTo(core.geo.zoom * ZOOM_STEP); @@ -86,8 +98,12 @@ export function createToolbar(core: Core, host: HTMLElement, actions: Actions): for (const act of ['split', 'splitLeft', 'splitRight']) setDisabled(buttons.get(act) as HTMLButtonElement, !canSplit); setDisabled(buttons.get('remove') as HTMLButtonElement, !has); setDisabled(buttons.get('duplicate') as HTMLButtonElement, !has); + const at = core.playhead(); + const scene = currentScene(store.doc); + setDisabled(buttons.get('dissolve') as HTMLButtonElement, !cutNear(scene, at, store.selection.clips, 2 * TICKS_PER_SECOND)); + setDisabled(buttons.get('freeze') as HTMLButtonElement, !allElements(scene).some((e) => e.kind === 'video' && !e.freeze && e.start <= at && at < e.start + e.duration)); const view = store.doc.view; - for (const [act, on] of [['ripple', view.ripple], ['snapping', view.snapping]] as const) { + for (const [act, on] of [['ripple', view.ripple], ['snapping', view.snapping], ['loop', core.ctx.transport.looping]] as const) { const n = buttons.get(act) as HTMLButtonElement; setClass(n, 'is-on', on); setAttr(n, 'aria-pressed', String(on)); diff --git a/frontend/src/ui/feed/card.ts b/frontend/src/ui/feed/card.ts index d112ed8..fe12b18 100644 --- a/frontend/src/ui/feed/card.ts +++ b/frontend/src/ui/feed/card.ts @@ -5,6 +5,7 @@ import { t } from '../i18n'; import { trackPlayback } from '../media/audio-player'; import { coverKey, onCover } from '../viewers/cover'; import { clockText, type CardState } from './model'; +import { RESULT_ACTIONS, type ResultAction } from './result-actions'; export const THUMB_W = 512; const REF_W = 256; @@ -34,7 +35,9 @@ export interface CardView { canRetry: boolean; canRecreate: boolean; media: Media | null; - canMakeVideo: boolean; + primary: ResultAction[]; + cost: string; + canAddKey: boolean; viewed: boolean; selected: boolean; selecting: boolean; @@ -62,11 +65,12 @@ const SHELL = `
` + `
` + `` + - `` + + `` + `` + `
` + word('retry', 'Retry', 'refresh') + - word('recreate', 'Recreate', 'create') + + word('recreate', 'Edit prompt', 'pencil') + + word('add-key', 'Add key', 'key') + word('dismiss', 'Dismiss', 'close') + `
` + `
` + @@ -80,11 +84,8 @@ const SHELL = `` + `
` + `
` + - act('recreate', 'Recreate', 'refresh') + - act('make-video', 'Make video', 'video') + - act('download', 'Download', 'download') + - act('copy-prompt', 'Copy prompt', 'copy') + - act('delete', 'Delete', 'trash') + + ``.repeat(3) + + act('more', 'More', 'more') + word('cancel', 'Cancel', 'close') + `
` + `` + @@ -122,6 +123,8 @@ export class Card { private readonly track: HTMLElement; private readonly ptime: HTMLElement; private readonly acts: Record = {}; + private readonly slots: HTMLButtonElement[]; + private readonly cost: HTMLElement; private thumbFor = ''; private coverFor = ''; private refFor = ''; @@ -152,6 +155,8 @@ export class Card { this.pp = q(this.el, '.fc-pp'); this.track = q(this.el, '.fc-track'); this.ptime = q(this.el, '.fc-ptime'); + this.slots = Array.from(this.el.querySelectorAll('.fc-slot')); + this.cost = q(this.el, '.fc-cost'); for (const b of Array.from(this.el.querySelectorAll('.fc-info [data-act]'))) { const name = b.dataset.act ?? ''; (this.acts[name] ??= []).push(b); @@ -212,15 +217,21 @@ export class Card { setAttr(this.open, 'aria-label', v.selecting ? `${t('Select')}: ${label}` : `${t('Open')}: ${label}`); } setHidden(this.player, !(media && v.kind === 'audio')); - for (const name of ['recreate', 'download', 'delete']) { - for (const b of this.acts[name]) { - const isIcon = b.classList.contains('fc-act'); - if (name === 'recreate') setHidden(b, isIcon ? !(media && v.canRecreate) : !(v.state === 'failed' && v.canRecreate)); - else setHidden(b, !(media && isIcon)); - } - } - setHidden(this.acts['make-video'][0], !(media && v.canMakeVideo)); - setHidden(this.acts['copy-prompt'][0], !(media && !!v.prompt)); + this.slots.forEach((b, i) => { + const id = media ? v.primary[i] : undefined; + const def = id ? RESULT_ACTIONS.find((a) => a.id === id) : undefined; + setHidden(b, !def); + if (!def || b.dataset.act === def.id) return; + b.dataset.act = def.id; + b.dataset.enTitle = def.text; + b.title = t(def.text); + b.setAttribute('aria-label', t(def.text)); + b.innerHTML = icon(def.icon, 15); + }); + setHidden(this.acts.more[0], !media); + setHidden(this.acts.recreate[0], !(v.state === 'failed' && v.canRecreate)); + setHidden(this.acts['add-key'][0], !(v.state === 'failed' && v.canAddKey)); + setText(this.cost, v.cost); setHidden(this.acts.cancel[0], !(v.state === 'pending' && v.canCancel)); setAttr(this.acts.cancel[0], 'aria-disabled', v.cancelling ? 'true' : null); setText(q(this.acts.cancel[0], 'span:last-child'), t(v.cancelling ? 'Cancelling' : 'Cancel')); diff --git a/frontend/src/ui/feed/feed.ts b/frontend/src/ui/feed/feed.ts index 6c9650f..6a0f985 100644 --- a/frontend/src/ui/feed/feed.ts +++ b/frontend/src/ui/feed/feed.ts @@ -16,8 +16,10 @@ import { failureLabel, failureMessage, FAILED_SHOWN_MS, + jobCost, jobLabel, jobProgress, + needsKey, jobPrompt, jobRatio, mediaRatio, @@ -33,8 +35,9 @@ import { type CardState, } from './model'; import { feedPrefs, lastViewed, onFeedPrefs, rememberViewed, setFeedAutoplay, setFeedView } from './prefs'; +import { addListToBoard, openResultMenu, primaryActions, recreateFrom, runResultAction, tagMedia, type ResultAction } from './result-actions'; -export type FeedAction = 'recreate' | 'make-video' | 'download' | 'delete' | 'copy-prompt' | 'open' | 'cancel' | 'dismiss' | 'retry'; +export type FeedAction = ResultAction | 'open' | 'cancel' | 'dismiss' | 'retry' | 'more' | 'add-key'; export interface FeedItem { job?: Job; media?: Media } export interface FeedOptions { page: string; @@ -123,12 +126,6 @@ const learnJobs = (): Promise => const SHELL = `
` + `
` + - `` + `` + `` + `
` + + `
` + + `` + + `
` + `
`; export class Feed { @@ -248,6 +255,7 @@ export class Feed { this.el.addEventListener('click', (ev) => this.onClick(ev)); this.el.addEventListener('keydown', (ev) => this.onKey(ev)); + this.el.addEventListener('contextmenu', (ev) => this.onContext(ev)); this.el.addEventListener('pointerover', (ev) => this.onOver(ev)); this.el.addEventListener('pointerleave', () => this.cool()); this.el.addEventListener( @@ -524,7 +532,9 @@ export class Feed { canRetry: false, canRecreate: false, media: m, - canMakeVideo: false, + primary: [], + cost: '', + canAddKey: false, viewed: false, selected: false, selecting: this.selecting, @@ -538,7 +548,7 @@ export class Feed { v.model = m.jobId ? (job ? this.labelOf(job) : (this.labels.get(m.jobId) ?? '')) : ''; v.when = ago(ts, now); v.whenTitle = ts ? new Date(ts).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : ''; - v.canMakeVideo = m.kind === 'image'; + v.primary = primaryActions(m); v.canRecreate = !!(m.jobId || m.prompt); v.viewed = m.id === this.viewed; v.selected = this.selected.has(m.id); @@ -556,9 +566,11 @@ export class Feed { v.when = ago(stamp(job.finishedAt ?? job.updatedAt), now); v.canRetry = Object.keys(requestOf(job)).length > 0; v.canRecreate = Object.keys(requestOf(job)).length > 0; + v.canAddKey = needsKey(job); return v; } Object.assign(v, this.status(job, now)); + v.cost = v.details ? jobCost(job) : ''; v.when = ago(stamp(job.createdAt), now); v.canCancel = v.details && !this.settling.has(job.id); v.cancelling = this.cancelling.has(job.id); @@ -909,7 +921,7 @@ export class Feed { setHidden(this.selbar, !this.selecting); const n = this.selected.size; setText(this.selcount, tn(n, '{n} selected', '{n} selected')); - for (const b of Array.from(this.selbar.querySelectorAll('[data-tool="download"], [data-tool="delete"]'))) setAttr(b, 'aria-disabled', n === 0 ? 'true' : null); + for (const b of Array.from(this.selbar.querySelectorAll('[data-tool="download"], [data-tool="delete"], [data-tool="board"], [data-tool="tag"]'))) setAttr(b, 'aria-disabled', n === 0 ? 'true' : null); setClass(this.el, 'is-selecting', this.selecting); this.paintNew(); } @@ -988,6 +1000,9 @@ export class Feed { void saveMedia(Array.from(this.selected)).then(() => this.setSelecting(false)); } else if (tool === 'delete') { void this.deleteMedia(Array.from(this.selected)); + } else if (tool === 'board' || tool === 'tag') { + const picked = this.order.filter((s) => s.media && this.selected.has(s.media.id)).map((s) => s.media as Media); + void (tool === 'board' ? addListToBoard(picked) : tagMedia(picked)).then(() => this.setSelecting(false)); } } @@ -1022,14 +1037,16 @@ export class Feed { if (!media) return; this.markViewed(media.id); this.opts.onAction('open', { media, job }); - } else if (action === 'recreate' || action === 'make-video') { - if (media || job) this.opts.onAction(action, { media, job }); - } else if (action === 'download') { - if (media) void saveMedia([media.id]); + } else if (action === 'recreate') { + void recreateFrom(media, job); + } else if (action === 'more') { + if (media) this.menuFor(slot, null); + } else if (action === 'add-key') { + this.opts.onAction('add-key', { media, job }); } else if (action === 'delete') { if (media) void this.deleteMedia([media.id]); - } else if (action === 'copy-prompt') { - const text = media?.prompt ?? (job ? jobPrompt(job) : ''); + } else if (action === 'copy-prompt' && !media) { + const text = job ? jobPrompt(job) : ''; if (text) void this.copy(text); } else if (action === 'cancel') { if (job) void this.cancel(job); @@ -1037,9 +1054,30 @@ export class Feed { if (job) void this.dismiss(job); } else if (action === 'retry') { if (job) void this.retry(job); + } else if (media) { + void runResultAction(action, media, job); } } + private menuFor(slot: Slot, at: { x: number; y: number } | null): void { + const media = slot.media; + if (!media || slot.state !== 'media') return; + const more = slot.card.el.querySelector('[data-act="more"]'); + const r = more && !at ? more.getBoundingClientRect() : null; + const x = at ? at.x : r ? r.right : 0; + const y = at ? at.y : r ? r.bottom + 4 : 0; + const job = slot.jobId ? jobs.get(slot.jobId) : undefined; + openResultMenu(media, x, y, { job, skip: at ? [] : primaryActions(media), returnTo: more ?? slot.card.el, run: (id) => this.perform(id, slot) }); + } + + private onContext(ev: MouseEvent): void { + const cardEl = ev.target instanceof Element ? ev.target.closest('.fc-card') : null; + const slot = cardEl ? this.slotOf.get(cardEl) : undefined; + if (!slot || slot.state !== 'media' || this.selecting) return; + ev.preventDefault(); + this.menuFor(slot, { x: ev.clientX, y: ev.clientY }); + } + private async copy(text: string): Promise { try { await navigator.clipboard.writeText(text); diff --git a/frontend/src/ui/feed/model.ts b/frontend/src/ui/feed/model.ts index c58871c..694a02b 100644 --- a/frontend/src/ui/feed/model.ts +++ b/frontend/src/ui/feed/model.ts @@ -119,22 +119,39 @@ export function slotCount(job: Job, siblings: readonly Job[]): number { } const FAILURES: Record = { - auth: 'Key not accepted', - billing: 'Balance too low', - invalid_input: 'Input not accepted', - content_policy: 'Blocked by content policy', - rate_limited: 'Too many requests', - unavailable: 'Provider unavailable', - network: 'Connection problem', - timeout: 'Timed out', - interrupted: 'Interrupted', - cancelled: 'Cancelled', - provider: 'Generation failed', + auth: 'The provider did not accept your key.', + provider_not_configured: 'There is no key for this provider yet.', + billing: 'Your account at the provider is out of credit.', + invalid_input: 'The provider did not accept one of the inputs.', + content_policy: 'The provider blocked this under its content policy.', + rate_limited: 'The provider is busy with too many requests. Try again in a minute.', + unavailable: 'The provider is not available right now.', + network: 'The connection to the provider was lost.', + timeout: 'This took too long and was stopped.', + interrupted: 'This stopped when formcraft closed.', + cancelled: 'This was cancelled.', + provider: 'The provider could not make this.', }; export function failureLabel(job: Job): string { if (job.status === 'timed_out') return t(FAILURES.timeout); - return t(FAILURES[job.error?.category ?? ''] ?? 'Generation failed'); + return t(FAILURES[job.error?.category ?? ''] ?? 'The provider could not make this.'); +} + +export function needsKey(job: Job): boolean { + const c = job.error?.category ?? ''; + return c === 'auth' || c === 'provider_not_configured'; +} + +export function jobCost(job: Job): string { + const remote = rec(job.payload.remote); + const usd = rec(remote.cost).usd; + const of = typeof remote.of === 'number' && remote.of > 0 ? remote.of : 1; + if (typeof usd !== 'number' || !Number.isFinite(usd)) return ''; + if (usd <= 0) return t('Free'); + const each = usd / of; + const text = each < 0.01 ? '< $0.01' : `$${each.toFixed(each < 1 ? 3 : 2).replace(/0$/, '')}`; + return t('about {price}').replace('{price}', text); } export function failureMessage(job: Job): string { diff --git a/frontend/src/ui/feed/result-actions.ts b/frontend/src/ui/feed/result-actions.ts new file mode 100644 index 0000000..87156d5 --- /dev/null +++ b/frontend/src/ui/feed/result-actions.ts @@ -0,0 +1,282 @@ +import '../../styles/library-studio.css'; +import { queueForEdit } from '../../engine/edit-handoff'; +import { makeObject, makeVideo, makeWorld, recreate, toRemoveBackground } from '../../engine/handoff'; +import { jobs } from '../../engine/jobs'; +import { models } from '../../engine/models'; +import { isCreatePage, promptStore, type CreatePageId } from '../../engine/prompt-store'; +import { studios } from '../../engine/studios'; +import { ApiError, generate, getJob, mediaFileUrl, type GenerateRequest, type Job, type Media, type MediaKind } from '../../io/api'; +import { applyTags } from '../../io/api-library'; +import { dropMediaOnBoard } from '../board'; +import { canvasApi, editInCanvas } from '../canvas/base/bridge'; +import { addCentred } from '../canvas/base/place'; +import { confirmAndDelete } from '../delete-media'; +import { t, tn } from '../i18n'; +import { ContextMenu, type MenuRow } from '../library/context-menu'; +import { editTags } from '../library/tag-editor'; +import { inDesktop } from '../prefs'; +import { saveMedia } from '../save-media'; +import { openInScene } from '../scene/bridge'; +import { toast } from '../toasts'; + +export type ResultAction = + | 'recreate' | 'variations' | 'edit-image' | 'make-video' | 'remove-background' | 'upscale' | 'make-object' | 'make-world' + | 'open-scene' | 'add-to-canvas' | 'add-to-board' | 'add-to-edit' | 'use-reference' | 'download' | 'reveal' | 'copy' | 'copy-prompt' | 'delete'; + +export interface ResultActionDef { id: ResultAction; text: string; icon: string; danger?: boolean } + +export const RESULT_ACTIONS: readonly ResultActionDef[] = [ + { id: 'recreate', text: 'Recreate', icon: 'refresh' }, + { id: 'variations', text: 'Variations', icon: 'layers' }, + { id: 'edit-image', text: 'Edit image', icon: 'pencil' }, + { id: 'make-video', text: 'Make video', icon: 'video' }, + { id: 'remove-background', text: 'Remove background', icon: 'removeBackground' }, + { id: 'upscale', text: 'Upscale', icon: 'capMax' }, + { id: 'make-object', text: 'Make 3D model', icon: 'cube' }, + { id: 'make-world', text: 'Make 3D world', icon: 'globe' }, + { id: 'open-scene', text: 'Add to scene', icon: 'scene' }, + { id: 'add-to-canvas', text: 'Add to canvas', icon: 'canvas' }, + { id: 'add-to-board', text: 'Add to board', icon: 'board' }, + { id: 'add-to-edit', text: 'Add to edit timeline', icon: 'edit' }, + { id: 'use-reference', text: 'Use as reference', icon: 'plus' }, + { id: 'download', text: 'Download', icon: 'download' }, + { id: 'reveal', text: 'Show in folder', icon: 'folderOpen' }, + { id: 'copy', text: 'Copy image', icon: 'copy' }, + { id: 'copy-prompt', text: 'Copy prompt', icon: 'copy' }, + { id: 'delete', text: 'Delete', icon: 'trash', danger: true }, +]; + +const PRIMARY: Record = { + image: ['recreate', 'edit-image', 'make-video'], + video: ['recreate', 'add-to-edit', 'download'], + audio: ['recreate', 'add-to-edit', 'download'], + model: ['recreate', 'open-scene', 'download'], + splat: ['recreate', 'open-scene', 'download'], + other: ['download'], +}; + +const PAGE_OF: Partial> = { image: 'image', video: 'video', audio: 'audio', model: 'object', splat: 'world' }; +const UPSCALE = 'upscale'; + +const generated = (m: Media): boolean => m.source === 'generated' && !!(m.jobId || m.prompt); + +export function applies(id: ResultAction, m: Media): boolean { + const k = m.kind; + switch (id) { + case 'recreate': return generated(m) && !!PAGE_OF[k]; + case 'variations': return m.source === 'generated' && !!m.jobId && !!PAGE_OF[k]; + case 'edit-image': case 'make-video': case 'remove-background': case 'make-object': case 'make-world': case 'add-to-canvas': case 'use-reference': case 'copy': + return k === 'image'; + case 'upscale': return k === 'image' && models.list(UPSCALE).length > 0; + case 'open-scene': return k === 'model' || k === 'splat' || k === 'image' || k === 'video'; + case 'add-to-board': return k === 'image' || k === 'video' || k === 'audio' || k === 'model'; + case 'add-to-edit': return k === 'image' || k === 'video' || k === 'audio'; + case 'reveal': return inDesktop(); + case 'copy-prompt': return !!m.prompt; + default: return true; + } +} + +export const applicableActions = (m: Media): ResultActionDef[] => RESULT_ACTIONS.filter((a) => applies(a.id, m)); + +export function primaryActions(m: Media): ResultAction[] { + const want = PRIMARY[m.kind] ?? PRIMARY.other; + return RESULT_ACTIONS.filter((a) => want.includes(a.id) && applies(a.id, m)).map((a) => a.id); +} + +const reason = (err: unknown, fallback: string): string => (err instanceof ApiError && err.message ? err.message : err instanceof Error && err.message ? err.message : t(fallback)); + +const newId = (): string => (typeof crypto !== 'undefined' && 'randomUUID' in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`); + +async function requestFor(m: Media, job?: Job): Promise | null> { + const source = job ?? (m.jobId ? (jobs.get(m.jobId) ?? (await getJob(m.jobId).catch(() => null))) : null); + const raw = source?.payload.request; + return raw && typeof raw === 'object' ? (raw as Partial) : null; +} + +export async function recreateFrom(m: Media | undefined, job?: Job): Promise { + const fallback = (m && PAGE_OF[m.kind]) || (job && isCreatePage(job.payload.page) ? job.payload.page : 'image'); + const request = m ? await requestFor(m, job) : job ? ((job.payload.request as Partial | undefined) ?? null) : null; + if (request && typeof request.prompt === 'string') { + const done = recreate(request, fallback); + if (!done.modelFound) toast(t('The model used for this item is no longer offered. Your other choices were restored.'), 'info', { key: 'result-model-gone' }); + return; + } + if (m?.prompt) { + recreate({ page: fallback, prompt: m.prompt }, fallback); + return; + } + toast(t('This item has no saved prompt to recreate it from.'), 'error', { key: 'result-no-prompt' }); +} + +export async function retryJob(job: Job): Promise { + const request = job.payload.request as GenerateRequest | undefined; + if (!request || !request.model) return []; + try { + const made = (await generate({ ...request, clientRequestId: newId() })).jobs; + void jobs.dismiss(job.id).catch(() => undefined); + return made; + } catch (err) { + toast(reason(err, 'The request could not be sent.'), 'error', { key: `result-retry:${job.id}` }); + return []; + } +} + +async function variations(m: Media): Promise { + const request = await requestFor(m); + if (!request || !request.model || !request.page) { + toast(t('This item has no saved recipe to make variations from.'), 'error', { key: 'result-variations' }); + return; + } + const options = { ...(request.options ?? {}) }; + delete options.seed; + try { + await generate({ ...(request as GenerateRequest), options, clientRequestId: newId() }); + if (isCreatePage(request.page)) studios.activate(request.page); + toast(t('Making variations.'), 'success', { key: 'result-variations' }); + } catch (err) { + toast(reason(err, 'The request could not be sent.'), 'error', { key: 'result-variations' }); + } +} + +async function upscale(m: Media): Promise { + const id = models.defaultFor(UPSCALE) ?? models.list(UPSCALE)[0]?.id; + if (!id) return; + try { + await generate({ model: id, page: UPSCALE, prompt: '', media: { sourceImage: m.id }, subscriberId: 'tool:upscale', clientRequestId: newId() }); + toast(t('Upscaling. The larger picture lands in your library.'), 'success', { key: 'result-upscale' }); + } catch (err) { + toast(reason(err, 'The request could not be sent.'), 'error', { key: 'result-upscale' }); + } +} + +async function addToCanvas(m: Media): Promise { + try { + const ctx = await canvasApi(); + if (!ctx.store.base) { + await editInCanvas(m); + return; + } + studios.activate('canvas'); + await addCentred(ctx, [m]); + } catch { + await editInCanvas(m); + } +} + +async function addToBoard(list: readonly Media[]): Promise { + studios.activate('board'); + const ok = await dropMediaOnBoard(Array.from(list), window.innerWidth / 2, window.innerHeight / 2); + if (!ok) toast(t('Those items could not be added to the board.'), 'error', { key: 'result-board' }); +} + +function useReference(m: Media): void { + const page = promptStore.get('image'); + const now = page.media.referenceImages; + const have = Array.isArray(now) ? now : typeof now === 'string' ? [now] : []; + const media = { ...page.media, referenceImages: have.includes(m.id) ? have : [...have, m.id] }; + promptStore.patch('image', { media, mode: 'reference' }, 'handoff'); + studios.activate('image'); +} + +async function copyImage(m: Media): Promise { + try { + const blob = await (await fetch(mediaFileUrl(m.id))).blob(); + const png = blob.type === 'image/png' ? blob : await toPng(blob); + await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })]); + toast(t('Image copied.'), 'success', { key: 'result-copy' }); + } catch { + toast(t('The image could not be copied.'), 'error', { key: 'result-copy' }); + } +} + +async function toPng(blob: Blob): Promise { + const bmp = await createImageBitmap(blob); + const c = document.createElement('canvas'); + c.width = bmp.width; + c.height = bmp.height; + c.getContext('2d')?.drawImage(bmp, 0, 0); + bmp.close(); + return new Promise((resolve, reject) => c.toBlob((b) => (b ? resolve(b) : reject(new Error('png'))), 'image/png')); +} + +async function copyPrompt(text: string): Promise { + try { + await navigator.clipboard.writeText(text); + toast(t('Prompt copied.'), 'success', { key: 'result-copy' }); + } catch { + toast(t('The prompt could not be copied.'), 'error', { key: 'result-copy' }); + } +} + +async function reveal(m: Media): Promise { + const { LibraryActions } = await import('../library/library-actions'); + const view = { folderId: () => null, lookup: () => [], items: () => [], patch: () => undefined, drop: () => undefined, scrub: () => undefined, reload: () => undefined, gone: () => undefined }; + await new LibraryActions(view).reveal(m); +} + +export async function tagMedia(list: readonly Media[]): Promise { + if (!list.length) return; + const edit = await editTags(list); + if (!edit) return; + try { + await applyTags(list.map((m) => m.id), edit.add, edit.remove); + toast(tn(list.length, 'Tags saved for {n} item.', 'Tags saved for {n} items.'), 'success', { key: 'result-tags' }); + } catch (err) { + toast(reason(err, 'The tags could not be saved.'), 'error', { key: 'result-tags' }); + } +} + +export const addListToBoard = (list: readonly Media[]): Promise => addToBoard(list); + +export async function runResultAction(id: ResultAction, m: Media, job?: Job): Promise { + switch (id) { + case 'recreate': await recreateFrom(m, job); break; + case 'variations': await variations(m); break; + case 'edit-image': await editInCanvas(m); break; + case 'make-video': makeVideo(m.id); break; + case 'remove-background': + if (!toRemoveBackground(m)) toast(t('The Remove background tool could not be opened.'), 'error', { key: 'result-rmbg' }); + break; + case 'upscale': await upscale(m); break; + case 'make-object': makeObject(m.id); break; + case 'make-world': makeWorld(m.id); break; + case 'open-scene': await openInScene(m); break; + case 'add-to-canvas': await addToCanvas(m); break; + case 'add-to-board': await addToBoard([m]); break; + case 'add-to-edit': + queueForEdit([m.id]); + studios.activate('edit'); + break; + case 'use-reference': useReference(m); break; + case 'download': await saveMedia([m.id]); break; + case 'reveal': await reveal(m); break; + case 'copy': await copyImage(m); break; + case 'copy-prompt': if (m.prompt) await copyPrompt(m.prompt); break; + case 'delete': return confirmAndDelete([m.id]); + } + return []; +} + +export const LEAVES: ReadonlySet = new Set([ + 'recreate', 'variations', 'edit-image', 'make-video', 'remove-background', 'make-object', 'make-world', 'open-scene', 'add-to-canvas', 'add-to-board', 'add-to-edit', 'use-reference', +]); + +let menu: ContextMenu | null = null; + +export function openResultMenu(m: Media, x: number, y: number, opts: { job?: Job; skip?: readonly ResultAction[]; returnTo?: HTMLElement | null; run?: (id: ResultAction) => void; lead?: readonly MenuRow[] } = {}): void { + menu ??= new ContextMenu(); + const rows: MenuRow[] = opts.lead?.length ? [...opts.lead, '-'] : []; + const head = rows.length; + let tail = false; + for (const a of applicableActions(m)) { + if (opts.skip?.includes(a.id)) continue; + if (!tail && (a.id === 'download' || a.id === 'reveal' || a.id === 'copy' || a.id === 'copy-prompt' || a.id === 'delete')) { + tail = true; + if (rows.length > head) rows.push('-'); + } + if (a.id === 'delete' && rows.length > head && rows[rows.length - 1] !== '-') rows.push('-'); + rows.push({ id: a.id, label: a.text, icon: a.icon, danger: a.danger, run: () => (opts.run ? opts.run(a.id) : void runResultAction(a.id, m, opts.job)) }); + } + if (rows.length > head) menu.open(x, y, rows, opts.returnTo ?? null); +} diff --git a/frontend/src/ui/first-run.ts b/frontend/src/ui/first-run.ts new file mode 100644 index 0000000..35291c0 --- /dev/null +++ b/frontend/src/ui/first-run.ts @@ -0,0 +1,145 @@ +import { hooks } from '../app'; +import { commands } from '../engine/commands'; +import { getKeys } from '../io/api'; +import { anyDialogOpen, Dialog } from './dialogs'; +import { el, escapeHtml, q, setHidden, setText } from './dom'; +import { t } from './i18n'; +import { icon } from './icons'; +import { readChoice, setTheme, THEMES } from './themes'; + +const DONE_KEY = 'formcraft.welcome.done'; +const PICKS = ['studio', 'nodemode-dark', 'midnight', 'light', 'sand', 'contrast']; + +export interface WelcomeHooks { + explore(): void; +} + +const tx = (s: string, cls: string, tag = 'p'): string => `<${tag} class="${cls}" data-en="${escapeHtml(s)}">${escapeHtml(t(s))}`; + +function seen(): boolean { + try { + return localStorage.getItem(DONE_KEY) === '1'; + } catch { + return true; + } +} + +function markSeen(): void { + try { + localStorage.setItem(DONE_KEY, '1'); + } catch { + return; + } +} + +function stepsHtml(): string { + const swatches = PICKS.filter((id) => THEMES[id]) + .map((id) => ``) + .join(''); + return ( + `
` + + `
` + + tx('Make pictures, video, sound, 3D models and worlds, then stage and cut them in one app.', 'fc-wl-lead') + + tx('Generation runs on your own fal and World Labs keys, so you pay the services directly. Your projects and library stay on this computer.', 'fc-wl-body') + + tx('You can look around, open demos, build 3D scenes and edit video without any key.', 'fc-wl-body') + + `
` + + `` + + `
` + ); +} + +class Welcome { + private readonly d = new Dialog('Welcome to formcraft', 560); + private step = 0; + private readonly back: HTMLButtonElement; + private readonly next: HTMLButtonElement; + private readonly root: HTMLElement; + + constructor(private readonly h: WelcomeHooks) { + this.root = el(stepsHtml()); + this.d.body.appendChild(this.root); + for (const s of Array.from(this.root.querySelectorAll('[data-swatch]'))) { + const v = THEMES[s.dataset.swatch ?? '']?.vars; + if (v) s.style.background = `linear-gradient(135deg, ${v['--bg-secondary']} 50%, ${v['--border-color'] ?? v['--bg-tertiary']} 50%)`; + } + this.d.button('Skip', 'ghost', () => this.finish()); + this.back = this.d.button('Back', '', () => this.go(this.step - 1)); + this.next = this.d.button('Next', 'primary', () => (this.step >= 2 ? this.finish() : this.go(this.step + 1))); + this.d.onClose = () => markSeen(); + this.root.addEventListener('click', (e) => { + const target = e.target as Element; + const theme = target.closest('[data-theme-id]')?.dataset.themeId; + if (theme) { + setTheme(theme); + this.paintThemes(); + return; + } + const act = target.closest('[data-wl]')?.dataset.wl; + if (act === 'key') { + this.finish(); + hooks.openPreferences?.('connections'); + } else if (act === 'explore') { + this.finish(); + this.h.explore(); + } + }); + } + + open(): void { + this.go(0); + this.d.open(this.next); + void this.paintKeys(); + } + + private go(n: number): void { + this.step = Math.max(0, Math.min(2, n)); + for (const s of Array.from(this.root.querySelectorAll('.fc-wl-step'))) setHidden(s, s.dataset.step !== String(this.step)); + Array.from(this.root.querySelectorAll('.fc-wl-dots li')).forEach((li, i) => li.classList.toggle('is-on', i <= this.step)); + this.back.disabled = this.step === 0; + this.next.dataset.en = this.step >= 2 ? 'Done' : 'Next'; + setText(this.next, t(this.next.dataset.en)); + if (this.step === 2) this.paintThemes(); + } + + private paintThemes(): void { + const cur = readChoice().theme; + for (const b of Array.from(this.root.querySelectorAll('[data-theme-id]'))) b.setAttribute('aria-pressed', String(b.dataset.themeId === cur)); + } + + private async paintKeys(): Promise { + const line = q(this.root, '.fc-wl-state'); + try { + const k = await getKeys(); + const have = [k.fal?.set ? 'fal' : '', k.worldlabs?.set ? 'World Labs' : ''].filter(Boolean); + setText(line, have.length ? t('Already set: {keys}.').replace('{keys}', have.join(', ')) : t('No key is set yet.')); + } catch { + setText(line, ''); + } + } + + private finish(): void { + markSeen(); + this.d.close(); + } +} + +let welcome: Welcome | null = null; + +export function mountWelcome(h: WelcomeHooks): void { + if (welcome) return; + welcome = new Welcome(h); + commands.register({ id: 'welcome', label: 'Getting Started...', group: 'Help', description: 'Show the three-step welcome again', run: () => welcome?.open() }); + if (seen()) return; + window.setTimeout(() => { + if (!anyDialogOpen()) welcome?.open(); + }, 400); +} diff --git a/frontend/src/ui/help/help-commands.ts b/frontend/src/ui/help/help-commands.ts new file mode 100644 index 0000000..b5be292 --- /dev/null +++ b/frontend/src/ui/help/help-commands.ts @@ -0,0 +1,77 @@ +import { commands, type Command } from '../../engine/commands'; +import { studios } from '../../engine/studios'; +import { capabilities } from '../../io/api'; +import { Dialog } from '../dialogs'; +import { el, escapeHtml } from '../dom'; +import { t } from '../i18n'; +import { inDesktop, invokeHost } from '../prefs'; +import { listDemos, openDemo, type Demo } from '../projects/demos'; +import { revealFile } from '../projects/disk'; +import { toast } from '../toasts'; +import { hasTour, mountTours, startTour, tourIdFor } from './tour'; +import { WHATS_NEW, WHATS_NEW_VERSION } from './whats-new-data'; + +const ISSUES_URL = 'https://github.com/nodemode-dev/formcraft/issues'; +const LOG_FILE = 'formcraft-engine.log'; +const DEMO_MAX = 12; +const DEMO_IDS: readonly string[] = Array.from({ length: DEMO_MAX }, (_, i) => `open-demo-${i}`); + +let demos: Demo[] = []; +let whatsNew: Dialog | null = null; + +function showWhatsNew(): void { + if (!whatsNew) { + whatsNew = new Dialog(t("What's new in {version}").replace('{version}', WHATS_NEW_VERSION), 480); + whatsNew.body.appendChild(el(`
    ${WHATS_NEW.map((line) => `
  • ${escapeHtml(t(line))}
  • `).join('')}
`)); + const d = whatsNew; + d.button('Close', 'primary', () => d.close()); + } + whatsNew.open(); +} + +function openPage(url: string): void { + if (inDesktop()) { + void invokeHost('open_url', { url }).catch(() => toast(t('The page could not be opened.'), 'error', { key: 'help-open-url' })); + return; + } + window.open(url, '_blank', 'noopener,noreferrer'); +} + +async function showLogs(): Promise { + try { + const caps = await capabilities(); + const sep = caps.dataDir.includes('\\') && !caps.dataDir.includes('/') ? '\\' : '/'; + await revealFile(`${caps.dataDir.replace(/[\\/]+$/, '')}${sep}logs${sep}${LOG_FILE}`); + } catch { + toast(t('The logs folder could not be found.'), 'error', { key: 'help-logs' }); + } +} + +export const demoIds = (): string[] => DEMO_IDS.filter((_, i) => i < demos.length); + +export function registerHelpCommands(): void { + mountTours(); + const list: Command[] = [ + { id: 'tour-studio', label: 'Tour This Studio', group: 'Help', description: 'Show the open studio one control at a time. Press Esc to leave.', enabled: () => hasTour(tourIdFor(studios.active)), run: () => void startTour() }, + { id: 'whats-new', label: () => t("What's New in {version}...").replace('{version}', WHATS_NEW_VERSION), group: 'Help', run: showWhatsNew }, + { id: 'report-problem', label: 'Report a Problem...', group: 'Help', description: 'Opens the formcraft issues page in your browser.', run: () => openPage(ISSUES_URL) }, + { id: 'show-logs', label: 'Show Logs Folder', group: 'Help', description: 'Shows the engine log in the file manager.', run: () => void showLogs() }, + ...DEMO_IDS.map((id, i): Command => ({ + id, + label: () => demos[i]?.title ?? t('No demo is installed.'), + group: 'Help', + enabled: () => i < demos.length, + run: () => { + const d = demos[i]; + if (d) void openDemo(d.id); + }, + })), + ]; + const fresh = list.filter((c) => !commands.get(c.id)); + if (!fresh.length) return; + commands.register(fresh); + void listDemos().then((found) => { + demos = found.slice(0, DEMO_MAX); + commands.refresh(); + }); +} diff --git a/frontend/src/ui/help/tour-steps.ts b/frontend/src/ui/help/tour-steps.ts new file mode 100644 index 0000000..083c1e1 --- /dev/null +++ b/frontend/src/ui/help/tour-steps.ts @@ -0,0 +1,49 @@ +import type { Side } from '../position'; + +export interface TourStep { + target: readonly string[]; + title: string; + body: string; + side?: Side; +} + +export const TOURS: Record = { + create: [ + { target: ['.fc-cr-pages'], title: 'Pick what to make', body: 'Image, Video, Audio, 3D model and World each have a page of their own. Your prompt and settings stay with each page.' }, + { target: ['.fc-pb-main'], title: 'Describe it', body: 'Type what you want to see or hear in plain words. Press Enter to start, or Shift and Enter for a new line.', side: 'top' }, + { target: ['.fc-deck-add'], title: 'Add references', body: 'Give the model pictures, video or sound to follow. Drop files here or pick them from the library.', side: 'right' }, + { target: ['.fc-pb-toolbar .fc-mp-pill'], title: 'Choose a model and its settings', body: 'Each model has its own strengths and price. The pills next to it set the shape, size and number of results.', side: 'top' }, + { target: ['.fc-pb-gen'], title: 'Generate', body: 'Starts the run and shows the estimated cost first. Without a key this button opens Preferences at Connections.', side: 'top' }, + { target: ['.fc-cr-tool[data-act="help"]'], title: 'Tips for this page', body: 'Short notes on writing prompts and on what each setting does.', side: 'top' }, + ], + canvas: [ + { target: ['.fc-cg-empty-acts'], title: 'Start with a picture', body: 'Bring in pictures from your computer or the library, or start from a blank page of the size you choose.', side: 'right' }, + { target: ['.fc-cvt'], title: 'Tools', body: 'Select, move, paint, erase and draw shapes. Hover a tool to see its shortcut.', side: 'right' }, + { target: ['.fc-cv-layers'], title: 'Layers', body: 'Every picture sits on a layer. Drag to reorder, and hide or lock what you are not working on.', side: 'left' }, + { target: ['.fc-cg-gen'], title: 'Generate on the canvas', body: 'Describe a change and generate it into the canvas, or extend the picture past its edges.', side: 'top' }, + { target: ['.fc-cv-colbar [data-act="export"]'], title: 'Export', body: 'Save the canvas as PNG, JPEG or WebP, or copy it to the clipboard.', side: 'left' }, + { target: ['.fc-cg-open'], title: 'Open a saved canvas', body: 'Canvases are saved as projects. Open one again from here or from File, Open Recent.' }, + ], + scene: [ + { target: ['.fc-pr-plus'], title: 'Add objects', body: 'Add characters, objects, sets, cameras and lights, upload your own models, or generate new ones.' }, + { target: ['.fc-scc-tools'], title: 'Move, rotate and scale', body: 'Pick a tool, then drag the handles on the selected object. Snap keeps moves to even steps.' }, + { target: ['.fc-sc-navbar'], title: 'Look around', body: 'Change how objects are drawn, switch to a flat view, frame the selection or reset the view. Drag in the view to orbit; scroll to zoom.', side: 'left' }, + { target: ['.fc-scc-mode'], title: 'Edit or look through the camera', body: 'Edit stages the scene. Camera shows what the camera sees, which is what a capture or a recording uses.' }, + { target: ['.fc-tl-bar'], title: 'Animate on the timeline', body: 'Move the playhead, change an object and a key is set. Press Play to watch it move.', side: 'top' }, + { target: ['.fc-shot-bar'], title: 'Make a shot', body: 'Describe the look you want and generate a picture from the camera view, or save the frame as it is.', side: 'top' }, + ], + board: [ + { target: ['.fc-bd-pick'], title: 'Your boards', body: 'Keep one board per idea. Switch between them or start a new one here.' }, + { target: ['.fc-bg-actions'], title: 'Add to the board', body: 'Upload pictures, pick from the library, or add notes, colours and sections.' }, + { target: ['.fc-bd-switch'], title: 'Grid or freeform', body: 'Grid keeps everything in tidy rows. Freeform lets you place items anywhere.' }, + { target: ['.fc-bg-search', '.fc-bg-tools'], title: 'Find things', body: 'Search the board, and filter by rating.' }, + { target: ['.fc-bd-present'], title: 'Present', body: 'Shows the board full screen, one item at a time. The arrow keys move between items.', side: 'left' }, + ], + edit: [ + { target: ['.fc-ea-tabs'], title: 'Bring in your media', body: 'Add video, pictures and sound from the Media tab, or drop files onto the window. The other tabs add sounds, text, stickers and effects.', side: 'right' }, + { target: ['.fc-etl-empty .cv-btn', '.fc-etl-tb[data-act="addMedia"]'], title: 'Arrange it on the timeline', body: 'Drag clips onto tracks and pull their ends to trim. Every change can be undone.', side: 'top' }, + { target: ['.fc-etl-tb[data-act="split"]'], title: 'Cut', body: 'Split the selected clip at the playhead. The buttons next to it remove one side, delete or duplicate.', side: 'top' }, + { target: ['.fc-pv-mid'], title: 'Play it back', body: 'Play, pause and step one frame at a time.', side: 'top' }, + { target: ['.fc-ed-export'], title: 'Finish and export', body: 'Make an MP4 or WebM file. Save it to disk, add it to the library, or both.', side: 'left' }, + ], +}; diff --git a/frontend/src/ui/help/tour.ts b/frontend/src/ui/help/tour.ts new file mode 100644 index 0000000..dd1cfaf --- /dev/null +++ b/frontend/src/ui/help/tour.ts @@ -0,0 +1,302 @@ +import '../../styles/tour.css'; +import { studios } from '../../engine/studios'; +import { anyDialogOpen } from '../dialogs'; +import { el, q, setHidden, setText } from '../dom'; +import { t } from '../i18n'; +import { placeFloating, type Side, type Target } from '../position'; +import { toast } from '../toasts'; +import { TOURS, type TourStep } from './tour-steps'; + +const SEEN_PREFIX = 'formcraft.tour.'; +const RING_PAD = 4; +const GAP = 14; +const AUTO_DELAY = 900; +const SIDES: Side[] = ['bottom', 'top', 'right', 'left']; + +const seenKey = (id: string): string => `${SEEN_PREFIX}${id}`; + +function seen(id: string): boolean { + try { + return localStorage.getItem(seenKey(id)) === '1'; + } catch { + return true; + } +} + +function markSeen(id: string): void { + try { + localStorage.setItem(seenKey(id), '1'); + } catch { + return; + } +} + +export function resetTours(): void { + try { + for (const id of Object.keys(TOURS)) localStorage.removeItem(seenKey(id)); + } catch { + return; + } +} + +export function toursButton(): HTMLButtonElement { + const b = el(``); + b.addEventListener('click', () => { + resetTours(); + toast(t('Each studio shows its tour again the next time it opens.'), 'success', { key: 'tours-reset' }); + }); + return b; +} + +function visible(node: Element | null): node is HTMLElement { + if (!(node instanceof HTMLElement) || !node.isConnected || node.closest('[hidden]')) return false; + const r = node.getBoundingClientRect(); + if (r.width < 2 || r.height < 2 || r.right <= 0 || r.bottom <= 0 || r.left >= window.innerWidth || r.top >= window.innerHeight) return false; + if (getComputedStyle(node).visibility === 'hidden') return false; + const x = Math.min(Math.max(r.left + r.width / 2, 0), window.innerWidth - 1); + const y = Math.min(Math.max(r.top + r.height / 2, 0), window.innerHeight - 1); + const hit = document.elementFromPoint(x, y); + return !!hit && (node === hit || node.contains(hit) || hit.closest('.fc-tour') !== null); +} + +function find(step: TourStep): HTMLElement | null { + for (const sel of step.target) { + for (const node of Array.from(document.querySelectorAll(sel))) if (visible(node)) return node; + } + return null; +} + +const overlaps = (a: DOMRect, b: Target): boolean => a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top; + +class Tour { + private readonly root: HTMLElement; + private readonly ring: HTMLElement; + private readonly card: HTMLElement; + private readonly arrow: HTMLElement; + private readonly title: HTMLElement; + private readonly body: HTMLElement; + private readonly dots: HTMLElement; + private readonly back: HTMLButtonElement; + private readonly next: HTMLButtonElement; + private id = ''; + private steps: readonly TourStep[] = []; + private at = -1; + private target: HTMLElement | null = null; + private returnTo: HTMLElement | null = null; + private frame = 0; + private readonly watch = new ResizeObserver(() => this.schedule()); + private readonly onMove = (): void => this.schedule(); + private readonly onKey = (e: KeyboardEvent): void => { + if (!this.running() || this.root.hidden || this.card.getClientRects().length === 0) return; + const from = e.target instanceof Element ? e.target : null; + if (from && !this.root.contains(from) && from.closest('[role="dialog"], [role="menu"], [popover]')) return; + if (e.key === 'Escape' && document.querySelector('.cv-jp-pop:not([hidden])')) return; + if (e.key === 'Escape') { + e.preventDefault(); + e.stopPropagation(); + this.end(); + } else if (this.card.contains(document.activeElement) && (e.key === 'ArrowRight' || e.key === 'ArrowLeft')) { + e.preventDefault(); + e.stopPropagation(); + if (e.key === 'ArrowRight') this.forward(); + else this.go(this.at - 1, -1); + } + }; + + constructor() { + this.root = el( + ``, + ); + this.ring = q(this.root, '.fc-tour-ring'); + this.card = q(this.root, '.fc-tour-card'); + this.arrow = q(this.root, '.fc-tour-arrow'); + this.title = q(this.root, '.fc-tour-title'); + this.body = q(this.root, '.fc-tour-body'); + this.dots = q(this.root, '.fc-tour-dots'); + this.back = q(this.root, '.fc-tour-back'); + this.next = q(this.root, '.fc-tour-next'); + q(this.root, '.fc-tour-skip').addEventListener('click', () => this.end()); + this.back.addEventListener('click', () => this.go(this.at - 1, -1)); + this.next.addEventListener('click', () => this.forward()); + document.body.append(this.root); + } + + running(): boolean { + return this.at >= 0; + } + + start(id: string): boolean { + const steps = TOURS[id]; + if (!steps) return false; + if (this.running()) this.end(); + this.id = id; + this.steps = steps; + if (!this.go(0, 1)) { + this.id = ''; + return false; + } + const active = document.activeElement; + this.returnTo = active instanceof HTMLElement && active !== document.body ? active : null; + window.addEventListener('resize', this.onMove); + window.addEventListener('scroll', this.onMove, true); + document.addEventListener('keydown', this.onKey, true); + markSeen(id); + this.card.focus({ preventScroll: true }); + return true; + } + + private forward(): void { + if (!this.go(this.at + 1, 1)) this.end(); + } + + private go(from: number, dir: 1 | -1): boolean { + for (let i = from; i >= 0 && i < this.steps.length; i += dir) { + const node = find(this.steps[i]); + if (!node) continue; + this.at = i; + this.watch.disconnect(); + this.target = node; + this.watch.observe(node); + this.fill(); + this.place(); + return true; + } + return false; + } + + private fill(): void { + const step = this.steps[this.at]; + const live = this.steps.map((s, i) => i === this.at || find(s) !== null); + const index = live.slice(0, this.at).filter(Boolean).length; + const total = live.filter(Boolean).length; + setText(this.title, t(step.title)); + setText(this.body, t(step.body)); + this.dots.replaceChildren(...live.filter(Boolean).map((_, i) => el(``))); + this.dots.setAttribute('title', t('Step {n} of {total}').replace('{n}', String(index + 1)).replace('{total}', String(total))); + setHidden(this.back, index === 0); + const last = index === total - 1; + this.next.dataset.en = last ? 'Done' : 'Next'; + setText(this.next, t(this.next.dataset.en)); + } + + private schedule(): void { + if (this.frame || !this.running()) return; + this.frame = requestAnimationFrame(() => { + this.frame = 0; + if (!this.running()) return; + if (this.target && this.target.isConnected && this.target.getBoundingClientRect().width > 0) this.place(); + else if (!this.go(this.at, 1) && !this.go(this.at, -1)) this.end(); + }); + } + + private place(): void { + if (!this.target) return; + setHidden(this.root, false); + const r = this.target.getBoundingClientRect(); + const box: Target = { left: r.left - RING_PAD, top: r.top - RING_PAD, right: r.right + RING_PAD, bottom: r.bottom + RING_PAD }; + const rs = this.ring.style; + rs.left = `${Math.round(box.left)}px`; + rs.top = `${Math.round(box.top)}px`; + rs.width = `${Math.round(box.right - box.left)}px`; + rs.height = `${Math.round(box.bottom - box.top)}px`; + const pref = this.steps[this.at].side ?? 'bottom'; + const order = [pref, ...SIDES.filter((s) => s !== pref)]; + let side: Side = pref; + let fitted = false; + for (const s of order) { + side = placeFloating(this.card, box, { side: s, align: 'center', gap: GAP, minHeight: 0 }).side; + if (side === s && !overlaps(this.card.getBoundingClientRect(), box) && this.card.scrollHeight <= this.card.clientHeight + 1) { + fitted = true; + break; + } + } + if (!fitted) side = placeFloating(this.card, box, { side: pref, align: 'center', gap: GAP }).side; + this.card.dataset.side = side; + const c = this.card.getBoundingClientRect(); + const as = this.arrow.style; + if (side === 'top' || side === 'bottom') { + const x = Math.min(Math.max((box.left + box.right) / 2 - c.left, 16), c.width - 16); + as.left = `${Math.round(x)}px`; + as.top = ''; + } else { + const y = Math.min(Math.max((box.top + box.bottom) / 2 - c.top, 16), c.height - 16); + as.top = `${Math.round(y)}px`; + as.left = ''; + } + } + + end(): void { + if (!this.running()) return; + markSeen(this.id); + this.at = -1; + this.id = ''; + this.target = null; + this.watch.disconnect(); + window.removeEventListener('resize', this.onMove); + window.removeEventListener('scroll', this.onMove, true); + document.removeEventListener('keydown', this.onKey, true); + setHidden(this.root, true); + const back = this.returnTo; + this.returnTo = null; + if (back?.isConnected) back.focus({ preventScroll: true }); + } +} + +let tour: Tour | null = null; +const instance = (): Tour => (tour ??= new Tour()); + +export const tourIdFor = (studioId: string): string => studios.rootOf(studioId); + +export const hasTour = (id: string): boolean => Boolean(TOURS[id]); + +export function startTour(id = tourIdFor(studios.active)): boolean { + return hasTour(id) && instance().start(id); +} + +const homeShowing = (): boolean => { + const h = document.querySelector('.cv-home'); + return !!h && !h.hidden && h.getBoundingClientRect().width > 0; +}; + +let timer = 0; + +function autoStart(): void { + window.clearTimeout(timer); + timer = window.setTimeout(() => { + const id = tourIdFor(studios.active); + if (!hasTour(id) || seen(id) || anyDialogOpen() || homeShowing() || tour?.running()) return; + if (document.querySelector('.ft-tour:not([hidden])')) return; + startTour(id); + }, AUTO_DELAY); +} + +let mounted = false; + +export function mountTours(): void { + if (mounted || typeof document === 'undefined') return; + mounted = true; + studios.on('active', (id, previous) => { + if (tourIdFor(id) !== tourIdFor(previous)) tour?.end(); + autoStart(); + }); + window.setTimeout(() => { + const home = document.querySelector('.cv-home'); + if (home) + new MutationObserver(() => { + if (homeShowing()) tour?.end(); + autoStart(); + }).observe(home, { attributes: true, attributeFilter: ['hidden'] }); + autoStart(); + }, 0); + document.addEventListener('click', (e) => { + const b = e.target instanceof Element ? e.target.closest('[data-tour-for]') : null; + if (b?.dataset.tourFor) startTour(b.dataset.tourFor); + }); +} diff --git a/frontend/src/ui/help/whats-new-data.ts b/frontend/src/ui/help/whats-new-data.ts new file mode 100644 index 0000000..9960884 --- /dev/null +++ b/frontend/src/ui/help/whats-new-data.ts @@ -0,0 +1,16 @@ +export const WHATS_NEW_VERSION = '0.11'; + +export const WHATS_NEW: readonly string[] = [ + 'Home and the side panel now look like the rest of the Form family, with the real app icon.', + 'A Jobs button shows what is running and lets you cancel or open each job.', + 'When a key is missing, a small sheet on the prompt box saves it and runs your generation.', + 'Each studio has a short guided tour, and Help, Tour This Studio runs it again.', + 'Edit adds dissolves between clips and controls on each track.', + 'Canvas adds text and better selection tools.', + 'Canvas generation offers more choices and keeps each version.', + 'Board can align items and draw arrows between them.', + 'The library can float in its own window.', + 'Scene can select several objects at once and look through a camera.', + "The starter library is re-sourced from each publisher's own site, with every licence checked twice.", + 'Many known faults are fixed.', +]; diff --git a/frontend/src/ui/home.ts b/frontend/src/ui/home.ts index a748c92..53f1e20 100644 --- a/frontend/src/ui/home.ts +++ b/frontend/src/ui/home.ts @@ -2,9 +2,19 @@ import '../styles/home.css'; import { hooks, type ShellMounts } from '../app'; import { commands } from '../engine/commands'; import { shortcuts } from '../engine/shortcuts'; -import { studios, type Studio } from '../engine/studios'; +import { studios } from '../engine/studios'; import { APP_NAME, VERSION } from '../version'; -import { anyDialogOpen } from './dialogs'; +import { ApiError } from '../io/api'; +import { createProject, deleteProject, getProject, type ProjectSummary } from '../io/api-projects'; +import { anyDialogOpen, confirmAction } from './dialogs'; +import { mountWelcome } from './first-run'; +import { ContextMenu } from './library/context-menu'; +import { listDemos, openDemo as openDemo0, type Demo } from './projects/demos'; +import { revealFile, revealLabel } from './projects/disk'; +import { showProject } from './projects/session'; +import { projectStore } from './projects/store'; +import { mountToolMenu } from './tool-menu'; +import { listStarter } from './library/starter/api-starter'; import { el, escapeHtml, mountOnce, patchList, q, setAttr, setClass, setHidden, setText } from './dom'; import { HomeFiles } from './home-files'; import { onLanguage, t } from './i18n'; @@ -12,11 +22,9 @@ import { icon } from './icons'; import { registerImportCommand } from './importer'; import { RecentProjects } from './projects/recent'; import { onProjectShown } from './projects/session'; -import { LATER, tileBadge } from './projects/tiles'; import { toast } from './toasts'; -import { EXAMPLES } from './tools/background-change/examples'; -export type HomePage = 'start' | 'recent' | 'library' | 'outputs'; +export type HomePage = 'start' | 'recent' | 'library' | 'outputs' | 'demos'; export interface HomeApi { show(page?: HomePage): void; @@ -28,7 +36,9 @@ const AUTO_KEY = 'formcraft.home.autoShow'; const NAV_W_KEY = 'formcraft.home.nav'; const NAV_HIDDEN_KEY = 'formcraft.home.navHidden'; const AGENTS = 'Claude Code, Codex, Cursor, Antigravity'; -const PAGES: readonly HomePage[] = ['start', 'recent', 'library', 'outputs']; +const PAGES = ['recent', 'library', 'outputs'] as const; +const DEMO_CATS: readonly string[] = ['scene', 'canvas', 'board', 'edit']; +const BRAND = ``; const POPUPS = '#overlay-root .cv-menu:not([hidden]), #overlay-root .cv-dd-pop:not([hidden]), #overlay-root .cv-flyout:not([hidden]), #overlay-root .cv-search-pop:not([hidden])'; const NAV: ReadonlyArray<{ page: HomePage; icon: string; label: string }> = [ @@ -36,36 +46,30 @@ const NAV: ReadonlyArray<{ page: HomePage; icon: string; label: string }> = [ { page: 'recent', icon: 'history', label: 'Recent' }, { page: 'library', icon: 'library', label: 'Library' }, { page: 'outputs', icon: 'download', label: 'Outputs' }, -]; - -const CREATE: ReadonlyArray<{ cmd: string; icon: string; label: string }> = [ - { cmd: 'new', icon: 'newFile', label: 'New project' }, - { cmd: 'open', icon: 'folderOpen', label: 'Open project...' }, - { cmd: 'import', icon: 'upload', label: 'Import...' }, + { page: 'demos', icon: 'play', label: 'Demos' }, ]; const HEADS: Record, { title: string; sub: string }> = { + demos: { title: 'Demos', sub: 'Ready-made projects that open as unsaved copies and need no key.' }, recent: { title: 'Recent', sub: 'Your projects, then files you added or generated in the last 30 days, newest first.' }, library: { title: 'Library', sub: 'Everything kept in your local library.' }, outputs: { title: 'Outputs', sub: 'Pictures, video, audio and models you generated.' }, }; -const BLURB: Record = { - create: 'Generate images, video, audio, 3D and worlds.', - canvas: 'Compose and retouch pictures on a 2D canvas.', - scene: 'Stage models, lights and cameras in 3D.', - board: 'Gather references and ideas on a free-form board.', - edit: 'Cut clips and sound together on a timeline.', - angles: 'See one picture from a new camera angle.', - 'remove-background': 'Cut a subject out of its background.', - 'remove-region': 'Erase part of a picture and fill the gap.', - 'frame-extractor': 'Pull still frames out of a video.', - 'background-change': 'Put a subject in a new setting.', - storyboard: 'Plan shots and lay them out in order.', - 'mesh-tools': 'Split a 3D model into parts or rebuild its mesh.', -}; -const FORMATS = ['PNG', 'JPEG', 'WEBP', 'GIF', 'MP4', 'MOV', 'WEBM', 'MP3', 'WAV', 'GLB', 'FBX', 'OBJ', 'SPLAT']; +interface Make { id: string; cmd: string; icon: string; label: string; line: string; studio: string } + +const MAKE: readonly Make[] = [ + { id: 'image', cmd: 'page-image', icon: 'image', label: 'Image', line: 'Describe a picture and generate it.', studio: 'create' }, + { id: 'video', cmd: 'page-video', icon: 'video', label: 'Video', line: 'Turn a prompt or a picture into a clip.', studio: 'create' }, + { id: 'audio', cmd: 'page-audio', icon: 'audio', label: 'Audio', line: 'Make a song, a sound effect or a voice.', studio: 'create' }, + { id: 'object', cmd: 'page-object', icon: 'cube', label: '3D model', line: 'Turn a picture into a textured model.', studio: 'create' }, + { id: 'scene', cmd: 'studio-scene', icon: 'scene', label: '3D scene', line: 'Stage models, lights and a camera, then render.', studio: 'scene' }, + { id: 'world', cmd: 'page-world', icon: 'globe', label: 'World', line: 'Turn a picture into a world you can walk.', studio: 'create' }, + { id: 'edit', cmd: 'studio-edit', icon: 'edit', label: 'Edit a video', line: 'Cut clips and sound on a timeline.', studio: 'edit' }, + { id: 'board', cmd: 'studio-board', icon: 'board', label: 'Board', line: 'Pin references and ideas in one place.', studio: 'board' }, +]; + export function homeAutoShow(): boolean { try { @@ -101,26 +105,52 @@ function cmdItem(cmd: string, ic: string, label: string): string { return ``; } -function tile(s: Studio, cmd: string): string { - const later = LATER[s.id]; - const chip = later ? `${tx(later)}` : ''; +function studioName(id: string): string { + return studios.get(id)?.label ?? id; +} + +function makeCard(c: Make): string { + const page = studios.get(c.id); + const where = studioName(c.studio); + const sub = page?.parent ? `, ${tx(page.label)}` : ''; return ( - `` + `` ); } -function exampleCard(ex: (typeof EXAMPLES)[number]): string { - return ( - `` +function demoCard(d: Demo): HTMLElement { + const studio = d.studio ? studioName(d.studio) : ''; + const n = el( + ``, ); + n.dataset.demo = d.id; + setText(q(n, '.cv-home-card-name'), d.title); + setText(q(n, '.cv-home-card-meta'), studio ? `${t(studio)} · ${d.blurb ?? ''}` : d.blurb ?? ''); + n.title = d.blurb ?? ''; + if (d.cover) { + const img = q(n, 'img'); + img.addEventListener('load', () => setHidden(img, false), { once: true }); + img.src = d.cover; + } + return n; } function pageHead(p: Exclude): string { const h = HEADS[p]; - return `
${text(h.title, 'cv-home-title', 'h1')}${text(h.sub, 'cv-home-sub', 'p')}
`; + const acts = p === 'demos' ? `
` : ''; + return `
${text(h.title, 'cv-home-title', 'h1')}${text(h.sub, 'cv-home-sub', 'p')}
${acts}
`; +} + +function demosPage(): string { + const chip = (id: string, label: string): string => ``; + return ( + `
${chip('all', 'All')}${DEMO_CATS.map((c) => chip(c, studioName(c))).join('')}` + + `
` + + `
` + ); } function recentProjectsBlock(): string { @@ -131,21 +161,18 @@ function recentProjectsBlock(): string { } function homeHtml(open: boolean): string { - const studioTiles = studios.roots().filter((s) => s.kind === 'studio').map((s) => tile(s, `studio-${s.id}`)).join(''); - const toolTiles = studios.all().filter((s) => s.kind === 'tool').map((s) => tile(s, `tool-${s.id}`)).join(''); - const chips = FORMATS.map((f) => `${f}`).join(''); const nav = NAV.map(navItem).join(''); - const create = CREATE.map((c) => cmdItem(c.cmd, c.icon, c.label)).join(''); + const starter = ``; return ( `
` + `` + `` + @@ -154,26 +181,18 @@ function homeHtml(open: boolean): string { `
` + `
${nav}
` + `
` + - `

${text('Pick a studio, bring in files, or start a project.', 'cv-home-sub', 'p')}
` + - `
` + - `
${icon('create', 26)}` + - `
${text('Start from a prompt, a picture or a scene', 'cv-home-hero-title', 'div')}` + - `${text('Describe what you want and generate it, bring in an image or video to work from, or set up a 3D scene. Everything you make stays in your local library.', 'cv-home-hero-sub', 'div')}` + - `
${chips}
` + - `
` + - `` + - `` + - `` + - `
` + - `
${text('Projects', 'cv-home-section-title', 'h2')}
` + - `
${text('Examples', 'cv-home-section-title', 'h2')}${text('Each opens in Background change with its clip, picture and prompt', 'cv-home-card-meta')}
${EXAMPLES.map(exampleCard).join('')}
` + - `
${text('Studios', 'cv-home-section-title', 'h2')}
${studioTiles}
` + - `
${text('Tools', 'cv-home-section-title', 'h2')}
${toolTiles}
` + - `
${text('Recent files', 'cv-home-section-title', 'h2')}
` + + `

${text('What do you want to make?', 'cv-home-sub fc-home-ask', 'p')}
` + + `
` + + `` + + `
` + + `
${MAKE.map(makeCard).join('')}
` + + `
${text('Continue', 'cv-home-section-title', 'h2')}${text('Right-click a project for more', 'cv-home-card-meta')}
` + + `` + `
` + (['recent', 'library', 'outputs'] as const) .map((p) => ``) .join('') + + `` + `
` + `` + `
` @@ -198,8 +217,7 @@ export function mountHome(m: ShellMounts): HomeApi { const count = (p: HomePage) => (n: number): void => { for (const c of Array.from(root.querySelectorAll(`[data-v="${p}"] .cv-home-count`))) setText(c, String(n)); }; - const files: Record = { - start: new HomeFiles('recent', { limit: 8, compact: true }), + const files: Record<(typeof PAGES)[number], HomeFiles> = { recent: new HomeFiles('recent', { onCount: count('recent') }), library: new HomeFiles('library', { onCount: count('library') }), outputs: new HomeFiles('outputs', { onCount: count('outputs') }), @@ -228,17 +246,6 @@ export function mountHome(m: ShellMounts): HomeApi { setText(title, greeting()); }; - const paintTiles = (): void => { - for (const n of Array.from(root.querySelectorAll('[data-tile]'))) { - const badge = tileBadge(n.dataset.tile ?? '', m.hosts); - const chip = q(n, '.fc-home-badge'); - setAttr(chip, 'data-en', badge); - setAttr(chip, 'data-tone', badge && badge !== 'New' ? 'muted' : null); - setText(chip, badge ? t(badge) : ''); - setHidden(chip, !badge); - } - }; - const openGroup = q(root, '.cv-home-open'); const openList = q(root, '.cv-home-open-list'); const paintOpen = (): void => { @@ -259,14 +266,86 @@ export function mountHome(m: ShellMounts): HomeApi { }); }; - const useExample = (id: string): void => { - hide(); - void Promise.resolve(commands.run('tool-background-change')).then(() => { - const host = m.hosts.get('background-change'); - host?.querySelector('[data-tab="examples"]')?.click(); - host?.querySelector(`.fc-vfx-ex[data-id="${CSS.escape(id)}"] .fc-vfx-ex-use`)?.click(); - }); + const demoSection = q(root, '.fc-home-demos'); + const demoList = q(root, '.fc-demo-list'); + const demoFull = q(root, '.fc-demo-full'); + const demoNone = q(root, '.fc-demo-none'); + const demoSearch = q(root, '.fc-home-search-input'); + let demos: Demo[] = []; + let demoCat = 'all'; + const demoRows = { key: (d: Demo) => d.id, create: demoCard, update: (n: HTMLElement, d: Demo) => setText(q(n, '.cv-home-card-name'), d.title) }; + const paintDemos = (): void => { + const words = demoSearch.value.trim().toLowerCase(); + const shown = demos.filter((d) => (demoCat === 'all' || d.studio === demoCat) && (!words || `${d.title} ${d.blurb ?? ''}`.toLowerCase().includes(words))); + patchList(demoFull, shown, demoRows); + setHidden(demoNone, shown.length > 0 || !demos.length); + for (const c of Array.from(root.querySelectorAll('.fc-home-chip[data-cat]'))) { + const id = c.dataset.cat ?? ''; + setClass(c, 'is-active', id === demoCat); + setAttr(c, 'aria-pressed', id === demoCat ? 'true' : 'false'); + setText(q(c, '.fc-home-chip-count'), String(id === 'all' ? demos.length : demos.filter((d) => d.studio === id).length)); + } + }; + demoSearch.addEventListener('input', paintDemos); + const loadDemos = async (): Promise => { + const list = await listDemos(); + demos = list; + patchList(demoList, list.slice(0, 4), demoRows); + setHidden(demoSection, !list.length); + count('demos')(list.length); + paintDemos(); }; + const loadStarter = async (): Promise => { + try { + const page = await listStarter({ limit: 1 }); + setText(q(root, '.fc-home-starter-count'), String(page.total)); + } catch { + return; + } + }; + + const openDemo = async (id: string): Promise => { + if (await openDemo0(id)) hide(); + }; + + const explore = (): void => { + if (demos[0]) void openDemo(demos[0].id); + else void commands.run('studio-scene').then(() => hide()); + }; + + const projectMenu = new ContextMenu(); + const duplicate = async (p: ProjectSummary): Promise => { + try { + const full = await getProject(p.id); + const copy = await createProject({ kind: full.kind, name: t('{name} copy').replace('{name}', full.name), doc: full.doc }); + projectStore.upsert(copy); + } catch (err) { + toast(err instanceof ApiError ? err.message : t('The project could not be duplicated.'), 'error', { key: 'project-dup-failed' }); + } + }; + const remove = async (p: ProjectSummary): Promise => { + const ok = await confirmAction('Delete project', t('Delete "{name}"? The pictures and clips it used stay in your library.').replace('{name}', p.name), 'Delete', true); + if (!ok) return; + try { + await deleteProject(p.id); + projectStore.remove(p.id); + } catch (err) { + toast(err instanceof ApiError ? err.message : t('The project could not be deleted.'), 'error', { key: 'project-delete-failed' }); + } + }; + root.addEventListener('contextmenu', (e) => { + const card = (e.target as Element).closest('.fc-rp-card'); + const p = card?.dataset.key ? projectStore.get(card.dataset.key) : undefined; + if (!card || !p) return; + e.preventDefault(); + projectMenu.open(e.clientX, e.clientY, [ + { id: 'open', label: t('Open'), icon: 'folderOpen', run: () => void showProject(p) }, + { id: 'reveal', label: p.filePath ? t(revealLabel()) : t('Save the project to a file first.'), disabled: !p.filePath, run: () => void revealFile(p.filePath) }, + { id: 'duplicate', label: t('Duplicate'), icon: 'copy', run: () => void duplicate(p) }, + '-', + { id: 'delete', label: t('Delete'), icon: 'trash', danger: true, run: () => void remove(p) }, + ], card.querySelector('.fc-rp-open')); + }); const navSide = (): void => { const bar = q(root, '.cv-home-resizer'); @@ -351,7 +430,6 @@ export function mountHome(m: ShellMounts): HomeApi { if (main.scrollTop !== 0) main.scrollTop = 0; } open = true; - paintTiles(); apply(); activate(); root.querySelector('.cv-home-nav .cv-home-nav-item.is-active')?.focus({ preventScroll: true }); @@ -375,6 +453,12 @@ export function mountHome(m: ShellMounts): HomeApi { hide(); return; } + const cat = target.closest('.fc-home-chip[data-cat]')?.dataset.cat; + if (cat) { + demoCat = cat; + paintDemos(); + return; + } const view = target.closest('[data-v]'); if (view?.dataset.v) { go(view.dataset.v as HomePage); @@ -386,11 +470,12 @@ export function mountHome(m: ShellMounts): HomeApi { m.tabs.querySelector(`.cv-tab[data-key="${CSS.escape(doc)}"]`)?.click(); return; } - const ex = target.closest('[data-example]')?.dataset.example; - if (ex) { - useExample(ex); + const demo = target.closest('[data-demo]')?.dataset.demo; + if (demo) { + void openDemo(demo); return; } + if (target.closest('[data-starter-open]')) return; const act = target.closest('[data-a]')?.dataset.a; if (act === 'agents') { hooks.openPreferences?.('agents'); @@ -402,7 +487,7 @@ export function mountHome(m: ShellMounts): HomeApi { } const id = target.closest('[data-cmd]')?.dataset.cmd; if (!id) return; - if (id.startsWith('studio-') || id.startsWith('tool-')) hide(); + if (id.startsWith('studio-') || id.startsWith('tool-') || id.startsWith('page-')) hide(); void commands.run(id); }); @@ -427,7 +512,6 @@ export function mountHome(m: ShellMounts): HomeApi { q(root, '.cv-home-nav').setAttribute('aria-label', t('Home')); setText(title, greeting()); paintKeys(); - paintTiles(); for (const p of PAGES) files[p].rerender(); startProjects.rerender(); recentProjects.rerender(); @@ -436,10 +520,13 @@ export function mountHome(m: ShellMounts): HomeApi { new MutationObserver(sync).observe(m.tabs, { childList: true, subtree: true }); new MutationObserver(() => setHidden(drop, !!m.drop.hidden || !open)).observe(m.drop, { attributes: true, attributeFilter: ['hidden'] }); + mountToolMenu(m.brand); + commands.register(MAKE.map((c) => ({ id: `make-${c.id}`, label: `${t('Make')}: ${t(c.label)}`, group: 'Make', description: c.line, run: () => { hide(); void commands.run(c.cmd); } }))); + mountWelcome({ explore }); + void loadDemos(); + void loadStarter(); navSide(); paintKeys(); - paintTiles(); - queueMicrotask(paintTiles); apply(); activate(); diff --git a/frontend/src/ui/importer.ts b/frontend/src/ui/importer.ts index 4bd2b18..85e6c71 100644 --- a/frontend/src/ui/importer.ts +++ b/frontend/src/ui/importer.ts @@ -4,6 +4,7 @@ import { ApiError, importMediaFiles as uploadFiles, type Media } from '../io/api import { delayedIndicator, el } from './dom'; import { t, tn } from './i18n'; import { toast } from './toasts'; +import { screenFiles } from './drop-check'; const BUSY_KEY = 'import-busy'; @@ -42,7 +43,7 @@ function endBusy(): void { } export async function importMediaFiles(files: File[]): Promise { - const list = Array.from(files); + const list = screenFiles(Array.from(files)); if (!list.length) return []; beginBusy(); try { diff --git a/frontend/src/ui/job-toasts.ts b/frontend/src/ui/job-toasts.ts index 0c61e3c..d0aa7ea 100644 --- a/frontend/src/ui/job-toasts.ts +++ b/frontend/src/ui/job-toasts.ts @@ -2,6 +2,8 @@ import { commands } from '../engine/commands'; import { jobs } from '../engine/jobs'; import { onJobCreateFailed, type Job } from '../io/api'; import { t } from './i18n'; +import { revealAction, savedFolder } from './output-files'; +import { outputActions } from './projects/outputs'; import { toast } from './toasts'; const FRESH_MS = 10000; @@ -16,12 +18,12 @@ const WORK: Record = { image: 'Image generation', video: 'Video generation', audio: 'Audio generation', - object: '3D object generation', + object: '3D model generation', world: 'World generation', 'gen.image': 'Image generation', 'gen.video': 'Video generation', 'gen.audio': 'Audio generation', - 'gen.mesh': '3D object generation', + 'gen.mesh': '3D model generation', 'gen.splat': 'World generation', }; @@ -54,7 +56,8 @@ function succeeded(job: Job): void { const work = workName(job.kind); const extra = distinct(job, work); const text = extra ? t('{work} finished: {title}').replace('{work}', work).replace('{title}', extra) : t('{work} finished.').replace('{work}', work); - toast(text, 'success', { key: jobToastKey(job.id) }); + const ids = job.results ?? []; + toast(ids.length ? `${text} ${t('It is in the library.')}` : text, 'success', { key: jobToastKey(job.id), actions: outputActions(ids, revealAction(savedFolder(job))) }); } function failed(job: Job): void { diff --git a/frontend/src/ui/jobs-list.ts b/frontend/src/ui/jobs-list.ts index 7ecfec0..42fe503 100644 --- a/frontend/src/ui/jobs-list.ts +++ b/frontend/src/ui/jobs-list.ts @@ -92,6 +92,7 @@ interface Parts { pct: HTMLElement; err: HTMLElement; act: HTMLButtonElement; + act2: HTMLButtonElement; } const SHELL = @@ -101,7 +102,14 @@ const SHELL = '
    ' + '

    ' + '
    ' + - '
    '; + ''; + +type Group = 'running' | 'waiting' | 'done' | 'failed'; +const GROUPS: ReadonlyArray = [['running', 'Running'], ['waiting', 'Waiting'], ['done', 'Done'], ['failed', 'Failed']]; +const groupOf = (j: Job): Group => (j.status === 'running' ? 'running' : j.status === 'queued' ? 'waiting' : j.status === 'failed' || j.status === 'timed_out' ? 'failed' : 'done'); +const canRetry = (j: Job): boolean => j.kind.startsWith('gen.') && !!(j.payload.request as { model?: unknown } | undefined)?.model; +type Entry = { key: string; job: Job } | { key: string; group: Group; label: string; n: number }; +const HEAD = ''; const GLYPHS = STATUSES.map((s) => ``).join(''); @@ -112,7 +120,7 @@ const ROW = '
    ' + '' + '

    ' + - ''; + ''; export class JobsList { readonly root: HTMLElement; @@ -145,10 +153,13 @@ export class JobsList { (document.getElementById('overlay-root') ?? document.body).appendChild(this.root); relabel(this.root); this.list.addEventListener('click', (e) => { - const btn = e.target instanceof Element ? e.target.closest('.cv-jobs-act') : null; + const btn = e.target instanceof Element ? e.target.closest('.cv-jobs-act, .cv-jobs-act2') : null; const id = btn?.closest('.cv-jobs-row')?.dataset.key; if (!btn || !id || btn.getAttribute('aria-disabled') === 'true') return; - void this.run(btn.dataset.act === 'cancel' ? 'cancel' : 'dismiss', id); + const act = btn.dataset.act; + if (act === 'open') void this.openResult(id); + else if (act === 'retry') void this.retry(id); + else void this.run(act === 'cancel' ? 'cancel' : 'dismiss', id); }); this.clear.addEventListener('click', () => { if (this.clear.getAttribute('aria-disabled') !== 'true') void this.dismissAll(); @@ -288,6 +299,30 @@ export class JobsList { } } + private async openResult(id: string): Promise { + const job = jobs.get(id); + if (!job?.results.length) return; + try { + const [{ getMedia }, { openLightbox }, { confirmAndDelete }] = await Promise.all([import('../io/api'), import('./lightbox/lightbox'), import('./delete-media')]); + const list = await Promise.all(job.results.map((r) => getMedia(r))); + this.hide(false); + openLightbox(list, 0, { actions: ['delete'], onAction: (a, m) => void (a === 'delete' && confirmAndDelete([m.id])) }); + } catch { + toast(t('That file could not be opened.'), 'error', { key: `jobs:open:${id}` }); + } + } + + private async retry(id: string): Promise { + const job = jobs.get(id); + if (!job || this.pending.has(id)) return; + this.pending.add(id); + this.repaint(id); + const { retryJob } = await import('./feed/result-actions'); + await retryJob(job); + this.pending.delete(id); + this.repaint(id); + } + private async dismissAll(): Promise { if (this.clearing) return; this.clearing = true; @@ -323,12 +358,23 @@ export class JobsList { this.rows.delete(id); this.pending.delete(id); } - patchList(this.list, all, { - key: (j) => j.id, - create: (j) => this.build(j), - update: (_node, j) => { - const parts = this.rows.get(j.id); - if (parts) this.paint(parts, j); + const entries: Entry[] = []; + for (const [g, label] of GROUPS) { + const part = all.filter((j) => groupOf(j) === g); + if (!part.length) continue; + entries.push({ key: `g:${g}`, group: g, label, n: part.length }); + for (const j of part) entries.push({ key: j.id, job: j }); + } + patchList(this.list, entries, { + key: (e) => e.key, + create: (e) => ('job' in e ? this.build(e.job) : this.head(el(HEAD), e)), + update: (node, e) => { + if (!('job' in e)) { + this.head(node, e); + return; + } + const parts = this.rows.get(e.job.id); + if (parts) this.paint(parts, e.job); }, }); const sum = tally(all); @@ -353,6 +399,13 @@ export class JobsList { else this.close.focus(); } + private head(node: HTMLElement, e: { group: Group; label: string; n: number }): HTMLElement { + setAttr(node, 'data-group', e.group); + setText(q(node, '.cv-jobs-gname'), t(e.label)); + setText(q(node, '.cv-jobs-gcount'), String(e.n)); + return node; + } + private build(job: Job): HTMLElement { const row = el(ROW); const glyphs = {} as Record; @@ -368,6 +421,7 @@ export class JobsList { pct: q(row, '.cv-jobs-pct'), err: q(row, '.cv-jobs-err'), act: q(row, '.cv-jobs-act'), + act2: q(row, '.cv-jobs-act2'), }; this.rows.set(job.id, parts); this.paint(parts, job); @@ -416,5 +470,14 @@ export class JobsList { setAttr(p.act, 'data-act', active ? 'cancel' : 'dismiss'); setAttr(p.act, 'aria-label', `${active ? t('Cancel') : t('Dismiss')}: ${title}`); setAttr(p.act, 'aria-disabled', busy || this.offline ? 'true' : null); + const second = active ? '' : (status === 'failed' || status === 'timed_out') && canRetry(job) ? 'retry' : status === 'succeeded' && job.results.length ? 'open' : ''; + setHidden(p.act2, !second); + if (second) { + const word = second === 'retry' ? t('Retry') : t('Open'); + setText(p.act2, word); + setAttr(p.act2, 'data-act', second); + setAttr(p.act2, 'aria-label', `${word}: ${title}`); + setAttr(p.act2, 'aria-disabled', busy || this.offline ? 'true' : null); + } } } diff --git a/frontend/src/ui/jobs-popover.ts b/frontend/src/ui/jobs-popover.ts new file mode 100644 index 0000000..dbd2a55 --- /dev/null +++ b/frontend/src/ui/jobs-popover.ts @@ -0,0 +1,521 @@ +import '../styles/jobs-popover.css'; +import { commands } from '../engine/commands'; +import { isActive, jobs } from '../engine/jobs'; +import { isLocalJob, localJobs } from '../engine/local-jobs'; +import { shortcuts } from '../engine/shortcuts'; +import { mediaThumbUrl, type Job } from '../io/api'; +import { el, patchList, q, setAttr, setClass, setHidden, setText, setTitle } from './dom'; +import { jobCost, jobPrompt } from './feed/model'; +import { onLanguage, t, tn } from './i18n'; +import { icon } from './icons'; +import { registerMissing } from './menus'; +import { placeFloating } from './position'; +import { toast } from './toasts'; + +export const JOBS_POPOVER_ID = 'jobs-popover'; +const TITLE_MAX = 64; +const THUMB_W = 96; + +type Group = 'running' | 'waiting' | 'done' | 'failed'; +const GROUPS: ReadonlyArray = [['running', 'Running'], ['waiting', 'Waiting'], ['done', 'Done'], ['failed', 'Failed']]; +const groupOf = (j: Job): Group => (j.status === 'running' ? 'running' : j.status === 'queued' ? 'waiting' : j.status === 'failed' || j.status === 'timed_out' ? 'failed' : 'done'); +type Act = 'cancel' | 'retry' | 'edit' | 'open' | 'recreate'; +type Entry = { key: string; job: Job } | { key: string; group: Group; label: string; n: number }; + +function kindIcon(kind: string): string { + if (kind === 'gen.image' || kind === 'image') return 'image'; + if (kind === 'gen.video' || kind === 'render' || kind === 'edit.export') return 'video'; + if (kind === 'gen.audio') return 'audio'; + if (kind === 'gen.mesh' || kind === 'character') return 'cube'; + if (kind === 'gen.splat' || kind.startsWith('world')) return 'globe'; + if (kind === 'scene.record') return 'outRecord'; + if (kind === 'import') return 'upload'; + if (kind === 'download' || kind === 'pack-install') return 'download'; + return 'tools'; +} + +const request = (j: Job): { model?: unknown; prompt?: unknown } | undefined => j.payload.request as { model?: unknown; prompt?: unknown } | undefined; +const canRetry = (j: Job): boolean => j.kind.startsWith('gen.') && !!request(j)?.model; +const hasPrompt = (j: Job): boolean => j.kind.startsWith('gen.') && typeof request(j)?.prompt === 'string'; + +function titleOf(j: Job): string { + const said = j.kind.startsWith('gen.') ? jobPrompt(j).replace(/\s+/g, ' ').trim() : ''; + if (!said) return j.title || j.kind; + return said.length > TITLE_MAX ? `${said.slice(0, TITLE_MAX - 3).trimEnd()}...` : said; +} + +function modelOf(j: Job): string { + const m = j.model ?? ''; + const tail = m.split('/').filter(Boolean); + return tail.length > 2 ? tail.slice(-2).join('/') : m; +} + +function span(ms: number): string { + const s = Math.floor(ms / 1000); + if (s < 60) return t('{n} s').replace('{n}', String(s)); + const m = Math.floor(s / 60); + if (m < 60) return t('{m} m {s} s').replace('{m}', String(m)).replace('{s}', String(s % 60).padStart(2, '0')); + return t('{h} h {m} m').replace('{h}', String(Math.floor(m / 60))).replace('{m}', String(m % 60).padStart(2, '0')); +} + +function timeOf(j: Job, now: number): string { + if (isActive(j)) { + const from = Date.parse((j.status === 'queued' ? j.createdAt : j.startedAt) ?? j.createdAt); + return Number.isFinite(from) ? span(Math.max(0, now - from)) : ''; + } + const at = Date.parse(j.finishedAt ?? j.updatedAt); + if (!Number.isFinite(at)) return ''; + const d = new Date(at); + const same = new Date(now).toDateString() === d.toDateString(); + return same ? d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : d.toLocaleDateString([], { month: 'short', day: 'numeric' }); +} + +function actsOf(j: Job): Act[] { + const g = groupOf(j); + if (g === 'running' || g === 'waiting') return ['cancel']; + if (g === 'failed') return [...(canRetry(j) ? (['retry'] as Act[]) : []), ...(hasPrompt(j) ? (['edit'] as Act[]) : [])]; + return [...(j.results.length ? (['open'] as Act[]) : []), ...(hasPrompt(j) ? (['recreate'] as Act[]) : [])]; +} + +const ACT_WORD: Record = { cancel: 'Cancel', retry: 'Retry', edit: 'Edit prompt', open: 'Open result', recreate: 'Recreate' }; +const ACTS: Act[] = ['cancel', 'retry', 'edit', 'open', 'recreate']; + +interface Parts { + row: HTMLElement; + img: HTMLImageElement; + glyph: HTMLElement; + glyphName: string; + title: HTMLElement; + time: HTMLElement; + meta: HTMLElement; + bar: HTMLElement; + acts: Record; +} + +const ROW = + '
  • ' + + '
    ' + + '
    ' + + `
    ${ACTS.map((a) => ``).join('')}
  • `; +const HEAD = ''; + +const SHELL = + ''; + +/** The Jobs button in the title bar and its popover: engine jobs and window-side work (Scene Record, Edit export) + * grouped as in the full jobs list. Rows are patched in place; the list is never rebuilt. */ +export class JobsPopover { + private readonly pop: HTMLElement; + private readonly list: HTMLElement; + private readonly empty: HTMLElement; + private readonly clear: HTMLButtonElement; + private readonly full: HTMLButtonElement; + private readonly heading: HTMLElement; + private readonly badge: HTMLElement; + private readonly rows = new Map(); + private readonly pending = new Set(); + private order: string[] = []; + private picked = ''; + private frame = 0; + private ticker = 0; + private back: HTMLElement | null = null; + + constructor(private readonly button: HTMLButtonElement) { + this.badge = q(button, '.cv-tt-badge'); + this.pop = el(SHELL); + this.list = q(this.pop, '.cv-jp-list'); + this.empty = q(this.pop, '.cv-jp-empty'); + this.heading = q(this.pop, '.cv-jp-heading'); + this.clear = q(this.pop, '[data-foot="clear"]'); + this.full = q(this.pop, '[data-foot="full"]'); + (document.getElementById('overlay-root') ?? document.body).append(this.pop); + + button.addEventListener('click', () => this.toggle()); + this.list.addEventListener('click', (e) => { + const target = e.target instanceof Element ? e.target : null; + const row = target?.closest('.cv-jp-row'); + const key = row?.dataset.key; + if (!row || !key) return; + const btn = target?.closest('.cv-jp-act'); + if (btn) void this.act(key, btn.dataset.act as Act); + else this.pick(key, true); + }); + this.list.addEventListener('dblclick', (e) => { + const key = (e.target instanceof Element ? e.target.closest('.cv-jp-row') : null)?.dataset.key; + if (key) this.enter(key); + }); + this.clear.addEventListener('click', () => void this.clearFinished()); + this.full.addEventListener('click', () => { + this.close(false); + void commands.run('jobs-toggle'); + }); + this.pop.addEventListener('keydown', (e) => this.key(e)); + document.addEventListener( + 'pointerdown', + (e) => { + if (!this.isOpen) return; + const target = e.target as Node; + if (!this.pop.contains(target) && !this.button.contains(target)) this.close(false); + }, + true, + ); + window.addEventListener('resize', () => this.isOpen && this.place()); + document.addEventListener('keydown', (e) => { + const at = document.activeElement; + if (e.key !== 'Escape' || !this.isOpen || e.defaultPrevented || (at && at !== document.body && !this.button.contains(at))) return; + e.preventDefault(); + this.close(); + }); + + registerMissing([{ id: JOBS_POPOVER_ID, label: 'Show Jobs', group: 'Window', keys: ['Mod+Alt+KeyJ'], checked: () => this.isOpen, run: () => this.toggle() }]); + + const again = (): void => this.queue(); + jobs.on('change', again); + jobs.on('sync', again); + localJobs.on(again); + shortcuts.on('change', again); + onLanguage(again); + this.refresh(); + } + + get isOpen(): boolean { + return !this.pop.hidden; + } + + toggle(): void { + if (this.isOpen) this.close(); + else this.open(); + } + + open(): void { + if (this.isOpen) return; + const from = document.activeElement; + this.back = from instanceof HTMLElement && from !== document.body ? from : this.button; + this.pop.style.visibility = 'hidden'; + setHidden(this.pop, false); + this.refresh(); + this.place(); + this.pop.style.visibility = ''; + setAttr(this.button, 'aria-expanded', 'true'); + this.ticker = window.setInterval(this.tick, 1000); + const first = this.order[0]; + if (first) this.pick(this.picked && this.rows.has(this.picked) ? this.picked : first, true); + else this.full.focus(); + } + + close(restore = true): void { + if (!this.isOpen) return; + setHidden(this.pop, true); + setAttr(this.button, 'aria-expanded', 'false'); + window.clearInterval(this.ticker); + this.ticker = 0; + const back = this.back?.isConnected && this.back.offsetParent !== null ? this.back : this.button; + this.back = null; + if (restore) back.focus(); + } + + private place(): void { + const r = this.button.getBoundingClientRect(); + placeFloating(this.pop, { left: r.left, top: r.top, right: r.right, bottom: r.bottom }, { side: 'bottom', align: 'end', gap: 4 }); + } + + private all(): Job[] { + const list = [...jobs.list(), ...localJobs.list()]; + return list.sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0)); + } + + private queue(): void { + if (this.frame) return; + this.frame = requestAnimationFrame(() => { + this.frame = 0; + this.refresh(); + }); + } + + private readonly tick = (): void => { + if (document.hidden) return; + const now = Date.now(); + for (const [key, p] of this.rows) { + const job = this.find(key); + if (job && isActive(job)) setText(p.time, timeOf(job, now)); + } + }; + + private find(key: string): Job | undefined { + return isLocalJob(key) ? localJobs.get(key) : jobs.get(key); + } + + private refresh(): void { + const all = this.all(); + let running = 0; + let waiting = 0; + let finished = 0; + for (const j of all) { + if (j.status === 'running') running++; + else if (j.status === 'queued') waiting++; + else finished++; + } + const busy = running + waiting; + setClass(this.button, 'is-running', running > 0); + setHidden(this.badge, busy === 0); + setText(this.badge, busy > 9 ? '9+' : String(busy)); + const keys = shortcuts.label(JOBS_POPOVER_ID); + const notes = [running ? tn(running, '{n} running', '{n} running') : '', waiting ? tn(waiting, '{n} waiting', '{n} waiting') : ''].filter(Boolean); + const label = `${t('Jobs')}${keys ? ` (${keys})` : ''}${notes.length ? `: ${notes.join(', ')}` : ''}`; + setTitle(this.button, label); + setAttr(this.button, 'aria-label', label); + setAttr(this.pop, 'aria-label', t('Jobs')); + setText(this.heading, t('Jobs')); + setText(this.empty, t('No jobs yet. Anything you generate or import shows up here.')); + setText(this.clear, t('Clear finished')); + setText(this.full, t('Open full list')); + setAttr(this.clear, 'aria-disabled', finished === 0 ? 'true' : null); + if (!this.isOpen) return; + + for (const [key] of this.rows) if (!all.some((j) => j.id === key)) this.drop(key); + const entries: Entry[] = []; + for (const [g, name] of GROUPS) { + const part = all.filter((j) => groupOf(j) === g); + if (!part.length) continue; + entries.push({ key: `g:${g}`, group: g, label: name, n: part.length }); + for (const j of part) entries.push({ key: j.id, job: j }); + } + const hadFocus = this.pop.contains(document.activeElement); + patchList(this.list, entries, { + key: (e) => e.key, + create: (e) => ('job' in e ? this.build(e.job) : this.head(el(HEAD), e)), + update: (node, e) => { + if (!('job' in e)) this.head(node, e); + else { + const p = this.rows.get(e.job.id); + if (p) this.paint(p, e.job); + } + }, + }); + const old = this.order; + this.order = entries.filter((e): e is { key: string; job: Job } => 'job' in e).map((e) => e.key); + setHidden(this.empty, all.length > 0); + if (this.picked && !this.rows.has(this.picked)) { + const at = old.indexOf(this.picked); + const next = old.slice(at + 1).find((k) => this.rows.has(k)) ?? old.slice(0, Math.max(0, at)).reverse().find((k) => this.rows.has(k)) ?? this.order[0] ?? ''; + this.picked = ''; + if (next) this.pick(next, hadFocus); + else if (hadFocus) this.full.focus(); + } + const at = document.activeElement; + if (hadFocus && at instanceof HTMLElement && at.hidden) this.rows.get(this.picked)?.row.focus({ preventScroll: true }); + if (old.length !== this.order.length) this.place(); + } + + private drop(key: string): void { + this.rows.delete(key); + this.pending.delete(key); + } + + private head(node: HTMLElement, e: { group: Group; label: string; n: number }): HTMLElement { + setAttr(node, 'data-group', e.group); + setText(q(node, '.cv-jp-gname'), t(e.label)); + setText(q(node, '.cv-jp-gcount'), String(e.n)); + return node; + } + + private build(job: Job): HTMLElement { + const row = el(ROW); + const acts = {} as Record; + for (const a of ACTS) acts[a] = q(row, `[data-act="${a}"]`); + const img = q(row, 'img'); + const p: Parts = { row, img, glyph: q(row, '.cv-jp-glyph'), glyphName: '', title: q(row, '.cv-jp-title'), time: q(row, '.cv-jp-time'), meta: q(row, '.cv-jp-meta'), bar: q(row, '.cv-jp-bar'), acts }; + img.addEventListener('load', () => { + setHidden(img, false); + setHidden(p.glyph, true); + }); + img.addEventListener('error', () => { + setHidden(img, true); + setHidden(p.glyph, false); + }); + this.rows.set(job.id, p); + this.paint(p, job); + return row; + } + + private paint(p: Parts, job: Job): void { + const g = groupOf(job); + setAttr(p.row, 'data-group', g); + setAttr(p.row, 'data-status', job.status); + setClass(p.row, 'is-picked', this.picked === job.id); + const glyph = g === 'running' ? 'loading' : kindIcon(job.kind); + if (p.glyphName !== glyph) { + p.glyphName = glyph; + p.glyph.innerHTML = icon(glyph, 16); + } + const thumb = g === 'done' && job.results[0] && !isLocalJob(job.id) && job.kind !== 'download' ? mediaThumbUrl(job.results[0], THUMB_W) : ''; + if (!thumb) { + setHidden(p.img, true); + setHidden(p.glyph, false); + if (p.img.getAttribute('src')) p.img.removeAttribute('src'); + } else if (p.img.getAttribute('src') !== thumb) { + p.img.src = thumb; + } + const title = titleOf(job); + setText(p.title, title); + setTitle(p.title, fullTitle(job)); + setText(p.time, timeOf(job, Date.now())); + const model = modelOf(job); + const cost = jobCost(job); + const err = g === 'failed' ? job.error?.message || t(job.status === 'timed_out' ? 'Timed out' : 'Failed') : job.status === 'cancelled' ? t('Cancelled') : ''; + const meta = [model, cost, err].filter(Boolean).join(' · '); + setText(p.meta, meta); + setTitle(p.meta, meta); + const live = job.status === 'running' && typeof job.progress === 'number' && Number.isFinite(job.progress) ? Math.min(1, Math.max(0, job.progress)) : null; + setHidden(p.bar, job.status !== 'running'); + setClass(p.bar, 'is-indeterminate', job.status === 'running' && live === null); + p.bar.style.setProperty('--p', String(live ?? 0)); + const want = actsOf(job); + const busy = this.pending.has(job.id); + for (const a of ACTS) { + const btn = p.acts[a]; + const on = want.includes(a); + setHidden(btn, !on); + if (!on) continue; + const word = a === 'cancel' && busy ? t('Cancelling') : t(ACT_WORD[a]); + setText(btn, word); + setAttr(btn, 'aria-label', `${t(ACT_WORD[a])}: ${title}`); + setAttr(btn, 'aria-disabled', busy ? 'true' : null); + } + setAttr(p.row, 'aria-label', `${title}, ${t(GROUPS.find((x) => x[0] === g)?.[1] ?? '')}${meta ? `, ${meta}` : ''}`); + } + + private pick(key: string, focus: boolean): void { + if (this.picked !== key) { + const was = this.rows.get(this.picked); + if (was) setClass(was.row, 'is-picked', false); + this.picked = key; + } + const p = this.rows.get(key); + if (!p) return; + setClass(p.row, 'is-picked', true); + for (const r of this.rows.values()) for (const b of Object.values(r.acts)) setAttr(b, 'tabindex', r === p ? '0' : '-1'); + if (focus) { + p.row.focus({ preventScroll: true }); + p.row.scrollIntoView({ block: 'nearest' }); + } + } + + private enter(key: string): void { + const job = this.find(key); + if (!job) return; + const acts = actsOf(job); + if (acts.includes('open')) void this.act(key, 'open'); + else if (acts.includes('edit')) void this.act(key, 'edit'); + else { + this.close(false); + void commands.run('jobs-toggle'); + } + } + + private key(e: KeyboardEvent): void { + if (e.isComposing) return; + if (e.key === 'Escape') { + e.preventDefault(); + e.stopPropagation(); + this.close(); + return; + } + const onRow = document.activeElement instanceof HTMLElement && document.activeElement.classList.contains('cv-jp-row'); + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + e.preventDefault(); + const n = this.order.length; + if (!n) return; + const at = this.order.indexOf(this.picked); + const next = at < 0 ? 0 : (at + (e.key === 'ArrowDown' ? 1 : n - 1)) % n; + this.pick(this.order[next], true); + } else if (e.key === 'Home' || e.key === 'End') { + if (!this.order.length) return; + e.preventDefault(); + this.pick(this.order[e.key === 'Home' ? 0 : this.order.length - 1], true); + } else if (e.key === 'Enter' && onRow && this.picked) { + e.preventDefault(); + this.enter(this.picked); + } else if (e.key === 'Delete' && onRow && this.picked) { + const job = this.find(this.picked); + if (job && isActive(job)) { + e.preventDefault(); + void this.act(this.picked, 'cancel'); + } + } + } + + private async act(key: string, a: Act): Promise { + const job = this.find(key); + if (!job || this.pending.has(key)) return; + if (a === 'cancel') { + if (isLocalJob(key)) { + localJobs.cancel(key); + return; + } + this.pending.add(key); + this.repaint(key); + try { + await jobs.cancel(key); + } catch (err) { + toast(err instanceof Error ? err.message : t('The engine could not do that.'), 'error', { key: `jobs:cancel:${key}` }); + } finally { + this.pending.delete(key); + this.repaint(key); + } + return; + } + if (a === 'retry') { + this.pending.add(key); + this.repaint(key); + const { retryJob } = await import('./feed/result-actions'); + await retryJob(job); + this.pending.delete(key); + this.repaint(key); + return; + } + if (a === 'edit' || a === 'recreate') { + this.close(false); + const { recreateFrom } = await import('./feed/result-actions'); + await recreateFrom(undefined, job); + return; + } + if (a === 'open') await this.openResult(job); + } + + private repaint(key: string): void { + const p = this.rows.get(key); + const job = this.find(key); + if (p && job) this.paint(p, job); + const at = document.activeElement; + if (p && this.isOpen && this.picked === key && (!at || at === document.body || (at instanceof HTMLElement && at.hidden))) p.row.focus({ preventScroll: true }); + } + + private async openResult(job: Job): Promise { + if (!job.results.length) return; + try { + const [{ getMedia }, { openLightbox }, { confirmAndDelete }] = await Promise.all([import('../io/api'), import('./lightbox/lightbox'), import('./delete-media')]); + const list = await Promise.all(job.results.map((r) => getMedia(r))); + this.close(false); + openLightbox(list, 0, { actions: ['delete'], onAction: (act, m) => void (act === 'delete' && confirmAndDelete([m.id])) }); + } catch { + toast(t('That file could not be opened.'), 'error', { key: `jobs:open:${job.id}` }); + } + } + + private async clearFinished(): Promise { + if (this.clear.getAttribute('aria-disabled') === 'true') return; + localJobs.dismissFinished(); + try { + await jobs.dismissFinished(); + } catch (err) { + toast(err instanceof Error ? err.message : t('The engine could not do that.'), 'error', { key: 'jobs:dismiss-finished' }); + } + } +} + +function fullTitle(job: Job): string { + return (job.kind.startsWith('gen.') ? jobPrompt(job) : '') || job.title || job.kind; +} diff --git a/frontend/src/ui/keybinds-panel.ts b/frontend/src/ui/keybinds-panel.ts index 0bfaff2..bfcd3ea 100644 --- a/frontend/src/ui/keybinds-panel.ts +++ b/frontend/src/ui/keybinds-panel.ts @@ -1,5 +1,8 @@ import '../styles/keybinds.css'; +import '../styles/keybinds-more.css'; import { commands } from '../engine/commands'; +import { exclusive, sceneAction } from '../engine/scene/actions'; +import { canvasAction, canvasExclusive } from '../engine/canvas/actions'; import { PRESETS, SURFACES, shortcuts, type PresetId, type ShortcutAction, type Surface } from '../engine/shortcuts'; import { el, patchList, q, setAttr, setClass, setDisabled, setHidden, setHtml, setStyleVar, setText, setValue } from './dom'; import { icon } from './icons'; @@ -29,6 +32,8 @@ interface SectionModel { interface RowRefs { name: HTMLElement; dot: HTMLElement; + ctx: HTMLElement; + swap: HTMLButtonElement; chips: HTMLElement; unbound: HTMLElement; hint: HTMLElement; @@ -56,10 +61,16 @@ const PANEL_HTML = `
    ` + `
    ` + `` + - `
    ${icon('search', 14)}
    ` + + `
    ${icon('search', 14)}` + + `
    ` + `` + `
    ` + - `

    A preset sets the starting keys. Your own changes stay on top of it.

    ` + + `
    ` + + `

    ` + + `` + + `` + + `` + + `
    ` + `
    ` + `
    ` + `
    `; @@ -78,7 +89,7 @@ const SECTION_HTML = const ROW_HTML = `
    ` + `
    ` + - `` + + `` + `
    Unbound
    ` + `
    ` + `` + @@ -86,7 +97,8 @@ const ROW_HTML = `` + `
    ` + `` + `
    `; @@ -111,6 +123,21 @@ const fill = (text: string, values: Record): string => text.repl const plain = (label: string): string => label.replace(/(\.\.\.|…)$/, ''); +function contextLabel(entry: ShortcutAction): string { + const gate = sceneAction(entry.action)?.gate ?? []; + const mode = gate.includes('build') ? t('Build mode') : gate.includes('record') ? t('Record mode') : ''; + return mode ? `${surfaceTitle(entry.surface)} · ${mode}` : surfaceTitle(entry.surface); +} + +function sameContext(a: string, b: string): boolean { + const x = sceneAction(a); + const y = sceneAction(b); + if (x && y && exclusive(x.gate, y.gate)) return false; + const c = canvasAction(a); + const d = canvasAction(b); + return !(c && d && canvasExclusive(c.gate, d.gate)); +} + export class KeybindsPanel { readonly el: HTMLElement; @@ -122,6 +149,12 @@ export class KeybindsPanel { private readonly empty: HTMLElement; private readonly resetAllBtn: HTMLButtonElement; private readonly resetAllLabel: HTMLElement; + private readonly presetNote: HTMLElement; + private readonly importFile: HTMLInputElement; + private readonly keyBtn: HTMLButtonElement; + private chord: string | null = null; + private keyRelease: (() => void) | null = null; + private listeningKey = false; private readonly presetOptions = new Map(); private readonly rowRefs = new WeakMap(); private readonly secRefs = new WeakMap(); @@ -148,6 +181,10 @@ export class KeybindsPanel { this.empty = q(this.el, '.fc-kb-empty'); this.resetAllBtn = q(this.el, '[data-do="reset-all"]'); this.resetAllLabel = q(this.el, '[data-role="reset-all"]'); + this.presetNote = q(this.el, '[data-role="preset-note"]'); + this.importFile = q(this.el, '[data-role="import-file"]'); + this.keyBtn = q(this.el, '[data-do="key-search"]'); + this.importFile.addEventListener('change', () => void this.readImport()); for (const p of PRESETS) { const o = document.createElement('option'); o.value = p.id; @@ -162,6 +199,8 @@ export class KeybindsPanel { if (this.armed && e.target === this.resetAllBtn) this.disarm(); }); this.search.addEventListener('input', () => { + this.chord = null; + this.stopKeySearch(); const next = this.search.value.trim().toLowerCase(); if (next && !this.query) setStyleVar(this.list, 'min-height', getComputedStyle(this.list).height); else if (!next) setStyleVar(this.list, 'min-height', ''); @@ -204,7 +243,7 @@ export class KeybindsPanel { for (const entry of own) { const label = liveLabel(entry.action) ?? entry.action; const hay = terms.length ? haystack(entry, label) : ''; - const visible = terms.every((w) => hay.includes(w)); + const visible = terms.every((w) => hay.includes(w)) && (this.chord === null || entry.bindings.includes(this.chord)); if (entry.customised) changed++; if (visible) shown++; const list = groups.get(entry.group); @@ -236,6 +275,15 @@ export class KeybindsPanel { setText(this.empty, live.length ? t('No matching shortcuts.') : t('No shortcuts are defined yet.')); for (const p of PRESETS) setText(this.presetOptions.get(p.id) ?? null, t(p.label)); setValue(this.preset, shortcuts.preset); + const note = t(PRESETS.find((p) => p.id === shortcuts.preset)?.note ?? ''); + setText( + this.presetNote, + changedTotal + ? `${note} ${fill(t(changedTotal === 1 ? '{n} of your own change stays on top.' : '{n} of your own changes stay on top.'), { n: String(changedTotal) })}` + : `${note} ${t('No changes of your own yet.')}`, + ); + setAttr(this.keyBtn, 'aria-pressed', String(this.listeningKey)); + setClass(this.keyBtn, 'is-active', this.listeningKey); if (changedTotal === 0 && this.armed) { this.armed = false; window.clearTimeout(this.armTimer); @@ -283,7 +331,7 @@ export class KeybindsPanel { private paintSection(node: HTMLElement, s: SectionModel): void { const r = this.secRefs.get(node); if (!r) return; - const open = this.query !== '' || !this.collapsed.has(s.surface); + const open = this.query !== '' || this.chord !== null || !this.collapsed.has(s.surface); setHidden(node, s.shown === 0); setClass(node, 'is-collapsed', !open); setAttr(r.toggle, 'aria-expanded', String(open)); @@ -315,6 +363,8 @@ export class KeybindsPanel { this.rowRefs.set(node, { name: q(node, '.fc-kb-name'), dot: q(node, '.fc-kb-dot'), + ctx: q(node, '.fc-kb-ctx'), + swap: q(node, '[data-do="swap"]'), chips: q(node, '.fc-kb-chips'), unbound: q(node, '.fc-kb-unbound'), hint: q(node, '.fc-kb-hint'), @@ -345,6 +395,7 @@ export class KeybindsPanel { setText(r.name, label); setHidden(r.dot, !entry.customised); setAttr(r.dot, 'title', t('Changed from the preset')); + setText(r.ctx, contextLabel(entry)); const paintChip = (chip: HTMLElement, b: string): void => { setHtml(q(chip, '.fc-keyset'), keycapsHtml(b), `${mac}|${b}`); @@ -381,6 +432,7 @@ export class KeybindsPanel { setAttr(r.reset, 'title', t('Reset to the preset')); setHidden(r.note, conflict === null); + setHidden(r.swap, conflict?.mode !== 'replace'); if (conflict) { const names = this.clashes(conflict.binding, entry.surface, entry.action) .map((a) => plain(liveLabel(a) ?? a)) @@ -410,6 +462,18 @@ export class KeybindsPanel { case 'force': this.force(); break; + case 'swap': + this.swap(); + break; + case 'key-search': + this.startKeySearch(); + break; + case 'import': + this.importFile.click(); + break; + case 'export': + this.exportFile(); + break; case 'cancel': this.dismiss(); break; @@ -436,6 +500,8 @@ export class KeybindsPanel { e.stopPropagation(); this.search.value = ''; this.query = ''; + this.chord = null; + setStyleVar(this.list, 'min-height', ''); this.refresh(); } return; @@ -506,10 +572,128 @@ export class KeybindsPanel { private clashes(binding: string, surface: Surface, action: string): string[] { return shortcuts .conflicts(binding, surface, action) - .filter((c) => commands.get(c.action) !== undefined) + .filter((c) => commands.get(c.action) !== undefined && sameContext(action, c.action)) .map((c) => c.action); } + private swap(): void { + const a = this.active; + if (a?.kind !== 'conflict' || a.mode !== 'replace') return; + const entry = shortcuts.entry(a.action); + this.active = null; + if (!entry) { + this.refresh(); + return; + } + const others = this.clashes(a.binding, entry.surface, a.action); + const old = entry.bindings.filter((b) => b !== a.binding); + this.writing = true; + try { + for (const other of others) { + const o = shortcuts.entry(other); + if (o) shortcuts.set(other, [...o.bindings.filter((b) => b !== a.binding), ...old.filter((b) => !o.bindings.includes(b))]); + } + shortcuts.set(a.action, [a.binding]); + } finally { + this.writing = false; + } + const name = plain(liveLabel(a.action) ?? a.action); + const names = others.map((x) => plain(liveLabel(x) ?? x)).join(', '); + this.say(fill(t('{name} and {names} swapped keys. {name} now uses {key}.'), { key: shortcuts.format(a.binding), name, names })); + this.refresh(); + this.focusRecord(a.action); + } + + private startKeySearch(): void { + if (this.listeningKey) { + this.stopKeySearch(); + this.refresh(); + return; + } + this.endAll(); + this.listeningKey = true; + this.keyRelease = holdSuspend(); + if (!this.upBound) { + this.upBound = true; + window.addEventListener('keyup', this.onKeyUp, true); + } + window.addEventListener('keydown', this.onSearchKey, true); + window.addEventListener('pointerdown', this.onSearchAway, true); + setAttr(this.search, 'placeholder', t('Press the key combination to look for. Esc cancels.')); + this.search.value = ''; + this.query = ''; + this.chord = null; + this.refresh(); + } + + private stopKeySearch(): void { + if (!this.listeningKey) return; + this.listeningKey = false; + window.removeEventListener('keydown', this.onSearchKey, true); + window.removeEventListener('pointerdown', this.onSearchAway, true); + this.keyRelease?.(); + this.keyRelease = null; + setAttr(this.search, 'placeholder', t('Search actions or keys')); + } + + private readonly onSearchKey = (e: KeyboardEvent): void => { + if (!this.listeningKey) return; + if (!this.visible()) { + this.stopKeySearch(); + return; + } + if (e.isComposing) return; + e.preventDefault(); + e.stopImmediatePropagation(); + if (e.repeat) return; + if (e.code === 'Escape' && !e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey) { + this.stopKeySearch(); + this.refresh(); + return; + } + const binding = shortcuts.parse(e); + if (!binding) return; + this.swallow.add(e.code); + this.stopKeySearch(); + this.chord = binding; + this.search.value = shortcuts.format(binding); + setStyleVar(this.list, 'min-height', getComputedStyle(this.list).height); + this.refresh(); + }; + + private readonly onSearchAway = (e: PointerEvent): void => { + if (e.target instanceof Node && this.keyBtn.contains(e.target)) return; + this.stopKeySearch(); + this.refresh(); + }; + + private exportFile(): void { + const blob = new Blob([shortcuts.exportJson()], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = 'formcraft-shortcuts.json'; + document.body.append(a); + a.click(); + a.remove(); + window.setTimeout(() => URL.revokeObjectURL(url), 1000); + this.say(t('Shortcuts exported.')); + } + + private async readImport(): Promise { + const file = this.importFile.files?.[0]; + this.importFile.value = ''; + if (!file) return; + try { + const n = shortcuts.importJson(await file.text()); + this.endAll(); + this.say(fill(t('Imported {n} custom shortcuts.'), { n: String(n) })); + } catch { + this.say(t('That file is not a FormCraft shortcuts file.')); + } + this.refresh(); + } + private toggleRecord(action: string, mode: Mode): void { if (!action) return; const a = this.active; @@ -552,6 +736,7 @@ export class KeybindsPanel { } private endAll(): void { + this.stopKeySearch(); this.stopListening(); this.active = null; } diff --git a/frontend/src/ui/keyview.ts b/frontend/src/ui/keyview.ts index a808496..9801b50 100644 --- a/frontend/src/ui/keyview.ts +++ b/frontend/src/ui/keyview.ts @@ -10,7 +10,7 @@ const MAC_GLYPHS: Record = { Mod: '⌘', Ctrl: '⌃', Alt: '⌥' const SURFACE_TEXT: Record = { global: { title: 'Everywhere', note: 'Works in every studio.' }, - create: { title: 'Create', note: 'The image, video, audio, 3D object and world pages.' }, + create: { title: 'Create', note: 'The image, video, audio, 3D model and world pages.' }, canvas: { title: 'Canvas', note: 'The 2D canvas.' }, scene: { title: 'Scene', note: 'The 3D scene stage.' }, board: { title: 'Board', note: 'The moodboard.' }, diff --git a/frontend/src/ui/library/context-menu.ts b/frontend/src/ui/library/context-menu.ts index 3cc41f4..edb5414 100644 --- a/frontend/src/ui/library/context-menu.ts +++ b/frontend/src/ui/library/context-menu.ts @@ -1,6 +1,7 @@ import { el, q, setAttr, setDisabled, setText } from '../dom'; import { t } from '../i18n'; import { icon } from '../icons'; +import { placeFloating, pointTarget } from '../position'; import { zoomOf } from './grid-shared'; import '../../styles/menu.css'; @@ -52,14 +53,7 @@ export class ContextMenu { this.panel.style.visibility = 'hidden'; this.panel.hidden = false; this.panel.scrollTop = 0; - const { width: w, height: h } = this.panel.getBoundingClientRect(); - const fitsRight = x + w <= window.innerWidth - PAD; - const fitsBelow = y + h <= window.innerHeight - PAD; - const left = Math.max(PAD, Math.min(fitsRight ? x : x - w, window.innerWidth - w - PAD)); - const top = Math.max(PAD, Math.min(fitsBelow ? y : y - h, window.innerHeight - h - PAD)); - const z = zoomOf(); - this.panel.style.left = `${Math.round(left / z)}px`; - this.panel.style.top = `${Math.round(top / z)}px`; + placeFloating(this.panel, pointTarget(x, y), { side: 'bottom', align: 'start', pad: PAD, scale: zoomOf() }); this.panel.style.visibility = ''; this.panel.focus({ preventScroll: true }); } diff --git a/frontend/src/ui/library/library-actions.ts b/frontend/src/ui/library/library-actions.ts index 8c66302..15f51e2 100644 --- a/frontend/src/ui/library/library-actions.ts +++ b/frontend/src/ui/library/library-actions.ts @@ -208,6 +208,12 @@ export class LibraryActions { await saveMedia(Array.from(ids)); } + async encode(m: Media): Promise { + if (m.kind !== 'video' && m.kind !== 'audio') return; + const { sendToFormEncoder } = await import('../rendering'); + await sendToFormEncoder(m.id); + } + async reveal(m: Media): Promise { if (!inDesktop()) return; try { diff --git a/frontend/src/ui/library/library-modal.ts b/frontend/src/ui/library/library-modal.ts index c41464d..5c5d9d1 100644 --- a/frontend/src/ui/library/library-modal.ts +++ b/frontend/src/ui/library/library-modal.ts @@ -112,7 +112,7 @@ class LibraryModal extends Dialog { `
    ` + `
    ` + TABS.map((d) => ``).join('') + - `
    ` + + `
    ` + `` + `` + `` + diff --git a/frontend/src/ui/library/library-sidebar.ts b/frontend/src/ui/library/library-sidebar.ts index 9f543f7..30a3001 100644 --- a/frontend/src/ui/library/library-sidebar.ts +++ b/frontend/src/ui/library/library-sidebar.ts @@ -29,7 +29,7 @@ const NAV: NavItem[][] = [ { view: 'kind:image', label: 'Images', icon: 'image' }, { view: 'kind:video', label: 'Videos', icon: 'video' }, { view: 'kind:audio', label: 'Audio', icon: 'audio' }, - { view: 'kind:model', label: '3D objects', icon: 'cube' }, + { view: 'kind:model', label: '3D models', icon: 'cube' }, { view: 'kind:splat', label: 'Worlds', icon: 'globe' }, ], [{ view: 'favorites', label: 'Favourites', icon: 'star' }], @@ -79,7 +79,8 @@ export class LibrarySidebar { `
    ${t('Tags')}` + `
    ` + `
    ` + - `
    ` + + `
    ` + + `` + navRow({ view: 'hidden', label: 'Hidden', icon: 'eyeOff' }) + `
    `, ); diff --git a/frontend/src/ui/library/library-studio.ts b/frontend/src/ui/library/library-studio.ts index a6a28e0..3bb2a0a 100644 --- a/frontend/src/ui/library/library-studio.ts +++ b/frontend/src/ui/library/library-studio.ts @@ -7,8 +7,10 @@ import { el, isMac, patchList, pendingClass, q, setAttr, setClass, setDisabled, import { onLanguage, relabel, t, tn } from '../i18n'; import { icon } from '../icons'; import { inDesktop } from '../prefs'; +import { encoderOffered } from '../rendering'; import { openUploadDialog } from '../upload/upload-dialog'; import { openCharacters } from './characters'; +import { addListToBoard, applies, openResultMenu, runResultAction } from '../feed/result-actions'; import { ContextMenu, type MenuRow } from './context-menu'; import { beginDrag } from './drag'; import { CHUNK_MAX, COL_MAX, COL_MIN, PAGE, Pager, SEARCH_MS, folderColor, newer, readColumns, readPref, thumbKind, writePref, type PagerFilter } from './grid-shared'; @@ -35,7 +37,7 @@ const TITLES: Record = { 'kind:image': 'Images', 'kind:video': 'Videos', 'kind:audio': 'Audio', - 'kind:model': '3D objects', + 'kind:model': '3D models', 'kind:splat': 'Worlds', favorites: 'Favourites', 'source:generated': 'Generated', @@ -178,12 +180,14 @@ class LibraryStudio { `` + `` + `` + + `` + `` + `
    ` + `` + `` + `
    ` + - `` + + `` + `${t('Loading')}
    `, ); const main = q(this.root, '.fc-ls-main'); @@ -570,6 +574,7 @@ class LibraryStudio { else if (act === 'moveto') void this.actions.chooseFolder(ids, true); else if (act === 'leave') void this.actions.leave(this.picked(), this.view.slice(7)); else if (act === 'tags') void this.actions.tags(ids); + else if (act === 'board') void addListToBoard(this.picked().filter((m) => applies('add-to-board', m))); else if (act === 'download') void this.actions.download(ids); else if (act === 'delete') void this.actions.remove(ids); } @@ -597,7 +602,21 @@ class LibraryStudio { { id: 'tags', label: 'Tags', icon: 'tag', run: () => void this.actions.tags(ids) }, { id: 'fav', label: all ? 'Remove from favourites' : 'Add to favourites', icon: all ? 'starFilled' : 'star', keys: 'F', run: () => void this.actions.favorite(ids, !all) }, ); - if (one && one.kind === 'image') rows.push({ id: 'edit', label: 'Edit image', icon: 'canvas', run: () => this.actions.edit(one) }); + if (one) rows.push({ id: 'rename', label: 'Rename', icon: 'pencil', run: () => void this.actions.rename(one) }); + if (one && (one.kind === 'video' || one.kind === 'audio') && encoderOffered()) rows.push({ id: 'encoder', label: 'Send to FormEncoder', icon: 'video', run: () => void this.actions.encode(one) }); + rows.push({ id: 'hide', label: hidden ? 'Show again' : 'Hide', icon: hidden ? 'eye' : 'eyeOff', run: () => void this.actions.hide(ids, !hidden) }); + if (one) { + openResultMenu(one, x, y, { + lead: rows, + returnTo: this.grid.el, + run: (id) => { + if (id === 'delete') void this.actions.remove(ids); + else if (id === 'download') void this.actions.download(ids); + else void runResultAction(id, one); + }, + }); + return; + } const editable = sel.filter((m) => m.kind === 'image' || m.kind === 'video' || m.kind === 'audio'); if (editable.length) { rows.push({ @@ -610,11 +629,10 @@ class LibraryStudio { }, }); } - if (one) rows.push({ id: 'rename', label: 'Rename', icon: 'pencil', run: () => void this.actions.rename(one) }); - rows.push({ id: 'download', label: 'Download', icon: 'download', run: () => void this.actions.download(ids) }); - if (one && inDesktop()) rows.push({ id: 'reveal', label: 'Show in folder', icon: 'folderOpen', run: () => void this.actions.reveal(one) }); + const boardable = sel.filter((m) => applies('add-to-board', m)); + if (boardable.length) rows.push({ id: 'addboard', label: 'Add to board', icon: 'board', run: () => void addListToBoard(boardable) }); rows.push( - { id: 'hide', label: hidden ? 'Show again' : 'Hide', icon: hidden ? 'eye' : 'eyeOff', run: () => void this.actions.hide(ids, !hidden) }, + { id: 'download', label: 'Download', icon: 'download', run: () => void this.actions.download(ids) }, '-', { id: 'delete', label: 'Delete', icon: 'trash', danger: true, keys: 'Del', run: () => void this.actions.remove(ids) }, ); diff --git a/frontend/src/ui/library/library-window.css b/frontend/src/ui/library/library-window.css new file mode 100644 index 0000000..adb7e64 --- /dev/null +++ b/frontend/src/ui/library/library-window.css @@ -0,0 +1,43 @@ +.fc-lw { position: fixed; top: 0; left: 0; z-index: var(--z-temp); display: flex; flex-direction: column; min-width: 0; min-height: 0; border: 1px solid var(--line-3); border-radius: var(--radius-xl); background: var(--surface-2); color: var(--text-primary); font-size: var(--fs-12); box-shadow: var(--shadow-window); outline: none; transition: opacity var(--transition-fast); } +.fc-lw[hidden] { display: none; } +.fc-lw button, .fc-lw input { font: inherit; color: inherit; } +.fc-lw.is-moving { user-select: none; -webkit-user-select: none; } +.fc-lw.is-dragging { opacity: 0.85; } +#overlay-root > .fc-lw.is-dragging.is-through { opacity: 0.25; pointer-events: none; } +.fc-lw-head { display: flex; flex: none; align-items: center; gap: var(--space-2); height: var(--ctl-lg); padding: 0 var(--space-2) 0 var(--space-3); border-bottom: 1px solid var(--line-1); cursor: grab; touch-action: none; user-select: none; -webkit-user-select: none; } +.fc-lw.is-moving .fc-lw-head { cursor: grabbing; } +.fc-lw-title { display: inline-flex; flex: none; align-items: center; gap: var(--space-1); font-weight: 600; } +.fc-lw-tabs { display: flex; flex: 1 1 auto; justify-content: center; gap: var(--space-1); min-width: 0; } +.fc-lw-tab { height: var(--ctl-sm); padding: 0 var(--space-3); border: 0; border-radius: var(--radius-pill); background: transparent; color: var(--text-secondary); cursor: pointer; } +.fc-lw-tab:hover { background: var(--bg-hover); } +.fc-lw-tab[aria-selected="true"] { background: var(--accent-soft); color: var(--text-primary); } +.fc-lw-tab:focus-visible, .fc-lw-chip:focus-visible, .fc-lw-close:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fc-lw-close { flex: none; } +.fc-lw-bar { display: flex; flex: none; padding: var(--space-2) var(--space-3) 0; } +.fc-lw-find { display: flex; flex: 1 1 auto; align-items: center; gap: var(--space-1); min-width: 0; height: var(--ctl-md); padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--surface-field); color: var(--text-muted); } +.fc-lw-find input { flex: 1 1 auto; min-width: 0; border: 0; outline: none; background: transparent; } +.fc-lw-chips { display: flex; flex: none; gap: var(--space-1); height: calc(var(--ctl-sm) + 2 * var(--space-2)); align-items: center; padding: 0 var(--space-3); overflow-x: auto; overflow-y: hidden; scrollbar-width: none; } +.fc-lw-chip { flex: none; height: var(--ctl-sm); padding: 0 var(--space-2); border: 1px solid var(--line-1); border-radius: var(--radius-pill); background: transparent; font-size: var(--fs-11); color: var(--text-secondary); cursor: pointer; } +.fc-lw-chip[hidden] { display: none; } +.fc-lw-chip:hover { background: var(--bg-hover); } +.fc-lw-chip[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent-line); color: var(--text-primary); } +.fc-lw-stage { position: relative; display: flex; flex: 1 1 0; flex-direction: column; min-height: 0; padding: 0 var(--space-3); } +.fc-lw-stage > .fc-ls-scroll[hidden] { display: none; } +.fc-lw .fc-ls-hbtn[data-act="fav"], .fc-lw .fc-ls-fav { display: none; } +.fc-lw-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; margin: 0; padding: var(--space-6); color: var(--text-muted); text-align: center; pointer-events: none; } +.fc-lw-empty[hidden] { display: none; } +.fc-lw-foot { display: flex; flex: none; align-items: center; justify-content: space-between; gap: var(--space-2); min-height: var(--ctl-md); padding: 0 var(--space-3); border-top: 1px solid var(--line-1); color: var(--text-muted); font-size: var(--fs-11); } +.fc-lw-keep { display: inline-flex; flex: none; align-items: center; gap: var(--space-1); color: var(--text-secondary); cursor: pointer; } +.fc-lw-hint { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fc-lw-edge { position: absolute; touch-action: none; } +.fc-lw-edge[data-edge="n"] { top: -3px; left: 8px; right: 8px; height: 6px; cursor: ns-resize; } +.fc-lw-edge[data-edge="s"] { bottom: -3px; left: 8px; right: 8px; height: 6px; cursor: ns-resize; } +.fc-lw-edge[data-edge="e"] { top: 8px; bottom: 8px; right: -3px; width: 6px; cursor: ew-resize; } +.fc-lw-edge[data-edge="w"] { top: 8px; bottom: 8px; left: -3px; width: 6px; cursor: ew-resize; } +.fc-lw-edge[data-edge="ne"] { top: -3px; right: -3px; width: 12px; height: 12px; cursor: nesw-resize; } +.fc-lw-edge[data-edge="sw"] { bottom: -3px; left: -3px; width: 12px; height: 12px; cursor: nesw-resize; } +.fc-lw-edge[data-edge="nw"] { top: -3px; left: -3px; width: 12px; height: 12px; cursor: nwse-resize; } +.fc-lw-edge[data-edge="se"] { bottom: -3px; right: -3px; width: 12px; height: 12px; cursor: nwse-resize; } +.fc-host.is-drop { outline: 2px solid var(--accent-color); outline-offset: -2px; } +.fc-etl-lane.is-drop { background: var(--accent-soft); box-shadow: inset 0 0 0 1px var(--accent-color); } +@media (prefers-reduced-motion: reduce) { .fc-lw { transition: none; } } diff --git a/frontend/src/ui/library/library-window.ts b/frontend/src/ui/library/library-window.ts new file mode 100644 index 0000000..2ae9ee6 --- /dev/null +++ b/frontend/src/ui/library/library-window.ts @@ -0,0 +1,490 @@ +import '../../styles/library-studio.css'; +import './library-window.css'; +import { studios } from '../../engine/studios'; +import { listMedia, mediaThumbUrl, type Media, type MediaKind, type MediaQuery } from '../../io/api'; +import { el, q, setClass, setHidden, setText } from '../dom'; +import { t } from '../i18n'; +import { icon } from '../icons'; +import { commands } from '../../engine/commands'; +import { shortcuts } from '../../engine/shortcuts'; +import { toast } from '../toasts'; +import { beginDrag, dragging } from './drag'; +import { SEARCH_MS, readPref, thumbKind, thumbWidth, writePref } from './grid-shared'; +import { VirtualGrid } from './virtual-grid'; +import { asMedia, listStarter, starterThumbUrl, type StarterItem, type StarterKind } from './starter/api-starter'; +import { renderedStamp, wantThumbs } from './starter/starter-thumbs'; +import { addToLibrary, targetStudio, trackStudios, useInStudio } from './starter/starter-use'; + +type Tab = 'library' | 'starter' | 'outputs'; +type Host = 'scene' | 'canvas' | 'board' | 'edit'; +interface Geo { x: number; y: number; w: number; h: number } +interface Chip { id: string; label: string; media?: MediaKind; starter: StarterKind[] } + +const HOSTS: readonly Host[] = ['scene', 'canvas', 'board', 'edit']; +const ACCEPT: Record> = { + scene: new Set(['model', 'splat', 'image', 'video']), + canvas: new Set(['image', 'model']), + board: new Set(['image', 'video']), + edit: new Set(['video', 'image', 'audio']), +}; +const TIP: Record = { scene: 'Add to Scene', canvas: 'Add to Canvas', board: 'Add to Board', edit: 'Add to Edit' }; +const CHIPS: Chip[] = [ + { id: 'all', label: 'All', starter: [] }, + { id: 'image', label: 'Images', media: 'image', starter: ['image', 'sprite'] }, + { id: 'video', label: 'Video', media: 'video', starter: ['video'] }, + { id: 'audio', label: 'Sound', media: 'audio', starter: ['audio'] }, + { id: 'model', label: '3D', media: 'model', starter: ['3d'] }, + { id: 'texture', label: 'Textures', starter: ['texture'] }, + { id: 'hdri', label: 'HDRIs', starter: ['hdri'] }, +]; +const TABS: Array<[Tab, string]> = [['library', 'Library'], ['starter', 'Starter'], ['outputs', 'Outputs']]; +const EDGES = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw']; +const PAGE = 120; +const COLUMNS = 4; +const MIN_W = 340; +const MIN_H = 300; +const KEEP_KEY = 'fc.libwin.keep'; +const GEO_KEY = 'fc.libwin.geo.'; + +class StarterGrid extends VirtualGrid {} +Object.defineProperty(StarterGrid.prototype, 'url', { + value(this: { cols: number }, m: Media): string { + return starterThumbUrl(m.id, thumbWidth(this.cols)) + renderedStamp(m.id); + }, +}); + +const hostOf = (node: Element | null): Host | null => { + const id = node?.closest('.fc-host[data-host]')?.dataset.host; + return id && (HOSTS as readonly string[]).includes(id) ? (id as Host) : null; +}; + +async function dropOn(host: Host, items: Media[], starter: StarterItem[], x: number, y: number): Promise { + if (host === 'scene') { + const [{ sceneApi }, { addMedia }, { spotUnder }] = await Promise.all([import('../scene/bridge'), import('../scene/presets/sources'), import('../scene/presets/place')]); + const ctx = await sceneApi(); + const over = document.elementFromPoint(x, y) === ctx.view.canvas; + const special = starter.length === 1 && (starter[0].kind === 'hdri' || starter[0].kind === 'texture') ? starter[0] : null; + if (special?.kind === 'hdri') { + const { setSceneEnvMap } = await import('../scene/materials/env-map'); + const ok = await setSceneEnvMap(ctx, items[0].id, special.file.slice(special.file.lastIndexOf('/') + 1)); + if (ok) toast(t('Set as the scene environment. It is saved with the project.'), 'success', { key: 'starter-used' }); + return ok; + } + if (special?.kind === 'texture') { + const { applyMaterialMedia } = await import('../scene/materials/use'); + const under = over ? ctx.view.pickAt(x, y) : null; + if (under) ctx.store.select(under); + return applyMaterialMedia(ctx, items[0]); + } + return addMedia(ctx, items, over ? spotUnder(ctx, x, y) : undefined).length > 0; + } + if (host === 'canvas') { + const [{ canvasApi }, place] = await Promise.all([import('../canvas/base/bridge'), import('../canvas/base/place')]); + const ctx = await canvasApi(); + if (!ctx.store.base) { + toast(t('Start a canvas page first.'), 'info', { key: 'canvas-drawer-empty' }); + return false; + } + if ((await place.dropMedia(ctx, items, x, y)) > 0) return true; + return (await place.addCentred(ctx, items)) > 0; + } + if (host === 'board') { + const { dropMediaOnBoard } = await import('../board'); + const ok = await dropMediaOnBoard(items, x, y); + if (!ok) toast(t('Open a board to add files.'), 'info', { key: 'board-drawer-empty' }); + return ok; + } + const { dropMediaInEdit } = await import('../edit/library-drop'); + return (await dropMediaInEdit(items, x, y)) > 0; +} + +async function useMedia(m: Media): Promise { + const host = targetStudio() as Host; + if (!ACCEPT[host]?.has(m.kind)) { + toast(t('Added to your library. Open a studio first to use it there.'), 'info', { key: 'starter-used' }); + return false; + } + if (host === 'edit') { + const { openInEdit } = await import('../edit/bridge'); + await openInEdit([m.id]); + return true; + } + studios.activate(host); + const r = document.querySelector(`.fc-host[data-host="${host}"]`)?.getBoundingClientRect(); + const x = r ? r.left + r.width / 2 : window.innerWidth / 2; + const y = r ? r.top + r.height / 2 : window.innerHeight / 2; + if (host === 'scene') { + const [{ sceneApi }, { addMedia }] = await Promise.all([import('../scene/bridge'), import('../scene/presets/sources')]); + return addMedia(await sceneApi(), [m]).length > 0; + } + return dropOn(host, [m], [], x, y); +} + +class LibraryWindow { + readonly root: HTMLElement; + private tab: Tab = 'library'; + private chip = 'all'; + private term = ''; + private run = 0; + private loaded = 0; + private total = 0; + private busy = false; + private timer = 0; + private geo: Geo | null = null; + private geoKey = ''; + private readonly starter = new Map(); + private readonly grid: VirtualGrid; + private readonly sgrid: StarterGrid; + private readonly stage: HTMLElement; + private readonly empty: HTMLElement; + private readonly chips: HTMLElement; + private readonly keep: HTMLInputElement; + private readonly qInput: HTMLInputElement; + + constructor() { + const hooks = (starter: boolean): ConstructorParameters[0] => ({ + selection: () => undefined, + open: (m) => void this.use(m, starter), + menu: () => undefined, + favorite: () => undefined, + more: () => void this.pull(this.run), + remove: () => undefined, + drag: (e, ids) => this.drag(e, ids, starter), + }); + this.grid = new VirtualGrid(hooks(false)); + this.sgrid = new StarterGrid(hooks(true)); + for (const g of [this.grid, this.sgrid]) { + g.setGrouped(false); + g.setColumns(COLUMNS); + } + this.root = el( + ``, + ); + this.stage = q(this.root, '.fc-lw-stage'); + this.empty = q(this.root, '.fc-lw-empty'); + this.chips = q(this.root, '.fc-lw-chips'); + this.keep = q(this.root, '.fc-lw-keep input'); + this.qInput = q(this.root, '.fc-lw-find input'); + this.keep.checked = readPref(KEEP_KEY) !== '0'; + this.stage.insertBefore(this.grid.el, this.empty); + this.stage.insertBefore(this.sgrid.el, this.empty); + setHidden(this.sgrid.el, true); + (document.getElementById('overlay-root') ?? document.body).appendChild(this.root); + this.wire(); + } + + get open(): boolean { + return !this.root.hidden; + } + + toggle(): void { + if (this.open) this.close(); + else this.show(); + } + + show(): void { + if (this.open) return; + this.place(this.load()); + setHidden(this.root, false); + if (!this.loaded) this.reload(); + this.root.focus({ preventScroll: true }); + for (const fn of listeners) fn(true); + } + + close(): void { + if (!this.open) return; + setHidden(this.root, true); + for (const fn of listeners) fn(false); + } + + private wire(): void { + q(this.root, '.fc-lw-close').addEventListener('click', () => this.close()); + window.addEventListener('keydown', (e) => { + if (e.key !== 'Escape' || dragging() || !this.open || !this.root.contains(document.activeElement)) return; + e.preventDefault(); + e.stopPropagation(); + this.close(); + }, true); + q(this.root, '.fc-lw-tabs').addEventListener('click', (e) => { + const id = (e.target as Element).closest('[data-tab]')?.dataset.tab as Tab | undefined; + if (!id || id === this.tab) return; + this.tab = id; + for (const b of this.root.querySelectorAll('[data-tab]')) b.setAttribute('aria-selected', String(b.dataset.tab === id)); + const starter = id === 'starter'; + setHidden(this.grid.el, starter); + setHidden(this.sgrid.el, !starter); + for (const b of this.chips.querySelectorAll('[data-chip]')) { + const c = CHIPS.find((x) => x.id === b.dataset.chip) as Chip; + setHidden(b, !(c.id === 'all' || (starter ? c.starter.length : c.media))); + } + if (!starter && !CHIPS.find((c) => c.id === this.chip)?.media) this.setChip('all'); + this.reload(); + }); + this.chips.addEventListener('click', (e) => { + const id = (e.target as Element).closest('[data-chip]')?.dataset.chip; + if (!id || id === this.chip) return; + this.setChip(id); + this.reload(); + }); + this.qInput.addEventListener('input', () => { + window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => { + this.term = this.qInput.value.trim(); + this.reload(); + }, SEARCH_MS); + }); + this.keep.addEventListener('change', () => writePref(KEEP_KEY, this.keep.checked ? '1' : '0')); + q(this.root, '.fc-lw-head').addEventListener('pointerdown', (e) => { + if (e.button !== 0 || (e.target as Element).closest('button')) return; + this.gesture(e, ''); + }); + for (const h of this.root.querySelectorAll('.fc-lw-edge')) h.addEventListener('pointerdown', (e) => e.button === 0 && this.gesture(e, h.dataset.edge ?? '')); + window.addEventListener('resize', () => this.open && this.geo && this.place(this.geo)); + studios.on('active', () => { + if (this.open && this.key() !== this.geoKey) this.place(this.load()); + }); + } + + private setChip(id: string): void { + this.chip = id; + for (const b of this.chips.querySelectorAll('[data-chip]')) b.setAttribute('aria-pressed', String(b.dataset.chip === id)); + } + + private key(): string { + return GEO_KEY + (studios.activeRoot || 'home'); + } + + private load(): Geo { + this.geoKey = this.key(); + try { + const g = JSON.parse(readPref(this.geoKey) ?? '') as Geo; + if ([g.x, g.y, g.w, g.h].every((n) => Number.isFinite(n))) return g; + } catch { + this.geoKey = this.key(); + } + const w = Math.min(560, window.innerWidth - 48); + const h = Math.min(620, window.innerHeight - 120); + return { x: window.innerWidth - w - 24, y: 72, w, h }; + } + + private place(g: Geo): void { + const vw = window.innerWidth; + const vh = window.innerHeight; + const w = Math.max(Math.min(MIN_W, vw), Math.min(g.w, vw)); + const h = Math.max(Math.min(MIN_H, vh), Math.min(g.h, vh)); + const next = { w, h, x: Math.min(Math.max(0, g.x), vw - w), y: Math.min(Math.max(0, g.y), vh - h) }; + this.geo = next; + const s = this.root.style; + s.translate = `${next.x}px ${next.y}px`; + s.width = `${next.w}px`; + s.height = `${next.h}px`; + } + + private gesture(e: PointerEvent, edge: string): void { + e.preventDefault(); + const start = this.geo ?? this.load(); + const x0 = e.clientX; + const y0 = e.clientY; + const target = e.currentTarget as HTMLElement; + try { + target.setPointerCapture(e.pointerId); + } catch { + target.dataset.cap = '0'; + } + setClass(this.root, 'is-moving', true); + const move = (ev: PointerEvent): void => { + const dx = ev.clientX - x0; + const dy = ev.clientY - y0; + if (!edge) return this.place({ ...start, x: start.x + dx, y: start.y + dy }); + const g = { ...start }; + if (edge.includes('e')) g.w = Math.max(MIN_W, start.w + dx); + if (edge.includes('s')) g.h = Math.max(MIN_H, start.h + dy); + if (edge.includes('w')) { + g.w = Math.max(MIN_W, start.w - dx); + g.x = start.x + start.w - g.w; + } + if (edge.includes('n')) { + g.h = Math.max(MIN_H, start.h - dy); + g.y = start.y + start.h - g.h; + } + this.place(g); + }; + const up = (): void => { + target.removeEventListener('pointermove', move); + target.removeEventListener('pointerup', up); + target.removeEventListener('pointercancel', up); + setClass(this.root, 'is-moving', false); + if (this.geo) writePref(this.geoKey, JSON.stringify(this.geo)); + }; + target.addEventListener('pointermove', move); + target.addEventListener('pointerup', up); + target.addEventListener('pointercancel', up); + } + + private reload(): void { + this.run++; + this.loaded = 0; + this.total = 0; + this.busy = false; + void this.pull(this.run, true); + } + + private async pull(run: number, first = false): Promise { + if (this.busy || (!first && this.loaded >= this.total)) return; + this.busy = true; + const chip = CHIPS.find((c) => c.id === this.chip) as Chip; + const starter = this.tab === 'starter'; + const grid = starter ? this.sgrid : this.grid; + try { + let list: Media[]; + let total: number; + if (starter) { + const page = await listStarter({ kinds: chip.starter, q: this.term, offset: this.loaded, limit: PAGE }); + if (run !== this.run) return; + for (const item of page.items) this.starter.set(item.uid, item); + wantThumbs(page.items); + list = page.items.map(asMedia); + total = page.total; + } else { + const query: MediaQuery = { q: this.term || undefined, kind: chip.media, offset: this.loaded, limit: PAGE, sort: 'new' }; + if (this.tab === 'outputs') query.source = 'generated'; + const page = await listMedia(query); + if (run !== this.run) return; + list = page.items; + total = page.total; + } + if (first) grid.setItems(list, total); + else grid.append(list, total); + this.loaded += list.length; + this.total = total; + this.paintEmpty(first && !list.length ? (this.term ? 'Nothing matches the search.' : 'Nothing here yet.') : ''); + } catch (err) { + if (run !== this.run) return; + if (first) grid.setItems([], 0); + this.paintEmpty(err instanceof Error ? err.message : 'The library could not be read.'); + } finally { + if (run === this.run) this.busy = false; + } + } + + private paintEmpty(text: string): void { + setText(this.empty, text ? t(text) : ''); + setHidden(this.empty, !text); + } + + private async media(ids: string[], starter: boolean): Promise<{ items: Media[]; starter: StarterItem[] }> { + if (!starter) return { items: ids.map((id) => this.grid.get(id)).filter((m): m is Media => !!m), starter: [] }; + const picked = ids.map((id) => this.starter.get(id)).filter((s): s is StarterItem => !!s); + const items: Media[] = []; + for (const s of picked) { + const m = await addToLibrary(s, true); + if (m) items.push(m); + } + return { items, starter: picked }; + } + + private done(ok: boolean): void { + if (ok && !this.keep.checked) this.close(); + } + + private async use(m: Media, starter: boolean): Promise { + if (starter) { + const item = this.starter.get(m.id); + if (!item) return; + await useInStudio(item); + this.done(true); + return; + } + this.done(await useMedia(m).catch(() => false)); + } + + private drag(e: PointerEvent, ids: string[], starter: boolean): void { + const grid = starter ? this.sgrid : this.grid; + const shown = ids.map((id) => grid.get(id)).filter((m): m is Media => !!m); + if (!shown.length) return; + const kinds = new Set(starter ? shown.map((m) => this.starter.get(m.id)?.kind ?? '') : []); + const special = starter && shown.length === 1 && (kinds.has('hdri') || kinds.has('texture')); + const marked: HTMLElement[] = []; + for (const h of HOSTS) { + const node = document.querySelector(`.fc-host[data-host="${h}"]`); + if (node && !node.hidden && node.dataset.drop === undefined) { + node.dataset.drop = h; + marked.push(node); + } + } + for (const lane of document.querySelectorAll('.fc-host[data-host="edit"] .fc-etl-lane[data-track]')) { + if (lane.dataset.drop !== undefined) continue; + lane.dataset.drop = 'edit'; + marked.push(lane); + } + const rect = this.root.getBoundingClientRect(); + let x = e.clientX; + let y = e.clientY; + const track = (ev: PointerEvent): void => { + x = ev.clientX; + y = ev.clientY; + setClass(this.root, 'is-through', x < rect.left || x > rect.right || y < rect.top || y > rect.bottom); + }; + window.addEventListener('pointermove', track, true); + window.addEventListener('pointerup', track, true); + setClass(this.root, 'is-dragging', true); + beginDrag(e, { + thumbs: shown.filter((m) => thumbKind(m.kind)).slice(0, 3).map((m) => (starter ? starterThumbUrl(m.id, 128) : mediaThumbUrl(m.id, 128))), + glyph: 'image', + count: shown.length, + copyable: false, + accept: (zone) => { + const host = zone as Host; + if (special) return host === 'scene'; + return shown.some((m) => ACCEPT[host]?.has(m.kind)); + }, + tip: (zone) => t(special ? (kinds.has('hdri') ? 'Set as environment' : 'Apply material') : TIP[zone as Host]), + drop: (zone) => { + const host = hostOf(document.elementFromPoint(x, y)) ?? (zone as Host); + void this.media(ids, starter) + .then((got) => (got.items.length ? dropOn(host, got.items, got.starter, x, y) : false)) + .then((ok) => this.done(ok)) + .catch((err) => console.error('[library-window] drop', err)); + }, + end: () => { + window.removeEventListener('pointermove', track, true); + window.removeEventListener('pointerup', track, true); + for (const node of marked) delete node.dataset.drop; + setClass(this.root, 'is-dragging', false); + setClass(this.root, 'is-through', false); + }, + }); + } +} + +let win: LibraryWindow | null = null; +const listeners = new Set<(open: boolean) => void>(); + +export function onLibraryWindow(fn: (open: boolean) => void): void { + listeners.add(fn); +} + +export function libraryWindow(): LibraryWindow { + if (!win) { + trackStudios(); + win = new LibraryWindow(); + } + return win; +} + +export function registerLibraryWindow(): void { + if (commands.get('show-library')) return; + const cmd = { id: 'show-library', label: 'Show Library', group: 'View', keys: ['Mod+Alt+KeyL'], checked: () => !!win?.open, run: () => libraryWindow().toggle() }; + commands.register(cmd); + shortcuts.adopt([cmd]); +} diff --git a/frontend/src/ui/library/starter/api-starter.ts b/frontend/src/ui/library/starter/api-starter.ts new file mode 100644 index 0000000..9b032ec --- /dev/null +++ b/frontend/src/ui/library/starter/api-starter.ts @@ -0,0 +1,109 @@ +import { request, type Media, type MediaKind } from '../../../io/api'; + +export type StarterKind = '3d' | 'texture' | 'hdri' | 'image' | 'sprite' | 'video' | 'audio'; + +export interface StarterPack { + id: string; + name: string; + kind: StarterKind; + section: string; + licence: string; + author: string; + sourceUrl: string; + version: string; + retrieved: string; + licenceEvidence: string; + count: number; + bytes: number; +} + +export interface StarterItem { + uid: string; + id: string; + pack: string; + name: string; + file: string; + kind: StarterKind; + mediaKind: MediaKind; + mime: string; + category: string; + tags: string[]; + bytes: number; + seconds: number | null; + maps: Record; + thumb: boolean; + material?: string; + map?: string; + rigged?: boolean; + animations?: string[]; + sourcePage?: string; +} + +const LICENCE_LABEL: Record = { 'CC0-1.0': 'CC0 1.0', 'CC-PD-Dedication-1.0-legacy': 'Public domain dedication','public-domain': 'Public domain', 'public-domain-us': 'Public domain (US)' }; +export const licenceLabel = (licence: string | undefined): string => LICENCE_LABEL[licence ?? 'CC0-1.0'] ?? licence ?? 'CC0 1.0'; + +export interface Counted { name: string; count: number } + +export interface StarterPage { + available: boolean; + packs: StarterPack[]; + kinds: Counted[]; + categories: Counted[]; + items: StarterItem[]; + total: number; + problems: string[]; +} + +export interface StarterQuery { kinds?: StarterKind[]; category?: string; pack?: string; q?: string; offset?: number; limit?: number } + +const BASE = '/api/starter'; +const path = (uid: string): string => uid.split('/').map(encodeURIComponent).join('/'); + +export function listStarter(query: StarterQuery, signal?: AbortSignal): Promise { + const search = new URLSearchParams(); + for (const k of query.kinds ?? []) search.append('kind', k); + if (query.category) search.set('category', query.category); + if (query.pack) search.set('pack', query.pack); + if (query.q) search.set('q', query.q); + search.set('offset', String(query.offset ?? 0)); + search.set('limit', String(query.limit ?? 100)); + return request('GET', `/starter?${search.toString()}`, undefined, { signal }); +} + +export const starterCredits = (): Promise<{ packs: StarterPack[]; problems: string[] }> => request('GET', '/starter/credits'); +export const addStarterItem = (uid: string): Promise => request('POST', `/starter/items/${path(uid)}/add`); +export async function putStarterThumb(uid: string, image: Blob): Promise { + const res = await fetch(`${BASE}/items/${path(uid)}/thumb`, { method: 'PUT', body: image, headers: { 'Content-Type': image.type || 'application/octet-stream' } }); + if (!res.ok) throw new Error(`thumb ${res.status}`); +} +export const starterFileUrl =(uid: string): string => `${BASE}/items/${path(uid)}/file`; +export const starterThumbUrl = (uid: string, width: number): string => `${BASE}/items/${path(uid)}/thumb?w=${width}`; +export const starterLicenceUrl = (pack: string): string => `${BASE}/packs/${encodeURIComponent(pack)}/licence`; + +export function displayName(item: StarterItem): string { + const dot = item.file.lastIndexOf('.'); + const ext = dot > 0 ? item.file.slice(dot) : ''; + return ext && !item.name.toLowerCase().endsWith(ext.toLowerCase()) ? `${item.name}${ext}` : item.name; +} + +export function asMedia(item: StarterItem): Media { + return { + id: item.uid, + kind: item.mediaKind, + name: displayName(item), + mime: item.mime, + bytes: item.bytes, + width: null, + height: null, + durationSec: item.seconds, + createdAt: '', + source: 'import', + jobId: null, + prompt: null, + favorite: false, + hidden: false, + coverId: item.uid, + folders: [], + tags: item.tags, + }; +} diff --git a/frontend/src/ui/library/starter/starter-credits.ts b/frontend/src/ui/library/starter/starter-credits.ts new file mode 100644 index 0000000..406f969 --- /dev/null +++ b/frontend/src/ui/library/starter/starter-credits.ts @@ -0,0 +1,57 @@ +import { openExternal } from '../../board/shell/media'; +import { Dialog } from '../../dialogs'; +import { el, escapeHtml, q, setText } from '../../dom'; +import { t } from '../../i18n'; +import { licenceLabel, starterCredits } from './api-starter'; + +let dialog: Dialog | null = null; +let list: HTMLElement | null = null; + +function build(): Dialog { + const d = new Dialog('Starter library credits', 560); + d.body.append( + el(`

    ${escapeHtml(t('The starter library is CC0 1.0: public domain, free for any use. Credit is not required, but here is where each pack came from.'))}

    `), + el('
      '), + ); + list = q(d.body, '.fc-st-credits'); + list.addEventListener('click', (e) => { + const a = (e.target as Element).closest('a.fc-st-link'); + if (!a) return; + e.preventDefault(); + void openExternal(a.href); + }); + d.button('OK', 'primary', () => d.close()); + return d; +} + +async function fill(): Promise { + if (!list) return; + const box = list; + try { + const { packs } = await starterCredits(); + if (!packs.length) { + box.innerHTML = ''; + box.append(el(`
    • `)); + setText(box.firstElementChild, t('No starter packs are in this build.')); + return; + } + box.innerHTML = packs + .map( + (p) => + `
    • ${escapeHtml(p.name)} ${escapeHtml(t(licenceLabel(p.licence)))} · ${escapeHtml(p.author)} · ${p.count}` + + (/^https?:\/\//.test(p.sourceUrl) ? `${escapeHtml(p.sourceUrl)}` : `${escapeHtml(p.sourceUrl)}`) + + `${escapeHtml(p.version)} · ${escapeHtml(p.retrieved)}
    • `, + ) + .join(''); + } catch (err) { + box.innerHTML = ''; + box.append(el(`
    • `)); + setText(box.firstElementChild, err instanceof Error ? err.message : t('The starter library could not be read.')); + } +} + +export function showStarterCredits(): void { + dialog ??= build(); + dialog.open(); + void fill(); +} diff --git a/frontend/src/ui/library/starter/starter-picker.ts b/frontend/src/ui/library/starter/starter-picker.ts new file mode 100644 index 0000000..2f15ca4 --- /dev/null +++ b/frontend/src/ui/library/starter/starter-picker.ts @@ -0,0 +1,478 @@ +import '../../../styles/library-studio.css'; +import '../../../styles/library-modal.css'; +import '../../../styles/about.css'; +import './starter.css'; +import { commands } from '../../../engine/commands'; +import type { Media } from '../../../io/api'; +import { openExternal } from '../../board/shell/media'; +import { Dialog } from '../../dialogs'; +import { el, escapeHtml, q, setAttr, setClass, setDisabled, setHidden, setText } from '../../dom'; +import { t, tn } from '../../i18n'; +import { icon } from '../../icons'; +import { ContextMenu, type MenuRow } from '../context-menu'; +import { SEARCH_MS, thumbWidth } from '../grid-shared'; +import { VirtualGrid } from '../virtual-grid'; +import { asMedia, licenceLabel, listStarter, starterFileUrl, starterLicenceUrl, starterThumbUrl, type StarterItem, type StarterKind, type StarterPack } from './api-starter'; +import { dropQueue, onRendered, renderedStamp, wantThumbs } from './starter-thumbs'; +import { addToLibrary, trackStudios, useInStudio } from './starter-use'; + +export interface StarterOptions { kinds?: StarterKind[]; max?: number; title?: string; pick?: boolean } + +interface KindTab { id: string; label: string; kinds: StarterKind[] } + +const TABS: KindTab[] = [ + { id: 'all', label: 'All', kinds: [] }, + { id: '3d', label: '3D', kinds: ['3d'] }, + { id: 'texture', label: 'Textures', kinds: ['texture'] }, + { id: 'hdri', label: 'HDRIs', kinds: ['hdri'] }, + { id: 'image', label: 'Images', kinds: ['image', 'sprite'] }, + { id: 'video', label: 'Video', kinds: ['video'] }, + { id: 'audio', label: 'Audio', kinds: ['audio'] }, +]; + +const PAGE = 120; +const COLUMNS = 6; +const HOVER_MS = 260; +const KIND_WORD: Record = { '3d': '3D model', texture: 'Texture', hdri: 'HDRI', image: 'Image', sprite: 'Sprite', video: 'Video', audio: 'Sound' }; + +const rigged = new Set(); + +class StarterGrid extends VirtualGrid {} +Object.defineProperty(StarterGrid.prototype, 'url', { + value(this: { cols: number }, m: Media): string { + return starterThumbUrl(m.id, thumbWidth(this.cols)) + renderedStamp(m.id); + }, +}); +const baseBind = (VirtualGrid.prototype as unknown as { bind(tile: { node: HTMLElement; badge: HTMLElement }, i: number): void }).bind; +Object.defineProperty(StarterGrid.prototype, 'bind', { + value(this: unknown, tile: { node: HTMLElement; badge: HTMLElement }, i: number): void { + baseBind.call(this, tile, i); + if (!rigged.has(tile.node.dataset.id ?? '')) return; + setText(tile.badge, t('Rigged')); + setHidden(tile.badge, false); + }, +}); + +class StarterPicker extends Dialog { + private opts: StarterOptions = {}; + private tab = 'all'; + private category = ''; + private term = ''; + private run = 0; + private loaded = 0; + private total = 0; + private busy = false; + private packs = new Map(); + private readonly items = new Map(); + private settle: ((items: Media[]) => void) | null = null; + private searchTimer = 0; + private hoverTimer = 0; + private hoverId = ''; + private readonly menu = new ContextMenu(); + private readonly grid: StarterGrid; + private readonly tabsEl: HTMLElement; + private readonly chips: HTMLElement; + private readonly qInput: HTMLInputElement; + private readonly countEl: HTMLElement; + private readonly empty: HTMLElement; + private readonly stage: HTMLElement; + private readonly video: HTMLVideoElement; + private readonly audio: HTMLAudioElement; + private readonly aboutBtn: HTMLButtonElement; + private readonly useBtn: HTMLButtonElement; + private readonly addBtn: HTMLButtonElement; + + constructor() { + super('Starter library', 1080); + this.frame.classList.add('fc-lib-dlg', 'fc-st-dlg'); + this.grid = new StarterGrid({ + selection: () => this.paintButtons(), + open: (m) => void this.primary([m.id]), + menu: (x, y) => this.openMenu(x, y), + favorite: () => undefined, + more: () => void this.pull(this.run), + remove: () => undefined, + drag: () => undefined, + }); + this.grid.setGrouped(false); + this.grid.setColumns(COLUMNS); + const root = el( + `
      ` + + `
      ` + + TABS.map((d) => ``).join('') + + `
      ` + + `
      ` + + `` + + `
      ` + + `
      ` + + `

      ${t('Everything here is CC0 or public domain: free to use for anything, no credit needed. formcraft keeps the source with each item you add.')}

      ` + + `
      `, + ); + this.tabsEl = q(root, '.fc-lib-tabs'); + this.chips = q(root, '.fc-st-chips'); + this.qInput = q(root, '.fc-lib-q'); + this.countEl = q(root, '.fc-st-count'); + this.empty = q(root, '.fc-st-empty'); + this.stage = q(root, '.fc-st-stage'); + this.video = q(root, '.fc-st-preview'); + this.audio = new Audio(); + this.audio.preload = 'none'; + this.stage.insertBefore(this.grid.el, this.empty); + this.body.append(root); + this.aboutBtn = this.button('About this asset', 'ghost', () => this.about()); + this.useBtn = this.button('Use in current studio', '', () => void this.useSelected()); + this.addBtn = this.button('Add to library', 'primary', () => void this.primary(Array.from(this.grid.picked.keys()))); + this.tabsEl.addEventListener('click', (e) => { + const id = (e.target as Element).closest('[data-kind]')?.dataset.kind; + if (id && id !== this.tab) { + this.tab = id; + this.category = ''; + this.reload(); + } + }); + this.chips.addEventListener('click', (e) => { + const chip = (e.target as Element).closest('[data-cat]'); + if (!chip) return; + const cat = chip.dataset.cat ?? ''; + this.category = this.category === cat ? '' : cat; + this.reload(); + }); + this.qInput.addEventListener('input', () => { + window.clearTimeout(this.searchTimer); + this.searchTimer = window.setTimeout(() => { + this.term = this.qInput.value.trim(); + this.reload(); + }, SEARCH_MS); + }); + this.stage.addEventListener('pointerover', (e) => this.hover(e)); + this.stage.addEventListener('pointerleave', () => this.stopPreview()); + this.grid.el.addEventListener('scroll', () => this.stopPreview(), { passive: true }); + onRendered((uid) => (this.grid as unknown as { coverArrived(id: string): void }).coverArrived(uid)); + this.onClose = () => { + dropQueue(); + this.stopPreview(); + this.grid.clearSelection(); + const done = this.settle; + this.settle = null; + done?.([]); + }; + } + + show(opts: StarterOptions): Promise { + this.settle?.([]); + this.opts = opts; + const allowed = this.allowedTabs(); + if (!allowed.some((d) => d.id === this.tab)) this.tab = allowed[0]?.id ?? 'all'; + for (const b of this.tabsEl.querySelectorAll('[data-kind]')) setHidden(b, !allowed.some((d) => d.id === b.dataset.kind)); + const addLabel = opts.pick ? 'Add and use' : 'Add to library'; + this.addBtn.dataset.en = addLabel; + setText(this.addBtn, t(addLabel)); + setHidden(this.useBtn, !!opts.pick); + this.setTitle(opts.title ?? 'Starter library'); + const result = new Promise((resolve) => { + this.settle = resolve; + }); + this.open(this.qInput); + this.reload(); + return result; + } + + private allowedTabs(): KindTab[] { + const only = this.opts.kinds; + if (!only?.length) return TABS; + const list = TABS.filter((d) => d.id !== 'all' && d.kinds.some((k) => only.includes(k))); + return list.length > 1 ? [TABS[0], ...list] : list; + } + + private kinds(): StarterKind[] { + const tab = TABS.find((d) => d.id === this.tab); + if (tab && tab.kinds.length) return tab.kinds; + return this.opts.kinds ?? []; + } + + private paintTabs(): void { + for (const b of this.tabsEl.querySelectorAll('[data-kind]')) { + const on = b.dataset.kind === this.tab; + setClass(b, 'is-active', on); + setAttr(b, 'aria-selected', on ? 'true' : 'false'); + } + } + + private reload(): void { + this.paintTabs(); + this.stopPreview(); + this.loaded = 0; + this.total = 0; + this.items.clear(); + this.grid.clearSelection(); + void this.pull(++this.run, true); + } + + private async pull(run: number, first = false): Promise { + if (this.busy && !first) return; + if (!first && this.loaded >= this.total) return; + this.busy = true; + try { + const page = await listStarter({ kinds: this.kinds(), category: this.category, q: this.term, offset: first ? 0 : this.loaded, limit: PAGE }); + if (run !== this.run) return; + this.packs = new Map(page.packs.map((p) => [p.id, p])); + for (const item of page.items) { + this.items.set(item.uid, item); + if (item.rigged) rigged.add(item.uid); + } + wantThumbs(page.items); + const list = page.items.map(asMedia); + if (first) this.grid.setItems(list, page.total); + else this.grid.append(list, page.total); + this.loaded = (first ? 0 : this.loaded) + page.items.length; + this.total = page.total; + if (first) this.paintChips(page.categories); + this.paintEmpty(page.available, page.packs.length); + } catch (err) { + if (run !== this.run) return; + if (first) this.grid.setItems([], 0); + this.paintEmpty(true, 0, err instanceof Error ? err.message : t('The starter library could not be read.')); + } finally { + if (run === this.run) this.busy = false; + this.paintButtons(); + } + } + + private paintChips(cats: Array<{ name: string; count: number }>): void { + const html = cats.length > 1 || this.category + ? cats.map((c) => ``).join('') + : ''; + this.chips.innerHTML = html; + } + + private paintEmpty(available: boolean, packs: number, error = ''): void { + const none = this.total === 0; + setHidden(this.empty, !none); + if (none) { + setText(this.empty, error || (!available || packs === 0 ? t('No starter packs are in this build.') : t('Nothing matches. Try another kind, category or search.'))); + } + setText(this.countEl, this.total ? tn(this.total, '1 item', `${this.total} items`) : ''); + } + + private picked(): StarterItem[] { + return Array.from(this.grid.picked.keys()).map((id) => this.items.get(id)).filter((x): x is StarterItem => !!x); + } + + private paintButtons(): void { + const n = this.grid.picked.size; + const max = this.opts.pick ? this.opts.max ?? 1 : Number.MAX_SAFE_INTEGER; + setDisabled(this.addBtn, n === 0 || n > max); + setDisabled(this.useBtn, n !== 1); + setDisabled(this.aboutBtn, n !== 1); + } + + private async primary(ids: string[]): Promise { + const chosen = ids.map((id) => this.items.get(id)).filter((x): x is StarterItem => !!x); + if (!chosen.length) return; + if (this.opts.pick) { + const limit = this.opts.max ?? 1; + const added: Media[] = []; + lastPicked = []; + for (const item of chosen.slice(0, limit)) { + const m = await addToLibrary(item, true); + if (m) { + added.push(m); + lastPicked.push(item); + } + } + if (!added.length) return; + const done = this.settle; + this.settle = null; + this.close(); + done?.(added); + return; + } + let ok = 0; + for (const item of chosen) if (await addToLibrary(item, true)) ok++; + if (ok) this.flash(tn(ok, 'Added 1 item to your library.', `Added ${ok} items to your library.`)); + } + + private flash(text: string): void { + void import('../../toasts').then(({ toast }) => toast(text, 'success', { key: 'starter-added' })); + } + + private async useSelected(): Promise { + const [item] = this.picked(); + if (!item) return; + this.close(); + await useInStudio(item); + } + + private openMenu(x: number, y: number): void { + const one = this.picked().length === 1; + const rows: MenuRow[] = [ + { id: 'add', label: t('Add to library'), icon: 'plus', run: () => void this.primary(Array.from(this.grid.picked.keys())) }, + ]; + if (!this.opts.pick) rows.push({ id: 'use', label: t('Use in current studio'), icon: 'create', disabled: !one, run: () => void this.useSelected() }); + rows.push('-', { id: 'about', label: t('About this asset'), icon: 'info', disabled: !one, run: () => this.about() }); + this.menu.open(x, y, rows, this.grid.el); + } + + private about(): void { + const [item] = this.picked(); + if (item) showAbout(item, this.packs.get(item.pack)); + } + + private hover(e: PointerEvent): void { + const tile = (e.target as Element).closest('.fc-ls-tile'); + const id = tile?.dataset.id ?? ''; + if (id === this.hoverId) return; + this.stopPreview(); + const item = id ? this.items.get(id) : undefined; + if (!tile || !item || (item.mediaKind !== 'video' && item.mediaKind !== 'audio')) return; + this.hoverId = id; + this.hoverTimer = window.setTimeout(() => this.startPreview(tile, item), HOVER_MS); + } + + private startPreview(tile: HTMLElement, item: StarterItem): void { + if (this.hoverId !== item.uid) return; + const url = starterFileUrl(item.uid); + if (item.mediaKind === 'audio') { + this.audio.src = url; + void this.audio.play().catch(() => undefined); + tile.classList.add('fc-st-playing'); + return; + } + const box = this.stage.getBoundingClientRect(); + const r = tile.getBoundingClientRect(); + this.video.style.translate = `${r.left - box.left}px ${r.top - box.top}px`; + this.video.style.width = `${r.width}px`; + this.video.style.height = `${r.height}px`; + this.video.src = url; + setHidden(this.video, false); + void this.video.play().catch(() => undefined); + } + + private stopPreview(): void { + window.clearTimeout(this.hoverTimer); + if (this.hoverId) this.stage.querySelector(`.fc-st-playing`)?.classList.remove('fc-st-playing'); + this.hoverId = ''; + if (!this.video.hidden) { + this.video.pause(); + this.video.removeAttribute('src'); + this.video.load(); + setHidden(this.video, true); + } + if (this.audio.src) { + this.audio.pause(); + this.audio.removeAttribute('src'); + } + } +} + +function aboutRow(label: string, value: string): string { + return `
      ${escapeHtml(t(label))}
      ${value}
      `; +} + +function evidenceLinks(text: string | undefined): string[] { + return [...new Set((text ?? '').match(/https?:\/\/[^\s,;()]+/g) ?? [])].filter((u) => !/[<>{}]/.test(u)); +} + +function showAbout(item: StarterItem, pack: StarterPack | undefined): void { + const d = new Dialog('About this asset', 480); + const source = pack?.sourceUrl ?? ''; + d.body.append( + el( + `
      ` + + aboutRow('Name', escapeHtml(item.name)) + + aboutRow('Kind', escapeHtml(t(KIND_WORD[item.kind]))) + + aboutRow('Category', escapeHtml(item.category)) + + (Object.keys(item.maps ?? {}).length ? aboutRow('Maps', escapeHtml(Object.keys(item.maps).join(', '))) : '') + + (item.rigged ? aboutRow('Rig', escapeHtml(t('Rigged'))) : '') + + (item.animations?.length ? aboutRow('Animations', escapeHtml(item.animations.join(', '))) : '') + + aboutRow('Pack', escapeHtml(pack?.name ?? item.pack)) + + aboutRow('Licence', `${escapeHtml(t(licenceLabel(pack?.licence)))}`) + + (evidenceLinks(pack?.licenceEvidence).length ? aboutRow('Licence evidence', evidenceLinks(pack?.licenceEvidence).map((u) => `${escapeHtml(u)}`).join('
      ')) : '') + + aboutRow('Author', escapeHtml(pack?.author ?? '')) + + (item.sourcePage && /^https?:\/\//.test(item.sourcePage) ? aboutRow('Asset page', `${escapeHtml(item.sourcePage)}`) : '') + + aboutRow('Source', /^https?:\/\//.test(source) ? `${escapeHtml(source)}` : escapeHtml(source)) + + aboutRow('Version', escapeHtml(pack?.version ?? '')) + + aboutRow('Retrieved', escapeHtml(pack?.retrieved ?? '')) + + `
      `, + ), + el(`

      ${escapeHtml(t(!pack || pack.licence === 'CC0-1.0' ? 'CC0 needs no credit. formcraft records the licence, author and source on the library item when you add it.' : 'Public domain needs no credit. formcraft records the licence, author and source on the library item when you add it.'))}

      `), + ); + d.body.addEventListener('click', (e) => { + const a = (e.target as Element).closest('a.fc-st-link'); + if (!a) return; + e.preventDefault(); + if (a.dataset.local) window.open(a.href, '_blank', 'noopener'); + else void openExternal(a.href); + }); + d.button('OK', 'primary', () => d.close()); + d.onClose = () => d.scrim.remove(); + d.open(); +} + +let picker: StarterPicker | null = null; +let lastPicked: StarterItem[] = []; + +export function openStarterPicker(opts: StarterOptions = {}): Promise { + picker ??= new StarterPicker(); + return picker.show(opts); +} + +const KIND_SET = new Set(['3d', 'texture', 'hdri', 'image', 'sprite', 'video', 'audio']); +const FROM_LIBRARY_TAB: Record = { image: ['image', 'texture', 'sprite', 'hdri'], video: ['video'], audio: ['audio'], '3d': ['3d'] }; + +export function kindsFrom(raw: string | undefined): StarterKind[] { + return (raw ?? '').split(',').map((s) => s.trim()).filter((s): s is StarterKind => KIND_SET.has(s)); +} + +export async function starterInto(target: 'scene' | 'edit'): Promise { + const kinds: StarterKind[] = target === 'scene' ? ['3d', 'hdri', 'image'] : ['video', 'audio', 'image']; + const title = target === 'scene' ? 'Add to the scene' : 'Add to the edit'; + const added = await openStarterPicker({ kinds, pick: true, max: 24, title }); + if (!added.length) return; + const items = lastPicked; + if (target === 'edit') { + const [{ queueForEdit }, { studios }] = await Promise.all([import('../../../engine/edit-handoff'), import('../../../engine/studios')]); + queueForEdit(added.map((m) => m.id)); + studios.activate('edit'); + return; + } + const { useInStudio } = await import('./starter-use'); + for (const item of items) await useInStudio(item, 'scene'); +} + +async function intoLibraryPicker(modal: HTMLElement): Promise { + const shown = Array.from(modal.querySelectorAll('.fc-lib-tab[data-tab]')).filter((b) => !b.hidden).map((b) => b.dataset.tab ?? ''); + const kinds = shown.includes('all') ? [] : shown.flatMap((id) => FROM_LIBRARY_TAB[id] ?? []); + const added = await openStarterPicker({ kinds, pick: true, max: 24, title: 'Add from the starter library' }); + if (!added.length) return; + const want = new Set(added.map((m) => m.id)); + let tries = 0; + const select = (): void => { + for (const tile of modal.querySelectorAll('.fc-lib-tile')) { + const id = tile.dataset.key ?? ''; + if (want.has(id)) { + want.delete(id); + if (tile.getAttribute('aria-pressed') !== 'true') tile.click(); + } + } + if (want.size && ++tries < 30) window.setTimeout(select, 100); + }; + select(); +} + +function boot(): void { + trackStudios(); + document.addEventListener('click', (e) => { + const hit = (e.target as Element | null)?.closest?.('[data-starter-open]'); + if (!hit) return; + const to = hit.dataset.starterTo; + const modal = hit.closest('.fc-lib'); + if (to === 'scene' || to === 'edit') void starterInto(to); + else if (modal && modal.querySelector('.fc-lib-tab[data-tab]')) void intoLibraryPicker(modal); + else void openStarterPicker({ kinds: kindsFrom(hit.dataset.starterOpen) }); + }); + commands.register({ id: 'library.starter', label: 'Starter library...', group: 'Library', description: 'Browse the bundled CC0 starter library', run: (p) => void openStarterPicker({ kinds: kindsFrom(typeof p?.kinds === 'string' ? p.kinds : '') }) }); + commands.register({ id: 'library.starterCredits', label: 'Starter library credits', group: 'Help', run: () => void import('./starter-credits').then((m) => m.showStarterCredits()) }); +} + +boot(); diff --git a/frontend/src/ui/library/starter/starter-thumbs.ts b/frontend/src/ui/library/starter/starter-thumbs.ts new file mode 100644 index 0000000..a2b3a39 --- /dev/null +++ b/frontend/src/ui/library/starter/starter-thumbs.ts @@ -0,0 +1,94 @@ +import { calm } from '../../viewers/idle'; +import { putStarterThumb, starterFileUrl, type StarterItem } from './api-starter'; + +const SIZE = 512; +const TIMEOUT_MS = 20000; + +const queue: StarterItem[] = []; +const queued = new Set(); +const done = new Set(); +const failed = new Set(); +let running = false; +let notify: (uid: string) => void = () => undefined; + +export const renderedStamp = (uid: string): string => (done.has(uid) ? '&r=1' : ''); + +export function onRendered(fn: (uid: string) => void): void { + notify = fn; +} + +export function wantThumbs(items: readonly StarterItem[]): void { + for (const item of items) { + if (item.kind !== '3d' || item.thumb || done.has(item.uid) || failed.has(item.uid) || queued.has(item.uid)) continue; + if (!/\.(glb|gltf)$/i.test(item.file)) continue; + queued.add(item.uid); + queue.push(item); + } + if (!running) void drain(); +} + +export function dropQueue(): void { + queue.length = 0; + queued.clear(); +} + +async function one(item: StarterItem): Promise { + const { ModelViewer } = await import('../../viewers/model-viewer'); + const v = new ModelViewer({ pace: calm }); + let timer = 0; + try { + const stalled = new Promise((_, reject) => { + timer = window.setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS); + }); + stalled.catch(() => undefined); + await Promise.race([v.load(starterFileUrl(item.uid), item.file.toLowerCase().endsWith('.gltf') ? 'gltf' : 'glb'), stalled]); + await calm(); + const blob = await Promise.race([v.capture(SIZE), stalled]); + await putStarterThumb(item.uid, blob); + } finally { + window.clearTimeout(timer); + v.dispose(); + } +} + +function rank(uid: string): number { + const tile = document.querySelector(`.fc-ls-tile[data-id="${CSS.escape(uid)}"]`); + if (!tile) return 2; + const r = tile.getBoundingClientRect(); + const box = tile.closest('.fc-ls-scroll')?.getBoundingClientRect() ?? new DOMRect(0, 0, window.innerWidth, window.innerHeight); + return r.bottom > box.top && r.top < box.bottom && r.right > box.left && r.left < box.right ? 0 : 1; +} + +function takeNext(): StarterItem { + let best = 0; + let bestRank = 3; + for (let i = 0; i < queue.length && bestRank > 0; i++) { + const r = rank(queue[i].uid); + if (r < bestRank) { + best = i; + bestRank = r; + } + } + return queue.splice(best, 1)[0]; +} + +async function drain(): Promise { + running = true; + try { + while (queue.length) { + const item = takeNext(); + queued.delete(item.uid); + await calm(); + try { + await one(item); + done.add(item.uid); + notify(item.uid); + } catch (err) { + failed.add(item.uid); + console.warn('[starter] thumbnail', item.uid, err); + } + } + } finally { + running = false; + } +} diff --git a/frontend/src/ui/library/starter/starter-use.ts b/frontend/src/ui/library/starter/starter-use.ts new file mode 100644 index 0000000..6b02b1c --- /dev/null +++ b/frontend/src/ui/library/starter/starter-use.ts @@ -0,0 +1,97 @@ +import { queueForEdit } from '../../../engine/edit-handoff'; +import { studios } from '../../../engine/studios'; +import type { Media } from '../../../io/api'; +import { t } from '../../i18n'; +import { toast } from '../../toasts'; +import { addStarterItem, type StarterItem } from './api-starter'; + +let last = ''; + +export function trackStudios(): void { + const note = (id: string): void => { + const root = studios.rootOf(id); + if (root && studios.get(root)?.kind !== 'library') last = root; + }; + note(studios.active); + studios.on('active', (id) => note(id)); +} + +export function targetStudio(): string { + const root = studios.activeRoot; + return root && studios.get(root)?.kind !== 'library' ? root : last; +} + +export async function addToLibrary(item: StarterItem, quiet = false): Promise { + try { + const m = await addStarterItem(item.uid); + if (!quiet) toast(t('Added to your library.'), 'success', { key: 'starter-added' }); + return m; + } catch (err) { + toast(err instanceof Error ? err.message : t('Could not add this to your library.'), 'error', { key: 'starter-add-failed' }); + return null; + } +} + +async function inScene(item: StarterItem, m: Media): Promise { + if (item.kind === 'hdri' || item.kind === 'texture') { + studios.activate('scene'); + const [{ sceneApi }, mats, env] = await Promise.all([import('../../scene/bridge'), import('../../scene/materials/use'), import('../../scene/materials/env-map')]); + const ctx = await sceneApi(); + if (item.kind === 'texture') return mats.applyMaterialMedia(ctx, m) || true; + if (!(await env.setSceneEnvMap(ctx, m.id, item.file.slice(item.file.lastIndexOf('/') + 1)))) return false; + toast(t('Set as the scene environment. It is saved with the project.'), 'success', { key: 'starter-used' }); + return true; + } + if (m.kind !== 'model' && m.kind !== 'image' && m.kind !== 'video') return false; + studios.activate('scene'); + const [{ sceneApi }, { addMedia }] = await Promise.all([import('../../scene/bridge'), import('../../scene/presets/sources')]); + return addMedia(await sceneApi(), [m]).length > 0; +} + +async function inCanvas(m: Media): Promise { + if (m.kind !== 'image') return false; + studios.activate('canvas'); + const [{ canvasApi }, place] = await Promise.all([import('../../canvas/base/bridge'), import('../../canvas/base/place')]); + const ctx = await canvasApi(); + if (!ctx.store.base) { + toast(t('Start a canvas page first.'), 'info', { key: 'canvas-drawer-empty' }); + return true; + } + await place.addCentred(ctx, [m]); + return true; +} + +async function inBoard(m: Media): Promise { + if (m.kind !== 'image' && m.kind !== 'video') return false; + studios.activate('board'); + const { dropMediaOnBoard } = await import('../../board'); + return dropMediaOnBoard([m], window.innerWidth / 2, window.innerHeight / 2); +} + +function inEdit(m: Media): boolean { + if (m.kind !== 'video' && m.kind !== 'audio' && m.kind !== 'image') return false; + queueForEdit([m.id]); + studios.activate('edit'); + return true; +} + +const WHERE: Record = { scene: 'Scene', canvas: 'Canvas', board: 'Board', edit: 'Edit' }; + +export async function useInStudio(item: StarterItem, into?: string): Promise { + const m = await addToLibrary(item, true); + if (!m) return; + const target = into ?? targetStudio(); + let used = false; + try { + if (target === 'scene') used = await inScene(item, m); + else if (target === 'canvas') used = await inCanvas(m); + else if (target === 'board') used = await inBoard(m); + else if (target === 'edit') used = inEdit(m); + } catch (err) { + console.error('[starter] use', err); + used = false; + } + if (used) return; + const name = WHERE[target]; + toast(name ? `${t('Added to your library.')} ${t(name)} ${t('cannot use this kind of item yet.')}` : t('Added to your library. Open a studio first to use it there.'), 'info', { key: 'starter-used' }); +} diff --git a/frontend/src/ui/library/starter/starter.css b/frontend/src/ui/library/starter/starter.css new file mode 100644 index 0000000..5b60e0f --- /dev/null +++ b/frontend/src/ui/library/starter/starter.css @@ -0,0 +1,25 @@ +.fc-st-entry { gap: var(--space-2); white-space: nowrap; } +.fc-st-entry-row { display: flex; flex: none; padding: var(--space-2); border-top: 1px solid var(--line-1); } +.fc-st-entry-row .fc-st-entry { flex: 1 1 auto; justify-content: center; } +.cv-dialog.fc-st-dlg .cv-dialog-body { display: flex; flex-direction: column; min-height: 0; padding: 0; overflow: hidden; } +.fc-st { display: flex; flex: 1 1 auto; flex-direction: column; min-height: 0; } +.fc-st-count { margin-left: auto; color: var(--text-muted); font-size: var(--fs-12); font-variant-numeric: tabular-nums; white-space: nowrap; } +.fc-st-chips { display: flex; flex: none; align-items: center; gap: var(--space-2); height: calc(var(--ctl-sm) + 2 * var(--space-2)); padding: 0 var(--space-4); overflow-x: auto; overflow-y: hidden; border-top: 1px solid var(--line-1); border-bottom: 1px solid var(--line-1); scrollbar-width: thin; } +.fc-st-chip { display: inline-flex; flex: none; align-items: center; gap: var(--space-1); height: var(--ctl-sm); padding: 0 var(--space-3); border: 1px solid var(--line-1); border-radius: var(--radius-pill); background: var(--surface-0); color: var(--text-secondary); font: inherit; font-size: var(--fs-12); cursor: pointer; } +.fc-st-chip:hover { border-color: var(--line-3); color: var(--text-primary); } +.fc-st-chip.is-active { border-color: var(--accent-line); background: var(--accent-wash); color: var(--text-primary); } +.fc-st-chip:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fc-st-chipn { color: var(--text-muted); font-size: var(--fs-11); font-variant-numeric: tabular-nums; } +.fc-st-stage { position: relative; display: flex; flex: 1 1 0; flex-direction: column; min-height: 0; padding: var(--space-2) var(--space-4) 0; } +.fc-st-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; margin: 0; padding: var(--space-6); color: var(--text-muted); font-size: var(--fs-13); text-align: center; pointer-events: none; } +.fc-st-empty[hidden] { display: none; } +.fc-st-preview { position: absolute; top: 0; left: 0; z-index: var(--z-raised); object-fit: cover; border-radius: var(--radius-md); background: var(--surface-1); pointer-events: none; } +.fc-st-preview[hidden] { display: none; } +.fc-st .fc-ls-hbtn[data-act="fav"], .fc-st .fc-ls-fav { display: none; } +.fc-st .fc-ls-tile.fc-st-playing { border-color: var(--accent-color); } +.fc-st-note { flex: none; margin: 0; padding: var(--space-2) var(--space-4); border-top: 1px solid var(--line-1); } +.fc-st-link { color: var(--accent-color); text-decoration: none; overflow-wrap: anywhere; } +.fc-st-link:hover { text-decoration: underline; } +.fc-st-credits { display: grid; gap: var(--space-3); max-height: 50vh; margin: 0; padding: 0; overflow-y: auto; list-style: none; } +.fc-st-credit { display: grid; gap: 2px; padding-bottom: var(--space-2); border-bottom: 1px solid var(--line-1); font-size: var(--fs-12); } +.fc-st-muted { color: var(--text-muted); font-size: var(--fs-11); } diff --git a/frontend/src/ui/lightbox/lightbox.ts b/frontend/src/ui/lightbox/lightbox.ts index 403ac3f..22f6bc2 100644 --- a/frontend/src/ui/lightbox/lightbox.ts +++ b/frontend/src/ui/lightbox/lightbox.ts @@ -1,7 +1,4 @@ import '../../styles/lightbox.css'; -import { queueForEdit } from '../../engine/edit-handoff'; -import { makeObject, makeWorld, toRemoveBackground } from '../../engine/handoff'; -import { studios } from '../../engine/studios'; import { jobs } from '../../engine/jobs'; import { getJob, mediaFileUrl, mediaThumbUrl, type Job, type Media } from '../../io/api'; import { onLibrary } from '../../io/events'; @@ -9,14 +6,13 @@ import { delayedIndicator, el, escapeHtml, patchList, q, setAttr, setClass, setH import { onLanguage, relabel, t } from '../i18n'; import { icon } from '../icons'; import { AudioPlayer, clockText, trackPlayback } from '../media/audio-player'; -import { editInCanvas } from '../canvas/base/bridge'; -import { openInScene } from '../scene/bridge'; +import { LEAVES, openResultMenu, primaryActions, RESULT_ACTIONS, runResultAction, type ResultAction } from '../feed/result-actions'; import { toast } from '../toasts'; import { FavouriteToggle, TagsEditor } from './tags-editor'; import { previewable } from '../viewers/kinds'; import { ThreeView } from '../viewers/lightbox-views'; -export type LightboxAction = 'recreate' | 'make-video' | 'remove-background' | 'edit-image' | 'make-object' | 'make-world' | 'open-scene' | 'add-to-edit' | 'download' | 'delete' | 'copy-prompt' | 'reveal'; +export type LightboxAction = ResultAction; export interface LightboxOptions { actions: LightboxAction[]; onAction(action: string, media: Media): void } interface Rect { x: number; y: number; w: number; h: number } @@ -545,54 +541,12 @@ class CardView implements Viewer { } } -const ACTIONS: ReadonlyArray<{ id: LightboxAction; text: string; icon: string; kind: string; note?: string }> = [ - { id: 'recreate', text: 'Recreate', icon: 'refresh', kind: '' }, - { id: 'make-video', text: 'Make video', icon: 'video', kind: '' }, - { id: 'remove-background', text: 'Remove background', icon: 'removeBackground', kind: '' }, - { id: 'edit-image', text: 'Edit image', icon: 'canvas', kind: '' }, - { id: 'make-object', text: 'Make 3D object', icon: 'cube', kind: '' }, - { id: 'make-world', text: 'Make 3D world', icon: 'globe', kind: '' }, - { id: 'open-scene', text: 'Open in Scene', icon: 'scene', kind: '' }, - { id: 'add-to-edit', text: 'Add to edit', icon: 'edit', kind: '' }, - { id: 'download', text: 'Download', icon: 'download', kind: '' }, - { id: 'reveal', text: 'Show in folder', icon: 'folderOpen', kind: '' }, - { id: 'delete', text: 'Delete', icon: 'trash', kind: ' cv-btn-danger' }, +const ACTIONS: ReadonlyArray<{ id: LightboxAction | 'more'; text: string; icon: string; kind: string; note?: string }> = [ + ...RESULT_ACTIONS.map((a) => ({ id: a.id, text: a.text, icon: a.icon, kind: a.danger ? ' cv-btn-danger' : '' })), + { id: 'more', text: 'More', icon: 'more', kind: '' }, ]; -const HAND_OFFS: ReadonlyArray = ['remove-background', 'edit-image', 'make-object', 'make-world', 'open-scene', 'add-to-edit']; - -const TAKE: Partial boolean>> = { - 'remove-background': (m) => toRemoveBackground(m), - 'edit-image': (m) => { - void editInCanvas(m); - return true; - }, - 'make-object': (m) => { - makeObject(m.id); - return true; - }, - 'make-world': (m) => { - makeWorld(m.id); - return true; - }, - 'open-scene': (m) => { - void openInScene(m); - return true; - }, - 'add-to-edit': (m) => { - queueForEdit([m.id]); - studios.activate('edit'); - return true; - }, -}; - -function applicable(id: LightboxAction, m: Media): boolean { - if (id === 'recreate') return m.source === 'generated' && (m.kind === 'image' || m.kind === 'video' || m.kind === 'audio' || m.kind === 'model' || m.kind === 'splat'); - if (id === 'make-video' || id === 'remove-background' || id === 'edit-image' || id === 'make-object' || id === 'make-world') return m.kind === 'image'; - if (id === 'add-to-edit') return m.kind === 'image' || m.kind === 'video' || m.kind === 'audio'; - if (id === 'open-scene') return m.kind === 'model' || m.kind === 'splat' || m.kind === 'image' || m.kind === 'video'; - return true; -} +const CALLER_RUNS: ReadonlySet = new Set(['delete']); const ROWS: ReadonlyArray = [ ['model', 'Model'], @@ -625,7 +579,7 @@ class Lightbox { private readonly tags = new TagsEditor(); private readonly fav = new FavouriteToggle(); private readonly actionsBar: HTMLElement; - private readonly actionBtns = new Map(); + private readonly actionBtns = new Map(); private readonly image = new ImageView(); private readonly video = new VideoView(); private readonly audio = new AudioView(); @@ -905,7 +859,7 @@ class Lightbox { if (at >= 0 && at !== this.index) this.select(at); return; } - const act = target.closest('[data-act]')?.dataset.act as LightboxAction | undefined; + const act = target.closest('[data-act]')?.dataset.act as LightboxAction | 'more' | undefined; if (act) { this.fire(act); return; @@ -1031,20 +985,25 @@ class Lightbox { this.render(); } - private fire(action: LightboxAction): void { + private fire(action: LightboxAction | 'more'): void { const m = this.items[this.index]; if (!m || this.actionBtns.get(action)?.hasAttribute('disabled')) return; - const take = TAKE[action]; - if (take) { - if (take(m)) this.close(); + if (action === 'more') { + const btn = this.actionBtns.get('more'); + const r = btn?.getBoundingClientRect(); + openResultMenu(m, r ? r.left : 0, r ? r.top - 4 : 0, { skip: primaryActions(m), returnTo: btn ?? null, run: (id) => this.fire(id) }); return; } - try { - this.config.onAction(action, m); - } catch (err) { - console.error('[lightbox]', err); + if (CALLER_RUNS.has(action) && this.config.actions.includes(action)) { + try { + this.config.onAction(action, m); + } catch (err) { + console.error('[lightbox]', err); + } + return; } - if (action === 'recreate' || action === 'make-video') this.close(); + if (LEAVES.has(action)) this.close(); + void runResultAction(action, m); } private copyPrompt(): void { @@ -1238,14 +1197,10 @@ class Lightbox { } private renderActions(m: Media): void { - let any = false; - for (const [id, btn] of this.actionBtns) { - const offered = HAND_OFFS.includes(id) ? this.config.actions.length > 0 : this.config.actions.includes(id); - const show = offered && applicable(id, m); - setHidden(btn, !show); - if (show) any = true; - } - setHidden(this.actionsBar, !any); + const offered = this.config.actions.length > 0; + const primary = offered ? primaryActions(m) : []; + for (const [id, btn] of this.actionBtns) setHidden(btn, id === 'more' ? !offered : !primary.includes(id)); + setHidden(this.actionsBar, !offered); } } diff --git a/frontend/src/ui/menu.ts b/frontend/src/ui/menu.ts index 17ffdae..f91f6ff 100644 --- a/frontend/src/ui/menu.ts +++ b/frontend/src/ui/menu.ts @@ -4,6 +4,7 @@ import { anyDialogOpen } from './dialogs'; import { el, isMac, q, setAttr, setClass, setDisabled, setText } from './dom'; import { icon } from './icons'; import { t } from './i18n'; +import { placeFloating, pointTarget } from './position'; import '../styles/menu.css'; export interface SubMenu { @@ -181,13 +182,7 @@ export class PopupMenu { this.panel.style.visibility = 'hidden'; this.panel.hidden = false; this.panel.scrollTop = 0; - const { width: w, height: h } = this.panel.getBoundingClientRect(); - const fitsRight = x + w <= window.innerWidth - 4; - const fitsBelow = y + h <= window.innerHeight - 4; - const left = Math.max(4, Math.min(fitsRight ? x : x - w, window.innerWidth - w - 4)); - const top = Math.max(4, Math.min(fitsBelow ? y : y - h, window.innerHeight - h - 4)); - this.panel.style.left = `${Math.round(left)}px`; - this.panel.style.top = `${Math.round(top)}px`; + placeFloating(this.panel, pointTarget(x, y), { side: 'bottom', align: 'start' }); this.panel.style.visibility = ''; } @@ -196,15 +191,7 @@ export class PopupMenu { this.panel.style.visibility = 'hidden'; this.panel.hidden = false; this.panel.scrollTop = 0; - const w = this.panel.offsetWidth; - const h = this.panel.offsetHeight; - const pad = 4; - const right = row.right - 2; - const left = row.left - w + 2; - const x = right + w <= window.innerWidth - pad ? right : Math.max(pad, left); - const y = Math.max(pad, Math.min(row.top - pad, window.innerHeight - h - pad)); - this.panel.style.left = `${Math.round(x)}px`; - this.panel.style.top = `${Math.round(y)}px`; + placeFloating(this.panel, { left: row.left, right: row.right, top: row.top - 4, bottom: row.bottom }, { side: 'right', align: 'start', gap: -2 }); this.panel.style.visibility = ''; } diff --git a/frontend/src/ui/menus.ts b/frontend/src/ui/menus.ts index 2ac8b89..ea18c21 100644 --- a/frontend/src/ui/menus.ts +++ b/frontend/src/ui/menus.ts @@ -2,10 +2,12 @@ import { commands, type Command } from '../engine/commands'; import { shortcuts } from '../engine/shortcuts'; import { studios } from '../engine/studios'; import { isMac } from './dom'; +import { demoIds, registerHelpCommands } from './help/help-commands'; import { t } from './i18n'; import { openLibraryBrowser } from './library/library-modal'; import type { MenuDef, MenuItem } from './menu'; import { MENUS_IN_WINDOW_KEY, inTauri, menusInWindow, runTextEdit, textFieldFocused } from './native-menu'; +import { recentIds, registerFileCommands } from './projects/file-commands'; import { softenLaterTools } from './projects/tiles'; import { toast } from './toasts'; import { openUploadDialog } from './upload/upload-dialog'; @@ -72,15 +74,21 @@ const toolIds = (): string[] => studios.all().filter((s) => s.kind === 'tool').m export function buildMenus(native = false): MenuDef[] { registerLibraryCommands(); softenLaterTools(); - const file = (): MenuItem[] => ['new', 'open', '-', 'import', 'upload-files', ...(native ? [] : ['-', 'settings', '-', 'quit'])]; + registerFileCommands(); + registerHelpCommands(); + const file = (): MenuItem[] => [ + 'new', 'open', { label: 'Open Recent', items: recentIds() }, '-', + 'save', 'saveAs', 'saveCopy', '-', 'exportOutput', 'revealProject', 'openOutputFolder', '-', + 'import', 'upload-files', '-', 'closeProject', ...(native ? [] : ['-', 'settings', '-', 'quit']), + ]; return [ { label: 'File', items: file }, { label: 'Edit', items: ['undo', 'redo', '-', 'cut', 'copy', 'paste', 'select-all'] }, - { label: 'View', items: ['theme-toggle', '-', 'view-terminal', 'new-terminal', 'claude-code', '-', 'custom-title-bar', 'menus-in-window'] }, + { label: 'View', items: ['view-agents', 'view-panels', 'show-library', '-', 'view-terminal', 'new-terminal', 'claude-code', '-', 'theme-toggle', 'custom-title-bar', 'menus-in-window'] }, { label: 'Studio', items: () => [...studioIds(), '-', 'library'] }, { label: 'Create', items: pageIds }, { label: 'Tools', items: toolIds }, { label: 'Window', items: ['home', 'browse-library', '-', 'window-minimize', 'window-maximize', '-', 'jobs-toggle'] }, - { label: 'Help', items: ['search-commands', 'shortcuts', '-', 'about'] }, + { label: 'Help', items: () => ['welcome', 'tour-studio', '-', 'cheatsheet', 'shortcuts', 'search-commands', ...(demoIds().length ? [{ label: 'Open a Demo', items: demoIds() }] : []), '-', 'whats-new', 'report-problem', 'show-logs', '-', 'about'] }, ]; } diff --git a/frontend/src/ui/output-files.ts b/frontend/src/ui/output-files.ts new file mode 100644 index 0000000..7872b46 --- /dev/null +++ b/frontend/src/ui/output-files.ts @@ -0,0 +1,82 @@ +import { ApiError, getSettings, importMediaFiles, type Job, type Media } from '../io/api'; +import { t } from './i18n'; +import { inDesktop, invokeHost } from './prefs'; +import { toast, type ToastAction } from './toasts'; + +const isMac = navigator.platform.toLowerCase().includes('mac'); + +export const revealLabel = (): string => (isMac ? 'Reveal in Finder' : navigator.userAgent.includes('Windows') ? 'Show in Explorer' : 'Show in Folder'); + +let projectName: () => string | null = () => null; + +export function setProjectNameSource(read: () => string | null): void { + projectName = read; +} + +export const currentProject = (): string | null => projectName(); + +export const folderOf = (path: string): string => path.replace(/[\\/][^\\/]*$/, '') || path; + +export async function outputFolder(): Promise { + try { + return (await getSettings()).downloadDir; + } catch { + return ''; + } +} + +export async function revealPath(path: string): Promise { + if (!path) return; + if (!inDesktop()) { + toast(t('Saved at {path}').replace('{path}', () => path), 'info', { key: 'output-reveal' }); + return; + } + try { + await invokeHost('reveal_path', { path }); + } catch (err) { + toast(typeof err === 'string' && err ? err : t('The file manager could not be opened.'), 'error', { key: 'output-reveal' }); + } +} + +export const revealAction = (path: string): ToastAction[] => (path && inDesktop() ? [{ label: t(revealLabel()), run: () => void revealPath(path) }] : []); + +export function savedFolder(job: Job): string { + if (job.kind === 'download' && typeof job.payload.dir === 'string') return job.payload.dir; + const saved = job.payload.saved; + if (Array.isArray(saved) && saved.length) { + const first = saved[0] as { path?: unknown }; + if (typeof first?.path === 'string') return folderOf(first.path); + } + return ''; +} + +export async function pickSavePath(title: string, defaultName: string, filters?: Array<{ name: string; extensions: string[] }>): Promise { + const defaultDir = await outputFolder(); + const args: Record = { title, defaultName }; + if (defaultDir) args.defaultDir = defaultDir; + if (filters) args.filters = filters; + const picked = await invokeHost('pick_save_path', args); + return typeof picked === 'string' && picked ? picked : null; +} + +export async function pickOutputFolder(title: string): Promise { + const picked = await invokeHost('pick_folder', { title }); + return typeof picked === 'string' && picked ? picked : null; +} + +export function browserSave(href: string, name: string): void { + const link = document.createElement('a'); + link.href = href; + link.download = name; + link.hidden = true; + document.body.append(link); + link.click(); + link.remove(); +} + +export async function importForSave(blob: Blob, name: string): Promise { + const made = await importMediaFiles([new File([blob], name, { type: blob.type })], true); + return made.items[0] ?? null; +} + +export const failure = (err: unknown): string => (err instanceof ApiError ? err.message : err instanceof Error && err.message ? err.message : t('The file could not be saved.')); diff --git a/frontend/src/ui/panels/connections.ts b/frontend/src/ui/panels/connections.ts index b162cd8..cf2bc57 100644 --- a/frontend/src/ui/panels/connections.ts +++ b/frontend/src/ui/panels/connections.ts @@ -1,18 +1,18 @@ import { models } from '../../engine/models'; -import { ApiError, checkKey, deleteKey, getKeys, putKey, type KeyStore, type KeysState, type Provider } from '../../io/api'; +import { ApiError, checkKey, deleteKey, getKeys, putKey, type KeyStore, type KeysState, type Provider, type SystemStore } from '../../io/api'; import { passwordRow } from '../controls'; import { el, pendingClass, q, setClass, setDisabled, setHidden, setText } from '../dom'; import { onLanguage, t } from '../i18n'; import { icon } from '../icons'; import { inDesktop, invokeHost } from '../prefs'; -interface KeyDef { +export interface KeyDef { provider: Provider; name: string; url: string; } -const KEYS: readonly KeyDef[] = [ +export const KEYS: readonly KeyDef[] = [ { provider: 'fal', name: 'fal', url: 'https://fal.ai/dashboard/keys' }, { provider: 'worldlabs', name: 'World Labs', url: 'https://platform.worldlabs.ai/api-keys' }, ]; @@ -22,6 +22,27 @@ const STORE_NOTE: Record = { file: 'Keys are kept in a private file on this computer. formcraft only shows the last four characters.', }; +const STORED_IN: Record = { + keychain: 'Stored in macOS Keychain', + 'credential-manager': 'Stored in Windows Credential Manager', + 'secret-service': 'Stored in your system keyring', + kwallet: 'Stored in KWallet', +}; + +const GOES_TO: Record = { + keychain: 'A key you save goes in macOS Keychain', + 'credential-manager': 'A key you save goes in Windows Credential Manager', + 'secret-service': 'A key you save goes in your system keyring', + kwallet: 'A key you save goes in KWallet', +}; + +export interface KeyPlace { store: KeyStore | null; system: SystemStore | null } + +export function placeText(set: boolean, place: KeyPlace): string { + if (set) return place.store !== 'file' && place.system ? STORED_IN[place.system] : 'Stored in a file only you can read'; + return place.system ? GOES_TO[place.system] : 'A key you save goes in a file only you can read'; +} + class KeyRow { readonly el: HTMLElement; readonly input: HTMLInputElement; @@ -30,7 +51,9 @@ class KeyRow { private readonly test: HTMLButtonElement; private readonly state: HTMLElement; private readonly link: HTMLElement; + private readonly where: HTMLElement; private status: { set: boolean; last4: string | null } | null = null; + private place: KeyPlace = { store: null, system: null }; private busy = false; constructor( @@ -49,6 +72,7 @@ class KeyRow { `` + `` + `` + + `

       

      ` + ``, ); this.el.prepend(field.el); @@ -57,7 +81,8 @@ class KeyRow { this.test = q(this.el, '[data-test]'); this.state = q(this.el, '.fc-key-state'); this.link = q(this.el, '.fc-key-url'); - for (const [btn, english] of [[this.save, 'Save'], [this.forget, 'Forget'], [this.test, 'Test']] as const) { + this.where = q(this.el, '.fc-key-where'); + for (const [btn, english] of [[this.save, 'Save'], [this.forget, 'Remove'], [this.test, 'Test']] as const) { btn.dataset.en = english; setText(btn, t(english)); } @@ -80,8 +105,9 @@ class KeyRow { onLanguage(() => this.paint()); } - show(status: { set: boolean; last4: string | null } | null): void { + show(status: { set: boolean; last4: string | null } | null, place: KeyPlace = { store: null, system: null }): void { this.status = status; + this.place = place; this.paint(); } @@ -95,6 +121,10 @@ class KeyRow { const text = !s ? '' : s.set ? (s.last4 ? t('Set, ends with {last4}').replace('{last4}', s.last4) : t('Set')) : t('Not set'); setText(this.state, text); setClass(this.state, 'is-set', !!s?.set); + setText(this.where, s ? t(placeText(s.set, this.place)) : ' '); + const action = s?.set ? 'Replace' : 'Save'; + this.save.dataset.en = action; + setText(this.save, t(action)); this.syncButtons(); } @@ -145,7 +175,7 @@ class KeyRow { const state = await deleteKey(this.def.provider); this.input.value = ''; this.onState(state); - this.say(`${this.def.name} key forgotten.`); + this.say(`${this.def.name} key removed.`); void models.refresh(); }); } @@ -218,7 +248,7 @@ export class ConnectionsPanel { private apply(state: KeysState): void { this.seq++; this.store = state.store; - KEYS.forEach((def, i) => this.rows[i].show(state[def.provider])); + KEYS.forEach((def, i) => this.rows[i].show(state[def.provider], { store: state.stores?.[def.provider] ?? state.store, system: state.system ?? null })); this.paintNote(); } diff --git a/frontend/src/ui/panels/files-output.ts b/frontend/src/ui/panels/files-output.ts new file mode 100644 index 0000000..d9a296d --- /dev/null +++ b/frontend/src/ui/panels/files-output.ts @@ -0,0 +1,229 @@ +import '../../styles/prefs-output.css'; +import { ApiError, getSettings, previewFileName, putSettings, type Settings } from '../../io/api'; +import { textRow, toggleRow } from '../controls'; +import { el, pendingClass, q, setDisabled, setText, setTitle } from '../dom'; +import { onLanguage, t } from '../i18n'; +import { icon } from '../icons'; +import { pickOutputFolder, revealPath } from '../output-files'; +import { inDesktop } from '../prefs'; + +const TOKENS: ReadonlyArray = [ + ['{date}', 'Date'], + ['{time}', 'Time'], + ['{model}', 'Model'], + ['{prompt}', 'First words of the prompt'], + ['{kind}', 'Kind of file'], + ['{project}', 'Project name'], + ['{seed}', 'Seed'], + ['{n}', 'Number in a batch'], +]; +const NOTE_OUTPUT = 'Finished files are saved here. A file that already exists is never replaced: a number is added instead.'; +const NOTE_TEMPLATE = 'The file type is added for you. Leave this empty for the standard name. A number is added when a batch makes several files.'; +const BROWSER_PICK = 'Folder picking works in the desktop app. Type the path instead.'; +const BROWSER_OPEN = 'Opening a folder works in the desktop app.'; +const PREVIEW_DELAY_MS = 250; + +function button(english: string, kind: string, withIcon?: string): HTMLButtonElement { + const b = el(``); + const label = q(b, '.fc-lbl'); + label.dataset.en = english; + setText(label, t(english)); + return b; +} + +function note(english: string, extra = ''): HTMLElement { + const p = el(`

      `); + p.dataset.en = english; + setText(p, t(english)); + return p; +} + +export class FilesOutputPanel { + readonly output: HTMLElement; + readonly template: HTMLElement; + + private readonly folder = textRow('Output folder', (v) => void this.setFolder(v), { placeholder: 'Full path of a folder', maxLength: 1024 }); + private readonly change = button('Change...', 'ghost', 'folderOpen'); + private readonly open = button('Open', 'ghost'); + private readonly useDefault = button('Use default', 'ghost'); + private readonly ask = toggleRow('Ask where to save each time', (v) => void this.save({ askLocation: v }, v ? 'You will be asked where each file goes.' : 'Files go to the output folder without asking.')); + private readonly auto = toggleRow('Save every finished result automatically', (v) => void this.save({ autoDownload: v }, v ? 'Finished results will be saved to the output folder.' : 'Results stay in the library until you save them.')); + private readonly outputNote = el('

      '); + + private readonly pattern = textRow('File name template', (v) => this.edited(v), { placeholder: 'Standard: model and date', maxLength: 200, live: true }); + private readonly reset = button('Use standard name', 'ghost'); + private readonly chips = el('
      '); + private readonly preview = el('

      '); + private readonly problem = el('

      '); + + private settings: Settings | null = null; + private loadError = ''; + private said = ''; + private busy = false; + private seq = 0; + private timer = 0; + private previewSeq = 0; + private valid = true; + + constructor() { + const bar = el('
      '); + bar.append(this.change, this.open, this.useDefault); + this.output = el('
      '); + this.output.append(this.folder.el, bar, this.ask.el, this.auto.el, note(NOTE_OUTPUT), this.outputNote); + + for (const [token, label] of TOKENS) { + const chip = button(token, 'ghost'); + chip.title = t(label); + chip.dataset.enTitle = label; + chip.dataset.token = token; + this.chips.append(chip); + } + const patternBar = el('
      '); + patternBar.append(this.reset); + this.template = el('
      '); + this.template.append(this.pattern.el, this.chips, patternBar, this.preview, this.problem, note(NOTE_TEMPLATE)); + + this.change.addEventListener('click', () => void this.pick()); + this.open.addEventListener('click', () => void revealPath(this.settings?.downloadDir ?? '')); + this.useDefault.addEventListener('click', () => void this.save({ downloadDir: '' }, 'Using the default output folder.')); + this.reset.addEventListener('click', () => { + this.pattern.input.value = ''; + this.edited(''); + }); + this.chips.addEventListener('click', (e) => { + const token = (e.target as HTMLElement).closest('[data-token]')?.dataset.token; + if (!token) return; + const input = this.pattern.input; + const at = input.selectionStart ?? input.value.length; + const end = input.selectionEnd ?? at; + input.value = `${input.value.slice(0, at)}${token}${input.value.slice(end)}`.slice(0, 200); + input.focus(); + input.setSelectionRange(at + token.length, at + token.length); + this.edited(input.value); + }); + this.folder.input.addEventListener('keydown', (e) => { + if (e.key === 'Enter') this.folder.input.blur(); + }); + this.paint(true); + onLanguage(() => this.paint(true)); + } + + async refresh(): Promise { + const mine = ++this.seq; + window.clearTimeout(this.timer); + this.said = ''; + try { + const s = await getSettings(); + if (mine !== this.seq) return; + this.settings = s; + this.loadError = ''; + } catch (err) { + if (mine !== this.seq) return; + this.settings = null; + this.loadError = err instanceof ApiError ? err.message : 'The engine did not answer.'; + } + this.paint(true); + void this.showPreview(this.currentScheme()); + } + + private currentScheme(): string { + const text = this.pattern.input.value.trim(); + return text || 'default'; + } + + private async save(patch: Partial, ok: string): Promise { + if (this.busy) return false; + this.busy = true; + this.sync(); + const done = pendingClass(this.output); + let saved = false; + try { + this.settings = await putSettings(patch); + this.seq++; + this.said = ok; + saved = true; + } catch (err) { + this.said = err instanceof ApiError ? err.message : 'The change could not be saved.'; + } finally { + this.busy = false; + done(); + this.paint(true); + } + return saved; + } + + private async setFolder(raw: string): Promise { + if (!this.settings) return; + const path = raw.trim(); + if (!path) { + await this.save({ downloadDir: '' }, 'Using the default output folder.'); + return; + } + if (path !== this.settings.downloadDir) await this.save({ downloadDir: path }, 'Output folder saved.'); + } + + private async pick(): Promise { + if (!inDesktop()) return; + try { + const picked = await pickOutputFolder(t('Choose the output folder')); + if (picked) await this.setFolder(picked); + } catch (err) { + this.said = err instanceof Error ? err.message : typeof err === 'string' ? err : 'The folder could not be chosen.'; + this.paint(); + } + } + + private edited(value: string): void { + window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => void this.showPreview(value.trim() || 'default', true), PREVIEW_DELAY_MS); + } + + private async showPreview(scheme: string, persist = false): Promise { + const mine = ++this.previewSeq; + try { + const made = await previewFileName(scheme, 'png'); + if (mine !== this.previewSeq) return; + this.valid = made.ok; + setText(this.preview, made.ok ? t('Example: {name}').replace('{name}', made.name) : ''); + setText(this.problem, made.ok ? '' : made.message); + if (made.ok && persist && this.settings && this.settings.namingScheme !== scheme) { + this.settings = await putSettings({ namingScheme: scheme }); + } + } catch (err) { + if (mine !== this.previewSeq) return; + this.valid = false; + setText(this.preview, ''); + setText(this.problem, err instanceof ApiError ? err.message : t('The engine did not answer.')); + } + } + + private sync(): void { + const ready = !!this.settings && !this.busy; + const desktop = inDesktop(); + setDisabled(this.folder.input, !ready); + setDisabled(this.useDefault, !ready); + setDisabled(this.change, !ready || !desktop); + setDisabled(this.open, !this.settings || !desktop); + setDisabled(this.pattern.input, !this.settings); + setDisabled(this.reset, !this.settings); + setDisabled(q(this.ask.el, 'input'), !ready); + setDisabled(q(this.auto.el, 'input'), !ready); + for (const chip of Array.from(this.chips.querySelectorAll('button'))) setDisabled(chip, !this.settings); + setTitle(this.change, desktop ? '' : t(BROWSER_PICK)); + setTitle(this.open, desktop ? '' : t(BROWSER_OPEN)); + } + + private paint(force = false): void { + const s = this.settings; + const typing = (n: HTMLInputElement): boolean => document.activeElement === n && !force; + const folder = s?.downloadDir ?? ''; + if (this.folder.input.value !== folder && !typing(this.folder.input)) this.folder.input.value = folder; + this.ask.set(!!s?.askLocation); + this.auto.set(!!s?.autoDownload); + const stored = s && s.namingScheme !== 'default' ? s.namingScheme : ''; + if (!typing(this.pattern.input) && this.pattern.input.value !== stored && this.valid) this.pattern.input.value = stored; + this.sync(); + const base = s ? (inDesktop() ? '' : t(BROWSER_PICK)) : this.loadError ? `${this.loadError} ${t('Output settings are unavailable.')}` : ''; + setText(this.outputNote, this.said ? t(this.said) : base); + } +} diff --git a/frontend/src/ui/panels/media-drawer.ts b/frontend/src/ui/panels/media-drawer.ts index e1c5dea..4b439b6 100644 --- a/frontend/src/ui/panels/media-drawer.ts +++ b/frontend/src/ui/panels/media-drawer.ts @@ -1,10 +1,11 @@ +import '../../styles/media-panel.css'; import { getMedia, type Media, type MediaKind } from '../../io/api'; -import { el, q, setHidden } from '../dom'; +import { el, q } from '../dom'; import { t } from '../i18n'; import { icon } from '../icons'; import { toast } from '../toasts'; import { DROP_MIME } from '../canvas/base/place'; -import { createMediaPanel } from './media-panel'; +import { libraryWindow, onLibraryWindow, registerLibraryWindow } from '../library/library-window'; export type DrawerHost = 'canvas' | 'board' | 'scene'; @@ -86,27 +87,15 @@ async function resolve(raw: string): Promise { } export function mountMediaDrawer(root: HTMLElement, host: DrawerHost): void { - if (root.querySelector(':scope > .fc-md')) return; + if (root.querySelector('.fc-md')) return; const wiring = WIRING[host]; + registerLibraryWindow(); const drawer = el( - `
      ` + - `
      `, + `
      `, ); - const holder = q(drawer, '.fc-md-panel'); const toggle = q(drawer, '.fc-md-toggle'); - const panel = createMediaPanel({ - kinds: wiring.kinds, - storeKey: 'shared', - addLabel: t('Add to the page'), - onAdd: (items) => void wiring.add(items, root).catch((err) => console.error('[media-drawer] add', err)), - }); - holder.appendChild(panel.el); - toggle.addEventListener('click', () => { - const open = toggle.getAttribute('aria-expanded') !== 'true'; - toggle.setAttribute('aria-expanded', String(open)); - setHidden(holder, !open); - if (open) panel.activate(); - }); + onLibraryWindow((open) => toggle.setAttribute('aria-expanded', String(open))); + toggle.addEventListener('click', () => libraryWindow().toggle()); if (wiring.drop) { const drop = wiring.drop; root.addEventListener('dragover', (e) => { @@ -123,5 +112,11 @@ export function mountMediaDrawer(root: HTMLElement, host: DrawerHost): void { void resolve(raw).then((items) => (items.length ? drop(items, clientX, clientY) : undefined)).catch((err) => console.error('[media-drawer] drop', err)); }); } - root.appendChild(drawer); + const dock = host === 'canvas' ? root.querySelector(':scope > [data-slot="right"]') : host === 'board' ? root.querySelector('.fc-bd-top') : null; + if (!dock) { + root.appendChild(drawer); + return; + } + drawer.dataset.dock = host; + dock.insertBefore(drawer, dock.querySelector('.fc-bd-present')); } diff --git a/frontend/src/ui/position.ts b/frontend/src/ui/position.ts new file mode 100644 index 0000000..e5c43ed --- /dev/null +++ b/frontend/src/ui/position.ts @@ -0,0 +1,102 @@ +export type Side = 'top' | 'bottom' | 'left' | 'right'; +export type Align = 'start' | 'center' | 'end'; + +export interface Target { + left: number; + top: number; + right: number; + bottom: number; +} + +export interface PlaceOptions { + side?: Side; + align?: Align; + gap?: number; + pad?: number; + minHeight?: number; + scale?: number; +} + +export interface Placed { + side: Side; + left: number; + top: number; + maxHeight: number; +} + +const DEFAULT_PAD = 8; +const DEFAULT_GAP = 6; +const OPPOSITE: Record = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' }; + +function px(name: string, fallback: number): number { + const v = Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue(name)); + return Number.isFinite(v) ? v : fallback; +} + +export function safeArea(pad = DEFAULT_PAD): Target { + const top = Math.max(px('--cv-titlebar-h', 40), document.querySelector('.cv-titlebar')?.getBoundingClientRect().bottom ?? 0); + const status = document.querySelector('.cv-status')?.getBoundingClientRect(); + const bottom = status && status.height > 0 ? status.top : window.innerHeight - px('--cv-status-h', 28); + return { left: pad, top: top + pad / 2, right: window.innerWidth - pad, bottom: bottom - pad / 2 }; +} + +export const pointTarget = (x: number, y: number): Target => ({ left: x, top: y, right: x, bottom: y }); + +function along(side: Side, a: Target, size: number, area: Target, align: Align): number { + const horizontal = side === 'top' || side === 'bottom'; + const lo = horizontal ? a.left : a.top; + const hi = horizontal ? a.right : a.bottom; + const room = horizontal ? area.right - area.left : area.bottom - area.top; + const start = align === 'end' ? hi - size : align === 'center' ? (lo + hi) / 2 - size / 2 : lo; + const min = horizontal ? area.left : area.top; + return Math.max(min, Math.min(start, min + Math.max(0, room - size))); +} + +/** Places a fixed-position floating panel next to a target rectangle or point, inside the area between the title bar + * and the status bar. It prefers the asked side, flips to the other side when that does not fit, shifts along the edge + * to stay on screen, and caps max-height so a tall panel scrolls inside itself. The panel must already be rendered + * (not display none); hide it with visibility while measuring. For a point target, a panel that overflows the right + * edge opens to the left of the point instead of covering it. */ +export function placeFloating(panel: HTMLElement, target: Target, opts: PlaceOptions = {}): Placed { + const pad = opts.pad ?? DEFAULT_PAD; + const gap = opts.gap ?? DEFAULT_GAP; + const k = opts.scale && opts.scale > 0 ? opts.scale : 1; + const area = safeArea(pad); + const point = target.left === target.right && target.top === target.bottom; + const pref = opts.side ?? 'bottom'; + panel.style.maxHeight = ''; + panel.style.overflowY = ''; + const w = panel.offsetWidth * k; + const natural = panel.offsetHeight * k; + const gapOf = point ? 0 : gap; + const room = (s: Side): number => + s === 'bottom' ? area.bottom - target.bottom - gapOf : s === 'top' ? target.top - area.top - gapOf : s === 'right' ? area.right - target.right - gapOf : target.left - area.left - gapOf; + const need = (s: Side): number => (s === 'top' || s === 'bottom' ? natural : w); + let side = pref; + if (room(side) < need(side) && room(OPPOSITE[side]) > room(side)) side = OPPOSITE[side]; + const vertical = side === 'top' || side === 'bottom'; + const cap = Math.max(opts.minHeight ?? 96, vertical ? room(side) : area.bottom - area.top); + const height = Math.min(natural, cap); + let left: number; + let top: number; + if (vertical) { + let align = opts.align ?? 'start'; + if (point && target.left + w > area.right && target.left - w >= area.left) align = 'end'; + left = along(side, target, w, area, align); + top = side === 'bottom' ? target.bottom + gapOf : target.top - gapOf - height; + top = Math.max(area.top, Math.min(top, area.bottom - height)); + } else { + top = along(side, target, height, area, opts.align ?? 'start'); + left = side === 'right' ? target.right + gapOf : target.left - gapOf - w; + left = Math.max(area.left, Math.min(left, area.right - w)); + } + const maxHeight = Math.floor(Math.min(height, area.bottom - area.top) / k); + if (natural > height) { + panel.style.maxHeight = `${maxHeight}px`; + panel.style.overflowY = 'auto'; + } + panel.style.left = `${Math.round(left / k)}px`; + panel.style.top = `${Math.round(top / k)}px`; + panel.dataset.side = side; + return { side, left, top, maxHeight }; +} diff --git a/frontend/src/ui/prefs-agents.ts b/frontend/src/ui/prefs-agents.ts index 9a051bf..33b5901 100644 --- a/frontend/src/ui/prefs-agents.ts +++ b/frontend/src/ui/prefs-agents.ts @@ -6,7 +6,9 @@ import { rotateAgentToken, stopAgents, type AgentActivity, - type AgentPolicy, + type AgentGrant, + type AgentLevel, + type AgentsPatch, type AgentsState, } from '../io/api-agents'; import { ApiError } from '../io/api'; @@ -19,11 +21,14 @@ import { toast } from './toasts'; const POLL_MS = 1500; const SHOWN_CALLS = 30; -const POLICIES: ReadonlyArray = [ - ['allow', 'Allow'], - ['ask', 'Ask each time'], +const POLICIES: ReadonlyArray = [ + ['ask', 'Ask every time'], + ['session', 'Ask once per session'], + ['project', 'Always allow in this project'], + ['allow', 'Always allow everywhere'], ['deny', 'Deny'], ]; +const SPEND_DEFAULT = 1; const FLAVOURS = ['claude', 'codex', 'cursor', 'antigravity'] as const; type Flavour = (typeof FLAVOURS)[number]; const FLAVOUR_LABEL: Record = { claude: 'Claude Code', codex: 'Codex', cursor: 'Cursor', antigravity: 'Antigravity' }; @@ -70,7 +75,7 @@ const toneOf = (status: string): string => (/^(ok|done|success|succeeded)$/i.tes interface ClientRow { name: string; - policy: AgentPolicy; + policy: AgentLevel; calls: number | null; lastSeen: string | number | null; } @@ -78,6 +83,7 @@ interface ClientRow { export class AgentsPanel { readonly access: HTMLElement[]; readonly clients: HTMLElement[]; + readonly grants: HTMLElement[]; readonly activity: HTMLElement[]; readonly setup: HTMLElement[]; @@ -87,6 +93,10 @@ export class AgentsPanel { private readonly copyPath = button('Copy path', 'ghost'); private readonly rotate = button('Rotate token', 'ghost'); private readonly clientList = el('
        '); + private readonly grantList = el('
          '); + private readonly spendOn = checkRow('Allow spending without asking', (v) => void this.apply({ spend: { on: v, limitUsd: this.spendLimit() } })); + private readonly spendAmount = el(''); + private readonly projectNote = el('

          '); private readonly callList = el('
            '); private readonly stop = button('Stop running calls', 'ghost'); private readonly tabs = el('
            '); @@ -132,7 +142,22 @@ export class AgentsPanel { tokenRow, note('Agents read this token file from your data folder. Rotating it signs every connected agent out until it starts again.'), ]; - this.clients = [this.clientList, note('Agents are listed by the name they give when they connect. Ask each time shows a prompt in this window for every risky step.')]; + this.clients = [this.clientList, this.projectNote, note('Agents are listed by the name they give when they connect. Reading never asks. Spending and deleting files outside the project always ask, whatever you choose here.')]; + const spendRow = el(''); + setText(q(spendRow, 'span'), t('Up to, in dollars per run')); + spendRow.append(this.spendAmount); + this.spendAmount.value = SPEND_DEFAULT.toFixed(2); + this.grantList.dataset.empty = t('Nothing is allowed yet.'); + this.grants = [this.grantList, this.spendOn.el, spendRow, note('Off by default. A generation that costs more than this still asks.')]; + this.spendAmount.addEventListener('change', () => { + if (this.state?.spend?.on) void this.apply({ spend: { on: true, limitUsd: this.spendLimit() } }); + }); + this.grantList.addEventListener('click', (e) => { + const row = (e.target as Element).closest('[data-key]'); + if (!(e.target as Element).closest('button') || !row?.dataset.key) return; + const [client, scope, key] = JSON.parse(row.dataset.key) as [string, AgentGrant['scope'], string]; + void this.apply({ revoke: { client, scope, key } }); + }); this.activity = [stopBar, this.callList]; this.setup = [this.tabs, cmdField, this.flavourNote, this.code, copyBar]; @@ -150,7 +175,7 @@ export class AgentsPanel { this.clientList.addEventListener('change', (e) => { const sel = e.target as HTMLSelectElement; const name = sel.closest('[data-key]')?.dataset.key; - if (name) void this.apply({ policies: { ...(this.state?.policies ?? {}), [name]: sel.value as AgentPolicy } }); + if (name) void this.apply({ level: { client: name, level: sel.value as AgentLevel } }); }); this.paintSnippet(); @@ -159,6 +184,7 @@ export class AgentsPanel { onLanguage(() => { this.clientList.dataset.empty = t('No agent has connected yet.'); this.callList.dataset.empty = t('No calls yet.'); + this.grantList.dataset.empty = t('Nothing is allowed yet.'); this.paintState(); this.paintSnippet(); }); @@ -194,7 +220,12 @@ export class AgentsPanel { this.paintState(); } - private async apply(patch: { allowed?: boolean; policies?: Record }): Promise { + private spendLimit(): number { + const v = Number.parseFloat(this.spendAmount.value); + return Number.isFinite(v) && v > 0 ? Math.min(1000, Math.round(v * 100) / 100) : SPEND_DEFAULT; + } + + private async apply(patch: AgentsPatch): Promise { try { this.state = await putAgentsState(patch); } catch (err) { @@ -240,8 +271,8 @@ export class AgentsPanel { const s = this.state; if (!s) return []; const seen = new Map(); - const fallback = s.defaultPolicy ?? 'allow'; - for (const c of s.clients) seen.set(c.name, { name: c.name, policy: s.policies[c.name] ?? c.policy ?? fallback, calls: c.calls ?? null, lastSeen: c.lastSeen ?? null }); + const fallback = s.defaultPolicy ?? 'ask'; + for (const c of s.clients) seen.set(c.name, { name: c.name, policy: c.level ?? s.policies[c.name] ?? c.policy ?? fallback, calls: c.calls ?? null, lastSeen: c.lastSeen ?? null }); for (const [name, policy] of Object.entries(s.policies)) if (!seen.has(name)) seen.set(name, { name, policy, calls: null, lastSeen: null }); return Array.from(seen.values()); } @@ -271,9 +302,32 @@ export class AgentsPanel { setText(q(node, '.fc-ag-client-name'), c.name); const parts = [c.calls !== null ? t('{n} calls').replace('{n}', String(c.calls)) : '', c.lastSeen ? `${t('Last seen')} ${clock(c.lastSeen)}` : ''].filter(Boolean); setText(q(node, '.fc-ag-client-meta'), parts.join(' - ')); - setValue(q(node, 'select'), c.policy); + const select = q(node, 'select'); + const projectOption = select.querySelector('option[value="project"]'); + if (projectOption) projectOption.disabled = !s?.project; + setValue(select, c.policy); + }, + }); + setText(this.projectNote, s?.project ? t('This project: {name}').replace('{name}', s.project.name) : t('Open or save a project to allow an agent in it.')); + + patchList(this.grantList, s?.grants ?? [], { + key: (g) => JSON.stringify([g.client, g.scope, g.key]), + create: () => { + const li = el('
          • '); + li.append(button('Revoke', 'ghost')); + return li; + }, + update: (node, g) => { + setText(q(node, '.fc-ag-client-name'), `${g.client}: ${t(g.label)}`); + const where = g.scope === 'project' ? t('Project: {name}').replace('{name}', g.project ?? '') : g.scope === 'session' ? t('Until FormCraft closes') : t('Everywhere'); + setText(q(node, '.fc-ag-client-meta'), where); }, }); + const spend = s?.spend; + this.spendOn.set(!!spend?.on); + const spendBox = this.spendOn.el.querySelector('input'); + if (spendBox) setDisabled(spendBox, !s); + if (spend?.on && document.activeElement !== this.spendAmount) setValue(this.spendAmount, spend.limitUsd.toFixed(2)); const shown = this.calls.slice(0, SHOWN_CALLS); const counts = new Map(); diff --git a/frontend/src/ui/prefs-dialog.ts b/frontend/src/ui/prefs-dialog.ts index 26e5e39..f044a32 100644 --- a/frontend/src/ui/prefs-dialog.ts +++ b/frontend/src/ui/prefs-dialog.ts @@ -1,18 +1,22 @@ import '../styles/prefs.css'; import { promptStore } from '../engine/prompt-store'; import { ApiError, getSettings, putSettings, type Strategy } from '../io/api'; -import { checkRow, colorRow, selectRow, sliderRow } from './controls'; +import { checkRow, colorRow, numberRow, selectRow, sliderRow } from './controls'; import { Dialog, confirmAction } from './dialogs'; import { el, q, setAttr, setClass, setDisabled, setHidden, setText } from './dom'; import { toast } from './toasts'; +import { toursButton } from './help/tour'; import { ICONS, icon } from './icons'; import { LANGUAGES, language, onLanguage, setLanguage, t } from './i18n'; import { KeybindsPanel } from './keybinds-panel'; import { buildUpdates } from './prefs-updates'; +import { buildRenderingPrefs } from './rendering'; import { AgentsPanel } from './prefs-agents'; import { ConnectionsPanel } from './panels/connections'; +import { FilesOutputPanel } from './panels/files-output'; import { LibraryFilesPanel } from './panels/library-files'; import { + COSTLY_RANGE, HOLD_RANGE, PREVIEW_QUALITIES, RAIL_KEY, @@ -77,7 +81,9 @@ export const PREF_SECTIONS: readonly PrefSection[] = [ { id: 'workspace', label: 'Workspace', icon: 'viewGrid' }, { id: 'generation', label: 'Generation', icon: 'create' }, { id: 'connections', label: 'Connections', icon: 'plug' }, + { id: 'output', label: 'Files and Output', icon: 'download' }, { id: 'library', label: 'Library and Files', icon: 'folder' }, + { id: 'rendering', label: 'Rendering', icon: 'video' }, { id: 'performance', label: 'Performance', icon: 'pfPerformance' }, { id: 'keyboard', label: 'Keyboard', icon: 'keyboard' }, { id: 'sounds', label: 'Alerts and Sounds', icon: 'bell' }, @@ -86,8 +92,9 @@ export const PREF_SECTIONS: readonly PrefSection[] = [ ]; const ALIASES: Record = { - files: 'Library and Files', - downloads: 'Library and Files', + files: 'Files and Output', + downloads: 'Files and Output', + output: 'Files and Output', keys: 'Connections', shortcuts: 'Keyboard', keybinds: 'Keyboard', @@ -187,7 +194,11 @@ class PreferencesDialog extends Dialog { private readonly tabsRow = checkRow('Open documents as tabs', (v) => this.change({ openAsTabs: v })); private readonly countRow = sliderRow('Images per run', 1, 4, 1, (v) => this.change({ defaultImageCount: Math.round(v) }), { def: 1 }); - private readonly costRow = checkRow('Confirm before costly runs', (v) => this.change({ confirmCostly: v })); + private readonly costRow = checkRow('Confirm before costly runs', (v) => { + this.change({ confirmCostly: v }); + this.costLineRow.input.disabled = !v; + }); + private readonly costLineRow = numberRow('Confirm before runs over ($)', COSTLY_RANGE.min, COSTLY_RANGE.max, 0.05, (v) => this.change({ costlyUsd: v })); private readonly strategyRow = selectRow('When a model does not offer your choice', STRATEGY_CHOICES, (v) => void this.saveStrategy(v as Strategy)); private readonly strategyNote = el(''); private readonly styleRow = selectRow('Model picker layout', PICKER_STYLES, (v) => writePickerStyle(v)); @@ -196,6 +207,7 @@ class PreferencesDialog extends Dialog { private readonly connections = new ConnectionsPanel(); private readonly library = new LibraryFilesPanel(); + private readonly filesOutput = new FilesOutputPanel(); private readonly gpuRow = checkRow('Prefer WebGPU when available', (v) => this.change({ preferWebGpu: v })); private readonly gpuNote = el('

            '); @@ -236,6 +248,8 @@ class PreferencesDialog extends Dialog { nt('The Home screen shows when formcraft starts. The brand mark at the top left opens it at any time. With the second choice on, formcraft opens in the studio you last used.')), grp('Behavior', this.enterRow.el, nt('With this on, Enter starts a run and Shift and Enter adds a new line. With it off, Enter adds a new line and the Generate button starts the run. Touch screens always add a new line.')), + grp('Studio Tours', toursButton(), + nt('Each studio shows a short guided tour the first time it opens. This shows them again. Help, Tour This Studio runs one at any time.')), grp('Reset', reset, nt('Puts every preference, the theme, the shortcuts and the sound settings back to how formcraft comes, then reloads the window. Your library and projects are kept.'))); @@ -262,8 +276,8 @@ class PreferencesDialog extends Dialog { this.add('Generation', grp('Defaults', this.countRow.el, nt('How many images the Image page makes per run until you choose a number there. Each model keeps its own limit.'), - this.costRow.el, - nt('Asks first when a run is estimated at one dollar or more. The final charge is set by the provider.'), + this.costRow.el, this.costLineRow.el, + nt('Asks first when a run is estimated at this amount or more (one dollar unless you change it). The confirm can raise it for you. The final charge is set by the provider.'), this.strategyRow.el, this.strategyNote, nt('Applies when you ask for a size, length or quality that the chosen model does not offer. Stop and tell me never swaps a value: the Generate button waits until you pick one the model offers.'), this.styleRow.el, @@ -272,11 +286,22 @@ class PreferencesDialog extends Dialog { this.add('Connections', grp('Provider keys', this.connections.keys)); + this.add('Files and Output', + grp('Output folder', this.filesOutput.output), + grp('File names', this.filesOutput.template)); + this.add('Library and Files', - grp('Downloads', this.library.downloads), - grp('File names', this.library.naming), grp('Engine data folder', this.library.data)); + const rendering = buildRenderingPrefs(); + this.add('Rendering', + grp('ffmpeg', ...rendering.binaries, + nt('formcraft runs ffmpeg as a separate program, the LGPL build from the Form family (formai-binaries) when no other is found. Every downloaded file is checked against the SHA-256 recorded in formcraft.')), + grp('Output', ...rendering.defaults, + nt('The format and quality the Edit export starts with until you change them there.')), + grp('FormEncoder', ...rendering.encoder, + nt('Adds Send to FormEncoder to the Edit export and to library items, to encode with its presets.'))); + this.add('Performance', grp('Graphics and previews', nt('WebGPU and preview quality are not used by any studio yet, so there is nothing to set here.'))); @@ -296,6 +321,7 @@ class PreferencesDialog extends Dialog { this.add('Agents', grp('Outside agents', ...agents.access), grp('Clients', ...agents.clients), + grp('Allowed', ...agents.grants), grp('Recent calls', ...agents.activity), grp('Connect a client', ...agents.setup)); @@ -385,6 +411,7 @@ class PreferencesDialog extends Dialog { this.keybinds.refresh(); void this.connections.refresh(); void this.library.refresh(); + void this.filesOutput.refresh(); void this.loadStrategy(); const target = resolveSection(section) ?? (this.current || 'General'); this.open(this.tabOf(target)); @@ -465,6 +492,8 @@ class PreferencesDialog extends Dialog { this.tabsRow.set(p.openAsTabs); this.countRow.set(p.defaultImageCount); this.costRow.set(p.confirmCostly); + if (document.activeElement !== this.costLineRow.input) this.costLineRow.set(p.costlyUsd); + this.costLineRow.input.disabled = !p.confirmCostly; this.styleRow.set(readPickerStyle()); this.gpuRow.set(p.preferWebGpu); this.qualityRow.set(p.previewQuality); diff --git a/frontend/src/ui/prefs-updates.ts b/frontend/src/ui/prefs-updates.ts index 42943a0..01bf267 100644 --- a/frontend/src/ui/prefs-updates.ts +++ b/frontend/src/ui/prefs-updates.ts @@ -1,5 +1,6 @@ import { checkForUpdate, restartApp, updaterGate, type FoundUpdate } from '../io/updater'; import { VERSION } from '../version'; +import { jobs } from '../engine/jobs'; import { el, q, setClass, setDisabled, setStyleVar, setText } from './dom'; import { t } from './i18n'; import { icon } from './icons'; @@ -88,6 +89,13 @@ export function buildUpdates(): HTMLElement[] { install.node.addEventListener('click', () => { if (!found) return; + const busy = jobs.running().length; + if (busy > 0) { + const reason = busy === 1 ? 'Wait for the running job to finish, then install' : `Wait for the ${busy} running jobs to finish, then install`; + setText(note, t(reason)); + note.dataset.en = reason; + return; + } phase = 'installing'; ratio = 0; known = false; diff --git a/frontend/src/ui/prefs.ts b/frontend/src/ui/prefs.ts index 47fd79a..0e86ebf 100644 --- a/frontend/src/ui/prefs.ts +++ b/frontend/src/ui/prefs.ts @@ -15,13 +15,15 @@ export interface Prefs { openAsTabs: boolean; defaultImageCount: number; confirmCostly: boolean; + costlyUsd: number; comfyuiUrl: string; preferWebGpu: boolean; previewQuality: PreviewQuality; cheatsheetHoldSec: number; } -export const HOLD_RANGE = { min: 1, max: 5, def: 3 } as const; +export const HOLD_RANGE = { min: 1, max: 5, def: 1 } as const; +export const COSTLY_RANGE = { min: 0.05, max: 100 } as const; export const PREFS_KEY = 'formcraft.prefs'; export const HOME_KEY = 'formcraft.home.autoShow'; @@ -56,6 +58,7 @@ export const DEFAULT_PREFS: Prefs = { openAsTabs: true, defaultImageCount: 1, confirmCostly: true, + costlyUsd: 1, comfyuiUrl: '', preferWebGpu: true, previewQuality: 'balanced', @@ -109,6 +112,7 @@ function clean(raw: unknown): Prefs { openAsTabs: flag(r.openAsTabs, d.openAsTabs), defaultImageCount: whole(r.defaultImageCount, 1, 4, d.defaultImageCount), confirmCostly: flag(r.confirmCostly, d.confirmCostly), + costlyUsd: Math.round(num(r.costlyUsd, COSTLY_RANGE.min, COSTLY_RANGE.max, d.costlyUsd) * 100) / 100, comfyuiUrl: cleanAddress(r.comfyuiUrl) ?? d.comfyuiUrl, preferWebGpu: flag(r.preferWebGpu, d.preferWebGpu), previewQuality: pick(r.previewQuality, QUALITY_IDS, d.previewQuality), diff --git a/frontend/src/ui/projects/autosave.ts b/frontend/src/ui/projects/autosave.ts new file mode 100644 index 0000000..02ed325 --- /dev/null +++ b/frontend/src/ui/projects/autosave.ts @@ -0,0 +1,181 @@ +import { request } from '../../io/api'; +import { createProject, type ProjectDoc } from '../../io/api-projects'; +import { onCanvasReady } from '../canvas/base/bridge'; +import { Dialog } from '../dialogs'; +import { el, setText } from '../dom'; +import { t } from '../i18n'; +import { onSceneReady } from '../scene/bridge'; +import { toast } from '../toasts'; +import { showProject } from './session'; +import { projectStore } from './store'; + +type Kind = 'scene' | 'canvas'; +type Answer = 'restore' | 'discard' | 'later'; + +interface Held { kind: Kind; name: string; projectId: string | null; savedAt: string; doc: ProjectDoc } +interface Source { dirty(): boolean; read(): Promise<{ name: string; id: string | null; doc: unknown }> } + +const DELAY_MS = 4000; +const sources = new Map(); +const timers = new Map(); +const kept = new Set(); +const busy = new Set(); +const again = new Set(); + +const path = (kind: Kind): string => `/autosave/${kind}`; + +async function write(kind: Kind): Promise { + window.clearTimeout(timers.get(kind)); + timers.delete(kind); + const src = sources.get(kind); + if (!src) return; + if (busy.has(kind)) { + again.add(kind); + return; + } + if (!src.dirty()) return drop(kind); + busy.add(kind); + try { + const { name, id, doc } = await src.read(); + await request('PUT', path(kind), { name, projectId: id, doc }); + kept.add(kind); + } catch (err) { + console.warn('[autosave]', kind, err); + } finally { + busy.delete(kind); + if (again.delete(kind)) schedule(kind, 0); + } +} + +async function drop(kind: Kind): Promise { + window.clearTimeout(timers.get(kind)); + timers.delete(kind); + if (!kept.delete(kind)) return; + await request('DELETE', path(kind)).catch(() => undefined); +} + +function schedule(kind: Kind, ms = DELAY_MS): void { + window.clearTimeout(timers.get(kind)); + timers.set(kind, window.setTimeout(() => void write(kind), ms)); +} + +function flushAll(): void { + for (const kind of Array.from(timers.keys())) void write(kind); +} + +function touched(kind: Kind, dirty: boolean): void { + if (dirty) schedule(kind); + else void drop(kind); +} + +export async function clearAutosaves(): Promise { + await Promise.all(Array.from(kept).map((kind) => drop(kind))); +} + +function watch(): void { + onSceneReady((ctx) => { + sources.set('scene', { + dirty: () => ctx.store.dirty, + read: async () => { + const files = (await import('../scene/chrome/files')).filesFor(ctx); + const shots = (await import('../scene/shot')).shotIds(ctx); + return { name: files.name, id: files.id, doc: { ...ctx.store.snapshot(), shots } }; + }, + }); + for (const e of ['added', 'removed', 'changed', 'order', 'env', 'timeline'] as const) ctx.store.on(e, () => touched('scene', ctx.store.dirty)); + ctx.store.on('dirty', (on) => touched('scene', on)); + void import('../scene/chrome/files').then((m) => m.filesFor(ctx).on(() => touched('scene', ctx.store.dirty))); + }); + onCanvasReady((ctx) => { + sources.set('canvas', { + dirty: () => ctx.store.dirty, + read: async () => { + const files = (await import('../canvas/files/files')).filesFor(ctx); + return { name: files.name, id: files.id, doc: ctx.store.serialize() }; + }, + }); + for (const e of ['base', 'scene', 'results'] as const) ctx.store.on(e, () => touched('canvas', ctx.store.dirty)); + ctx.store.on('dirty', (on) => touched('canvas', on)); + void import('../canvas/files/files').then((m) => m.filesFor(ctx).on(() => touched('canvas', ctx.store.dirty))); + }); + window.addEventListener('blur', flushAll); + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') flushAll(); + }); +} + +class RecoverDialog extends Dialog { + private readonly note = el('

            '); + private resolve: ((v: Answer) => void) | null = null; + + constructor() { + super('Restore unsaved changes', 420); + this.body.appendChild(this.note); + this.button('Discard', 'danger', () => this.finish('discard')).classList.add('cv-btn-apart'); + this.button('Restore', 'primary', () => this.finish('restore')); + this.onClose = () => this.finish('later'); + } + + ask(name: string): Promise { + setText(this.note, t("FormCraft closed while '{name}' had changes that were not saved.").replace('{name}', () => name)); + this.open(this.foot.querySelector('.cv-btn-primary')); + return new Promise((resolve) => { + this.resolve = resolve; + }); + } + + private finish(v: Answer): void { + const done = this.resolve; + this.resolve = null; + if (this.isOpen) this.close(); + done?.(v); + } +} + +async function recover(list: readonly Held[]): Promise { + const dialog = new RecoverDialog(); + for (const held of list) { + const name = (held.projectId ? projectStore.get(held.projectId)?.name : '') || held.name || t(held.kind === 'scene' ? 'Untitled scene' : 'Untitled canvas'); + const answer = await dialog.ask(name); + if (answer === 'later') continue; + if (answer === 'restore') { + try { + const made = await createProject({ kind: held.kind, name: t('{name} (recovered)').replace('{name}', () => name), doc: held.doc }); + projectStore.upsert(made); + await showProject(made); + } catch (err) { + toast(err instanceof Error && err.message ? err.message : t('The changes could not be restored.'), 'error', { key: `autosave-restore:${held.kind}` }); + continue; + } + } + if (!timers.has(held.kind) && !kept.has(held.kind)) await request('DELETE', path(held.kind)).catch(() => undefined); + } +} + +function whenReady(fn: () => void): void { + if (projectStore.state === 'ready' || projectStore.state === 'error') { + fn(); + return; + } + const off = projectStore.on(() => { + if (projectStore.state !== 'ready' && projectStore.state !== 'error') return; + off(); + fn(); + }); +} + +let started = false; + +export function startAutosave(): void { + if (started) return; + started = true; + whenReady(() => { + void request<{ autosaves: Held[] }>('GET', '/autosave') + .catch(() => ({ autosaves: [] as Held[] })) + .then((res) => { + const list = res.autosaves.filter((h) => h.kind === 'scene' || h.kind === 'canvas'); + watch(); + if (list.length) void recover(list); + }); + }); +} diff --git a/frontend/src/ui/projects/demos.ts b/frontend/src/ui/projects/demos.ts new file mode 100644 index 0000000..4aa5a87 --- /dev/null +++ b/frontend/src/ui/projects/demos.ts @@ -0,0 +1,50 @@ +import { request } from '../../io/api'; +import type { ProjectSummary } from '../../io/api-projects'; +import { t } from '../i18n'; +import { toast } from '../toasts'; +import { showProject } from './session'; +import { projectStore } from './store'; + +export interface Demo { id: string; title: string; blurb?: string; studio?: string; minutes?: number; cover?: string } + +let cached: Promise | null = null; + +export function listDemos(): Promise { + cached ??= request<{ demos?: Demo[] } | Demo[]>('GET', '/demos') + .then((raw) => (Array.isArray(raw) ? raw : raw?.demos ?? []).filter((d) => d && typeof d.id === 'string' && typeof d.title === 'string')) + .catch(() => { + cached = null; + return []; + }); + return cached; +} + +export async function openDemo(id: string): Promise { + try { + const res = await request<{ project?: ProjectSummary } & Partial>('POST', `/demos/${encodeURIComponent(id)}/open`); + const p = res.project ?? (res.id && res.kind ? (res as ProjectSummary) : null); + if (!p) throw new Error(t('This demo could not be opened.')); + projectStore.upsert(p); + return await showProject(p); + } catch (err) { + toast(err instanceof Error ? err.message : t('This demo could not be opened.'), 'error', { key: 'demo-open' }); + return false; + } +} + +export async function openDemoFor(studio: string): Promise { + const list = await listDemos(); + const pick = list.find((d) => d.studio === studio) ?? list[0]; + if (!pick) { + toast(t('No demo is installed.'), 'info', { key: 'demo-open' }); + return false; + } + return openDemo(pick.id); +} + +if (typeof document !== 'undefined') { + document.addEventListener('click', (e) => { + const b = e.target instanceof Element ? e.target.closest('[data-demo-for]') : null; + if (b?.dataset.demoFor) void openDemoFor(b.dataset.demoFor); + }); +} diff --git a/frontend/src/ui/projects/disk.ts b/frontend/src/ui/projects/disk.ts new file mode 100644 index 0000000..83e9a05 --- /dev/null +++ b/frontend/src/ui/projects/disk.ts @@ -0,0 +1,139 @@ +import { Emitter } from '../../engine/emitter'; +import { ApiError, getSettings } from '../../io/api'; +import { exportProject } from '../../io/api-projects'; +import { isMac } from '../dom'; +import { t } from '../i18n'; +import { inDesktop, invokeHost } from '../prefs'; +import { toast } from '../toasts'; +import { projectStore } from './store'; + +export type DiskMode = 'save' | 'as' | 'copy'; +export type SaveState = 'saved' | 'edited' | 'saving'; + +const FOLDER_KEY = 'formcraft.files.lastFolder'; +const WRITTEN_KEY = 'formcraft.files.written'; +const EXTENSION = /\.fcrft$/i; + +const writing = new Set(); +const emitter = new Emitter<{ change: [] }>(); +const written: Record = (() => { + try { + const v = JSON.parse(localStorage.getItem(WRITTEN_KEY) ?? '{}') as unknown; + return v && typeof v === 'object' ? (v as Record) : {}; + } catch { + return {}; + } +})(); + +const fileSafe = (name: string): string => name.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').replace(/^[ .]+|[ .]+$/g, '').slice(0, 80) || 'project'; +const folderOf = (path: string): string => path.replace(/[\\/][^\\/]*$/, '') || path; +const reasonOf = (err: unknown): string => (err instanceof ApiError && err.message ? err.message : typeof err === 'string' && err ? err : t('The project file could not be written.')); + +function remember(key: string, value: string): void { + try { + localStorage.setItem(key, value); + } catch { + return; + } +} + +function lastFolder(): string { + try { + return localStorage.getItem(FOLDER_KEY) ?? ''; + } catch { + return ''; + } +} + +export const revealLabel = (): string => (isMac ? 'Reveal in Finder' : navigator.userAgent.includes('Windows') ? 'Show in Explorer' : 'Show in Folder'); + +export function onSaveState(fn: () => void): () => void { + const a = emitter.on('change', fn); + const b = projectStore.on(fn); + return () => { + a(); + b(); + }; +} + +export function filePathOf(id: string | null): string | null { + return id ? projectStore.get(id)?.filePath ?? null : null; +} + +export function saveStateOf(id: string | null, dirty: boolean): SaveState { + if (id && writing.has(id)) return 'saving'; + if (!id || dirty) return 'edited'; + const p = projectStore.get(id); + if (!p?.filePath) return 'edited'; + return written[id] === p.updatedAt ? 'saved' : 'edited'; +} + +export async function revealFile(path: string | null): Promise { + if (!path) return; + if (!inDesktop()) { + toast(t('Saved at {path}').replace('{path}', () => path), 'info', { key: 'project-reveal' }); + return; + } + try { + await invokeHost('reveal_path', { path }); + } catch (err) { + toast(typeof err === 'string' && err ? err : t('The file manager could not be opened.'), 'error', { key: 'project-reveal' }); + } +} + +export async function openOutputFolder(): Promise { + const settings = await getSettings().catch(() => null); + if (settings?.downloadDir) await revealFile(settings.downloadDir); +} + +async function choosePath(name: string, current: string | null, mode: DiskMode): Promise { + const title = mode === 'copy' ? t('Save a copy') : t('Save project'); + const picked = await invokeHost('pick_save_path', { + title, + defaultName: `${fileSafe(name)}${mode === 'copy' ? ` ${t('copy')}` : ''}.fcrft`, + defaultDir: lastFolder() || (current ? folderOf(current) : null), + filters: [{ name: t('FormCraft project'), extensions: ['fcrft'] }], + }); + if (typeof picked !== 'string' || !picked) return null; + return EXTENSION.test(picked) ? picked : `${picked}.fcrft`; +} + +export async function writeProjectFile(id: string, name: string, mode: DiskMode): Promise { + if (writing.has(id)) return null; + const current = filePathOf(id); + let path: string | null = mode === 'save' ? current : null; + if (!path && inDesktop()) { + try { + path = await choosePath(name, current, mode); + } catch (err) { + toast(reasonOf(err), 'error', { key: 'project-pick-failed' }); + return null; + } + if (!path) return null; + } + const keep = mode !== 'copy'; + writing.add(id); + emitter.emit('change'); + try { + const done = await exportProject(id, path, path !== null, keep); + if (inDesktop()) remember(FOLDER_KEY, folderOf(done.path)); + const summary = projectStore.get(id); + if (keep && summary) { + written[id] = summary.updatedAt; + remember(WRITTEN_KEY, JSON.stringify(written)); + projectStore.upsert({ ...summary, filePath: done.path }); + } + const text = (keep ? t('Saved to {path}') : t('Saved a copy to {path}')).replace('{path}', () => done.path); + toast(text, 'success', { key: `project-file:${id}`, actions: [{ label: t(revealLabel()), run: () => void revealFile(done.path) }] }); + return done.path; + } catch (err) { + toast(reasonOf(err), 'error', { + key: `project-file-failed:${id}`, + actions: [{ label: t('Try again'), run: () => void writeProjectFile(id, name, mode) }], + }); + return null; + } finally { + writing.delete(id); + emitter.emit('change'); + } +} diff --git a/frontend/src/ui/projects/file-commands.ts b/frontend/src/ui/projects/file-commands.ts new file mode 100644 index 0000000..c48abdd --- /dev/null +++ b/frontend/src/ui/projects/file-commands.ts @@ -0,0 +1,174 @@ +import { commands, type Command } from '../../engine/commands'; +import { shortcuts } from '../../engine/shortcuts'; +import { studios } from '../../engine/studios'; +import { anyDialogOpen } from '../dialogs'; +import { t } from '../i18n'; +import { setProjectNameSource } from '../output-files'; +import { toast } from '../toasts'; +import { startAutosave } from './autosave'; +import { filePathOf, openOutputFolder, revealFile, revealLabel, writeProjectFile, type DiskMode } from './disk'; +import { showProject } from './session'; +import { projectStore } from './store'; + +interface Adapter { + readonly id: string | null; + readonly name: string; + save(): Promise; + close?(): Promise; +} + +const ROOTS = new Set(['scene', 'canvas', 'edit', 'board']); +const BOARD_KEY = 'formcraft.board.active'; +const RECENT_MAX = 8; +const EXPORTS: Record = { scene: 'scene.record', edit: 'edit-export-video' }; + +export const RECENT_IDS: readonly string[] = Array.from({ length: RECENT_MAX }, (_, i) => `open-recent-${i}`); + +const inStudio = (): boolean => ROOTS.has(studios.activeRoot); + +function boardId(): string | null { + try { + return localStorage.getItem(BOARD_KEY); + } catch { + return null; + } +} + +async function adapter(): Promise { + const root = studios.activeRoot; + if (root === 'scene') { + const ctx = await (await import('../scene/bridge')).sceneApi(); + const f = (await import('../scene/chrome/files')).filesFor(ctx); + return { get id() { return f.id; }, get name() { return f.name; }, save: () => f.save(), close: () => f.newScene() }; + } + if (root === 'canvas') { + const ctx = await (await import('../canvas/base/bridge')).canvasApi(); + const f = (await import('../canvas/files/files')).filesFor(ctx); + return { get id() { return f.id; }, get name() { return f.name; }, save: () => f.save(), close: () => f.newCanvas() }; + } + if (root === 'edit') { + const f = (await (await import('../edit/bridge')).editApi()).files; + return { get id() { return f.id; }, get name() { return f.name; }, save: () => f.flush(), close: () => f.newEdit() }; + } + if (root === 'board') { + const board = await import('../board'); + return { + get id() { return boardId(); }, + get name() { const id = boardId(); return (id && projectStore.get(id)?.name) || t('Board'); }, + save: () => board.boardReadyToClose(), + }; + } + return null; +} + +export async function activeProjectId(): Promise { + try { + return (await adapter())?.id ?? null; + } catch { + return null; + } +} + +async function saveTo(mode: DiskMode): Promise { + const a = await adapter(); + if (!a || !(await a.save())) return; + if (!a.id) { + toast(t('Add something to the project before saving it to a file.'), 'info', { key: 'project-empty' }); + return; + } + await writeProjectFile(a.id, a.name, mode); +} + +async function reveal(): Promise { + const a = await adapter(); + const path = filePathOf(a?.id ?? null); + if (path) await revealFile(path); + else toast(t('Save the project to a file first.'), 'info', { key: 'project-no-file' }); +} + +async function close(): Promise { + const a = await adapter(); + if (a?.close) await a.close(); +} + +function recent(i: number): { id: string; name: string } | null { + const list = projectStore + .entries() + .filter((p) => p.openedAt) + .slice() + .sort((a, b) => (b.openedAt ?? '').localeCompare(a.openedAt ?? '')); + const p = list[i]; + return p ? { id: p.id, name: p.name } : null; +} + +export const recentIds = (): string[] => RECENT_IDS.filter((_, i) => recent(i) !== null); + +function interceptSave(): void { + window.addEventListener( + 'keydown', + (e) => { + if (e.defaultPrevented || e.isComposing || e.repeat || !inStudio() || anyDialogOpen()) return; + const id = shortcuts.resolve(e, 'global', {}); + if (id !== 'save' && id !== 'saveAs') return; + e.preventDefault(); + e.stopImmediatePropagation(); + void commands.run(id); + }, + true, + ); +} + +let done = false; + +export function registerFileCommands(): void { + if (done) return; + done = true; + let activeName: string | null = null; + const trackName = (): void => { + void adapter().then((a) => { + activeName = a && a.id ? a.name || null : null; + }, () => undefined); + }; + setProjectNameSource(() => activeName); + studios.on('active', () => queueMicrotask(trackName)); + projectStore.on(trackName); + trackName(); + projectStore.start(); + startAutosave(); + const list: Command[] = [ + { id: 'save', label: 'Save', group: 'File', keys: ['Mod+KeyS'], enabled: inStudio, run: () => saveTo('save') }, + { id: 'saveAs', label: 'Save As...', group: 'File', keys: ['Mod+Shift+KeyS'], enabled: inStudio, run: () => saveTo('as') }, + { id: 'saveCopy', label: 'Save a Copy...', group: 'File', enabled: inStudio, run: () => saveTo('copy') }, + { + id: 'exportOutput', + label: 'Export...', + group: 'File', + enabled: () => !!EXPORTS[studios.activeRoot] || inStudio(), + run: async () => { + const target = EXPORTS[studios.activeRoot]; + if (target && commands.get(target)) await commands.run(target); + else await saveTo('copy'); + }, + }, + { id: 'revealProject', label: () => t(revealLabel()), group: 'File', enabled: inStudio, run: reveal }, + { id: 'closeProject', label: 'Close', group: 'File', keys: ['Mod+KeyW'], enabled: () => inStudio() && studios.activeRoot !== 'board', run: close }, + { id: 'openOutputFolder', label: 'Open Output Folder', group: 'File', run: openOutputFolder }, + ...RECENT_IDS.map((id, i): Command => ({ + id, + label: () => recent(i)?.name ?? t('No recent projects'), + group: 'File', + enabled: () => recent(i) !== null, + run: async () => { + const r = recent(i); + const p = r ? projectStore.get(r.id) : undefined; + if (p) await showProject(p); + }, + })), + ]; + const fresh = list.filter((c) => !commands.get(c.id)); + if (!fresh.length) return; + commands.register(fresh); + shortcuts.adopt(fresh); + projectStore.on(() => commands.refresh()); + interceptSave(); +} diff --git a/frontend/src/ui/projects/new-project.ts b/frontend/src/ui/projects/new-project.ts index c01c8ba..0b42b61 100644 --- a/frontend/src/ui/projects/new-project.ts +++ b/frontend/src/ui/projects/new-project.ts @@ -1,8 +1,9 @@ import '../../styles/projects.css'; +import { commands } from '../../engine/commands'; import { ApiError } from '../../io/api'; import { createProject, type ProjectKind } from '../../io/api-projects'; import { Dialog } from '../dialogs'; -import { el, escapeHtml, setAttr, setClass, setDisabled } from '../dom'; +import { el, escapeHtml, setAttr, setClass, setDisabled, setText } from '../dom'; import { t } from '../i18n'; import { icon } from '../icons'; import { toast } from '../toasts'; @@ -10,30 +11,68 @@ import { KINDS, blankDoc, kindDef } from './kinds'; import { showProject } from './session'; const NAME_MAX = 120; +const LAST_KEY = 'formcraft.newProject.last'; + +interface MakeDef { id: string; label: string; icon: string; blurb: string; page?: string; kind?: ProjectKind; ready: boolean } + +const PAGE_MAKES: readonly MakeDef[] = [ + { id: 'image', page: 'image', label: 'Image', icon: 'image', blurb: 'Describe a picture and generate it.', ready: true }, + { id: 'video', page: 'video', label: 'Video', icon: 'video', blurb: 'Turn a prompt or a picture into a clip.', ready: true }, + { id: 'audio', page: 'audio', label: 'Audio', icon: 'audio', blurb: 'Make a song, a sound effect or a voice.', ready: true }, + { id: 'object', page: 'object', label: '3D model', icon: 'cube', blurb: 'Turn a picture into a textured model.', ready: true }, +]; + +const fromKind = (kind: ProjectKind, label?: string): MakeDef => { + const d = kindDef(kind); + return { id: kind, kind, label: label ?? d.label, icon: d.icon, blurb: d.blurb, ready: d.ready }; +}; + +const MAKES: readonly MakeDef[] = [ + ...PAGE_MAKES, + fromKind('scene', '3D scene'), + { id: 'world', page: 'world', label: 'World', icon: 'globe', blurb: 'Turn a picture into a world you can walk.', ready: true }, + ...(['canvas', 'board', 'edit', 'storyboard'] as const).filter((k) => KINDS.some((d) => d.kind === k)).map((k) => fromKind(k)), +]; + +function lastUsed(): string { + try { + return localStorage.getItem(LAST_KEY) ?? ''; + } catch { + return ''; + } +} + +function remember(id: string): void { + try { + localStorage.setItem(LAST_KEY, id); + } catch { + return; + } +} const later = (label: string): string => t('Arrives with {studio}').replace('{studio}', t(label)); -const defaultName = (kind: ProjectKind): string => t('Untitled {kind}').replace('{kind}', t(kindDef(kind).label).toLowerCase()); +const defaultName = (def: MakeDef): string => t('Untitled {kind}').replace('{kind}', t(def.label).toLowerCase()); class NewProjectDialog extends Dialog { private readonly list = el('
            '); private readonly input = el(``); private readonly make: HTMLButtonElement; - private readonly rows = new Map(); - private kind: ProjectKind = 'storyboard'; + private readonly rows = new Map(); + private def: MakeDef = MAKES[0]; private edited = false; private busy = false; constructor() { - super('New project', 460); - for (const def of KINDS) { + super('New project', 640); + for (const def of MAKES) { const row = el( - ``, ); - this.rows.set(def.kind, row); + this.rows.set(def.id, row); this.list.appendChild(row); } this.list.setAttribute('aria-label', t('Project type')); @@ -43,17 +82,22 @@ class NewProjectDialog extends Dialog { this.make = this.button('Create', 'primary', () => void this.create()); this.list.addEventListener('click', (e) => { const row = (e.target as Element).closest('.fc-np-kind'); - if (row && !row.disabled) this.pick(row.dataset.kind as ProjectKind); + if (row && !row.disabled) this.pick(row.dataset.kind ?? ''); + }); + this.list.addEventListener('dblclick', (e) => { + const row = (e.target as Element).closest('.fc-np-kind'); + if (row && !row.disabled) void this.create(); }); this.list.addEventListener('keydown', (e) => { - if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return; - const ready = KINDS.filter((k) => k.ready); + const step = e.key === 'ArrowDown' || e.key === 'ArrowRight' ? 1 : e.key === 'ArrowUp' || e.key === 'ArrowLeft' ? -1 : 0; + if (!step) return; + const ready = MAKES.filter((k) => k.ready); if (ready.length < 2) return; e.preventDefault(); - const at = ready.findIndex((k) => k.kind === this.kind); - const next = ready[(at + (e.key === 'ArrowDown' ? 1 : ready.length - 1)) % ready.length]; - this.pick(next.kind); - this.rows.get(next.kind)?.focus(); + const at = ready.findIndex((k) => k.id === this.def.id); + const next = ready[(at + step + ready.length) % ready.length]; + this.pick(next.id); + this.rows.get(next.id)?.focus(); }); this.input.addEventListener('input', () => { this.edited = true; @@ -68,22 +112,27 @@ class NewProjectDialog extends Dialog { show(): void { if (this.isOpen) return; this.edited = false; - this.pick(KINDS.find((k) => k.ready)?.kind ?? 'storyboard'); - this.input.value = defaultName(this.kind); + const last = MAKES.find((k) => k.id === lastUsed() && k.ready) ?? MAKES.find((k) => k.ready) ?? MAKES[0]; + this.pick(last.id); this.busyState(false); - this.open(this.input); - this.input.select(); + this.open(this.def.page ? this.rows.get(this.def.id) : this.input); + if (!this.def.page) this.input.select(); } - private pick(kind: ProjectKind): void { - this.kind = kind; + private pick(id: string): void { + this.def = MAKES.find((k) => k.id === id) ?? this.def; for (const [k, row] of this.rows) { - const on = k === kind; + const on = k === this.def.id; setAttr(row, 'aria-checked', String(on)); setAttr(row, 'tabindex', on ? '0' : '-1'); setClass(row, 'is-selected', on); } - if (!this.edited) this.input.value = defaultName(kind); + const page = !!this.def.page; + this.input.disabled = page; + setAttr(this.input, 'placeholder', page ? t('Results are kept in your library') : null); + if (page) this.input.value = ''; + else if (!this.edited) this.input.value = defaultName(this.def); + setText(this.make, t(page ? 'Open' : 'Create')); } private busyState(on: boolean): void { @@ -94,10 +143,18 @@ class NewProjectDialog extends Dialog { private async create(): Promise { if (this.busy) return; - const name = this.input.value.trim() || defaultName(this.kind); + const def = this.def; + remember(def.id); + if (def.page) { + this.close(); + await commands.run(`page-${def.page}`); + return; + } + if (!def.kind) return; + const name = this.input.value.trim() || defaultName(def); this.busyState(true); try { - const project = await createProject({ kind: this.kind, name, doc: blankDoc(this.kind) }); + const project = await createProject({ kind: def.kind, name, doc: blankDoc(def.kind) }); this.close(); await showProject(project); } catch (err) { diff --git a/frontend/src/ui/projects/outputs.ts b/frontend/src/ui/projects/outputs.ts new file mode 100644 index 0000000..fb9fbb1 --- /dev/null +++ b/frontend/src/ui/projects/outputs.ts @@ -0,0 +1,41 @@ +import { studios } from '../../engine/studios'; +import { capabilities, getMedia } from '../../io/api'; +import { t } from '../i18n'; +import { inDesktop, invokeHost } from '../prefs'; +import { joinPath } from '../save-media'; +import { toast, type ToastAction } from '../toasts'; +import { revealLabel } from './disk'; + +const EXT: Record = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'video/mp4': 'mp4', 'video/webm': 'webm', 'audio/mpeg': 'mp3', 'audio/wav': 'wav', 'model/gltf-binary': 'glb' }; + +async function revealMedia(id: string): Promise { + try { + const [caps, media] = await Promise.all([capabilities(), getMedia(id)]); + const dir = joinPath(joinPath(caps.dataDir, 'library'), id.slice(0, 2)); + const dot = media.name.lastIndexOf('.'); + for (const ext of new Set([dot > 0 ? media.name.slice(dot + 1).toLowerCase() : '', EXT[media.mime] ?? ''].filter(Boolean))) { + try { + await invokeHost('reveal_path', { path: joinPath(dir, `${id}.${ext}`) }); + return; + } catch { + continue; + } + } + await invokeHost('reveal_path', { path: dir }); + } catch (err) { + toast(typeof err === 'string' && err ? err : t('The folder could not be shown.'), 'error', { key: 'output-reveal' }); + } +} + +export function outputActions(ids: readonly string[], reveal: ToastAction[] = []): ToastAction[] { + if (!ids.length) return reveal; + const list: ToastAction[] = [{ label: t('Show in Library'), run: () => void studios.activate('library') }]; + if (reveal.length) list.push(...reveal); + else if (inDesktop()) list.push({ label: t(revealLabel()), run: () => void revealMedia(ids[0]) }); + return list; +} + +export function announceOutput(ids: readonly string[], text: string, key: string): void { + if (!ids.length) return; + toast(`${text} ${t('It is in the library.')}`, 'success', { key, actions: outputActions(ids) }); +} diff --git a/frontend/src/ui/projects/recent.ts b/frontend/src/ui/projects/recent.ts index 9a73f2d..07528b6 100644 --- a/frontend/src/ui/projects/recent.ts +++ b/frontend/src/ui/projects/recent.ts @@ -7,6 +7,7 @@ import { whenText } from '../home-files'; import { t } from '../i18n'; import { icon } from '../icons'; import { toast } from '../toasts'; +import { filePathOf, saveStateOf } from './disk'; import { kindDef } from './kinds'; import { showProject } from './session'; import { projectStore } from './store'; @@ -117,7 +118,11 @@ export class RecentProjects { private fill(n: HTMLElement, p: ProjectSummary): void { const def = kindDef(p.kind); setText(q(n, '.fc-rp-name'), p.name); + const state = !filePathOf(p.id) ? 'Not saved to a file yet' : saveStateOf(p.id, false) === 'saved' ? 'Saved' : saveStateOf(p.id, false) === 'saving' ? 'Saving' : 'Edited'; setText(q(n, '.fc-rp-meta'), `${t(def.label)} · ${whenText(stamp(p))}`); + const save = n.querySelector('.fc-rp-save') ?? q(n, '.fc-rp-text').appendChild(el('')); + setText(save, t(state)); + setAttr(n, 'data-save', state === 'Saved' ? 'saved' : state === 'Not saved to a file yet' ? 'none' : 'edited'); setTitle(q(n, '.fc-rp-open'), p.name); const glyph = q(n, '.fc-rp-glyph'); if (glyph.dataset.icon !== def.icon) { diff --git a/frontend/src/ui/prompt/key-sheet.ts b/frontend/src/ui/prompt/key-sheet.ts new file mode 100644 index 0000000..be9514e --- /dev/null +++ b/frontend/src/ui/prompt/key-sheet.ts @@ -0,0 +1,244 @@ +import { models } from '../../engine/models'; +import { ApiError, checkKey, getKeys, putKey, type KeysState, type Provider } from '../../io/api'; +import { passwordRow } from '../controls'; +import { el, q, setDisabled, setHidden, setText } from '../dom'; +import { t } from '../i18n'; +import { icon } from '../icons'; +import { KEYS, placeText, type KeyPlace } from '../panels/connections'; +import { inDesktop, invokeHost } from '../prefs'; +import { toast } from '../toasts'; +import '../../styles/key-sheet.css'; + +/** + * A small sheet that opens on top of a prompt box when the chosen model's provider has no key. + * It saves through the same key route Preferences, Connections uses, then runs what was asked. + * Esc or Cancel closes it and leaves the prompt exactly as it was. + */ + +const CHARGE_KEY = 'formcraft.keySheet.chargeNoted'; + +function chargeNoted(): boolean { + try { + return localStorage.getItem(CHARGE_KEY) === '1'; + } catch { + return true; + } +} + +function markChargeNoted(): void { + try { + localStorage.setItem(CHARGE_KEY, '1'); + } catch { + /* private mode: the note simply shows again next time */ + } +} + +const placeOf = (state: KeysState, provider: Provider): KeyPlace => ({ store: state.stores?.[provider] ?? state.store, system: state.system ?? null }); + +let current: KeySheet | null = null; + +export interface KeySheetOptions { + /** Runs the generation the person asked for, after the key is saved. */ + onSaved(): void; +} + +class KeySheet { + readonly el: HTMLElement; + private readonly input: HTMLInputElement; + private readonly msg: HTMLElement; + private readonly where: HTMLElement; + private readonly save: HTMLButtonElement; + private readonly test: HTMLButtonElement; + private readonly name: string; + private readonly url: string; + private readonly back: Element | null; + private place: KeyPlace = { store: null, system: null }; + private saved = false; + private busy = false; + + constructor( + private readonly anchor: HTMLElement, + private readonly provider: Provider, + private readonly opts: KeySheetOptions, + ) { + const def = KEYS.find((k) => k.provider === provider) ?? KEYS[0]; + this.name = def.name; + this.url = def.url; + this.back = document.activeElement; + const title = t('Add your {provider} key').replace('{provider}', def.name); + const host = def.url.replace(/^https?:\/\//, ''); + this.el = el( + ``, + ); + this.el.setAttribute('aria-label', title); + setText(q(this.el, '.fc-ks-t'), title); + const close = q(this.el, '.fc-ks-x'); + close.setAttribute('aria-label', t('Cancel')); + close.title = t('Cancel'); + setText(q(this.el, '.fc-ks-get span'), t('Get one from {provider}:').replace('{provider}', def.name)); + const link = q(this.el, '.fc-ks-link'); + link.href = def.url; + setText(link, host); + link.addEventListener('click', (e) => { + if (!inDesktop()) return; + e.preventDefault(); + invokeHost('open_url', { url: this.url }).catch(() => this.say(t('The link could not be opened.'))); + }); + const first = q(this.el, '.fc-ks-first'); + if (!chargeNoted()) { + setText(first, t('Runs are charged by {provider} on your own key, at {provider} prices. formcraft adds nothing and never sees your bill.').replace(/\{provider\}/g, def.name)); + setHidden(first, false); + markChargeNoted(); + } + const field = passwordRow(`${def.name} key`, () => undefined, { placeholder: t('Paste your key here') }); + this.input = field.input; + this.input.autocomplete = 'new-password'; + this.input.maxLength = 512; + const paste = el(``); + setText(paste, t('Paste')); + const canRead = typeof navigator !== 'undefined' && !!navigator.clipboard?.readText; + setHidden(paste, !canRead); + paste.addEventListener('click', () => void this.paste()); + q(this.el, '.fc-ks-field').append(field.el, paste); + this.msg = q(this.el, '.fc-ks-msg'); + this.where = q(this.el, '.fc-ks-where'); + this.save = q(this.el, '[data-save]'); + this.test = q(this.el, '[data-test]'); + const cancel = q(this.el, '[data-cancel]'); + setText(cancel, t('Cancel')); + setText(this.test, t('Test')); + setText(this.save, t('Save and generate')); + cancel.addEventListener('click', () => this.close()); + close.addEventListener('click', () => this.close()); + this.test.addEventListener('click', () => void this.check()); + this.save.addEventListener('click', () => void this.submit()); + this.input.addEventListener('input', () => this.sync()); + this.el.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + e.preventDefault(); + e.stopPropagation(); + this.close(); + } else if (e.key === 'Enter' && e.target === this.input) { + e.preventDefault(); + e.stopPropagation(); + void this.submit(); + } + }); + this.el.addEventListener('pointerdown', (e) => e.stopPropagation()); + this.anchor.append(this.el); + this.sync(); + this.input.focus({ preventScroll: true }); + void this.loadPlace(); + } + + close(restore = true): void { + if (current === this) current = null; + this.el.remove(); + if (restore && this.back instanceof HTMLElement && this.back.isConnected) this.back.focus({ preventScroll: true }); + } + + private say(text: string): void { + setText(this.msg, text); + } + + private sync(): void { + const empty = !this.input.value.trim(); + setDisabled(this.save, this.busy || (empty && !this.saved)); + setDisabled(this.test, this.busy || (empty && !this.saved)); + } + + private async loadPlace(): Promise { + try { + const state = await getKeys(); + this.place = placeOf(state, this.provider); + setText(this.where, t(placeText(false, this.place))); + } catch { + setText(this.where, ' '); + } + } + + private async paste(): Promise { + try { + const text = (await navigator.clipboard.readText()).trim(); + if (text) this.input.value = text; + this.sync(); + this.input.focus({ preventScroll: true }); + } catch { + this.say(t('The clipboard could not be read. Press {keys} in the field instead.').replace('{keys}', /Mac/.test(navigator.platform) ? 'Cmd+V' : 'Ctrl+V')); + this.input.focus({ preventScroll: true }); + } + } + + /** Saves what is typed, if anything. True when a key is saved for this provider. */ + private async store(): Promise { + const key = this.input.value.trim(); + if (!key) return this.saved; + const state = await putKey(this.provider, key); + this.input.value = ''; + this.saved = true; + this.place = placeOf(state, this.provider); + setText(this.where, t(placeText(true, this.place))); + await models.refresh(); + return true; + } + + private async work(job: () => Promise, failure: string): Promise { + if (this.busy) return; + this.busy = true; + this.sync(); + try { + await job(); + } catch (err) { + this.say(err instanceof ApiError && err.message ? err.message : failure); + } finally { + this.busy = false; + if (this.el.isConnected) this.sync(); + } + } + + private check(): Promise { + return this.work(async () => { + if (!(await this.store())) return; + this.say(t('Testing the key with {provider}').replace('{provider}', this.name)); + const res = await checkKey(this.provider); + this.say(res.message.trim() || (res.ok ? t('{provider} accepted the key.') : t('{provider} did not accept the key.')).replace('{provider}', this.name)); + }, t('The key could not be tested.')); + } + + private submit(): Promise { + return this.work(async () => { + if (!(await this.store())) { + this.say(t('Paste a {provider} key first.').replace('{provider}', this.name)); + this.input.focus({ preventScroll: true }); + return; + } + toast(`${t('{provider} key saved.').replace('{provider}', this.name)} ${t(placeText(true, this.place))}.`, 'success', { key: 'key-sheet-saved' }); + this.close(); + this.opts.onSaved(); + }, t('The key could not be saved.')); + } +} + +/** Opens the key sheet on a prompt box. A second call on the same box keeps the open sheet. */ +export function openKeySheet(anchor: HTMLElement, provider: Provider, opts: KeySheetOptions): void { + if (current && current.el.parentElement === anchor) { + q(current.el, 'input').focus({ preventScroll: true }); + return; + } + current?.close(false); + current = new KeySheet(anchor, provider, opts); +} + +export function keySheetOpen(): boolean { + return !!current; +} diff --git a/frontend/src/ui/prompt/model-picker.ts b/frontend/src/ui/prompt/model-picker.ts index 176a960..e52cfdf 100644 --- a/frontend/src/ui/prompt/model-picker.ts +++ b/frontend/src/ui/prompt/model-picker.ts @@ -5,6 +5,7 @@ import type { Provider, WindowModel } from '../../io/api'; import { el, patchList, q, setAttr, setClass, setHidden, setHtml, setText, setTitle } from '../dom'; import { onLanguage, t, tn } from '../i18n'; import { icon } from '../icons'; +import { openKeySheet } from './key-sheet'; import { PickPop } from './pick-pop'; import '../../styles/picker.css'; @@ -27,6 +28,8 @@ interface RowRefs { add: HTMLButtonElement; addText: HTMLElement; badges: HTMLElement; + tags: HTMLElement; + fav: HTMLButtonElement; tile: HTMLElement; haystack: string; } @@ -47,6 +50,38 @@ function writeStyle(style: PickerStyle): void { } } +const FAVS_KEY = 'formcraft.picker.favs'; +const RECENT_KEY = 'formcraft.picker.recent.'; +const RECENT_MAX = 3; +const NEW_DAYS = 120; +const FAST_SEC: Record = { image: 8, video: 45, audio: 20, mesh: 45, splat: 90 }; + +function readIds(key: string): string[] { + try { + const raw = JSON.parse(localStorage.getItem(key) ?? '[]'); + return Array.isArray(raw) ? raw.filter((x): x is string => typeof x === 'string') : []; + } catch { + return []; + } +} + +function writeIds(key: string, ids: string[]): void { + try { + localStorage.setItem(key, JSON.stringify(ids)); + } catch { + return; + } +} + +function tagsOf(m: WindowModel, recommended: boolean): string[] { + const out: string[] = []; + if (recommended) out.push('Recommended'); + if (m.expectedSec > 0 && m.expectedSec <= (FAST_SEC[m.kind] ?? 30)) out.push('Fast'); + const at = m.released ? Date.parse(m.released) : NaN; + if (Number.isFinite(at) && Date.now() - at < NEW_DAYS * 86400000) out.push('New'); + return out; +} + function badgesOf(m: WindowModel): Array<{ name: string; title: string }> { const out: Array<{ name: string; title: string }> = []; if (m.options.some((o) => o.key === 'audio')) out.push({ name: 'volume', title: 'Sound' }); @@ -207,8 +242,27 @@ export class ModelPicker { return this.page === 'video' ? 'video' : this.page === 'audio' ? 'audio' : this.page === 'object' ? 'mesh' : this.page === 'world' ? 'splat' : 'image'; } - private entries(list: WindowModel[], grouped: boolean): Entry[] { + private entries(all: WindowModel[], grouped: boolean): Entry[] { const out: Entry[] = []; + const byId = new Map(all.map((m) => [m.id, m])); + const taken = new Set(); + const pin = (key: string, head: string, ids: string[]): void => { + const hits = ids.map((id) => byId.get(id)).filter((m): m is WindowModel => !!m && !taken.has(m.id)); + if (!hits.length) return; + out.push({ key: `p:${key}`, head }); + for (const m of hits) { + taken.add(m.id); + out.push({ key: `m:${m.id}`, model: m }); + } + }; + if (all.length >= GROUP_FROM) { + pin('favs', 'Favourites', readIds(FAVS_KEY)); + pin('recent', 'Recently used', readIds(RECENT_KEY + this.page)); + const rec = models.defaultFor(this.page); + pin('rec', 'Recommended', rec ? [rec] : []); + if (taken.size) out.push({ key: 'p:all', head: 'All models' }); + } + const list = all.filter((m) => !taken.has(m.id)); const current = list.filter((m) => m.tier !== 'older'); const older = list.filter((m) => m.tier === 'older'); const push = (group: WindowModel[], byFamily: boolean): void => { @@ -270,7 +324,8 @@ export class ModelPicker { `` + `` + `` + - `` + + `` + + `` + `${icon('check', 14)}`, ); node.dataset.id = m.id; @@ -283,6 +338,8 @@ export class ModelPicker { add: q(node, '.fc-mp-add'), addText: q(node, '.fc-mp-add span'), badges: q(node, '.fc-mp-badges'), + tags: q(node, '.fc-mp-tags'), + fav: q(node, '.fc-mp-fav'), tile: q(node, '.fc-mp-tile'), haystack: '', }; @@ -305,6 +362,15 @@ export class ModelPicker { const badges = badgesOf(m); const sig = badges.map((b) => b.name).join('|'); setHtml(r.badges, badges.map((b) => `${icon(b.name, 13)}`).join(''), sig); + const tags = tagsOf(m, m.id === models.defaultFor(this.page)); + setHtml(r.tags, tags.map((x) => `${t(x)}`).join(''), `${tags.join('|')}|${t('New')}`); + const fav = readIds(FAVS_KEY).includes(m.id); + setHtml(r.fav, icon(fav ? 'starFilled' : 'star', 14), fav ? 'on' : 'off'); + setAttr(r.fav, 'aria-pressed', String(fav)); + setClass(r.fav, 'is-on', fav); + const favLabel = t(fav ? 'Remove from favourites' : 'Add to favourites'); + setAttr(r.fav, 'aria-label', favLabel); + setAttr(r.fav, 'title', favLabel); const off = !m.available; setClass(r.node, 'is-off', off); setHidden(r.price, off); @@ -313,7 +379,7 @@ export class ModelPicker { const on = m.id === this.currentId(); setClass(r.node, 'is-chosen', on); setAttr(r.node, 'aria-selected', String(on)); - r.haystack = `${m.label} ${m.family} ${m.maker} ${m.blurb}`.toLowerCase(); + r.haystack = `${m.label} ${m.family} ${m.maker} ${m.blurb} ${tags.map((x) => t(x)).join(' ')}`.toLowerCase(); } private onListClick(e: MouseEvent): void { @@ -321,10 +387,23 @@ export class ModelPicker { if (!target) return; const row = target.closest('.fc-mp-row'); if (!row?.dataset.id) return; + if (target.closest('.fc-mp-fav')) { + e.stopPropagation(); + const id = row.dataset.id; + const favs = readIds(FAVS_KEY); + writeIds(FAVS_KEY, favs.includes(id) ? favs.filter((x) => x !== id) : [id, ...favs]); + this.render(); + this.markPicked(id, false); + return; + } if (target.closest('.fc-mp-add')) { e.stopPropagation(); this.pop.close(); - hooks.openPreferences?.('connections'); + const id = row.dataset.id; + const m = models.get(id); + const box = this.el.closest('.fc-pb'); + if (m && box) openKeySheet(box, m.provider, { onSaved: () => this.choose(id) }); + else hooks.openPreferences?.('connections'); return; } this.choose(row.dataset.id); @@ -334,6 +413,8 @@ export class ModelPicker { const m = models.get(id); if (!m) return; const changed = this.currentId() !== m.id; + const key = RECENT_KEY + this.page; + writeIds(key, [m.id, ...readIds(key).filter((x) => x !== m.id)].slice(0, RECENT_MAX)); this.pop.close(true); if (!changed) return; models.select(this.page, m.id); diff --git a/frontend/src/ui/prompt/pick-pop.ts b/frontend/src/ui/prompt/pick-pop.ts index 68f20c3..78abc80 100644 --- a/frontend/src/ui/prompt/pick-pop.ts +++ b/frontend/src/ui/prompt/pick-pop.ts @@ -1,5 +1,6 @@ import { el, setAttr, setHidden } from '../dom'; import { relabel, t } from '../i18n'; +import { safeArea } from '../position'; import '../../styles/picker.css'; const MARGIN = 8; @@ -113,8 +114,9 @@ export class PickPop { const own = this.el.getBoundingClientRect(); const vw = window.innerWidth; const vh = window.innerHeight; - const above = anchor.top - GAP * z - MARGIN * z; - const below = vh - anchor.bottom - GAP * z - MARGIN * z; + const area = safeArea(0); + const above = anchor.top - Math.max(area.top, MARGIN * z) - GAP * z; + const below = Math.min(area.bottom, vh - MARGIN * z) - anchor.bottom - GAP * z; const need = Math.min(own.height, 260 * z); const up = this.cfg.prefer === 'down' ? !(below >= need || below >= above) : above >= need || above >= below; const left = Math.min(Math.max(this.cfg.align === 'end' ? anchor.right - own.width : anchor.left, MARGIN * z), Math.max(MARGIN * z, vw - own.width - MARGIN * z)); diff --git a/frontend/src/ui/prompt/prompt-box.ts b/frontend/src/ui/prompt/prompt-box.ts index bf48284..27f051e 100644 --- a/frontend/src/ui/prompt/prompt-box.ts +++ b/frontend/src/ui/prompt/prompt-box.ts @@ -23,6 +23,9 @@ export interface PromptBoxOptions { accepts?(kinds: Set): boolean; onPreviewMention?(m: Mention): void; onCostClick?(anchor: HTMLElement): void; + onBlocked?(reason: string): void; + onRecall?(): void; + onAddKey?(): void; } interface BoxEvents { input: [string]; release: [] } @@ -43,6 +46,7 @@ interface Dropper { host: HTMLElement; layer: HTMLElement | null; depth: number type Blocker = 'busy' | 'blank' | 'limit' | 'host' | null; +const MOD_ENTER = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent) ? 'Cmd+Enter' : 'Ctrl+Enter'; const BUSY_MS = 10000; const SUBMIT_GAP_MS = 400; const EXPANDED_KEY = 'formcraft.prompt.expanded'; @@ -149,6 +153,7 @@ export class PromptBox { private busyOff: Disposer | null = null; private hostOk = true; private hostReason = ''; + private needsKey = false; private blankOk = false; private cost: PromptCost | null = null; private hintText = ''; @@ -254,6 +259,12 @@ export class PromptBox { }); } + setNeedsKey(on: boolean): void { + if (this.needsKey === on || !this.opts.onAddKey) return; + this.needsKey = on; + this.paint(); + } + setBlankOk(ok: boolean): void { this.attempt(() => { if (this.blankOk === ok) return; @@ -348,7 +359,7 @@ export class PromptBox { private makeParts(): Parts { const bar = el( `
            ` + - `
            `, + ``, ); const foot = el( `
            ${icon('info', 14)}${icon('warning', 14)}` + @@ -382,6 +393,7 @@ export class PromptBox { ); const mainEl = q(inner, '.fc-pb-main'); mainEl.insertBefore(this.editor.root, mainEl.firstChild); + this.editor.root.addEventListener('keydown', this.safe((e: KeyboardEvent) => this.onRecallKey(e))); inner.insertBefore(this.deckSlot, mainEl); inner.insertBefore(this.main.bar, q(inner, '.fc-pb-drop')); inner.insertBefore(this.main.foot, q(inner, '.fc-pb-drop')); @@ -493,7 +505,7 @@ export class PromptBox { : why === 'blank' ? t('Write a prompt first') : why === 'limit' ? this.overText() : why === 'host' ? this.hostReason || t('Generate') - : this.enterToGenerate ? `${t('Generate')} (Enter)` : t('Generate'); + : this.enterToGenerate ? `${t('Generate')} (Enter)` : `${t('Generate')} (${MOD_ENTER})`; const hint = over > 0 ? this.overText() : this.hintText; const kind: HintKind = over > 0 ? 'error' : this.hintKind; const idle = this.value === '' && this.refs === 0 && this.deckMentions() === 0; @@ -506,10 +518,12 @@ export class PromptBox { setAttr(p.cost, 'aria-label', costName || null); setAttr(p.cost, 'aria-disabled', this.cost ? null : 'true'); setAttr(p.cost, 'tabindex', this.cost ? null : '-1'); - setAttr(p.gen, 'aria-disabled', why ? 'true' : 'false'); + setAttr(p.gen, 'aria-disabled', why && !this.needsKey ? 'true' : 'false'); setAttr(p.gen, 'aria-busy', this.busy ? 'true' : null); - setAttr(p.gen, 'title', tip); - setClass(p.gen, 'is-disabled', why !== null); + setAttr(p.gen, 'title', this.needsKey ? t('Add your key in Preferences, Connections') : tip); + setAttr(p.gen, 'aria-label', t(this.needsKey ? 'Add key' : 'Generate')); + setClass(p.gen, 'is-key', this.needsKey); + setClass(p.gen, 'is-disabled', why !== null && !this.needsKey); setClass(p.gen, 'is-pending', this.busy && this.spinner); setText(p.hintText, hint); setClass(p.hint, 'is-empty', hint === ''); @@ -528,21 +542,39 @@ export class PromptBox { } private press(): void { + if (this.needsKey && this.opts.onAddKey) { + this.opts.onAddKey(); + return; + } const why = this.blocker(); if (why === 'limit') toast(this.overText(), 'error', { key: 'prompt-limit' }); - else if (why === 'host' && this.hostReason) toast(this.hostReason, 'info', { key: 'prompt-blocked' }); - else if (why === null) this.submit(); + else if (why === 'host' && this.hostReason) { + if (this.opts.onBlocked) this.opts.onBlocked(this.hostReason); + else toast(this.hostReason, 'info', { key: 'prompt-blocked' }); + } else if (why === null) this.submit(); } private onEnter(e: KeyboardEvent): boolean { const coarse = typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches; - if (!this.enterToGenerate || coarse || e.shiftKey || e.ctrlKey || e.altKey || e.metaKey) return false; + const chord = (e.ctrlKey || e.metaKey) && !e.shiftKey && !e.altKey; + if (!chord && (!this.enterToGenerate || coarse || e.shiftKey || e.ctrlKey || e.altKey || e.metaKey)) return false; + if (chord) { + this.press(); + return true; + } const why = this.blocker(); if (why === 'limit') toast(this.overText(), 'error', { key: 'prompt-limit' }); else if (why === null) this.submit(); return true; } + private onRecallKey(e: KeyboardEvent): void { + if (e.key !== 'ArrowUp' || e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || e.isComposing) return; + if (this.value !== '' || !this.opts.onRecall) return; + e.preventDefault(); + this.opts.onRecall(); + } + private submit(): void { const now = performance.now(); if (now - this.lastSubmit < SUBMIT_GAP_MS) return; diff --git a/frontend/src/ui/prompt/reference-deck.ts b/frontend/src/ui/prompt/reference-deck.ts index d30d5d8..65e0726 100644 --- a/frontend/src/ui/prompt/reference-deck.ts +++ b/frontend/src/ui/prompt/reference-deck.ts @@ -287,7 +287,7 @@ const slotWord = (g: GroupId): string => const pickTitle = (g: GroupId): string => g === 'first' ? 'Choose the first frame' : g === 'last' ? 'Choose the last frame' : g === 'images' ? 'Choose reference images' : g === 'videos' ? 'Choose reference videos' : 'Choose reference audio'; -interface MenuHooks { upload(): void; library(): void } +interface MenuHooks { upload(): void; library(): void; starter(): void } class AddMenu { private readonly root: HTMLElement; @@ -307,7 +307,8 @@ class AddMenu { this.root = el( ``, + `` + + `
            `, ); (document.getElementById('overlay-root') ?? document.body).appendChild(this.root); this.root.addEventListener('click', (e) => { @@ -316,6 +317,7 @@ class AddMenu { const hooks = this.hooks; this.close(false); if (hit.dataset.act === 'upload') hooks?.upload(); + else if (hit.dataset.act === 'starter') hooks?.starter(); else hooks?.library(); }); this.root.addEventListener('keydown', (e) => this.onKey(e)); @@ -1172,7 +1174,7 @@ export class ReferenceDeck { this.say(this.fullMsg(g)); return; } - menu().open(add, { upload: () => this.pickFiles(g), library: () => void this.fromLibrary(g) }); + menu().open(add, { upload: () => this.pickFiles(g), library: () => void this.fromLibrary(g), starter: () => void this.fromLibrary(g, true) }); return; } const node = target.closest('.fc-deck-card'); @@ -1228,7 +1230,7 @@ export class ReferenceDeck { this.input.click(); } - private async fromLibrary(g: GroupId): Promise { + private async fromLibrary(g: GroupId, starter = false): Promise { const cap = this.caps[g]; if (!cap || this.picking) return; const room = cap.max - this.lists[g].length; @@ -1239,7 +1241,9 @@ export class ReferenceDeck { this.picking = true; try { const exclude = this.lists[g].filter((it) => it.mediaId).map((it) => it.mediaId); - const picked = await openLibraryPicker({ kinds: [KIND_OF[g]], max: room, exclude, title: pickTitle(g) }); + const picked = starter + ? await import('../library/starter/starter-picker').then((m) => m.openStarterPicker({ kinds: KIND_OF[g] === 'image' ? ['image', 'texture', 'sprite'] : [KIND_OF[g]], pick: true, max: room, title: pickTitle(g) })) + : await openLibraryPicker({ kinds: [KIND_OF[g]], max: room, exclude, title: pickTitle(g) }); if (picked.length && !this.gone) this.admitMedia(picked, g); } finally { this.picking = false; diff --git a/frontend/src/ui/rendering.ts b/frontend/src/ui/rendering.ts new file mode 100644 index 0000000..9285197 --- /dev/null +++ b/frontend/src/ui/rendering.ts @@ -0,0 +1,265 @@ +import { ApiError, request, type Job } from '../io/api'; +import type { EditFormat, EditQuality } from '../io/api-edit'; +import { checkRow, selectRow } from './controls'; +import { Dialog } from './dialogs'; +import { el, setDisabled, setHidden, setText } from './dom'; +import { t } from './i18n'; +import { inDesktop, invokeHost } from './prefs'; +import { toast } from './toasts'; + +export interface BinariesStatus { + available: boolean; + source: 'bundled' | 'shared' | 'system' | 'sibling' | 'none'; + version: string | null; + ffmpeg: string | null; + ffprobe: string | null; + verified: boolean | null; + licenceTexts: boolean; + release: string; + downloading: boolean; + lastError: string | null; + fetching?: boolean; + encoders?: { available: boolean; mp4: boolean; webm: boolean; h264: string | null } | null; +} + +export interface EncoderState { + installed: boolean; + running: boolean; + version: string | null; + page: string; + presets: Array<{ id: string; label: string }>; +} + +export interface EncoderSent { + sent: boolean; + how: 'queue' | 'opened' | 'missing'; + page?: string; +} + +export interface RenderSpec { + type: 'sequence' | 'concat'; + preset?: string; + format?: EditFormat; + quality?: EditQuality; + fps?: number | { num: number; den: number }; + width?: number; + height?: number; + framesDir?: string; + mediaIds?: string[]; + paths?: string[]; + audioMediaId?: string; + audioPath?: string; + name?: string; + timeoutSec?: number; +} + +export interface RenderingPrefs { + format: EditFormat; + quality: EditQuality; + offerEncoder: boolean; +} + +const KEY = 'formcraft.rendering'; +const QUALITIES: readonly EditQuality[] = ['low', 'medium', 'high', 'veryhigh']; +const DEFAULTS: RenderingPrefs = { format: 'mp4', quality: 'high', offerEncoder: true }; + +export const getBinaries = (): Promise => request('GET', '/render/binaries'); +export const checkBinaries = (fetch = false): Promise => request('POST', '/render/binaries/check', { fetch }); +export const getEncoder = (): Promise => request('GET', '/render/formencoder'); +export const startRender = (spec: RenderSpec): Promise => request('POST', '/render', spec); +export const cancelRender = (jobId: string): Promise => request('POST', `/render/${encodeURIComponent(jobId)}/cancel`, {}); +const postToEncoder = (mediaId: string, preset: string | null, start: boolean): Promise => request('POST', '/render/formencoder/send', { mediaId, preset, start }); + +export function readRenderingPrefs(): RenderingPrefs { + try { + const raw = JSON.parse(localStorage.getItem(KEY) ?? 'null') as Partial | null; + if (!raw || typeof raw !== 'object') return { ...DEFAULTS }; + return { + format: raw.format === 'webm' ? 'webm' : 'mp4', + quality: QUALITIES.includes(raw.quality as EditQuality) ? (raw.quality as EditQuality) : 'high', + offerEncoder: raw.offerEncoder !== false, + }; + } catch { + return { ...DEFAULTS }; + } +} + +function writeRenderingPrefs(patch: Partial): void { + try { + localStorage.setItem(KEY, JSON.stringify({ ...readRenderingPrefs(), ...patch })); + } catch { + return; + } +} + +function openPage(url: string): void { + if (inDesktop()) { + void invokeHost('open_url', { url }).catch(() => undefined); + return; + } + window.open(url, '_blank', 'noopener,noreferrer'); +} + +function why(err: unknown, fallback: string): string { + return err instanceof ApiError && err.message ? err.message : t(fallback); +} + +let picker: PresetPicker | null = null; + +class PresetPicker extends Dialog { + private readonly select = el(''); + private readonly start = el(''); + private readonly note = el('

            '); + private readonly sendBtn: HTMLButtonElement; + private mediaId = ''; + + constructor() { + super('Send to FormEncoder', 420); + this.field('Preset', this.select); + const row = el(''); + const label = row.querySelector('span') as HTMLElement; + label.dataset.en = 'Start encoding at once'; + setText(label, t('Start encoding at once')); + row.append(this.start); + this.body.append(row, this.note); + this.button('Cancel', 'ghost', () => this.close()); + this.sendBtn = this.button('Send', 'primary', () => void this.send()); + } + + show(mediaId: string, state: EncoderState): void { + this.mediaId = mediaId; + if (!this.select.options.length) { + for (const p of state.presets) { + const o = document.createElement('option'); + o.value = p.id; + o.textContent = p.label; + this.select.append(o); + } + } + setText(this.note, state.running ? t('FormEncoder is open. The file joins its queue with this preset.') : t('FormEncoder is not open. It opens with the file in its queue; choose the preset there.')); + setDisabled(this.select, !state.running); + setDisabled(this.start, !state.running); + setDisabled(this.sendBtn, false); + this.open(this.select); + } + + private async send(): Promise { + setDisabled(this.sendBtn, true); + try { + const done = await postToEncoder(this.mediaId, this.select.disabled ? null : this.select.value, this.start.checked); + this.close(); + if (done.how === 'missing') notInstalled(done.page ?? ''); + else toast(done.how === 'queue' ? t('Sent to FormEncoder.') : t('Opening FormEncoder with the file.'), 'success', { key: 'formencoder-send' }); + } catch (err) { + setDisabled(this.sendBtn, false); + toast(why(err, 'The file could not be sent to FormEncoder.'), 'error', { key: 'formencoder-send' }); + } + } +} + +function notInstalled(page: string): void { + toast(t('FormEncoder is not installed.'), 'info', { + key: 'formencoder-missing', + actions: page ? [{ label: t('Get FormEncoder'), run: () => openPage(page) }] : [], + }); +} + +export function encoderOffered(): boolean { + return readRenderingPrefs().offerEncoder; +} + +export async function sendToFormEncoder(mediaId: string): Promise { + let state: EncoderState; + try { + state = await getEncoder(); + } catch (err) { + toast(why(err, 'FormEncoder could not be looked for.'), 'error', { key: 'formencoder-send' }); + return; + } + if (!state.installed && !state.running) { + notInstalled(state.page); + return; + } + picker ??= new PresetPicker(); + picker.show(mediaId, state); +} + +const SOURCE_TEXT: Record = { + bundled: 'Bundled with formcraft', + shared: 'Form family download (formai-binaries)', + sibling: 'Shared from another Form app', + system: 'Installed on this computer', + none: 'None found', +}; + +export function buildRenderingPrefs(): { binaries: HTMLElement[]; defaults: HTMLElement[]; encoder: HTMLElement[] } { + const prefs = readRenderingPrefs(); + const facts: HTMLElement[] = []; + const rows = new Map(); + for (const [id, label] of [ + ['source', 'ffmpeg in use'], + ['version', 'Version'], + ['path', 'Program'], + ['check', 'Checked against the family record'], + ] as const) { + const row = el('
            -
            '); + const name = row.firstElementChild as HTMLElement; + name.dataset.en = label; + setText(name, t(label)); + rows.set(id, row.lastElementChild as HTMLElement); + facts.push(row); + } + const status = el('

            '); + const check = el(''); + check.dataset.en = 'Check binaries'; + setText(check, t('Check binaries')); + const fetch = el(''); + fetch.dataset.en = 'Download ffmpeg'; + setText(fetch, t('Download ffmpeg')); + const buttons = el('
            '); + buttons.append(check, fetch); + + const paint = (s: BinariesStatus): void => { + setText(rows.get('source') as HTMLElement, t(SOURCE_TEXT[s.source] ?? s.source)); + setText(rows.get('version') as HTMLElement, s.version ?? '-'); + setText(rows.get('path') as HTMLElement, s.ffmpeg ?? '-'); + setText(rows.get('check') as HTMLElement, s.verified === true ? t('Matches') : s.verified === false ? t('Differs (replaced by hand)') : t('Not recorded')); + const enc = s.encoders; + let note = s.downloading || s.fetching ? t('Downloading ffmpeg {release} from formai-binaries...').replace('{release}', s.release) : ''; + if (!note && !s.available) note = s.lastError ?? t('No ffmpeg was found. Download the Form family build, or install ffmpeg and check again.'); + if (!note && enc) note = enc.mp4 || enc.webm ? t('Can render {list}.').replace('{list}', [enc.mp4 ? `MP4 (${enc.h264 ?? 'H.264'})` : '', enc.webm ? 'WebM (VP9)' : ''].filter(Boolean).join(', ')) : t('This ffmpeg cannot encode MP4 or WebM here.'); + setText(status, note); + setHidden(fetch, s.available || s.downloading === true); + }; + const run = async (download: boolean): Promise => { + setDisabled(check, true); + setDisabled(fetch, true); + setText(status, t('Checking...')); + try { + paint(await checkBinaries(download)); + } catch (err) { + setText(status, why(err, 'The binaries could not be checked.')); + } finally { + setDisabled(check, false); + setDisabled(fetch, false); + } + }; + check.addEventListener('click', () => void run(false)); + fetch.addEventListener('click', () => void run(true)); + void getBinaries().then(paint, () => setText(status, t('The engine did not answer.'))); + + const format = selectRow('Default format', [['mp4', 'MP4 (H.264 and AAC)'], ['webm', 'WebM (VP9 and Opus)']], (v) => writeRenderingPrefs({ format: v === 'webm' ? 'webm' : 'mp4' })); + const quality = selectRow('Default quality', [['low', 'Low'], ['medium', 'Medium'], ['high', 'High'], ['veryhigh', 'Very high']], (v) => writeRenderingPrefs({ quality: v as EditQuality })); + format.set(prefs.format); + quality.set(prefs.quality); + + const offer = checkRow('Offer Send to FormEncoder', (v) => writeRenderingPrefs({ offerEncoder: v })); + offer.set(prefs.offerEncoder); + const found = el('

            '); + void getEncoder().then( + (s) => setText(found, s.running ? t('FormEncoder {v} is open.').replace('{v}', s.version ?? '') : s.installed ? t('FormEncoder is installed but not open.') : t('FormEncoder is not installed.')), + () => setText(found, ''), + ); + + return { binaries: [...facts, buttons, status], defaults: [format.el, quality.el], encoder: [offer.el, found] }; +} diff --git a/frontend/src/ui/save-label.ts b/frontend/src/ui/save-label.ts new file mode 100644 index 0000000..3c878ba --- /dev/null +++ b/frontend/src/ui/save-label.ts @@ -0,0 +1,53 @@ +import { commands } from '../engine/commands'; +import { studios } from '../engine/studios'; +import { el, setAttr, setClass, setText, setTitle } from './dom'; +import { onLanguage, t } from './i18n'; +import { filePathOf, onSaveState, revealFile, saveStateOf, type SaveState } from './projects/disk'; +import { activeProjectId } from './projects/file-commands'; + +const WORDS: Record = { saved: 'Saved', edited: 'Edited', saving: 'Saving' }; + +export class SaveLabel { + readonly el: HTMLButtonElement; + private dirty = false; + private path: string | null = null; + private run = 0; + + constructor() { + this.el = el(''); + this.el.addEventListener('click', () => { + if (this.path) void revealFile(this.path); + else void commands.run('revealProject'); + }); + onSaveState(() => this.refresh()); + onLanguage(() => this.refresh()); + studios.on('active', () => queueMicrotask(() => this.refresh())); + this.refresh(); + } + + setDirty(dirty: boolean): void { + if (this.dirty === dirty) return; + this.dirty = dirty; + this.refresh(); + } + + refresh(): void { + const run = ++this.run; + void activeProjectId().then((id) => { + if (run !== this.run) return; + this.paint(id); + }); + } + + private paint(id: string | null): void { + const state = id ? saveStateOf(id, this.dirty) : 'edited'; + this.path = filePathOf(id); + this.el.style.visibility = id ? '' : 'hidden'; + setText(this.el, t(WORDS[state])); + setClass(this.el, 'is-saved', state === 'saved'); + setClass(this.el, 'is-saving', state === 'saving'); + setAttr(this.el, 'data-state', state); + setTitle(this.el, this.path ?? t('Not saved to a file yet')); + setAttr(this.el, 'aria-label', this.path ? `${t(WORDS[state])}: ${this.path}` : t(WORDS[state])); + } +} diff --git a/frontend/src/ui/save-media.ts b/frontend/src/ui/save-media.ts index 82584a3..8b6caae 100644 --- a/frontend/src/ui/save-media.ts +++ b/frontend/src/ui/save-media.ts @@ -1,9 +1,10 @@ import { commands } from '../engine/commands'; import { jobs } from '../engine/jobs'; -import { ApiError, downloadBatch, downloadMedia, getMedia, getSettings, mediaFileUrl, type FailedFile, type Media, type SavedFile, type Settings } from '../io/api'; +import { ApiError, deleteMedia, downloadBatch, downloadMedia, getMedia, getSettings, mediaFileUrl, previewFileName, type FailedFile, type Media, type SavedFile, type Settings } from '../io/api'; import { t, tn } from './i18n'; import { jobToastKey } from './job-toasts'; -import { inDesktop, invokeHost } from './prefs'; +import { browserSave, currentProject, folderOf, importForSave, pickOutputFolder, pickSavePath, revealAction } from './output-files'; +import { inDesktop } from './prefs'; import { toast } from './toasts'; const SAVE_KEY = 'media-save'; @@ -68,26 +69,27 @@ export function joinPath(folder: string, name: string): string { return folder.endsWith('/') || folder.endsWith('\\') ? `${folder}${name}` : `${folder}${sep}${name}`; } -const folderOf = (path: string): string => path.replace(/[\\/][^\\/]*$/, '') || path; +export { pickSavePath }; -export async function pickSavePath(title: string, defaultName: string): Promise { - const picked = await invokeHost('pick_save_path', { title, defaultName }); - return typeof picked === 'string' && picked ? picked : null; -} - -async function pickFolder(title: string): Promise { - const picked = await invokeHost('pick_folder', { title }); - return typeof picked === 'string' && picked ? picked : null; -} - -function suggestedName(media: Media, scheme: string): string { +async function suggestedName(media: Media, scheme: string): Promise { const dot = media.name.lastIndexOf('.'); const ext = dot > 0 ? media.name.slice(dot + 1) : media.mime.split('/')[1] || 'bin'; - const stem = dot > 0 ? media.name.slice(0, dot) : media.name; - const model = media.jobId ? jobs.get(media.jobId)?.model ?? null : null; - return exampleName(scheme, { model, name: stem, ext }); + try { + const made = await previewFileName('', ext, media.id, currentProject()); + if (made.ok && made.name) return made.name; + } catch { + const stem = dot > 0 ? media.name.slice(0, dot) : media.name; + const model = media.jobId ? jobs.get(media.jobId)?.model ?? null : null; + return exampleName(scheme, { model, name: stem, ext }); + } + return media.name; } +const withProject = (): { project: string } | Record => { + const project = currentProject(); + return project ? { project } : {}; +}; + interface Busy { end(): Promise; drop(): void } function busy(text: string): Busy { @@ -115,13 +117,7 @@ function busy(text: string): Busy { const reason = (err: unknown): string => (err instanceof ApiError ? err.message : err instanceof Error && err.message ? err.message : t('The file could not be saved.')); function startBrowserDownload(id: string): void { - const link = document.createElement('a'); - link.href = mediaFileUrl(id); - link.download = ''; - link.hidden = true; - document.body.append(link); - link.click(); - link.remove(); + browserSave(mediaFileUrl(id), ''); toast(t('Your browser is downloading the file.'), 'info', { key: SAVE_KEY }); } @@ -135,7 +131,7 @@ async function saveOne(id: string, settings: Settings | null): Promise { if (ask && settings) { try { const media = await getMedia(id); - path = await pickSavePath(t('Save file'), suggestedName(media, settings.namingScheme)); + path = await pickSavePath(t('Save file'), await suggestedName(media, settings.namingScheme)); } catch (err) { toast(reason(err), 'error', { key: SAVE_KEY, ms: SUMMARY_MS }); return; @@ -144,9 +140,9 @@ async function saveOne(id: string, settings: Settings | null): Promise { } const wait = busy(t('Saving...')); try { - const res = await downloadMedia(id, path ? { path, overwrite: true } : {}); + const res = await downloadMedia(id, path ? { path, overwrite: true } : withProject()); await wait.end(); - toast(t('Saved to {path}').replace('{path}', res.path), 'success', { key: SAVE_KEY }); + toast(t('Saved to {path}').replace('{path}', res.path), 'success', { key: SAVE_KEY, actions: revealAction(res.path) }); } catch (err) { await wait.end(); toast(reason(err), 'error', { key: SAVE_KEY, ms: SUMMARY_MS }); @@ -165,7 +161,7 @@ async function summarize(saved: SavedFile[], failed: FailedFile[]): Promise let dir: string | null = null; if (settings?.askLocation === true && inDesktop()) { try { - dir = await pickFolder(t('Choose where to save the files')); + dir = await pickOutputFolder(t('Choose where to save the files')); } catch (err) { toast(reason(err), 'error', { key: SAVE_KEY, ms: SUMMARY_MS }); return; @@ -190,7 +186,8 @@ async function saveMany(ids: string[], settings: Settings | null): Promise } const wait = busy(tn(ids.length, 'Saving {n} file...', 'Saving {n} files...')); try { - const res = await downloadBatch(ids, dir); + const project = currentProject(); + const res = project ? await downloadBatch(ids, dir, project) : await downloadBatch(ids, dir); if (res.jobId !== undefined) { wait.drop(); const state = jobs.get(res.jobId)?.status; @@ -230,3 +227,42 @@ export async function saveMedia(ids: string[]): Promise { saving = false; } } + +export async function saveBlob(blob: Blob, name: string, title: string): Promise { + if (!inDesktop()) { + const url = URL.createObjectURL(blob); + browserSave(url, name); + window.setTimeout(() => URL.revokeObjectURL(url), 60000); + toast(t('Your browser is downloading {name}').replace('{name}', name), 'info', { key: SAVE_KEY }); + return null; + } + let settings: Settings | null = null; + try { + settings = await getSettings(); + } catch { + settings = null; + } + let picked: string | null = null; + if (settings?.askLocation === true) { + try { + picked = await pickSavePath(t(title), name); + } catch (err) { + toast(reason(err), 'error', { key: SAVE_KEY, ms: SUMMARY_MS }); + return null; + } + if (!picked) return null; + } + let made: Media | null = null; + try { + made = await importForSave(blob, name); + if (!made) throw new Error(t('The file could not be saved.')); + const res = await downloadMedia(made.id, picked ? { path: picked, overwrite: true } : { name, project: currentProject() }); + toast(t('Saved to {path}').replace('{path}', res.path), 'success', { key: SAVE_KEY, actions: revealAction(res.path) }); + return res.path; + } catch (err) { + toast(reason(err), 'error', { key: SAVE_KEY, ms: SUMMARY_MS }); + return null; + } finally { + if (made) await deleteMedia(made.id).catch(() => undefined); + } +} diff --git a/frontend/src/ui/scene/chrome/camera.ts b/frontend/src/ui/scene/chrome/camera.ts index 9476587..b740df5 100644 --- a/frontend/src/ui/scene/chrome/camera.ts +++ b/frontend/src/ui/scene/chrome/camera.ts @@ -1,4 +1,5 @@ import { ASPECTS, DEFAULT_FOCAL_MM, OUTPUT_SIZES, type AspectId } from '../../../engine/scene/types'; +import { commands } from '../../../engine/commands'; import { shortcuts } from '../../../engine/shortcuts'; import { el, patchList, setAttr, setHidden, setText, setTitle } from '../../dom'; import { onLanguage, relabel, t } from '../../i18n'; @@ -74,6 +75,12 @@ export function mountCamera(ctx: SceneContext): void { const focalPop = new Popover(modal, { label: t('Focal length'), role: 'dialog', align: 'end', onClose: () => focalPanel.settle() }); focalPop.panel.classList.add('fc-scc-focalpop'); focalPop.panel.append(focalPanel.node); + const align = el(``); + focalPop.panel.append(align); + align.addEventListener('click', () => { + void commands.run('scene.alignCamera'); + focalPop.close(true); + }); const active = () => store.object(store.doc.activeCamera); diff --git a/frontend/src/ui/scene/chrome/commands.ts b/frontend/src/ui/scene/chrome/commands.ts index a52fd36..17a8431 100644 --- a/frontend/src/ui/scene/chrome/commands.ts +++ b/frontend/src/ui/scene/chrome/commands.ts @@ -30,7 +30,7 @@ export function registerChromeCommands(ctx: SceneContext, files: SceneFiles, she }; return registerOnce([ make('scene.mode', () => void editor.toggleMode(), { checked: () => editor.mode === 'record' }), - make('scene.save', () => void files.save(), { enabled: idle }), + make('scene.save', () => void ctx.commands.run('save'), { enabled: idle }), make('scene.saveCopy', () => void files.saveCopy(), { enabled: idle }), own('scene.new', 'New scene', 'File', () => void files.newScene(), { enabled: idle }), own('scene.open', 'Open a scene...', 'File', () => void files.openScene(), { enabled: idle }), diff --git a/frontend/src/ui/scene/chrome/file-menu.ts b/frontend/src/ui/scene/chrome/file-menu.ts index bfa39f2..e47196c 100644 --- a/frontend/src/ui/scene/chrome/file-menu.ts +++ b/frontend/src/ui/scene/chrome/file-menu.ts @@ -7,7 +7,7 @@ import { Popover } from './popover'; import type { Sheet } from './sheet'; import { chromeButton, keepFocus, ownTab, tip } from './widgets'; -const ROWS: readonly string[] = ['scene.new', 'scene.open', '-', 'scene.save', 'scene.saveCopy', 'scene.revert', '-', 'scene.export']; +const ROWS: readonly string[] = ['scene.new', 'scene.open', '-', 'scene.save', 'scene.saveCopy', 'scene.revert', '-', 'scene.export', '-', 'scene.resetLayout']; export function mountFileCluster(ctx: SceneContext, sheet: Sheet): void { const { editor, slots } = ctx; diff --git a/frontend/src/ui/scene/chrome/files.ts b/frontend/src/ui/scene/chrome/files.ts index c8c9114..6c82ca3 100644 --- a/frontend/src/ui/scene/chrome/files.ts +++ b/frontend/src/ui/scene/chrome/files.ts @@ -1,10 +1,9 @@ import { Emitter } from '../../../engine/emitter'; import { contentSignature } from '../../../engine/scene/doc'; import { studios } from '../../../engine/studios'; -import { ApiError, getSettings } from '../../../io/api'; +import { ApiError } from '../../../io/api'; import { createProject, - exportProject, getProject, listProjects, patchProject, @@ -15,9 +14,8 @@ import { } from '../../../io/api-projects'; import { confirmAction, promptName } from '../../dialogs'; import { t, tn } from '../../i18n'; -import { inDesktop } from '../../prefs'; +import { writeProjectFile } from '../../projects/disk'; import { projectStore } from '../../projects/store'; -import { pickSavePath } from '../../save-media'; import { toast } from '../../toasts'; import type { SceneContext } from '../context'; import { packNote } from '../pack'; @@ -32,7 +30,6 @@ const NAME_MAX = 120; const COPY_TRIES = 9999; const reason = (err: unknown, fallback: string): string => (err instanceof ApiError && err.message ? err.message : fallback); -const fileSafe = (name: string): string => name.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').replace(/^[ .]+|[ .]+$/g, '').slice(0, 80) || 'scene'; export function copyName(name: string, taken: ReadonlySet): string { const match = /^(.*?)(?: \((\d+)\))?$/.exec(name.trim()); @@ -255,22 +252,11 @@ export class SceneFiles { const id = this.id; if (id === null) return false; return this.track(async () => { - try { - let path: string | null = null; - const settings = await getSettings().catch(() => null); - if (settings?.askLocation === true && inDesktop()) { - path = await pickSavePath(t('Export scene'), `${fileSafe(this.name)}.fcrft`); - if (!path) return false; - } - const written = await exportProject(id, path, path !== null); - toast(t('Exported to {path}').replace('{path}', () => written.path), 'success', { key: 'scene-export' }); - const note = packNote(this.ctx); - if (note) toast(note, 'info', { key: 'scene-export-pack', ms: 9000 }); - return true; - } catch (err) { - toast(reason(err, t('The scene could not be exported.')), 'error', { key: 'scene-export' }); - return false; - } + const written = await writeProjectFile(id, this.name, 'copy'); + if (!written) return false; + const note = packNote(this.ctx); + if (note) toast(note, 'info', { key: 'scene-export-pack', ms: 9000 }); + return true; }); } diff --git a/frontend/src/ui/scene/chrome/index.ts b/frontend/src/ui/scene/chrome/index.ts index 1b74002..690d20c 100644 --- a/frontend/src/ui/scene/chrome/index.ts +++ b/frontend/src/ui/scene/chrome/index.ts @@ -4,6 +4,7 @@ import { mountCamera } from './camera'; import { registerChromeCommands } from './commands'; import { mountFileCluster } from './file-menu'; import { filesFor } from './files'; +import { mountOverflow } from './overflow'; import { Sheet } from './sheet'; import { bindTitle } from './title'; import { mountTools } from './tools'; @@ -23,6 +24,7 @@ export function mountChrome(ctx: SceneContext): void { mountFileCluster(ctx, sheet); mountTools(ctx); mountCamera(ctx); + mountOverflow(ctx); bindTitle(ctx, files); const refresh = (): void => ctx.commands.refresh(); files.on(refresh); diff --git a/frontend/src/ui/scene/chrome/overflow.ts b/frontend/src/ui/scene/chrome/overflow.ts new file mode 100644 index 0000000..5d64e1d --- /dev/null +++ b/frontend/src/ui/scene/chrome/overflow.ts @@ -0,0 +1,113 @@ +import { commands } from '../../../engine/commands'; +import { shortcuts } from '../../../engine/shortcuts'; +import { studios } from '../../../engine/studios'; +import { el, setDisabled, setText } from '../../dom'; +import { t } from '../../i18n'; +import type { SceneContext } from '../context'; +import { Popover } from './popover'; +import { chromeButton, keepFocus, ownTab } from './widgets'; + +const LEVELS = 4; +const WAND = 'wand'; + +interface Row { + id: string; + level: number; + english?: string; +} + +const ROWS: readonly Row[] = [ + { id: 'scene.shortcuts', level: 2 }, + { id: 'scene.toggleSpace', level: 2, english: 'Transform space' }, + { id: 'scene.toggleSnapping', level: 2, english: 'Snap to steps' }, + { id: WAND, level: 2, english: 'Create a 3D model from an image' }, + { id: 'scene.outliner', level: 4 }, +]; + +export function mountOverflow(ctx: SceneContext): void { + const { slots, editor } = ctx; + const top = slots['top-right'].parentElement as HTMLElement; + const parts = [slots['top-left'], slots['top-centre'], slots['top-right']]; + const bar = el('
            '); + const more = chromeButton({ icon: 'more', cls: 'fc-scc-tool' }); + more.setAttribute('aria-haspopup', 'menu'); + more.setAttribute('aria-expanded', 'false'); + bar.append(more); + slots['top-right'].append(bar); + keepFocus(bar); + ownTab(bar); + + const pop = new Popover(slots.modal, { label: t('More tools'), role: 'menu', align: 'end' }); + pop.panel.classList.add('fc-scc-menu'); + keepFocus(pop.panel); + ownTab(pop.panel); + const rows = new Map(); + for (const row of ROWS) { + const node = el( + ``, + ); + rows.set(row.id, node); + pop.panel.append(node); + } + + let level = 0; + const paintMenu = (): void => { + for (const row of ROWS) { + const node = rows.get(row.id) as HTMLButtonElement; + node.hidden = level < row.level; + const cmd = row.id === WAND ? null : commands.get(row.id); + setText(node.querySelector('.fc-scc-item-label'), row.english ? t(row.english) : cmd ? t(commands.label(cmd)) : row.id); + setText(node.querySelector('.fc-scc-item-keys'), row.id === WAND ? '' : shortcuts.label(row.id)); + setDisabled(node, editor.busy || (cmd ? !commands.enabled(cmd) : false)); + } + }; + + const apply = (next: number): void => { + level = next; + for (let i = 1; i <= LEVELS; i++) top.classList.toggle(`is-sq${i}`, next >= i); + }; + + const fits = (): boolean => { + const style = getComputedStyle(top); + const room = top.clientWidth - (parseFloat(style.paddingLeft) || 0) - (parseFloat(style.paddingRight) || 0); + const gap = parseFloat(style.columnGap) || 0; + let used = gap * (parts.length - 1); + for (const part of parts) used += part.scrollWidth; + return used <= room + 0.5; + }; + + let frame = 0; + const measure = (): void => { + frame = 0; + if (top.clientWidth < 1) return; + let next = 0; + apply(0); + while (!fits() && next < LEVELS) apply(++next); + if (level < 2 && pop.isOpen) pop.close(false); + if (pop.isOpen) paintMenu(); + }; + const schedule = (): void => { + if (!frame) frame = requestAnimationFrame(measure); + }; + + more.addEventListener('click', (e) => { + paintMenu(); + pop.toggle(more, e.detail === 0); + }); + pop.panel.addEventListener('click', (e) => { + const node = e.target instanceof Element ? e.target.closest('.fc-scc-item') : null; + if (!node || node.disabled || !node.dataset.id) return; + pop.close(false); + if (node.dataset.id === WAND) void studios.activate('object'); + else void commands.run(node.dataset.id); + }); + more.setAttribute('aria-label', t('More tools')); + more.setAttribute('title', t('More tools')); + + const watcher = new ResizeObserver(schedule); + watcher.observe(top); + for (const part of parts) watcher.observe(part); + editor.on('mode', schedule); + editor.on('panels', schedule); + measure(); +} diff --git a/frontend/src/ui/scene/chrome/popover.ts b/frontend/src/ui/scene/chrome/popover.ts index 174de30..991ab9b 100644 --- a/frontend/src/ui/scene/chrome/popover.ts +++ b/frontend/src/ui/scene/chrome/popover.ts @@ -1,5 +1,6 @@ import { el, setAttr } from '../../dom'; -import { clamp, rove } from './widgets'; +import { placeFloating } from '../../position'; +import { rove } from './widgets'; export interface PopoverOptions { label: string; @@ -9,9 +10,6 @@ export interface PopoverOptions { onClose?: () => void; } -const GAP = 6; -const EDGE = 8; - export class Popover { readonly panel: HTMLElement; @@ -91,20 +89,9 @@ export class Popover { if (!trigger) return; const area = this.host.getBoundingClientRect(); const scale = this.host.offsetWidth > 0 ? area.width / this.host.offsetWidth : 1; - const at = trigger.getBoundingClientRect(); - const width = this.panel.offsetWidth; - const height = this.panel.offsetHeight; - const room = this.host.offsetWidth; - const tall = this.host.offsetHeight; - const triggerLeft = (at.left - area.left) / scale; - const triggerRight = (at.right - area.left) / scale; - const triggerTop = (at.top - area.top) / scale; - const triggerBottom = (at.bottom - area.top) / scale; - const left = clamp(this.align === 'end' ? triggerRight - width : triggerLeft, EDGE, Math.max(EDGE, room - width - EDGE)); - const below = triggerBottom + GAP; - const top = below + height > tall - EDGE ? Math.max(EDGE, triggerTop - GAP - height) : below; - this.panel.style.left = `${Math.round(left)}px`; - this.panel.style.top = `${Math.round(top)}px`; + const placed = placeFloating(this.panel, trigger.getBoundingClientRect(), { side: 'bottom', align: this.align, scale }); + this.panel.style.left = `${Math.round((placed.left - area.left) / scale)}px`; + this.panel.style.top = `${Math.round((placed.top - area.top) / scale)}px`; } private readonly onDown = (e: PointerEvent): void => { diff --git a/frontend/src/ui/scene/chrome/tools.ts b/frontend/src/ui/scene/chrome/tools.ts index d49f788..f6dd3e4 100644 --- a/frontend/src/ui/scene/chrome/tools.ts +++ b/frontend/src/ui/scene/chrome/tools.ts @@ -5,8 +5,10 @@ import { studios } from '../../../engine/studios'; import { el, setAttr, setDisabled, setHidden, setText, setTitle } from '../../dom'; import { onLanguage, relabel, t } from '../../i18n'; import { icon } from '../../icons'; +import { toggleTipText } from '../../tooltip'; import type { SceneContext } from '../context'; import { chromeButton, keepFocus, ownTab, tip } from './widgets'; +import { Popover } from './popover'; const TOOLS = [ { mode: 'move', id: 'scene.gizmoMove', icon: 'scMove', label: 'Move' }, @@ -49,10 +51,55 @@ export function mountTools(ctx: SceneContext): void { const spaceWorld = space.querySelector('[data-k="world"]') as HTMLElement; const spaceLocal = space.querySelector('[data-k="local"]') as HTMLElement; const spaceText = space.querySelector('.fc-scc-text') as HTMLElement; - const snap = chromeButton({ icon: 'scSnap', cls: 'fc-scc-tool' }); + const snap = chromeButton({ icon: 'scSnap', text: '', cls: 'fc-scc-snap' }); + const snapText = snap.querySelector('.fc-scc-text') as HTMLElement; + const snapMore = chromeButton({ icon: 'chevronDown', size: 12, cls: 'fc-scc-tool fc-scc-snapmore' }); + setAttr(snapMore, 'aria-haspopup', 'dialog'); + setAttr(snapMore, 'aria-expanded', 'false'); + space.dataset.tipKeys = 'scene.toggleSpace'; + snap.dataset.tipKeys = 'scene.toggleSnapping'; space.addEventListener('click', () => void commands.run('scene.toggleSpace')); snap.addEventListener('click', () => void commands.run('scene.toggleSnapping')); - bar.append(space, snap); + bar.append(space, snap, snapMore); + + const snapPop = new Popover(slots.modal, { label: t('Snap steps'), role: 'dialog', align: 'start' }); + const field = (key: 'move' | 'rotate' | 'scale', english: string, unit: string, step: string): string => + ``; + const snapPanel = el( + `
            ` + + `${t('Snap steps')}` + + field('move', 'Move', 'm', '0.01') + + field('rotate', 'Rotate', 'deg', '1') + + field('scale', 'Scale', 'x', '0.01') + + `` + + `
            `, + ); + ownTab(snapPanel); + snapPop.panel.append(snapPanel); + const snapInputs = Array.from(snapPanel.querySelectorAll('input[data-snap]')); + const paintSnapPanel = (): void => { + const s = editor.snapSteps; + for (const input of snapInputs) { + const k = input.dataset.snap as 'move' | 'rotate' | 'scale' | 'grid'; + if (k === 'grid') input.checked = s.grid; + else if (document.activeElement !== input) input.value = String(s[k]); + } + }; + snapPanel.addEventListener('change', (e) => { + const input = e.target as HTMLInputElement; + const k = input.dataset.snap; + if (k === 'grid') editor.setSnapSteps({ grid: input.checked }); + else if (k === 'move' || k === 'rotate' || k === 'scale') { + const v = Number(input.value); + if (Number.isFinite(v) && v > 0) editor.setSnapSteps({ [k]: v }); + if (!editor.snapping) editor.setSnapping(true); + } + paintSnapPanel(); + }); + snapMore.addEventListener('click', (e) => { + paintSnapPanel(); + snapPop.toggle(snapMore, e.detail === 0); + }); const wandBar = el('
            '); const wand = chromeButton({ icon: 'scWand', cls: 'fc-scc-tool' }); @@ -90,25 +137,29 @@ export function mountTools(ctx: SceneContext): void { } const local = editor.gizmoSpace === 'local'; const scaling = editor.gizmoMode === 'scale'; - const spaceKeys = shortcuts.label('scene.toggleSpace'); setHidden(spaceWorld, local); setHidden(spaceLocal, !local); - setText(spaceText, t(local ? 'Local' : 'World')); + setText(spaceText, t(local ? 'Local' : 'Global')); setDisabled(space, scaling || editor.busy); - setAttr(space, 'aria-label', `${t('Transform space')}: ${t(local ? 'Local' : 'World')}`); + setAttr(space, 'aria-label', `${t('Transform space')}: ${t(local ? 'Local' : 'Global')}`); + setAttr(space, 'aria-pressed', String(local)); setTitle( space, - scaling - ? t('Scale always works in local space') - : `${t('Transform space')}: ${t(local ? 'Local' : 'World')}${spaceKeys ? ` (${spaceKeys} ${t('to switch')})` : ''}`, + scaling ? t('Scale always works in local space') : toggleTipText(t('Transform space'), t(local ? 'Local' : 'Global'), t(local ? 'Global' : 'Local')), ); setAttr(snap, 'aria-pressed', String(editor.snapping)); snap.classList.toggle('is-on', editor.snapping); setDisabled(snap, editor.busy); setAttr(snap, 'aria-label', t('Snap to steps')); - setTitle(snap, `${t('Snap to steps')}: ${t(editor.snapping ? 'On' : 'Off')}${shortcuts.label('scene.toggleSnapping') ? ` (${shortcuts.label('scene.toggleSnapping')})` : ''}`); - setAttr(wand, 'aria-label', t('Create a 3D object from an image')); - setTitle(wand, t('Create a 3D object from an image')); + setTitle(snap, toggleTipText(t('Snap to steps'), t(editor.snapping ? 'On' : 'Off'), t(editor.snapping ? 'Off' : 'On'))); + const steps = editor.snapSteps; + setText(snapText, editor.snapping ? `${steps.grid ? t('Grid') : steps.move} · ${steps.rotate}°` : t('Off')); + setDisabled(snapMore, editor.busy); + setAttr(snapMore, 'aria-label', t('Snap steps')); + setTitle(snapMore, t('Snap steps')); + if (snapPop.isOpen) paintSnapPanel(); + setAttr(wand, 'aria-label', t('Create a 3D model from an image')); + setTitle(wand, t('Create a 3D model from an image')); setDisabled(wand, editor.busy); }; diff --git a/frontend/src/ui/scene/generate/model-pick.ts b/frontend/src/ui/scene/generate/model-pick.ts index f60c529..0d6529d 100644 --- a/frontend/src/ui/scene/generate/model-pick.ts +++ b/frontend/src/ui/scene/generate/model-pick.ts @@ -34,7 +34,7 @@ export class ModelPick { private picked = ''; private query = ''; - constructor(private readonly opts: { modelId: string; onChange(model: WindowModel): void }) { + constructor(private readonly opts: { modelId: string; onChange(model: WindowModel): void; onAddKey?(model: WindowModel): void }) { this.wanted = opts.modelId; this.el = el( `` + + `` + + `${t(ROLE_LABEL[r])}
            `, + ).join(''); + const root = el( + '
            ' + + `
            ${t('Material')}
            ` + + `
            ` + + `
            ${slots}
            ` + + `
            ${t('Tiling X')}
            ${t('Tiling Y')}
            ` + + range('Metalness', 'metalness') + range('Roughness', 'roughness') + range('Opacity', 'opacity') + + `
            ${t('Glow colour')}
            ` + + `
            ${t('Glow strength')}
            ` + + '
            ', + ); + const presetBox = q(root, '.fc-mt-presets'); + const current = (): Readonly | undefined => host.object(); + const mat = (): NonNullable => current()?.material ?? { metalness: 0, roughness: 1 }; + const repeat = (): [number, number] => mat().repeat ?? [1, 1]; + + const rx = numField(host, 'Tiling X', 2, (v) => ({ repeat: [v, repeat()[1]] })); + const ry = numField(host, 'Tiling Y', 2, (v) => ({ repeat: [repeat()[0], v] })); + const glow = numField(host, 'Glow strength', 2, (v) => ({ emissive: mat().emissive ?? '#ffffff', emissiveStrength: v })); + q(root, '[data-slot="rx"]').replaceWith(rx.el); + q(root, '[data-slot="ry"]').replaceWith(ry.el); + q(root, '[data-slot="glow"]').replaceWith(glow.el); + + const ranges = (['metalness', 'roughness', 'opacity'] as const).map((key) => { + const input = q(root, `[data-k="${key}"]`); + const out = input.parentElement?.querySelector('output') as HTMLElement; + input.addEventListener('input', () => { + const o = current(); + if (o) host.run.preview(o.id, 'Change material', { material: { [key]: Number(input.value) } }); + }); + for (const ev of ['change', 'pointerup', 'blur']) input.addEventListener(ev, () => void host.run.close()); + return { key, input, out }; + }); + const emissive = q(root, '[data-k="emissive"]'); + emissive.addEventListener('input', () => { + const o = current(); + if (o) host.run.preview(o.id, 'Change material', { material: { emissive: emissive.value, emissiveStrength: mat().emissiveStrength || 1 } }); + }); + emissive.addEventListener('change', () => void host.run.close()); + + const setMap = (role: MapRole, m: Media): void => { + host.run.close(); + const maps = mapsOfMedia(m); + applyMaterial(host.ctx, { [role]: maps[role] ?? { $media: m.id } }); + }; + for (const role of MAP_ROLES) { + const slot = q(root, `[data-r="${role}"]`); + const pick = q(slot, '.fc-mt-map'); + pick.addEventListener('click', () => + menuAt(pick, [ + { id: 'lib', label: t('From the library'), icon: 'library', run: () => void fromLibrary(['image'], t('Choose a map')).then((m) => m && setMap(role, m)) }, + { id: 'starter', label: t('From the starter library'), icon: 'image', run: () => void fromStarter(['texture'], t('Choose a map')).then((m) => m && setMap(role, m)) }, + ]), + ); + q(slot, '.fc-mt-clear').addEventListener('click', () => { + host.run.close(); + applyMaterial(host.ctx, { [role]: null }, 'Clear map'); + }); + } + q(root, '[data-k="more"]').addEventListener('click', () => { + host.run.close(); + void fromStarter(['texture'], t('Choose a material')).then((m) => m && applyMaterialMedia(host.ctx, m)); + }); + + let presetsAsked = false; + const loadPresets = async (): Promise => { + presetsAsked = true; + try { + const { listStarter, starterThumbUrl } = await import('../../library/starter/api-starter'); + const page = await listStarter({ kinds: ['texture'], limit: PRESETS }); + for (const item of page.items.slice(0, PRESETS)) { + const b = el(``); + b.title = item.name; + setAttr(b, 'aria-label', item.name); + q(b, 'img').src = starterThumbUrl(item.uid, 64); + b.addEventListener('click', async () => { + host.run.close(); + const { addToLibrary } = await import('../../library/starter/starter-use'); + const m = await addToLibrary(item, true); + if (m) applyMaterialMedia(host.ctx, m); + }); + presetBox.append(b); + } + setClass(presetBox, 'is-empty', presetBox.childElementCount === 0); + } catch { + setClass(presetBox, 'is-empty', true); + } + }; + + return { + el: root, + kinds: ['shape', 'model'], + refresh(o) { + if (!presetsAsked) void loadPresets(); + const m = o.material ?? { metalness: 0, roughness: 1 }; + const off = o.locked; + for (const role of MAP_ROLES) { + const slot = q(root, `[data-r="${role}"]`); + const img = q(slot, 'img'); + const id = m[role]?.$media ?? ''; + if (img.dataset.id !== id) { + img.dataset.id = id; + if (id) img.src = mediaThumbUrl(id, 96); + else img.removeAttribute('src'); + } + setHidden(img, !id); + setHidden(q(slot, '.fc-mt-none'), !!id); + setClass(q(slot, '.fc-mt-clear'), 'is-void', !id); + setDisabled(q(slot, '.fc-mt-map'), off); + setDisabled(q(slot, '.fc-mt-clear'), off || !id); + } + const r = m.repeat ?? [1, 1]; + rx.show(r[0]); + ry.show(r[1]); + glow.show(m.emissiveStrength ?? 0); + for (const f of [rx, ry, glow]) f.setDisabled(off); + for (const { key, input, out } of ranges) { + const v = key === 'opacity' ? m.opacity ?? 1 : m[key]; + if (document.activeElement !== input) input.value = String(v); + setText(out, trimmed(v, 2).toFixed(2)); + setDisabled(input, off); + } + if (!host.run.open) setValue(emissive, m.emissive ?? '#000000'); + setDisabled(emissive, off); + setDisabled(q(root, '[data-k="more"]'), off); + for (const b of Array.from(presetBox.querySelectorAll('button'))) setDisabled(b as HTMLButtonElement, off); + }, + }; +} + +export function environmentSection(host: SectionHost): Section { + const root = el( + '
            ' + + `
            ${t('Environment')}
            ` + + '

            ' + + `
            ` + + `
            ${t('Light strength')}
            ${t('Turn')}
            ` + + `
            ` + + '
            ', + ); + const { ctx } = host; + const name = q(root, '[data-k="name"]'); + const note = q(root, '[data-k="note"]'); + const choose = q(root, '[data-k="choose"]'); + const clear = q(root, '[data-k="clear"]'); + const bg = q(root, '[data-k="bg"]'); + const hooks = (apply: (v: number) => void) => ({ type: apply, close: () => undefined, cancel: () => undefined, history: (d: 'undo' | 'redo') => host.history(d) }); + const k = new NumInput({ label: 'Light strength', decimals: 2 }, hooks((v) => void patchSceneEnvMap(ctx, { intensity: v }))); + const rot = new NumInput({ label: 'Turn', decimals: 0 }, hooks((v) => void patchSceneEnvMap(ctx, { rotation: v }))); + q(root, '[data-slot="k"]').replaceWith(k.el); + q(root, '[data-slot="rot"]').replaceWith(rot.el); + const use = (m: Media | null, file?: string): void => { + if (m) void setSceneEnvMap(ctx, m.id, file ?? m.name); + }; + choose.addEventListener('click', () => + menuAt(choose, [ + { id: 'lib', label: t('From the library'), icon: 'library', run: () => void fromLibrary(['image', 'other'], t('Choose an environment image')).then((m) => use(m)) }, + { id: 'starter', label: t('From the starter library'), icon: 'image', run: () => void fromStarter(['hdri'], t('Choose an environment image')).then((m) => use(m)) }, + ]), + ); + clear.addEventListener('click', () => void ctx.store.setEnvMap(null)); + bg.addEventListener('change', () => void patchSceneEnvMap(ctx, { background: bg.checked })); + + const section: Section = { + el: root, + kinds: ['camera'], + refresh() { + const map = ctx.store.doc.envMap ?? null; + setText(name, map ? map.name : t('None')); + setText(note, !map ? t('Light the scene with an HDRI or a panorama image.') : map.hdr ? t('HDR image: lights the scene in full range.') : t('Tone-mapped image: works as a background and lights the scene approximately. An .hdr file lights it correctly.')); + k.show(map?.intensity ?? 1); + rot.show(map?.rotation ?? 0); + setChecked(bg, map?.background ?? true); + for (const f of [k, rot]) f.setDisabled(!map); + setDisabled(bg, !map); + setDisabled(clear, !map); + }, + }; + ctx.store.on('env', (keys) => { + if (keys.includes('envMap') && !root.hidden) section.refresh(host.object() as SceneObject); + }); + return section; +} diff --git a/frontend/src/ui/scene/materials/textures.ts b/frontend/src/ui/scene/materials/textures.ts new file mode 100644 index 0000000..a5c8ffe --- /dev/null +++ b/frontend/src/ui/scene/materials/textures.ts @@ -0,0 +1,79 @@ +import * as THREE from 'three'; + +export type TexRole = 'color' | 'data'; +type Src = THREE.Source; + +interface Shared { + refs: number; + ready: Promise; + source: Src | null; +} + +const MAX_EDGE = 4096; +const ANISOTROPY = 8; +const cache = new Map(); + +async function decode(url: string): Promise { + const res = await fetch(url); + if (!res.ok) throw new Error(`texture ${res.status}`); + const blob = await res.blob(); + const opts = { imageOrientation: 'flipY', premultiplyAlpha: 'none', colorSpaceConversion: 'none' } as const; + let bitmap = await createImageBitmap(blob, opts); + if (Math.max(bitmap.width, bitmap.height) > MAX_EDGE) { + const k = MAX_EDGE / Math.max(bitmap.width, bitmap.height); + const small = await createImageBitmap(blob, { ...opts, resizeWidth: Math.max(1, Math.round(bitmap.width * k)), resizeHeight: Math.max(1, Math.round(bitmap.height * k)), resizeQuality: 'high' }); + bitmap.close(); + bitmap = small; + } + return new THREE.Source(bitmap); +} + +export interface TexHandle { + readonly texture: THREE.Texture; + release(): void; +} + +export async function acquireTexture(url: string, role: TexRole): Promise { + let shared = cache.get(url); + if (!shared) { + const made: Shared = { refs: 0, source: null, ready: decode(url) }; + made.ready.then((s) => (made.source = s), () => cache.delete(url)); + cache.set(url, made); + shared = made; + } + shared.refs++; + const entry = shared; + let source: Src; + try { + source = await entry.ready; + } catch (err) { + entry.refs--; + throw err; + } + const texture = new THREE.Texture(); + texture.source = source; + texture.flipY = false; + texture.wrapS = THREE.RepeatWrapping; + texture.wrapT = THREE.RepeatWrapping; + texture.anisotropy = ANISOTROPY; + texture.colorSpace = role === 'color' ? THREE.SRGBColorSpace : THREE.NoColorSpace; + texture.needsUpdate = true; + let done = false; + return { + texture, + release() { + if (done) return; + done = true; + texture.dispose(); + entry.refs--; + if (entry.refs > 0 || cache.get(url) !== entry) return; + cache.delete(url); + const data = entry.source?.data as ImageBitmap | undefined; + data?.close?.(); + }, + }; +} + +export function sharedTextureCount(): number { + return cache.size; +} diff --git a/frontend/src/ui/scene/materials/use.ts b/frontend/src/ui/scene/materials/use.ts new file mode 100644 index 0000000..862b4ee --- /dev/null +++ b/frontend/src/ui/scene/materials/use.ts @@ -0,0 +1,42 @@ +import type { MaterialPatch, MediaRef } from '../../../engine/scene/material'; +import type { Media } from '../../../io/api'; +import { t } from '../../i18n'; +import type { SceneContext } from '../context'; + +const ROLE_OF: Record = { color: 'colorMap', normal: 'normalMap', roughness: 'roughnessMap' }; + +export function mapsOfMedia(m: Media): MaterialPatch { + const credit = (m as Media & { meta?: { credit?: { maps?: Record } } }).meta?.credit; + const out: MaterialPatch = {}; + const maps = credit?.maps; + if (maps && typeof maps === 'object') { + for (const [role, id] of Object.entries(maps)) { + const key = ROLE_OF[role]; + if (key && typeof id === 'string' && id) out[key] = { $media: id }; + } + } + if (!out.colorMap) out.colorMap = { $media: m.id }; + return out; +} + +export const takesMaterial = (kind: string | undefined): boolean => kind === 'shape' || kind === 'model'; + +export function applyMaterial(ctx: SceneContext, patch: MaterialPatch, label = 'Change material'): boolean { + const id = ctx.store.selected; + const o = id ? ctx.store.object(id) : undefined; + if (!o || !takesMaterial(o.kind)) { + ctx.toast(t('Select a shape or a model first to give it a material.'), 'info', { key: 'scene-material' }); + return false; + } + if (o.locked) { + ctx.toast(t('This object is locked.'), 'info', { key: 'scene-material' }); + return false; + } + const white = (patch.colorMap as MediaRef | null | undefined) && o.kind === 'shape' && !o.material?.colorMap; + return ctx.store.update(o.id, { material: patch, ...(white ? { color: '#ffffff' } : {}) }, { label }); +} + +export function applyMaterialMedia(ctx: SceneContext, m: Media): boolean { + const maps = mapsOfMedia(m); + return applyMaterial(ctx, { colorMap: null, normalMap: null, roughnessMap: null, ...maps }, 'Apply material'); +} diff --git a/frontend/src/ui/scene/objects/model.ts b/frontend/src/ui/scene/objects/model.ts index 18c21f7..41b3f51 100644 --- a/frontend/src/ui/scene/objects/model.ts +++ b/frontend/src/ui/scene/objects/model.ts @@ -9,6 +9,7 @@ import { disposeTree } from '../../viewers/stage'; import { describeSkinned } from './bones'; import { boundsOf, checkAbort, loadError, localBox, MESSAGES, type ObjectBuilt, once, releaseTexture } from './common'; import { advance, createEntrance } from './entrance'; +import { MaterialBinder } from '../materials/binder'; import { CENTIMETRE_MAX, FIT_SIZE, SANE_MAX, SANE_MIN, TEXTURE_ANISOTROPY } from './palette'; interface Loaded { @@ -164,6 +165,8 @@ export const modelBuilder: Builder = { } }); for (const node of strip) node.removeFromParent(); + const binder = new MaterialBinder(env, Array.from(owns.keys()) as THREE.MeshStandardMaterial[]); + binder.apply(obj.material); let fit = 1; if (!(ref && 'kit' in ref)) { fit = fitFactor(localBox(model).getSize(new THREE.Vector3()).toArray()); @@ -187,6 +190,7 @@ export const modelBuilder: Builder = { if (keys.has('material')) { const now = specOf(next); for (const item of owns.values()) apply(item, now); + binder.apply(next.material); } env.requestRender(); }, @@ -195,6 +199,7 @@ export const modelBuilder: Builder = { built.tick = undefined; node.removeFromParent(); model.removeFromParent(); + binder.dispose(); if (shared) freeShared(model); else disposeTree(model); for (const item of owns.values()) { diff --git a/frontend/src/ui/scene/objects/shape.ts b/frontend/src/ui/scene/objects/shape.ts index 28cdbf3..ffe68b5 100644 --- a/frontend/src/ui/scene/objects/shape.ts +++ b/frontend/src/ui/scene/objects/shape.ts @@ -4,6 +4,7 @@ import type { SceneObject, ShapeKey } from '../../../engine/scene/types'; import { boundsOf, type ObjectBuilt, once, parseColor } from './common'; import { advance, createEntrance } from './entrance'; import { MATTE_METALNESS, MATTE_ROUGHNESS, SHAPE_DEFAULT_COLOR } from './palette'; +import { MaterialBinder } from '../materials/binder'; const GEOMETRY: Record THREE.BufferGeometry> = { cube: () => new THREE.BoxGeometry(1, 1, 1), @@ -34,6 +35,8 @@ export const shapeBuilder: Builder = { let geometry = geometryFor(key); const material = new THREE.MeshStandardMaterial(); paint(material, obj); + const binder = new MaterialBinder(env, [material]); + binder.apply(obj.material); const mesh = new THREE.Mesh(geometry, material); mesh.castShadow = true; mesh.receiveShadow = true; @@ -50,6 +53,7 @@ export const shapeBuilder: Builder = { localBounds: () => local.clone(), update(next, keys) { if (keys.has('color') || keys.has('material')) paint(material, next); + if (keys.has('material')) binder.apply(next.material); if (keys.has('shape') && (next.shape ?? 'cube') !== key) { key = next.shape ?? 'cube'; const old = geometry; @@ -65,6 +69,7 @@ export const shapeBuilder: Builder = { built.tick = undefined; mesh.removeFromParent(); geometry.dispose(); + binder.dispose(); material.dispose(); }), }; diff --git a/frontend/src/ui/scene/output/controller.ts b/frontend/src/ui/scene/output/controller.ts index 7a5b2ac..9c0a1f5 100644 --- a/frontend/src/ui/scene/output/controller.ts +++ b/frontend/src/ui/scene/output/controller.ts @@ -1,8 +1,11 @@ import { SCENE_FPS } from '../../../engine/scene/types'; +import { localJobs } from '../../../engine/local-jobs'; import { studios } from '../../../engine/studios'; import { ApiError } from '../../../io/api'; import { t } from '../../i18n'; import type { SceneContext } from '../context'; +import { announceOutput } from '../../projects/outputs'; +import { driverOf } from '../timeline/driver'; import { registerOnce, sceneCommand } from '../view/commands'; import { captureStill } from './capture'; import { Controls } from './controls'; @@ -12,7 +15,10 @@ import { recordVideo, type RecordPlan } from './record'; import { Review } from './review'; import { announce, saveArtifact, saveFailure } from './save'; import { findSupport, unavailableReason, usable, windowCodec, type Support } from './support'; -import { Cancelled, isCancel, type Artifact, type EncodePath, type OutputKind, type Phase, type Run } from './types'; +import { Cancelled, guard, isCancel, type Artifact, type EncodePath, type OutputKind, type Phase, type Run } from './types'; + +const STOP_GRACE_MS = 1500; +const SAVE_MS = 120000; export interface OutputApi { capture(): Promise; @@ -31,6 +37,7 @@ export class OutputController implements OutputApi { private starting = false; private support: Support | null = null; private ticket = 0; + private uploading = false; constructor(private readonly ctx: SceneContext) { this.controls = new Controls(ctx.slots['top-centre'], { capture: () => void this.capture(), record: () => void this.record() }); @@ -87,7 +94,7 @@ export class OutputController implements OutputApi { const ticket = ++this.ticket; const known = this.support; const engine = fetchEngine || !known ? await engineEncodes() : known.engine; - const win = await windowCodec(w, h, SCENE_FPS); + const win = await windowCodec(w, h, this.ctx.editor.fps || SCENE_FPS); if (ticket !== this.ticket) return; this.support = { window: win, engine }; this.paint(); @@ -111,16 +118,21 @@ export class OutputController implements OutputApi { try { const { view } = this.ctx; const [w, h] = view.videoSize(); - const support = await findSupport(w, h, SCENE_FPS); + const fps = this.ctx.editor.fps || SCENE_FPS; + const support = await findSupport(w, h, fps); this.support = support; this.paint(); if (!usable(support)) { this.ctx.toast(unavailableReason(support), 'warning', { key: 'scene-output-no-encoder' }); } else { const paths: EncodePath[] = []; - if (support.window) paths.push('window'); if (support.engine) paths.push('engine'); - plan = { paths, codec: support.window }; + if (support.window) paths.push('window'); + const passes = this.controls.withPasses; + if (passes && !support.engine) { + this.ctx.toast(t('Depth and mask videos need the engine video encoder, which is not available, so only the main video is recorded.'), 'warning', { key: 'scene-output-passes' }); + } + plan = { paths, codec: support.window, fps, passes }; } } finally { this.starting = false; @@ -132,11 +144,17 @@ export class OutputController implements OutputApi { cancel(): void { const abort = this.abort; - if (!abort || abort.signal.aborted || this.phase === 'saving') return; + if (!abort || abort.signal.aborted || (this.phase === 'saving' && (this.current !== 'video' || this.uploading))) return; abort.abort(); this.show('stopping'); } + private stopWithin(signal: AbortSignal): Promise { + return new Promise((_, reject) => { + signal.addEventListener('abort', () => window.setTimeout(() => reject(new Cancelled()), STOP_GRACE_MS), { once: true }); + }); + } + private show(phase: Phase, done?: number, total?: number): void { this.phase = phase; this.cover.show(phase, done, total); @@ -150,27 +168,34 @@ export class OutputController implements OutputApi { this.abort = abort; this.current = kind; this.phase = null; + const local = kind === 'video' ? localJobs.start('scene.record', t('Scene recording'), () => this.cancel()) : null; const run: Run = { kind, signal: abort.signal, phase: (phase, done, total) => { if (abort.signal.aborted && phase !== 'stopping') return; this.show(phase, done, total); + if (typeof done === 'number' && typeof total === 'number' && total > 0) local?.progress(done / total); }, }; editor.setBusy(true); - this.cover.begin(immediate); + this.cover.begin(immediate, kind === 'video'); this.cover.show(kind === 'video' ? 'recording' : 'capturing'); this.paint(); let artifact: Artifact | null = null; let failure: string | null = null; + const playhead = editor.playhead; try { - artifact = await work(run); + const working = work(run); + working.catch(() => undefined); + artifact = await Promise.race([working, this.stopWithin(abort.signal)]); if (abort.signal.aborted) throw new Cancelled(); - if (artifact.kind === 'still') { + if (artifact.kind === 'still' || !artifact.media) { + this.uploading = true; + this.cover.stopsWhileSaving(false); run.phase('saving'); try { - await saveArtifact(ctx, artifact); + await guard(saveArtifact(ctx, artifact), null, SAVE_MS, t('The library did not take the file in time.')); } catch (err) { failure = saveFailure(err); console.error('[scene] save', err); @@ -184,9 +209,22 @@ export class OutputController implements OutputApi { artifact = null; if (!isCancel(err)) { console.error('[scene] output', err); - ctx.toast(this.failureText(kind, err), 'error', { key: 'scene-output-failed' }); + const again = kind === 'video' ? () => void this.record() : () => void this.capture(); + ctx.toast(this.failureText(kind, err), 'error', { key: 'scene-output-failed', actions: [{ label: t('Retry'), run: again }] }); + } else if (kind === 'video') { + ctx.toast(t('Recording stopped. No video was saved and the scene is as it was.'), 'info', { key: 'scene-output-failed' }); } } finally { + this.uploading = false; + if (view.outputActive) { + view.endOutput(); + try { + driverOf(ctx)?.applyAt(playhead); + } catch (err) { + console.error('[scene] restoring the playhead pose', err); + } + view.requestRender(); + } editor.setBusy(false); this.current = null; this.abort = null; @@ -195,6 +233,11 @@ export class OutputController implements OutputApi { this.paint(); ctx.commands.refresh(); } + if (local) { + if (artifact && !failure) local.done(artifact.media ? [artifact.media.id] : []); + else if (artifact || !abort.signal.aborted) local.fail(failure ?? t('The recording stopped before it finished.')); + else local.cancelled(); + } if (artifact) this.present(artifact, failure); } @@ -205,11 +248,17 @@ export class OutputController implements OutputApi { } private present(artifact: Artifact, failure: string | null): void { + const announced = artifact.kind === 'video' && artifact.media !== null; + if (announced && artifact.media) { + const ids = [artifact.media.id, artifact.depth?.media?.id, artifact.mask?.media?.id].filter((id): id is string => !!id); + announceOutput(ids, t('Your recording is ready.'), 'scene-output-ready'); + } if (studios.activeRoot === 'scene') { this.review.show(artifact, failure, true); return; } this.review.show(artifact, failure, false); + if (announced) return; this.ctx.toast(artifact.kind === 'video' ? t('Your recording is ready.') : t('Your capture is ready.'), 'success', { key: 'scene-output-ready', actions: [{ label: t('Review'), run: () => void studios.activate('scene') }], diff --git a/frontend/src/ui/scene/output/controls.ts b/frontend/src/ui/scene/output/controls.ts index 363e5c3..931b6ba 100644 --- a/frontend/src/ui/scene/output/controls.ts +++ b/frontend/src/ui/scene/output/controls.ts @@ -57,7 +57,7 @@ export class Controls { this.recordKey = q(this.record, 'kbd'); this.passes = q(this.root, '[data-opt="passes"]'); setAttr(this.passes, 'aria-checked', this.passesOn ? 'true' : 'false'); - setTitle(this.passes, t('With a still, also save a grey depth image and a black and white mask to the library')); + setTitle(this.passes, t('Also save a grey depth pass and a black and white mask to the library: images with a still, videos with a recording')); this.passes.addEventListener('click', () => { this.passesOn = !this.passesOn; setAttr(this.passes, 'aria-checked', this.passesOn ? 'true' : 'false'); diff --git a/frontend/src/ui/scene/output/cover.ts b/frontend/src/ui/scene/output/cover.ts index c6b08d8..b26b3a4 100644 --- a/frontend/src/ui/scene/output/cover.ts +++ b/frontend/src/ui/scene/output/cover.ts @@ -19,6 +19,7 @@ export class Cover { private hideTimer = 0; private shownAt = 0; private wanted = false; + private saveStops = false; private lastText = ''; private lastFocus: HTMLElement | null = null; @@ -47,11 +48,16 @@ export class Cover { setText(this.keyHint, shortcuts.label('scene.cancelOutput')); } + stopsWhileSaving(on: boolean): void { + this.saveStops = on; + } + get visible(): boolean { return !this.root.hidden; } - begin(immediate: boolean): void { + begin(immediate: boolean, saveStops = false): void { + this.saveStops = saveStops; window.clearTimeout(this.hideTimer); this.hideTimer = 0; this.wanted = true; @@ -84,7 +90,7 @@ export class Cover { setAttr(this.track, 'aria-valuenow', String(percent)); setStyleVar(this.fill, '--fc-so-progress', String(percent / 100)); } - const canStop = phase === 'capturing' || phase === 'recording'; + const canStop = phase === 'capturing' || phase === 'recording' || (phase === 'saving' && this.saveStops); const wasHidden = this.cancel.hidden; setHidden(this.cancel, !canStop); if (this.phase !== phase) { diff --git a/frontend/src/ui/scene/output/engine-api.ts b/frontend/src/ui/scene/output/engine-api.ts index 20ca0aa..bf735ce 100644 --- a/frontend/src/ui/scene/output/engine-api.ts +++ b/frontend/src/ui/scene/output/engine-api.ts @@ -4,19 +4,21 @@ const BASE = '/api/scene/encode'; export async function engineEncodes(): Promise { try { - const caps = await request<{ videoEncode?: { engine?: boolean } }>('GET', '/capabilities'); + const caps = await request<{ videoEncode?: { engine?: boolean } }>('GET', '/capabilities', undefined, { signal: AbortSignal.timeout(15000) }); return caps.videoEncode?.engine === true; } catch { return false; } } -export const openEncode = (width: number, height: number, fps: number, frames: number, name: string): Promise<{ id: string }> => - request('POST', '/scene/encode', { width, height, fps, frames, name }); +export const openEncode = (width: number, height: number, fps: number, frames: number, name: string, signal?: AbortSignal): Promise<{ id: string }> => + request('POST', '/scene/encode', { width, height, fps, frames, name }, { signal }); -export const finishEncode = (id: string): Promise => request('POST', `/scene/encode/${encodeURIComponent(id)}/finish`); +export const finishEncode = (id: string, signal?: AbortSignal): Promise => + request('POST', `/scene/encode/${encodeURIComponent(id)}/finish`, undefined, { signal }); -export const cancelEncode = (id: string): Promise<{ cancelled: boolean }> => request('DELETE', `/scene/encode/${encodeURIComponent(id)}`); +export const cancelEncode = (id: string, signal?: AbortSignal): Promise<{ cancelled: boolean }> => + request('DELETE', `/scene/encode/${encodeURIComponent(id)}`, undefined, { signal }); export async function putFrames(id: string, body: Uint8Array, signal: AbortSignal): Promise { let res: Response; diff --git a/frontend/src/ui/scene/output/engine-sink.ts b/frontend/src/ui/scene/output/engine-sink.ts index d2fdb7b..04cd3a8 100644 --- a/frontend/src/ui/scene/output/engine-sink.ts +++ b/frontend/src/ui/scene/output/engine-sink.ts @@ -1,5 +1,6 @@ +import { t } from '../../i18n'; import { cancelEncode, finishEncode, openEncode, putFrames } from './engine-api'; -import type { FrameSink } from './types'; +import { guard, type FrameSink } from './types'; const CHUNK_BYTES = 8 * 1024 * 1024; @@ -11,20 +12,36 @@ export interface EngineSinkOptions { readonly name: string; } +const OPEN_MS = 20000; +const SEND_MS = 30000; +const FINISH_MS = 330000; +const CANCEL_MS = 1500; + export async function openEngineSink(o: EngineSinkOptions, signal: AbortSignal): Promise { - const { id } = await openEncode(o.width, o.height, o.fps, o.frames, o.name); + const own = new AbortController(); + const drop = (): void => own.abort(); + signal.addEventListener('abort', drop, { once: true }); + let id: string; + try { + ({ id } = await guard(openEncode(o.width, o.height, o.fps, o.frames, o.name, own.signal), signal, OPEN_MS, t('The engine did not start the video encoder in time.'))); + } catch (err) { + own.abort(); + signal.removeEventListener('abort', drop); + throw err; + } const frameBytes = o.width * o.height * 4; const perChunk = Math.max(1, Math.floor(CHUNK_BYTES / frameBytes)); let chunk = new Uint8Array(frameBytes * perChunk); let held = 0; let acked = 0; let flight: Promise | null = null; + const late = t('The engine stopped taking frames. It may be busy or the encoder may have stopped.'); const flush = async (): Promise => { if (held === 0) return; - if (flight) await flight; + if (flight) await guard(flight, signal, SEND_MS, late); const body = held === perChunk ? chunk : chunk.slice(0, held * frameBytes); - const sent = putFrames(id, body, signal).then((received) => { + const sent = putFrames(id, body, own.signal).then((received) => { acked = received; }); sent.catch(() => undefined); @@ -43,12 +60,16 @@ export async function openEngineSink(o: EngineSinkOptions, signal: AbortSignal): }, async finish() { await flush(); - if (flight) await flight; - return { blob: null, media: await finishEncode(id) }; + if (flight) await guard(flight, signal, SEND_MS, late); + const media = await guard(finishEncode(id, own.signal), signal, FINISH_MS, t('The engine did not finish the video in time.')); + signal.removeEventListener('abort', drop); + return { blob: null, media }; }, async abort() { + own.abort(); + signal.removeEventListener('abort', drop); try { - await cancelEncode(id); + await cancelEncode(id, AbortSignal.timeout(CANCEL_MS)); } catch (err) { console.error('[scene] encode session cancel', err); } diff --git a/frontend/src/ui/scene/output/record.ts b/frontend/src/ui/scene/output/record.ts index e663bc7..64c6663 100644 --- a/frontend/src/ui/scene/output/record.ts +++ b/frontend/src/ui/scene/output/record.ts @@ -1,14 +1,18 @@ import { SCENE_FPS } from '../../../engine/scene/types'; +import { t } from '../../i18n'; import type { SceneContext } from '../context'; import { applyTime } from '../timeline/driver'; +import type { OutputSession } from '../view/output'; import { openEngineSink } from './engine-sink'; import { reserveName } from './names'; -import { checkRun, isCancel, type Artifact, type EncodePath, type Finished, type FrameSink, type Run } from './types'; +import { checkRun, guard, isCancel, type Artifact, type DepthArtifact, type EncodePath, type Finished, type FrameSink, type Run } from './types'; import { openWindowSink } from './window-sink'; export interface RecordPlan { readonly paths: readonly EncodePath[]; readonly codec: string | null; + readonly fps: number; + readonly passes: boolean; } interface Pass { @@ -17,53 +21,100 @@ interface Pass { readonly fps: number; readonly frames: number; readonly name: string; + readonly passes: boolean; +} + +interface Done { + readonly main: Finished; + readonly depth: Finished | null; + readonly mask: Finished | null; } -async function pass(ctx: SceneContext, run: Run, path: EncodePath, codec: string | null, o: Pass): Promise { +const POSE_MS = 45000; +const RENDER_MS = 20000; + +const passName = (name: string, kind: 'depth' | 'mask'): string => name.replace(/\.mp4$/i, '') + `-${kind}.mp4`; + +async function pass(ctx: SceneContext, run: Run, path: EncodePath, codec: string | null, o: Pass): Promise { const { view } = ctx; let sink: FrameSink | null = null; + let depth: FrameSink | null = null; + let mask: FrameSink | null = null; + let session: OutputSession | null = null; try { if (path === 'window') { if (!codec) throw new Error('No H.264 profile fits this size.'); - sink = await openWindowSink({ width: o.width, height: o.height, fps: o.fps, codec }); + sink = await openWindowSink({ width: o.width, height: o.height, fps: o.fps, codec }, run.signal); } else { sink = await openEngineSink(o, run.signal); + if (o.passes) { + depth = await openEngineSink({ ...o, name: passName(o.name, 'depth') }, run.signal); + mask = await openEngineSink({ ...o, name: passName(o.name, 'mask') }, run.signal); + } } - view.beginOutput(o.width, o.height); + checkRun(run); + session = view.beginOutput(o.width, o.height); run.phase('recording', 0, o.frames); for (let n = 0; n < o.frames; n++) { checkRun(run); - await applyTime(ctx, n / o.fps); - const frame = await view.renderFrame(); + const at = (n / o.fps).toFixed(2); + await guard(applyTime(ctx, n / o.fps), run.signal, POSE_MS, t('The scene did not finish posing for the frame at {time} s.').replace('{time}', at)); + const frame = await guard(view.renderFrame(), run.signal, RENDER_MS, t('The frame at {time} s did not finish drawing.').replace('{time}', at)); checkRun(run); - const durable = await sink.add(frame.rgba, n); + let durable = await sink.add(frame.rgba, n); + if (depth && mask) { + const extra = await session.passFrames(); + checkRun(run); + durable = Math.min(durable, await depth.add(extra.depth, n), await mask.add(extra.mask, n)); + } run.phase('recording', durable, o.frames); } checkRun(run); if (path === 'engine') run.phase('saving'); - return await sink.finish(); + const main = await sink.finish(); + sink = null; + let depthDone: Finished | null = null; + let maskDone: Finished | null = null; + if (depth && mask) { + const [d, m] = [depth, mask]; + depth = null; + mask = null; + try { + depthDone = await d.finish(); + maskDone = await m.finish(); + } catch (err) { + if (isCancel(err) || run.signal.aborted) throw err; + console.error('[scene] depth and mask videos', err); + await Promise.all([d.abort(), m.abort()]); + ctx.toast(t('The depth and mask videos could not be made. The main video was saved.'), 'warning', { key: 'scene-output-passes' }); + } + } + return { main, depth: depthDone, mask: maskDone }; } catch (err) { - if (sink) await sink.abort(); + await Promise.all([sink?.abort(), depth?.abort(), mask?.abort()]); throw err; } finally { - view.endOutput(); + session?.end(); } } export async function recordVideo(ctx: SceneContext, run: Run, plan: RecordPlan): Promise { const { view, editor } = ctx; const [width, height] = view.videoSize(); - const fps = SCENE_FPS; + const fps = plan.fps || SCENE_FPS; const frames = Math.max(1, Math.round(editor.duration * fps)); const name = reserveName('mp4'); const playhead = editor.playhead; - const job: Pass = { width, height, fps, frames, name: name.name }; + const job: Pass = { width, height, fps, frames, name: name.name, passes: plan.passes }; + const extra = (done: Finished | null, kind: 'depth' | 'mask'): DepthArtifact | null => + done?.media ? { name: passName(name.name, kind), blob: null, media: done.media } : null; try { let failure: unknown = new Error('Recording is not available here.'); for (const path of plan.paths) { try { const done = await pass(ctx, run, path, plan.codec, job); - return { kind: 'video', name: name.name, width, height, fps, frames, via: path, blob: done.blob, depth: null, mask: null, media: done.media, commit: name.commit }; + const { main } = done; + return { kind: 'video', name: name.name, width, height, fps, frames, via: path, blob: main.blob, depth: extra(done.depth, 'depth'), mask: extra(done.mask, 'mask'), media: main.media, commit: name.commit }; } catch (err) { if (isCancel(err) || run.signal.aborted) throw err; console.error('[scene] recording path failed', path, err); @@ -73,7 +124,7 @@ export async function recordVideo(ctx: SceneContext, run: Run, plan: RecordPlan) throw failure; } finally { try { - await applyTime(ctx, playhead); + await guard(applyTime(ctx, playhead), null, 5000, 'The playhead pose did not come back in time.'); } catch (err) { console.error('[scene] restoring the playhead pose', err); } diff --git a/frontend/src/ui/scene/output/review.ts b/frontend/src/ui/scene/output/review.ts index 9ff96b6..661da4a 100644 --- a/frontend/src/ui/scene/output/review.ts +++ b/frontend/src/ui/scene/output/review.ts @@ -1,4 +1,6 @@ -import { mediaFileUrl, type Media } from '../../../io/api'; +import { capabilities, mediaFileUrl, type Media } from '../../../io/api'; +import { inDesktop, invokeHost } from '../../prefs'; +import { joinPath } from '../../save-media'; import { Dialog, confirmAction } from '../../dialogs'; import { setAttr, setDisabled, setHidden, setHtml, setStyleVar, setText, el, q } from '../../dom'; import { icon } from '../../icons'; @@ -51,6 +53,7 @@ export class Review { private makeImage!: HTMLButtonElement; private makeVideo!: HTMLButtonElement; private open!: HTMLButtonElement; + private folder!: HTMLButtonElement; constructor(private readonly ctx: SceneContext) {} @@ -113,6 +116,7 @@ export class Review { this.makeImage = dlg.button('Make image', 'ghost', () => this.hand(makeImageFrom)); this.makeVideo = dlg.button('Make video', 'ghost', () => this.hand(makeVideoFrom)); this.open = dlg.button('Open', 'ghost', () => this.openItem()); + this.folder = dlg.button('Show in folder', 'ghost', () => void this.showFolder()); dlg.gate = () => this.mayClose(); dlg.onClose = () => { if (this.suspending || this.releasing) return; @@ -182,13 +186,19 @@ export class Review { ].filter((x) => x.item !== null); setStyleVar(this.passes, '--fc-so-ratio', String(a.width / a.height)); const tiles = found.map((x) => { - const url = URL.createObjectURL(x.item!.blob); - this.passUrls.push(url); + const item = x.item!; + const moving = a.kind === 'video'; + let url = item.media ? mediaFileUrl(item.media.id) : ''; + if (item.blob) { + url = URL.createObjectURL(item.blob); + this.passUrls.push(url); + } + const shot = moving ? `` : `${t(x.label)}`; const tile = el( - `
            ${t(x.label)}` + + `
            ${shot}` + `
            ${t(x.label)}
            `, ); - (q(tile, 'img') as HTMLImageElement).src = url; + (q(tile, moving ? 'video' : 'img') as HTMLImageElement | HTMLVideoElement).src = url; return tile; }); this.passes.replaceChildren(...tiles); @@ -232,6 +242,7 @@ export class Review { setHidden(this.makeImage, !(saved && !video)); setHidden(this.makeVideo, !saved); setHidden(this.open, !saved); + setHidden(this.folder, !(saved && inDesktop())); let key = 'idle'; let text = ''; if (saved) { @@ -290,6 +301,24 @@ export class Review { openInLightbox(media); } + private async showFolder(): Promise { + const media = this.artifact?.media; + if (!media || !inDesktop()) return; + try { + const caps = await capabilities(); + const dir = joinPath(joinPath(caps.dataDir, 'library'), media.id.slice(0, 2)); + const dot = media.name.lastIndexOf('.'); + const ext = dot > 0 ? media.name.slice(dot + 1).toLowerCase() : media.kind === 'video' ? 'mp4' : 'png'; + try { + await invokeHost('reveal_path', { path: joinPath(dir, `${media.id}.${ext}`) }); + } catch { + await invokeHost('reveal_path', { path: dir }); + } + } catch (err) { + toast(typeof err === 'string' ? err : t('The folder could not be shown.'), 'error', { key: 'scene-output-reveal' }); + } + } + private drop(): void { if (this.state === 'saving') return; this.release(); diff --git a/frontend/src/ui/scene/output/save.ts b/frontend/src/ui/scene/output/save.ts index 7b7d6fd..829352a 100644 --- a/frontend/src/ui/scene/output/save.ts +++ b/frontend/src/ui/scene/output/save.ts @@ -30,7 +30,7 @@ export function announce(ctx: SceneContext, media: Media): void { async function saveExtras(ctx: SceneContext, artifact: Artifact): Promise { let failed = false; for (const extra of [artifact.depth, artifact.mask]) { - if (!extra || extra.media) continue; + if (!extra || extra.media || !extra.blob) continue; try { extra.media = await upload(extra.blob, extra.name); } catch (err) { diff --git a/frontend/src/ui/scene/output/support.ts b/frontend/src/ui/scene/output/support.ts index a0a87ad..ea6b4db 100644 --- a/frontend/src/ui/scene/output/support.ts +++ b/frontend/src/ui/scene/output/support.ts @@ -1,5 +1,8 @@ import { t } from '../../i18n'; import { engineEncodes } from './engine-api'; +import { guard } from './types'; + +const PROBE_MS = 5000; export interface Support { readonly window: string | null; @@ -33,7 +36,7 @@ async function probe(width: number, height: number, fps: number): Promise(work: Promise, signal: AbortSignal | null, ms: number, stalled: string): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + work.catch(() => undefined); + reject(new Cancelled()); + return; + } + const stop = (): void => { + window.clearTimeout(timer); + reject(new Cancelled()); + }; + const timer = window.setTimeout(() => { + signal?.removeEventListener('abort', stop); + reject(new Stalled(stalled)); + }, ms); + signal?.addEventListener('abort', stop, { once: true }); + work.then( + (value) => { + window.clearTimeout(timer); + signal?.removeEventListener('abort', stop); + resolve(value); + }, + (err: unknown) => { + window.clearTimeout(timer); + signal?.removeEventListener('abort', stop); + reject(err); + }, + ); + }); +} diff --git a/frontend/src/ui/scene/output/window-sink.ts b/frontend/src/ui/scene/output/window-sink.ts index 04a1862..e8f49e4 100644 --- a/frontend/src/ui/scene/output/window-sink.ts +++ b/frontend/src/ui/scene/output/window-sink.ts @@ -1,4 +1,5 @@ -import type { FrameSink } from './types'; +import { t } from '../../i18n'; +import { guard, type FrameSink } from './types'; export interface WindowSinkOptions { readonly width: number; @@ -7,13 +8,18 @@ export interface WindowSinkOptions { readonly codec: string; } -export async function openWindowSink(o: WindowSinkOptions): Promise { - const mb = await import('mediabunny'); +const START_MS = 15000; +const FRAME_MS = 12000; +const FINISH_MS = 60000; +const CANCEL_MS = 1500; + +export async function openWindowSink(o: WindowSinkOptions, signal: AbortSignal): Promise { + const mb = await guard(import('mediabunny'), signal, START_MS, t('The video encoder in this window did not load.')); const target = new mb.BufferTarget(); const output = new mb.Output({ format: new mb.Mp4OutputFormat({ fastStart: 'in-memory' }), target }); const source = new mb.VideoSampleSource({ codec: 'avc', fullCodecString: o.codec, quality: mb.QUALITY_VERY_HIGH, latencyMode: 'quality' }); output.addVideoTrack(source, { frameRate: o.fps }); - await output.start(); + await guard(output.start(), signal, START_MS, t('The video encoder in this window did not start.')); let added = 0; return { path: 'window', @@ -26,7 +32,7 @@ export async function openWindowSink(o: WindowSinkOptions): Promise { duration: 1 / o.fps, }); try { - await source.add(sample); + await guard(source.add(sample), signal, FRAME_MS, t('The video encoder in this window stopped answering.')); } finally { sample.close(); } @@ -34,14 +40,14 @@ export async function openWindowSink(o: WindowSinkOptions): Promise { return added; }, async finish() { - await output.finalize(); + await guard(output.finalize(), signal, FINISH_MS, t('The video encoder in this window did not finish the file.')); const buffer = target.buffer; - if (!buffer) throw new Error('The encoder produced no file.'); + if (!buffer) throw new Error(t('The encoder produced no file.')); return { blob: new Blob([buffer], { type: 'video/mp4' }), media: null }; }, async abort() { try { - await output.cancel(); + await guard(output.cancel(), null, CANCEL_MS, 'cancel'); } catch (err) { console.error('[scene] encoder cancel', err); } diff --git a/frontend/src/ui/scene/panels/column.ts b/frontend/src/ui/scene/panels/column.ts deleted file mode 100644 index 43386b5..0000000 --- a/frontend/src/ui/scene/panels/column.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { setStyleVar } from '../../dom'; -import { rootZoom } from '../../viewers/stage'; -import type { SceneContext } from '../context'; -import { onTimelineBox, timelineBox } from '../timeline'; - -const GAP = 8; -const FLOOR = 120; - -export function mountColumn(ctx: SceneContext): void { - const { slots, host, editor } = ctx; - const column = slots['bottom-right']; - const top = slots['top-right'].parentElement; - let lift = -1; - let room = -1; - let frame = 0; - - const measure = (): void => { - frame = 0; - const z = rootZoom(); - const area = host.getBoundingClientRect(); - if (area.width < 1 || area.height < 1) return; - const mine = column.getBoundingClientRect(); - const pad = parseFloat(getComputedStyle(column).bottom) || 0; - const bar = timelineBox(); - let up = 0; - if (editor.timelineOpen && bar && bar.height > 0 && mine.width > 0 && mine.height > 0 && bar.left < mine.right - 1 && bar.right > mine.left + 1) { - up = Math.max(0, Math.ceil((area.bottom - bar.top) / z + GAP - pad)); - } - const edge = top ? top.getBoundingClientRect().bottom : area.top; - const free = Math.max(FLOOR, Math.floor((area.bottom - edge) / z - GAP - pad - up)); - if (up === lift && free === room) return; - lift = up; - room = free; - setStyleVar(column, '--sc-br-lift', `${up}px`); - setStyleVar(column, '--sc-br-room', `${free}px`); - column.dispatchEvent(new CustomEvent('fc-sc-column')); - }; - - const schedule = (): void => { - if (!frame) frame = requestAnimationFrame(measure); - }; - - if (typeof ResizeObserver === 'function') { - const watcher = new ResizeObserver(schedule); - for (const node of [host, top, column]) if (node) watcher.observe(node); - } - onTimelineBox(schedule); - editor.on('mode', schedule); - schedule(); -} diff --git a/frontend/src/ui/scene/panels/dock.ts b/frontend/src/ui/scene/panels/dock.ts new file mode 100644 index 0000000..1aa50fe --- /dev/null +++ b/frontend/src/ui/scene/panels/dock.ts @@ -0,0 +1,209 @@ +import '../../../styles/scene-dock.css'; +import { shortcuts } from '../../../engine/shortcuts'; +import { el, setAttr, setClass, setHidden, setStyleVar } from '../../dom'; +import { t } from '../../i18n'; +import { icon } from '../../icons'; +import { rootZoom } from '../../viewers/stage'; +import type { SceneContext } from '../context'; + +type Side = 'left' | 'right'; + +export interface SceneLayout { + left: number; + right: number; + leftOff: boolean; + rightOff: boolean; + shotSmall: boolean; +} + +const KEY = 'formcraft.layout.scene'; +const STEP = 16; +const LIMITS: Record = { + left: { min: 200, max: 420, base: 260 }, + right: { min: 260, max: 480, base: 300 }, +}; +const FOLD_TEXT: Record = { + left: ['Hide the outliner', 'Show the outliner'], + right: ['Hide the inspector', 'Show the inspector'], +}; +const DEFAULTS: SceneLayout = { left: LIMITS.left.base, right: LIMITS.right.base, leftOff: false, rightOff: false, shotSmall: false }; + +const clampSide = (side: Side, v: number): number => Math.round(Math.min(LIMITS[side].max, Math.max(LIMITS[side].min, v))); + +function load(): SceneLayout { + try { + const raw = JSON.parse(localStorage.getItem(KEY) ?? 'null') as Partial | null; + if (!raw || typeof raw !== 'object') return { ...DEFAULTS }; + return { + left: clampSide('left', typeof raw.left === 'number' ? raw.left : DEFAULTS.left), + right: clampSide('right', typeof raw.right === 'number' ? raw.right : DEFAULTS.right), + leftOff: raw.leftOff === true, + rightOff: raw.rightOff === true, + shotSmall: raw.shotSmall === true, + }; + } catch { + return { ...DEFAULTS }; + } +} + +const state: SceneLayout = load(); +const listeners = new Set<() => void>(); + +function save(): void { + try { + localStorage.setItem(KEY, JSON.stringify(state)); + } catch { + return; + } +} + +export function sceneLayout(): Readonly { + return state; +} + +export function patchLayout(next: Partial): void { + Object.assign(state, next); + save(); + for (const fn of listeners) fn(); +} + +export function onLayout(fn: () => void): () => void { + listeners.add(fn); + return () => void listeners.delete(fn); +} + +function grip(side: Side): HTMLElement { + const label = side === 'left' ? 'Resize the outliner' : 'Resize the inspector'; + return el( + `', + ); +} + +export function mountDock(ctx: SceneContext): void { + const { editor, slots, commands } = ctx; + const root = slots.left.parentElement as HTMLElement; + const grips: Record = { left: grip('left'), right: grip('right') }; + const hint = el( + '

            ' + + `${t('Select an object to see its settings here.')}` + + `

            `, + ); + const hintPick = hint.querySelector('[data-k="pick"]') as HTMLElement; + const hintStart = hint.querySelector('[data-k="start"]') as HTMLElement; + slots['bottom-right'].append(hint); + const inspector = slots['bottom-right'].querySelector('.fc-sp-inspector'); + + const strip = el('
            '); + const media = root.querySelector(':scope > .fc-md'); + slots.bottom.before(strip); + strip.append(slots.bottom); + if (media) strip.append(media); + root.append(grips.left, grips.right); + + const collapsed = (side: Side): boolean => (side === 'left' ? !editor.outlinerOpen : state.rightOff); + + const paint = (): void => { + setStyleVar(root, '--sc-left-w', `${state.left}px`); + setStyleVar(root, '--sc-right-w', `${state.right}px`); + setAttr(root, 'data-sc-mode', editor.mode); + for (const side of ['left', 'right'] as const) { + const off = collapsed(side); + const g = grips[side]; + setAttr(root, `data-${side}`, off ? 'off' : 'on'); + setAttr(g, 'aria-valuenow', String(state[side])); + const fold = g.querySelector('.fc-sc-fold') as HTMLButtonElement; + setHidden(fold.querySelector('[data-k="in"]') as HTMLElement, off); + setHidden(fold.querySelector('[data-k="out"]') as HTMLElement, !off); + const text = t(FOLD_TEXT[side][off ? 1 : 0]); + setAttr(fold, 'aria-label', text); + setAttr(fold, 'title', text); + setAttr(fold, 'aria-expanded', String(!off)); + } + const picked = !!inspector && !inspector.hidden; + setHidden(hint, picked || editor.mode !== 'build'); + const blank = !ctx.store.objects.some((o) => o.kind !== 'camera'); + setHidden(hintPick, blank); + setHidden(hintStart, !blank); + }; + + const fold = (side: Side): void => { + if (side === 'left') { + editor.setOutlinerOpen(!editor.outlinerOpen); + patchLayout({ leftOff: !editor.outlinerOpen }); + } else patchLayout({ rightOff: !state.rightOff }); + }; + + const resize = (side: Side, width: number): void => { + const next = clampSide(side, width); + if (next === state[side]) return; + patchLayout(side === 'left' ? { left: next } : { right: next }); + }; + + for (const side of ['left', 'right'] as const) { + const g = grips[side]; + const button = g.querySelector('.fc-sc-fold') as HTMLButtonElement; + button.addEventListener('click', () => fold(side)); + button.addEventListener('pointerdown', (e) => e.stopPropagation()); + g.addEventListener('dblclick', (e) => { + if (e.target instanceof Element && e.target.closest('.fc-sc-fold')) return; + resize(side, LIMITS[side].base); + }); + g.addEventListener('keydown', (e) => { + if (e.target !== g || collapsed(side)) return; + const sign = side === 'left' ? 1 : -1; + if (e.key === 'ArrowLeft') resize(side, state[side] - STEP * sign); + else if (e.key === 'ArrowRight') resize(side, state[side] + STEP * sign); + else return; + e.preventDefault(); + }); + g.addEventListener('pointerdown', (e) => { + if (e.button !== 0 || collapsed(side)) return; + e.preventDefault(); + g.setPointerCapture(e.pointerId); + setClass(g, 'is-dragging', true); + const move = (ev: PointerEvent): void => { + const box = root.getBoundingClientRect(); + const z = rootZoom(); + resize(side, side === 'left' ? (ev.clientX - box.left) / z : (box.right - ev.clientX) / z); + }; + const end = (): void => { + setClass(g, 'is-dragging', false); + g.removeEventListener('pointermove', move); + g.removeEventListener('pointerup', end); + g.removeEventListener('pointercancel', end); + }; + g.addEventListener('pointermove', move); + g.addEventListener('pointerup', end); + g.addEventListener('pointercancel', end); + }); + } + + if (state.leftOff === editor.outlinerOpen) editor.setOutlinerOpen(!state.leftOff); + editor.on('panels', () => { + if (editor.mode === 'build' && state.leftOff === editor.outlinerOpen) patchLayout({ leftOff: !editor.outlinerOpen }); + else paint(); + }); + editor.on('mode', paint); + ctx.store.on('added', paint); + ctx.store.on('removed', paint); + ctx.store.on('reset', paint); + onLayout(paint); + if (inspector) new MutationObserver(paint).observe(inspector, { attributes: true, attributeFilter: ['hidden'] }); + + const RESET = 'scene.resetLayout'; + if (!shortcuts.has(RESET)) shortcuts.define({ action: RESET, surface: 'scene', keys: [], group: 'View' }); + if (!commands.get(RESET)) { + commands.register({ + id: RESET, + label: () => t('Reset layout'), + group: 'View', + run: () => { + if (!editor.outlinerOpen && editor.mode === 'build') editor.setOutlinerOpen(true); + patchLayout({ ...DEFAULTS }); + }, + }); + } + paint(); +} diff --git a/frontend/src/ui/scene/panels/index.ts b/frontend/src/ui/scene/panels/index.ts index d1da9c2..9e195cb 100644 --- a/frontend/src/ui/scene/panels/index.ts +++ b/frontend/src/ui/scene/panels/index.ts @@ -2,7 +2,7 @@ import '../../../styles/scene-panels.css'; import { shortcuts } from '../../../engine/shortcuts'; import { t } from '../../i18n'; import type { SceneContext } from '../context'; -import { mountColumn } from './column'; +import { mountDock } from './dock'; import { mountInspector, type Inspector } from './inspector'; import { mountOutliner, type Outliner } from './outliner'; @@ -26,6 +26,6 @@ function registerRename(ctx: SceneContext, outliner: Outliner, inspector: Inspec export function mountPanels(ctx: SceneContext): void { const outliner = mountOutliner(ctx); const inspector = mountInspector(ctx); - mountColumn(ctx); + mountDock(ctx); registerRename(ctx, outliner, inspector); } diff --git a/frontend/src/ui/scene/panels/inspector.ts b/frontend/src/ui/scene/panels/inspector.ts index 15f1c91..55292a4 100644 --- a/frontend/src/ui/scene/panels/inspector.ts +++ b/frontend/src/ui/scene/panels/inspector.ts @@ -1,5 +1,6 @@ import { actionOpen, gateFacts } from '../../../engine/scene/actions'; import type { SceneObject, Vec3 } from '../../../engine/scene/types'; +import type { ObjectPatch } from '../../../engine/scene/objects'; import { el, q, setAttr, setClass, setDisabled, setHidden, setValue } from '../../dom'; import { icon } from '../../icons'; import { t } from '../../i18n'; @@ -9,6 +10,7 @@ import { NumInput } from './num-input'; import { toDegrees, toRadians, trimmed } from './numeric'; import { EditRun } from './run'; import { buildSections } from './sections'; +import { environmentSection } from '../materials/section'; const PRECISIONS = [10, 1, 0.1, 0.01, 0.001] as const; const PRECISION_KEY = 'formcraft.scene.precision'; @@ -97,9 +99,15 @@ export function mountInspector(ctx: SceneContext): Inspector { type(v) { const o = current(); if (!o) return; - const next: Vec3 = [...o.transform[g.key]]; - next[i] = g.write(v); - run.preview(o.id, g.run, { transform: { [g.key]: next } }); + const edits: Array<[string, ObjectPatch]> = []; + for (const id of [o.id, ...store.selection.filter((x) => x !== o.id)]) { + const each = store.object(id); + if (!each || (id !== o.id && (each.locked || (g.key === 'scale' && each.kind === 'camera')))) continue; + const next: Vec3 = [...each.transform[g.key]]; + next[i] = g.write(v); + edits.push([id, { transform: { [g.key]: next } }]); + } + run.previewAll(g.run, edits); }, close: () => void run.close(), cancel: () => run.cancel(), @@ -113,6 +121,13 @@ export function mountInspector(ctx: SceneContext): Inspector { } const everyField = Array.from(fields.values()).flat(); + const sceneBox = el(``); + sceneBox.style.order = '2'; + const sceneSection = environmentSection({ ctx, run, object: current, history }); + sceneSection.el.hidden = false; + sceneBox.append(sceneSection.el); + ctx.slots['bottom-right'].append(sceneBox); + const sections = buildSections({ ctx, run, object: current, history }); for (const s of sections) { s.el.hidden = true; @@ -191,7 +206,7 @@ export function mountInspector(ctx: SceneContext): Inspector { color.addEventListener('input', () => { const o = current(); - if (o) run.preview(o.id, 'Change colour', { color: color.value }); + if (o) run.previewAll('Change colour', [o.id, ...store.selection.filter((x) => x !== o.id && !store.object(x)?.locked)].map((id) => [id, { color: color.value }] as const)); }); color.addEventListener('change', () => void run.close()); color.addEventListener('blur', () => void run.close()); @@ -202,6 +217,9 @@ export function mountInspector(ctx: SceneContext): Inspector { const o = current(); const visible = !!o && editor.mode === 'build'; setHidden(root, !visible); + const sceneShown = !o && editor.mode === 'build'; + setHidden(sceneBox, !sceneShown); + if (sceneShown) sceneSection.refresh({} as SceneObject); if (!o || !visible) return; const locked = o.locked; const isCamera = o.kind === 'camera'; diff --git a/frontend/src/ui/scene/panels/outliner.ts b/frontend/src/ui/scene/panels/outliner.ts index 3fd321a..cf3762f 100644 --- a/frontend/src/ui/scene/panels/outliner.ts +++ b/frontend/src/ui/scene/panels/outliner.ts @@ -1,9 +1,8 @@ import type { SceneObject } from '../../../engine/scene/types'; -import { el, patchList, q, setAttr, setHidden, setStyleVar } from '../../dom'; +import { el, patchList, q, setAttr, setHidden, setStyleVar, setText } from '../../dom'; import { icon } from '../../icons'; import { PopupMenu } from '../../menu'; import { t } from '../../i18n'; -import { setInset } from '../chrome/insets'; import type { SceneContext } from '../context'; import { openPresets } from '../presets'; import { RowDrag, type Shown } from './drag'; @@ -12,7 +11,7 @@ import { InlineRename } from './rename'; import { buildItems, createRow, fillRow, type RowFlags, type RowItem, type RowParts } from './rows'; const WATCHED: ReadonlySet = new Set(['name', 'locked', 'visible', 'role', 'skeleton', 'kind', 'asset']); -const MENU_ITEMS = ['scene.duplicate', 'scene.delete', '-', 'scene.group', 'scene.ungroup', '-', 'scene.rename']; +const MENU_ITEMS = ['scene.duplicate', 'scene.delete', '-', 'scene.group', 'scene.ungroup', '-', 'scene.rename', '-', 'scene.displayAsInherit', 'scene.displayAsWire', 'scene.displayAsBounds', 'scene.displayAsNoRender']; const HEIGHT_SHARE = 0.45; const HEIGHT_FLOOR = 160; const HEIGHT_GAP = 64; @@ -27,14 +26,23 @@ function template(): string { `' ); } @@ -49,6 +57,8 @@ export function mountOutliner(ctx: SceneContext): Outliner { const line = q(root, '.fc-sp-drop'); const empty = q(root, '.fc-sp-empty'); const add = q(root, '[data-k="add"]'); + const search = q(root, '.fc-sp-search'); + const count = q(root, '.fc-sp-count'); const collapsed = new Set(); const parts = new WeakMap(); @@ -63,7 +73,7 @@ export function mountOutliner(ctx: SceneContext): Outliner { const rename = new InlineRename(); const flags = (o: Readonly): RowFlags => ({ - selected: store.selected === o.id, + selected: store.selected === o.id || store.selection.includes(o.id), looking: editor.cameraView && store.doc.activeCamera === o.id, active: store.doc.activeCamera === o.id, skinned: !!view.builtFor(o.id)?.skinned, @@ -98,7 +108,21 @@ export function mountOutliner(ctx: SceneContext): Outliner { } stale = false; for (const id of Array.from(collapsed)) if (!store.has(id)) collapsed.delete(id); - items = buildItems(store.objects, collapsed); + const needle = search.value.trim().toLowerCase(); + items = buildItems(store.objects, needle ? new Set() : collapsed); + if (needle) { + const keep = new Set(); + for (const i of items) { + if (!i.obj.name.toLowerCase().includes(needle) && !i.obj.kind.toLowerCase().includes(needle)) continue; + keep.add(i.obj.id); + for (const a of store.ancestors(i.obj.id)) keep.add(a.id); + } + for (const i of items) i.hidden = !keep.has(i.obj.id); + } + const total = store.objects.length; + const visible = items.reduce((n, i) => n + (i.hidden ? 0 : 1), 0); + setText(count, needle ? t('{shown} of {total}').replace('{shown}', String(visible)).replace('{total}', String(total)) : String(total)); + setAttr(count, 'title', t('{n} objects in the scene').replace('{n}', String(total))); alignOrder(list, items.map((i) => i.obj.id)); patchList(list, items, { key: (i) => i.obj.id, @@ -232,6 +256,7 @@ export function mountOutliner(ctx: SceneContext): Outliner { if (!row || !id || target.closest('.fc-sp-rename')) return; const button = target.closest('button[data-act]'); if (button) act(button.dataset.act ?? '', id, button); + else if (e.shiftKey || e.metaKey || e.ctrlKey) store.toggleSelected(id); else store.select(id); }); @@ -272,6 +297,26 @@ export function mountOutliner(ctx: SceneContext): Outliner { q(root, '[data-k="close"]').addEventListener('click', () => editor.setOutlinerOpen(false)); add.addEventListener('click', () => openPresets(ctx)); + q(root, '[data-sp-empty-add]').addEventListener('click', () => openPresets(ctx)); + search.addEventListener('input', () => { + schedule(); + if (store.selected) reveal = store.selected; + }); + search.addEventListener('keydown', (e) => { + if (e.key !== 'Escape' || !search.value) return; + e.stopPropagation(); + search.value = ''; + schedule(); + }); + q(root, '[data-k="fold-all"]').addEventListener('click', () => { + for (const o of store.objects) if (store.objects.some((c) => c.parent === o.id)) collapsed.add(o.id); + schedule(); + }); + q(root, '[data-k="open-all"]').addEventListener('click', () => { + collapsed.clear(); + if (store.selected) reveal = store.selected; + schedule(); + }); const visibility = (): void => { const next = editor.outlinerOpen && editor.mode === 'build'; @@ -286,9 +331,13 @@ export function mountOutliner(ctx: SceneContext): Outliner { }; let before = store.selected; + let beforeAll: readonly string[] = store.selection; store.on('selection', (id) => { const prev = before; before = id; + const all = store.selection; + for (const x of new Set([...beforeAll, ...all])) if (x !== id && x !== prev && store.has(x)) refreshRow(x); + beforeAll = all; if (prev) refreshRow(prev); if (id) { if (expandAround(id)) { @@ -329,12 +378,7 @@ export function mountOutliner(ctx: SceneContext): Outliner { if (h <= 0) return; setStyleVar(root, '--sp-outliner-h', `${Math.round(Math.max(HEIGHT_FLOOR, Math.min(h * HEIGHT_SHARE, h - HEIGHT_GAP)))}px`); }; - const report = (): void => { - const left = root.hidden ? 0 : Math.round(root.getBoundingClientRect().right - ctx.host.getBoundingClientRect().left); - setInset(ctx, 'outliner', { left }); - }; new ResizeObserver(sizeToHost).observe(ctx.host); - new ResizeObserver(report).observe(root); sizeToHost(); visibility(); diff --git a/frontend/src/ui/scene/panels/run.ts b/frontend/src/ui/scene/panels/run.ts index 42d7064..600b8e9 100644 --- a/frontend/src/ui/scene/panels/run.ts +++ b/frontend/src/ui/scene/panels/run.ts @@ -7,6 +7,7 @@ interface Open { id: string; label: string; moved: boolean; + others?: Set; } export class EditRun { @@ -30,12 +31,25 @@ export class EditRun { return store.preview(id, patch); } + previewAll(label: string, entries: ReadonlyArray): void { + if (!entries.length) return; + this.preview(entries[0][0], label, entries[0][1]); + const c = this.current; + for (const [id, patch] of entries.slice(1)) { + this.parts.store.preview(id, patch); + if (c && patch.transform) (c.others ??= new Set()).add(id); + } + } + close(): boolean { const { store, editor } = this.parts; const c = this.current; this.current = null; if (!c || !store.gesturing) return false; - if (c.moved && !editor.playing && store.has(c.id) && store.tl.hasKeys(c.id)) store.tl.autoKey(c.id, editor.playhead); + if (c.moved && !editor.playing) { + if (c.others) store.autoKeyMany([c.id, ...c.others], editor.playhead); + else if (store.has(c.id) && store.tl.hasKeys(c.id)) store.tl.autoKey(c.id, editor.playhead); + } return store.commit(); } diff --git a/frontend/src/ui/scene/panels/sections.ts b/frontend/src/ui/scene/panels/sections.ts index 4e6b697..cb82233 100644 --- a/frontend/src/ui/scene/panels/sections.ts +++ b/frontend/src/ui/scene/panels/sections.ts @@ -1,4 +1,5 @@ import type { ObjectPatch } from '../../../engine/scene/objects'; +import { OBJECT_DISPLAYS, type ObjectDisplay } from '../../../engine/scene/viewport'; import type { ModelRole, ObjectKind, SceneObject } from '../../../engine/scene/types'; import { el, q, setChecked, setClass, setDisabled, setText, setValue } from '../../dom'; import { icon } from '../../icons'; @@ -9,6 +10,7 @@ import { togglePose } from '../pose'; import { NumInput } from './num-input'; import { trimmed } from './numeric'; import type { EditRun } from './run'; +import { environmentSection, materialSection } from '../materials/section'; export interface SectionHost { readonly ctx: SceneContext; @@ -188,6 +190,30 @@ function modelSection(host: SectionHost): Section { }; } +function displaySection(host: SectionHost): Section { + const options = OBJECT_DISPLAYS.map((d) => ``).join(''); + const select = el(``); + const root = el('
            '); + root.append(labelled('Display as', select)); + const vp = host.ctx.editor.viewport; + select.addEventListener('change', () => { + const o = host.object(); + if (o) vp.setObjectDisplay(o.id, select.value as ObjectDisplay); + }); + const paint = (): void => { + const o = host.object(); + if (o && !root.hidden) setValue(select, vp.objectDisplay(o.id)); + }; + vp.on('object', paint); + return { + el: root, + kinds: ['shape', 'water', 'image', 'video', 'model', 'splat', 'group'], + refresh(o) { + setValue(select, vp.objectDisplay(o.id)); + }, + }; +} + export function buildSections(host: SectionHost): Section[] { - return [lightSection(host), planeSection(host), cameraSection(host), modelSection(host)]; + return [lightSection(host), planeSection(host), cameraSection(host), modelSection(host), materialSection(host), displaySection(host), environmentSection(host)]; } diff --git a/frontend/src/ui/scene/presets/menu.ts b/frontend/src/ui/scene/presets/menu.ts index 7cf380c..1fb3916 100644 --- a/frontend/src/ui/scene/presets/menu.ts +++ b/frontend/src/ui/scene/presets/menu.ts @@ -36,6 +36,7 @@ function rowsOf(h: MenuHandlers): Array { { id: 'animations', glyph: 'play', label: 'Animations', run: h.animations }, null, { id: 'library', glyph: 'library', label: 'From library', run: h.library }, + { id: 'starter', glyph: 'spShapes', label: 'From starter library...', run: () => void import('../../library/starter/starter-picker').then((m) => m.starterInto('scene')) }, { id: 'model', glyph: 'cube', label: 'Upload a 3D model', run: () => h.upload('model') }, { id: 'image', glyph: 'image', label: 'Upload an image', run: () => h.upload('image') }, { id: 'world', glyph: 'globe', label: 'Upload a world', run: () => h.upload('splat') }, diff --git a/frontend/src/ui/scene/shot/bar.ts b/frontend/src/ui/scene/shot/bar.ts index 4cb4543..e2c446e 100644 --- a/frontend/src/ui/scene/shot/bar.ts +++ b/frontend/src/ui/scene/shot/bar.ts @@ -4,6 +4,7 @@ import type { Media, WindowModel } from '../../../io/api'; import { optionLabel } from '../../../engine/labels'; import { el, patchList, q, setAttr, setClass, setHidden, setText, setTitle } from '../../dom'; import { onLanguage, relabel, t } from '../../i18n'; +import { confirmAndDelete } from '../../delete-media'; import { icon } from '../../icons'; import { loadPrefs, onPrefs } from '../../prefs'; import { PickPop } from '../../prompt/pick-pop'; @@ -16,7 +17,8 @@ import { importFrame } from '../generate/frame'; import { chooseModel, fitAspect, frameCounts, frameModels, frameSlot } from '../generate/frame-models'; import { SceneHistory } from '../generate/history'; import { ModelPick } from '../generate/model-pick'; -import { needKey, submitFrame } from '../generate/run'; +import { openKeySheet } from '../../prompt/key-sheet'; +import { submitFrame } from '../generate/run'; import { readSaved, writeSaved } from '../generate/saved'; import { alive, characterRefs } from './refs'; import type { ShotFloat } from './strip'; @@ -60,7 +62,11 @@ export class ShotBar { this.saveBtn = q(this.el, '.fc-shot-save'); this.dlBtn = q(this.el, '.fc-shot-dl'); this.go = q(this.el, '.fc-shot-go'); - this.picker = new ModelPick({ modelId: saved.modelId, onChange: (m) => this.onModel(m) }); + this.picker = new ModelPick({ + modelId: saved.modelId, + onChange: (m) => this.onModel(m), + onAddKey: (m) => openKeySheet(q(this.el, '.fc-shot-bar'), m.provider, { onSaved: () => undefined }), + }); this.cam = new CameraPick(ctx); q(this.el, '.fc-shot-slot-model').replaceWith(this.picker.el); q(this.el, '.fc-shot-slot-history').replaceWith(new SceneHistory({ onPick: (entry) => this.fromHistory(entry) }).el); @@ -293,7 +299,7 @@ export class ShotBar { return; } if (!models.configured(model.provider)) { - needKey(model); + openKeySheet(q(this.el, '.fc-shot-bar'), model.provider, { onSaved: () => void this.run() }); return; } const text = this.prompt.value; @@ -337,7 +343,7 @@ export class ShotBar { else toast(t('Frame saved to your library.'), 'success', { key: 'scene-frame-saved', - actions: [{ label: t('Open'), run: () => openLightbox([media], 0, { actions: ['download', 'delete'], onAction: () => undefined }) }], + actions: [{ label: t('Open'), run: () => openLightbox([media], 0, { actions: ['download', 'delete'], onAction: (a, m) => void (a === 'delete' && confirmAndDelete([m.id])) }) }], }); } catch (err) { toast(err instanceof Error && err.message ? err.message : t('The scene frame could not be captured.'), 'error', { key: 'scene-gen-frame' }); diff --git a/frontend/src/ui/scene/shot/index.ts b/frontend/src/ui/scene/shot/index.ts index dc90729..b258ea8 100644 --- a/frontend/src/ui/scene/shot/index.ts +++ b/frontend/src/ui/scene/shot/index.ts @@ -25,7 +25,7 @@ export function mountShot(ctx: SceneContext): void { const float = new ShotFloat(ctx, store, { useReference: (media) => bar?.useReference(media) }); bar = new ShotBar(ctx, store, float); root.append(float.el, bar.el); - ctx.slots.modal.prepend(root); + ctx.slots.modal.before(root); const sync = (): void => setHidden(root, ctx.editor.mode === 'record'); ctx.editor.on('mode', sync); sync(); diff --git a/frontend/src/ui/scene/shot/layout.ts b/frontend/src/ui/scene/shot/layout.ts index 37e00e4..402e694 100644 --- a/frontend/src/ui/scene/shot/layout.ts +++ b/frontend/src/ui/scene/shot/layout.ts @@ -1,87 +1,27 @@ -import { setAttr, setStyleVar } from '../../dom'; -import { rootZoom } from '../../viewers/stage'; +import { el, setAttr, setClass, setHidden } from '../../dom'; +import { t } from '../../i18n'; +import { icon } from '../../icons'; import { setInset } from '../chrome/insets'; import type { SceneContext } from '../context'; -import { onTimelineBox, timelineBox } from '../timeline'; -import { SIDE_RESERVE } from '../view/framing'; - -const MARGIN = 12; -const GAP = 8; -const MIN_WIDTH = 340; -const MAX_WIDTH = 880; -const SETTLE_MS = 320; +import { onLayout, patchLayout, sceneLayout } from '../panels/dock'; export function mountLayout(ctx: SceneContext, root: HTMLElement, bar: HTMLElement): void { - const { view, editor, host } = ctx; - let key = ''; - let inset = -1; - let frame = 0; - let settling = 0; - - const settle = (): void => { - if (root.dataset.settled === '1') return; - window.clearTimeout(settling); - settling = window.setTimeout(() => setAttr(root, 'data-settled', '1'), SETTLE_MS); - }; - - const measure = (force: boolean): void => { - const z = rootZoom(); - const area = host.getBoundingClientRect(); - if (area.width < 1 || area.height < 1) return; - const record = editor.mode === 'record'; - if (record) { - if (inset !== 0) { - inset = 0; - setInset(ctx, 'shot', null); - } - return; - } - const edges = view.rig.insets(); - const tl = timelineBox(); - const open = editor.timelineOpen; - const tlTop = tl && tl.height > 0 ? Math.round(tl.top) : -1; - const panelW = Number.parseFloat(getComputedStyle(root).getPropertyValue('--fc-panel-w')) || 320; - const right = Math.max(edges.right, panelW + MARGIN); - const next = `${Math.round(area.width)}|${Math.round(area.bottom)}|${edges.left}|${right}|${tlTop}|${open}`; - const lift = tl && tl.height > 0 ? Math.max(MARGIN, (area.bottom - tl.top) / z + GAP) : MARGIN; - if (force || next !== key) { - key = next; - settle(); - const from = edges.left > SIDE_RESERVE ? edges.left + GAP : MARGIN; - const to = Math.max(from, area.width / z - (right + GAP)); - const width = Math.min(Math.max(to - from, MIN_WIDTH), MAX_WIDTH, area.width / z - 2 * MARGIN); - const left = from + Math.max(0, (to - from - width) / 2); - setStyleVar(root, '--fc-shot-w', `${Math.round(width)}px`); - setStyleVar(root, '--fc-shot-x', `${Math.round(left)}px`); - setStyleVar(root, '--fc-shot-lift', `${Math.round(lift)}px`); - } - const box = bar.getBoundingClientRect(); - if (box.height < 1) return; - const total = Math.round((area.bottom - box.top) / z + GAP); - const reported = open && tl && tl.height > 0 ? Math.max(0, Math.round((area.bottom - tl.top) / z + GAP)) : 0; - const mine = Math.max(0, total - reported); - if (mine === inset) return; - inset = mine; - setInset(ctx, 'shot', { bottom: mine }); + setInset(ctx, 'shot', null); + const fold = el( + ``, + ); + bar.prepend(fold); + const paint = (): void => { + const small = sceneLayout().shotSmall; + setClass(root, 'is-small', small); + setHidden(fold.querySelector('[data-k="in"]') as HTMLElement, small); + setHidden(fold.querySelector('[data-k="out"]') as HTMLElement, !small); + const text = t(small ? 'Show all shot settings' : 'Fold the shot box to one line'); + setAttr(fold, 'aria-label', text); + setAttr(fold, 'title', text); + setAttr(fold, 'aria-expanded', String(!small)); }; - - const later = (): void => { - if (frame) return; - frame = requestAnimationFrame(() => { - frame = 0; - measure(false); - }); - }; - - if (typeof ResizeObserver === 'function') { - const watcher = new ResizeObserver(later); - watcher.observe(host); - watcher.observe(bar); - } - onTimelineBox(later); - editor.on('mode', later); - editor.on('panels', later); - view.events.on('size', later); - view.onFrame(later); - measure(true); + fold.addEventListener('click', () => patchLayout({ shotSmall: !sceneLayout().shotSmall })); + onLayout(paint); + paint(); } diff --git a/frontend/src/ui/scene/studio.ts b/frontend/src/ui/scene/studio.ts index 76bf77c..9a49837 100644 --- a/frontend/src/ui/scene/studio.ts +++ b/frontend/src/ui/scene/studio.ts @@ -18,6 +18,7 @@ import { mountShot } from './shot'; import { mountTimeline } from './timeline'; import { mountWorld } from './world'; import { mountPack } from './pack'; +import { mountEnvMap } from './materials/env-map'; import { SceneView, registerEditCommands, registerViewCommands } from './view'; import { createStorePort } from './view/store-port'; @@ -28,16 +29,42 @@ function mountParts(ctx: SceneContext): void { mountPresets(ctx); mountWorld(ctx); mountPack(ctx); + mountEnvMap(ctx); mountPose(ctx); mountTimeline(ctx); mountShot(ctx); ctx.commands.refresh(); } +function bindEditorPrefs(store: SceneStore, editor: EditorState): void { + let applying = false; + const apply = (): void => { + const p = store.doc.editorPrefs; + if (!p) return; + applying = true; + editor.viewport.restore(p); + if (typeof p.overlays?.grid === 'boolean') editor.setGrid(p.overlays.grid); + if (typeof p.snapping === 'boolean') editor.setSnapping(p.snapping); + if (p.snap) editor.setSnapSteps(p.snap); + applying = false; + }; + const save = (): void => { + if (applying) return; + const shown = editor.viewport.saved(); + store.setEditorPrefs({ ...shown, overlays: { ...shown.overlays, grid: editor.grid }, snapping: editor.snapping, snap: { ...editor.snapSteps } }); + }; + store.on('reset', apply); + editor.viewport.on('display', save); + editor.on('gizmo', save); + editor.on('grid', save); + apply(); +} + export function startStudio(shell: SceneShell): SceneContext { defineSceneShortcuts(shortcuts); const store = new SceneStore(blankScene()); const editor = new EditorState(store); + bindEditorPrefs(store, editor); const view = new SceneView({ stage: shell.stage, frame: shell.slots.frame, diff --git a/frontend/src/ui/scene/timeline/bar.ts b/frontend/src/ui/scene/timeline/bar.ts index 6fbb18b..a5dd645 100644 --- a/frontend/src/ui/scene/timeline/bar.ts +++ b/frontend/src/ui/scene/timeline/bar.ts @@ -34,6 +34,8 @@ export function createBar(ctx: SceneContext, duration: DurationField, toggle: () let dragging = false; let written = Number.NaN; + playBtn.dataset.tipKeys = 'scene.togglePlay'; + expand.dataset.tipKeys = 'scene.timelineToggle'; playBtn.addEventListener('click', () => editor.togglePlay()); expand.addEventListener('click', toggle); scrub.addEventListener('pointerdown', () => { diff --git a/frontend/src/ui/scene/timeline/index.ts b/frontend/src/ui/scene/timeline/index.ts index e6be3ee..933ab41 100644 --- a/frontend/src/ui/scene/timeline/index.ts +++ b/frontend/src/ui/scene/timeline/index.ts @@ -2,7 +2,6 @@ import '../../../styles/scene-timeline.css'; import { el, setAttr, setHidden, setStyleVar } from '../../dom'; import { setInset } from '../chrome/insets'; import type { SceneContext } from '../context'; -import { SIDE_RESERVE } from '../view/framing'; import { createBar } from './bar'; import { registerTimelineCommands } from './commands'; import { mountDriver } from './driver'; @@ -12,13 +11,6 @@ import { createPanel, type Panel } from './panel'; export { applyTime } from './driver'; export { addClip } from './ops'; -const INSET_GAP = 8; -const MARGIN = 12; -const GAP = 8; -const MIN_WIDTH = 480; -const BAR_WIDTH = 240; -const MAX_WIDTH = 1024; - let active: Panel | null = null; let shown: (() => DOMRect) | null = null; const watchers = new Set<() => void>(); @@ -64,31 +56,14 @@ export function mountTimeline(ctx: SceneContext): void { for (const fn of watchers) fn(); }; - const reportInset = (): void => { - if (!editor.timelineOpen) { - setInset(ctx, 'timeline', null); - return; - } - const host = ctx.host.getBoundingClientRect(); - const box = panel.node.getBoundingClientRect(); - setInset(ctx, 'timeline', { bottom: Math.max(0, Math.round(host.bottom - box.top + INSET_GAP)) }); - }; + const reportInset = (): void => setInset(ctx, 'timeline', null); - let fitted = ''; + let fitted = -1; const fit = (force = false): void => { - const edges = view.rig.insets(); - const open = editor.timelineOpen; - const key = `${edges.left}|${edges.right}|${open}`; - if (!force && key === fitted) return; - fitted = key; - const host = ctx.host.getBoundingClientRect(); - const slot = slots.bottom.getBoundingClientRect(); - const from = edges.left > SIDE_RESERVE ? edges.left + GAP : MARGIN; - const to = Math.max(from, host.width - (edges.right > SIDE_RESERVE ? edges.right + GAP : MARGIN)); - const width = Math.min(Math.max(to - from, open ? MIN_WIDTH : BAR_WIDTH), MAX_WIDTH); - const left = from + Math.max(0, (to - from - width) / 2); - setStyleVar(root, '--tl-w', `${Math.round(width)}px`); - setStyleVar(root, '--tl-x', `${Math.round(left - (slot.left - host.left))}px`); + const width = Math.round(slots.bottom.clientWidth); + if (!force && width === fitted) return; + fitted = width; + setStyleVar(root, '--tl-w', `${Math.max(0, width)}px`); announce(); }; @@ -150,8 +125,7 @@ export function mountTimeline(ctx: SceneContext): void { schedule(); }); view.events.on('gone', schedule); - view.events.on('size', () => fit(true)); - view.onFrame(() => fit()); + new ResizeObserver(() => fit()).observe(slots.bottom); driver.events.on('strip-added', (objectId) => { armed = false; editor.setTimelineOpen(true); diff --git a/frontend/src/ui/scene/timeline/pop.ts b/frontend/src/ui/scene/timeline/pop.ts index 5744f03..8f5f8d5 100644 --- a/frontend/src/ui/scene/timeline/pop.ts +++ b/frontend/src/ui/scene/timeline/pop.ts @@ -1,3 +1,4 @@ +import { placeFloating } from '../../position'; import type { SceneContext } from '../context'; export interface Pop { @@ -24,14 +25,10 @@ export function openPop(ctx: SceneContext, node: HTMLElement, anchor: HTMLElemen host.append(node); const place = (): void => { const hostRect = host.getBoundingClientRect(); - const at = anchor.getBoundingClientRect(); - const w = node.offsetWidth; - const h = node.offsetHeight; - const left = Math.min(Math.max(at.left + at.width / 2 - w / 2, hostRect.left + EDGE), hostRect.right - w - EDGE); - const above = at.top - h - EDGE; - const top = above >= hostRect.top + EDGE ? above : Math.min(at.bottom + EDGE, hostRect.bottom - h - EDGE); - node.style.left = `${Math.round(left - hostRect.left)}px`; - node.style.top = `${Math.round(top - hostRect.top)}px`; + const scale = host.offsetWidth > 0 ? hostRect.width / host.offsetWidth : 1; + const placed = placeFloating(node, anchor.getBoundingClientRect(), { side: 'top', align: 'center', gap: EDGE, scale }); + node.style.left = `${Math.round((placed.left - hostRect.left) / scale)}px`; + node.style.top = `${Math.round((placed.top - hostRect.top) / scale)}px`; node.style.visibility = ''; }; place(); diff --git a/frontend/src/ui/scene/view/commands.ts b/frontend/src/ui/scene/view/commands.ts index 4ca61bd..64dc945 100644 --- a/frontend/src/ui/scene/view/commands.ts +++ b/frontend/src/ui/scene/view/commands.ts @@ -1,5 +1,6 @@ import { commands, type Command } from '../../../engine/commands'; import { actionOpen, gateFacts, sceneAction } from '../../../engine/scene/actions'; +import type { DisplayMode, ObjectDisplay, Overlay, ViewPreset } from '../../../engine/scene/viewport'; import { t } from '../../i18n'; import type { SceneContext } from '../context'; @@ -44,5 +45,51 @@ export function registerViewCommands(parts: CommandParts): () => void { make('scene.grid', () => editor.toggleGrid(), { checked: () => editor.grid }), make('scene.escape', () => editor.escape(store)), make('scene.deselect', () => store.select(null)), + make('scene.selectAll', () => void store.selectAll()), + make('scene.invertSelection', () => void store.invertSelection()), + make('scene.alignCamera', () => void view.alignCameraToView(), { enabled: () => view.running && !view.inCameraView }), + ...registerNavList(parts, make), ]); } + +function registerNavList(parts: CommandParts, make: (id: string, run: () => void, extra?: Extra) => Command): Command[] { + const { store, editor, view } = parts; + const vp = editor.viewport; + const free = { enabled: () => view.running && !view.inCameraView }; + const preset = (id: string, name: ViewPreset): Command => make(id, () => void view.viewPreset(name), free); + const mode = (id: string, m: DisplayMode): Command => make(id, () => void vp.setMode(m), { checked: () => vp.mode === m }); + const overlay = (id: string, o: Overlay): Command => make(id, () => void vp.toggleOverlay(o), { checked: () => vp.overlay(o) }); + const as = (id: string, d: ObjectDisplay): Command => + make(id, () => { + const sel = store.selected; + if (sel) vp.setObjectDisplay(sel, d); + }, { checked: () => !!store.selected && vp.objectDisplay(store.selected) === d }); + return [ + make('scene.frameAll', () => void view.frameAll(), free), + make('scene.viewHome', () => void view.resetView(), free), + preset('scene.viewFront', 'front'), + preset('scene.viewBack', 'back'), + preset('scene.viewLeft', 'left'), + preset('scene.viewRight', 'right'), + preset('scene.viewTop', 'top'), + preset('scene.viewBottom', 'bottom'), + make('scene.viewOrtho', () => void view.toggleOrtho(), { ...free, checked: () => vp.ortho }), + make('scene.navHelp', () => view.nav.toggleHelp()), + make('scene.displayMenu', () => view.nav.toggleDisplay()), + make('scene.displayWireToggle', () => void vp.toggleWire(), { checked: () => vp.mode === 'wire' }), + mode('scene.displaySolid', 'solid'), + mode('scene.displayWire', 'wire'), + mode('scene.displaySolidWire', 'solid-wire'), + mode('scene.displayMaterial', 'material'), + mode('scene.displayBounds', 'bounds'), + overlay('scene.overlayAxes', 'axes'), + overlay('scene.overlayLights', 'lights'), + overlay('scene.overlayCameras', 'cameras'), + overlay('scene.overlayOutline', 'outline'), + overlay('scene.overlayBackface', 'backface'), + as('scene.displayAsInherit', 'inherit'), + as('scene.displayAsWire', 'wire'), + as('scene.displayAsBounds', 'bounds'), + as('scene.displayAsNoRender', 'no-render'), + ]; +} diff --git a/frontend/src/ui/scene/view/display.ts b/frontend/src/ui/scene/view/display.ts new file mode 100644 index 0000000..28a5a9f --- /dev/null +++ b/frontend/src/ui/scene/view/display.ts @@ -0,0 +1,236 @@ +import * as THREE from 'three'; +import type { SceneSource } from '../../../engine/scene/types'; +import type { ObjectDisplay, ViewportState } from '../../../engine/scene/viewport'; +import { CONTENT_LAYER, EDITOR_LAYER } from '../contract'; +import type { ObjectSync } from './objects'; +import type { SceneTheme } from './theme'; + +type Look = 'keep' | 'solid' | 'wire' | 'hide'; + +interface Swap { + mesh: THREE.Mesh; + material: THREE.Material | THREE.Material[]; + visible: boolean; + look: Look; + sides: Array<[THREE.Material, THREE.Side]>; +} + +const AXIS_REACH = 900; +const NO_BOX = new Set(['camera', 'light', 'group']); + +function drawable(mesh: THREE.Mesh): boolean { + if (!mesh.layers.isEnabled(CONTENT_LAYER)) return false; + const m = mesh.material; + const list = Array.isArray(m) ? m : [m]; + return list.length > 0 && list.every((x) => !(x instanceof THREE.ShaderMaterial) && x.visible !== false); +} + +function lineSegments(from: THREE.Vector3, to: THREE.Vector3, color: THREE.Color): THREE.Line { + const geo = new THREE.BufferGeometry().setFromPoints([from, to]); + const line = new THREE.Line(geo, new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.75, depthWrite: false })); + line.layers.set(EDITOR_LAYER); + line.renderOrder = -1; + line.raycast = () => undefined; + return line; +} + +export class Display { + readonly group = new THREE.Group(); + private readonly solid = new THREE.MeshStandardMaterial({ roughness: 0.75, metalness: 0, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1 }); + private readonly wire = new THREE.MeshBasicMaterial({ wireframe: true, side: THREE.DoubleSide }); + private readonly overlay = new THREE.MeshBasicMaterial({ wireframe: true, transparent: true, opacity: 0.55, depthWrite: false, side: THREE.DoubleSide }); + private readonly boxes: THREE.Box3Helper[] = []; + private readonly axes = new THREE.Group(); + private swaps: Swap[] = []; + private helpers: Array<[THREE.Object3D, boolean]> = []; + private wirePassWanted = false; + private boxColor = new THREE.Color(0xffffff); + + constructor(private readonly scene: THREE.Scene, private readonly sync: ObjectSync, private readonly source: SceneSource, private readonly state: ViewportState) { + this.group.name = 'display'; + this.group.visible = false; + this.axes.name = 'axes'; + this.group.add(this.axes); + scene.add(this.group); + } + + setTheme(theme: SceneTheme): void { + this.solid.color.copy(theme.solid); + this.wire.color.copy(theme.wire); + this.overlay.color.copy(theme.solid).multiplyScalar(0.3); + this.boxColor.copy(theme.wire); + for (const b of this.boxes) (b.material as THREE.LineBasicMaterial).color.copy(theme.wire); + for (const child of [...this.axes.children]) { + this.axes.remove(child); + const line = child as THREE.Line; + line.geometry.dispose(); + (line.material as THREE.Material).dispose(); + } + const y = 0.001; + this.axes.add(lineSegments(new THREE.Vector3(-AXIS_REACH, y, 0), new THREE.Vector3(AXIS_REACH, y, 0), theme.axisX)); + this.axes.add(lineSegments(new THREE.Vector3(0, y, -AXIS_REACH), new THREE.Vector3(0, y, AXIS_REACH), theme.axisZ)); + } + + private lookFor(display: ObjectDisplay): Look { + if (display === 'wire') return 'wire'; + if (display === 'bounds') return 'hide'; + const mode = this.state.mode; + if (mode === 'solid' || mode === 'solid-wire') return 'solid'; + if (mode === 'wire') return 'wire'; + if (mode === 'bounds') return 'hide'; + return 'keep'; + } + + begin(grid: boolean): void { + const st = this.state; + const cull = st.overlay('backface'); + this.solid.side = cull ? THREE.FrontSide : THREE.DoubleSide; + this.wire.side = this.solid.side; + this.overlay.side = this.solid.side; + const boxed = new Set(); + const cache = new Map(); + this.sync.content.traverse((node) => { + const mesh = node as THREE.Mesh; + if (!mesh.isMesh || !drawable(mesh)) return; + const id = this.sync.idOf(mesh); + let display: ObjectDisplay = 'inherit'; + if (id) { + const hit = cache.get(id); + display = hit ?? st.objectDisplay(id); + if (!hit) cache.set(id, display); + } + const look = this.lookFor(display); + if (look === 'hide' && id) boxed.add(id); + if (look === 'keep' && !cull) return; + const swap: Swap = { mesh, material: mesh.material, visible: mesh.visible, look, sides: [] }; + if (look === 'keep') { + for (const m of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) { + swap.sides.push([m, m.side]); + m.side = THREE.FrontSide; + } + } else if (look === 'hide') mesh.visible = false; + else mesh.material = look === 'solid' ? this.solid : this.wire; + this.swaps.push(swap); + }); + this.wirePassWanted = st.mode === 'solid-wire' && this.swaps.some((s) => s.look === 'solid' && s.visible); + for (const id of this.sync.ids()) { + const built = this.sync.builtOf(id); + const kind = this.source.object(id)?.kind; + if (!built?.helpers) continue; + const off = (kind === 'light' && !st.overlay('lights')) || (kind === 'camera' && !st.overlay('cameras')); + if (!off) continue; + for (const h of built.helpers) { + this.helpers.push([h, h.visible]); + h.visible = false; + } + } + let used = 0; + for (const id of boxed) { + const obj = this.source.object(id); + if (!obj || !obj.visible || NO_BOX.has(obj.kind)) continue; + const root = this.sync.rootOf(id); + if (!root) continue; + root.updateWorldMatrix(true, true); + const box = this.sync.boundsOf(id); + if (!box) continue; + let helper = this.boxes[used]; + if (!helper) { + helper = new THREE.Box3Helper(new THREE.Box3(), this.boxColor.clone()); + helper.layers.set(EDITOR_LAYER); + helper.raycast = () => undefined; + this.boxes.push(helper); + this.group.add(helper); + } + helper.box.copy(box); + helper.visible = true; + used++; + } + for (let i = used; i < this.boxes.length; i++) this.boxes[i].visible = false; + this.axes.visible = st.overlay('axes') && grid; + this.group.visible = true; + } + + get wantsWirePass(): boolean { + return this.wirePassWanted; + } + + wirePass(renderer: THREE.WebGLRenderer, draw: () => void): void { + const hidden: THREE.Object3D[] = []; + for (const child of this.scene.children) { + if (child !== this.sync.content && child.visible) { + child.visible = false; + hidden.push(child); + } + } + const shown: THREE.Mesh[] = []; + const quiet: THREE.Object3D[] = []; + const solid = new Set(this.swaps.filter((s) => s.look === 'solid' && s.visible).map((s) => s.mesh)); + this.sync.content.traverse((node) => { + if (solid.has(node as THREE.Mesh)) { + (node as THREE.Mesh).material = this.overlay; + shown.push(node as THREE.Mesh); + } else if (((node as THREE.Mesh).isMesh || (node as THREE.Line).isLine || (node as THREE.Points).isPoints || (node as THREE.Sprite).isSprite) && node.visible) { + node.visible = false; + quiet.push(node); + } + }); + const background = this.scene.background; + const auto = renderer.autoClear; + this.scene.background = null; + renderer.autoClear = false; + try { + draw(); + } finally { + renderer.autoClear = auto; + this.scene.background = background; + for (const m of shown) m.material = this.solid; + for (const n of quiet) n.visible = true; + for (const n of hidden) n.visible = true; + } + } + + end(): void { + for (const s of this.swaps) { + s.mesh.material = s.material; + s.mesh.visible = s.visible; + for (const [m, side] of s.sides) m.side = side; + } + this.swaps = []; + for (const [h, v] of this.helpers) h.visible = v; + this.helpers = []; + this.group.visible = false; + this.wirePassWanted = false; + } + + hideForRender(): () => void { + const hidden: THREE.Object3D[] = []; + for (const [id, display] of this.state.objectEntries()) { + if (display !== 'no-render') continue; + const root = this.sync.rootOf(id); + if (root && root.visible) { + root.visible = false; + hidden.push(root); + } + } + return () => { + for (const n of hidden) n.visible = true; + }; + } + + dispose(): void { + this.end(); + this.scene.remove(this.group); + this.solid.dispose(); + this.wire.dispose(); + this.overlay.dispose(); + for (const b of this.boxes) { + b.geometry.dispose(); + (b.material as THREE.Material).dispose(); + } + for (const child of this.axes.children) { + const line = child as THREE.Line; + line.geometry.dispose(); + (line.material as THREE.Material).dispose(); + } + } +} diff --git a/frontend/src/ui/scene/view/environment.ts b/frontend/src/ui/scene/view/environment.ts index 6184975..178bcb1 100644 --- a/frontend/src/ui/scene/view/environment.ts +++ b/frontend/src/ui/scene/view/environment.ts @@ -208,7 +208,7 @@ export class Environment { this.scene.environment = null; this.hemisphere.visible = true; } - this.scene.environmentIntensity = 1; + this.scene.environmentIntensity = typeof this.scene.userData.envIntensity === 'number' ? this.scene.userData.envIntensity : 1; return; } const look = id === 'empty' ? STUDIO : id === 'black' ? null : { ...LOOKS[id as 'day'], glowSize: 0, stars: 0, clouds: 0 }; diff --git a/frontend/src/ui/scene/view/fly.ts b/frontend/src/ui/scene/view/fly.ts index 65503cc..f22c694 100644 --- a/frontend/src/ui/scene/view/fly.ts +++ b/frontend/src/ui/scene/view/fly.ts @@ -146,6 +146,7 @@ export class FlyCamera { yaw = 0; pitch = 0; roll = 0; + speed = 1; private readonly velocity = new THREE.Vector3(); private readonly glide = new THREE.Vector3(); @@ -193,6 +194,10 @@ export class FlyCamera { this.glide.addScaledVector(scratch.set(0, 0, -1).applyQuaternion(this.quaternion), notches * BASE_SPEED * scale); } + push(delta: THREE.Vector3): void { + this.glide.add(delta); + } + get gliding(): boolean { return this.glide.lengthSq() > 1e-8; } @@ -202,7 +207,7 @@ export class FlyCamera { } step(dt: number, keys: Keys, enabled: boolean): boolean { - const mul = (keys.shift ? FAST : 1) * (keys.alt ? SLOW : 1); + const mul = (keys.shift ? FAST : 1) * (keys.alt ? SLOW : 1) * this.speed; const blend = 1 - Math.pow(1 - SMOOTHING, dt * 60); const before = this.moving; let acted = false; diff --git a/frontend/src/ui/scene/view/frame-overlay.ts b/frontend/src/ui/scene/view/frame-overlay.ts index 79c8bdd..d492131 100644 --- a/frontend/src/ui/scene/view/frame-overlay.ts +++ b/frontend/src/ui/scene/view/frame-overlay.ts @@ -12,7 +12,7 @@ export class FrameOverlay { constructor(parent: HTMLElement) { this.root = el( '', + '
            ', ); this.box = this.root.querySelector('.fc-sc-frame-box') as HTMLElement; this.label = this.root.querySelector('.fc-sc-frame-focal') as HTMLElement; diff --git a/frontend/src/ui/scene/view/framing.ts b/frontend/src/ui/scene/view/framing.ts index 076b5f9..f18dc01 100644 --- a/frontend/src/ui/scene/view/framing.ts +++ b/frontend/src/ui/scene/view/framing.ts @@ -14,10 +14,10 @@ export function aspectValue(id: AspectId): number { return w > 0 && h > 0 ? w / h : 16 / 9; } -export function defaultInsets(record: boolean): Insets { - return record - ? { top: 76, right: SIDE_RESERVE, bottom: 152, left: SIDE_RESERVE } - : { top: 124, right: SIDE_RESERVE, bottom: 88, left: SIDE_RESERVE }; +export const FRAME_MARGIN = 16; + +export function defaultInsets(_record: boolean): Insets { + return { top: FRAME_MARGIN, right: FRAME_MARGIN, bottom: FRAME_MARGIN, left: FRAME_MARGIN }; } export function fitFrame(aspect: number, width: number, height: number, insets: Insets): Rect { diff --git a/frontend/src/ui/scene/view/gizmo.ts b/frontend/src/ui/scene/view/gizmo.ts index 6d0e791..ef71512 100644 --- a/frontend/src/ui/scene/view/gizmo.ts +++ b/frontend/src/ui/scene/view/gizmo.ts @@ -1,6 +1,6 @@ import * as THREE from 'three'; import { TransformControls } from 'three/addons/controls/TransformControls.js'; -import type { GizmoMode, GizmoSpace, Transform } from '../../../engine/scene/types'; +import type { GizmoMode, GizmoSpace, SnapSteps, Transform } from '../../../engine/scene/types'; import { t } from '../../i18n'; export interface Gestures { @@ -19,6 +19,7 @@ export interface GizmoDeps { export const GIZMO_SIZE = 0.5; export const SNAP_STEP = 0.01; +export const GRID_CELL = 0.5; const MODES: Record = { move: 'translate', rotate: 'rotate', scale: 'scale' }; const LABELS: Record = { move: 'Move', rotate: 'Rotate', scale: 'Scale' }; @@ -61,12 +62,23 @@ export class Gizmo { private readonly onRedraw = (): void => this.deps.changed(); + private readonly proxy = new THREE.Object3D(); + private many: Array<{ id: string; node: THREE.Object3D; start: THREE.Matrix4 }> | null = null; + private readonly proxyStart = new THREE.Matrix4(); + private readonly onDown = (): void => { const target = this.target; if (!target) return; this.begun = readTransform(target.node); this.moved = false; - this.deps.grab(target.id); + if (this.many) { + this.proxy.updateMatrixWorld(true); + this.proxyStart.copy(this.proxy.matrixWorld).invert(); + for (const m of this.many) { + m.node.updateMatrixWorld(true); + m.start.copy(m.node.matrixWorld); + } + } else this.deps.grab(target.id); this.deps.gestures.begin(t(LABELS[this.mode])); this.deps.dragging(true); }; @@ -75,9 +87,57 @@ export class Gizmo { const target = this.target; if (!target) return; this.moved = true; - this.deps.gestures.preview(target.id, readTransform(target.node)); + if (!this.many) { + this.deps.gestures.preview(target.id, readTransform(target.node)); + return; + } + this.proxy.updateMatrixWorld(true); + const delta = new THREE.Matrix4().multiplyMatrices(this.proxy.matrixWorld, this.proxyStart); + const world = new THREE.Matrix4(); + const parentInv = new THREE.Matrix4(); + const p = new THREE.Vector3(); + const q = new THREE.Quaternion(); + const s = new THREE.Vector3(); + const e = new THREE.Euler(); + for (const m of this.many) { + world.multiplyMatrices(delta, m.start); + if (m.node.parent) { + m.node.parent.updateMatrixWorld(true); + parentInv.copy(m.node.parent.matrixWorld).invert(); + world.premultiply(parentInv); + } + world.decompose(p, q, s); + e.setFromQuaternion(q, m.node.rotation.order); + this.deps.gestures.preview(m.id, { position: [p.x, p.y, p.z], rotation: [e.x, e.y, e.z], scale: [s.x, s.y, s.z] }); + } }; + attachMany(primary: string, entries: ReadonlyArray<{ id: string; node: THREE.Object3D }>, scene: THREE.Object3D): void { + if (this.controls.dragging) return; + const centre = new THREE.Vector3(); + const at = new THREE.Vector3(); + for (const en of entries) { + en.node.updateMatrixWorld(true); + centre.add(en.node.getWorldPosition(at)); + } + centre.divideScalar(Math.max(1, entries.length)); + if (this.proxy.parent !== scene) scene.add(this.proxy); + this.proxy.position.copy(centre); + this.proxy.rotation.set(0, 0, 0); + this.proxy.scale.set(1, 1, 1); + this.many = entries.map((en) => ({ id: en.id, node: en.node, start: new THREE.Matrix4() })); + if (this.target?.node !== this.proxy || this.controls.object !== this.proxy) { + if (this.target) { + this.target = null; + this.controls.detach(); + } + this.target = { id: primary, node: this.proxy }; + this.controls.attach(this.proxy); + } else this.target.id = primary; + this.helper.visible = !this.forced; + this.deps.changed(); + } + private readonly onUp = (): void => { const target = this.target; const begun = this.begun; @@ -105,6 +165,7 @@ export class Gizmo { attach(id: string, node: THREE.Object3D): void { if (this.target?.node === node && this.controls.object === node) return; this.detach(); + this.many = null; this.target = { id, node }; this.controls.attach(node); this.helper.visible = !this.forced; @@ -119,6 +180,7 @@ export class Gizmo { this.deps.dragging(false); this.deps.grab(null); } + this.many = null; if (!this.target) return; this.target = null; this.controls.detach(); @@ -132,10 +194,11 @@ export class Gizmo { this.deps.changed(); } - setSnapping(on: boolean): void { - this.controls.setTranslationSnap(on ? SNAP_STEP : null); - this.controls.setRotationSnap(on ? SNAP_STEP : null); - this.controls.setScaleSnap(on ? SNAP_STEP : null); + setSnapping(on: boolean, steps?: Readonly): void { + const move = steps ? (steps.grid ? GRID_CELL : steps.move) : SNAP_STEP; + this.controls.setTranslationSnap(on ? move : null); + this.controls.setRotationSnap(on ? (steps ? THREE.MathUtils.degToRad(steps.rotate) : SNAP_STEP) : null); + this.controls.setScaleSnap(on ? (steps ? steps.scale : SNAP_STEP) : null); } hide(on: boolean): void { @@ -150,6 +213,7 @@ export class Gizmo { this.controls.removeEventListener('objectChange', this.onChange); this.controls.removeEventListener('change', this.onRedraw); this.helper.parent?.remove(this.helper); + this.proxy.parent?.remove(this.proxy); this.controls.dispose(); } } diff --git a/frontend/src/ui/scene/view/nav.css b/frontend/src/ui/scene/view/nav.css new file mode 100644 index 0000000..748f1da --- /dev/null +++ b/frontend/src/ui/scene/view/nav.css @@ -0,0 +1,42 @@ +.fc-sc-nav { position: absolute; top: var(--fc-sc-nav-top, var(--space-3)); right: var(--fc-sc-nav-right, var(--space-3)); display: flex; flex-direction: column; align-items: flex-end; gap: var(--space-2); width: max-content; pointer-events: none; } +.fc-sc-nav > * { pointer-events: auto; } +.fc-sc-stage:not(.is-ready) .fc-sc-nav { visibility: hidden; } +.fc-sc-axes { display: block; width: 72px; height: 72px; border-radius: var(--radius-pill); background: var(--bg-scrim); overflow: visible; } +.fc-sc-axis-line { stroke-width: 2; stroke-linecap: round; } +.fc-sc-axis-line.is-x, .fc-sc-axis-dot.is-x { stroke: var(--scene-axis-x); } +.fc-sc-axis-line.is-y, .fc-sc-axis-dot.is-y { stroke: var(--scene-axis-y); } +.fc-sc-axis-line.is-z, .fc-sc-axis-dot.is-z { stroke: var(--scene-axis-z); } +.fc-sc-axis-dot { cursor: pointer; stroke-width: 1.5; } +.fc-sc-axis-dot.is-x { fill: var(--scene-axis-x); } +.fc-sc-axis-dot.is-y { fill: var(--scene-axis-y); } +.fc-sc-axis-dot.is-z { fill: var(--scene-axis-z); } +.fc-sc-axis-dot.is-neg { fill: var(--surface-1); fill-opacity: 0.7; } +.fc-sc-axis-dot.is-back { opacity: 0.55; } +.fc-sc-axis-dot:hover { stroke: var(--text-primary); } +.fc-sc-axis-label { fill: var(--surface-0); font-family: var(--font-ui); font-size: var(--fs-9); font-weight: 700; text-anchor: middle; dominant-baseline: central; pointer-events: none; } +.fc-sc-navbar { display: flex; flex-direction: column; gap: var(--space-1); padding: var(--space-1); border-radius: var(--radius); background: var(--bg-scrim); } +.fc-sc-navbtn { display: inline-flex; align-items: center; justify-content: center; width: var(--ctl-sm); height: var(--ctl-sm); padding: 0; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-secondary); font: inherit; font-size: var(--fs-10); cursor: pointer; } +.fc-sc-navbtn.is-text { font-family: var(--font-mono); font-size: var(--fs-9); } +.fc-sc-navbtn:hover, .fc-sc-navbtn[aria-expanded="true"] { background: var(--bg-hover); color: var(--text-primary); } +.fc-sc-navbtn:focus-visible { outline: 1px solid var(--accent-line); outline-offset: 1px; } +.fc-sc-pop { position: absolute; top: 0; right: calc(100% + var(--space-2)); width: 15rem; max-height: var(--fc-sc-nav-room, min(70vh, 32rem)); overflow: auto; padding: var(--space-2); border: 1px solid var(--line-1); border-radius: var(--radius-md); background: var(--surface-raised); box-shadow: var(--shadow-md); color: var(--text-primary); font-size: var(--fs-12); } +.fc-sc-pop.is-help { width: 21rem; } +.fc-sc-pop-head { margin: var(--space-2) var(--space-1) var(--space-1); color: var(--text-muted); font-size: var(--fs-10); text-transform: uppercase; letter-spacing: 0.04em; } +.fc-sc-pop-head:first-child { margin-top: 0; } +.fc-sc-pop-item { display: flex; align-items: center; gap: var(--space-2); width: 100%; min-height: var(--ctl-sm); padding: 0 var(--space-2); border: 0; border-radius: var(--radius-sm); background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; } +.fc-sc-pop-item:hover:not(:disabled), .fc-sc-pop-item:focus-visible { background: var(--bg-hover); outline: none; } +.fc-sc-pop-item:disabled { color: var(--text-muted); cursor: default; } +.fc-sc-pop-tick { display: inline-flex; width: 12px; visibility: hidden; color: var(--accent-color); } +.fc-sc-pop-item[aria-checked="true"] .fc-sc-pop-tick { visibility: visible; } +.fc-sc-help { display: grid; grid-template-columns: max-content 1fr; gap: var(--space-1) var(--space-3); margin: 0 var(--space-1); } +.fc-sc-help dt { color: var(--text-secondary); font-weight: 600; } +.fc-sc-help dd { margin: 0; color: var(--text-primary); line-height: 1.35; } +.fc-sc-pop-row { display: flex; align-items: center; gap: var(--space-2); min-height: var(--ctl-sm); padding: 0 var(--space-1); cursor: pointer; } +.fc-sc-pop-row.is-range { justify-content: space-between; } +.fc-sc-pop-row.is-range input { width: 8rem; accent-color: var(--accent-color); } +.fc-scc-snap { gap: var(--space-1); padding: 0 var(--space-2); } +.fc-scc-snapmore { width: var(--ctl-sm); } +.fc-scc-snap .fc-scc-text { display: inline-block; min-width: 7ch; font-size: var(--fs-11); font-variant-numeric: tabular-nums; white-space: nowrap; } +.fc-sc-marquee { position: absolute; box-sizing: border-box; border: 1px dashed var(--accent-color); background: var(--accent-wash); pointer-events: none; } +.fc-sc-frame-safe { position: absolute; inset: 5%; border: 1px dashed var(--scene-frame-guide); pointer-events: none; } +.fc-sc-frame-safe.is-title { inset: 10%; } diff --git a/frontend/src/ui/scene/view/navui.ts b/frontend/src/ui/scene/view/navui.ts new file mode 100644 index 0000000..64ffbaf --- /dev/null +++ b/frontend/src/ui/scene/view/navui.ts @@ -0,0 +1,276 @@ +import * as THREE from 'three'; +import './nav.css'; +import { commands } from '../../../engine/commands'; +import { shortcuts } from '../../../engine/shortcuts'; +import { DISPLAY_MODES, OBJECT_DISPLAYS, ORBIT_SPEED_MAX, ORBIT_SPEED_MIN, OVERLAYS, type ViewportState } from '../../../engine/scene/viewport'; +import { el } from '../../dom'; +import { t } from '../../i18n'; +import { icon } from '../../icons'; + +const R = 26; +const AXES: ReadonlyArray<{ k: string; v: THREE.Vector3; cmd: string; label: string; cls: string }> = [ + { k: 'x', v: new THREE.Vector3(1, 0, 0), cmd: 'scene.viewRight', label: 'X', cls: 'x' }, + { k: 'y', v: new THREE.Vector3(0, 1, 0), cmd: 'scene.viewTop', label: 'Y', cls: 'y' }, + { k: 'z', v: new THREE.Vector3(0, 0, 1), cmd: 'scene.viewFront', label: 'Z', cls: 'z' }, + { k: '-x', v: new THREE.Vector3(-1, 0, 0), cmd: 'scene.viewLeft', label: '', cls: 'x' }, + { k: '-y', v: new THREE.Vector3(0, -1, 0), cmd: 'scene.viewBottom', label: '', cls: 'y' }, + { k: '-z', v: new THREE.Vector3(0, 0, -1), cmd: 'scene.viewBack', label: '', cls: 'z' }, +]; + +const DISPLAY_CMD: Record = { + solid: 'scene.displaySolid', + wire: 'scene.displayWire', + 'solid-wire': 'scene.displaySolidWire', + material: 'scene.displayMaterial', + bounds: 'scene.displayBounds', +}; + +const OVERLAY_CMD: Record = { + axes: 'scene.overlayAxes', + lights: 'scene.overlayLights', + cameras: 'scene.overlayCameras', + outline: 'scene.overlayOutline', + backface: 'scene.overlayBackface', +}; + +const OBJECT_CMD: Record = { + inherit: 'scene.displayAsInherit', + wire: 'scene.displayAsWire', + bounds: 'scene.displayAsBounds', + 'no-render': 'scene.displayAsNoRender', +}; + +export interface NavDeps { + viewport: ViewportState; + grid(): boolean; + selected(): string | null; + ortho(): boolean; +} + +function keyOf(action: string): string { + return shortcuts.label(action); +} + +function helpRows(mac: boolean): Array<[string, string]> { + return [ + [t('Orbit'), mac ? t('Left drag, Option drag or middle drag') : t('Left drag, Alt drag or middle drag')], + [t('Pan'), t('Shift and middle drag, Space and drag, or two-finger scroll in trackpad mode')], + [t('Zoom'), t('Scroll wheel or pinch, toward the pointer')], + [t('Fly'), t('Hold the right button, then W A S D to move and Q E for down and up; scroll to change speed')], + [t('Frame'), t('F frames the selection, or everything when nothing is selected; double-click an object to focus it')], + [t('Views'), mac ? t('Numpad or 1, 3, 7 for front, right, top; with Command or Option for the opposite side; 5 for orthographic') : t('Numpad or 1, 3, 7 for front, right, top; with Ctrl or Alt for the opposite side; 5 for orthographic')], + [t('Reset'), t('Home puts the view back where it started')], + [t('Display'), t('Z opens the display menu; Shift Z switches wireframe')], + ]; +} + +export class NavUi { + readonly root: HTMLElement; + private readonly svg: SVGSVGElement; + private readonly dots = new Map(); + private readonly displayPop: HTMLElement; + private readonly helpPop: HTMLElement; + private readonly orthoLabel: HTMLElement; + private readonly displayBtn: HTMLButtonElement; + private readonly helpBtn: HTMLButtonElement; + private lastSig = ''; + private readonly offs: Array<() => void> = []; + + constructor(parent: HTMLElement, private readonly deps: NavDeps) { + const mac = shortcuts.isMac; + const axisMarkup = AXES.map((a) => { + const pos = !a.k.startsWith('-'); + return ( + (pos ? `` : '') + + `${t('Snap to this view')}` + + (pos ? `${a.label}` : '') + ); + }).join(''); + const radio = (group: string, items: ReadonlyArray<{ id: string; label: string }>, role: string): string => + items.map((i) => ``).join(''); + const rows = helpRows(mac).map(([a, b]) => `
            ${a}
            ${b}
            `).join(''); + this.root = el( + '
            ' + + `${axisMarkup}` + + '
            ' + + `` + + `` + + `` + + `` + + `` + + '
            ' + + `' + + `' + + '
            ', + ); + this.svg = this.root.querySelector('.fc-sc-axes') as SVGSVGElement; + for (const a of AXES) { + this.dots.set(a.k, { + dot: this.svg.querySelector(`circle[data-k="${a.k}"]`) as SVGCircleElement, + line: this.svg.querySelector(`line[data-k="${a.k}"]`), + text: this.svg.querySelector(`text[data-k="${a.k}"]`), + }); + } + this.displayPop = this.root.querySelector('[data-pop="display"]') as HTMLElement; + this.helpPop = this.root.querySelector('[data-pop="help"]') as HTMLElement; + this.orthoLabel = this.root.querySelector('[data-k="ortho-label"]') as HTMLElement; + this.displayBtn = this.root.querySelector('[data-k="display"]') as HTMLButtonElement; + this.helpBtn = this.root.querySelector('[data-k="help"]') as HTMLButtonElement; + this.displayBtn.title = this.titled(t('Display'), 'scene.displayMenu'); + this.helpBtn.title = this.titled(t('Navigation'), 'scene.navHelp'); + parent.append(this.root); + this.root.addEventListener('click', this.onClick); + this.root.addEventListener('input', this.onInput); + window.addEventListener('pointerdown', this.onOutside, true); + window.addEventListener('keydown', this.onKey, true); + this.offs.push(deps.viewport.on('display', () => this.paintState()), deps.viewport.on('prefs', () => this.paintPrefs()), commands.on('change', () => this.paintState())); + this.paintState(); + this.paintPrefs(); + } + + private titled(label: string, action: string): string { + const k = keyOf(action); + return k ? `${label} (${k})` : label; + } + + setRoom(px: number): void { + this.root.style.setProperty('--fc-sc-nav-room', `${Math.max(120, Math.round(px))}px`); + } + + setTop(px: number): void { + if (px > 0) this.root.style.setProperty('--fc-sc-nav-top', `${Math.round(px)}px`); + else this.root.style.removeProperty('--fc-sc-nav-top'); + } + + orient(q: THREE.Quaternion): void { + const sig = `${q.x.toFixed(4)},${q.y.toFixed(4)},${q.z.toFixed(4)},${q.w.toFixed(4)}`; + if (sig === this.lastSig) return; + this.lastSig = sig; + const inv = q.clone().invert(); + const v = new THREE.Vector3(); + for (const a of AXES) { + v.copy(a.v).applyQuaternion(inv); + const x = (v.x * R).toFixed(2); + const y = (-v.y * R).toFixed(2); + const parts = this.dots.get(a.k); + if (!parts) continue; + parts.dot.setAttribute('cx', x); + parts.dot.setAttribute('cy', y); + parts.dot.classList.toggle('is-back', v.z < -0.05); + parts.line?.setAttribute('x2', x); + parts.line?.setAttribute('y2', y); + parts.text?.setAttribute('x', x); + parts.text?.setAttribute('y', y); + } + } + + toggleDisplay(force?: boolean): void { + const open = force ?? this.displayPop.hidden; + this.displayPop.hidden = !open; + this.displayBtn.setAttribute('aria-expanded', String(open)); + if (open) { + this.toggleHelp(false); + this.paintState(); + (this.displayPop.querySelector('[aria-checked="true"]') as HTMLElement | null)?.focus({ preventScroll: true }); + } + } + + toggleHelp(force?: boolean): void { + const open = force ?? this.helpPop.hidden; + this.helpPop.hidden = !open; + this.helpBtn.setAttribute('aria-expanded', String(open)); + if (open) this.toggleDisplay(false); + } + + get open(): boolean { + return !this.displayPop.hidden || !this.helpPop.hidden; + } + + paintState(): void { + const vp = this.deps.viewport; + const sel = this.deps.selected(); + for (const b of this.displayPop.querySelectorAll('[data-mode]')) b.setAttribute('aria-checked', String(b.dataset.mode === vp.mode)); + for (const b of this.displayPop.querySelectorAll('[data-overlay]')) { + const id = b.dataset.overlay ?? ''; + const on = id === 'grid' ? this.deps.grid() : vp.overlay(id as never); + b.setAttribute('aria-checked', String(on)); + } + const current = sel ? vp.objectDisplay(sel) : null; + for (const b of this.displayPop.querySelectorAll('[data-object]')) { + b.setAttribute('aria-checked', String(b.dataset.object === current)); + b.disabled = !sel; + } + const label = this.deps.ortho() ? t('Ortho') : t('Persp'); + if (this.orthoLabel.textContent !== label) this.orthoLabel.textContent = label; + } + + private paintPrefs(): void { + const p = this.deps.viewport.prefs; + for (const input of this.helpPop.querySelectorAll('[data-pref]')) { + const k = input.dataset.pref; + if (k === 'orbitSpeed') input.value = String(p.orbitSpeed); + else if (k === 'trackpad') input.checked = p.trackpad; + else if (k === 'invertZoom') input.checked = p.invertZoom; + } + } + + private readonly onClick = (e: MouseEvent): void => { + const target = e.target as Element; + const dot = target.closest('circle[data-k]'); + if (dot) { + const axis = AXES.find((a) => a.k === dot.getAttribute('data-k')); + if (axis) void commands.run(axis.cmd); + return; + } + const btn = target.closest('button') as HTMLButtonElement | null; + if (!btn) return; + if (btn.dataset.mode) void commands.run(DISPLAY_CMD[btn.dataset.mode]); + else if (btn.dataset.overlay) void commands.run(btn.dataset.overlay === 'grid' ? 'scene.grid' : OVERLAY_CMD[btn.dataset.overlay]); + else if (btn.dataset.object) void commands.run(OBJECT_CMD[btn.dataset.object]); + else if (btn.dataset.k === 'display') this.toggleDisplay(); + else if (btn.dataset.k === 'help') this.toggleHelp(); + else if (btn.dataset.k === 'ortho') void commands.run('scene.viewOrtho'); + else if (btn.dataset.k === 'frame') void commands.run(this.deps.selected() ? 'scene.focus' : 'scene.frameAll'); + else if (btn.dataset.k === 'home') void commands.run('scene.viewHome'); + this.paintState(); + }; + + private readonly onInput = (e: Event): void => { + const input = e.target as HTMLInputElement; + const k = input.dataset.pref; + if (k === 'orbitSpeed') this.deps.viewport.setPrefs({ orbitSpeed: Number(input.value) }); + else if (k === 'trackpad') this.deps.viewport.setPrefs({ trackpad: input.checked }); + else if (k === 'invertZoom') this.deps.viewport.setPrefs({ invertZoom: input.checked }); + }; + + private readonly onOutside = (e: PointerEvent): void => { + if (!this.open || this.root.contains(e.target as Node)) return; + this.toggleDisplay(false); + this.toggleHelp(false); + }; + + private readonly onKey = (e: KeyboardEvent): void => { + if (e.code !== 'Escape' || !this.open) return; + e.preventDefault(); + e.stopPropagation(); + this.toggleDisplay(false); + this.toggleHelp(false); + }; + + dispose(): void { + window.removeEventListener('pointerdown', this.onOutside, true); + window.removeEventListener('keydown', this.onKey, true); + for (const off of this.offs) off(); + this.root.remove(); + } +} diff --git a/frontend/src/ui/scene/view/output.ts b/frontend/src/ui/scene/view/output.ts index b4a6269..883e02e 100644 --- a/frontend/src/ui/scene/view/output.ts +++ b/frontend/src/ui/scene/view/output.ts @@ -288,7 +288,18 @@ export class OutputSession { return [lo, Math.min(Math.max(hi, lo + 0.001), far)]; } + async passFrames(): Promise<{ depth: Uint8ClampedArray; mask: Uint8ClampedArray }> { + if (this.done) throw new Error('The output session has ended.'); + const pass = this.passTargets(); + this.drawPass(pass); + return { depth: this.flatRgba(pass, 'depth'), mask: this.flatRgba(pass, 'mask') }; + } + private async flatten(pass: PassTargets, kind: PassKind): Promise { + return await this.encode(this.flatRgba(pass, kind)); + } + + private flatRgba(pass: PassTargets, kind: PassKind): Uint8ClampedArray { const { renderer } = this.host; const [lo, hi] = this.depthRange(); const u = pass.material.uniforms; @@ -311,7 +322,7 @@ export class OutputSession { for (let y = 0; y < this.height; y++) { grey.set(raw.subarray((this.height - 1 - y) * row, (this.height - y) * row), y * row); } - return await this.encode(grey); + return grey; } private async encode(rgba: Uint8ClampedArray): Promise { diff --git a/frontend/src/ui/scene/view/port.ts b/frontend/src/ui/scene/view/port.ts index 1f2c85b..b0731dd 100644 --- a/frontend/src/ui/scene/view/port.ts +++ b/frontend/src/ui/scene/view/port.ts @@ -3,6 +3,8 @@ import type { Gestures } from './gizmo'; export interface ViewPort extends Gestures { select(id: string | null): void; + selection?(): readonly string[]; + setSelection?(ids: readonly string[], primary?: string | null): void; persistView(pose: ViewPose): void; cameraView(on: boolean): void; } diff --git a/frontend/src/ui/scene/view/rig.ts b/frontend/src/ui/scene/view/rig.ts index ca82767..5f1dfdf 100644 --- a/frontend/src/ui/scene/view/rig.ts +++ b/frontend/src/ui/scene/view/rig.ts @@ -1,7 +1,7 @@ import * as THREE from 'three'; import { DEFAULT_FOCAL_MM, type EditorSource, type SceneObject, type SceneSource, type Transform, type ViewPose } from '../../../engine/scene/types'; import { t } from '../../i18n'; -import { FlyCamera, type Keys } from './fly'; +import { FlyCamera, PITCH_LIMIT as PITCH_LIMIT_VIEW, type Keys } from './fly'; import { aspectValue, defaultInsets, fitFrame, fovFromFocal, type Insets, type Rect } from './framing'; import type { Gestures } from './gizmo'; import type { ObjectSync } from './objects'; @@ -16,6 +16,24 @@ const FRAME_SLACK = 1.05; const TWEEN_SECONDS = 0.28; const PERSIST_MS = 250; const QUIET_SECONDS = 0.3; +const ORBIT_PER_PIXEL = 0.006; +const ORBIT_SMOOTH = 0.45; +const ZOOM_STEP = 0.86; +const MIN_DIST = 0.05; +const ROAM = 1200; +const FIT_SLACK = 1.15; +const ORTHO_MIN = 0.02; +const ORTHO_MAX = 600; + +function flagOrtho(cam: THREE.PerspectiveCamera, on: boolean, half: number): void { + const c = cam as unknown as { isPerspectiveCamera: boolean; isOrthographicCamera: boolean; top: number; bottom: number; left: number; right: number }; + c.isPerspectiveCamera = !on; + c.isOrthographicCamera = on; + c.top = half; + c.bottom = -half; + c.left = -half * cam.aspect; + c.right = half * cam.aspect; +} export interface RigDeps { source: SceneSource; @@ -74,6 +92,11 @@ export class CameraRig { private persistTimer = 0; private written = ''; private lastProject = ''; + private orbitYaw = 0; + private orbitPitch = 0; + readonly pivot = new THREE.Vector3(0, 0.5, 0); + ortho = false; + private orthoHalf = 5; constructor(private readonly deps: RigDeps) { this.camera.layers.enable(0); @@ -241,23 +264,129 @@ export class CameraRig { if (this.inCameraView) return false; const target = box ? box.getCenter(new THREE.Vector3()) : fallback; if (!target) return false; - const forward = this.camera.getWorldDirection(new THREE.Vector3()); - forward.y = 0; - if (forward.lengthSq() < 1e-6) forward.set(0, 0, -1); - forward.normalize(); - const to = target.clone().addScaledVector(forward, -FOCUS_BACK); - to.y += FOCUS_UP; - const look = new THREE.Matrix4().lookAt(to, target, new THREE.Vector3(0, 1, 0)); - this.tween = { - from: this.fly.position.clone(), - to, - fromQ: this.fly.quaternion.clone(), - toQ: new THREE.Quaternion().setFromRotationMatrix(look), - t: 0, - }; + const radius = box ? Math.max(0.05, box.getSize(new THREE.Vector3()).length() / 2) : FOCUS_BACK / 3; + const half = THREE.MathUtils.degToRad(this.camera.fov) / 2; + const narrow = Math.min(half, Math.atan(Math.tan(half) * Math.max(0.2, this.camera.aspect))); + const dist = (radius / Math.sin(narrow)) * FIT_SLACK; + const forward = new THREE.Vector3(0, 0, -1).applyQuaternion(this.fly.quaternion); + this.pivot.copy(target); + if (this.ortho) this.orthoHalf = THREE.MathUtils.clamp(radius * FIT_SLACK, ORTHO_MIN, ORTHO_MAX); + this.orbitYaw = 0; + this.orbitPitch = 0; + this.fly.stop(); + const q = this.fly.quaternion.clone(); + this.tween = { from: this.fly.position.clone(), to: target.clone().addScaledVector(forward, -dist), fromQ: q, toQ: q.clone(), t: 0 }; return true; } + private distance(): number { + return Math.max(MIN_DIST, this.fly.position.distanceTo(this.pivot)); + } + + setPivot(point: THREE.Vector3): void { + if (Number.isFinite(point.x) && Number.isFinite(point.y) && Number.isFinite(point.z)) this.pivot.copy(point); + } + + orbit(dx: number, dy: number, speed: number): void { + if (this.inCameraView) { + this.look(dx, dy); + return; + } + if (!this.drive()) return; + this.orbitYaw -= dx * ORBIT_PER_PIXEL * speed; + this.orbitPitch -= dy * ORBIT_PER_PIXEL * speed; + } + + private rotateAbout(dYaw: number, dPitch: number): void { + const before = this.fly.quaternion.clone(); + this.fly.setAngles(this.fly.pitch + dPitch, this.fly.yaw + dYaw, this.fly.roll); + const turn = this.fly.quaternion.clone().multiply(before.invert()); + const offset = this.fly.position.clone().sub(this.pivot).applyQuaternion(turn); + this.fly.position.copy(this.pivot).add(offset); + } + + panPixels(dx: number, dy: number): void { + if (this.inCameraView) { + this.pan(dx, dy); + return; + } + if (!this.drive()) return; + const { height } = this.deps.size(); + const perPixel = this.ortho ? (2 * this.orthoHalf) / Math.max(1, height) : (2 * this.distance() * Math.tan(THREE.MathUtils.degToRad(this.camera.fov) / 2)) / Math.max(1, height); + const q = this.fly.quaternion; + const shift = new THREE.Vector3(1, 0, 0).applyQuaternion(q).multiplyScalar(-dx * perPixel); + shift.addScaledVector(new THREE.Vector3(0, 1, 0).applyQuaternion(q), dy * perPixel); + this.pivot.add(shift); + this.fly.push(shift); + } + + zoomAt(notches: number, ndcX: number, ndcY: number, reach: number | null): void { + if (this.inCameraView) { + this.dolly(notches); + return; + } + if (!this.drive() || notches === 0) return; + const factor = Math.pow(ZOOM_STEP, notches); + const cam = this.camera; + if (this.ortho) { + const before = this.orthoHalf; + this.orthoHalf = THREE.MathUtils.clamp(before * factor, ORTHO_MIN, ORTHO_MAX); + const k = 1 - this.orthoHalf / before; + const q = this.fly.quaternion; + const shift = new THREE.Vector3(1, 0, 0).applyQuaternion(q).multiplyScalar(ndcX * before * cam.aspect * k); + shift.addScaledVector(new THREE.Vector3(0, 1, 0).applyQuaternion(q), ndcY * before * k); + this.fly.position.add(shift); + this.pivot.add(shift); + this.lastProject = ''; + return; + } + cam.updateMatrixWorld(); + const dir = new THREE.Vector3(ndcX, ndcY, 0.5).unproject(cam).sub(cam.position).normalize(); + const dist = Math.max(MIN_DIST * 2, reach ?? this.distance()); + let move = notches > 0 ? dist * (1 - factor) : -dist * (1 / factor - 1); + move = Math.min(move, dist - MIN_DIST); + this.fly.push(dir.multiplyScalar(move)); + } + + setFlySpeed(steps: number): number { + this.fly.speed = THREE.MathUtils.clamp(this.fly.speed * Math.pow(1.2, steps), 0.05, 20); + return this.fly.speed; + } + + view(yaw: number, pitch: number, centre: THREE.Vector3 | null): boolean { + if (this.inCameraView) return false; + if (centre) this.pivot.copy(centre); + const dist = this.distance(); + const p = THREE.MathUtils.clamp(pitch, -PITCH_LIMIT_VIEW, PITCH_LIMIT_VIEW); + const toQ = new THREE.Quaternion().setFromEuler(new THREE.Euler(p, yaw, 0, 'YXZ')); + const to = this.pivot.clone().addScaledVector(new THREE.Vector3(0, 0, -1).applyQuaternion(toQ), -dist); + this.orbitYaw = 0; + this.orbitPitch = 0; + this.fly.stop(); + this.tween = { from: this.fly.position.clone(), to, fromQ: this.fly.quaternion.clone(), toQ, t: 0 }; + return true; + } + + home(pose: ViewPose): boolean { + if (this.inCameraView) return false; + const to = new THREE.Vector3(pose.position[0], pose.position[1], pose.position[2]); + const toQ = new THREE.Quaternion().setFromEuler(new THREE.Euler(pose.rotation[0], pose.rotation[1], pose.rotation[2], 'XYZ')); + this.pivot.copy(to).addScaledVector(new THREE.Vector3(0, 0, -1).applyQuaternion(toQ), to.length() || 8); + this.orbitYaw = 0; + this.orbitPitch = 0; + this.fly.stop(); + this.fly.speed = 1; + this.tween = { from: this.fly.position.clone(), to, fromQ: this.fly.quaternion.clone(), toQ, t: 0 }; + return true; + } + + setOrtho(on: boolean): void { + if (on === this.ortho) return; + if (on) this.orthoHalf = THREE.MathUtils.clamp(this.distance() * Math.tan(THREE.MathUtils.degToRad(this.camera.fov) / 2), ORTHO_MIN, ORTHO_MAX); + this.ortho = on; + this.lastProject = ''; + } + frameClear(box: THREE.Box3): boolean { if (this.inCameraView || box.isEmpty()) return false; const { height } = this.deps.size(); @@ -299,7 +428,23 @@ export class CameraRig { const live = enabled && (!this.inCameraView || (!this.deps.editor.playing && !!obj && !obj.locked)); const drove = this.touched; this.touched = false; - const moved = this.fly.step(dt, keys, live) || drove; + let orbited = false; + if (!this.inCameraView && (this.orbitYaw !== 0 || this.orbitPitch !== 0)) { + const blend = 1 - Math.pow(1 - ORBIT_SMOOTH, dt * 60); + const done = Math.abs(this.orbitYaw) < 1e-5 && Math.abs(this.orbitPitch) < 1e-5; + const dy = done ? this.orbitYaw : this.orbitYaw * blend; + const dp = done ? this.orbitPitch : this.orbitPitch * blend; + this.orbitYaw -= dy; + this.orbitPitch -= dp; + if (done) this.orbitYaw = this.orbitPitch = 0; + this.rotateAbout(dy, dp); + orbited = true; + } + const moved = this.fly.step(dt, keys, live) || drove || orbited; + if (!this.inCameraView && this.fly.position.length() > ROAM) { + this.fly.position.setLength(ROAM); + this.fly.stop(); + } if (this.inCameraView) { if (moved && (live || drove)) { if (!this.flying) { @@ -367,18 +512,25 @@ export class CameraRig { cam.far = OUT_FAR; cam.setViewOffset(rect.width, rect.height, -rect.x, -rect.y, width, height); } else { - const sig = `f|${width}|${height}`; + const sig = `f|${width}|${height}|${this.ortho ? this.orthoHalf : 0}`; if (sig === this.lastProject) return; this.lastProject = sig; this.frame = null; this.focal = DEFAULT_FOCAL_MM; cam.fov = fovFromFocal(DEFAULT_FOCAL_MM); cam.aspect = width / height; - cam.near = VIEW_NEAR; + cam.near = this.ortho ? -VIEW_FAR / 2 : VIEW_NEAR; cam.far = VIEW_FAR; cam.clearViewOffset(); } cam.updateProjectionMatrix(); + const ortho = this.ortho && !this.inCameraView; + flagOrtho(cam, ortho, this.orthoHalf); + if (ortho) { + const h = this.orthoHalf; + cam.projectionMatrix.makeOrthographic(-h * cam.aspect, h * cam.aspect, h, -h, cam.near, cam.far); + cam.projectionMatrixInverse.copy(cam.projectionMatrix).invert(); + } } dispose(): void { diff --git a/frontend/src/ui/scene/view/scene-view.ts b/frontend/src/ui/scene/view/scene-view.ts index a351a1a..12a7b98 100644 --- a/frontend/src/ui/scene/view/scene-view.ts +++ b/frontend/src/ui/scene/view/scene-view.ts @@ -1,6 +1,10 @@ import * as THREE from 'three'; import type { SparkRenderer } from '@sparkjsdev/spark'; +import { commands } from '../../../engine/commands'; import { Emitter } from '../../../engine/emitter'; +import { defaultViewPose } from '../../../engine/scene/doc'; +import { VIEW_PRESETS, type ViewPreset } from '../../../engine/scene/viewport'; +import { shortcuts } from '../../../engine/shortcuts'; import { studios } from '../../../engine/studios'; import type { EditorState } from '../../../engine/scene/editor-state'; import { OUTPUT_SIZES, isPackSky, type SceneObject, type SceneSource } from '../../../engine/scene/types'; @@ -9,9 +13,11 @@ import { el } from '../../dom'; import { t } from '../../i18n'; import { toast } from '../../toasts'; import { rootZoom } from '../../viewers/stage'; -import { type Built, type Builder, type KitApi } from '../contract'; +import { EDITOR_LAYER, type Built, type Builder, type KitApi } from '../contract'; import { MESSAGES, SELECTION_ONLY, isAbort } from '../objects/common'; import { ContactShadows } from './contact'; +import { Display } from './display'; +import { NavUi } from './navui'; import { Environment, configureRenderer } from './environment'; import { Floor } from './floor'; import { FrameOverlay } from './frame-overlay'; @@ -59,9 +65,15 @@ const IDLE_GAP_MS = 250; const MAX_NOTCHES = 3; const LINE_PX = 16; +const PINCH_PER_DELTA = 0.035; +const FRONT_REACH = 8; + +type PressKind = 'orbit' | 'pan' | 'look' | 'zoom' | 'box'; + interface Press { id: number; button: number; + kind: PressKind; x: number; y: number; startX: number; @@ -114,6 +126,11 @@ export class SceneView { private readonly picker: Picker; private readonly keys: Keys; private readonly frameBox: FrameOverlay; + private readonly display: Display; + readonly nav: NavUi; + private hover = false; + private spaceHeld = false; + private spaceDragged = false; private readonly watchers: ResizeObserver[] = []; private readonly offs: Array<() => void> = []; private readonly holds = new Set(); @@ -163,6 +180,7 @@ export class SceneView { this.floor = new Floor(this.scene); this.frameBox = new FrameOverlay(opts.frame); this.stats = new Stats(opts.overlay); + opts.overlay.append(this.marquee); this.sync = new ObjectSync({ source: this.source, @@ -176,6 +194,8 @@ export class SceneView { }); this.scene.add(this.sync.content); this.contact = new ContactShadows(this.scene, this.renderer, this.sync, this.source, () => this.worldSplats, (x, y, z) => this.picker.floorBelow(x, y, z)?.y ?? null); + this.display = new Display(this.scene, this.sync, this.source, this.editor.viewport); + this.display.setTheme(this.theme); this.rig = new CameraRig({ source: this.source, @@ -186,6 +206,12 @@ export class SceneView { size: () => ({ width: this.stage.clientWidth, height: this.stage.clientHeight }), }); this.rig.loadView(this.source.doc.view); + this.nav = new NavUi(opts.overlay, { + viewport: this.editor.viewport, + grid: () => this.editor.grid, + selected: () => this.source.selected, + ortho: () => this.rig.ortho, + }); this.keys = new Keys( { @@ -252,7 +278,12 @@ export class SceneView { canvas.addEventListener('dblclick', this.onDouble); canvas.addEventListener('wheel', this.onWheel, { passive: false }); canvas.addEventListener('contextmenu', this.onMenu); + canvas.addEventListener('pointerenter', this.onEnter); + canvas.addEventListener('pointerleave', this.onLeave); window.addEventListener('pointermove', this.onTrack, true); + window.addEventListener('keydown', this.onSpaceDown, true); + window.addEventListener('keyup', this.onSpaceUp, true); + window.addEventListener('blur', this.onSpaceReset); const size = new ResizeObserver(() => this.resize()); size.observe(this.stage); @@ -271,7 +302,15 @@ export class SceneView { source.on('order', () => this.requestRender()), editor.on('cameraView', (on) => this.applyCameraView(on)), editor.on('mode', (mode) => this.onMode(mode)), - editor.on('grid', () => this.paintLook()), + editor.on('grid', () => { + this.paintLook(); + this.nav.paintState(); + }), + editor.viewport.on('display', () => { + this.rig.setOrtho(editor.viewport.ortho); + this.nav.paintState(); + this.requestRender(); + }), editor.on('gizmo', () => { this.syncGizmo(); this.refreshGizmo(); @@ -294,6 +333,7 @@ export class SceneView { this.theme = next; this.outline.pale.copy(next.outline); this.outline.deep.copy(next.outlineDeep); + this.display.setTheme(next); this.paintLook(); }); this.offs.push(theme); @@ -313,8 +353,11 @@ export class SceneView { private reserveTop(): void { const top = this.top; if (!top) return; - const used = top.offsetHeight > 0 ? top.offsetTop + top.offsetHeight + TOP_GAP : 0; + const bar = top.getBoundingClientRect(); + const overlap = top.offsetHeight > 0 ? bar.bottom - this.stage.getBoundingClientRect().top : 0; + const used = overlap > 0 ? overlap + TOP_GAP : 0; this.rig.reserve({ top: used }); + this.nav.setTop(used); this.requestRender(); } @@ -425,20 +468,28 @@ export class SceneView { this.frameBox.setRecord(this.editor.mode === 'record'); this.frameBox.show(rig.inCameraView ? rig.frame : null, rig.focal); this.contact.update(); - this.renderer.render(this.scene, rig.camera); - if (!this.revealed) { - this.revealed = true; - this.stage.classList.add('is-ready'); - } - const id = this.source.selected; - const marked = !!id && !rig.inCameraView && this.editor.mode === 'build' && this.outlined(id); - this.pulsing = marked; - if (marked && id) { - const seconds = this.still?.matches ? 0 : performance.now() / 1000; - this.outline.render(this.renderer, this.scene, rig.camera, this.sync.rootOf(id), this.sync.content, this.sync.version, seconds); - } else { - this.outline.release(); + const shaded = this.editor.mode === 'build'; + if (shaded) this.display.begin(this.editor.grid); + try { + this.renderer.render(this.scene, rig.camera); + if (shaded && this.display.wantsWirePass) this.display.wirePass(this.renderer, () => this.renderer.render(this.scene, rig.camera)); + if (!this.revealed) { + this.revealed = true; + this.stage.classList.add('is-ready'); + } + const id = this.source.selected; + const marked = !!id && !rig.inCameraView && shaded && this.editor.viewport.overlay('outline') && this.outlined(id); + this.pulsing = marked; + if (marked && id) { + const seconds = this.still?.matches ? 0 : performance.now() / 1000; + this.outline.render(this.renderer, this.scene, rig.camera, this.sync.rootOf(id), this.sync.content, this.sync.version, seconds); + } else { + this.outline.release(); + } + } finally { + if (shaded) this.display.end(); } + this.nav.orient(rig.camera.quaternion); } private armPulse(): void { @@ -474,6 +525,7 @@ export class SceneView { this.renderer.setPixelRatio(ratio); this.renderer.setSize(w, h, false); this.rig.project(); + this.nav.setRoom(this.stage.clientHeight - this.rig.insets().top - 2 * TOP_GAP); this.events.emit('size', this.stage.clientWidth, this.stage.clientHeight); if (this.paused === 0 && !this.disposed) { this.paint(); @@ -505,11 +557,85 @@ export class SceneView { this.canvas.focus({ preventScroll: true }); } if (!this.canMouse() || this.gizmo.dragging || this.press) return; - if (this.gizmo.hovering && e.button === 0) return; - this.press = { id: e.pointerId, button: e.button, x: e.clientX, y: e.clientY, startX: e.clientX, startY: e.clientY, travel: 0 }; + if (this.gizmo.hovering && e.button === 0 && !e.altKey && !this.spaceHeld) return; + if (e.button > 2) return; + let kind: PressKind; + if (e.button === 2) kind = 'look'; + else if (e.button === 0 && e.shiftKey && !this.spaceHeld && this.editor.mode === 'build' && !this.rig.inCameraView) kind = 'box'; + else if (this.spaceHeld || (e.button === 1 && e.shiftKey)) kind = 'pan'; + else if (e.button === 1 && (e.ctrlKey || e.metaKey)) kind = 'zoom'; + else kind = 'orbit'; + if (this.spaceHeld) this.spaceDragged = true; + if (e.button === 1) e.preventDefault(); + if (kind === 'orbit' || kind === 'pan' || kind === 'zoom') this.rig.setPivot(this.pivotAt(e.clientX, e.clientY)); + this.press = { id: e.pointerId, button: e.button, kind, x: e.clientX, y: e.clientY, startX: e.clientX, startY: e.clientY, travel: 0 }; capture(this.canvas, e.pointerId, true); }; + private pivotAt(clientX: number, clientY: number): THREE.Vector3 { + this.rig.project(); + const hit = this.picker.hitAt(clientX, clientY); + if (hit.kind === 'object') return hit.point.clone(); + const sel = this.source.selected; + const box = sel ? this.sync.boundsOf(sel) : null; + if (box) return box.getCenter(new THREE.Vector3()); + if (hit.kind === 'ground' && hit.distance < FRONT_REACH * 12) return hit.point.clone(); + return this.picker.lookPoint(Math.max(1, this.rig.camera.position.distanceTo(this.rig.pivot) || FRONT_REACH)); + } + + private ndc(clientX: number, clientY: number): [number, number] { + const rect = this.canvas.getBoundingClientRect(); + if (rect.width < 1 || rect.height < 1) return [0, 0]; + return [((clientX - rect.left) / rect.width) * 2 - 1, -((clientY - rect.top) / rect.height) * 2 + 1]; + } + + private reachAt(clientX: number, clientY: number): number | null { + this.rig.project(); + const hit = this.picker.hitAt(clientX, clientY); + return hit.kind === 'origin' || !Number.isFinite(hit.distance) ? null : hit.distance; + } + + private readonly onEnter = (): void => { + this.hover = true; + }; + + private readonly onLeave = (): void => { + this.hover = false; + }; + + private readonly onSpaceDown = (e: KeyboardEvent): void => { + if (e.code !== 'Space' || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return; + if (this.spaceHeld) { + e.preventDefault(); + return; + } + if (e.repeat || e.isComposing || !this.hover || !this.canMouse() || typing(e.target) || anyDialogOpen()) return; + this.spaceHeld = true; + this.spaceDragged = !!this.press; + this.canvas.classList.add('is-pan-ready'); + e.preventDefault(); + }; + + private readonly onSpaceUp = (e: KeyboardEvent): void => { + if (e.code !== 'Space' || !this.spaceHeld) return; + const dragged = this.spaceDragged; + this.onSpaceReset(); + if (dragged) return; + const action = shortcuts.resolve(e, 'scene', { + enabled: (id) => { + const c = commands.get(id); + return !!c && commands.enabled(c); + }, + }); + if (action) void commands.run(action); + }; + + private readonly onSpaceReset = (): void => { + this.spaceHeld = false; + this.spaceDragged = false; + this.canvas.classList.remove('is-pan-ready'); + }; + private readonly onMove = (e: PointerEvent): void => { const press = this.press; if (!press || press.id !== e.pointerId) { @@ -522,12 +648,17 @@ export class SceneView { press.y = e.clientY; press.travel = Math.hypot(e.clientX - press.startX, e.clientY - press.startY); if (press.travel < CLICK_PX && press.button !== 2) return; - this.canvas.classList.add('is-drag'); - if (press.button === 2) { - this.rig.pan(dx, dy); - } else if (press.button === 0 || press.button === 1) { - this.rig.look(dx, dy); + if (press.kind === 'box') { + this.drawMarquee(press.startX, press.startY, e.clientX, e.clientY); + return; } + this.canvas.classList.add('is-drag'); + if (press.kind === 'look') this.rig.look(dx, dy); + else if (press.kind === 'pan') this.rig.panPixels(dx, dy); + else if (press.kind === 'zoom') { + const [nx, ny] = this.ndc(press.startX, press.startY); + this.rig.zoomAt((-dy / WHEEL_UNIT) * 4 * (this.editor.viewport.prefs.invertZoom ? -1 : 1), nx, ny, null); + } else this.rig.orbit(dx, dy, this.editor.viewport.prefs.orbitSpeed); this.requestRender(); }; @@ -537,14 +668,68 @@ export class SceneView { this.press = null; this.canvas.classList.remove('is-drag'); capture(this.canvas, e.pointerId, false); + this.marquee.hidden = true; + if (press.kind === 'box' && press.travel >= CLICK_PX) { + this.boxSelect(press.startX, press.startY, e.clientX, e.clientY); + return; + } if (press.button !== 0 || press.travel >= CLICK_PX) return; if (this.rig.inCameraView || this.editor.mode !== 'build') return; const id = this.picker.pick(e.clientX, e.clientY); - if (id !== this.source.selected) this.port.select(id); + const now = this.picked(); + if ((e.shiftKey || e.metaKey || e.ctrlKey) && this.port.setSelection) { + if (!id) return; + this.port.setSelection(now.includes(id) ? now.filter((x) => x !== id) : [...now, id], now.includes(id) ? null : id); + return; + } + if (id !== this.source.selected || now.length > 1) this.port.select(id); }; + private readonly marquee: HTMLElement = el(''); + + private drawMarquee(x0: number, y0: number, x1: number, y1: number): void { + const host = this.marquee.parentElement; + if (!host) return; + const r = host.getBoundingClientRect(); + const s = this.marquee.style; + s.left = `${Math.min(x0, x1) - r.left}px`; + s.top = `${Math.min(y0, y1) - r.top}px`; + s.width = `${Math.abs(x1 - x0)}px`; + s.height = `${Math.abs(y1 - y0)}px`; + this.marquee.hidden = false; + } + + private boxSelect(x0: number, y0: number, x1: number, y1: number): void { + if (!this.port.setSelection) return; + const rect = this.canvas.getBoundingClientRect(); + const minX = Math.min(x0, x1); + const maxX = Math.max(x0, x1); + const minY = Math.min(y0, y1); + const maxY = Math.max(y0, y1); + this.rig.project(); + const cam = this.rig.camera; + const at = new THREE.Vector3(); + const hits: string[] = []; + for (const o of this.source.doc.objects) { + if (o.parent || !o.visible) continue; + const box = this.sync.boundsOf(o.id); + const root = this.sync.rootOf(o.id); + if (box && !box.isEmpty()) box.getCenter(at); + else if (root) root.getWorldPosition(at); + else continue; + at.project(cam); + if (at.z < -1 || at.z > 1) continue; + const sx = rect.left + ((at.x + 1) / 2) * rect.width; + const sy = rect.top + ((1 - at.y) / 2) * rect.height; + if (sx >= minX && sx <= maxX && sy >= minY && sy <= maxY) hits.push(o.id); + } + const now = this.picked(); + this.port.setSelection([...now, ...hits.filter((h) => !now.includes(h))], hits[hits.length - 1] ?? this.source.selected); + } + private readonly onCancel = (e: PointerEvent): void => { if (this.press && this.press.id === e.pointerId) this.press = null; + this.marquee.hidden = true; this.canvas.classList.remove('is-drag'); }; @@ -567,11 +752,28 @@ export class SceneView { private readonly onWheel = (e: WheelEvent): void => { e.preventDefault(); - if (!this.canMouse() || this.press) return; + if (!this.canMouse()) return; const unit = e.deltaMode === 1 ? LINE_PX : e.deltaMode === 2 ? 400 : 1; - const notches = Math.max(-MAX_NOTCHES, Math.min(MAX_NOTCHES, (-e.deltaY * unit) / WHEEL_UNIT)); - if (notches === 0) return; - this.rig.dolly(notches); + if (this.press) { + if (this.press.kind === 'look' && e.deltaY !== 0) this.rig.setFlySpeed(e.deltaY < 0 ? 1 : -1); + return; + } + const prefs = this.editor.viewport.prefs; + const sign = prefs.invertZoom ? -1 : 1; + const [nx, ny] = this.ndc(e.clientX, e.clientY); + if (e.ctrlKey) { + const notches = Math.max(-MAX_NOTCHES, Math.min(MAX_NOTCHES, -e.deltaY * unit * PINCH_PER_DELTA)) * sign; + if (notches !== 0) this.rig.zoomAt(notches, nx, ny, this.reachAt(e.clientX, e.clientY)); + } else if (prefs.trackpad && e.deltaMode === 0 && !(e.deltaX === 0 && Number.isInteger(e.deltaY) && Math.abs(e.deltaY) >= 50)) { + if (e.altKey) { + this.rig.setPivot(this.pivotAt(e.clientX, e.clientY)); + this.rig.orbit(-e.deltaX, -e.deltaY, prefs.orbitSpeed); + } else this.rig.panPixels(-e.deltaX, -e.deltaY); + } else { + const notches = Math.max(-MAX_NOTCHES, Math.min(MAX_NOTCHES, (-e.deltaY * unit) / WHEEL_UNIT)) * sign; + if (notches === 0) return; + this.rig.zoomAt(notches, nx, ny, this.reachAt(e.clientX, e.clientY)); + } this.requestRender(); }; @@ -612,8 +814,36 @@ export class SceneView { if (this.source.selected === id) this.refreshGizmo(); } + private readonly boxes = new Map(); + + private paintExtras(): void { + const all = this.picked(); + const want = new Set(all.length > 1 ? all.filter((id) => id !== this.source.selected) : []); + for (const [id, box] of this.boxes) { + if (want.has(id)) continue; + box.removeFromParent(); + box.dispose(); + this.boxes.delete(id); + } + for (const id of want) { + const root = this.sync.rootOf(id); + if (!root) continue; + let box = this.boxes.get(id); + if (!box) { + box = new THREE.BoxHelper(root, this.outline.pale.getHex()); + box.layers.set(EDITOR_LAYER); + box.name = 'selection-box'; + this.scene.add(box); + this.boxes.set(id, box); + } + box.setFromObject(root); + } + } + private onSelection(): void { + this.paintExtras(); this.paintSelection(this.source.selected); + this.nav.paintState(); this.refreshGizmo(); this.requestRender(); } @@ -633,6 +863,10 @@ export class SceneView { private onChanged(id: string, keys: readonly (keyof SceneObject)[]): void { if (this.source.selected === id && keys.some((k) => k === 'locked' || k === 'visible' || k === 'parent')) this.refreshGizmo(); + else if (!this.gizmo.dragging && this.picked().length > 1 && this.picked().includes(id)) this.refreshGizmo(); + const box = this.boxes.get(id); + const root = box ? this.sync.rootOf(id) : null; + if (box && root) box.setFromObject(root); if (id === this.source.doc.activeCamera && keys.some((k) => k === 'camera' || k === 'transform')) this.rig.reserve({}); this.requestRender(); } @@ -673,13 +907,50 @@ export class SceneView { private syncGizmo(): void { this.gizmo.setMode(this.editor.gizmoMode, this.editor.gizmoSpace); - this.gizmo.setSnapping(this.editor.snapping); + this.gizmo.setSnapping(this.editor.snapping, this.editor.snapSteps); + } + + private picked(): readonly string[] { + return this.port.selection?.() ?? (this.source.selected ? [this.source.selected] : []); } private refreshGizmo(): void { const id = this.source.selected; const obj = id ? this.source.object(id) : undefined; const node = id ? this.sync.rootOf(id) : null; + const free = + this.editor.mode === 'build' && + !this.rig.inCameraView && + !this.grabber.running && + this.editor.poseTarget === null && + !this.editor.busy; + const all = this.picked(); + if (id && all.length > 1 && free) { + const ids = new Set(all); + const movable: Array<{ id: string; node: THREE.Object3D }> = []; + for (const each of all) { + const o = this.source.object(each); + const n = this.sync.rootOf(each); + let up = o?.parent ?? null; + let nested = false; + while (up) { + if (ids.has(up)) nested = true; + up = this.source.object(up)?.parent ?? null; + } + if (!o || !n || nested || !o.visible || o.locked || (o.kind === 'camera' && this.editor.gizmoMode === 'scale')) continue; + movable.push({ id: each, node: n }); + } + if (movable.length > 1) { + this.gizmo.attachMany(id, movable, this.scene); + this.requestRender(); + return; + } + if (movable.length === 1) { + this.gizmo.attach(movable[0].id, movable[0].node); + this.requestRender(); + return; + } + } const ok = !!id && !!obj && @@ -718,7 +989,7 @@ export class SceneView { } this.gizmo.detach(); const cam = this.source.doc.activeCamera; - if (this.source.selected !== cam) { + if (this.editor.mode === 'build' && this.source.selected !== cam) { this.lookFrom = { id: this.source.selected, cam }; this.port.select(cam); } @@ -742,6 +1013,23 @@ export class SceneView { if (this.editor.cameraView && this.editor.mode !== 'record') this.port.cameraView(false); } + alignCameraToView(): boolean { + const cam = this.source.doc.activeCamera; + if (!cam || this.rig.inCameraView || this.editor.mode !== 'build' || this.source.object(cam)?.kind !== 'camera') return false; + this.rig.project(); + const c = this.rig.camera; + c.updateMatrixWorld(true); + const p = new THREE.Vector3(); + const q = new THREE.Quaternion(); + c.getWorldPosition(p); + c.getWorldQuaternion(q); + const e = new THREE.Euler().setFromQuaternion(q); + this.port.begin(t('Align camera to view')); + this.port.preview(cam, { position: [p.x, p.y, p.z], rotation: [e.x, e.y, e.z], scale: [1, 1, 1] }); + this.port.commit(); + return true; + } + toggleCameraView(): void { if (this.editor.cameraView) this.exitCameraView(); else this.enterCameraView(); @@ -762,6 +1050,46 @@ export class SceneView { return ok; } + frameAll(): boolean { + if (this.editor.mode === 'record' || this.rig.inCameraView) return false; + const all = new THREE.Box3(); + for (const obj of this.source.doc.objects) { + if (!obj.visible || obj.kind === 'camera' || obj.kind === 'light') continue; + const box = this.sync.boundsOf(obj.id); + if (box && box.max.distanceTo(box.min) < 2000) all.union(box); + } + const ok = all.isEmpty() ? this.rig.home(defaultViewPose()) : this.rig.focus(all, null); + if (ok) this.requestRender(); + return ok; + } + + viewPreset(name: ViewPreset): boolean { + const preset = VIEW_PRESETS[name]; + if (!preset || this.editor.mode === 'record') return false; + const sel = this.source.selected; + const box = sel ? this.sync.boundsOf(sel) : null; + const ok = this.rig.view(preset.yaw, preset.pitch, box ? box.getCenter(new THREE.Vector3()) : null); + if (ok) this.requestRender(); + return ok; + } + + resetView(): boolean { + if (this.editor.mode === 'record') return false; + this.editor.viewport.setOrtho(false); + const ok = this.rig.home(defaultViewPose()); + if (ok) this.requestRender(); + return ok; + } + + toggleOrtho(): boolean { + if (this.rig.inCameraView) return false; + const sel = this.source.selected; + const box = sel ? this.sync.boundsOf(sel) : null; + if (box && !this.editor.viewport.ortho) this.rig.setPivot(box.getCenter(new THREE.Vector3())); + this.editor.viewport.setOrtho(!this.editor.viewport.ortho); + return this.editor.viewport.ortho; + } + frameClear(id: string): boolean { if (this.editor.mode === 'record') return false; const box = this.sync.boundsOf(id); @@ -947,9 +1275,11 @@ export class SceneView { this.floor.grid.visible = false; this.gizmo.helper.visible = false; this.env.setEditorLook(false, this.theme.lightSky); + const unhide = this.display.hideForRender(); try { draw(); } finally { + unhide(); this.floor.grid.visible = grid; this.gizmo.helper.visible = gizmoShown; this.env.setEditorLook(this.lookLight(), this.theme.lightSky); @@ -1077,6 +1407,13 @@ export class SceneView { canvas.removeEventListener('dblclick', this.onDouble); canvas.removeEventListener('wheel', this.onWheel); canvas.removeEventListener('contextmenu', this.onMenu); + canvas.removeEventListener('pointerenter', this.onEnter); + canvas.removeEventListener('pointerleave', this.onLeave); + window.removeEventListener('keydown', this.onSpaceDown, true); + window.removeEventListener('keyup', this.onSpaceUp, true); + window.removeEventListener('blur', this.onSpaceReset); + this.display.dispose(); + this.nav.dispose(); canvas.removeEventListener('webglcontextlost', this.onLost); canvas.removeEventListener('webglcontextrestored', this.onRestored); window.removeEventListener('pointermove', this.onTrack, true); diff --git a/frontend/src/ui/scene/view/store-port.ts b/frontend/src/ui/scene/view/store-port.ts index 9b565b5..82a77a2 100644 --- a/frontend/src/ui/scene/view/store-port.ts +++ b/frontend/src/ui/scene/view/store-port.ts @@ -3,29 +3,36 @@ import type { SceneStore } from '../../../engine/scene/store'; import type { ViewPort } from './port'; export function createStorePort(store: SceneStore, editor: EditorState): ViewPort { - let last: string | null = null; + const moved = new Set(); return { begin(label) { - last = null; + moved.clear(); store.begin(label); }, preview(id, transform) { - last = id; + moved.add(id); store.preview(id, { transform }); }, commit() { - const id = last; - last = null; - if (id && !editor.playing && store.tl.hasKeys(id)) store.tl.autoKey(id, editor.playhead); + const ids = [...moved]; + moved.clear(); + if (ids.length > 1 && !editor.playing) store.autoKeyMany(ids, editor.playhead); + else if (ids[0] && !editor.playing && store.tl.hasKeys(ids[0])) store.tl.autoKey(ids[0], editor.playhead); store.commit(); }, cancel() { - last = null; + moved.clear(); store.cancel(); }, select(id) { store.select(id); }, + selection() { + return store.selection; + }, + setSelection(ids, primary) { + store.setSelection(ids, primary); + }, persistView(pose) { store.setView(pose); }, diff --git a/frontend/src/ui/scene/view/theme.ts b/frontend/src/ui/scene/view/theme.ts index 67f1022..9a8f54f 100644 --- a/frontend/src/ui/scene/view/theme.ts +++ b/frontend/src/ui/scene/view/theme.ts @@ -5,9 +5,14 @@ export interface SceneTheme { outline: THREE.Color; outlineDeep: THREE.Color; lightSky: THREE.Color; + axisX: THREE.Color; + axisY: THREE.Color; + axisZ: THREE.Color; + solid: THREE.Color; + wire: THREE.Color; } -const FALLBACK = { outline: 0xfdba74, outlineDeep: 0xc2410c, lightSky: 0xf5f6f8 }; +const FALLBACK = { outline: 0xfdba74, outlineDeep: 0xc2410c, lightSky: 0xf5f6f8, axisX: 0xf05a6a, axisY: 0x8bd450, axisZ: 0x4f9cf7, solid: 0xb8bcc4, wire: 0xe6e8ec }; let probe: CanvasRenderingContext2D | null | undefined; @@ -33,6 +38,11 @@ export function readTheme(node: HTMLElement): SceneTheme { outline: pick('--scene-outline', FALLBACK.outline), outlineDeep: pick('--scene-outline-deep', FALLBACK.outlineDeep), lightSky: pick('--scene-light-sky', FALLBACK.lightSky), + axisX: pick('--scene-axis-x', FALLBACK.axisX), + axisY: pick('--scene-axis-y', FALLBACK.axisY), + axisZ: pick('--scene-axis-z', FALLBACK.axisZ), + solid: pick('--scene-solid', FALLBACK.solid), + wire: pick('--scene-wire', FALLBACK.wire), }; } diff --git a/frontend/src/ui/scene/world/row.ts b/frontend/src/ui/scene/world/row.ts index cacd6cb..b55e6fb 100644 --- a/frontend/src/ui/scene/world/row.ts +++ b/frontend/src/ui/scene/world/row.ts @@ -38,6 +38,10 @@ export function mountRow(ctx: SceneContext, actions: RowActions): EnvRow | null const run = (fn: () => void): (() => void) => () => { if (!ctx.editor.busy) fn(); }; + node.addEventListener('click', (e) => { + if ((e.target as HTMLElement).closest('button')) return; + ctx.store.select(null); + }); add.addEventListener('click', run(actions.add)); complete.addEventListener('click', run(actions.complete)); remove.addEventListener('click', run(actions.remove)); diff --git a/frontend/src/ui/titlebar-tools.ts b/frontend/src/ui/titlebar-tools.ts index 8bfaa08..5d94534 100644 --- a/frontend/src/ui/titlebar-tools.ts +++ b/frontend/src/ui/titlebar-tools.ts @@ -1,8 +1,10 @@ +import { AGENTS_ID, agentActivity, onAgentActivity } from '../dock-adapter'; import { commands, type Command } from '../engine/commands'; import { shortcuts } from '../engine/shortcuts'; import { el, q, setAttr, setClass, setDisabled, setHidden, setStyleVar, setText, setTitle } from './dom'; import { onLanguage, t } from './i18n'; import { icon } from './icons'; +import { JobsPopover } from './jobs-popover'; import { registerMissing } from './menus'; import { TEXT_EDITS } from './native-menu'; import { isLightTheme, onThemeChange, readChoice, setTheme } from './themes'; @@ -28,6 +30,9 @@ function rank(label: string, needle: string): number { export class TitleTools { private readonly theme: HTMLButtonElement; private readonly search: HTMLButtonElement; + private readonly agents: HTMLButtonElement; + private readonly badge: HTMLElement; + private readonly shell: HTMLButtonElement; private readonly gear: HTMLButtonElement; private readonly pop: HTMLElement; private readonly input: HTMLInputElement; @@ -43,8 +48,17 @@ export class TitleTools { ``, ); this.search = el(``); + this.agents = el( + ``, + ); + this.badge = q(this.agents, '.cv-tt-badge'); + this.shell = el(``); this.gear = el(``); - host.append(this.theme, this.search, this.gear); + const jobsBtn = el( + ``, + ); + host.append(this.theme, this.search, jobsBtn, this.agents, this.shell, this.gear); + new JobsPopover(jobsBtn); this.pop = el( `