diff --git a/.agents/skills/formshot-rendering/SKILL.md b/.agents/skills/formshot-rendering/SKILL.md index f9f7ea6d..0e2285c0 100644 --- a/.agents/skills/formshot-rendering/SKILL.md +++ b/.agents/skills/formshot-rendering/SKILL.md @@ -1,6 +1,6 @@ --- name: formshot-rendering -description: Set up, dress, light and render 3D product scenes in formshot, the 3D product renderer, by asking in plain language through its MCP server. Use whenever the person wants a product shot, a model placed on a studio floor, a material put on a part, a studio preset applied, a light, IES profile, sky or camera changed, exposure, colour grade or display transform (including OpenColorIO) adjusted, render size, samples, passes or denoising set, a step undone, or a picture rendered or queued to files, and the formshot tools are available or the person mentions formshot. Covers reading the scene, the command names, partial updates, units and checking work. Also use when a formshot tool fails and the next step is unclear. Not for editing formshot's own source code (use formshot-harness for that). +description: Set up, dress, light and render 3D product scenes in formshot, the 3D product renderer, by asking in plain language through its MCP server. Use whenever the person wants a product shot, a model placed on a studio floor, a material put on a part, a studio preset applied, a light, IES profile, sky or camera changed, exposure, colour grade or display transform (including OpenColorIO) adjusted, render size, samples, passes or denoising set, a step undone, a picture rendered or queued to files, shots, material variants, product configurations, measurements, a turntable, keyed animation or a movie, liquids and wax, spectral rendering, caustics or cutaways, and the formshot tools are available or the person mentions formshot. Covers reading the scene, the command names, partial updates, units and checking work. Also use when a formshot tool fails and the next step is unclear. Not for editing formshot's own source code (use formshot-harness for that). --- # Rendering in formshot @@ -56,6 +56,29 @@ The tool list comes from the engine's catalogue. `references/tools.md`, when pre 1. `render.set_settings {values: {denoise: true, denoising: {denoiser: "own" or "oidn", quality_final: "fast", "balanced" or "high", strength: 1}}}` chooses the denoiser for final renders. 2. Open Image Denoise is optional and downloaded once: check with `denoise.oidn_status {probe: true}`. If it is not installed, the person downloads it in the Final Render window or with `./formshot oidn fetch`; never download it yourself. Without it the engine uses its own denoiser and `denoise.status` and `render.status` say why. +## Workflow 6: shots, variants and configurations + +1. `shot.add {name}` keeps the current camera, look, environment, render settings, lights, visibility and variant choices; `shot.apply {id}` brings one back in one undo step; `shot.render {folder, ...}` queues one render per shot with `render.queue_add`'s options (`{shot}` in `name` is the shot's name). +2. `variant.add_set` and `variant.capture` keep the materials of chosen parts as named variants, `variant.select` chooses one and `variant.diff` says what it would change; `model_set.add` and `model_set.select` show one set of parts and hide the other sets'. +3. The configurator: `config.add_option` with choices whose actions put materials on parts, show or hide parts, choose a variant or a model set, or apply a shot; `config.add_rule` adds requires or excludes rules; `config.select` chooses and moves other options to the nearest valid configuration; `config.check` names problems; `config.list` lists every valid configuration; `config.render_all {folder, ...}` queues one render each (`{config}` and `{variant}` in `name`). +4. `template.list`, then `template.preview {id}` and `template.apply {id}`, dress imported parts by their material names in one undo step; the import tools take `template` too. +5. `measure.add_distance`, `measure.add_size` and `measure.add_angle` keep measurements pinned to parts, `measure.list` reads them in the display unit and `measure.render` queues a render with them drawn in. + +## Workflow 7: animation and movies + +1. `anim.set {fps, start, end}` sets the timeline; `anim.key {target, time, value}` keys a part's `translation`, `rotation` or `scale`, a camera field, a material parameter or a light field (the schema lists the targets); `anim.status` lists tracks, keys and rigs; `anim.seek {time}` shows the document at a time and `{time: null}` the stored values again. +2. Rigs: `anim.turntable {frames}` turns the product once over the animation; `anim.orbit` and `anim.camera_path` move the camera. +3. Motion blur: `render.set_settings {values: {motion_blur: {enabled: true, shutter: 0.5}}}`. Both the CPU and the GPU render it. +4. `anim.render {folder, video: {format: "mp4"}}` queues one job per frame and then a movie job (mp4, webm, mov or gif); poll `render.queue_list`. `video.ffmpeg` says whether ffmpeg is there. When it is not, the person downloads it in Render Animation; never download it yourself. +5. From a shell: `./formshot cli render model.glb out.mp4 --turntable 36`. + +## Workflow 8: light transport + +1. Materials: `material.set_params` with `transmission_depth` (metres light travels before it takes the colour) and `medium_priority` (where parts overlap the higher one wins, a drink inside its glass); `subsurface_weight`, `subsurface_color` and `subsurface_radius` for wax, marble or milk; `edge_radius` (metres) rounds sharp edges; `fibre_density`, `fibre_length` and the other `fibre_*` fields grow fibres. +2. `render.set_settings {values: {transport: {spectral: {enabled: true}}}}` renders spectrally (dispersion in prisms and gems); `{transport: {caustics: {mode: "photons"}}}` adds photon caustics, which only the CPU renders. +3. `scene.add_cutaway {cutaway: {shape, cap, targets}}` opens parts; `scene.set_cutaway`, `cutaway.set_enabled` and `cutaway.set_targets` change it. +4. `transport.features` lists each feature with whether the document uses it and whether the GPU renders it; when the GPU refuses, the CPU renders and `render.status` says why. + ## When something fails - "locked": the node or a group above it is locked; `scene.set_locked` unlocks it. diff --git a/.agents/skills/formshot-rendering/references/tools.md b/.agents/skills/formshot-rendering/references/tools.md index b27b1695..aef199c5 100644 --- a/.agents/skills/formshot-rendering/references/tools.md +++ b/.agents/skills/formshot-rendering/references/tools.md @@ -1,10 +1,11 @@ # formshot tools -Generated from the engine's command catalogue (formshot 0.8.0) by `./formshot agents sync`; do not edit by hand. +Generated from the engine's command catalogue (formshot 0.10.0) by `./formshot agents sync`; do not edit by hand. ## Contents - Scene: `scene.add_group`, `scene.add_part`, `scene.add_primitive`, `scene.add_light`, `scene.add_cutaway`, `scene.remove`, `scene.rename`, `scene.set_transform`, `scene.set_visible`, `scene.set_locked`, `scene.set_ray_visibility`, `scene.set_part_colour`, `scene.set_metadata`, `scene.set_pivot`, `scene.set_part_mesh`, `scene.set_light`, `scene.set_cutaway`, `scene.reparent`, `scene.duplicate`, `scene.import`, `scene.summary`, `scene.meshes`, `scene.mesh_data`, `scene.retessellate` +- Cutaway: `cutaway.set_enabled`, `cutaway.set_targets` - Mesh: `mesh.add`, `mesh.remove` - Materials: `material.create`, `material.set_params`, `material.set_type`, `material.set_slot`, `material.clear_slot`, `material.set_graph`, `material.label_add`, `material.label_set`, `material.label_remove`, `material.label_move`, `material.assign`, `material.rename`, `material.remove`, `material.types`, `material.node_kinds`, `material.program`, `material.preview_maps`, `material.get`, `material.labels` - Texture: `texture.add`, `texture.remove` @@ -17,6 +18,12 @@ Generated from the engine's command catalogue (formshot 0.8.0) by `./formshot ag - Rendering: `render.set_settings`, `render.start`, `render.status`, `render.frame`, `render.stop`, `render.still`, `render.develop`, `render.interaction`, `render.devices`, `render.set_device`, `render.region`, `render.viewport`, `render.passes`, `render.queue_add`, `render.queue_list`, `render.queue_cancel`, `render.queue_remove`, `render.queue_move`, `render.queue_clear`, `render.queue_pause`, `render.output_formats`, `render.output_thumbnail` - Units: `units.set_display` - Document: `document.set_info`, `document.new`, `document.open`, `document.import`, `document.save`, `document.close` +- Anim: `anim.add_rig`, `anim.set_rig`, `anim.remove_rig`, `anim.turntable`, `anim.orbit`, `anim.camera_path`, `anim.set`, `anim.key`, `anim.set_key`, `anim.remove_key`, `anim.move_key`, `anim.remove_track`, `anim.clear`, `anim.seek`, `anim.status`, `anim.sample`, `anim.render` +- Config: `config.add_option`, `config.set_option`, `config.remove_option`, `config.move_option`, `config.add_choice`, `config.set_choice`, `config.remove_choice`, `config.move_choice`, `config.add_rule`, `config.remove_rule`, `config.select`, `config.apply`, `config.get`, `config.check`, `config.list`, `config.render_all` +- Shot: `shot.add`, `shot.update`, `shot.set`, `shot.remove`, `shot.move`, `shot.duplicate`, `shot.apply`, `shot.list`, `shot.render` +- Variant: `variant.add_set`, `variant.set_set`, `variant.remove_set`, `variant.capture`, `variant.add`, `variant.set`, `variant.remove`, `variant.move`, `variant.select`, `variant.apply_choice`, `variant.list`, `variant.diff` +- Model_Set: `model_set.add`, `model_set.set`, `model_set.remove`, `model_set.move`, `model_set.select`, `model_set.list` +- Measure: `measure.add_distance`, `measure.add_size`, `measure.add_angle`, `measure.set`, `measure.remove`, `measure.clear`, `measure.list`, `measure.pick`, `measure.render` - App: `app.version`, `app.catalogue` - Selection: `selection.set`, `selection.clear` - History: `history.undo`, `history.redo`, `history.begin_group`, `history.end_group`, `history.abandon_group`, `history.barrier` @@ -27,6 +34,9 @@ Generated from the engine's command catalogue (formshot 0.8.0) by `./formshot ag - Handoff: `handoff.inspect`, `handoff.open` - Library: `library.list`, `library.get`, `library.favorite`, `library.recent`, `library.apply`, `library.save`, `library.remove`, `library.thumbnail`, `library.thumbnails` - Denoise: `denoise.status`, `denoise.oidn_status`, `denoise.oidn_device`, `denoise.oidn_release` +- Template: `template.list`, `template.get`, `template.save`, `template.remove`, `template.preview`, `template.apply`, `template.capture` +- Video: `video.ffmpeg`, `video.encode` +- Transport: `transport.features` - Nodes: `node.set_visible`, `node.set_locked`, `node.rename`, `node.remove` - Undo: `undo` - Redo: `redo` @@ -81,7 +91,7 @@ Add a light node (area rectangle, area disc, point, spot or sun). Add a cutaway volume (plane, box, sphere or cylinder) that clips parts. -- `cutaway`: object; fields cap, enabled, shape, targets +- `cutaway`: object; fields cap, enabled, invert, shape, targets - `id`: integer; range 1 to inf; Id for the new node; allocated when absent - `index`: integer; range 0 to inf; Position among the siblings; last when absent - `name`: string; Name @@ -90,7 +100,7 @@ Add a cutaway volume (plane, box, sphere or cylinder) that clips parts. ## scene.remove -Remove nodes with everything under them. +Remove nodes with everything under them; cutaways, variants, model sets, shots, rigs, tracks, measurements and configurator actions stop naming them in the same undo step. - `ids`: array of integer; required; Nodes to remove with their descendants @@ -171,7 +181,22 @@ Change a light node's settings; give only the fields to change. Change a cutaway node's settings; give only the fields to change. - `id`: integer; required; range 1 to inf; Node -- `values`: object; required; Only the fields to change; fields cap, enabled, shape, targets +- `values`: object; required; Only the fields to change; fields cap, enabled, invert, shape, targets + +## cutaway.set_enabled + +Turn cutaways on or off. + +- `enabled`: boolean; required; Whether they cut +- `ids`: array of integer; required; Cutaway nodes + +## cutaway.set_targets + +Set, add to, remove from or clear the nodes cutaways cut (an empty list cuts every part); a group stands for its descendants. + +- `ids`: array of integer; required; Cutaway nodes +- `nodes`: array of integer; Nodes; a group stands for its descendants +- `op`: string (set | add | remove | clear); set replaces the list (default) ## scene.reparent @@ -184,7 +209,7 @@ Move nodes under another parent (or to the root), keeping their world placement ## scene.duplicate -Copy nodes with their children; copies share meshes and materials. +Copy nodes with their children; copies share meshes and materials, and cutaways, variants, model sets, shots and configurator actions treat each copy as its original. - `ids`: array of integer; required; Nodes to copy - `new_ids`: array of integer; Ids for the copies in pre-order; allocated when empty @@ -216,14 +241,14 @@ Create a material, from a material type's preset when type is given. - `key`: integer; range 1 to inf; Key; allocated when absent - `material`: object; fields graph, labels, name, params, slots, textures, type_id - `name`: string; Name; the type's name when absent -- `type`: string (generic | plastic | plastic_clear | metal | metal_brushed | paint | paint_metallic | glass | glass_thin | liquid | gem | rubber | fabric | ceramic | diffuse | emissive | wood | stone); Start from this material type's preset (ignores material) +- `type`: string (generic | plastic | plastic_clear | metal | metal_brushed | paint | paint_metallic | glass | glass_thin | liquid | gem | rubber | fabric | ceramic | diffuse | emissive | wood | stone | translucent | volume); Start from this material type's preset (ignores material) ## material.set_params Change a material's surface parameters; give only the fields to change. - `key`: integer; required; range 1 to inf; Material -- `values`: object; required; Only the parameters to change; fields base_color, base_diffuse_roughness, base_metalness, base_weight, coat_color, coat_darkening, coat_ior, coat_roughness, coat_weight, emission_color, emission_luminance, fuzz_color, fuzz_roughness, fuzz_weight, geometry_opacity, geometry_thin_walled, specular_color, specular_ior, specular_roughness, specular_roughness_anisotropy, specular_weight, subsurface_color, subsurface_radius, subsurface_radius_scale, subsurface_weight, thin_film_ior, thin_film_thickness, thin_film_weight, transmission_color, transmission_depth, transmission_dispersion_abbe_number, transmission_dispersion_scale, transmission_weight +- `values`: object; required; Only the parameters to change; fields base_color, base_diffuse_roughness, base_metalness, base_weight, coat_color, coat_darkening, coat_ior, coat_roughness, coat_weight, edge_other_parts, edge_radius, emission_color, emission_luminance, fibre_clumping, fibre_color, fibre_comb, fibre_comb_direction, fibre_curl, fibre_density, fibre_length, fibre_own_color, fibre_radial_roughness, fibre_randomness, fibre_root_width, fibre_roughness, fibre_seed, fibre_tip_width, fuzz_color, fuzz_roughness, fuzz_weight, geometry_opacity, geometry_thin_walled, medium_priority, specular_color, specular_ior, specular_roughness, specular_roughness_anisotropy, specular_weight, subsurface_color, subsurface_radius, subsurface_radius_scale, subsurface_scatter_anisotropy, subsurface_weight, thin_film_ior, thin_film_thickness, thin_film_weight, transmission_color, transmission_depth, transmission_dispersion_abbe_number, transmission_dispersion_scale, transmission_scatter, transmission_scatter_anisotropy, transmission_weight ## material.set_type @@ -309,7 +334,7 @@ Rename a material. ## material.remove -Remove a material; parts wearing it fall back to the default material. +Remove a material; parts wearing it fall back to the default material. Refused while a variant or a configurator choice puts it on parts. - `key`: integer; required; range 1 to inf; Material @@ -479,7 +504,7 @@ Change the image style (exposure, white balance, tones, saturation, contrast, bl Change resolution, samples, bounces, seed and denoising. -- `values`: object; required; Only the fields to change; fields ao_distance, denoise, denoising, height, max_bounces, passes, samples, seed, width +- `values`: object; required; Only the fields to change; fields ao_distance, denoise, denoising, height, max_bounces, motion_blur, passes, samples, seed, transport, width ## units.set_display @@ -493,6 +518,457 @@ Change document metadata (name, author, description). - `values`: object; required; Only the fields to change; fields author, description, name, writer +## anim.add_rig + +Add a rig (turntable, orbit or camera_path): motion made from a few settings; fields left out take their defaults and the animation's range. + +- `index`: integer; range 0 to inf; Position in the rig list; last when absent +- `rig`: value; required; A rig with its kind: turntable, orbit or camera_path; fields left out take their defaults + +## anim.set_rig + +Change a rig; give only the fields to change (null clears an optional one); its id and kind stay. + +- `id`: string; required; Rig id +- `values`: object; required; Fields to change; null clears an optional one; fields camera, closed, direction, ease_in, ease_out, end, look_at, name, node, points, roll, start, start_angle, turns + +## anim.remove_rig + +Remove a rig. + +- `id`: string; required; Rig id + +## anim.turntable + +Turn the product (or one node) about its centre as a seamless loop over the animation's range; frames or seconds set the range to exactly that many frames, the turn spanning one frame more so no frame repeats. + +- `direction`: string (ccw | cw); Direction seen from above: ccw (counterclockwise, default) or cw +- `fps`: number; range 1 to 1000; Frames per second; the animation's when absent +- `frames`: integer; range 2 to inf; Frames in the loop: the range becomes exactly this many frames and the turn spans one more, so the loop is seamless +- `id`: string; Id of the new rig; turntable when absent +- `node`: integer; range 1 to inf; Node to turn; the whole product when absent +- `seconds`: number; range 0 to inf; Loop length in seconds when frames is absent (rounded to whole frames) +- `turns`: number; Full turns over the loop (default 1) + +## anim.orbit + +Circle a camera (the active one by default) around the product at its current distance and height, looking at the product's centre, as a loop over the animation's range. + +- `camera`: integer; range 0 to inf; Camera index; the active camera when absent +- `direction`: string (ccw | cw); Direction seen from above: ccw (counterclockwise, default) or cw +- `ease_in`: number; range 0.0 to 1.0; Share of the run spent speeding up from rest (0, the default, starts at full speed) +- `ease_out`: number; range 0.0 to 1.0; Share of the run spent slowing down to rest; ease_in + ease_out at most 1 +- `end`: number; End time in seconds; when absent the animation's end, one frame past it for motion that loops +- `id`: string; Id of the new rig; orbit when absent +- `start`: number; Start time in seconds; the animation's start when absent +- `turns`: number; Full turns from start to end (default 1) + +## anim.camera_path + +Move a camera (the active one by default) along a smooth curve through points at constant speed over the animation's range, looking at a point, a node or the product's centre. + +- `camera`: integer; range 0 to inf; Camera index; the active camera when absent +- `closed`: boolean; The curve returns smoothly to its first point +- `ease_in`: number; range 0.0 to 1.0; Share of the run spent speeding up from rest (0, the default, starts at full speed) +- `ease_out`: number; range 0.0 to 1.0; Share of the run spent slowing down to rest; ease_in + ease_out at most 1 +- `end`: number; End time in seconds; when absent the animation's end, one frame past it for motion that loops +- `id`: string; Id of the new rig; path when absent +- `look_at`: value; What the camera looks at: {"point": [x, y, z]} or {"node": id} (its centre, following it); the product's centre when absent +- `points`: array of array; required; Control points [x, y, z] in metres; the curve passes through each (2 or more, 3 or more when closed) +- `roll`: number; Roll in degrees about the viewing direction; positive banks to the right +- `start`: number; Start time in seconds; the animation's start when absent + +## config.add_option + +Add a configurator option (something the customer chooses, such as colour or trim), optionally with its first choices and a default; the id is option when not given. + +- `choices`: array of object; Choices to start with +- `default`: string; Choice in force while nothing is selected; the first choice when absent (letters, digits, _, - and .) +- `id`: string; Option id; option with the lowest free number when absent (letters, digits, _, - and .) +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `name`: string; Name shown to the customer; Option when empty + +## config.set_option + +Rename a configurator option or change its default choice (null clears it). + +- `default`: ['string', 'null']; New default choice id; null clears it +- `name`: string; New name +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.remove_option + +Remove a configurator option with its choices and every rule that names it; the scene is not changed. + +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.move_option + +Move a configurator option to another position in the list. + +- `index`: integer; required; range 0 to inf; New position (clamped) +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.add_choice + +Add a choice to a configurator option with the actions choosing it runs (variant, model_set, shot, show, hide, material); the id is choice when not given. + +- `actions`: array of value; What choosing it does, in order +- `id`: string; Choice id; choice with the lowest free number in the option when absent (letters, digits, _, - and .) +- `index`: integer; range 0 to inf; Position in the option; last when absent +- `name`: string; Name shown to the customer; Choice when empty +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.set_choice + +Rename a configurator choice or replace its actions; give only what changes. + +- `actions`: array of value; New action list; replaces the old one +- `choice`: string; required; Choice id (letters, digits, _, - and .) +- `name`: string; New name +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.remove_choice + +Remove a choice from a configurator option; rules it triggers go, and it leaves the choice lists of rules on its option (a rule left with none goes). + +- `choice`: string; required; Choice id (letters, digits, _, - and .) +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.move_choice + +Move a choice to another position in its configurator option. + +- `choice`: string; required; Choice id (letters, digits, _, - and .) +- `index`: integer; required; range 0 to inf; New position in the option (clamped) +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.add_rule + +Add a configurator rule: while option is on choice, target requires one of choices (kind requires) or none of them (kind excludes); the id is rule when not given. + +- `choice`: string; required; The triggering choice (letters, digits, _, - and .) +- `choices`: array of string; required; Choices of the target option +- `id`: string; Rule id; rule with the lowest free number when absent (letters, digits, _, - and .) +- `kind`: string (requires | excludes); default "requires"; requires: target must be on one of choices; excludes: on none of them +- `option`: string; required; Option whose choice triggers the rule (letters, digits, _, - and .) +- `target`: string; required; Option the rule restricts (another option) (letters, digits, _, - and .) + +## config.remove_rule + +Remove a configurator rule. + +- `rule`: string; required; Rule id (letters, digits, _, - and .) + +## config.select + +Choose one choice of a configurator option and run its actions; options a rule now forbids move to their first allowed choice and run theirs, all as one undo step. + +- `choice`: string; required; Choice id (letters, digits, _, - and .) +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.apply + +Set a whole configuration at once (choice per option; options left out keep their choice where the rules allow) and run every option's actions in option order, as one undo step. + +- `selection`: object; required; Choice id per option id + +## shot.add + +Save the current view as a named shot: the active camera with its lens, image style, environment and ground, render settings, each light's on, power and colour, every node's visibility and the chosen variants; include picks what applying it restores. + +- `id`: string; Id for the new shot; the lowest free shot when absent +- `include`: value; What applying the shot restores: an object of the flags to change (camera, image, environment with the ground, render, lights, visibility, variants; all on for a new shot), or a list of the parts to include +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `name`: string; Name; Shot when absent + +## shot.update + +Recapture a shot from the current document, keeping its id and name; include changes its flags at the same time. + +- `id`: string; required; Shot id (shot.list lists them) +- `include`: value; What applying the shot restores: an object of the flags to change (camera, image, environment with the ground, render, lights, visibility, variants; all on for a new shot), or a list of the parts to include + +## shot.set + +Rename a shot or change its include flags; the captured state is kept. + +- `id`: string; required; Shot id (shot.list lists them) +- `include`: value; What applying the shot restores: an object of the flags to change (camera, image, environment with the ground, render, lights, visibility, variants; all on for a new shot), or a list of the parts to include +- `name`: string; New name + +## shot.remove + +Remove a shot. + +- `id`: string; required; Shot id (shot.list lists them) + +## shot.move + +Move a shot to another position in the list. + +- `id`: string; required; Shot id (shot.list lists them) +- `index`: integer; required; range 0 to inf; New position in the list (clamped) + +## shot.duplicate + +Copy a shot; the copy goes right after it with a new id. + +- `id`: string; required; Shot id (shot.list lists them) +- `name`: string; Name of the copy; the original's name with " copy" when absent +- `new_id`: string; Id of the copy; the lowest free shot when absent + +## shot.apply + +Restore the parts of a shot its include flags name, as one undo step; lights and nodes that no longer exist are skipped and listed. + +- `id`: string; required; Shot id (shot.list lists them) + +## variant.add_set + +Add a material variant set (such as Colourway) covering parts; a group stands for its descendant parts. + +- `id`: ['string', 'integer']; Id of the new set; set1, set2, ... when absent +- `index`: integer; range 0 to inf; Position among the sets; last when absent +- `name`: string; required; Name, such as Colourway +- `parts`: array of ['integer', 'string']; Covered nodes (ids as numbers or decimal strings); a group stands for its descendant parts + +## variant.set_set + +Rename a variant set or change the parts it covers; give only the fields to change. + +- `name`: string; New name +- `parts`: array of ['integer', 'string']; New covered nodes; variant entries for parts no longer covered are dropped +- `set`: ['string', 'integer']; required; Variant set id + +## variant.remove_set + +Remove a variant set with its variants; the parts keep the materials they wear. + +- `set`: ['string', 'integer']; required; Variant set id + +## variant.capture + +Add a variant to a set from the materials its covered parts wear now, and make it the active one. + +- `id`: ['string', 'integer']; Id of the new variant; variant1, variant2, ... within the set when absent +- `index`: integer; range 0 to inf; Position in the set; last when absent +- `name`: string; Name; Variant when absent +- `set`: ['string', 'integer']; required; Variant set id + +## variant.add + +Add a variant to a set: one material for every covered part, or a material per part or group. + +- `id`: ['string', 'integer']; Id of the new variant; variant1, variant2, ... within the set when absent +- `index`: integer; range 0 to inf; Position in the set; last when absent +- `materials`: value; The variant's materials; absent for an empty variant: one material key every covered part wears, an object from part or group id to material key (a group stands for its descendant parts), or a list of {part, material} +- `name`: string; required; Name, such as Graphite +- `set`: ['string', 'integer']; required; Variant set id + +## variant.set + +Rename a variant or replace its materials; give only the fields to change. + +- `id`: ['string', 'integer']; required; Variant id +- `materials`: value; New materials, replacing the old ones: one material key every covered part wears, an object from part or group id to material key (a group stands for its descendant parts), or a list of {part, material} +- `name`: string; New name +- `set`: ['string', 'integer']; required; Variant set id + +## variant.remove + +Remove a variant from its set; the parts keep the materials they wear. + +- `id`: ['string', 'integer']; required; Variant id +- `set`: ['string', 'integer']; required; Variant set id + +## variant.move + +Move a variant within its set, or the set among the sets when no variant id is given. + +- `id`: ['string', 'integer']; Variant to move within the set; without it the set moves among the sets +- `index`: integer; required; range 0 to inf; New position +- `set`: ['string', 'integer']; required; Variant set id + +## variant.select + +Choose a set's variant: its parts put on the variant's materials as one step; missing parts and materials are skipped (variant.diff lists them). + +- `set`: ['string', 'integer']; required; Variant set id +- `variant`: ['string', 'integer']; required; Variant id + +## model_set.add + +Add a model set (such as Open lid) listing the nodes it shows; without nodes, the product nodes visible now under the roots. + +- `id`: ['string', 'integer']; Id of the new model set; model1, model2, ... when absent +- `index`: integer; range 0 to inf; Position among the model sets; last when absent +- `name`: string; required; Name, such as Open lid +- `nodes`: array of ['integer', 'string']; Nodes it shows; when absent, the visible part and group children of each visible root (a part root itself), leaving lights and cutaways out + +## model_set.set + +Rename a model set or replace the nodes it shows; give only the fields to change. + +- `id`: ['string', 'integer']; required; Model set id +- `name`: string; New name +- `nodes`: array of ['integer', 'string']; New list of nodes it shows + +## model_set.remove + +Remove a model set; every node keeps its visibility. + +- `id`: ['string', 'integer']; required; Model set id + +## model_set.move + +Move a model set among the model sets. + +- `id`: ['string', 'integer']; required; Model set id +- `index`: integer; required; range 0 to inf; New position + +## model_set.select + +Choose a model set as one step: show its nodes and hide the nodes of the other model sets; nodes in no model set are left alone. + +- `id`: ['string', 'integer']; required; Model set id + +## variant.apply_choice + +Apply a stored choice as one step: a variant per set (in the document's set order), then a model set; sets, variants and model sets that no longer exist are skipped. + +- `model_set`: ['string', 'null']; Model set id +- `variants`: object; Variant id by variant set id + +## anim.set + +Change the animation timeline: frames per second, start and end in seconds; give only the fields to change. + +- `end`: number; End of the timeline (its last frame), seconds +- `fps`: number; range -inf to 240.0; Frames per second (default 30) +- `start`: number; Start of the timeline, seconds + +## anim.key + +Key a target (a node's translation, rotation or scale, a camera field, a material parameter, a light field or a node's visibility) at a time; without a value it keys the value the target has at that time. Replaces a key already at that time. + +- `id`: string; Key id; the key at that time, or a new id, when absent +- `interpolation`: string (step | linear | smooth | ease); To the next key: step holds, linear goes straight, smooth is a monotone cubic through the keys (no overshoot), ease stops at both keys +- `target`: value; required; What the key drives +- `time`: number; required; Seconds +- `track`: string; Track id for a new track; chosen when absent +- `value`: value; A number; true or false for switches; [x, y, z] for vectors; [r, g, b] (ACEScg) or an sRGB hex string for colours; [x, y, z, w] or Euler degrees [x, y, z] for rotations + +## anim.set_key + +Change one key's time, value or interpolation (step, linear, smooth, ease); name the track or its target, and the key or its time. + +- `at`: number; Time of the key, within half a frame (instead of key) +- `interpolation`: string (step | linear | smooth | ease); To the next key: step holds, linear goes straight, smooth is a monotone cubic through the keys (no overshoot), ease stops at both keys +- `key`: string; Key id (or give at) +- `target`: value; What the key drives +- `time`: number; New time, seconds +- `track`: string; Track id (or give target) +- `value`: value; A number; true or false for switches; [x, y, z] for vectors; [r, g, b] (ACEScg) or an sRGB hex string for colours; [x, y, z, w] or Euler degrees [x, y, z] for rotations + +## anim.remove_key + +Remove one key; a track left without keys is removed. + +- `at`: number; Time of the key, within half a frame (instead of key) +- `key`: string; Key id (or give at) +- `target`: value; What the key drives +- `track`: string; Track id (or give target) + +## anim.move_key + +Move one key to another time; drags of the same key merge into one undo step. + +- `at`: number; Time of the key, within half a frame (instead of key) +- `key`: string; Key id (or give at) +- `target`: value; What the key drives +- `time`: number; required; New time, seconds +- `track`: string; Track id (or give target) + +## anim.remove_track + +Remove a track with all its keys; the target keeps its stored value. + +- `target`: value; What the key drives +- `track`: string; Track id (or give target) + +## anim.clear + +Remove every keyed track; with all true also remove the rigs and reset the timeline, leaving no animation. + +- `all`: boolean; Also remove the rigs and reset the timeline + +## measure.add_distance + +Add a distance between two points, each pinned to a part in the part's own space (it follows the part) or free in the world; points are given in world space as picked; the id is distance when not given. + +- `a`: object; required; First point: a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `axis`: string (direct | x | y | z); default "direct"; direct (the straight line) or only the part along the world x, y (up) or z axis +- `b`: object; required; Second point: a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `id`: string; Id; the lowest free distance when absent +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `label`: object; Label options; give only the ones to change; fields hidden, precision, show_name +- `name`: string; Name; Distance when absent +- `visible`: boolean; default true; Shown in the viewport and in renders that draw measurements + +## measure.add_size + +Add a size box: the width (x), height (y) and depth (z) of the bounds of nodes together, in world axes or the first node's own axes; the id is size when not given. + +- `frame`: string (world | local); default "world"; world axes (width x, height y, depth z) or the first node's own axes +- `id`: string; Id; the lowest free size when absent +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `label`: object; Label options; give only the ones to change; fields hidden, precision, show_name +- `name`: string; Name; Size when absent +- `nodes`: array of ['integer', 'string']; required; Nodes measured together; a group stands for its parts +- `visible`: boolean; default true; Shown in the viewport and in renders that draw measurements + +## measure.add_angle + +Add an angle at a vertex between the lines to two points, each pinned to a part or free; the id is angle when not given. + +- `a`: object; required; End of the first arm: a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `b`: object; required; End of the second arm: a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `id`: string; Id; the lowest free angle when absent +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `label`: object; Label options; give only the ones to change; fields hidden, precision, show_name +- `name`: string; Name; Angle when absent +- `vertex`: object; required; Corner of the angle: a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `visible`: boolean; default true; Shown in the viewport and in renders that draw measurements + +## measure.set + +Change a measurement (name, visibility, label options, points, axis, nodes or frame; give only what changes), or without id the document's label precision. + +- `a`: object; New first point (distance, angle): a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `axis`: string (direct | x | y | z); default "direct"; direct (the straight line) or only the part along the world x, y (up) or z axis +- `b`: object; New second point (distance, angle): a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `frame`: string (world | local); default "world"; world axes (width x, height y, depth z) or the first node's own axes +- `id`: string; Measurement to change; absent to change the document's precision +- `label`: object; Label options; give only the ones to change; fields hidden, precision, show_name +- `name`: string; New name +- `nodes`: array of ['integer', 'string']; Nodes measured together; a group stands for its parts +- `precision`: integer; range 0 to 6; Without id: digits after the decimal point of every label that does not set its own (default 1) +- `vertex`: object; New corner (angle): a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `visible`: boolean; Show or hide + +## measure.remove + +Remove a measurement. + +- `id`: string; required; Measurement id (measure.list lists them) + +## measure.clear + +Remove every measurement as one undo step. + +- `keep_precision`: boolean; default true; Keep the document's precision; false resets it to 1 + ## app.version Engine, format and catalogue versions. @@ -592,6 +1068,7 @@ Open a .fshot project, or a model file as a new document with the file.import op - `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group - `path`: string; required; A .fshot project, or a model file (glb, gltf, obj, stl, ply, 3mf, fbx, step, stp, iges, igs) opened as a new document; the other options apply to a model only - `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `template`: string; Material template id (template.list) applied to the imported parts when the import finishes, in the same undo step - `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size - `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y @@ -613,6 +1090,7 @@ Import a model (glb, gltf, obj, stl, ply, 3mf, fbx, step, iges) with clean-up as - `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group - `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker - `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `template`: string; Material template id (template.list) applied to the imported parts when the import finishes, in the same undo step - `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size - `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y @@ -814,6 +1292,7 @@ Start importing a model in the background with the file.import options and retur - `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group - `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker - `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `template`: string; Material template id (template.list) applied to the imported parts when the import finishes, in the same undo step - `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size - `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y @@ -1117,7 +1596,7 @@ Note: read-only. ## render.queue_add -Queue a final render of the current document (as it is now) or of a saved project: camera (index, name, active or all), size, samples, passes, denoise, device, output folder, file name template and format (one multi-layer exr, one layered psd, or one png, jpeg or tiff per pass). Jobs render one at a time in the background while the viewport keeps working; files appear only when complete. Answers the new jobs and the queue. +Queue a final render of the current document (as it is now) or of a saved project: camera (index, name, active or all), size, samples, passes, denoise, device, output folder, file name template and format (one multi-layer exr, one layered psd, or one png, jpeg or tiff per pass); measurements true draws the visible measurements into the beauty. Jobs render one at a time in the background while the viewport keeps working; files appear only when complete. Answers the new jobs and the queue. - `alpha`: boolean; Write an alpha channel with the beauty; on for a transparent background when absent (never in jpeg) - `ao_distance`: number; range -inf to 1000; Reach of the ambient_occlusion pass in metres @@ -1132,6 +1611,7 @@ Queue a final render of the current document (as it is now) or of a saved projec - `frame`: integer; default 1; range 0 to inf; Value of the {frame} token (4 digits) - `height`: integer; range 1 to 16384; Output height; the document's when absent - `label`: string; Free text shown in the list +- `measurements`: boolean; default false; Draw the document's visible measurements into the beauty (lines, end ticks and labels, as measure.render does; pinhole and orthographic cameras) - `name`: string; File name template without extension; tokens {project} {camera} {pass} {date} {time} {frame} {job} {width} {height} {samples}; default {project}_{camera}_{pass} - `overwrite`: boolean; Replace existing files; otherwise _2, _3, ... is added - `passes`: array of string; Passes written beside the beauty (names or groups); the document's render.passes when absent @@ -1227,6 +1707,310 @@ Free Open Image Denoise's device and the filters it keeps per picture size (thei - no parameters +## shot.list + +The document's shots in order: each one's id, name, include flags, a short summary of what it restores, whether the document matches it now, and the nodes it names that are gone (skipped when applied). id lists one shot; full adds the captured state. + +- `full`: boolean; default false; Add each shot's captured state (camera, image style, environment, ground, render settings, lights, visibility, variants) under state +- `id`: string; Only this shot + +Note: read-only. + +## shot.render + +Queue one final render per shot (the given ids, or every shot), each of a copy of the document with that shot applied; the document itself is not changed. Takes render.queue_add's output, size, samples, passes, camera and device arguments; the file name's {shot} token is the shot's name (default name {project}_{shot}_{pass}). Answers the new jobs and the queue. + +- `alpha`: boolean; Write an alpha channel with the beauty; on for a transparent background when absent (never in jpeg) +- `ao_distance`: number; range -inf to 1000; Reach of the ambient_occlusion pass in metres +- `camera`: value; Camera index, camera name, active (the default: the document's camera as it is now) or all (one job per camera) +- `compression`: string; exr: none, zips, zip (default), piz; tiff: none, deflate (default); psd: raw, rle, zip (default) +- `denoise`: boolean; Denoise the beauty with the document's render.denoising (denoiser, quality_final, strength); the document's render.denoise when absent +- `depth`: integer (8 | 16); default 8; Bits per channel of png, psd and integer tiff +- `device`: string; cpu, gpu (the best adapter) or gpu:; the session's render device when absent. A GPU that cannot render the scene falls back to the CPU with a note. +- `float`: boolean; tiff only: 32-bit float scene-linear instead of display-referred integers +- `folder`: string; required; Absolute output folder; created when missing. The engine writes nowhere else. +- `format`: string (exr | psd | png | jpeg | tiff); default "png"; exr: one multi-layer OpenEXR (scene-linear ACEScg); psd: one layered Photoshop file; png, jpeg, tiff: one file per pass +- `frame`: integer; default 1; range 0 to inf; Value of the {frame} token (4 digits) +- `height`: integer; range 1 to 16384; Output height; the document's when absent +- `ids`: array of string; Shots to render, in this order; every shot in list order when absent +- `label`: string; Free text shown in the list; "Shot: " when absent +- `measurements`: boolean; default false; Draw the document's visible measurements into the beauty (lines, end ticks and labels, as measure.render does; pinhole and orthographic cameras) +- `name`: string; File name template without extension; tokens {project} {shot} {camera} {pass} {date} {time} {frame} {job} {width} {height} {samples} {config} {variant}; default {project}_{shot}_{pass} +- `overwrite`: boolean; Replace existing files; otherwise _2, _3, ... is added +- `passes`: array of string; Passes written beside the beauty (names or groups); the document's render.passes when absent +- `precision`: string (half | float); default "half"; exr colour precision (depth, position, ids and Cryptomatte are always float) +- `quality`: integer; range 1 to 100; jpeg quality (default 90) +- `samples`: integer; range 1 to 1048576; Samples per pixel; the document's when absent +- `seed`: integer; range 0 to inf; Sampler seed; the document's when absent +- `transparent`: boolean; Transparent background; the document's background when absent +- `width`: integer; range 1 to 16384; Output width; the document's when absent + +## variant.list + +Material variant sets: each set's covered parts with names, its variants (id, name, active, whether the parts wear it now, a swatch colour from the material most of its parts wear, and every part and material with any that would be skipped) and the active variant; the active model set; materials only variants use are listed in variant_materials. + +- no parameters + +Note: read-only. + +## model_set.list + +Model sets in order: id, name, active, whether the scene shows exactly its nodes now, and its nodes with name, kind, visibility and any that no longer exist. + +- no parameters + +Note: read-only. + +## variant.diff + +What choosing a variant would change, without changing anything: the parts whose material would change (from and to), the parts already wearing theirs, and the entries variant.select would skip with the reason (missing_part, not_a_part, locked, missing_material). + +- `set`: ['string', 'integer']; required; Variant set id +- `variant`: ['string', 'integer']; required; Variant id + +Note: read-only. + +## config.get + +The configurator: options with their choices and actions, the choice in force for each, whether each choice keeps every rule with the other options as they are (allowed; config.select on a choice that is not moves other options), the rules, and the current configuration's name and whether it keeps every rule. + +- no parameters + +Note: read-only. + +## config.check + +Problems with the configurator: rules naming missing options or choices, options with no valid choice, choices that no valid configuration can use, a current configuration that breaks a rule, and actions naming missing nodes, materials, variants, model sets or shots. ok is true when there are none. + +- no parameters + +Note: read-only. + +## config.list + +Every valid configuration (one choice per option that keeps every rule), in option and choice order, up to limit, with the total count. Each has a name made from option and choice names and its selection for config.apply. + +- `limit`: integer; default 100; range 1 to 10000; Most configurations listed; the count covers them all + +Note: read-only. + +## config.render_all + +Queue one final render per valid configuration (up to limit): each renders a copy of the document with that configuration applied, so the open document never changes. Takes render.queue_add's arguments; file names may use {config} and {variant}, and default to {project}_{config}_{pass}. Answers the new jobs. + +- `alpha`: boolean; Write an alpha channel with the beauty; on for a transparent background when absent (never in jpeg) +- `ao_distance`: number; range -inf to 1000; Reach of the ambient_occlusion pass in metres +- `camera`: value; Camera index, camera name, active (the default: the document's camera as it is now) or all (one job per camera) +- `compression`: string; exr: none, zips, zip (default), piz; tiff: none, deflate (default); psd: raw, rle, zip (default) +- `denoise`: boolean; Denoise the beauty with the document's render.denoising (denoiser, quality_final, strength); the document's render.denoise when absent +- `depth`: integer (8 | 16); default 8; Bits per channel of png, psd and integer tiff +- `device`: string; cpu, gpu (the best adapter) or gpu:; the session's render device when absent. A GPU that cannot render the scene falls back to the CPU with a note. +- `float`: boolean; tiff only: 32-bit float scene-linear instead of display-referred integers +- `folder`: string; required; Absolute output folder; created when missing. The engine writes nowhere else. +- `format`: string (exr | psd | png | jpeg | tiff); default "png"; exr: one multi-layer OpenEXR (scene-linear ACEScg); psd: one layered Photoshop file; png, jpeg, tiff: one file per pass +- `frame`: integer; default 1; range 0 to inf; Value of the {frame} token (4 digits) +- `height`: integer; range 1 to 16384; Output height; the document's when absent +- `label`: string; Free text shown in the list +- `limit`: integer; default 100; range 1 to 10000; Most configurations queued, in list order +- `measurements`: boolean; default false; Draw the document's visible measurements into the beauty (lines, end ticks and labels, as measure.render does; pinhole and orthographic cameras) +- `name`: string; default "{project}_{config}_{pass}"; File name template without extension; render.queue_add's tokens plus {config} (the configuration's name) and {variant} (the active variants) +- `overwrite`: boolean; Replace existing files; otherwise _2, _3, ... is added +- `passes`: array of string; Passes written beside the beauty (names or groups); the document's render.passes when absent +- `precision`: string (half | float); default "half"; exr colour precision (depth, position, ids and Cryptomatte are always float) +- `quality`: integer; range 1 to 100; jpeg quality (default 90) +- `samples`: integer; range 1 to 1048576; Samples per pixel; the document's when absent +- `seed`: integer; range 0 to inf; Sampler seed; the document's when absent +- `transparent`: boolean; Transparent background; the document's background when absent +- `width`: integer; range 1 to 16384; Output width; the document's when absent + +## template.list + +The material templates: FormShot's own from the library's templates folder, then the user's own (user/...), each with its name, description, rule count, file, valid plus error, and the library presets it names that are missing. + +- no parameters + +Note: read-only. + +## template.get + +One material template with its rules in order (field, key, pattern, and the preset or stored material each applies, with the preset's name). + +- `id`: string; required; Template id (cad-materials, user/my-rules) + +Note: read-only. + +## template.save + +Save a material template as one of the user's own (user/), or replace one given id; every pattern is checked and every preset id must be in the library. + +- `description`: string; What the template is for +- `id`: string; Replace this user template (user/...) instead of saving a new one +- `name`: string; required; Template name +- `rules`: array of object; required; Rules in order; the first rule matching a part decides its material + +## template.remove + +Delete one of the user's own material templates; FormShot's own cannot be removed. + +- `id`: string; required; Id of one of the user's own templates (user/...) + +## template.preview + +Which material a template would put on each part without changing anything: per part its source material name, current material, the first rule matching it and the target, with counts of matched, unmatched and changing parts and the parts per rule. + +- `id`: string; required; Template id +- `parts`: array of ['integer', 'string']; Parts or groups whose parts to look at (every part when absent) + +Note: read-only. + +## template.apply + +Apply a material template as one undo step: each part takes the material of the first rule matching it (a library preset built as library.apply builds it, or the template's stored material; an identical document material is reused), parts no rule matches keep theirs, and each changed part keeps its original material name in source.material. + +- `id`: string; required; Template id +- `parts`: array of ['integer', 'string']; Parts or groups whose parts the template dresses (every part when absent) + +## template.capture + +A material template from the current document: one rule per distinct source material name on parts, applying the material those parts wear now, stored in the template (textures left out); answered with notes, and saved as a user template when save is true. + +- `description`: string; What the template is for +- `name`: string; required; Name of the captured template +- `save`: boolean; default false; Also save it as one of the user's templates (otherwise only answered, ready for template.save) + +## measure.list + +Every measurement in order with its current world points (a distance's two ends; an angle's vertex and arm ends; a size box's eight corners), its value in metres or degrees and as text in the document's display unit, its definition, and the nodes it names that are gone (missing; the value is null then). id lists one. + +- `id`: string; Only this measurement +- `visible_only`: boolean; default false; Leave out hidden measurements + +Note: read-only. + +## measure.pick + +The surface point, normal and part under a viewport pixel through the active camera (as view.pick), with the point in the part's own space; snap vertex moves it to the part's nearest vertex within radius pixels. Pass the point and node to measure.add_distance or measure.add_angle. + +- `height`: number; required; range 1 to inf; Viewport height in pixels +- `radius`: number; default 12.0; range 1 to 200; Snap radius in viewport pixels +- `snap`: string (none | vertex); default "none"; vertex moves the point to the picked part's nearest vertex within radius pixels +- `width`: number; required; range 1 to inf; Viewport width in pixels +- `x`: number; required; Viewport x in pixels from the left edge +- `y`: number; required; Viewport y in pixels from the top edge + +Note: read-only. + +## measure.render + +Queue final renders of the document with its visible measurements drawn into the beauty (lines, end ticks and labels in a plain built-in style); render.queue_add (and shot, configurator and frame renders) draw them with measurements true. Takes render.queue_add's output, size, samples, passes, camera and device arguments. + +- `alpha`: boolean; Write an alpha channel with the beauty; on for a transparent background when absent (never in jpeg) +- `ao_distance`: number; range -inf to 1000; Reach of the ambient_occlusion pass in metres +- `camera`: value; Camera index, camera name, active (the default: the document's camera as it is now) or all (one job per camera) +- `compression`: string; exr: none, zips, zip (default), piz; tiff: none, deflate (default); psd: raw, rle, zip (default) +- `denoise`: boolean; Denoise the beauty with the document's render.denoising (denoiser, quality_final, strength); the document's render.denoise when absent +- `depth`: integer (8 | 16); default 8; Bits per channel of png, psd and integer tiff +- `device`: string; cpu, gpu (the best adapter) or gpu:; the session's render device when absent. A GPU that cannot render the scene falls back to the CPU with a note. +- `float`: boolean; tiff only: 32-bit float scene-linear instead of display-referred integers +- `folder`: string; required; Absolute output folder; created when missing. The engine writes nowhere else. +- `format`: string (exr | psd | png | jpeg | tiff); default "png"; exr: one multi-layer OpenEXR (scene-linear ACEScg); psd: one layered Photoshop file; png, jpeg, tiff: one file per pass +- `frame`: integer; default 1; range 0 to inf; Value of the {frame} token (4 digits) +- `height`: integer; range 1 to 16384; Output height; the document's when absent +- `label`: string; Free text shown in the list; "Measured" when absent +- `measurements`: boolean; default false; Draw the document's visible measurements into the beauty (lines, end ticks and labels, as measure.render does; pinhole and orthographic cameras) +- `name`: string; File name template without extension; tokens {project} {camera} {pass} {date} {time} {frame} {job} {width} {height} {samples}; default {project}_{camera}_{pass} +- `overwrite`: boolean; Replace existing files; otherwise _2, _3, ... is added +- `passes`: array of string; Passes written beside the beauty (names or groups); the document's render.passes when absent +- `precision`: string (half | float); default "half"; exr colour precision (depth, position, ids and Cryptomatte are always float) +- `quality`: integer; range 1 to 100; jpeg quality (default 90) +- `samples`: integer; range 1 to 1048576; Samples per pixel; the document's when absent +- `seed`: integer; range 0 to inf; Sampler seed; the document's when absent +- `transparent`: boolean; Transparent background; the document's background when absent +- `width`: integer; range 1 to 16384; Output width; the document's when absent + +## anim.seek + +Show the animation at a time (seconds) or a frame number: the viewport restarts at that time and renders use it; time null shows the document's stored values again. The document does not change. + +- `frame`: integer; range 0 to inf; Frame number counted from the timeline's start (instead of time) +- `time`: value; Seconds; null shows the stored values again + +## anim.status + +The animation's timeline and the time shown: time and frame, start, end, fps, frame count, each track with its target, key times, values and interpolations and the key sitting at the time shown (key_at_time), and the rigs (each with id, kind, name, start, end, node or camera and its other fields; rig_count counts them). + +- no parameters + +Note: read-only. + +## anim.sample + +Values of one target over a list of times (every frame when times is absent), as the renderer would see them, with the times of its keys; rotations also as Euler degrees. For drawing curves in a timeline. + +- `target`: value; required; What the key drives +- `times`: array of number; Seconds; every frame of the timeline when absent + +Note: read-only. + +## anim.render + +Render frames of the animation through the render queue, one job per frame (each with its own progress and cancel), named {project}_{camera}_{frame} by default with 4-digit frame numbers; with video, a movie job after the frames encodes them with ffmpeg into mp4, webm, mov or gif and reports the encoder, the movie's path and any ffmpeg error. Takes every render.queue_add argument but frame and project. + +- `alpha`: boolean; Write an alpha channel with the beauty; on for a transparent background when absent (never in jpeg) +- `ao_distance`: number; range -inf to 1000; Reach of the ambient_occlusion pass in metres +- `camera`: value; Camera index, camera name, active (the default: the document's camera as it is now) or all (one job per camera) +- `compression`: string; exr: none, zips, zip (default), piz; tiff: none, deflate (default); psd: raw, rle, zip (default) +- `denoise`: boolean; Denoise the beauty with the document's render.denoising (denoiser, quality_final, strength); the document's render.denoise when absent +- `depth`: integer (8 | 16); default 8; Bits per channel of png, psd and integer tiff +- `device`: string; cpu, gpu (the best adapter) or gpu:; the session's render device when absent. A GPU that cannot render the scene falls back to the CPU with a note. +- `float`: boolean; tiff only: 32-bit float scene-linear instead of display-referred integers +- `folder`: string; required; Absolute output folder; created when missing. The engine writes nowhere else. +- `format`: string (exr | psd | png | jpeg | tiff); default "png"; exr: one multi-layer OpenEXR (scene-linear ACEScg); psd: one layered Photoshop file; png, jpeg, tiff: one file per pass +- `frames`: array of integer; [first, last] frame numbers to render, 1 being the animation's start; the whole range when absent +- `height`: integer; range 1 to 16384; Output height; the document's when absent +- `label`: string; Free text shown in the list +- `measurements`: boolean; default false; Draw the document's visible measurements into the beauty (lines, end ticks and labels, as measure.render does; pinhole and orthographic cameras) +- `name`: string; File name template of each frame (tokens as render.queue_add; {frame} is the frame number, 4 digits); default {project}_{camera}_{frame} +- `overwrite`: boolean; Replace existing files; otherwise _2, _3, ... is added +- `passes`: array of string; Passes written beside the beauty (names or groups); the document's render.passes when absent +- `precision`: string (half | float); default "half"; exr colour precision (depth, position, ids and Cryptomatte are always float) +- `quality`: integer; range 1 to 100; jpeg quality (default 90) +- `samples`: integer; range 1 to 1048576; Samples per pixel; the document's when absent +- `seed`: integer; range 0 to inf; Sampler seed; the document's when absent +- `step`: integer; default 1; range 1 to inf; Render every step-th frame of the range +- `transparent`: boolean; Transparent background; the document's background when absent +- `video`: object; Encode a movie with ffmpeg after the last frame is written (a movie job queued after the frame jobs); fields folder, format, fps, keep_frames, name, quality +- `width`: integer; range 1 to 16384; Output width; the document's when absent + +## video.ffmpeg + +The ffmpeg program movies are encoded with: whether one is found and where (FORMSHOT_FFMPEG, the Form family's shared install folder, or the PATH), its version, which of FormShot's encoders it lists, the encoder each movie format would use, and the licence of the build. The engine never downloads ffmpeg; the service fetches the family's LGPL build on request. + +- no parameters + +Note: read-only. + +## video.encode + +Queue a movie (mp4, webm, mov or gif) encoded by ffmpeg from frames already on disk (a folder and a file name pattern). The job runs in the render queue: render.queue_list shows its progress, the encoder used, the movie's path and any ffmpeg error; a cancelled job leaves no movie. + +- `alpha`: boolean; Keep the frames' alpha (mov writes ProRes 4444; other formats have none) +- `format`: string (mp4 | webm | mov | gif); mp4: H.264 (a hardware encoder, else libx264 when this ffmpeg has it, else MPEG-4 Part 2); webm: VP9; mov: ProRes 422 (4444 with alpha); gif: palette GIF +- `fps`: number; default 24; range -inf to 240; Frames per second +- `frames`: object; required; fields folder, pattern +- `label`: string; Free text shown in the queue list +- `out`: string; required; Absolute path of the movie; its extension picks the format when format is absent +- `overwrite`: boolean; Replace an existing movie; otherwise _2, _3, ... is added +- `quality`: integer; default 80; range 1 to 100; 1 (smallest file) to 100 (best picture); maps to each encoder's own scale + +## transport.features + +Per light transport feature (spectral, nested_media, volume, subsurface, caustics, cutaways, rounded_edges, fibres, motion_blur): whether the CPU engine renders it, whether the GPU path renders or refuses it (with the refusal code), and whether the open document uses it. A refused scene renders on the CPU. Turn spectral rendering on with render.set_settings values {transport: {spectral: {enabled: true}}}. + +- no parameters + +Note: read-only. + ## node.set_visible Same as scene.set_visible ({id, visible} -> {ids: [id], visible}). @@ -1274,6 +2058,7 @@ Same as file.open ({path} unchanged). - `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group - `path`: string; required; A .fshot project, or a model file (glb, gltf, obj, stl, ply, 3mf, fbx, step, stp, iges, igs) opened as a new document; the other options apply to a model only - `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `template`: string; Material template id (template.list) applied to the imported parts when the import finishes, in the same undo step - `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size - `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y @@ -1289,6 +2074,7 @@ Same as file.import ({path, name?, options?} unchanged). - `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group - `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker - `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `template`: string; Material template id (template.list) applied to the imported parts when the import finishes, in the same undo step - `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size - `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y diff --git a/.claude/skills/formshot-harness/SKILL.md b/.claude/skills/formshot-harness/SKILL.md index f2da3387..5d5d6af5 100644 --- a/.claude/skills/formshot-harness/SKILL.md +++ b/.claude/skills/formshot-harness/SKILL.md @@ -1,15 +1,15 @@ --- name: formshot-harness -description: "Guides work on formshot, the Form-family 3D product renderer by nodemode-ai: Rust engine workspace (fsh-*), CPU and GPU (wgpu, WGSL) path tracers, the live viewport (WebGL2 raster modes, the WebAssembly engine on WebGPU), layered materials, the .fshot project file, MCP tools, FastAPI service, Tauri desktop. Use whenever a task touches the document, commands, undo, the render snapshot, the BVH, BSDFs, sampling, tone mapping, model import (glTF, OBJ, 3MF, FBX, STEP, IGES), hand-offs, material types, slots and graphs, the material library, the .fshot format or journal, the command registry or catalogue, the MCP endpoint or consent, the agent dock, the window shell, Home, the workspace, the service, the Tauri sidecar, doctor and notices runs, version bumps (0.x from 0.8.0), or any file under native/, frontend/src, backend/app, src-tauri or setup/. Enforces project laws (SEDO, zero DOM flicker, z-index tokens, no tests). Not for formsculpt or formsurface." +description: "Guides work on formshot, the Form-family 3D product renderer by nodemode-ai: Rust engine workspace (fsh-*), CPU and GPU (wgpu, WGSL) path tracers, the live viewport (WebGL2 raster modes, the WebAssembly engine on WebGPU), layered materials, the .fshot project file, MCP tools, FastAPI service, Tauri desktop. Use whenever a task touches the document, commands, undo, the render snapshot, the BVH, BSDFs, sampling, tone mapping, model import (glTF, OBJ, 3MF, FBX, STEP, IGES), hand-offs, material types, slots and graphs, the material library, the .fshot format or journal, the command registry or catalogue, the MCP endpoint or consent, the agent dock, the window shell, Home, the workspace, the service, the Tauri sidecar, doctor and notices runs, version bumps (0.x from 0.10.0), or any file under native/, frontend/src, backend/app, src-tauri or setup/. Enforces project laws (SEDO, zero DOM flicker, z-index tokens, no tests). Not for formsculpt or formsurface." license: Apache-2.0 metadata: nodemode.author: nodemode-ai - nodemode.pack-version: "0.8.0" + nodemode.pack-version: "0.10.0" --- # Formshot Harness -formshot is the Form family's 3D product renderer by nodemode-ai (Apache-2.0): open a model, drag materials onto parts, light it, watch a physically based picture converge, then render stills, animations and variants. It is modeled on its siblings formsurface (shell and service), formsculpt (launcher, setup and engine bridge) and formvis (the shared dock). Current state: v0.2.0, unreleased. The shell, the document and project file, the CPU path tracer and the command line render exist; everything else is planned with the version the plan gives it, and the sub-skills mark it planned. Since then the GPU path tracer (fsh-render-gpu, held to the CPU picture), device choice with a fallback to the CPU, the live viewport (WebGL2 raster modes, picking, gizmo, interaction regimes, an optional WebAssembly engine on WebGPU with a streamed fallback) and the engine-driven crash journal have landed. GPU work has run only on software drivers (lavapipe, SwiftShader, llvmpipe), and the path tracer in the window has not drawn a frame yet. After that came import (3MF, FBX, background jobs, reimport, embedded textures), STEP and IGES through FormCAD's kernel worker (fsh-cad), family hand-offs, material types, texture slots, graphs compiled to a material program, and the material library; both path tracers run material programs with textures (loaded by `fsh-commands/src/textures.rs`), image labels, thin film and dispersion. Then lighting (light spread, edge softness, IES profiles, light and shadow links, the Hosek-Wilkie physical sky, studio presets; pins, finite dome, backplate and background image are in the document but still being rendered), cameras (six projections, bladed and anamorphic apertures, pick focus), the image (grade, effects, AgX, ACES 1.3, OpenColorIO through fsh-ocio), 23 render passes with Cryptomatte, image writers in fsh-io, the render queue, and the denoisers (fsh-denoise, optional Open Image Denoise through fsh-oidn) landed; the GPU port of the denoiser is still being merged. Read the code before trusting a claim here. +formshot is the Form family's 3D product renderer by nodemode-ai (Apache-2.0): open a model, drag materials onto parts, light it, watch a physically based picture converge, then render stills, animations and variants. It is modeled on its siblings formsurface (shell and service), formsculpt (launcher, setup and engine bridge) and formvis (the shared dock). Current state: v0.2.0, unreleased. The shell, the document and project file, the CPU path tracer and the command line render exist; everything else is planned with the version the plan gives it, and the sub-skills mark it planned. Since then the GPU path tracer (fsh-render-gpu, held to the CPU picture), device choice with a fallback to the CPU, the live viewport (WebGL2 raster modes, picking, gizmo, interaction regimes, an optional WebAssembly engine on WebGPU with a streamed fallback) and the engine-driven crash journal have landed. GPU work has run only on software drivers (lavapipe, SwiftShader, llvmpipe), and the path tracer in the window has not drawn a frame yet. After that came import (3MF, FBX, background jobs, reimport, embedded textures), STEP and IGES through FormCAD's kernel worker (fsh-cad), family hand-offs, material types, texture slots, graphs compiled to a material program, and the material library; both path tracers run material programs with textures (loaded by `fsh-commands/src/textures.rs`), image labels, thin film and dispersion. Then lighting (light spread, edge softness, IES profiles, light and shadow links, the Hosek-Wilkie physical sky, studio presets; pins, finite dome, backplate and background image are in the document but still being rendered), cameras (six projections, bladed and anamorphic apertures, pick focus), the image (grade, effects, AgX, ACES 1.3, OpenColorIO through fsh-ocio), 23 render passes with Cryptomatte, image writers in fsh-io, the render queue, and the denoisers (fsh-denoise, optional Open Image Denoise through fsh-oidn) landed; the GPU port of the denoiser is still being merged. At 0.9.0 shots, material variants and model sets, the configurator with rules, material templates and measurements (document blocks in fsh-scene with groups in fsh-commands), keyed animation with rigs, motion blur on the CPU (the GPU refuses moving scenes), and frame sequences and movies through a separate ffmpeg program landed, with their window pages and the timeline. At 0.10.0 advanced light transport landed on the CPU (nested media, volumes, subsurface, spectral rendering with dispersion, photon caustics, cutaways with caps, rounded edges, fibres) and the GPU ports of media, motion blur, spectral, cutaways and rounded edges; the GPU still refuses caustics, fibres, more than 4 overlapping media and more than 32 cutaways, and `transport.features` says which engine renders what. Read the code before trusting a claim here. This pack exists so that an agent entering the repo cold edits the right layer, in the right order, under the project laws, and proves the result. @@ -31,23 +31,23 @@ Sub-skill paths resolve as `sub-skills/[skill-name]/SUB-SKILL.md` from this fold | Area | Location | Role | | --- | --- | --- | -| Rust engine | `native/` (one Cargo workspace, edition 2021, all crates 0.8.0) | everything that knows about scenes, rays and pixels | +| Rust engine | `native/` (one Cargo workspace, edition 2021, all crates 0.10.0) | everything that knows about scenes, rays and pixels | | fsh-core | `native/crates/fsh-core` | maths, Transform, Ray, Aabb, Rgb in ACEScg, typed ids and document keys, units, the deterministic sampler, warps and MIS heuristics; std only | -| fsh-scene | `native/crates/fsh-scene` | the document, the command enum and its table, undo and redo with merge and groups, change levels, selection, `flatten()` to `RenderSnapshot`; the 18 material types, texture slots, material graphs, the compiler to programs and the preview bake; `lighting/` (IES table, link masks, pins, dome, pictures, reference evaluation, studio presets), camera lens fields, the image style, passes and `denoise_settings.rs` | +| fsh-scene | `native/crates/fsh-scene` | the document, the command enum and its table, undo and redo with merge and groups, change levels, selection, `flatten()` to `RenderSnapshot`; the 18 material types, texture slots, material graphs, the compiler to programs and the preview bake; `lighting/` (IES table, link masks, pins, dome, pictures, reference evaluation, studio presets), camera lens fields, the image style, passes and `denoise_settings.rs`; the document blocks `shots`, `variants` (with model sets), `configurator`, `measure` and `animation` (tracks, keys, rigs), and `motion.rs` (motion blur settings and the shutter flatten) | | fsh-accel | `native/crates/fsh-accel` | two-level binned-SAH BVH, watertight triangle test, `Intersector` | -| fsh-materials | `native/crates/fsh-materials` | the layered surface BSDF (diffuse, GGX, coat, transmission, fuzz) with energy compensation tables; thin film and dispersion (`film.rs`, `optics.rs`); the material program (25 opcodes, 24 the label projection), the texture sampler and mips, its interpreter, texture pixel types and the ten procedural patterns | +| fsh-materials | `native/crates/fsh-materials` | the layered surface BSDF (diffuse, GGX, coat, transmission, fuzz) with energy compensation tables; thin film and dispersion (`film.rs`, `optics.rs`); the material program (25 opcodes, 24 the label projection), the texture sampler and mips, its interpreter, texture pixel types and the ten procedural patterns; media and phase functions (`medium.rs`, `phase.rs`, `scatter.rs`) and fibre shading (`fibre.rs`, `fibre_lobes.rs`) | | fsh-io | `native/crates/fsh-io` | glTF/GLB, OBJ, STL, PLY, 3MF and FBX (ufbx, native only) readers to a raw scene with texture slots, clean-up with tangents, `probe`, the Form family hand-off readers (`family/`), PNG and HDR or EXR writers; the IES LM-63 reader (`ies.rs`); `write/`, layered writers for PNG, JPEG, TIFF, OpenEXR and PSD | | fsh-cad | `native/crates/fsh-cad` | STEP and IGES through FormCAD's kernel worker (a child process, JSON lines): locate, client, quality, `.mesh` parsing, colours and shared shapes, file scans; native only | | fsh-format | `native/crates/fsh-format` | the `.fshot` stored ZIP, deterministic save, validated load, atomic write, embedded textures named by SHA-256, kept CAD sources, the command journal and recovery | -| fsh-render-cpu | `native/crates/fsh-render-cpu` | the CPU path tracer (the specification engine), progressive passes and the 23 render passes, the physical sky (`hosek.rs`), lamp shaping and links (`lamp_extras.rs`), every camera projection, develop (`develop/`: grade, effects, AgX, ACES, quantizers, the OpenColorIO adapter), denoising through fsh-denoise | +| fsh-render-cpu | `native/crates/fsh-render-cpu` | the CPU path tracer (the specification engine), progressive passes and the 23 render passes, the physical sky (`hosek.rs`), lamp shaping and links (`lamp_extras.rs`), every camera projection, develop (`develop/`: grade, effects, AgX, ACES, quantizers, the OpenColorIO adapter), denoising through fsh-denoise; motion blur (`motion.rs`), media and subsurface (`media.rs`), spectral rendering (`spectral/`), photon caustics (`caustics/`), cutaways (`cutaway.rs`), rounded edges (`edges.rs`) and fibres (`fibres.rs`) | | fsh-ocio | `native/crates/fsh-ocio` | FormShot's own OpenColorIO v2 evaluator (YAML, configs, transforms, LUTs, ACES built-ins); std only, wasm32-safe | | fsh-denoise | `native/crates/fsh-denoise` | the own a-trous denoiser (Fast, Balanced, High), deterministic everywhere; the specification a GPU port matches | | fsh-oidn | `native/crates/fsh-oidn` | Intel Open Image Denoise loaded at run time with libloading, never linked; native only | -| fsh-render-gpu | `native/crates/fsh-render-gpu` | the GPU path tracer on wgpu 30: one WGSL megakernel, software BVH and ray-query traversal, refusals, bands, readback, the lighting block (`lighting.rs`, `lighting.wgsl`), pass records in the film; held to fsh-render-cpu's picture (the planned-for-0.3.0 tracer, now built) | -| fsh-commands | `native/crates/fsh-commands` | the one catalogue (156 entries), the texture loader (`textures.rs`) and `dispatch(session, name, args)` over an engine session; device choice and the GPU fallback ladder, interaction regimes, render jobs and the render region, picking and framing, the crash journal; command groups in `src/ext/` (import with jobs and reimport, cad, handoff, materials, library with its thumbnail worker, lighting with studio presets, camera, image, output with the render queue, denoise with the Open Image Denoise route) | -| fsh-cli | `native/crates/fsh-cli` | `formshot-engine`: render (`--device`), info, convert, devices, bench, catalogue, dispatch (`--journal`) over stdin JSON lines | +| fsh-render-gpu | `native/crates/fsh-render-gpu` | the GPU path tracer on wgpu 30: one WGSL megakernel, software BVH and ray-query traversal, refusals, bands, readback, the lighting block (`lighting.rs`, `lighting.wgsl`), pass records in the film, the transport and geometry blocks (`media.rs`, `spectral.rs`, `transport.rs`, `geo.rs`) behind per-feature kernel overrides; held to fsh-render-cpu's picture (the planned-for-0.3.0 tracer, now built) | +| fsh-commands | `native/crates/fsh-commands` | the one catalogue (241 entries), the texture loader (`textures.rs`) and `dispatch(session, name, args)` over an engine session; device choice and the GPU fallback ladder, interaction regimes, render jobs and the render region, picking and framing, the crash journal; command groups in `src/ext/` (import with jobs and reimport, cad, handoff, materials, library with its thumbnail worker, lighting with studio presets, camera, image, output with the render queue, denoise with the Open Image Denoise route, shots, variants, configurator, templates, measure, anim with frame sequences, video with the ffmpeg finder and movie jobs, transport with its feature table) | +| fsh-cli | `native/crates/fsh-cli` | `formshot-engine`: render (`--device`, `--frames`, `--turntable`, movie outputs), info, convert, devices, bench, catalogue, dispatch (`--journal`) over stdin JSON lines | | fsh-py, fsh-wasm | `native/crates/fsh-py`, `fsh-wasm` | PyO3 module `fsh_py` and the wasm-bindgen package (session, service mirror, `create_viewport` on WebGPU, the GPU develop in `present.rs`, `develop.wgsl`, `effects.wgsl`, OpenColorIO tables, the WebGPU self-check in `check.rs`), both outside the default members | -| Frontend | `frontend/` (vanilla TypeScript, Vite, port 5300) | `src/shell/` frame, registry, menus, Home, settings, dock adapter; `src/ui/` workspace and viewport, `import/`, `cad/`, `handoff/`, the Material page (`pages/material.ts`, `material/`), the graph editor (`graph/`), the library panel (`library/`), the Lighting and Environment pages (`lighting/`), the Camera page (`camera/`), the Image page (`image/`), the Final Render window and queue (`render/`); `src/engine/` client, streamed render loop, `raster/` (WebGL2), `gpu/` (WebGPU engine), `pkg/` (built wasm, ignored); `src/dock/` shared dock | +| Frontend | `frontend/` (vanilla TypeScript, Vite, port 5300) | `src/shell/` frame, registry, menus, Home, settings, dock adapter; `src/ui/` workspace and viewport, `import/`, `cad/`, `handoff/`, the Material page (`pages/material.ts`, `material/`), the graph editor (`graph/`), the library panel (`library/`), the Lighting and Environment pages (`lighting/`), the Camera page (`camera/`), the Image page (`image/`), the Final Render window and queue (`render/`), the Shots and Configurator pages (`shots/`, `configurator/`), material templates (`templates/`), the measure tool (`measure/`), the timeline (`timeline/`), Render Animation (`movie/`) and the light transport controls (`transport/`); `src/engine/` client, streamed render loop, `raster/` (WebGL2), `gpu/` (WebGPU engine), `pkg/` (built wasm, ignored); `src/dock/` shared dock | | Backend | `backend/app/` (FastAPI, 127.0.0.1:8300) | window key and local guard, projects library, engine bridge (with the journal folder), render routes, mesh and snapshot byte routes, `/mcp`, consent, the agent bus; `routers/` imports (uploads, sweep), cad (worker fetch), handoff (watcher, offers), textures (images and `.ies`), library (thumbnails), denoise (Open Image Denoise fetch), output (render files, thumbnails, open folder) | | Material presets | `assets/library/` | 249 preset JSON files and the generated `materials/index.json`, and seven studio presets in `studios/`, bundled as a Tauri resource | | Sidecar entry | `backend/formshot_engine.py` | PyInstaller entry, frozen as `formshot-engine-backend` | diff --git a/.claude/skills/formshot-rendering/SKILL.md b/.claude/skills/formshot-rendering/SKILL.md index f9f7ea6d..0e2285c0 100644 --- a/.claude/skills/formshot-rendering/SKILL.md +++ b/.claude/skills/formshot-rendering/SKILL.md @@ -1,6 +1,6 @@ --- name: formshot-rendering -description: Set up, dress, light and render 3D product scenes in formshot, the 3D product renderer, by asking in plain language through its MCP server. Use whenever the person wants a product shot, a model placed on a studio floor, a material put on a part, a studio preset applied, a light, IES profile, sky or camera changed, exposure, colour grade or display transform (including OpenColorIO) adjusted, render size, samples, passes or denoising set, a step undone, or a picture rendered or queued to files, and the formshot tools are available or the person mentions formshot. Covers reading the scene, the command names, partial updates, units and checking work. Also use when a formshot tool fails and the next step is unclear. Not for editing formshot's own source code (use formshot-harness for that). +description: Set up, dress, light and render 3D product scenes in formshot, the 3D product renderer, by asking in plain language through its MCP server. Use whenever the person wants a product shot, a model placed on a studio floor, a material put on a part, a studio preset applied, a light, IES profile, sky or camera changed, exposure, colour grade or display transform (including OpenColorIO) adjusted, render size, samples, passes or denoising set, a step undone, a picture rendered or queued to files, shots, material variants, product configurations, measurements, a turntable, keyed animation or a movie, liquids and wax, spectral rendering, caustics or cutaways, and the formshot tools are available or the person mentions formshot. Covers reading the scene, the command names, partial updates, units and checking work. Also use when a formshot tool fails and the next step is unclear. Not for editing formshot's own source code (use formshot-harness for that). --- # Rendering in formshot @@ -56,6 +56,29 @@ The tool list comes from the engine's catalogue. `references/tools.md`, when pre 1. `render.set_settings {values: {denoise: true, denoising: {denoiser: "own" or "oidn", quality_final: "fast", "balanced" or "high", strength: 1}}}` chooses the denoiser for final renders. 2. Open Image Denoise is optional and downloaded once: check with `denoise.oidn_status {probe: true}`. If it is not installed, the person downloads it in the Final Render window or with `./formshot oidn fetch`; never download it yourself. Without it the engine uses its own denoiser and `denoise.status` and `render.status` say why. +## Workflow 6: shots, variants and configurations + +1. `shot.add {name}` keeps the current camera, look, environment, render settings, lights, visibility and variant choices; `shot.apply {id}` brings one back in one undo step; `shot.render {folder, ...}` queues one render per shot with `render.queue_add`'s options (`{shot}` in `name` is the shot's name). +2. `variant.add_set` and `variant.capture` keep the materials of chosen parts as named variants, `variant.select` chooses one and `variant.diff` says what it would change; `model_set.add` and `model_set.select` show one set of parts and hide the other sets'. +3. The configurator: `config.add_option` with choices whose actions put materials on parts, show or hide parts, choose a variant or a model set, or apply a shot; `config.add_rule` adds requires or excludes rules; `config.select` chooses and moves other options to the nearest valid configuration; `config.check` names problems; `config.list` lists every valid configuration; `config.render_all {folder, ...}` queues one render each (`{config}` and `{variant}` in `name`). +4. `template.list`, then `template.preview {id}` and `template.apply {id}`, dress imported parts by their material names in one undo step; the import tools take `template` too. +5. `measure.add_distance`, `measure.add_size` and `measure.add_angle` keep measurements pinned to parts, `measure.list` reads them in the display unit and `measure.render` queues a render with them drawn in. + +## Workflow 7: animation and movies + +1. `anim.set {fps, start, end}` sets the timeline; `anim.key {target, time, value}` keys a part's `translation`, `rotation` or `scale`, a camera field, a material parameter or a light field (the schema lists the targets); `anim.status` lists tracks, keys and rigs; `anim.seek {time}` shows the document at a time and `{time: null}` the stored values again. +2. Rigs: `anim.turntable {frames}` turns the product once over the animation; `anim.orbit` and `anim.camera_path` move the camera. +3. Motion blur: `render.set_settings {values: {motion_blur: {enabled: true, shutter: 0.5}}}`. Both the CPU and the GPU render it. +4. `anim.render {folder, video: {format: "mp4"}}` queues one job per frame and then a movie job (mp4, webm, mov or gif); poll `render.queue_list`. `video.ffmpeg` says whether ffmpeg is there. When it is not, the person downloads it in Render Animation; never download it yourself. +5. From a shell: `./formshot cli render model.glb out.mp4 --turntable 36`. + +## Workflow 8: light transport + +1. Materials: `material.set_params` with `transmission_depth` (metres light travels before it takes the colour) and `medium_priority` (where parts overlap the higher one wins, a drink inside its glass); `subsurface_weight`, `subsurface_color` and `subsurface_radius` for wax, marble or milk; `edge_radius` (metres) rounds sharp edges; `fibre_density`, `fibre_length` and the other `fibre_*` fields grow fibres. +2. `render.set_settings {values: {transport: {spectral: {enabled: true}}}}` renders spectrally (dispersion in prisms and gems); `{transport: {caustics: {mode: "photons"}}}` adds photon caustics, which only the CPU renders. +3. `scene.add_cutaway {cutaway: {shape, cap, targets}}` opens parts; `scene.set_cutaway`, `cutaway.set_enabled` and `cutaway.set_targets` change it. +4. `transport.features` lists each feature with whether the document uses it and whether the GPU renders it; when the GPU refuses, the CPU renders and `render.status` says why. + ## When something fails - "locked": the node or a group above it is locked; `scene.set_locked` unlocks it. diff --git a/.claude/skills/formshot-rendering/references/tools.md b/.claude/skills/formshot-rendering/references/tools.md index b27b1695..aef199c5 100644 --- a/.claude/skills/formshot-rendering/references/tools.md +++ b/.claude/skills/formshot-rendering/references/tools.md @@ -1,10 +1,11 @@ # formshot tools -Generated from the engine's command catalogue (formshot 0.8.0) by `./formshot agents sync`; do not edit by hand. +Generated from the engine's command catalogue (formshot 0.10.0) by `./formshot agents sync`; do not edit by hand. ## Contents - Scene: `scene.add_group`, `scene.add_part`, `scene.add_primitive`, `scene.add_light`, `scene.add_cutaway`, `scene.remove`, `scene.rename`, `scene.set_transform`, `scene.set_visible`, `scene.set_locked`, `scene.set_ray_visibility`, `scene.set_part_colour`, `scene.set_metadata`, `scene.set_pivot`, `scene.set_part_mesh`, `scene.set_light`, `scene.set_cutaway`, `scene.reparent`, `scene.duplicate`, `scene.import`, `scene.summary`, `scene.meshes`, `scene.mesh_data`, `scene.retessellate` +- Cutaway: `cutaway.set_enabled`, `cutaway.set_targets` - Mesh: `mesh.add`, `mesh.remove` - Materials: `material.create`, `material.set_params`, `material.set_type`, `material.set_slot`, `material.clear_slot`, `material.set_graph`, `material.label_add`, `material.label_set`, `material.label_remove`, `material.label_move`, `material.assign`, `material.rename`, `material.remove`, `material.types`, `material.node_kinds`, `material.program`, `material.preview_maps`, `material.get`, `material.labels` - Texture: `texture.add`, `texture.remove` @@ -17,6 +18,12 @@ Generated from the engine's command catalogue (formshot 0.8.0) by `./formshot ag - Rendering: `render.set_settings`, `render.start`, `render.status`, `render.frame`, `render.stop`, `render.still`, `render.develop`, `render.interaction`, `render.devices`, `render.set_device`, `render.region`, `render.viewport`, `render.passes`, `render.queue_add`, `render.queue_list`, `render.queue_cancel`, `render.queue_remove`, `render.queue_move`, `render.queue_clear`, `render.queue_pause`, `render.output_formats`, `render.output_thumbnail` - Units: `units.set_display` - Document: `document.set_info`, `document.new`, `document.open`, `document.import`, `document.save`, `document.close` +- Anim: `anim.add_rig`, `anim.set_rig`, `anim.remove_rig`, `anim.turntable`, `anim.orbit`, `anim.camera_path`, `anim.set`, `anim.key`, `anim.set_key`, `anim.remove_key`, `anim.move_key`, `anim.remove_track`, `anim.clear`, `anim.seek`, `anim.status`, `anim.sample`, `anim.render` +- Config: `config.add_option`, `config.set_option`, `config.remove_option`, `config.move_option`, `config.add_choice`, `config.set_choice`, `config.remove_choice`, `config.move_choice`, `config.add_rule`, `config.remove_rule`, `config.select`, `config.apply`, `config.get`, `config.check`, `config.list`, `config.render_all` +- Shot: `shot.add`, `shot.update`, `shot.set`, `shot.remove`, `shot.move`, `shot.duplicate`, `shot.apply`, `shot.list`, `shot.render` +- Variant: `variant.add_set`, `variant.set_set`, `variant.remove_set`, `variant.capture`, `variant.add`, `variant.set`, `variant.remove`, `variant.move`, `variant.select`, `variant.apply_choice`, `variant.list`, `variant.diff` +- Model_Set: `model_set.add`, `model_set.set`, `model_set.remove`, `model_set.move`, `model_set.select`, `model_set.list` +- Measure: `measure.add_distance`, `measure.add_size`, `measure.add_angle`, `measure.set`, `measure.remove`, `measure.clear`, `measure.list`, `measure.pick`, `measure.render` - App: `app.version`, `app.catalogue` - Selection: `selection.set`, `selection.clear` - History: `history.undo`, `history.redo`, `history.begin_group`, `history.end_group`, `history.abandon_group`, `history.barrier` @@ -27,6 +34,9 @@ Generated from the engine's command catalogue (formshot 0.8.0) by `./formshot ag - Handoff: `handoff.inspect`, `handoff.open` - Library: `library.list`, `library.get`, `library.favorite`, `library.recent`, `library.apply`, `library.save`, `library.remove`, `library.thumbnail`, `library.thumbnails` - Denoise: `denoise.status`, `denoise.oidn_status`, `denoise.oidn_device`, `denoise.oidn_release` +- Template: `template.list`, `template.get`, `template.save`, `template.remove`, `template.preview`, `template.apply`, `template.capture` +- Video: `video.ffmpeg`, `video.encode` +- Transport: `transport.features` - Nodes: `node.set_visible`, `node.set_locked`, `node.rename`, `node.remove` - Undo: `undo` - Redo: `redo` @@ -81,7 +91,7 @@ Add a light node (area rectangle, area disc, point, spot or sun). Add a cutaway volume (plane, box, sphere or cylinder) that clips parts. -- `cutaway`: object; fields cap, enabled, shape, targets +- `cutaway`: object; fields cap, enabled, invert, shape, targets - `id`: integer; range 1 to inf; Id for the new node; allocated when absent - `index`: integer; range 0 to inf; Position among the siblings; last when absent - `name`: string; Name @@ -90,7 +100,7 @@ Add a cutaway volume (plane, box, sphere or cylinder) that clips parts. ## scene.remove -Remove nodes with everything under them. +Remove nodes with everything under them; cutaways, variants, model sets, shots, rigs, tracks, measurements and configurator actions stop naming them in the same undo step. - `ids`: array of integer; required; Nodes to remove with their descendants @@ -171,7 +181,22 @@ Change a light node's settings; give only the fields to change. Change a cutaway node's settings; give only the fields to change. - `id`: integer; required; range 1 to inf; Node -- `values`: object; required; Only the fields to change; fields cap, enabled, shape, targets +- `values`: object; required; Only the fields to change; fields cap, enabled, invert, shape, targets + +## cutaway.set_enabled + +Turn cutaways on or off. + +- `enabled`: boolean; required; Whether they cut +- `ids`: array of integer; required; Cutaway nodes + +## cutaway.set_targets + +Set, add to, remove from or clear the nodes cutaways cut (an empty list cuts every part); a group stands for its descendants. + +- `ids`: array of integer; required; Cutaway nodes +- `nodes`: array of integer; Nodes; a group stands for its descendants +- `op`: string (set | add | remove | clear); set replaces the list (default) ## scene.reparent @@ -184,7 +209,7 @@ Move nodes under another parent (or to the root), keeping their world placement ## scene.duplicate -Copy nodes with their children; copies share meshes and materials. +Copy nodes with their children; copies share meshes and materials, and cutaways, variants, model sets, shots and configurator actions treat each copy as its original. - `ids`: array of integer; required; Nodes to copy - `new_ids`: array of integer; Ids for the copies in pre-order; allocated when empty @@ -216,14 +241,14 @@ Create a material, from a material type's preset when type is given. - `key`: integer; range 1 to inf; Key; allocated when absent - `material`: object; fields graph, labels, name, params, slots, textures, type_id - `name`: string; Name; the type's name when absent -- `type`: string (generic | plastic | plastic_clear | metal | metal_brushed | paint | paint_metallic | glass | glass_thin | liquid | gem | rubber | fabric | ceramic | diffuse | emissive | wood | stone); Start from this material type's preset (ignores material) +- `type`: string (generic | plastic | plastic_clear | metal | metal_brushed | paint | paint_metallic | glass | glass_thin | liquid | gem | rubber | fabric | ceramic | diffuse | emissive | wood | stone | translucent | volume); Start from this material type's preset (ignores material) ## material.set_params Change a material's surface parameters; give only the fields to change. - `key`: integer; required; range 1 to inf; Material -- `values`: object; required; Only the parameters to change; fields base_color, base_diffuse_roughness, base_metalness, base_weight, coat_color, coat_darkening, coat_ior, coat_roughness, coat_weight, emission_color, emission_luminance, fuzz_color, fuzz_roughness, fuzz_weight, geometry_opacity, geometry_thin_walled, specular_color, specular_ior, specular_roughness, specular_roughness_anisotropy, specular_weight, subsurface_color, subsurface_radius, subsurface_radius_scale, subsurface_weight, thin_film_ior, thin_film_thickness, thin_film_weight, transmission_color, transmission_depth, transmission_dispersion_abbe_number, transmission_dispersion_scale, transmission_weight +- `values`: object; required; Only the parameters to change; fields base_color, base_diffuse_roughness, base_metalness, base_weight, coat_color, coat_darkening, coat_ior, coat_roughness, coat_weight, edge_other_parts, edge_radius, emission_color, emission_luminance, fibre_clumping, fibre_color, fibre_comb, fibre_comb_direction, fibre_curl, fibre_density, fibre_length, fibre_own_color, fibre_radial_roughness, fibre_randomness, fibre_root_width, fibre_roughness, fibre_seed, fibre_tip_width, fuzz_color, fuzz_roughness, fuzz_weight, geometry_opacity, geometry_thin_walled, medium_priority, specular_color, specular_ior, specular_roughness, specular_roughness_anisotropy, specular_weight, subsurface_color, subsurface_radius, subsurface_radius_scale, subsurface_scatter_anisotropy, subsurface_weight, thin_film_ior, thin_film_thickness, thin_film_weight, transmission_color, transmission_depth, transmission_dispersion_abbe_number, transmission_dispersion_scale, transmission_scatter, transmission_scatter_anisotropy, transmission_weight ## material.set_type @@ -309,7 +334,7 @@ Rename a material. ## material.remove -Remove a material; parts wearing it fall back to the default material. +Remove a material; parts wearing it fall back to the default material. Refused while a variant or a configurator choice puts it on parts. - `key`: integer; required; range 1 to inf; Material @@ -479,7 +504,7 @@ Change the image style (exposure, white balance, tones, saturation, contrast, bl Change resolution, samples, bounces, seed and denoising. -- `values`: object; required; Only the fields to change; fields ao_distance, denoise, denoising, height, max_bounces, passes, samples, seed, width +- `values`: object; required; Only the fields to change; fields ao_distance, denoise, denoising, height, max_bounces, motion_blur, passes, samples, seed, transport, width ## units.set_display @@ -493,6 +518,457 @@ Change document metadata (name, author, description). - `values`: object; required; Only the fields to change; fields author, description, name, writer +## anim.add_rig + +Add a rig (turntable, orbit or camera_path): motion made from a few settings; fields left out take their defaults and the animation's range. + +- `index`: integer; range 0 to inf; Position in the rig list; last when absent +- `rig`: value; required; A rig with its kind: turntable, orbit or camera_path; fields left out take their defaults + +## anim.set_rig + +Change a rig; give only the fields to change (null clears an optional one); its id and kind stay. + +- `id`: string; required; Rig id +- `values`: object; required; Fields to change; null clears an optional one; fields camera, closed, direction, ease_in, ease_out, end, look_at, name, node, points, roll, start, start_angle, turns + +## anim.remove_rig + +Remove a rig. + +- `id`: string; required; Rig id + +## anim.turntable + +Turn the product (or one node) about its centre as a seamless loop over the animation's range; frames or seconds set the range to exactly that many frames, the turn spanning one frame more so no frame repeats. + +- `direction`: string (ccw | cw); Direction seen from above: ccw (counterclockwise, default) or cw +- `fps`: number; range 1 to 1000; Frames per second; the animation's when absent +- `frames`: integer; range 2 to inf; Frames in the loop: the range becomes exactly this many frames and the turn spans one more, so the loop is seamless +- `id`: string; Id of the new rig; turntable when absent +- `node`: integer; range 1 to inf; Node to turn; the whole product when absent +- `seconds`: number; range 0 to inf; Loop length in seconds when frames is absent (rounded to whole frames) +- `turns`: number; Full turns over the loop (default 1) + +## anim.orbit + +Circle a camera (the active one by default) around the product at its current distance and height, looking at the product's centre, as a loop over the animation's range. + +- `camera`: integer; range 0 to inf; Camera index; the active camera when absent +- `direction`: string (ccw | cw); Direction seen from above: ccw (counterclockwise, default) or cw +- `ease_in`: number; range 0.0 to 1.0; Share of the run spent speeding up from rest (0, the default, starts at full speed) +- `ease_out`: number; range 0.0 to 1.0; Share of the run spent slowing down to rest; ease_in + ease_out at most 1 +- `end`: number; End time in seconds; when absent the animation's end, one frame past it for motion that loops +- `id`: string; Id of the new rig; orbit when absent +- `start`: number; Start time in seconds; the animation's start when absent +- `turns`: number; Full turns from start to end (default 1) + +## anim.camera_path + +Move a camera (the active one by default) along a smooth curve through points at constant speed over the animation's range, looking at a point, a node or the product's centre. + +- `camera`: integer; range 0 to inf; Camera index; the active camera when absent +- `closed`: boolean; The curve returns smoothly to its first point +- `ease_in`: number; range 0.0 to 1.0; Share of the run spent speeding up from rest (0, the default, starts at full speed) +- `ease_out`: number; range 0.0 to 1.0; Share of the run spent slowing down to rest; ease_in + ease_out at most 1 +- `end`: number; End time in seconds; when absent the animation's end, one frame past it for motion that loops +- `id`: string; Id of the new rig; path when absent +- `look_at`: value; What the camera looks at: {"point": [x, y, z]} or {"node": id} (its centre, following it); the product's centre when absent +- `points`: array of array; required; Control points [x, y, z] in metres; the curve passes through each (2 or more, 3 or more when closed) +- `roll`: number; Roll in degrees about the viewing direction; positive banks to the right +- `start`: number; Start time in seconds; the animation's start when absent + +## config.add_option + +Add a configurator option (something the customer chooses, such as colour or trim), optionally with its first choices and a default; the id is option when not given. + +- `choices`: array of object; Choices to start with +- `default`: string; Choice in force while nothing is selected; the first choice when absent (letters, digits, _, - and .) +- `id`: string; Option id; option with the lowest free number when absent (letters, digits, _, - and .) +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `name`: string; Name shown to the customer; Option when empty + +## config.set_option + +Rename a configurator option or change its default choice (null clears it). + +- `default`: ['string', 'null']; New default choice id; null clears it +- `name`: string; New name +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.remove_option + +Remove a configurator option with its choices and every rule that names it; the scene is not changed. + +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.move_option + +Move a configurator option to another position in the list. + +- `index`: integer; required; range 0 to inf; New position (clamped) +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.add_choice + +Add a choice to a configurator option with the actions choosing it runs (variant, model_set, shot, show, hide, material); the id is choice when not given. + +- `actions`: array of value; What choosing it does, in order +- `id`: string; Choice id; choice with the lowest free number in the option when absent (letters, digits, _, - and .) +- `index`: integer; range 0 to inf; Position in the option; last when absent +- `name`: string; Name shown to the customer; Choice when empty +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.set_choice + +Rename a configurator choice or replace its actions; give only what changes. + +- `actions`: array of value; New action list; replaces the old one +- `choice`: string; required; Choice id (letters, digits, _, - and .) +- `name`: string; New name +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.remove_choice + +Remove a choice from a configurator option; rules it triggers go, and it leaves the choice lists of rules on its option (a rule left with none goes). + +- `choice`: string; required; Choice id (letters, digits, _, - and .) +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.move_choice + +Move a choice to another position in its configurator option. + +- `choice`: string; required; Choice id (letters, digits, _, - and .) +- `index`: integer; required; range 0 to inf; New position in the option (clamped) +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.add_rule + +Add a configurator rule: while option is on choice, target requires one of choices (kind requires) or none of them (kind excludes); the id is rule when not given. + +- `choice`: string; required; The triggering choice (letters, digits, _, - and .) +- `choices`: array of string; required; Choices of the target option +- `id`: string; Rule id; rule with the lowest free number when absent (letters, digits, _, - and .) +- `kind`: string (requires | excludes); default "requires"; requires: target must be on one of choices; excludes: on none of them +- `option`: string; required; Option whose choice triggers the rule (letters, digits, _, - and .) +- `target`: string; required; Option the rule restricts (another option) (letters, digits, _, - and .) + +## config.remove_rule + +Remove a configurator rule. + +- `rule`: string; required; Rule id (letters, digits, _, - and .) + +## config.select + +Choose one choice of a configurator option and run its actions; options a rule now forbids move to their first allowed choice and run theirs, all as one undo step. + +- `choice`: string; required; Choice id (letters, digits, _, - and .) +- `option`: string; required; Option id (letters, digits, _, - and .) + +## config.apply + +Set a whole configuration at once (choice per option; options left out keep their choice where the rules allow) and run every option's actions in option order, as one undo step. + +- `selection`: object; required; Choice id per option id + +## shot.add + +Save the current view as a named shot: the active camera with its lens, image style, environment and ground, render settings, each light's on, power and colour, every node's visibility and the chosen variants; include picks what applying it restores. + +- `id`: string; Id for the new shot; the lowest free shot when absent +- `include`: value; What applying the shot restores: an object of the flags to change (camera, image, environment with the ground, render, lights, visibility, variants; all on for a new shot), or a list of the parts to include +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `name`: string; Name; Shot when absent + +## shot.update + +Recapture a shot from the current document, keeping its id and name; include changes its flags at the same time. + +- `id`: string; required; Shot id (shot.list lists them) +- `include`: value; What applying the shot restores: an object of the flags to change (camera, image, environment with the ground, render, lights, visibility, variants; all on for a new shot), or a list of the parts to include + +## shot.set + +Rename a shot or change its include flags; the captured state is kept. + +- `id`: string; required; Shot id (shot.list lists them) +- `include`: value; What applying the shot restores: an object of the flags to change (camera, image, environment with the ground, render, lights, visibility, variants; all on for a new shot), or a list of the parts to include +- `name`: string; New name + +## shot.remove + +Remove a shot. + +- `id`: string; required; Shot id (shot.list lists them) + +## shot.move + +Move a shot to another position in the list. + +- `id`: string; required; Shot id (shot.list lists them) +- `index`: integer; required; range 0 to inf; New position in the list (clamped) + +## shot.duplicate + +Copy a shot; the copy goes right after it with a new id. + +- `id`: string; required; Shot id (shot.list lists them) +- `name`: string; Name of the copy; the original's name with " copy" when absent +- `new_id`: string; Id of the copy; the lowest free shot when absent + +## shot.apply + +Restore the parts of a shot its include flags name, as one undo step; lights and nodes that no longer exist are skipped and listed. + +- `id`: string; required; Shot id (shot.list lists them) + +## variant.add_set + +Add a material variant set (such as Colourway) covering parts; a group stands for its descendant parts. + +- `id`: ['string', 'integer']; Id of the new set; set1, set2, ... when absent +- `index`: integer; range 0 to inf; Position among the sets; last when absent +- `name`: string; required; Name, such as Colourway +- `parts`: array of ['integer', 'string']; Covered nodes (ids as numbers or decimal strings); a group stands for its descendant parts + +## variant.set_set + +Rename a variant set or change the parts it covers; give only the fields to change. + +- `name`: string; New name +- `parts`: array of ['integer', 'string']; New covered nodes; variant entries for parts no longer covered are dropped +- `set`: ['string', 'integer']; required; Variant set id + +## variant.remove_set + +Remove a variant set with its variants; the parts keep the materials they wear. + +- `set`: ['string', 'integer']; required; Variant set id + +## variant.capture + +Add a variant to a set from the materials its covered parts wear now, and make it the active one. + +- `id`: ['string', 'integer']; Id of the new variant; variant1, variant2, ... within the set when absent +- `index`: integer; range 0 to inf; Position in the set; last when absent +- `name`: string; Name; Variant when absent +- `set`: ['string', 'integer']; required; Variant set id + +## variant.add + +Add a variant to a set: one material for every covered part, or a material per part or group. + +- `id`: ['string', 'integer']; Id of the new variant; variant1, variant2, ... within the set when absent +- `index`: integer; range 0 to inf; Position in the set; last when absent +- `materials`: value; The variant's materials; absent for an empty variant: one material key every covered part wears, an object from part or group id to material key (a group stands for its descendant parts), or a list of {part, material} +- `name`: string; required; Name, such as Graphite +- `set`: ['string', 'integer']; required; Variant set id + +## variant.set + +Rename a variant or replace its materials; give only the fields to change. + +- `id`: ['string', 'integer']; required; Variant id +- `materials`: value; New materials, replacing the old ones: one material key every covered part wears, an object from part or group id to material key (a group stands for its descendant parts), or a list of {part, material} +- `name`: string; New name +- `set`: ['string', 'integer']; required; Variant set id + +## variant.remove + +Remove a variant from its set; the parts keep the materials they wear. + +- `id`: ['string', 'integer']; required; Variant id +- `set`: ['string', 'integer']; required; Variant set id + +## variant.move + +Move a variant within its set, or the set among the sets when no variant id is given. + +- `id`: ['string', 'integer']; Variant to move within the set; without it the set moves among the sets +- `index`: integer; required; range 0 to inf; New position +- `set`: ['string', 'integer']; required; Variant set id + +## variant.select + +Choose a set's variant: its parts put on the variant's materials as one step; missing parts and materials are skipped (variant.diff lists them). + +- `set`: ['string', 'integer']; required; Variant set id +- `variant`: ['string', 'integer']; required; Variant id + +## model_set.add + +Add a model set (such as Open lid) listing the nodes it shows; without nodes, the product nodes visible now under the roots. + +- `id`: ['string', 'integer']; Id of the new model set; model1, model2, ... when absent +- `index`: integer; range 0 to inf; Position among the model sets; last when absent +- `name`: string; required; Name, such as Open lid +- `nodes`: array of ['integer', 'string']; Nodes it shows; when absent, the visible part and group children of each visible root (a part root itself), leaving lights and cutaways out + +## model_set.set + +Rename a model set or replace the nodes it shows; give only the fields to change. + +- `id`: ['string', 'integer']; required; Model set id +- `name`: string; New name +- `nodes`: array of ['integer', 'string']; New list of nodes it shows + +## model_set.remove + +Remove a model set; every node keeps its visibility. + +- `id`: ['string', 'integer']; required; Model set id + +## model_set.move + +Move a model set among the model sets. + +- `id`: ['string', 'integer']; required; Model set id +- `index`: integer; required; range 0 to inf; New position + +## model_set.select + +Choose a model set as one step: show its nodes and hide the nodes of the other model sets; nodes in no model set are left alone. + +- `id`: ['string', 'integer']; required; Model set id + +## variant.apply_choice + +Apply a stored choice as one step: a variant per set (in the document's set order), then a model set; sets, variants and model sets that no longer exist are skipped. + +- `model_set`: ['string', 'null']; Model set id +- `variants`: object; Variant id by variant set id + +## anim.set + +Change the animation timeline: frames per second, start and end in seconds; give only the fields to change. + +- `end`: number; End of the timeline (its last frame), seconds +- `fps`: number; range -inf to 240.0; Frames per second (default 30) +- `start`: number; Start of the timeline, seconds + +## anim.key + +Key a target (a node's translation, rotation or scale, a camera field, a material parameter, a light field or a node's visibility) at a time; without a value it keys the value the target has at that time. Replaces a key already at that time. + +- `id`: string; Key id; the key at that time, or a new id, when absent +- `interpolation`: string (step | linear | smooth | ease); To the next key: step holds, linear goes straight, smooth is a monotone cubic through the keys (no overshoot), ease stops at both keys +- `target`: value; required; What the key drives +- `time`: number; required; Seconds +- `track`: string; Track id for a new track; chosen when absent +- `value`: value; A number; true or false for switches; [x, y, z] for vectors; [r, g, b] (ACEScg) or an sRGB hex string for colours; [x, y, z, w] or Euler degrees [x, y, z] for rotations + +## anim.set_key + +Change one key's time, value or interpolation (step, linear, smooth, ease); name the track or its target, and the key or its time. + +- `at`: number; Time of the key, within half a frame (instead of key) +- `interpolation`: string (step | linear | smooth | ease); To the next key: step holds, linear goes straight, smooth is a monotone cubic through the keys (no overshoot), ease stops at both keys +- `key`: string; Key id (or give at) +- `target`: value; What the key drives +- `time`: number; New time, seconds +- `track`: string; Track id (or give target) +- `value`: value; A number; true or false for switches; [x, y, z] for vectors; [r, g, b] (ACEScg) or an sRGB hex string for colours; [x, y, z, w] or Euler degrees [x, y, z] for rotations + +## anim.remove_key + +Remove one key; a track left without keys is removed. + +- `at`: number; Time of the key, within half a frame (instead of key) +- `key`: string; Key id (or give at) +- `target`: value; What the key drives +- `track`: string; Track id (or give target) + +## anim.move_key + +Move one key to another time; drags of the same key merge into one undo step. + +- `at`: number; Time of the key, within half a frame (instead of key) +- `key`: string; Key id (or give at) +- `target`: value; What the key drives +- `time`: number; required; New time, seconds +- `track`: string; Track id (or give target) + +## anim.remove_track + +Remove a track with all its keys; the target keeps its stored value. + +- `target`: value; What the key drives +- `track`: string; Track id (or give target) + +## anim.clear + +Remove every keyed track; with all true also remove the rigs and reset the timeline, leaving no animation. + +- `all`: boolean; Also remove the rigs and reset the timeline + +## measure.add_distance + +Add a distance between two points, each pinned to a part in the part's own space (it follows the part) or free in the world; points are given in world space as picked; the id is distance when not given. + +- `a`: object; required; First point: a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `axis`: string (direct | x | y | z); default "direct"; direct (the straight line) or only the part along the world x, y (up) or z axis +- `b`: object; required; Second point: a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `id`: string; Id; the lowest free distance when absent +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `label`: object; Label options; give only the ones to change; fields hidden, precision, show_name +- `name`: string; Name; Distance when absent +- `visible`: boolean; default true; Shown in the viewport and in renders that draw measurements + +## measure.add_size + +Add a size box: the width (x), height (y) and depth (z) of the bounds of nodes together, in world axes or the first node's own axes; the id is size when not given. + +- `frame`: string (world | local); default "world"; world axes (width x, height y, depth z) or the first node's own axes +- `id`: string; Id; the lowest free size when absent +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `label`: object; Label options; give only the ones to change; fields hidden, precision, show_name +- `name`: string; Name; Size when absent +- `nodes`: array of ['integer', 'string']; required; Nodes measured together; a group stands for its parts +- `visible`: boolean; default true; Shown in the viewport and in renders that draw measurements + +## measure.add_angle + +Add an angle at a vertex between the lines to two points, each pinned to a part or free; the id is angle when not given. + +- `a`: object; required; End of the first arm: a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `b`: object; required; End of the second arm: a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `id`: string; Id; the lowest free angle when absent +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `label`: object; Label options; give only the ones to change; fields hidden, precision, show_name +- `name`: string; Name; Angle when absent +- `vertex`: object; required; Corner of the angle: a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `visible`: boolean; default true; Shown in the viewport and in renders that draw measurements + +## measure.set + +Change a measurement (name, visibility, label options, points, axis, nodes or frame; give only what changes), or without id the document's label precision. + +- `a`: object; New first point (distance, angle): a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `axis`: string (direct | x | y | z); default "direct"; direct (the straight line) or only the part along the world x, y (up) or z axis +- `b`: object; New second point (distance, angle): a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `frame`: string (world | local); default "world"; world axes (width x, height y, depth z) or the first node's own axes +- `id`: string; Measurement to change; absent to change the document's precision +- `label`: object; Label options; give only the ones to change; fields hidden, precision, show_name +- `name`: string; New name +- `nodes`: array of ['integer', 'string']; Nodes measured together; a group stands for its parts +- `precision`: integer; range 0 to 6; Without id: digits after the decimal point of every label that does not set its own (default 1) +- `vertex`: object; New corner (angle): a point pinned to a node (it follows the node when it moves) or free in the world when node is absent; fields node, point, space +- `visible`: boolean; Show or hide + +## measure.remove + +Remove a measurement. + +- `id`: string; required; Measurement id (measure.list lists them) + +## measure.clear + +Remove every measurement as one undo step. + +- `keep_precision`: boolean; default true; Keep the document's precision; false resets it to 1 + ## app.version Engine, format and catalogue versions. @@ -592,6 +1068,7 @@ Open a .fshot project, or a model file as a new document with the file.import op - `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group - `path`: string; required; A .fshot project, or a model file (glb, gltf, obj, stl, ply, 3mf, fbx, step, stp, iges, igs) opened as a new document; the other options apply to a model only - `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `template`: string; Material template id (template.list) applied to the imported parts when the import finishes, in the same undo step - `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size - `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y @@ -613,6 +1090,7 @@ Import a model (glb, gltf, obj, stl, ply, 3mf, fbx, step, iges) with clean-up as - `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group - `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker - `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `template`: string; Material template id (template.list) applied to the imported parts when the import finishes, in the same undo step - `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size - `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y @@ -814,6 +1292,7 @@ Start importing a model in the background with the file.import options and retur - `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group - `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker - `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `template`: string; Material template id (template.list) applied to the imported parts when the import finishes, in the same undo step - `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size - `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y @@ -1117,7 +1596,7 @@ Note: read-only. ## render.queue_add -Queue a final render of the current document (as it is now) or of a saved project: camera (index, name, active or all), size, samples, passes, denoise, device, output folder, file name template and format (one multi-layer exr, one layered psd, or one png, jpeg or tiff per pass). Jobs render one at a time in the background while the viewport keeps working; files appear only when complete. Answers the new jobs and the queue. +Queue a final render of the current document (as it is now) or of a saved project: camera (index, name, active or all), size, samples, passes, denoise, device, output folder, file name template and format (one multi-layer exr, one layered psd, or one png, jpeg or tiff per pass); measurements true draws the visible measurements into the beauty. Jobs render one at a time in the background while the viewport keeps working; files appear only when complete. Answers the new jobs and the queue. - `alpha`: boolean; Write an alpha channel with the beauty; on for a transparent background when absent (never in jpeg) - `ao_distance`: number; range -inf to 1000; Reach of the ambient_occlusion pass in metres @@ -1132,6 +1611,7 @@ Queue a final render of the current document (as it is now) or of a saved projec - `frame`: integer; default 1; range 0 to inf; Value of the {frame} token (4 digits) - `height`: integer; range 1 to 16384; Output height; the document's when absent - `label`: string; Free text shown in the list +- `measurements`: boolean; default false; Draw the document's visible measurements into the beauty (lines, end ticks and labels, as measure.render does; pinhole and orthographic cameras) - `name`: string; File name template without extension; tokens {project} {camera} {pass} {date} {time} {frame} {job} {width} {height} {samples}; default {project}_{camera}_{pass} - `overwrite`: boolean; Replace existing files; otherwise _2, _3, ... is added - `passes`: array of string; Passes written beside the beauty (names or groups); the document's render.passes when absent @@ -1227,6 +1707,310 @@ Free Open Image Denoise's device and the filters it keeps per picture size (thei - no parameters +## shot.list + +The document's shots in order: each one's id, name, include flags, a short summary of what it restores, whether the document matches it now, and the nodes it names that are gone (skipped when applied). id lists one shot; full adds the captured state. + +- `full`: boolean; default false; Add each shot's captured state (camera, image style, environment, ground, render settings, lights, visibility, variants) under state +- `id`: string; Only this shot + +Note: read-only. + +## shot.render + +Queue one final render per shot (the given ids, or every shot), each of a copy of the document with that shot applied; the document itself is not changed. Takes render.queue_add's output, size, samples, passes, camera and device arguments; the file name's {shot} token is the shot's name (default name {project}_{shot}_{pass}). Answers the new jobs and the queue. + +- `alpha`: boolean; Write an alpha channel with the beauty; on for a transparent background when absent (never in jpeg) +- `ao_distance`: number; range -inf to 1000; Reach of the ambient_occlusion pass in metres +- `camera`: value; Camera index, camera name, active (the default: the document's camera as it is now) or all (one job per camera) +- `compression`: string; exr: none, zips, zip (default), piz; tiff: none, deflate (default); psd: raw, rle, zip (default) +- `denoise`: boolean; Denoise the beauty with the document's render.denoising (denoiser, quality_final, strength); the document's render.denoise when absent +- `depth`: integer (8 | 16); default 8; Bits per channel of png, psd and integer tiff +- `device`: string; cpu, gpu (the best adapter) or gpu:; the session's render device when absent. A GPU that cannot render the scene falls back to the CPU with a note. +- `float`: boolean; tiff only: 32-bit float scene-linear instead of display-referred integers +- `folder`: string; required; Absolute output folder; created when missing. The engine writes nowhere else. +- `format`: string (exr | psd | png | jpeg | tiff); default "png"; exr: one multi-layer OpenEXR (scene-linear ACEScg); psd: one layered Photoshop file; png, jpeg, tiff: one file per pass +- `frame`: integer; default 1; range 0 to inf; Value of the {frame} token (4 digits) +- `height`: integer; range 1 to 16384; Output height; the document's when absent +- `ids`: array of string; Shots to render, in this order; every shot in list order when absent +- `label`: string; Free text shown in the list; "Shot: " when absent +- `measurements`: boolean; default false; Draw the document's visible measurements into the beauty (lines, end ticks and labels, as measure.render does; pinhole and orthographic cameras) +- `name`: string; File name template without extension; tokens {project} {shot} {camera} {pass} {date} {time} {frame} {job} {width} {height} {samples} {config} {variant}; default {project}_{shot}_{pass} +- `overwrite`: boolean; Replace existing files; otherwise _2, _3, ... is added +- `passes`: array of string; Passes written beside the beauty (names or groups); the document's render.passes when absent +- `precision`: string (half | float); default "half"; exr colour precision (depth, position, ids and Cryptomatte are always float) +- `quality`: integer; range 1 to 100; jpeg quality (default 90) +- `samples`: integer; range 1 to 1048576; Samples per pixel; the document's when absent +- `seed`: integer; range 0 to inf; Sampler seed; the document's when absent +- `transparent`: boolean; Transparent background; the document's background when absent +- `width`: integer; range 1 to 16384; Output width; the document's when absent + +## variant.list + +Material variant sets: each set's covered parts with names, its variants (id, name, active, whether the parts wear it now, a swatch colour from the material most of its parts wear, and every part and material with any that would be skipped) and the active variant; the active model set; materials only variants use are listed in variant_materials. + +- no parameters + +Note: read-only. + +## model_set.list + +Model sets in order: id, name, active, whether the scene shows exactly its nodes now, and its nodes with name, kind, visibility and any that no longer exist. + +- no parameters + +Note: read-only. + +## variant.diff + +What choosing a variant would change, without changing anything: the parts whose material would change (from and to), the parts already wearing theirs, and the entries variant.select would skip with the reason (missing_part, not_a_part, locked, missing_material). + +- `set`: ['string', 'integer']; required; Variant set id +- `variant`: ['string', 'integer']; required; Variant id + +Note: read-only. + +## config.get + +The configurator: options with their choices and actions, the choice in force for each, whether each choice keeps every rule with the other options as they are (allowed; config.select on a choice that is not moves other options), the rules, and the current configuration's name and whether it keeps every rule. + +- no parameters + +Note: read-only. + +## config.check + +Problems with the configurator: rules naming missing options or choices, options with no valid choice, choices that no valid configuration can use, a current configuration that breaks a rule, and actions naming missing nodes, materials, variants, model sets or shots. ok is true when there are none. + +- no parameters + +Note: read-only. + +## config.list + +Every valid configuration (one choice per option that keeps every rule), in option and choice order, up to limit, with the total count. Each has a name made from option and choice names and its selection for config.apply. + +- `limit`: integer; default 100; range 1 to 10000; Most configurations listed; the count covers them all + +Note: read-only. + +## config.render_all + +Queue one final render per valid configuration (up to limit): each renders a copy of the document with that configuration applied, so the open document never changes. Takes render.queue_add's arguments; file names may use {config} and {variant}, and default to {project}_{config}_{pass}. Answers the new jobs. + +- `alpha`: boolean; Write an alpha channel with the beauty; on for a transparent background when absent (never in jpeg) +- `ao_distance`: number; range -inf to 1000; Reach of the ambient_occlusion pass in metres +- `camera`: value; Camera index, camera name, active (the default: the document's camera as it is now) or all (one job per camera) +- `compression`: string; exr: none, zips, zip (default), piz; tiff: none, deflate (default); psd: raw, rle, zip (default) +- `denoise`: boolean; Denoise the beauty with the document's render.denoising (denoiser, quality_final, strength); the document's render.denoise when absent +- `depth`: integer (8 | 16); default 8; Bits per channel of png, psd and integer tiff +- `device`: string; cpu, gpu (the best adapter) or gpu:; the session's render device when absent. A GPU that cannot render the scene falls back to the CPU with a note. +- `float`: boolean; tiff only: 32-bit float scene-linear instead of display-referred integers +- `folder`: string; required; Absolute output folder; created when missing. The engine writes nowhere else. +- `format`: string (exr | psd | png | jpeg | tiff); default "png"; exr: one multi-layer OpenEXR (scene-linear ACEScg); psd: one layered Photoshop file; png, jpeg, tiff: one file per pass +- `frame`: integer; default 1; range 0 to inf; Value of the {frame} token (4 digits) +- `height`: integer; range 1 to 16384; Output height; the document's when absent +- `label`: string; Free text shown in the list +- `limit`: integer; default 100; range 1 to 10000; Most configurations queued, in list order +- `measurements`: boolean; default false; Draw the document's visible measurements into the beauty (lines, end ticks and labels, as measure.render does; pinhole and orthographic cameras) +- `name`: string; default "{project}_{config}_{pass}"; File name template without extension; render.queue_add's tokens plus {config} (the configuration's name) and {variant} (the active variants) +- `overwrite`: boolean; Replace existing files; otherwise _2, _3, ... is added +- `passes`: array of string; Passes written beside the beauty (names or groups); the document's render.passes when absent +- `precision`: string (half | float); default "half"; exr colour precision (depth, position, ids and Cryptomatte are always float) +- `quality`: integer; range 1 to 100; jpeg quality (default 90) +- `samples`: integer; range 1 to 1048576; Samples per pixel; the document's when absent +- `seed`: integer; range 0 to inf; Sampler seed; the document's when absent +- `transparent`: boolean; Transparent background; the document's background when absent +- `width`: integer; range 1 to 16384; Output width; the document's when absent + +## template.list + +The material templates: FormShot's own from the library's templates folder, then the user's own (user/...), each with its name, description, rule count, file, valid plus error, and the library presets it names that are missing. + +- no parameters + +Note: read-only. + +## template.get + +One material template with its rules in order (field, key, pattern, and the preset or stored material each applies, with the preset's name). + +- `id`: string; required; Template id (cad-materials, user/my-rules) + +Note: read-only. + +## template.save + +Save a material template as one of the user's own (user/), or replace one given id; every pattern is checked and every preset id must be in the library. + +- `description`: string; What the template is for +- `id`: string; Replace this user template (user/...) instead of saving a new one +- `name`: string; required; Template name +- `rules`: array of object; required; Rules in order; the first rule matching a part decides its material + +## template.remove + +Delete one of the user's own material templates; FormShot's own cannot be removed. + +- `id`: string; required; Id of one of the user's own templates (user/...) + +## template.preview + +Which material a template would put on each part without changing anything: per part its source material name, current material, the first rule matching it and the target, with counts of matched, unmatched and changing parts and the parts per rule. + +- `id`: string; required; Template id +- `parts`: array of ['integer', 'string']; Parts or groups whose parts to look at (every part when absent) + +Note: read-only. + +## template.apply + +Apply a material template as one undo step: each part takes the material of the first rule matching it (a library preset built as library.apply builds it, or the template's stored material; an identical document material is reused), parts no rule matches keep theirs, and each changed part keeps its original material name in source.material. + +- `id`: string; required; Template id +- `parts`: array of ['integer', 'string']; Parts or groups whose parts the template dresses (every part when absent) + +## template.capture + +A material template from the current document: one rule per distinct source material name on parts, applying the material those parts wear now, stored in the template (textures left out); answered with notes, and saved as a user template when save is true. + +- `description`: string; What the template is for +- `name`: string; required; Name of the captured template +- `save`: boolean; default false; Also save it as one of the user's templates (otherwise only answered, ready for template.save) + +## measure.list + +Every measurement in order with its current world points (a distance's two ends; an angle's vertex and arm ends; a size box's eight corners), its value in metres or degrees and as text in the document's display unit, its definition, and the nodes it names that are gone (missing; the value is null then). id lists one. + +- `id`: string; Only this measurement +- `visible_only`: boolean; default false; Leave out hidden measurements + +Note: read-only. + +## measure.pick + +The surface point, normal and part under a viewport pixel through the active camera (as view.pick), with the point in the part's own space; snap vertex moves it to the part's nearest vertex within radius pixels. Pass the point and node to measure.add_distance or measure.add_angle. + +- `height`: number; required; range 1 to inf; Viewport height in pixels +- `radius`: number; default 12.0; range 1 to 200; Snap radius in viewport pixels +- `snap`: string (none | vertex); default "none"; vertex moves the point to the picked part's nearest vertex within radius pixels +- `width`: number; required; range 1 to inf; Viewport width in pixels +- `x`: number; required; Viewport x in pixels from the left edge +- `y`: number; required; Viewport y in pixels from the top edge + +Note: read-only. + +## measure.render + +Queue final renders of the document with its visible measurements drawn into the beauty (lines, end ticks and labels in a plain built-in style); render.queue_add (and shot, configurator and frame renders) draw them with measurements true. Takes render.queue_add's output, size, samples, passes, camera and device arguments. + +- `alpha`: boolean; Write an alpha channel with the beauty; on for a transparent background when absent (never in jpeg) +- `ao_distance`: number; range -inf to 1000; Reach of the ambient_occlusion pass in metres +- `camera`: value; Camera index, camera name, active (the default: the document's camera as it is now) or all (one job per camera) +- `compression`: string; exr: none, zips, zip (default), piz; tiff: none, deflate (default); psd: raw, rle, zip (default) +- `denoise`: boolean; Denoise the beauty with the document's render.denoising (denoiser, quality_final, strength); the document's render.denoise when absent +- `depth`: integer (8 | 16); default 8; Bits per channel of png, psd and integer tiff +- `device`: string; cpu, gpu (the best adapter) or gpu:; the session's render device when absent. A GPU that cannot render the scene falls back to the CPU with a note. +- `float`: boolean; tiff only: 32-bit float scene-linear instead of display-referred integers +- `folder`: string; required; Absolute output folder; created when missing. The engine writes nowhere else. +- `format`: string (exr | psd | png | jpeg | tiff); default "png"; exr: one multi-layer OpenEXR (scene-linear ACEScg); psd: one layered Photoshop file; png, jpeg, tiff: one file per pass +- `frame`: integer; default 1; range 0 to inf; Value of the {frame} token (4 digits) +- `height`: integer; range 1 to 16384; Output height; the document's when absent +- `label`: string; Free text shown in the list; "Measured" when absent +- `measurements`: boolean; default false; Draw the document's visible measurements into the beauty (lines, end ticks and labels, as measure.render does; pinhole and orthographic cameras) +- `name`: string; File name template without extension; tokens {project} {camera} {pass} {date} {time} {frame} {job} {width} {height} {samples}; default {project}_{camera}_{pass} +- `overwrite`: boolean; Replace existing files; otherwise _2, _3, ... is added +- `passes`: array of string; Passes written beside the beauty (names or groups); the document's render.passes when absent +- `precision`: string (half | float); default "half"; exr colour precision (depth, position, ids and Cryptomatte are always float) +- `quality`: integer; range 1 to 100; jpeg quality (default 90) +- `samples`: integer; range 1 to 1048576; Samples per pixel; the document's when absent +- `seed`: integer; range 0 to inf; Sampler seed; the document's when absent +- `transparent`: boolean; Transparent background; the document's background when absent +- `width`: integer; range 1 to 16384; Output width; the document's when absent + +## anim.seek + +Show the animation at a time (seconds) or a frame number: the viewport restarts at that time and renders use it; time null shows the document's stored values again. The document does not change. + +- `frame`: integer; range 0 to inf; Frame number counted from the timeline's start (instead of time) +- `time`: value; Seconds; null shows the stored values again + +## anim.status + +The animation's timeline and the time shown: time and frame, start, end, fps, frame count, each track with its target, key times, values and interpolations and the key sitting at the time shown (key_at_time), and the rigs (each with id, kind, name, start, end, node or camera and its other fields; rig_count counts them). + +- no parameters + +Note: read-only. + +## anim.sample + +Values of one target over a list of times (every frame when times is absent), as the renderer would see them, with the times of its keys; rotations also as Euler degrees. For drawing curves in a timeline. + +- `target`: value; required; What the key drives +- `times`: array of number; Seconds; every frame of the timeline when absent + +Note: read-only. + +## anim.render + +Render frames of the animation through the render queue, one job per frame (each with its own progress and cancel), named {project}_{camera}_{frame} by default with 4-digit frame numbers; with video, a movie job after the frames encodes them with ffmpeg into mp4, webm, mov or gif and reports the encoder, the movie's path and any ffmpeg error. Takes every render.queue_add argument but frame and project. + +- `alpha`: boolean; Write an alpha channel with the beauty; on for a transparent background when absent (never in jpeg) +- `ao_distance`: number; range -inf to 1000; Reach of the ambient_occlusion pass in metres +- `camera`: value; Camera index, camera name, active (the default: the document's camera as it is now) or all (one job per camera) +- `compression`: string; exr: none, zips, zip (default), piz; tiff: none, deflate (default); psd: raw, rle, zip (default) +- `denoise`: boolean; Denoise the beauty with the document's render.denoising (denoiser, quality_final, strength); the document's render.denoise when absent +- `depth`: integer (8 | 16); default 8; Bits per channel of png, psd and integer tiff +- `device`: string; cpu, gpu (the best adapter) or gpu:; the session's render device when absent. A GPU that cannot render the scene falls back to the CPU with a note. +- `float`: boolean; tiff only: 32-bit float scene-linear instead of display-referred integers +- `folder`: string; required; Absolute output folder; created when missing. The engine writes nowhere else. +- `format`: string (exr | psd | png | jpeg | tiff); default "png"; exr: one multi-layer OpenEXR (scene-linear ACEScg); psd: one layered Photoshop file; png, jpeg, tiff: one file per pass +- `frames`: array of integer; [first, last] frame numbers to render, 1 being the animation's start; the whole range when absent +- `height`: integer; range 1 to 16384; Output height; the document's when absent +- `label`: string; Free text shown in the list +- `measurements`: boolean; default false; Draw the document's visible measurements into the beauty (lines, end ticks and labels, as measure.render does; pinhole and orthographic cameras) +- `name`: string; File name template of each frame (tokens as render.queue_add; {frame} is the frame number, 4 digits); default {project}_{camera}_{frame} +- `overwrite`: boolean; Replace existing files; otherwise _2, _3, ... is added +- `passes`: array of string; Passes written beside the beauty (names or groups); the document's render.passes when absent +- `precision`: string (half | float); default "half"; exr colour precision (depth, position, ids and Cryptomatte are always float) +- `quality`: integer; range 1 to 100; jpeg quality (default 90) +- `samples`: integer; range 1 to 1048576; Samples per pixel; the document's when absent +- `seed`: integer; range 0 to inf; Sampler seed; the document's when absent +- `step`: integer; default 1; range 1 to inf; Render every step-th frame of the range +- `transparent`: boolean; Transparent background; the document's background when absent +- `video`: object; Encode a movie with ffmpeg after the last frame is written (a movie job queued after the frame jobs); fields folder, format, fps, keep_frames, name, quality +- `width`: integer; range 1 to 16384; Output width; the document's when absent + +## video.ffmpeg + +The ffmpeg program movies are encoded with: whether one is found and where (FORMSHOT_FFMPEG, the Form family's shared install folder, or the PATH), its version, which of FormShot's encoders it lists, the encoder each movie format would use, and the licence of the build. The engine never downloads ffmpeg; the service fetches the family's LGPL build on request. + +- no parameters + +Note: read-only. + +## video.encode + +Queue a movie (mp4, webm, mov or gif) encoded by ffmpeg from frames already on disk (a folder and a file name pattern). The job runs in the render queue: render.queue_list shows its progress, the encoder used, the movie's path and any ffmpeg error; a cancelled job leaves no movie. + +- `alpha`: boolean; Keep the frames' alpha (mov writes ProRes 4444; other formats have none) +- `format`: string (mp4 | webm | mov | gif); mp4: H.264 (a hardware encoder, else libx264 when this ffmpeg has it, else MPEG-4 Part 2); webm: VP9; mov: ProRes 422 (4444 with alpha); gif: palette GIF +- `fps`: number; default 24; range -inf to 240; Frames per second +- `frames`: object; required; fields folder, pattern +- `label`: string; Free text shown in the queue list +- `out`: string; required; Absolute path of the movie; its extension picks the format when format is absent +- `overwrite`: boolean; Replace an existing movie; otherwise _2, _3, ... is added +- `quality`: integer; default 80; range 1 to 100; 1 (smallest file) to 100 (best picture); maps to each encoder's own scale + +## transport.features + +Per light transport feature (spectral, nested_media, volume, subsurface, caustics, cutaways, rounded_edges, fibres, motion_blur): whether the CPU engine renders it, whether the GPU path renders or refuses it (with the refusal code), and whether the open document uses it. A refused scene renders on the CPU. Turn spectral rendering on with render.set_settings values {transport: {spectral: {enabled: true}}}. + +- no parameters + +Note: read-only. + ## node.set_visible Same as scene.set_visible ({id, visible} -> {ids: [id], visible}). @@ -1274,6 +2058,7 @@ Same as file.open ({path} unchanged). - `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group - `path`: string; required; A .fshot project, or a model file (glb, gltf, obj, stl, ply, 3mf, fbx, step, stp, iges, igs) opened as a new document; the other options apply to a model only - `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `template`: string; Material template id (template.list) applied to the imported parts when the import finishes, in the same undo step - `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size - `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y @@ -1289,6 +2074,7 @@ Same as file.import ({path, name?, options?} unchanged). - `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group - `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker - `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `template`: string; Material template id (template.list) applied to the imported parts when the import finishes, in the same undo step - `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size - `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b6f08c9..48ee16da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,68 @@ # Changelog -Versions follow `v*.*.*` with dots. Dates are UTC. FormShot has not been released; these versions exist in the repository only. +Versions follow `v*.*.*` with dots. Dates are US Eastern time; entries before 0.9.0 give the UTC date. FormShot has not been released; these versions exist in the repository only. + +## 0.10.0 · 2026-12-03 + +Advanced light transport: nested media, volumes and subsurface scattering, spectral rendering with dispersion, photon caustics, cutaways with caps, rounded edges and fibres on the CPU; media, motion blur, spectral rendering, cutaways and rounded edges on the GPU, held to the CPU's picture; and a pass over the shots and animation work. + +### Added + +- Media (`fsh_materials` medium, phase and scatter; the translucent and volume material types): absorption by depth in transmissive parts, nesting by medium priority so a liquid sits inside its glass, homogeneous volumes with Henyey-Greenstein scattering and light sampled from inside them, and random-walk subsurface scattering, with coefficients derived from the OpenPBR parameters. +- Spectral rendering (`RenderSettings.transport.spectral`): three hero wavelengths per path, a sigmoid uplift of RGB colours, the CIE 1931 observer and daylight basis (from colour-science, BSD-3-Clause, noticed in NOTICE.md and THIRD-PARTY-NOTICES.txt), continuous dispersion in glass and gems, the physical sky and kelvin lights by their spectra. +- Photon caustics on the CPU (`transport.caustics`): progressive photon passes gathered at diffuse surfaces with a shrinking radius, seen directly, in reflections and through glass, and dispersed into a spectrum in spectral mode. +- Cutaways in renders (`cutaway.set_enabled`, `cutaway.set_targets`): plane, box, sphere and cylinder cuts on chosen parts, with caps in the part's material, a flat colour or none; shadows, reflections and passes follow the cut. +- Rounded edges (`edge_radius`): the shading normal is rounded near edges at render time, on its own part or into touching parts. +- Fibres: velvet, felt, carpet and fur trims grow fibres by density on the parts that wear the material, shaded as fibres. +- The GPU ports: media up to 4 overlapping, motion blur through software traversal, spectral rendering, cutaways up to 32 and rounded edges, each compiled out of the kernel when unused, so other scenes render byte-identically and as fast as before. The GPU refuses with a stable code, and the CPU renders, more than 4 overlapping media (`media_depth`), more cutaways or a colour cap on a thin film (`cutaways`), rounded edges next to caps (`rounded_edges`), caustics (`caustics`) and fibres (`fibres`). `transport.features` lists which engine renders each feature, whether the document uses it and why the GPU would refuse. +- The light transport controls in the window, for spectral rendering, cutaways, rounded edges, media and fibres, translated into every language. The command line's `render` takes `--motion-blur` and `--spectral`. + +### Changed + +- Shots, configurations and animations render with the Final Render window's own options, and measurements can be drawn into any final render; a sequence toasts once when its last frame ends, and the queue shows the movie's encoder. +- The outline, gizmo and raster view modes follow the timeline's time; navigating a keyed camera shows a note with Key camera here and Back to the keyed view; playback uses a lighter streamed preview (about 0.9 to 2.6 pictures per second on two cores). +- Every surface and render settings field is listed in the command schemas, `anim.status` lists the rigs, `scene.summary` reports motion blur and transport, and the set commands can return a field to its default. + +### Fixed + +- Spectral mode showed red glass as grey and flat-colour cutaway caps in the part's colour; sun lights on the CPU ignored light links; a kelvin light's temperature was lost in the snapshot; removing nodes or cameras left references behind in shots, configurations, measurements and rigs, and a material that a variant still uses could be deleted. +- The configurator's Show in Shots opened the Shots page without showing the shot; frame sequences ignored `--float`; boolean command line flags needed a value; a reversed frame range gets its own message; the last seventeen window strings were English in Finnish. +- Add a label from an image was always off in the browser, because the window probed the texture upload route with a GET it never answers (since 0.8.0). +- The Final Render window, the command line help and the setting schemas still said the GPU refuses motion blur and spectral rendering. + +### Checked + +- Each feature renders its reference scene on the CPU. On software Vulkan the GPU matches it: media reference scenes within 0.0048 (under 1e-6 with the shadow catcher off), motion blur and spectral within 0.00001 (dispersive glass 0.0002, the physical sky 0.0019), cutaways and rounded edges within 0.00001 to 0.0001; caustics and fibres are refused loudly and render on the CPU. +- Caustic brightness matches a slow path-traced reference within 0.5 percent, which path tracing alone missed by more than half; with caustics off the CPU output is byte-identical to before. +- Scenes that use none of the new features render byte-identically to 0.9.0 on both tracers, and projects re-save byte for byte. +- An independent QA pass against the 0.8.0 engine: the seven templates and the sample render byte-identically to 0.8.0 on the CPU and on software Vulkan, and 0.8.0 projects re-save byte for byte; a project using every new block re-saves and recovers from its crash journal byte for byte; every new command undoes in one step, and removing a part that shots, variants, the configurator, measurements, tracks, rigs and cutaways name leaves no reference behind. Its GPU figures: liquid 0.0031, smoke 0.0030, wax 0.0006, spectral 0.000001, cutaways 0.00001, rounded edges 0.000001; caustics and fibres refused with their codes. +- Not yet: any physical GPU, Metal or Direct3D 12; the window's WebGPU engine with the new features (its package was not built here); caustics and fibres on the GPU. + +## 0.9.0 · 2026-12-03 + +Shots and animation: named shots, material variants and model sets, a configurator with rules that renders every configuration from one command, material templates for imports, measurements, keyed animation with turntables, orbits and camera paths, motion blur on the CPU, and frame sequences and movies through ffmpeg, each with its page in the window. + +### Added + +- Shots (`shot.add`, `update`, `set`, `remove`, `move`, `duplicate`, `apply`, `list`, `render`): a shot keeps the camera, the image style, the environment and ground, the render settings, each light's on or off, power and colour, every node's visibility and the variant choices, with include flags for what applying it restores. Applying is one undo step that activates a saved camera already showing the view, skips lights and nodes that are gone and reports them; `shot.render` queues one job per shot on a copy of the document with a `{shot}` file name token. The Shots page lists shots, variant sets and model sets with apply, rename, reorder, duplicate and capture. +- Material variants and model sets (the `variant` and `model_set` groups): a variant set covers parts and captures their materials as named variants with swatches and a diff of what choosing one changes; a model set shows its nodes and hides the other sets'; `variant.apply_choice` applies both in one step, and shots keep the choice. +- The configurator (`config.*`): options with choices whose actions put materials on parts, show or hide nodes, choose a variant or a model set, or apply a shot; requires and excludes rules; selecting a choice moves the other options to the nearest valid configuration in one undo step; `config.check` names impossible and never-chosen choices and missing references; `config.list` lists every valid configuration and `config.render_all` queues one render each on copies of the document, with `{config}` and `{variant}` file name tokens. The Configurator page edits options, choices, actions and rules, counts the configurations and renders them all. +- Material templates (`template.list`, `get`, `save`, `remove`, `capture`, `preview`, `apply`, and `template` on `file.import`, `file.open` and `import.start`): first-match rules on the material name, the part name or a metadata key with case-insensitive globs, applying a library preset or a stored material, inside the import's own undo step when given at import; parts keep their original material name in `source.material`. Two of FormShot's own: CAD and engineering material names, and colour words to plastics. A dialog previews, applies, captures and saves them. +- Measurements (`measure.add_distance`, `add_size`, `add_angle`, `set`, `remove`, `clear`, `list`, `pick`, `render`): distances direct or along an axis, size boxes in world or local axes and angles, with points pinned to parts in their own space; values in the display unit with a label precision; vertex snapping when picking; drawn over the viewport by the measure tool and into final renders by `measure.render`. +- Keyed animation (the `animation` document block and `anim.*`): a timeline with a frame rate and range, tracks keying part placement, camera position, target, orientation, lens, focus and aperture, material parameters and light power, colour, temperature, spread and visibility, with step, linear, smooth (monotone cubic) and ease interpolation and shortest-path rotations; `anim.seek` shows the document at a time without touching the history. +- Rigs: turntables of the product or a node about its bounds centre, camera orbits and camera paths (a centripetal Catmull-Rom curve walked at even speed, with a look-at and roll), with eased timing and a direction, held to the animation's frame rate and range. +- Motion blur (`RenderSettings.motion_blur`): parts and the camera move while the shutter is open, set as a fraction of a frame and centred on, opening at or closing at the frame; the CPU path tracer places moving instances at each ray's shutter time and draws a time per camera path. The GPU refuses moving scenes as `motion_blur` and the CPU renders them. +- Frame sequences and movies (`anim.render`, `video.encode`, `video.ffmpeg`): each frame is a queue job on a copy of the document evaluated at its time, and a movie job encodes MP4, WebM, MOV (ProRes) or GIF with ffmpeg, run as a separate program found through `FORMSHOT_FFMPEG`, the Form family's shared install or the PATH, choosing a hardware H.264 encoder, libx264 or MPEG-4 Part 2 for MP4; written through a part file, so a cancelled or failed encode leaves nothing. The service downloads the family's LGPL ffmpeg build on request and checks every file against pinned SHA-256 values. The command line's `render` takes movie outputs, `--frames`, `--turntable`, `--fps`, `--quality` and `--keep-frames`. +- The timeline panel (key lanes with curves, keying from the selection or the camera, rig rows and editors, scrubbing and playback on the wall clock), Render Animation (frames, size, image sequence, movie with its ffmpeg block and download), sequences as one row in the render queue, and a Motion Blur section in Final Render. Commands that create items answer the new item's string id. +- The shots, configurator, measure, animation and movie pages are translated into every interface language. + +### Checked + +- Projects written before these blocks existed open and re-save byte for byte, and each new block is left out of the file while empty; crash journal replay rebuilds shots and the configurator exactly. +- `config.render_all` wrote 8 configurations of a two-option product with a rule, each picture matching its name, and the open document did not change; `shot.render` wrote one picture per shot. +- A 36-frame turntable from `formshot-engine render model.glb out.mp4 --turntable 36` is a 36-frame H.264 MP4 through libx264; without libx264 the same render is MPEG-4 Part 2. Turntable frames step 10 degrees within 3.4e-5 degrees, an orbit keeps its distance exactly and a camera path keeps its speed within 0.04 percent. +- Motion blur on a frame of a moving cube differs from the sharp frame only around the cube; the pages were checked under 4x CPU throttling with no layout shift and no rebuilt containers. +- Not yet: motion blur on the GPU; the raster view modes, outline and gizmo do not follow the timeline's time; streamed playback shows about one picture per second; movies have been encoded on Linux only. ## 0.8.0 · 2026-12-03 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e3c1074e..cc468460 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ Thank you for helping. FormShot is the Form family's 3D product renderer: open a model, dress its parts in materials, light it and render it in one window, with no account, -running on your own computer, and open to agents over MCP. It is at 0.8.0 and not +running on your own computer, and open to agents over MCP. It is at 0.10.0 and not released yet, so the most useful help now is careful use and clear reports. ## Where to start diff --git a/NOTICE.md b/NOTICE.md index bd37912a..23466fd0 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -4,7 +4,7 @@ FormShot is licensed under the Apache License 2.0 (see `LICENSE`). Copyright 202 This file is the human list: what each component is and why it is there. `THIRD-PARTY-NOTICES.txt` lists every package that ships with its version and licence; `./formshot notices` replaces it with the full licence texts (copyright lines, conditions and disclaimers) from the installed Python packages, `frontend/package-lock.json`, `native/Cargo.lock`, `src-tauri/Cargo.lock` and the cargo registry, and `./formshot notices --check` checks it covers what ships. It ships in every installer beside this file, is frozen into the service, and is shown in Preferences under About. -FormShot 0.8.0 is unreleased. Licences marked "to confirm" below were not read from package metadata on the machine that wrote this file, and are confirmed when the lock files are complete and `./formshot notices` runs. +FormShot 0.10.0 is unreleased. Licences marked "to confirm" below were not read from package metadata on the machine that wrote this file, and are confirmed when the lock files are complete and `./formshot notices` runs. ## Included in this repository @@ -63,6 +63,15 @@ FormShot 0.8.0 is unreleased. Licences marked "to confirm" below were not read f | FormCAD kernel worker `formcad-kernel` (release occt-8.0.1, built on OpenCascade by nodemode-ai) | as listed in its release record `occt-licence.json`, which is pinned by SHA-256 and checked before install | opens STEP and IGES files; downloaded into the user cache folder only when the person asks (`./formshot cad fetch` or Preferences > CAD Import), run as a separate process and never linked into FormShot | | Intel Open Image Denoise 2.5.1 (the upstream release archives of RenderKit/oidn, unchanged) with oneTBB | Apache-2.0 (OIDN and oneTBB); its third-party notices list PyTorch (BSD-3-Clause), pytorch-msssim (MIT), CUTLASS (BSD-3-Clause), Catch2 (BSL-1.0, tests only) and oneTBB's own BSD and MIT notices | the optional denoiser; downloaded into the user cache only when the person asks (the Final Render window or `./formshot oidn fetch`), every archive and unpacked file checked against SHA-256 pins carried in `backend/app/routers/denoise.py`; the three licence files (`LICENSE.txt`, `third-party-programs.txt`, `third-party-programs-oneTBB.txt`) are unpacked beside the libraries; loaded at run time, never linked or shipped | +## ffmpeg + +FormShot encodes movies (MP4, WebM, MOV, GIF) from rendered frames by running ffmpeg as a separate program. ffmpeg is never linked into FormShot and is not shipped in its installer. The engine runs the program named by `FORMSHOT_FFMPEG`, else the Form family's build in the shared install folder (`formcut-binaries/ffmpeg-` in the user data folder), else `ffmpeg` on the PATH; it never downloads anything. + +| Program | License | Notes | +| --- | --- | --- | +| FFmpeg 7.1.5, the Form family's build (release `ffmpeg-7.1.5-2` of nodemode-dev/formai-binaries), with libvpx 1.17.0 and libopus 1.6.1 built in, and libva and libdrm (Linux) beside it | FFmpeg: LGPL-2.1-or-later (configured with `--disable-gpl --disable-nonfree`, no libx264 or libx265); libvpx and libopus: BSD-3-Clause; libva, libdrm, nv-codec-headers and AMF: MIT | downloaded by the service only when the person asks (`POST /api/video/ffmpeg/fetch`), every file checked against the SHA-256 pins carried in `backend/app/ffmpeg_fetch.py` before anything is installed; the shared libraries sit beside the program and can be replaced, as the LGPL requires. The exact source (`ffmpeg-7.1.5.tar.xz`, libvpx and libopus) is published with that release, and `LGPL-2.1.txt` and `THIRD-PARTY-NOTICES.txt` are installed beside the program | +| an ffmpeg the person installed | the licence it was built under (an ffmpeg built with `--enable-gpl` is GPL) | used when found; `video.ffmpeg` reports whether it is a GPL build. FormShot only runs it and never redistributes it | + ## Data in the material library The presets in `assets/library/` are our own work under Apache-2.0. Their numbers come from these sources, cited in each preset's `source` field and in `assets/library/README.md`: @@ -88,6 +97,24 @@ The presets in `assets/library/` are our own work under Apache-2.0. Their number | MurmurHash3 x86_32 (Austin Appleby) and the Cryptomatte specification (Psyop) | algorithm and format followed; no code copied | Cryptomatte ids and EXR attributes | | IES LM-63 photometric file format (1986 to 2019 editions) | format followed; the luminaire files used to check the reader (three.js examples) stay outside the repository | `fsh_io::ies` | +## Spectral rendering data: colour-science + +The CIE 1931 2 degree colour-matching functions (360 to 830 nm at 1 nm) and the CIE daylight basis S0, S1 and S2 (360 to 830 nm at 5 nm) that spectral rendering ships in `native/crates/fsh-render-cpu/src/spectral/cie.rs` were converted, values unchanged, from colour-science (`colour/colorimetry/datasets/cmfs.py`, "CIE 1931 2 Degree Standard Observer", and `colour/colorimetry/datasets/illuminants/sds_d_illuminant_series.py`, github.com/colour-science/colour, branch develop). They were compared with the CIE's own table (CIE 018:2019 table 6), which was not copied. colour-science is distributed under the BSD-3-Clause licence, reproduced here from the package's `LICENSE` file: + +```text +Copyright 2013 Colour Developers + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE +``` + ## Trademarks glTF is a trademark of the Khronos Group Inc. FBX is a trademark of Autodesk, Inc. Other names are the property of their owners. They are used only to describe compatibility and file formats; FormShot is not affiliated with or endorsed by them. FormShot's features carry its own names, and no other product's artwork, presets, materials or code are included. diff --git a/README.md b/README.md index aaae539a..0621c510 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version 0.8.0 + version 0.10.0 Rust TypeScript macOS, Windows, Linux @@ -65,7 +65,7 @@ ## Features -FormShot is at 0.8.0 and has not been released. This is what exists in the repository today: +FormShot is at 0.10.0 and has not been released. This is what exists in the repository today: - **The window.** Home with recent projects, four starting templates and a Trash you can restore from; the workspace with the live viewport, a material library panel, an inspector (Scene, Camera, Environment, Image and more) and a status bar; menus, a command palette, Preferences with a shortcut editor, 29 themes and the interface in English and 23 more languages. - **The live viewport.** Rendered, Material preview, Solid and Wireframe modes (the last three drawn in the window with WebGL2); click and box selection with a selection outline; a move, rotate and scale gizmo in world or local space with snapping; navigation presets for mouse, trackpad and touch; Frame Selection, Frame All, the six views and composition guides; light and camera outlines. While you move the camera the path tracer drops to fast low-resolution passes and climbs back to full resolution when you stop. A chip says what is drawing, on which device, and why the window is not drawing itself when it is not; the island menu picks the device, the viewport quality and adaptive sampling. @@ -85,7 +85,16 @@ FormShot is at 0.8.0 and has not been released. This is what exists in the repos - **Pictures.** PNG and Radiance HDR read and written, OpenEXR read (scanline, uncompressed or RLE, ZIP, PIZ and PXR24), JPEG read; final pictures written by FormShot's own writers as PNG (8 and 16 bit), JPEG, TIFF (8, 16 and 32-bit float), multi-layer OpenEXR (half or float; ZIP, ZIPS or PIZ) and layered PSD (8 or 16 bit). - **Render passes and the queue.** 23 passes on both path tracers: nine light passes that add up to the beauty, depth, normal, position, albedo, roughness, uv, object and material ids, alpha, sample count, shadow, ambient occlusion, the catcher's shadow and reflection, and Cryptomatte object and material mattes. The Final Render window puts the output size first, then samples, camera, passes, format, file name template, folder and denoiser; the render queue renders jobs one after another in the background while the viewport keeps working, and writes each through a part file so a cancelled job leaves nothing half-written. See [`docs/OUTPUT.md`](docs/OUTPUT.md). - **Denoising.** FormShot's own edge-aware denoiser (Fast, Balanced and High, guided by the film's albedo, normal, depth and variance) on the processor and, for the viewport, on the graphics card; Intel Open Image Denoise downloaded on request, checked against its pinned SHA-256 and loaded at run time, with the own denoiser standing in and saying why when it is missing. See [`docs/DENOISE.md`](docs/DENOISE.md). -- **The command line.** `./formshot render model.glb out.png --samples 256` renders a picture without the window. `./formshot cli` runs the engine's own program, `formshot-engine`, with `render`, `info`, `convert` (with import options), `probe`, `reimport`, `devices`, `bench`, `catalogue`, `dispatch`, `version` and `help`. Run so far: the sample scene renders byte-identical on 1 and 2 threads, a GLB and `.fshot` round trip renders the same picture from both files, and `bench` renders it on the processor, software Vulkan and software OpenGL within 0.00001 mean difference of each other. +- **Shots.** Named views kept in the project: each keeps the camera, the image style, the environment and ground, the render settings, the lights, what is shown and the chosen variants, with flags for what applying it restores. Apply one in one undo step, see which no longer match the document, and render all of them through the queue with the shot's name in the file name. The Shots page edits them. See [`docs/SHOTS.md`](docs/SHOTS.md). +- **Material variants and model sets.** Variant sets capture the materials of chosen parts (black, white, walnut), and model sets show one group of parts and hide the others (with stand, without); choosing either is one undo step, and each shot remembers its choices. +- **The configurator.** Options with choices (colour, trim, accessories) whose actions put materials on parts, show or hide parts, choose variants and model sets or apply a shot, with requires and excludes rules between options. It lists every valid configuration, moves other options to the nearest valid one when a choice breaks a rule, checks itself for impossible choices, and renders every configuration from one command, `config.render_all`, with `{config}` and `{variant}` in the file names. See [`docs/CONFIGURATOR.md`](docs/CONFIGURATOR.md). +- **Material templates.** Saved rules that dress imported parts by material name, part name or file path, applied after an import or during it, previewed before they change anything, and captured from a dressed document; two of FormShot's own match engineering material names and colour words. See [`docs/TEMPLATES.md`](docs/TEMPLATES.md). +- **Measurements.** Distances (direct or along an axis), size boxes in world or local axes and angles, pinned to parts so they follow them, listed in the document's display unit, drawn over the viewport with vertex snapping and, when asked, into final renders. See [`docs/MEASURE.md`](docs/MEASURE.md). +- **Animation.** A timeline with keys on part placement, camera position, target, lens and focus, material parameters and light power, colour and temperature, with step, linear, smooth and ease interpolation; turntables, camera orbits and camera paths as rigs; the timeline panel with key lanes, curves, scrubbing and playback in the viewport. See [`docs/ANIMATION.md`](docs/ANIMATION.md). +- **Motion blur.** Parts and the camera move while the shutter is open, set as a fraction of a frame or a shutter angle and centred on, opening at or closing at the frame; both path tracers render it. +- **Light transport.** Liquids, glass and gems absorb light by their depth, parts nest by medium priority (a drink in a glass), volumes scatter (smoke, fog) and subsurface parts glow from within by a random walk (wax, marble, milk); spectral rendering follows wavelengths for dispersion in prisms and gems; photon caustics focus light through glass and off metal onto surfaces; cutaways open parts with caps in the part's material or a flat colour; rounded edges give sharp CAD corners a small radius at render time; fibres grow on velvet, felt, carpet and fur. `transport.features` says which engine renders each: the GPU renders media, spectral, cutaways and rounded edges, and hands caustics and fibres to the CPU with a note. See [`docs/TRANSPORT.md`](docs/TRANSPORT.md) and [`docs/MATERIALS.md`](docs/MATERIALS.md). +- **Frame sequences and movies.** Render Animation renders every frame (or a range and a step) through the render queue as PNG, JPEG, TIFF, OpenEXR or PSD and encodes MP4, WebM, MOV (ProRes) or GIF with ffmpeg, run as a separate program: one the person set, the Form family's shared download (fetched on request and checked against pinned SHA-256 values) or the one on the PATH. Each frame is its own queue job, and the queue shows the sequence as one row. See [`docs/VIDEO.md`](docs/VIDEO.md). +- **The command line.** `./formshot render model.glb out.png --samples 256` renders a picture without the window. `./formshot cli render model.glb out.mp4 --turntable 36` renders a turntable movie, and `--frames A-B` renders part of a project's animation. `./formshot cli` runs the engine's own program, `formshot-engine`, with `render`, `info`, `convert` (with import options), `probe`, `reimport`, `devices`, `bench`, `catalogue`, `dispatch`, `version` and `help`. Run so far: the sample scene renders byte-identical on 1 and 2 threads, a GLB and `.fshot` round trip renders the same picture from both files, and `bench` renders it on the processor, software Vulkan and software OpenGL within 0.00001 mean difference of each other. - **The agent dock.** A shell, Chat and tabs for Claude Code, Codex, Cursor and Antigravity, each connected to FormShot's MCP server. Everything else in this README marked planned is on the plan with the version it is due in, and is not built yet. @@ -116,6 +125,9 @@ The output names the device that drew the picture, and adds a `note:` line when - Textured materials in the window's own WebGPU path tracer have run only against a stand-in viewport; dispersion stays within the three colour channels, and shadows through glass are opaque. - STEP and IGES through the CAD worker have run on Linux x86_64 only; the worker reports no progress inside one body. - FBX is read by the desktop engine, not by the engine in the browser. +- The GPU engine hands caustics and fibres to the CPU, and also scenes where more than 4 transparent or subsurface parts overlap, more than 32 cutaways, a flat-colour cap on a part with a thin film, or rounded edges next to a cap; the output says why. +- Playback in the streamed viewport shows two or three pictures per second; the window's own WebGPU engine does not use the lighter playback preview. +- MP4 from the Form family's ffmpeg build is H.264 only through a hardware encoder and otherwise MPEG-4 Part 2; an ffmpeg with libx264 that the person installed gives H.264. Movies have been encoded on Linux only. - The Tauri desktop build has been built and run only by the owner, on macOS, at 0.6.0. ## Everything in the box @@ -123,23 +135,23 @@ The output names the device that drew the picture, and adds a `note:` line when
-

Today (0.8.0)

- Home and projects · Scene tree · CPU path tracer · GPU path tracer · Live viewport with raster modes, selection and gizmo · Region render on the GPU · Device choice and bench · Lights with spread, softness, IES and linking · Environment pins, dome, backplate and background image · Physical sky · Studio presets · Every common lens, bladed apertures and Pick focus · Grade, lens effects and display transforms · OpenColorIO configs · WebGPU self-check · 23 render passes with Cryptomatte · The Final Render window and the render queue · PNG, JPEG, TIFF, OpenEXR and PSD output · Own denoiser on CPU and GPU · Open Image Denoise on request · .fshot projects · Crash recovery commands · Import with background jobs and reimport · STEP and IGES through FormCAD's kernel · Hand-offs from the Form apps · Material types, texture slots, the node graph and labels, rendered on both tracers · Thin film and dispersion · Material library with 249 presets · Command line render · MCP · Agent dock +

Today (0.10.0)

+ Home and projects · Scene tree · CPU path tracer · GPU path tracer · Live viewport with raster modes, selection and gizmo · Region render on the GPU · Device choice and bench · Lights with spread, softness, IES and linking · Environment pins, dome, backplate and background image · Physical sky · Studio presets · Every common lens, bladed apertures and Pick focus · Grade, lens effects and display transforms · OpenColorIO configs · WebGPU self-check · 23 render passes with Cryptomatte · The Final Render window and the render queue · PNG, JPEG, TIFF, OpenEXR and PSD output · Own denoiser on CPU and GPU · Open Image Denoise on request · .fshot projects · Crash recovery commands · Import with background jobs and reimport · STEP and IGES through FormCAD's kernel · Hand-offs from the Form apps · Material types, texture slots, the node graph and labels, rendered on both tracers · Thin film and dispersion · Material library with 249 presets · Shots · Material variants and model sets · The configurator with rules and render-all · Material templates · Measurements · Keyed animation and the timeline · Turntables, orbits and camera paths · Motion blur on both tracers · Frame sequences and movies through ffmpeg · Nested media, volumes and subsurface · Spectral rendering · Photon caustics · Cutaways with caps · Rounded edges · Fibres · Command line render · MCP · Agent dock

Planned

- The WebGPU path tracer in the window proven on a real graphics card, and region render on the CPU engine (after 0.4.0) · Shots, animation and advanced light transport (0.9.0 to 0.10.0) · Editors and exchange (0.11.0 to 0.12.0) · Agents, render farm and release (0.13.0 to 0.14.0) + The WebGPU path tracer in the window proven on a real graphics card, and region render on the CPU engine (after 0.4.0) · Caustics and fibres on the GPU (not scheduled yet) · Editors and exchange (0.11.0 to 0.12.0) · Agents, render farm and release (0.13.0 to 0.14.0)

Formats

- Native: .fshot · Models in: glTF/GLB, OBJ, STL, PLY, 3MF, FBX, STEP, IGES · Pictures: PNG, HDR and EXR in; PNG, JPEG, TIFF, HDR, multi-layer EXR and layered PSD out; PNG, JPEG, HDR and EXR textures kept in projects · Planned: video, GLB, USD out + Native: .fshot · Models in: glTF/GLB, OBJ, STL, PLY, 3MF, FBX, STEP, IGES · Pictures: PNG, HDR and EXR in; PNG, JPEG, TIFF, HDR, multi-layer EXR and layered PSD out; PNG, JPEG, HDR and EXR textures kept in projects · Movies out: MP4, WebM, MOV (ProRes) and GIF through ffmpeg · Planned: GLB, USD out
## Built for agents -The engine's 156 commands (53 document commands, 38 engine commands, 50 import, CAD, hand-off, material, library, lighting, camera, image, output and denoise commands, and 15 aliases) are listed in one catalogue built by `native/crates/fsh-commands`; the window, the command line and the MCP server all call them. +The engine's 241 commands (112 document commands, 38 engine commands, 76 import, CAD, hand-off, material, library, lighting, camera, image, output, denoise, shot, variant, configurator, template, measurement, animation, video and transport commands, and 15 aliases) are listed in one catalogue built by `native/crates/fsh-commands`; the window, the command line and the MCP server all call them. ```sh ./formshot mcp # MCP server on stdio for Claude Code, Codex, Cursor and Antigravity @@ -187,7 +199,7 @@ cd formshot Render from the command line with `./formshot render model.glb out.png --samples 256` (also `--width`, `--height`, `--threads`, `--seed`, `--denoise` and `--device`). `./formshot engine wasm` builds the optional in-window engine; the window works without it. `./formshot desktop dev` opens the desktop window instead, after `./formshot install-desktop`. On Windows use `formshot_oc_install.bat` and `formshot.bat`. `FORMSHOT_DATA` moves the data folder and `FORMSHOT_PROJECTS` the projects folder (`~/Documents/FormShot` by default). > [!IMPORTANT] -> **Status:** pre-release. FormShot 0.6.0 has the shell, the document and project file, the CPU and GPU path tracers, the live viewport with region render on the GPU, and the command line render. It has not been built or tested as a desktop app on any platform yet, and GPU rendering has run only on software drivers (see [Known limits](#known-limits)). See [`CHANGELOG.md`](CHANGELOG.md). +> **Status:** pre-release. FormShot 0.10.0 has the shell, the document and project file, the CPU and GPU path tracers, the live viewport, import, materials and the library, lighting, cameras and the picture, render passes and the queue, denoising, shots, variants and the configurator, measurements, animation and movies, advanced light transport, and the command line render. It has not been built or tested as a desktop app on any platform yet, and GPU rendering has run only on software drivers (see [Known limits](#known-limits)). See [`CHANGELOG.md`](CHANGELOG.md). **Contributing:** branch from `main`, keep changes to source here, and leave packaging and releases to FormCompiler. See [`CONTRIBUTING.md`](CONTRIBUTING.md), [`.docs/BRANCHING.md`](.docs/BRANCHING.md) and [`AGENTS.md`](AGENTS.md). @@ -200,7 +212,7 @@ Render from the command line with `./formshot render model.glb out.png --samples | `backend/` · `src-tauri/` | FastAPI service · Tauri 2 desktop shell | | `setup/` · `mcp/` | the scripts behind `./formshot` · the MCP stdio bridge | -Docs: [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md), [`docs/GPU-ENGINE.md`](docs/GPU-ENGINE.md), [`docs/VIEWPORT.md`](docs/VIEWPORT.md), [`docs/IMPORT.md`](docs/IMPORT.md), [`docs/MATERIALS.md`](docs/MATERIALS.md), [`docs/LIBRARY.md`](docs/LIBRARY.md), [`docs/FILE-FORMAT.md`](docs/FILE-FORMAT.md), [`.docs/wiki`](.docs/wiki), [`CHANGELOG.md`](CHANGELOG.md) · Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md) +Docs: [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md), [`docs/GPU-ENGINE.md`](docs/GPU-ENGINE.md), [`docs/VIEWPORT.md`](docs/VIEWPORT.md), [`docs/IMPORT.md`](docs/IMPORT.md), [`docs/MATERIALS.md`](docs/MATERIALS.md), [`docs/LIBRARY.md`](docs/LIBRARY.md), [`docs/LIGHTING.md`](docs/LIGHTING.md), [`docs/IMAGE.md`](docs/IMAGE.md), [`docs/OUTPUT.md`](docs/OUTPUT.md), [`docs/DENOISE.md`](docs/DENOISE.md), [`docs/SHOTS.md`](docs/SHOTS.md), [`docs/CONFIGURATOR.md`](docs/CONFIGURATOR.md), [`docs/TEMPLATES.md`](docs/TEMPLATES.md), [`docs/MEASURE.md`](docs/MEASURE.md), [`docs/ANIMATION.md`](docs/ANIMATION.md), [`docs/VIDEO.md`](docs/VIDEO.md), [`docs/TRANSPORT.md`](docs/TRANSPORT.md), [`docs/FILE-FORMAT.md`](docs/FILE-FORMAT.md), [`.docs/wiki`](.docs/wiki), [`CHANGELOG.md`](CHANGELOG.md) · Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md)
diff --git a/SECURITY.md b/SECURITY.md index 8be6afa2..55e20f5a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -7,7 +7,7 @@ FormShot has not been released yet. Until the first release, security fixes go i | Version | Supported | | --- | --- | -| `main` (0.8.0, unreleased) | Yes | +| `main` (0.10.0, unreleased) | Yes | | Anything older | No | ## Reporting a vulnerability diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index bc75c259..54bc3315 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -56,6 +56,9 @@ wgpu. It also added published data and constants whose licences ask that a notice be kept, reproduced below under "Data and constants": the Hosek-Wilkie sky model tables (BSD-3-Clause), the ACES 1.3 CTL transforms (A.M.P.A.S. licence) and the AgX constants as published in Filament (Apache-2.0). +The spectral rendering work added the CIE 1931 colour-matching functions and +the CIE daylight basis as published by colour-science (BSD-3-Clause), also +reproduced under "Data and constants". Intel Open Image Denoise 2.5.1 (Apache-2.0, with oneTBB) is not shipped: it is downloaded into the user cache on request, checked against SHA-256 pins, and loaded at run time; its own LICENSE.txt and third-party-programs files are @@ -550,6 +553,39 @@ Licence: Apache-2.0 (as published in Filament; the licence of the originating Ag Source: https://github.com/google/filament (ToneMapper.cpp, whose header reads "Copyright (C) 2021 The Android Open Source Project" under the Apache License 2.0); originally https://github.com/EaryChow/AgX_LUT_Gen (AgXBaseRec2020.py, sigmoid.py) Note: The Rec.2020 inset and outset matrices and the sigmoid's parameters of T. Sobotka's AgX as built for Blender by E. Chow, used in native/crates/fsh-render-cpu/src/develop/agx.rs and native/crates/fsh-wasm/src/develop.wgsl. The code is our own; the numbers are the published constants. The full Apache-2.0 text is added by ./formshot notices. +------------------------------------------------------------------------------ +data: CIE 1931 2 degree colour-matching functions and CIE daylight basis, as published by colour-science +Licence: BSD-3-Clause +Source: https://github.com/colour-science/colour (colour/colorimetry/datasets/cmfs.py and colour/colorimetry/datasets/illuminants/sds_d_illuminant_series.py, branch develop) +Note: The matching functions (360 to 830 nm at 1 nm) and the daylight basis S0, S1 and S2 (360 to 830 nm at 5 nm), values unchanged, in native/crates/fsh-render-cpu/src/spectral/cie.rs; the GPU engine and the browser engine upload tables built from them (native/crates/fsh-render-gpu/src/spectral.rs). The licence as published in the package's LICENSE file: + +Copyright 2013 Colour Developers + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ============================================================================== Shared licence texts diff --git a/VERSION b/VERSION index a3df0a69..78bc1abd 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.8.0 +0.10.0 diff --git a/agents/manifest.json b/agents/manifest.json index cb58d46e..6ff697d5 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -21,6 +21,8 @@ "scene.set_part_mesh", "scene.set_light", "scene.set_cutaway", + "cutaway.set_enabled", + "cutaway.set_targets", "scene.reparent", "scene.duplicate", "scene.import", @@ -61,6 +63,59 @@ "render.set_settings", "units.set_display", "document.set_info", + "anim.add_rig", + "anim.set_rig", + "anim.remove_rig", + "anim.turntable", + "anim.orbit", + "anim.camera_path", + "config.add_option", + "config.set_option", + "config.remove_option", + "config.move_option", + "config.add_choice", + "config.set_choice", + "config.remove_choice", + "config.move_choice", + "config.add_rule", + "config.remove_rule", + "config.select", + "config.apply", + "shot.add", + "shot.update", + "shot.set", + "shot.remove", + "shot.move", + "shot.duplicate", + "shot.apply", + "variant.add_set", + "variant.set_set", + "variant.remove_set", + "variant.capture", + "variant.add", + "variant.set", + "variant.remove", + "variant.move", + "variant.select", + "model_set.add", + "model_set.set", + "model_set.remove", + "model_set.move", + "model_set.select", + "variant.apply_choice", + "anim.set", + "anim.key", + "anim.set_key", + "anim.remove_key", + "anim.move_key", + "anim.remove_track", + "anim.clear", + "measure.add_distance", + "measure.add_size", + "measure.add_angle", + "measure.set", + "measure.remove", + "measure.clear", "app.version", "app.catalogue", "scene.summary", @@ -149,6 +204,32 @@ "denoise.oidn_status", "denoise.oidn_device", "denoise.oidn_release", + "shot.list", + "shot.render", + "variant.list", + "model_set.list", + "variant.diff", + "config.get", + "config.check", + "config.list", + "config.render_all", + "template.list", + "template.get", + "template.save", + "template.remove", + "template.preview", + "template.apply", + "template.capture", + "measure.list", + "measure.pick", + "measure.render", + "anim.seek", + "anim.status", + "anim.sample", + "anim.render", + "video.ffmpeg", + "video.encode", + "transport.features", "node.set_visible", "node.set_locked", "node.rename", @@ -201,7 +282,23 @@ "render.output_formats", "render.output_thumbnail", "denoise.status", - "denoise.oidn_status" + "denoise.oidn_status", + "shot.list", + "variant.list", + "model_set.list", + "variant.diff", + "config.get", + "config.check", + "config.list", + "template.list", + "template.get", + "template.preview", + "measure.list", + "measure.pick", + "anim.status", + "anim.sample", + "video.ffmpeg", + "transport.features" ], "approval_gated": [ "scene.add_group", @@ -221,6 +318,8 @@ "scene.set_part_mesh", "scene.set_light", "scene.set_cutaway", + "cutaway.set_enabled", + "cutaway.set_targets", "scene.reparent", "scene.duplicate", "scene.import", @@ -261,6 +360,59 @@ "render.set_settings", "units.set_display", "document.set_info", + "anim.add_rig", + "anim.set_rig", + "anim.remove_rig", + "anim.turntable", + "anim.orbit", + "anim.camera_path", + "config.add_option", + "config.set_option", + "config.remove_option", + "config.move_option", + "config.add_choice", + "config.set_choice", + "config.remove_choice", + "config.move_choice", + "config.add_rule", + "config.remove_rule", + "config.select", + "config.apply", + "shot.add", + "shot.update", + "shot.set", + "shot.remove", + "shot.move", + "shot.duplicate", + "shot.apply", + "variant.add_set", + "variant.set_set", + "variant.remove_set", + "variant.capture", + "variant.add", + "variant.set", + "variant.remove", + "variant.move", + "variant.select", + "model_set.add", + "model_set.set", + "model_set.remove", + "model_set.move", + "model_set.select", + "variant.apply_choice", + "anim.set", + "anim.key", + "anim.set_key", + "anim.remove_key", + "anim.move_key", + "anim.remove_track", + "anim.clear", + "measure.add_distance", + "measure.add_size", + "measure.add_angle", + "measure.set", + "measure.remove", + "measure.clear", "selection.set", "selection.clear", "history.undo", @@ -309,6 +461,16 @@ "render.queue_pause", "denoise.oidn_device", "denoise.oidn_release", + "shot.render", + "config.render_all", + "template.save", + "template.remove", + "template.apply", + "template.capture", + "measure.render", + "anim.seek", + "anim.render", + "video.encode", "node.set_visible", "node.set_locked", "node.rename", diff --git a/assets/library/templates/cad-materials.json b/assets/library/templates/cad-materials.json new file mode 100644 index 00000000..9a693272 --- /dev/null +++ b/assets/library/templates/cad-materials.json @@ -0,0 +1,213 @@ +{ + "format": "formshot-material-template", + "version": 1, + "id": "cad-materials", + "name": "CAD and engineering materials", + "description": "Dresses parts by the engineering material names CAD programs export (AL6061, SS304, ABS_black, PC_clear, PA66, POM, EPDM, ...). Matches the material name the part came in with; finishes and colours in the name choose the finish or colour, otherwise a neutral machined or moulded look is used.", + "rules": [ + {"field": "material", "pattern": "*stainless*mirror*", "preset": "metal/stainless-steel-mirror"}, + {"field": "material", "pattern": "*stainless*polish*", "preset": "metal/stainless-steel-austenitic-polished"}, + {"field": "material", "pattern": "*stainless*brush*", "preset": "metal/stainless-steel-brushed"}, + {"field": "material", "pattern": "*stainless*blast*", "preset": "metal/stainless-steel-bead-blasted"}, + {"field": "material", "pattern": "*stainless*bead*", "preset": "metal/stainless-steel-bead-blasted"}, + {"field": "material", "pattern": "*stainless*", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "*inox*", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "ss", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "ss_*", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "ss-*", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "ss *", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "ss3*", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "*aisi*3??*", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "*aisi*4??*", "preset": "metal/stainless-steel-ferritic-polished"}, + {"field": "material", "pattern": "*304*", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "*316*", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "*1.430?*", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "*1.440?*", "preset": "metal/stainless-steel-satin"}, + {"field": "material", "pattern": "*galvani?ed*", "preset": "metal/zinc-polished"}, + {"field": "material", "pattern": "*cast*iron*", "preset": "metal/iron-as-cast"}, + {"field": "material", "pattern": "*steel*polish*", "preset": "metal/iron-polished"}, + {"field": "material", "pattern": "*steel*blast*", "preset": "metal/iron-bead-blasted"}, + {"field": "material", "pattern": "*steel*", "preset": "metal/iron-satin"}, + {"field": "material", "pattern": "s235*", "preset": "metal/iron-satin"}, + {"field": "material", "pattern": "s355*", "preset": "metal/iron-satin"}, + {"field": "material", "pattern": "st37*", "preset": "metal/iron-satin"}, + {"field": "material", "pattern": "st52*", "preset": "metal/iron-satin"}, + {"field": "material", "pattern": "*c45*", "preset": "metal/iron-satin"}, + {"field": "material", "pattern": "*1018*", "preset": "metal/iron-satin"}, + {"field": "material", "pattern": "*1045*", "preset": "metal/iron-satin"}, + {"field": "material", "pattern": "*4140*", "preset": "metal/iron-satin"}, + {"field": "material", "pattern": "*iron*", "preset": "metal/iron-satin"}, + {"field": "material", "pattern": "*anod*black*", "preset": "metal/aluminium-anodised-black"}, + {"field": "material", "pattern": "*anod*blue*", "preset": "metal/aluminium-anodised-blue"}, + {"field": "material", "pattern": "*anod*red*", "preset": "metal/aluminium-anodised-red"}, + {"field": "material", "pattern": "*anod*gold*", "preset": "metal/aluminium-anodised-gold"}, + {"field": "material", "pattern": "*anod*green*", "preset": "metal/aluminium-anodised-green"}, + {"field": "material", "pattern": "*anod*purple*", "preset": "metal/aluminium-anodised-purple"}, + {"field": "material", "pattern": "*anod*bronze*", "preset": "metal/aluminium-anodised-bronze"}, + {"field": "material", "pattern": "*anod*rose*", "preset": "metal/aluminium-anodised-rose"}, + {"field": "material", "pattern": "*alumin*polish*", "preset": "metal/aluminium-polished"}, + {"field": "material", "pattern": "al*polish*", "preset": "metal/aluminium-polished"}, + {"field": "material", "pattern": "*alumin*brush*", "preset": "metal/aluminium-brushed"}, + {"field": "material", "pattern": "al*brush*", "preset": "metal/aluminium-brushed"}, + {"field": "material", "pattern": "*alumin*blast*", "preset": "metal/aluminium-bead-blasted"}, + {"field": "material", "pattern": "al*blast*", "preset": "metal/aluminium-bead-blasted"}, + {"field": "material", "pattern": "*alumin*bead*", "preset": "metal/aluminium-bead-blasted"}, + {"field": "material", "pattern": "al*bead*", "preset": "metal/aluminium-bead-blasted"}, + {"field": "material", "pattern": "*alumin*cast*", "preset": "metal/aluminium-as-cast"}, + {"field": "material", "pattern": "*cast*alumin*", "preset": "metal/aluminium-as-cast"}, + {"field": "material", "pattern": "*alumin*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "alu*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "al", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "al_*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "al-*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "al *", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "al1*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "al2*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "al3*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "al5*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "al6*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "al7*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "almg*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "alsi*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "alzn*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "*2024*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "*5052*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "*5083*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "*6061*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "*6063*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "*6082*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "*7075*", "preset": "metal/aluminium-satin"}, + {"field": "material", "pattern": "*titan*polish*", "preset": "metal/titanium-polished"}, + {"field": "material", "pattern": "*titan*brush*", "preset": "metal/titanium-brushed"}, + {"field": "material", "pattern": "*titan*", "preset": "metal/titanium-satin"}, + {"field": "material", "pattern": "ti6al4v*", "preset": "metal/titanium-satin"}, + {"field": "material", "pattern": "ti-6al*", "preset": "metal/titanium-satin"}, + {"field": "material", "pattern": "*brass*polish*", "preset": "metal/brass-polished"}, + {"field": "material", "pattern": "*brass*brush*", "preset": "metal/brass-brushed"}, + {"field": "material", "pattern": "*brass*", "preset": "metal/brass-satin"}, + {"field": "material", "pattern": "cuzn*", "preset": "metal/brass-satin"}, + {"field": "material", "pattern": "*c360*", "preset": "metal/brass-satin"}, + {"field": "material", "pattern": "*copper*polish*", "preset": "metal/copper-polished"}, + {"field": "material", "pattern": "*copper*brush*", "preset": "metal/copper-brushed"}, + {"field": "material", "pattern": "*copper*", "preset": "metal/copper-satin"}, + {"field": "material", "pattern": "cu", "preset": "metal/copper-satin"}, + {"field": "material", "pattern": "cu_*", "preset": "metal/copper-satin"}, + {"field": "material", "pattern": "cu-*", "preset": "metal/copper-satin"}, + {"field": "material", "pattern": "cu *", "preset": "metal/copper-satin"}, + {"field": "material", "pattern": "*c110*", "preset": "metal/copper-satin"}, + {"field": "material", "pattern": "*chrom*", "preset": "metal/chromium-polished"}, + {"field": "material", "pattern": "*nickel*", "preset": "metal/nickel-satin"}, + {"field": "material", "pattern": "*zinc*", "preset": "metal/zinc-polished"}, + {"field": "material", "pattern": "*zamak*", "preset": "metal/zinc-polished"}, + {"field": "material", "pattern": "*magnesium*", "preset": "metal/magnesium-polished"}, + {"field": "material", "pattern": "*abs*black*", "preset": "plastic/abs-black-satin"}, + {"field": "material", "pattern": "*abs*white*", "preset": "plastic/abs-white-gloss"}, + {"field": "material", "pattern": "*abs*red*", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "*abs*blue*", "preset": "plastic/abs-blue-gloss"}, + {"field": "material", "pattern": "*abs*yellow*", "preset": "plastic/abs-yellow-gloss"}, + {"field": "material", "pattern": "*abs*gr?y*", "preset": "plastic/abs-grey-matte"}, + {"field": "material", "pattern": "*abs*", "preset": "plastic/abs-grey-matte"}, + {"field": "material", "pattern": "*acrylonitrile*", "preset": "plastic/abs-grey-matte"}, + {"field": "material", "pattern": "*pmma*frost*", "preset": "plastic/acrylic-frosted"}, + {"field": "material", "pattern": "*acrylic*frost*", "preset": "plastic/acrylic-frosted"}, + {"field": "material", "pattern": "*pmma*", "preset": "plastic/acrylic-clear"}, + {"field": "material", "pattern": "*acrylic*", "preset": "plastic/acrylic-clear"}, + {"field": "material", "pattern": "*plexi*", "preset": "plastic/acrylic-clear"}, + {"field": "material", "pattern": "*perspex*", "preset": "plastic/acrylic-clear"}, + {"field": "material", "pattern": "*polycarbonate*frost*", "preset": "plastic/polycarbonate-frosted"}, + {"field": "material", "pattern": "pc*frost*", "preset": "plastic/polycarbonate-frosted"}, + {"field": "material", "pattern": "*polycarbonate*", "preset": "plastic/polycarbonate-clear"}, + {"field": "material", "pattern": "pc", "preset": "plastic/polycarbonate-clear"}, + {"field": "material", "pattern": "pc_*", "preset": "plastic/polycarbonate-clear"}, + {"field": "material", "pattern": "pc-*", "preset": "plastic/polycarbonate-clear"}, + {"field": "material", "pattern": "pc *", "preset": "plastic/polycarbonate-clear"}, + {"field": "material", "pattern": "*lexan*", "preset": "plastic/polycarbonate-clear"}, + {"field": "material", "pattern": "*makrolon*", "preset": "plastic/polycarbonate-clear"}, + {"field": "material", "pattern": "*polypropylene*black*", "preset": "plastic/polypropylene-black-satin"}, + {"field": "material", "pattern": "pp*black*", "preset": "plastic/polypropylene-black-satin"}, + {"field": "material", "pattern": "*polypropylene*white*", "preset": "plastic/polypropylene-white-satin"}, + {"field": "material", "pattern": "pp*white*", "preset": "plastic/polypropylene-white-satin"}, + {"field": "material", "pattern": "*polypropylene*", "preset": "plastic/polypropylene-natural"}, + {"field": "material", "pattern": "pp", "preset": "plastic/polypropylene-natural"}, + {"field": "material", "pattern": "pp_*", "preset": "plastic/polypropylene-natural"}, + {"field": "material", "pattern": "pp-*", "preset": "plastic/polypropylene-natural"}, + {"field": "material", "pattern": "pp *", "preset": "plastic/polypropylene-natural"}, + {"field": "material", "pattern": "*nylon*black*", "preset": "plastic/nylon-black-matte"}, + {"field": "material", "pattern": "pa_*black*", "preset": "plastic/nylon-black-matte"}, + {"field": "material", "pattern": "pa-*black*", "preset": "plastic/nylon-black-matte"}, + {"field": "material", "pattern": "pa *black*", "preset": "plastic/nylon-black-matte"}, + {"field": "material", "pattern": "pa6*black*", "preset": "plastic/nylon-black-matte"}, + {"field": "material", "pattern": "pa1*black*", "preset": "plastic/nylon-black-matte"}, + {"field": "material", "pattern": "*polyamide*black*", "preset": "plastic/nylon-black-matte"}, + {"field": "material", "pattern": "*nylon*", "preset": "plastic/nylon-natural-matte"}, + {"field": "material", "pattern": "*polyamide*", "preset": "plastic/nylon-natural-matte"}, + {"field": "material", "pattern": "pa", "preset": "plastic/nylon-natural-matte"}, + {"field": "material", "pattern": "pa_*", "preset": "plastic/nylon-natural-matte"}, + {"field": "material", "pattern": "pa-*", "preset": "plastic/nylon-natural-matte"}, + {"field": "material", "pattern": "pa *", "preset": "plastic/nylon-natural-matte"}, + {"field": "material", "pattern": "pa1*", "preset": "plastic/nylon-natural-matte"}, + {"field": "material", "pattern": "pa4*", "preset": "plastic/nylon-natural-matte"}, + {"field": "material", "pattern": "pa6*", "preset": "plastic/nylon-natural-matte"}, + {"field": "material", "pattern": "*pom*black*", "preset": "plastic/acetal-black-satin"}, + {"field": "material", "pattern": "*acetal*black*", "preset": "plastic/acetal-black-satin"}, + {"field": "material", "pattern": "*delrin*black*", "preset": "plastic/acetal-black-satin"}, + {"field": "material", "pattern": "pom", "preset": "plastic/acetal-white-satin"}, + {"field": "material", "pattern": "pom_*", "preset": "plastic/acetal-white-satin"}, + {"field": "material", "pattern": "pom-*", "preset": "plastic/acetal-white-satin"}, + {"field": "material", "pattern": "pom *", "preset": "plastic/acetal-white-satin"}, + {"field": "material", "pattern": "*acetal*", "preset": "plastic/acetal-white-satin"}, + {"field": "material", "pattern": "*delrin*", "preset": "plastic/acetal-white-satin"}, + {"field": "material", "pattern": "*polyoxymethylene*", "preset": "plastic/acetal-white-satin"}, + {"field": "material", "pattern": "*hdpe*", "preset": "plastic/hdpe-white-matte"}, + {"field": "material", "pattern": "*ldpe*", "preset": "plastic/hdpe-natural"}, + {"field": "material", "pattern": "*polyethylene*", "preset": "plastic/hdpe-natural"}, + {"field": "material", "pattern": "*pvc*", "preset": "plastic/pvc-grey-satin"}, + {"field": "material", "pattern": "*petg*", "preset": "plastic/pet-clear"}, + {"field": "material", "pattern": "pet", "preset": "plastic/pet-clear"}, + {"field": "material", "pattern": "pet_*", "preset": "plastic/pet-clear"}, + {"field": "material", "pattern": "pet-*", "preset": "plastic/pet-clear"}, + {"field": "material", "pattern": "pet *", "preset": "plastic/pet-clear"}, + {"field": "material", "pattern": "pla", "preset": "plastic/pla-white-satin"}, + {"field": "material", "pattern": "pla_*", "preset": "plastic/pla-white-satin"}, + {"field": "material", "pattern": "pla-*", "preset": "plastic/pla-white-satin"}, + {"field": "material", "pattern": "pla *", "preset": "plastic/pla-white-satin"}, + {"field": "material", "pattern": "*polystyrene*", "preset": "plastic/polystyrene-clear"}, + {"field": "material", "pattern": "*silicone*black*", "preset": "rubber/black-rubber-satin"}, + {"field": "material", "pattern": "*silicone*red*", "preset": "rubber/silicone-rubber-red"}, + {"field": "material", "pattern": "*silicone*clear*", "preset": "plastic/pdms-clear"}, + {"field": "material", "pattern": "*silicone*", "preset": "rubber/silicone-rubber-white"}, + {"field": "material", "pattern": "*tpe*", "preset": "rubber/black-rubber-satin"}, + {"field": "material", "pattern": "*tpu*", "preset": "rubber/black-rubber-satin"}, + {"field": "material", "pattern": "*tpv*", "preset": "rubber/black-rubber-satin"}, + {"field": "material", "pattern": "*santoprene*", "preset": "rubber/black-rubber-satin"}, + {"field": "material", "pattern": "*soft*touch*", "preset": "rubber/soft-touch-black"}, + {"field": "material", "pattern": "*epdm*", "preset": "rubber/epdm-grey"}, + {"field": "material", "pattern": "*nbr*", "preset": "rubber/black-rubber-matte"}, + {"field": "material", "pattern": "*nitrile*", "preset": "rubber/black-rubber-matte"}, + {"field": "material", "pattern": "*neoprene*", "preset": "rubber/black-rubber-matte"}, + {"field": "material", "pattern": "*elastomer*", "preset": "rubber/black-rubber-satin"}, + {"field": "material", "pattern": "*rubber*", "preset": "rubber/black-rubber-matte"}, + {"field": "material", "pattern": "*bk7*", "preset": "glass/optical-crown-n-bk7"}, + {"field": "material", "pattern": "*fused*silica*", "preset": "glass/fused-silica"}, + {"field": "material", "pattern": "*quartz*", "preset": "glass/fused-silica"}, + {"field": "material", "pattern": "*boro*", "preset": "glass/window-glass-low-iron"}, + {"field": "material", "pattern": "*glass*frost*", "preset": "glass/window-glass-frosted"}, + {"field": "material", "pattern": "*frost*glass*", "preset": "glass/window-glass-frosted"}, + {"field": "material", "pattern": "*glass*", "preset": "glass/window-glass-clear"}, + {"field": "material", "pattern": "*walnut*", "preset": "wood/walnut-oiled"}, + {"field": "material", "pattern": "*oak*", "preset": "wood/oak-oiled"}, + {"field": "material", "pattern": "*maple*", "preset": "wood/maple-lacquered"}, + {"field": "material", "pattern": "*birch*", "preset": "wood/maple-lacquered"}, + {"field": "material", "pattern": "*beech*", "preset": "wood/maple-lacquered"}, + {"field": "material", "pattern": "*cherry*", "preset": "wood/cherry-oiled"}, + {"field": "material", "pattern": "*teak*", "preset": "wood/teak-oiled"}, + {"field": "material", "pattern": "*ebony*", "preset": "wood/ebony-polished"}, + {"field": "material", "pattern": "*pine*", "preset": "wood/pine-raw"}, + {"field": "material", "pattern": "ash", "preset": "wood/ash-oiled"}, + {"field": "material", "pattern": "ash_*", "preset": "wood/ash-oiled"}, + {"field": "material", "pattern": "ash-*", "preset": "wood/ash-oiled"}, + {"field": "material", "pattern": "ash *", "preset": "wood/ash-oiled"}, + {"field": "material", "pattern": "*plywood*", "preset": "wood/maple-lacquered"}, + {"field": "material", "pattern": "*wood*", "preset": "wood/oak-oiled"} + ] +} diff --git a/assets/library/templates/colour-plastics.json b/assets/library/templates/colour-plastics.json new file mode 100644 index 00000000..6956bdbb --- /dev/null +++ b/assets/library/templates/colour-plastics.json @@ -0,0 +1,69 @@ +{ + "format": "formshot-material-template", + "version": 1, + "id": "colour-plastics", + "name": "Colour words to plastics", + "description": "Dresses parts as moulded plastics by the colour word in their material name, then in their part name (Housing_black, Cover-White, Lens clear): black, white, grey or gray, red, blue, yellow, orange, clear or transparent, frosted, smoke, amber, natural or translucent. Short words such as red only count between separators, so Covered is not red.", + "rules": [ + {"field": "material", "pattern": "*frost*", "preset": "plastic/polycarbonate-frosted"}, + {"field": "material", "pattern": "*smok*", "preset": "plastic/acrylic-smoke"}, + {"field": "material", "pattern": "*amber*", "preset": "plastic/acrylic-amber"}, + {"field": "material", "pattern": "*clear*", "preset": "plastic/polycarbonate-clear"}, + {"field": "material", "pattern": "*transparent*", "preset": "plastic/polycarbonate-clear"}, + {"field": "material", "pattern": "*transluc*", "preset": "plastic/polypropylene-natural"}, + {"field": "material", "pattern": "*natural*", "preset": "plastic/polypropylene-natural"}, + {"field": "material", "pattern": "*black*", "preset": "plastic/abs-black-satin"}, + {"field": "material", "pattern": "*white*", "preset": "plastic/abs-white-gloss"}, + {"field": "material", "pattern": "*grey*", "preset": "plastic/abs-grey-matte"}, + {"field": "material", "pattern": "*gray*", "preset": "plastic/abs-grey-matte"}, + {"field": "material", "pattern": "*blue*", "preset": "plastic/abs-blue-gloss"}, + {"field": "material", "pattern": "*yellow*", "preset": "plastic/abs-yellow-gloss"}, + {"field": "material", "pattern": "*orange*", "preset": "plastic/pla-orange-satin"}, + {"field": "material", "pattern": "red", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "red_*", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "red-*", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "red *", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "*_red", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "*-red", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "* red", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "*_red_*", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "*_red-*", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "*_red *", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "*-red_*", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "*-red-*", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "*-red *", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "* red_*", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "* red-*", "preset": "plastic/abs-red-gloss"}, + {"field": "material", "pattern": "* red *", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "*frost*", "preset": "plastic/polycarbonate-frosted"}, + {"field": "part", "pattern": "*smok*", "preset": "plastic/acrylic-smoke"}, + {"field": "part", "pattern": "*amber*", "preset": "plastic/acrylic-amber"}, + {"field": "part", "pattern": "*clear*", "preset": "plastic/polycarbonate-clear"}, + {"field": "part", "pattern": "*transparent*", "preset": "plastic/polycarbonate-clear"}, + {"field": "part", "pattern": "*transluc*", "preset": "plastic/polypropylene-natural"}, + {"field": "part", "pattern": "*natural*", "preset": "plastic/polypropylene-natural"}, + {"field": "part", "pattern": "*black*", "preset": "plastic/abs-black-satin"}, + {"field": "part", "pattern": "*white*", "preset": "plastic/abs-white-gloss"}, + {"field": "part", "pattern": "*grey*", "preset": "plastic/abs-grey-matte"}, + {"field": "part", "pattern": "*gray*", "preset": "plastic/abs-grey-matte"}, + {"field": "part", "pattern": "*blue*", "preset": "plastic/abs-blue-gloss"}, + {"field": "part", "pattern": "*yellow*", "preset": "plastic/abs-yellow-gloss"}, + {"field": "part", "pattern": "*orange*", "preset": "plastic/pla-orange-satin"}, + {"field": "part", "pattern": "red", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "red_*", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "red-*", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "red *", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "*_red", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "*-red", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "* red", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "*_red_*", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "*_red-*", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "*_red *", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "*-red_*", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "*-red-*", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "*-red *", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "* red_*", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "* red-*", "preset": "plastic/abs-red-gloss"}, + {"field": "part", "pattern": "* red *", "preset": "plastic/abs-red-gloss"} + ] +} diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 6559f530..ba164c62 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # backend HASHOUT_LOG -Living log for the service side, _v0.8.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. +Living log for the service side, _v0.10.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. ## Org-navi-map @@ -33,6 +33,8 @@ backend/ app/routers/library.py /api/library/*: preset thumbnails from the engine's cache, the index, batch queueing app/routers/denoise.py /api/denoise/oidn and /oidn/fetch: Open Image Denoise's status and its pinned, checked download; CLI main() app/routers/output.py /api/output/files, /thumbnail, /open: finished render outputs, cached thumbnails, open folder + app/routers/video.py /api/video/ffmpeg, /ffmpeg/fetch, /movie: the engine's ffmpeg view, the family download on request, movie files; CLI main() + app/ffmpeg_fetch.py the pinned family ffmpeg record (release 7.1.5-2, SHA-256 and size per target file) and its checked install app/agent/ agent bus: config, events, commands, router, terminal, cmd_terminal, claude_code, agent_programs, cmd_agents, cmd_chat, cmd_prefs, external, consent, agent_lookup ``` @@ -45,6 +47,7 @@ backend/ - [Agents, MCP and consent](#agents-mcp-and-consent) - [Import, CAD, hand-offs, textures and the library](#import-cad-hand-offs-textures-and-the-library) - [Denoiser download and render outputs](#denoiser-download-and-render-outputs) +- [ffmpeg and movies](#ffmpeg-and-movies) - [Verification](#verification) ## Layout and names @@ -221,6 +224,22 @@ The engine never touches the network, so the service (and `./formshot oidn fetch - logged: v0.8.0 · 2026-12-03 `GET /api/output/files?folder=&limit=` lists finished outputs (png, jpg, jpeg, exr, psd, tif, tiff; `.part` files skipped) newest first with a thumbnail link. `GET /api/output/thumbnail?path=&size=` answers image/png from the engine's `render.output_thumbnail` (the service has no image library, and fsh-io already decodes these formats), cached in `/formshot/output/thumbs/.png`, newest 4000 kept. `POST /api/output/open {folder}` (window key) opens the folder in the system file browser (`xdg-open`, `open`, `explorer`). Run on 127.0.0.1: a folder listed newest first, a thumbnail 200 then served from the cache, relative folder and `/etc/passwd` 400, open 403 without the key, 200 with it (xdg-open), 404 for a missing folder. Not run: the macOS and Windows branches of open. +## ffmpeg and movies + +### app/routers/video.py, app/main.py · the video router +- refers-to: app/routers/video.py :: router, status, engine_status, ffmpeg_status, ffmpeg_fetch_start, _run, _set, movie_file, movie, main; app/main.py :: include_router(video.router) +- kind: decision +- logged: v0.9.0 · 2026-12-03 + +`app/main.py` imports `video` with the other routers and includes `video.router` (prefix `/api/video`); the lead merged that line. `GET /api/video/ffmpeg` answers `{engine, published, installed, fetch}`: `engine` is the engine's own `video.ffmpeg` reply (where it found ffmpeg, the encoders, the formats), asked through `engine.dispatch` on a worker thread and turned into `{found: false, reason}` when the engine cannot be asked, so the window's block always has something to show; `published` and `installed` come from `ffmpeg_fetch`; `fetch` is the download job. `POST /api/video/ffmpeg/fetch` requires the window key (`window_key.require`), answers 409 with the sentence when this computer has no pinned build, answers `started: false` while a job runs, and otherwise starts one daemon thread `ffmpeg-fetch` that calls `ffmpeg_fetch.install(report)`. The job record (`state` idle, running, done or failed, `stage`, `fraction`, `message`, `release`) lives behind a lock and is published as a `video.ffmpeg` event on every stage change or every 0.25 s, so the window follows by event and polls only as a fallback; every `FetchError` and any other exception becomes a failed job with "Nothing was installed." and never an unhandled error. Nothing downloads on startup, nothing new is bound, and the engine still never touches the network: it finds the installed folder on its next encode, with `FORMSHOT_FFMPEG` first. `GET /api/video/movie?path=` serves a finished movie from an absolute path whose extension is mp4, webm, mov or gif (400 otherwise, 404 when missing) as a `FileResponse` with the right media type. `python -m app.routers.video [status|fetch]` prints the published and installed records or runs the install with a progress line per stage, exit 0, 1 on a failed fetch, 2 on a bad command. The window's ffmpeg block is the client (`src/ui/movie/ffmpeg.ts`). Verified by the video work, not rerun here: the app imported and the fetch route function ran against a fake release folder, a POST without the window key gave 403, the real pins failed on a 42-byte fake with "ffmpeg-x86_64-unknown-linux-gnu is 42 bytes, the record says 383392. Nothing was installed." and left the family folder empty, and `python -m compileall backend/app` passed. Not verified: a real download from GitHub, Windows or macOS data folders. The `/movie` route is not called by the window in this tree (no `/api/video/movie` string in `frontend/src`). + +### app/ffmpeg_fetch.py · the family ffmpeg pins and the checked install +- refers-to: app/ffmpeg_fetch.py :: RELEASE, FFMPEG, LICENCE, SOURCE_URL, SOURCE_SHA256, BASES, MIRROR_ENV, DOCUMENTS, FILES, pins, sources, expected, verify, unpack, install, installed, published; app/routers/cad.py :: FetchError, download, host_triple, sha256_file +- kind: decision +- logged: v0.9.0 · 2026-12-03 + +The Form family's LGPL ffmpeg 7.1.5 (release `7.1.5-2`, licence LGPL-2.1-or-later, source tarball URL and SHA-256 recorded) is pinned in the module the way OIDN is pinned in `denoise.py`: `FILES` holds, for each of four targets (aarch64 and x86_64 macOS, x86_64 Linux, x86_64 Windows), every file of the build with its SHA-256 and size (the ffmpeg and ffprobe programs and the shared libraries under `lib-/`), and `DOCUMENTS` holds the SHA-256 of the LGPL text and the third-party notices. The values were copied from `formai-binaries`' `ffmpeg-licence.json` by a one-off print and written into the file by hand. `install` works in a hidden `.formshot-fetch-*` folder inside `/formcut-binaries` (stale ones older than an hour are removed), downloads `ffmpeg-lgpl--.tar.gz` with `cad.download` from the sources in order (formai-binaries, then formcut-binaries, release tag `ffmpeg-`), unpacks with `tarfile` and `filter="data"`, checks that each recorded file is a plain file (no symlink), has the recorded size and the recorded SHA-256 (`verify`, run on the unpacked tree and again on the staged copy), refuses unsafe paths in the record (`safe_rel`), marks programs executable, and only then renames the staged tree to `/formcut-binaries/ffmpeg-`, moving an older install aside first; any mismatch ends with "Nothing was installed." and the next source is tried, with the reasons joined if all fail. The folder is named exactly as the other Form apps name theirs and `data_dir()` matches each platform's data folder, so a build another Form app downloaded is used and one FormShot downloads is shared, and the engine's lookup (`video/find.rs`) reads the same path. `FORMCUT_FFMPEG_RELEASE` points the sources at a folder or URL for checks and mirrors. `published()` gives the window the release, licence, source, the archive name, sources, file count and total bytes (or `available: false` with the reason for a computer with no build); `installed()` gives the folder, program path, whether it is present and other installed releases. Run by the video work against a fake release: with the pins patched to the fake files but one SHA-256 wrong the install was refused and nothing was installed; with all pins matching the tree was installed and the engine's `video.ffmpeg` found it as `source: family, release 7.1.5-2`. Not run: the real release archive, whose pins are only as good as the copied record. + ## Verification ### (service) · run in this workspace diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 777f190d..61fb31ca 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.8.0" +__version__ = "0.10.0" diff --git a/backend/app/ffmpeg_fetch.py b/backend/app/ffmpeg_fetch.py new file mode 100644 index 00000000..5608365b --- /dev/null +++ b/backend/app/ffmpeg_fetch.py @@ -0,0 +1,248 @@ +"""The Form family's ffmpeg (0.9.0): the build FormShot pins, and installing it on request into the folder every Form +app shares (`/formcut-binaries/ffmpeg-`, named exactly as the other Form apps name it), so a build +another Form app downloaded is used and one FormShot downloads is shared. Every file is checked against the SHA-256 +recorded here before anything is installed. Nothing is downloaded on startup; the engine finds the folder itself +and runs ffmpeg as a separate program. + +The pins are copied from formai-binaries' ffmpeg-licence.json (release 7.1.5-2, record written 2026-09-22): each +target's files with their SHA-256 and size, and the two licence documents.""" + +import os +import shutil +import sys +import tarfile +import tempfile +import time +from pathlib import Path +from urllib.parse import quote + +from app.routers.cad import FetchError, download, host_triple, sha256_file + +RELEASE = "7.1.5-2" +FFMPEG = "7.1.5" +LICENCE = "LGPL-2.1-or-later" +SOURCE_URL = "https://ffmpeg.org/releases/ffmpeg-7.1.5.tar.xz" +SOURCE_SHA256 = "de668509caf9e35e3cd162473441fdb29538c6d96ed080292b3cf9e6fc5d558f" +BASES = ( + "https://github.com/nodemode-dev/formai-binaries/releases/download", + "https://github.com/nodemode-dev/formcut-binaries/releases/download", +) +MIRROR_ENV = "FORMCUT_FFMPEG_RELEASE" + +DOCUMENTS = { + "LGPL-2.1.txt": "246041b6ecf9bc32d718a62c57877c78b5eb397b6467e74ed7ae2626ab189c30", + "THIRD-PARTY-NOTICES.txt": "b0e7f25e1c096dd262c7d0253641008cdc5203a1c36cf419aed62b252ead7c1b", +} + +FILES = { + "aarch64-apple-darwin": ( + ("ffmpeg-aarch64-apple-darwin", "58821a3cc7409caa3e54571584fc89f3b336fde5fa0b2dc72598d94a64ed2db4", 370688), + ("ffprobe-aarch64-apple-darwin", "5e3358b2fdab1130588a7348e46654e265e19da844a1d9995d3edd92e9cc2370", 267568), + ("lib-aarch64-apple-darwin/libavcodec.61.dylib", "5d162dc69f296070db400bc29710f138dd28a80ebfa4d5e195607bd4cdfd5672", 15823520), + ("lib-aarch64-apple-darwin/libavdevice.61.dylib", "e3d2eea06a53a4553c0663470a18362c245b58ff87038eccc34c46f09523188e", 114688), + ("lib-aarch64-apple-darwin/libavfilter.10.dylib", "046cf48af9a34ec8dce1781a8c87b585650d70369f734d7f081060ec6d0e94a9", 3927248), + ("lib-aarch64-apple-darwin/libavformat.61.dylib", "75f42a9bab8815ea69ba63237ac17ab92a863a76a3367d02b7fd949234060e8b", 2473744), + ("lib-aarch64-apple-darwin/libavutil.59.dylib", "78ed8424177581aef4e55302631057e86f9fe6e47f615bb5aeacef18a9e98c83", 722384), + ("lib-aarch64-apple-darwin/libswresample.5.dylib", "47176afc562ea09b9c07c6f5382af3733645d767bb31cd9fa632d2882e90207e", 136128), + ("lib-aarch64-apple-darwin/libswscale.8.dylib", "64c454dfd1ad035876e9cd1235c1e901ca36493bdce6b08fb4aa4fa1bd8455d5", 794560), + ), + "x86_64-apple-darwin": ( + ("ffmpeg-x86_64-apple-darwin", "286c5a054124386e074589a296da40fbc3870bc82a06faec8a18713ff34c169a", 348256), + ("ffprobe-x86_64-apple-darwin", "661bce6e4cfa012b9f318791b3ab1e7a2248326a904eacf610866cacabf65dd6", 240288), + ("lib-x86_64-apple-darwin/libavcodec.61.dylib", "7d3ae2916e6a89fdd01093f795144f18d2cf91355b2bdc7f19cb913a4cc90565", 19839872), + ("lib-x86_64-apple-darwin/libavdevice.61.dylib", "842e9c16442d8dd4bfc47885743c71c99bd5a59120e1d17d9d4ad3aea8868457", 90592), + ("lib-x86_64-apple-darwin/libavfilter.10.dylib", "ecee537500a9b50712ea714dc2fdd764a412764ea23bb557768b6d8f6a48061b", 4637920), + ("lib-x86_64-apple-darwin/libavformat.61.dylib", "c65ef7cb0dd65b4d1448fd9bfe8d93de101a83a51d583029495339e3dcd3f368", 2394432), + ("lib-x86_64-apple-darwin/libavutil.59.dylib", "485c43b7cd2d993653e035742ee81e2ce668bb588abe9f5bd8aa9a76d7c08031", 855536), + ("lib-x86_64-apple-darwin/libswresample.5.dylib", "d1d9539ebeb0f23880a8a7438fc4620ab74b1703bb56a0374548324d677b4e2c", 149952), + ("lib-x86_64-apple-darwin/libswscale.8.dylib", "6bcdceb425989d0afb7291611b2a2322858c14c29fc5091f1b0f9122492889e2", 1061056), + ), + "x86_64-unknown-linux-gnu": ( + ("ffmpeg-x86_64-unknown-linux-gnu", "3d69dc24197a0d22cbc14228438c4ab9ff467dd24e45010841f30efb0ea610f1", 383392), + ("ffprobe-x86_64-unknown-linux-gnu", "d960b1e97d28eef08abdc461699fc250e4d751761b513e26a2e73955259970ba", 215968), + ("lib-x86_64-unknown-linux-gnu/libavcodec.so.61", "a055665593e70140f9392e7162766827c580282fc169697cb0788be10636d287", 17711648), + ("lib-x86_64-unknown-linux-gnu/libavdevice.so.61", "e079c97aa5c81d6112e2d4b69a8dd2f843663094d1849b4f23781501ba9b45e8", 77296), + ("lib-x86_64-unknown-linux-gnu/libavfilter.so.10", "0f44b5565e3ae3d5a9d27fa6e2ff2e2ea6c6dd14dcfa2f3a60e7d0782ffebb47", 4519256), + ("lib-x86_64-unknown-linux-gnu/libavformat.so.61", "86527012dc434a83823808453da66472df3c859b763854ad2573b922fea4f27c", 2733424), + ("lib-x86_64-unknown-linux-gnu/libavutil.so.59", "4c65e32eb4f806633ff9370013f3c649a0c849c133d595bfa3a9490f6771bd89", 1067936), + ("lib-x86_64-unknown-linux-gnu/libdrm.so.2", "cdce5fe2f157f623f90e6ff3bd99e74d46568b6d9afcd0c9eecc8e3d41bfeb2f", 330504), + ("lib-x86_64-unknown-linux-gnu/libswresample.so.5", "b41ebec6de028e67a1e450f3d3a2ae9a13ba2aaa838c8658b25f0887f417de2e", 125008), + ("lib-x86_64-unknown-linux-gnu/libswscale.so.8", "7c831badc3a05759bc70bca19a2a500e0eac753b2ff93d540f7360035fbd69c7", 616696), + ("lib-x86_64-unknown-linux-gnu/libva-drm.so.2", "197d126a11deaefdd24eb0de94d83547f04e0ff39cc7b44b12c15ef61834e300", 50696), + ("lib-x86_64-unknown-linux-gnu/libva.so.2", "a3a7746c58252d0318dad512fce3b7dea485e49119083f3da8164a7fea4d605c", 814648), + ), + "x86_64-pc-windows-msvc": ( + ("ffmpeg-x86_64-pc-windows-msvc.exe", "842ed489ba43db2deb4386f821a583e44765554a335ceb2f52a2ad1828920006", 377344), + ("ffprobe-x86_64-pc-windows-msvc.exe", "7b6401a2d0f1bb92b0017c3c9a60d99d4530309591614128a249f34ffc7f95d2", 204800), + ("lib-x86_64-pc-windows-msvc/avcodec-61.dll", "87bd9679bd98d5280341a9f8bc6cf520e66cb05dba5f067fe8e992471724dcec", 17740288), + ("lib-x86_64-pc-windows-msvc/avdevice-61.dll", "76348cb9eabab6799c70355184623d6b9c11972b1857692ee76866ed4486141a", 137216), + ("lib-x86_64-pc-windows-msvc/avfilter-10.dll", "479fcde9aded8f3307a1f4292ae7484b67235dd5c6a8d287dd98325e2215019b", 6840320), + ("lib-x86_64-pc-windows-msvc/avformat-61.dll", "f17d8f99fb5dbbcb98bec2d860859734c4523b80747b525daaef3eb2f4036d07", 2556928), + ("lib-x86_64-pc-windows-msvc/avutil-59.dll", "2bd68edeb5507c40d32f36a784ae529b519d6996605ba2739e65e6131e576e1c", 1051648), + ("lib-x86_64-pc-windows-msvc/swresample-5.dll", "5bfdf8dba05ca916b985ce07532c9f03e59f0777d1fd2d1cafe65dd88e5a0a06", 123392), + ("lib-x86_64-pc-windows-msvc/swscale-8.dll", "0231c1f6eedbdbdcf06a964c28d25d1a1f214f5860494901d52fa2fc2aa851f9", 650752), + ), +} + + +def windows() -> bool: + return sys.platform.startswith("win") + + +def data_dir() -> Path: + if sys.platform == "darwin": + return Path.home() / "Library" / "Application Support" + if windows(): + return Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local") + xdg = os.environ.get("XDG_DATA_HOME", "").strip() + return Path(xdg) if xdg else Path.home() / ".local" / "share" + + +def family_root() -> Path: + return data_dir() / "formcut-binaries" + + +def folder() -> Path: + return family_root() / f"ffmpeg-{RELEASE}" + + +def program_name(triple: str | None = None) -> str: + return f"ffmpeg-{triple or host_triple()}" + (".exe" if windows() else "") + + +def archive_name(triple: str | None = None) -> str: + return f"ffmpeg-lgpl-{RELEASE}-{triple or host_triple()}.tar.gz" + + +def pins(triple: str | None = None) -> tuple: + triple = triple or host_triple() + found = FILES.get(triple) + if not found: + raise FetchError(f"The Form family's ffmpeg {RELEASE} has no build for this computer ({triple}); it has {', '.join(sorted(FILES))}. Nothing was downloaded.") + return found + + +def sources() -> list[str]: + mirror = os.environ.get(MIRROR_ENV, "").strip() + if mirror: + if "://" not in mirror: + mirror = "file://" + quote(str(Path(mirror).expanduser().resolve())) + return [f"{mirror.rstrip('/')}/{archive_name()}"] + return [f"{base}/ffmpeg-{RELEASE}/{archive_name()}" for base in BASES] + + +def safe_rel(rel: str) -> str: + parts = Path(rel).parts + if not rel or rel.startswith(("/", "\\")) or ".." in parts or ":" in rel or "\\" in rel: + raise FetchError(f"The record names an unsafe path {rel!r}. Nothing was installed.") + return rel + + +def expected() -> dict[str, tuple[str, int | None]]: + out: dict[str, tuple[str, int | None]] = {safe_rel(path): (digest, size) for path, digest, size in pins()} + out.update({name: (digest, None) for name, digest in DOCUMENTS.items()}) + return out + + +def check_file(path: Path, rel: str, digest: str, size: int | None) -> None: + if path.is_symlink() or not path.is_file(): + raise FetchError(f"{rel} is not a plain file. Nothing was installed.") + if size is not None and path.stat().st_size != size: + raise FetchError(f"{rel} is {path.stat().st_size} bytes, the record says {size}. Nothing was installed.") + if sha256_file(path) != digest: + raise FetchError(f"{rel} does not match the SHA-256 in the record. Nothing was installed.") + + +def verify(tree: Path, report=None) -> None: + want = expected() + for i, (rel, (digest, size)) in enumerate(want.items()): + if report: + report("verify", i / len(want), f"Checking {rel}.") + check_file(tree / rel, rel, digest, size) + + +def package_root(unpacked: Path) -> Path: + first = pins()[0][0] + for hit in unpacked.rglob(first): + if hit.is_file() and not hit.is_symlink(): + return hit.parent + raise FetchError(f"The archive has no {first}. Nothing was installed.") + + +def unpack(bundle: Path, work: Path, report) -> Path: + report("unpack", 0.0, f"Unpacking {bundle.name}.") + unpacked = work / "archive" + try: + with tarfile.open(bundle) as t: + t.extractall(unpacked, filter="data") + except (tarfile.TarError, OSError) as error: + raise FetchError(f"{bundle.name} could not be unpacked ({error}). Nothing was installed.") from None + root = package_root(unpacked) + verify(root, report) + staged = work / "staged" + for rel in expected(): + (staged / rel).parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(root / rel, staged / rel) + for path, _, _ in pins(): + if not path.startswith("lib-") and not windows(): + (staged / path).chmod(0o755) + verify(staged) + return staged + + +def install(report=print) -> Path: + triple = host_triple() + report("record", 0.0, f"Checking the record of ffmpeg {RELEASE} for {triple}.") + pins(triple) + root = family_root() + root.mkdir(parents=True, exist_ok=True) + for stale in root.glob(".formshot-fetch-*"): + if stale.is_dir() and time.time() - stale.stat().st_mtime > 3600: + shutil.rmtree(stale, ignore_errors=True) + work = Path(tempfile.mkdtemp(prefix=".formshot-fetch-", dir=root)) + destination = folder() + try: + bundle = work / archive_name(triple) + reasons = [] + staged = None + for url in sources(): + report("download", 0.0, f"Downloading {bundle.name}.") + try: + download(url, bundle, lambda done, total: report("download", done / total if total else 0.0, f"Downloading {bundle.name}."), timeout=120.0) + staged = unpack(bundle, work, report) + break + except FetchError as error: + reasons.append(f"{url}: {error}") + shutil.rmtree(work / "archive", ignore_errors=True) + shutil.rmtree(work / "staged", ignore_errors=True) + report("download", 0.0, f"{error} Trying the next source.") + if staged is None: + raise FetchError(" ".join(reasons) if reasons else "No source was tried. Nothing was installed.") + if destination.exists(): + os.replace(destination, work / "old") + os.replace(staged, destination) + finally: + shutil.rmtree(work, ignore_errors=True) + report("done", 1.0, f"ffmpeg {RELEASE} is installed in {destination}.") + return destination + + +def installed() -> dict: + where = folder() + program = where / program_name() + out = {"release": RELEASE, "folder": str(where), "program": str(program), "present": program.is_file()} + others = sorted(p.name.removeprefix("ffmpeg-") for p in family_root().glob("ffmpeg-*") if p.is_dir() and p != where) if family_root().is_dir() else [] + out["other_releases"] = others + return out + + +def published() -> dict: + triple = host_triple() + out = {"release": RELEASE, "ffmpeg": FFMPEG, "triple": triple, "licence": LICENCE, "source": {"url": SOURCE_URL, "sha256": SOURCE_SHA256}} + try: + files = pins(triple) + except FetchError as error: + out.update(available=False, reason=str(error)) + return out + out.update(available=True, archive=archive_name(triple), sources=sources(), files=len(files) + len(DOCUMENTS), bytes=sum(size for _, _, size in files)) + return out diff --git a/backend/app/main.py b/backend/app/main.py index b5236a9c..bfdd8d55 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -14,7 +14,7 @@ from app.agent import router as agent_router from app.engine import EngineError, EngineUnavailable, engine from app.local_guard import LocalGuard -from app.routers import cad, denoise, handoff, imports, library, mcp, output, textures +from app.routers import cad, denoise, handoff, imports, library, mcp, output, textures, video mimetypes.add_type("text/javascript", ".js") mimetypes.add_type("text/javascript", ".mjs") @@ -52,6 +52,7 @@ async def lifespan(app): app.include_router(textures.router) app.include_router(denoise.router) app.include_router(output.router) +app.include_router(video.router) @app.middleware("http") diff --git a/backend/app/routers/video.py b/backend/app/routers/video.py new file mode 100644 index 00000000..2f7f450b --- /dev/null +++ b/backend/app/routers/video.py @@ -0,0 +1,136 @@ +"""Video: finding or downloading the family's ffmpeg and serving the movies the engine writes (0.9.0). + +The download runs only when the window (or `python -m app.routers.video fetch`) asks for it, never on startup. It +installs the Form family's LGPL build into the folder every Form app shares, where the engine finds it on its next +encode; FORMSHOT_FFMPEG still comes first for the engine when it is set.""" + +import json +import sys +import threading +import time +from pathlib import Path + +from fastapi import APIRouter, HTTPException, Query, Request +from fastapi.responses import FileResponse +from starlette.concurrency import run_in_threadpool + +from app import ffmpeg_fetch, window_key +from app.routers.cad import FetchError + +router = APIRouter(prefix="/api/video", tags=["video"]) + +MOVIES = {".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".gif": "image/gif"} + +_lock = threading.Lock() +_job = {"state": "idle", "stage": "", "fraction": 0.0, "message": "", "release": ffmpeg_fetch.RELEASE} + + +def _set(state: str, stage: str, fraction: float, message: str) -> None: + with _lock: + _job.update(state=state, stage=stage, fraction=round(max(0.0, min(1.0, fraction)), 4), message=message, at=time.time()) + snapshot = dict(_job) + try: + from app.agent import events + + events.publish("video.ffmpeg", **snapshot) + except Exception: + pass + + +def _run() -> None: + last = {"at": 0.0, "stage": ""} + + def report(stage: str, fraction: float, message: str) -> None: + now = time.monotonic() + if stage != last["stage"] or now - last["at"] > 0.25 or fraction >= 1.0: + last.update(at=now, stage=stage) + _set("done" if stage == "done" else "running", stage, fraction, message) + + try: + ffmpeg_fetch.install(report) + except FetchError as error: + _set("failed", "", 0.0, str(error)) + except Exception as error: + _set("failed", "", 0.0, f"ffmpeg could not be installed ({error}). Nothing was installed.") + + +def engine_status() -> dict: + try: + from app.engine import EngineError, EngineUnavailable, engine + + try: + return engine.dispatch("video.ffmpeg", {}) + except (EngineError, EngineUnavailable) as error: + return {"found": False, "reason": f"The engine could not be asked ({error})."} + except Exception as error: + return {"found": False, "reason": f"The engine could not be asked ({error})."} + + +def status() -> dict: + with _lock: + job = dict(_job) + return {"engine": engine_status(), "published": ffmpeg_fetch.published(), "installed": ffmpeg_fetch.installed(), "fetch": job} + + +@router.get("/ffmpeg") +async def ffmpeg_status() -> dict: + return await run_in_threadpool(status) + + +@router.post("/ffmpeg/fetch") +async def ffmpeg_fetch_start(request: Request) -> dict: + window_key.require(request) + try: + ffmpeg_fetch.pins() + except FetchError as error: + raise HTTPException(409, str(error)) from None + with _lock: + if _job["state"] == "running": + return {"started": False, "fetch": dict(_job)} + _job.update(state="running", stage="record", fraction=0.0, message="Starting.") + threading.Thread(target=_run, name="ffmpeg-fetch", daemon=True).start() + with _lock: + return {"started": True, "fetch": dict(_job)} + + +def movie_file(path: str) -> Path: + p = Path(path).expanduser() + if not p.is_absolute(): + raise HTTPException(400, "path must be an absolute path") + if p.suffix.lower() not in MOVIES: + raise HTTPException(400, f"{p.name} is not a movie ({', '.join(sorted(MOVIES))})") + if not p.is_file(): + raise HTTPException(404, f"{p} does not exist") + return p + + +@router.get("/movie") +async def movie(path: str = Query(..., min_length=1, max_length=4096)): + p = movie_file(path) + return FileResponse(p, media_type=MOVIES[p.suffix.lower()], filename=p.name) + + +def main(argv: list[str]) -> int: + command = argv[0] if argv else "status" + if command == "status": + print(json.dumps({"published": ffmpeg_fetch.published(), "installed": ffmpeg_fetch.installed()}, indent=2)) + return 0 + if command != "fetch": + print("usage: python -m app.routers.video [status|fetch]", file=sys.stderr) + return 2 + + def report(stage: str, fraction: float, message: str) -> None: + if stage != "download" or fraction in (0.0, 1.0): + print(f"[formshot] {stage:8} {fraction * 100:5.1f}% {message}", flush=True) + + try: + where = ffmpeg_fetch.install(report) + except FetchError as error: + print(f"[formshot] error: {error}", file=sys.stderr) + return 1 + print(f"[formshot] ffmpeg ready: {where / ffmpeg_fetch.program_name()}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/docs/ANIMATION.md b/docs/ANIMATION.md new file mode 100644 index 00000000..b327a2fd --- /dev/null +++ b/docs/ANIMATION.md @@ -0,0 +1,156 @@ +# Animation + +This page describes FormShot's keyed animation as it is in the repository: the timeline, tracks and keys, how keys interpolate, the time the viewport shows, and the commands, then rigs (turntables, orbits, camera paths), motion blur and the timeline in the window. Rendering frame sequences and movies is in [`VIDEO.md`](VIDEO.md). Times are seconds, lengths metres, angles degrees unless a field says radians, and colours scene-linear ACEScg. + +## The timeline + +A document's animation lives in `animation` (the `Animation` block in `fsh_scene::animation`). It is left out of the saved file while it is empty, so a project that never used animation keeps its bytes. + +| Field | Default | Meaning | +| --- | --- | --- | +| `fps` | 30 | frames per second, above 0 and at most 240 | +| `start` | 0 | time of the first frame, seconds | +| `end` | 5 | time of the last frame, seconds (at least `start`) | +| `tracks` | none | keyed tracks, one per target | +| `rigs` | none | generated motion, applied after the tracks | + +Frames run from `start` to `end` at `fps`, both ends included: a timeline from 0 to 1 at 24 fps has 25 frames, frame `n` at `start + n / fps`. A timeline holds at most 100000 frames. `fsh_scene::animation::frame_times(doc)` lists the frame times. + +## Tracks and keys + +A track keys one target. Each key has a short id (`key1`, `key2`, ... unique within its track), a time, a value and the interpolation that leads to the next key. Tracks have ids too (`track1`, ...). Ids are made by the commands with the lowest free number and never change; a removed id may be used again later. + +| Target | JSON | Value | +| --- | --- | --- | +| Node translation, rotation, scale | `{"kind": "transform", "node": 5, "field": "translation"}` | `[x, y, z]`; rotations a quaternion `[x, y, z, w]` | +| Camera field | `{"kind": "camera", "camera": 0, "field": "focal_length"}` | see below | +| Material parameter | `{"kind": "material", "material": 3, "param": "base_color"}` | a number or `[r, g, b]` | +| Light field | `{"kind": "light", "node": 7, "field": "power"}` | see below | +| Node visibility | `{"kind": "visibility", "node": 5}` | true or false | + +- Transforms key the node's local transform (relative to its parent). +- Camera fields: `position` and `target` (`[x, y, z]`), `orientation` (a quaternion: the camera looks along its local -Z with +Y up; keying it moves the target to keep its distance and sets the up direction), `focal_length` (millimetres), `fov` (horizontal field of view in degrees, turned into a focal length through the sensor width, so keys on it change the angle evenly), `focus_distance` (metres, 0 focuses on the target) and `aperture` (the f-number). A camera is named by its index in the camera list. +- Material parameters are the `SurfaceParams` fields that are numbers or colours (`base_color`, `specular_roughness`, `emission_luminance`, `coat_weight`, ...); `anim.key`'s schema lists them. +- Light fields: `power` (in the light's unit), `colour` (`[r, g, b]`), `temperature` (kelvin, 1000 to 40000), `spread` (degrees, rect and disc lights) and `visible` (whether the camera sees the emitter itself). +- Values are checked when keyed: a key that would make its object invalid (a zero scale, a focal length out of range, a roughness above 1) is refused. + +When typing a value, colours may also be an sRGB hex string (`"#d04020"`), switches a number (0.5 and above is on), and rotations Euler angles in degrees `[x, y, z]` (applied about X, then Y, then Z, fixed axes); keys store the canonical form. + +Removing a node with `scene.remove` also removes the tracks keyed on it and a turntable on it, and a camera path looking at it looks at the point where its centre was, in the same undo step; removing a camera removes its rigs and tracks and renumbers the later ones. A track keyed on a removed material stays and does nothing (`anim.status` marks it `valid: false`, as for any target that is gone); remove it with `anim.remove_track`. + +## Interpolation + +Each key's `interpolation` says how the value travels to the next key. Before the first key a target holds the first key's value, after the last key the last value. + +| Interpolation | Motion | +| --- | --- | +| `step` | holds the value until the next key, then jumps | +| `linear` | a straight line between the keys (constant speed) | +| `smooth` (default) | a monotone cubic through all the keys: it passes interior keys without stopping, starts and ends at rest at the first and last key, and never overshoots (it stays between neighbouring key values, and a series of rising keys only rises) | +| `ease` | eases out of this key and into the next one, stopping at both | + +Smooth is a cubic Hermite curve with Fritsch-Butland tangents: at an interior key the slope is the weighted harmonic mean of the slopes of the two neighbouring pieces, zero where the value turns back (a local peak or dip) and zero at the first and last key. Between only two keys smooth and ease are the same curve, `3u^2 - 2u^3`. Example: keys 0 at 0 s, 1 at 1 s and 3 at 2 s give, at 0.5 s, 0.3333 (smooth) where linear gives 0.5. + +Rotations always take the shorter way between two keys (spherical linear interpolation). Linear rotations turn at a constant angular speed; ease slows into each key; smooth spreads the turn with the same monotone cubic laid over the angle turned so far, so a rotation through several keys keeps turning without stopping at each. Visibility and `visible` are always stepped, whatever the key says. + +Keys apply in track order, then rigs. Keying two fields that both move the same thing (a camera's `target` and its `orientation`) is allowed; the later track wins. + +## The time the viewport shows + +Keys never change the stored document: the stored values are what the file saves, and the animation is laid over them at a time. The engine has one evaluation time. `anim.seek {time}` (or `{frame}`) sets it, the viewport restarts at that time (render.status's `revision` moves, so the window fetches the new frame) and still renders use it; `anim.seek {time: null}` shows the stored values again. A newly opened document starts with no time. Seeking does not touch the history and does not move `content_revision`. + +While a time is set, editing a keyed field (moving a keyed part with `scene.set_transform`, for example) changes the stored value, which the key then overrides in the picture; key the new value with `anim.key` instead. The raster view modes (solid, material, wireframe) and the window's own GPU mirror draw the stored document for now. + +## Commands + +Document commands (undoable, journalled, in the catalogue): + +| Command | Arguments | Notes | +| --- | --- | --- | +| `anim.set` | `fps?`, `start?`, `end?` | changes the timeline; merges while dragged | +| `anim.key` | `target`, `time`, `value?`, `interpolation?` | keys a target; without a value it keys what the target shows at that time (the animated value, so keying an animated target in place adds a key without changing the motion). A key already at that time (within 0.1 ms) is replaced and keeps its interpolation. Repeats on one key merge into one undo step | +| `anim.set_key` | the track (`track` or `target`) and the key (`key` or `at`), then `time?`, `value?`, `interpolation?` | changes one key; merges while dragged | +| `anim.move_key` | the track and key, `time` | moves a key; two keys of a track cannot share a time; merges while dragged | +| `anim.remove_key` | the track and key | a track left without keys is removed | +| `anim.remove_track` | `track` or `target` | | +| `anim.clear` | `all?` | removes every track; `all` also removes the rigs and resets the timeline | + +`at` finds the key nearest to a time within half a frame, so an agent can address a key by the time it keyed it at. + +Engine commands: + +| Command | Answer | +| --- | --- | +| `anim.seek {time \| frame \| null}` | `change` (full when the picture moves), `time`, `frame`, `revision` | +| `anim.status` | `time`, `frame`, `start`, `end`, `fps`, `frames`, `duration`, `moves`, `tracks` (id, target, label, kind, valid, key `times`, `key_at_time` (the key within half a frame of the time shown, or null), and `keys` with id, time, value and interpolation) and `rigs` (the list of rigs, each with its id, kind, name, start, end and its other fields; `rig_count` counts them) | +| `anim.sample {target, times?}` | the target's `values` at each time (every frame when `times` is absent), as the renderer sees them, and its `key_times`; rotations also as `euler_deg` (X, then Y, then Z about fixed axes; at Y of plus or minus 90 degrees the turn is put on Z) | + +`anim.seek` answers `change: full` whenever the time shown changes on a document with tracks or rigs, including back to `null`, and `none` otherwise. + +Example, a part sliding and turning over two seconds: + +```json +{"name": "anim.set", "args": {"fps": 24, "start": 0, "end": 2}} +{"name": "anim.key", "args": {"target": {"kind": "transform", "node": 5, "field": "translation"}, "time": 0, "value": [0, 0, 0]}} +{"name": "anim.key", "args": {"target": {"kind": "transform", "node": 5, "field": "translation"}, "time": 2, "value": [1, 0, 0]}} +{"name": "anim.key", "args": {"target": {"kind": "transform", "node": 5, "field": "rotation"}, "time": 2, "value": [0, 90, 0], "interpolation": "linear"}} +{"name": "anim.seek", "args": {"frame": 24}} +``` + +## Rigs: turntables, orbits and camera paths + +A rig makes motion from a few settings instead of keys. Rigs are applied after the keyed tracks at every time, turntables first, then camera rigs, each in list order. Every rig has an `id` (made for you, such as `turntable1`), a `name`, a `start` and `end` time in seconds, and `ease_in` and `ease_out`: the share of the run spent speeding up from rest and slowing down to rest (both 0 by default, so the motion runs at one steady speed). Before its start a rig holds its first position and after its end its last. A rig whose node or camera was removed does nothing. + +**Turntable.** Turns one node with everything under it, or the whole product when no node is given, about the vertical axis through the centre of its bounds. The pivot you set for the gizmo does not matter, and studio lights never turn. Settings: `node`, `turns` (1 by default; fractions allowed), `direction` (`ccw`, counterclockwise seen from above, or `cw`) and `start_angle` in degrees. At the start the product is exactly where you left it. + +The quickest way to a seamless loop is `anim.turntable {"frames": 36, "fps": 30}`: the animation becomes exactly 36 frames and the product turns 10 degrees per frame, so frame 36 would be frame 0 again and the loop never shows a repeated frame. `seconds` works the same way (rounded to whole frames). Without either, the turntable loops over the animation's current range. + +**Orbit.** `anim.orbit {}` circles the active camera (or `camera`, by index) around the product at its current distance and height, always looking at the product's centre with the horizon level. Settings: `turns`, `direction`, times and easing. A counterclockwise orbit makes the product appear to turn clockwise. + +**Camera path.** `anim.camera_path {"points": [[3,1,3], [0,2,4], [-3,1,3]]}` moves the camera along a smooth curve that passes through every point, at constant speed along the curve. `closed: true` brings it smoothly back to the first point (for loops). `look_at` is `{"point": [x, y, z]}` or `{"node": id}` (the camera follows that node's centre even while a turntable moves it); without it the camera looks at the product's centre. `roll` tilts the camera in degrees (positive banks right). Cameras with keep focus carry their focus distance along. + +**Editing.** `anim.add_rig {"rig": {"kind": "turntable", ...}}` adds any rig with only the fields you want to change from the defaults; `anim.set_rig {"id": "turntable1", "values": {"turns": 2}}` changes fields (null clears `node` or `look_at`); `anim.remove_rig {"id": "orbit1"}` removes one. All are undoable. `anim.status` lists the rigs with their settings. + +## Motion blur + +When parts or the camera move during an animation, motion blur smears them along their path the way a camera's open shutter does. It is off by default and lives in the render settings: + +```json +{"name": "render.set_settings", "args": {"values": {"motion_blur": {"enabled": true, "shutter": 0.5, "position": "centred"}}}} +``` + +| Setting | Values | Default | Meaning | +| --- | --- | --- | --- | +| `enabled` | true, false | false | Blur what moves while the shutter is open. | +| `shutter` | 0 to 1 | 0.5 | How long the shutter stays open, as a fraction of a frame. 0.5 is the classic 180 degree shutter; 1 blurs across the whole frame; 0 turns the blur off. | +| `position` | `centred`, `opening`, `closing` | `centred` | Where the open shutter sits around the frame's time: centred on it, opening at it, or closing at it. | + +At 24 frames per second with the defaults, frame 24 (1 s) is exposed from 0.98958 s to 1.01042 s. + +What blurs: parts that move, turn or change size between the shutter's opening and closing (turning follows the arc, not a straight line), and the camera's position and direction. The camera's lens, focal length, focus and projection are taken at the middle of the shutter, so a zoom or focus pull does not blur. + +What does not move within one exposure: lights, the environment and sky, the ground, materials and visibility. They are taken at the middle of the shutter. A part that glows (an emissive material) blurs where the camera sees it, but the light it casts on other things comes from its place at the middle of the shutter. A part that appears or disappears during the shutter is drawn still, as it is at the middle. + +Motion blur needs the animation to move something: a still scene with blur on renders exactly as without it. It adds noise, because moving parts need more samples to smooth their streaks than still ones; each frame keys nine positions across the shutter, and fast turns are interpolated smoothly between them. Where the GPU renders it, and where it falls back to the CPU, is in [`TRANSPORT.md`](TRANSPORT.md). + +## The timeline in the window + +The timeline panel sits at the bottom of the viewport. Folded it is a thin bar with an Animate button; open it holds a transport (to start, previous frame, play or pause, next frame, to end, loop), a frame and time readout, the fields Rate, Begins and Ends (`anim.set`), a ruler, one row per rig and one lane per track. Its state (open or folded, loop) is kept per machine. The View menu and the command palette have Timeline, Play Animation and Add Turntable. + +- **Scrubbing and playing.** Drag in the ruler to scrub frame by frame; Right and Left step a frame with the timeline focused, and Space plays or pauses. Playback follows the clock and always asks for the frame that is due, so slow pictures drop frames instead of queueing. While playing, the streamed viewport shows a quarter-size preview at a small sample count and returns to full size when paused. Playback in the in-window GPU engine was not verified. +- **Keys.** Each key is drawn by its interpolation (step square, linear diamond, smooth circle, ease rounded diamond). Click selects, Shift or Ctrl click adds, dragging moves keys and snaps to frames (hold Alt to move freely); one drag is one undo step. The right-click menu sets the interpolation of the selected keys, goes to the key or deletes it, and Delete removes selected keys. A curve toggle on each lane draws the values sampled per frame (rotations as Euler angles). +- **Keying.** The Keys menu has Key transform (translation, rotation and scale of the selected nodes), Key camera (position, target and focal length of the active camera) and a picker for a material parameter, a light, shown or hidden, a camera setting or a part's placement, with an optional typed value. Keys are made at the time shown, and each is one undo group. +- **Rigs.** The Rigs menu adds a turntable (frames, turns, direction, whole product or the selected node), a camera orbit or a camera path. Add camera position here builds a path: the first press keeps a point, the second makes the path, later ones insert points by time. A rig row is a bar from start to end with its name, an edit popover (name, start, end, turns, direction, start angle, node, closed, roll, ease) and remove. +- **Keyed camera.** When the active camera is under keys or a rig and a time is set, navigating in the viewport switches the view to Material Preview so the navigated view and posed parts show, while the rendered picture keeps showing the keyed camera. A pill offers Key camera here and Back to the keyed view; changing the time goes back. Under a rig only Back is offered, because rigs apply after keys and a key would not hold the view. + +Not done yet in the window: dragging several keys at once as a group, zooming the timeline, dragging the ends of a rig bar and typing a key's value in a lane (`anim.set_key` does it by command). The selection outline and gizmo are drawn at the stored pose, not the posed one, while a time is set. + +## Rendering frames and movies + +`anim.render` renders the animation as a frame sequence and optionally a movie. The Render Animation dialog, the sequence options and the movie encoder are in [`VIDEO.md`](VIDEO.md); the queue is in [`OUTPUT.md`](OUTPUT.md). + +## For other parts of the engine + +- `fsh_scene::animation::evaluate(doc, time)` returns the document at a time; with no tracks and no rigs it returns an equal copy. Meshes are shared, so the copy costs the node, material and camera tables only. +- `fsh_scene::animation::frame_times(doc)` lists the frame times; `sample_target(doc, target, time)` reads one target. +- `Editor::set_time` and `Editor::time` set the time `Editor::snapshot` renders at; `Editor::evaluated` is the document it renders. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 23511e1c..1f8bfdc5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -30,7 +30,7 @@ Conventions everywhere in the engine: right-handed, Y up, metres, radians, colou ## The engine crates -All crates live in `native/crates/`, edition 2021, Apache-2.0, version 0.8.0. `fsh-py` and `fsh-wasm` are outside the workspace's default members, so a plain `cargo build` does not need Python or the wasm target; `fsh-render-gpu` is a default member, so a plain build compiles wgpu. +All crates live in `native/crates/`, edition 2021, Apache-2.0, version 0.10.0. `fsh-py` and `fsh-wasm` are outside the workspace's default members, so a plain `cargo build` does not need Python or the wasm target; `fsh-render-gpu` is a default member, so a plain build compiles wgpu. | Crate | Holds | Depends on | | --- | --- | --- | @@ -46,12 +46,12 @@ All crates live in `native/crates/`, edition 2021, Apache-2.0, version 0.8.0. `f | `fsh-denoise` | the own edge-aware denoiser: an a-trous wavelet filter on albedo-demodulated light, guided by albedo, normal, depth and film variance, with Fast, Balanced and High qualities, deterministic on every platform; and a coverage filter | rayon natively | | `fsh-oidn` | Intel Open Image Denoise loaded at run time from the user cache, beside the program or `FORMSHOT_OIDN`, never linked: hand-written bindings, devices, cached filters, the same input types as fsh-denoise; native only | fsh-denoise, libloading | | `fsh-render-gpu` | the GPU path tracer on wgpu 30 compute: adapters and refusals, the flat scene buffers, one WGSL megakernel with a software BVH traversal and a ray-query variant, the material program interpreter and textures packed into its tables buffer, thin film and dispersion, the lighting block (lamp extras, IES tables, link masks, pins, dome, pictures), every camera projection, render passes in the accumulation buffer, the film in row bands, adaptive sampling, reduced-resolution passes and readback through the CPU's develop step (see [`GPU-ENGINE.md`](GPU-ENGINE.md)) | fsh-core, fsh-scene, fsh-accel, fsh-materials, fsh-render-cpu, wgpu, bytemuck, pollster (native), naga (validation feature only) | -| `fsh-commands` | the one command catalogue (156 entries: 53 document commands from `fsh-scene`, 38 engine commands for the app, selection, history, files, viewing and rendering, 50 commands of the import, cad, handoff, materials, library, lighting, camera, image, output and denoise groups in `src/ext/`, and 15 aliases from its one alias table) and `dispatch(session, name, args)` over an `Engine` session that owns the document, the history, the selected renderer (CPU or GPU behind one `PreviewRenderer` trait), its background render thread, the render queue and its worker thread, import jobs, the library's thumbnail worker and the crash journal | every crate above; fsh-render-gpu, fsh-cad, fsh-oidn and pollster natively only | +| `fsh-commands` | the one command catalogue (241 entries: 112 document commands from `fsh-scene`, 38 engine commands for the app, selection, history, files, viewing and rendering, 76 commands of the import, cad, handoff, materials, library, lighting, camera, image, output, denoise, shots, variants, configurator, templates, measure, anim, video and transport groups in `src/ext/`, and 15 aliases from its one alias table) and `dispatch(session, name, args)` over an `Engine` session that owns the document, the history, the selected renderer (CPU or GPU behind one `PreviewRenderer` trait), its background render thread, the render queue and its worker thread, import jobs, the library's thumbnail worker and the crash journal | every crate above; fsh-render-gpu, fsh-cad, fsh-oidn and pollster natively only | | `fsh-cli` | the `formshot-engine` program: `render` (with `--device`, and `--passes`, `--format`, `--depth` and `--float` through the render queue), `info`, `convert` (these three with import options), `probe`, `reimport`, `devices`, `bench`, `catalogue`, `dispatch` over JSON lines on stdin (with `--journal`), `version` and `help`. Run so far: the sample scene rendered byte-identical on 1 and 2 threads, a GLB and `.fshot` round trip rendered byte-identical pictures from both files, and `bench` rendered the sample on the CPU, software Vulkan and software OpenGL within 0.00001 of each other | fsh-commands, fsh-io | | `fsh-py` | the PyO3 module `fsh_py`: `catalogue()` and `Session(journal=None).dispatch(name, args_json)`, behind a feature so the workspace builds without Python | fsh-commands | | `fsh-wasm` | the wasm-bindgen package for the window: the document and commands in a `Session`, a mirror of the service's document, and `create_viewport`, which runs `fsh-render-gpu` on WebGPU, develops the film on the GPU like the engine's develop (grade, effects, display transforms, an OpenColorIO table) and presents to a canvas; the WebGPU self-check against the CPU tracer | fsh-commands, fsh-ocio, fsh-render-cpu; on wasm32 also fsh-render-gpu, wgpu (WebGPU), js-sys, web-sys, wasm-bindgen-futures | -The planned crates and features arrive by phase. The GPU tracer with our own BVH in compute shaders and hardware ray queries (0.3.0) and the WebGPU viewport with a native streamed fallback (0.4.0) are in the tree, with the limits named below. Import of 3MF and FBX, CAD through FormCAD's kernel worker, family hand-offs, material types, texture slots, the node graph and the library are in the tree too, with the limits their sections name, as are labels, thin film and dispersion, and textures and material programs in both path tracers. Lighting, cameras, the image, output and the denoisers are in the tree too, with the limits [Lighting, cameras and the image](#lighting-cameras-and-the-image) and [Output and denoising](#output-and-denoising) name. Still to come: shots, animation and advanced transport (0.9.0 to 0.10.0), editors and exchange (0.11.0 to 0.12.0), and agents, the render farm and the release (0.13.0 to 0.14.0). +The planned crates and features arrive by phase. The GPU tracer with our own BVH in compute shaders and hardware ray queries (0.3.0) and the WebGPU viewport with a native streamed fallback (0.4.0) are in the tree, with the limits named below. Import of 3MF and FBX, CAD through FormCAD's kernel worker, family hand-offs, material types, texture slots, the node graph and the library are in the tree too, with the limits their sections name, as are labels, thin film and dispersion, and textures and material programs in both path tracers. Lighting, cameras, the image, output and the denoisers are in the tree too, with the limits [Lighting, cameras and the image](#lighting-cameras-and-the-image) and [Output and denoising](#output-and-denoising) name. Shots, animation and advanced light transport (0.9.0 and 0.10.0) are in the tree, with the limits their own sections and [`TRANSPORT.md`](TRANSPORT.md) name. Still to come: editors and exchange (0.11.0 to 0.12.0), and agents, the render farm and the release (0.13.0 to 0.14.0). ## The document and the command registry @@ -71,7 +71,7 @@ How each surface gets to the catalogue: | --- | --- | | Window | `GET /api/engine/catalogue`; each entry is registered in the command registry as `engine.` and appears in the palette; edits go through `POST /api/engine/dispatch` | | MCP | `POST /mcp` `tools/list` returns the catalogue as tools with the same dotted names; `tools/call` dispatches through consent | -| Command line | `formshot-engine catalogue` (or `./formshot cli catalogue`) prints all 156 entries; `formshot-engine dispatch` reads `{"id","name","args"}` lines and answers each with `{id, result}` or `{id, error}` plus `meta: {revision, content_revision}` | +| Command line | `formshot-engine catalogue` (or `./formshot cli catalogue`) prints all 241 entries; `formshot-engine dispatch` reads `{"id","name","args"}` lines and answers each with `{id, result}` or `{id, error}` plus `meta: {revision, content_revision}` | | Agent skills | `./formshot agents sync` writes `.claude/skills/formshot-rendering/references/tools.md`, mirrors the skill into `.agents/skills` and writes `agents/manifest.json` | ## The project file @@ -211,6 +211,16 @@ The window edits materials through the Material page (types, parameters, slots) - **The render queue.** `render.queue_*` renders jobs one at a time on their own thread and renderer while the viewport keeps refining; a job captures the document when it is added, writes part files and renames them when every file is done, and names files from a template. The service lists outputs and thumbnails them; the window's Final Render window drives it. - **Denoisers.** The own denoiser (`fsh-denoise`) runs in every denoised develop, guided by the film's albedo, normal, depth and variance, at Fast, Balanced or High. Intel Open Image Denoise is optional: the service downloads it against a pinned record, `fsh-oidn` loads it at run time, and the document's `render.denoising` chooses it; any failure falls back to the own denoiser with a note. The GPU tracer runs the own denoiser on the device natively (fsh-render-gpu `denoise.rs`), the CPU filter otherwise. +## Shots, animation and light transport + +The detail is in [`SHOTS.md`](SHOTS.md), [`CONFIGURATOR.md`](CONFIGURATOR.md), [`TEMPLATES.md`](TEMPLATES.md), [`MEASURE.md`](MEASURE.md), [`ANIMATION.md`](ANIMATION.md), [`VIDEO.md`](VIDEO.md) and [`TRANSPORT.md`](TRANSPORT.md). The outline: + +- **Document blocks.** Each of these is a block of `DocumentData` in `fsh-scene`, left out of the saved file while it is empty or at its default, so older projects load unchanged and save byte for byte: `shots` (`shots.rs`, `shots/`), `variants` (material variants and model sets, `variants.rs`, `variants/`), `configurator` (`configurator.rs`, `configurator/`), `measurements` (`measure.rs`, `measure/`) and `animation` (`animation/`: tracks, keys, rigs, the timeline). Render settings gained `motion_blur` and `transport` (spectral and caustics settings in `transport/`); materials gained the medium, edge and fibre fields; cutaway nodes gained `invert`. Their commands are in the `commands!` table and so are undoable and journalled; `scene.remove`, `scene.duplicate`, `camera.remove` and `material.remove` keep these blocks consistent (a removed node leaves shots, variants, cutaway targets, rigs and configurator actions). +- **Command groups.** The engine-side commands of each live in `fsh-commands/src/ext/`: `shots.rs` (`shot.list`, `shot.render`), `variants.rs` (`variant.list`, `model_set.list`, `variant.diff`), `configurator.rs` (`config.get`, `config.check`, `config.list`, `config.render_all`), `templates.rs` and `templates/` (`template.*`), `measure.rs` and `measure/` (`measure.list`, `measure.pick`, `measure.render`, and the drawing of measurements into renders), `anim.rs` (`anim.seek`, `anim.status`, `anim.sample`), `video.rs` and `video/` (`anim.render`, `video.encode`, `video.ffmpeg`) and `transport.rs` (`transport.features`). +- **Editor time and motion.** `Editor::set_time` sets the time the snapshot shows; `Editor::evaluated` is the document laid over by its keys and rigs at that time (`animation::evaluate`), and is the same document when nothing moves. The snapshot of a document with motion blur on carries each moving part's and the camera's motion over the shutter (`motion.rs`), which both tracers read; `anim.seek` is the one command that sets the time. +- **`queue_documents`.** `ext/output.rs` has one function that queues jobs for documents prepared by a command: a copy of the open document with a shot applied (`shot.render`), a configuration applied (`config.render_all`), a frame's time evaluated (`anim.render`), or the document as it is with measurements drawn (`measure.render`). They take `render.queue_add`'s output, settings, camera and device arguments plus `measurements`, and the open document and its history never change. A movie job follows the frame jobs of `anim.render` and runs ffmpeg as a separate program (`video/`). The window reaches all of them through one route, `render.source`, which opens Final Render with the source and sends its own options along (see [`OUTPUT.md`](OUTPUT.md)). +- **The CPU tracer.** The tracer's scene is layered: `geometry.rs` holds a `CutScene` (cutaway filtering and caps, `cutaway.rs`) over a `FibredScene` (the instances' two-level BVH from `fsh-accel` plus each material's grown fibres as curve BVHs, `fibres.rs`) over the plain accel scene; every closest-hit and occlusion query goes through the cut first. With no cutaways and no fibres each layer answers directly, which is why such scenes render exactly as before. Inside the path loop, `media.rs` holds a path's medium stack, the free-flight sampling and the `Closure` that says what scatters at a point: the material's BSDF (or a fibre's), the subsurface variant, or the exit of a subsurface walk. `edges.rs` rounds normals, `spectral.rs` and `spectral/` hold wavelength sampling, the CIE tables and the uplift table, and `caustics.rs` and `caustics/` hold the photon passes. The GPU port of each of these is in [`GPU-ENGINE.md`](GPU-ENGINE.md); a scene it cannot draw is refused with a code and the CPU draws it. + ## Ports and processes | Port or name | What | diff --git a/docs/CONFIGURATOR.md b/docs/CONFIGURATOR.md new file mode 100644 index 00000000..70eb5570 --- /dev/null +++ b/docs/CONFIGURATOR.md @@ -0,0 +1,99 @@ +# The configurator + +The configurator describes a product the way a customer chooses it: a list of options (colour, trim, accessories), each with choices, and rules that keep combinations valid. Choosing a choice changes the scene; listing the configurator gives every valid combination; one command queues a render of each. The data and the document commands are in `native/crates/fsh-scene/src/configurator.rs` and `configurator/`, the listing and rendering commands in `native/crates/fsh-commands/src/ext/configurator.rs`. + +## Options, choices and actions + +An option has an id, a name, its choices in display order, the choice selected last and, optionally, a default choice. The choice in force is the selected one, else the default, else the first. A choice has an id, a name and a list of actions, run in order when the choice is made: + +| Action | Fields | What it does | +| --- | --- | --- | +| `material` | `material` (a material key, or null for the default material), `nodes` | puts the material on every part under the nodes | +| `show` | `nodes` | shows the nodes | +| `hide` | `nodes` | hides the nodes | +| `variant` | `set`, `variant` | makes the variant the active one of its variant set | +| `model_set` | `model_set` | shows the model set and hides the other model sets' nodes | +| `shot` | `shot` | applies the shot (camera, look, lighting and the rest the shot keeps) | + +Material, show and hide actions ignore node locks: a configuration is a deliberate change. The variant, model set and shot actions use the material variants, model sets and shots of the same document (see `SHOTS.md`); in a build where those are not connected yet, choosing such a choice fails with a plain message and `config.check` lists it as `action_unavailable`. + +Ids are short strings of letters, digits, `_`, `-` and `.`, at most 64 characters. Option and rule ids are unique in the configurator, choice ids within their option. When a command is not given an id it makes one from a prefix and the lowest free number (`option1`, `choice2`, `rule1`); an id never changes, names are free to change. + +## Rules + +A rule reads "while option X is on choice A, option Y requires one of choices B" (kind `requires`) or "... excludes choices B" (kind `excludes`). A configuration (one choice per option that has choices) is valid when it keeps every rule. Rules link two different options; a rule naming a missing option or choice is ignored by the search and reported by `config.check`. + +Example: a green body only comes without a handle. + +```json +{"name": "config.add_rule", "args": {"option": "colour", "choice": "green", "target": "parts", "choices": ["plain", "stand"]}} +``` + +## Commands + +Document commands (undoable, journaled, in the catalogue with their argument schemas): + +| Command | Arguments | Effect | +| --- | --- | --- | +| `config.add_option` | `id?`, `name?`, `index?`, `choices?`, `default?` | adds an option, optionally with its first choices | +| `config.set_option` | `option`, `name?`, `default?` | renames it or changes its default (null clears it) | +| `config.remove_option` | `option` | removes it with its choices and every rule naming it | +| `config.move_option` | `option`, `index` | moves it in the list | +| `config.add_choice` | `option`, `id?`, `name?`, `index?`, `actions?` | adds a choice | +| `config.set_choice` | `option`, `choice`, `name?`, `actions?` | renames it or replaces its actions | +| `config.remove_choice` | `option`, `choice` | removes it; rules it triggers go, it leaves rules' choice lists, and a rule left with no choices goes | +| `config.move_choice` | `option`, `choice`, `index` | moves it within its option | +| `config.add_rule` | `id?`, `kind`, `option`, `choice`, `target`, `choices` | adds a rule | +| `config.remove_rule` | `rule` | removes a rule | +| `config.select` | `option`, `choice` | makes the choice and runs its actions; see below | +| `config.apply` | `selection` (choice id per option id) | sets a whole configuration and runs every option's actions | + +None of the editing commands change the scene. `config.select` keeps the chosen choice fixed and looks for the valid configuration nearest the current one: each other option keeps its choice when the rules allow, and an option a rule now forbids moves to its first allowed choice. The chosen choice's actions run, then those of every option that moved, and the whole change undoes as one step. When no valid configuration has that choice, the command fails and nothing changes. `config.apply` does the same with several fixed choices (options it leaves out keep theirs where the rules allow) and then runs the actions of every option in option order, so the scene shows exactly that configuration; where two options touch the same part, the later option wins. + +Engine commands (read only, except that `config.render_all` adds render jobs): + +| Command | Answer | +| --- | --- | +| `config.get` | the options with their choices, actions and the choice in force, for each choice whether it keeps every rule with the other options as they are (`allowed`, for greying out choices; selecting one that is not moves other options), the rules, and the current configuration's name and validity | +| `config.check` | `ok` and the problems: `duplicate_id` (from a hand-edited file), `option_empty`, `missing_choice`, `rule_missing_option`, `rule_missing_choice`, `rule_same_option`, `rule_empty`, `no_configuration`, `option_impossible` (no choice keeps every rule), `never_chosen` (no valid configuration uses the choice), `not_checked` (too many combinations), `selection_invalid`, `action_missing` and `action_unavailable` | +| `config.list {limit?}` | every valid configuration in option and choice order, up to `limit` (default 100, at most 10000), each with its name, its `selection` (ready for `config.apply`) and whether it is the current one; `total` counts them all and `more` the ones left out | +| `config.render_all {limit?, ...}` | queues one render per valid configuration (up to `limit`) | + +A configuration's name joins "

_beauty.png`, checked against a montage; replacing a hide action by the selection, a variant, model set and shot action, and a default choice each read back and undid as one step. Not run: the desktop shell. + +### src/ui/templates/ · the material template dialogs +- refers-to: src/ui/templates/model.ts; dialog.ts :: TemplateDialog; editor.ts :: RuleEditor; index.ts :: registerTemplates (`templates.open`, `templates.sheet`); src/ui/import/sheet.ts :: open; src/ui/import/engine.ts :: args +- kind: decision +- logged: v0.9.0 · 2026-12-03 + +`TemplateDialog` (a wide shell dialog) lists FormShot templates and Your templates from `template.list` (skeleton rows from `localStorage['formshot.templates.count']`), shows a template's rules in order (`template.get`), a scope of Selected parts (n) or Whole scene (`formshot.templates.scope`), the counts and a per-part preview (`template.preview`: part, source material, target, "already"), and Apply (`template.apply` through the workspace `run`, so the summary refreshes, one undo step). FormShot's templates offer Edit a copy, yours Edit rules and a confirmed Remove, and Capture from this scene (`template.capture {name}`) opens the editor as an unsaved draft. `RuleEditor` edits name, description and rules (look at material name, part name or part data plus key, a pattern, and a library preset grouped by category or "Keep this material: " for stored materials), with add, move up and remove; local checks run first, then `template.save` (with `id` when replacing a user template) and engine errors appear inline. The module needs no workspace handle: read-only and file commands go through `api.dispatch`, document changes through the shell `run`, and `registerTemplates()` runs at load of the Configurator page module. Commands: `templates.open` "Material Templates..." (palette and Scene menu) and `templates.sheet`, a hook the import sheet runs in `open()` that inserts a "Material template" select (valid templates, yours marked "(yours)", last pick in `formshot.templates.import`) before the CAD row; `import/engine.ts` `args()` reads that select and adds `template`. One line each in files this work does not own. The Material page has no registry hook, so the dialog opens only from the palette and the Scene menu. Namespace `configurator` (shared with the page). Run: an OBJ with four named materials previewed 4 of 4, Apply dressed all four and Ctrl+Z restored them; the selection scope previewed only the lens; capture, rule edits, save, preview and remove worked; an import with "CAD and engineering materials" came in dressed and one undo removed it. Not done: the engine's synchronous STEP and IGES import does not apply `template` (a service-side gap noted by the templates work); the dialog is not on the Material page. + +### src/ui/inspector.ts, src/ui/import/sheet.ts · lines in shared files +- refers-to: src/ui/inspector.ts :: PAGES, imports; src/ui/import/sheet.ts :: open; src/ui/import/engine.ts :: args +- kind: decision +- logged: v0.9.0 · 2026-12-03 + +Three shared files got one small region each for this work. In `inspector.ts` the `snapshots` entry now mounts the Shots page (title "Shots", command "Shots Page", order 70) and a `configurator` entry follows it (order 75); the two import lines are adjacent, and the lead merged the two branches' regions in that order. In `import/sheet.ts` `open()` runs `templates.sheet` with the options element, the same hook pattern as `cad.sheet`. In `import/engine.ts` `args()` adds `template` from the sheet's `select[data-o="template"]`. Not touched: the Material page and `ui/render/`. + +## Measurements in the window + +### src/ui/measure/index.ts, src/ui/viewport-input.ts · the measure tool +- refers-to: src/ui/measure/index.ts :: MeasureTool; model.ts :: LIST, PICK, ADD_DISTANCE, ADD_SIZE, ADD_ANGLE, SET, REMOVE, CLEAR; icons.ts; src/ui/viewport-input.ts :: ViewportTool, ViewportSession, withTool, attachInput; src/ui/view-camera.ts :: ViewCamera.ws +- kind: decision +- logged: v0.9.0 · 2026-12-03 + +A small Measure island at the bottom left of the viewport (a toolbar of three pressed-state buttons: Measure Distance, Measure Angle, Measure Size Box) and the controller behind it. The tool is mounted from `viewport-input.ts` because `viewport.ts` is not this work's file: `attachInput` now starts with `const hooks = withTool(target, camera, view, given)`, and `withTool` mounts the measure module once and wraps `click` and `hover`; the module reaches the Workspace through the camera it receives, which needed one visibility change in `view-camera.ts` (`private readonly ws` to `readonly ws`). Clicks run `measure.pick` (the engine's pick plus the point in the part's own space, the part, and whether it snapped; Shift snaps to a vertex of the picked part) and then `measure.add_distance` (two points), `measure.add_angle` (corner, then the two arms) or `measure.add_size` (a clicked part, or the selected parts when the tool is chosen again); the pending point and a rubber band are drawn, a hint line says what to click ("Esc stops measuring." and the Shift snap sentence included), M toggles the tool and Escape stops it. Measurements are change level none in the engine, so nothing restarts a render; the window refreshes `measure.list` on its own dispatch notices (not list, pick, view, camera, render, selection, summary or mesh reads) and on summary refreshes, with one request in flight and one queued, which is why a part moved with the gizmo updates the value during the drag and undo restores it. Two choices (list open, own axes) are kept per machine in `localStorage['formshot.measure']`. Commands `measure.tool` ("Measure", key M, View group) and `measure.panel` ("Measurements List"). Namespace `measure`. Run in headless Chrome against an engine built for the measure work: two-click distance with a Shift snap, three-click angle, pending point and hint, Escape twice, the size box of a selection, M, a gizmo drag updating values (144.5 cm mid-drag, 156.6 cm after) and undo; a 60-step orbit drag at 4x CPU throttle gave zero layout shifts and no node added or removed in the island, panel or hint. Not done: edge snapping, adding several parts to one size box by clicking (select them first), and a switch for drawing measurements in `render.queue_add` renders (the engine draws them only through `measure.render`). The GPU viewport was not available in the headless run. + +### src/ui/overlay.ts, src/ui/measure/draw.ts, panel.ts · overlay layers and the measurements list +- refers-to: src/ui/overlay.ts :: addOverlayLayer, invalidateOverlays, paintLayers; src/ui/measure/draw.ts :: paintMeasurements; src/ui/measure/panel.ts :: MeasurePanel +- kind: decision +- logged: v0.9.0 · 2026-12-03 + +`overlay.ts` gained a small layer API at its end (`addOverlayLayer(layer)` returns a remover, `invalidateOverlays()`, `paintLayers`) and one call in `paint()`, so a module can paint on the viewport's overlay canvas without owning it. `paintMeasurements` draws the engine's evaluated points, axes and value text for each visible measurement, projecting with `cameraMatrices(camera.raster(), w/h, null)` from the live `ViewCamera`, the same matrices the raster view and the gizmo use, so the lines follow an orbit at once while the streamed picture lags under load; labels that overlap are moved apart from each other only (not from other lines), and a hidden measurement stays hidden while its row is hovered. The list is a floating panel of its own above the island (the Scene page has no registry hook) with a row per measurement: show and hide, an inline name field (double-click), the value, remove, a Decimals field (the document precision, sent as `measure.set` without an id), Own axes, and Remove All (`measure.clear`); a measurement whose part was deleted reads "Part removed" with "Missing nodes: {ids}" in its tooltip and comes back on undo; the empty state is a sentence in the list. Rows are keyed and updated in place. Namespace `measure`. Run: the existing measurements drew in register with the picture, rename, hide, Remove All and decimals worked, and the removed-part row appeared and recovered; the zero-shift orbit run is the one in the entry above. Not run: WebGPU in the window, other camera types (fisheye, equirectangular and cylindrical cameras are not drawn by the engine's render drawing either). + +## The timeline and Render Animation + +### src/ui/timeline/ · the timeline bar: status, playback and scrubbing +- refers-to: src/ui/timeline/index.ts :: mountTimeline; panel.ts :: Timeline; model.ts :: TIME_EVENT, parseStatus, parseRigs; store.ts :: TimelineStore; rigs-source.ts :: readRigs; player.ts :: Player; view.ts :: TrackView; edits.ts :: TimelineEdits; src/ui/workspace.ts :: mountTimeline call +- kind: decision +- logged: v0.9.0 · 2026-12-03 + +`mountTimeline(ws)` registers a `timeline` panel in the viewport slot, placed under the viewport, and the commands `timeline.toggle` ("Timeline", also in the View menu), `timeline.play` ("Play Animation") and `timeline.addTurntable` ("Add Turntable"); `workspace.ts` gained the import and the call right after `mountViewport(ws)`. The bar reserves its height before first paint through `--fsh-tl-reserved` on the slot (34 px folded, 224 px open, stored in `localStorage['formshot.timeline.open']`, default folded so a document with no animation shows a 34 px bar with Animate); the viewport panel's bottom follows that variable, so the stage moves only when the user folds or opens the bar (measured: exactly 190 px). Animate and the transport share one grid cell swapped by `visibility`, the readout and the Rate, Begins and Ends number fields have fixed widths (`anim.set` live, then `history.barrier`), a container query narrows the header at 980 and 760 px, and the empty state and lanes live inside the fixed-height body. `TimelineStore` reads `anim.status` 40 ms after any window dispatch that changes something (navigation, selection and render commands are skipped), after `scene.changed`, `document.changed` or `history.changed` events (agent, MCP, undo), resync and engine ready, and emits only when the reply differs; because `anim.status` gives only a rig count, `readRigs` fetches `GET /api/engine/snapshot` as a stream, walks the zip's local headers until `scene.json` has arrived and cancels the download (falling back to the central directory, `file.snapshot` and `DecompressionStream('deflate-raw')`), and it runs only when the count changes or the command could have touched rigs. `Player` plays, pauses, steps, loops (`formshot.timeline.loop`) and scrubs: one `anim.seek` is in flight at a time, the next goes out when the previous answer has come back and the picture has arrived or the wait has passed (one frame interval when the streamed loop is not drawing, else the last measured seek-to-picture time times 1.25, at least a frame and at most 4 s), and playback follows the wall clock and always asks for the frame due now, so frames are dropped, never queued; seeks go through `api.dispatch` directly so playback does not refresh the scene summary 30 times a second, then kick the streamed loop and emit `ui.anim.time` on the shell bus. `TrackView` is one scroller with a sticky canvas ruler (redrawn only on resize or range change) and the rows under it, times mapped as `pad + f * (width - 2 pad)` through `--f` so resizing writes nothing, and the playhead is one element moved with a `transform` from `--fsh-tl-now` (its `left` produced layout-shift entries). Space plays only when the timeline is focused and not in a number field; Left and Right step. Namespace `animation`. Run in headless Chrome against the 7401c29 engine: range typed in Ends, a ruler scrub 0 to 30 to 0 with the streamed viewport showing the part at rest and moved, 8 seeks in 6 s each for the frame due, fold and reopen, and under a 4x throttle a 10 s play added no timeline nodes and made zero layout shifts (only the readout's text nodes were replaced); an orbit drag of 20 moves caused one `anim.status` read. Not run: the in-window WebGPU path at a time (see the engine entry), touch, zooming the timeline. On this loaded machine a streamed first picture took 0.5 to 4 s, so streamed playback showed a few pictures per second. + +### src/ui/timeline/lanes.ts, curves.ts, keying.ts, rigs.ts · keys, curves and rigs +- refers-to: src/ui/timeline/lanes.ts :: Lanes; curves.ts; keying.ts; rigs.ts; popover.ts; glyphs.ts; edits.ts :: TimelineEdits (live, commit, once, group) +- kind: decision +- logged: v0.9.0 · 2026-12-03 + +`Lanes` patches one lane per track by id with keys inside it keyed by key id, and a lane rewrites itself only when its signature (target, validity, keys, names, range) changes; key shapes follow the interpolation (step square, linear diamond, smooth circle, ease rounded diamond) with `is-now` and `is-sel`. Click, Shift or Ctrl click and drag (snapping to frames, Alt for free time) send quiet live `anim.move_key` calls and one commit plus `history.barrier` per drag, so a drag is one undo step, and the dragged key holds its place until the engine agrees (1.5 s cap); a context menu (right click, Enter or the ContextMenu key) sets interpolation on all selected keys through `anim.set_key`, goes to a key or deletes (`anim.remove_key`), and Delete, Backspace, Escape and a double-click work from the keyboard and pointer; a track is removed with `anim.remove_track`. The curve toggle per lane (`formshot.timeline.curves`) makes a taller lane with a canvas drawn from `anim.sample` (one sample per frame, at most 240), refetched only when that track's signature or the range changes; rotations use `euler_deg` unwrapped per component. The Keys menu has Key transform (translation, rotation and scale of every selected node, one undo group), Key camera (position, target and focal length of the active camera, one group) and a picker (material parameter, light, shown or hidden, camera setting, part placement, with enums read from `anim.key`'s catalogue schema, an optional typed value and an interpolation); the time is the shown time. Key transform and Key camera key the value shown at that time except for parts and cameras this window moved (`scene.set_transform`, `camera.set` seen on the client) since their last key, which get the stored value explicitly because with a time set the engine shows the keyed value and would key the old one; moves made by an agent are not tracked. The Rigs menu builds a turntable (`anim.turntable`: frames, turns, direction, whole product or a selected node; fps stays the timeline's), a camera orbit (`anim.orbit`) and a camera path (`anim.camera_path`: the first "Add camera position here" keeps a pending point, the second creates the path, later ones insert by time and widen the range with `anim.set_rig`); rig rows are a bar from start to end with an editor popover (name, start, end, turns, direction, start angle, node, closed, roll, ease in and out through `anim.set_rig`, one undo step per change, `anim.remove_rig`). Point times of a path are remembered in the window per rig and assumed evenly spaced for a path made elsewhere, since the rig moves at constant speed. Popovers sit in `#overlay-root` at the menu layer and open above their anchor. Run: a Key transform with three tracks, a picker key (samples 0, 0.5 and 1 s matched), a drag of a key from frame 30 to 45 that Ctrl+Z undid in one step and Ctrl+Y redid, a 36-frame turntable whose frames turned the product 90 degrees at frame 9, an orbit, a path from two positions, the rig editor (name and turns read back from the snapshot), Key camera at frame 60 after a viewport orbit keying the navigated position; an outside agent's `anim.key` and `history.undo` added and removed one key node and kept the lanes. Not done: dragging several keys together, dragging rig bar ends, editing a key's value in the window (agents can through `anim.set_key`). With a keyed camera and a time set, viewport navigation changes the stored camera while the picture keeps showing the keyed one, and the selection outline, gizmo and raster modes draw the stored pose (an engine-side follow-up). + +### src/engine/gpu/engine.ts · the in-window engine follows the timeline +- refers-to: src/engine/gpu/engine.ts :: GpuEngine.setTime, applyTime, shownTime, timeFeed; src/ui/timeline/model.ts :: TIME_EVENT +- kind: decision +- logged: v0.9.0 · 2026-12-03 + +One region after `applyCamera`: `applyCamera` now ends with `applyTime()`, a static `shownTime` and a static subscription to `ui.anim.time` call `setTime` on every live `GpuEngine`, and `setTime` seeks the WebAssembly session (`anim.seek`), hands `session.scene()` to `viewport.set_scene` and marks interaction so the picture restarts at preview quality; `applyTime` repeats the seek after every mirror reload and camera hand-off, because a project reload resets the session's time. A session that lacks `anim.seek` logs a warning and keeps drawing the stored document. This was typechecked, not run: the window's WebAssembly package (`src/engine/pkg`) was not built in the work tree, so the in-window engine never started in the headless runs, and playback speed there is unverified. + +### src/ui/movie/ · Render Animation and its ffmpeg block +- refers-to: src/ui/movie/index.ts :: mountMovie; dialog.ts :: AnimationDialog; settings.ts :: movie, planOf, frameOptions, movieFrames, SEQ_FORMATS, MOVIE_FORMATS; anim.ts :: timeline; ffmpeg.ts :: ffmpeg, FFMPEG_ROUTE, FFMPEG_FETCH_ROUTE; ffmpeg-view.ts; src/ui/render/window.ts :: RenderWindow constructor +- kind: decision +- logged: v0.9.0 · 2026-12-03 + +`mountMovie(win)` is loaded by one line at the end of the `RenderWindow` constructor (`void import('../movie/index').then((m) => m.mountMovie(this))`), so the movie code is its own chunk and its sections come after the ones `index.ts` mounts. It registers `render.animation` ("Render Animation...", palette and the Render menu) and `render.motionBlur`, builds `AnimationDialog` once on first use and shows or hides it, never rebuilds it (a modal dialog on the shell's `.fsh-scrim`, chosen over a mode of Final Render), and queues through `anim.render`, then shows the Final Render queue. The dialog has Frames (every frame or a range, first, last, step, a count line with the animation's length and rate, a warning when nothing moves), Output size and samples (document settings, the same values Final Render edits, so a still and an animation never disagree), a camera, the Final Render passes and denoise sections mounted a second time (`mountPasses`, `mountDenoise`), Image sequence (PNG, JPEG, TIFF, OpenEXR, PSD, transparent background), Movie (on, MP4, WebM, MOV (ProRes) or GIF, the animation's rate or a typed one, quality 1 to 100, keep frames, the encoder line and warnings) and File names and folder (frame name that must hold `{frame}`, a preview, movie name, folder, Open Folder); the footer holds the plan ("12 frames at 240 × 160, then an MP4") and the folder and the movie's path or the reason the button is off. Format options and "replace existing files" come from Final Render's image file settings; the dialog's own choices are kept per machine in `localStorage['formshot.movie.settings']`. A movie needs PNG or JPEG frames (with TIFF, EXR or PSD the switch is off and a note says why), the folder defaults to Final Render's or `/renders` (an unsaved project needs one typed, and there is no Choose... button), the movie goes into the frames' folder named `_` unless a name is given and the dialog always sends `video.name` so the path it shows is the path the engine writes. The `timeline` reader in `anim.ts` holds `anim.status` (fps, frame count, start, end, rigs, tracks) only while a user holds it, refreshed on document change events and the local `ui.dispatched` event (undo from the window reaches pages that way, not as a service event). The ffmpeg block reads `GET /api/video/ffmpeg` (the engine's `video.ffmpeg` view, the published record, the install and the download job), follows `video.ffmpeg` events and polls every 1.5 s only while a download runs, and never starts a download itself: `POST /api/video/ffmpeg/fetch` runs only from the Download ffmpeg button, which shows the size from the published record, a reserved progress row with the stages record, download, unpack, verify and done (the OIDN block's strings), the state dot and sentence, the path and where it was found (`FORMSHOT_FFMPEG`, the family's shared install or the PATH), the encoders ffmpeg lists and a licence sentence (the GPL build the user installed, or the family's LGPL build with its source URL). With the movie on and no ffmpeg, Render Animation is off and the footer says to download it or turn the movie off; the MPEG-4 Part 2 fallback is announced before rendering from `formats.mp4.encoder`. The queued label is `, HH:MM`. Namespace `movie`. Run against the 7401c29 engine in headless Chrome: a 12-frame turntable rendered from the palette gave 12 frame jobs and one movie job and an MP4 ffprobe read as `h264,High,320,180,yuv420p,30/1,12`; with a stand-in family ffmpeg that hides libx264 the dialog warned and the movie was `mpeg4,Simple Profile,240,160,yuv420p,30/1,12`; with no ffmpeg the offer, the licence note and the disabled button showed and the service's fetch state stayed idle until the button was pressed; the download ran against a local fake release (progress 5 percent, 10 percent and on, then found as the family install), nothing real was downloaded; twelve setting changes moved no section and made no layout shift. Not run: the real family build and a real download, a hardware H.264 encoder, ProRes 4444 with alpha, GIF and WebM from the window, the desktop folder picker, right-to-left or translated tables. + +### src/ui/movie/rows.ts, src/ui/render/queue.ts · sequence and movie rows in the render queue +- refers-to: src/ui/movie/rows.ts :: sequenceRows, rememberSequence, createSequence, updateSequence, decorateJob; src/ui/render/queue.ts :: paint (paintRow); src/ui/render/jobs.ts :: Job +- kind: decision +- logged: v0.9.0 · 2026-12-03 + +`anim.render` queues one job per frame and one more for the movie, and the queue would otherwise list them as dozens of unrelated rows. `sequenceRows(jobs)` turns the polled job list into rows keyed `seq:`: the frame jobs of one sequence become one row followed by its frames when opened and by the movie job's row. Sequences queued from this window are grouped by the ids `anim.render` answered (`rememberSequence`); sequences from the CLI or an agent are grouped by label (`

+

+ +

+
+
+

+
`); + host.appendChild(root); + const count = q(root, '.fsh-cfg-count'); + const name = q(root, '.fsh-cfg-name'); + const note = q(root, '.fsh-cfg-foot-note'); + const renderBtn = q(root, '.fsh-cfg-render'); + const saidNode = q(root, '.fsh-cfg-foot-said'); + setValue(name, storedName()); + let sending = false; + let said = ''; + let saidError = false; + let timer: number | undefined; + + const folder = (): string => output.value.folder.trim() || rendersFolder(ws.client.summary?.document?.path ?? ''); + + const problem = (): string => { + if (!ws.canRun(CONFIG_CMD.renderAll)) return ws.why(CONFIG_CMD.renderAll); + if (store.loaded && store.count.total === 0) return t('There is no valid configuration to render.'); + const f = folder(); + if (!f) return t('Choose an output folder in the Final Render window first: this project has not been saved, so it has no folder of its own.'); + if (!absolute(f)) return t('The output folder must be a full path, such as {example}.', { example: '/Users/me/Renders' }); + return renderNameProblem(name.value); + }; + + const update = (): void => { + const c = store.count; + const text = !store.loaded ? '' : c.total === 0 ? t('No valid configuration') + : !c.complete ? t('At least {n} valid configurations', { n: c.total }) + : c.total === 1 ? t('One valid configuration') : t('{n} valid configurations', { n: c.total }); + setText(count, text); + const v = output.value; + const fmt = FORMATS.find(([f]) => f === v.format)?.[1] ?? v.format; + const cam = v.camera === 'all' ? t('every camera') : /^\d+$/.test(v.camera) ? t('camera {n}', { n: Number(v.camera) + 1 }) : t('the active camera'); + setText(note, t('{format} from {camera} into {folder}, with the size, samples and passes of the Final Render window.', { format: fmt, camera: cam, folder: folder() || '?' })); + const why = problem(); + setDisabled(renderBtn, sending || why !== ''); + setTitle(renderBtn, why || t('Queue one final render per valid configuration')); + setText(saidNode, said || why); + setClass(saidNode, 'is-error', saidError || (!said && why !== '')); + }; + + const say = (text: string, error: boolean): void => { + said = text; + saidError = error; + window.clearTimeout(timer); + timer = window.setTimeout(() => { said = ''; saidError = false; update(); }, 8000); + update(); + }; + + const renderAll = async (): Promise => { + if (sending || problem()) return; + sending = true; + update(); + try { + const template = name.value.trim() || DEFAULT_RENDER_NAME; + const done = (reply: unknown): string => { + const out = obj(reply); + const n = Array.isArray(out.configurations) ? out.configurations.length : 0; + const more = typeof out.more === 'number' ? out.more : 0; + const text = more > 0 ? t('Queued {n} configurations; {more} more were left out.', { n, more }) : t('Queued {n} configurations.', { n }); + say(text, false); + toast(text, 'info', { label: t('Render Queue'), run: () => runCommand('render.queue') }); + return text; + }; + const c = store.count; + const label = c.complete ? t('{n} valid configurations', { n: c.total }) : t('At least {n} valid configurations', { n: c.total }); + if (!runCommand('render.source', { source: { kind: 'configurations', label, command: CONFIG_CMD.renderAll, args: { name: template }, done } })) throw new Error(t('Final Render is not available.')); + say(t('Final Render shows the options; add the configurations to the queue there.'), false); + } catch (err) { + say(t('Could not queue the renders: {reason}', { reason: err instanceof Error ? err.message : String(err) }), true); + } finally { + sending = false; + update(); + } + }; + + name.addEventListener('input', () => update()); + name.addEventListener('change', () => { const v = name.value.trim() || DEFAULT_RENDER_NAME; setValue(name, v); keepName(v); update(); }); + name.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); name.blur(); } e.stopPropagation(); }); + q(root, '.fsh-cfg-open-render').addEventListener('click', () => runCommand('render.window')); + renderBtn.addEventListener('click', () => void renderAll()); + const offs = [output.onChange(update), ws.client.onSummary(update)]; + update(); + return { update, dispose: () => { window.clearTimeout(timer); for (const off of offs) off(); } }; +} diff --git a/frontend/src/ui/configurator/model.ts b/frontend/src/ui/configurator/model.ts new file mode 100644 index 00000000..a8bf4564 --- /dev/null +++ b/frontend/src/ui/configurator/model.ts @@ -0,0 +1,143 @@ +import { t } from '../../i18n'; + +export type NodeRef = string | number; + +export type Action = + | { kind: 'variant'; set: string; variant: string } + | { kind: 'model_set'; model_set: string } + | { kind: 'shot'; shot: string } + | { kind: 'show'; nodes: NodeRef[] } + | { kind: 'hide'; nodes: NodeRef[] } + | { kind: 'material'; material: NodeRef | null; nodes: NodeRef[] }; + +export type ActionKind = Action['kind']; +export const ACTION_KINDS: readonly ActionKind[] = ['variant', 'model_set', 'shot', 'show', 'hide', 'material']; + +export interface Choice { id: string; name: string; actions: Action[]; allowed: boolean } +export interface ConfigOption { id: string; name: string; current: string | null; default: string | null; choices: Choice[] } +export type RuleKind = 'requires' | 'excludes'; +export interface Rule { id: string; kind: RuleKind; option: string; choice: string; target: string; choices: string[] } + +export interface ConfigState { + options: ConfigOption[]; + rules: Rule[]; + name: string; + valid: boolean; +} + +export interface Problem { code: string; message: string; option: string | null; choice: string | null; rule: string | null } + +export interface Count { total: number; complete: boolean } + +type Obj = Record; +export const obj = (v: unknown): Obj => (v && typeof v === 'object' && !Array.isArray(v) ? v as Obj : {}); +export const str = (v: unknown): string => (typeof v === 'string' ? v : typeof v === 'number' ? String(v) : ''); +const strOrNull = (v: unknown): string | null => (typeof v === 'string' && v ? v : null); +const ref = (v: unknown): NodeRef | null => (typeof v === 'string' || typeof v === 'number' ? v : null); +const refs = (v: unknown): NodeRef[] => (Array.isArray(v) ? v.map(ref).filter((r): r is NodeRef => r !== null) : []); + +export function parseAction(raw: unknown): Action | null { + const o = obj(raw); + switch (o.kind) { + case 'variant': return { kind: 'variant', set: str(o.set), variant: str(o.variant) }; + case 'model_set': return { kind: 'model_set', model_set: str(o.model_set) }; + case 'shot': return { kind: 'shot', shot: str(o.shot) }; + case 'show': return { kind: 'show', nodes: refs(o.nodes) }; + case 'hide': return { kind: 'hide', nodes: refs(o.nodes) }; + case 'material': return { kind: 'material', material: ref(o.material), nodes: refs(o.nodes) }; + default: return null; + } +} + +export function parseState(raw: unknown): ConfigState { + const o = obj(raw); + const options: ConfigOption[] = (Array.isArray(o.options) ? o.options : []).map((x) => { + const op = obj(x); + const choices: Choice[] = (Array.isArray(op.choices) ? op.choices : []).map((c) => { + const ch = obj(c); + const actions = (Array.isArray(ch.actions) ? ch.actions : []).map(parseAction).filter((a): a is Action => a !== null); + return { id: str(ch.id), name: str(ch.name), actions, allowed: ch.allowed !== false }; + }); + return { id: str(op.id), name: str(op.name), current: strOrNull(op.current), default: strOrNull(op.default), choices }; + }); + const rules: Rule[] = (Array.isArray(o.rules) ? o.rules : []).map((x) => { + const r = obj(x); + return { + id: str(r.id), kind: r.kind === 'excludes' ? 'excludes' : 'requires', option: str(r.option), choice: str(r.choice), + target: str(r.target), choices: Array.isArray(r.choices) ? r.choices.map(str) : [], + }; + }); + const conf = obj(o.configuration); + return { options, rules, name: str(conf.name), valid: o.valid !== false }; +} + +export function parseProblems(raw: unknown): Problem[] { + const o = obj(raw); + return (Array.isArray(o.problems) ? o.problems : []).map((x) => { + const p = obj(x); + return { code: str(p.code), message: str(p.message), option: strOrNull(p.option), choice: strOrNull(p.choice), rule: strOrNull(p.rule) }; + }); +} + +export function parseCount(raw: unknown): Count { + const o = obj(raw); + return { total: typeof o.total === 'number' ? o.total : 0, complete: o.complete !== false }; +} + +export function optionOf(s: ConfigState, id: string): ConfigOption | undefined { + return s.options.find((o) => o.id === id); +} + +export function choiceOf(s: ConfigState, option: string, choice: string): Choice | undefined { + return optionOf(s, option)?.choices.find((c) => c.id === choice); +} + +export function orList(names: readonly string[]): string { + if (names.length === 0) return ''; + if (names.length === 1) return names[0]; + return t('{list} or {last}', { list: names.slice(0, -1).join(', '), last: names[names.length - 1] }); +} + +const optName = (s: ConfigState, id: string): string => optionOf(s, id)?.name || id; +const chName = (s: ConfigState, option: string, id: string): string => choiceOf(s, option, id)?.name || id; + +export function ruleSentence(s: ConfigState, r: Rule): string { + const vars = { + option: optName(s, r.option), + choice: chName(s, r.option, r.choice), + target: optName(s, r.target), + choices: orList(r.choices.map((c) => chName(s, r.target, c))), + }; + return r.kind === 'requires' + ? t('When {option} is {choice}, {target} must be {choices}', vars) + : t('When {option} is {choice}, {target} cannot be {choices}', vars); +} + +function breaks(r: Rule, triggerOn: boolean, targetChoice: string | null): boolean { + if (!triggerOn || targetChoice === null) return false; + const inList = r.choices.includes(targetChoice); + return r.kind === 'requires' ? !inList : inList; +} + +export function blockingRules(s: ConfigState, option: string, choice: string): Rule[] { + const cur = (id: string): string | null => optionOf(s, id)?.current ?? null; + return s.rules.filter((r) => { + if (r.option === option && r.choice === choice) return breaks(r, true, cur(r.target)); + if (r.target === option) return breaks(r, cur(r.option) === r.choice, choice); + return false; + }); +} + +export interface Moved { option: string; from: string | null; to: string | null } + +export function movedOptions(before: ConfigState, after: ConfigState, picked: string): Moved[] { + const out: Moved[] = []; + for (const o of after.options) { + if (o.id === picked) continue; + const was = optionOf(before, o.id)?.current ?? null; + if (was !== o.current) out.push({ option: o.id, from: was, to: o.current }); + } + return out; +} + +export function nodeList(v: readonly NodeRef[]): string { return v.map(String).join(','); } diff --git a/frontend/src/ui/configurator/options.ts b/frontend/src/ui/configurator/options.ts new file mode 100644 index 00000000..00deb36b --- /dev/null +++ b/frontend/src/ui/configurator/options.ts @@ -0,0 +1,210 @@ +import { el, escapeHtml, patchList, q, setAttr, setClass, setDisabled, setHidden, setText, setTitle, setValue } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { blockingRules, ruleSentence, type Choice, type ConfigOption, type Moved } from './model'; +import { problemList } from './rules'; +import { CONFIG_CMD, rememberedShape, type ConfigStore } from './store'; + +export interface OptionsHost { + moved(): readonly Moved[]; + picked(option: string, choice: string): void; + editing(): boolean; + editChoice(option: string, choice: string): void; + send(name: string, args: Record): Promise; +} + +export function newId(reply: unknown, before: readonly string[], after: readonly string[]): string | null { + const id = reply && typeof reply === 'object' ? (reply as Record).id : undefined; + if (typeof id === 'string' && id) return id; + return after.find((x) => !before.includes(x)) ?? null; +} + +export interface OptionsView { update(): void; dispose(): void } + +const NEVER = new Set(['never_chosen']); + +export function mountOptions(host: HTMLElement, ws: Workspace, store: ConfigStore, page: OptionsHost): OptionsView { + const root = el('
'); + const empty = el(''); + const addBtn = el(``); + host.append(root, empty, addBtn); + + const shape = rememberedShape(); + for (let i = 0; i < shape.options; i++) { + const chips = Array.from({ length: Math.max(1, shape.chips[i] ?? 2) }, () => '').join(''); + root.appendChild(el(``)); + } + + const never = (option: string, choice: string): string => { + const p = store.problems.find((x) => x.option === option && x.choice === choice && NEVER.has(x.code)); + return p ? p.message : ''; + }; + + const chipTitle = (o: ConfigOption, c: Choice): string => { + const why = never(o.id, c.id); + if (why) return t('This choice can never be made: {reason}', { reason: why }); + if (c.allowed) return c.name; + const rules = blockingRules(store.state, o.id, c.id).map((r) => ruleSentence(store.state, r)); + return rules.length ? t('Choosing {name} moves other options to keep the rules: {rules}', { name: c.name, rules: rules.join('; ') }) : c.name; + }; + + const paintChip = (b: HTMLElement, o: ConfigOption, c: Choice): void => { + const on = o.current === c.id; + const blocked = never(o.id, c.id) !== ''; + setText(q(b, '.fsh-cfg-chip-name'), c.name); + setAttr(b, 'aria-checked', on ? 'true' : 'false'); + setAttr(b, 'tabindex', on || (!o.current && o.choices[0]?.id === c.id) ? '0' : '-1'); + setClass(b, 'is-moves', !c.allowed && !blocked && !on); + const editing = page.editing(); + setDisabled(b as HTMLButtonElement, !editing && (blocked || !ws.canRun(CONFIG_CMD.select))); + setTitle(b, editing ? t('Edit {name}', { name: c.name }) : chipTitle(o, c)); + }; + + const paintOption = (sec: HTMLElement, o: ConfigOption): void => { + setText(q(sec, '.fsh-cfg-opt-name'), o.name); + setValue(q(sec, '.fsh-cfg-opt-input'), o.name); + const at = store.state.options.indexOf(o); + const tool = (op: string): HTMLButtonElement => q(sec, `.fsh-cfg-opt-tools [data-op="${op}"]`); + setDisabled(tool('up'), at <= 0 || !ws.canRun(CONFIG_CMD.moveOption)); + setDisabled(tool('down'), at < 0 || at >= store.state.options.length - 1 || !ws.canRun(CONFIG_CMD.moveOption)); + setDisabled(tool('remove'), !ws.canRun(CONFIG_CMD.removeOption)); + setDisabled(q(sec, '[data-op="add-choice"]'), !ws.canRun(CONFIG_CMD.addChoice)); + const moved = page.moved().find((m) => m.option === o.id); + const badge = q(sec, '.fsh-cfg-moved'); + const to = moved ? o.choices.find((c) => c.id === moved.to)?.name ?? '' : ''; + setText(badge, moved ? t('Moved to {name}', { name: to }) : ''); + setHidden(badge, !moved); + const chips = q(sec, '.fsh-cfg-chips'); + setAttr(chips, 'aria-label', o.name); + patchList(chips, o.choices, { + key: (c) => c.id, + create: (c) => { + const b = el(''); + paintChip(b, o, c); + return b; + }, + update: (b, c) => paintChip(b, o, c), + }); + setClass(sec, 'is-empty', o.choices.length === 0); + const mine = store.problems.filter((p) => p.option === o.id && p.rule === null); + problemList(q(sec, '.fsh-cfg-problems'), mine); + for (const b of Array.from(chips.children) as HTMLElement[]) setClass(b, 'is-problem', mine.some((p) => p.choice === b.dataset.key)); + }; + + const update = (): void => { + const s = store.state; + if (!store.loaded) return; + patchList(root, s.options, { + key: (o) => `o:${o.id}`, + create: (o) => { + const sec = el(`
+
+ + + + + +
+
+
+ +
`); + sec.dataset.option = o.id; + for (const [op, label] of [['up', 'Move option up'], ['down', 'Move option down'], ['remove', 'Remove option']] as const) { + const b = q(sec, `.fsh-cfg-opt-tools [data-op="${op}"]`); + setAttr(b, 'aria-label', t(label)); + setTitle(b, t(label)); + } + setAttr(q(sec, '.fsh-cfg-opt-input'), 'aria-label', t('Option name')); + const input = q(sec, '.fsh-cfg-opt-input'); + input.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { e.preventDefault(); input.blur(); } + else if (e.key === 'Escape') { e.preventDefault(); input.value = store.state.options.find((x) => x.id === o.id)?.name ?? ''; input.blur(); } + e.stopPropagation(); + }); + input.addEventListener('change', () => { + const name = input.value.trim(); + const cur = store.state.options.find((x) => x.id === o.id); + if (!cur || !name || name === cur.name) { input.value = cur?.name ?? ''; return; } + void page.send(CONFIG_CMD.setOption, { option: o.id, name }); + }); + paintOption(sec, o); + return sec; + }, + update: paintOption, + }); + const msg = s.options.length ? '' : t('No options yet. Turn on Edit options to add the options a customer chooses from, such as Colour or Size.'); + setText(empty, msg); + setHidden(empty, msg === ''); + setDisabled(addBtn, !ws.canRun(CONFIG_CMD.addOption)); + if (focusOption) { + const input = root.querySelector(`.fsh-cfg-opt[data-option="${CSS.escape(focusOption)}"] .fsh-cfg-opt-input`); + if (input) { focusOption = null; input.focus(); input.select(); } + } + }; + + const select = (option: string, choice: string): void => { + const o = store.state.options.find((x) => x.id === option); + if (!o || o.current === choice) return; + page.picked(option, choice); + }; + + const ids = (): string[] => store.state.options.map((o) => o.id); + let focusOption: string | null = null; + + const addChoice = async (option: string): Promise => { + const before = store.state.options.find((o) => o.id === option)?.choices.map((c) => c.id) ?? []; + const out = await page.send(CONFIG_CMD.addChoice, { option }); + if (out === undefined) return; + store.state = await store.fetchState(); + const after = store.state.options.find((o) => o.id === option)?.choices.map((c) => c.id) ?? []; + update(); + const id = newId(out, before, after); + if (id) page.editChoice(option, id); + }; + + const addOption = async (): Promise => { + const before = ids(); + const out = await page.send(CONFIG_CMD.addOption, {}); + if (out === undefined) return; + store.state = await store.fetchState(); + focusOption = newId(out, before, ids()); + update(); + }; + + const optionOp = (option: string, op: string): void => { + const at = ids().indexOf(option); + if (op === 'up' && at > 0) void page.send(CONFIG_CMD.moveOption, { option, index: at - 1 }); + else if (op === 'down' && at >= 0) void page.send(CONFIG_CMD.moveOption, { option, index: at + 1 }); + else if (op === 'remove') void page.send(CONFIG_CMD.removeOption, { option }); + else if (op === 'add-choice') void addChoice(option); + }; + + root.addEventListener('click', (e) => { + const target = e.target as HTMLElement; + const sec = target.closest('.fsh-cfg-opt'); + const option = sec?.dataset.option; + if (!sec || !option) return; + const opBtn = target.closest('[data-op]'); + if (opBtn) { if (!opBtn.disabled) optionOp(option, opBtn.dataset.op ?? ''); return; } + const chip = target.closest('.fsh-cfg-chip'); + if (!chip || chip.disabled || !chip.dataset.key) return; + if (page.editing()) page.editChoice(option, chip.dataset.key); + else select(option, chip.dataset.key); + }); + addBtn.addEventListener('click', () => void addOption()); + root.addEventListener('keydown', (e) => { + const chip = (e.target as HTMLElement).closest('.fsh-cfg-chip'); + if (!chip || page.editing() || (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft')) return; + const list = Array.from(chip.parentElement?.children ?? []) as HTMLButtonElement[]; + const live = list.filter((b) => b.classList.contains('fsh-cfg-chip') && !b.disabled); + const at = live.indexOf(chip); + const next = live[(at + (e.key === 'ArrowRight' ? 1 : live.length - 1)) % live.length]; + if (next && next !== chip) { next.focus(); next.click(); } + e.preventDefault(); + }); + + update(); + return { update, dispose: () => undefined }; +} diff --git a/frontend/src/ui/configurator/rules.ts b/frontend/src/ui/configurator/rules.ts new file mode 100644 index 00000000..4a28847a --- /dev/null +++ b/frontend/src/ui/configurator/rules.ts @@ -0,0 +1,149 @@ +import { el, escapeHtml, patchList, q, setAttr, setDisabled, setHidden, setText, setTitle } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { optionOf, ruleSentence, type Problem, type Rule, type RuleKind } from './model'; +import { CONFIG_CMD, type ConfigStore } from './store'; + +export interface RulesView { update(): void; dispose(): void } + +type Send = (name: string, args: Record) => Promise; + +interface Item { key: string; text: string } + +function fillSelect(select: HTMLSelectElement, items: readonly Item[]): void { + const keep = select.value; + patchList(select, items, { + key: (i) => i.key, + create: (i) => { const o = document.createElement('option'); o.value = i.key; o.textContent = i.text; return o; }, + update: (o, i) => { if (o.textContent !== i.text) o.textContent = i.text; }, + }); + if (items.some((i) => i.key === keep)) select.value = keep; + else if (items.length) select.value = items[0].key; +} + +export function problemList(list: HTMLElement, problems: readonly Problem[]): void { + patchList(list, problems, { + key: (p) => `${p.code}|${p.message}`, + create: (p) => { + const li = el(`
  • ${icon('warning', 12)}
  • `); + setText(q(li, '.fsh-cfg-problem-text'), p.message); + return li; + }, + update: () => undefined, + }); + setHidden(list, problems.length === 0); +} + +export function mountRules(host: HTMLElement, ws: Workspace, store: ConfigStore, send: Send): RulesView { + const root = el(`
    +
      + +
      +${escapeHtml(t('When'))} + +${escapeHtml(t('is'))} + +, + + + + +
      +
      `); + host.appendChild(root); + const list = q(root, '.fsh-cfg-rule-list'); + const empty = q(root, '.fsh-cfg-rules-empty'); + const form = q(root, '.fsh-cfg-rule-form'); + const sel = (k: string): HTMLSelectElement => q(form, `[data-r="${k}"]`); + const optionSel = sel('option'), choiceSel = sel('choice'), targetSel = sel('target'), kindSel = sel('kind'); + const targets = q(form, '.fsh-cfg-rule-targets'); + const addBtn = q(form, '.fsh-cfg-rule-add'); + setAttr(optionSel, 'aria-label', t('Option that triggers the rule')); + setAttr(choiceSel, 'aria-label', t('Choice that triggers the rule')); + setAttr(targetSel, 'aria-label', t('Option the rule restricts')); + setAttr(kindSel, 'aria-label', t('Kind of rule')); + setAttr(targets, 'aria-label', t('Choices the rule names')); + const picked = new Set(); + + const paintRule = (li: HTMLElement, r: Rule): void => { + setText(q(li, '.fsh-cfg-rule-text'), ruleSentence(store.state, r)); + problemList(q(li, '.fsh-cfg-problems'), store.problems.filter((p) => p.rule === r.id)); + const b = q(li, '.fsh-cfg-rule-remove'); + setDisabled(b, !ws.canRun(CONFIG_CMD.removeRule)); + }; + + const paintForm = (): void => { + const s = store.state; + const opts = s.options.filter((o) => o.choices.length > 0).map((o) => ({ key: o.id, text: o.name })); + fillSelect(optionSel, opts); + const trigger = optionOf(s, optionSel.value); + fillSelect(choiceSel, (trigger?.choices ?? []).map((c) => ({ key: c.id, text: c.name }))); + fillSelect(targetSel, opts.filter((o) => o.key !== optionSel.value)); + const target = optionOf(s, targetSel.value); + const choices = target?.choices ?? []; + for (const k of [...picked]) if (!choices.some((c) => c.id === k)) picked.delete(k); + patchList(targets, choices, { + key: (c) => c.id, + create: (c) => { + const b = el(''); + setText(q(b, '.fsh-cfg-chip-name'), c.name); + return b; + }, + update: (b, c) => setText(q(b, '.fsh-cfg-chip-name'), c.name), + }); + for (const b of Array.from(targets.children) as HTMLElement[]) setAttr(b, 'aria-checked', picked.has(b.dataset.key ?? '') ? 'true' : 'false'); + const ok = ws.canRun(CONFIG_CMD.addRule) && !!trigger && !!choiceSel.value && !!target && picked.size > 0; + setDisabled(addBtn, !ok); + setTitle(addBtn, ok ? t('Add rule') : opts.length < 2 ? t('A rule links two options; add a second option first.') : t('Pick the choices the rule names.')); + }; + + const update = (): void => { + const s = store.state; + patchList(list, s.rules, { + key: (r) => r.id, + create: (r) => { + const li = el(`
    • `); + const b = q(li, '.fsh-cfg-rule-remove'); + setAttr(b, 'aria-label', t('Remove rule')); + setTitle(b, t('Remove rule')); + paintRule(li, r); + return li; + }, + update: paintRule, + }); + const msg = store.loaded && !s.rules.length ? t('No rules: every combination of choices is allowed.') : ''; + setText(empty, msg); + setHidden(empty, msg === ''); + paintForm(); + }; + + list.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('.fsh-cfg-rule-remove'); + const id = b?.closest('.fsh-cfg-rule')?.dataset.key; + if (b && id) void send(CONFIG_CMD.removeRule, { rule: id }); + }); + for (const s of [optionSel, targetSel]) s.addEventListener('change', () => { if (s === targetSel) picked.clear(); paintForm(); }); + targets.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('.fsh-cfg-chip'); + const k = b?.dataset.key; + if (!k) return; + if (picked.has(k)) picked.delete(k); else picked.add(k); + paintForm(); + }); + form.addEventListener('submit', (e) => { + e.preventDefault(); + if (addBtn.disabled) return; + const target = optionOf(store.state, targetSel.value); + const choices = (target?.choices ?? []).map((c) => c.id).filter((id) => picked.has(id)); + const kind: RuleKind = kindSel.value === 'excludes' ? 'excludes' : 'requires'; + void send(CONFIG_CMD.addRule, { kind, option: optionSel.value, choice: choiceSel.value, target: targetSel.value, choices }).then((out) => { + if (out === undefined) return; + picked.clear(); + paintForm(); + }); + }); + + update(); + return { update, dispose: () => undefined }; +} diff --git a/frontend/src/ui/configurator/sheet.ts b/frontend/src/ui/configurator/sheet.ts new file mode 100644 index 00000000..b6279baa --- /dev/null +++ b/frontend/src/ui/configurator/sheet.ts @@ -0,0 +1,336 @@ +import { el, escapeHtml, patchList, q, setAttr, setChecked, setDisabled, setHidden, setStyleVar, setText, setTitle } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { runCommand } from '../../shell/registry'; +import { events } from '../../shell/events'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { ACTION_KINDS, choiceOf, obj, optionOf, str, type Action, type ActionKind, type NodeRef } from './model'; +import { problemList } from './rules'; +import { CONFIG_CMD, type ConfigStore } from './store'; + +const LISTS = { variants: 'variant.list', modelSets: 'model_set.list', shots: 'shot.list' } as const; + +const KIND_LABELS: Record = { + variant: 'Select a material variant', + model_set: 'Select a model set', + shot: 'Apply a shot', + show: 'Show nodes', + hide: 'Hide nodes', + material: 'Put a material on parts', +}; + +interface Named { id: string; name: string } +interface VariantSetInfo extends Named { variants: Named[] } +interface Lists { sets: VariantSetInfo[]; modelSets: Named[]; shots: Named[]; loaded: boolean; error: string } + +interface Draft { uid: number; action: Action } + +const named = (v: unknown): Named => { const o = obj(v); return { id: str(o.id), name: str(o.name) || str(o.id) }; }; + +function parseSets(raw: unknown): VariantSetInfo[] { + const sets = obj(raw).sets; + return (Array.isArray(sets) ? sets : []).map((s) => ({ ...named(s), variants: (Array.isArray(obj(s).variants) ? obj(s).variants as unknown[] : []).map(named) })); +} + +const listOf = (raw: unknown, key: string): Named[] => { const v = obj(raw)[key]; return (Array.isArray(v) ? v : []).map(named); }; + +function fill(select: HTMLSelectElement, items: readonly Named[], value: string, missing: string): void { + let rows = items.some((i) => i.id === value) || !value ? items : [{ id: value, name: missing }, ...items]; + if (!rows.length) rows = [{ id: '', name: t('None in this document') }]; + patchList(select, rows, { + key: (i) => i.id, + create: (i) => { const o = document.createElement('option'); o.value = i.id; o.textContent = i.name; return o; }, + update: (o, i) => { if (o.textContent !== i.name) o.textContent = i.name; }, + }); + if (select.value !== value && rows.some((i) => i.id === value)) select.value = value; +} + +export class ChoiceSheet { + readonly root: HTMLElement; + private option = ''; + private choice = ''; + private drafts: Draft[] = []; + private uid = 0; + private lists: Lists = { sets: [], modelSets: [], shots: [], loaded: false, error: '' }; + private readonly nameInput: HTMLInputElement; + private readonly list: HTMLElement; + private readonly kindSelect: HTMLSelectElement; + private readonly saveBtn: HTMLButtonElement; + private readonly offs: Array<() => void> = []; + private sending = false; + private opened = 0; + + constructor(private readonly ws: Workspace, private readonly store: ConfigStore, private readonly send: (name: string, args: Record) => Promise) { + const kinds = ACTION_KINDS.map((k) => ``).join(''); + this.root = el(``); + (document.getElementById('overlay-root') ?? document.body).appendChild(this.root); + this.nameInput = q(this.root, '.fsh-cfg-sheet-name'); + this.list = q(this.root, '.fsh-cfg-actions'); + this.kindSelect = q(this.root, '.fsh-cfg-sheet-add select'); + this.saveBtn = q(this.root, '.fsh-cfg-save'); + const x = q(this.root, '.fsh-cfg-sheet-x'); + setAttr(x, 'aria-label', t('Close')); + x.addEventListener('click', () => this.close()); + q(this.root, '.fsh-cfg-cancel').addEventListener('click', () => this.close()); + this.saveBtn.addEventListener('click', () => void this.save()); + q(this.root, '.fsh-cfg-remove-choice').addEventListener('click', () => void this.remove()); + q(this.root, '.fsh-cfg-add-action').addEventListener('click', () => this.addAction(this.kindSelect.value as ActionKind)); + for (const b of Array.from(this.root.querySelectorAll('[data-move]'))) b.addEventListener('click', () => void this.move(Number(b.dataset.move))); + const def = q(this.root, '.fsh-cfg-default'); + def.addEventListener('change', () => void this.send(CONFIG_CMD.setOption, { option: this.option, default: def.checked ? this.choice : null })); + this.root.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { e.stopPropagation(); this.close(); } + if (e.key === 'Enter' && e.target === this.nameInput) { e.preventDefault(); void this.save(); } + e.stopPropagation(); + }); + this.list.addEventListener('click', (e) => this.onListClick(e)); + this.list.addEventListener('change', (e) => this.onListChange(e)); + this.offs.push(ws.client.onSummary(() => { if (this.isOpen) this.paint(); }), store.onChange(() => { if (this.isOpen) this.paint(); })); + } + + get isOpen(): boolean { return !this.root.hidden; } + + open(option: string, choice: string, anchor: HTMLElement | null): void { + const c = choiceOf(this.store.state, option, choice); + if (!c) return; + this.option = option; + this.choice = choice; + this.opened++; + this.drafts = c.actions.map((a) => ({ uid: ++this.uid, action: structuredClone(a) })); + this.nameInput.value = c.name; + this.note(''); + const box = anchor?.getBoundingClientRect(); + const right = box ? Math.max(8, window.innerWidth - box.left + 8) : 8; + setStyleVar(this.root, '--fsh-cfg-sheet-right', `${Math.round(right)}px`); + setHidden(this.root, false); + this.paint(); + this.nameInput.focus(); + this.nameInput.select(); + void this.loadLists(); + } + + close(): void { setHidden(this.root, true); } + + dispose(): void { for (const off of this.offs) off(); this.root.remove(); } + + private note(text: string): void { setText(q(this.root, '.fsh-cfg-sheet-note'), text); } + + private async loadLists(): Promise { + const ask = async (name: string): Promise => (this.ws.canRun(name) ? this.ws.client.dispatch(name, {}) : {}); + try { + const [v, m, s] = await Promise.all([ask(LISTS.variants), ask(LISTS.modelSets), ask(LISTS.shots)]); + this.lists = { sets: parseSets(v), modelSets: listOf(m, 'model_sets'), shots: listOf(s, 'shots'), loaded: true, error: '' }; + } catch (err) { + this.lists = { ...this.lists, loaded: true, error: err instanceof Error ? err.message : String(err) }; + } + if (this.isOpen) this.paint(); + } + + private nodeNames(nodes: readonly NodeRef[]): string { + const byId = new Map((this.ws.client.summary?.nodes ?? []).map((n) => [String(n.id), n.name])); + const names = nodes.map((n) => byId.get(String(n)) ?? t('missing node {id}', { id: String(n) })); + if (!names.length) return t('No nodes yet'); + return names.length > 4 ? t('{names} and {n} more', { names: names.slice(0, 3).join(', '), n: names.length - 3 }) : names.join(', '); + } + + private selection(): NodeRef[] { return [...(this.ws.client.summary?.selection ?? [])]; } + + private materials(): Named[] { + const list = (this.ws.client.summary?.materials ?? []).map((m) => ({ id: str(m.key), name: str(m.name) || str(m.key) })); + return [{ id: '', name: t('Default material') }, ...list]; + } + + private addAction(kind: ActionKind): void { + const sel = this.selection(); + const first = this.lists.sets[0]; + const action: Action = kind === 'variant' ? { kind, set: first?.id ?? '', variant: first?.variants[0]?.id ?? '' } + : kind === 'model_set' ? { kind, model_set: this.lists.modelSets[0]?.id ?? '' } + : kind === 'shot' ? { kind, shot: this.lists.shots[0]?.id ?? '' } + : kind === 'material' ? { kind, material: this.materials()[1]?.id ?? null, nodes: sel } + : { kind, nodes: sel }; + this.drafts.push({ uid: ++this.uid, action }); + this.paint(); + } + + private rowHtml(a: Action): string { + const nodes = `
      `; + const select = (field: string, label: string): string => ``; + let body = ''; + if (a.kind === 'variant') body = select('set', 'Variant set') + select('variant', 'Variant'); + else if (a.kind === 'model_set') body = select('model_set', 'Model set'); + else if (a.kind === 'shot') body = `${select('shot', 'Shot')}`; + else if (a.kind === 'material') body = select('material', 'Material') + nodes; + else body = nodes; + return `
    • ${escapeHtml(t(KIND_LABELS[a.kind]))} +
      ${body}
    • `; + } + + private paintRow(li: HTMLElement, d: Draft, i: number): void { + const a = d.action; + const field = (f: string): HTMLSelectElement | null => li.querySelector(`select[data-field="${f}"]`); + const missing = (id: string): string => t('Missing: {id}', { id }); + const loading = !this.lists.loaded; + if (a.kind === 'variant' && !a.set && this.lists.sets[0]) a.set = this.lists.sets[0].id; + if (a.kind === 'variant' && !a.variant) a.variant = this.lists.sets.find((x) => x.id === a.set)?.variants[0]?.id ?? ''; + if (a.kind === 'model_set' && !a.model_set) a.model_set = this.lists.modelSets[0]?.id ?? ''; + if (a.kind === 'shot' && !a.shot) a.shot = this.lists.shots[0]?.id ?? ''; + if (a.kind === 'variant') { + const setSel = field('set'), varSel = field('variant'); + if (setSel) fill(setSel, this.lists.sets, a.set, missing(a.set)); + const set = this.lists.sets.find((s) => s.id === a.set); + if (varSel) fill(varSel, set?.variants ?? [], a.variant, missing(a.variant)); + } else if (a.kind === 'model_set') { + const s = field('model_set'); + if (s) fill(s, this.lists.modelSets, a.model_set, missing(a.model_set)); + } else if (a.kind === 'shot') { + const s = field('shot'); + if (s) fill(s, this.lists.shots, a.shot, missing(a.shot)); + } else if (a.kind === 'material') { + const s = field('material'); + if (s) fill(s, this.materials(), a.material === null ? '' : String(a.material), missing(String(a.material))); + } + for (const s of Array.from(li.querySelectorAll('select'))) setDisabled(s, loading && s.dataset.field !== 'material'); + if (a.kind === 'show' || a.kind === 'hide' || a.kind === 'material') { + setText(q(li, '.fsh-cfg-act-node-names'), this.nodeNames(a.nodes)); + const n = this.selection().length; + const b = q(li, '[data-act="use-selection"]'); + setText(b, n ? t('Use the selection ({n})', { n }) : t('Use the selection')); + setDisabled(b, n === 0); + setTitle(b, n ? t('Replace these nodes with the nodes selected in the scene') : t('Select nodes in the scene or the viewport first')); + } + const up = q(li, '[data-act="up"]'); + setDisabled(up, i === 0); + setAttr(up, 'aria-label', t('Run earlier')); + setTitle(up, t('Run earlier')); + const rm = q(li, '[data-act="remove"]'); + setAttr(rm, 'aria-label', t('Remove action')); + setTitle(rm, t('Remove action')); + } + + private paint(): void { + const s = this.store.state; + const o = optionOf(s, this.option); + const c = choiceOf(s, this.option, this.choice); + if (!o || !c) { this.close(); return; } + setText(q(this.root, '.fsh-cfg-sheet-title'), t('{option}: {choice}', { option: o.name, choice: c.name })); + problemList(q(this.root, '.fsh-cfg-sheet-problems'), this.store.problems.filter((p) => p.option === this.option && p.choice === this.choice)); + patchList(this.list, this.drafts, { + key: (d) => String(d.uid), + create: (d) => { const li = el(this.rowHtml(d.action)); return li; }, + update: () => undefined, + }); + Array.from(this.list.children).forEach((li, i) => this.paintRow(li as HTMLElement, this.drafts[i], i)); + const empty = q(this.root, '.fsh-cfg-actions-empty'); + setText(empty, this.drafts.length ? '' : t('No actions: choosing it changes nothing in the scene.')); + setHidden(empty, this.drafts.length > 0); + const at = o.choices.findIndex((x) => x.id === c.id); + const def = q(this.root, '.fsh-cfg-default'); + const implicit = !o.default && at === 0; + setChecked(def, o.default === c.id || implicit); + setDisabled(def, implicit || !this.ws.canRun(CONFIG_CMD.setOption)); + const move = (d: number): HTMLButtonElement => q(this.root, `[data-move="${d}"]`); + setDisabled(move(-1), at <= 0 || !this.ws.canRun(CONFIG_CMD.moveChoice)); + setDisabled(move(1), at >= o.choices.length - 1 || !this.ws.canRun(CONFIG_CMD.moveChoice)); + if (this.lists.error) this.note(this.lists.error); + setDisabled(this.saveBtn, this.sending || !this.ws.canRun(CONFIG_CMD.setChoice)); + } + + private draftOf(target: EventTarget | null): { li: HTMLElement; d: Draft; i: number } | null { + const li = (target as HTMLElement | null)?.closest('.fsh-cfg-act'); + if (!li) return null; + const i = this.drafts.findIndex((d) => String(d.uid) === li.dataset.key); + return i < 0 ? null : { li, d: this.drafts[i], i }; + } + + private onListClick(e: Event): void { + const b = (e.target as HTMLElement).closest('[data-act]'); + const hit = this.draftOf(e.target); + if (!b || !hit || b.disabled) return; + const a = hit.d.action; + switch (b.dataset.act) { + case 'remove': this.drafts.splice(hit.i, 1); break; + case 'up': if (hit.i > 0) this.drafts.splice(hit.i - 1, 0, ...this.drafts.splice(hit.i, 1)); break; + case 'use-selection': if (a.kind === 'show' || a.kind === 'hide' || a.kind === 'material') a.nodes = this.selection(); break; + case 'reveal': + if (a.kind === 'shot') { runCommand('inspector.page', { id: 'snapshots' }); events.emit({ type: 'ui.shots.reveal', kind: 'shot', id: a.shot }); } + return; + default: return; + } + this.paint(); + } + + private onListChange(e: Event): void { + const s = e.target as HTMLSelectElement; + const hit = this.draftOf(s); + if (!hit || !(s instanceof HTMLSelectElement)) return; + const a = hit.d.action; + const v = s.value; + if (a.kind === 'variant' && s.dataset.field === 'set') { a.set = v; a.variant = this.lists.sets.find((x) => x.id === v)?.variants[0]?.id ?? ''; } + else if (a.kind === 'variant' && s.dataset.field === 'variant') a.variant = v; + else if (a.kind === 'model_set') a.model_set = v; + else if (a.kind === 'shot') a.shot = v; + else if (a.kind === 'material') a.material = v === '' ? null : /^\d+$/.test(v) ? Number(v) : v; + this.paint(); + } + + private problem(): string { + for (const { action: a } of this.drafts) { + if (a.kind === 'variant' && (!a.set || !a.variant)) return t('Pick a variant set and a variant, or remove that action.'); + if (a.kind === 'model_set' && !a.model_set) return t('Pick a model set, or remove that action.'); + if (a.kind === 'shot' && !a.shot) return t('Pick a shot, or remove that action.'); + if ((a.kind === 'show' || a.kind === 'hide' || a.kind === 'material') && !a.nodes.length) return t('Pick the nodes with Use the selection, or remove that action.'); + } + return ''; + } + + private async save(): Promise { + if (this.sending) return; + const c = choiceOf(this.store.state, this.option, this.choice); + if (!c) { this.close(); return; } + const why = this.problem(); + if (why) { this.note(why); return; } + const name = this.nameInput.value.trim(); + const actions = this.drafts.map((d) => d.action); + const args: Record = { option: this.option, choice: this.choice }; + if (name && name !== c.name) args.name = name; + if (JSON.stringify(actions) !== JSON.stringify(c.actions)) args.actions = actions; + if (Object.keys(args).length === 2) { this.close(); return; } + this.sending = true; + this.paint(); + const was = this.opened; + const out = await this.send(CONFIG_CMD.setChoice, args); + this.sending = false; + if (was !== this.opened) return; + if (out !== undefined) this.close(); + else this.paint(); + } + + private async remove(): Promise { + const was = this.opened; + const out = await this.send(CONFIG_CMD.removeChoice, { option: this.option, choice: this.choice }); + if (out !== undefined && was === this.opened) this.close(); + } + + private async move(delta: number): Promise { + const o = optionOf(this.store.state, this.option); + const at = o?.choices.findIndex((c) => c.id === this.choice) ?? -1; + if (at < 0) return; + await this.send(CONFIG_CMD.moveChoice, { option: this.option, choice: this.choice, index: Math.max(0, at + delta) }); + } +} diff --git a/frontend/src/ui/configurator/store.ts b/frontend/src/ui/configurator/store.ts new file mode 100644 index 00000000..93bf9ddb --- /dev/null +++ b/frontend/src/ui/configurator/store.ts @@ -0,0 +1,109 @@ +import type { Workspace } from '../context'; +import { parseCount, parseProblems, parseState, type ConfigState, type Count, type Problem } from './model'; + +export const CONFIG_CMD = { + get: 'config.get', + check: 'config.check', + list: 'config.list', + select: 'config.select', + addOption: 'config.add_option', + setOption: 'config.set_option', + removeOption: 'config.remove_option', + moveOption: 'config.move_option', + addChoice: 'config.add_choice', + setChoice: 'config.set_choice', + removeChoice: 'config.remove_choice', + moveChoice: 'config.move_choice', + addRule: 'config.add_rule', + removeRule: 'config.remove_rule', + renderAll: 'config.render_all', +} as const; + +const SHAPE_KEY = 'formshot.configurator.shape'; + +export interface Shape { options: number; chips: number[]; rules: number } + +export function rememberedShape(): Shape { + try { + const raw = JSON.parse(localStorage.getItem(SHAPE_KEY) ?? 'null') as Partial | null; + const chips = Array.isArray(raw?.chips) ? raw.chips.filter((n): n is number => typeof n === 'number').slice(0, 24) : []; + return { options: Math.min(24, Math.max(0, Number(raw?.options) || 0)), chips, rules: Math.min(24, Math.max(0, Number(raw?.rules) || 0)) }; + } catch { + return { options: 2, chips: [3, 3], rules: 1 }; + } +} + +function keepShape(s: ConfigState): void { + const shape: Shape = { options: s.options.length, chips: s.options.map((o) => o.choices.length), rules: s.rules.length }; + try { localStorage.setItem(SHAPE_KEY, JSON.stringify(shape)); } catch { return; } +} + +const EMPTY: ConfigState = { options: [], rules: [], name: '', valid: true }; + +export class ConfigStore { + state: ConfigState = EMPTY; + problems: Problem[] = []; + count: Count = { total: 0, complete: true }; + loaded = false; + error = ''; + private revision = -1; + private loading = false; + private again = false; + private visible = false; + private readonly fns = new Set<() => void>(); + private readonly offs: Array<() => void>; + + constructor(private readonly ws: Workspace) { + const follow = (): void => { + const rev = ws.client.summary?.revision ?? -1; + if (rev !== this.revision) void this.reload(); + }; + this.offs = [ws.client.onSummary(follow), ws.client.onCatalogue(() => void this.reload())]; + } + + onChange(fn: () => void): () => void { this.fns.add(fn); return () => { this.fns.delete(fn); }; } + + available(): boolean { return this.ws.canRun(CONFIG_CMD.get); } + + setVisible(on: boolean): void { + if (on === this.visible) return; + this.visible = on; + if (on && this.revision !== (this.ws.client.summary?.revision ?? -1)) void this.reload(); + } + + async reload(): Promise { + if (!this.visible) return; + if (this.loading) { this.again = true; return; } + if (!this.available()) { this.emit(); return; } + this.loading = true; + const rev = this.ws.client.summary?.revision ?? -1; + try { + const [state, check, list] = await Promise.all([ + this.ws.client.dispatch(CONFIG_CMD.get, {}), + this.ws.canRun(CONFIG_CMD.check) ? this.ws.client.dispatch(CONFIG_CMD.check, {}) : Promise.resolve({}), + this.ws.canRun(CONFIG_CMD.list) ? this.ws.client.dispatch(CONFIG_CMD.list, { limit: 1 }) : Promise.resolve({}), + ]); + this.state = parseState(state); + this.problems = parseProblems(check); + this.count = parseCount(list); + this.revision = rev; + this.loaded = true; + this.error = ''; + keepShape(this.state); + } catch (err) { + this.error = err instanceof Error ? err.message : String(err); + } finally { + this.loading = false; + } + this.emit(); + if (this.again) { this.again = false; void this.reload(); } + } + + async fetchState(): Promise { + return parseState(await this.ws.client.dispatch(CONFIG_CMD.get, {})); + } + + dispose(): void { for (const off of this.offs) off(); this.fns.clear(); } + + private emit(): void { for (const fn of this.fns) fn(); } +} diff --git a/frontend/src/ui/import/engine.ts b/frontend/src/ui/import/engine.ts index af0e9f24..952da1a1 100644 --- a/frontend/src/ui/import/engine.ts +++ b/frontend/src/ui/import/engine.ts @@ -132,6 +132,8 @@ export async function probe(path: string): Promise { function args(path: string, o: ImportOptions): Obj { const out: Obj = { path, units: o.units, up_axis: o.up_axis, stand_on_floor: o.stand_on_floor, center: o.center, frame: o.frame, merge: o.merge }; if (o.cad_quality) out.cad_quality = o.cad_quality; + const template = document.querySelector('.fsh-imp select[data-o="template"]')?.value; + if (template) out.template = template; return out; } diff --git a/frontend/src/ui/import/sheet.ts b/frontend/src/ui/import/sheet.ts index 540e7073..045fd1eb 100644 --- a/frontend/src/ui/import/sheet.ts +++ b/frontend/src/ui/import/sheet.ts @@ -160,6 +160,7 @@ export class ImportSheet { this.show(0); this.units.focus(); runCommand('cad.sheet', { select: this.cad, row: q(this.root, '.fsh-imp-cad') }); + runCommand('templates.sheet', { options: q(this.root, '.fsh-imp-options') }); } private options(): ImportOptions { diff --git a/frontend/src/ui/inspector.ts b/frontend/src/ui/inspector.ts index 89401b51..d4fcdbe1 100644 --- a/frontend/src/ui/inspector.ts +++ b/frontend/src/ui/inspector.ts @@ -6,12 +6,14 @@ import { import { t } from '../i18n'; import type { Workspace } from './context'; import { mountCameraPage } from './pages/camera'; +import { mountConfiguratorPage } from './pages/configurator'; import { mountEnvironmentPage } from './pages/environment'; import { mountImagePage } from './pages/image'; import { mountLightingPage } from './pages/lighting'; import { mountMaterialPage } from './pages/material'; -import { emptyPage, type PageMount } from './pages/page'; +import type { PageMount } from './pages/page'; import { mountScenePage } from './pages/scene'; +import { mountShotsPage } from './pages/shots'; const PAGE_KEY = 'formshot.inspectorPage'; @@ -24,7 +26,8 @@ const PAGES: readonly OwnPage[] = [ { id: 'lighting', title: 'Lighting', command: 'Lighting Page', icon: 'light', order: 40, mount: mountLightingPage }, { id: 'camera', title: 'Camera', command: 'Camera Page', icon: 'camera', order: 50, mount: mountCameraPage }, { id: 'image', title: 'Image', command: 'Image Page', icon: 'image', order: 60, mount: mountImagePage }, - { id: 'snapshots', title: 'Snapshots', command: 'Snapshots Page', icon: 'snapshot', order: 70, mount: emptyPage('Snapshots', 'Snapshots, variants and turntables arrive in 0.9.0.') }, + { id: 'snapshots', title: 'Shots', command: 'Shots Page', icon: 'snapshot', order: 70, mount: mountShotsPage }, + { id: 'configurator', title: 'Configurator', command: 'Configurator Page', icon: 'sliders', order: 75, mount: mountConfiguratorPage }, ]; function storedPage(): string { diff --git a/frontend/src/ui/labels/image.ts b/frontend/src/ui/labels/image.ts index 55d0e377..abdbe455 100644 --- a/frontend/src/ui/labels/image.ts +++ b/frontend/src/ui/labels/image.ts @@ -13,8 +13,8 @@ let routeProbe: Promise | null = null; function uploadRoute(): Promise { if (!routeProbe) { - routeProbe = fetch(api.url(ROUTE), { method: 'GET' }) - .then((r) => r.status !== 404) + routeProbe = fetch(api.url(ROUTE), { method: 'POST', body: new FormData(), cache: 'no-store' }) + .then((r) => r.status !== 404 && r.status !== 405) .catch(() => false); } return routeProbe; diff --git a/frontend/src/ui/material/list.ts b/frontend/src/ui/material/list.ts index 7c2ac200..2600d50e 100644 --- a/frontend/src/ui/material/list.ts +++ b/frontend/src/ui/material/list.ts @@ -56,6 +56,7 @@ export function mountList(host: HTMLElement, ws: Workspace, store: MaterialStore const picker = new Popover('fsh-mat-types', t('Material types')); picker.root.addEventListener('click', (e) => { + if ((e.target as HTMLElement).closest('button[data-cmd]')) { picker.close(); return; } const b = (e.target as HTMLElement).closest('button[data-type]'); if (!b) return; picker.close(); @@ -73,6 +74,7 @@ export function mountList(host: HTMLElement, ws: Workspace, store: MaterialStore const ia = CATEGORY_ORDER.indexOf(a), ib = CATEGORY_ORDER.indexOf(b); return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib) || a.localeCompare(b); }); + const templates = `
      `; const html = cats.map((cat) => { const items = (groups.get(cat) ?? []).map((ty) => ``).join(''); const metals = cat === 'Metal' && store.metals.length @@ -80,7 +82,7 @@ export function mountList(host: HTMLElement, ws: Workspace, store: MaterialStore : ''; return `

      ${escapeHtml(t(cat))}

      ${items}
      ${metals}
      `; }).join(''); - setHtml(picker.root, html || `

      ${escapeHtml(t('The engine lists no material types yet'))}

      `, JSON.stringify([store.types.map((x) => x.id), store.metals.map((m) => m.id)])); + setHtml(picker.root, (html || `

      ${escapeHtml(t('The engine lists no material types yet'))}

      `) + templates, JSON.stringify([store.types.map((x) => x.id), store.metals.map((m) => m.id)])); }; const create = async (typeId: string, metalId: string | null): Promise => { diff --git a/frontend/src/ui/material/model.ts b/frontend/src/ui/material/model.ts index 7681326b..f6fc2621 100644 --- a/frontend/src/ui/material/model.ts +++ b/frontend/src/ui/material/model.ts @@ -88,6 +88,56 @@ export const FIELDS: Readonly> = { normal: { label: 'Normal', kind: 'float', min: 0, max: 1 }, bump: { label: 'Bump', kind: 'float', min: 0, max: 1 }, displacement: { label: 'Displacement', kind: 'float', min: 0, max: 1 }, + transmission_scatter_anisotropy: F('Scatter anisotropy', -1, 1), + subsurface_scatter_anisotropy: F('Subsurface anisotropy', -1, 1), + edge_radius: F('Edge radius', 0, 0.01, 'm'), + edge_other_parts: { label: 'Round against other parts', kind: 'bool', min: 0, max: 1 }, + fibre_density: F('Fibre density', 0, 2000), + fibre_length: F('Fibre length', 0, 0.05, 'm'), + fibre_root_width: F('Root width', 0, 0.001, 'm'), + fibre_tip_width: F('Tip width', 0, 0.001, 'm'), + fibre_comb: F('Comb'), + fibre_randomness: F('Randomness'), + fibre_curl: F('Curl'), + fibre_clumping: F('Clumping'), + fibre_own_color: { label: 'Own fibre colour', kind: 'bool', min: 0, max: 1 }, + fibre_color: C('Fibre colour'), + fibre_roughness: F('Fibre roughness'), + fibre_radial_roughness: F('Radial roughness'), +}; + +export interface ParamSection { id: string; title: string; feature: string; fields: readonly string[] } + +export const TRANSPORT_SECTIONS: readonly ParamSection[] = [ + { id: 'medium', title: 'Medium inside', feature: 'volume', fields: ['transmission_scatter', 'transmission_scatter_anisotropy', 'medium_priority'] }, + { id: 'subsurface', title: 'Subsurface scattering', feature: 'subsurface', fields: ['subsurface_radius_scale', 'subsurface_scatter_anisotropy'] }, + { id: 'edges', title: 'Rounded edges', feature: 'rounded_edges', fields: ['edge_radius', 'edge_other_parts'] }, + { id: 'fibres', title: 'Fibres', feature: 'fibres', fields: [ + 'fibre_density', 'fibre_length', 'fibre_root_width', 'fibre_tip_width', 'fibre_comb', 'fibre_comb_direction', 'fibre_randomness', + 'fibre_curl', 'fibre_clumping', 'fibre_own_color', 'fibre_color', 'fibre_roughness', 'fibre_radial_roughness', 'fibre_seed', + ] }, +]; + +export const TRANSPORT_LABELS: Readonly> = { + transmission_scatter: 'Scatter colour', + transmission_scatter_amount: 'Scatter amount', + medium_priority: 'Medium priority', + subsurface_radius_scale: 'Radius scale', + fibre_comb_direction: 'Comb direction', + fibre_seed: 'Fibre seed', +}; + +export interface DisplayUnit { unit: string; scale: number; min: number; max: number; integer?: boolean } + +export const TRANSPORT_UNITS: Readonly> = { + transmission_scatter_amount: { unit: '', scale: 1, min: 0, max: 10 }, + medium_priority: { unit: '', scale: 1, min: 0, max: 1000, integer: true }, + edge_radius: { unit: 'mm', scale: 1000, min: 0, max: 10 }, + fibre_density: { unit: '/cm²', scale: 1, min: 0, max: 2000 }, + fibre_length: { unit: 'mm', scale: 1000, min: 0, max: 50 }, + fibre_root_width: { unit: 'µm', scale: 1e6, min: 0, max: 1000 }, + fibre_tip_width: { unit: 'µm', scale: 1e6, min: 0, max: 1000 }, + fibre_seed: { unit: '', scale: 1, min: 0, max: 99999, integer: true }, }; export const FIELD_ORDER: readonly string[] = Object.keys(FIELDS).filter((f) => !(GEOMETRY_INPUTS as readonly string[]).includes(f)); diff --git a/frontend/src/ui/material/params.ts b/frontend/src/ui/material/params.ts index 76ccd6d9..e7407a25 100644 --- a/frontend/src/ui/material/params.ts +++ b/frontend/src/ui/material/params.ts @@ -10,6 +10,7 @@ import { import { Popover } from './popover'; import { colourRow, numberRow, toggleRow, type Control } from './rows'; import { CMD, type MaterialStore } from './store'; +import { mountTransportParams } from '../transport/material'; export interface ParamsHost { current(): string | null; @@ -34,6 +35,7 @@ export function mountParams(host: HTMLElement, ws: Workspace, store: MaterialSto const all = q(root, '.fsh-mat-all'); const allList = q(root, '.fsh-mat-all-list'); const allRows: Row[] = []; + const transport = mountTransportParams(list, ws, store, edits, page); let pendingType: string | null = null; const choice = new Popover('fsh-mat-typechoice', t('Change the material type')); @@ -147,7 +149,7 @@ export function mountParams(host: HTMLElement, ws: Workspace, store: MaterialSto setDisabled(typeSelect, !canType); setTitle(typeSelect, !row ? '' : canType ? '' : ws.why(CMD.setType)); setHidden(root, !row); - const specs = type?.shown ?? (d ? FIELD_ORDER.slice(0, 6).map((f) => specFor(f, null)) : []); + const specs = (type?.shown ?? (d ? FIELD_ORDER.slice(0, 6).map((f) => specFor(f, null)) : [])).filter((s) => !transport.owns(s.field)); patchList(list, specs, { key: (s) => `${s.field}:${s.kind}`, create: (s) => { @@ -159,6 +161,7 @@ export function mountParams(host: HTMLElement, ws: Workspace, store: MaterialSto update: (_node, s) => { shownRows.get(`${s.field}:${s.kind}`)?.update(d); }, }); for (const k of [...shownRows.keys()]) if (!specs.some((s) => `${s.field}:${s.kind}` === k)) shownRows.delete(k); + transport.update(type, d); const msg = !row ? '' : !store.types.length ? t('Waiting for the material types') : type ? '' : t('The engine does not know the type {id}; showing the main values.', { id: typeId }); setText(note, msg); setHidden(note, msg === ''); diff --git a/frontend/src/ui/measure/draw.ts b/frontend/src/ui/measure/draw.ts new file mode 100644 index 00000000..03799e7d --- /dev/null +++ b/frontend/src/ui/measure/draw.ts @@ -0,0 +1,215 @@ +import { transformPoint } from '../../engine/raster/math'; +import { cameraMatrices } from '../../engine/raster/renderer'; +import type { Vec3 } from '../../engine/types'; +import type { Overlay } from '../overlay'; +import type { ViewCamera } from '../view-camera'; +import type { Point } from '../viewport-input'; +import type { MeasureItem, ToolMode } from './model'; + +const LINE = 'rgba(255, 255, 255, 0.92)'; +const HALO = 'rgba(0, 0, 0, 0.55)'; +const PLATE = 'rgba(18, 18, 20, 0.84)'; +const INK = '#f4f4f5'; +const BOX_DASH = [5, 4]; +const TICK = 6; +const NEAR = 1e-4; + +export interface MeasureScene { + items: readonly MeasureItem[]; + pending: readonly Vec3[]; + hover: Point | null; + mode: ToolMode | null; + highlight: string | null; + accent: string; +} + +type Screen = [number, number]; + +interface Projector { + point(p: Vec3): Screen | null; + segment(a: Vec3, b: Vec3): [Screen, Screen] | null; + depth(p: Vec3): number; +} + +function projector(cam: ViewCamera, w: number, h: number): Projector { + const aspect = w / Math.max(h, 1); + const m = cameraMatrices(cam.raster(), aspect, null); + const toScreen = (v: Vec3): Screen => { + let x: number, y: number; + if (m.ortho) { x = v[0] / (m.orthoHalfH * aspect); y = v[1] / m.orthoHalfH; } else { + const z = Math.max(-v[2], NEAR); + x = v[0] / (z * m.tanX); + y = v[1] / (z * m.tanY); + } + return [(x + 1) * 0.5 * w, (1 - y) * 0.5 * h]; + }; + const inFront = (v: Vec3): boolean => m.ortho || -v[2] > NEAR; + return { + point(p) { const v = transformPoint(m.view, p); return inFront(v) ? toScreen(v) : null; }, + depth(p) { return -transformPoint(m.view, p)[2]; }, + segment(a, b) { + let va = transformPoint(m.view, a), vb = transformPoint(m.view, b); + const fa = inFront(va), fb = inFront(vb); + if (!fa && !fb) return null; + if (!fa || !fb) { + const t = (-NEAR - va[2]) / (vb[2] - va[2]); + const c: Vec3 = [va[0] + (vb[0] - va[0]) * t, va[1] + (vb[1] - va[1]) * t, -NEAR * 1.0001]; + if (!fa) va = c; else vb = c; + } + return [toScreen(va), toScreen(vb)]; + }, + }; +} + +function stroke(ctx: CanvasRenderingContext2D, segs: [Screen, Screen][], colour: string, width: number, dash: number[] = []): void { + if (!segs.length) return; + ctx.setLineDash(dash); + for (const [c, wd] of [[HALO, width + 2], [colour, width]] as const) { + ctx.strokeStyle = c; + ctx.lineWidth = wd; + ctx.beginPath(); + for (const [a, b] of segs) { ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); } + ctx.stroke(); + } + ctx.setLineDash([]); +} + +function ticks(a: Screen, b: Screen): [Screen, Screen][] { + const dx = b[0] - a[0], dy = b[1] - a[1]; + const len = Math.hypot(dx, dy) || 1; + const nx = (-dy / len) * TICK, ny = (dx / len) * TICK; + return [a, b].map((e): [Screen, Screen] => [[e[0] - nx, e[1] - ny], [e[0] + nx, e[1] + ny]]); +} + +interface Plate { text: string; at: Screen; accent: string | null } + +const plates: Plate[] = []; + +function label(_ctx: CanvasRenderingContext2D, text: string, at: Screen, accent: string | null): void { + if (text) plates.push({ text, at, accent }); +} + +function flushLabels(ctx: CanvasRenderingContext2D): void { + const placed: [number, number, number, number][] = []; + ctx.font = '600 11px system-ui, -apple-system, "Segoe UI", sans-serif'; + const lit = plates.filter((p) => p.accent); + const order = [...plates.filter((p) => !p.accent), ...lit]; + plates.length = 0; + for (const p of order) { + const w = Math.ceil(ctx.measureText(p.text).width) + 12; + let cy = p.at[1]; + for (let i = 0; i < 6; i++) { + const hit = placed.find((r) => Math.abs(p.at[0] - r[0]) < (w + r[2]) / 2 && Math.abs(cy - r[1]) < 20); + if (!hit) break; + cy = hit[1] + 21; + } + placed.push([p.at[0], cy, w, 18]); + drawLabel(ctx, p.text, [p.at[0], cy], w, p.accent); + } +} + +function drawLabel(ctx: CanvasRenderingContext2D, text: string, at: Screen, w: number, accent: string | null): void { + const h = 18; + const x = Math.round(at[0] - w / 2), y = Math.round(at[1] - h / 2); + ctx.fillStyle = PLATE; + ctx.beginPath(); + ctx.roundRect(x, y, w, h, 4); + ctx.fill(); + if (accent) { ctx.strokeStyle = accent; ctx.lineWidth = 1; ctx.stroke(); } + ctx.fillStyle = INK; + ctx.textBaseline = 'middle'; + ctx.textAlign = 'center'; + ctx.fillText(text, at[0], y + h / 2 + 0.5); +} + +function dot(ctx: CanvasRenderingContext2D, p: Screen, colour: string): void { + ctx.fillStyle = HALO; + ctx.beginPath(); + ctx.arc(p[0], p[1], 5, 0, Math.PI * 2); + ctx.fill(); + ctx.fillStyle = colour; + ctx.beginPath(); + ctx.arc(p[0], p[1], 3.5, 0, Math.PI * 2); + ctx.fill(); +} + +const mid = (a: Screen, b: Screen): Screen => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; + +function arcSegments(v: Screen, a: Screen, b: Screen): { segs: [Screen, Screen][]; at: Screen } { + const la = Math.hypot(a[0] - v[0], a[1] - v[1]), lb = Math.hypot(b[0] - v[0], b[1] - v[1]); + const r = Math.min(56, Math.max(12, 0.3 * Math.min(la, lb))); + const t0 = Math.atan2(a[1] - v[1], a[0] - v[0]); + let t1 = Math.atan2(b[1] - v[1], b[0] - v[0]); + while (t1 - t0 > Math.PI) t1 -= Math.PI * 2; + while (t0 - t1 > Math.PI) t1 += Math.PI * 2; + const n = Math.max(4, Math.ceil(Math.abs(t1 - t0) * r / 4)); + const at = (t: number): Screen => [v[0] + r * Math.cos(t), v[1] + r * Math.sin(t)]; + const segs: [Screen, Screen][] = []; + for (let i = 0; i < n; i++) segs.push([at(t0 + (t1 - t0) * i / n), at(t0 + (t1 - t0) * (i + 1) / n)]); + const m = (t0 + t1) / 2; + return { segs, at: [v[0] + (r + 16) * Math.cos(m), v[1] + (r + 16) * Math.sin(m)] }; +} + +function paintItem(ctx: CanvasRenderingContext2D, pr: Projector, it: MeasureItem, accent: string, lit: boolean): void { + const colour = lit ? accent : LINE; + const ring = lit ? accent : null; + const pts = it.points; + if (it.kind === 'distance' && pts.length === 2) { + const s = pr.segment(pts[0], pts[1]); + if (!s) return; + stroke(ctx, [s, ...ticks(s[0], s[1])], colour, 1.5); + if (!it.labelHidden) label(ctx, it.text, mid(s[0], s[1]), ring); + return; + } + if (it.kind === 'angle' && pts.length === 3) { + const v = pr.point(pts[0]), a = pr.point(pts[1]), b = pr.point(pts[2]); + if (!v || !a || !b) return; + const arc = arcSegments(v, a, b); + stroke(ctx, [[v, a], [v, b], ...arc.segs], colour, 1.5); + if (!it.labelHidden) label(ctx, it.text, arc.at, ring); + return; + } + if (it.kind === 'size' && pts.length === 8) { + const segs: [Screen, Screen][] = []; + const best: (Screen | null)[] = [null, null, null]; + for (let axis = 0; axis < 3; axis++) { + let near = -Infinity; + for (let c = 0; c < 8; c++) { + if (c & (1 << axis)) continue; + const s = pr.segment(pts[c], pts[c | (1 << axis)]); + if (!s) continue; + segs.push(s); + const d = -(pr.depth(pts[c]) + pr.depth(pts[c | (1 << axis)])); + if (d > near) { near = d; best[axis] = mid(s[0], s[1]); } + } + } + stroke(ctx, segs, colour, 1, BOX_DASH); + if (it.labelHidden || !it.size) return; + const texts = [it.size.width, it.size.height, it.size.depth]; + best.forEach((at, i) => { if (at) label(ctx, texts[i], at, ring); }); + } +} + +export function paintMeasurements(ctx: CanvasRenderingContext2D, overlay: Overlay, cam: ViewCamera, scene: MeasureScene): void { + const w = overlay.width, h = overlay.height; + if (w <= 0 || h <= 0) return; + ctx.scale(overlay.dpr, overlay.dpr); + ctx.lineCap = 'round'; + ctx.lineJoin = 'round'; + const pr = projector(cam, w, h); + for (const it of scene.items) { + if (!it.visible || it.id === scene.highlight) continue; + paintItem(ctx, pr, it, scene.accent, false); + } + const lit = scene.items.find((it) => it.id === scene.highlight && it.visible); + if (lit) paintItem(ctx, pr, lit, scene.accent, true); + flushLabels(ctx); + if (!scene.mode) return; + const pend = scene.pending.map((p) => pr.point(p)).filter((p): p is Screen => p !== null); + const segs: [Screen, Screen][] = []; + if (scene.mode === 'angle' && pend.length >= 2) segs.push([pend[0], pend[1]]); + const last = scene.mode === 'angle' ? pend[0] : pend[pend.length - 1]; + if (last && scene.hover) segs.push([last, [scene.hover.x, scene.hover.y]]); + stroke(ctx, segs, scene.accent, 1.5, [4, 3]); + for (const p of pend) dot(ctx, p, scene.accent); +} \ No newline at end of file diff --git a/frontend/src/ui/measure/icons.ts b/frontend/src/ui/measure/icons.ts new file mode 100644 index 00000000..75e43f5c --- /dev/null +++ b/frontend/src/ui/measure/icons.ts @@ -0,0 +1,14 @@ +const s = (body: string): string => ``; + +const MEASURE_ICONS = { + distance: s(''), + angle: s(''), + size: s(''), + list: s(''), +} as const; + +export type MeasureIcon = keyof typeof MEASURE_ICONS; + +export function measureIcon(name: MeasureIcon, size = 16): string { + return ``; +} \ No newline at end of file diff --git a/frontend/src/ui/measure/index.ts b/frontend/src/ui/measure/index.ts new file mode 100644 index 00000000..99c5f9e9 --- /dev/null +++ b/frontend/src/ui/measure/index.ts @@ -0,0 +1,244 @@ +import './measure.css'; +import { el, q, setAttr, setDisabled, setHidden, setPressed, setText, setTitle } from '../../shell/dom'; +import { registerCommands } from '../../shell/registry'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { addOverlayLayer, invalidateOverlays } from '../overlay'; +import type { Point, ViewportSession } from '../viewport-input'; +import { paintMeasurements } from './draw'; +import { measureIcon } from './icons'; +import { + ADD_ANGLE, ADD_DISTANCE, ADD_SIZE, CLEAR, LIST, NEEDED, PICK, REMOVE, SET, VIEW_PICK, parseList, pickedOf, + type MeasureList, type PickedPoint, type ToolMode, +} from './model'; +import { MeasurePanel } from './panel'; + +const STORE = 'formshot.measure'; +const QUIET = /^(measure\.(list|pick)|view\.|camera\.|render\.|selection\.|scene\.summary|scene\.meshes|scene\.mesh_data|history\.barrier)/; +const MODES: readonly ToolMode[] = ['distance', 'angle', 'size']; +const MODE_COMMAND: Record = { distance: ADD_DISTANCE, angle: ADD_ANGLE, size: ADD_SIZE }; +const MODE_LABEL: Record = { distance: 'Measure Distance', angle: 'Measure Angle', size: 'Measure Size Box' }; +const MODE_KEYS: Record = { distance: ' (M)', angle: '', size: '' }; + +interface Stored { panel: boolean; ownAxes: boolean } + +function load(): Stored { + try { + const raw = JSON.parse(localStorage.getItem(STORE) ?? '{}') as Partial; + return { panel: raw.panel === true, ownAxes: raw.ownAxes === true }; + } catch { return { panel: false, ownAxes: false }; } +} + +function hintFor(mode: ToolMode, pending: number): string { + if (mode === 'size') return 'Click a part to measure its size box, or select parts and choose the tool again.'; + if (mode === 'angle') return ['Click the corner of the angle.', 'Click the end of the first arm.', 'Click the end of the second arm.'][pending] ?? ''; + return pending === 0 ? 'Click the first point. Hold Shift to snap to a corner.' : 'Click the second point. Hold Shift to snap to a corner.'; +} + +class MeasureTool { + private readonly ws: Workspace; + private mode: ToolMode | null = null; + private pending: PickedPoint[] = []; + private hover: Point | null = null; + private data: MeasureList | null = null; + private highlight: string | null = null; + private stored = load(); + private fetching = false; + private again = false; + private chain: Promise = Promise.resolve(); + private accent = '#f97316'; + private readonly buttons: HTMLButtonElement[]; + private readonly listBtn: HTMLButtonElement; + private readonly hint: HTMLElement; + private readonly hintText: HTMLElement; + private readonly panel: MeasurePanel; + + constructor(private readonly s: ViewportSession) { + this.ws = s.camera.ws; + const host = s.target.parentElement ?? s.target; + const island = el(``); + this.hint = el(''); + host.append(island, this.hint); + this.hintText = q(this.hint, '.fsh-ms-hint-text'); + this.buttons = [...island.querySelectorAll('[data-ms-mode]')]; + this.listBtn = q(island, '.fsh-ms-list-btn'); + for (const b of this.buttons) b.addEventListener('click', () => this.choose(b.dataset.msMode as ToolMode)); + this.listBtn.addEventListener('click', () => this.setPanel(!this.panel.open)); + this.panel = new MeasurePanel(host, { + rename: (id, name) => void this.edit(SET, { id, name }), + show: (id, visible) => void this.edit(SET, { id, visible }), + remove: (id) => void this.edit(REMOVE, { id }), + clear: () => void this.edit(CLEAR, {}), + precision: (digits) => void this.edit(SET, { precision: digits }), + highlight: (id) => { if (this.highlight !== id) { this.highlight = id; invalidateOverlays(); } }, + close: () => this.setPanel(false), + ownAxes: (on) => { this.stored.ownAxes = on; this.save(); }, + }); + this.panel.setOwnAxes(this.stored.ownAxes); + this.setPanel(this.stored.panel); + + addOverlayLayer((ctx, overlay) => paintMeasurements(ctx, overlay, s.camera, { + items: this.data?.items ?? [], pending: this.pending.map((p) => p.point), hover: this.hover, + mode: this.mode, highlight: this.highlight, accent: this.accent, + })); + registerCommands([ + { id: 'measure.tool', label: 'Measure', group: 'View', keys: ['M'], description: 'Measure distances in the viewport; choose again to stop.', run: () => this.choose(this.mode ?? 'distance') }, + { id: 'measure.panel', label: 'Measurements List', group: 'View', checked: () => this.panel.open, run: () => this.setPanel(!this.panel.open) }, + ]); + const client = this.ws.client; + client.onDispatch((n) => { if (!QUIET.test(n.name)) this.refresh(); }); + client.onSummary(() => this.refresh()); + client.onCatalogue(() => { this.paintTools(); this.refresh(); }); + client.onState(() => this.paintTools()); + window.addEventListener('keydown', (e) => this.key(e), true); + s.setTool({ click: (p, m, double) => this.click(p, m.shift, double), hover: (p) => this.hoverAt(p) }); + this.readAccent(); + this.paintTools(); + } + + private readAccent(): void { + const v = getComputedStyle(this.s.target).getPropertyValue('--accent-color').trim(); + if (v) this.accent = v; + } + + private save(): void { + try { localStorage.setItem(STORE, JSON.stringify(this.stored)); } catch { return; } + } + + private setPanel(open: boolean): void { + this.panel.setOpen(open); + setPressed(this.listBtn, open); + if (this.stored.panel !== open) { this.stored.panel = open; this.save(); } + if (open) this.refresh(); + } + + private choose(mode: ToolMode): void { + if (mode === 'size') { + const sel = (this.ws.client.summary?.selection ?? []).map(String); + if (sel.length && this.mode !== 'size') { void this.addSize(sel); return; } + } + if (this.mode === mode) { this.stop(); return; } + if (!this.ws.canRun(MODE_COMMAND[mode])) { this.ws.client.message(this.ws.why(MODE_COMMAND[mode]), 'error'); return; } + this.readAccent(); + this.mode = mode; + this.pending = []; + this.paintTools(); + invalidateOverlays(); + } + + private stop(): void { + this.mode = null; + this.pending = []; + this.hover = null; + this.paintTools(); + invalidateOverlays(); + } + + private key(e: KeyboardEvent): void { + if (e.key !== 'Escape' || !this.mode) return; + const target = e.target as HTMLElement | null; + if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return; + e.preventDefault(); + e.stopPropagation(); + if (this.pending.length) { this.pending = []; this.paintTools(); invalidateOverlays(); } else this.stop(); + } + + private hoverAt(p: Point | null): void { + if (!this.mode) { if (this.hover) { this.hover = null; invalidateOverlays(); } return; } + this.hover = p; + if (this.pending.length) invalidateOverlays(); + } + + private click(p: Point, snap: boolean, double: boolean): boolean { + if (!this.mode) return false; + if (double) return true; + this.chain = this.chain.then(() => this.pickAt(p, snap)); + return true; + } + + private async pickAt(p: Point, snap: boolean): Promise { + const mode = this.mode; + if (!mode) return; + const r = this.s.frame(); + const width = r.width, height = r.height; + if (width < 1 || height < 1 || p.x < 0 || p.y < 0 || p.x > width || p.y > height) return; + const client = this.ws.client; + const name = this.ws.canRun(PICK) ? PICK : this.ws.canRun(VIEW_PICK) ? VIEW_PICK : null; + if (!name) { client.message(this.ws.why(PICK), 'error'); return; } + const args: Record = { x: p.x, y: p.y, width, height }; + if (name === PICK) args.snap = snap ? 'vertex' : 'none'; + let hit: PickedPoint | null = null; + try { hit = pickedOf(await client.dispatch(name, args)); } catch (err) { + client.message(err instanceof Error ? err.message : String(err), 'error'); + return; + } + if (this.mode !== mode) return; + if (!hit) { client.message(t('Click on a part to place a point')); return; } + if (mode === 'size') { await this.addSize([hit.node]); return; } + this.pending.push(hit); + this.paintTools(); + invalidateOverlays(); + if (this.pending.length < NEEDED[mode]) return; + const pts = this.pending.map((x) => ({ node: x.node, point: x.point })); + this.pending = []; + this.paintTools(); + if (mode === 'distance') await this.edit(ADD_DISTANCE, { a: pts[0], b: pts[1] }); + else await this.edit(ADD_ANGLE, { vertex: pts[0], a: pts[1], b: pts[2] }); + invalidateOverlays(); + } + + private async addSize(nodes: string[]): Promise { + const args: Record = { nodes }; + if (this.stored.ownAxes) args.frame = 'local'; + await this.edit(ADD_SIZE, args); + } + + private async edit(name: string, args: Record): Promise { + await this.ws.run(name, args); + this.refresh(); + } + + private refresh(): void { + if (!this.ws.canRun(LIST)) { + if (this.data) { this.data = null; this.paintList(); } + return; + } + if (this.fetching) { this.again = true; return; } + this.fetching = true; + void this.ws.client.dispatch(LIST, {}).then((reply) => { + const next = parseList(reply); + if (next) { this.data = next; this.paintList(); } + }, () => undefined).finally(() => { + this.fetching = false; + if (this.again) { this.again = false; this.refresh(); } + }); + } + + private paintList(): void { + this.panel.update(this.data, this.ws.canRun(SET)); + if (this.highlight && !this.data?.items.some((i) => i.id === this.highlight)) this.highlight = null; + invalidateOverlays(); + } + + private paintTools(): void { + for (const b of this.buttons) { + const mode = b.dataset.msMode as ToolMode; + setPressed(b, this.mode === mode); + const can = this.ws.canRun(MODE_COMMAND[mode]); + setDisabled(b, !can); + setTitle(b, can ? `${t(MODE_LABEL[mode])}${MODE_KEYS[mode]}` : this.ws.why(MODE_COMMAND[mode])); + } + setDisabled(this.listBtn, !this.ws.canRun(LIST)); + setAttr(this.s.target.parentElement, 'data-measuring', this.mode ?? null); + setHidden(this.hint, this.mode === null); + setText(this.hintText, this.mode ? t(hintFor(this.mode, this.pending.length)) : ''); + } +} + +export function mountMeasure(s: ViewportSession): void { + new MeasureTool(s); +} \ No newline at end of file diff --git a/frontend/src/ui/measure/measure.css b/frontend/src/ui/measure/measure.css new file mode 100644 index 00000000..cf895482 --- /dev/null +++ b/frontend/src/ui/measure/measure.css @@ -0,0 +1,36 @@ +.fsh-ms-island { left: var(--space-3); bottom: var(--space-3); } +.fsh-ms-sep { flex: none; width: 1px; height: 60%; min-height: 14px; margin: 0 var(--space-0); background: var(--line-1); } +.fsh-ws-vp[data-measuring] .fsh-ws-vp-stage, .fsh-ws-vp.can-navigate[data-measuring] .fsh-ws-vp-stage { cursor: crosshair; } + +.fsh-ms-hint { position: absolute; z-index: var(--z-raised); left: 50%; bottom: var(--space-3); display: flex; align-items: center; gap: var(--space-2); max-width: calc(100% - 2 * var(--space-8) - 360px); height: var(--ctl-md); padding: 0 var(--space-3); transform: translateX(-50%); border-radius: var(--radius-lg); background: var(--glass-bg); border: 1px solid var(--glass-border); box-shadow: var(--glass-shadow); backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); color: var(--text-primary); font-size: var(--fs-11); white-space: nowrap; pointer-events: none; } +.fsh-ms-hint[hidden] { display: none; } +.fsh-ms-hint-text { overflow: hidden; text-overflow: ellipsis; } +.fsh-ms-hint-esc { flex: none; color: var(--text-faint); } + +.fsh-ms-panel { position: absolute; z-index: var(--z-raised); left: var(--space-3); bottom: calc(var(--space-3) + var(--ctl-md) + 2 * var(--space-0) + 2px + var(--space-2)); display: flex; flex-direction: column; width: 320px; max-width: calc(100% - 2 * var(--space-3)); max-height: calc(100% - 2 * var(--ctl-md) - 6 * 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); backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); font-size: var(--fs-12); color: var(--text-primary); } +.fsh-ms-panel[hidden] { display: none; } +.fsh-ms-head { display: flex; align-items: center; gap: var(--space-2); height: var(--ctl-lg); padding: 0 var(--space-1) 0 var(--space-3); border-bottom: 1px solid var(--line-1); } +.fsh-ms-title { font-weight: 600; } +.fsh-ms-count { flex: 1; color: var(--text-faint); font-size: var(--fs-11); } +.fsh-ms-listbox { position: relative; flex: 1 1 auto; min-height: calc(var(--ctl-md) * 3 + var(--space-1) * 2); overflow-y: auto; } +.fsh-ms-list { display: flex; flex-direction: column; padding: var(--space-1); } +.fsh-ms-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; margin: 0; padding: var(--space-2) var(--space-4); color: var(--text-faint); font-size: var(--fs-11); text-align: center; pointer-events: none; } +.fsh-ms-empty[hidden] { display: none; } +.fsh-ms-row { display: grid; grid-template-columns: 16px minmax(0, 1fr) auto auto auto; align-items: center; gap: var(--space-1); height: var(--ctl-md); padding: 0 0 0 var(--space-2); border-radius: var(--radius); } +.fsh-ms-row:hover { background: var(--bg-hover); } +.fsh-ms-kind { display: inline-flex; color: var(--text-secondary); } +.fsh-ms-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: text; } +.fsh-ms-rename { min-width: 0; height: var(--ctl-sm); padding: 0 var(--space-1); border: 1px solid var(--accent-line); border-radius: var(--radius-sm); background: var(--surface-field); color: var(--text-primary); font: inherit; } +.fsh-ms-rename[hidden], .fsh-ms-name[hidden] { display: none; } +.fsh-ms-value { padding: 0 var(--space-1); color: var(--text-secondary); font-size: var(--fs-11); white-space: nowrap; } +.fsh-ms-row .fsh-ws-tool { min-width: var(--ctl-sm); height: var(--ctl-sm); padding: 0 4px; } +.fsh-ms-row .fsh-ms-remove { visibility: hidden; } +.fsh-ms-row:hover .fsh-ms-remove, .fsh-ms-row:focus-within .fsh-ms-remove { visibility: visible; } +.fsh-ms-row.is-hidden .fsh-ms-name, .fsh-ms-row.is-hidden .fsh-ms-value, .fsh-ms-row.is-hidden .fsh-ms-kind { opacity: 0.45; } +.fsh-ms-row.is-broken .fsh-ms-value { color: var(--text-faint); font-style: italic; } +.fsh-ms-foot { display: flex; align-items: center; gap: var(--space-3); min-height: var(--ctl-lg); padding: 0 var(--space-2) 0 var(--space-3); border-top: 1px solid var(--line-1); color: var(--text-secondary); font-size: var(--fs-11); } +.fsh-ms-field, .fsh-ms-check { display: inline-flex; align-items: center; gap: var(--space-1); white-space: nowrap; } +.fsh-ms-digits { height: var(--ctl-sm); padding: 0 var(--space-1); border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: var(--surface-field); color: var(--text-primary); font: inherit; } +.fsh-ms-clear { margin-left: auto; height: var(--ctl-sm); padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: transparent; color: var(--text-secondary); font: inherit; cursor: pointer; } +.fsh-ms-clear:hover:not(:disabled) { background: var(--bg-hover); color: var(--text-primary); } +.fsh-ms-clear:disabled { opacity: 0.4; cursor: default; } \ No newline at end of file diff --git a/frontend/src/ui/measure/model.ts b/frontend/src/ui/measure/model.ts new file mode 100644 index 00000000..6c30a2df --- /dev/null +++ b/frontend/src/ui/measure/model.ts @@ -0,0 +1,87 @@ +import type { Vec3 } from '../../engine/types'; + +export const LIST = 'measure.list'; +export const PICK = 'measure.pick'; +export const VIEW_PICK = 'view.pick'; +export const ADD_DISTANCE = 'measure.add_distance'; +export const ADD_SIZE = 'measure.add_size'; +export const ADD_ANGLE = 'measure.add_angle'; +export const SET = 'measure.set'; +export const REMOVE = 'measure.remove'; +export const CLEAR = 'measure.clear'; + +export type MeasureKind = 'distance' | 'size' | 'angle'; +export type ToolMode = MeasureKind; + +export interface SizeText { width: string; height: string; depth: string } + +export interface MeasureItem { + id: string; + name: string; + kind: MeasureKind; + visible: boolean; + text: string; + ok: boolean; + points: Vec3[]; + size: SizeText | null; + labelHidden: boolean; + missing: string[]; +} + +export interface MeasureList { + unit: string; + precision: number; + items: MeasureItem[]; +} + +export interface PickedPoint { node: string; point: Vec3 } + +const vec = (v: unknown): Vec3 | null => + Array.isArray(v) && v.length >= 3 && v.slice(0, 3).every((n) => typeof n === 'number' && Number.isFinite(n)) ? [v[0], v[1], v[2]] : null; + +const str = (v: unknown): string => (typeof v === 'string' ? v : typeof v === 'number' ? String(v) : ''); + +function kindOf(v: unknown): MeasureKind | null { + return v === 'distance' || v === 'size' || v === 'angle' ? v : null; +} + +function itemOf(v: unknown): MeasureItem | null { + if (!v || typeof v !== 'object') return null; + const r = v as Record; + const kind = kindOf(r.kind); + const id = str(r.id); + if (!kind || !id) return null; + const points = Array.isArray(r.points) ? r.points.map(vec).filter((p): p is Vec3 => p !== null) : []; + const size = r.size && typeof r.size === 'object' ? (r.size as Record).text : null; + const st = size && typeof size === 'object' ? size as Record : null; + const label = r.label && typeof r.label === 'object' ? r.label as Record : {}; + return { + id, + name: str(r.name) || id, + kind, + visible: r.visible !== false, + text: str(r.text), + ok: r.ok === true, + points, + size: st ? { width: str(st.width), height: str(st.height), depth: str(st.depth) } : null, + labelHidden: label.hidden === true, + missing: Array.isArray(r.missing) ? r.missing.map(str) : [], + }; +} + +export function parseList(v: unknown): MeasureList | null { + if (!v || typeof v !== 'object') return null; + const r = v as Record; + const items = Array.isArray(r.measurements) ? r.measurements.map(itemOf).filter((m): m is MeasureItem => m !== null) : []; + return { unit: str(r.unit) || 'm', precision: typeof r.precision === 'number' ? r.precision : 1, items }; +} + +export function pickedOf(v: unknown): PickedPoint | null { + if (!v || typeof v !== 'object') return null; + const r = v as Record; + const node = str(r.node); + const point = vec(r.point); + return node && point ? { node, point } : null; +} + +export const NEEDED: Record = { distance: 2, angle: 3, size: 1 }; \ No newline at end of file diff --git a/frontend/src/ui/measure/panel.ts b/frontend/src/ui/measure/panel.ts new file mode 100644 index 00000000..bf182794 --- /dev/null +++ b/frontend/src/ui/measure/panel.ts @@ -0,0 +1,146 @@ +import { el, patchList, q, setAttr, setChecked, setClass, setDisabled, setHidden, setText, setTitle, setValue } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { measureIcon } from './icons'; +import type { MeasureItem, MeasureList } from './model'; + +export interface PanelHooks { + rename(id: string, name: string): void; + show(id: string, visible: boolean): void; + remove(id: string): void; + clear(): void; + precision(digits: number): void; + highlight(id: string | null): void; + close(): void; + ownAxes(on: boolean): void; +} + +const KIND_LABEL: Record = { distance: 'Distance', size: 'Size Box', angle: 'Angle' }; +const DIGITS = [0, 1, 2, 3, 4]; + +export class MeasurePanel { + readonly root: HTMLElement; + private readonly list: HTMLElement; + private readonly empty: HTMLElement; + private readonly count: HTMLElement; + private readonly digits: HTMLSelectElement; + private readonly own: HTMLInputElement; + private readonly clearBtn: HTMLButtonElement; + private renaming: string | null = null; + + constructor(host: HTMLElement, private readonly hooks: PanelHooks) { + this.root = el(``); + host.appendChild(this.root); + this.list = q(this.root, '.fsh-ms-list'); + this.empty = q(this.root, '.fsh-ms-empty'); + this.count = q(this.root, '.fsh-ms-count'); + this.digits = q(this.root, '.fsh-ms-digits'); + this.own = q(this.root, '.fsh-ms-own'); + this.clearBtn = q(this.root, '.fsh-ms-clear'); + q(this.root, '.fsh-ms-close').addEventListener('click', () => hooks.close()); + this.digits.addEventListener('change', () => hooks.precision(Number(this.digits.value))); + this.own.addEventListener('change', () => hooks.ownAxes(this.own.checked)); + this.clearBtn.addEventListener('click', () => hooks.clear()); + this.list.addEventListener('pointerleave', () => hooks.highlight(null)); + } + + get open(): boolean { return !this.root.hidden; } + + setOpen(open: boolean): void { setHidden(this.root, !open); } + + update(data: MeasureList | null, editable: boolean): void { + const items = data?.items ?? []; + setText(this.count, items.length ? String(items.length) : ''); + setHidden(this.empty, items.length > 0); + setDisabled(this.digits, !editable || !data); + setDisabled(this.clearBtn, !editable || items.length === 0); + if (data) setValue(this.digits, String(Math.min(4, data.precision))); + patchList(this.list, items, { + key: (it) => it.id, + create: (it) => { const node = this.row(it); this.paintRow(node, it, editable); return node; }, + update: (node, it) => this.paintRow(node, it, editable), + }); + } + + setOwnAxes(on: boolean): void { setChecked(this.own, on); } + + private row(it: MeasureItem): HTMLElement { + const node = el(`
      + + + + + + +
      `); + const id = it.id; + const name = q(node, '.fsh-ms-name'); + const input = q(node, '.fsh-ms-rename'); + const finish = (commit: boolean): void => { + if (this.renaming !== id) return; + this.renaming = null; + const next = input.value.trim(); + setHidden(input, true); + setHidden(name, false); + if (commit && next && next !== name.textContent) this.hooks.rename(id, next); + }; + name.addEventListener('dblclick', () => { + if (node.classList.contains('is-locked')) return; + this.renaming = id; + input.value = name.textContent ?? ''; + setHidden(name, true); + setHidden(input, false); + input.focus(); + input.select(); + }); + input.addEventListener('keydown', (e) => { + e.stopPropagation(); + if (e.key === 'Enter') finish(true); + else if (e.key === 'Escape') finish(false); + }); + input.addEventListener('blur', () => finish(true)); + q(node, '.fsh-ms-eye').addEventListener('click', () => this.hooks.show(id, node.classList.contains('is-hidden'))); + q(node, '.fsh-ms-remove').addEventListener('click', () => this.hooks.remove(id)); + node.addEventListener('pointerenter', () => this.hooks.highlight(id)); + return node; + } + + private paintRow(node: HTMLElement, it: MeasureItem, editable: boolean): void { + const kind = q(node, '.fsh-ms-kind'); + if (kind.dataset.kind !== it.kind) { + kind.dataset.kind = it.kind; + kind.innerHTML = measureIcon(it.kind, 14); + } + setTitle(kind, t(KIND_LABEL[it.kind])); + if (this.renaming !== it.id) setText(q(node, '.fsh-ms-name'), it.name); + const broken = !it.ok; + setText(q(node, '.fsh-ms-value'), broken ? t('Part removed') : it.text); + setClass(node, 'is-broken', broken); + setClass(node, 'is-hidden', !it.visible); + setClass(node, 'is-locked', !editable); + setTitle(node, broken && it.missing.length ? t('Missing nodes: {ids}', { ids: it.missing.join(', ') }) : ''); + const eye = q(node, '.fsh-ms-eye'); + const eyeName = it.visible ? 'eye' : 'eyeOff'; + if (eye.dataset.icon !== eyeName) { eye.dataset.icon = eyeName; eye.innerHTML = icon(eyeName, 14); } + const eyeLabel = it.visible ? t('Hide Measurement') : t('Show Measurement'); + setTitle(eye, eyeLabel); + setAttr(eye, 'aria-label', eyeLabel); + setDisabled(eye, !editable); + setDisabled(q(node, '.fsh-ms-remove'), !editable); + } +} \ No newline at end of file diff --git a/frontend/src/ui/movie/anim.ts b/frontend/src/ui/movie/anim.ts new file mode 100644 index 00000000..f2db1c74 --- /dev/null +++ b/frontend/src/ui/movie/anim.ts @@ -0,0 +1,64 @@ +import { api } from '../../shell/api'; +import { events } from '../../shell/events'; +import { CHANGE_EVENTS, errorText } from '../render/store'; + +export interface Timeline { fps: number; frames: number; start: number; end: number; moves: boolean; rigs: number; tracks: number } + +const obj = (v: unknown): Record => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record : {}); +const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d); + +export const resultOf = (v: unknown): Record => { + const o = obj(v); + return 'result' in o && o.result && typeof o.result === 'object' ? obj(o.result) : o; +}; + +class TimelineStore { + value: Timeline | null = null; + error = ''; + private readonly fns = new Set<() => void>(); + private users = 0; + private wired = false; + private timer = 0; + private seq = 0; + + onChange(fn: () => void): () => void { this.fns.add(fn); return () => { this.fns.delete(fn); }; } + private changed(): void { for (const fn of this.fns) fn(); } + + use(on: boolean): void { + this.users = Math.max(0, this.users + (on ? 1 : -1)); + if (!this.wired) { + this.wired = true; + for (const type of [...CHANGE_EVENTS, 'ui.dispatched']) events.on(type, () => { if (this.users > 0) this.schedule(200); }); + } + if (on) this.schedule(0); + } + + schedule(delay: number): void { + window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => void this.read(), delay); + } + + async read(): Promise { + const seq = ++this.seq; + try { + const s = resultOf(await api.dispatch('anim.status', {}, { timeoutMs: 15000 })); + if (seq !== this.seq) return; + this.value = { + fps: num(s.fps, 30), + frames: Math.max(1, Math.round(num(s.frames, 1))), + start: num(s.start, 0), + end: num(s.end, 0), + moves: s.moves === true, + rigs: num(s.rig_count, Array.isArray(s.rigs) ? s.rigs.length : num(s.rigs, 0)), + tracks: Array.isArray(s.tracks) ? s.tracks.length : 0, + }; + this.error = ''; + } catch (err) { + if (seq !== this.seq) return; + this.error = errorText(err); + } + this.changed(); + } +} + +export const timeline = new TimelineStore(); diff --git a/frontend/src/ui/movie/dialog.ts b/frontend/src/ui/movie/dialog.ts new file mode 100644 index 00000000..1b0cbdc6 --- /dev/null +++ b/frontend/src/ui/movie/dialog.ts @@ -0,0 +1,378 @@ +import { el, q,setAttr, setClass, setDisabled, setHidden, setText, setTitle, setValue } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { mountDenoise } from '../render/denoise'; +import { Check, NumberField, Segmented, nextId, section } from '../render/fields'; +import { nameProblem, output, previewName } from '../render/output'; +import { mountPasses } from '../render/passes'; +import { rendersFolder, store } from '../render/store'; +import { timeline } from './anim'; +import { ffmpeg } from './ffmpeg'; +import { mountFfmpeg } from './ffmpeg-view'; +import { + DEFAULT_FRAME_NAME, FRAME_TOKEN, MOVIE_FORMATS, SEQ_FORMATS, extensionOf, movie, movieFrames, planOf, + type FrameMode, type MovieFormat, type SeqFormat, +} from './settings'; + +export interface DialogHooks { + openFolder: (folder: string) => void; + submit: () => Promise; + active: (open: boolean) => void; +} + +const absolute = (p: string): boolean => p.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(p) || p.startsWith('\\\\'); +const join = (dir: string, name: string): string => dir + (dir.includes('\\') && !dir.includes('/') ? '\\' : '/') + name; + +export function frameFolder(): string { return movie.value.folder.trim() || output.value.folder.trim() || rendersFolder(store.path); } + +export function cameraName(): string { + const c = movie.value.camera; + const hit = /^\d+$/.test(c) ? store.cameras.find((x) => String(x.index) === c) : store.cameras.find((x) => x.active); + return hit?.name ?? 'Camera'; +} + +export function movieFileName(): string { + const v = movie.value; + const base = v.movieName.trim() || `${store.title || 'Untitled'}_${cameraName()}`; + return `${base.replace(/[^\p{L}\p{N} \-_.()]/gu, '_')}.${v.movieFormat}`; +} + +const PLAN: Record = { + none: ['One frame at {width} × {height}, {samples} samples, as a {format} file', '{n} frames at {width} × {height}, {samples} samples, as {format} files'], + mp4: ['One frame at {width} × {height}, then an MP4', '{n} frames at {width} × {height}, then an MP4'], + webm: ['One frame at {width} × {height}, then a WebM', '{n} frames at {width} × {height}, then a WebM'], + mov: ['One frame at {width} × {height}, then a ProRes MOV', '{n} frames at {width} × {height}, then a ProRes MOV'], + gif: ['One frame at {width} × {height}, then a GIF', '{n} frames at {width} × {height}, then a GIF'], +}; + +export class AnimationDialog { + readonly scrim: HTMLElement; + private readonly body: HTMLElement; + private readonly status: HTMLElement; + private readonly detail: HTMLElement; + private readonly go: HTMLButtonElement; + private before: Element | null = null; + private sending = false; + private said = ''; + private saidError = false; + private readonly paints: Array<() => void> = []; + + constructor(private readonly hooks: DialogHooks) { + this.scrim = el(``); + this.body = q(this.scrim, '.fsh-movie-body'); + this.status = q(this.scrim, '.fsh-movie-plan-main'); + this.detail = q(this.scrim, '.fsh-movie-plan-more'); + this.go = q(this.scrim, '.fsh-movie-go'); + q(this.scrim, '.fsh-dialog-x').addEventListener('click', () => this.close()); + q(this.scrim, '.fsh-movie-cancel').addEventListener('click', () => this.close()); + this.go.addEventListener('click', () => void this.send()); + this.scrim.addEventListener('pointerdown', (e) => { if (e.target === this.scrim) this.close(); }); + this.scrim.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && !e.defaultPrevented) { e.stopPropagation(); this.close(); } + }); + this.mountFrames(); + this.mountSize(); + mountPasses(this.body); + mountDenoise(this.body); + this.mountSequence(); + this.mountMovie(); + this.mountNames(); + (document.getElementById('overlay-root') ?? document.body).appendChild(this.scrim); + const paint = (): void => this.paint(); + store.onChange(paint); + output.onChange(paint); + movie.onChange(paint); + timeline.onChange(paint); + ffmpeg.onChange(paint); + this.paint(); + } + + get isOpen(): boolean { return !this.scrim.hidden; } + + open(): void { + if (this.isOpen) return; + this.before = document.activeElement; + this.said = ''; + setHidden(this.scrim, false); + this.hooks.active(true); + timeline.use(true); + void ffmpeg.refresh(); + this.paint(); + q(this.scrim, '.fsh-dialog-x').focus(); + } + + close(): void { + if (!this.isOpen) return; + setHidden(this.scrim, true); + this.hooks.active(false); + timeline.use(false); + if (this.before instanceof HTMLElement && this.before.isConnected) this.before.focus(); + this.before = null; + } + + toggle(): void { if (this.isOpen) this.close(); else this.open(); } + + private mountFrames(): void { + const sec = section('Frames', 'fsh-movie-frames'); + const mode = new Segmented('Frames to render', [['all', 'Every frame'], ['range', 'A range']], (v) => movie.set({ frames: v })); + const first = new NumberField({ label: 'First frame', min: 1, max: 1e6, step: 1, integer: true, commit: (v) => movie.set({ first: v, last: Math.max(v, movie.value.last) }) }); + const last = new NumberField({ label: 'Last frame', min: 1, max: 1e6, step: 1, integer: true, commit: (v) => movie.set({ last: v, first: Math.min(v, movie.value.first) }) }); + const step = new NumberField({ label: 'Frame step', min: 1, max: 1000, step: 1, integer: true, commit: (v) => movie.set({ step: v }) }); + const pair = el('
      '); + pair.append(first.el, last.el); + const line = el('

      '); + const warn = el('

      '); + sec.append(mode.el, pair, step.el, line, warn); + this.body.appendChild(sec); + this.paints.push(() => { + const v = movie.value; + const tl = timeline.value; + const total = tl?.frames ?? 1; + const plan = planOf(v, total); + const can = store.has('anim.render'); + mode.set(v.frames); + mode.disable(!can); + first.set(v.frames === 'range' ? plan.first : 1); + last.set(v.frames === 'range' ? plan.last : total); + first.disable(!can || v.frames !== 'range'); + last.disable(!can || v.frames !== 'range'); + step.set(v.step); + step.disable(!can); + let text = ''; + if (timeline.error) text = timeline.error; + else if (tl) { + text = t('{count} of {total} frames: {first} to {last}, every {step}. The animation runs {seconds} s at {fps} fps.', { + count: plan.count, total, first: plan.first, last: plan.last, step: plan.step, seconds: Number(((tl.frames - 1) / Math.max(tl.fps, 1e-6)).toFixed(2)), fps: Number(tl.fps.toFixed(3)), + }); + } + setText(line, text); + let w = ''; + if (!can && store.loaded) w = t('This engine cannot render animations.'); + else if (tl && !tl.moves) w = t('Nothing moves in this animation yet, so every frame looks the same. Add a turntable or keys first.'); + setText(warn, w); + }); + } + + private mountSize(): void { + const sec = section('Output size and samples', 'fsh-movie-size'); + const width = new NumberField({ label: 'Width', min: 1, max: 16384, step: 1, integer: true, unit: 'px', commit: (v) => void store.set({ width: v }) }); + const height = new NumberField({ label: 'Height', min: 1, max: 16384, step: 1, integer: true, unit: 'px', commit: (v) => void store.set({ height: v }) }); + const samples = new NumberField({ label: 'Samples', min: 1, max: 1048576, step: 16, integer: true, commit: (v) => void store.set({ samples: v }) }); + const grid = el('
      '); + grid.append(width.el, height.el, samples.el); + const id = nextId('cam'); + const camRow = el(`
      `); + const cam = q(camRow, 'select'); + cam.addEventListener('change', () => movie.set({ camera: cam.value })); + const note = el('

      These are the document\'s render settings, shared with Final Render.

      '); + sec.append(grid, camRow, note); + this.body.appendChild(sec); + let camKey = ''; + this.paints.push(() => { + const v = store.values; + width.set(v.width); + height.set(v.height); + samples.set(v.samples); + const off = !store.has('render.set_settings'); + width.disable(off); height.disable(off); samples.disable(off); + const key = store.cameras.map((c) => `${c.index}:${c.name}`).join('|'); + if (key !== camKey) { + camKey = key; + for (const o of [...cam.options]) if (o.value !== 'active') o.remove(); + for (const c of store.cameras) { + const o = document.createElement('option'); + o.value = String(c.index); + o.textContent = c.name; + o.setAttribute('data-no-i18n', ''); + cam.appendChild(o); + } + } + const want = [...cam.options].some((o) => o.value === movie.value.camera) ? movie.value.camera : 'active'; + if (cam.value !== want) cam.value = want; + }); + } + + private mountSequence(): void { + const sec = section('Image sequence', 'fsh-movie-seq'); + const format = new Segmented('Frame format', SEQ_FORMATS.map(([f, label]) => [f, label, true] as const), (v) => movie.set({ format: v })); + const transparent = new Check('Transparent background', (on) => movie.set({ transparent: on })); + const note = el('

      '); + sec.append(format.el, transparent.el, note); + this.body.appendChild(sec); + this.paints.push(() => { + const v = movie.value; + format.set(v.format); + transparent.set(v.transparent && v.format !== 'jpeg'); + transparent.disable(v.format === 'jpeg'); + let text: string; + if (v.movie && !movieFrames(v.format)) text = t('A movie is made from PNG or JPEG frames; with this format only the frames are written.'); + else text = t('Bit depth, quality and compression follow the image file settings in Final Render.'); + setText(note, text); + }); + } + + private mountMovie(): void { + const sec = section('Movie', 'fsh-movie-movie'); + const on = new Check('Encode a movie after the last frame', (v) => movie.set({ movie: v })); + const format = new Segmented('Movie format', MOVIE_FORMATS.map(([f, label]) => [f, label, true] as const), (v) => movie.set({ movieFormat: v })); + const own = new Check('Use the animation\'s frame rate', (v) => movie.set({ ownRate: v })); + const fps = new NumberField({ label: 'Frame rate', min: 0.01, max: 240, step: 1, digits: 3, unit: 'fps', commit: (v) => movie.set({ fps: v }) }); + const quality = new NumberField({ label: 'Movie quality', min: 1, max: 100, step: 5, integer: true, commit: (v) => movie.set({ quality: v }) }); + const keep = new Check('Keep the frame files after the movie is written', (v) => movie.set({ keepFrames: v })); + const rate = el('
      '); + rate.append(fps.el, quality.el); + const ownRow = el('
      '); + ownRow.appendChild(own.el); + const encoder = el('

      '); + const warn = el('

      '); + const block = el('
      '); + block.append(format.el, rate, ownRow, keep.el, encoder, warn); + sec.append(on.el, block); + this.body.appendChild(sec); + mountFfmpeg(sec); + this.paints.push(() => { + const v = movie.value; + const usable = movieFrames(v.format); + const tl = timeline.value; + const off = !v.movie || !usable; + on.set(v.movie && usable); + on.disable(!usable); + format.set(v.movieFormat); + format.disable(off); + own.set(v.ownRate); + own.disable(off); + fps.set(v.ownRate && tl ? Number((tl.fps / Math.max(1, movie.value.step)).toFixed(3)) : v.fps); + fps.disable(off || v.ownRate); + quality.set(v.quality); + quality.disable(off); + keep.set(v.keepFrames); + keep.disable(off); + setAttr(sec, 'data-off', off ? 'true' : null); + const plan = ffmpeg.engine?.formats[v.movieFormat]; + let enc = ''; + if (!off && ffmpeg.found && plan) { + enc = plan.hardware + ? t('{codec} through the {encoder} hardware encoder', { codec: plan.codec, encoder: plan.encoder }) + : t('{codec} through {encoder}', { codec: plan.codec, encoder: plan.encoder }); + if (v.movieFormat === 'mov' && v.transparent) enc = t('ProRes 4444 with alpha through {encoder}', { encoder: plan.encoder }); + } + setText(encoder, enc); + let w = ''; + if (!off && ffmpeg.found && v.movieFormat === 'mp4' && plan?.encoder === 'mpeg4') { + w = t('This ffmpeg has no H.264 encoder, so the MP4 will be MPEG-4 Part 2: it plays almost everywhere but is larger at the same quality. WebM or MOV keep a better picture.'); + } else if (!off && v.movieFormat === 'gif') { + w = t('A GIF holds at most 256 colours and frame times in hundredths of a second, so its rate is rounded.'); + } else if (!off && v.transparent && (v.movieFormat === 'mp4' || v.movieFormat === 'webm')) { + w = t('{format} has no transparency: the movie shows the background colour. MOV (ProRes 4444) keeps it.', { format: v.movieFormat === 'mp4' ? 'MP4' : 'WebM' }); + } + setText(warn, w); + }); + } + + private mountNames(): void { + const sec = section('File names and folder', 'fsh-movie-names'); + const nameId = nextId('name'), movieId = nextId('movie'), folderId = nextId('folder'); + const row = el(`
      `); + const name = q(row, 'input'); + const preview = el('

      '); + const under = el('
      '); + under.appendChild(preview); + const movieRow = el(`
      `); + const movieName = q(movieRow, 'input'); + const folderRow = el(`
      `); + const folder = q(folderRow, 'input'); + const open = q(folderRow, '.fsh-movie-open'); + name.addEventListener('input', () => movie.set({ name: name.value })); + movieName.addEventListener('input', () => movie.set({ movieName: movieName.value })); + folder.addEventListener('change', () => movie.set({ folder: folder.value.trim() })); + open.addEventListener('click', () => this.hooks.openFolder(frameFolder())); + sec.append(row, under, movieRow, folderRow); + this.body.appendChild(sec); + this.paints.push(() => { + const v = movie.value; + setValue(name, v.name); + name.placeholder = DEFAULT_FRAME_NAME; + setValue(movieName, v.movieName); + movieName.placeholder = `${store.title || 'Untitled'}_${cameraName()}`; + setDisabled(movieName, !movie.usesMovie()); + setValue(folder, v.folder); + folder.placeholder = output.value.folder.trim() || rendersFolder(store.path) || t('The project folder'); + const problem = this.nameProblem(); + const vars = { project: store.title || 'Untitled', camera: cameraName(), width: store.values.width, height: store.values.height, samples: store.values.samples }; + setText(preview, problem || `${previewName(v.name || DEFAULT_FRAME_NAME, vars)}.${extensionOf(v.format)}`); + setClass(preview, 'is-error', problem !== ''); + setAttr(name, 'aria-invalid', problem ? 'true' : null); + setDisabled(open, frameFolder() === ''); + }); + } + + private nameProblem(): string { + const v = movie.value; + const n = v.name.trim() || DEFAULT_FRAME_NAME; + const p = nameProblem(n); + if (p) return p; + if (!n.includes(FRAME_TOKEN)) return t('The file name needs {token} so that each frame gets a file of its own.', { token: FRAME_TOKEN }); + if (/[\\/]/.test(v.movieName) || v.movieName.includes('..')) return t('A file name cannot hold a slash or two dots in a row.'); + return ''; + } + + problem(): string { + if (!store.loaded) return store.error || t('Reading...'); + if (!store.has('anim.render')) return t('This engine cannot render animations.'); + if (timeline.error) return timeline.error; + const f = frameFolder(); + if (!f) return t('Choose an output folder first: this project has not been saved, so it has no folder of its own.'); + if (!absolute(f)) return t('The output folder must be a full path, such as {example}.', { example: '/Users/me/Renders' }); + const n = this.nameProblem(); + if (n) return n; + if (movie.usesMovie() && ffmpeg.read && !ffmpeg.found) return t('ffmpeg was not found, so no movie can be made. Download it in the Movie section, or turn the movie off to render the frames alone.'); + return ''; + } + + planText(): string { + const v = movie.value; + const plan = planOf(v, timeline.value?.frames ?? 1); + const s = store.values; + const which = movie.usesMovie() ? v.movieFormat : 'none'; + const fmt = SEQ_FORMATS.find(([f]) => f === v.format)?.[1] ?? v.format; + return t(PLAN[which][plan.count === 1 ? 0 : 1], { n: plan.count, width: s.width, height: s.height, samples: s.samples, format: fmt }); + } + + private paint(): void { + for (const p of this.paints) p(); + const why = this.problem(); + const main = this.said || why || this.planText(); + setText(this.status, main); + setTitle(this.status, main); + setClass(this.status, 'is-error', this.saidError || (!this.said && why !== '')); + let more = ''; + if (!why && !this.said) { + const f = frameFolder(); + more = movie.usesMovie() + ? t('Into {folder}; the movie is {movie}.', { folder: f, movie: join(f, movieFileName()) }) + : t('Into {folder}.', { folder: f }); + } + setText(this.detail, more); + setTitle(this.detail, more); + setDisabled(this.go, this.sending || why !== ''); + setAttr(this.go, 'aria-busy', this.sending ? 'true' : null); + } + + private async send(): Promise { + if (this.sending || this.problem()) return; + this.sending = true; + this.said = ''; + this.paint(); + const said = await this.hooks.submit(); + this.sending = false; + if (said) { this.said = said; this.saidError = true; this.paint(); window.setTimeout(() => { this.said = ''; this.saidError = false; this.paint(); }, 8000); return; } + this.close(); + this.paint(); + } +} diff --git a/frontend/src/ui/movie/ffmpeg-view.ts b/frontend/src/ui/movie/ffmpeg-view.ts new file mode 100644 index 00000000..8cb94b0b --- /dev/null +++ b/frontend/src/ui/movie/ffmpeg-view.ts @@ -0,0 +1,73 @@ +import { el, q, setAttr, setClass, setDisabled, setStyleVar, setText, setTitle } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { bytesText, stageText } from '../render/oidn'; +import { ffmpeg } from './ffmpeg'; + +const SOURCES: Record = { + env: 'set by FORMSHOT_FFMPEG', + FORMSHOT_FFMPEG: 'set by FORMSHOT_FFMPEG', + family: 'the Form family\'s shared install', + PATH: 'found on the PATH', +}; + +export function mountFfmpeg(host: HTMLElement): () => void { + const box = el(`
      +
      +
      + + +
      +

      +

      +

      +
      +
      `); + const getBtn = q(box, '.fsh-movie-ff-get'); + const refreshBtn = q(box, '.fsh-movie-ff-refresh'); + const progress = q(box, '.fsh-render-progress'); + getBtn.addEventListener('click', () => void ffmpeg.start()); + refreshBtn.addEventListener('click', () => void ffmpeg.refresh()); + host.appendChild(box); + + const paint = (): void => { + const e = ffmpeg.engine, p = ffmpeg.published, job = ffmpeg.fetch; + const running = job.state === 'running'; + let text: string, state: string; + if (!ffmpeg.read) { text = t('Reading...'); state = 'unknown'; } + else if (ffmpeg.error) { text = t('Unknown'); state = 'unknown'; } + else if (e?.found) { text = t('ffmpeg {version} is ready for movies.', { version: e.version || e.release || '' }); state = 'ok'; } + else { text = t('ffmpeg was not found on this computer.'); state = 'off'; } + setText(q(box, '.fsh-movie-ff-text'), text); + setAttr(q(box, '.fsh-render-dot'), 'data-state', state); + setClass(box, 'is-found', e?.found === true); + + let where = ''; + if (ffmpeg.error) where = t('The status could not be read: {reason}', { reason: ffmpeg.error }); + else if (e?.found) where = `${e.path} (${t(SOURCES[e.source] ?? e.source)})`; + else if (job.state === 'failed') where = t('The download failed: {reason}', { reason: job.message || t('no reason was given') }); + else if (e && !e.found) where = p?.available === false ? p.reason : t('About {size} to download once, into the folder every Form app shares. Nothing is downloaded until you ask.', { size: bytesText(p?.bytes) || '?' }); + setText(q(box, '.fsh-movie-ff-where'), where); + setTitle(q(box, '.fsh-movie-ff-where'), where); + + const enc = e?.found ? t('Encoders: {list}', { list: e.encoders.join(', ') || t('none') }) : ''; + setText(q(box, '.fsh-movie-ff-enc'), enc); + + let licence = ''; + if (e?.found && e.gpl) licence = t('This ffmpeg is a GPL build that you installed; FormShot only runs it as a separate program.'); + else if (e?.found && e.source === 'family') licence = t('The Form family\'s ffmpeg is LGPL-2.1-or-later, a separate program FormShot runs and never links; its source is published with the release.'); + else if (e && !e.found) licence = t('The Form family\'s ffmpeg {version} is LGPL-2.1-or-later and has no libx264: MP4 uses a hardware H.264 encoder or MPEG-4 Part 2. It stays a separate program that FormShot runs, never part of FormShot, and its source ({url}) is published with the release.', { version: p?.ffmpeg || '', url: p?.sourceUrl || '' }); + setText(q(box, '.fsh-movie-ff-licence'), licence); + setTitle(q(box, '.fsh-movie-ff-licence'), licence); + + setDisabled(getBtn, running || !ffmpeg.read || e?.found !== false || p?.available === false); + setAttr(getBtn, 'aria-busy', running ? 'true' : null); + setDisabled(refreshBtn, running); + setClass(progress, 'is-on', running); + setText(q(progress, '.fsh-render-stage'), running ? stageText(job.stage) : ''); + setStyleVar(progress, '--fsh-render-fraction', String(running ? job.fraction : 0)); + setText(q(progress, '.fsh-render-pct'), running ? `${Math.round(job.fraction * 100)}%` : ''); + }; + paint(); + return ffmpeg.onChange(paint); +} diff --git a/frontend/src/ui/movie/ffmpeg.ts b/frontend/src/ui/movie/ffmpeg.ts new file mode 100644 index 00000000..28dd21ed --- /dev/null +++ b/frontend/src/ui/movie/ffmpeg.ts @@ -0,0 +1,147 @@ +import { api } from '../../shell/api'; +import { events, type EngineEvent } from '../../shell/events'; +import { errorText } from '../render/store'; +import type { MovieFormat } from './settings'; + +export const FFMPEG_ROUTE = '/api/video/ffmpeg'; +export const FFMPEG_FETCH_ROUTE = '/api/video/ffmpeg/fetch'; +export const FFMPEG_EVENT = 'video.ffmpeg'; + +export interface FormatPlan { codec: string; encoder: string; fallbacks: string[]; hardware: boolean } + +export interface FfmpegEngine { + found: boolean; + path: string; + version: string; + source: string; + release: string; + gpl: boolean; + licence: string; + reason: string; + notes: string[]; + encoders: string[]; + formats: Partial>; + familyLicence: string; + familySource: string; +} + +export interface FfmpegPublished { release: string; ffmpeg: string; licence: string; available: boolean; reason: string; bytes: number; sourceUrl: string } +export interface FfmpegFetch { state: 'idle' | 'running' | 'done' | 'failed'; stage: string; fraction: number; message: string } + +const obj = (v: unknown): Record => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record : {}); +const str = (v: unknown): string => (typeof v === 'string' ? v : ''); + +function fetchOf(v: unknown): FfmpegFetch { + const o = obj(v); + const state = o.state === 'running' || o.state === 'done' || o.state === 'failed' ? o.state : 'idle'; + const fraction = typeof o.fraction === 'number' && Number.isFinite(o.fraction) ? Math.min(1, Math.max(0, o.fraction)) : 0; + return { state, stage: str(o.stage), fraction, message: str(o.message) }; +} + +function engineOf(v: unknown): FfmpegEngine { + const e = obj(v); + const enc = obj(e.encoders); + const fam = obj(e.family); + const formats: Partial> = {}; + for (const [k, p] of Object.entries(obj(e.formats))) { + const o = obj(p); + if (k === 'mp4' || k === 'webm' || k === 'mov' || k === 'gif') { + formats[k] = { codec: str(o.codec), encoder: str(o.encoder), fallbacks: Array.isArray(o.fallbacks) ? o.fallbacks.map(String) : [], hardware: o.hardware === true }; + } + } + return { + found: e.found === true, + path: str(e.path), + version: str(e.version), + source: str(e.source), + release: str(e.release), + gpl: e.gpl === true, + licence: str(e.licence), + reason: str(e.reason) || str(e.advice), + notes: Array.isArray(e.notes) ? e.notes.map(String) : [], + encoders: Object.entries(enc).filter(([, on]) => on === true).map(([k]) => k).sort(), + formats, + familyLicence: str(fam.licence), + familySource: str(fam.source), + }; +} + +class FfmpegStore { + engine: FfmpegEngine | null = null; + published: FfmpegPublished | null = null; + fetch: FfmpegFetch = { state: 'idle', stage: '', fraction: 0, message: '' }; + error = ''; + read = false; + private loading: Promise | null = null; + private readonly fns = new Set<() => void>(); + private wired = false; + private poll = 0; + + onChange(fn: () => void): () => void { + this.fns.add(fn); + if (!this.wired) { + this.wired = true; + events.on(FFMPEG_EVENT, (e) => this.take(e)); + } + return () => { this.fns.delete(fn); }; + } + + private changed(): void { for (const fn of this.fns) fn(); } + + get running(): boolean { return this.fetch.state === 'running'; } + get found(): boolean { return this.engine?.found === true; } + + refresh(): Promise { + if (this.loading) return this.loading; + this.loading = api.get(FFMPEG_ROUTE, { timeoutMs: 30000 }).then((s) => { + const o = obj(s); + this.engine = engineOf(o.engine); + const p = obj(o.published); + this.published = { + release: str(p.release), ffmpeg: str(p.ffmpeg), licence: str(p.licence), available: p.available !== false, reason: str(p.reason), + bytes: typeof p.bytes === 'number' ? p.bytes : 0, sourceUrl: str(obj(p.source).url), + }; + const job = fetchOf(o.fetch); + if (!(this.running && job.state === 'idle')) this.fetch = job; + this.error = ''; + this.read = true; + }).catch((err: unknown) => { + this.error = errorText(err); + this.read = true; + }).finally(() => { + this.loading = null; + this.follow(); + this.changed(); + }); + return this.loading; + } + + private follow(): void { + window.clearTimeout(this.poll); + if (this.running) this.poll = window.setTimeout(() => void this.refresh(), 1500); + } + + private take(e: EngineEvent): void { + const before = this.fetch.state; + this.fetch = fetchOf(e); + this.changed(); + if (before === 'running' && this.fetch.state !== 'running') void this.refresh(); + } + + async start(): Promise { + if (this.running) return; + this.fetch = { state: 'running', stage: 'record', fraction: 0, message: '' }; + this.changed(); + try { + const reply = obj(await api.post(FFMPEG_FETCH_ROUTE, {}, { timeoutMs: 60000 })); + const job = fetchOf(reply.fetch); + if (job.state !== 'idle' && this.fetch.stage === 'record' && this.fetch.fraction === 0) this.fetch = job; + } catch (err) { + this.fetch = { state: 'failed', stage: '', fraction: 0, message: errorText(err) }; + } + this.follow(); + this.changed(); + } +} + +export const ffmpeg = new FfmpegStore(); diff --git a/frontend/src/ui/movie/index.ts b/frontend/src/ui/movie/index.ts new file mode 100644 index 00000000..fd5d466b --- /dev/null +++ b/frontend/src/ui/movie/index.ts @@ -0,0 +1,98 @@ +import { api } from '../../shell/api'; +import { callCommand, registry } from '../../shell/registry'; +import { toast } from '../../shell/toast'; +import { t } from '../../i18n'; +import { jobs } from '../render/jobs'; +import { mountMotion } from '../render/motion'; +import { output } from '../render/output'; +import { errorText, store } from '../render/store'; +import type { RenderWindow } from '../render/window'; +import { resultOf, timeline } from './anim'; +import { AnimationDialog, cameraName, frameFolder, movieFileName } from './dialog'; +import { rememberSequence } from './rows'; +import { DEFAULT_FRAME_NAME, frameOptions, movie, planOf } from './settings'; +import './movie.css'; + +const DIALOG = 'render.animation'; +const MOTION = 'render.motionBlur'; + +const clockNow = (): string => { + const d = new Date(); + return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; +}; + +function jobArgs(): Record { + const v = movie.value; + const plan = planOf(v, timeline.value?.frames ?? 1); + const camera = /^\d+$/.test(v.camera) ? Number(v.camera) : 'active'; + const args: Record = { + folder: frameFolder(), + name: v.name.trim() || DEFAULT_FRAME_NAME, + format: v.format, + ...frameOptions(v.format), + transparent: v.format === 'jpeg' ? false : v.transparent, + overwrite: output.value.overwrite, + camera, + step: plan.step, + label: `${store.title || t('Untitled')}, ${cameraName()} ${clockNow()}`, + }; + if (v.frames === 'range') args.frames = [plan.first, plan.last]; + if (movie.usesMovie()) { + const video: Record = { format: v.movieFormat, quality: v.quality, keep_frames: v.keepFrames, name: movieFileName().replace(/\.[a-z0-9]+$/, '') }; + if (!v.ownRate) video.fps = v.fps; + args.video = video; + } + return args; +} + +export function mountMovie(win: RenderWindow): void { + const motion = mountMotion(win.settings); + let dialogOpen = false; + const sync = (): void => { store.setActive(win.isOpen || dialogOpen); motion.setActive(win.isOpen); }; + win.onOpen(() => sync()); + + const openFolder = (f: string): void => { + void jobs.openFolder(f).catch((err: unknown) => toast(t('Could not open the folder: {reason}', { reason: errorText(err) }), 'error')); + }; + + let dialog: AnimationDialog | null = null; + const submit = async (): Promise => { + try { + const source = { kind: 'animation', label: t('Animation'), command: 'anim.render', args: jobArgs() }; + const queued = await callCommand('render.source', { source, open: false }); + if (!queued.ran) throw new Error(t('Final Render is not available.')); + const reply = resultOf(queued.result); + const ids = Array.isArray(reply.ids) ? reply.ids.filter((x): x is number => typeof x === 'number') : []; + const m = reply.movie && typeof reply.movie === 'object' ? reply.movie as Record : null; + rememberSequence(ids, typeof m?.id === 'number' ? m.id : null); + if (jobs.list.paused) await api.dispatch('render.queue_pause', { paused: false }, { timeoutMs: 20000 }); + jobs.setVisible(true); + void jobs.read(); + win.open('queue'); + toast(m ? t('{n} frames and a movie added to the queue.', { n: ids.length }) : t('{n} frames added to the queue.', { n: ids.length }), 'info'); + return ''; + } catch (err) { + return t('Could not add the animation: {reason}', { reason: errorText(err) }); + } + }; + const theDialog = (): AnimationDialog => { + if (!dialog) dialog = new AnimationDialog({ openFolder, submit, active: (open) => { dialogOpen = open; sync(); } }); + return dialog; + }; + + registry.registerCommands([ + { + id: DIALOG, label: 'Render Animation...', group: 'Render', icon: 'render', + description: 'Render every frame of the animation, or a range, through the render queue, and encode a movie with ffmpeg.', + checked: () => dialog?.isOpen === true, + enabled: () => !store.loaded || store.has('anim.render'), + run: () => theDialog().toggle(), + }, + { + id: MOTION, label: 'Motion Blur', group: 'Render', icon: 'sliders', + description: 'Blur what moves while the shutter is open: on or off, shutter length and position, in Final Render.', + run: () => { win.open('settings'); motion.focus(); }, + }, + ]); + registry.registerMenu({ id: 'render', items: [{ command: DIALOG, section: 2 }, { command: MOTION, section: 2 }] }); +} diff --git a/frontend/src/ui/movie/movie.css b/frontend/src/ui/movie/movie.css new file mode 100644 index 00000000..3989063d --- /dev/null +++ b/frontend/src/ui/movie/movie.css @@ -0,0 +1,44 @@ +.fsh-movie-pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: var(--space-2) var(--space-4); } +.fsh-movie-pair .fsh-render-row { grid-template-columns: 14ch minmax(0, 1fr); } +.fsh-render-motion .fsh-render-line { min-height: calc(var(--fs-12) * var(--lh) * 2); white-space: normal; text-overflow: clip; } +.fsh-render-motion .fsh-render-line[data-error="true"] { color: var(--danger-text); } +.fsh-render-motion[data-off="true"] .fsh-movie-pair .fsh-render-label { color: var(--text-faint); } + +.fsh-movie-dlg { width: min(720px, calc(100vw - 48px)); height: min(760px, calc(100vh - 64px)); max-height: none; grid-template-rows: 44px minmax(0, 1fr) auto; color: var(--text-primary); font-size: var(--fs-12); } +.fsh-movie-body { min-height: 0; overflow-y: auto; overscroll-behavior: contain; scrollbar-gutter: stable; padding: var(--space-1) var(--space-4) var(--space-3); } +.fsh-movie-foot { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: var(--space-2); padding: var(--space-3) var(--space-4); border-top: 1px solid var(--line-1); } +.fsh-movie-foot .fsh-btn { height: 32px; min-width: 12ch; padding: 0 var(--space-4); border-radius: 9px; font-size: var(--fs-13); } +.fsh-movie-go { min-width: 20ch; } +.fsh-movie-plan { display: grid; grid-template-rows: auto auto; gap: 2px; min-width: 0; } +.fsh-movie-plan p { height: calc(var(--fs-12) * var(--lh)); margin: 0; overflow: hidden; line-height: var(--lh); text-overflow: ellipsis; white-space: nowrap; } +.fsh-movie-plan-main { color: var(--text-primary); font-weight: var(--fw-medium); } +.fsh-movie-plan-main.is-error { color: var(--danger-text); font-weight: var(--fw-regular); white-space: normal; height: auto; min-height: calc(var(--fs-12) * var(--lh)); max-height: calc(var(--fs-12) * var(--lh) * 2); } +.fsh-movie-plan-more { color: var(--text-muted); font-size: var(--fs-11); } +.fsh-movie-trio { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--space-2) var(--space-3); } +.fsh-movie-trio .fsh-render-row { grid-template-columns: auto minmax(0, 1fr); } +.fsh-movie-warn { height: calc(var(--fs-12) * var(--lh) * 2); margin: 0; overflow: hidden; color: var(--warn); font-size: var(--fs-12); line-height: var(--lh); } +.fsh-movie-wrap { height: calc(var(--fs-12) * var(--lh) * 2); white-space: normal; } +.fsh-movie-dlg .fsh-render-line { height: calc(var(--fs-12) * var(--lh)); font-size: var(--fs-12); line-height: var(--lh); } +.fsh-movie-dlg .fsh-render-line.fsh-movie-wrap { height: calc(var(--fs-12) * var(--lh) * 2); } +.fsh-movie-movie[data-off="true"] .fsh-movie-movie-fields .fsh-render-label { color: var(--text-faint); } +.fsh-movie-movie-fields { display: grid; gap: var(--space-2); } +.fsh-movie-movie-fields > .fsh-render-check { margin-left: calc(14ch + var(--space-2)); } + +.fsh-movie-ff { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: var(--space-1) var(--space-3); padding: var(--space-2) var(--space-3); border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-1); } +.fsh-movie-ff-state { display: flex; align-items: center; gap: var(--space-2); min-width: 0; height: var(--ctl-md); } +.fsh-movie-ff-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fsh-movie-ff-actions { display: flex; align-items: center; justify-content: flex-end; gap: var(--space-1); } +.fsh-movie-ff-get { min-width: 20ch; } +.fsh-movie-ff.is-found .fsh-movie-ff-get { visibility: hidden; } +.fsh-movie-ff p { grid-column: 1 / -1; margin: 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); line-height: var(--lh); } +.fsh-movie-ff-where, .fsh-movie-ff-enc { height: calc(var(--fs-11) * var(--lh)); text-overflow: ellipsis; white-space: nowrap; } +.fsh-movie-ff-licence { height: calc(var(--fs-11) * var(--lh) * 3); overflow-wrap: anywhere; } + +.fsh-movie-seq-row .fsh-render-job-actions { justify-content: flex-end; width: calc(var(--ctl-sm) * 5); } +.fsh-movie-seq-chev { display: inline-grid; transition: transform var(--dur-fast); } +.fsh-movie-seq-row.is-open .fsh-movie-seq-chev { transform: rotate(180deg); } +.fsh-render-job.is-in-seq { padding-left: var(--space-6); background: var(--surface-1); } +.fsh-render-job.is-in-seq .fsh-render-thumb { width: 54px; height: 36px; } +.fsh-movie-row .fsh-render-job-detail { display: none; } +.fsh-movie-detail { overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-movie-row[data-state="failed"] .fsh-movie-detail { color: var(--danger-text); } diff --git a/frontend/src/ui/movie/rows.ts b/frontend/src/ui/movie/rows.ts new file mode 100644 index 00000000..2387194b --- /dev/null +++ b/frontend/src/ui/movie/rows.ts @@ -0,0 +1,226 @@ +import { el, q, setAttr, setClass, setDisabled, setStyleVar, setText, setTitle, swapMedia } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { isActive, jobs, type Job } from '../render/jobs'; + +export interface Sequence { key: string; label: string; frames: Job[]; movie: Job | null; open: boolean } + +export type QueueRow = + | { kind: 'job'; key: string; job: Job; inSeq: boolean; movie: boolean } + | { kind: 'seq'; key: string; seq: Sequence }; + +const FRAME = /^(.*) frame (\d+)$/; +const MOVIE = /^(.*) movie$/; + +const known = new Map(); +const opened = new Set(); + +export function rememberSequence(frames: number[], movieId: number | null): void { + if (!frames.length) return; + const head = frames[0]; + for (const id of frames) known.set(id, head); + if (movieId !== null) known.set(movieId, head); +} + +export const isMovieJob = (j: Job): boolean => j.drew === 'ffmpeg' || (j.passes.length === 1 && j.passes[0] === 'movie'); + +function prefixOf(j: Job): string | null { + const m = FRAME.exec(j.label); + return m ? m[1] : null; +} + +export function sequenceRows(list: readonly Job[]): QueueRow[] { + const groups: Array<{ head: number; label: string; frames: Job[]; movie: Job | null }> = []; + const byHead = new Map(); + let last: (typeof groups)[number] | null = null; + let lastFrame = -1; + const owner = new Map(); + for (const j of list) { + const explicit = known.get(j.id); + if (explicit !== undefined) { + let g = byHead.get(explicit); + if (!g) { g = { head: explicit, label: prefixOf(j) ?? MOVIE.exec(j.label)?.[1] ?? j.label, frames: [], movie: null }; byHead.set(explicit, g); groups.push(g); } + if (isMovieJob(j)) g.movie = j; else g.frames.push(j); + owner.set(j.id, g); + last = null; + continue; + } + const prefix = prefixOf(j); + const n = prefix !== null ? Number(FRAME.exec(j.label)?.[2]) : -1; + if (prefix !== null && !isMovieJob(j)) { + if (last && last.label === prefix && last.frames[0].folder === j.folder && n > lastFrame && !last.movie) last.frames.push(j); + else { last = { head: j.id, label: prefix, frames: [j], movie: null }; groups.push(last); } + lastFrame = n; + owner.set(j.id, last); + continue; + } + if (isMovieJob(j) && last && MOVIE.exec(j.label)?.[1] === last.label && !last.movie) { + last.movie = j; + owner.set(j.id, last); + last = null; + continue; + } + last = null; + } + const rows: QueueRow[] = []; + const emitted = new Set<(typeof groups)[number]>(); + for (const j of list) { + const g = owner.get(j.id); + if (!g || g.frames.length < 2) { + rows.push({ kind: 'job', key: String(j.id), job: j, inSeq: false, movie: isMovieJob(j) }); + continue; + } + if (emitted.has(g)) continue; + emitted.add(g); + const key = `seq:${g.head}`; + const open = opened.has(key); + rows.push({ kind: 'seq', key, seq: { key, label: g.label, frames: g.frames, movie: g.movie, open } }); + if (open) for (const f of g.frames) rows.push({ kind: 'job', key: String(f.id), job: f, inSeq: true, movie: false }); + if (g.movie) rows.push({ kind: 'job', key: String(g.movie.id), job: g.movie, inSeq: false, movie: true }); + } + return rows; +} + +const base = (p: string): string => p.slice(Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\')) + 1); + +function clock(seconds: number): string { + const s = Math.max(0, Math.round(seconds)); + const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), r = s % 60; + return h ? `${h}:${String(m).padStart(2, '0')}:${String(r).padStart(2, '0')}` : `${m}:${String(r).padStart(2, '0')}`; +} + +const frameNo = (j: Job): string => FRAME.exec(j.label)?.[2] ?? ''; + +export interface SequenceHooks { repaint: () => void; openFolder: (folder: string) => void } + +export function createSequence(hooks: SequenceHooks): HTMLElement { + const row = el(`
    • +
      ${FILM}
      +
      +
      +
      +
      +
      +
      + + + + +
      +
    • `); + row.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-s]'); + if (!b || b.disabled) return; + e.stopPropagation(); + const seq = current.get(row); + if (!seq) return; + const all = [...seq.frames, ...(seq.movie ? [seq.movie] : [])]; + const quiet = (p: Promise): Promise => p.catch(() => undefined); + if (b.dataset.s === 'toggle') { + if (opened.has(seq.key)) opened.delete(seq.key); else opened.add(seq.key); + hooks.repaint(); + } else if (b.dataset.s === 'cancel') { + void (async () => { for (const j of [...all].reverse()) if (isActive(j) && !j.cancelling) await quiet(jobs.cancel(j.id)); })(); + } else if (b.dataset.s === 'remove') { + void (async () => { for (const j of [...all].reverse()) await quiet(jobs.remove(j.id)); })(); + } else if (b.dataset.s === 'folder') { + hooks.openFolder(seq.frames[0].folder); + } + }); + return row; +} + +const current = new WeakMap(); +const thumbs = new WeakMap(); + +export function updateSequence(row: HTMLElement, seq: Sequence): void { + current.set(row, seq); + const f = seq.frames; + const n = f.length; + const done = f.filter((j) => j.state === 'done').length; + const failed = f.filter((j) => j.state === 'failed').length; + const cancelled = f.filter((j) => j.state === 'cancelled').length; + const run = f.find((j) => j.state === 'running' || j.state === 'writing'); + const waiting = f.filter((j) => j.state === 'queued').length; + let state: string; + if (run) state = 'running'; + else if (waiting && done + failed + cancelled === 0) state = 'queued'; + else if (waiting) state = 'running'; + else if (failed) state = 'failed'; + else if (cancelled === n) state = 'cancelled'; + else state = done === n ? 'done' : 'cancelled'; + setAttr(row, 'data-state', state); + setClass(row, 'is-open', seq.open); + const firstNo = Number(frameNo(f[0])), lastNo = Number(frameNo(f[n - 1])); + const name = `${seq.label}: ${t('frames {first} to {last}', { first: firstNo, last: lastNo })}`; + const nameNode = q(row, '.fsh-render-job-name'); + setText(nameNode, name); + setTitle(nameNode, `${name}\n${f[0].folder}`); + const STATE: Record = { queued: 'Waiting', running: 'In progress', done: 'Finished', failed: 'Failed', cancelled: 'Cancelled' }; + setText(q(row, '.fsh-render-job-state'), t(STATE[state])); + const progress = (done + (run ? run.progress : 0)) / Math.max(1, n); + setStyleVar(row, '--fsh-render-p', String(Math.min(1, progress))); + let det = t('{done} of {n} frames rendered', { done, n }); + if (run) det = `${det}, ${t('frame {frame} at {pct}%', { frame: Number(frameNo(run)), pct: Math.round(run.progress * 100) })}`; + if (failed) det = `${det}, ${t('{n} failed', { n: failed })}`; + if (cancelled) det = `${det}, ${t('{n} cancelled', { n: cancelled })}`; + const detNode = q(row, '.fsh-render-job-detail'); + setText(detNode, det); + setTitle(detNode, det); + const spent = f.reduce((s, j) => s + j.seconds, 0); + const each = done ? f.filter((j) => j.state === 'done').reduce((s, j) => s + j.seconds, 0) / done : 0; + const left = (run?.eta ?? 0) + each * waiting; + setText(q(row, '.fsh-render-job-time'), state === 'running' && each > 0 ? t('{spent}, about {left} left', { spent: clock(spent), left: clock(left) }) : spent > 0 ? clock(spent) : ''); + const toggle = q(row, '[data-s="toggle"]'); + const tip = seq.open ? t('Hide the frames') : t('Show the {n} frames', { n }); + setTitle(toggle, tip); + setAttr(toggle, 'aria-label', tip); + setAttr(toggle, 'aria-expanded', seq.open ? 'true' : 'false'); + const active = [...f, ...(seq.movie ? [seq.movie] : [])].some((j) => isActive(j) && !j.cancelling); + setDisabled(q(row, '[data-s="cancel"]'), !active); + setDisabled(q(row, '[data-s="folder"]'), !f[0].folder || !jobs.available); + const latest = [...f].reverse().find((j) => j.state === 'done' && j.files.length); + const path = latest ? (latest.files.find((x) => x.pass === 'beauty') ?? latest.files[0]).path : ''; + const encoded = seq.movie?.state === 'done' || seq.movie?.state === 'running'; + if (thumbs.get(row) !== path && !(encoded && thumbs.has(row))) { + thumbs.set(row, path); + const img = q(row, 'img'); + if (!path) setClass(row, 'has-thumb', false); + else void jobs.thumbnail(path).then((url) => { + if (!url || thumbs.get(row) !== path) return; + return swapMedia(img, url).then(() => setClass(row, 'has-thumb', true)); + }).catch(() => undefined); + } +} + +export function decorateJob(row: HTMLElement, r: Extract): void { + setClass(row, 'is-in-seq', r.inSeq); + setClass(row, 'fsh-movie-row', r.movie); + if (!r.movie) return; + const j = r.job; + const ph = q(row, '.fsh-render-thumb-ph'); + if (ph.dataset.film !== '1') { ph.dataset.film = '1'; ph.innerHTML = FILM; } + const file = j.files.find((x) => x.pass === 'movie') ?? j.files[0]; + const kind = (file ? file.path.slice(file.path.lastIndexOf('.') + 1) : '').toUpperCase(); + let det: string; + const encoder = j.backend; + if (j.state === 'done' && file) det = encoder ? t('{file}, encoded with {encoder}', { file: base(file.path), encoder }) : base(file.path); + else if (j.state === 'running' || j.state === 'writing') det = encoder ? t('Encoding with {encoder}: {pct}%', { encoder, pct: Math.round(j.progress * 100) }) : t('Encoding: {pct}%', { pct: Math.round(j.progress * 100) }); + else if (j.state === 'failed') det = j.error || t('no reason was given'); + else if (j.state === 'cancelled') det = t('Not encoded: a frame was cancelled or the movie was.'); + else det = t('Encodes the frames with ffmpeg when they are done'); + if (kind && j.state === 'done') det = `${kind}: ${det}`; + let detNode = row.querySelector('.fsh-movie-detail'); + if (!detNode) { + detNode = el(''); + q(row, '.fsh-render-job-detail').after(detNode); + } + setText(detNode, det); + setTitle(detNode, [det, file?.path ?? '', j.note].filter(Boolean).join('\n')); + const folderBtn = q(row, '[data-a="folder"]'); + const tip = t('Show the movie in its folder'); + setTitle(folderBtn, tip); + setAttr(folderBtn, 'aria-label', tip); +} + +const FILM = ''; diff --git a/frontend/src/ui/movie/settings.ts b/frontend/src/ui/movie/settings.ts new file mode 100644 index 00000000..a706eaaf --- /dev/null +++ b/frontend/src/ui/movie/settings.ts @@ -0,0 +1,110 @@ +import { output } from '../render/output'; + +export type SeqFormat = 'png' | 'jpeg' | 'tiff' | 'exr' | 'psd'; +export type MovieFormat = 'mp4' | 'webm' | 'mov' | 'gif'; +export type FrameMode = 'all' | 'range'; + +export interface MovieSettings { + frames: FrameMode; + first: number; + last: number; + step: number; + format: SeqFormat; + transparent: boolean; + movie: boolean; + movieFormat: MovieFormat; + ownRate: boolean; + fps: number; + quality: number; + keepFrames: boolean; + camera: string; + name: string; + movieName: string; + folder: string; +} + +export const SEQ_FORMATS: ReadonlyArray = [ + ['png', 'PNG', 'png'], ['jpeg', 'JPEG', 'jpg'], ['tiff', 'TIFF', 'tif'], ['exr', 'OpenEXR', 'exr'], ['psd', 'PSD', 'psd'], +]; + +export const MOVIE_FORMATS: ReadonlyArray = [ + ['mp4', 'MP4'], ['webm', 'WebM'], ['mov', 'MOV (ProRes)'], ['gif', 'GIF'], +]; + +export const FRAME_TOKEN = '{frame}'; +export const DEFAULT_FRAME_NAME = '{project}_{camera}_{frame}'; + +const KEY = 'formshot.movie.settings'; + +const DEFAULTS: MovieSettings = { + frames: 'all', first: 1, last: 1, step: 1, format: 'png', transparent: false, + movie: true, movieFormat: 'mp4', ownRate: true, fps: 30, quality: 80, keepFrames: false, + camera: 'active', name: DEFAULT_FRAME_NAME, movieName: '', folder: '', +}; + +const int = (v: unknown, d: number, lo: number, hi: number): number => { + const n = Math.round(Number(v)); + return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : d; +}; + +function read(): MovieSettings { + try { + const raw = JSON.parse(localStorage.getItem(KEY) ?? 'null') as Partial | null; + const v: MovieSettings = { ...DEFAULTS, ...(raw && typeof raw === 'object' ? raw : {}) }; + if (!SEQ_FORMATS.some(([f]) => f === v.format)) v.format = 'png'; + if (!MOVIE_FORMATS.some(([f]) => f === v.movieFormat)) v.movieFormat = 'mp4'; + if (v.frames !== 'range') v.frames = 'all'; + v.first = int(v.first, 1, 1, 1e6); + v.last = int(v.last, v.first, 1, 1e6); + v.step = int(v.step, 1, 1, 1e6); + v.quality = int(v.quality, 80, 1, 100); + v.fps = Math.min(240, Math.max(0.01, Number(v.fps) || 30)); + return v; + } catch { + return { ...DEFAULTS }; + } +} + +export function movieFrames(format: SeqFormat): boolean { return format === 'png' || format === 'jpeg'; } + +export function extensionOf(format: SeqFormat): string { return SEQ_FORMATS.find(([f]) => f === format)?.[2] ?? 'png'; } + +export function frameOptions(format: SeqFormat): Record { + const o = output.value; + switch (format) { + case 'png': return { depth: o.pngDepth }; + case 'jpeg': return { quality: o.jpegQuality }; + case 'tiff': return o.tiffDepth === 32 ? { float: true, compression: o.tiffCompression } : { depth: o.tiffDepth, compression: o.tiffCompression }; + case 'exr': return { precision: o.exrPrecision, compression: o.exrCompression }; + case 'psd': return { depth: o.psdDepth }; + } +} + +export interface Plan { first: number; last: number; step: number; count: number } + +export function planOf(v: MovieSettings, total: number): Plan { + const all = v.frames === 'all' || total < 1; + const first = all ? 1 : Math.min(Math.max(1, v.first), Math.max(1, total)); + const last = all ? Math.max(1, total) : Math.min(Math.max(first, v.last), Math.max(1, total)); + const step = Math.max(1, v.step); + return { first, last, step, count: Math.floor((last - first) / step) + 1 }; +} + +type Listener = () => void; + +class MovieStore { + value: MovieSettings = read(); + private readonly fns = new Set(); + + onChange(fn: Listener): () => void { this.fns.add(fn); return () => { this.fns.delete(fn); }; } + + set(patch: Partial): void { + this.value = { ...this.value, ...patch }; + for (const fn of this.fns) fn(); + try { localStorage.setItem(KEY, JSON.stringify(this.value)); } catch { return; } + } + + usesMovie(): boolean { return this.value.movie && movieFrames(this.value.format); } +} + +export const movie = new MovieStore(); diff --git a/frontend/src/ui/overlay.ts b/frontend/src/ui/overlay.ts index 605ce44e..e57cc3f7 100644 --- a/frontend/src/ui/overlay.ts +++ b/frontend/src/ui/overlay.ts @@ -41,6 +41,7 @@ export class Overlay { ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.guides(ctx); for (const p of this.painters) p(ctx); + paintLayers(ctx, this); } private guides(ctx: CanvasRenderingContext2D): void { @@ -78,3 +79,26 @@ export class Overlay { ctx.restore(); } } + +export type OverlayLayer = (ctx: CanvasRenderingContext2D, overlay: Overlay) => void; + +const layers = new Set(); +const painted = new Set(); + +function paintLayers(ctx: CanvasRenderingContext2D, overlay: Overlay): void { + painted.add(overlay); + for (const layer of layers) { + ctx.save(); + try { layer(ctx, overlay); } finally { ctx.restore(); } + } +} + +export function addOverlayLayer(layer: OverlayLayer): () => void { + layers.add(layer); + invalidateOverlays(); + return () => { layers.delete(layer); invalidateOverlays(); }; +} + +export function invalidateOverlays(): void { + for (const o of painted) o.invalidate(); +} diff --git a/frontend/src/ui/pages/configurator.ts b/frontend/src/ui/pages/configurator.ts new file mode 100644 index 00000000..2ed354e8 --- /dev/null +++ b/frontend/src/ui/pages/configurator.ts @@ -0,0 +1,118 @@ +import '../configurator/configurator.css'; +import { el, escapeHtml, setClass, setHidden, setPressed, setText, setTitle } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { choiceOf, movedOptions, optionOf, type Moved } from '../configurator/model'; +import { mountOptions } from '../configurator/options'; +import { mountRules, problemList } from '../configurator/rules'; +import { ChoiceSheet } from '../configurator/sheet'; +import { mountFooter } from '../configurator/footer'; +import { registerTemplates } from '../templates'; +import { CONFIG_CMD, ConfigStore } from '../configurator/store'; +import { engineNote, pageHead, section, type PageMount } from './page'; + +const BARRIER = 'history.barrier'; + +registerTemplates(); + +export const mountConfiguratorPage: PageMount = (host, ws) => { + const store = new ConfigStore(ws); + host.classList.add('fsh-cfg-page'); + const head = pageHead(host, 'Configurator'); + const editBtn = el(``); + head.appendChild(editBtn); + const offNote = engineNote(host, ws); + const status = el('

      '); + const error = el(''); + const general = el(''); + host.append(status, error, general); + + const send = async (name: string, args: Record): Promise => { + const out = await ws.run(name, args); + if (out !== undefined && ws.canRun(BARRIER)) await ws.client.dispatch(BARRIER, {}).catch(() => undefined); + return out; + }; + + let editing = false; + const setEditing = (on: boolean): void => { + editing = on; + setClass(host, 'is-editing', on); + setPressed(editBtn, on); + setTitle(editBtn, on ? t('Stop editing the options and rules') : t('Edit the options, choices and rules')); + if (!on) sheet.close(); + options.update(); + }; + editBtn.addEventListener('click', () => setEditing(!editing)); + + let moved: Moved[] = []; + let said = ''; + let busy = false; + + const optionsHost = section(host, 'Options'); + const sheet = new ChoiceSheet(ws, store, send); + const options = mountOptions(optionsHost, ws, store, { + moved: () => moved, + picked: (option, choice) => { void pick(option, choice); }, + editing: () => editing, + editChoice: (option, choice) => sheet.open(option, choice, host), + send, + }); + + const rules = mountRules(section(host, 'Rules'), ws, store, send); + const footer = mountFooter(section(host, 'Every configuration'), ws, store); + setEditing(false); + + const movedText =(list: readonly Moved[]): string => { + const s = store.state; + return list.map((m) => t('{option} to {choice}', { option: optionOf(s, m.option)?.name ?? m.option, choice: (m.to && choiceOf(s, m.option, m.to)?.name) || '' })).join(', '); + }; + + const paintStatus = (): void => { + const s = store.state; + moved = moved.filter((m) => optionOf(s, m.option)?.current === m.to); + if (said && !moved.length) said = ''; + let text = said; + if (!text && store.loaded && s.name) text = s.valid ? t('Current configuration: {name}', { name: s.name }) : t('Current configuration: {name} (breaks a rule)', { name: s.name }); + setText(status, text); + setClass(status, 'is-moved', said !== ''); + setText(error, store.error); + setHidden(error, store.error === ''); + }; + + const pick = async (option: string, choice: string): Promise => { + if (busy || !ws.canRun(CONFIG_CMD.select)) return; + busy = true; + const before = store.state; + try { + const out = await ws.run(CONFIG_CMD.select, { option, choice }); + if (out === undefined) return; + if (ws.canRun(BARRIER)) await ws.client.dispatch(BARRIER, {}).catch(() => undefined); + const after = await store.fetchState(); + moved = movedOptions(before, after, option); + const picked = choiceOf(after, option, choice)?.name ?? choice; + said = moved.length ? t('{choice} moved {list} to keep the rules.', { choice: picked, list: movedText(moved) }) : ''; + store.state = after; + options.update(); + paintStatus(); + } finally { + busy = false; + } + }; + + const paint = (): void => { + paintStatus(); + options.update(); + rules.update(); + footer.update(); + problemList(general, store.problems.filter((p) => p.option === null && p.rule === null)); + }; + + const visible = (): void => store.setVisible(!host.hidden && ws.ctx.shell.isOpen('inspector')); + const watch = new MutationObserver(visible); + watch.observe(host, { attributes: true, attributeFilter: ['hidden'] }); + const offLayout = ws.ctx.shell.onLayout(visible); + const offs = [store.onChange(paint), ws.client.onState(paint)]; + visible(); + paint(); + return () => { watch.disconnect(); offLayout(); offNote(); options.dispose(); rules.dispose(); sheet.dispose(); footer.dispose(); for (const off of offs) off(); store.dispose(); }; +}; diff --git a/frontend/src/ui/pages/scene.ts b/frontend/src/ui/pages/scene.ts index de563dfc..0eb01890 100644 --- a/frontend/src/ui/pages/scene.ts +++ b/frontend/src/ui/pages/scene.ts @@ -6,6 +6,7 @@ import type { Workspace } from '../context'; import { setGlyph, type GlyphName } from '../glyphs'; import type { IconName } from '../../shell/icons'; import { engineNote, pageHead, type PageMount } from './page'; +import { mountCutaways } from '../transport/cutaways'; export const SCENE_COMMANDS = { select: 'selection.set', @@ -191,6 +192,7 @@ export const mountScenePage: PageMount = (host, ws) => { }); update(); - const offs = [client.onSummary(update), client.onState(update), client.onCatalogue(update)]; + const offCutaways = mountCutaways(host, ws); + const offs = [client.onSummary(update), client.onState(update), client.onCatalogue(update), offCutaways]; return () => { offNote(); for (const off of offs) off(); }; }; diff --git a/frontend/src/ui/pages/shots.ts b/frontend/src/ui/pages/shots.ts new file mode 100644 index 00000000..da671280 --- /dev/null +++ b/frontend/src/ui/pages/shots.ts @@ -0,0 +1,43 @@ +import '../shots/shots.css'; +import { connectShots, registerShotCommands } from '../shots/commands'; +import { SHOT_CMD } from '../shots/model'; +import { mountModelSets } from '../shots/models'; +import { mountShots, type Section } from '../shots/shots'; +import { ShotsStore } from '../shots/store'; +import { mountVariants } from '../shots/variants'; +import { engineNote, pageHead, section, type PageMount } from './page'; + +registerShotCommands(); + +export const mountShotsPage: PageMount = (host, ws) => { + pageHead(host, 'Shots'); + const offNote = engineNote(host, ws); + const store = new ShotsStore(ws, () => !host.hidden && host.isConnected); + + const shots = mountShots(section(host, 'Shots'), ws, store); + const variants = mountVariants(section(host, 'Material variants'), ws, store); + const models = mountModelSets(section(host, 'Model sets'), ws, store); + const parts: Section[] = [shots, variants, models]; + const paint = (): void => { for (const p of parts) p.update(); }; + + const offBridge = connectShots({ + add: () => shots.add(), + renderAll: async () => { if (!store.loaded) await store.reload(); await shots.renderAll(); }, + canAdd: () => ws.canRun(SHOT_CMD.add), + canRender: () => ws.canRun(SHOT_CMD.render) && (!store.loaded || store.shots.length > 0), + }); + + const follow = (): void => { store.follow(); paint(); }; + const seen = new MutationObserver(() => store.wake()); + seen.observe(host, { attributes: true, attributeFilter: ['hidden'] }); + const offs = [store.onChange(paint), ws.client.onSummary(follow), ws.client.onState(follow), ws.client.onCatalogue(() => { store.schedule(0); paint(); })]; + follow(); + return () => { + offNote(); + offBridge(); + seen.disconnect(); + for (const off of offs) off(); + for (const p of parts) p.dispose(); + store.dispose(); + }; +}; diff --git a/frontend/src/ui/render/index.ts b/frontend/src/ui/render/index.ts index 4b2d8318..24f2371a 100644 --- a/frontend/src/ui/render/index.ts +++ b/frontend/src/ui/render/index.ts @@ -5,11 +5,13 @@ import { icon } from '../../shell/icons'; import { t } from '../../i18n'; import { mountDenoise } from './denoise'; import { isActive, jobs, QUEUE_COMMANDS } from './jobs'; -import { FORMATS, mountFormat, mountNaming, nameProblem, output } from './output'; +import { DEFAULT_NAME, FORMATS, mountFormat, mountNaming, nameProblem, output } from './output'; import { mountPasses } from './passes'; import { mountQueue } from './queue'; import { mountSize } from './size'; +import { api } from '../../shell/api'; import { errorText, rendersFolder, store } from './store'; +import { measured, mountMeasureOption, RENDER_SOURCE, sourceOf, type RenderSource } from './source'; import { RenderWindow } from './window'; const OPEN = 'render.window'; @@ -52,6 +54,9 @@ export function mount(ctx: ModuleContext): void { let said = ''; let saidError = false; + let source: RenderSource | null = null; + mountMeasureOption(win.settings); + const problem = (): string => { if (!store.loaded) return store.error; if (!jobs.available) return t('This engine has no render queue.'); @@ -70,9 +75,32 @@ export function mount(ctx: ModuleContext): void { : t('{width} × {height}, {samples} samples, {format}, the picture alone, into {folder}', vars); }; + const options = (f: string): Record => { + const v = store.values; + const o: Record = { ...output.job(f), width: v.width, height: v.height, samples: v.samples, passes: [...v.passes], denoise: v.denoise }; + if (measured.on) o.measurements = true; + return o; + }; + const sourceName = (src: RenderSource): string => { + if (typeof src.args?.name === 'string' && src.args.name.trim()) return src.args.name.trim(); + const n = output.value.name.trim() || DEFAULT_NAME; + return src.name ? src.name(n, output.job('').camera) : n; + }; + const idsOf = (reply: unknown): number[] => { + const o = reply && typeof reply === 'object' ? reply as Record : {}; + return Array.isArray(o.ids) ? o.ids.filter((x): x is number => typeof x === 'number') : []; + }; + const queueSource = async (src: RenderSource, f: string): Promise => { + if (!store.loaded) await store.reload(); + await measured.read(); + const reply = await api.dispatch(src.command, { ...options(f), name: sourceName(src), ...src.args }, { timeoutMs: 60000 }); + jobs.poll(0); + return reply; + }; + const paintFoot = (): void => { const why = problem(); - const text = said || why || summary(); + const text = said || why || (source ? t('Rendering {source} as {name}: {details}', { source: source.label, name: sourceName(source), details: summary() }) : summary()); setText(status, text); setTitle(status, text); setClass(status, 'is-error', saidError || (!said && why !== '')); @@ -89,14 +117,23 @@ export function mount(ctx: ModuleContext): void { said = ''; paintFoot(); try { - const ids = await jobs.add({ ...output.job(folder()), label: '' }); + const src = source; + let reply: unknown = null; + let ids: number[]; + if (src) { + reply = await queueSource(src, folder()); + ids = idsOf(reply); + source = null; + } else ids = await jobs.add({ ...options(folder()), label: '' }); if (now && ids.length) { - const first = jobs.list.jobs.findIndex((j) => j.state === 'queued'); - for (const [i, id] of ids.entries()) await jobs.move(id, Math.max(0, first) + i); + await jobs.read(); + const first = jobs.list.jobs.findIndex((j) => j.state === 'queued' && !ids.includes(j.id)); + const waiting = ids.filter((id) => jobs.list.jobs.some((j) => j.id === id && j.state === 'queued')); + for (const [i, id] of waiting.entries()) await jobs.move(id, Math.max(0, first) + i); if (jobs.list.paused) await jobs.pause(false); win.show('queue'); } - said = ids.length === 1 ? t('Added to the queue.') : t('{n} renders added to the queue.', { n: ids.length }); + said = src?.done ? src.done(reply) : ids.length === 1 ? t('Added to the queue.') : t('{n} renders added to the queue.', { n: ids.length }); saidError = false; } catch (err) { said = t('Could not add the render: {reason}', { reason: errorText(err) }); @@ -109,11 +146,43 @@ export function mount(ctx: ModuleContext): void { }; addBtn.addEventListener('click', () => void submit(false)); nowBtn.addEventListener('click', () => void submit(true)); + win.onOpen((open) => { + measured.setActive(open); + if (!open && source) { source = null; paintFoot(); } + }); + measured.onChange(paintFoot); + registry.registerCommands([{ + id: RENDER_SOURCE, label: 'Render With the Final Render Options', group: 'Render', palette: false, + run: async (args) => { + const src = sourceOf(args?.source); + if (!src) return null; + if (args?.open === false) return queueSource(src, typeof src.args?.folder === 'string' ? src.args.folder : folder()); + source = src; + said = ''; + win.open('settings'); + paintFoot(); + return null; + }, + }]); store.onChange(() => { jobs.setAvailable(QUEUE_COMMANDS.every((c) => store.has(c))); paintFoot(); queue.paint(); naming.paint(); }); output.onChange(paintFoot); jobs.onChange(paintFoot); + const sequenceOf = (label: string): string | null => /^(.*) (?:frame \d+|movie)$/.exec(label)?.[1] ?? null; + const toldSequences = new Set(); jobs.onEnded((j) => { + const seq = sequenceOf(j.label); + if (seq !== null) { + const mates = jobs.list.jobs.filter((x) => sequenceOf(x.label) === seq && x.folder === j.folder); + const key = `${seq}|${mates[0]?.id ?? j.id}`; + if (mates.some(isActive) || toldSequences.has(key)) return; + toldSequences.add(key); + const failed = mates.filter((x) => x.state === 'failed'); + const frames = mates.filter((x) => x.state === 'done' && !x.label.endsWith(' movie')).length; + if (failed.length) ctx.toast(t('Animation finished with {n} failed: {name}: {reason}', { n: failed.length, name: seq, reason: failed[0].error || t('no reason was given') }), 'error'); + else if (frames) ctx.toast(t('Animation finished: {name}, {n} frames', { name: seq, n: frames }), 'info', { label: t('Open Folder'), run: () => openFolder(j.folder) }); + return; + } const name = j.label || `${j.title || t('Untitled')}, ${j.camera}`; if (j.state === 'done') ctx.toast(t('Render finished: {name}', { name }), 'info', { label: t('Open Folder'), run: () => openFolder(j.folder) }); else if (j.state === 'failed') ctx.toast(t('Render failed: {name}: {reason}', { name, reason: j.error || t('no reason was given') }), 'error'); diff --git a/frontend/src/ui/render/jobs.ts b/frontend/src/ui/render/jobs.ts index 4b26152a..afa4d43f 100644 --- a/frontend/src/ui/render/jobs.ts +++ b/frontend/src/ui/render/jobs.ts @@ -23,6 +23,7 @@ export interface Job { passes: string[]; device: string; drew: string; + backend: string; note: string; files: JobFile[]; error: string; @@ -62,6 +63,7 @@ function jobOf(v: unknown): Job | null { passes: Array.isArray(o.passes) ? o.passes.map(String) : [], device: str(o.device), drew: str(o.drew), + backend: str(o.backend), note: str(o.note), files: (Array.isArray(o.files) ? o.files : []).map((f) => { const x = obj(f); return { pass: str(x.pass), path: str(x.path), bytes: num(x.bytes) }; }).filter((f) => f.path), error: str(err.message), diff --git a/frontend/src/ui/render/motion.ts b/frontend/src/ui/render/motion.ts new file mode 100644 index 00000000..b2123ae5 --- /dev/null +++ b/frontend/src/ui/render/motion.ts @@ -0,0 +1,159 @@ +import { api } from '../../shell/api'; +import { events } from '../../shell/events'; +import { el, setAttr, setText } from '../../shell/dom'; +import { t } from '../../i18n'; +import { Check, NumberField, Segmented, section } from './fields'; +import { CHANGE_EVENTS, errorText, store } from './store'; +import { timeline, resultOf } from '../movie/anim'; +import '../movie/movie.css'; + +export type ShutterPosition = 'centred' | 'opening' | 'closing'; + +export interface MotionBlur { enabled: boolean; shutter: number; position: ShutterPosition } + +export const MOTION_DEFAULTS: MotionBlur = { enabled: false, shutter: 0.5, position: 'centred' }; + +const obj = (v: unknown): Record => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record : {}); + +export function blurOf(v: unknown): MotionBlur { + const o = obj(v); + const shutter = typeof o.shutter === 'number' && Number.isFinite(o.shutter) ? Math.min(1, Math.max(0, o.shutter)) : MOTION_DEFAULTS.shutter; + const position = o.position === 'opening' || o.position === 'closing' ? o.position : 'centred'; + return { enabled: o.enabled === true, shutter, position }; +} + +class MotionStore { + value: MotionBlur = { ...MOTION_DEFAULTS }; + error = ''; + loaded = false; + private readonly fns = new Set<() => void>(); + private active = false; + private wired = false; + private timer = 0; + private seq = 0; + private pending: MotionBlur | null = null; + + onChange(fn: () => void): () => void { this.fns.add(fn); return () => { this.fns.delete(fn); }; } + private changed(): void { for (const fn of this.fns) fn(); } + + setActive(on: boolean): void { + this.active = on; + if (!this.wired) { + this.wired = true; + for (const type of [...CHANGE_EVENTS, 'ui.dispatched']) events.on(type, () => { if (this.active) this.schedule(type === 'hello' || type === 'resync' ? 0 : 200); }); + } + if (on) this.schedule(0); + } + + schedule(delay: number): void { + window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => void this.read(), delay); + } + + async read(): Promise { + const seq = ++this.seq; + try { + const s = resultOf(await api.dispatch('scene.summary', {}, { timeoutMs: 15000 })); + const next = blurOf(obj(s.render).motion_blur); + if (seq !== this.seq) return; + this.value = this.pending ?? next; + this.error = ''; + this.loaded = true; + } catch (err) { + if (seq !== this.seq) return; + this.error = errorText(err); + } + this.changed(); + } + + async set(patch: Partial): Promise { + const before = this.value; + const next = { ...this.value, ...patch }; + this.value = next; + this.pending = next; + this.changed(); + try { + await api.dispatch('render.set_settings', { values: { motion_blur: next } }, { timeoutMs: 20000 }); + events.emit({ type: 'document.changed', source: 'render' }); + return true; + } catch (err) { + this.value = before; + this.error = errorText(err); + this.changed(); + return false; + } finally { + if (this.pending === next) this.pending = null; + this.schedule(60); + } + } +} + +export const motion = new MotionStore(); + +const POSITIONS: ReadonlyArray = [ + ['centred', 'Centred on the frame'], ['opening', 'Opens at the frame'], ['closing', 'Closes at the frame'], +]; + +export interface MotionSection { el: HTMLElement; focus: () => void; setActive: (on: boolean) => void } + +export function mountMotion(host: HTMLElement): MotionSection { + const sec = section('Motion blur', 'fsh-render-motion'); + const on = new Check('Blur what moves while the shutter is open', (v) => void motion.set({ enabled: v })); + const shutter = new NumberField({ label: 'Shutter open', min: 0, max: 1, step: 0.05, digits: 3, unit: '', commit: (v) => void motion.set({ shutter: v }) }); + const angle = new NumberField({ label: 'Shutter angle', min: 0, max: 360, step: 15, digits: 1, unit: '°', commit: (v) => void motion.set({ shutter: Math.round((v / 360) * 1000) / 1000 }) }); + const pair = el('
      '); + pair.append(shutter.el, angle.el); + const where = new Segmented('Shutter position', POSITIONS, (v) => void motion.set({ position: v })); + const line = el('

      '); + const note = el('

      '); + sec.append(on.el, pair, where.el, line, note); + const place = (): void => { host.appendChild(sec); }; + queueMicrotask(place); + + const paint = (): void => { + const v = motion.value; + const can = store.has('render.set_settings') && motion.loaded; + on.set(v.enabled); + on.disable(!can); + shutter.set(v.shutter); + angle.set(v.shutter * 360); + where.set(v.position); + shutter.disable(!can || !v.enabled); + angle.disable(!can || !v.enabled); + where.disable(!can || !v.enabled); + setAttr(sec, 'data-off', v.enabled ? null : 'true'); + const fps = timeline.value?.fps ?? 0; + let text = ''; + if (motion.error) text = motion.error; + else if (!v.enabled) text = t('Off: every frame is a sharp instant.'); + else if (v.shutter <= 0) text = t('A closed shutter blurs nothing.'); + else if (fps > 0) { + const ms = (v.shutter / fps) * 1000; + text = t('At {fps} fps the shutter stays open {ms} ms of each frame ({fraction} of a frame, a {angle} degree shutter).', { + fps: Number(fps.toFixed(3)), ms: ms.toFixed(1), fraction: Number(v.shutter.toFixed(3)), angle: Number((v.shutter * 360).toFixed(1)), + }); + } else text = t('{fraction} of a frame, a {angle} degree shutter.', { fraction: Number(v.shutter.toFixed(3)), angle: Number((v.shutter * 360).toFixed(1)) }); + setText(line, text); + setAttr(line, 'data-error', motion.error ? 'true' : null); + setText(note, v.enabled ? t('Only parts and cameras that move in the animation blur. The GPU engine does not render motion blur yet: moving frames render on the CPU.') : ''); + if (wantFocus && can) { wantFocus = false; on.input.focus(); } + }; + let wantFocus = false; + paint(); + motion.onChange(paint); + store.onChange(paint); + timeline.onChange(paint); + let using = false; + return { + el: sec, + focus: () => { + sec.scrollIntoView({ block: 'nearest' }); + if (on.input.disabled) wantFocus = true; + else on.input.focus(); + }, + setActive: (active: boolean) => { + motion.setActive(active); + if (active !== using) { using = active; timeline.use(active); } + }, + }; +} diff --git a/frontend/src/ui/render/queue.ts b/frontend/src/ui/render/queue.ts index 588b7b13..94c92814 100644 --- a/frontend/src/ui/render/queue.ts +++ b/frontend/src/ui/render/queue.ts @@ -2,6 +2,7 @@ import { el, patchList, q, setAttr, setClass, setDisabled, setHidden, setStyleVa import { icon } from '../../shell/icons'; import { t } from '../../i18n'; import { isActive, isFinished, jobs, type Job, type JobState } from './jobs'; +import { createSequence, decorateJob, sequenceRows, updateSequence, type QueueRow } from '../movie/rows'; const STATE_TEXT: Record = { queued: 'Waiting', @@ -137,7 +138,15 @@ export function mountQueue(host: HTMLElement, hooks: QueueHooks): { paint: () => const paint = (): void => { const l = jobs.list; - patchList(list, l.jobs, { key: (j) => String(j.id), create, update }); + const paintRow = (node: HTMLElement, r: QueueRow): void => { + if (r.kind === 'seq') updateSequence(node, r.seq); + else { update(node, r.movie ? { ...r.job, files: [] } : r.job); decorateJob(node, r); } + }; + patchList(list, sequenceRows(l.jobs), { + key: (r) => r.key, + create: (r) => { const node = r.kind === 'seq' ? createSequence({ repaint: () => paint(), openFolder: hooks.openFolder }) : create(); paintRow(node, r); return node; }, + update: paintRow, + }); setHidden(empty, l.jobs.length > 0); const waiting = l.jobs.filter((j) => j.state === 'queued').length; const running = l.jobs.filter((j) => j.state === 'running' || j.state === 'writing').length; diff --git a/frontend/src/ui/render/source.css b/frontend/src/ui/render/source.css new file mode 100644 index 00000000..e963beaa --- /dev/null +++ b/frontend/src/ui/render/source.css @@ -0,0 +1 @@ +.fsh-render-measure.is-absent { visibility: hidden; } diff --git a/frontend/src/ui/render/source.ts b/frontend/src/ui/render/source.ts new file mode 100644 index 00000000..6b9784eb --- /dev/null +++ b/frontend/src/ui/render/source.ts @@ -0,0 +1,117 @@ +import './source.css'; +import { api } from '../../shell/api'; +import { events } from '../../shell/events'; +import { q, setAttr, setClass, setTitle } from '../../shell/dom'; +import { t } from '../../i18n'; +import { Check } from './fields'; +import { CHANGE_EVENTS } from './store'; + +/** The hook other modules run (through the registry) to render their own source with the Final Render options. */ +export const RENDER_SOURCE = 'render.source'; + +/** + * Something other than the open document rendered with the window's options: a set of shots, every configuration, + * an animation. `command` is the source's own engine command; it gets the window's options (render.queue_add's + * arguments) with `args` on top. `name` turns the window's file name template into the source's (adding `{shot}` or + * `{config}`), `done` turns the reply into the sentence the window shows. + */ +export interface RenderSource { + kind: string; + label: string; + command: string; + args?: Record; + name?: (template: string, camera: unknown) => string; + done?: (reply: unknown) => string; +} + +const obj = (v: unknown): Record => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record : {}); + +export function sourceOf(v: unknown): RenderSource | null { + const o = obj(v); + if (typeof o.command !== 'string' || !o.command || typeof o.label !== 'string') return null; + return { + kind: typeof o.kind === 'string' ? o.kind : 'other', + label: o.label, + command: o.command, + args: obj(o.args), + name: typeof o.name === 'function' ? o.name as RenderSource['name'] : undefined, + done: typeof o.done === 'function' ? o.done as RenderSource['done'] : undefined, + }; +} + +const MEASURE_KEY = 'formshot.render.measurements'; +const MEASURE_COMMANDS = /^(measure\.|history\.|file\.|scene\.remove|scene\.duplicate)/; + +class Measured { + visible = 0; + wanted: boolean; + private readonly fns = new Set<() => void>(); + private active = false; + private wired = false; + private timer = 0; + private seq = 0; + + constructor() { + let raw: string | null = null; + try { raw = localStorage.getItem(MEASURE_KEY); } catch { raw = null; } + this.wanted = raw === 'on'; + } + + onChange(fn: () => void): () => void { this.fns.add(fn); return () => { this.fns.delete(fn); }; } + private changed(): void { for (const fn of this.fns) fn(); } + + /** True when the next render should draw measurements: asked for, and the document has visible ones. */ + get on(): boolean { return this.wanted && this.visible > 0; } + + want(on: boolean): void { + this.wanted = on; + try { localStorage.setItem(MEASURE_KEY, on ? 'on' : 'off'); } catch { this.changed(); return; } + this.changed(); + } + + setActive(on: boolean): void { + this.active = on; + if (!this.wired) { + this.wired = true; + for (const type of CHANGE_EVENTS) events.on(type, () => { if (this.active) this.schedule(150); }); + events.on('ui.dispatched', (e) => { if (this.active && typeof e.name === 'string' && MEASURE_COMMANDS.test(e.name)) this.schedule(60); }); + } + if (on) this.schedule(0); + } + + async read(): Promise { + const seq = ++this.seq; + try { + const reply = obj(await api.dispatch('measure.list', {}, { timeoutMs: 15000 })); + const list = Array.isArray(reply.measurements) ? reply.measurements : []; + const n = list.filter((m) => obj(m).visible !== false).length; + if (seq === this.seq && n !== this.visible) { this.visible = n; this.changed(); } + } catch { + if (seq === this.seq && this.visible !== 0) { this.visible = 0; this.changed(); } + } + return this.visible; + } + + private schedule(ms: number): void { + window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => void this.read(), ms); + } +} + +export const measured = new Measured(); + +/** "Draw measurements" beside the image file checks; its place is kept (visibility) when there is nothing to draw. */ +export function mountMeasureOption(settings: HTMLElement): void { + const check = new Check('Draw measurements', (on) => measured.want(on), 'fsh-render-measure'); + q(settings, '.fsh-render-checks').appendChild(check.el); + const paint = (): void => { + const has = measured.visible > 0; + check.set(measured.wanted); + check.disable(!has); + setClass(check.el, 'is-absent', !has); + setAttr(check.el, 'aria-hidden', has ? null : 'true'); + setTitle(check.el, t('Draws the visible measurements into the picture, as the viewport shows them.')); + }; + paint(); + measured.onChange(paint); +} diff --git a/frontend/src/ui/render/transport.ts b/frontend/src/ui/render/transport.ts new file mode 100644 index 00000000..b1d37c22 --- /dev/null +++ b/frontend/src/ui/render/transport.ts @@ -0,0 +1,67 @@ +import '../transport/transport.css'; +import { api } from '../../shell/api'; +import { events } from '../../shell/events'; +import { el, q, setAttr, setHidden, setText, setTitle } from '../../shell/dom'; +import { t } from '../../i18n'; +import { cpuOnlyText, features } from '../transport/features'; +import { cpuBadge } from '../transport/badge'; +import { Check, section } from './fields'; +import { errorText } from './store'; +import type { RenderWindow } from './window'; + +const SET = 'render.set_settings'; + +export function mountTransport(win: RenderWindow): void { + const sec = section('Light transport', 'fsh-render-transport'); + const spectral = new Check('Spectral rendering', (on) => void send(on), 'fsh-tr-spectral'); + const badge = cpuBadge(); + spectral.el.appendChild(badge.el); + const help = el('

      Traces wavelengths of light instead of red, green and blue: accurate dispersion and colour, but slower to clear up.

      '); + const note = el('

      '); + const err = el(''); + sec.append(spectral.el, help, note, err); + let sending = false; + let failure = ''; + + const paint = (): void => { + const on = features.spectralOn(); + spectral.set(on === true); + spectral.disable(sending || !features.available || on === null); + const refused = features.refusedList(); + badge.set(features.refused('spectral')); + const text = refused.length ? cpuOnlyText(refused) : ''; + setText(note, text); + setTitle(note, text); + setAttr(note, 'data-on', text ? 'true' : null); + const e = failure || (!features.available && features.loaded ? t('This engine does not report light transport features.') : ''); + setText(err, e); + setHidden(err, e === ''); + }; + + const send = async (on: boolean): Promise => { + if (sending) return; + sending = true; + failure = ''; + features.setSpectral(on); + try { + await api.dispatch(SET, { values: { transport: { spectral: { enabled: on } } } }, { timeoutMs: 20000 }); + events.emit({ type: 'document.changed', source: 'render' }); + } catch (e) { + failure = t('Spectral rendering could not be changed: {reason}', { reason: errorText(e) }); + features.setSpectral(!on); + } finally { + sending = false; + features.schedule(0); + paint(); + } + }; + + features.onChange(paint); + let release: (() => void) | null = null; + win.onOpen((open) => { + if (open && !release) release = features.use(); + else if (!open && release) { release(); release = null; } + }); + paint(); + queueMicrotask(() => win.settings.appendChild(sec)); +} diff --git a/frontend/src/ui/render/window.ts b/frontend/src/ui/render/window.ts index 1dc4d135..7ea919d6 100644 --- a/frontend/src/ui/render/window.ts +++ b/frontend/src/ui/render/window.ts @@ -1,6 +1,7 @@ import { el, q, setAttr, setHidden, setStyleVar, setText } from '../../shell/dom'; import { icon } from '../../shell/icons'; import { t } from '../../i18n'; +import { mountTransport } from './transport'; export type Tab = 'settings' | 'queue'; @@ -70,7 +71,9 @@ export class RenderWindow { this.drag(q(this.root, '.fsh-render-head')); this.paintTabs(); (document.getElementById('overlay-root') ?? document.body).appendChild(this.root); + void import('../movie/index').then((m) => m.mountMovie(this)); window.addEventListener('resize', () => { if (!this.root.hidden) this.applyPlace(); }); + mountTransport(this); } get isOpen(): boolean { return !this.root.hidden; } diff --git a/frontend/src/ui/shots/commands.ts b/frontend/src/ui/shots/commands.ts new file mode 100644 index 00000000..ee92c852 --- /dev/null +++ b/frontend/src/ui/shots/commands.ts @@ -0,0 +1,41 @@ +import { registerCommands, runCommand } from '../../shell/registry'; + +export interface ShotsBridge { + add(): Promise; + renderAll(): Promise; + canAdd(): boolean; + canRender(): boolean; +} + +const PAGE_COMMAND = 'inspector.snapshots'; +let bridge: ShotsBridge | null = null; +let registered = false; + +export function connectShots(b: ShotsBridge): () => void { + bridge = b; + return () => { if (bridge === b) bridge = null; }; +} + +function withPage(fn: (b: ShotsBridge) => Promise): Promise | undefined { + runCommand(PAGE_COMMAND); + return bridge ? fn(bridge) : undefined; +} + +export function registerShotCommands(): void { + if (registered) return; + registered = true; + registerCommands([ + { + id: 'shots.new', label: 'New Shot', group: 'Render', icon: 'snapshot', + description: 'Keep the current view as a named shot on the Shots page.', + enabled: () => !bridge || bridge.canAdd(), + run: () => withPage((b) => b.add()), + }, + { + id: 'shots.renderAll', label: 'Render All Shots', group: 'Render', icon: 'render', + description: 'Queue one final render per shot with the Final Render output settings.', + enabled: () => !bridge || bridge.canRender(), + run: () => withPage((b) => b.renderAll()), + }, + ]); +} diff --git a/frontend/src/ui/shots/glyphs.ts b/frontend/src/ui/shots/glyphs.ts new file mode 100644 index 00000000..c3fa8352 --- /dev/null +++ b/frontend/src/ui/shots/glyphs.ts @@ -0,0 +1,19 @@ +const s = (body: string): string => ``; + +const GLYPHS = { + grip: s(''), + apply: s(''), + current: s(''), + duplicate: s(''), + recapture: s(''), + rename: s(''), + capture: s(''), + models: s(''), + include: s(''), +} as const; + +export type GlyphName = keyof typeof GLYPHS; + +export function glyph(name: GlyphName, size = 16): string { + return ``; +} diff --git a/frontend/src/ui/shots/model.ts b/frontend/src/ui/shots/model.ts new file mode 100644 index 00000000..3af5d4a9 --- /dev/null +++ b/frontend/src/ui/shots/model.ts @@ -0,0 +1,201 @@ +export const SHOT_CMD = { + list: 'shot.list', + add: 'shot.add', + update: 'shot.update', + set: 'shot.set', + remove: 'shot.remove', + move: 'shot.move', + duplicate: 'shot.duplicate', + apply: 'shot.apply', + render: 'shot.render', +} as const; + +export const VARIANT_CMD = { + list: 'variant.list', + diff: 'variant.diff', + addSet: 'variant.add_set', + setSet: 'variant.set_set', + removeSet: 'variant.remove_set', + capture: 'variant.capture', + set: 'variant.set', + remove: 'variant.remove', + move: 'variant.move', + select: 'variant.select', +} as const; + +export const MODEL_CMD = { + list: 'model_set.list', + add: 'model_set.add', + set: 'model_set.set', + remove: 'model_set.remove', + move: 'model_set.move', + select: 'model_set.select', +} as const; + +export const INCLUDE_KEYS = ['camera', 'image', 'environment', 'render', 'lights', 'visibility', 'variants'] as const; +export type IncludeKey = typeof INCLUDE_KEYS[number]; +export type Include = Record; + +export const INCLUDE_LABELS: Record = { + camera: 'Camera and lens', + image: 'Image style', + environment: 'Environment and ground', + render: 'Render settings', + lights: 'Lights on, power and colour', + visibility: 'Shown and hidden nodes', + variants: 'Chosen variants and model set', +}; + +export interface ShotView { + id: string; + name: string; + summary: string; + camera: string; + include: Include; + matches: boolean; + missing: string[]; +} + +export interface VariantView { + id: string; + name: string; + active: boolean; + applied: boolean; + swatch: string; + swatches: string[]; + skipped: number; +} + +export interface VariantSetView { + id: string; + name: string; + active: string | null; + parts: number; + covered: number; + variants: VariantView[]; +} + +export interface ModelSetView { + id: string; + name: string; + active: boolean; + applied: boolean; + nodes: number; + shown: number; + missing: number; +} + +export interface DiffView { + changes: Array<{ part: string; from: string; to: string }>; + unchanged: number; + skipped: number; +} + +const obj = (v: unknown): Record => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record : {}); +const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []); +const str = (v: unknown): string => (typeof v === 'string' ? v : typeof v === 'number' ? String(v) : ''); +const HEX = /^#[0-9a-f]{6}$/i; + +function includeOf(v: unknown): Include { + const o = obj(v); + const out = {} as Include; + for (const k of INCLUDE_KEYS) out[k] = o[k] !== false; + return out; +} + +export function shotsOf(reply: unknown): ShotView[] { + const out: ShotView[] = []; + for (const raw of arr(obj(reply).shots)) { + const o = obj(raw); + const id = str(o.id); + if (!id) continue; + out.push({ + id, + name: str(o.name) || id, + summary: str(o.summary), + camera: str(o.camera), + include: includeOf(o.include), + matches: o.matches === true, + missing: arr(o.missing).map(str).filter(Boolean), + }); + } + return out; +} + +function variantOf(raw: unknown): VariantView | null { + const o = obj(raw); + const id = str(o.id); + if (!id) return null; + const swatch = str(o.swatch); + return { + id, + name: str(o.name) || id, + active: o.active === true, + applied: o.applied === true, + swatch: HEX.test(swatch) ? swatch : '', + swatches: arr(o.swatches).map(str).filter((s) => HEX.test(s)), + skipped: typeof o.skipped === 'number' ? o.skipped : 0, + }; +} + +export function setsOf(reply: unknown): VariantSetView[] { + const out: VariantSetView[] = []; + for (const raw of arr(obj(reply).sets)) { + const o = obj(raw); + const id = str(o.id); + if (!id) continue; + const active = str(o.active); + out.push({ + id, + name: str(o.name) || id, + active: active || null, + parts: arr(o.parts).length, + covered: arr(o.covered).length, + variants: arr(o.variants).map(variantOf).filter((v): v is VariantView => v !== null), + }); + } + return out; +} + +export function modelSetsOf(reply: unknown): ModelSetView[] { + const out: ModelSetView[] = []; + for (const raw of arr(obj(reply).model_sets)) { + const o = obj(raw); + const id = str(o.id); + if (!id) continue; + const nodes = arr(o.nodes).map(obj); + out.push({ + id, + name: str(o.name) || id, + active: o.active === true, + applied: o.applied === true, + nodes: nodes.length, + shown: nodes.filter((n) => n.visible === true && n.missing !== true).length, + missing: nodes.filter((n) => n.missing === true).length, + }); + } + return out; +} + +export function diffOf(reply: unknown): DiffView { + const o = obj(reply); + const side = (v: unknown): string => { + const s = obj(v); + return str(s.material_name) || (s.material === null || s.material === undefined ? '' : str(s.material)); + }; + return { + changes: arr(o.changes).map((c) => { + const x = obj(c); + return { part: str(x.name) || str(x.part), from: side(x.from), to: side(x.to) }; + }), + unchanged: arr(o.unchanged).length, + skipped: arr(o.skipped).length, + }; +} + +export function createdString(reply: unknown): string { + const o = obj(reply); + return str(o.id); +} + +export function sameJson(a: unknown, b: unknown): boolean { return JSON.stringify(a) === JSON.stringify(b); } diff --git a/frontend/src/ui/shots/models.ts b/frontend/src/ui/shots/models.ts new file mode 100644 index 00000000..9fb56fad --- /dev/null +++ b/frontend/src/ui/shots/models.ts @@ -0,0 +1,208 @@ +import { el, escapeHtml, patchList, q, setAttr, setClass, setDisabled, setHidden, setStyleVar, setText, setTitle } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { glyph } from './glyphs'; +import { createdString, MODEL_CMD, type ModelSetView } from './model'; +import { ShotsPopover } from './popover'; +import { inlineName, type InlineName } from './rename'; +import { action, type Section } from './shots'; +import { sortable } from './sortable'; +import type { ShotsStore } from './store'; + +export function mountModelSets(host: HTMLElement, ws: Workspace, store: ShotsStore): Section { + const root = el(`
      + +
      + +
      `); + host.appendChild(root); + const list = q(root, '.fsh-models-list'); + const empty = q(root, '.fsh-shots-empty'); + const addBtn = q(root, '.fsh-models-add'); + setAttr(list, 'aria-label', t('Model sets')); + setAttr(q(root, '.fsh-shots-tools'), 'aria-label', t('Model set actions')); + setStyleVar(list, '--fsh-shots-reserve', String(store.remembered.models)); + setClass(list, 'is-reserved', store.remembered.models > 0); + + const names = new WeakMap(); + const models = (): ModelSetView[] => store.ordered('models.order', store.models); + const byId = (id: string): ModelSetView | undefined => store.models.find((m) => m.id === id); + const rowFor = (id: string): HTMLElement | null => list.querySelector(`:scope > [data-key="${CSS.escape(id)}"]`); + const activeId = (): string | null => store.shown('models.active', store.models.find((m) => m.active)?.id ?? null); + + const choose = (id: string): void => { + const m = byId(id); + if (!m || !ws.canRun(MODEL_CMD.select) || (activeId() === id && m.applied)) return; + store.hold('models.active', id); + void store.act(MODEL_CMD.select, { id }); + }; + const rename = (id: string): void => { + const row = rowFor(id); + const m = byId(id); + if (!row || !m || !ws.canRun(MODEL_CMD.set)) return; + row.dataset.editing = 'true'; + names.get(row)?.begin(store.shown(`model.name.${id}`, m.name)); + }; + const move = (id: string, index: number): void => { + if (!ws.canRun(MODEL_CMD.move)) return; + const keys = models().map((m) => m.id).filter((k) => k !== id); + const at = Math.max(0, Math.min(keys.length, index)); + keys.splice(at, 0, id); + store.hold('models.order', keys); + void store.act(MODEL_CMD.move, { id, index: at }); + }; + const nudge = (id: string, by: number): void => { + const at = models().findIndex((m) => m.id === id); + if (at < 0 || at + by < 0 || at + by >= store.models.length) return; + move(id, at + by); + }; + const add = async (): Promise => { + if (!ws.canRun(MODEL_CMD.add)) return; + const before = new Set(store.models.map((m) => m.id)); + const reply = await store.act(MODEL_CMD.add, { name: t('Model set {n}', { n: store.models.length + 1 }) }); + const id = createdString(reply) || store.models.find((m) => !before.has(m.id))?.id || ''; + if (!id) return; + rowFor(id)?.focus(); + rename(id); + }; + const remove = async (id: string): Promise => { + const at = models().findIndex((m) => m.id === id); + await store.act(MODEL_CMD.remove, { id }); + const next = models()[Math.min(at, store.models.length - 1)]; + if (next) rowFor(next.id)?.focus(); + }; + + const menu = new ShotsPopover('fsh-shots-options', t('Model set options')); + menu.root.innerHTML = `
      + + + + + +
      `; + let menuFor = ''; + const paintMenu = (): void => { + if (!menu.isOpen) return; + const at = models().findIndex((m) => m.id === menuFor); + if (at < 0) { menu.close(); return; } + const enable = (act: string, ok: boolean): void => setDisabled(q(menu.root, `[data-act="${act}"]`), !ok); + enable('rename', ws.canRun(MODEL_CMD.set)); + enable('up', at > 0 && ws.canRun(MODEL_CMD.move)); + enable('down', at < store.models.length - 1 && ws.canRun(MODEL_CMD.move)); + enable('remove', ws.canRun(MODEL_CMD.remove)); + }; + const openMenu = (id: string, anchor: HTMLElement): void => { + if (menu.isOpen && menuFor === id) { menu.close(); return; } + menuFor = id; + menu.open(anchor); + paintMenu(); + }; + menu.root.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-act]'); + const id = menuFor; + if (!b || b.disabled || !id) return; + const act = b.dataset.act; + if (act === 'up' || act === 'down') { nudge(id, act === 'up' ? -1 : 1); return; } + menu.close(); + if (act === 'rename') rename(id); + else if (act === 'remove') void remove(id); + }); + + const subOf = (m: ModelSetView): string => { + const base = m.nodes === 1 ? t('Shows 1 node') : t('Shows {n} nodes', { n: m.nodes }); + if (m.missing) return `${base} · ${t('{n} gone', { n: m.missing })}`; + return activeId() === m.id && !m.applied ? `${base} · ${t('changed since it was chosen')}` : base; + }; + + const paintRow = (row: HTMLElement, m: ModelSetView): void => { + const on = activeId() === m.id; + setAttr(row, 'aria-selected', on ? 'true' : 'false'); + setClass(row, 'is-current', on); + setClass(row, 'is-stale', on && !m.applied && m.active); + setText(q(row, '.fsh-shots-name'), store.shown(`model.name.${m.id}`, m.name)); + setText(q(row, '.fsh-shots-sub'), subOf(m)); + const mark = q(row, '.fsh-shots-mark'); + setAttr(mark, 'aria-hidden', on ? null : 'true'); + setTitle(mark, on ? t('Chosen model set') : ''); + }; + + const createRow = (m: ModelSetView): HTMLElement => { + const row = el(`
      +${glyph('grip', 14)} + +${glyph('current', 14)} + +
      `); + const more = q(row, '.fsh-shots-more'); + setAttr(more, 'aria-label', t('Model set options')); + setTitle(more, t('Model set options')); + setAttr(q(row, '.fsh-shots-mark'), 'aria-label', t('Chosen model set')); + const input = q(row, '.fsh-shots-name-input'); + setAttr(input, 'aria-label', t('Model set name')); + names.set(row, inlineName(q(row, '.fsh-shots-name'), input, (name) => { + store.hold(`model.name.${m.id}`, name); + void store.act(MODEL_CMD.set, { id: m.id, name }); + })); + input.addEventListener('blur', () => { delete row.dataset.editing; }); + paintRow(row, m); + return row; + }; + + const update = (): void => { + patchList(list, models(), { key: (m) => m.id, create: createRow, update: paintRow }); + if (store.loaded) setClass(list, 'is-reserved', false); + const ready = ws.client.state === 'ready' && store.loaded; + const msg = !ws.client.has(MODEL_CMD.list) && ws.client.state === 'ready' ? t('This engine has no model sets yet.') + : !ready || store.models.length ? '' + : t('No model sets yet. Show and hide parts until the product looks right, then Add from what is shown.'); + setText(empty, msg); + setHidden(empty, msg === ''); + action(addBtn, 'Add from what is shown', ws.canRun(MODEL_CMD.add), ws.why(MODEL_CMD.add)); + paintMenu(); + }; + + const rowOf = (target: EventTarget | null): HTMLElement | null => { + const row = (target as HTMLElement | null)?.closest('.fsh-shots-row'); + return row && row.parentElement === list ? row : null; + }; + addBtn.addEventListener('click', () => { void add(); }); + list.addEventListener('click', (e) => { + const row = rowOf(e.target); + const id = row?.dataset.key; + if (!row || !id) return; + if ((e.target as HTMLElement).closest('.fsh-shots-more')) { openMenu(id, q(row, '.fsh-shots-more')); return; } + row.focus(); + choose(id); + }); + list.addEventListener('dblclick', (e) => { + const row = rowOf(e.target); + if (row?.dataset.key && (e.target as HTMLElement).closest('.fsh-shots-name')) rename(row.dataset.key); + }); + list.addEventListener('keydown', (e) => { + const row = rowOf(e.target); + const id = row?.dataset.key; + if (!row || !id || e.target !== row) return; + if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && e.altKey) nudge(id, e.key === 'ArrowUp' ? -1 : 1); + else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + const next = (e.key === 'ArrowDown' ? row.nextElementSibling : row.previousElementSibling) as HTMLElement | null; + next?.focus(); + } else if (e.key === 'Enter' || e.key === ' ') choose(id); + else if (e.key === 'F2') rename(id); + else if (e.key === 'Delete' || e.key === 'Backspace') { if (ws.canRun(MODEL_CMD.remove)) void remove(id); } + else if (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey)) openMenu(id, q(row, '.fsh-shots-more')); + else return; + e.preventDefault(); + e.stopPropagation(); + }); + const offSort = sortable(list, { + item: '.fsh-shots-row', handle: '.fsh-shots-grip', axis: 'y', type: 'application/x-formshot-model-set', + onMove: (id, index) => move(id, index), + }); + + update(); + return { update, dispose: () => { menu.dispose(); offSort(); } }; +} diff --git a/frontend/src/ui/shots/popover.ts b/frontend/src/ui/shots/popover.ts new file mode 100644 index 00000000..26c5e508 --- /dev/null +++ b/frontend/src/ui/shots/popover.ts @@ -0,0 +1,63 @@ +import { el, setHidden, setStyleVar } from '../../shell/dom'; + +export class ShotsPopover { + readonly root: HTMLElement; + private anchor: HTMLElement | null = null; + private readonly closeFns = new Set<() => void>(); + private readonly outside = (e: PointerEvent): void => { + const target = e.target as Node; + if (!this.root.contains(target) && !this.anchor?.contains(target)) this.close(); + }; + + constructor(className: string, label: string) { + this.root = el(``); + this.root.setAttribute('aria-label', label); + this.root.addEventListener('keydown', (e) => { + if (e.key !== 'Escape') return; + e.stopPropagation(); + const back = this.anchor; + this.close(); + if (back?.isConnected) back.focus(); + }); + (document.getElementById('overlay-root') ?? document.body).appendChild(this.root); + } + + get isOpen(): boolean { return !this.root.hidden; } + get owner(): HTMLElement | null { return this.isOpen ? this.anchor : null; } + + onClose(fn: () => void): void { this.closeFns.add(fn); } + + open(anchor: HTMLElement): void { + this.anchor = anchor; + setHidden(this.root, false); + this.place(); + document.addEventListener('pointerdown', this.outside, true); + this.root.querySelector('input:not([disabled]), button:not([disabled])')?.focus(); + } + + place(): void { + if (!this.anchor || this.root.hidden) return; + const r = this.anchor.getBoundingClientRect(); + const w = this.root.offsetWidth; + const h = this.root.offsetHeight; + const left = Math.max(8, Math.min(window.innerWidth - w - 8, r.right - w)); + const below = r.bottom + 4; + const top = below + h > window.innerHeight - 8 ? Math.max(8, r.top - h - 4) : below; + setStyleVar(this.root, '--fsh-shots-pop-x', `${Math.round(left)}px`); + setStyleVar(this.root, '--fsh-shots-pop-y', `${Math.round(top)}px`); + } + + toggle(anchor: HTMLElement): void { + if (this.isOpen && this.anchor === anchor) this.close(); + else this.open(anchor); + } + + close(): void { + if (this.root.hidden) return; + setHidden(this.root, true); + document.removeEventListener('pointerdown', this.outside, true); + for (const fn of this.closeFns) fn(); + } + + dispose(): void { this.close(); this.root.remove(); } +} diff --git a/frontend/src/ui/shots/rename.ts b/frontend/src/ui/shots/rename.ts new file mode 100644 index 00000000..8faf762e --- /dev/null +++ b/frontend/src/ui/shots/rename.ts @@ -0,0 +1,38 @@ +import { setHidden } from '../../shell/dom'; + +export interface InlineName { + begin(value: string): void; + editing(): boolean; +} + +export function inlineName(label: HTMLElement, input: HTMLInputElement, commit: (value: string) => void): InlineName { + let start = ''; + let open = false; + const end = (save: boolean): void => { + if (!open) return; + open = false; + const v = input.value.trim(); + setHidden(input, true); + setHidden(label, false); + if (save && v && v !== start) commit(v); + }; + input.addEventListener('keydown', (e) => { + e.stopPropagation(); + if (e.key === 'Enter') { e.preventDefault(); end(true); label.closest('[tabindex]')?.focus(); } + else if (e.key === 'Escape') { e.preventDefault(); end(false); label.closest('[tabindex]')?.focus(); } + }); + input.addEventListener('blur', () => end(true)); + for (const type of ['click', 'dblclick', 'pointerdown'] as const) input.addEventListener(type, (e) => e.stopPropagation()); + return { + begin: (value) => { + start = value; + input.value = value; + open = true; + setHidden(label, true); + setHidden(input, false); + input.focus(); + input.select(); + }, + editing: () => open, + }; +} diff --git a/frontend/src/ui/shots/render.ts b/frontend/src/ui/shots/render.ts new file mode 100644 index 00000000..7a264e94 --- /dev/null +++ b/frontend/src/ui/shots/render.ts @@ -0,0 +1,67 @@ +import { getCommand, runCommand } from '../../shell/registry'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { jobs } from '../render/jobs'; +import { DEFAULT_NAME, nameProblem, output } from '../render/output'; +import { rendersFolder } from '../render/store'; +import { SHOT_CMD } from './model'; + +const OPEN_SETTINGS = 'render.window'; +const OPEN_QUEUE = 'render.queue'; + +export interface RenderOutcome { ok: boolean; text: string } + +const absolute = (p: string): boolean => p.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(p) || p.startsWith('\\\\'); + +export function shotName(template: string, camera: unknown): string { + const s = template.trim() || DEFAULT_NAME; + if (s.includes('{shot}')) return s; + if (s.includes('{camera}')) return s.replace('{camera}', camera === 'all' ? '{shot}_{camera}' : '{shot}'); + return s.includes('_{pass}') ? s.replace('_{pass}', '_{shot}_{pass}') : `${s}_{shot}`; +} + +export function outputFolder(ws: Workspace): string { + return output.value.folder.trim() || rendersFolder(ws.client.summary?.document?.path ?? ''); +} + +export function renderProblem(ws: Workspace): string { + if (!ws.canRun(SHOT_CMD.render)) return ws.why(SHOT_CMD.render); + const folder = outputFolder(ws); + if (!folder) return t('Choose an output folder in Final Render first: this project has not been saved, so it has no folder of its own.'); + if (!absolute(folder)) return t('The output folder must be a full path, such as {example}.', { example: '/Users/me/Renders' }); + return nameProblem(output.value.name); +} + +export function openRenderSettings(): void { + const cmd = getCommand(OPEN_SETTINGS); + if (cmd?.checked?.()) return; + runCommand(OPEN_SETTINGS); +} + +function openQueue(): void { + const cmd = getCommand(OPEN_QUEUE); + if (cmd?.checked?.()) return; + runCommand(OPEN_QUEUE); +} + +export async function renderShots(ws: Workspace, ids: string[] | null): Promise { + const problem = renderProblem(ws); + if (problem) { + openRenderSettings(); + return { ok: false, text: problem }; + } + const args: Record = {}; + if (ids && ids.length) args.ids = ids; + const count = ids?.length ?? 0; + const done = (reply: unknown): string => { + const o = reply && typeof reply === 'object' ? reply as Record : {}; + const made = Array.isArray(o.ids) ? o.ids.length : Array.isArray(o.jobs) ? o.jobs.length : 0; + jobs.poll(0); + openQueue(); + return made === 1 ? t('One shot render added to the queue.') : t('{n} shot renders added to the queue.', { n: made }); + }; + const label = count === 1 ? t('one shot') : count > 1 ? t('{n} shots', { n: count }) : t('every shot'); + const ran = runCommand('render.source', { source: { kind: 'shots', label, command: SHOT_CMD.render, args, name: shotName, done } }); + if (!ran) return { ok: false, text: t('The shots could not be queued.') }; + return { ok: true, text: t('Final Render shows the options; add the shots to the queue there.') }; +} diff --git a/frontend/src/ui/shots/shots.css b/frontend/src/ui/shots/shots.css new file mode 100644 index 00000000..591665da --- /dev/null +++ b/frontend/src/ui/shots/shots.css @@ -0,0 +1,83 @@ +.fsh-shots-block { display: flex; flex-direction: column; } +.fsh-shots-tools { display: flex; align-items: center; gap: var(--space-1); height: var(--ctl-md); margin-bottom: var(--space-2); } +.fsh-shots-tools .fsh-btn { display: inline-flex; align-items: center; gap: var(--space-1); } +.fsh-shots-tools .fsh-icon-btn:disabled { opacity: 0.5; cursor: default; } +.fsh-shots-gap { flex: 1; } +.fsh-shots-render { min-width: 17ch; justify-content: flex-start; } +.fsh-shots-render[aria-busy="true"] { cursor: progress; } +.fsh-shots-status { min-height: calc(var(--fs-11) * 1.5); margin: var(--space-1) 0 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); line-height: 1.5; text-overflow: ellipsis; white-space: nowrap; } +.fsh-shots-status.is-error { color: var(--danger-text); } + +.fsh-shots-list { display: flex; flex-direction: column; gap: 1px; } +.fsh-shots-list.is-reserved { min-height: max(0px, calc(var(--fsh-shots-reserve, 0) * 45px - 1px)); } +.fsh-shots-list.fsh-models-list.is-reserved { min-height: max(0px, calc(var(--fsh-shots-reserve, 0) * 41px - 1px)); } +.fsh-shots-row { position: relative; display: grid; grid-template-columns: 14px minmax(0, 1fr) 16px var(--ctl-md) var(--ctl-md); align-items: center; gap: var(--space-1); height: 44px; padding: 0 var(--space-1) 0 var(--space-1); border-radius: var(--radius-md); color: var(--text-secondary); cursor: pointer; outline: none; user-select: none; } +.fsh-shots-row:hover { background: var(--bg-hover); } +.fsh-shots-row:focus-visible { box-shadow: inset 0 0 0 1px var(--accent-color); } +.fsh-shots-row[aria-selected="true"] { background: var(--accent-tint); color: var(--text-primary); } +.fsh-shots-row.fsh-models-row { grid-template-columns: 14px minmax(0, 1fr) 16px var(--ctl-md); height: 40px; } +.fsh-shots-row.is-stale .fsh-shots-mark { opacity: 0.5; } +.fsh-shots-row.is-pending { opacity: 0.55; cursor: default; pointer-events: none; } +.fsh-shots-row.is-pending[hidden] { display: none; } +.fsh-shots-list:not(:empty) + .fsh-shots-row.is-pending { margin-top: 1px; } +.fsh-shots-row.is-dragging { opacity: 0.45; } +.fsh-shots-row.is-drop-before { box-shadow: inset 0 2px 0 var(--accent-color); } +.fsh-shots-row.is-drop-after { box-shadow: inset 0 -2px 0 var(--accent-color); } +.fsh-shots-grip { display: inline-flex; align-items: center; justify-content: center; width: 14px; height: 24px; color: var(--text-faint); cursor: grab; } +.fsh-shots-row:not(:hover):not(:focus-within) .fsh-shots-grip { opacity: 0.4; } +.fsh-shots-text { display: flex; flex-direction: column; justify-content: center; min-width: 0; height: 100%; line-height: var(--lh-tight); } +.fsh-shots-name { overflow: hidden; color: var(--text-primary); font-size: var(--fs-12); text-overflow: ellipsis; white-space: nowrap; } +.fsh-shots-name[hidden], .fsh-shots-name-input[hidden] { display: none; } +.fsh-shots-name-input { height: 20px; margin: -1px 0 1px; padding: 0 var(--space-1); font-size: var(--fs-12); } +.fsh-shots-sub { overflow: hidden; color: var(--text-faint); font-size: var(--fs-10); text-overflow: ellipsis; white-space: nowrap; } +.fsh-shots-row.is-warn .fsh-shots-sub { color: var(--danger-text); } +.fsh-shots-mark { display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; color: var(--accent-color); visibility: hidden; } +.fsh-shots-row.is-current .fsh-shots-mark { visibility: visible; } +.fsh-shots-row .fsh-icon-btn { width: var(--ctl-md); height: var(--ctl-md); } +.fsh-shots-row .fsh-icon-btn:disabled { opacity: 0.45; cursor: default; } +.fsh-shots-empty { margin: var(--space-1) 0 0; color: var(--text-muted); font-size: var(--fs-12); line-height: var(--lh); } +.fsh-shots-empty[hidden] { display: none; } + +.fsh-var-sets { display: flex; flex-direction: column; gap: var(--space-2); } +.fsh-var-sets.is-reserved { min-height: max(0px, calc(var(--fsh-shots-reserve, 0) * 78px - 8px)); } +.fsh-var-set { display: flex; flex-direction: column; gap: var(--space-1); padding: var(--space-1) var(--space-1) var(--space-2); border: 1px solid var(--line-1); border-radius: var(--radius-md); } +.fsh-var-head { display: grid; grid-template-columns: minmax(0, 1fr) auto var(--ctl-md) var(--ctl-md); align-items: center; gap: var(--space-1); height: var(--ctl-md); padding-left: var(--space-1); } +.fsh-var-head .fsh-icon-btn:disabled { opacity: 0.45; cursor: default; } +.fsh-var-label { display: flex; align-items: center; min-width: 0; } +.fsh-var-name { overflow: hidden; color: var(--text-primary); font-size: var(--fs-12); font-weight: var(--fw-semibold); text-overflow: ellipsis; white-space: nowrap; } +.fsh-var-name[hidden], .fsh-var-name-input[hidden], .fsh-var-chip-name[hidden], .fsh-var-chip-input[hidden] { display: none; } +.fsh-var-name-input { height: 22px; padding: 0 var(--space-1); font-size: var(--fs-12); } +.fsh-var-count { color: var(--text-faint); font-size: var(--fs-10); white-space: nowrap; } +.fsh-var-chips { display: flex; flex-wrap: wrap; gap: var(--space-1); padding: 0 var(--space-1); } +.fsh-var-chip { position: relative; display: inline-flex; align-items: center; gap: 6px; max-width: 100%; height: var(--ctl-sm); padding: 0 var(--space-2) 0 3px; border: 1px solid var(--line-2); border-radius: var(--radius-pill); background: var(--surface-2); color: var(--text-secondary); font-size: var(--fs-11); cursor: pointer; outline: none; user-select: none; } +.fsh-var-chip:hover { background: var(--bg-hover); color: var(--text-primary); } +.fsh-var-chip:focus-visible { box-shadow: 0 0 0 2px var(--accent-color); } +.fsh-var-chip[aria-selected="true"] { border-color: var(--accent-color); background: var(--accent-tint-strong); color: var(--text-primary); } +.fsh-var-chip.is-stale { border-style: dashed; } +.fsh-var-chip.is-dragging { opacity: 0.45; } +.fsh-var-chip.is-drop-before { box-shadow: -3px 0 0 var(--accent-color); } +.fsh-var-chip.is-drop-after { box-shadow: 3px 0 0 var(--accent-color); } +.fsh-var-swatch { flex: none; width: 16px; height: 16px; border: 1px solid var(--line-3); border-radius: 50%; background: linear-gradient(135deg, var(--fsh-var-a, transparent) 50%, var(--fsh-var-b, transparent) 50%); } +.fsh-var-chip-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fsh-var-chip-input { width: 12ch; height: 18px; padding: 0 var(--space-1); border-radius: var(--radius-pill); font-size: var(--fs-11); } +.fsh-var-hint { min-height: calc(var(--fs-11) * 1.5); margin: var(--space-1) 0 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); line-height: 1.5; text-overflow: ellipsis; white-space: nowrap; } +.fsh-var-hint[hidden] { display: none; } +.fsh-var-none { margin: 0 var(--space-1); color: var(--text-muted); font-size: var(--fs-11); } +.fsh-var-none[hidden] { display: none; } + +.fsh-shots-pop { position: fixed; left: var(--fsh-shots-pop-x, 0); top: var(--fsh-shots-pop-y, 0); z-index: var(--z-menu); max-height: min(70vh, 520px); overflow-y: auto; padding: var(--space-1); 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); backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); pointer-events: auto; } +.fsh-shots-pop[hidden] { display: none; } +.fsh-shots-options { width: 250px; } +.fsh-shots-menu { display: flex; flex-direction: column; gap: 1px; } +.fsh-shots-menu-item { display: flex; align-items: center; gap: var(--space-2); height: var(--ctl-md); padding: 0 var(--space-2); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-primary); font: inherit; font-size: var(--fs-12); text-align: left; cursor: pointer; } +.fsh-shots-menu-item > span:not(.fsh-icon) { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fsh-shots-menu-item kbd { color: var(--text-faint); font: var(--fs-10) var(--mono); } +.fsh-shots-menu-item:hover, .fsh-shots-menu-item:focus-visible { background: var(--bg-hover); outline: none; } +.fsh-shots-menu-item:disabled { opacity: 0.45; cursor: default; } +.fsh-shots-menu-item:disabled:hover { background: transparent; } +.fsh-shots-menu-item.is-danger { color: var(--danger-text); } +.fsh-shots-menu-rule { height: 1px; margin: var(--space-1) var(--space-1); background: var(--line-1); } +.fsh-shots-pop-title { margin: var(--space-1) var(--space-2); color: var(--text-faint); font-size: var(--fs-10); font-weight: var(--fw-semibold); letter-spacing: 0.06em; text-transform: uppercase; } +.fsh-shots-flag { display: flex; align-items: center; gap: var(--space-2); height: var(--ctl-sm); padding: 0 var(--space-2); border-radius: var(--radius); color: var(--text-primary); font-size: var(--fs-12); cursor: pointer; } +.fsh-shots-flag:hover { background: var(--bg-hover); } +.fsh-shots-flag input { flex: none; width: 14px; height: 14px; margin: 0; accent-color: var(--accent-color); } diff --git a/frontend/src/ui/shots/shots.ts b/frontend/src/ui/shots/shots.ts new file mode 100644 index 00000000..d0b54850 --- /dev/null +++ b/frontend/src/ui/shots/shots.ts @@ -0,0 +1,382 @@ +import { el, escapeHtml, patchList, q, setAttr, setChecked, setClass, setDisabled, setHidden, setStyleVar, setText, setTitle } from '../../shell/dom'; +import { events } from '../../shell/events'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { glyph } from './glyphs'; +import { createdString, INCLUDE_KEYS, INCLUDE_LABELS, SHOT_CMD, type Include, type IncludeKey, type ShotView } from './model'; +import { ShotsPopover } from './popover'; +import { inlineName, type InlineName } from './rename'; +import { openRenderSettings, renderShots } from './render'; +import { sortable } from './sortable'; +import type { ShotsStore } from './store'; + +const PENDING_MS = 6000; + +export interface Section { update(): void; dispose(): void } + +export interface ShotsSection extends Section { + add(): Promise; + renderAll(): Promise; +} + +export function action(b: HTMLButtonElement, label: string, ok: boolean, why: string): void { + setDisabled(b, !ok); + const text = t(label); + setAttr(b, 'aria-label', text); + setTitle(b, ok || !why ? text : why); +} + +export function mountShots(host: HTMLElement, ws: Workspace, store: ShotsStore): ShotsSection { + const root = el(`
      + +
      + + +

      +
      `); + host.appendChild(root); + const list = q(root, '.fsh-shots-list'); + const pending = q(root, '.fsh-shots-row.is-pending'); + const empty = q(root, '.fsh-shots-empty'); + const addBtn = q(root, '.fsh-shots-add'); + const renderBtn = q(root, '.fsh-shots-render'); + const outputBtn = q(root, '.fsh-shots-output'); + const status = q(root, '.fsh-shots-status'); + let rendering = false; + let statusTimer: number | undefined; + const say = (text: string, error: boolean): void => { + setText(status, text); + setTitle(status, text); + setClass(status, 'is-error', error); + window.clearTimeout(statusTimer); + statusTimer = window.setTimeout(() => { setText(status, ''); setTitle(status, ''); setClass(status, 'is-error', false); }, 8000); + }; + setAttr(list, 'aria-label', t('Shots')); + setAttr(q(root, '.fsh-shots-tools'), 'aria-label', t('Shot actions')); + setStyleVar(list, '--fsh-shots-reserve', String(store.remembered.shots)); + setClass(list, 'is-reserved', store.remembered.shots > 0); + + const selected = new Set(); + let revealing = ''; + const names = new WeakMap(); + const rowFor = (id: string): HTMLElement | null => list.querySelector(`:scope > [data-key="${CSS.escape(id)}"]`); + const rename = (id: string): void => { + const row = rowFor(id); + const s = byId(id); + if (!row || !s || !ws.canRun(SHOT_CMD.set)) return; + row.dataset.editing = 'true'; + names.get(row)?.begin(store.shown(`shot.name.${id}`, s.name)); + }; + const commitName = (id: string, name: string): void => { + store.hold(`shot.name.${id}`, name); + void store.act(SHOT_CMD.set, { id, name }); + }; + + const menu = new ShotsPopover('fsh-shots-options', t('Shot options')); + menu.root.innerHTML = `
      + + + + + + +

      ${escapeHtml(t('Applying the shot restores'))}

      +${INCLUDE_KEYS.map((k) => ``).join('')} + + +
      `; + let menuFor = ''; + const paintMenu = (): void => { + if (!menu.isOpen) return; + const s = byId(menuFor); + if (!s) { menu.close(); return; } + const keys = shots().map((x) => x.id); + const at = keys.indexOf(s.id); + const can = (b: string, ok: boolean, why = ''): void => { + const btn = q(menu.root, `[data-act="${b}"]`); + setDisabled(btn, !ok); + setTitle(btn, ok ? '' : why); + }; + can('rename', ws.canRun(SHOT_CMD.set), ws.why(SHOT_CMD.set)); + can('recapture', ws.canRun(SHOT_CMD.update), ws.why(SHOT_CMD.update)); + can('duplicate', ws.canRun(SHOT_CMD.duplicate), ws.why(SHOT_CMD.duplicate)); + can('up', at > 0 && ws.canRun(SHOT_CMD.move), ws.why(SHOT_CMD.move)); + can('down', at >= 0 && at < keys.length - 1 && ws.canRun(SHOT_CMD.move), ws.why(SHOT_CMD.move)); + can('remove', ws.canRun(SHOT_CMD.remove), ws.why(SHOT_CMD.remove)); + const flags = store.shown(`shot.include.${s.id}`, s.include); + for (const box of menu.root.querySelectorAll('input[data-flag]')) { + setChecked(box, flags[box.dataset.flag as IncludeKey]); + setDisabled(box, !ws.canRun(SHOT_CMD.set)); + } + }; + const openMenu = (id: string, anchor: HTMLElement): void => { + if (menu.isOpen && menuFor === id) { menu.close(); return; } + menuFor = id; + menu.open(anchor); + paintMenu(); + menu.place(); + }; + const move = (id: string, index: number): void => { + const keys = shots().map((s) => s.id).filter((k) => k !== id); + const at = Math.max(0, Math.min(keys.length, index)); + keys.splice(at, 0, id); + store.hold('shots.order', keys); + void store.act(SHOT_CMD.move, { id, index: at }); + }; + const nudge = (id: string, by: number): void => { + const at = shots().findIndex((s) => s.id === id); + if (at < 0 || at + by < 0 || at + by >= store.shots.length) return; + move(id, at + by); + }; + const remove = async (id: string): Promise => { + const keys = shots().map((s) => s.id); + const at = keys.indexOf(id); + await store.act(SHOT_CMD.remove, { id }); + selected.delete(id); + const next = shots()[Math.min(at, store.shots.length - 1)]; + if (next) rowFor(next.id)?.focus(); + update(); + }; + const duplicate = async (id: string): Promise => { + const before = new Set(store.shots.map((s) => s.id)); + const reply = await store.act(SHOT_CMD.duplicate, { id }); + const made = createdString(reply) || store.shots.find((s) => !before.has(s.id))?.id || ''; + if (!made) return; + rowFor(made)?.focus(); + }; + menu.root.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-act]'); + const id = menuFor; + if (!b || !id || b.disabled) return; + const act = b.dataset.act; + if (act === 'up' || act === 'down') { nudge(id, act === 'up' ? -1 : 1); return; } + menu.close(); + if (act === 'rename') rename(id); + else if (act === 'recapture') void store.act(SHOT_CMD.update, { id }); + else if (act === 'duplicate') void duplicate(id); + else if (act === 'remove') void remove(id); + }); + menu.root.addEventListener('change', (e) => { + const box = (e.target as HTMLElement).closest('input[data-flag]'); + const s = byId(menuFor); + if (!box || !s) return; + const flag = box.dataset.flag as IncludeKey; + const next = { ...store.shown(`shot.include.${s.id}`, s.include), [flag]: box.checked }; + store.hold(`shot.include.${s.id}`, next); + void store.act(SHOT_CMD.set, { id: s.id, include: { [flag]: box.checked } }); + }); + let pendingTimer: number | undefined; + let adding = false; + + const shots = (): ShotView[] => store.ordered('shots.order', store.shots); + const byId = (id: string): ShotView | undefined => store.shots.find((s) => s.id === id); + + const endPending = (): void => { + window.clearTimeout(pendingTimer); + adding = false; + setHidden(pending, true); + }; + const beginPending = (): void => { + setText(q(pending, '.fsh-shots-name'), t('Shot {n}', { n: store.shots.length + 1 })); + setText(q(pending, '.fsh-shots-sub'), t('Capturing the view')); + adding = true; + setHidden(pending, false); + setHidden(empty, true); + window.clearTimeout(pendingTimer); + pendingTimer = window.setTimeout(() => { endPending(); update(); }, PENDING_MS); + }; + + const apply = async (id: string): Promise => { + const s = byId(id); + if (!s || !ws.canRun(SHOT_CMD.apply)) return; + const reply = await store.act(SHOT_CMD.apply, { id }); + const o = reply && typeof reply === 'object' ? reply as Record : {}; + const skipped = Array.isArray(o.skipped) ? o.skipped.length : 0; + if (skipped) ws.ctx.toast(t('{name} applied; {n} nodes it names are gone and were skipped.', { name: s.name, n: skipped }), 'info'); + }; + + const add = async (): Promise => { + if (adding || !ws.canRun(SHOT_CMD.add)) return; + const before = new Set(store.shots.map((s) => s.id)); + beginPending(); + const reply = await store.act(SHOT_CMD.add, {}); + endPending(); + const id = createdString(reply) || store.shots.find((s) => !before.has(s.id))?.id || ''; + update(); + if (!id) return; + rowFor(id)?.focus(); + rename(id); + }; + + const paintRow = (row: HTMLElement, s: ShotView): void => { + setAttr(row, 'aria-selected', selected.has(s.id) ? 'true' : 'false'); + setText(q(row, '.fsh-shots-name'), store.shown(`shot.name.${s.id}`, s.name)); + const sub = s.missing.length ? `${t('{n} nodes it names are gone', { n: s.missing.length })} · ${s.summary}` : s.summary; + setText(q(row, '.fsh-shots-sub'), sub); + setTitle(q(row, '.fsh-shots-text'), sub); + setClass(row, 'is-warn', s.missing.length > 0); + setClass(row, 'is-current', s.matches); + const mark = q(row, '.fsh-shots-mark'); + setAttr(mark, 'aria-hidden', s.matches ? null : 'true'); + setTitle(mark, s.matches ? t('The document matches this shot') : ''); + action(q(row, '.fsh-shots-apply'), 'Apply shot', ws.canRun(SHOT_CMD.apply), ws.why(SHOT_CMD.apply)); + }; + + const createRow = (s: ShotView): HTMLElement => { + const row = el(`
      +${glyph('grip', 14)} + +${glyph('current', 14)} + + +
      `); + const more = q(row, '.fsh-shots-more'); + setAttr(more, 'aria-label', t('Shot options')); + setTitle(more, t('Shot options')); + setAttr(q(row, '.fsh-shots-mark'), 'aria-label', t('Current')); + const input = q(row, '.fsh-shots-name-input'); + setAttr(input, 'aria-label', t('Shot name')); + names.set(row, inlineName(q(row, '.fsh-shots-name'), input, (v) => commitName(s.id, v))); + input.addEventListener('blur', () => { delete row.dataset.editing; }); + paintRow(row, s); + return row; + }; + + const update = (): void => { + const all = shots(); + for (const id of [...selected]) if (!byId(id)) selected.delete(id); + patchList(list, all, { key: (s) => s.id, create: createRow, update: paintRow }); + if (store.loaded) setClass(list, 'is-reserved', false); + const ready = ws.client.state === 'ready' && store.loaded; + const msg = !ws.client.has(SHOT_CMD.list) && ws.client.state === 'ready' ? t('This engine has no shots yet.') + : !ready || adding || all.length ? '' + : t('No shots yet. Set up the view, then Add shot keeps the camera, image style, environment, lights and render settings under a name.'); + setText(empty, msg); + setHidden(empty, msg === ''); + action(addBtn, 'Add shot', ws.canRun(SHOT_CMD.add) && !adding, ws.why(SHOT_CMD.add)); + const label = selected.size ? 'Render selected shots' : 'Render all shots'; + setText(q(renderBtn, '.fsh-shots-render-label'), t(label)); + action(renderBtn, label, all.length > 0 && !rendering && ws.canRun(SHOT_CMD.render), all.length ? ws.why(SHOT_CMD.render) : t('Add a shot first')); + setAttr(renderBtn, 'aria-busy', rendering ? 'true' : null); + action(outputBtn, 'Final Render settings', true, ''); + paintMenu(); + if (revealing && store.loaded) { const id = revealing; revealing = ''; reveal(id); } + }; + + const render = async (ids: string[] | null): Promise => { + if (rendering || !store.shots.length) return; + rendering = true; + update(); + try { + const out = await renderShots(ws, ids); + say(out.text, !out.ok); + } finally { + rendering = false; + update(); + } + }; + + const rowOf = (target: EventTarget | null): HTMLElement | null => { + const row = (target as HTMLElement | null)?.closest('.fsh-shots-row'); + return row && row.parentElement === list ? row : null; + }; + let anchor = ''; + const pick = (id: string, e: MouseEvent | KeyboardEvent): void => { + const keys = shots().map((s) => s.id); + if (e.shiftKey && anchor && keys.includes(anchor)) { + const [a, b] = [keys.indexOf(anchor), keys.indexOf(id)].sort((x, y) => x - y); + selected.clear(); + for (const k of keys.slice(a, b + 1)) selected.add(k); + } else if (e.metaKey || e.ctrlKey) { + if (selected.has(id)) selected.delete(id); else selected.add(id); + anchor = id; + } else { + selected.clear(); + selected.add(id); + anchor = id; + } + update(); + }; + const reveal = (id: string): void => { + const row = rowFor(id); + if (!row) return; + revealing = ''; + selected.clear(); + selected.add(id); + anchor = id; + update(); + row.scrollIntoView({ block: 'nearest' }); + row.focus(); + }; + const offReveal = events.on('ui.shots.reveal', (e) => { + if (e.kind !== 'shot' || typeof e.id !== 'string') return; + revealing = e.id; + reveal(e.id); + }); + + addBtn.addEventListener('click', () => { void add(); }); + renderBtn.addEventListener('click', () => { + const ids = shots().map((s) => s.id).filter((id) => selected.has(id)); + void render(ids.length ? ids : null); + }); + outputBtn.addEventListener('click', () => openRenderSettings()); + list.addEventListener('click', (e) => { + const row = rowOf(e.target); + const id = row?.dataset.key; + if (!row || !id) return; + if ((e.target as HTMLElement).closest('.fsh-shots-apply')) { void apply(id); return; } + if ((e.target as HTMLElement).closest('.fsh-shots-more')) { openMenu(id, q(row, '.fsh-shots-more')); return; } + row.focus(); + pick(id, e); + }); + list.addEventListener('dblclick', (e) => { + const row = rowOf(e.target); + if (!row?.dataset.key || (e.target as HTMLElement).closest('button')) return; + void apply(row.dataset.key); + }); + list.addEventListener('keydown', (e) => { + const row = rowOf(e.target); + const id = row?.dataset.key; + if (!row || !id || e.target !== row) return; + if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && e.altKey) { + nudge(id, e.key === 'ArrowUp' ? -1 : 1); + } else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + const next = (e.key === 'ArrowDown' ? row.nextElementSibling : row.previousElementSibling) as HTMLElement | null; + if (next?.dataset.key) { next.focus(); pick(next.dataset.key, e); } + } else if (e.key === 'F2') { + rename(id); + } else if (e.key === 'Delete' || e.key === 'Backspace') { + if (ws.canRun(SHOT_CMD.remove)) void remove(id); + } else if (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey)) { + openMenu(id, q(row, '.fsh-shots-more')); + } else if (e.key === 'Enter') { + void apply(id); + } else if (e.key === ' ') { + pick(id, e); + } else if (e.key === 'Escape' && selected.size) { + selected.clear(); + update(); + } else return; + e.preventDefault(); + e.stopPropagation(); + }); + + const offSort = sortable(list, { + item: '.fsh-shots-row', handle: '.fsh-shots-grip', axis: 'y', type: 'application/x-formshot-shot', + onMove: (id, index) => { if (ws.canRun(SHOT_CMD.move)) move(id, index); }, + }); + + update(); + return { + update, + add, + renderAll: () => render(null), + dispose: () => { window.clearTimeout(pendingTimer); window.clearTimeout(statusTimer); menu.dispose(); offSort(); offReveal(); }, + }; +} diff --git a/frontend/src/ui/shots/sortable.ts b/frontend/src/ui/shots/sortable.ts new file mode 100644 index 00000000..5d15bea8 --- /dev/null +++ b/frontend/src/ui/shots/sortable.ts @@ -0,0 +1,102 @@ +import { setAttr, setClass } from '../../shell/dom'; + +export interface SortOptions { + item: string; + handle?: string; + axis: 'x' | 'y'; + type: string; + onMove: (key: string, index: number) => void; +} + +export function moveIndex(keys: readonly string[], key: string, target: string, after: boolean): number { + const from = keys.indexOf(key); + let to = keys.indexOf(target) + (after ? 1 : 0); + if (from >= 0 && from < to) to -= 1; + return Math.max(0, to); +} + +export function sortable(list: HTMLElement, o: SortOptions): () => void { + let dragging: HTMLElement | null = null; + let mark: HTMLElement | null = null; + const items = (): HTMLElement[] => Array.from(list.querySelectorAll(`:scope > ${o.item}`)); + const clearMark = (): void => { + if (!mark) return; + setClass(mark, 'is-drop-before', false); + setClass(mark, 'is-drop-after', false); + mark = null; + }; + const hit = (e: DragEvent): { node: HTMLElement; after: boolean } | null => { + const node = (e.target as HTMLElement | null)?.closest(o.item); + if (!node || node.parentElement !== list) return null; + const r = node.getBoundingClientRect(); + const after = o.axis === 'y' ? e.clientY > r.top + r.height / 2 : e.clientX > r.left + r.width / 2; + return { node, after }; + }; + + const down = (e: PointerEvent): void => { + const node = (e.target as HTMLElement).closest(o.item); + if (!node || node.parentElement !== list || node.dataset.editing === 'true') return; + if (o.handle && !(e.target as HTMLElement).closest(o.handle)) return; + setAttr(node, 'draggable', 'true'); + }; + const start = (e: DragEvent): void => { + const node = (e.target as HTMLElement).closest(o.item); + if (!node || node.parentElement !== list || !node.dataset.key) return; + dragging = node; + setClass(node, 'is-dragging', true); + if (e.dataTransfer) { + e.dataTransfer.effectAllowed = 'move'; + e.dataTransfer.setData(o.type, node.dataset.key); + e.dataTransfer.setData('text/plain', node.dataset.key); + } + }; + const over = (e: DragEvent): void => { + if (!dragging) return; + const h = hit(e); + e.preventDefault(); + if (e.dataTransfer) e.dataTransfer.dropEffect = 'move'; + if (!h || h.node === dragging) { clearMark(); return; } + if (mark !== h.node) clearMark(); + mark = h.node; + setClass(h.node, 'is-drop-before', !h.after); + setClass(h.node, 'is-drop-after', h.after); + }; + const drop = (e: DragEvent): void => { + if (!dragging) return; + e.preventDefault(); + const h = hit(e); + const key = dragging.dataset.key ?? ''; + finish(); + if (!h || !h.node.dataset.key || h.node.dataset.key === key) return; + const keys = items().map((n) => n.dataset.key ?? ''); + const index = moveIndex(keys, key, h.node.dataset.key, h.after); + if (index !== keys.indexOf(key)) o.onMove(key, index); + }; + const finish = (): void => { + clearMark(); + if (dragging) { setClass(dragging, 'is-dragging', false); setAttr(dragging, 'draggable', null); } + dragging = null; + }; + const leave = (e: DragEvent): void => { if (!list.contains(e.relatedTarget as Node | null)) clearMark(); }; + const up = (e: PointerEvent): void => { + const node = (e.target as HTMLElement).closest(o.item); + if (node && !dragging) setAttr(node, 'draggable', null); + }; + + list.addEventListener('pointerdown', down); + list.addEventListener('pointerup', up); + list.addEventListener('dragstart', start); + list.addEventListener('dragover', over); + list.addEventListener('dragleave', leave); + list.addEventListener('drop', drop); + list.addEventListener('dragend', finish); + return () => { + list.removeEventListener('pointerdown', down); + list.removeEventListener('pointerup', up); + list.removeEventListener('dragstart', start); + list.removeEventListener('dragover', over); + list.removeEventListener('dragleave', leave); + list.removeEventListener('drop', drop); + list.removeEventListener('dragend', finish); + }; +} diff --git a/frontend/src/ui/shots/store.ts b/frontend/src/ui/shots/store.ts new file mode 100644 index 00000000..938879c2 --- /dev/null +++ b/frontend/src/ui/shots/store.ts @@ -0,0 +1,117 @@ +import type { Workspace } from '../context'; +import { + MODEL_CMD, modelSetsOf, SHOT_CMD, setsOf, shotsOf, VARIANT_CMD, + type ModelSetView, type ShotView, type VariantSetView, +} from './model'; + +const BARRIER = 'history.barrier'; +const HOLD_MS = 2000; +const COUNTS_KEY = 'formshot.shots.counts'; + +export interface Counts { shots: number; sets: number; models: number } + +function readCounts(): Counts { + try { + const v = JSON.parse(localStorage.getItem(COUNTS_KEY) ?? 'null') as Partial | null; + const n = (x: unknown): number => (typeof x === 'number' && Number.isFinite(x) ? Math.min(12, Math.max(0, Math.round(x))) : 0); + return { shots: n(v?.shots), sets: n(v?.sets), models: n(v?.models) }; + } catch { + return { shots: 0, sets: 0, models: 0 }; + } +} + +export class ShotsStore { + shots: ShotView[] = []; + sets: VariantSetView[] = []; + models: ModelSetView[] = []; + loaded = false; + error = ''; + readonly remembered: Counts = readCounts(); + private readonly fns = new Set<() => void>(); + private readonly held = new Map(); + private timer = 0; + private seq = 0; + private revision = -1; + private stale = true; + + constructor(private readonly ws: Workspace, private readonly visible: () => boolean) {} + + onChange(fn: () => void): () => void { this.fns.add(fn); return () => { this.fns.delete(fn); }; } + changed(): void { for (const fn of this.fns) fn(); } + + has(name: string): boolean { return this.ws.canRun(name); } + + follow(): void { + const rev = this.ws.client.summary?.revision ?? -1; + if (rev === this.revision && !this.stale) return; + this.revision = rev; + this.stale = true; + if (this.visible()) this.schedule(60); + } + + wake(): void { if (this.stale && this.visible()) this.schedule(0); } + + schedule(delay = 60): void { + window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => void this.reload(), delay); + } + + async reload(): Promise { + const client = this.ws.client; + if (client.state !== 'ready' || !client.catalogue().length || !client.summary) { this.stale = true; return; } + const seq = ++this.seq; + this.stale = false; + const read = (name: string): Promise => (client.has(name) ? client.dispatch(name, {}) : Promise.resolve(null)); + try { + const [shots, sets, models] = await Promise.all([read(SHOT_CMD.list), read(VARIANT_CMD.list), read(MODEL_CMD.list)]); + if (seq !== this.seq) return; + this.shots = shotsOf(shots); + this.sets = setsOf(sets); + this.models = modelSetsOf(models); + this.error = ''; + this.loaded = true; + if (client.has(SHOT_CMD.list)) this.remember(); + } catch (err) { + if (seq !== this.seq) return; + this.error = err instanceof Error ? err.message : String(err); + } + this.changed(); + } + + async act(name: string, args: Record): Promise { + const out = await this.ws.run(name, args); + if (out !== undefined && this.ws.canRun(BARRIER)) await this.ws.client.dispatch(BARRIER, {}).catch(() => undefined); + await this.reload(); + return out; + } + + hold(key: string, value: unknown): void { + this.held.set(key, { value, until: performance.now() + HOLD_MS }); + this.changed(); + } + + drop(key: string): void { if (this.held.delete(key)) this.changed(); } + + shown(key: string, engine: T): T { + const h = this.held.get(key); + if (!h) return engine; + if (performance.now() > h.until || JSON.stringify(h.value) === JSON.stringify(engine)) { this.held.delete(key); return engine; } + return h.value as T; + } + + ordered(key: string, items: T[]): T[] { + const order = this.shown(key, items.map((i) => i.id)); + if (!order) return items; + const byId = new Map(items.map((i) => [i.id, i])); + const out = order.map((id) => byId.get(id)).filter((i): i is T => i !== undefined); + for (const i of items) if (!order.includes(i.id)) out.push(i); + return out; + } + + dispose(): void { window.clearTimeout(this.timer); this.fns.clear(); } + + private remember(): void { + const c = { shots: this.shots.length, sets: this.sets.length, models: this.models.length }; + try { localStorage.setItem(COUNTS_KEY, JSON.stringify(c)); } catch { return; } + } +} diff --git a/frontend/src/ui/shots/variants.ts b/frontend/src/ui/shots/variants.ts new file mode 100644 index 00000000..35c9b90d --- /dev/null +++ b/frontend/src/ui/shots/variants.ts @@ -0,0 +1,371 @@ +import { el, escapeHtml, patchList, q, setAttr, setClass, setDisabled, setHidden, setStyleVar, setText, setTitle } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { glyph } from './glyphs'; +import { createdString, diffOf, VARIANT_CMD, type DiffView, type VariantSetView, type VariantView } from './model'; +import { ShotsPopover } from './popover'; +import { inlineName, type InlineName } from './rename'; +import { action, type Section } from './shots'; +import { sortable } from './sortable'; +import type { ShotsStore } from './store'; + +const PART_KINDS = new Set(['part', 'group']); +const NEUTRAL = '#8a8a8a'; + +export function mountVariants(host: HTMLElement, ws: Workspace, store: ShotsStore): Section { + const root = el(`
      + +
      +

      + +
      `); + host.appendChild(root); + const setsHost = q(root, '.fsh-var-sets'); + const empty = q(root, '.fsh-shots-empty'); + const addBtn = q(root, '.fsh-var-add'); + setAttr(q(root, '.fsh-shots-tools'), 'aria-label', t('Variant set actions')); + setStyleVar(setsHost, '--fsh-shots-reserve', String(store.remembered.sets)); + setClass(setsHost, 'is-reserved', store.remembered.sets > 0); + + const sets = (): VariantSetView[] => store.ordered('variants.order', store.sets); + const setById = (id: string): VariantSetView | undefined => store.sets.find((s) => s.id === id); + const blockFor = (id: string): HTMLElement | null => setsHost.querySelector(`:scope > [data-key="${CSS.escape(id)}"]`); + + const selectedParts = (): Array => { + const s = ws.client.summary; + if (!s) return []; + const kinds = new Map(s.nodes.map((n) => [String(n.id), n.kind])); + return s.selection.filter((id) => PART_KINDS.has(kinds.get(String(id)) ?? '')); + }; + + const activeOf = (set: VariantSetView): string | null => store.shown(`variant.active.${set.id}`, set.active); + + const choose = (setId: string, variant: string): void => { + const set = setById(setId); + if (!set || !ws.canRun(VARIANT_CMD.select)) return; + if (activeOf(set) === variant && set.variants.find((v) => v.id === variant)?.applied) return; + store.hold(`variant.active.${setId}`, variant); + void store.act(VARIANT_CMD.select, { set: setId, variant }); + }; + + const capture = async (setId: string): Promise => { + const set = setById(setId); + if (!set || !ws.canRun(VARIANT_CMD.capture)) return; + await store.act(VARIANT_CMD.capture, { set: setId }); + }; + + const addSet = async (): Promise => { + const parts = selectedParts(); + if (!parts.length || !ws.canRun(VARIANT_CMD.addSet)) return; + const before = new Set(store.sets.map((s) => s.id)); + const reply = await store.act(VARIANT_CMD.addSet, { name: t('Variant set {n}', { n: store.sets.length + 1 }), parts }); + const id = createdString(reply) || store.sets.find((s) => !before.has(s.id))?.id || ''; + if (id) blockFor(id)?.querySelector('.fsh-var-capture')?.focus(); + }; + + const names = new WeakMap(); + const chipFor = (setId: string, id: string): HTMLElement | null => blockFor(setId)?.querySelector(`.fsh-var-chip[data-key="${CSS.escape(id)}"]`) ?? null; + const renameSet = (setId: string): void => { + const block = blockFor(setId); + const set = setById(setId); + if (!block || !set || !ws.canRun(VARIANT_CMD.setSet)) return; + names.get(block)?.begin(store.shown(`variant.set.name.${setId}`, set.name)); + }; + const renameVariant = (setId: string, id: string): void => { + const chip = chipFor(setId, id); + const v = setById(setId)?.variants.find((x) => x.id === id); + if (!chip || !v || !ws.canRun(VARIANT_CMD.set)) return; + chip.dataset.editing = 'true'; + names.get(chip)?.begin(store.shown(`variant.name.${setId}.${id}`, v.name)); + }; + const moveVariant = (setId: string, id: string, index: number): void => { + const set = setById(setId); + if (!set || !ws.canRun(VARIANT_CMD.move)) return; + const keys = store.ordered(`variant.order.${setId}`, set.variants).map((v) => v.id).filter((k) => k !== id); + const at = Math.max(0, Math.min(keys.length, index)); + keys.splice(at, 0, id); + store.hold(`variant.order.${setId}`, keys); + void store.act(VARIANT_CMD.move, { set: setId, id, index: at }); + }; + const moveSet = (setId: string, by: number): void => { + const keys = sets().map((s) => s.id); + const from = keys.indexOf(setId); + const at = from + by; + if (from < 0 || at < 0 || at >= keys.length || !ws.canRun(VARIANT_CMD.move)) return; + keys.splice(from, 1); + keys.splice(at, 0, setId); + store.hold('variants.order', keys); + void store.act(VARIANT_CMD.move, { set: setId, index: at }); + }; + + const setMenu = new ShotsPopover('fsh-shots-options', t('Variant set options')); + setMenu.root.innerHTML = `
      + + + + + + +
      `; + const variantMenu = new ShotsPopover('fsh-shots-options', t('Variant options')); + variantMenu.root.innerHTML = `
      + + + + + +
      `; + let menuSet = ''; + let menuVariant = ''; + const enable = (pop: ShotsPopover, act: string, ok: boolean): void => setDisabled(q(pop.root, `[data-act="${act}"]`), !ok); + const paintMenus = (): void => { + const set = setById(menuSet); + if (setMenu.isOpen) { + if (!set) setMenu.close(); + else { + const at = sets().findIndex((s) => s.id === set.id); + enable(setMenu, 'rename', ws.canRun(VARIANT_CMD.setSet)); + enable(setMenu, 'capture', ws.canRun(VARIANT_CMD.capture)); + enable(setMenu, 'up', at > 0 && ws.canRun(VARIANT_CMD.move)); + enable(setMenu, 'down', at < store.sets.length - 1 && ws.canRun(VARIANT_CMD.move)); + enable(setMenu, 'remove', ws.canRun(VARIANT_CMD.removeSet)); + } + } + if (variantMenu.isOpen) { + const order = set ? store.ordered(`variant.order.${set.id}`, set.variants).map((v) => v.id) : []; + const at = order.indexOf(menuVariant); + if (at < 0) variantMenu.close(); + else { + enable(variantMenu, 'rename', ws.canRun(VARIANT_CMD.set)); + enable(variantMenu, 'left', at > 0 && ws.canRun(VARIANT_CMD.move)); + enable(variantMenu, 'right', at < order.length - 1 && ws.canRun(VARIANT_CMD.move)); + enable(variantMenu, 'remove', ws.canRun(VARIANT_CMD.remove)); + } + } + }; + const openSetMenu = (setId: string, anchor: HTMLElement): void => { + if (setMenu.isOpen && menuSet === setId) { setMenu.close(); return; } + variantMenu.close(); + menuSet = setId; + setMenu.open(anchor); + paintMenus(); + }; + const openVariantMenu = (setId: string, id: string, anchor: HTMLElement): void => { + setMenu.close(); + menuSet = setId; + menuVariant = id; + variantMenu.open(anchor); + paintMenus(); + }; + setMenu.root.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-act]'); + const id = menuSet; + if (!b || b.disabled || !id) return; + const act = b.dataset.act; + if (act === 'up' || act === 'down') { moveSet(id, act === 'up' ? -1 : 1); return; } + setMenu.close(); + if (act === 'rename') renameSet(id); + else if (act === 'capture') void capture(id); + else if (act === 'remove') void store.act(VARIANT_CMD.removeSet, { set: id }); + }); + variantMenu.root.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-act]'); + const setId = menuSet, id = menuVariant; + if (!b || b.disabled || !setId || !id) return; + const act = b.dataset.act; + const set = setById(setId); + if ((act === 'left' || act === 'right') && set) { + const at = store.ordered(`variant.order.${setId}`, set.variants).findIndex((v) => v.id === id); + moveVariant(setId, id, at + (act === 'left' ? -1 : 1)); + return; + } + variantMenu.close(); + if (act === 'rename') renameVariant(setId, id); + else if (act === 'remove') void store.act(VARIANT_CMD.remove, { set: setId, id }); + }); + + const paintChip = (chip: HTMLElement, v: VariantView, set: VariantSetView): void => { + const on = activeOf(set) === v.id; + setAttr(chip, 'aria-selected', on ? 'true' : 'false'); + setAttr(chip, 'tabindex', on || (!activeOf(set) && set.variants[0]?.id === v.id) ? '0' : '-1'); + setClass(chip, 'is-stale', on && !v.applied && set.active === v.id); + setText(q(chip, '.fsh-var-chip-name'), store.shown(`variant.name.${set.id}.${v.id}`, v.name)); + const a = v.swatches[0] ?? (v.swatch || NEUTRAL); + const b = v.swatches[1] ?? a; + const sw = q(chip, '.fsh-var-swatch'); + setStyleVar(sw, '--fsh-var-a', a); + setStyleVar(sw, '--fsh-var-b', b); + const tip = on && !v.applied ? t('{name} is chosen, but the parts have been changed since', { name: v.name }) : v.name; + setTitle(chip, tip); + }; + + const createChip = (v: VariantView, set: VariantSetView): HTMLElement => { + const chip = el(`
      `); + const input = q(chip, '.fsh-var-chip-input'); + setAttr(input, 'aria-label', t('Variant name')); + names.set(chip, inlineName(q(chip, '.fsh-var-chip-name'), input, (name) => { + store.hold(`variant.name.${set.id}.${v.id}`, name); + void store.act(VARIANT_CMD.set, { set: set.id, id: v.id, name }); + })); + input.addEventListener('blur', () => { delete chip.dataset.editing; }); + paintChip(chip, v, set); + return chip; + }; + + const paintSet = (block: HTMLElement, set: VariantSetView): void => { + const name = store.shown(`variant.set.name.${set.id}`, set.name); + setText(q(block, '.fsh-var-name'), name); + setText(q(block, '.fsh-var-count'), set.covered === 1 ? t('1 part') : t('{n} parts', { n: set.covered })); + const chips = q(block, '.fsh-var-chips'); + setAttr(chips, 'aria-label', name); + const more = q(block, '.fsh-var-more'); + setAttr(more, 'aria-label', t('Variant set options')); + setTitle(more, t('Variant set options')); + patchList(chips, store.ordered(`variant.order.${set.id}`, set.variants), { key: (v) => v.id, create: (v) => createChip(v, set), update: (c, v) => paintChip(c, v, set) }); + const none = q(block, '.fsh-var-none'); + setHidden(none, set.variants.length > 0); + action(q(block, '.fsh-var-capture'), 'Capture variant from the parts', ws.canRun(VARIANT_CMD.capture), ws.why(VARIANT_CMD.capture)); + }; + + const createSet = (set: VariantSetView): HTMLElement => { + const block = el(`
      +
      + + + + +
      +
      + +
      `); + setText(q(block, '.fsh-var-none'), t('No variants yet: dress the parts, then capture one.')); + const input = q(block, '.fsh-var-name-input'); + setAttr(input, 'aria-label', t('Variant set name')); + names.set(block, inlineName(q(block, '.fsh-var-name'), input, (name) => { + store.hold(`variant.set.name.${set.id}`, name); + void store.act(VARIANT_CMD.setSet, { set: set.id, name }); + })); + const chips = q(block, '.fsh-var-chips'); + sortable(chips, { + item: '.fsh-var-chip', axis: 'x', type: 'application/x-formshot-variant', + onMove: (id, index) => moveVariant(set.id, id, index), + }); + paintSet(block, set); + return block; + }; + + const update = (): void => { + patchList(setsHost, sets(), { key: (s) => s.id, create: createSet, update: paintSet }); + if (store.loaded) setClass(setsHost, 'is-reserved', false); + const ready = ws.client.state === 'ready' && store.loaded; + const msg = !ws.client.has(VARIANT_CMD.list) && ws.client.state === 'ready' ? t('This engine has no material variants yet.') + : !ready || store.sets.length ? '' + : t('No variant sets yet. Select the parts that change between looks, then Add set from selection.'); + setText(empty, msg); + setHidden(empty, msg === ''); + setHidden(hint, (store.loaded ? store.sets.length : store.remembered.sets) === 0); + const parts = selectedParts(); + action(addBtn, 'Add set from selection', parts.length > 0 && ws.canRun(VARIANT_CMD.addSet), + parts.length ? ws.why(VARIANT_CMD.addSet) : t('Select one or more parts or groups first')); + paintMenus(); + }; + + const chipOf = (target: EventTarget | null): { chip: HTMLElement; set: string; variant: string } | null => { + const chip = (target as HTMLElement | null)?.closest('.fsh-var-chip'); + const block = chip?.closest('.fsh-var-set'); + if (!chip || !block || !chip.dataset.key || !block.dataset.key) return null; + return { chip, set: block.dataset.key, variant: chip.dataset.key }; + }; + + const hint = q(root, '.fsh-var-hint'); + const diffs = new Map>(); + let hinting = ''; + let hintTimer: number | undefined; + const sayHint = (text: string): void => { setText(hint, text); setTitle(hint, text); }; + const describe = (name: string, d: DiffView): string => { + if (!d.changes.length) return d.skipped ? t('{name}: nothing changes; {n} parts are skipped.', { name, n: d.skipped }) : t('{name}: nothing changes, the parts already wear it.', { name }); + const list = d.changes.map((c) => t('{part} from {from} to {to}', { part: c.part, from: c.from || t('Default material'), to: c.to || t('Default material') })).join(', '); + const head = d.changes.length === 1 ? t('{name} changes one part:', { name }) : t('{name} changes {n} parts:', { name, n: d.changes.length }); + return `${head} ${list}${d.skipped ? `; ${t('{n} skipped', { n: d.skipped })}` : ''}`; + }; + const showHint = (setId: string, variant: string): void => { + window.clearTimeout(hintTimer); + const v = setById(setId)?.variants.find((x) => x.id === variant); + if (!v || !ws.client.has(VARIANT_CMD.diff)) return; + const key = `${ws.client.summary?.revision ?? -1}|${setId}|${variant}`; + hinting = key; + let p = diffs.get(key); + if (!p) { + if (diffs.size > 64) diffs.clear(); + p = ws.client.dispatch(VARIANT_CMD.diff, { set: setId, variant }).then(diffOf).catch(() => null); + diffs.set(key, p); + } + void p.then((d) => { if (hinting === key && d) sayHint(describe(v.name, d)); }); + }; + const clearHint = (): void => { + window.clearTimeout(hintTimer); + hintTimer = window.setTimeout(() => { hinting = ''; sayHint(''); }, 250); + }; + setsHost.addEventListener('pointerover', (e) => { const hit = chipOf(e.target); if (hit) showHint(hit.set, hit.variant); }); + setsHost.addEventListener('pointerout', (e) => { if (!chipOf(e.relatedTarget) && !chipOf(document.activeElement)) clearHint(); }); + setsHost.addEventListener('focusin', (e) => { const hit = chipOf(e.target); if (hit) showHint(hit.set, hit.variant); }); + setsHost.addEventListener('focusout', (e) => { if (!chipOf(e.relatedTarget)) clearHint(); }); + + addBtn.addEventListener('click', () => { void addSet(); }); + setsHost.addEventListener('click', (e) => { + const cap = (e.target as HTMLElement).closest('.fsh-var-capture'); + const block = cap?.closest('.fsh-var-set'); + if (cap && block?.dataset.key) { void capture(block.dataset.key); return; } + const more = (e.target as HTMLElement).closest('.fsh-var-more'); + const moreSet = more?.closest('.fsh-var-set')?.dataset.key; + if (more && moreSet) { openSetMenu(moreSet, more); return; } + const hit = chipOf(e.target); + if (!hit) return; + hit.chip.focus(); + choose(hit.set, hit.variant); + }); + setsHost.addEventListener('keydown', (e) => { + const hit = chipOf(e.target); + if (!hit || e.target !== hit.chip) return; + if ((e.key === 'ArrowRight' || e.key === 'ArrowLeft') && e.altKey) { + const set = setById(hit.set); + const at = set ? store.ordered(`variant.order.${hit.set}`, set.variants).findIndex((v) => v.id === hit.variant) : -1; + if (at >= 0) moveVariant(hit.set, hit.variant, at + (e.key === 'ArrowLeft' ? -1 : 1)); + } else if (e.key === 'F2') { + renameVariant(hit.set, hit.variant); + } else if (e.key === 'Delete' || e.key === 'Backspace') { + if (ws.canRun(VARIANT_CMD.remove)) void store.act(VARIANT_CMD.remove, { set: hit.set, id: hit.variant }); + } else if (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey)) { + openVariantMenu(hit.set, hit.variant, hit.chip); + } else if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { + const next = (e.key === 'ArrowRight' ? hit.chip.nextElementSibling : hit.chip.previousElementSibling) as HTMLElement | null; + if (next) { next.focus(); if (next.dataset.key) choose(hit.set, next.dataset.key); } + } else if (e.key === 'Enter' || e.key === ' ') { + choose(hit.set, hit.variant); + } else return; + e.preventDefault(); + e.stopPropagation(); + }); + + setsHost.addEventListener('contextmenu', (e) => { + const hit = chipOf(e.target); + if (!hit || hit.chip.dataset.editing === 'true') return; + e.preventDefault(); + hit.chip.focus(); + openVariantMenu(hit.set, hit.variant, hit.chip); + }); + setsHost.addEventListener('dblclick', (e) => { + const hit = chipOf(e.target); + if (hit) { renameVariant(hit.set, hit.variant); return; } + const label = (e.target as HTMLElement).closest('.fsh-var-name'); + const setId = label?.closest('.fsh-var-set')?.dataset.key; + if (setId) renameSet(setId); + }); + + update(); + return { update, dispose: () => { window.clearTimeout(hintTimer); setMenu.dispose(); variantMenu.dispose(); } }; +} diff --git a/frontend/src/ui/templates/dialog.ts b/frontend/src/ui/templates/dialog.ts new file mode 100644 index 00000000..81c34beb --- /dev/null +++ b/frontend/src/ui/templates/dialog.ts @@ -0,0 +1,368 @@ +import { api } from '../../shell/api'; +import { canRun, run, why } from '../../shell/commands'; +import { confirmDialog, Dialog } from '../../shell/dialog'; +import { el, escapeHtml, patchList, q, setAttr, setClass, setDisabled, setHidden, setText, setTitle } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { toast } from '../../shell/toast'; +import { t } from '../../i18n'; +import { RuleEditor } from './editor'; +import { + errorText, obj, parseList, parsePresets, parsePreview, parseTemplate, ruleArgs, ruleText, str, targetLabel, TEMPLATE_CMD, + type PresetInfo, type Preview, type Template, type TemplateInfo, +} from './model'; + +type Scope = 'selection' | 'scene'; +const SCOPE_KEY = 'formshot.templates.scope'; +const COUNT_KEY = 'formshot.templates.count'; + +function storedCount(): number { + try { return Math.min(12, Math.max(1, Number(localStorage.getItem(COUNT_KEY)) || 2)); } catch { return 2; } +} + +function keepCount(n: number): void { + try { localStorage.setItem(COUNT_KEY, String(n)); } catch { return; } +} + +export class TemplateDialog { + private readonly dialog = new Dialog('Material Templates', 'wide'); + private readonly root: HTMLElement; + private readonly editor: RuleEditor; + private list: TemplateInfo[] = []; + private current: Template | null = null; + private currentId = ''; + private preview: Preview | null = null; + private selection: string[] = []; + private scope: Scope = 'scene'; + private presets: PresetInfo[] = []; + private token = 0; + private busy = false; + + constructor(private readonly onClosed: () => void) { + this.dialog.scrim.querySelector('.fsh-dialog')?.classList.add('fsh-tpl-dialog'); + const skeleton = Array.from({ length: storedCount() }, (_, i) => ``).join(''); + this.root = el(`
      + +
      +
      +

      +

      +
      + + +
      +

      +
      +

      ${escapeHtml(t('What applying changes'))}

        +

        ${escapeHtml(t('Rules, first match wins'))}

          +
          +
          + + + + +
          +
          + +

          +
          +
          `); + this.dialog.body.appendChild(this.root); + this.editor = new RuleEditor(q(this.root, '.fsh-tpl-editor'), { + save: (draft) => this.save(draft), + cancel: () => this.showEditor(false), + }); + this.dialog.action('Close', () => this.dialog.close()); + this.dialog.onClose = () => this.onClosed(); + try { this.scope = localStorage.getItem(SCOPE_KEY) === 'selection' ? 'selection' : 'scene'; } catch { this.scope = 'scene'; } + this.wire(); + } + + async open(): Promise { + this.dialog.open(); + this.paint(); + await Promise.all([this.loadSelection(), this.loadList()]); + if (!this.currentId && this.list.length) this.pick(this.list[0].id); + void this.loadPresets(); + } + + private say(text: string, error = false): void { + const p = q(this.root, '.fsh-tpl-said'); + setText(p, text); + setClass(p, 'is-error', error); + } + + private wire(): void { + for (const list of Array.from(this.root.querySelectorAll('.fsh-tpl-list'))) { + list.addEventListener('click', (e) => { + const row = (e.target as HTMLElement).closest('.fsh-tpl-item'); + if (row?.dataset.key) this.pick(row.dataset.key); + }); + } + for (const b of Array.from(this.root.querySelectorAll('.fsh-tpl-seg'))) { + b.addEventListener('click', () => { + if (b.disabled) return; + this.scope = b.dataset.scope === 'selection' ? 'selection' : 'scene'; + try { localStorage.setItem(SCOPE_KEY, this.scope); } catch { this.scope = b.dataset.scope === 'selection' ? 'selection' : 'scene'; } + this.paint(); + void this.loadPreview(); + }); + } + q(this.root, '.fsh-tpl-apply').addEventListener('click', () => void this.apply()); + q(this.root, '.fsh-tpl-edit').addEventListener('click', () => this.edit()); + q(this.root, '.fsh-tpl-remove').addEventListener('click', () => void this.remove()); + q(this.root, '.fsh-tpl-capture').addEventListener('submit', (e) => { e.preventDefault(); void this.capture(); }); + } + + private async loadSelection(): Promise { + try { + const s = obj(await api.dispatch(TEMPLATE_CMD.summary, {})); + const sel = Array.isArray(s.selection) ? s.selection.map(str).filter(Boolean) : []; + this.selection = sel; + } catch { + this.selection = []; + } + if (!this.selection.length) this.scope = 'scene'; + this.paint(); + } + + private async loadList(): Promise { + try { + this.list = parseList(await api.dispatch(TEMPLATE_CMD.list, {})); + keepCount(this.list.filter((x) => x.source === 'builtin').length); + } catch (err) { + this.say(t('The templates could not be listed: {reason}', { reason: errorText(err) }), true); + } + this.paintList(); + } + + private async loadPresets(): Promise { + if (this.presets.length) return; + try { this.presets = parsePresets(await api.dispatch(TEMPLATE_CMD.presets, {})); } catch { this.presets = []; } + this.editor.setPresets(this.presets); + } + + private pick(id: string): void { + if (id === this.currentId && this.current) return; + this.currentId = id; + this.current = null; + this.preview = null; + this.showEditor(false); + this.say(''); + this.paintList(); + this.paint(); + void this.loadCurrent(); + } + + private async loadCurrent(): Promise { + const token = ++this.token; + const id = this.currentId; + try { + const got = parseTemplate(await api.dispatch(TEMPLATE_CMD.get, { id })); + if (token !== this.token) return; + this.current = got; + } catch (err) { + if (token !== this.token) return; + this.say(errorText(err), true); + } + this.paint(); + await this.loadPreview(); + } + + private async loadPreview(): Promise { + const id = this.currentId; + if (!id) return; + const token = ++this.token; + const args: Record = { id }; + if (this.scope === 'selection' && this.selection.length) args.parts = this.selection; + try { + const p = parsePreview(await api.dispatch(TEMPLATE_CMD.preview, args)); + if (token !== this.token) return; + this.preview = p; + } catch (err) { + if (token !== this.token) return; + this.preview = null; + this.say(errorText(err), true); + } + this.paint(); + } + + private paintList(): void { + for (const src of ['builtin', 'user'] as const) { + const host = q(this.root, `.fsh-tpl-list[data-src="${src}"]`); + const items = this.list.filter((x) => x.source === src); + patchList(host, items, { + key: (x) => x.id, + create: () => el('
          '), + update: () => undefined, + }); + for (const row of Array.from(host.children) as HTMLElement[]) { + const x = items.find((i) => i.id === row.dataset.key); + if (!x) continue; + setText(q(row, '.fsh-tpl-item-name'), x.name); + const sub = !x.valid ? (x.error || t('This template does not validate.')) + : x.missing.length ? t('{n} presets are missing from the library', { n: x.missing.length }) + : x.rules === 1 ? t('One rule') : t('{n} rules', { n: x.rules }); + setText(q(row, '.fsh-tpl-item-sub'), sub); + setClass(row, 'is-invalid', !x.valid || x.missing.length > 0); + setAttr(row, 'aria-selected', x.id === this.currentId ? 'true' : 'false'); + } + if (src === 'user') { + const empty = q(this.root, '.fsh-tpl-empty[data-src="user"]'); + setText(empty, items.length ? '' : t('None yet. Capture the materials of this scene, or edit a copy of a FormShot template.')); + setHidden(empty, items.length > 0); + } + } + } + + private paint(): void { + const cur = this.current; + const info = this.list.find((x) => x.id === this.currentId); + setText(q(this.root, '.fsh-tpl-name'), cur?.name ?? info?.name ?? ''); + setText(q(this.root, '.fsh-tpl-badge'), (cur?.source ?? info?.source) === 'user' ? t('Yours') : (cur || info) ? t('FormShot') : ''); + setText(q(this.root, '.fsh-tpl-desc'), cur?.description ?? info?.description ?? ''); + const selBtn = q(this.root, '.fsh-tpl-seg[data-scope="selection"]'); + setText(selBtn, this.selection.length ? t('Selected parts ({n})', { n: this.selection.length }) : t('Selected parts')); + setDisabled(selBtn, this.selection.length === 0); + setTitle(selBtn, this.selection.length ? '' : t('Select parts in the scene first; the template then dresses only them.')); + for (const b of Array.from(this.root.querySelectorAll('.fsh-tpl-seg'))) setAttr(b, 'aria-checked', b.dataset.scope === this.scope ? 'true' : 'false'); + + const p = this.preview; + setText(q(this.root, '.fsh-tpl-counts'), !p ? (this.currentId ? t('Looking at the parts...') : '') + : t('{matched} of {total} parts match a rule; {changes} would change.', { matched: p.matched, total: p.total, changes: p.changes })); + patchList(q(this.root, '.fsh-tpl-preview'), p?.parts ?? [], { + key: (x) => x.id, + create: () => el(`
        1. ${icon('chevronRight', 12)}
        2. `), + update: () => undefined, + }); + for (const li of Array.from(q(this.root, '.fsh-tpl-preview').children) as HTMLElement[]) { + const x = p?.parts.find((i) => i.id === li.dataset.key); + if (!x) continue; + const from = x.source || x.current || t('Default material'); + const to = x.rule === null ? t('No rule matches') : x.changes ? x.target : t('{name} already', { name: x.target }); + setText(q(li, '.fsh-tpl-part-name'), x.name); + setText(q(li, '.fsh-tpl-part-from'), from); + setText(q(li, '.fsh-tpl-part-to'), to); + setTitle(li, `${x.name}: ${from} > ${to}`); + setClass(li, 'is-same', !x.changes); + } + const rules = cur?.rules ?? []; + patchList(q(this.root, '.fsh-tpl-rules'), rules.map((r, i) => ({ r, i })), { + key: ({ i }) => String(i), + create: () => el('
        3. '), + update: () => undefined, + }); + Array.from(q(this.root, '.fsh-tpl-rules').children).forEach((li, i) => { + const r = rules[i]; + if (!r) return; + setText(q(li as HTMLElement, '.fsh-tpl-rule-when'), ruleText(r)); + setText(q(li as HTMLElement, '.fsh-tpl-rule-then'), r.error ? r.error : targetLabel(r)); + setClass(li as HTMLElement, 'is-invalid', r.error !== ''); + }); + + const user = (cur?.source ?? info?.source) === 'user'; + const applyBtn = q(this.root, '.fsh-tpl-apply'); + const canApply = !!cur && canRun(TEMPLATE_CMD.apply) && !!p && p.changes > 0 && !this.busy; + setDisabled(applyBtn, !canApply); + setTitle(applyBtn, canApply ? t('Apply as one undo step') : !canRun(TEMPLATE_CMD.apply) ? why(TEMPLATE_CMD.apply) : p && p.changes === 0 ? t('Nothing would change.') : ''); + const editBtn = q(this.root, '.fsh-tpl-edit'); + setText(editBtn, user ? t('Edit rules') : t('Edit a copy')); + setDisabled(editBtn, !cur); + const removeBtn = q(this.root, '.fsh-tpl-remove'); + setHidden(removeBtn, !user); + setDisabled(removeBtn, this.busy); + } + + private async apply(): Promise { + const cur = this.current; + if (!cur || this.busy) return; + this.busy = true; + this.paint(); + const args: Record = { id: cur.id }; + if (this.scope === 'selection' && this.selection.length) args.parts = this.selection; + const out = obj(await run(TEMPLATE_CMD.apply, args)); + this.busy = false; + if (Object.keys(out).length) { + const changed = typeof out.changed === 'number' ? out.changed : 0; + const made = Array.isArray(out.materials_created) ? out.materials_created.length : 0; + this.say(t('Applied {name}: {changed} parts changed, {made} materials made. Undo puts the old materials back.', { name: cur.name, changed, made })); + } + await this.loadPreview(); + } + + private edit(): void { + const cur = this.current; + if (!cur) return; + const draft: Template = cur.source === 'user' ? structuredClone(cur) : { ...structuredClone(cur), id: '', source: 'user', name: t('{name} copy', { name: cur.name }) }; + this.editor.load(draft, this.presets); + this.showEditor(true); + } + + private showEditor(on: boolean): void { + setHidden(q(this.root, '.fsh-tpl-view'), on); + setHidden(q(this.root, '.fsh-tpl-editor'), !on); + } + + private async save(draft: Template): Promise { + const args: Record = { name: draft.name.trim(), description: draft.description.trim(), rules: draft.rules.map(ruleArgs) }; + if (draft.id && draft.source === 'user') args.id = draft.id; + if (!canRun(TEMPLATE_CMD.save)) return why(TEMPLATE_CMD.save); + try { + const out = obj(await api.dispatch(TEMPLATE_CMD.save, args)); + const id = str(out.id) || draft.id; + await this.loadList(); + this.showEditor(false); + this.currentId = ''; + this.pick(id || this.list.filter((x) => x.source === 'user').slice(-1)[0]?.id || ''); + this.say(t('Saved {name}.', { name: str(args.name) })); + return ''; + } catch (err) { + return errorText(err); + } + } + + private async remove(): Promise { + const cur = this.current; + if (!cur || cur.source !== 'user') return; + const sure = await confirmDialog(t('Remove template?'), t('{name} is deleted from your templates. This cannot be undone.', { name: cur.name }), { ok: 'Remove', danger: true }); + if (!sure) return; + try { + await api.dispatch(TEMPLATE_CMD.remove, { id: cur.id }); + toast(t('Removed the template {name}.', { name: cur.name })); + this.currentId = ''; + this.current = null; + await this.loadList(); + if (this.list.length) this.pick(this.list[0].id); + } catch (err) { + this.say(errorText(err), true); + } + } + + private async capture(): Promise { + const input = q(this.root, '.fsh-tpl-capture input'); + const name = input.value.trim(); + if (!name) { input.focus(); this.say(t('Name the template first.'), true); return; } + try { + const out = obj(await api.dispatch(TEMPLATE_CMD.capture, { name })); + const draft = parseTemplate({ ...out, id: '', source: 'user' }); + if (!draft.rules.length) { this.say(t('No part in this scene has a material name to capture.'), true); return; } + input.value = ''; + this.editor.load(draft, this.presets); + this.showEditor(true); + const notes = Array.isArray(out.notes) ? out.notes.map(str).filter(Boolean) : []; + this.say(notes.length ? notes.join(' ') : t('Captured {n} rules. Change them if you like, then save.', { n: draft.rules.length })); + } catch (err) { + this.say(errorText(err), true); + } + } +} diff --git a/frontend/src/ui/templates/editor.ts b/frontend/src/ui/templates/editor.ts new file mode 100644 index 00000000..e134354f --- /dev/null +++ b/frontend/src/ui/templates/editor.ts @@ -0,0 +1,182 @@ +import { el, escapeHtml, patchList, q, setDisabled, setHidden, setText, setValue } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { FIELDS, fieldLabel, type PresetInfo, type Template, type TemplateRule } from './model'; + +const KEEP = '@keep'; +const PATTERN_HINT = '*abs*black*'; + +export interface EditorHooks { + save(draft: Template): Promise; + cancel(): void; +} + +interface Row { uid: number; rule: TemplateRule } + +export class RuleEditor { + private draft: Template | null = null; + private rows: Row[] = []; + private uid = 0; + private presetHtml = ''; + private presets: PresetInfo[] = []; + private saving = false; + private readonly list: HTMLElement; + private readonly nameInput: HTMLInputElement; + private readonly descInput: HTMLTextAreaElement; + private readonly error: HTMLElement; + private readonly saveBtn: HTMLButtonElement; + + constructor(host: HTMLElement, private readonly hooks: EditorHooks) { + const root = el(`
          + + +

          ${escapeHtml(t('Rules, first match wins'))}

          + +
            + + +
            +
            `); + host.appendChild(root); + this.list = q(root, '.fsh-tpl-ed-rules'); + this.nameInput = q(root, 'input'); + this.descInput = q(root, 'textarea'); + this.error = q(root, '.fsh-tpl-ed-error'); + this.saveBtn = q(root, '.fsh-tpl-ed-save'); + q(root, '.fsh-tpl-ed-add').addEventListener('click', () => this.add()); + q(root, '.fsh-tpl-ed-cancel').addEventListener('click', () => this.hooks.cancel()); + this.saveBtn.addEventListener('click', () => void this.save()); + this.list.addEventListener('input', (e) => this.onInput(e)); + this.list.addEventListener('change', (e) => this.onInput(e)); + this.list.addEventListener('click', (e) => this.onClick(e)); + root.addEventListener('keydown', (e) => { if (e.key !== 'Escape') e.stopPropagation(); }); + } + + setPresets(presets: readonly PresetInfo[]): void { + this.presets = [...presets]; + const groups = new Map(); + for (const p of presets) { const g = groups.get(p.category) ?? []; g.push(p); groups.set(p.category, g); } + this.presetHtml = [...groups].map(([cat, list]) => `${list.map((p) => ``).join('')}`).join(''); + if (this.draft) for (const li of Array.from(this.list.children) as HTMLElement[]) this.fillTarget(li, this.rowOf(li)?.rule); + } + + load(draft: Template, presets: readonly PresetInfo[]): void { + if (presets.length && presets.length !== this.presets.length) this.setPresets(presets); + this.draft = draft; + this.rows = draft.rules.map((rule) => ({ uid: ++this.uid, rule: { ...rule } })); + this.nameInput.value = draft.name; + this.descInput.value = draft.description; + setText(this.error, ''); + this.list.replaceChildren(); + this.paint(); + this.nameInput.focus(); + } + + private rowOf(li: HTMLElement | null): Row | undefined { + return li ? this.rows.find((r) => String(r.uid) === li.dataset.key) : undefined; + } + + private fillTarget(li: HTMLElement, rule: TemplateRule | undefined): void { + if (!rule) return; + const sel = q(li, '[data-f="target"]'); + const keep = rule.material ? `` : ''; + const known = !rule.preset || this.presets.some((p) => p.id === rule.preset); + const extra = known ? '' : ``; + const none = !rule.preset && !rule.material ? `` : ''; + const html = none + keep + extra + this.presetHtml; + if (sel.dataset.html !== html) { sel.innerHTML = html; sel.dataset.html = html; } + sel.value = rule.preset || (rule.material ? KEEP : ''); + } + + private paintRow(li: HTMLElement, row: Row, i: number): void { + const r = row.rule; + setValue(q(li, '[data-f="field"]'), r.field); + const key = q(li, '[data-f="key"]'); + setValue(key, r.key); + setHidden(key, r.field !== 'metadata'); + setValue(q(li, '[data-f="pattern"]'), r.pattern); + this.fillTarget(li, r); + setDisabled(q(li, '[data-op="up"]'), i === 0); + } + + private paint(): void { + const fields = FIELDS.map((f) => ``).join(''); + patchList(this.list, this.rows, { + key: (r) => String(r.uid), + create: () => { + const li = el(`
          1. + + + + +
          2. `); + return li; + }, + update: () => undefined, + }); + Array.from(this.list.children).forEach((li, i) => { const row = this.rows[i]; if (row) this.paintRow(li as HTMLElement, row, i); }); + setDisabled(this.saveBtn, this.saving); + } + + private add(): void { + this.rows.push({ uid: ++this.uid, rule: { field: 'material', key: '', pattern: '', preset: '', presetName: '', material: null, materialName: '', error: '' } }); + this.paint(); + (this.list.lastElementChild?.querySelector('[data-f="pattern"]'))?.focus(); + } + + private onInput(e: Event): void { + const target = e.target as HTMLInputElement | HTMLSelectElement; + const li = target.closest('.fsh-tpl-ed-rule'); + const row = this.rowOf(li); + if (!li || !row) return; + const r = row.rule; + const f = target.dataset.f; + if (f === 'field') { r.field = target.value === 'part' ? 'part' : target.value === 'metadata' ? 'metadata' : 'material'; this.paintRow(li, row, this.rows.indexOf(row)); } + else if (f === 'key') r.key = target.value; + else if (f === 'pattern') r.pattern = target.value; + else if (f === 'target' && e.type === 'change') { + if (target.value === KEEP) r.preset = ''; + else { r.preset = target.value; r.presetName = this.presets.find((p) => p.id === target.value)?.name ?? ''; } + } + } + + private onClick(e: Event): void { + const b = (e.target as HTMLElement).closest('[data-op]'); + const row = this.rowOf(b?.closest('.fsh-tpl-ed-rule') ?? null); + if (!b || !row || b.disabled) return; + const i = this.rows.indexOf(row); + if (b.dataset.op === 'remove') this.rows.splice(i, 1); + else if (b.dataset.op === 'up' && i > 0) this.rows.splice(i - 1, 0, ...this.rows.splice(i, 1)); + this.paint(); + } + + private problem(): string { + if (!this.nameInput.value.trim()) return t('Name the template first.'); + if (!this.rows.length) return t('Add at least one rule.'); + for (const [i, { rule: r }] of this.rows.entries()) { + if (!r.pattern.trim()) return t('Rule {n} has no pattern.', { n: i + 1 }); + if (r.field === 'metadata' && !r.key.trim()) return t('Rule {n} looks at part data but names no key.', { n: i + 1 }); + if (!r.preset && !r.material) return t('Rule {n} names no material.', { n: i + 1 }); + } + return ''; + } + + private async save(): Promise { + if (!this.draft || this.saving) return; + const why = this.problem(); + setText(this.error, why); + if (why) return; + this.saving = true; + this.paint(); + const draft: Template = { + ...this.draft, + name: this.nameInput.value.trim(), + description: this.descInput.value.trim(), + rules: this.rows.map(({ rule }) => ({ ...rule, pattern: rule.pattern.trim(), key: rule.key.trim(), material: rule.preset ? null : rule.material })), + }; + const err = await this.hooks.save(draft); + this.saving = false; + setText(this.error, err); + this.paint(); + } +} diff --git a/frontend/src/ui/templates/index.ts b/frontend/src/ui/templates/index.ts new file mode 100644 index 00000000..f8773f41 --- /dev/null +++ b/frontend/src/ui/templates/index.ts @@ -0,0 +1,66 @@ +import './templates.css'; +import { api } from '../../shell/api'; +import { canRun } from '../../shell/commands'; +import { el, escapeHtml, q, setDisabled } from '../../shell/dom'; +import { registerCommands, registerMenu } from '../../shell/registry'; +import { t } from '../../i18n'; +import { TemplateDialog } from './dialog'; +import { parseList, TEMPLATE_CMD } from './model'; + +export const OPEN_TEMPLATES = 'templates.open'; +export const IMPORT_HOOK = 'templates.sheet'; +const IMPORT_KEY = 'formshot.templates.import'; + +let open: TemplateDialog | null = null; +let registered = false; + +function storedChoice(): string { + try { return localStorage.getItem(IMPORT_KEY) ?? ''; } catch { return ''; } +} + +function keepChoice(id: string): void { + try { localStorage.setItem(IMPORT_KEY, id); } catch { return; } +} + +function importRow(host: HTMLElement): void { + if (host.querySelector('[data-o="template"]')) return; + const row = el(``); + host.insertBefore(row, host.querySelector('.fsh-imp-cad')); + const select = q(row, 'select'); + select.title = t('Dress the imported parts with a material template, in the same undo step as the import.'); + select.addEventListener('change', () => keepChoice(select.value)); + setDisabled(select, true); + void api.dispatch(TEMPLATE_CMD.list, {}).then((raw) => { + const list = parseList(raw).filter((x) => x.valid && !x.missing.length); + for (const x of list) { + const o = document.createElement('option'); + o.value = x.id; + o.textContent = x.source === 'user' ? t('{name} (yours)', { name: x.name }) : x.name; + select.appendChild(o); + } + const kept = storedChoice(); + if (list.some((x) => x.id === kept)) select.value = kept; + }).catch(() => undefined).finally(() => setDisabled(select, false)); +} + +export function registerTemplates(): void { + if (registered) return; + registered = true; + registerCommands([ + { + id: OPEN_TEMPLATES, label: 'Material Templates...', group: 'Scene', icon: 'material', + description: 'Dress parts by their material or part names with saved rules: preview, apply, capture and edit templates.', + enabled: () => canRun(TEMPLATE_CMD.list), + run: () => { + if (open) return; + open = new TemplateDialog(() => { open = null; }); + return open.open(); + }, + }, + { + id: IMPORT_HOOK, label: 'Template Choice in the Import Sheet', group: 'File', palette: false, + run: (args) => { const host = args?.options; if (host instanceof HTMLElement) importRow(host); }, + }, + ]); + registerMenu({ id: 'scene', items: [{ command: OPEN_TEMPLATES, section: 3 }] }); +} diff --git a/frontend/src/ui/templates/model.ts b/frontend/src/ui/templates/model.ts new file mode 100644 index 00000000..c0a9e9b3 --- /dev/null +++ b/frontend/src/ui/templates/model.ts @@ -0,0 +1,122 @@ +import { t } from '../../i18n'; + +export const TEMPLATE_CMD = { + list: 'template.list', + get: 'template.get', + save: 'template.save', + remove: 'template.remove', + preview: 'template.preview', + apply: 'template.apply', + capture: 'template.capture', + presets: 'library.list', + summary: 'scene.summary', +} as const; + +export type Field = 'material' | 'part' | 'metadata'; +export const FIELDS: readonly Field[] = ['material', 'part', 'metadata']; + +export interface TemplateInfo { + id: string; + name: string; + description: string; + source: 'builtin' | 'user'; + rules: number; + valid: boolean; + error: string; + missing: string[]; +} + +export interface TemplateRule { + field: Field; + key: string; + pattern: string; + preset: string; + presetName: string; + material: Record | null; + materialName: string; + error: string; +} + +export interface Template { id: string; name: string; description: string; source: 'builtin' | 'user'; rules: TemplateRule[] } + +export interface PreviewPart { id: string; name: string; source: string; current: string; rule: number | null; target: string; changes: boolean } +export interface Preview { total: number; matched: number; changes: number; parts: PreviewPart[] } + +export interface PresetInfo { id: string; name: string; category: string } + +type Obj = Record; +export const obj = (v: unknown): Obj => (v && typeof v === 'object' && !Array.isArray(v) ? v as Obj : {}); +export const str = (v: unknown): string => (typeof v === 'string' ? v : typeof v === 'number' ? String(v) : ''); +const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0); + +export function parseList(raw: unknown): TemplateInfo[] { + const list = obj(raw).templates; + return (Array.isArray(list) ? list : []).map((x) => { + const o = obj(x); + return { + id: str(o.id), name: str(o.name) || str(o.id), description: str(o.description), source: o.source === 'user' ? 'user' : 'builtin', + rules: num(o.rules), valid: o.valid !== false, error: str(o.error), missing: Array.isArray(o.missing_presets) ? o.missing_presets.map(str) : [], + }; + }); +} + +export function parseRule(raw: unknown): TemplateRule { + const o = obj(raw); + const field: Field = o.field === 'part' ? 'part' : o.field === 'metadata' ? 'metadata' : 'material'; + const material = o.material && typeof o.material === 'object' ? o.material as Record : null; + return { + field, key: str(o.key), pattern: str(o.pattern), preset: str(o.preset), presetName: str(o.preset_name), + material, materialName: str(o.material_name) || str(material?.name), error: str(o.error), + }; +} + +export function parseTemplate(raw: unknown): Template { + const o = obj(raw); + return { + id: str(o.id), name: str(o.name), description: str(o.description), source: o.source === 'user' ? 'user' : 'builtin', + rules: (Array.isArray(o.rules) ? o.rules : []).map(parseRule), + }; +} + +export function parsePreview(raw: unknown): Preview { + const o = obj(raw); + const parts = (Array.isArray(o.parts) ? o.parts : []).map((x) => { + const p = obj(x); + const target = obj(p.target); + return { + id: str(p.id), name: str(p.name), source: str(p.source_material), current: str(obj(p.material).name), + rule: typeof p.rule === 'number' ? p.rule : null, target: str(target.name), changes: p.changes === true, + }; + }); + return { total: num(o.total), matched: num(o.matched), changes: num(o.changes), parts }; +} + +export function parsePresets(raw: unknown): PresetInfo[] { + const list = obj(raw).presets; + return (Array.isArray(list) ? list : []).map((x) => { const p = obj(x); return { id: str(p.id), name: str(p.name) || str(p.id), category: str(p.category) }; }).filter((p) => p.id); +} + +export function fieldLabel(field: Field, key: string): string { + if (field === 'part') return t('Part name'); + if (field === 'metadata') return key ? t('Part data {key}', { key }) : t('Part data'); + return t('Material name'); +} + +export function targetLabel(r: TemplateRule): string { + if (r.preset) return r.presetName || r.preset; + return r.materialName ? t('{name} (kept in the template)', { name: r.materialName }) : t('A material kept in the template'); +} + +export function ruleText(r: TemplateRule): string { + return t('{field} matches {pattern}', { field: fieldLabel(r.field, r.key), pattern: r.pattern }); +} + +export function ruleArgs(r: TemplateRule): Record { + const out: Record = { field: r.field, pattern: r.pattern }; + if (r.field === 'metadata') out.key = r.key; + if (r.preset) out.preset = r.preset; + else if (r.material) out.material = r.material; + return out; +} + +export function errorText(err: unknown): string { return err instanceof Error ? err.message : String(err); } diff --git a/frontend/src/ui/templates/templates.css b/frontend/src/ui/templates/templates.css new file mode 100644 index 00000000..c9510bdb --- /dev/null +++ b/frontend/src/ui/templates/templates.css @@ -0,0 +1,78 @@ +.fsh-dialog.fsh-tpl-dialog { width: min(1080px, calc(100vw - 32px)); } +.fsh-tpl { display: grid; grid-template-columns: 220px minmax(0, 1fr); gap: var(--space-4); height: min(620px, calc(100vh - 180px)); min-height: 0; } +.fsh-tpl-side { display: flex; flex-direction: column; gap: var(--space-1); min-height: 0; overflow-y: auto; padding-right: var(--space-2); border-right: 1px solid var(--line-1); } +.fsh-tpl-head { margin: var(--space-2) 0 var(--space-1); color: var(--text-faint); font-size: var(--fs-10); font-weight: var(--fw-semibold); letter-spacing: 0.06em; text-transform: uppercase; } +.fsh-tpl-head:first-child { margin-top: 0; } +.fsh-tpl-list { display: flex; flex-direction: column; gap: 1px; } +.fsh-tpl-item { display: flex; flex-direction: column; justify-content: center; height: 44px; padding: 0 var(--space-2); border-radius: var(--radius-md); color: var(--text-secondary); cursor: pointer; } +.fsh-tpl-item:hover { background: var(--bg-hover); } +.fsh-tpl-item[aria-selected="true"] { background: var(--accent-tint-strong); color: var(--text-primary); } +.fsh-tpl-item-name { overflow: hidden; color: var(--text-primary); font-size: var(--fs-12); text-overflow: ellipsis; white-space: nowrap; } +.fsh-tpl-item-sub { overflow: hidden; color: var(--text-faint); font-size: var(--fs-10); text-overflow: ellipsis; white-space: nowrap; } +.fsh-tpl-item.is-invalid .fsh-tpl-item-sub { color: var(--warn); } +.fsh-tpl-item.is-skeleton { cursor: default; } +.fsh-tpl-item.is-skeleton .fsh-tpl-item-name { width: 70%; height: 10px; margin-bottom: 6px; border-radius: var(--radius-sm); background: var(--bg-hover); } +.fsh-tpl-item.is-skeleton .fsh-tpl-item-sub { width: 40%; height: 8px; border-radius: var(--radius-sm); background: var(--bg-hover); } +.fsh-tpl-empty { margin: 0; color: var(--text-muted); font-size: var(--fs-11); line-height: 1.45; } +.fsh-tpl-empty[hidden] { display: none; } +.fsh-tpl-capture { display: flex; flex-direction: column; gap: var(--space-1); margin-top: auto; padding-top: var(--space-3); border-top: 1px solid var(--line-1); } +.fsh-tpl-capture-label { color: var(--text-muted); font-size: var(--fs-11); } +.fsh-tpl-capture-row { display: flex; gap: var(--space-1); } +.fsh-tpl-capture-row .fsh-input { flex: 1; min-width: 0; height: var(--ctl-md); font-size: var(--fs-12); } + +.fsh-tpl-main { display: flex; flex-direction: column; gap: var(--space-2); min-width: 0; min-height: 0; } +.fsh-tpl-view { display: flex; flex-direction: column; gap: var(--space-2); flex: 1; min-height: 0; } +.fsh-tpl-view[hidden], .fsh-tpl-editor[hidden] { display: none; } +.fsh-tpl-title { display: flex; align-items: baseline; gap: var(--space-2); min-height: 22px; } +.fsh-tpl-name { margin: 0; color: var(--text-primary); font-size: var(--fs-13); font-weight: var(--fw-semibold); } +.fsh-tpl-badge { color: var(--text-faint); font-size: var(--fs-10); text-transform: uppercase; letter-spacing: 0.06em; } +.fsh-tpl-desc { display: -webkit-box; min-height: calc(var(--fs-12) * 1.45 * 2); margin: 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-12); line-height: 1.45; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } +.fsh-tpl-scope { display: inline-flex; align-self: flex-start; padding: 2px; border: 1px solid var(--line-2); border-radius: var(--radius-pill); } +.fsh-tpl-seg { height: var(--ctl-sm); padding: 0 var(--space-3); border: 0; border-radius: var(--radius-pill); background: transparent; color: var(--text-secondary); font: inherit; font-size: var(--fs-11); cursor: pointer; } +.fsh-tpl-seg[aria-checked="true"] { background: var(--accent-tint-strong); color: var(--text-primary); } +.fsh-tpl-seg:disabled { opacity: 0.5; cursor: default; } +.fsh-tpl-counts { min-height: calc(var(--fs-12) * 1.45); margin: 0; color: var(--text-primary); font-size: var(--fs-12); line-height: 1.45; } +.fsh-tpl-remove[hidden] { display: none; } +.fsh-tpl-panes { display: grid; grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr); gap: var(--space-3); flex: 1; min-height: 0; } +.fsh-tpl-pane { display: flex; flex-direction: column; gap: var(--space-1); min-height: 0; } +.fsh-tpl-sub { margin: 0; color: var(--text-faint); font-size: var(--fs-10); font-weight: var(--fw-semibold); letter-spacing: 0.06em; text-transform: uppercase; } +.fsh-tpl-preview, .fsh-tpl-rules { flex: 1; min-height: 0; margin: 0; padding: 0; overflow-y: auto; list-style: none; } +.fsh-tpl-part { display: grid; grid-template-columns: minmax(0, 0.9fr) minmax(0, 1fr) 12px minmax(0, 1.1fr); align-items: center; gap: var(--space-1); height: 28px; padding: 0 var(--space-1); border-bottom: 1px solid var(--line-0); font-size: var(--fs-11); } +.fsh-tpl-part > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fsh-tpl-part-name { color: var(--text-primary); } +.fsh-tpl-part-from { color: var(--text-muted); font-family: var(--mono); } +.fsh-tpl-part-arrow { display: inline-flex; color: var(--text-faint); } +.fsh-tpl-part-to { color: var(--accent-ink); } +.fsh-tpl-part.is-same .fsh-tpl-part-to { color: var(--text-faint); } +.fsh-tpl-rules { counter-reset: tplrule; } +.fsh-tpl-rule { display: flex; flex-direction: column; gap: 1px; padding: var(--space-1); border-bottom: 1px solid var(--line-0); font-size: var(--fs-11); line-height: 1.4; } +.fsh-tpl-rule-when { color: var(--text-secondary); } +.fsh-tpl-rule-then { color: var(--text-primary); } +.fsh-tpl-rule.is-invalid .fsh-tpl-rule-then { color: var(--warn); } +.fsh-tpl-actions { display: flex; align-items: center; gap: var(--space-2); padding-top: var(--space-2); } +.fsh-tpl-actions .fsh-btn:disabled { opacity: 0.5; cursor: default; } +.fsh-tpl-gap { flex: 1; } +.fsh-tpl-said { min-height: calc(var(--fs-11) * 1.45 * 2); margin: 0; color: var(--text-secondary); font-size: var(--fs-11); line-height: 1.45; overflow-wrap: anywhere; } +.fsh-tpl-said.is-error { color: var(--warn); } + +.fsh-tpl-editor { display: flex; flex-direction: column; flex: 1; min-height: 0; } +.fsh-tpl-ed { display: flex; flex-direction: column; gap: var(--space-2); flex: 1; min-height: 0; } +.fsh-tpl-ed-row { display: grid; grid-template-columns: 120px minmax(0, 1fr); align-items: center; gap: var(--space-2); color: var(--text-muted); font-size: var(--fs-12); } +.fsh-tpl-ed-row .fsh-input { min-width: 0; font-size: var(--fs-12); } +.fsh-tpl-ed-row input { height: var(--ctl-md); } +.fsh-tpl-ed-row textarea { resize: none; } +.fsh-tpl-ed-legend, .fsh-tpl-ed-rule { display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr) minmax(0, 1.4fr) 56px; align-items: center; gap: var(--space-1); } +.fsh-tpl-ed-legend { color: var(--text-faint); font-size: var(--fs-10); } +.fsh-tpl-ed-rules { flex: 1; min-height: 0; margin: 0; padding: 0; overflow-y: auto; list-style: none; } +.fsh-tpl-ed-rule { padding: 2px 0; } +.fsh-tpl-ed-rule .fsh-input { height: var(--ctl-md); min-width: 0; font-size: var(--fs-11); } +.fsh-tpl-ed-when { display: flex; gap: 2px; min-width: 0; } +.fsh-tpl-ed-when select { flex: 1; min-width: 0; } +.fsh-tpl-ed-when input { width: 84px; } +.fsh-tpl-ed-when input[hidden] { display: none; } +.fsh-tpl-ed-tools { display: inline-flex; gap: 2px; } +.fsh-tpl-ed-tools .fsh-icon-btn { width: var(--ctl-md); height: var(--ctl-md); } +.fsh-tpl-ed-tools .fsh-icon-btn:disabled { opacity: 0.4; cursor: default; } +.fsh-tpl-ed-add { display: inline-flex; align-items: center; gap: var(--space-1); align-self: flex-start; } +.fsh-tpl-ed-error { min-height: calc(var(--fs-11) * 1.45); margin: 0; color: var(--warn); font-size: var(--fs-11); line-height: 1.45; } +.fsh-tpl-import select:disabled { opacity: 0.6; } diff --git a/frontend/src/ui/timeline/curves.ts b/frontend/src/ui/timeline/curves.ts new file mode 100644 index 00000000..d61016b0 --- /dev/null +++ b/frontend/src/ui/timeline/curves.ts @@ -0,0 +1,141 @@ +import { api } from '../../shell/api'; +import { q, setAttr, setClass, setHidden } from '../../shell/dom'; +import { body, CMD, trackSignature, type TrackInfo } from './model'; +import type { Timeline } from './panel'; +import { cssColour, PAD_PX, viewRange } from './view'; + +const CURVES_KEY = 'formshot.timeline.curves'; +const MAX_SAMPLES = 240; +const COMPONENT_VARS = ['--danger', '--ok', '--accent-color', '--warn']; + +interface Curve { sig: string; times: number[]; series: number[][]; loading: boolean } + +function numbers(v: unknown): number[] | null { + if (typeof v === 'number') return [v]; + if (typeof v === 'boolean') return [v ? 1 : 0]; + if (Array.isArray(v) && v.every((x) => typeof x === 'number')) return v as number[]; + return null; +} + +function unwrap(rows: number[][]): number[][] { + const out = rows.map((r) => r.slice()); + for (let i = 1; i < out.length; i++) { + for (let c = 0; c < out[i].length; c++) { + const prev = out[i - 1][c]; + let v = out[i][c]; + while (v - prev > 180) v -= 360; + while (v - prev < -180) v += 360; + out[i][c] = v; + } + } + return out; +} + +export class Curves { + private readonly shown: Set; + private readonly cache = new Map(); + + constructor(private readonly tl: Timeline) { + let stored: string[] = []; + try { stored = JSON.parse(localStorage.getItem(CURVES_KEY) ?? '[]') as string[]; } catch { stored = []; } + this.shown = new Set(Array.isArray(stored) ? stored.map(String) : []); + tl.lanes.onLane((lane, tr, changed) => this.lane(lane, tr, changed)); + tl.view.onResize(() => this.redrawAll()); + tl.view.lanes.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-act="curve"]'); + const lane = b?.closest('.fsh-tl-lane'); + if (!b || !lane?.dataset.track) return; + this.toggle(lane.dataset.track); + }); + } + + toggle(track: string): void { + if (this.shown.has(track)) this.shown.delete(track); + else this.shown.add(track); + try { localStorage.setItem(CURVES_KEY, JSON.stringify([...this.shown])); } catch { /* storage may be off */ } + const lane = this.laneNode(track); + const tr = this.tl.lanes.track(track); + if (lane && tr) this.lane(lane, tr, true); + } + + private laneNode(track: string): HTMLElement | null { + return this.tl.view.lanes.querySelector(`.fsh-tl-lane[data-key="${CSS.escape(track)}"]`); + } + + private lane(lane: HTMLElement, tr: TrackInfo, changed: boolean): void { + const on = this.shown.has(tr.id); + const btn = lane.querySelector('button[data-act="curve"]'); + if (btn) setAttr(btn, 'aria-pressed', on ? 'true' : 'false'); + setClass(lane, 'is-curve', on); + const canvas = q(lane, '.fsh-tl-curve'); + setHidden(canvas, !on); + if (!on) return; + const s = this.tl.store.status; + const sig = `${trackSignature(tr)}|${s.start}|${s.end}|${s.fps}`; + const have = this.cache.get(tr.id); + if (have && have.sig === sig) { if (changed && !have.loading) this.draw(canvas, have); return; } + void this.load(tr, sig); + } + + private async load(tr: TrackInfo, sig: string): Promise { + const s = this.tl.store.status; + const r = viewRange(s); + const n = Math.max(2, Math.min(MAX_SAMPLES, Math.round((r.end - r.start) * s.fps) + 1)); + const times = Array.from({ length: n }, (_, i) => r.start + ((r.end - r.start) * i) / (n - 1)); + const entry: Curve = { sig, times, series: this.cache.get(tr.id)?.series ?? [], loading: true }; + this.cache.set(tr.id, entry); + try { + const o = body(await api.dispatch(CMD.sample, { target: tr.target, times }, { timeoutMs: 15000 })); + if (this.cache.get(tr.id) !== entry) return; + const raw = Array.isArray(o.euler_deg) ? o.euler_deg : Array.isArray(o.values) ? o.values : []; + let rows = raw.map(numbers).filter((x): x is number[] => x !== null); + if (Array.isArray(o.euler_deg)) rows = unwrap(rows); + const width = rows[0]?.length ?? 0; + entry.series = Array.from({ length: width }, (_, c) => rows.map((row) => row[c] ?? 0)); + } catch { + entry.series = []; + } + entry.loading = false; + const lane = this.laneNode(tr.id); + if (lane && this.shown.has(tr.id)) this.draw(q(lane, '.fsh-tl-curve'), entry); + } + + private redrawAll(): void { + for (const lane of this.tl.view.lanes.querySelectorAll('.fsh-tl-lane.is-curve')) { + const c = this.cache.get(lane.dataset.key ?? ''); + if (c && !c.loading) this.draw(q(lane, '.fsh-tl-curve'), c); + } + } + + private draw(canvas: HTMLCanvasElement, c: Curve): void { + const dpr = Math.min(window.devicePixelRatio || 1, 2); + const w = Math.max(1, Math.round(canvas.clientWidth * dpr)); + const h = Math.max(1, Math.round(canvas.clientHeight * dpr)); + if (canvas.width !== w) canvas.width = w; + if (canvas.height !== h) canvas.height = h; + const g = canvas.getContext('2d'); + if (!g) return; + g.clearRect(0, 0, w, h); + if (!c.series.length || c.times.length < 2) return; + let lo = Infinity, hi = -Infinity; + for (const s of c.series) for (const v of s) { if (v < lo) lo = v; if (v > hi) hi = v; } + if (!Number.isFinite(lo)) return; + if (hi - lo < 1e-9) { lo -= 1; hi += 1; } + const pad = PAD_PX * dpr; + const top = 8 * dpr, bottom = h - 8 * dpr; + const t0 = c.times[0], t1 = c.times[c.times.length - 1]; + g.lineWidth = 1.5 * dpr; + c.series.forEach((series, i) => { + g.strokeStyle = c.series.length === 1 ? cssColour(canvas, '--text-secondary', '#aaa') : cssColour(canvas, COMPONENT_VARS[i % COMPONENT_VARS.length], '#aaa'); + g.globalAlpha = 0.85; + g.beginPath(); + series.forEach((v, j) => { + const x = pad + ((c.times[j] - t0) / (t1 - t0)) * (w - 2 * pad); + const y = bottom - ((v - lo) / (hi - lo)) * (bottom - top); + if (j === 0) g.moveTo(x, y); else g.lineTo(x, y); + }); + g.stroke(); + }); + g.globalAlpha = 1; + } +} diff --git a/frontend/src/ui/timeline/edits.ts b/frontend/src/ui/timeline/edits.ts new file mode 100644 index 00000000..32a292d3 --- /dev/null +++ b/frontend/src/ui/timeline/edits.ts @@ -0,0 +1,104 @@ +import { toastError } from '../../shell/toast'; +import type { Workspace } from '../context'; +import { CMD } from './model'; + +interface Gesture { name: string; pending: Record | null; inflight: Promise | null; queued: boolean } + +export class TimelineEdits { + private readonly open = new Map(); + + constructor(private readonly ws: Workspace) {} + + live(gesture: string, name: string, args: Record): void { + const g = this.gesture(gesture, name); + g.name = name; + g.pending = args; + if (g.queued) return; + g.queued = true; + requestAnimationFrame(() => { g.queued = false; this.pump(g); }); + } + + async commit(gesture: string, name: string, args: Record | null): Promise { + const g = this.gesture(gesture, name); + if (args) { g.name = name; g.pending = args; } + this.open.delete(gesture); + let ok = true; + for (;;) { + if (g.inflight) { await g.inflight; continue; } + if (!g.pending) break; + const next = g.pending; + g.pending = null; + g.inflight = this.send(g.name, next, false).then((r) => { ok = r; }).finally(() => { g.inflight = null; }); + } + await this.barrier(); + return ok; + } + + cancel(gesture: string): void { + const g = this.open.get(gesture); + if (g) g.pending = null; + this.open.delete(gesture); + } + + async once(name: string, args: Record): Promise { + let out: unknown; + try { + out = await this.ws.client.dispatch(name, args); + } catch (err) { + toastError(err); + return undefined; + } + await this.barrier(); + return out; + } + + async group(calls: ReadonlyArray]>): Promise { + if (!calls.length) return 0; + const grouped = calls.length > 1 && this.ws.canRun(CMD.begin) && this.ws.canRun(CMD.end); + if (grouped) await this.ws.client.dispatch(CMD.begin, {}).catch(() => undefined); + let done = 0; + let failure: unknown = null; + for (const [name, args] of calls) { + try { + await this.ws.client.dispatch(name, args); + done++; + } catch (err) { + failure ??= err; + } + } + if (grouped) await this.ws.client.dispatch(CMD.end, {}).catch(() => undefined); + else await this.barrier(); + if (failure) toastError(failure); + return done; + } + + private async send(name: string, args: Record, quiet: boolean): Promise { + try { + await this.ws.client.dispatch(name, args); + return true; + } catch (err) { + if (!quiet) toastError(err); + return false; + } + } + + private async barrier(): Promise { + if (this.ws.canRun(CMD.barrier)) await this.ws.client.dispatch(CMD.barrier, {}).catch(() => undefined); + } + + private gesture(key: string, name: string): Gesture { + let g = this.open.get(key); + if (!g) { g = { name, pending: null, inflight: null, queued: false }; this.open.set(key, g); } + return g; + } + + private pump(g: Gesture): void { + if (g.inflight || !g.pending) return; + const args = g.pending; + g.pending = null; + g.inflight = this.send(g.name, args, true).finally(() => { + g.inflight = null; + if (g.pending && !g.queued) { g.queued = true; requestAnimationFrame(() => { g.queued = false; this.pump(g); }); } + }); + } +} diff --git a/frontend/src/ui/timeline/follow.ts b/frontend/src/ui/timeline/follow.ts new file mode 100644 index 00000000..81b77d70 --- /dev/null +++ b/frontend/src/ui/timeline/follow.ts @@ -0,0 +1,36 @@ +import { events } from '../../shell/events'; +import type { Workspace } from '../context'; +import { KeyedCamera } from './keyed-camera'; +import { TIME_EVENT } from './model'; +import type { Timeline } from './panel'; + +const POSE_STREAMED_MS = 500; +const POSE_RASTER_MS = 120; + +/** + * What the rest of the window does when the timeline plays or shows another time. Playing switches the streamed + * viewport to its cheaper preview (RenderLoop.setPlayback). A shown time re-reads the scene summary (posed world and + * bounds at that time; its revision moves with the time), and with it the raster's scene.meshes (posed instances), + * so the selection outline, the gizmo and the raster view modes follow the time; while playing at most every + * POSE_STREAMED_MS (streamed picture) or POSE_RASTER_MS (raster modes). + */ +export function followTime(ws: Workspace, tl: Timeline): void { + let playing = false; + let timer = 0; + const samples = (): number => { + const s = ws.client.summary?.render?.samples; + return typeof s === 'number' && Number.isFinite(s) ? s : 0; + }; + tl.player.onChange(() => { + if (playing === tl.player.playing) return; + playing = tl.player.playing; + ws.render.setPlayback(playing, samples()); + }); + ws.client.onSummary(() => ws.render.followSamples(samples())); + new KeyedCamera(tl); + events.on(TIME_EVENT, () => { + if (!tl.player.playing) { window.clearTimeout(timer); timer = 0; ws.client.scheduleRefresh(0); return; } + if (timer) return; + timer = window.setTimeout(() => { timer = 0; ws.client.scheduleRefresh(0); }, ws.render.isSuspended ? POSE_RASTER_MS : POSE_STREAMED_MS); + }); +} diff --git a/frontend/src/ui/timeline/glyphs.ts b/frontend/src/ui/timeline/glyphs.ts new file mode 100644 index 00000000..ae792498 --- /dev/null +++ b/frontend/src/ui/timeline/glyphs.ts @@ -0,0 +1,25 @@ +const s = (body: string): string => ``; + +const GLYPHS = { + toStart: s(''), + toEnd: s(''), + stepBack: s(''), + stepForward: s(''), + play: s(''), + pause: s(''), + loop: s(''), + key: s(''), + rig: s(''), + curve: s(''), + more: s(''), + chevron: s(''), + remove: s(''), + point: s(''), + close: s(''), +} as const; + +export type GlyphName = keyof typeof GLYPHS; + +export function glyph(name: GlyphName, size = 16): string { + return ``; +} diff --git a/frontend/src/ui/timeline/index.ts b/frontend/src/ui/timeline/index.ts new file mode 100644 index 00000000..48c597b4 --- /dev/null +++ b/frontend/src/ui/timeline/index.ts @@ -0,0 +1,49 @@ +import './timeline.css'; +import { refreshState, registerCommands, registerMenu, registerPanel } from '../../shell/registry'; +import type { Workspace } from '../context'; +import { followTime } from './follow'; +import { CMD } from './model'; +import { Timeline } from './panel'; + +export const TIMELINE_COMMANDS = { + toggle: 'timeline.toggle', + play: 'timeline.play', + turntable: 'timeline.addTurntable', +} as const; + +export function mountTimeline(ws: Workspace): Timeline { + const timeline = new Timeline(ws); + registerPanel({ + id: 'timeline', + slot: 'viewport', + order: 20, + title: 'Timeline', + mount: (host) => timeline.mount(host), + }); + registerCommands([ + { + id: TIMELINE_COMMANDS.toggle, label: 'Timeline', group: 'View', + description: 'Show or hide the timeline under the viewport: keys, rigs and playback.', + checked: () => timeline.open, + run: () => { timeline.setOpen(!timeline.open); if (timeline.open) timeline.focus(); }, + }, + { + id: TIMELINE_COMMANDS.play, label: 'Play Animation', group: 'Animation', + description: 'Play or pause the animation in the viewport.', + enabled: () => timeline.player.canPlay, + checked: () => timeline.player.playing, + run: () => timeline.player.toggle(), + }, + { + id: TIMELINE_COMMANDS.turntable, label: 'Add Turntable', group: 'Animation', + description: 'Turn the product, or the selected part, about its centre as a seamless loop.', + enabled: () => ws.canRun(CMD.turntable), + run: () => { timeline.setOpen(true); requestAnimationFrame(() => timeline.rigs.openTurntable()); }, + }, + ]); + registerMenu({ id: 'view', items: [{ command: TIMELINE_COMMANDS.toggle, section: 1 }] }); + timeline.player.onChange(refreshState); + timeline.store.onChange(refreshState); + followTime(ws, timeline); + return timeline; +} diff --git a/frontend/src/ui/timeline/keyed-camera.css b/frontend/src/ui/timeline/keyed-camera.css new file mode 100644 index 00000000..82ef2abe --- /dev/null +++ b/frontend/src/ui/timeline/keyed-camera.css @@ -0,0 +1,3 @@ +.fsh-tl-camoffer { bottom: var(--space-3); left: 50%; gap: var(--space-2); padding: var(--space-1) var(--space-1) var(--space-1) var(--space-3); transform: translateX(-50%); color: var(--text-secondary); font-size: var(--fs-12); white-space: nowrap; visibility: hidden; } +.fsh-tl-camoffer.is-on { visibility: visible; } +.fsh-tl-camoffer .is-absent { display: none; } diff --git a/frontend/src/ui/timeline/keyed-camera.ts b/frontend/src/ui/timeline/keyed-camera.ts new file mode 100644 index 00000000..16b4d1c8 --- /dev/null +++ b/frontend/src/ui/timeline/keyed-camera.ts @@ -0,0 +1,98 @@ +import './keyed-camera.css'; +import { el, q, setAttr, setClass } from '../../shell/dom'; +import { events } from '../../shell/events'; +import { getCommand, runCommand } from '../../shell/registry'; +import { t } from '../../i18n'; +import { TIME_EVENT } from './model'; +import type { Timeline } from './panel'; + +const INTERACTION = 'render.interaction'; + +/** + * Navigating the viewport while the shown time puts the active camera under keys or a camera rig. The engine renders + * the keyed camera at that time, so the streamed picture would not move; the view switches to Material Preview (the + * raster draws the navigated camera and the posed parts) for as long as the view differs from the keys, and offers + * Key camera here (keys position, target and focal length at the shown time) or Back to the keyed view. Changing the + * time also goes back: the camera is then where its keys put it, and the streamed picture returns. A camera rig (orbit, + * path) is applied after the keys, so keying would not hold the view there: under a rig only Back is offered. + */ +export class KeyedCamera { + private readonly node: HTMLElement; + private moved = false; + private restore: string | null = null; + private shownTime: number | null = null; + + constructor(private readonly tl: Timeline) { + this.node = el(``); + q(this.node, '.fsh-tl-camoffer-text').textContent = t('The view has left the keyed camera.'); + q(this.node, '[data-act="key"]').textContent = t('Key camera here'); + q(this.node, '[data-act="back"]').textContent = t('Back to the keyed view'); + this.node.title = t('The keys decide the camera at this time, so the view shows Material Preview until you key it here or change the time.'); + q(this.node, '[data-act="key"]').addEventListener('click', () => void this.keyHere()); + q(this.node, '[data-act="back"]').addEventListener('click', () => this.back()); + tl.ws.client.onDispatch((n) => { + if (n.name !== INTERACTION || n.args.active !== true) return; + const by = this.driven(); + if (by) this.leave(by); + }); + events.on(TIME_EVENT, (e) => { + const time = typeof e.time === 'number' ? e.time : null; + if (time === this.shownTime) return; + this.shownTime = time; + if (this.moved) this.back(); + }); + } + + /** What moves the active camera at the time shown: a camera rig (which wins over keys), keys, or nothing. */ + driven(): 'rig' | 'keys' | null { + const s = this.tl.store.status; + if (s.time === null) return null; + const active = this.tl.ws.client.summary?.camera?.index; + const index = typeof active === 'number' ? active : 0; + if (this.tl.store.rigs.some((r) => (r.kind === 'orbit' || r.kind === 'camera_path') && (typeof r.raw.camera === 'number' ? r.raw.camera : index) === index)) return 'rig'; + return s.tracks.some((tr) => tr.target.kind === 'camera' && (tr.target.camera ?? 0) === index && tr.keys.length > 0) ? 'keys' : null; + } + + private place(): void { + if (this.node.isConnected) return; + const frame = document.querySelector('.fsh-ws-vp'); + if (frame) frame.appendChild(this.node); + } + + private leave(by: 'rig' | 'keys'): void { + this.place(); + q(this.node, '.fsh-tl-camoffer-text').textContent = by === 'rig' ? t('A camera rig moves this camera at this time.') : t('The view has left the keyed camera.'); + setClass(q(this.node, '[data-act="key"]'), 'is-absent', by === 'rig'); + if (!this.moved) { + this.moved = true; + const mode = getMode(); + this.restore = mode === 'rendered' ? mode : null; + if (this.restore) runCommand('view.mode', { mode: 'material' }); + } + setClass(this.node, 'is-on', true); + setAttr(this.node, 'aria-hidden', null); + } + + back(): void { + if (!this.moved) return; + this.moved = false; + setClass(this.node, 'is-on', false); + setAttr(this.node, 'aria-hidden', 'true'); + if (this.restore) runCommand('view.mode', { mode: this.restore }); + this.restore = null; + } + + private async keyHere(): Promise { + await this.tl.keying.keyCamera(); + this.back(); + } +} + +function getMode(): string { + const mode = getCommand('view.mode')?.run({}); + return typeof mode === 'string' ? mode : ''; +} diff --git a/frontend/src/ui/timeline/keying.ts b/frontend/src/ui/timeline/keying.ts new file mode 100644 index 00000000..61d76a0d --- /dev/null +++ b/frontend/src/ui/timeline/keying.ts @@ -0,0 +1,275 @@ +import { el, escapeHtml, q, setDisabled, setHidden, setHtml, setText, setTitle } from '../../shell/dom'; +import { toast } from '../../shell/toast'; +import { t } from '../../i18n'; +import { glyph } from './glyphs'; +import { CAMERA_FIELD, CMD, fieldText, INTERP_LABEL, INTERPS, LIGHT_FIELD, obj, seconds, TRANSFORM_FIELD, type Target, type TargetKind } from './model'; +import type { Timeline } from './panel'; +import { Popover } from './popover'; + +const KINDS: readonly TargetKind[] = ['material', 'light', 'visibility', 'camera', 'transform']; +const KIND_LABEL: Record = { + material: 'Material parameter', + light: 'Light', + visibility: 'Shown or hidden', + camera: 'Camera setting', + transform: 'Part placement', +}; + +type Fields = Partial>; + +const MOVE_PART = 'scene.set_transform'; +const MOVE_CAMERA = 'camera.set'; + +function nodeArg(id: string | number): number | string { + const n = Number(id); + return Number.isInteger(n) && String(n) === String(id) ? n : id; +} + +export function parseValue(text: string): unknown { + const s = text.trim(); + if (!s) return undefined; + if (s.startsWith('#')) return s; + if (/^(true|on|yes)$/i.test(s)) return 1; + if (/^(false|off|no)$/i.test(s)) return 0; + const parts = s.split(/[\s,;]+/).filter(Boolean).map(Number); + if (!parts.length || parts.some((n) => !Number.isFinite(n))) return null; + return parts.length === 1 ? parts[0] : parts; +} + +export class Keying { + private readonly pop: Popover; + private readonly button: HTMLButtonElement; + private readonly list: HTMLElement; + private readonly form: HTMLElement; + private kind: HTMLSelectElement; + private object: HTMLSelectElement; + private field: HTMLSelectElement; + private value: HTMLInputElement; + private interp: HTMLSelectElement; + private readonly movedParts = new Set(); + private readonly movedCameras = new Set(); + + constructor(private readonly tl: Timeline) { + this.watchEdits(); + this.button = el(``); + tl.menus.appendChild(this.button); + this.pop = new Popover('fsh-tl-keying', 'Add keys at the current frame'); + this.pop.root.innerHTML = `
            +

            + + + + +
            +`; + this.list = q(this.pop.root, '.fsh-tl-keying-list'); + this.form = q(this.pop.root, '.fsh-tl-keying-form'); + this.kind = q(this.form, '[data-k="kind"]'); + this.object = q(this.form, '[data-k="object"]'); + this.field = q(this.form, '[data-k="field"]'); + this.value = q(this.form, '[data-k="value"]'); + this.interp = q(this.form, '[data-k="interp"]'); + setHtml(this.kind, KINDS.map((k) => ``).join(''), 'kinds'); + setHtml(this.interp, INTERPS.map((i) => ``).join(''), 'interps'); + this.pop.onClose(() => { this.button.setAttribute('aria-expanded', 'false'); this.showForm(false); }); + this.button.addEventListener('click', () => this.toggle()); + this.list.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-act]'); + if (!b || b.disabled) return; + if (b.dataset.act === 'transform') { this.pop.close(); void this.keyTransform(); } + else if (b.dataset.act === 'camera') { this.pop.close(); void this.keyCamera(); } + else if (b.dataset.act === 'pick') this.showForm(true); + }); + this.kind.addEventListener('change', () => { this.fillObjects(); this.fillFields(); }); + this.object.addEventListener('change', () => this.fillFields()); + q(this.form, '[data-act="back"]').addEventListener('click', () => this.showForm(false)); + this.form.addEventListener('submit', (e) => { e.preventDefault(); void this.addPicked(); }); + tl.ws.client.onSummary(() => this.paint()); + tl.ws.client.onCatalogue(() => this.paint()); + tl.ws.client.onState(() => this.paint()); + tl.store.onChange(() => this.paint()); + this.paint(); + } + + get anchor(): HTMLButtonElement { return this.button; } + + toggle(): void { + if (this.pop.isOpen) { this.pop.close(); return; } + this.button.setAttribute('aria-expanded', 'true'); + this.pop.open(this.button); + this.paint(); + this.pop.place(); + } + + openPicker(): void { + if (!this.pop.isOpen) this.toggle(); + this.showForm(true); + } + + private selection(): string[] { + const s = this.tl.ws.client.summary; + return (s?.selection ?? []).map(String).filter((id) => s?.nodes.some((n) => String(n.id) === id)); + } + + private paint(): void { + const can = this.tl.ws.canRun(CMD.key); + setDisabled(this.button, !can); + setTitle(this.button, can ? t('Add keys at the current frame') : this.tl.ws.why(CMD.key)); + if (!this.pop.isOpen) return; + setText(q(this.pop.root, '.fsh-tl-keying-at'), t('At frame {frame} ({time})', { frame: this.frame(), time: seconds(this.tl.player.displayTime()) })); + const sel = this.selection(); + const tBtn = q(this.list, '[data-act="transform"]'); + setDisabled(tBtn, !can || sel.length === 0); + setText(q(this.list, '[data-note="transform"]'), sel.length === 0 ? t('Select one or more parts first') : sel.length === 1 ? t('Position, rotation and scale of 1 selected part') : t('Position, rotation and scale of {n} selected parts', { n: sel.length })); + const cam = this.tl.ws.client.summary?.camera; + setDisabled(q(this.list, '[data-act="camera"]'), !can || !cam); + setText(q(this.list, '[data-note="camera"]'), t('Position, look-at point and focal length of {name}', { name: typeof cam?.name === 'string' ? cam.name : t('the active camera') })); + } + + private frame(): number { + const s = this.tl.store.status; + return Math.round((this.tl.player.displayTime() - s.start) * s.fps); + } + + private showForm(on: boolean): void { + setHidden(this.form, !on); + setHidden(this.list, on); + if (on) { + const sel = this.selection(); + const nodes = this.tl.ws.client.summary?.nodes ?? []; + const light = sel.find((id) => nodes.find((n) => String(n.id) === id)?.kind === 'light'); + if (light) this.kind.value = 'light'; + this.fillObjects(); + this.fillFields(); + this.value.value = ''; + this.pop.place(); + this.kind.focus(); + } else this.pop.place(); + } + + private fields(): Fields { + const out: Fields = {}; + const args = obj(this.tl.ws.client.entry(CMD.key)?.args); + const target = obj(obj(args?.properties)?.target); + for (const item of Array.isArray(target?.oneOf) ? target.oneOf : []) { + const props = obj(obj(item)?.properties); + const kind = obj(props?.kind)?.const; + if (typeof kind !== 'string') continue; + const list = obj(props?.field)?.enum ?? obj(props?.param)?.enum; + out[kind as TargetKind] = Array.isArray(list) ? list.map(String) : []; + } + if (!out.transform) out.transform = Object.keys(TRANSFORM_FIELD); + if (!out.camera) out.camera = Object.keys(CAMERA_FIELD); + if (!out.light) out.light = Object.keys(LIGHT_FIELD); + if (!out.visibility) out.visibility = []; + return out; + } + + private fillObjects(): void { + const kind = this.kind.value as TargetKind; + const s = this.tl.ws.client.summary; + const sel = this.selection(); + let options: [string, string][] = []; + let pick = ''; + if (kind === 'material') { + options = (s?.materials ?? []).map((m) => [String(m.key), typeof m.name === 'string' ? m.name : String(m.key)]); + const part = s?.nodes.find((n) => sel.includes(String(n.id)) && typeof n.raw.material === 'string'); + pick = part ? String(part.raw.material) : ''; + } else if (kind === 'camera') { + options = (s?.cameras ?? []).map((c) => [String(c.index), typeof c.name === 'string' ? c.name : String(c.index)]); + pick = String(s?.camera?.index ?? ''); + } else { + const want = kind === 'light' ? (k: string) => k === 'light' : (k: string) => k !== 'light'; + options = (s?.nodes ?? []).filter((n) => want(n.kind)).map((n) => [String(n.id), n.name]); + pick = sel.find((id) => options.some(([v]) => v === id)) ?? ''; + } + const key = `${kind}:${JSON.stringify(options)}`; + setHtml(this.object, options.map(([v, label]) => ``).join(''), key); + if (pick && options.some(([v]) => v === pick)) this.object.value = pick; + setDisabled(this.object, options.length === 0); + } + + private fillFields(): void { + const kind = this.kind.value as TargetKind; + const list = this.fields()[kind] ?? []; + const label = (f: string): string => t(fieldText({ kind, field: f, param: f })); + setHtml(this.field, list.map((f) => ``).join(''), `${kind}:${list.join(',')}`); + setHidden(this.field.closest('label') as HTMLElement, kind === 'visibility'); + setDisabled(q(this.form, '[data-act="add"]'), this.object.options.length === 0 || !this.tl.ws.canRun(CMD.key)); + } + + private target(): Target | null { + const kind = this.kind.value as TargetKind; + const which = this.object.value; + if (!which) return null; + switch (kind) { + case 'material': return { kind, material: nodeArg(which), param: this.field.value }; + case 'camera': return { kind, camera: Number(which), field: this.field.value }; + case 'light': return { kind, node: nodeArg(which), field: this.field.value }; + case 'transform': return { kind, node: nodeArg(which), field: this.field.value }; + case 'visibility': return { kind, node: nodeArg(which) }; + } + return null; + } + + private async addPicked(): Promise { + const target = this.target(); + if (!target) return; + const value = parseValue(this.value.value); + if (value === null) { toast(t('The value is not a number, a list of numbers or a #rrggbb colour'), 'error'); this.value.focus(); return; } + const args: Record = { target, time: this.tl.player.displayTime(), interpolation: this.interp.value }; + if (value !== undefined) args.value = value; + const done = await this.tl.edits.once(CMD.key, args); + if (done !== undefined) { this.pop.close(); this.reveal(); } + } + + private reveal(): void { + this.tl.setOpen(true); + this.tl.store.schedule(0); + } + + private watchEdits(): void { + this.tl.ws.client.onDispatch((n) => { + if (n.name === MOVE_PART && n.args.id !== undefined) this.movedParts.add(String(n.args.id)); + else if (n.name === MOVE_CAMERA) this.movedCameras.add(String(n.args.index ?? this.tl.ws.client.summary?.camera?.index ?? 0)); + }); + } + + async keyTransform(): Promise { + const sel = this.selection(); + if (!sel.length) { toast(t('Select one or more parts first')); return; } + const time = this.tl.player.displayTime(); + const nodes = this.tl.ws.client.summary?.nodes ?? []; + const calls = sel.flatMap((id) => { + const trs = this.movedParts.has(id) ? obj(nodes.find((n) => String(n.id) === id)?.raw.trs) : null; + return (['translation', 'rotation', 'scale'] as const).map((field) => { + const args: Record = { target: { kind: 'transform', node: nodeArg(id), field }, time }; + if (Array.isArray(trs?.[field])) args.value = trs[field]; + return [CMD.key, args] as const; + }); + }); + if (await this.tl.edits.group(calls)) { for (const id of sel) this.movedParts.delete(id); this.reveal(); } + } + + async keyCamera(): Promise { + const cam = this.tl.ws.client.summary?.camera; + const index = typeof cam?.index === 'number' ? cam.index : 0; + const time = this.tl.player.displayTime(); + const moved = this.movedCameras.has(String(index)); + const stored: Record = { position: cam?.position, target: cam?.target, focal_length: cam?.focal_length_mm }; + const calls = (['position', 'target', 'focal_length'] as const).map((field) => { + const args: Record = { target: { kind: 'camera', camera: index, field }, time }; + if (moved && stored[field] !== undefined) args.value = stored[field]; + return [CMD.key, args] as const; + }); + if (await this.tl.edits.group(calls)) { this.movedCameras.delete(String(index)); this.reveal(); } + } +} diff --git a/frontend/src/ui/timeline/lanes.ts b/frontend/src/ui/timeline/lanes.ts new file mode 100644 index 00000000..72eff8df --- /dev/null +++ b/frontend/src/ui/timeline/lanes.ts @@ -0,0 +1,252 @@ +import { el, patchList, q, setAttr, setClass, setStyleVar, setText, setTitle } from '../../shell/dom'; +import { t } from '../../i18n'; +import { glyph } from './glyphs'; +import { CMD, fieldText, INTERP_LABEL, INTERPS, objectName, seconds, snapTime, trackSignature, type Interp, type KeyInfo, type TrackInfo } from './model'; +import type { Timeline } from './panel'; +import { Popover } from './popover'; +import { fraction, timeAt } from './view'; + +const DRAG_SLOP_PX = 3; +const HOLD_MS = 1500; + +const keyId = (track: string, key: string): string => `${track}\n${key}`; + +interface Drag { pointer: number; x0: number; track: string; key: string; node: HTMLElement; area: HTMLElement; moved: boolean; time: number } + +export class Lanes { + readonly selected = new Set(); + private readonly held = new Map(); + private readonly menu: Popover; + private menuFor: { track: string; key: string } | null = null; + private drag: Drag | null = null; + private readonly laneFns = new Set<(lane: HTMLElement, track: TrackInfo, changed: boolean) => void>(); + + constructor(private readonly tl: Timeline) { + this.menu = new Popover('fsh-tl-menu', 'Key', 'menu'); + this.menu.root.innerHTML = `

            Interpolation to the next key

            +${INTERPS.map((i) => ``).join('')} + + +`; + this.menu.root.addEventListener('click', (e) => this.menuClick(e)); + this.listen(); + tl.store.onChange((what) => { if (what === 'status') this.sync(); }); + tl.player.onChange(() => this.paintNow()); + tl.ws.client.onSummary(() => this.sync()); + this.sync(); + } + + onLane(fn: (lane: HTMLElement, track: TrackInfo, changed: boolean) => void): void { this.laneFns.add(fn); } + + track(id: string): TrackInfo | undefined { return this.tl.store.status.tracks.find((x) => x.id === id); } + + sync(): void { + const s = this.tl.store.status; + const live = new Set(); + for (const tr of s.tracks) for (const k of tr.keys) live.add(keyId(tr.id, k.id)); + for (const k of [...this.selected]) if (!live.has(k)) this.selected.delete(k); + patchList(this.tl.view.lanes, s.tracks, { + key: (tr) => tr.id, + create: (tr) => this.createLane(tr), + update: (node, tr) => this.updateLane(node, tr), + }); + this.paintNow(); + } + + private createLane(tr: TrackInfo): HTMLElement { + const node = el(`
            +
            + + +
            +
            +
            `); + node.dataset.track = tr.id; + this.updateLane(node, tr); + return node; + } + + private updateLane(node: HTMLElement, tr: TrackInfo): void { + const summary = this.tl.ws.client.summary; + const s = this.tl.store.status; + const obj = objectName(tr.target, summary); + const field = t(fieldText(tr.target)); + const sig = `${trackSignature(tr)}|${obj}|${field}|${s.start}|${s.end}|${s.fps}`; + const changed = node.dataset.sig !== sig; + if (changed) { + node.dataset.sig = sig; + setText(q(node, '.fsh-tl-lane-obj'), obj); + setText(q(node, '.fsh-tl-lane-field'), field); + setTitle(q(node, '.fsh-tl-lane-name'), tr.valid ? `${obj}: ${field}` : t('{name}: its object is gone, so this track does nothing', { name: `${obj}: ${field}` })); + setClass(node, 'is-invalid', !tr.valid); + patchList(q(node, '.fsh-tl-keys'), tr.keys, { + key: (k) => k.id, + create: (k) => this.createKey(tr, k), + update: (n, k) => this.updateKey(n, tr, k), + }); + } + for (const fn of this.laneFns) fn(node, tr, changed); + } + + private createKey(tr: TrackInfo, k: KeyInfo): HTMLElement { + const n = el('
            '); + n.dataset.track = tr.id; + this.updateKey(n, tr, k); + return n; + } + + private updateKey(n: HTMLElement, tr: TrackInfo, k: KeyInfo): void { + const id = keyId(tr.id, k.id); + const h = this.held.get(id); + let time = k.time; + if (h) { + if (Math.abs(h.time - k.time) < 1e-4 || performance.now() > h.until) this.held.delete(id); + else time = h.time; + } + if (this.drag && this.drag.track === tr.id && this.drag.key === k.id) time = this.drag.time; + setStyleVar(n, '--f', String(fraction(this.tl.store.status, time))); + setAttr(n, 'data-interp', k.interpolation); + const label = t('Key at {time}, {how}', { time: seconds(k.time), how: t(INTERP_LABEL[k.interpolation]) }); + setAttr(n, 'aria-label', label); + setTitle(n, label); + } + + paintNow(): void { + const s = this.tl.store.status; + const now = this.tl.player.displayTime(); + const half = 0.5 / s.fps; + for (const n of this.tl.view.lanes.querySelectorAll('.fsh-tl-key')) { + const tr = n.dataset.track ?? ''; + const kid = n.dataset.key ?? ''; + const key = this.track(tr)?.keys.find((k) => k.id === kid); + setClass(n, 'is-now', key !== undefined && Math.abs(key.time - now) <= half); + setClass(n, 'is-sel', this.selected.has(keyId(tr, kid))); + } + } + + private selectOnly(track: string, key: string): void { + this.selected.clear(); + this.selected.add(keyId(track, key)); + this.paintNow(); + } + + selectedKeys(): { track: string; key: string }[] { + return [...this.selected].map((k) => { const [track, key] = k.split('\n'); return { track, key }; }); + } + + async deleteSelected(): Promise { + const keys = this.selectedKeys(); + if (!keys.length || !this.tl.ws.canRun(CMD.removeKey)) return; + this.selected.clear(); + await this.tl.edits.group(keys.map(({ track, key }) => [CMD.removeKey, { track, key }] as const)); + } + + private async setInterp(how: Interp): Promise { + const keys = this.selectedKeys(); + if (!keys.length) return; + await this.tl.edits.group(keys.map(({ track, key }) => [CMD.setKey, { track, key, interpolation: how }] as const)); + } + + private openMenu(track: string, key: string, at: { x: number; y: number }, anchor: HTMLElement): void { + if (!this.selected.has(keyId(track, key))) this.selectOnly(track, key); + this.menuFor = { track, key }; + const k = this.track(track)?.keys.find((x) => x.id === key); + for (const b of this.menu.root.querySelectorAll('[data-interp]')) { + if (b.tagName === 'BUTTON') setAttr(b, 'aria-checked', b.dataset.interp === k?.interpolation ? 'true' : 'false'); + } + const many = this.selected.size > 1; + setText(q(this.menu.root, '.fsh-tl-menu-delete'), many ? t('Delete the {n} selected keys', { n: this.selected.size }) : t('Delete this key')); + this.menu.open(anchor, at); + } + + private menuClick(e: MouseEvent): void { + const b = (e.target as HTMLElement).closest('button'); + if (!b) return; + const target = this.menuFor; + this.menu.close(); + if (b.dataset.interp) { void this.setInterp(b.dataset.interp as Interp); return; } + if (b.dataset.act === 'delete') { void this.deleteSelected(); return; } + if (b.dataset.act === 'seek' && target) { + const k = this.track(target.track)?.keys.find((x) => x.id === target.key); + if (k) this.tl.player.scrub(k.time); + } + } + + private listen(): void { + const lanes = this.tl.view.lanes; + lanes.addEventListener('pointerdown', (e) => { + if (e.button !== 0) return; + const keyNode = (e.target as HTMLElement).closest('.fsh-tl-key'); + if (!keyNode) { + if ((e.target as HTMLElement).closest('.fsh-tl-track') && !e.shiftKey && !e.ctrlKey && !e.metaKey) { this.selected.clear(); this.paintNow(); } + return; + } + const track = keyNode.dataset.track ?? ''; + const key = keyNode.dataset.key ?? ''; + const id = keyId(track, key); + this.tl.focus(); + e.preventDefault(); + if (e.shiftKey || e.ctrlKey || e.metaKey) { + if (this.selected.has(id)) this.selected.delete(id); + else this.selected.add(id); + this.paintNow(); + return; + } + if (!this.selected.has(id)) this.selectOnly(track, key); + const k = this.track(track)?.keys.find((x) => x.id === key); + if (!k || !this.tl.ws.canRun(CMD.moveKey)) return; + keyNode.setPointerCapture(e.pointerId); + this.drag = { pointer: e.pointerId, x0: e.clientX, track, key, node: keyNode, area: keyNode.closest('.fsh-tl-track') as HTMLElement, moved: false, time: k.time }; + }); + lanes.addEventListener('pointermove', (e) => { + const d = this.drag; + if (!d || e.pointerId !== d.pointer) return; + if (!d.moved && Math.abs(e.clientX - d.x0) < DRAG_SLOP_PX) return; + if (!d.moved) { d.moved = true; setClass(d.node, 'is-drag', true); this.selectOnly(d.track, d.key); } + const s = this.tl.store.status; + let time = timeAt(s, d.area, e.clientX); + time = e.altKey ? Math.min(s.end, Math.max(s.start, time)) : snapTime(s, time); + if (Math.abs(time - d.time) < 1e-6) return; + d.time = time; + setStyleVar(d.node, '--f', String(fraction(s, time))); + setTitle(d.node, seconds(time)); + this.tl.edits.live(`move:${d.track}:${d.key}`, CMD.moveKey, { track: d.track, key: d.key, time }); + }); + const end = (e: PointerEvent): void => { + const d = this.drag; + if (!d || e.pointerId !== d.pointer) return; + this.drag = null; + setClass(d.node, 'is-drag', false); + if (!d.moved) return; + this.held.set(keyId(d.track, d.key), { time: d.time, until: performance.now() + HOLD_MS }); + void this.tl.edits.commit(`move:${d.track}:${d.key}`, CMD.moveKey, e.type === 'pointerup' ? { track: d.track, key: d.key, time: d.time } : null) + .then(() => this.tl.store.schedule(0)); + }; + lanes.addEventListener('pointerup', end); + lanes.addEventListener('pointercancel', end); + lanes.addEventListener('dblclick', (e) => { + const keyNode = (e.target as HTMLElement).closest('.fsh-tl-key'); + const k = keyNode ? this.track(keyNode.dataset.track ?? '')?.keys.find((x) => x.id === keyNode.dataset.key) : undefined; + if (k) this.tl.player.scrub(k.time); + }); + lanes.addEventListener('contextmenu', (e) => { + const keyNode = (e.target as HTMLElement).closest('.fsh-tl-key'); + if (!keyNode) return; + e.preventDefault(); + this.openMenu(keyNode.dataset.track ?? '', keyNode.dataset.key ?? '', { x: e.clientX, y: e.clientY }, keyNode); + }); + lanes.addEventListener('keydown', (e) => { + const keyNode = (e.target as HTMLElement).closest('.fsh-tl-key'); + if (!keyNode || (e.key !== 'Enter' && e.key !== 'ContextMenu')) return; + e.preventDefault(); + const r = keyNode.getBoundingClientRect(); + this.openMenu(keyNode.dataset.track ?? '', keyNode.dataset.key ?? '', { x: r.left, y: r.top }, keyNode); + }); + lanes.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-act="remove-track"]'); + const lane = b?.closest('.fsh-tl-lane'); + if (!b || !lane?.dataset.track || !this.tl.ws.canRun(CMD.removeTrack)) return; + void this.tl.edits.once(CMD.removeTrack, { track: lane.dataset.track }); + }); + } +} diff --git a/frontend/src/ui/timeline/model.ts b/frontend/src/ui/timeline/model.ts new file mode 100644 index 00000000..eef55182 --- /dev/null +++ b/frontend/src/ui/timeline/model.ts @@ -0,0 +1,224 @@ +import type { SceneSummary } from '../../engine/types'; +import { fieldLabel } from '../material/model'; + +export const CMD = { + status: 'anim.status', + seek: 'anim.seek', + sample: 'anim.sample', + set: 'anim.set', + key: 'anim.key', + setKey: 'anim.set_key', + moveKey: 'anim.move_key', + removeKey: 'anim.remove_key', + removeTrack: 'anim.remove_track', + addRig: 'anim.add_rig', + setRig: 'anim.set_rig', + removeRig: 'anim.remove_rig', + turntable: 'anim.turntable', + orbit: 'anim.orbit', + cameraPath: 'anim.camera_path', + barrier: 'history.barrier', + begin: 'history.begin_group', + end: 'history.end_group', +} as const; + +export const TIME_EVENT = 'ui.anim.time'; + +export type Interp = 'step' | 'linear' | 'smooth' | 'ease'; +export const INTERPS: readonly Interp[] = ['step', 'linear', 'smooth', 'ease']; +export const INTERP_LABEL: Record = { + step: 'Step (hold)', + linear: 'Linear', + smooth: 'Smooth curve', + ease: 'Ease in and out', +}; + +export type TargetKind = 'transform' | 'camera' | 'material' | 'light' | 'visibility'; + +export interface Target { + kind: TargetKind; + node?: number | string; + camera?: number; + material?: number | string; + field?: string; + param?: string; +} + +export interface KeyInfo { id: string; time: number; value: unknown; interpolation: Interp } + +export interface TrackInfo { + id: string; + target: Target; + kind: string; + valid: boolean; + keys: KeyInfo[]; + keyAtTime: string | null; +} + +export type RigKind = 'turntable' | 'orbit' | 'camera_path'; + +export interface RigInfo { + id: string; + kind: RigKind; + name: string; + start: number; + end: number; + raw: Record; +} + +export interface AnimStatus { + time: number | null; + frame: number | null; + start: number; + end: number; + fps: number; + frames: number; + moves: boolean; + rigs: number; + tracks: TrackInfo[]; +} + +export const EMPTY_STATUS: AnimStatus = { time: null, frame: null, start: 0, end: 5, fps: 30, frames: 151, moves: false, rigs: 0, tracks: [] }; + +type Json = Record; +export const obj = (v: unknown): Json | null => (v && typeof v === 'object' && !Array.isArray(v) ? v as Json : null); +const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d); +const str = (v: unknown, d = ''): string => (typeof v === 'string' ? v : d); + +export function body(raw: unknown): Json { + const o = obj(raw) ?? {}; + return obj(o.result) ?? o; +} + +function interpOf(v: unknown): Interp { + return typeof v === 'string' && (INTERPS as readonly string[]).includes(v) ? v as Interp : 'smooth'; +} + +function targetOf(v: unknown): Target | null { + const o = obj(v); + if (!o || typeof o.kind !== 'string') return null; + const t: Target = { kind: o.kind as TargetKind }; + for (const k of ['node', 'camera', 'material', 'field', 'param'] as const) if (o[k] !== undefined) (t as unknown as Json)[k] = o[k]; + return t; +} + +export function parseStatus(raw: unknown): AnimStatus { + const o = body(raw); + const tracks: TrackInfo[] = []; + for (const r of Array.isArray(o.tracks) ? o.tracks : []) { + const tr = obj(r); + const target = targetOf(tr?.target); + if (!tr || !target || typeof tr.id !== 'string') continue; + const keys: KeyInfo[] = []; + for (const k of Array.isArray(tr.keys) ? tr.keys : []) { + const ko = obj(k); + if (!ko || typeof ko.id !== 'string') continue; + keys.push({ id: ko.id, time: num(ko.time, 0), value: ko.value, interpolation: interpOf(ko.interpolation) }); + } + keys.sort((a, b) => a.time - b.time); + tracks.push({ id: tr.id, target, kind: str(tr.kind), valid: tr.valid !== false, keys, keyAtTime: typeof tr.key_at_time === 'string' ? tr.key_at_time : null }); + } + const fps = num(o.fps, 30); + return { + time: typeof o.time === 'number' ? o.time : null, + frame: typeof o.frame === 'number' ? o.frame : null, + start: num(o.start, 0), + end: num(o.end, 5), + fps: fps > 0 ? fps : 30, + frames: num(o.frames, 1), + moves: o.moves === true, + rigs: num(o.rig_count, Array.isArray(o.rigs) ? o.rigs.length : num(o.rigs, 0)), + tracks, + }; +} + +export function parseRigs(animation: unknown): RigInfo[] { + const a = obj(animation); + const out: RigInfo[] = []; + for (const r of Array.isArray(a?.rigs) ? a.rigs : []) { + const o = obj(r); + if (!o || typeof o.id !== 'string') continue; + const kind = o.kind === 'orbit' || o.kind === 'camera_path' ? o.kind : 'turntable'; + out.push({ id: o.id, kind, name: str(o.name, o.id), start: num(o.start, 0), end: num(o.end, 0), raw: o }); + } + return out; +} + +export function hasAnimation(s: AnimStatus): boolean { + return s.tracks.length > 0 || s.rigs > 0; +} + +export function frameOf(s: AnimStatus, time: number): number { + return Math.round((time - s.start) * s.fps + 1e-6); +} + +export function timeOfFrame(s: AnimStatus, frame: number): number { + return s.start + frame / s.fps; +} + +export function lastFrame(s: AnimStatus): number { + return Math.max(0, Math.round((s.end - s.start) * s.fps + 1e-6)); +} + +export function snapTime(s: AnimStatus, time: number): number { + const f = Math.min(lastFrame(s), Math.max(0, frameOf(s, time))); + return timeOfFrame(s, f); +} + +export function shownTime(s: AnimStatus): number { + return s.time ?? s.start; +} + +export function seconds(v: number): string { + return `${v.toFixed(2)} s`; +} + +export function sameTarget(a: Target, b: Target): boolean { + return a.kind === b.kind && String(a.node ?? '') === String(b.node ?? '') && String(a.camera ?? '') === String(b.camera ?? '') + && String(a.material ?? '') === String(b.material ?? '') && (a.field ?? '') === (b.field ?? '') && (a.param ?? '') === (b.param ?? ''); +} + +export const TRANSFORM_FIELD: Record = { translation: 'Position', rotation: 'Rotation', scale: 'Scale' }; +export const CAMERA_FIELD: Record = { + position: 'Camera position', target: 'Look-at point', orientation: 'Camera orientation', focal_length: 'Focal length', + fov: 'Field of view', focus_distance: 'Focus distance', aperture: 'f-number', +}; +export const LIGHT_FIELD: Record = { + power: 'Light power', colour: 'Light colour', temperature: 'Temperature', spread: 'Spread angle', visible: 'Seen by the camera', +}; + +export function fieldText(t: Target): string { + switch (t.kind) { + case 'transform': return TRANSFORM_FIELD[t.field ?? ''] ?? t.field ?? ''; + case 'camera': return CAMERA_FIELD[t.field ?? ''] ?? t.field ?? ''; + case 'light': return LIGHT_FIELD[t.field ?? ''] ?? t.field ?? ''; + case 'material': return fieldLabel(t.param ?? ''); + case 'visibility': return 'Visibility'; + } + return ''; +} + +export function objectName(t: Target, summary: SceneSummary | null): string { + if (t.kind === 'camera') { + const c = summary?.cameras.find((x) => x.index === t.camera); + return typeof c?.name === 'string' ? c.name : `#${String(t.camera ?? '')}`; + } + if (t.kind === 'material') { + const m = summary?.materials.find((x) => String(x.key) === String(t.material)); + return typeof m?.name === 'string' ? m.name : `#${String(t.material ?? '')}`; + } + const n = summary?.nodes.find((x) => String(x.id) === String(t.node)); + return n?.name ?? `#${String(t.node ?? '')}`; +} + +export function trackSignature(tr: TrackInfo): string { + return JSON.stringify([tr.target, tr.valid, tr.keys]); +} + +export function rigSignature(r: RigInfo): string { + return JSON.stringify(r.raw); +} + +export function rigKindLabel(k: RigKind): string { + return k === 'turntable' ? 'Turntable rig' : k === 'orbit' ? 'Camera orbit' : 'Camera path'; +} diff --git a/frontend/src/ui/timeline/panel.ts b/frontend/src/ui/timeline/panel.ts new file mode 100644 index 00000000..1a12119c --- /dev/null +++ b/frontend/src/ui/timeline/panel.ts @@ -0,0 +1,184 @@ +import { el, q, setAttr, setClass, setDisabled, setStyleVar, setText, setTitle, textFieldFocused } from '../../shell/dom'; +import { refreshState } from '../../shell/registry'; +import { t } from '../../i18n'; +import { NumberField } from '../number-field'; +import type { Workspace } from '../context'; +import { Curves } from './curves'; +import { TimelineEdits } from './edits'; +import { glyph } from './glyphs'; +import { Keying } from './keying'; +import { Lanes } from './lanes'; +import { CMD, frameOf, hasAnimation, lastFrame, seconds } from './model'; +import { Player } from './player'; +import { Rigs } from './rigs'; +import { TimelineStore } from './store'; +import { TrackView } from './view'; + +const OPEN_KEY = 'formshot.timeline.open'; +const HEAD_PX = 34; +const BODY_PX = 190; + +export class Timeline { + readonly store: TimelineStore; + readonly player: Player; + readonly edits: TimelineEdits; + readonly root: HTMLElement; + readonly view: TrackView; + readonly lanes: Lanes; + readonly keying: Keying; + readonly rigs: Rigs; + open: boolean; + private slot: HTMLElement | null = null; + private readonly fps: NumberField; + private readonly from: NumberField; + private readonly to: NumberField; + private readonly openFns = new Set<() => void>(); + + constructor(readonly ws: Workspace) { + this.store = new TimelineStore(ws); + this.player = new Player(ws, this.store); + this.edits = new TimelineEdits(ws); + let stored: string | null = null; + try { stored = localStorage.getItem(OPEN_KEY); } catch { stored = null; } + this.open = stored === 'open'; + this.root = el(`
            + +
            +
            `); + this.fps = new NumberField({ label: 'Rate', unit: 'fps', min: 1, max: 240, step: 1, onInput: (v) => this.setRange('fps', v, false), onCommit: (v) => this.setRange('fps', v, true) }); + this.from = new NumberField({ label: 'Begins', unit: 's', step: 0.01, onInput: (v) => this.setRange('start', v, false), onCommit: (v) => this.setRange('start', v, true) }); + this.to = new NumberField({ label: 'Ends', unit: 's', step: 0.01, onInput: (v) => this.setRange('end', v, false), onCommit: (v) => this.setRange('end', v, true) }); + const fields = q(this.root, '.fsh-tl-fields'); + for (const f of [this.fps, this.from, this.to]) fields.appendChild(f.root); + this.view = new TrackView(this); + this.lanes = new Lanes(this); + new Curves(this); + this.keying = new Keying(this); + this.rigs = new Rigs(this); + this.listen(); + this.store.onChange(() => this.paint()); + this.player.onChange(() => this.paint()); + ws.client.onState(() => this.paint()); + ws.client.onCatalogue(() => this.paint()); + } + + get body(): HTMLElement { return q(this.root, '.fsh-tl-body'); } + get menus(): HTMLElement { return q(this.root, '.fsh-tl-menus'); } + + onOpen(fn: () => void): void { this.openFns.add(fn); } + + mount(host: HTMLElement): void { + host.classList.add('fsh-tl-host'); + host.appendChild(this.root); + this.slot = host.parentElement; + this.reserve(); + this.paint(); + this.store.schedule(0); + } + + setOpen(open: boolean): void { + if (open === this.open) return; + this.open = open; + try { localStorage.setItem(OPEN_KEY, open ? 'open' : 'closed'); } catch { /* storage may be off */ } + this.reserve(); + this.paint(); + for (const fn of this.openFns) fn(); + refreshState(); + } + + focus(): void { this.root.focus({ preventScroll: true }); } + + private reserve(): void { + const h = HEAD_PX + (this.open ? BODY_PX : 0); + if (this.slot) setStyleVar(this.slot, '--fsh-tl-reserved', `${h}px`); + setAttr(this.root, 'data-open', this.open ? 'true' : 'false'); + } + + private setRange(field: 'fps' | 'start' | 'end', value: number, commit: boolean): void { + const args = { [field]: value }; + if (commit) void this.edits.commit('range', CMD.set, args); + else this.edits.live('range', CMD.set, args); + } + + paint(): void { + const s = this.store.status; + const can = this.ws.canRun(CMD.status); + const has = hasAnimation(s); + const why = can ? '' : this.ws.why(CMD.status); + setClass(this.root, 'is-empty', !has); + setClass(this.root, 'is-off', !can); + setTitle(q(this.root, '.fsh-tl-head'), why); + const fold = q(this.root, '.fsh-tl-fold'); + setAttr(fold, 'aria-expanded', this.open ? 'true' : 'false'); + const playBtn = q(this.root, '.fsh-tl-play'); + const label = this.player.playing ? t('Pause') : t('Play'); + setTitle(playBtn, label); + setAttr(playBtn, 'aria-label', label); + setAttr(playBtn, 'aria-pressed', this.player.playing ? 'true' : 'false'); + setAttr(q(this.root, '[data-act="loop"]'), 'aria-pressed', this.player.loop ? 'true' : 'false'); + for (const b of this.root.querySelectorAll('.fsh-tl-transport button')) setDisabled(b, !can || !has); + setDisabled(q(this.root, '.fsh-tl-animate'), !can); + const time = this.player.displayTime(); + setText(q(this.root, '.fsh-tl-frame'), `${frameOf(s, time)} / ${lastFrame(s)}`); + setText(q(this.root, '.fsh-tl-time'), seconds(time)); + this.fps.set(s.fps); + this.from.set(s.start); + this.to.set(s.end); + const canSet = can && this.ws.canRun(CMD.set); + for (const f of [this.fps, this.from, this.to]) f.setDisabled(!canSet, canSet ? '' : this.ws.why(CMD.set)); + } + + private listen(): void { + q(this.root, '.fsh-tl-fold').addEventListener('click', () => this.setOpen(!this.open)); + q(this.root, '.fsh-tl-head').addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-act]'); + if (!b || b.disabled) return; + switch (b.dataset.act) { + case 'start': this.player.toStart(); break; + case 'back': this.player.step(-1); break; + case 'play': this.player.toggle(); break; + case 'forward': this.player.step(1); break; + case 'end': this.player.toEnd(); break; + case 'loop': this.player.setLoop(!this.player.loop); break; + case 'animate': + this.setOpen(true); + requestAnimationFrame(() => this.keying.toggle()); + break; + } + }); + this.root.addEventListener('keydown', (e) => { + if (e.defaultPrevented || textFieldFocused() || e.ctrlKey || e.metaKey || e.altKey) return; + const has = hasAnimation(this.store.status); + let handled = true; + if (e.key === ' ' && has) this.player.toggle(); + else if (e.key === 'ArrowLeft' && has) this.player.step(e.shiftKey ? -10 : -1); + else if (e.key === 'ArrowRight' && has) this.player.step(e.shiftKey ? 10 : 1); + else if (e.key === 'Home' && has) this.player.toStart(); + else if (e.key === 'End' && has) this.player.toEnd(); + else if ((e.key === 'Delete' || e.key === 'Backspace') && this.lanes.selected.size) void this.lanes.deleteSelected(); + else if (e.key === 'Escape' && this.lanes.selected.size) { this.lanes.selected.clear(); this.lanes.paintNow(); } + else handled = false; + if (!handled) return; + e.preventDefault(); + e.stopPropagation(); + }); + } +} diff --git a/frontend/src/ui/timeline/player.ts b/frontend/src/ui/timeline/player.ts new file mode 100644 index 00000000..80823ef2 --- /dev/null +++ b/frontend/src/ui/timeline/player.ts @@ -0,0 +1,177 @@ +import { api } from '../../shell/api'; +import { events } from '../../shell/events'; +import type { Workspace } from '../context'; +import { body, CMD, frameOf, hasAnimation, lastFrame, shownTime, snapTime, TIME_EVENT, timeOfFrame } from './model'; +import type { TimelineStore } from './store'; + +const LOOP_KEY = 'formshot.timeline.loop'; +const STREAM_PATIENCE_MS = 1500; +const STREAM_WAIT_MAX_MS = 4000; + +export class Player { + playing = false; + loop: boolean; + private wanted: { time: number | null } | null = null; + private inflight = false; + private sentAt = 0; + private picture = true; + private latency = 0; + private timer: number | undefined; + private raf = 0; + private base = 0; + private began = 0; + private lastWanted: number | null = null; + private emitted: number | null | undefined = undefined; + private readonly fns = new Set<() => void>(); + + constructor(private readonly ws: Workspace, private readonly store: TimelineStore) { + let stored: string | null = null; + try { stored = localStorage.getItem(LOOP_KEY); } catch { stored = null; } + this.loop = stored !== 'off'; + ws.render.onFrame(() => { + if (this.inflight) return; + if (!this.picture && this.sentAt > 0) this.latency = performance.now() - this.sentAt; + this.picture = true; + this.pump(); + }); + store.onChange((what) => { + if (what !== 'status') return; + const t = store.status.time; + if (!this.inflight && this.wanted === null && t !== this.emitted) this.announce(t); + if (this.playing && !hasAnimation(store.status)) this.pause(); + }); + } + + onChange(fn: () => void): () => void { + this.fns.add(fn); + return () => { this.fns.delete(fn); }; + } + + private changed(): void { + for (const fn of this.fns) fn(); + } + + displayTime(): number { + const shown = shownTime(this.store.status); + return (this.inflight || this.wanted) && this.lastWanted !== null ? this.lastWanted : shown; + } + + get canPlay(): boolean { return this.ws.canRun(CMD.seek) && hasAnimation(this.store.status); } + + setLoop(on: boolean): void { + this.loop = on; + try { localStorage.setItem(LOOP_KEY, on ? 'on' : 'off'); } catch { return; } + this.changed(); + } + + toggle(): void { + if (this.playing) this.pause(); + else this.play(); + } + + play(): void { + if (this.playing || !this.canPlay) return; + const s = this.store.status; + let from = this.lastWanted ?? shownTime(s); + if (frameOf(s, from) >= lastFrame(s) || from < s.start) from = s.start; + this.playing = true; + this.base = from; + this.began = performance.now(); + this.lastWanted = null; + this.changed(); + this.tick(); + } + + pause(): void { + if (!this.playing) return; + this.playing = false; + cancelAnimationFrame(this.raf); + this.raf = 0; + this.changed(); + } + + step(delta: number): void { + this.pause(); + const s = this.store.status; + const last = lastFrame(s); + let f = frameOf(s, this.lastWanted ?? shownTime(s)) + delta; + if (f < 0) f = this.loop ? last : 0; + if (f > last) f = this.loop ? 0 : last; + this.seek(timeOfFrame(s, f)); + } + + toStart(): void { this.pause(); this.seek(this.store.status.start); } + + toEnd(): void { this.pause(); this.seek(timeOfFrame(this.store.status, lastFrame(this.store.status))); } + + scrub(time: number): void { + this.pause(); + this.seek(snapTime(this.store.status, time)); + } + + seek(time: number | null): void { + if (!this.ws.canRun(CMD.seek)) return; + this.lastWanted = time; + this.wanted = { time }; + this.pump(); + } + + private tick(): void { + this.raf = 0; + if (!this.playing) return; + const s = this.store.status; + const period = (lastFrame(s) + 1) / s.fps; + let t = this.base + (performance.now() - this.began) / 1000; + let finished = false; + if (t >= s.start + period) { + if (this.loop && period > 0) t = s.start + ((t - s.start) % period); + else { t = timeOfFrame(s, lastFrame(s)); finished = true; } + } + const snapped = timeOfFrame(s, Math.min(lastFrame(s), Math.floor((t - s.start) * s.fps + 1e-6))); + if (snapped !== this.lastWanted) this.seek(snapped); + if (finished) { this.pause(); return; } + this.raf = requestAnimationFrame(() => this.tick()); + } + + private patience(): number { + const interval = 1000 / Math.max(1, this.store.status.fps); + const streamed = !this.ws.render.isSuspended && this.ws.render.running; + if (!streamed) return interval; + const wait = this.latency > 0 ? this.latency * 1.25 : STREAM_PATIENCE_MS; + return Math.max(interval, Math.min(STREAM_WAIT_MAX_MS, wait)); + } + + private pump(): void { + if (this.inflight || !this.wanted) return; + const wait = this.sentAt + this.patience() - performance.now(); + if (!this.picture && wait > 0) { + window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => this.pump(), wait); + return; + } + const { time } = this.wanted; + this.wanted = null; + this.inflight = true; + this.picture = false; + this.sentAt = performance.now(); + void api.dispatch(CMD.seek, { time }, { timeoutMs: 15000 }).then((raw) => { + const o = body(raw); + const shown = typeof o.time === 'number' ? o.time : null; + this.store.setTimeShown(shown, typeof o.frame === 'number' ? o.frame : null); + this.announce(shown); + if (o.change !== 'none') this.ws.render.kick(); + else this.picture = true; + }, () => { + this.picture = true; + this.store.schedule(0); + }).finally(() => { + this.inflight = false; + this.pump(); + }); + } + + private announce(time: number | null): void { + this.emitted = time; + events.emit({ type: TIME_EVENT, time }); + } +} diff --git a/frontend/src/ui/timeline/popover.ts b/frontend/src/ui/timeline/popover.ts new file mode 100644 index 00000000..c5219928 --- /dev/null +++ b/frontend/src/ui/timeline/popover.ts @@ -0,0 +1,53 @@ +import { el, setHidden, setStyleVar } from '../../shell/dom'; + +export class Popover { + readonly root: HTMLElement; + private anchor: HTMLElement | null = null; + private closeFns = new Set<() => void>(); + private readonly outside = (e: PointerEvent): void => { + const target = e.target as Node; + if (!this.root.contains(target) && !this.anchor?.contains(target)) this.close(); + }; + + constructor(className: string, label: string, role = 'dialog') { + this.root = el(``); + this.root.setAttribute('aria-label', label); + this.root.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); this.close(); this.anchor?.focus(); } + }); + (document.getElementById('overlay-root') ?? document.body).appendChild(this.root); + } + + get isOpen(): boolean { return !this.root.hidden; } + + onClose(fn: () => void): void { this.closeFns.add(fn); } + + open(anchor: HTMLElement, at?: { x: number; y: number }): void { + this.anchor = anchor; + setHidden(this.root, false); + this.place(at); + document.addEventListener('pointerdown', this.outside, true); + this.root.querySelector('[data-focus], button:not([disabled]), input:not([disabled]), select:not([disabled])')?.focus(); + } + + place(at?: { x: number; y: number }): void { + if (!this.anchor || this.root.hidden) return; + const r = at ? { left: at.x, right: at.x, top: at.y, bottom: at.y } : this.anchor.getBoundingClientRect(); + const w = this.root.offsetWidth; + const h = this.root.offsetHeight; + const left = Math.max(8, Math.min(window.innerWidth - w - 8, at ? r.left : r.left)); + const above = r.top - h - 4; + const top = above >= 8 ? above : Math.min(window.innerHeight - h - 8, r.bottom + 4); + setStyleVar(this.root, '--fsh-tl-pop-x', `${Math.round(left)}px`); + setStyleVar(this.root, '--fsh-tl-pop-y', `${Math.round(Math.max(8, top))}px`); + } + + toggle(anchor: HTMLElement): void { if (this.isOpen) this.close(); else this.open(anchor); } + + close(): void { + if (this.root.hidden) return; + setHidden(this.root, true); + document.removeEventListener('pointerdown', this.outside, true); + for (const fn of this.closeFns) fn(); + } +} diff --git a/frontend/src/ui/timeline/rigs.ts b/frontend/src/ui/timeline/rigs.ts new file mode 100644 index 00000000..8a62daf7 --- /dev/null +++ b/frontend/src/ui/timeline/rigs.ts @@ -0,0 +1,326 @@ +import { el, escapeHtml, patchList, q, setAttr, setDisabled, setHidden, setHtml, setStyleVar, setText, setTitle } from '../../shell/dom'; +import { toast } from '../../shell/toast'; +import { t } from '../../i18n'; +import { glyph } from './glyphs'; +import { body, CMD, frameOf, obj, rigKindLabel, rigSignature, seconds, type RigInfo } from './model'; +import type { Timeline } from './panel'; +import { Popover } from './popover'; +import { fraction } from './view'; + +type Vec3 = [number, number, number]; + +const DEFAULT_FRAMES = 36; + +function vec3(v: unknown): Vec3 | null { + return Array.isArray(v) && v.length === 3 && v.every((x) => typeof x === 'number') ? [v[0], v[1], v[2]] : null; +} + +function num(input: HTMLInputElement, fallback: number): number { + const v = parseFloat(input.value.replace(',', '.')); + return Number.isFinite(v) ? v : fallback; +} + +export class Rigs { + private readonly button: HTMLButtonElement; + private readonly menu: Popover; + private readonly editor: Popover; + private editing: string | null = null; + private pending: { point: Vec3; time: number } | null = null; + private currentPath: string | null = null; + private readonly pointTimes = new Map(); + + constructor(private readonly tl: Timeline) { + this.button = el(``); + tl.menus.appendChild(this.button); + this.menu = new Popover('fsh-tl-rigmenu', 'Add a turntable, a camera orbit or a camera path'); + this.menu.root.innerHTML = `
            +

            Turntable

            + + + + +
            +
            + +
            +

            Camera orbit

            + + +
            +
            + +
            +

            Camera path

            +

            +
            +
            `; + this.editor = new Popover('fsh-tl-rigedit', 'Edit rig'); + tl.view.rigRows.addEventListener('click', (e) => this.rowClick(e)); + this.button.addEventListener('click', () => this.toggleMenu()); + this.menu.onClose(() => setAttr(this.button, 'aria-expanded', 'false')); + this.editor.onClose(() => { this.editing = null; }); + q(this.menu.root, '[data-form="turntable"]').addEventListener('submit', (e) => { e.preventDefault(); void this.addTurntable(); }); + q(this.menu.root, '[data-form="orbit"]').addEventListener('submit', (e) => { e.preventDefault(); void this.addOrbit(); }); + q(this.menu.root, '[data-act="point"]').addEventListener('click', () => { void this.addPoint(); }); + q(this.menu.root, '[data-act="new-path"]').addEventListener('click', () => { this.pending = null; this.currentPath = null; this.paintMenu(); }); + tl.store.onChange(() => { this.sync(); this.paintMenu(); }); + tl.ws.client.onSummary(() => this.paintMenu()); + tl.ws.client.onCatalogue(() => this.paint()); + tl.ws.client.onState(() => this.paint()); + this.sync(); + this.paint(); + } + + get anchor(): HTMLButtonElement { return this.button; } + + toggleMenu(): void { + if (this.menu.isOpen) { this.menu.close(); return; } + setAttr(this.button, 'aria-expanded', 'true'); + this.menu.open(this.button); + this.paintMenu(); + } + + openTurntable(): void { + if (!this.menu.isOpen) this.toggleMenu(); + q(this.menu.root, '[data-form="turntable"] [data-k="frames"]').focus(); + } + + private paint(): void { + const can = this.tl.ws.canRun(CMD.addRig) || this.tl.ws.canRun(CMD.turntable); + setDisabled(this.button, !can); + setTitle(this.button, can ? t('Add a turntable, a camera orbit or a camera path') : this.tl.ws.why(CMD.turntable)); + } + + private paintMenu(): void { + if (!this.menu.isOpen) return; + const s = this.tl.ws.client.summary; + const sel = (s?.selection ?? []).map(String); + const nodes = (s?.nodes ?? []).filter((n) => sel.includes(String(n.id)) && n.kind !== 'light'); + const opts = [``, ...nodes.map((n) => ``)]; + const select = q(this.menu.root, '[data-form="turntable"] [data-k="node"]'); + const before = select.value; + setHtml(select, opts.join(''), JSON.stringify(nodes.map((n) => [n.id, n.name]))); + if ([...select.options].some((o) => o.value === before)) select.value = before; + const st = this.tl.store.status; + const path = this.currentPath ? this.tl.store.rigs.find((r) => r.id === this.currentPath) : undefined; + const frame = frameOf(st, this.tl.player.displayTime()); + let note: string; + if (path) note = t('Adding to {name}: {n} points. Move the view, go to another frame and add the camera position again.', { name: path.name, n: Array.isArray(path.raw.points) ? path.raw.points.length : 0 }); + else if (this.pending) note = t('First point kept at frame {frame}. Move the view, go to another frame and add the next point.', { frame: frameOf(st, this.pending.time) }); + else note = t('Adds the current camera position as a point at frame {frame}; two points make a path.', { frame }); + setText(q(this.menu.root, '.fsh-tl-path-note'), note); + setHidden(q(this.menu.root, '[data-act="new-path"]'), !path && !this.pending); + for (const b of this.menu.root.querySelectorAll('button')) setDisabled(b, !this.tl.ws.canRun(CMD.addRig)); + this.menu.place(); + } + + private async addTurntable(): Promise { + const f = q(this.menu.root, '[data-form="turntable"]'); + const frames = Math.max(2, Math.round(num(q(f, '[data-k="frames"]'), DEFAULT_FRAMES))); + const args: Record = { + frames, + turns: num(q(f, '[data-k="turns"]'), 1), + direction: q(f, '[data-k="direction"]').value, + }; + const node = q(f, '[data-k="node"]').value; + if (node) args.node = Number(node); + this.menu.close(); + await this.addTurntableWith(args); + } + + async addTurntableWith(args: Record): Promise { + const out = await this.tl.edits.once(CMD.turntable, args); + if (out !== undefined) { this.tl.setOpen(true); this.tl.store.changed('anim.turntable'); this.tl.player.seek(this.tl.store.status.start); } + } + + private async addOrbit(): Promise { + const f = q(this.menu.root, '[data-form="orbit"]'); + const args = { turns: num(q(f, '[data-k="turns"]'), 1), direction: q(f, '[data-k="direction"]').value }; + this.menu.close(); + const out = await this.tl.edits.once(CMD.orbit, args); + if (out !== undefined) { this.tl.setOpen(true); this.tl.store.changed('anim.orbit'); } + } + + private async addPoint(): Promise { + const cam = this.tl.ws.client.summary?.camera; + const point = vec3(cam?.position); + if (!point) return; + const time = this.tl.player.displayTime(); + const path = this.currentPath ? this.tl.store.rigs.find((r) => r.id === this.currentPath) : undefined; + if (path) { await this.extendPath(path, point, time); return; } + if (!this.pending) { this.pending = { point, time }; this.paintMenu(); return; } + if (Math.abs(this.pending.time - time) < 1e-4) { toast(t('Go to another frame before adding the next point')); return; } + const pts = [this.pending, { point, time }].sort((a, b) => a.time - b.time); + const args: Record = { points: pts.map((p) => p.point), start: pts[0].time, end: pts[1].time }; + if (typeof cam?.index === 'number') args.camera = cam.index; + const out = obj(body(await this.tl.edits.once(CMD.cameraPath, args))); + if (!out) return; + this.pending = null; + const id = typeof out.id === 'string' ? out.id : null; + if (id) { this.currentPath = id; this.pointTimes.set(id, pts.map((p) => p.time)); } + this.tl.setOpen(true); + this.tl.store.changed('anim.camera_path'); + } + + private async extendPath(path: RigInfo, point: Vec3, time: number): Promise { + const points = (Array.isArray(path.raw.points) ? path.raw.points : []).map(vec3).filter((p): p is Vec3 => p !== null); + let times = this.pointTimes.get(path.id); + if (!times || times.length !== points.length) { + times = points.map((_, i) => path.start + ((path.end - path.start) * i) / Math.max(1, points.length - 1)); + } + if (times.some((x) => Math.abs(x - time) < 1e-4)) { toast(t('Go to another frame before adding the next point')); return; } + const all = points.map((p, i) => ({ point: p, time: times[i] })).concat({ point, time }).sort((a, b) => a.time - b.time); + const values = { points: all.map((p) => p.point), start: all[0].time, end: all[all.length - 1].time }; + const out = await this.tl.edits.once(CMD.setRig, { id: path.id, values }); + if (out === undefined) return; + this.pointTimes.set(path.id, all.map((p) => p.time)); + this.tl.store.changed('anim.set_rig'); + } + + sync(): void { + const rigs = this.tl.store.rigs; + const s = this.tl.store.status; + patchList(this.tl.view.rigRows, rigs, { + key: (r) => r.id, + create: (r) => this.createRow(r), + update: (n, r) => this.updateRow(n, r), + }); + for (const n of this.tl.view.rigRows.children) { + const r = rigs.find((x) => x.id === (n as HTMLElement).dataset.key); + if (r) this.placeBar(n as HTMLElement, r, `${s.start}:${s.end}:${s.fps}`); + } + if (this.currentPath && !rigs.some((r) => r.id === this.currentPath) && this.tl.store.status.rigs === rigs.length) this.currentPath = null; + if (this.editing) { + const r = rigs.find((x) => x.id === this.editing); + if (r) this.fillEditor(r); else this.editor.close(); + } + } + + private createRow(r: RigInfo): HTMLElement { + const node = el(`
            +
            + + +
            +
            +
            `); + this.updateRow(node, r); + return node; + } + + private updateRow(node: HTMLElement, r: RigInfo): void { + const sig = rigSignature(r); + if (node.dataset.sig === sig) return; + node.dataset.sig = sig; + node.dataset.kind = r.kind; + setText(q(node, '.fsh-tl-lane-obj'), r.name); + setTitle(q(node, '.fsh-tl-lane-name'), `${r.name}: ${t(rigKindLabel(r.kind))}`); + const range = `${seconds(r.start)} - ${seconds(r.end)}`; + setText(q(node, '.fsh-tl-bar-text'), `${r.name} ${range}`); + setTitle(q(node, '.fsh-tl-bar'), t('{name} from {start} to {end}; choose to edit', { name: r.name, start: seconds(r.start), end: seconds(r.end) })); + delete node.dataset.place; + } + + private placeBar(node: HTMLElement, r: RigInfo, rangeKey: string): void { + const key = `${r.start}:${r.end}:${rangeKey}`; + if (node.dataset.place === key) return; + node.dataset.place = key; + const s = this.tl.store.status; + const bar = q(node, '.fsh-tl-bar'); + setStyleVar(bar, '--a', String(fraction(s, r.start))); + setStyleVar(bar, '--b', String(fraction(s, r.end))); + } + + private rowClick(e: MouseEvent): void { + const b = (e.target as HTMLElement).closest('button[data-act]'); + const row = b?.closest('.fsh-tl-rigrow'); + const id = row?.dataset.key; + if (!b || !id) return; + if (b.dataset.act === 'remove-rig') { + if (this.currentPath === id) this.currentPath = null; + void this.tl.edits.once(CMD.removeRig, { id }).then(() => this.tl.store.changed('anim.remove_rig')); + return; + } + const r = this.tl.store.rigs.find((x) => x.id === id); + if (!r) return; + if (r.kind === 'camera_path') this.currentPath = r.id; + this.openEditor(r, b); + } + + private openEditor(r: RigInfo, anchor: HTMLElement): void { + this.editing = r.id; + this.editor.root.innerHTML = this.editorHtml(r); + this.editor.root.dataset.rig = r.id; + this.fillEditor(r); + this.editor.root.querySelectorAll('[data-k]').forEach((input) => { + input.addEventListener('change', () => { void this.changeField(input); }); + }); + q(this.editor.root, '[data-act="remove"]').addEventListener('click', () => { + const id = this.editing; + this.editor.close(); + if (id) void this.tl.edits.once(CMD.removeRig, { id }).then(() => this.tl.store.changed('anim.remove_rig')); + }); + this.editor.root.querySelector('[data-act="point"]')?.addEventListener('click', () => { + this.currentPath = r.id; + void this.addPoint(); + }); + this.editor.open(anchor); + } + + private editorHtml(r: RigInfo): string { + const row = (label: string, input: string): string => ``; + const numInput = (k: string, step: string, extra = ''): string => ``; + const dir = ``; + const parts = [ + `

            ${escapeHtml(t(rigKindLabel(r.kind)))}

            `, + row('Name', ''), + row('Starts at', numInput('start', '0.01')), + row('Ends at', numInput('end', '0.01')), + ]; + if (r.kind !== 'camera_path') parts.push(row('Turns', numInput('turns', '0.25')), row('Direction', dir)); + if (r.kind === 'turntable') { + const nodes = (this.tl.ws.client.summary?.nodes ?? []).filter((n) => n.kind !== 'light'); + parts.push(row('Start angle', numInput('start_angle', '1'))); + parts.push(row('What turns', ``)); + } + if (r.kind === 'camera_path') { + parts.push(row('Closed loop', '')); + parts.push(row('Roll', numInput('roll', '1'))); + } + parts.push(row('Ease in', numInput('ease_in', '0.05', 'min="0" max="1"')), row('Ease out', numInput('ease_out', '0.05', 'min="0" max="1"'))); + if (r.kind === 'camera_path') parts.push(`

            `); + parts.push(`
            ${r.kind === 'camera_path' ? `` : ''}
            `); + return `
            ${parts.join('')}
            `; + } + + private fillEditor(r: RigInfo): void { + const root = this.editor.root; + for (const input of root.querySelectorAll('[data-k]')) { + if (document.activeElement === input) continue; + const k = input.dataset.k ?? ''; + const v = r.raw[k]; + if (input instanceof HTMLInputElement && input.type === 'checkbox') input.checked = v === true; + else if (k === 'node') input.value = v === undefined || v === null ? '' : String(v); + else input.value = v === undefined || v === null ? '' : typeof v === 'number' ? String(Math.round(v * 10000) / 10000) : String(v); + } + const pts = root.querySelector('.fsh-tl-rig-points'); + if (pts) setText(pts, t('{n} points', { n: Array.isArray(r.raw.points) ? r.raw.points.length : 0 })); + } + + private async changeField(input: HTMLInputElement | HTMLSelectElement): Promise { + const id = this.editing; + const k = input.dataset.k; + if (!id || !k) return; + let value: unknown; + if (input instanceof HTMLInputElement && input.type === 'checkbox') value = input.checked; + else if (k === 'name' || k === 'direction') value = input.value; + else if (k === 'node') value = input.value ? Number(input.value) : null; + else { + const n = parseFloat(input.value.replace(',', '.')); + if (!Number.isFinite(n)) return; + value = n; + } + await this.tl.edits.once(CMD.setRig, { id, values: { [k]: value } }); + this.tl.store.changed('anim.set_rig'); + } +} diff --git a/frontend/src/ui/timeline/store.ts b/frontend/src/ui/timeline/store.ts new file mode 100644 index 00000000..2719c53d --- /dev/null +++ b/frontend/src/ui/timeline/store.ts @@ -0,0 +1,78 @@ +import { api } from '../../shell/api'; +import type { Workspace } from '../context'; +import { body, CMD, EMPTY_STATUS, parseRigs, parseStatus, type AnimStatus, type RigInfo } from './model'; + +const STATUS_DELAY_MS = 40; +const CHANGE_EVENTS = ['scene.changed', 'document.changed', 'history.changed']; +const QUIET = /^(selection\.|view\.|render\.|camera\.set$|camera\.pick_focus$)/; + +export type StoreChange = 'status' | 'rigs'; + +export class TimelineStore { + status: AnimStatus = EMPTY_STATUS; + rigs: RigInfo[] = []; + loaded = false; + private statusTimer: number | undefined; + private statusBusy = false; + private statusAgain = false; + private readonly fns = new Set<(what: StoreChange) => void>(); + + constructor(private readonly ws: Workspace) { + ws.client.onDispatch((n) => { + if (n.change === 'none' || n.name === CMD.status || QUIET.test(n.name)) return; + this.changed(n.name); + }); + for (const type of CHANGE_EVENTS) ws.ctx.events.on(type, (e) => this.changed(typeof e.command === 'string' ? e.command : type)); + ws.ctx.events.on('resync', () => this.changed('history.resync')); + ws.client.onState(() => { if (ws.client.state === 'ready') this.changed('history.ready'); }); + ws.client.onCatalogue(() => this.changed('history.catalogue')); + } + + onChange(fn: (what: StoreChange) => void): () => void { + this.fns.add(fn); + return () => { this.fns.delete(fn); }; + } + + get available(): boolean { return this.ws.canRun(CMD.status); } + + changed(_command: string): void { + this.schedule(STATUS_DELAY_MS); + } + + schedule(ms = 0): void { + window.clearTimeout(this.statusTimer); + this.statusTimer = window.setTimeout(() => { void this.load(); }, ms); + } + + setTimeShown(time: number | null, frame: number | null): void { + if (this.status.time === time) return; + this.status = { ...this.status, time, frame }; + this.emit('status'); + } + + private emit(what: StoreChange): void { + for (const fn of this.fns) fn(what); + } + + private async load(): Promise { + if (!this.available) return; + if (this.statusBusy) { this.statusAgain = true; return; } + this.statusBusy = true; + try { + const raw = await api.dispatch(CMD.status, {}, { timeoutMs: 15000 }); + const next = parseStatus(raw); + const rigs = parseRigs(body(raw)); + const before = this.status; + const first = !this.loaded; + this.status = next; + this.loaded = true; + if (first || JSON.stringify(before) !== JSON.stringify(next)) this.emit('status'); + if (JSON.stringify(rigs) !== JSON.stringify(this.rigs)) { this.rigs = rigs; this.emit('rigs'); } + } catch { + return; + } finally { + this.statusBusy = false; + if (this.statusAgain) { this.statusAgain = false; this.schedule(0); } + } + } +} diff --git a/frontend/src/ui/timeline/timeline.css b/frontend/src/ui/timeline/timeline.css new file mode 100644 index 00000000..c3bd8183 --- /dev/null +++ b/frontend/src/ui/timeline/timeline.css @@ -0,0 +1,122 @@ +.fsh-viewport > .fsh-panel[data-panel="workspace.viewport"] { bottom: var(--fsh-tl-reserved, 0px); } +.fsh-viewport > .fsh-panel.fsh-tl-host { top: auto; height: var(--fsh-tl-reserved, 0px); overflow: hidden; border-top: 1px solid var(--line-1); background: var(--surface-1); } + +.fsh-tl { display: grid; grid-template-rows: 34px minmax(0, 1fr); height: 100%; outline: none; color: var(--text-secondary); font-size: var(--fs-12); contain: strict; } +.fsh-tl:focus-visible { box-shadow: inset 0 0 0 1px var(--accent-line); } +.fsh-tl-head { display: flex; align-items: center; gap: var(--space-1); min-width: 0; height: 34px; padding: 0 var(--space-2) 0 var(--space-1); overflow: clip; container-type: inline-size; } +.fsh-tl-fold .fsh-tl-glyph { transition: transform var(--dur-fast); } +.fsh-tl-fold[aria-expanded="true"] .fsh-tl-glyph { transform: rotate(180deg); } +.fsh-tl-title { flex: none; width: 64px; overflow: hidden; color: var(--text-primary); font-weight: var(--fw-medium); text-overflow: ellipsis; white-space: nowrap; } +.fsh-tl-stack { display: grid; flex: none; align-items: center; } +.fsh-tl-stack > * { grid-area: 1 / 1; } +.fsh-tl-transport { display: flex; align-items: center; gap: 1px; } +.fsh-tl-animate { justify-self: start; } +.fsh-tl.is-empty .fsh-tl-transport, .fsh-tl:not(.is-empty) .fsh-tl-animate { visibility: hidden; } +.fsh-tl-play .fsh-tl-glyph + .fsh-tl-glyph { display: none; } +.fsh-tl-play[aria-pressed="true"] .fsh-tl-glyph:first-child { display: none; } +.fsh-tl-play[aria-pressed="true"] .fsh-tl-glyph + .fsh-tl-glyph { display: inline-grid; } +.fsh-tl-readout { display: flex; flex: none; align-items: baseline; gap: var(--space-2); width: 168px; padding: 0 var(--space-2); overflow: hidden; white-space: nowrap; } +.fsh-tl-readout-label { color: var(--text-faint); } +.fsh-tl-frame { width: 64px; color: var(--text-primary); font: var(--fs-12) var(--mono); } +.fsh-tl-time { color: var(--text-muted); font: var(--fs-11) var(--mono); } +.fsh-tl.is-empty .fsh-tl-readout, .fsh-tl.is-empty .fsh-tl-fields { opacity: 0.55; } +.fsh-tl-fields { display: flex; flex: none; gap: var(--space-1); } +.fsh-tl-fields .fsh-ws-num { width: 104px; } +.fsh-tl-gap { flex: 1 1 0; min-width: 0; } +.fsh-tl-menus { display: flex; flex: none; align-items: center; gap: 2px; } +@container (max-width: 980px) { + .fsh-tl-title, .fsh-tl-time, .fsh-tl-readout-label { display: none; } + .fsh-tl-readout { width: 72px; } + .fsh-tl-fields .fsh-ws-num { width: 110px; } +} +@container (max-width: 760px) { + .fsh-tl-menu-btn .fsh-ws-tool-text { display: none; } + .fsh-tl-fields .fsh-ws-num-label { display: none; } + .fsh-tl-fields .fsh-ws-num { width: 66px; } +} +.fsh-tl-body { position: relative; min-height: 0; border-top: 1px solid var(--line-1); } +.fsh-tl[data-open="false"] .fsh-tl-body { visibility: hidden; } + +.fsh-tl-scroll { --fsh-tl-head-w: 184px; position: absolute; inset: 0; overflow-x: hidden; overflow-y: auto; scrollbar-gutter: stable; overscroll-behavior: contain; } +.fsh-tl-row { display: grid; grid-template-columns: var(--fsh-tl-head-w) minmax(0, 1fr); min-width: 0; } +.fsh-tl-rulerrow { position: sticky; top: 0; z-index: var(--z-raised); height: 22px; border-bottom: 1px solid var(--line-1); background: var(--surface-1); } +.fsh-tl-corner { border-right: 1px solid var(--line-1); } +.fsh-tl-ruler { position: relative; overflow-x: clip; cursor: ew-resize; outline: none; touch-action: none; } +.fsh-tl-ruler:focus-visible { box-shadow: inset 0 0 0 1px var(--accent-line); } +.fsh-tl-ticks { position: absolute; inset: 0; width: 100%; height: 100%; } +.fsh-tl-cursor { position: absolute; top: 0; left: var(--fsh-tl-pad); width: calc(100% - 2 * var(--fsh-tl-pad)); height: var(--fsh-tl-view-h, 200px); transform: translateX(calc(var(--fsh-tl-now, 0) * 100%)); pointer-events: none; } +.fsh-tl-cursor::before { content: ''; position: absolute; top: 0; left: 0; width: 1px; height: 100%; background: var(--accent-color); } +.fsh-tl-cursor.is-out { visibility: hidden; } +.fsh-tl-cursor-cap { position: absolute; top: 0; left: -5px; width: 11px; height: 8px; border-radius: 0 0 3px 3px; background: var(--accent-color); } +.fsh-tl.is-empty .fsh-tl-cursor { visibility: hidden; } +.fsh-tl-empty { display: flex; align-items: center; justify-content: center; height: 140px; padding: 0 var(--space-6); color: var(--text-muted); text-align: center; } +.fsh-tl-empty[hidden] { display: none; } +.fsh-tl-empty p { max-width: 520px; margin: 0; line-height: var(--lh); } + +.fsh-tl-lane { height: 26px; border-bottom: 1px solid var(--line-0); } +.fsh-tl-lane.is-curve { height: 84px; } +.fsh-tl-lanehead { display: flex; align-items: center; gap: var(--space-1); min-width: 0; padding: 0 var(--space-1) 0 var(--space-3); border-right: 1px solid var(--line-1); } +.fsh-tl-lane-name { display: flex; flex: 1 1 auto; gap: var(--space-1); min-width: 0; overflow: hidden; white-space: nowrap; } +.fsh-tl-lane-obj { flex: 0 1 auto; min-width: 0; overflow: hidden; color: var(--text-primary); text-overflow: ellipsis; } +.fsh-tl-lane-field { flex: 0 1 auto; min-width: 0; overflow: hidden; color: var(--text-muted); text-overflow: ellipsis; } +.fsh-tl-lane.is-invalid .fsh-tl-lane-name { opacity: 0.5; text-decoration: line-through; } +.fsh-tl-lane-tools { display: flex; flex: none; gap: 1px; opacity: 0.6; } +.fsh-tl-lane:hover .fsh-tl-lane-tools, .fsh-tl-lane-tools:focus-within { opacity: 1; } +.fsh-tl-mini { display: inline-grid; place-items: center; width: 22px; height: 22px; padding: 0; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-muted); cursor: pointer; } +.fsh-tl-mini:hover { background: var(--bg-hover); color: var(--text-primary); } +.fsh-tl-mini[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent-color); } +.fsh-tl-mini:disabled { opacity: 0.4; cursor: default; } +.fsh-tl-track { position: relative; min-width: 0; overflow: hidden; } +.fsh-tl-keys { position: absolute; inset: 0; } +.fsh-tl-curve { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; } +.fsh-tl-curve[hidden] { display: none; } +.fsh-tl-key { position: absolute; top: 50%; left: calc(var(--fsh-tl-pad) + var(--f, 0) * (100% - 2 * var(--fsh-tl-pad))); width: 10px; height: 10px; margin: -5px 0 0 -5px; transform: rotate(45deg); border: 1px solid var(--line-3); border-radius: 1px; background: var(--text-muted); cursor: grab; touch-action: none; } +.fsh-tl-key[data-interp="step"] { transform: none; border-radius: 0; } +.fsh-tl-key[data-interp="smooth"] { transform: none; border-radius: 50%; } +.fsh-tl-key[data-interp="ease"] { border-radius: 4px; } +.fsh-tl-key:hover { background: var(--text-primary); } +.fsh-tl-key.is-now { border-color: var(--accent-color); } +.fsh-tl-key.is-sel { background: var(--accent-color); border-color: var(--accent-contrast); } +.fsh-tl-key.is-drag { cursor: grabbing; box-shadow: 0 0 0 3px var(--accent-soft); } +.fsh-tl-key:focus-visible { outline: 1px solid var(--accent-color); outline-offset: 2px; } +.fsh-tl-rigrow { background: var(--surface-0); } +.fsh-tl-bar { position: absolute; top: 4px; bottom: 4px; left: calc(var(--fsh-tl-pad) + var(--a, 0) * (100% - 2 * var(--fsh-tl-pad))); width: max(6px, calc((var(--b, 1) - var(--a, 0)) * (100% - 2 * var(--fsh-tl-pad)))); display: flex; align-items: center; min-width: 0; padding: 0 var(--space-2); overflow: hidden; border: 1px solid var(--accent-line); border-radius: var(--radius-sm); background: var(--accent-tint); color: var(--text-primary); font-size: var(--fs-11); text-align: left; cursor: pointer; } +.fsh-tl-bar:hover { background: var(--accent-tint-strong); } +.fsh-tl-bar:focus-visible { outline: 1px solid var(--accent-color); outline-offset: 1px; } +.fsh-tl-rigrow[data-kind="orbit"] .fsh-tl-bar, .fsh-tl-rigrow[data-kind="camera_path"] .fsh-tl-bar { border-color: var(--line-3); background: var(--surface-3); } +.fsh-tl-bar-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fsh-tl-rigmenu, .fsh-tl-rigedit { width: 320px; } +.fsh-tl-rigmenu .fsh-tl-form-foot button[hidden] { display: none; } + +.fsh-tl-pop { position: fixed; top: var(--fsh-tl-pop-y, 0); left: var(--fsh-tl-pop-x, 0); z-index: var(--z-menu); display: flex; flex-direction: column; min-width: 200px; max-width: 360px; max-height: min(70vh, 560px); overflow-y: auto; padding: var(--space-1); 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); backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); color: var(--text-secondary); font-size: var(--fs-12); } +.fsh-tl-pop[hidden] { display: none; } +.fsh-tl-menu-title { margin: var(--space-1) var(--space-2); color: var(--text-faint); font-size: var(--fs-11); } +.fsh-tl-menu-item { display: flex; align-items: center; gap: var(--space-2); height: 28px; padding: 0 var(--space-2); border: 0; border-radius: var(--radius-md); background: transparent; color: var(--text-primary); font-size: var(--fs-12); text-align: left; cursor: pointer; } +.fsh-tl-menu-item:hover, .fsh-tl-menu-item:focus-visible { background: var(--bg-hover); outline: none; } +.fsh-tl-menu-item:disabled { opacity: 0.45; cursor: default; } +.fsh-tl-menu-item[aria-checked="true"] { color: var(--accent-color); } +.fsh-tl-menu-sep { height: 1px; margin: var(--space-1) 0; background: var(--line-1); } +.fsh-tl-shape { flex: none; width: 9px; height: 9px; margin: 0 3px; transform: rotate(45deg); background: currentColor; } +.fsh-tl-shape[data-interp="step"] { transform: none; } +.fsh-tl-shape[data-interp="smooth"] { transform: none; border-radius: 50%; } +.fsh-tl-shape[data-interp="ease"] { border-radius: 3px; } +.fsh-tl-shape.is-blank { background: transparent; } +.fsh-tl-menu-item .fsh-tl-glyph { color: var(--text-muted); } +.fsh-tl-item-text { display: flex; flex-direction: column; min-width: 0; line-height: var(--lh-tight); } +.fsh-tl-item-note { color: var(--text-faint); font-size: var(--fs-11); } +.fsh-tl-item-note:empty { display: none; } +.fsh-tl-keying .fsh-tl-menu-item { height: auto; min-height: 34px; padding-top: 3px; padding-bottom: 3px; } +.fsh-tl-keying-list[hidden], .fsh-tl-form[hidden] { display: none; } +.fsh-tl-keying { width: 320px; } + +.fsh-tl-form { display: flex; flex-direction: column; gap: var(--space-1); padding: var(--space-1); } +.fsh-tl-form-row { display: grid; grid-template-columns: 96px minmax(0, 1fr); align-items: center; gap: var(--space-2); min-height: var(--ctl-md); } +.fsh-tl-form-row[hidden] { display: none; } +.fsh-tl-form-row > span { color: var(--text-secondary); } +.fsh-tl-form-row select, .fsh-tl-form-row input[type="text"], .fsh-tl-form-row input[type="number"] { width: 100%; height: var(--ctl-md); padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-field); color: var(--text-primary); font-size: var(--fs-12); } +.fsh-tl-form-row input[type="checkbox"] { justify-self: start; width: 16px; height: 16px; margin: 0; accent-color: var(--accent-color); } +.fsh-tl-form-note { margin: var(--space-1) 0 0; color: var(--text-faint); font-size: var(--fs-11); line-height: var(--lh); } +.fsh-tl-form-foot { display: flex; justify-content: flex-end; gap: var(--space-2); margin-top: var(--space-2); } +.fsh-tl-primary { border-color: var(--accent-color); background: var(--accent-color); color: var(--accent-contrast); } +.fsh-tl-primary:hover { background: var(--accent-color-hover); } +.fsh-tl-menu-btn .fsh-ws-tool-text { margin-right: 2px; } diff --git a/frontend/src/ui/timeline/view.ts b/frontend/src/ui/timeline/view.ts new file mode 100644 index 00000000..973fe79e --- /dev/null +++ b/frontend/src/ui/timeline/view.ts @@ -0,0 +1,159 @@ +import { el, q, setAttr, setClass, setHidden, setStyleVar } from '../../shell/dom'; +import { frameOf, hasAnimation, lastFrame, type AnimStatus } from './model'; +import type { Timeline } from './panel'; + +export const PAD_PX = 10; +const TICK_MIN_PX = 56; +const STEPS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 1200, 3000, 6000]; + +export function viewRange(s: AnimStatus): { start: number; end: number } { + const end = s.end > s.start ? s.end : s.start + 1 / s.fps; + return { start: s.start, end }; +} + +export function fraction(s: AnimStatus, time: number): number { + const r = viewRange(s); + return (time - r.start) / (r.end - r.start); +} + +export function timeAt(s: AnimStatus, track: HTMLElement, clientX: number): number { + const box = track.getBoundingClientRect(); + const w = Math.max(1, box.width - 2 * PAD_PX); + const r = viewRange(s); + return r.start + ((clientX - box.left - PAD_PX) / w) * (r.end - r.start); +} + +export function cssColour(node: Element, name: string, fallback: string): string { + const v = getComputedStyle(node).getPropertyValue(name).trim(); + return v || fallback; +} + +export class TrackView { + readonly scroll: HTMLElement; + readonly ruler: HTMLElement; + readonly rigRows: HTMLElement; + readonly lanes: HTMLElement; + private readonly canvas: HTMLCanvasElement; + private readonly cursor: HTMLElement; + private readonly empty: HTMLElement; + private scrubbing = false; + private drawn = ''; + private readonly resizeFns = new Set<() => void>(); + + constructor(private readonly tl: Timeline) { + const root = el(`
            +
            +
            +
            +
            +
            +
            +

            Nothing moves yet. Key the selected parts or the camera at this frame, then at another frame; or add a turntable from the Rigs menu.

            +
            `); + tl.body.appendChild(root); + this.scroll = root; + this.ruler = q(root, '.fsh-tl-ruler'); + this.rigRows = q(root, '.fsh-tl-rigs'); + this.lanes = q(root, '.fsh-tl-lanes'); + this.canvas = q(root, '.fsh-tl-ticks'); + this.cursor = q(root, '.fsh-tl-cursor'); + this.empty = q(root, '.fsh-tl-empty'); + setStyleVar(root, '--fsh-tl-pad', `${PAD_PX}px`); + new ResizeObserver(() => { + setStyleVar(root, '--fsh-tl-view-h', `${root.clientHeight}px`); + this.drawTicks(true); + for (const fn of this.resizeFns) fn(); + }).observe(root); + this.listen(); + tl.store.onChange(() => this.paint()); + this.paint(); + } + + onResize(fn: () => void): void { this.resizeFns.add(fn); } + + paint(): void { + const s = this.tl.store.status; + const now = this.tl.player.displayTime(); + if (!this.scrubbing) this.placeCursor(now); + setHidden(this.empty, hasAnimation(s) || !this.tl.store.loaded); + setAttr(this.ruler, 'aria-valuemax', String(lastFrame(s))); + setAttr(this.ruler, 'aria-valuenow', String(frameOf(s, now))); + this.drawTicks(false); + } + + placeCursor(time: number): void { + const f = fraction(this.tl.store.status, time); + setStyleVar(this.scroll, '--fsh-tl-now', String(Math.round(f * 100000) / 100000)); + setClass(this.cursor, 'is-out', f < -0.0001 || f > 1.0001); + } + + private drawTicks(force: boolean): void { + const s = this.tl.store.status; + const c = this.canvas; + const dpr = Math.min(window.devicePixelRatio || 1, 2); + const w = Math.max(1, Math.round(this.ruler.clientWidth * dpr)); + const h = Math.max(1, Math.round(this.ruler.clientHeight * dpr)); + const key = `${w}x${h}:${s.start}:${s.end}:${s.fps}`; + if (!force && key === this.drawn) return; + this.drawn = key; + if (c.width !== w) c.width = w; + if (c.height !== h) c.height = h; + const g = c.getContext('2d'); + if (!g) return; + g.clearRect(0, 0, w, h); + const frames = lastFrame(s); + const inner = w - 2 * PAD_PX * dpr; + const perFrame = frames > 0 ? inner / frames : inner; + const step = STEPS.find((n) => n * perFrame >= TICK_MIN_PX * dpr) ?? STEPS[STEPS.length - 1]; + const minor = STEPS.find((n) => n * perFrame >= 6 * dpr && step % n === 0) ?? step; + g.font = `${10 * dpr}px ${cssColour(this.ruler, '--mono', 'monospace')}`; + g.textBaseline = 'top'; + const faint = cssColour(this.ruler, '--text-faint', '#777'); + const line = cssColour(this.ruler, '--line-2', '#444'); + for (let f = 0; f <= frames; f += minor) { + const x = Math.round(PAD_PX * dpr + (frames > 0 ? f / frames : 0) * inner) + 0.5; + const major = f % step === 0; + g.strokeStyle = major ? faint : line; + g.beginPath(); + g.moveTo(x, h); + g.lineTo(x, h - (major ? 8 : 4) * dpr); + g.stroke(); + if (major) { + g.fillStyle = faint; + g.fillText(String(f), x + 3 * dpr, 3 * dpr); + } + } + } + + private listen(): void { + let pointer = -1; + const at = (e: PointerEvent): number => timeAt(this.tl.store.status, this.ruler, e.clientX); + const move = (e: PointerEvent): void => { + const s = this.tl.store.status; + const t = Math.min(s.end, Math.max(s.start, at(e))); + const f = Math.round((t - s.start) * s.fps); + const snapped = s.start + f / s.fps; + this.placeCursor(snapped); + this.tl.player.scrub(snapped); + }; + this.ruler.addEventListener('pointerdown', (e) => { + if (e.button !== 0 || !hasAnimation(this.tl.store.status)) return; + pointer = e.pointerId; + this.ruler.setPointerCapture(e.pointerId); + this.scrubbing = true; + setClass(this.scroll, 'is-scrubbing', true); + this.ruler.focus({ preventScroll: true }); + e.preventDefault(); + move(e); + }); + this.ruler.addEventListener('pointermove', (e) => { if (e.pointerId === pointer) move(e); }); + const end = (e: PointerEvent): void => { + if (e.pointerId !== pointer) return; + pointer = -1; + this.scrubbing = false; + setClass(this.scroll, 'is-scrubbing', false); + }; + this.ruler.addEventListener('pointerup', end); + this.ruler.addEventListener('pointercancel', end); + } +} diff --git a/frontend/src/ui/transport/badge.ts b/frontend/src/ui/transport/badge.ts new file mode 100644 index 00000000..26438f6f --- /dev/null +++ b/frontend/src/ui/transport/badge.ts @@ -0,0 +1,25 @@ +import { el, setAttr, setClass, setTitle } from '../../shell/dom'; +import { t } from '../../i18n'; + +export interface Badge { + readonly el: HTMLElement; + set(on: boolean, why?: string): void; +} + +const CHIP = ''; + +export function cpuBadge(): Badge { + const node = el(``); + let shown: boolean | null = null; + return { + el: node, + set: (on, why) => { + setTitle(node, on ? why ?? t('The GPU engine refuses this, so the picture renders on the CPU.') : ''); + if (shown === on) return; + shown = on; + setClass(node, 'is-on', on); + setAttr(node, 'aria-hidden', on ? null : 'true'); + setAttr(node, 'role', on ? 'note' : null); + }, + }; +} diff --git a/frontend/src/ui/transport/cutaways.ts b/frontend/src/ui/transport/cutaways.ts new file mode 100644 index 00000000..43e3be01 --- /dev/null +++ b/frontend/src/ui/transport/cutaways.ts @@ -0,0 +1,395 @@ +import './transport.css'; +import { el, escapeHtml, patchList, q, setAttr, setChecked, setClass, setDisabled, setHidden, setText, setTitle, setValue } from '../../shell/dom'; +import { t } from '../../i18n'; +import type { NodeSummary } from '../../engine/types'; +import type { Workspace } from '../context'; +import { acescgToHex, hexToAcescg } from '../material/model'; +import { numberRow, toggleRow, type Control } from '../material/rows'; +import { section } from '../pages/page'; +import { cpuBadge, type Badge } from './badge'; +import { capArg, parseCutaway, readCutaways, shapeArg, type CapMode, type CutawayInfo, type ShapeKind } from './doc'; +import { cpuOnlyText, features, useWhileVisible } from './features'; + +const CMD = { + add: 'scene.add_cutaway', + set: 'scene.set_cutaway', + enable: 'cutaway.set_enabled', + targets: 'cutaway.set_targets', + select: 'selection.set', + barrier: 'history.barrier', + remove: 'scene.remove', +} as const; +const BOUNDS = 'view.bounds'; + +const SHAPES: ReadonlyArray = [['plane', 'Plane cut'], ['box', 'Box cut'], ['sphere', 'Sphere cut'], ['cylinder', 'Cylinder cut']]; +const CAPS: ReadonlyArray = [['none', 'No cap'], ['part_material', 'Part material'], ['colour', 'Flat colour']]; + +const SVG = (d: string): string => ``; +const GLYPH: Record = { + plane: SVG(''), + box: SVG(''), + sphere: SVG(''), + cylinder: SVG(''), +}; + +const shapeName = (k: ShapeKind): string => t(SHAPES.find(([s]) => s === k)?.[1] ?? k); +const key = (id: string | number): string => String(id); +const idArg = (id: string): number | string => (Number.isSafeInteger(Number(id)) ? Number(id) : id); +const obj = (v: unknown): Record => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record : {}); +const body = (v: unknown): Record => { const o = obj(v); return 'result' in o ? obj(o.result) : o; }; +const vec = (v: unknown): [number, number, number] | null => + Array.isArray(v) && v.length >= 3 && v.slice(0, 3).every((x) => typeof x === 'number' && Number.isFinite(x)) ? [v[0] as number, v[1] as number, v[2] as number] : null; + +interface Dim { root: HTMLElement; control: Control; kinds: ShapeKind[]; read(c: CutawayInfo): number; write(c: CutawayInfo, v: number): void } + +export function mountCutaways(host: HTMLElement, ws: Workspace): () => void { + const { client } = ws; + const holder = section(host, 'Cutaways'); + const root = el(`
            +
            Add a cutaway${SHAPES.map(([k, l]) => ``).join('')}
            +
            +

            No cutaways yet. A cutaway cuts parts open to show what is inside.

            +

            +
            +
            +

            A plane removes everything on the side its blue axis points to. Move and turn it with the gizmo.

            +
            +
            +
            Cuts
            +
            + + + + +
            +
            +
            `); + holder.appendChild(root); + const list = q(root, '.fsh-tr-cut-list'); + const empty = q(root, '.fsh-tr-cut-empty'); + const note = q(root, '.fsh-tr-cut-note'); + const edit = q(root, '.fsh-tr-cut-edit'); + const kindSel = q(root, '.fsh-tr-cut-kind'); + const capSel = q(root, '.fsh-tr-cut-cap'); + const capColour = q(root, '.fsh-tr-cut-capcolour'); + const dimsBox = q(root, '.fsh-tr-cut-dims'); + const planeNote = q(root, '.fsh-tr-cut-plane'); + const targetsList = q(root, '.fsh-tr-cut-targets-list'); + const offVisible = useWhileVisible(root); + + let infos = new Map(); + let current: string | null = null; + let epoch = 0; + let readKey = ''; + let reading = false; + let again = false; + let seen = false; + const badges = new Map(); + + let chain: Promise = Promise.resolve(); + const enqueue = (fn: () => Promise): Promise => { + chain = chain.then(fn).catch((e: unknown) => { ws.ctx.toast(t('The cutaway could not be changed: {reason}', { reason: e instanceof Error ? e.message : String(e) }), 'error'); }); + return chain; + }; + let pendingLive: Record | null = null; + let liveQueued = false; + const live = (args: Record): void => { + pendingLive = args; + if (liveQueued) return; + liveQueued = true; + requestAnimationFrame(() => { + liveQueued = false; + const a = pendingLive; + pendingLive = null; + if (a) void enqueue(() => ws.run(CMD.set, a)); + }); + }; + const once = (name: string, args: Record): void => { + pendingLive = null; + void enqueue(() => ws.run(name, args)); + if (ws.canRun(CMD.barrier)) void enqueue(() => ws.run(CMD.barrier, {})); + }; + + const cur = (): CutawayInfo | null => (current ? infos.get(current) ?? null : null); + const nodes = (): NodeSummary[] => client.summary?.nodes ?? []; + const cutNodes = (): NodeSummary[] => nodes().filter((n) => n.kind === 'cutaway'); + + const patch = (id: string, fn: (c: CutawayInfo) => void): CutawayInfo | null => { + const c = infos.get(id); + if (!c) return null; + fn(c); + epoch++; + paint(); + return c; + }; + + const sendValues = (id: string, values: Record, final: boolean): void => { + const args = { id: idArg(id), values }; + if (final) once(CMD.set, args); + else live(args); + }; + + const dim = (label: string, kinds: ShapeKind[], read: (c: CutawayInfo) => number, write: (c: CutawayInfo, v: number) => void): Dim => { + const change = (v: number, final: boolean): void => { + if (!current) return; + const c = patch(current, (x) => write(x, v)); + if (c) sendValues(c.id, { shape: shapeArg(c.shape) }, final); + }; + const control = numberRow({ label, min: 0.001, max: 5, step: 0.005, unit: 'm', onLive: (v) => change(v, false), onCommit: (v) => change(v, true) }); + control.root.classList.add('fsh-tr-cut-dim'); + dimsBox.appendChild(control.root); + return { root: control.root, control, kinds, read, write }; + }; + const dims: Dim[] = [ + dim('Width', ['box'], (c) => c.shape.size[0], (c, v) => { c.shape.size = [v, c.shape.size[1], c.shape.size[2]]; }), + dim('Height', ['box'], (c) => c.shape.size[1], (c, v) => { c.shape.size = [c.shape.size[0], v, c.shape.size[2]]; }), + dim('Depth', ['box'], (c) => c.shape.size[2], (c, v) => { c.shape.size = [c.shape.size[0], c.shape.size[1], v]; }), + dim('Radius', ['sphere', 'cylinder'], (c) => c.shape.radius, (c, v) => { c.shape.radius = v; }), + dim('Cylinder height', ['cylinder'], (c) => c.shape.height, (c, v) => { c.shape.height = v; }), + ]; + + const toggles = q(root, '.fsh-tr-cut-toggles'); + const enabled = toggleRow('Cut is on', (on) => { if (current) { patch(current, (c) => { c.enabled = on; }); once(CMD.enable, { ids: [idArg(current)], enabled: on }); } }); + const invert = toggleRow('Invert the cut', (on) => { if (current) { patch(current, (c) => { c.invert = on; }); sendValues(current, { invert: on }, true); } }); + toggles.append(enabled.root, invert.root); + setTitle(invert.root, t('Remove the outside of the shape instead of its inside; a plane removes the other side.')); + + const sendCap = (final: boolean): void => { + const c = cur(); + if (c) sendValues(c.id, { cap: capArg(c.cap) }, final); + }; + kindSel.addEventListener('change', () => { + const k = kindSel.value as ShapeKind; + const c = current ? patch(current, (x) => { x.shape.kind = k; }) : null; + if (c) sendValues(c.id, { shape: shapeArg(c.shape) }, true); + }); + capSel.addEventListener('change', () => { + if (!current) return; + patch(current, (c) => { c.cap.mode = capSel.value as CapMode; }); + sendCap(true); + }); + capColour.addEventListener('input', () => { + const v = hexToAcescg(capColour.value); + if (current && v) { patch(current, (c) => { c.cap.colour = v; }); sendCap(false); } + }); + capColour.addEventListener('change', () => { + const v = hexToAcescg(capColour.value); + if (current && v) { patch(current, (c) => { c.cap.colour = v; }); sendCap(true); } + }); + + const selectedParts = (): string[] => { + const byId = new Map(nodes().map((n) => [key(n.id), n])); + return (client.summary?.selection ?? []).map(key).filter((id) => { + const n = byId.get(id); + return !!n && (n.kind === 'part' || n.kind === 'group'); + }); + }; + + q(root, '.fsh-tr-cut-actions').addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-targets]'); + const c = cur(); + if (!b || b.disabled || !c) return; + const op = b.dataset.targets as 'set' | 'add' | 'clear'; + const picked = selectedParts(); + if (op !== 'clear' && !picked.length) return; + patch(c.id, (x) => { x.targets = op === 'clear' ? [] : op === 'set' ? picked : [...new Set([...x.targets, ...picked])]; }); + once(CMD.targets, op === 'clear' ? { ids: [idArg(c.id)], op } : { ids: [idArg(c.id)], op, nodes: picked.map(idArg) }); + }); + + const add = async (kind: ShapeKind): Promise => { + const targets = selectedParts(); + let b: { min: number[]; max: number[] } | null = client.summary?.bounds ?? null; + if (targets.length && ws.canRun(BOUNDS)) { + const vb = body(await ws.run(BOUNDS, { nodes: targets.map(idArg) })); + const lo = vec(vb.min), hi = vec(vb.max); + if (lo && hi) b = { min: lo, max: hi }; + } + const min = b?.min ?? [-0.25, 0, -0.25], max = b?.max ?? [0.25, 0.5, 0.25]; + const centre: [number, number, number] = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2]; + const ext = [max[0] - min[0], max[1] - min[1], max[2] - min[2]].map((x) => Math.max(0.02, x)); + const r = +(Math.max(...ext) * 0.3).toFixed(3); + const round = (x: number): number => +x.toFixed(3); + const shape = { kind, size: [round(ext[0] * 0.5), round(ext[1] * 0.6), round(ext[2] * 0.5)] as [number, number, number], radius: r, height: round(ext[1] * 1.2) }; + const count = cutNodes().length + 1; + const cutaway: Record = { shape: shapeArg(shape), cap: { mode: 'part_material' }, enabled: true }; + if (targets.length) cutaway.targets = targets.map(idArg); + try { + const reply = body(await ws.run(CMD.add, { name: t('Cutaway {n}', { n: count }), cutaway, transform: { translation: centre.map(round) } })); + if (ws.canRun(CMD.barrier)) await ws.run(CMD.barrier, {}); + const made = Array.isArray(reply.created) ? reply.created.map(String) : []; + const id = typeof reply.id === 'string' || typeof reply.id === 'number' ? String(reply.id) : made[0]; + if (!id) return; + infos.set(id, parseCutaway(id, cutaway)); + current = id; + epoch++; + if (ws.canRun(CMD.select)) await ws.run(CMD.select, { ids: [id] }); + client.scheduleRefresh(0); + paint(); + } catch (e) { + ws.ctx.toast(t('The cutaway could not be added: {reason}', { reason: e instanceof Error ? e.message : String(e) }), 'error'); + } + }; + q(root, '.fsh-tr-cut-add').addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-shape]'); + if (b && !b.disabled) void add(b.dataset.shape as ShapeKind); + }); + + list.addEventListener('click', (e) => { + const row = (e.target as HTMLElement).closest('.fsh-tr-cut-row'); + if (!row) return; + const id = row.dataset.key ?? ''; + const sw = (e.target as HTMLElement).closest('input[data-role="on"]'); + if (sw) { + patch(id, (c) => { c.enabled = sw.checked; }); + once(CMD.enable, { ids: [idArg(id)], enabled: sw.checked }); + return; + } + choose(id); + }); + const choose = (id: string): void => { + current = id; + paint(); + if (ws.canRun(CMD.select)) void ws.run(CMD.select, { ids: [idArg(id)] }).then(() => client.scheduleRefresh(0)); + }; + list.addEventListener('keydown', (e) => { + const row = (e.target as HTMLElement).closest('.fsh-tr-cut-row'); + if (!row || (e.target as HTMLElement).closest('input')) return; + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + const next = (e.key === 'ArrowDown' ? row.nextElementSibling : row.previousElementSibling) as HTMLElement | null; + if (next) { next.focus(); choose(next.dataset.key ?? ''); } + } else if (e.key === 'Enter') choose(row.dataset.key ?? ''); + else if (e.key === ' ') { + const sw = q(row, 'input[data-role="on"]'); + if (!sw.disabled) sw.click(); + } else return; + e.preventDefault(); + e.stopPropagation(); + }); + q(root, '.fsh-tr-cut-remove').addEventListener('click', () => { + const c = cur(); + if (!c || !ws.canRun(CMD.remove)) return; + infos.delete(c.id); + current = null; + epoch++; + once(CMD.remove, { ids: [idArg(c.id)] }); + paint(); + }); + + const read = async (): Promise => { + if (reading) { again = true; return; } + reading = true; + const started = epoch; + try { + const fromSummary = cutNodes().filter((n) => obj(n.raw.cutaway).shape !== undefined); + const next = fromSummary.length === cutNodes().length && fromSummary.length + ? new Map(fromSummary.map((n) => [key(n.id), parseCutaway(key(n.id), n.raw.cutaway)])) + : await readCutaways(); + if (started === epoch) { infos = next; paint(); } + } catch (e) { + setText(note, t('The cutaways could not be read: {reason}', { reason: e instanceof Error ? e.message : String(e) })); + setAttr(note, 'data-on', 'true'); + } finally { + reading = false; + if (again) { again = false; void read(); } + } + }; + + const io = new IntersectionObserver((entries) => { + seen = entries.some((x) => x.isIntersecting); + if (seen) follow(); + }); + io.observe(root); + + const follow = (): void => { + const s = client.summary; + const cuts = cutNodes(); + const sel = (s?.selection ?? []).map(key); + const picked = sel.find((id) => cuts.some((n) => key(n.id) === id)); + if (picked && picked !== current) current = picked; + if (current && !cuts.some((n) => key(n.id) === current)) current = null; + if (!current && cuts.length) current = key(cuts[cuts.length - 1].id); + const k = `${s?.revision ?? ''}|${cuts.map((n) => key(n.id)).join(',')}`; + if (seen && cuts.length && k !== readKey) { readKey = k; void read(); } + paint(); + }; + + const paintRow = (row: HTMLElement, n: NodeSummary): void => { + const id = key(n.id); + const c = infos.get(id); + setText(q(row, '.fsh-tr-cut-name'), n.name); + setText(q(row, '.fsh-tr-cut-kindtext'), c ? shapeName(c.shape.kind) : ''); + const sw = q(row, 'input[data-role="on"]'); + setChecked(sw, c?.enabled ?? true); + setDisabled(sw, !c || !ws.canRun(CMD.enable)); + setAttr(row, 'aria-selected', id === current ? 'true' : 'false'); + setAttr(row, 'tabindex', id === current ? '0' : '-1'); + setClass(row, 'is-off', c?.enabled === false || !n.visible); + badges.get(id)?.set(features.refused('cutaways') && c?.enabled !== false && n.visible); + }; + + const paint = (): void => { + const cuts = cutNodes(); + patchList(list, cuts, { + key: (n) => key(n.id), + create: (n) => { + const row = el(`
            `); + const badge = cpuBadge(); + row.appendChild(badge.el); + badges.set(key(n.id), badge); + paintRow(row, n); + return row; + }, + update: paintRow, + }); + for (const id of [...badges.keys()]) if (!cuts.some((n) => key(n.id) === id)) badges.delete(id); + const canAdd = ws.canRun(CMD.add); + for (const b of root.querySelectorAll('.fsh-tr-cut-shape')) { setDisabled(b, !canAdd); setTitle(b, canAdd ? t(SHAPES.find(([k]) => k === b.dataset.shape)?.[1] ?? '') : ws.why(CMD.add)); } + setHidden(empty, cuts.length > 0); + const refused = features.refused('cutaways'); + const text = refused ? cpuOnlyText(['cutaways']) : ''; + setText(note, text); + setAttr(note, 'data-on', text ? 'true' : null); + const c = cur(); + setHidden(edit, !current); + const can = !!c && ws.canRun(CMD.set); + setDisabled(kindSel, !can); + setDisabled(capSel, !can); + if (c) { + setValue(kindSel, c.shape.kind); + setValue(capSel, c.cap.mode); + const hex = acescgToHex(c.cap.colour); + if (document.activeElement !== capColour && capColour.value !== hex) capColour.value = hex; + } + setDisabled(capColour, !can || c?.cap.mode !== 'colour'); + setAttr(capColour, 'data-off', c?.cap.mode === 'colour' ? null : 'true'); + const kind = c?.shape.kind ?? 'plane'; + for (const d of dims) { + const on = d.kinds.includes(kind); + setHidden(d.root, !on); + if (c && on) d.control.set(d.read(c)); + d.control.setDisabled(!can, can ? '' : c ? ws.why(CMD.set) : ''); + } + setHidden(planeNote, kind !== 'plane'); + enabled.set(c?.enabled ?? true); + enabled.setDisabled(!c || !ws.canRun(CMD.enable), c ? ws.why(CMD.enable) : ''); + enabled.setTag(refused && c?.enabled !== false ? 'CPU' : '', t('The GPU engine refuses this, so the picture renders on the CPU.')); + invert.set(c?.invert ?? false); + invert.setDisabled(!can, ''); + const byId = new Map(nodes().map((n) => [key(n.id), n.name])); + setText(targetsList, !c ? '' : c.targets.length ? c.targets.map((id) => byId.get(id) ?? id).join(', ') : t('every part')); + const removeBtn = q(root, '.fsh-tr-cut-remove'); + setDisabled(removeBtn, !c || !ws.canRun(CMD.remove)); + setTitle(removeBtn, c && !ws.canRun(CMD.remove) ? ws.why(CMD.remove) : ''); + const picked = selectedParts().length > 0; + const canT = !!c && ws.canRun(CMD.targets); + for (const b of root.querySelectorAll('button[data-targets]')) { + const off = !canT || (b.dataset.targets !== 'clear' && !picked) || (b.dataset.targets === 'clear' && !c?.targets.length); + setDisabled(b, off); + setTitle(b, !canT ? ws.why(CMD.targets) : off && b.dataset.targets !== 'clear' ? t('Select parts in the scene first') : ''); + } + }; + + follow(); + const offs = [client.onSummary(follow), client.onState(follow), client.onCatalogue(follow), features.onChange(paint)]; + return () => { io.disconnect(); offVisible(); for (const off of offs) off(); }; +} diff --git a/frontend/src/ui/transport/doc.ts b/frontend/src/ui/transport/doc.ts new file mode 100644 index 00000000..4c7fb6dd --- /dev/null +++ b/frontend/src/ui/transport/doc.ts @@ -0,0 +1,111 @@ +import { api } from '../../shell/api'; + +export type ShapeKind = 'plane' | 'box' | 'sphere' | 'cylinder'; +export type CapMode = 'none' | 'part_material' | 'colour'; + +export interface CutShape { kind: ShapeKind; size: [number, number, number]; radius: number; height: number } +export interface CutCap { mode: CapMode; colour: [number, number, number] } + +export interface CutawayInfo { + id: string; + enabled: boolean; + invert: boolean; + shape: CutShape; + cap: CutCap; + targets: string[]; +} + +const ROUTE = '/api/engine/snapshot'; +const EXACT = 'file.snapshot'; +const EOCD = 0x06054b50; + +const obj = (v: unknown): Record => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record : {}); +const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d); +const vec3 = (v: unknown, d: [number, number, number]): [number, number, number] => + Array.isArray(v) && v.length >= 3 && v.slice(0, 3).every((x) => typeof x === 'number') ? [v[0] as number, v[1] as number, v[2] as number] : d; + +export function parseShape(v: unknown): CutShape { + const o = obj(v); + const kind: ShapeKind = o.kind === 'box' || o.kind === 'sphere' || o.kind === 'cylinder' ? o.kind : 'plane'; + return { kind, size: vec3(o.size, [0.2, 0.2, 0.2]), radius: num(o.radius, 0.1), height: num(o.height, 0.2) }; +} + +export function shapeArg(s: CutShape): Record { + switch (s.kind) { + case 'box': return { kind: 'box', size: s.size }; + case 'sphere': return { kind: 'sphere', radius: s.radius }; + case 'cylinder': return { kind: 'cylinder', radius: s.radius, height: s.height }; + default: return { kind: 'plane' }; + } +} + +export function capArg(c: CutCap): Record { + return c.mode === 'colour' ? { mode: 'colour', colour: c.colour } : { mode: c.mode }; +} + +export function parseCutaway(id: string, v: unknown): CutawayInfo { + const o = obj(v); + const cap = obj(o.cap); + const mode: CapMode = cap.mode === 'none' || cap.mode === 'colour' ? cap.mode : 'part_material'; + return { + id, + enabled: o.enabled !== false, + invert: o.invert === true, + shape: parseShape(o.shape), + cap: { mode, colour: vec3(cap.colour, [0.8, 0.8, 0.8]) }, + targets: Array.isArray(o.targets) ? o.targets.map(String) : [], + }; +} + +function sceneJson(bytes: Uint8Array): unknown { + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let end = -1; + for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 65557); i--) if (dv.getUint32(i, true) === EOCD) { end = i; break; } + if (end < 0) throw new Error('not a project file'); + const count = dv.getUint16(end + 10, true); + let p = dv.getUint32(end + 16, true); + const text = new TextDecoder(); + for (let n = 0; n < count; n++) { + const method = dv.getUint16(p + 10, true); + const size = dv.getUint32(p + 20, true); + const nameLen = dv.getUint16(p + 28, true), extra = dv.getUint16(p + 30, true), comment = dv.getUint16(p + 32, true); + const local = dv.getUint32(p + 42, true); + const name = text.decode(bytes.subarray(p + 46, p + 46 + nameLen)); + if (name === 'scene.json') { + if (method !== 0) throw new Error('compressed scene'); + const start = local + 30 + dv.getUint16(local + 26, true) + dv.getUint16(local + 28, true); + return JSON.parse(text.decode(bytes.subarray(start, start + size))); + } + p += 46 + nameLen + extra + comment; + } + throw new Error('no scene in the project file'); +} + +let routeMissing = false; + +async function snapshotBytes(): Promise { + if (!routeMissing) { + const res = await fetch(api.url(ROUTE), { cache: 'no-store' }); + if (res.ok) return new Uint8Array(await res.arrayBuffer()); + if (res.status !== 404 && res.status !== 405) throw new Error(`${ROUTE} ${res.status}`); + routeMissing = true; + } + const reply = obj(await api.dispatch(EXACT, {}, { timeoutMs: 60000 })); + const b64 = obj('result' in reply ? reply.result : reply).fshot_b64; + if (typeof b64 !== 'string') throw new Error('no project bytes'); + const bin = atob(b64); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} + +export async function readCutaways(): Promise> { + const scene = obj(sceneJson(await snapshotBytes())); + const nodes = obj(scene.nodes); + const out = new Map(); + for (const [id, n] of Object.entries(nodes)) { + const kind = obj(obj(n).kind); + if (kind.type === 'cutaway' || 'cutaway' in kind) out.set(id, parseCutaway(id, kind.cutaway)); + } + return out; +} diff --git a/frontend/src/ui/transport/features.ts b/frontend/src/ui/transport/features.ts new file mode 100644 index 00000000..67679aeb --- /dev/null +++ b/frontend/src/ui/transport/features.ts @@ -0,0 +1,180 @@ +import { api } from '../../shell/api'; +import { events } from '../../shell/events'; +import { t } from '../../i18n'; + +export type GpuAnswer = 'renders' | 'refuses' | 'unknown'; + +export interface FeatureRow { + feature: string; + cpu: boolean; + gpu: GpuAnswer; + refusal: string | null; + used: boolean | null; +} + +export interface DeviceInfo { id: string; kind: 'cpu' | 'gpu' | ''; name: string } + +export const FEATURES_COMMAND = 'transport.features'; +const DEVICES = 'render.devices'; + +const LABELS: ReadonlyArray = [ + ['spectral', 'Spectral rendering'], + ['nested_media', 'Nested transparent solids'], + ['volume', 'Absorbing or cloudy media'], + ['subsurface', 'Subsurface scattering'], + ['caustics', 'Caustics'], + ['cutaways', 'Cutaways'], + ['rounded_edges', 'Rounded edges'], + ['fibres', 'Fibres'], + ['motion_blur', 'Motion blur'], +]; + +export const FEATURE_ORDER: readonly string[] = LABELS.map(([k]) => k); + +export function featureLabel(code: string): string { + const hit = LABELS.find(([k]) => k === code); + return hit ? t(hit[1]) : code.replace(/_/g, ' '); +} + +const CHANGE_EVENTS = ['scene.changed', 'document.changed', 'history.changed', 'hello', 'resync', 'ui.workspace.loaded', 'ui.workspace.closed']; +const READS = /^(transport\.features|scene\.(summary|meshes|mesh_data)|render\.(status|devices|passes|frame|output_|queue_list|interaction|develop|viewport|region)|view\.|camera\.(get|lens_kinds)|material\.(get|types|node_kinds|program|preview_maps|labels)|file\.(snapshot|save|export_|recover_list)|history\.(barrier|begin_group|end_group)|app\.|library\.(list|get|thumbnail|recent)|import\.(probe|status)|denoise\.|image\.(display_transforms|ocio_info)|selection\.)/; + +const obj = (v: unknown): Record => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record : {}); +const body = (v: unknown): Record => { const o = obj(v); return 'result' in o ? obj(o.result) : o; }; + +function parseRow(v: unknown): FeatureRow | null { + const o = obj(v); + if (typeof o.feature !== 'string') return null; + const gpu: GpuAnswer = o.gpu === 'renders' || o.gpu === 'refuses' ? o.gpu : 'unknown'; + const refusal = typeof o.gpu_refusal === 'string' ? o.gpu_refusal : typeof o.refusal === 'string' ? o.refusal : null; + return { feature: o.feature, cpu: o.cpu === true, gpu, refusal, used: typeof o.used === 'boolean' ? o.used : null }; +} + +class FeatureStore { + rows = new Map(); + refusals: string[] = []; + device: DeviceInfo = { id: '', kind: '', name: '' }; + available = false; + loaded = false; + error = ''; + private readonly fns = new Set<() => void>(); + private users = 0; + private timer = 0; + private seq = 0; + private wired = false; + private key = ''; + + onChange(fn: () => void): () => void { + this.fns.add(fn); + return () => { this.fns.delete(fn); }; + } + + use(): () => void { + this.users++; + this.wire(); + if (this.users === 1) this.schedule(0); + let done = false; + return () => { if (!done) { done = true; this.users = Math.max(0, this.users - 1); } }; + } + + refused(code: string): boolean { + if (this.refusals.includes(code)) return true; + const r = this.rows.get(code); + return !!r && r.used === true && r.gpu === 'refuses'; + } + + refusedList(): string[] { + const out = FEATURE_ORDER.filter((c) => this.refused(c)); + for (const c of this.refusals) if (!out.includes(c)) out.push(c); + return out; + } + + spectralOn(): boolean | null { + const r = this.rows.get('spectral'); + return r ? r.used : null; + } + + setSpectral(on: boolean): void { + const r = this.rows.get('spectral'); + if (r) r.used = on; + const has = this.refusals.includes('spectral'); + if (on && !has && (r?.gpu ?? 'refuses') === 'refuses') this.refusals = [...this.refusals, 'spectral']; + if (!on && has) this.refusals = this.refusals.filter((c) => c !== 'spectral'); + this.key = ''; + this.emit(); + } + + schedule(delay = 250): void { + if (this.users <= 0) return; + window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => void this.reload(), delay); + } + + private wire(): void { + if (this.wired) return; + this.wired = true; + for (const type of CHANGE_EVENTS) events.on(type, () => this.schedule(type === 'hello' || type === 'resync' ? 0 : 250)); + events.on('ui.dispatched', (e) => { + const name = typeof e.name === 'string' ? e.name : ''; + if (name && !READS.test(name)) this.schedule(name === 'render.set_device' ? 0 : 200); + }); + } + + private async reload(): Promise { + const seq = ++this.seq; + try { + const [raw, dev] = await Promise.all([ + api.dispatch(FEATURES_COMMAND, {}, { timeoutMs: 15000 }), + api.dispatch(DEVICES, {}, { timeoutMs: 15000 }).catch(() => null), + ]); + if (seq !== this.seq) return; + const o = body(raw); + const rows = new Map(); + for (const item of Array.isArray(o.features) ? o.features : []) { + const r = parseRow(item); + if (r) rows.set(r.feature, r); + } + this.rows = rows; + this.refusals = Array.isArray(o.gpu_refusals) ? o.gpu_refusals.filter((x): x is string => typeof x === 'string') : []; + if (dev) { + const d = body(dev); + const id = typeof d.current === 'string' ? d.current : typeof d.active === 'string' ? d.active : ''; + const list = Array.isArray(d.devices) ? d.devices.map(obj) : []; + const hit = list.find((x) => x.id === id); + const kind = hit?.kind === 'gpu' || id.startsWith('gpu') ? 'gpu' : id ? 'cpu' : ''; + this.device = { id, kind, name: typeof hit?.name === 'string' ? hit.name : id }; + } + this.available = true; + this.error = ''; + } catch (err) { + if (seq !== this.seq) return; + const status = obj(err).status; + this.available = !(status === 400 || status === 404); + this.error = err instanceof Error ? err.message : String(err); + } + this.loaded = true; + const key = JSON.stringify([[...this.rows.values()], this.refusals, this.device, this.available, this.error]); + if (key === this.key) return; + this.key = key; + this.emit(); + } + + private emit(): void { for (const fn of this.fns) fn(); } +} + +export const features = new FeatureStore(); + +export function useWhileVisible(node: HTMLElement): () => void { + let release: (() => void) | null = null; + const io = new IntersectionObserver((entries) => { + const seen = entries.some((e) => e.isIntersecting); + if (seen && !release) release = features.use(); + else if (!seen && release) { release(); release = null; } + }); + io.observe(node); + return () => { io.disconnect(); release?.(); release = null; }; +} + +export function cpuOnlyText(codes: readonly string[]): string { + return t('Renders on the CPU, because the GPU engine does not draw these yet: {features}.', { features: codes.map(featureLabel).join(', ') }); +} diff --git a/frontend/src/ui/transport/material.ts b/frontend/src/ui/transport/material.ts new file mode 100644 index 00000000..c0847ba0 --- /dev/null +++ b/frontend/src/ui/transport/material.ts @@ -0,0 +1,288 @@ +import './transport.css'; +import { el, escapeHtml, q, setAttr, setClass, setHidden, setText } from '../../shell/dom'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import type { Edits } from '../material/edits'; +import { + acescgToHex, fieldLabel, hexToAcescg, keyArg, rgbOf, stepFor, TRANSPORT_LABELS, TRANSPORT_SECTIONS, TRANSPORT_UNITS, unitText, + type FieldSpec, type MaterialDoc, type MaterialType, type ParamSection, type Rgb, +} from '../material/model'; +import { colourRow, numberRow, toggleRow, type Control } from '../material/rows'; +import { CMD, type MaterialStore } from '../material/store'; +import { cpuBadge, type Badge } from './badge'; +import { features, useWhileVisible } from './features'; +import { VectorRow } from './vector'; + +export interface TransportParamsHost { current(): string | null } + +export interface TransportParams { + owns(field: string): boolean; + update(type: MaterialType | null, d: MaterialDoc | null): void; +} + +const CHEVRON = ''; +const EXTRA: Readonly> = { fibre_density: ['fibre_comb_direction', 'fibre_seed'] }; +const OWNED = new Set(TRANSPORT_SECTIONS.flatMap((s) => s.fields)); + +const DEFAULTS: Readonly> = { + transmission_scatter: [0, 0, 0], transmission_scatter_anisotropy: 0, subsurface_scatter_anisotropy: 0, medium_priority: 0, + edge_radius: 0, edge_other_parts: false, + fibre_density: 0, fibre_length: 0.004, fibre_root_width: 0.0001, fibre_tip_width: 0.00004, fibre_comb: 0, fibre_comb_direction: [0, -1, 0], + fibre_randomness: 0.15, fibre_curl: 0, fibre_clumping: 0, fibre_own_color: false, fibre_color: [0.8, 0.8, 0.8], + fibre_roughness: 0.3, fibre_radial_roughness: 0.6, fibre_seed: 0, +}; + +const num = (v: unknown, d = 0): number => (typeof v === 'number' && Number.isFinite(v) ? v : d); +const label = (field: string): string => TRANSPORT_LABELS[field] ?? fieldLabel(field); +const valueOf = (d: MaterialDoc, field: string): unknown => d.params[field] ?? DEFAULTS[field]; + +function uses(feature: string, p: Record): boolean { + const solid = num(p.transmission_weight) > 0 && p.geometry_thin_walled !== true; + switch (feature) { + case 'volume': return solid && num(p.transmission_depth) > 0; + case 'nested_media': return solid && num(p.medium_priority) > 0; + case 'subsurface': return num(p.subsurface_weight) > 0 && p.geometry_thin_walled !== true; + case 'rounded_edges': return num(p.edge_radius) > 0; + case 'fibres': return num(p.fibre_density) > 0 && num(p.fibre_length, 0.004) > 0; + default: return false; + } +} + +const TYPE_HINTS: Readonly> = { + volume: 'Fills the part with a medium such as smoke, fog or tinted liquid. White light that travels the transmission depth takes on the transmission colour; the scatter amount makes it cloudy.', + translucent: 'Light enters the part, wanders beneath the surface and leaves elsewhere, as in wax, soap or marble. The subsurface radius sets how far it travels; the radius scale sets it per colour.', +}; + +const FIELD_FEATURE: Readonly> = { medium_priority: 'nested_media', edge_radius: 'rounded_edges', fibre_density: 'fibres' }; + +interface Row { + field: string; + root: HTMLElement; + control: { setDisabled(d: boolean, why?: string): void; setTag(text: string, why?: string): void }; + paint(d: MaterialDoc): void; +} + +interface Group { + section: ParamSection; + root: HTMLElement; + body: HTMLElement; + toggle: HTMLButtonElement; + badge: Badge; + rows: Map; +} + +export function mountTransportParams(after: HTMLElement, ws: Workspace, store: MaterialStore, edits: Edits, page: TransportParamsHost): TransportParams { + const wrap = el('
            '); + const hint = el(''); + after.after(hint, wrap); + useWhileVisible(wrap); + const groups = new Map(); + const opened = new Map(); + const scatterColour = new Map(); + let lastType: MaterialType | null = null; + let lastDoc: MaterialDoc | null = null; + + const send = (field: string, value: unknown, final: boolean): void => { + const key = page.current(); + if (!key) return; + store.patchParams(key, { [field]: value }); + const args = { key: keyArg(key), values: { [field]: value } }; + const target = `params:${key}`; + if (final) void edits.commit(target, CMD.setParams, args); + else edits.live(target, CMD.setParams, args); + }; + + const scatterOf = (d: MaterialDoc): { colour: Rgb; amount: number } => { + const v = rgbOf(d.params.transmission_scatter) ?? [0, 0, 0]; + const amount = Math.max(v[0], v[1], v[2]); + if (amount > 0) { + const c: Rgb = [v[0] / amount, v[1] / amount, v[2] / amount]; + scatterColour.set(d.key, c); + return { colour: c, amount }; + } + return { colour: scatterColour.get(d.key) ?? [1, 1, 1], amount: 0 }; + }; + + const numberFor = (field: string, spec: FieldSpec | null): Row => { + const shown = TRANSPORT_UNITS[field]; + const scale = shown?.scale ?? 1; + const min = shown ? shown.min : spec?.min ?? 0; + const max = shown ? shown.max : spec?.max ?? 1; + const n = numberRow({ + label: label(field), min, max, integer: shown?.integer, + step: shown?.integer ? 1 : stepFor({ field, kind: 'float', min, max, unit: '', slot: false }), + unit: shown ? shown.unit : unitText(spec?.unit ?? ''), + onLive: (v) => send(field, shown?.integer ? Math.round(v) : v / scale, false), + onCommit: (v) => send(field, shown?.integer ? Math.round(v) : v / scale, true), + }); + return { field, root: n.root, control: n, paint: (d) => { const v = valueOf(d, field); n.set(typeof v === 'number' ? v * scale : 0); } }; + }; + + const scatterRows = (): Row[] => { + const colour = colourRow({ + label: label('transmission_scatter'), + onLive: (hex) => setScatter(hex, null, false), + onCommit: (hex) => setScatter(hex, null, true), + }); + const u = TRANSPORT_UNITS.transmission_scatter_amount; + const amount = numberRow({ + label: label('transmission_scatter_amount'), min: u.min, max: u.max, step: stepFor({ field: '', kind: 'float', min: u.min, max: u.max, unit: '', slot: false }), + onLive: (v) => setScatter(null, v, false), + onCommit: (v) => setScatter(null, v, true), + }); + return [ + { field: 'transmission_scatter', root: colour.root, control: colour, paint: (d) => colour.set(acescgToHex(scatterOf(d).colour)) }, + { field: 'transmission_scatter_amount', root: amount.root, control: amount, paint: (d) => amount.set(scatterOf(d).amount) }, + ]; + }; + + const setScatter = (hex: string | null, amount: number | null, final: boolean): void => { + const key = page.current(); + const d = store.doc(key); + if (!key || !d) return; + const cur = scatterOf(d); + let c = cur.colour; + if (hex !== null) { + const v = hexToAcescg(hex); + if (!v) return; + const m = Math.max(v[0], v[1], v[2]); + c = m > 0 ? [v[0] / m, v[1] / m, v[2] / m] : [1, 1, 1]; + scatterColour.set(key, c); + } + const a = amount ?? cur.amount; + const r = (x: number): number => +(x * a).toFixed(6); + send('transmission_scatter', [r(c[0]), r(c[1]), r(c[2])], final); + }; + + const vectorFor = (field: string, names: readonly [string, string, string], min: number, max: number, fallback: Rgb): Row => { + const row = new VectorRow(label(field), names, min, max, (v, final) => send(field, v, final)); + return { field, root: row.root, control: row, paint: (d) => row.set(rgbOf(valueOf(d, field)) ?? fallback) }; + }; + + const makeRows = (field: string, spec: FieldSpec | null): Row[] => { + if (field === 'transmission_scatter') return scatterRows(); + if (field === 'subsurface_radius_scale') return [vectorFor(field, ['R', 'G', 'B'], 0, 1, [1, 1, 1])]; + if (field === 'fibre_comb_direction') return [vectorFor(field, ['X', 'Y', 'Z'], -1, 1, [0, -1, 0])]; + const kind = spec?.kind ?? (field === 'fibre_color' ? 'colour' : field === 'fibre_own_color' || field === 'edge_other_parts' ? 'bool' : 'float'); + if (kind === 'colour') { + const c = colourRow({ + label: label(field), + onLive: (hex) => { const v = hexToAcescg(hex); if (v) send(field, v, false); }, + onCommit: (hex) => { const v = hexToAcescg(hex); if (v) send(field, v, true); }, + }); + return [{ field, root: c.root, control: c, paint: (d) => { const v = rgbOf(valueOf(d, field)); if (v) c.set(acescgToHex(v)); } }]; + } + if (kind === 'bool') { + const b: Control = toggleRow(label(field), (on) => { + const key = page.current(); + if (!key) return; + store.patchParams(key, { [field]: on }); + void edits.once(CMD.setParams, { key: keyArg(key), values: { [field]: on } }); + }); + return [{ field, root: b.root, control: b, paint: (d) => b.set(valueOf(d, field) === true) }]; + } + return [numberFor(field, spec)]; + }; + + const groupFor = (section: ParamSection): Group => { + let g = groups.get(section.id); + if (g) return g; + const bodyId = `fsh-tr-group-${section.id}`; + const root = el(`
            + + +
            `); + const toggle = q(root, '.fsh-tr-group-head'); + const badge = cpuBadge(); + toggle.appendChild(badge.el); + g = { section, root, body: q(root, '.fsh-tr-group-body'), toggle, badge, rows: new Map() }; + const group = g; + toggle.addEventListener('click', () => { + const key = `${page.current() ?? ''}:${section.id}`; + const open = toggle.getAttribute('aria-expanded') !== 'true'; + opened.set(key, open); + paintOpen(group, open); + }); + groups.set(section.id, g); + return g; + }; + + const paintOpen = (g: Group, open: boolean): void => { + setAttr(g.toggle, 'aria-expanded', open ? 'true' : 'false'); + setClass(g.root, 'is-open', open); + setHidden(g.body, !open); + }; + + const fieldsFor = (section: ParamSection, type: MaterialType | null): { field: string; spec: FieldSpec | null }[] => { + const shown = type?.shown ?? []; + const out: { field: string; spec: FieldSpec | null }[] = []; + for (const field of section.fields) { + const spec = shown.find((s) => s.field === field) ?? null; + if (spec) out.push({ field, spec }); + else if (shown.some((s) => (EXTRA[s.field] ?? []).includes(field))) out.push({ field, spec: null }); + } + return out; + }; + + const paintRow = (r: Row, d: MaterialDoc | null, used: Set): void => { + if (d) r.paint(d); + const driven = !!d?.graph?.outputs.includes(r.field); + const can = ws.canRun(CMD.setParams); + const why = !d ? t('Reading the material') : !can ? ws.why(CMD.setParams) : driven ? t('Driven by the graph. Edit the graph to change it.') : ''; + r.control.setDisabled(!d || !can || driven, why); + const feature = FIELD_FEATURE[r.field]; + if (driven) r.control.setTag(t('Graph'), t('Driven by the graph. Edit the graph to change it.')); + else if (feature && used.has(feature) && features.refused(feature)) r.control.setTag('CPU', t('The GPU engine refuses this, so the picture renders on the CPU.')); + else r.control.setTag(''); + }; + + let openedFor = ''; + const update = (type: MaterialType | null, d: MaterialDoc | null): void => { + lastType = type; + const about = type ? TYPE_HINTS[type.id] ?? '' : ''; + setText(hint, about ? t(about) : ''); + setHidden(hint, about === ''); + lastDoc = d; + const key = page.current() ?? ''; + const used = new Set(); + if (d) for (const f of ['volume', 'nested_media', 'subsurface', 'rounded_edges', 'fibres']) if (uses(f, d.params)) used.add(f); + const fresh = d !== null && openedFor !== `${key}:${d.typeId}`; + if (fresh) openedFor = `${key}:${d?.typeId ?? ''}`; + let index = 0; + for (const section of TRANSPORT_SECTIONS) { + const fields = fieldsFor(section, type); + const g = fields.length ? groupFor(section) : groups.get(section.id); + if (!g) continue; + if (!fields.length) { if (g.root.isConnected) g.root.remove(); continue; } + const want = new Set(); + let cursor: Element | null = g.body.firstElementChild; + for (const { field, spec } of fields) { + let rows = [...g.rows.values()].filter((r) => r.field === field || (field === 'transmission_scatter' && r.field === 'transmission_scatter_amount')); + if (!rows.length) { + rows = makeRows(field, spec); + for (const r of rows) { r.root.dataset.field = r.field; g.rows.set(r.field, r); } + } + for (const r of rows) { + want.add(r.field); + if (r.root !== cursor) g.body.insertBefore(r.root, cursor); + else cursor = cursor.nextElementSibling; + paintRow(r, d, used); + } + } + for (const [f, r] of g.rows) if (!want.has(f) && r.root.isConnected) r.root.remove(); + const at = wrap.children[index] ?? null; + if (g.root !== at) wrap.insertBefore(g.root, at); + index++; + const featureOf = section.id === 'medium' ? ['volume', 'nested_media'] : [section.feature]; + const mine = featureOf.filter((f) => used.has(f)); + g.badge.set(mine.some((f) => features.refused(f))); + setClass(g.root, 'is-used', mine.length > 0); + const remembered = opened.get(`${key}:${section.id}`); + if (remembered !== undefined) paintOpen(g, remembered); + else if (fresh) paintOpen(g, mine.length > 0 || (section.id === 'medium' && d?.typeId === 'volume') || (section.id === 'subsurface' && d?.typeId === 'translucent')); + } + }; + + features.onChange(() => update(lastType, lastDoc)); + return { owns: (field) => OWNED.has(field), update }; +} diff --git a/frontend/src/ui/transport/transport.css b/frontend/src/ui/transport/transport.css new file mode 100644 index 00000000..93dd8bea --- /dev/null +++ b/frontend/src/ui/transport/transport.css @@ -0,0 +1,62 @@ +.fsh-tr-badge { display: inline-flex; flex: none; align-items: center; gap: 3px; height: 18px; padding: 0 var(--space-1); border-radius: var(--radius-sm); background: var(--accent-soft); color: var(--accent-ink); font-size: var(--fs-10); font-weight: var(--fw-medium); line-height: 18px; white-space: nowrap; visibility: hidden; } +.fsh-tr-badge.is-on { visibility: visible; } +.fsh-tr-badge svg { flex: none; } + +.fsh-render-check.fsh-tr-spectral { grid-template-columns: auto auto auto; justify-content: start; justify-self: start; } +.fsh-tr-help { margin: 0; color: var(--text-muted); font-size: var(--fs-12); line-height: var(--lh); } +.fsh-tr-note { height: calc(var(--fs-12) * var(--lh) * 2); margin: 0; overflow: hidden; color: var(--text-secondary); font-size: var(--fs-12); line-height: var(--lh); visibility: hidden; } +.fsh-tr-note[data-on] { visibility: visible; } +.fsh-tr-error { margin: 0; color: var(--danger-text); font-size: var(--fs-12); } +.fsh-tr-error[hidden] { display: none; } + +.fsh-tr-typehint { margin: var(--space-2) 0 0; color: var(--text-muted); font-size: var(--fs-12); line-height: var(--lh); } +.fsh-tr-typehint[hidden] { display: none; } +.fsh-tr-groups { display: grid; gap: var(--space-1); margin-top: var(--space-2); } +.fsh-tr-groups:empty { display: none; } +.fsh-tr-group { border-top: 1px solid var(--line-1); } +.fsh-tr-group-head { display: flex; align-items: center; gap: var(--space-1); width: 100%; height: var(--ctl-md); margin: 0; padding: 0 var(--space-1); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-secondary); font-size: var(--fs-12); font-weight: var(--fw-semibold); text-align: left; cursor: pointer; } +.fsh-tr-group-head:hover { background: var(--bg-hover); color: var(--text-primary); } +.fsh-tr-group-head:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -2px; } +.fsh-tr-chev { display: inline-flex; flex: none; color: var(--text-faint); transform: rotate(-90deg); transition: transform var(--dur-fast) ease; } +.fsh-tr-group.is-open .fsh-tr-chev { transform: none; } +.fsh-tr-group-title { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fsh-tr-group-dot { flex: none; width: 6px; height: 6px; border-radius: var(--radius-pill); background: var(--accent-color); visibility: hidden; } +.fsh-tr-group.is-used .fsh-tr-group-dot { visibility: visible; } +.fsh-tr-group-head .fsh-tr-badge { margin-left: auto; } +.fsh-tr-group-body { display: grid; gap: var(--space-1); padding: 0 0 var(--space-2); } +.fsh-tr-group-body[hidden] { display: none; } + +.fsh-tr-vector { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: var(--space-1) var(--space-2); } +.fsh-tr-vector-label { grid-column: 1 / -1; color: var(--text-secondary); font-size: var(--fs-12); } +.fsh-tr-vector-fields { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--space-1); min-width: 0; } +.fsh-tr-vector .fsh-mat-tag { grid-row: 1; grid-column: 2; } +.fsh-tr-vector.is-disabled .fsh-tr-vector-label { color: var(--text-faint); } + +.fsh-tr-cut { display: grid; gap: var(--space-2); } +.fsh-tr-cut-add { display: flex; align-items: center; gap: var(--space-1); min-height: var(--ctl-md); } +.fsh-tr-cut-add-label { flex: 1; min-width: 0; overflow: hidden; color: var(--text-secondary); font-size: var(--fs-12); text-overflow: ellipsis; white-space: nowrap; } +.fsh-tr-cut-shape { width: var(--ctl-md); height: var(--ctl-md); } +.fsh-tr-cut-list { display: grid; gap: 2px; } +.fsh-tr-cut-list:empty { display: none; } +.fsh-tr-cut-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; align-items: center; gap: var(--space-2); height: 32px; padding: 0 var(--space-2); border-radius: var(--radius); color: var(--text-primary); font-size: var(--fs-12); cursor: pointer; } +.fsh-tr-cut-row:hover { background: var(--bg-hover); } +.fsh-tr-cut-row[aria-selected="true"] { background: var(--accent-soft); } +.fsh-tr-cut-row.is-off .fsh-tr-cut-name { color: var(--text-faint); } +.fsh-tr-cut-row input { margin: 0; accent-color: var(--accent-color); } +.fsh-tr-cut-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fsh-tr-cut-kindtext { color: var(--text-muted); font-size: var(--fs-11); } +.fsh-tr-cut-empty { margin: 0; color: var(--text-muted); font-size: var(--fs-12); } +.fsh-tr-cut-empty[hidden], .fsh-tr-cut-edit[hidden] { display: none; } +.fsh-tr-cut-note { height: auto; min-height: calc(var(--fs-12) * var(--lh)); } +.fsh-tr-cut-edit { display: grid; gap: var(--space-1); padding-top: var(--space-1); border-top: 1px solid var(--line-1); } +.fsh-tr-cut-dims { display: grid; align-content: start; gap: var(--space-1); min-height: calc(var(--ctl-md) * 3 + var(--space-1) * 2); } +.fsh-tr-cut-plane { margin: 0; color: var(--text-muted); font-size: var(--fs-12); line-height: var(--lh); } +.fsh-tr-cut-plane[hidden] { display: none; } +.fsh-tr-cut-caprow { grid-template-columns: minmax(0, 1fr) auto; } +.fsh-tr-cut-capcolour { width: 32px; height: 22px; padding: 0; border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: transparent; cursor: pointer; } +.fsh-tr-cut-capcolour[data-off] { opacity: 0.35; cursor: default; } +.fsh-tr-cut-toggles { display: grid; gap: var(--space-1); } +.fsh-tr-cut-targets { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: var(--space-2); align-items: baseline; min-height: var(--ctl-sm); font-size: var(--fs-12); } +.fsh-tr-cut-targets-label { color: var(--text-secondary); } +.fsh-tr-cut-targets-list { overflow: hidden; color: var(--text-primary); text-overflow: ellipsis; white-space: nowrap; } +.fsh-tr-cut-actions { display: flex; flex-wrap: wrap; gap: var(--space-1); } diff --git a/frontend/src/ui/transport/vector.ts b/frontend/src/ui/transport/vector.ts new file mode 100644 index 00000000..9c3fd4a4 --- /dev/null +++ b/frontend/src/ui/transport/vector.ts @@ -0,0 +1,52 @@ +import { el, escapeHtml, q, setAttr, setClass, setHidden, setText, setTitle } from '../../shell/dom'; +import { t } from '../../i18n'; +import { NumberField } from '../number-field'; +import type { Rgb } from '../material/model'; + +export class VectorRow { + readonly root: HTMLElement; + private readonly fields: NumberField[] = []; + private value: Rgb = [0, 0, 0]; + private readonly tag: HTMLElement; + + constructor(label: string, names: readonly [string, string, string], min: number, max: number, private readonly send: (v: Rgb, final: boolean) => void) { + this.root = el(`
            ${escapeHtml(t(label))}
            `); + this.tag = q(this.root, '.fsh-mat-tag'); + const box = q(this.root, '.fsh-tr-vector-fields'); + const step = (max - min) / 200; + names.forEach((name, i) => { + const f = new NumberField({ + label: name, min, max, step, + onInput: (v) => this.change(i, v, false), + onCommit: (v) => this.change(i, v, true), + }); + f.root.setAttribute('data-no-i18n', ''); + this.fields.push(f); + box.appendChild(f.root); + }); + } + + private change(i: number, v: number, final: boolean): void { + const next: Rgb = [...this.value]; + next[i] = v; + this.value = next; + this.send(next, final); + } + + set(v: Rgb): void { + this.value = [v[0], v[1], v[2]]; + this.fields.forEach((f, i) => f.set(v[i])); + } + + setDisabled(d: boolean, why = ''): void { + for (const f of this.fields) f.setDisabled(d, why); + setClass(this.root, 'is-disabled', d); + } + + setTag(text: string, why = ''): void { + setText(this.tag, text); + setTitle(this.tag, why); + setHidden(this.tag, text === ''); + setAttr(this.root, 'data-tagged', text ? 'true' : null); + } +} diff --git a/frontend/src/ui/view-camera.ts b/frontend/src/ui/view-camera.ts index 87dec652..6b0cb016 100644 --- a/frontend/src/ui/view-camera.ts +++ b/frontend/src/ui/view-camera.ts @@ -27,7 +27,7 @@ export class ViewCamera { private readonly sendPose: (p: Pose) => void; private readonly sendFocal: (f: number) => void; - constructor(private readonly ws: Workspace) { + constructor(readonly ws: Workspace) { this.sendPose = coalesce((p) => this.quiet(CAMERA_SET, cameraArgs(p))); this.sendFocal = coalesce((f) => this.quiet(CAMERA_SET, { focal_length_mm: +f.toFixed(3) })); } diff --git a/frontend/src/ui/viewport-input.ts b/frontend/src/ui/viewport-input.ts index 3a9785d0..8f418af7 100644 --- a/frontend/src/ui/viewport-input.ts +++ b/frontend/src/ui/viewport-input.ts @@ -1,3 +1,4 @@ +import { mountMeasure } from './measure'; import { looksLikeTrackpad, modsOf, navAction, preset, type Mods, type NavAction } from './navigation'; import type { ViewCamera } from './view-camera'; import type { ViewState } from './view-state'; @@ -31,7 +32,8 @@ type Drag = | { kind: 'gizmo' } | { kind: 'select'; start: Point; last: Point; moved: boolean; mods: Mods; box: boolean; region?: boolean }; -export function attachInput(target: HTMLElement, camera: ViewCamera, view: ViewState, hooks: InputHooks): void { +export function attachInput(target: HTMLElement, camera: ViewCamera, view: ViewState, given: InputHooks): void { + const hooks = withTool(target, camera, view, given); let drag: Drag | null = null; let pointer = -1; let wheelTimer: number | undefined; @@ -202,3 +204,26 @@ export function attachInput(target: HTMLElement, camera: ViewCamera, view: ViewS lastScale = s; }); } + +export interface ViewportTool { + click(p: Point, m: Mods, double: boolean): boolean; + hover?(p: Point | null): void; +} + +export interface ViewportSession { + readonly target: HTMLElement; + readonly camera: ViewCamera; + readonly view: ViewState; + frame(): DOMRect; + setTool(tool: ViewportTool | null): void; +} + +function withTool(target: HTMLElement, camera: ViewCamera, view: ViewState, hooks: InputHooks): InputHooks { + let tool: ViewportTool | null = null; + mountMeasure({ target, camera, view, frame: () => hooks.frame(), setTool: (next) => { tool = next; } }); + return { + ...hooks, + click: (p, m, double) => { if (!tool?.click(p, m, double)) hooks.click(p, m, double); }, + hover: (p) => { hooks.hover(p); tool?.hover?.(p); }, + }; +} diff --git a/frontend/src/ui/workspace.ts b/frontend/src/ui/workspace.ts index 62e4b452..0bd00c30 100644 --- a/frontend/src/ui/workspace.ts +++ b/frontend/src/ui/workspace.ts @@ -11,6 +11,7 @@ import { mountLibrary } from './library'; import { mountStatusbar } from './statusbar'; import { mountViewport } from './viewport'; import { registerViewCommands } from './view-commands'; +import { mountTimeline } from './timeline'; const RERENDER: ReadonlySet = new Set(['region', 'full', 'display']); @@ -24,6 +25,7 @@ export function mount(ctx: ModuleContext): void { const ws: Workspace = { ctx, client, render, run, canRun, why }; const viewport = mountViewport(ws); + mountTimeline(ws); mountLibrary(ws); mountInspector(ws); mountStatusbar(ws); diff --git a/frontend/src/version.ts b/frontend/src/version.ts index ca24a8e2..699451ec 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.8.0'; +export const VERSION = '0.10.0'; diff --git a/native/Cargo.lock b/native/Cargo.lock index 7c315194..0759fa4a 100644 --- a/native/Cargo.lock +++ b/native/Cargo.lock @@ -218,7 +218,7 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "fsh-accel" -version = "0.8.0" +version = "0.10.0" dependencies = [ "fsh-core", "rayon", @@ -226,7 +226,7 @@ dependencies = [ [[package]] name = "fsh-cad" -version = "0.8.0" +version = "0.10.0" dependencies = [ "fsh-core", "fsh-io", @@ -235,7 +235,7 @@ dependencies = [ [[package]] name = "fsh-cli" -version = "0.8.0" +version = "0.10.0" dependencies = [ "fsh-commands", "fsh-io", @@ -244,7 +244,7 @@ dependencies = [ [[package]] name = "fsh-commands" -version = "0.8.0" +version = "0.10.0" dependencies = [ "fsh-accel", "fsh-cad", @@ -262,18 +262,18 @@ dependencies = [ [[package]] name = "fsh-core" -version = "0.8.0" +version = "0.10.0" [[package]] name = "fsh-denoise" -version = "0.8.0" +version = "0.10.0" dependencies = [ "rayon", ] [[package]] name = "fsh-format" -version = "0.8.0" +version = "0.10.0" dependencies = [ "fsh-core", "fsh-scene", @@ -283,7 +283,7 @@ dependencies = [ [[package]] name = "fsh-io" -version = "0.8.0" +version = "0.10.0" dependencies = [ "bevy_mikktspace", "fsh-core", @@ -296,7 +296,7 @@ dependencies = [ [[package]] name = "fsh-materials" -version = "0.8.0" +version = "0.10.0" dependencies = [ "fsh-core", "serde", @@ -304,11 +304,11 @@ dependencies = [ [[package]] name = "fsh-ocio" -version = "0.8.0" +version = "0.10.0" [[package]] name = "fsh-oidn" -version = "0.8.0" +version = "0.10.0" dependencies = [ "fsh-denoise", "libloading", @@ -316,7 +316,7 @@ dependencies = [ [[package]] name = "fsh-py" -version = "0.8.0" +version = "0.10.0" dependencies = [ "fsh-commands", "pyo3", @@ -324,7 +324,7 @@ dependencies = [ [[package]] name = "fsh-render-cpu" -version = "0.8.0" +version = "0.10.0" dependencies = [ "fsh-accel", "fsh-core", @@ -337,7 +337,7 @@ dependencies = [ [[package]] name = "fsh-render-gpu" -version = "0.8.0" +version = "0.10.0" dependencies = [ "bytemuck", "fsh-accel", @@ -353,7 +353,7 @@ dependencies = [ [[package]] name = "fsh-scene" -version = "0.8.0" +version = "0.10.0" dependencies = [ "fsh-core", "fsh-materials", @@ -363,7 +363,7 @@ dependencies = [ [[package]] name = "fsh-wasm" -version = "0.8.0" +version = "0.10.0" dependencies = [ "bytemuck", "fsh-commands", diff --git a/native/HASHOUT_LOG.md b/native/HASHOUT_LOG.md index 83487f33..ada27ba9 100644 --- a/native/HASHOUT_LOG.md +++ b/native/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # native HASHOUT_LOG -Living log for the Rust engine side, _v0.8.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. Entries are appended to their crate's section as each part lands; the GPU engine's entries (fsh-render-gpu, last) carry the buffer layout contract, the WGSL module map and the recipe for running it on software Vulkan, GL and WebGPU, and docs/GPU-ENGINE.md restates them as tables. +Living log for the Rust engine side, _v0.10.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. Entries are appended to their crate's section as each part lands; the GPU engine's entries (fsh-render-gpu, last) carry the buffer layout contract, the WGSL module map and the recipe for running it on software Vulkan, GL and WebGPU, and docs/GPU-ENGINE.md restates them as tables. ## Org-navi-map @@ -14,6 +14,7 @@ native/ crates/fsh-core/src/color.rs Rgb (ACEScg), matrices, sRGB transfer, hex, blackbody crates/fsh-core/src/ids.rs render_id!, doc_key!, RenderId, DocKey, KeyGen crates/fsh-core/src/units.rs LengthUnit + crates/fsh-core/src/motion.rs Pose (T R S decomposition), quat_from_rotation, MotionPath: motion keys over the shutter and their bounds crates/fsh-core/src/sampler.rs hashes, Pcg32, Owen scramble, generated Sobol, dimension layout, PixelSampler crates/fsh-core/src/sampling.rs warps, pdfs, MIS heuristics crates/fsh-core/src/error.rs CoreError, Result @@ -21,6 +22,8 @@ native/ crates/fsh-accel/src/tri.rs RayPre, slab test, watertight triangle test, triangle_area crates/fsh-accel/src/mesh.rs MeshBvh: build, helpers, traversal, Intersector crates/fsh-accel/src/scene.rs masks, Hit, Intersector, Instance, Scene (two levels, refit, rebuild) + crates/fsh-accel/src/curve.rs CurveSegment (round truncated cone), SegmentHit, CurveBvh (one reference per fibre), CurveHit + crates/fsh-accel/src/fibres.rs FibreScene (Scene plus fibre layers, Intersector, Deref), FibreLayer, FibreHit, FIBRE_PRIM crates/fsh-accel/src/error.rs AccelError, Result crates/fsh-materials/src/inputs.rs SurfaceInputs and sanitized() crates/fsh-materials/src/fresnel.rs dielectric Fresnel, refract, specular weight to ior, F82-tint conductor @@ -35,6 +38,10 @@ native/ crates/fsh-materials/src/film.rs Airy thin-film reflectance (Belcour and Barla), s/p Fresnel with phases, Gulbrandsen, FilmLayer crates/fsh-materials/src/optics.rs Optics (film and Cauchy dispersion), dispersion_channel, thin_film_dielectric, thin_film_conductor crates/fsh-materials/src/procedural.rs ProcKind, ProcOutput, procedural(); procedural/common.rs, noise.rs, cells.rs, patterns.rs hold the ten kinds + crates/fsh-materials/src/phase.rs henyey_greenstein, sample_henyey_greenstein, PhaseSample + crates/fsh-materials/src/medium.rs MediumCoefficients, transmission_medium, single_scattering_albedo, subsurface_medium (OpenPBR) + crates/fsh-materials/src/scatter.rs Scatter: the surface Bsdf or the FibreBsdf behind the same calls + crates/fsh-materials/src/fibre.rs, fibre_lobes.rs FibreBsdf, FibreInputs (Chiang et al. 2016 hair and fibre model); Mp, Np, Ap, roughness maps crates/fsh-scene/src/error.rs SceneError with code() crates/fsh-scene/src/ser.rs serde with-helpers for fsh-core types crates/fsh-scene/src/mesh.rs Mesh, validation, compute_normals @@ -59,6 +66,22 @@ native/ crates/fsh-scene/src/lighting.rs spread and edge weights, IesRef, LightLinks, EnvPin, Dome, Backplate, BackgroundImage, lat_long, env_to_world crates/fsh-scene/src/lighting/ ies.rs (IesTable), snapshot.rs (RenderLighting, resolve_links, build), eval.rs (reference evaluation), commands.rs, studio.rs (presets, apply, capture), schema.rs crates/fsh-scene/src/denoise_settings.rs Denoiser, Quality, DenoiseSettings (RenderSettings.denoising) + crates/fsh-scene/src/shots.rs Shots, Shot, Include, LightState, capture, apply_shot, shot_document + crates/fsh-scene/src/shots/ choice.rs (the variant choice a shot keeps), commands.rs (the seven shot commands, answer) + crates/fsh-scene/src/variants.rs Variants, VariantSet, Variant, ModelSet, VariantChoice, apply_variant, apply_model_set, apply_choice, variant_diff + crates/fsh-scene/src/variants/ commands.rs (the 16 variant.* and model_set.* commands), schema.rs + crates/fsh-scene/src/configurator.rs Configurator, ConfigOption, Choice, Action, Rule + crates/fsh-scene/src/configurator/ solve.rs (the rule search), commands.rs (12 config.* commands, run_actions), check.rs (problems), bridge.rs (to variants and shots), schema.rs + crates/fsh-scene/src/measure.rs Measurements, Measurement, MeasureKind (distance, size, angle), Anchor, LabelOptions + crates/fsh-scene/src/measure/ eval.rs (evaluate, formatting, project), commands.rs (six measure.* commands), schema.rs + crates/fsh-scene/src/animation/ mod.rs (Animation, Track, Key, evaluate, frame_times), target.rs (what a track keys), curve.rs (interpolation), commands.rs (seven anim.* commands), schema.rs + crates/fsh-scene/src/animation/rigs.rs, rigs/ Rig and apply; timing.rs, turntable.rs, orbit.rs, path.rs, spline.rs, range.rs, scene.rs, commands.rs (six rig commands), schema.rs + crates/fsh-scene/src/motion.rs MotionBlur, ShutterPosition, CameraMotion, flatten_motion, flatten_frame, has_motion + crates/fsh-scene/src/transport/ mod.rs (Transport, RenderSettings.transport), spectral.rs (Spectral), caustics.rs (Caustics, CausticsMode) + crates/fsh-scene/src/cutaway.rs CutawaySetEnabled, CutawaySetTargets, cutaway_level (cutaway.set_enabled, cutaway.set_targets) + crates/fsh-scene/src/fibres.rs fibre settings, FibreCurves, RenderFibres, grow, grow_cached, MAX_SEGMENTS (RenderSnapshot.fibres) + crates/fsh-scene/src/catalogue/fields.rs fields::full: schemas read from a type's Deserialize, fields at default included + crates/fsh-scene/src/command/hooks.rs forget_nodes, copy_references, renumber_cameras, material_user: references kept consistent crates/fsh-io/src/ raw scene, glTF/GLB, OBJ+MTL, STL, PLY readers, clean-up, convert, GLB writer, deflate, PNG, HDR, EXR crates/fsh-io/src/zip.rs in-memory ZIP reader for 3MF packages (stored and deflated, ZIP64 sizes, CRC and bomb checks) crates/fsh-io/src/threemf.rs 3MF reader: units, build items, components, materials, colour and texture groups @@ -79,8 +102,16 @@ native/ crates/fsh-format/src/ zip, canonical json, meshbin, version, project save/load, journal, session and recovery, platform (wall clock, process id, file-system guard) crates/fsh-format/src/sha256.rs FIPS 180-4 SHA-256 for texture member names crates/fsh-render-cpu/src/ geometry, env, sky, lights, emissive, camera, film, integrator, denoise, develop, renderer, clock, spec (the GPU port's specification) + crates/fsh-render-cpu/src/motion.rs InstanceData::placed, motion_keys, Ctx::path_time (the shutter time draw) crates/fsh-render-cpu/src/hosek.rs, hosek_data.rs PhysicalSky (Hosek-Wilkie 1.4a, spectral) and its generated BSD-licensed tables crates/fsh-render-cpu/src/lamp_extras.rs LampExtras, LampTables: spread, edge softness, IES and link masks of the lamps + crates/fsh-render-cpu/src/media.rs Medium, MediumStack, PathMedia, transmittance, sample_segment, track, Closure, walk (media, nesting, subsurface) + crates/fsh-render-cpu/src/spectral.rs Wavelengths, Emitter, Blackbody, reflectance, sample_visible_wavelength (spectral mode) + crates/fsh-render-cpu/src/spectral/ cie.rs (generated CIE tables), observer.rs, uplift.rs (Sigmoid, solver), table.rs, uplift_table.bin (generated), scene.rs (SpectralScene), media.rs (MediumSpectra) + crates/fsh-render-cpu/src/caustics.rs Class, pass_radius, auto_radius; caustics/ grid.rs (PhotonMap), emit.rs, trace.rs, gather.rs, pass.rs (photon passes) + crates/fsh-render-cpu/src/cutaway.rs CutScene (the cut and the caps), cutaway_removes, cutaway_spans, is_closed + crates/fsh-render-cpu/src/edges.rs EdgeRounding, rounded_material, Ctx::round_edges (rounded edges by probe chords) + crates/fsh-render-cpu/src/fibres.rs FibredScene, FibreShading, fibre_root (fibres in the tracer) crates/fsh-render-cpu/src/develop/ colour.rs, grade.rs, effects.rs, aces.rs, agx.rs, quant.rs, fastmath.rs, ocio.rs (adapter), ocio_link.rs (fsh-ocio backend) crates/fsh-ocio/src/ FormShot's own OpenColorIO v2 evaluator: yaml.rs, config.rs, transform.rs, build.rs, processor.rs, ops.rs, lut.rs, colorimetry.rs, aces.rs, builtin.rs crates/fsh-denoise/src/ the own denoiser: lib.rs (API), params.rs, prepare.rs, variance.rs, atrous.rs, refine.rs, alpha.rs, exec.rs @@ -98,6 +129,18 @@ native/ crates/fsh-commands/src/ext/materials.rs material.types, material.node_kinds, material.program, material.preview_maps crates/fsh-commands/src/ext/library.rs library.list, get, favorite, recent, apply, save, remove, thumbnail, thumbnails crates/fsh-commands/src/ext/library/ locate.rs, preset.rs, store.rs, search.rs, state.rs, ball.rs, thumbs.rs, apply.rs, sha256.rs + crates/fsh-commands/src/ext/shots.rs shot.list, shot.render + crates/fsh-commands/src/ext/variants.rs variant.list, model_set.list, variant.diff + crates/fsh-commands/src/ext/configurator.rs config.get, config.check, config.list, config.render_all + crates/fsh-commands/src/ext/templates.rs template.list, get, save, remove, preview, apply, capture; dress, preset_material (used by the import) + crates/fsh-commands/src/ext/templates/ model.rs (Template, Rule, the glob, the file format), store.rs (built-in and user files), plan.rs (the plan, apply, capture) + crates/fsh-commands/src/ext/measure.rs measure.list, measure.pick, measure.render, draw_into + crates/fsh-commands/src/ext/measure/ draw.rs (the line, plate and text rasteriser), font.rs (the own 5 by 7 font) + crates/fsh-commands/src/ext/anim.rs anim.seek, anim.status, anim.sample, anim.render (render_sequence) + crates/fsh-commands/src/ext/video.rs video.ffmpeg, video.encode, Movie, MovieFrames, timeline (the animation's frame times) + crates/fsh-commands/src/ext/video/ find.rs (the ffmpeg lookup), probe.rs (version, encoders, hardware test), encoders.rs (formats, quality), encode.rs (the encode run) + crates/fsh-commands/src/ext/transport.rs transport.features: per feature cpu, gpu (probed against Refusals::check) and used + assets/library/templates/ cad-materials.json, colour-plastics.json: the built-in material templates crates/fsh-cli/src/main.rs formshot-engine: render (--device), info, convert, devices, bench, catalogue, dispatch (--journal), version, help crates/fsh-py/src/lib.rs pyo3 binding fsh_py (python feature, Session(journal=...)), pyproject.toml for maturin crates/fsh-wasm/src/lib.rs, session.rs, mirror.rs wasm-bindgen binding: catalogue, Session, Scene, the service mirror, the host clock @@ -125,6 +168,11 @@ native/ crates/fsh-render-gpu/src/shaders/texture.wgsl tex_sample: the texture directory, nearest, bilinear, trilinear, wraps, sRGB LUT, primaries crates/fsh-render-gpu/src/shaders/program.wgsl HitCtx, run_program: the material program interpreter (opcodes 0 to 24), sanitize_inputs crates/fsh-render-gpu/src/texpack.rs append, block_len: a TextureSet packed into the tables block + crates/fsh-render-gpu/src/media.rs set_medium, uses_media, stack_depth, stack_fits (the media block of Material, media_depth) + crates/fsh-render-gpu/src/transport.rs, spectral.rs TransportBlock (motion keys, camera keys), the spectral tables: appended to `tables` after the lighting block + crates/fsh-render-gpu/src/geo.rs GeoBlock (cut records, instance and edge records), usable_cutaways, cutaway_refusal, edges_refusal + crates/fsh-render-gpu/src/shaders/media.wgsl, motion.wgsl, spectral.wgsl the medium stack and walks, shutter-time poses, hero wavelengths + crates/fsh-render-gpu/src/shaders/cutaway.wgsl, edges.wgsl cut-aware traces and caps, rounded-edge normals crates/fsh-wasm/src/textures.rs Ident, TextureStore, SceneTextures, decode, pack and unpack for the window's texture worker crates/fsh-wasm/src/develop.wgsl, effects.wgsl, look.rs the window's GPU develop: grade, display transforms, effects, the dispatch plan (look.rs wasm32 only) crates/fsh-wasm/src/ocio_window.rs OpenColorIO configs handed over as text, the window's develop backend and the 65^3 baked table @@ -188,6 +236,12 @@ A pure function of (pixel, sample, dimension, seed). Dimensions 0 to 63 take the - logged: v0.2.0 · 2026-12-02 `cargo check -p fsh-core` clean. A throwaway program in /home/claude/targets/core/scratch (outside the repo) printed the sampler values, the stratification counts, identical output across 4 threads, PCG advance equal to stepping, the M times M inverse maximum error (1.2e-7) and the colour round trip. No unit tests, by rule. +### crates/fsh-core/src/motion.rs, math.rs · ray time, Pose and MotionPath +- refers-to: src/motion.rs :: Pose, Pose::from_transform, Pose::transform, quat_from_rotation, MotionPath, MotionPath::at, MotionPath::bounds; src/math.rs :: Ray::time, Ray::at_time, Transform::ray +- kind: decision +- logged: v0.9.0 · 2026-12-03 +`Ray` gains `time: f32`, in [0, 1) across the open shutter, 0 by default in every constructor (so it is 0 for every ray of a still scene), with `at_time(t)`, and `Transform::ray` keeps it. `Pose` is the polar decomposition `M = T R S` of a transform: translation, a proper rotation (a quaternion) and a symmetric stretch, with a mirror kept in the stretch so the rotation is always a rotation; between two poses translation and stretch blend linearly and rotation slerps along the shorter arc, so a turning part follows its arc and does not shrink through a straight blend. A blend whose matrix is singular takes the nearer key. `Pose::transform` builds the inverse from the stretch's 3 by 3 inverse and the transposed rotation, not a general 4 by 4 inverse (a change made after the first version, so traversal of a moving instance does less work per visit, and a blend is refused only when the stretch is singular). `MotionPath` holds keys evenly spaced over the shutter, the first at its opening (ray time 0) and the last at its closing (ray time 1), with `at(t)` and a conservative `bounds`: the box transformed at 16 substeps per key interval and each interval padded by the most a point can leave the chord between substeps, `(a^2 r + 2 a d) / 8` with `a` the rotation per substep, `r` the largest stretched corner radius and `d` the largest per-substep stretch change of a corner. Verified by scratch programs: the decomposition round trip within 2.4e-7 on three poses (one mirrored, one scaled 100 to 0.01), the inverse times the matrix within 2.4e-7 of the identity after the optimisation, and 10001 samples of a box that translated 1 m, turned 86 degrees and stretched 2 times, none outside the bounds. No pass of a still scene reads the time, so renders without motion are byte for byte as before (checked through fsh-render-cpu). + ## fsh-accel ### crates/fsh-accel/src/tri.rs · watertight triangle test and box test @@ -232,6 +286,18 @@ Not done: SIMD or wide (BVH4/8) nodes (the profile shows about 21 interior visit - logged: v0.3.0 · 2026-12-02 The GPU engine reads the CPU's own trees, flattened into one node array: `nodes[0 .. top_capacity)` is the top level (root at 0, unused slots zeroed), then each unique mesh's nodes in first-use instance order, every index absolute. A node is 32 bytes (min, data, max, info); `info & 0xff` is the leaf count, top-level nodes carry the compressed mask `mask24(m) = (m & 0x7fffff) | (m >> 23 != 0 ? 1 << 23 : 0)` in `info >> 8`, and since the ray-query work each mesh root carries its first triangle slot there. Triangles are 48 bytes of object-space corners in leaf order with each corner's vertex index within its mesh, and `slot_prims[slot]` maps back to the source triangle for picking and reports. `gpu_export_top` rewrites only the top level, for instance moves. Verified with a Rust port of the specified traversal over 60 instances and 200,000 random rays with 5 mask values: 0 mismatches in t, instance, prim, u and v (19,825 hits) and in occlusion, deterministic export, maximum stack 11 against a reported bound of 23. +### crates/fsh-accel/src/scene.rs · moving instances in the top level +- refers-to: src/scene.rs :: Instance::with_motion, Instance::motion, Instance::transform_at, Scene::world_triangle_at, Scene::hit_corners_at, Scene::has_motion, Scene::refit_instances; src/lib.rs +- kind: decision +- logged: v0.9.0 · 2026-12-03 +An `Instance` may carry motion keys (`with_motion(mesh, transform, keys, id, mask)`): world transforms at times evenly spaced over the shutter, kept as a `fsh_core::MotionPath`, while the plain `transform` stays the transform at the shutter's middle (what emissive sampling, the GPU flattening, picking and region resets keep using). The top-level tree is built over each moving instance's whole-motion bounds, traversal inverts the ray into the instance at the ray's own time (`transform_at(ray.time)`), and hit normals and `world_triangle_at` and `hit_corners_at` take the time too, so a hit on a moving part is found where the part was at that shutter time and not at the middle. `has_motion` is true when any instance moves, which the renderer uses to decide whether to draw a time at all. `refit_instances`, the viewport's fast path for a part moved by hand, drops an instance's motion, on the reasoning that a refit means the part was moved by hand and the keys no longer describe it. An instance with fewer than two keys, or none, keeps the old code path, so scenes without motion traverse as before. The tree is built once; the shutter time travels on the ray (the CPU tracer gives every ray of one path the same time). The crate summaries in lib.rs now name moving instances and motion blur. Nothing here was exercised alone; it was checked through the CPU renders described under fsh-render-cpu, with clippy for fsh-accel and the wasm32 check, both clean. + +### crates/fsh-accel/src/curve.rs, fibres.rs · curve segments, the curve BVH and FibreScene +- refers-to: src/curve.rs :: CurveSegment, SegmentHit, CurveBvh, CurveHit, MAX_LEAF_SEGMENTS; src/fibres.rs :: FibreScene, FibreLayer, FibreHit, FIBRE_PRIM +- kind: decision +- logged: v0.10.0 · 2026-12-03 +A fibre is a chain of round truncated cones: `CurveSegment` between p0 (radius r0) and p1 (r1), side wall only, no caps. With w the unit axis, k = (r1 - r0)/L, s the distance along the axis and q the offset from it, the wall is |q|^2 = (r0 + k s)^2, which along the ray is a quadratic A t^2 + 2 B t + C = 0 solved in f64 after moving the origin to the ray's closest approach to the segment's middle (a 50 micron fibre one metre away keeps its precision; checked out to 50 units). A root counts when 0 <= s <= L, the radius there is positive (which rejects the far nappe) and the ray enters the wall: entering only, because a ray leaving a fibre hit into the fibre (the TT direction) starts inside it and must pass out, the BSDF already accounting for crossing the fibre. `CurveBvh` uses the crate's binned-SAH builder with one reference per fibre (`from_polylines`, one leaf whose segments are tested together): 0.64 million nodes for 321,538 fibres instead of 1.44 million with one reference per segment. `FibreScene` wraps the instance `Scene` rather than changing scene.rs (which motion and cutaways also touched this release) and derefs to it, so every existing call keeps working; it keeps one layer per instance with the caller's id, `closest_hit` takes the instance hit and then each layer (world-bounds slab test, the instance's mask, the ray in object space, `tmax` at the best so far), and `occluded` is the instance test or any layer. A fibre hit has `prim = FIBRE_PRIM | segment`, `u` along the segment, `v` across (-1..1) and `ng` the world outward normal from the axis; `fibre_hit` expands it to segment, fibre index, position along and across, tangent (blended with the neighbouring segment toward each joint), normal, point and radius. Limits: fibres use the instance's still transform (`Instance::transform()`), so a moving part's fibres do not move with its motion keys until `FibreScene::fibres` takes the transform at `ray.time` (one line, not done); prim numbers from 1 << 30 belong to cutaway caps and curve hits must stay out of that range. + ## fsh-materials ### crates/fsh-materials/src/bsdf.rs · lobes and their sources @@ -324,6 +390,18 @@ OpenPBR 1.1's `thin_film_*` parameters, which the 0.4.0 BSDF ignored, follow Bel - logged: v0.6.0 · 2026-12-02 OpenPBR 1.1: V_d = abbe / scale, a Cauchy law through n_d with that Abbe number, stored as the slope k = scale / (abbe (lambda_F^-2 - lambda_C^-2)), so `n_c = n_d + (n_d - 1) k D_c` with D_c = lambda_c^-2 - lambda_d^-2 = (-0.0062823046, 0.5049531, 1.9850688) um^-2 for ACEScg R, G, B. The channel wavelengths (588.2, 542.2, 452.6 nm) are those whose Cauchy ior equals each channel's sensitivity-weighted mean ior, the first-order exact choice; red sits near the d line and close to green, blue far away, so a prism shows three slit images. The renderer (both tracers, identically) picks c = floor(3u) from sampler dimension 5 (`DIM_WAVELENGTH`, reserved by fsh-core and unused until now, so no other draw moves) at a dispersive, transmissive, not thin-walled hit, sets specular_ior to n_c, and the first transmission sample multiplies the throughput by 3 on channel c and 0 elsewhere; next-event estimation before that point takes the same weight. Diamond (n_d 2.4175, V 55.3) gives 2.41742, 2.42428, 2.44415. Not done: dispersion inside a channel, on thin walls, in the catcher mirror, transparent shadows through dispersive glass. +### crates/fsh-materials/src/phase.rs, medium.rs, scatter.rs · medium coefficients, the phase function and Scatter +- refers-to: src/phase.rs :: henyey_greenstein, sample_henyey_greenstein, PhaseSample; src/medium.rs :: MediumCoefficients, transmission_medium, single_scattering_albedo, subsurface_medium; src/scatter.rs :: Scatter +- kind: decision +- logged: v0.10.0 · 2026-12-03 +The maths of participating media lives in fsh-materials so that the CPU tracer, the GPU port and the spectral code read one definition. `henyey_greenstein(cos, g)` and `sample_henyey_greenstein(d, g, u)` (exact inversion, returning `PhaseSample { wi, pdf }`; `cos` is taken between the propagation directions before and after the event, |g| is clamped to 0.99 and the phase is isotropic under 1e-3). `MediumCoefficients { sigma_a, sigma_s, g }` carries per-channel absorption and scattering in 1/m (`sigma_t`, `scatters`, `is_vacuum`). `transmission_medium(colour, depth, scatter, g)` follows OpenPBR: the extinction is mu_t = -ln(T)/d from the transmission colour T at the transmission depth d, the scattering is mu_s = S/d from the scatter colour S, and the absorption mu_a = mu_t - mu_s is shifted by a grey amount until no channel is negative, so a white colour with a grey scatter does not absorb and a coloured scatter over a white colour absorbs the other channels; it answers `None` at depth 0, which keeps the old surface tint and every old document byte for byte. `single_scattering_albedo(C, g)` is OpenPBR's van de Hulst form with the Chiang, Kutz and Burley (2016) fit (s = 4.09712 + 4.20863 C - sqrt(9.59217 + 41.6808 C + 17.7126 C^2), alpha = (1 - s^2)/(1 - g s^2)), and `subsurface_medium(colour, radius, scale, g)` turns the subsurface colour and the radius times the per-channel radius scale into mu_t = 1/(radius x scale), floored at a path of 1e-6 m. `Scatter` (scatter.rs) is the closure the path loop shades with: the surface `Bsdf` or the fibre `FibreBsdf`, behind the same method names (eval, pdf, sample, albedo), so the integrator does not branch on what it hit. The module is additive: no existing function changed, and the white-furnace check of the CPU tracer (below, under fsh-render-cpu) exercises these formulas end to end. Not done: chromatic phase functions, and any medium that is not homogeneous. + +### crates/fsh-materials/src/fibre.rs, fibre_lobes.rs · the hair and fibre BSDF +- refers-to: src/fibre.rs :: FibreBsdf, FibreInputs, FIBRE_IOR, FIBRE_SCALE_TILT; src/fibre_lobes.rs :: Mp, Np, Ap, the roughness maps, colour to absorption +- kind: decision +- logged: v0.10.0 · 2026-12-03 +`FibreBsdf` is the hair and fibre model of Chiang, Bitterli, Tappan and Burley (2016), written from the paper: R, TT and TRT lobes plus a residual summed as a geometric series, a longitudinal lobe of d'Eon et al. (2011) in its low-variance log form, trimmed logistic azimuthal lobes about Phi = 2 p gamma_t - 2 gamma_o + p pi, Fresnel at `FIBRE_IOR` 1.55 and absorption per order, a cuticle tilt of 2 degrees (`FIBRE_SCALE_TILT`), the variance and logistic scale from the paper's roughness maps, and absorption from the colour with the paper's equation 9 (so the colour is what the multiply scattered fibre looks like, which makes a single scattering grey 0.5 fibre integrate to 0.90 to 0.97). The frame at a hit is x along the tangent, z the part of `wo` normal to it, y = z x x, and h = n . y from the hit's radial normal. `eval` returns the scattering function with the cosine included, as `Bsdf::eval` does; sampling picks a lobe by attenuation luminance and then inverts the longitudinal and azimuthal distributions (the lobe number is rescaled for the azimuth). Every sample is flagged GLOSSY | REFLECTION with eta 1, so fibres count against `max_bounces`, use the glossy ray mask and never count against the transmission limit. `Scatter` (scatter.rs) lets the path loop hold either this or the surface `Bsdf` behind the same calls. White furnace, 400,000 uniform directions per case at four outgoing angles: white fibres integrate to 0.986..1.048 at roughness 0.05 (the pdf, which must integrate to 1, gives the same spread there, so it is Monte Carlo noise of a narrow lobe), 0.993..1.004 at 0.3, 0.996..1.004 at 0.6 and 0.9998..1.0002 at 1, and importance-sampled weights are exactly 1. Not done: no GPU port of the lobes (the GPU refuses fibre scenes, see fsh-render-gpu), and grey fibres lose energy to single scattering by design (the colour mapping targets the multiply scattered look). + ## fsh-scene ### crates/fsh-scene/src/command.rs · ids and resolve @@ -488,6 +566,114 @@ The resolved values of `environment.set`, `ground.set`, `image.set`, `render.set - logged: v0.8.0 · 2026-12-03 Light-doc's release CLI driven over JSON-lines dispatch: 49 checks, 0 failures: seven templates written by the base reopen and re-save byte for byte; a journal written by the base CLI (killed mid-session) is recovered by the new one; every new lighting field created through commands, saved, reopened and saved again byte for byte with its `.ies`, `.png` and `.hdr` members; merges, refusals (truncated IES, unknown link node, unknown backplate texture, newer preset version, wrong format tag, a non-slug id); `studio.capture` and `studio.apply` variants each undone in one step back to the start, compared member by member with only `next_key` moved. Reference functions: rect and disc mean edge weights match numeric integration within 1e-4; spread gives exactly half radiance at half the spread. Camera: a project saved by the base, opened and saved, byte-identical (549,999 bytes); duplicate, rename, three undos and two redos, refusals of bad blades (2), field of view (400), an empty name and an unknown index. Image style: the style JSON round-trips; ten display edits through dispatch kept the job and its samples. Passes and denoise settings: old documents re-save byte for byte; unknown pass names, `ao_distance` 0 and an unknown quality are refused. clippy `-D warnings` and the wasm32 check ran clean on each branch. +### crates/fsh-scene/src/shots.rs, shots/choice.rs, shots/commands.rs · shots: named views kept in the document +- refers-to: src/shots.rs :: Shots, Shot, Include, LightState, SHOT_ID_PREFIX, Shot::capture, Shot::validate, Shot::missing, Shot::matches, Shot::summary, Shots::free_id, apply_shot, shot_document, node_map; src/shots/choice.rs :: VariantChoice, current, apply; src/shots/commands.rs :: answer, apply_remove; src/command.rs :: commands! (seven shot rows) +- kind: decision +- logged: v0.9.0 · 2026-12-03 +`DocumentData.shots` is an ordered list of shots, left out of the file when empty and checked on read (every shot valid, ids unique, so a hand-edited project with two shots of one id is refused). A shot always captures everything: a copy of the active camera with its lens and focus, the image style, environment, ground, render settings, per light node its visibility, power with its unit and colour, every node's own visibility, and the variant choice (left out when empty). The `include` flags (camera, image, environment which carries the ground, render, lights, visibility, variants; all true by default) only decide what applying restores, so switching a flag on later restores state that was captured all along; `include` takes an object of flags to change or a list of the parts that stay on, and history stores the full object. Ids are `shot` with the lowest free n (at most 64 characters, unique), names are trimmed and never empty, and a duplicate is named " copy" and placed right after its original. `shot.add` and `shot.update` capture while resolving and store the whole `Shot` in the command, so redo and journal replay put back the same capture; `shot.set` and `shot.duplicate` resolve to full values, and `shot.apply` resolves `skipped` (nodes that are gone). Applying is one undo step: a saved camera that already equals the shot camera (name ignored) becomes the active one, otherwise the active camera takes the shot's values and keeps its own name; a backplate or background picture whose texture is gone is dropped; visibility then lights are set, skipping missing or non-light nodes instead of failing; the variant choice goes through `variants::apply_choice` (the lead connected the adapter in choice.rs, so a shot keeps and restores its variant and model set choice). The change level is Full for scene changes, Display when only the image changes, None when the document already matches. `Shot::matches` compares only the included parts and ignores vanished nodes. The light and visibility maps serialise with decimal string keys like `ser::key_map` but deserialise through `node_map`, because `ser::key_map` reads keys as u64 and fails on a parsed `serde_json::Value`, which broke journal replay of `shot.add` until this. Documents without shots serialise exactly as before (no `shots` key; a project that had shots added and all removed re-saves byte for byte). Verified by dispatch on a debug build: capture, flip between shots with undo and redo, a saved camera activated instead of overwritten, save, reopen and re-save byte for byte, a crash-journal replay that rebuilt the same shots with undo depth 4, a removed light skipped on apply, and clippy and the wasm32 check clean. The variants part of a shot was first a stub and was not run until the lead connected it; no renderer or snapshot code changed. + +### crates/fsh-scene/src/variants.rs, variants/commands.rs, variants/schema.rs · material variants and model sets +- refers-to: src/variants.rs :: Variants, VariantSet, Variant, PartMaterial, ModelSet, VariantChoice, Variants::choice, Variants::uses_material, Variants::materials, covered_parts, part_skip, variant_diff, variant_matches, model_set_matches, choice_problems, apply_variant, apply_model_set, apply_choice; src/variants/commands.rs :: default_model_nodes; src/command.rs :: commands! (16 variant.* and model_set.* rows) +- kind: decision +- logged: v0.9.0 · 2026-12-03 +`DocumentData.variants` holds `sets` (id, name, covered `parts`, `variants`, `active`), `model_sets` (id, name, `nodes`) and `active_model_set`, every field skipped when empty so a document without variants has no `variants` key and re-saves byte for byte. A variant stores one `PartMaterial` per covered part, sorted by part id, with null meaning the default material; a group listed as a covered part is expanded to its descendant parts when a variant is captured or given materials, resolve stores the expanded list so redo and journal replay repeat exactly, and the set keeps the list the user typed. Ids are `set`, `variant` (unique within the set) and `model`, lowest free number, made in resolve when not given; numeric ids are accepted and stored as strings. The 16 document commands are variant.add_set, set_set, remove_set, capture, add, set, remove, move, select, apply_choice and model_set.add, set, remove, move, select; they do not merge. `variant.select` answers Region (the level of `material.assign`), `model_set.select` and `variant.apply_choice` answer Full, bookkeeping edits answer None, and marking the active variant happens in the same transaction. `variant.capture` records what every covered part wears and makes the new variant active; `variant.add` accepts one material key, an object of part-or-group id to key, or the stored list, and refuses uncovered parts and missing materials at command time; `variant.set_set` with parts drops entries of parts no longer covered (one undo step restores them); `variant.move` without `id` moves the set. `model_set.add` without nodes takes the visible roots, or the visible part and group children of a group root, and never lights, cutaways or hidden nodes; `model_set.select` shows the listed nodes and hides only nodes that other sets list alone (a node in both stays shown). `apply_choice` applies sets in document order (a later set wins a shared part) and then the model set, and never errors for stale ids: it skips parts that are gone or no longer parts, locked parts, and materials that no longer exist, while visibility of locked nodes does change, as `scene.set_visible` does; `choice_problems` and `variant_diff` report the same skips as sentences with reasons. Nothing prunes unused materials (save writes every material), so a material that only a variant uses stays in the file; `material.remove` is unchanged, so removing one leaves the key in the variant, which then skips it and marks it `missing_material`, and undo restores it (`uses_material` is there for a later refusal). Verified by a release CLI session of 58 commands: renders of a body in white, red and graphite looked at, undo and redo between variants, `variant.apply_choice` with a model set undone in one step, a removed material skipped without a panic, save and reopen with identical listings and a byte-identical re-save, and a variant-free document byte-identical with no `variants` key; clippy and the wasm32 check clean. Not run: a pixel comparison against the base binary (nothing in flatten, the snapshot or either tracer changed). + +### crates/fsh-scene/src/configurator.rs, configurator/solve.rs, commands.rs, check.rs, bridge.rs · the configurator: options, choices, rules and the search +- refers-to: src/configurator.rs :: Configurator, ConfigOption, Choice, Action, Rule, RuleKind; src/configurator/solve.rs :: Space, Listing, SEARCH_BUDGET, Space::enumerate, Space::first, Space::reachable, Space::name, Space::selection; src/configurator/commands.rs :: run_actions; src/configurator/check.rs :: problems, Problem; src/configurator/bridge.rs :: apply_variant, apply_model_set, apply_shot, has_variant, has_model_set, has_shot, active_variant_names +- kind: decision +- logged: v0.9.0 · 2026-12-03 +`DocumentData.configurator` is `{options, rules}`, left out of the file when empty. An option (`ConfigOption`, renamed from the plan's `Option` so it never hides `std::option::Option`) has an id, name, `choices`, `selected` and `default`; a choice has an id, name and `actions`, each action tagged by `kind`: `variant {set, variant}`, `model_set {model_set}`, `shot {shot}`, `show {nodes}`, `hide {nodes}` and `material {material|null, nodes}`; node and material keys accept numbers or decimal strings. A rule is a one-directional implication on (option, choice) with a `target` option and a choice list: `requires` holds when the target's choice is in the list, `excludes` when it is not, and a configuration is valid when every rule holds. Rules that name missing items, or tie an option to itself, are ignored by the search and reported by `config.check`. The solver (`Space`) turns options into positions and rules into constraints checked at the later of their two positions, and searches depth first with pruning, within a shared budget of 4,000,000 tried choices (`SEARCH_BUDGET`). `config.select {option, choice}` pins that choice, keeps every other option's current choice where it can, and moves forbidden ones to their first allowed choice (options earlier in the list keep theirs first); it runs the actions of the chosen choice and then of each moved option, as one undo step with the configurator block and the node and material changes in one `Tx`, and fails without changing anything when no valid configuration has that choice. `config.apply {selection}` pins every listed option, resolves the rest the same way, sets `selected` on all and runs every option's actions in option order, so a later option wins a shared part; `config.render_all` builds each copy with it. Variant, model set and shot actions go through `bridge.rs`: the lead connected it to `variants::apply_variant`, `variants::apply_model_set` and `shots::apply_shot`, so they run inside the configurator's transaction (before the connection the `has_*` answers were `None`, `config.check` said `action_unavailable` and select refused), and `active_variant_names` lists each set's active variant for the `{variant}` token. Show, hide and material actions deliberately ignore node locks, like `scene.set_visible`. Ids (`option`, `choice` per option, `rule`, lowest free number) are made in resolve and `config.set_option` and `set_choice` resolve to full values, so redo and journal replay repeat exactly; removing an option removes the rules naming it, removing a choice drops it from rule target lists and removes rules left empty, and an option without choices is skipped by the search (`option_empty`). `config.check` returns codes such as `duplicate_id`, `action_missing`, `never_chosen` and `not_checked`; `reachable` runs one search first and shares the budget, which cut a 11 option by 5 choice check with a late contradiction from 4.67 s to 0.09 s. Verified by dispatch on a dev build: a colour and parts example whose `config.list` total of 8 matched 3 x 3 - 1 by hand, selects that moved other options, refusals naming the rule, 9 undos back to the saved block, a byte-identical re-save with and without a configurator, crash-journal replay giving the identical block and scene, and clippy and the wasm32 check clean. Documents without a configurator are unchanged on disk. + +### crates/fsh-scene/src/measure.rs, measure/eval.rs, measure/commands.rs, measure/schema.rs · measurements +- refers-to: src/measure.rs :: Measurements, Measurement, MeasureKind, Anchor, LabelOptions, DistanceAxis, SizeFrame; src/measure/eval.rs :: evaluate, Evaluation, format_length, format_angle, project; src/measure/commands.rs :: MAKES; src/command.rs :: commands! (six measure.* rows, change level None), Command::answer +- kind: decision +- logged: v0.9.0 · 2026-12-03 +`DocumentData.measurements` is `{list, precision}`: `precision` is the document's digits after the decimal point (default 1, left out when 1) and each `Measurement` has an id, name, `visible`, `label` (`LabelOptions {precision?, show_name, hidden}`) and a `kind` tagged by `kind`: `Distance {a, b, axis}`, `Size {nodes, frame}` or `Angle {vertex, a, b}`. An `Anchor {node?, point}` is either pinned in a node's space, so it turns and moves with the node, or free in world space; node ids read from integers or decimal strings, and the block is validated on load (`try_from`). The block is left out of the file when empty, so old documents re-save byte for byte (checked on the templates, product-white and turntable projects, also after adding and undoing a measurement). `evaluate` returns the drawn points and axes, the value, its text and the ids of parts that are gone; a measurement whose part was removed reads `ok: false` with `missing` and a null value, never a panic, and undo brings it back. Size boxes measure vertices, or the eight corners of a part's own box when it is aligned with the measuring axes (exact and cheap); hidden parts under the listed nodes are left out unless all are hidden; the `local` frame is the first node's world rotation with scale removed. `project` is the exact inverse of fsh-commands' `view::camera_ray` for pinhole, shifted and orthographic cameras; fisheye, equirectangular and cylindrical cameras are not drawn. Ids are `distance`, `size`, `angle`, answered in the reply through `Command::answer` (`MAKES` names the three add commands), and world points on nodes are converted to node space in resolve (`space` becomes `local`) so redo and journal replay repeat exactly. The six commands (`measure.add_distance`, `add_size`, `add_angle`, `set`, `remove`, `clear`) all have change level None, because a measurement never changes the picture, so no render restarts; `measure.set` without an `id` sets the document precision (there is no seventh command) and resolves to the full new measurement for history; `measure.clear {keep_precision}` is one undo step. Undo goes through `UndoOp::Measurements` under flag 8192 (some notes say 4096, which is the animation block's). Verified on a release CLI: a pinned distance of 353.6 mm between two cubes (353.553 expected) that followed a move and a turn, a group size of 850.0 by 200.0 by 200.0 mm, a turned cube measured in world axes 141.4 by 100.0 by 141.4 and in its own axes 100.0 cubed, an angle of 15.9 degrees (atan(0.2/0.7)), undo and redo of every command, refusals for a wrong field or a duplicate or unknown node, and save and reopen with the same values; clippy and the wasm32 check clean. Not done: edge snapping, and labels may still overlap lines of other measurements in renders. + +### crates/fsh-scene/src/document.rs, tx.rs · the five document blocks and their undo flags +- refers-to: src/document.rs :: DocumentData (shots, variants, configurator, measurements, animation); src/tx.rs :: UndoOp (Rigs, Configurator, Shots, Variants, Animation, Measurements), F_CONFIGURATOR, F_RIGS, F_SHOTS, F_VARIANTS, F_ANIMATION, F_MEASUREMENTS, Tx::configurator_mut, rigs_mut, shots_mut, variants_mut, animation_mut, measurements_mut +- kind: decision +- logged: v0.9.0 · 2026-12-03 +`DocumentData` carries five blocks for this release, each `skip_serializing_if` its own `is_empty`, so a document that never used them has no `shots`, `variants`, `configurator`, `measurements` or `animation` key and loads and re-saves byte for byte as before; the places for them were reserved in an earlier seam commit, and each module only filled its block, so nothing else in `document.rs` changed. Every block follows the same undo pattern in `tx.rs`: an `UndoOp` variant holding the whole block (the two small ones, shots and variants, hold it by value; configurator, animation and measurements are boxed), a restore arm in `Document::restore`, a flag bit, and a `*_mut` accessor on `Tx` that pushes a snapshot of the block once per step (when the flag is not yet set) and then lends the block for editing. The flags are the next free bits after the base's 128: `F_CONFIGURATOR` 256, `F_RIGS` 512, `F_SHOTS` 1024, `F_VARIANTS` 2048, `F_ANIMATION` 4096 and `F_MEASUREMENTS` 8192. They were first assigned from separate branches (the measurements block and the animation block both took 4096, and some part notes still say so); the integration moved measurements to 8192, and the code is the authority. Rigs have their own op, `UndoOp::Rigs`, that records only the rig list, while `animation_mut` snapshots the whole `Animation` including the rigs; ops restore in reverse order, so a step that touches both returns to the right state either way. A step that edits two blocks (a configurator selection that also changes visibility, a shot that applies variants) records each block once with the node and material ops in the one `Tx`, which is what makes those commands single undo steps. Loading does not validate the animation, rigs or measurements (a tolerant `from_data`): evaluation tolerates unsorted keys and bad frame rates, a rig on a removed node does nothing, and `anim.status` reports `valid: false`. `scene.remove` and `camera.remove` do not prune rigs that name the removed node or camera, so a rig left behind does nothing and a removed camera index can shift onto another camera. Verified through the commands of each block (undo and redo, the crash-journal replay of shots and the configurator, byte-identical re-saves); clippy and the wasm32 check were clean. + +### crates/fsh-scene/src/command.rs · Command::answer: string ids of created items +- refers-to: src/command.rs :: Command::answer; src/shots/commands.rs :: answer; crates/fsh-commands/src/engine.rs :: Engine::dispatch_value (the reply merge) +- kind: decision +- logged: v0.9.0 · 2026-12-03 +Scene commands reply with `created: Vec`, which cannot carry the string ids of shots, variant sets, variants, model sets, configurator items, rigs or measurements. `Command::answer` returns the extra reply fields instead: `shot.add` and `shot.duplicate` answer `{shot}`, `shot.apply` answers `{shot, skipped}` (computed in `shots::commands::answer`), and `variant.add_set`, `variant.add`, `variant.capture`, `model_set.add`, `config.add_option`, `config.add_choice`, `config.add_rule`, `anim.add_rig`, `anim.turntable`, `anim.orbit`, `anim.camera_path` and the three `measure.add_*` commands answer `{id}`. The id is read from the resolved command (`args.id`, or `args.rig.id`, or `args.plan.rig.id` for the rig helpers), which is why it must be resolved before history; only string ids are answered. `Engine::dispatch_value` merges the object into the reply with `entry(k).or_insert(v)`, so an answer never overwrites a field the engine already set. The commands that answer are listed by name in one `matches!`, so a new command that makes a string id has to be added there. The window's shots page used the reply's `id` and diffed the list before and after only against older engines. The integration notes name two lead check scripts (integ.py and integ2.py) for this change but not their results, so treat the per-command replies as not independently confirmed here; until the change the ids were only predictable (lowest free number) or readable from the lists. + +### crates/fsh-scene/src/animation/mod.rs, target.rs, curve.rs, commands.rs, schema.rs · the animation block: timeline, tracks, keys and interpolation +- refers-to: src/animation/mod.rs :: Animation, Track, Key, KeyValue, Interpolation, evaluate, frame_times, track_value, sample_target, DEFAULT_FPS, DEFAULT_END, MAX_FPS, MAX_FRAMES, Animation::{moves, rate, frame_count, frame_time, validate_timeline}; src/animation/target.rs :: Target, TransformField, CameraField, LightField, ValueKind, material_params, look_rotation; src/animation/curve.rs :: sample; src/animation/commands.rs :: key_merge; src/animation/schema.rs :: target_schema; src/command.rs :: commands! (seven anim.* rows) +- kind: decision +- logged: v0.9.0 · 2026-12-03 +`DocumentData.animation` is `{fps, start, end, tracks, rigs}` with the defaults 30 fps, 0 to 5 seconds and nothing keyed, and the whole block is left out of the file while it equals `Animation::default()`. Frames run from `start` to `end` with both ends included (`frame_count` allows 1e-3 of a frame, capped at `MAX_FRAMES` 100,000, and `fps` is capped at `MAX_FPS` 240), `frame_time(f)` is `start + f / rate`, and `frame_times` lists them; an unusable stored rate reads as the default instead of failing. A track keys one `Target`, tagged by `kind`: `transform` (translation, rotation or scale of a node), `camera` (position, target, orientation, focal length, fov, focus distance, aperture), `material` (any numeric or colour `SurfaceParams` field, found through serde in `material_params`, so fields added later by media or edges become keyable without a change here), `light` (power, colour, temperature, spread, visible) and `visibility`. There is one track per target, keys sorted by time, no two keys of a track within 0.1 ms, and a key's interpolation governs the piece after it; values are `KeyValue`, a number or an array in JSON. Interpolation is `step`, `linear`, `smooth` (the default) or `ease`: smooth is a cubic Hermite with Fritsch-Butland tangents (a weighted harmonic mean, zero at extremes and at the first and last key), so it never overshoots and evaluated values stay valid; rotations slerp, and smooth rotations put the same monotone cubic over the cumulative angle; visibility and a light's `visible` are always stepped. `evaluate(doc, t)` clones `DocumentData` (meshes are `Arc`, so it copies the node, material and camera tables), writes each track's value, then applies the rigs, and returns `doc.clone()` when there are no tracks or rigs. The seven commands are `anim.set` (timeline), `key`, `set_key`, `remove_key`, `move_key`, `remove_track` and `clear` (all Full; `clear` with `all` also removes rigs and resets the timeline); ids are `track` and `key`. `anim.key` without a value keys the target's value in the document evaluated at that time (rigs included), and a key at the same time is replaced and keeps its interpolation; keys are addressed by id or by `at` (the nearest key within half a frame), and resolve clears `target` and `at` and fills the ids so journal and redo are exact. Light colour keys write `Rgb` (Kelvin colours are read as `Rgb::from_kelvin`) and temperature keys write Kelvin; camera `orientation` keeps the target distance and sets `up`; `fov` is the horizontal angle through the sensor width. `anim.set`, `key`, `set_key` and `move_key` merge continuous edits (a key drag is one undo step, merge keyed by track and key). Loading does not validate the block: evaluation tolerates unsorted keys and bad rates, and tracks on removed objects do nothing. Verified by hand arithmetic through dispatch: smooth keys -0.75, 0 and 0.75 at 0, 1 and 2 s gave -0.46875 at 0.5 s, a linear 90 degree turn about Y gave the 45 degree quaternion at 1 s, a smooth turn 0, 90, 180 gave 33.75 degrees at 0.5 s, a focal ease from 45 to 90 mm gave 52.03125 at 0.5 s and 67.5 at 1 s, and a smooth light power was monotone over 49 frames with a maximum of 1100; renders at three seek times looked right; the saved and reopened document re-saved byte for byte, and a base-saved project, `file.new` and renders of three sample scenes (also after `anim.seek`) were byte-identical to the base. `euler_deg` keeps Y within -90 to 90, so a turn past 90 degrees about Y reads as an equal rotation with different angles (a timeline that draws it should plot the quaternion or unwrap it). + +### crates/fsh-scene/src/animation/rigs.rs, rigs/ · rigs: turntables, orbits and camera paths +- refers-to: src/animation/rigs.rs :: Rig, apply; src/animation/rigs/timing.rs :: Direction, progress; src/animation/rigs/turntable.rs :: Turntable; src/animation/rigs/orbit.rs :: Orbit; src/animation/rigs/path.rs :: CameraPath, LookAt; src/animation/rigs/spline.rs :: ArcSpline; src/animation/rigs/range.rs :: Range, current, set, DEFAULT_FPS, DEFAULT_START, DEFAULT_END; src/animation/rigs/commands.rs :: merge_target; src/animation/rigs/scene.rs :: view; src/command.rs :: commands! (six rig rows) +- kind: decision +- logged: v0.9.0 · 2026-12-03 +A rig makes motion from a few settings instead of keys and lives in `Animation.rigs`: a `Rig` is tagged by `kind` as `turntable`, `orbit` or `camera_path`, with an id (`turntable`, `orbit`, `path`, lowest free number, or an explicit one of 1 to 64 characters of letters, digits, `_` and `-`), a name, `start` and `end` seconds and `ease_in` and `ease_out` fractions. `timing::progress` is a trapezoid speed profile: constant acceleration over the ease fractions and constant speed between, linear when both are 0 (the default); before its start a rig holds its first position and after its end its last. `rigs::apply(rigs, data, time)` runs after the tracks: every rig's centres are read first from the data as given, then turntables in list order, then orbits and camera paths in list order, and a rig that names a missing node or camera does nothing. The turntable turns one node, or every root that holds a visible product part, so studio light groups never turn, about the world +Y axis through the centre of its bounds (the product bounds come from `lighting::studio::{product_parts, parts_bounds}`, the same meaning of "product" as studio presets), independent of the pivot; the centre is stored in the node's parent frame and the axis mapped through the current parent world, so a turntable on a child of a turned parent follows it, and at angle 0 the node is not written at all, so it is bitwise unchanged. Settings are `node`, `turns` (default 1), `direction` (`ccw` seen from above, or `cw`) and `start_angle` in degrees. The orbit keeps the camera's horizontal radius and height relative to the product centre, looks at the centre and makes up +Y (a ccw camera travel looks like the opposite spin to a ccw turntable); the camera path is a centripetal Catmull-Rom spline (alpha 0.5, Barry-Goldman form in f64, 128 chords per segment for the arc-length table, the point inside a chord found by 24 bisection steps, mirrored phantom end points when open, wrapping when closed, repeated points dropped) travelled at constant arc speed between the ramps, looking at `look_at` (`{point}` or `{node}`, the node's centre stored in its local frame so it follows turntables) or at the product centre, with `roll` banking right for positive degrees; both camera rigs go through `Camera::kept_focus`, so a keep-focus camera's focus distance follows the target distance. The bisection matters: before it the path speed varied 1.6 percent. The commands are `anim.add_rig`, `anim.set_rig` (a shallow replace of the given fields, null clears `node` or `look_at`, kind and id cannot change, edits merge by an FNV-1a hash of the id), `anim.remove_rig` and the helpers `anim.turntable`, `anim.orbit` and `anim.camera_path`, which resolve into a stored `plan {rig, range}` so redo and journal replay repeat the exact rig and range. Default times run over the animation's range plus one frame for motion that cycles (turntable, orbit, closed path), so a loop never repeats its first frame, and an open path ends exactly on the last frame; `anim.turntable {frames}` sets the range to `start .. start + (frames - 1) / fps` and the turn to `start .. start + frames / fps` (`seconds` is rounded to frames), so 36 frames turn 10 degrees per frame and frame 36 would be frame 0. `rigs/range.rs` first answered a stub 30 fps and 0 to 4 seconds; the lead connected it to the animation's fps, start and end, written through `Tx::animation_mut` (the 30 and 4 remain only as the named defaults). Verified by a scratch program: a 36-frame turntable of a cube with a far pivot, a sphere and a tilted scaled cylinder stepped 10 degrees within 3.4e-5 degrees per frame, frame 0 bitwise equal to rest and frame 36 back within 1.5e-7 m; an orbit kept its distance to 6 digits; a path over 4000 steps ran within 99.985 to 100.034 percent of mean speed open and 99.988 to 100.029 closed; commands, 12 refusals, JSON round trips, and pictures of frames 0, 9 and 18 looked at. Not run: a byte comparison of renders against a base build (no renderer or format code changed) and any GPU run. Not done: pruning rigs when their node or camera is removed. + +### crates/fsh-scene/src/editor.rs · the editor's time and the snapshot at that time +- refers-to: src/editor.rs :: Editor::set_time, Editor::time, Editor::evaluated, Editor::snapshot; src/animation/mod.rs :: evaluate; src/motion.rs :: flatten_frame +- kind: decision +- logged: v0.9.0 · 2026-12-03 +`Editor` gets a `time: Option` that is never stored in the document, history or file: `None` shows the stored values, `Some(t)` shows the animation at `t` seconds (`set_time` drops a non-finite value). `Editor::snapshot` used to be `flatten(&doc)`; it now answers `flatten_frame(&|s| animation::evaluate(doc, s), t, rate, &motion_blur)` when a time is set and the animation moves (`Animation::moves`, some track or rig exists), and `flatten(doc)` otherwise, so a document without animation, or with no time set, takes the old path and renders as before. The lead wired motion blur here rather than the motion agent, because `flatten_frame` needs the animation's `evaluate`: with blur off, a closed shutter or a rate that is not positive it is `flatten(&at(t))`, one evaluation, and with blur on it evaluates 1 plus the key count times (10 with the default 9 keys). `Editor::evaluated` returns the document as the snapshot shows it (a `Cow`, borrowed when nothing is evaluated), which is what the sequence renderer and the window's reads at a time use. Because the stored document is untouched, undo, save and the crash journal ignore the time, and a window that follows the timeline has to set it again on its own engine instance (the in-window WebAssembly session copies the service's time in `Session::snapshot`). Not verified here: the GPU path at a time (the snapshot goes through the same refresh path as any document change, and a moving scene with blur is refused by the GPU, see fsh-render-gpu). + +### crates/fsh-scene/src/motion.rs, snapshot.rs · motion blur settings, motion keys and flatten_frame +- refers-to: src/motion.rs :: MotionBlur, ShutterPosition, MotionBlur::interval, CameraKey, CameraMotion, RenderSnapshot::has_motion, flatten_motion, flatten_frame, auto_steps, DEFAULT_MOTION_STEPS, MOTION_STEPS_AUTO, MAX_MOTION_KEYS; src/snapshot.rs :: Instance::motion, RenderCamera::motion +- kind: decision +- logged: v0.9.0 · 2026-12-03 +`RenderSettings.motion_blur` is `{enabled: false, shutter: 0.5, position: centred}`, each field left out of the JSON when default and the block when all are, so old documents re-save byte for byte (checked; `{"enabled": true}` is all that is written when only that is set, and `shutter: 1.5` is refused as outside 0..1). `shutter` is a fraction of a frame (0.5 is a 180 degree shutter) and `MotionBlur::interval(time, fps)` gives the open and close times: centred `[t - s/2f, t + s/2f]`, opening `[t, t + s/f]`, closing `[t - s/f, t]`, and None when blur is off, the shutter is 0 or fps is not positive (24 fps, 1 s, centred 0.5 gives 0.98958 to 1.01042). `flatten_motion(at, open, close, steps)` takes the snapshot at the shutter's middle, flattens the document again at `steps` times evenly spaced over the shutter (at most `MAX_MOTION_KEYS` 16, default `DEFAULT_MOTION_STEPS` 9, odd so the middle key is the shutter's middle), matches instances by part node id, and gives any instance whose world transform differs at some time all its keys as `Instance::motion`; the camera's eye and orientation are keyed the same way in a fixed array of 16 (`CameraMotion`), so `RenderCamera` stays `Copy` (fsh-wasm, fsh-commands and fsh-render-gpu copy it by value); a camera key list longer than 16 is resampled evenly over the whole shutter (a first version kept only the first 16 keys and so cut the shutter short). `MOTION_STEPS_AUTO` (0) picks the count from three probes at opening, middle and closing: one key per `AUTO_TURN_PER_KEY` of the largest turn of any part or the camera, odd, at least 3 and at most 15, and 0 when nothing moves; a part that spins a whole turn within the shutter looks still at three probes, so such shots need a fixed count. Lights, the environment, the ground, materials and visibility are taken at the shutter's middle; a part that appears or vanishes within the shutter keeps the middle snapshot's place, still; only the camera's eye and orientation blur, so a zoom or focus pull takes its middle value; light from a moving emissive part is sampled at its middle place, so a fast emitter is slightly biased in next-event estimation while the visible part blurs. `flatten_frame(at, time, fps, blur)` is `flatten(&at(time))` when blur is off, and `flatten_motion` over the interval when on (1 plus steps evaluations, three more for auto); `Editor::snapshot` and the frame renderer call it. Verified by scratch programs: a cube moved 0.69 m and turned 69 degrees through `flatten_motion` over a blending closure rendered at 480 by 320 and 128 samples (the cube streaks along its path, its shadow and reflection smear, everything else sharp, looked at, also at the final commit), a 0.5 m camera pan streaked the whole picture, and `flatten_motion` over identical documents equalled `flatten` and rendered identical pixels; clippy and the wasm32 check clean. Not verified: moving emissive parts, and motion with a render region, passes or adaptive sampling (they take the same per-path time, but no picture was looked at). + +### crates/fsh-scene/src/material.rs, types.rs · transmission scatter, medium priority and the translucent and volume types +- refers-to: src/material.rs :: SurfaceParams (transmission_scatter, transmission_scatter_anisotropy, subsurface_scatter_anisotropy, medium_priority), MAX_MEDIUM_PRIORITY; src/types.rs :: SCATTER, SCATTER_ANISO, SSS_SCALE, SSS_ANISO, PRIORITY, VOLUME_DEPTH, the translucent and volume types +- kind: decision +- logged: v0.10.0 · 2026-12-03 +Four fields join `SurfaceParams`: `transmission_scatter` (Rgb, default black, 0..1000 per channel; the scatter coefficient in multiples of 1/depth), `transmission_scatter_anisotropy` and `subsurface_scatter_anisotropy` (-1..1, default 0, the Henyey-Greenstein g) and `medium_priority` (u32, 0..1000, default 0 meaning the part never nests). Each is `skip_serializing_if` its default, so every document and library preset written before re-saves byte for byte and a new document that never uses them has no trace of them. The existing `transmission_depth` and `subsurface_*` fields keep their meaning, but their effect now follows OpenPBR: a depth above 0 removes the surface tint and absorbs along the path inside a closed solid (depth 0 is still the old single tint), and a subsurface weight above 0 now scatters light inside the part instead of only mixing diffuse. types.rs shows the new rows (scatter colour with a 0..10 slider, the two anisotropies, the radius scale that was hidden, the depth for the volume type, and the priority as a float row clamped to an integer) on the Generic page and `medium_priority` on the glass, thin glass and liquid pages, and appends two types to the catalogue: `translucent` (Generic; subsurface weight 1, colour and base (0.85, 0.80, 0.70) in sRGB, radius 5 mm, roughness 0.35, ior 1.45, a warm wax) and `volume` (Generic; transmission 1, ior 1.0, roughness 0, depth 1 m, scatter 0.5 grey, base white, a box of fog or smoke whose surface bends nothing). Existing types keep their parameter lists. Decision worth knowing: 44 library presets carry a transmission depth (16 gems, 9 glasses, 13 liquids, acrylic and PET, whose LIBRARY.md colour is the Beer-Lambert transmittance at that depth) and 10 a subsurface weight (milk, orange juice, opal glass, glazed porcelain, HDPE, polypropylene, two silicones, two marbles); they now render with absorption and subsurface as their parameters describe, which is a deliberate change to those presets and the only place where "existing presets render as before" gives way to the transport rule. Every other preset and type renders exactly as before. The new fields were first invisible to the `material.set_params` schema (it was inferred from the serialised defaults); see the schema entry under engine gaps below. + +### crates/fsh-scene/src/transport/mod.rs, transport/spectral.rs, settings.rs · the transport settings block +- refers-to: src/transport/mod.rs :: Transport; src/transport/spectral.rs :: Spectral; src/transport/caustics.rs :: Caustics, CausticsMode; src/settings.rs :: RenderSettings::transport +- kind: decision +- logged: v0.10.0 · 2026-12-03 +`RenderSettings.transport` is the one home of the light transport options that are not material parameters: `spectral { enabled }` (default off) and `caustics { mode, photons, radius, shrink }` (see the caustics entry). The block and each field are `skip_serializing_if` default, so a document that never touches them has no `transport` key and re-saves byte for byte, and one that turns photons on saves only `"transport": {"caustics": {"mode": "photons"}}`; `validate` runs from `RenderSettings::validate` so `render.set_settings` refuses out-of-range values with `invalid_value`. It is set with `render.set_settings {values: {transport: {spectral: {enabled: true}}}}` (a deep merge). A change to `transport` is a Full change (a different integrator), while a `motion_blur` edit is Full only when the document is animated; both rules are in `command.rs` (engine gaps). The switch is read by the CPU (`SpectralScene`, the photon passes), by `Refusals::check` and the kernel features on the GPU, by `transport.features`, and by the window's self-check class. Not done: no per-light or per-material switch, so spectral mode and photons apply to the whole render. + +### crates/fsh-scene/src/node.rs, snapshot.rs, cutaway.rs, command.rs, catalogue.rs · cutaway invert, cutaway.set_enabled and cutaway.set_targets +- refers-to: src/node.rs :: Cutaway::invert; src/snapshot.rs :: RenderCutaway::invert, RenderCutaway::cuts; src/cutaway.rs :: CutawaySetEnabled, CutawaySetTargets, cutaway_level; src/command.rs :: SetCutaway apply arm +- kind: decision +- logged: v0.10.0 · 2026-12-03 +The document already held cutaway nodes (`Cutaway`: shape plane, box, sphere or cylinder, cap mode none, part material or colour, enabled, targets) and the snapshot already carried `RenderCutaway` with its instance list, but neither tracer read them. This release adds `Cutaway.invert` (default false, left out of the JSON when false, so old documents re-save byte for byte): a plane removes local +Z and, inverted, local -Z, and a box, sphere or cylinder (along local Y) removes its inside and, inverted, its outside, which keeps only what lies within the shape. `RenderCutaway::cuts(instance)` answers whether a cutaway cuts an instance, where an empty target list means every part (the document's existing rule); the snapshot drops disabled cutaways, hidden ones and those whose explicit targets reach no visible part. Two commands join `scene.add_cutaway` and `scene.set_cutaway`: `cutaway.set_enabled` (turn several on or off) and `cutaway.set_targets` (set, add, remove or clear, reusing lighting's `LinkOp`), both reporting a change level through `cutaway_level` (none when nothing changed or the cutaway is hidden or off before and after, else full) so an edit that changes nothing does not restart the render; naming a node that is not a cutaway answers `wrong_kind`, and undo restores. `scene.set_cutaway` answers the same level instead of always Full. A cutaway change makes the CPU's `same_layout` fail so the cut is rebuilt, and the film resets on any cutaway change. Cleaning cutaway targets when a node is removed or duplicated came later, in the engine gaps entry on hooks. Not done: lamps are never cut and emissive triangles inside a removed volume still light the scene through next event estimation. + +### crates/fsh-scene/src/material.rs, types.rs · edge_radius and edge_other_parts +- refers-to: src/material.rs :: SurfaceParams (edge_radius, edge_other_parts); src/types.rs :: ROUND, ROUND_OTHERS +- kind: decision +- logged: v0.10.0 · 2026-12-03 +`edge_radius` (f32 in metres, 0 is off, validated 0..1) and `edge_other_parts` (bool, default false) join `SurfaceParams`, each left out of the JSON at its default, so documents and library presets written before re-save byte for byte. types.rs adds `ROUND` (unit m, slider to 1 cm so the window shows a length) and `ROUND_OTHERS` to the Generic, plastic, clear plastic, metal, brushed metal, paint, metallic paint, glass, thin glass, liquid, gem, rubber, ceramic, diffuse, wood and stone pages and not to fabric or emissive; presets keep radius 0. The radius is a material parameter, so every part that wears the material rounds alike and `material.set_params` sets it with no new command; the window shows it in millimetres (0 to 10). In the struct the order is media's fields, then these two, then the fibre block. Same schema gap as the media fields until the engine gaps pass generated schemas from the types. + +### crates/fsh-scene/src/fibres.rs, material.rs, snapshot.rs, types.rs · fibre settings and deterministic growth +- refers-to: src/fibres.rs :: FibreCurves, FibreRoot, RenderFibres, FibreTotals, totals, has_fibres, requested_count, segments_for, grow, grow_cached, MAX_SEGMENTS, DEFAULT_LENGTH; src/material.rs :: SurfaceParams (fibre_*); src/snapshot.rs :: RenderSnapshot::fibres; src/types.rs :: FIBRE_* +- kind: decision +- logged: v0.10.0 · 2026-12-03 +Velvet, felt, peach-skin plastics, carpet and fur trims grow real fibres: 14 flat `fibre_*` fields at the end of `SurfaceParams`, each left out of the JSON at its default so old documents re-save byte for byte. They are flat so `material.set_params` sets them with no new command and the pages show them as ordinary rows. `fibre_density` (per cm2 of the part's world surface, 0..100000, default 0 which grows nothing), `fibre_length` (m, default 0.004), `fibre_root_width` and `fibre_tip_width` (diameter in m, 1e-4 and 4e-5, 0..0.01), `fibre_comb` (0 to 1, lean toward the comb direction, 0 along the normal, 1 about 80 degrees), `fibre_comb_direction` (world, default [0, -1, 0]), `fibre_randomness` (0.15; spread of direction and up to 50 percent shorter), `fibre_curl` (helix about the growth direction), `fibre_clumping` (tips toward a clump leader), `fibre_own_color` and `fibre_color` (0.8 grey), `fibre_roughness` (beta_m 0.3), `fibre_radial_roughness` (beta_n 0.6) and `fibre_seed` (u32). The Generic and Fabric pages show all but the comb direction and the seed (they need a vector and an integer editor). `flatten()` grows the fibres into `RenderSnapshot.fibres`, so the same inputs give the same fibres on every platform: the count is density x 1e4 x the part's world area; roots are stratified over the area CDF with uniform barycentrics and a Pcg32 seeded by (`fibre_seed`, fibre index); each fibre has 3 + ceil(6 curl) segments, direction starting at the jittered normal (the interpolated vertex normal when the mesh has normals) and bending toward the comb; every 24th fibre leads a clump found through a grid of side sqrt(area / leaders), and points move toward the leader's polyline by clumping x t. Lengths and widths are world metres, divided by the transform's mean axis scale into local space, and fibres are stored in local space and placed by the instance, so moving a part reuses its curves (the comb direction goes through the inverse transform, so rotation and scale enter the cache key only when combed). `grow_cached` keeps the last 8 results keyed by mesh identity, settings, scale and count (0.21 s first, 0.009 s cached). The cap is `MAX_SEGMENTS` 2,000,000 per snapshot: past it every instance is thinned by the same factor so density stays even and `RenderFibres::requested` keeps what was asked. Memory measured on a 964,614-segment ball: snapshot curves 20 MB per million segments plus 61 MB of CPU curve BVH, so the cap bounds a snapshot near 165 MB. `has_fibres` (density above 0, length above 0, a width above 0) decides whether a part grows any and is what `transport.features` reads; `totals` gives the counts but nothing reports them to the user yet. Not done: the schema listed none of these fields until the engine gaps pass, and the window needed labels. + +### crates/fsh-scene/src/catalogue.rs, catalogue/fields.rs · schemas that list every field +- refers-to: src/catalogue.rs :: render_settings_schema, the material.set_params and material.create params, the shots render block; src/catalogue/fields.rs :: full +- kind: decision +- logged: v0.10.0 · 2026-12-03 +Until this release `block::()` inferred a command's argument schema from `T::default()` serialised, which leaves out every `skip_serializing_if` field at its default, so agents (and the MCP clients that read the catalogue) could not see `edge_radius`, the `fibre_*` fields, `medium_priority`, the scatter fields, `transport` or a cutaway's `invert`, although the commands accepted them. `fields::full::()` reads field names and kinds from `T`'s `Deserialize` through a probe deserializer that records each field's shape (bool, integer, number, string, enum variants, fixed or open arrays, nested structs, options); the default comes from the default JSON, and for a field the JSON leaves out the generator tries candidates (false, true, 0, a zero array, null, each enum variant) and keeps the one that is left out again on a round trip. A new field therefore appears in the schema with no edit (`transport.caustics` showed as an empty object at first, then with its fields). It is used by `material.set_params`, `material.create` params, `render.set_settings` and the shots' render block (one word in the shots region); other `block::()` users are unchanged. Verified: `material.set_params` lists 53 fields (media, edges and fibres with kinds and defaults) and `render.set_settings` lists `motion_blur` (enabled, shutter 0..1 default 0.5, position enum) and `transport` (spectral, caustics). Limits: ranges are not generated (validation code owns them), and defaults of numbers left out at a non-zero default (`fibre_length`, the shutter) cannot be found by the trial and are omitted, except the shutter, filled from `MotionBlur::default()`. Agents' generated references (`agents/manifest.json`, the skills' tools.md) need `./formshot agents sync` after this change. + +### crates/fsh-scene/src/command.rs, command/hooks.rs · references kept consistent when nodes, cameras and materials go +- refers-to: src/command/hooks.rs :: subtrees, forget_nodes, copy_references, renumber_cameras, material_user; src/command.rs :: scene.remove, scene.duplicate, camera.add, camera.duplicate, camera.remove, material.remove, render.set_settings, scene.set_light, scene.set_cutaway, material.set_params; src/animation/rigs.rs :: node_centre +- kind: decision +- logged: v0.10.0 · 2026-12-03 +Several blocks hold ids of nodes, cameras and materials, and 0.9.0 left them dangling when the thing they named went away. Now `scene.remove` (one undo step, each block recorded only when it names a removed node, descendants of a group included) drops removed nodes from cutaway targets and switches off a cutaway left with no target (an empty list would mean "every part"), from variant sets, variant entries and model sets, from shots' light and visibility entries, from configurator show, hide and material actions (an action left empty goes), removes keyed tracks and turntables on them, gives a camera path that looked at a removed node a fixed point where its centre was (`node_centre`), turns measurement points pinned to removed parts into world points where they were (the value is kept; the window's "Part removed" state now shows only for documents saved before) and drops size boxes naming removed nodes (one with none left goes). `scene.duplicate` treats a copy as its original: cutaways outside the copy that cut an original also cut the copy, a cutaway copied with its targets cuts the copies and the original keeps the originals, and variant sets, variant entries, model sets, shot entries and configurator actions name the copy too; measurements, rigs and tracks stay on the originals. `camera.add` and `camera.duplicate` move rig and camera-track indices at or after the insert up by one, and `camera.remove` drops the rigs and tracks of the removed camera and moves later ones down. `material.remove` now refuses with `invalid_value`, naming the variant and set or the configurator choice and option, while one of them uses the material; tracks keyed on a removed material are not cleaned (animation tolerates them). Defaults: `resolve` stores the full value minus fields at their default, and `apply` merged that into the current value, so a new field could never be set back to its default (edge radius, fibre density, medium priority and a black scatter stayed at the previous value, and a cutaway's `invert` could not return to false); `scene.set_light`, `scene.set_cutaway` and `material.set_params` now apply over `T::default()`, as the Turn 4 settings do, and each field set and set back was checked to return to its default and leave the JSON. Change levels: a `transport` edit is Full, and a `motion_blur` edit is Full when the document has animation and None otherwise (nothing moves without it), so the film and viewport restart exactly when they must. Not done: duplicated parts are not added to measurements, rigs or tracks, and tracks keyed on a removed material remain. + +### crates/fsh-scene/src/snapshot.rs · kelvin temperature in the render light +- refers-to: src/snapshot.rs :: RenderLight::kelvin, light +- kind: decision +- logged: v0.10.0 · 2026-12-03 +`RenderLight` gains `kelvin: Option`: a light whose colour is a temperature carries it into the snapshot, clamped to 1667..25000 K, the range `Rgb::from_kelvin` follows so both modes agree, where before only the normalised colour survived and spectral mode had to recover the temperature by a colour match. RGB-coloured lights still go through `Blackbody::detect`, which accepts an RGB colour equal to a blackbody colour within 1e-4. The field is snapshot-only and not a document field, so documents are unaffected; the GPU layout is unchanged (lamp records come from the CPU lamps). Check: a 3200 K sun and a 1200 K point lamp at 128 samples, spectral within 0.001 of RGB per channel and base and head equal in both modes (the match had found the same temperatures; the field removes the search and its range limit). + ## fsh-io ### crates/fsh-io/src/gltf.rs, obj.rs, stl.rs, ply.rs · readers into the raw scene @@ -672,6 +858,12 @@ Against the 0.4.0 writer copied out of git: saves without sources were byte-iden - logged: v0.6.0 · 2026-12-02 `referenced_sources(&Document)` collects the `fshot:sources/...` names that some node's `source.cad` metadata holds, and `encode` writes only those `sources/` members (and lists only those in the manifest). Pruning happens in the writer rather than on the kept project, so the session can still bring a source back when an undo restores its parts (imp-cad's reason for never pruning); `prune_sources` uses the same helper and is still unused. Run (polish): saves after an import, its removal, undo and redo held 1, 0, 1 and 0 source members, and the reopened undo save re-tessellated. `encode` also keeps the `textures/` member that an embedded environment image names (`environment.source.path = "fshot:textures/..."`), which is not a material texture and would otherwise be dropped (QA pass). +### crates/fsh-format/src/project.rs · the reserved scene blocks are known fields +- refers-to: src/project.rs :: scene_known +- kind: decision +- logged: v0.9.0 · 2026-12-03 +`scene_known` builds the set of scene field names the loader accepts from a serialised default `DocumentData`, and a default document leaves every empty block out, so a saved `shots`, `variants`, `configurator`, `measurements` or `animation` block came back as "kept unknown scene field" and the reopened document had none of it. The function now extends that set with the five names (`k.extend(["shots", "variants", "configurator", "measurements", "animation"])`), one generic line that fixes every reserved block at once; the shots, variants, configurator and animation work each found the bug on its own and added their own name, and the integration kept the one line. A project written by an older build, which has none of the blocks, loads with no warning and re-saves byte for byte, and a project with blocks reopens to the same blocks and re-saves with the same bytes (checked for shots, the configurator, variants and animation). Any future block that is left out when empty needs its name here too, or it will silently be treated as an unknown field and survive only as preserved JSON. + ## fsh-cad ### crates/fsh-cad · a client of FormCAD's kernel worker @@ -838,6 +1030,66 @@ Every contribution the beauty adds (after the indirect clamp, exactly the value - logged: v0.8.0 · 2026-12-03 The old in-crate a-trous filter is gone; `denoise(means, w, h, strength)` and `denoise_with` keep their signatures and delegate to fsh-denoise at `DEFAULT_QUALITY` (Balanced). `FilmGuides::new(&means)` turns film means into the shared input: colour, albedo and normal times the hit fraction (so a mostly missed pixel reads as background), the variance of the mean luminance, the mean first-hit depth, and `noisy` when any sampled pixel has fewer than 4 samples (`NOISY_GUIDE_SAMPLES`). `denoise_options` takes a `DenoiseOptions` (quality and strength), `denoise_alpha` filters coverage, `quality_of` maps the document's quality. `Renderer::develop` on both renderers and the `PreviewRenderer` trait take `Option` (merged from the denoise-gpu branch) and denoise coverage on a transparent background. +### crates/fsh-render-cpu/src/motion.rs, geometry.rs, camera.rs, integrator.rs, spec.rs · the CPU tracer renders motion blur +- refers-to: src/motion.rs :: InstanceData::placed, InstanceData::motion_keys, Ctx::path_time; src/geometry.rs :: InstanceData::motion, Geometry::moving, Geometry::surface, Geometry::shade_at, Geometry::shading_normal_at, Geometry::hit_context, Geometry::same_layout; src/camera.rs :: CameraModel::ray_at, CameraModel::moves; src/integrator.rs :: the path time; src/spec.rs :: DRAW_ORDER "shutter time" +- kind: decision +- logged: v0.9.0 · 2026-12-03 +Each camera path draws one shutter time in [0, 1) from `DIM_TIME` (4), a sampler dimension that was already reserved, so no other draw moves and the order of every existing draw is kept; `spec.rs` gets one `DRAW_ORDER` row, "shutter time", as the specification for the GPU port. `Ctx::path_time` draws it only when something moves (`Geometry::moving`, `CameraModel::moves`) and otherwise answers 0 without reading the sampler, which is why scenes without motion render byte for byte as before, and helpers that only hold the sampler (ambient occlusion, catcher probes) recompute the same time from it. The time rides on every ray of the path: the camera ray (`CameraModel::ray_at` moves the eye and orientation along the camera's keys), bounce, pass-through, shadow, ground reflection, catcher and occlusion rays, and surface and program shading read the moving instance's pose at that time (`surface(hit, time)`, `shade_at`, `shading_normal_at`, `hit_context`), so a streak carries its own shadow and reflection. `Geometry::same_layout`, the test that allows a material-only update, is never true for a moving scene: a streak reaches beyond the pixels the first hit at the shutter's middle covers, so a material edit in a moving scene resets the whole film and still scenes keep the region path (an earlier version took the region path and left stale streaks). Verified by CLI release builds against a base build: seven scenes (templates sample, spheres, product-white, studio-dark, daylight, turntable, and the built-in sample) at 240 by 160 and 16 samples were byte-identical on the CPU, sample and spheres byte-identical on the GPU through lavapipe, and the sample with blur enabled and nothing moving byte-identical; the blurred pictures are described under fsh-scene. Not done: light from a moving emissive part on other surfaces (it uses the part's middle place), and a motion render through the wasm tracer at run time (only the wasm32 check ran). + +### crates/fsh-render-cpu/src/media.rs, integrator.rs, geometry.rs · absorption, nested media, volumes and the subsurface random walk +- refers-to: src/media.rs :: Medium, instance_medium, MediumStack, PathMedia, transmittance, sample_segment, track, Closure, walk, MEDIA_DIM_BASE, MAX_STACK, DEFAULT_WALK_STEPS, MAX_NULL_COLLISIONS, MAJORANT_SCALE; src/integrator.rs :: Ctx::sample, Ctx::medium_light, Ctx::medium_shadow, IntegratorSettings::max_subsurface_steps; src/geometry.rs :: InstanceData::medium +- kind: decision +- logged: v0.10.0 · 2026-12-03 +The CPU tracer (the specification) gains four things that share one per-path `PathMedia` and a `MediumStack` of 8 entries ordered by priority, then by entry order, with a subsurface walk ranking above everything. Absorption: a closed, transmissive, not thin-walled part with a transmission depth above 0 holds an interior medium (OpenPBR, see fsh-materials) and light inside it fades by exp(-mu_t d); the surface no longer tints (`transmission_color` is forced white at the event). Nested dielectrics (Schmidt and Budge 2002): `medium_priority` above 0 makes a part nest, the higher priority owns an overlap and ties go to the part entered last; a surface of a lower-priority part inside a higher-priority medium is a false hit crossed without interaction (the ray is spawned straight on, at most `MAX_PASS_THROUGH` per path), and a real interface refracts with eta = ior over the index of the highest-priority nesting medium beyond it, or air. Priority 0 parts keep their old interfaces against air even inside a nested medium, so every part of a nested arrangement needs a priority, and a liquid in a glass is modelled by overlapping the liquid 1 mm into the glass wall with the glass at the higher priority. Volumes: `sample_segment` picks a distance with one channel (half uniform, half by throughput) and divides by the mixture pdf over the three channels (single-sample spectral MIS); a scattering event does light sampling with the phase function as the BSDF, MIS against phase sampling, and counts as a diffuse bounce against `max_bounces`. Medium draws use their own PCG dimensions (`MEDIA_DIM_BASE` = 1 << 20 plus a counter), so a path that never meets a medium draws exactly what it drew before. Shadow rays from a medium are attenuated by every medium they cross and pass index-matched boundaries (transmission 1, ior within 1e-3 of 1, no coat, opacity 1, which is the `volume` type); any refracting boundary blocks them, so a smoke box is lit by a spot while a medium inside real glass (ior 1.5) gets only light that finds it by phase sampling. Subsurface: OpenPBR's diffuse and subsurface mix, done stochastically per hit with probability `subsurface_weight`; the closure is the BSDF without its diffuse lobe plus an entry lobe carrying albedo(white base) minus albedo(no base) (a cosine direction into the part), the walk uses spectral tracking (Kutz, Habel, Li and Novak 2017) with the majorant at twice the largest channel extinction (`MAJORANT_SCALE`; at exactly the largest, every null collision zeroed a channel and near-grey marble broke into coloured speckles) and Henyey-Greenstein turns, and the first surface the walk reaches is left through a white Lambertian lobe about the outward normal with no Fresnel on the way out. A walk is capped by `IntegratorSettings::max_subsurface_steps` (256, not a document field) and 4096 null collisions per segment: past either the path ends and its light is dropped, so very dense white parts darken a little instead of costing unbounded time; a walk that leaves through an open mesh also ends the path. Subsurface ignores `base_metalness` and thin-walled parts. `Closure` (Surface, Subsurface, Exit) wraps the BSDF behind the same method names, so the later loop code is unchanged. Byte for byte: scenes with no medium, priority or subsurface render identically on the CPU and the GPU to the base (checked on the seven templates plus a glass scene, CPU and lavapipe). Parity and checks: a white furnace with a 0.4 m volume ball (white colour, depth 0.2 m, scatter 2, g 0.5) centre mean 0.9969 at 256 samples (pixel std 0.043) and 0.999 over the frame, isotropic 0.9955; the GPU port matches the same scenes to 0.000008 (see fsh-render-gpu). Not changed and not done: surface light sampling still treats an index-matched box as a blocker (the floor under a smoke box gets a full shadow), lamps hit by BSDF rays inside a medium are attenuated to the next surface rather than to the lamp, the ground catcher ignores media, a camera that starts inside a medium is treated as in air, and photons do not scatter in media (see caustics). + +### crates/fsh-render-cpu/src/spectral.rs, spectral/ (cie.rs, observer.rs, uplift.rs, table.rs, scene.rs, uplift_table.bin), crates/fsh-materials/src/optics.rs · spectral rendering with hero wavelengths +- refers-to: src/spectral.rs :: Wavelengths, Emitter, EMITTER_PEAK, Blackbody, reflectance, sample_visible_wavelength, visible_wavelength_pdf, LAMBDA_MIN, LAMBDA_MAX; src/spectral/observer.rs; src/spectral/uplift.rs :: Sigmoid, solve_sigmoid; src/spectral/table.rs :: uplift_lookup, UPLIFT_TABLE_RES; src/spectral/scene.rs :: SpectralScene; crates/fsh-materials/src/optics.rs :: Optics::wavelength_ior +- kind: decision +- logged: v0.10.0 · 2026-12-03 +With `transport.spectral.enabled` the CPU path tracer carries three wavelengths per camera path in the three channels of the `Rgb` throughput, so the BSDF code runs unchanged per channel: a hero wavelength from `DIM_WAVELENGTH` and two more a third and two thirds round the range 360..830 nm (Wilkie et al. 2014). Deviation from a uniform hero: the sample number is warped through the visible-range density of Radziszewski, Boryczko and Alda (0.0039398042 / cosh^2(0.0072 (lambda - 538))), and each wavelength stays marginally distributed by it, so (1/3) sum f/p is unbiased with less colour noise. The film converts XYZ = mean of cmf(lambda_i) L_i / p(lambda_i) to ACEScg through matrices built from the published AP1 primaries and the XYZ of the working white's illuminant (CIE daylight through the ACES white chromaticity, luminance 1, so that illuminant films to exactly (1, 1, 1)); radiance is carried times `unit`, the integral of y-bar, and divided out at the film, so the indirect clamp and roulette act at ACEScg scale as in RGB mode. The CIE 1931 2 degree matching functions (360..830 nm at 1 nm) and the CIE daylight S0, S1 and S2 (5 nm) in `cie.rs` are generated data taken from the colour-science package (BSD-3-Clause, Copyright 2013 Colour Developers) and checked against the CIE's own table (largest difference 5e-13; that CIE file is CC BY-SA 4.0 so it was only compared, never copied); the notice lives in NOTICE.md and THIRD-PARTY-NOTICES.txt and the file headers name the holder. Reflectances (base, specular, transmission, coat and fuzz colours) are Jakob and Hanika sigmoids of a quadratic in wavelength: constant colours are solved at snapshot time by Gauss-Newton on CIELAB (`solve_sigmoid`, up to 40 steps, memoised per equal colour in `SpectralScene`, greys exact in closed form), colours made by a program or texture are looked up per hit in `uplift_table.bin`, a generated 3 x 32 x 32 x 32 x 3 little-endian f32 table (1,179,648 bytes, sha256 970cb447...1670e4, solved by the crate's own solver, kept with its generator outside the repository). Emitters (emission, environment, background colour and pictures, emissive triangles, lamp colours) are uplifted as `Emitter`: the colour scaled to a largest channel of `EMITTER_PEAK` 0.5, uplifted as a reflectance, times the illuminant, times max/0.5; at a peak of 1 every lookup fell on the table's top layer and near-white skies turned grey (found by the sky check). Dispersion: `Optics::wavelength_ior(ior_d, lambda)` is the Cauchy law through n_d with the material's Abbe number, used at the hero wavelength, and the first dispersive transmission keeps the hero at three times its weight and zeroes the secondaries (the RGB branch is the old code), so a prism disperses into a continuous spectrum. MIS needs no change: its weights come from the scalar pdfs of light selection and BSDF sampling, and only the radiance a light sample or a lamp hit returns is replaced by the lamp's spectrum at the path's wavelengths (`spectral_light`, `spectral_lamp`), scaled by the luminance of the RGB radiance so IES, spread and edge factors carry over. Kelvin lights emit Planck's law times the ratio of the ACES-white daylight to D65 daylight, the spectral counterpart of `Rgb::from_kelvin`'s Bradford adaptation, so a Kelvin light keeps its look across modes (4000 K films to (1.2054, 0.9496, 0.5917) against from_kelvin's (1.2032, 0.9504, 0.5926)); the temperature reaches the tracer through `RenderLight::kelvin` (see engine gaps), and RGB lights that happen to equal a blackbody colour within 1e-4 are still matched by `Blackbody::detect`. The physical sky is baked into the RGB environment table and uplifted per lookup as an emitter, and its limb-darkened sun is uplifted per sample from its radiance. Every change is a no-op in RGB mode (each helper returns its input without wavelengths), and a spectral scene draws `DIM_WAVELENGTH` at the start of every camera path instead of at the first dispersive hit. Byte for byte with spectral off: 12 of 12 CPU PNGs and 3 of 3 float TIFFs identical to the base, 4 of 4 GPU PNGs, and a base document re-saves unchanged. Agreement: white furnace mean (0.99994, 0.99995, 0.99995) spectral against 0.99995 RGB; a grey sphere differs by 0.0002 relative and a red one by 0.0013; the physical sky differs by under 0.002 relative in the sky band, sphere and catcher ground; the sigmoid solver is within 7.9e-8 mean on 2000 random sRGB colours and the table within 1.2e-3 mean (0.032 at most). The GPU renders spectral mode too (see fsh-render-gpu). Not done: thin film still uses the per-channel Airy fits in spectral mode (filmed materials are approximate), near-white reflectances with a largest channel of exactly 1 can be off by up to about 0.04, saturated ACEScg colours outside the reflectance gamut end at the nearest reachable colour (every sRGB colour is reachable), the shadow catcher's ratio stays an RGB luminance ratio, and `spec.rs` `DRAW_ORDER` does not list the wavelength draw. + +### crates/fsh-render-cpu/src/spectral/media.rs, integrator.rs, renderer.rs, lights.rs · spectral media, colour caps and sun links +- refers-to: src/spectral/media.rs :: MediumSpectra, of, at; src/spectral/scene.rs :: SpectralScene::build, Ctx::path_medium; src/integrator.rs :: medium_light, medium_shadow, the stack.cross sites; src/renderer.rs :: build_lights; src/lights.rs :: Lamp::sun +- kind: decision +- logged: v0.10.0 · 2026-12-03 +Three CPU fixes found where the P15 areas met. Media in spectral mode: before, the medium coefficients stayed the RGB ones, so a tinted or scattering medium came out grey (a red glass cube read 0.38 grey). `MediumSpectra` uplifts the transmission colour as a reflectance and turns it into extinction at each wavelength (-ln T(lambda) / depth), so white light through `depth` films to the colour in both modes; the scatter colour and the subsurface radius scale are unbounded and uplifted as shape times largest channel, and OpenPBR's grey shift is taken over the visible range (scanned over 360..830 nm at 5 nm) so it does not vary from path to path. `Ctx::path_medium(wl, instance, base)` hands the coefficients at the path's wavelengths to the three stack crossings, the subsurface closure, `medium_light` and `medium_shadow`; RGB mode passes the stored `Medium` through untouched. Check: the white furnace volume centre reads (0.992, 0.996, 0.993) spectral against 0.996 RGB (the base gave 1.046, 0.980, 0.990), and red glass of colour (0.8, 0.25, 0.1) at depth 0.3 m reads (1.196, 0.176, 0.061) against RGB (1.195, 0.179, 0.063). Colour caps: a cutaway's flat-colour cap was shaded in the part's own colour in spectral mode because the per-instance spectra ignored the cap swap; a cap hit now passes `u32::MAX` to `spectral_inputs` and takes the table uplift of the cap's inputs, so a yellow cap on a red cube is yellow in both modes. Sun links: `Lamp::sun` built default lamp extras, so a sun ignored its light links on the CPU while the GPU honoured them (a sun linked to one of two cubes differed from the GPU by 0.0076 mean absolute, 0.0 after); it now keeps `links`. Scenes with none of these render as before. + +### crates/fsh-render-cpu/src/caustics.rs, caustics/ (grid.rs, emit.rs, trace.rs, gather.rs), integrator.rs · photon-mapped caustics +- refers-to: src/caustics.rs :: Class, Class::of, NEAR_SPECULAR, pass_radius, auto_radius; src/caustics/grid.rs :: Photon, PhotonMap; src/caustics/emit.rs :: Target, Ctx::emit; src/caustics/trace.rs :: Ctx::trace_photon; src/caustics/gather.rs :: CausticPath, Ctx::caustic_vertex; src/integrator.rs :: Ctx::caustics; crates/fsh-scene/src/transport/caustics.rs :: Caustics, CausticsMode +- kind: decision +- logged: v0.10.0 · 2026-12-03 +`transport.caustics { mode: off | photons, photons, radius, shrink }` (defaults off, 200000 per pass within 1000..2000000, radius 0 meaning automatic and at most 100 m, shrink 0.7 within 0.1..1; every field and the block left out of the JSON at its default) turns on progressive photon mapping of caustic paths only (Hachisuka, Ogaki and Jensen 2008) with the probabilistic global radius schedule of Knaus and Zwicker 2011: pass i gathers within r_i with r_{i+1}^2 = r_i^2 (i + shrink) / (i + 1), and each pass is an independent estimate whose running film mean is the progressive estimate, so no per-pixel statistics are kept. Why: path tracing finds light focused by glass or polished metal only by chance, and the tracer regularises specular paths (roughness floor 0.3 after the first diffuse bounce, indirect clamp 10) so that they do not speckle, which blurs or removes small-light caustics; photons recover them without touching either. Classes use the material's own inputs before regularisation: Specular when there is no diffuse part ((1 - metalness)(1 - transmission) max(base x weight) = 0), no fuzz, no subsurface, and specular and coat roughness at most `NEAR_SPECULAR` 0.1 (glass, liquid, polished metal); every other surface is Diffuse, and fibres and the exit of a subsurface walk are Neither (never stored on or gathered, their caustics stay the path tracer's). Photons cover L S+ D only: a photon leaves a lamp, emissive triangle or the environment, bounces through Specular surfaces only (the weight is the BSDF sample weight times eta^2 at transmissions) and is stored at the first Diffuse surface after at least one bounce, as a 32-byte `Photon` (position, octahedral 16-bit normal and incoming direction, ACEScg power) in a hashed grid of cells twice the radius wide, sorted in place, gathered over at most 8 buckets with a normal agreement of cos at least 0.7. Photons are aimed at the casters (parts whose constant inputs are Specular and that glossy or transmission rays see), each with its own bounding sphere through its farthest vertex (one sphere around all past 16 casters; a moving part uses its world bounds over the shutter): point, spot, rect, disc, sphere and emissive emitters sample the light, pick a caster by the solid angle its sphere subtends and aim uniformly in that cone with a mixture density, suns, directional lights and the environment start a photon on a uniform point of the caster's disc outside the scene. This raised the stored share from 14 percent to 42 percent of the emitted photons with the same caustic energy. Dispersion follows camera paths (RGB: one channel and x3; spectral: the hero wavelength's ior), nested-media false hits pass and `exterior_ior` divides eta, a photon is attenuated by the full transmittance of any medium it crosses (no scattering in media), opacity pass-through, cutaway filters and caps, and rounded edges apply as on camera paths, and a lamp's photon ends where light links stop that lamp lighting the first surface it meets. Gather at every Diffuse camera vertex (not only the first after a specular chain) is L = sum of f(wo, wi) Phi / (pi r^2) with f the closure's non-delta lobes; the first diffuse vertex adds it unclamped as direct light, later ones as indirect. Nothing is counted twice: after a Diffuse vertex that gathered and was left by a non-delta lobe, the path is armed, and while a chain of one or more Specular surfaces follows, the path tracer drops lamp hits (only lamps that emit photons), environment misses (only when the environment emits photons), emissive triangles in the emissive set, and light sampling at Specular surfaces; a medium scatter, a Neither surface or a walk ends the chain. With caustics off no photon map exists, every new check is false and nothing extra is drawn, which is why the off mode is byte for byte the base (11 of 11 CPU files, base on one thread against head on two). Energy: a glass ball under an 8 cm sphere lamp matched an unregularised, unclamped reference within 0.5 percent in the caustic box (162.89 against 162.07, image mean 0.070913 against 0.070921), a 4 degree sun within 0.15 percent, and the shipped path tracer's clamp cuts that caustic to less than half. The GPU refuses photons (`caustics`, see fsh-render-gpu). Not done: photons do not scatter in media (light focused into fog or a murky liquid stays the path tracer's), the shadow catcher ground and fibres get no caustics, a part that is specular only through a texture is aimed at only after another caster, shadow links do not affect photons, and `spec.rs` `DRAW_ORDER` lists no photon draws. + +### crates/fsh-render-cpu/src/caustics/pass.rs, renderer.rs · photon passes in the render loop +- refers-to: src/caustics/pass.rs :: PhotonPasses, Renderer::caustic_pass, Renderer::photon_pass; src/renderer.rs :: Renderer::render_pass, Stats::photon_passes, Stats::photons; src/caustics.rs :: PHOTON_CHUNK +- kind: decision +- logged: v0.10.0 · 2026-12-03 +With photons on, `render_pass(samples)` runs, per asked sample, one photon pass (index = passes since the film reset plus 1, so a reset restarts the radius schedule) on the renderer's thread pool and then the usual pass of one sample, reported as a single `PassReport` whose rays and seconds include the photon passes; `Stats.photon_passes` and `Stats.photons` count them and `Stats.passes` counts one per sample. Photons are traced in chunks of 4096 (`PHOTON_CHUNK`) and photon i of pass p draws from `PixelSampler::new(p, i, seed ^ salt)` (Sobol index = photon index, so a pass is stratified), the chunks are joined in chunk order and sorted in place, so the map depends on neither the thread count nor scheduling: float TIFFs of a spot-lit sphere at 4 samples were identical for one and two threads. The cap of 2,000,000 photons keeps a map near 64 MB and only one map exists at a time. A photon pass checks the cancel flag before each chunk (a cancel set 300 ms into a 4 s pass returned after 0.31 s with no map kept). While the film is scaled below 1 (interaction) no photon pass runs and the picture is the path tracer's alone until the film is back at full size, which resets it; the window therefore shows path-traced caustics while the camera moves and photons resume once it settles. Automatic radius (0) is the radius of a disc on the casters' summed cross section in which 48 of the pass's photons would fall, sqrt(sum r_k^2) x sqrt(48 / photons). Cost: photons are not scaled with the film, so at small sizes they dominate (a 320 x 240 sphere took 173.6 s with photons against 26.9 s without at 64 samples on a loaded shared machine); about a tenth of the pixel count is a good photon count. `render.status` does not report the photon counters yet. Renderer.rs needed seven small regions rather than one (a `#[path]` module line, the two stats, the `PhotonPasses` field, `ctx()` taking `Option<&PhotonMap>` with both callers updated, and the first lines of `render_pass`). + +### crates/fsh-render-cpu/src/cutaway.rs, geometry.rs, integrator.rs · cutaways with caps +- refers-to: src/cutaway.rs :: CutScene, cutaway_removes, cutaway_spans, is_closed, CAP_PRIM, MAX_CUT_SKIPS, Geometry::cap_instance, cap_surface, cap_context; src/geometry.rs :: Geometry::scene, same_layout; src/integrator.rs :: Ctx::sample (cap_instance line) +- kind: decision +- logged: v0.10.0 · 2026-12-03 +The cut is a wrapper in the CPU geometry layer, not a filter inside fsh-accel's traversal: fsh-accel has no hit-filter hook, its scene.rs was shared with motion and fibres this release, and a traversal filter would also have to produce the caps, which are not triangles. `Geometry.scene` is a `CutScene` that derefs to the scene below it and implements `Intersector`, so every `geo.scene.closest_hit` and `occluded` call (camera and bounce rays, shadow rays, the shadow-link loop, the catcher probe, ambient occlusion, the centre-pixel id, the rounded-edge probes and photon rays) passes through the cut with no change at the call site; with no cutaway both methods return the accel answer directly, which is the byte-identity path. `closest_hit` re-traces from each skipped hit (`tmin = t`, at most `MAX_CUT_SKIPS` 64 removed surfaces, then it reports no hit); a hit is removed when its instance is a target and the point lies in the removed volume (several cutaways remove the union), and `occluded` asks the accel scene first and filters only then, so light passes through the opening as the camera sees it. Caps: for each cutaway whose cap is not none, the ray's removed spans are computed analytically in the cutaway's space (plane, box slabs, sphere and cylinder quadratics, complemented when inverted); each span's end in front of the first kept hit is where the ray leaves the removed volume, and a capped target whose bounds contain the point, that no other cutaway of the instance still removes, and whose own next surface along the ray is a back face (the point is inside the solid), gets a cap there; the nearest wins, and at equal distance the instance whose back face is nearest (the innermost part) wins, so a sphere nested in a box shows its own section, and a box cap in front of a nested sphere's outside is found too. The inside test uses a one-instance accel scene per capped part that shares the mesh BVH. Only closed parts get caps: `is_closed` welds corners within 1e-6 of the bounds diagonal and requires every edge to be used as often in each direction (cached per mesh `Arc`), winding must face outward, open meshes show their inside, and thin-walled materials get no cap (the cut layout records this, so editing the flag rebuilds the cut). A cap hit is an ordinary `Hit` of the cut part: `prim = CAP_PRIM (1 << 30) | cut << 1 | flip`, `u = v = 0`, `ng` carrying the world point; `Geometry::surface` rebuilds the point and the boundary normal facing the ray, and `hit_context` gives material programs the world and object-space point, the cap normal and a frame, with no uv sets, so procedural and object-space patterns continue into the cap but uv textures do not. Cap shading is the part's material, one flat colour (the `Colour` mode, shaded from the base colour with specular weight 0 and in spectral mode through the table uplift) or nothing; passes count a cap as the part (object and material ids, Cryptomatte, alpha 255). Prim numbers from 1 << 30 are caps and curve hits stay out of that range. `cutaway_removes` and `cutaway_spans` are public as the reference rules the GPU port reads. The GPU renders cutaways from the same rules (see fsh-render-gpu) and matches to 0.000010. Byte for byte: seven templates and the sample with all passes, CPU and GPU, identical to the base. Not done: the cap search only runs when the ray's live segment crosses the bounds of the capped parts, self-intersecting or overlapping parts that are not nested get caps by the innermost back face rule, and a cut-away emissive triangle still lights the scene. + +### crates/fsh-render-cpu/src/edges.rs, integrator.rs, geometry.rs · rounded edges by probe chords +- refers-to: src/edges.rs :: EdgeRounding, rounded_material, Ctx::round_edges, EDGE_DIM_BASE, EDGE_DIMS_PER_VERTEX, EDGE_PROBES, EDGE_MAX_HITS, MIN_RELATIVE_RADIUS, edge_dim; src/integrator.rs :: Ctx::sample (the line after the shading normal is chosen); src/geometry.rs :: InstanceData::edges +- kind: decision +- logged: v0.10.0 · 2026-12-03 +A material with `edge_radius` r above 0 shades near edges and corners as if they had a fillet of radius r: the shading normal bends smoothly from face to face, a thin highlight runs along the edge, and the geometry and silhouette stay sharp (keep r to about 0.5 to 3 mm on a part a few centimetres to decimetres across). The method is the axis-projection probe sampling of King, Kulla, Conty and Fajardo (SIGGRAPH 2013 Talks): at a hit, with axes the geometric normal and two tangents, two probes per axis (an antithetic pair, six in all) are chords of the sphere of radius r through a disc point (density 3 w(s) / (pi r^2) with w(s) = (1 - s^2/r^2)^2), and every surface a chord crosses (up to 8, closest-hit repeated) is a sample unless it belongs to another part and `edge_other_parts` is off, is farther than r, or faces away from the hit's normal (the far side of a sheet thinner than r); the rounded normal is the weighted sum of the samples' outward shading normals with balance-heuristic weights over the three disc families, and if every sample's normal equals the hit's own (within 1e-6) nothing changes, so flat regions keep their normal exactly. A normal that a program bent (normal map, bump, flakes) keeps its bend, `normalize(ns + rounded - n0)`, and the integrator lifts the result with `clamp_bent_normal` like any bent normal; radii at or below 64 f32::EPSILON of the hit's magnitude are skipped. Each sample draws a fresh estimate, so the rounding converges with samples; it applies at every vertex on such a material (camera hits, reflections, refractions) and in the normal pass. Random numbers come from the hashed sampler range `EDGE_DIM_BASE` = 1 << 18 plus `vertex * 6 + offset` (clear of the Sobol dimensions 0..63, the catcher range and `AO_DIM`), so no existing dimension moved. Probes go through the cut scene, so cutaways remove surfaces from probes too, and after the integration merge they trace and read surfaces at the path's shutter time. Cost: only materials with a radius pay, about 7 to 9 extra ray casts per rounded hit (36.5 M rays against 25.0 M flat on the reference, 2.4x when every object is rounded); two runs gave byte-identical pictures. `rounded_material(snapshot)` names the first material worn by a part that rounds, for `transport.features` and the GPU refusal. Byte for byte: CPU, 240 x 150 at 16 samples, sample, spheres, studio-dark, daylight and a library scene identical to the base, GPU sample and spheres identical, and four base documents re-save unchanged. The GPU port is a line-by-line port and matches to 0.000001. Known CPU defect: for a cap hit `density(offset, d2, h.ng)` reads `h.ng`, which on caps holds the world point and not a normal, so a probe that meets a cap is wrong; the GPU refuses exactly those scenes rather than copy it. Not done: a spec.rs draw entry for the edge discs. + +### crates/fsh-render-cpu/src/fibres.rs, geometry.rs, integrator.rs · fibres in the CPU tracer +- refers-to: src/fibres.rs :: FibredScene, FibreShading::bsdf, surface, fibre_root; src/geometry.rs :: Geometry::scene, same_layout, surface; src/integrator.rs :: Ctx::sample (fibre_root and Scatter::pick lines) +- kind: decision +- logged: v0.10.0 · 2026-12-03 +`FibredScene` is the tracer's scene when parts grow fibres: the accel `FibreScene` plus each layer's roots and look, a curve BVH cache keyed by the curves' identity, `surface` for fibre hits and `fibre_root`, which moves a hit to the fibre's root (its triangle and barycentrics) so the material program, textures, the part tint and the data passes read the part at the root; the fibre takes the base colour there unless `fibre_own_color`, and the albedo guide is that colour. In the loop two inserted lines do the work: after `self.geo.surface(&h)`, `let (h, fibre) = self.geo.scene.fibre_root(h)`, and after the BSDF is built, `Scatter::pick(bsdf, fibre.map(|f| f.bsdf(&inputs)))`, so a fibre hit shades with `FibreBsdf` and everything else is the old code. A part whose material grows fibres never takes the `update_materials` fast path (`same_layout` is false), so a rebuild reuses the mesh BVHs as before and the curve BVHs through the cache. Fibres count as glossy reflections against `max_bounces`. Reference velvet ball (321,538 fibres, 964,614 segments, 480 x 360 at 64 samples): the curve BVH built in 1.9 s, scene build 2.1 s, render 91.6 s for 28.8 million rays on the loaded two-core machine, a deep red ball whose rim is lit (mean luminance on a ring at 0.95 of the radius 68.9 against 42.4 at the centre, the grazing sheen of velvet). The first fur trim showed clumps as large tufts on a grid with seams, which the clump leader grid fixed. Byte for byte with no fibres: four base documents re-save identically, CPU float EXRs of sample, spheres, product-white and daylight identical, GPU sample and spheres identical. The GPU refuses fibre scenes (`fibres`). Not done: fibres are neither stored on nor gathered by photons, a fibre on a moving part does not move (see fsh-accel), fibre counts are not shown to the user, and the window path through WebAssembly was only checked for wasm32 compilation. + +### crates/fsh-render-cpu/src/geometry.rs, cutaway.rs, fibres.rs, media.rs, edges.rs, integrator.rs · how the P15 features layer in the CPU tracer +- refers-to: src/geometry.rs :: Geometry::scene, InstanceData (medium, edges, motion), Geometry::build, refresh_materials, same_layout; src/cutaway.rs :: CutScene, Geometry::cap_instance; src/fibres.rs :: FibredScene; src/media.rs :: Closure; src/edges.rs :: Ctx::round_edges; src/integrator.rs :: Ctx::sample +- kind: rationale +- logged: v0.10.0 · 2026-12-03 +Five features (media, spectral, cutaways, rounded edges, fibres) were written in parallel against `Ctx::sample`, each as insertions at named places, and the integration fixed the layering so that they compose. Geometry nests three wrappers: `Geometry::scene` is a `CutScene`, which wraps a `FibredScene`, which wraps a `FibreScene`, which wraps the accel `Scene`; each derefs to the one below, so every `closest_hit` and `occluded` call sees fibres first and the cut last, and with neither feature present each layer answers straight from below (the byte-identity path). `Geometry::build` wraps `Scene::new(accel)` in `FibredScene::build` and then in `CutScene::new`, and `same_layout` is false when fibres are involved and also compares cutaways and the thin-walled flags of cut parts, so material edits fall back to a rebuild that reuses mesh BVHs and the curve cache. Per-part data rides on `InstanceData` because the integrator has no snapshot: `medium` (set in `build` and `refresh_materials` from `instance_medium`), `edges` (`EdgeRounding`) and `motion`; a cutaway cap is an `InstanceData` of its own (the colour cap's) returned by `cap_instance`, and the merge made caps fill the new medium, rounding and motion fields with defaults. In the loop the order is, roughly as the path meets them: `let inst = ...cap_instance(&h).unwrap_or(inst)` right after the instance is looked up, the fibre root and surface, the shading normal and `round_edges` (probes trace at the path's shutter time and read surfaces at that time, so a rounded part that moves rounds correctly) followed by `clamp_bent_normal`, the opacity pass-through, then spectral inputs, the dispersion block, medium step, nested false hits, the BSDF and `Scatter::pick`, and the closure choice. `Closure::Surface` holds `fsh_materials::Scatter`, so a fibre hit passes through the subsurface and exit code as an ordinary surface hit and spectral dispersion, colour and edges code are untouched. Photon passes (caustics) reuse the same scene, so photons see the cut, the caps and the rounded edges. Sampler dimensions stay disjoint so adding a feature moves no draw of another: Sobol dimensions 0..63 (time, wavelength, lens, light), the catcher range from 64, `EDGE_DIM_BASE` 1 << 18, `AO_DIM` 65536 and `MEDIA_DIM_BASE` 1 << 20 in the hashed PCG range; a scene that uses none of them draws exactly what it drew at 0.9.0. Moving scenes: the software traversal places moving instances at the ray's time; fibres on a moving part are the open gap, and the 64-surface cut limit and the 8-entry medium stack are the per-path bounds. What the integration verified: the workspace built and passed clippy with the five together (commit 3d5f6ef fixed the cap, probe and motion fields), and each feature's old-scene byte identity was proven against the base before the merge; the part files record no picture rendered with media, cutaways, edges and motion all on at once. + ## fsh-ocio ### crates/fsh-ocio · an OpenColorIO version 2 evaluator of our own @@ -1201,6 +1453,72 @@ Looking at thumbnails showed every metallic paint blue (the paint_metallic graph - logged: v0.8.0 · 2026-12-03 `studio.list` with the seven built-ins (light counts 3, 4, 2, 1, 3, 4, 2), a user copy and two broken user files (listed invalid with warnings); every preset applied to the product-white and spheres templates, rendered on the CPU and undone in one step back to the same document (28 checks, 0 failures). Pick focus on the room's ball set 3.116 m axial (3.237 m along the ray), one undo back; keep focus moved an explicit 2.0 to 3.0 on a 1 m dolly. Image commands kept job 1 and the rising sample count through ten display edits. Queue (dev build through dispatch, load average 10 to 18): an EXR with all 23 passes (73 channels, both Cryptomatte attribute sets), a PSD and six PNGs while the viewport kept rendering; cancel at 12 samples left no folder; cancel while writing left the folder empty; the nine light passes summed to the beauty within 2.4e-7; float and 16-bit TIFF, 16-bit PNG and PSD, JPEG, transparent EXR, camera `all`, a project job, a name collision and a GPU job on lavapipe all checked with OpenEXR, psd-tools, Pillow and tifffile. OIDN through the release CLI at 640 by 480, 16 samples: 4.62 s at high, 1.94 s at fast on the CPU device; with an empty cache the PNG was byte-identical to the own denoiser's and the note said why. Not run: OIDN through the queue, a real GPU, Windows and macOS. +### crates/fsh-commands/src/ext/shots.rs, variants.rs · shot.list, shot.render, variant.list, model_set.list, variant.diff +- refers-to: src/ext/shots.rs :: shot.list, shot.render; src/ext/variants.rs :: variant.list, model_set.list, variant.diff; src/ext/output.rs :: add_schema (now pub(crate)), queue_documents, Queued +- kind: decision +- logged: v0.9.0 · 2026-12-03 +The document commands of shots, variants and model sets live in fsh-scene; the engine adds the read side and the render side. `shot.list` lists the shots with their summary line and which nodes they name that are gone (`missing`), and flags the shot the document matches now. `shot.render {ids?}` renders each listed shot (all by default, in list order) through `shot_document`, which applies the shot to a copy of the document so the open document and its history never change, and `queue_documents`, one `Queued` per shot with the file name token `shot` set to the shot's name and the label "Shot: " unless one is given; the default name template is `{project}_{shot}_{pass}`, and its arguments are those of `render.queue_add` (its `add_schema` was made `pub(crate)` so the schema extends it) except `project`, which is refused because the shot belongs to the open document. `variant.list` returns each set with its listed parts, the covered parts with what they wear, each variant with `active`, `applied` (do the parts still wear it after hand edits), a `swatch` (the base colour as sRGB hex of the material most of its parts wear, the first on a tie, the default grey for null) and every distinct swatch, per-material skip reasons (`missing_part`, not a part, locked, `missing_material`), and `variant_materials`, the materials only variants use; `model_set.list` gives nodes with visibility and `missing` flags, `active` and `applied`; `variant.diff {set, variant}` previews the change from and to, the unchanged parts, the skipped ones with reasons and the change level it would cause. All three listings are read-only and cost no history. The shots part of the engine is CPU and queue only, so on wasm32 `shot.render` answers the queue's own `unsupported`. Verified by two renders at 160 by 120 and 4 samples (`Bottle_Hero front_beauty.png` and `Bottle_Detail top_beauty.png`, the second without the hidden band, looked at) and by the variants session described under fsh-scene; scenes without shots render as before since no renderer code changed. + +### crates/fsh-commands/src/ext/configurator.rs · config.get, config.check, config.list, config.render_all +- refers-to: src/ext/configurator.rs :: config.get, config.check, config.list, config.render_all, DEFAULT_NAME; src/ext/output.rs :: queue_documents, Queued +- kind: decision +- logged: v0.9.0 · 2026-12-03 +`config.get` returns the options, choices and rules, the choice in force per option, the current configuration's name and whether it keeps every rule, and per choice an `allowed` flag (the current configuration with that choice swapped in keeps every rule), which is what lets a window grey out choices that `config.select` would answer by moving other options. `config.check` returns the `problems` of fsh-scene's checker (duplicate ids, missing nodes, materials, variants, model sets and shots, empty options, choices no valid configuration reaches, rules that mention missing items) and `config.list {limit}` lists valid configurations by name, "