diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 070df2a2a..4e1dda9fa 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -7,6 +7,8 @@ from fastapi import Request +from opendirector.domain.language import wants_english_language +from opendirector.domain.storyboard_errors import storyboard_error_message from opendirector.domain.timeline_errors import timeline_error_message from opendirector.domain.creation.commands import CommandReceipt @@ -111,15 +113,6 @@ } -def wants_english_language(value: str | None) -> bool: - """Use the primary Accept-Language tag, matching the browser decision.""" - value = (value or "").strip() - if not value: - return False - primary = value.split(",", 1)[0].split(";", 1)[0].strip().lower() - return not primary.startswith("zh") - - def wants_english(request: Request) -> bool: return wants_english_language(request.headers.get("accept-language")) @@ -132,6 +125,8 @@ def localized_error_for_language( code: str = "operation_rejected", ) -> str: specific = timeline_error_message(code, language) + if specific is None: + specific = storyboard_error_message(code, language) if specific is not None: return specific if not wants_english_language(language): diff --git a/artifacts/director-stage/visual/v1-stage-shell-1700x1100.png b/artifacts/director-stage/visual/v1-stage-shell-1700x1100.png new file mode 100644 index 000000000..91957f4a2 Binary files /dev/null and b/artifacts/director-stage/visual/v1-stage-shell-1700x1100.png differ diff --git a/artifacts/director-stage/visual/v1-stage-shell-1920x1080.png b/artifacts/director-stage/visual/v1-stage-shell-1920x1080.png new file mode 100644 index 000000000..9c6d842e4 Binary files /dev/null and b/artifacts/director-stage/visual/v1-stage-shell-1920x1080.png differ diff --git a/artifacts/director-stage/visual/v2-stage-dynamic-1700x1100.png b/artifacts/director-stage/visual/v2-stage-dynamic-1700x1100.png new file mode 100644 index 000000000..5de52b3a3 Binary files /dev/null and b/artifacts/director-stage/visual/v2-stage-dynamic-1700x1100.png differ diff --git a/artifacts/director-stage/visual/v2-stage-dynamic-1920x1080.png b/artifacts/director-stage/visual/v2-stage-dynamic-1920x1080.png new file mode 100644 index 000000000..314852615 Binary files /dev/null and b/artifacts/director-stage/visual/v2-stage-dynamic-1920x1080.png differ diff --git a/artifacts/director-stage/visual/v5-stage-pip-1700x1100.png b/artifacts/director-stage/visual/v5-stage-pip-1700x1100.png new file mode 100644 index 000000000..a2f4ddbe3 Binary files /dev/null and b/artifacts/director-stage/visual/v5-stage-pip-1700x1100.png differ diff --git a/artifacts/director-stage/visual/v5-stage-pip-1920x1080.png b/artifacts/director-stage/visual/v5-stage-pip-1920x1080.png new file mode 100644 index 000000000..7afbc7ae7 Binary files /dev/null and b/artifacts/director-stage/visual/v5-stage-pip-1920x1080.png differ diff --git a/artifacts/director-stage/visual/v5-stage-shoot-1700x1100.png b/artifacts/director-stage/visual/v5-stage-shoot-1700x1100.png new file mode 100644 index 000000000..3e94dd631 Binary files /dev/null and b/artifacts/director-stage/visual/v5-stage-shoot-1700x1100.png differ diff --git a/artifacts/director-stage/visual/v5-stage-shoot-1920x1080.png b/artifacts/director-stage/visual/v5-stage-shoot-1920x1080.png new file mode 100644 index 000000000..7b35e3d42 Binary files /dev/null and b/artifacts/director-stage/visual/v5-stage-shoot-1920x1080.png differ diff --git a/artifacts/director-stage/visual/v5-stage-view-settings-1700x1100.png b/artifacts/director-stage/visual/v5-stage-view-settings-1700x1100.png new file mode 100644 index 000000000..36bd21efa Binary files /dev/null and b/artifacts/director-stage/visual/v5-stage-view-settings-1700x1100.png differ diff --git a/artifacts/director-stage/visual/v5-stage-view-settings-1920x1080.png b/artifacts/director-stage/visual/v5-stage-view-settings-1920x1080.png new file mode 100644 index 000000000..8a5247849 Binary files /dev/null and b/artifacts/director-stage/visual/v5-stage-view-settings-1920x1080.png differ diff --git a/docs/development/director-stage-implementation-plan.md b/docs/development/director-stage-implementation-plan.md new file mode 100644 index 000000000..317665fb2 --- /dev/null +++ b/docs/development/director-stage-implementation-plan.md @@ -0,0 +1,44 @@ +# Director Stage implementation plan + +This plan keeps the Director Stage work in reviewable, dependency-ordered +feature branches. Each branch owns a complete user-facing capability and is +stacked on the branch immediately before it. + +## Branch stack + +1. `feat/stage-output-assets` — output assets, frozen render plans, and the + publication contract. +2. `feat/stage-fullscreen` — the Director Stage shell, full-screen layout, and + shared stage geometry contracts. +3. `feat/director-stage-assets` — asset rail cards, thumbnail capture, and + registered asset references. +4. `feat/stage-gizmo-placement` — the editable stage core: placement from + preview cards, mutually exclusive transform tools, viewport/view state, + object tree and inspector, timeline editing, environment controls, and + persistence validation. +5. `feat/stage-camera-rigs` — independent camera rigs, viewpoint controls, + Director View, and camera monitors. +6. `feat/stage-agent-publish` — the parallel agent publication capability, + based on the shared stage core and independent of the camera UI. + +## Delivery rules + +- Keep a branch limited to its capability and the contracts it must expose to + the next branch. +- Move a prerequisite to the lowest branch that needs it; do not duplicate it + in a later feature branch. +- Every feature unit includes focused tests, a production build, bilingual + message validation, and the relevant Python contract tests. +- Every code-ready unit receives a semantic signed commit with a body starting + with `## summary`. +- Rebase the stack from low to high only after the lower branch passes its + checks. Keep the branches local until the review targets are agreed. + +## Acceptance boundary + +The Director Stage document is the persisted source of business facts. View +state, selection, preview mode, split view, menus, and interaction modes stay +ephemeral. Asset cards and agent operations use the same placement and apply +contracts as direct user interaction. Camera preview output is independent +from the main Director View and does not make viewpoint movement move the main +stage camera. diff --git a/docs/development/director-stage-ui-feedback-plan.md b/docs/development/director-stage-ui-feedback-plan.md new file mode 100644 index 000000000..adff7bd84 --- /dev/null +++ b/docs/development/director-stage-ui-feedback-plan.md @@ -0,0 +1,16 @@ +# Director Stage UI feedback follow-up + +This plan tracks the three follow-up changes identified from the annotated +Director Stage comparison against the local Jiemeng reference screenshots. +Work stays on the semantic `feat/stage-gizmo-placement` branch. + +## Acceptance stages + +| Stage | Scope | Acceptance | Status | +| --- | --- | --- | --- | +| F1 | Transform tool mode | Move, rotate, and scale are a discriminated single-choice state; only the selected helper is visible and keyboard/buttons preserve that invariant | complete | +| F2 | Asset card previews | Stage object cards show a PNG thumbnail rendered from the corresponding 3D object at the origin, centered and cropped from the render; imported objects use their loaded scene when available | complete | +| F3 | Object tree and inspector layout | Right rail follows the reference split between a searchable object tree and an independently scrolling property inspector, with stable grouping and scroll behavior | complete | + +Each stage requires a focused behavior or browser check, the relevant project +checks, and a signed Git commit before the next stage begins. diff --git a/docs/development/director-stage-visual-alignment-plan.md b/docs/development/director-stage-visual-alignment-plan.md new file mode 100644 index 000000000..a03b61152 --- /dev/null +++ b/docs/development/director-stage-visual-alignment-plan.md @@ -0,0 +1,45 @@ +# Director Stage visual alignment plan + +This execution plan tracks the visual-alignment work against the native Jiemeng +Director Stage screenshots referenced by the external audit plan. It is scoped +to the existing `feat/stage-fullscreen` branch because the branch owns the +Director Stage shell, layout, asset tabs, and viewport tools. + +The reference is the screenshot set in the local audit workspace: + +`C:\Users\10425\.zcode\workspace\draft-9c960b48-85bb-4dbe-8ee1-03eba20460c0\jimeng-canvas-audit\screenshots` + +Primary comparison states: + +- `02-director-console.png`: static console shell. +- `09-director-console-dynamic.png`: dynamic-mode transition. +- `11-director-console-dynamic-mode.png`: dynamic console and timeline. +- `12-director-console-camera-moves.png`: camera-move asset tab. +- `13-director-console-view-settings.png`: viewport settings popover. +- `14-director-console-shoot.png`: camera/shoot view. + +## Rules + +- Match the reference geometry, spacing, density, color hierarchy, and state + transitions before introducing new visual language. +- Keep the 3D viewport as the base layer. Panels are full-height workbench + regions or overlays, not document-flow dialogs. +- Keep business values and bilingual message keys unchanged while changing + presentation. +- Work on the existing semantic branch. Do not create a new branch for this + alignment pass. +- Each stage must have a browser screenshot or computed-geometry check, the + smallest relevant automated checks, and a signed commit (`commit -s`). +- After the shell commits land, rebase `feat/stage-gizmo-placement` onto this + branch before continuing work that depends on the shell. + +## Stages + +| Stage | Scope | Reference states | Acceptance | Status | +| --- | --- | --- | --- | --- | +| V1 | Workbench shell geometry and base color tokens: top bar, left asset rail, right inspector, viewport bounds, and bottom timeline boundary | 02, 11 | No floating-dialog margins on the main shell; panel widths and boundaries are stable at 1920×1080 and 1700×1100; existing console browser flow remains green | complete | +| V2 | Top bar and asset-library density: compact actions, mode switch, asset tabs, search, cards, and active states | 02, 11, 12 | Header and left rail follow the reference rhythm; active tab and compact control states are visible and keyboard accessible | complete | +| V3 | Object tree and inspector hierarchy: grouped rows, section dividers, fields, toggles, and scroll behavior | 02, 11, 13 | Right side reads as object tree above properties; selected/empty states preserve the same geometry | complete | +| V4 | Dynamic timeline: transport, ruler, tracks, playhead, frame/keyframe density, and dynamic/static state transition | 09, 11, 12 | Dynamic mode exposes the timeline with reference density; static mode does not reserve an unexplained editor area | planned | +| V5 | Viewport overlays and transient surfaces: tool rail, PiP, settings menu, viewfinder, help, and shoot state | 03, 13, 14 | Each overlay matches its reference anchor, z-order, padding, and dismissal behavior | planned | +| V6 | Screenshot matrix and rebase handoff | 02, 09, 11–14 | Capture before/after comparison evidence, run required checks, commit, then rebase `feat/stage-gizmo-placement` and rerun its browser lanes | planned | diff --git a/docs/development/lessons.md b/docs/development/lessons.md index 8e6ea679a..1306ef29c 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -86,6 +86,7 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Trigger:** A workspace timer retains its document while an editor commit installs a newer authoritative baseline. - **Lesson:** A timer may run after the editor's saving flag clears but before React installs the new document. Comparing that old closure against the new baseline can turn a view-only save into a business rollback, invalidating a previously captured publication version. - **Check:** Invalidate scheduled automatic callbacks when the editor transaction starts, drain queued saves and explicitly persist the current draft before the edit. Preserve publication CAS checks. Exercise the real due callback at the acknowledgment boundary; isolate projection-test gates by snapshot identity, assert release/restoration and always clean up. Distinguish a forced reproduction from proof of the exact CI schedule. +- **Same-continuation follow-up:** The Director Stage Storyboard add (commit `33e084dc`) reproduced the rollback without a timer. After an editor save was acknowledged, the step that followed it in the same asynchronous continuation sent the next server command and first persisted `historyRef.current.present`. React had not yet installed the document the save produced, so that persist compared the previous canvas with the new baseline and wrote the saved draft back to what it was before the save; the command was then refused with `revision_conflict`. Only the real-browser journey showed it; the unit tests of either side could not. After an acknowledged editor save, a later step in the same continuation must not flush the canvas from `historyRef` again, because the save already did; `appendStageStoryboard` takes `savedDraft` for exactly that case. Cover a flow that saves a draft and then sends a command with a browser step that reads the stored document afterwards. ## An upstream response and a consumer finishing it are separate facts @@ -100,3 +101,40 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Lesson:** [Issue #302](https://github.com/ThinkFlowLab/OpenDirector/issues/302) identified four citation groups whose Unicode private-use delimiters and internal source IDs were displayed as text. The native and persisted replies agreed byte for byte; intact text transport did not establish usable presentation. - **Check:** Verify the source metadata as well as reply text, multiple citations, split streaming markers, history reopening, copying and missing-source fallback. Preserve raw execution evidence and tool offsets; leave literal code examples unchanged and inspect both interface languages in the browser. - **Presentation follow-up:** The source-link UI in #302 initially inherited a library modal's utility classes without the corresponding CSS. Text and click checks passed while the border and close-button positioning failed. Use the supported custom renderer with repository-owned styles, and check computed styles, element geometry, long URLs, keyboard close and focus restoration as well as translated text. + +## Values read back from renderer math need tolerant edit comparison + +- **Trigger:** Committing document values that were read back from three.js after the renderer recomputed them, such as camera orbit gesture ends or transform-handle drags in the Director Stage. +- **Lesson:** The stage's orbit commit compared the read-back pose with exact equality while `setCamera` round-trips the pose through OrbitControls' spherical update; an unchanged camera could read one ulp away (5.000000000000001 vs 5), so every frozen gesture end committed an epsilon pose plus a phantom camera keyframe at the playhead. Unit fixtures used exact values, so only a real browser (tests/browser/director_stage_gizmo.mjs) exposed the phantom undo entry. +- **Check:** When a gesture commits values that passed through renderer math, compare edit results within a small float tolerance while keeping parse-time validation exact, and cover the unchanged-gesture path in the browser rather than only with exact unit fixtures. + +## A relation rule in a stored model makes older records unreadable + +- **Trigger:** Adding a new business rule to a pydantic model that a stored snapshot or a stored command payload uses, so that it seems to be enforced everywhere at once. +- **Lesson:** The first plan for the continuous Storyboard put the rule into the stored `DirectorData` model. `ProjectSnapshot.model_validate` runs on project load and on every command, and a commit record re-parses its stored command whenever history loads, so a project saved with sparse shots would have failed to open instead of refusing one Director Stage write. The same ordering hides specific rejections: the HTTP and Agent entry points parse a command payload before the application service runs, so a relation check in the payload model answers with a generic `invalid_input` before the write boundary can report its stable code, and on raw values it rejects sub-millisecond input that the normalized rule accepts. +- **Check:** Put the rule in a domain function that the application write boundary calls on normalized copies, and leave the stored model as the last line of defence. When a command has to reach that boundary before the model's own relation checks, parse the incoming document with a sibling model that defers only those checks and dumps identically, so commit records and replay fingerprints are unaffected. Add a test that stores the unsupported shape through the store, reopens the project from disk, and asserts that the write is rejected with the stable code while the stored document is unchanged. Commit `d878d5f9` and `tests/test_creation_director.py` show the shape. + + +## WebGL viewport and canvas readback use different units + +- **Trigger:** Drawing a preview into a WebGL canvas rectangle and copying the result into a 2D canvas. +- **Lesson:** During Storyboard ticket 03, the viewport was sized in logical pixels to render a fixed-size device-pixel thumbnail. Multiplying the readback dimensions by the device pixel ratio again included neighboring viewport content. At 2×, a solid-color 128×72 probe contained only 2,304 of the expected 9,216 pixels of that color. +- **Check:** Convert the viewport rectangle to device pixels once, then read that rectangle using the drawing buffer height and the 2D canvas origin. Verify the actual image at DPR greater than 1 and check that the visible viewport is restored before the thumbnail task returns. See [the Storyboard browser journey](../../tests/browser/director_stage_storyboard.mjs). + +## Storyboard edits and export need the same endpoint calculation + +- **Trigger:** Appending a block or shortening the main timeline when saved intervals contain sub-millisecond times. +- **Evidence:** The [Director Stage command tests](../../tests/test_creation_director.py) reproduce an append that previously created an internal gap and a duration clamp that failed structural validation. The continuity check rounded each interval component, while append rounded their sum and clamp could fall below the original stored end. +- **Check:** Compare the stored intervals, query result, applied receipt, and replay after append or clamp. Include a legacy interval whose rounded endpoint differs from its stored endpoint. Verify existing block timing and animation survive the operation. + +## A picture inside a dragged element takes the pointer gesture away + +- **Trigger:** A pointer gesture that may begin wherever the user presses inside an element holding an ``, such as a block with a thumbnail, while the gesture owns the pointer through `setPointerCapture`. +- **Lesson:** A picture left draggable starts the browser's own drag on the press. It fires `dragstart`, then `pointercancel` at the element holding the capture and `lostpointercapture`, so a gesture that ends on a cancel is over before the pointer has moved and its release writes nothing. Commit `3a1bdd29` fixed the Director Stage Storyboard block by making its thumbnail `draggable={false}`. Measured in a minimal page in headless Chromium (a button holding a picture, the capture on its outer element): a press on the name gave `pointerdown` → `pointerup`; a press on the picture gave `pointerdown` → `dragstart` → `pointercancel` → `lostpointercapture` → `dragend`; with `draggable=false` the picture gave `pointerdown` → `pointerup`. The [Storyboard browser journey](../../tests/browser/director_stage_storyboard.mjs) started each drag from the centre of the block, which is its name, so the one press that could not drag, the one on the picture, was never made. +- **Check:** Give every picture inside an element that is dragged `draggable={false}`, as `ReferenceThumbnail.tsx` and `SubjectNodeCard.tsx` do, and start one browser gesture from the picture itself, asserting that its release still commits. A gesture that is exercised only from text has not shown that the whole target can be dragged. + +## A cancelled pointer gesture keeps its capture until the pointer is let go + +- **Trigger:** A pointer gesture that holds its pointer through `setPointerCapture` and can be cancelled while the button is still held, by Escape, a `pointercancel` or the window losing focus. +- **Lesson:** Commit `e2e2784e` fixed the Director Stage Storyboard drag. Its cancel released the capture at once, so the release that followed was sent to whatever lay under the pointer, and the `click` it produced went to the common ancestor of the press and the release. Over an empty stretch of the lane that ancestor was the lane itself, whose click moves the playhead: a drag cancelled with Escape moved the playhead when the mouse was let go, although nothing had been written. The [Storyboard browser journey](../../tests/browser/director_stage_storyboard.mjs) could not see it, because its lane was full of blocks and every release landed on one. The same shape, a cancel that releases the capture, is in `LayerBoard.tsx`, `TimelineEditor.tsx`, `LocalImageTools.tsx` and `TimelineTextLane.tsx`; none of them was checked for a release that lands elsewhere. +- **Check:** Leave the capture to the browser, which gives it up with the `pointerup`, and let the surface that holds the pointer stop the `click`. Cover every way of cancelling with a release where no target of the gesture lies, on an empty part of the surface and outside it, in a real browser. diff --git a/docs/development/validation.md b/docs/development/validation.md index 3e64544db..a420cd74d 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -247,8 +247,26 @@ CREATION_WEB_URL=http://127.0.0.1:5179 CREATION_API_URL=http://127.0.0.1:8019 \ 同一套隔离服务下的浏览器检查: +分镜测试在中英文界面验证拖拽重排及其拖动反馈(抓取光标、只有被拖块跟随指针、标出块将插入位置的粗线、拖动中其余不动且不写入、被拖块在键盘焦点下也不带焦点环、松手后播放头落在被拖块的新起点、保存被拒时顺序与播放头一起回到拖动前)、波纹调整、取消(取消后在空白的轨道或标尺上松开也不移动播放头)、松手后持久化及单步撤销重做。删除流程覆盖波纹删除、机位级联、最后机位保护、预览回退和保存重开。 + +The Storyboard test covers drag reorder and its drag feedback (the grab cursors, only the dragged block following the pointer, the line that stands where it would be let in, everything else still and nothing written while it is dragged, a carried block that shows no ring of keyboard focus, the playhead landing on the dragged block's new start once it is let go, and the order and the playhead going back together when the save is refused), ripple resize, cancellation (a release on an empty part of the lane or on the ruler after a cancelled drag moves no playhead either), persistence on release, and single-step undo and redo in both locales. Deletion coverage includes ripple deletion, camera cascades, final-camera protection, preview fallback, and reopening. + +生产验收使用浏览器清单的 `production` 测试层,在中英文界面连接隔离的工程服务和真实工程存储。导出通过 Chromium 在本地渲染和编码,使用 `ffprobe` 检查文件信息,并使用 `ffmpeg` 解码检查切点前后的画面。此流程的范围是单轨机位硬切,转场、多轨、音频和关闭浏览器后的后台渲染属于独立能力。模型服务使用替身,验收记录应注明浏览器和渲染环境。 + +The `production` browser lane runs acceptance in both languages against the isolated project API and real project storage. Chromium renders and encodes locally. `ffprobe` reads the published file metadata, and `ffmpeg` decodes frames around cuts. The journey covers hard cuts on a single camera track. Transitions, multiple tracks, audio, and rendering after the browser closes are separate capabilities. The fixture uses model stubs. Record the browser and rendering environment with the results. + ```sh node scripts/verify_creation_browser.mjs # UI/API 主流程与重载 +node tests/browser/director_stage_entry.mjs # 导演台创建、GLB 导入、关键帧、撤销、重做与重开(默认 en-US) +DIRECTOR_STAGE_LOCALE=zh-CN node tests/browser/director_stage_entry.mjs # 同一导演台与 GLB 流程走中文界面 +node tests/browser/director_stage_gizmo.mjs # 预览窗口内拖动操作轴摆位,不写关键帧,单次撤销还原 +DIRECTOR_STAGE_LOCALE=zh-CN node tests/browser/director_stage_gizmo.mjs # 同一摆位流程走中文界面 +node tests/browser/director_stage_storyboard.mjs # 连续分镜:时间轴 `+` 上方的机位单选栏、共享追加命令、选中与播放头、撤销重做、保存重开与 HTTP 命令等价结果;以及预览来源:来源选择器、按分镜或固定机位预览与分镜末端保持、取景器/机位预览/分屏/定格同源、位姿提交落在预览机位、机位列表点击移动机位预览而保留分镜预览,且视图状态不弄脏草稿;以及块展示:选中填充与播放头白框各自独立并可叠加、共享边界与终点的归属、按空闲时间异步生成并在机位或场景变化后刷新的缩略图、窄块先隐名称后隐缩略图、播放中缩略图刷新不影响视口与点击响应;以及拖动反馈:抓取光标、只有被拖块跟随指针、标出块将插入位置的粗线、拖动中其余不动且不写入、被拖块在键盘焦点下不带焦点环、松手后播放头落在被拖块的新起点、保存被拒时顺序与播放头一起还原、取消后在空白的轨道或标尺上松开不移动播放头(默认 en-US;设置 DIRECTOR_STAGE_STORYBOARD_SCREENSHOT_DIR 可另存界面截图) +DIRECTOR_STAGE_LOCALE=zh-CN node tests/browser/director_stage_storyboard.mjs # 同一分镜流程走中文界面 +node tests/browser/director_stage_animation.mjs # 动画 GLB 导入、播放头采样与 MP4 同源合成 +node tests/browser/director_stage_output.mjs # 定格与 MP4 登记为工程资产并被时间线引用 +CREATION_DEVICE_SCALE_FACTOR=2 node tests/browser/director_stage_output.mjs # 同一流程在高 DPI 下复验定格尺寸 +node tests/browser/director_stage_delivery.mjs # 被后端明确拒绝的存储投递只损失一次尝试,随后重规划恢复渲染与应用 node tests/browser/reference_reconnect.mjs # 参考连线删除后重连 node tests/browser/context_menu_dismissal.mjs # 右键菜单关闭 node tests/browser/mp4_export.mjs # 合成 MP4(WebCodecs + 软件 AAC) diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 11597b2f2..16b8dc19f 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -176,6 +176,20 @@ Editable JSON describes the timeline within the same project and does not embed Keep the page and editor open while rendering. Closing the editor or canceling stops the current render. MP4 rendering requires the browser; the assistant cannot render a final video after the browser is closed. +### Arrange a Director Stage Storyboard + +The Storyboard is the **Shots** row of the Director Stage timeline: blocks that each show one camera, laid end to end from zero. Choose **+** on that row to add a camera as a new block at the end. The new block is selected and the playhead moves to where it starts. + +Hold a block and drag it sideways to change the order. The pointer is an open hand over a block and closes when you press. Only the block you hold moves with the pointer, and it stops at the row's edges; the other blocks, the playhead and the preview stay as they are. Where letting go would change the order, a thick white line across the row stands where the block would be inserted: before the block that would then follow it, or at the end of the last block when it would come last. A block carried as far as it will go, to either edge of the row, is inserted last or first. Dragging the edge between two blocks moves the cut and shifts the blocks after it to stay end to end; dragging the end of the last block changes where the Storyboard ends. + +Let go and the blocks are arranged in the new order at once. Every block keeps its camera and its length, and the playhead moves to where the block you dragged now starts. The new order is saved as one step, so one undo takes it back. Let go where the order would not change, or press `Esc` while dragging, and the block returns to its place with nothing changed. + +### Export a Director Stage Storyboard + +In the Director Stage, choose **Render preview MP4** and select **Storyboard**. The video starts at zero, cuts directly between cameras, and ends with the last block. The first output frame at or after a cut uses the next block's camera. Changing the output frame rate leaves the saved cut times intact. Camera and subject animation continue on the same timeline even if a camera appears in several blocks. + +If a shorter **Stage duration** would cut through the Storyboard, the stage ends at the last block. The editor shows the requested and applied durations. Storyboard blocks and keyframes keep their saved times. + ## Save, back up, and download - Use a node's download control to save its asset. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index a5fd095e2..4b3c1f118 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -176,6 +176,20 @@ AI 助手可通过共用编辑命令修改同一份已保存时间线。交接 合成期间保持页面和编辑器打开。关闭编辑器或取消会停止本次合成。MP4 合成需要浏览器参与;关闭浏览器后,助手不能独立合成最终视频。 +### 调整导演台分镜的顺序 + +分镜是导演台时间轴的 **分镜** 一行:每个分镜块显示一个机位的画面,首尾相接,从 0 秒排起。点击这一行的 **+**,在末尾添加一个机位块。新块处于选中状态,播放头跳到它的起点。 + +按住一个分镜块左右拖动可以调整顺序。指针悬停在块上时是张开的小手,按下后握紧。拖动时只有按住的块跟随指针移动,到这一行的两端为止;其他块、播放头和预览都保持不动。如果松手会改变顺序,这一行会出现一条贯穿的白色粗线,标出该块将插入的位置:在排在它后面的那一块之前,排在最后时则在最后一块的末端。把块拖到这一行的尽头,它会排到最后或最前。拖动两个块之间的边界会移动切点,后面的块随之平移以保持首尾相接;拖动最后一个块的末端则改变分镜的结束位置。 + +松手后,各块立即按新顺序排好。每个块保留自己的机位和时长,播放头跳到被拖块的新起点。新顺序作为一步保存,撤销一次即可还原。在不会改变顺序的位置松手,或拖动时按 `Esc`,块回到原位,什么都不会改变。 + +### 导出导演台分镜 + +在导演台选择 **合成预演 MP4**,将来源设为 **分镜编排**。视频从零秒开始,在机位间直接硬切,到最后一个分镜块结束。切点当时或之后的第一帧使用右侧分镜块的机位。修改输出帧率不会改变已保存的切点。同一机位反复出现时,机位和场景对象的动画仍按主时间轴采样。 + +如果缩短 **舞台总时长** 会截断分镜,舞台会停在最后一个分镜块的结束位置。编辑器同时显示请求时长和实际应用时长。分镜块和关键帧保留已保存的时间。 + ## 保存、备份和下载 - 节点中的下载入口用于保存对应素材。 diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 1d6e9d19d..2e8af52c3 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -13,12 +13,15 @@ from opendirector.domain.creation.assets import AssetRef from opendirector.domain.creation.base import CanvasItemVersion, ObjectVersion -from opendirector.domain.creation.commands import CanvasShow, Query, ReferenceWrite, SpecWrite +from opendirector.domain.creation.commands import CanvasShow, DirectorStoryboardResult, Query, ReferenceWrite, SpecWrite from opendirector.domain.creation.generation import FollowingSource, ResolvedReference from opendirector.domain.creation.canvas import CanvasReferenceSources, FollowingReferenceSource, PinnedReferenceSource, media_card_size, node_capabilities, VideoCanvasItem from opendirector.domain.creation.models import ModelConfigPublic from opendirector.domain.creation.project import ProjectSnapshot, asset_references from opendirector.domain.creation.index import object_index +from opendirector.domain.creation.storyboard import ( + STORYBOARD_DEFAULT_SECONDS, appended_block, delete_storyboard_blocks, normalize_storyboard_time, pack_storyboard, + storyboard_blocks, storyboard_end, storyboard_issue, storyboard_rejection, storyboard_state) from opendirector.domain.creation.validation import ContractError from opendirector.domain.input_rules import input_rules from opendirector.domain.rule_facts import FRAME_IMAGE_LIMIT @@ -299,14 +302,43 @@ def _available(self, asset): return self.assets.reference_available(asset.projectId, asset.id) def execute(self, command, *, session=None, source='ui'): - return self.projects.commit(command, lambda before: self.apply(before, command), session=session, source=source) + durations, storyboard = [], [] + return self.projects.commit( + command, lambda before: self.apply(before, command, durations=durations, storyboard=storyboard), + session=session, source=source, director_durations=durations, director_storyboard=storyboard, + ) - def apply(self, before, command): + def apply(self, before, command, *, durations=None, storyboard=None): data = before.model_dump(mode='json') operations = command.payload.operations if command.type == 'creation.batch' else [command] - for operation in operations: - if operation.type != 'canvas.applyEdit': - self._mutate(data, operation.type, operation.payload) + storyboard_evidence = [] + for index, operation in enumerate(operations): + kind, payload = operation.type, operation.payload + if kind == 'canvas.applyEdit': + continue + observes_storyboard = storyboard is not None and ( + kind.startswith('director.storyboard.') or kind in {'director.duration.set', 'director.camera.delete'}) + if observes_storyboard: + document = self._get(data, 'editor_document', payload.documentId) + old_shots = storyboard_blocks(document['data']['shots']) if document['kind'] == 'director' else () + if kind == 'director.duration.set': + duration = self._set_director_duration(data, payload) + if durations is not None: + durations.append(duration) + else: + self._mutate(data, kind, payload) + if observes_storyboard: + blocks = storyboard_blocks(document['data']['shots']) + old_by_id = {block.id: block for block in old_shots} + new_ids = {block.id for block in blocks} + limit = kind == 'director.storyboard.append' and blocks[-1].duration < STORYBOARD_DEFAULT_SECONDS + storyboard_evidence.append(dict( + operationIndex=index, operation=kind, documentId=payload.documentId, blocks=blocks, + affectedBlockIds=tuple(block.id for block in blocks if old_by_id.get(block.id) != block), + removedBlockIds=tuple(block.id for block in old_shots if block.id not in new_ids), + blockId=getattr(payload, 'blockId', None), cameraId=getattr(payload, 'cameraId', None), + appendLimitReason='storyboard_tail' if limit else None, + )) # Publish against the final document in this atomic batch. published = set() for operation in operations: @@ -360,8 +392,30 @@ def apply(self, before, command): if actual.kind in {'video', 'audio'} and actual.metadata.durationSeconds is None: raise ContractError('invalid_input', '请先读取视频或音频的实际时长,再添加到目标节点。', value.sourceId) self._available(actual) + if storyboard_evidence: + versions = {doc.id: doc.revision for doc in result.editorDocuments} + storyboard.extend(DirectorStoryboardResult(version=versions[evidence['documentId']], **evidence) + for evidence in storyboard_evidence) return result + def _set_director_duration(self, data, payload): + document = self._get(data, 'editor_document', payload.documentId) + if document['kind'] != 'director': + raise ContractError('role_restricted', '请选择导演预演文档。 Select a Director Stage document.', payload.documentId) + self._editable_document(data, payload.documentId) + stage = document['data'] + issue = storyboard_issue(stage['shots'], stage['duration'], [camera['id'] for camera in stage['cameras']], + object_id=payload.documentId) + if issue is not None: + raise issue + # Preserve both the effective cut endpoint and the original interval's + # stored bounds when clamping a legacy document. + raw_end = max((shot['start'] + shot['duration'] for shot in stage['shots']), default=0) + applied = max(payload.duration, storyboard_end(stage['shots']), raw_end) + stage['duration'] = applied + return dict(documentId=payload.documentId, requestedDuration=payload.duration, appliedDuration=applied, + clampReason='storyboard_end' if applied > payload.duration else None) + def _apply_edit(self, data, payload, before, command): item = self._editable(data, payload.itemId) if item['kind'] != 'image' or item['binding']['role'] not in {'material', 'generation'}: @@ -423,6 +477,24 @@ def _get(data, kind, object_id): raise ContractError('missing_object', '业务对象不存在。', object_id) return obj + @staticmethod + def _validate_director_locks(old, new): + """Reject edits to locked stage objects before the document is mutated.""" + if old.get('kind') != 'director' or new.get('kind') != 'director': + raise ContractError('role_restricted', 'director.apply 只能保存 Director Stage 文档。 director.apply only accepts Director Stage documents.', UUID(str(old['id']))) + previous = {str(item['id']): item for item in old['data'].get('objects', [])} + following = {str(item['id']): item for item in new['data'].get('objects', [])} + for object_id, item in previous.items(): + if not item.get('locked'): + continue + next_item = following.get(object_id) + if next_item is None: + raise ContractError('role_restricted', 'Locked stage objects cannot be removed. 已锁定的舞台对象不能删除。') + unlocked_only = dict(next_item) + unlocked_only['locked'] = True + if unlocked_only != item: + raise ContractError('role_restricted', 'Locked stage objects cannot be modified; unlock in a separate command first. 已锁定的舞台对象不能修改,请先单独解锁。') + @classmethod def _editable(cls, data, item_id, *, unlocking=False): item = cls._get(data, 'canvas_item', item_id) @@ -437,6 +509,34 @@ def _editable(cls, data, item_id, *, unlocking=False): current = cls._get(data, 'canvas_item', current['parentId']) if current['parentId'] else None return item + @classmethod + def _editable_document(cls, data, document_id): + """Every canvas item bound to a document, or carrying it as an attached editor, must be editable.""" + for item in data['canvasItems']: + binding = item['binding'] + ref = binding.get('objectRef') or binding.get('draftSpec') + attached = any(str(editor['id']) == str(document_id) for editor in item.get('editors', [])) + if (ref and str(ref.get('id')) == str(document_id)) or attached: + cls._editable(data, item['id']) + + @staticmethod + def _write_director(document): + """The Director Stage write boundary. + + Block times are normalized to milliseconds once, here, as the document enters + project state; the continuity rule then judges exactly what will be stored. Reads + and unrelated commands never pass through, so older stored values stay as they are. + """ + stage = document['data'] + stage['shots'] = [ + {**shot, 'start': normalize_storyboard_time(shot['start']), + 'duration': normalize_storyboard_time(shot['duration'])} + for shot in stage['shots']] + issue = storyboard_issue(stage['shots'], stage['duration'], [camera['id'] for camera in stage['cameras']], + object_id=UUID(str(document['id']))) + if issue is not None: + raise issue + def _validate_timeline(self, document, snapshot): from .creation_timeline import validate_timeline_resources validate_timeline_resources(document.data, snapshot, self.assets) @@ -484,7 +584,7 @@ def _publish_render(self, data, payload): def _mutate(self, data, kind, payload): value = payload.model_dump(mode='json', exclude_unset=True) - if kind in {'editor.create', 'editor.save'} and payload.document.kind == 'timeline': + if kind in {'editor.create', 'editor.save', 'director.apply'} and payload.document.kind == 'timeline': self._validate_timeline(payload.document, ProjectSnapshot.model_validate(data)) if kind == 'canvas.publishMedia': from .creation_media_publication import publish_media @@ -505,21 +605,95 @@ def _mutate(self, data, kind, payload): raise ContractError('invalid_input', '对象标识已存在。', UUID(obj['id'])) if key == 'spec' and obj['currentResultId'] is not None: raise ContractError('invalid_input', '新配置不能指定生成结果。') + if obj['kind'] == 'director': + self._write_director(obj) data[collection].append(obj) - elif kind in {'generationSpec.update', 'editor.save'}: + elif kind in {'generationSpec.update', 'editor.save', 'director.apply'}: key, object_type = ('spec', 'generation_spec') if kind.startswith('generation') else ('document', 'editor_document') obj = getattr(payload, key).model_dump(mode='json') old = self._get(data, object_type, obj['id']) + if kind in {'editor.save', 'director.apply'} and payload.document.kind == 'director': + self._validate_director_locks(old, obj) immutable = ('kind', 'purpose', 'currentResultId') if key == 'spec' else ('kind',) if any(obj[field] != old[field] for field in (*immutable, 'projectId')): raise ContractError('role_restricted', '配置编辑不能修改对象角色或结果选择。', UUID(obj['id'])) - for item in data['canvasItems']: - binding = item['binding'] - ref = binding.get('objectRef') or binding.get('draftSpec') - attached = any(str(editor['id']) == str(obj['id']) for editor in item.get('editors', [])) - if (ref and str(ref.get('id')) == str(obj['id'])) or attached: - self._editable(data, item['id']) + self._editable_document(data, obj['id']) + if obj['kind'] == 'director': + self._write_director(obj) old.update(obj) + elif kind in {'director.storyboard.append', 'director.storyboard.reorder', 'director.storyboard.resize', 'director.storyboard.delete', 'director.camera.delete'}: + document = self._get(data, 'editor_document', payload.documentId) + if document['kind'] != 'director': + raise ContractError('role_restricted', '只能编辑 Director Stage 文档的分镜。', payload.documentId) + self._editable_document(data, payload.documentId) + stage = document['data'] + camera_ids = [camera['id'] for camera in stage['cameras']] + if kind != 'director.storyboard.append': + stored = storyboard_issue(stage['shots'], stage['duration'], camera_ids, object_id=payload.documentId) + if stored is not None: + raise stored + shots_by_id = {shot['id']: shot for shot in stage['shots']} + if kind == 'director.storyboard.reorder': + if len(payload.blockIds) != len(shots_by_id) or set(payload.blockIds) != shots_by_id.keys(): + raise storyboard_rejection('storyboard_order_invalid', payload.documentId) + shots = [shots_by_id[identity] for identity in payload.blockIds] + elif kind == 'director.storyboard.delete': + if payload.blockId not in shots_by_id: + raise storyboard_rejection('storyboard_block_unknown', payload.documentId) + shots = delete_storyboard_blocks(stage['shots'], {payload.blockId}) + elif kind == 'director.camera.delete': + if payload.cameraId not in camera_ids: + raise storyboard_rejection('director_camera_unknown', payload.documentId) + if len(camera_ids) == 1: + raise storyboard_rejection('director_camera_required', payload.documentId) + removed = {shot['id'] for shot in stage['shots'] if shot['cameraId'] == payload.cameraId} + shots = delete_storyboard_blocks(stage['shots'], removed) + camera_ids.remove(payload.cameraId) + else: + if payload.blockId not in shots_by_id: + raise storyboard_rejection('storyboard_block_unknown', payload.documentId) + # Reject grossly oversized input before multiplying in normalization. + if payload.duration > stage['duration'] + 0.001: + raise storyboard_rejection('storyboard_exceeds_duration', payload.documentId) + if payload.duration < 0.0005: + raise storyboard_rejection('storyboard_duration_invalid', payload.documentId) + shots_by_id[payload.blockId] = { + **shots_by_id[payload.blockId], 'duration': normalize_storyboard_time(payload.duration)} + shots = shots_by_id.values() + packed = pack_storyboard(shots) + issue = storyboard_issue(packed, stage['duration'], camera_ids, object_id=payload.documentId) + if issue is not None: + raise issue + stage['shots'] = packed + if kind == 'director.camera.delete': + stage['cameras'] = [camera for camera in stage['cameras'] if camera['id'] != payload.cameraId] + if stage['activeCameraId'] not in camera_ids: + stage['activeCameraId'] = camera_ids[0] + if not packed and stage['cameraSource'] == 'storyboard': + stage['cameraSource'] = 'camera' + stage['activeCameraId'] = camera_ids[0] + return + if payload.cameraId not in camera_ids: + raise storyboard_rejection('storyboard_camera_unknown', payload.documentId) + # The payload contract already requires a non-blank identity; the service keeps + # the rule itself so an internal caller cannot append an unnamed block. + if not payload.blockId.strip(): + raise storyboard_rejection('storyboard_block_invalid', payload.documentId) + if any(shot['id'] == payload.blockId for shot in stage['shots']): + raise storyboard_rejection('storyboard_block_exists', payload.documentId) + # A stored track that is not continuous is reported as it is, never repaired by appending to it. + stored = storyboard_issue(stage['shots'], stage['duration'], camera_ids, object_id=payload.documentId) + if stored is not None: + raise stored + placement = appended_block(stage['shots'], stage['duration']) + if placement is None: + raise storyboard_rejection('storyboard_exhausted', payload.documentId) + shots = [*stage['shots'], + dict(id=payload.blockId, cameraId=payload.cameraId, start=placement[0], duration=placement[1])] + issue = storyboard_issue(shots, stage['duration'], camera_ids, object_id=payload.documentId) + if issue is not None: + raise issue + stage['shots'] = shots elif kind == 'canvas.show': obj = payload.item.model_dump(mode='json') if str(obj['projectId']) != str(data['project']['id']): @@ -862,6 +1036,15 @@ def query_snapshot(self, query): if query.type == 'asset.usage': assets = [a for a in snapshot.assets if query.objectId is None or a.id == query.objectId] return [history.usage(snapshot, a.id) for a in assets[query.offset:query.offset+query.limit]] + if query.type == 'director.storyboard.get': + document = next((doc for doc in snapshot.editorDocuments if doc.id == query.objectId), None) + if document is None: + raise ContractError('missing_object', '业务对象不存在。', query.objectId) + if document.kind != 'director': + raise ContractError('role_restricted', '只有 Director Stage 文档包含分镜。', query.objectId) + return storyboard_state( + document.id, document.revision, [shot.model_dump(mode='json') for shot in document.data.shots], + document.data.duration, [camera.id for camera in document.data.cameras]) snapshots = [snapshot] if query.revision is None else [record.snapshot for record in self.projects.history(query.projectId)] for state in snapshots: for (kind, object_id), value in object_index(state).items(): diff --git a/packages/core/src/opendirector/application/creation_history.py b/packages/core/src/opendirector/application/creation_history.py index abf3ef9f8..1b7a1a879 100644 --- a/packages/core/src/opendirector/application/creation_history.py +++ b/packages/core/src/opendirector/application/creation_history.py @@ -16,7 +16,7 @@ ABSENT = object() UNDOABLE = {'canvas.createGeneration', 'creation.batch', 'canvas.show', 'canvas.hide', 'canvas.move', 'canvas.update', 'canvas.configure', 'canvas.materialize', 'canvas.applyEdit', 'timeline.publishRender', 'canvas.publishMedia', 'canvas.applyVersion', 'canvas.attachEditor', 'canvas.detachEditor', 'generationSpec.update', 'generationSpec.restore', - 'reference.add', 'reference.update', 'reference.restore', 'reference.remove', 'result.select', 'editor.save', 'generationSpec.setPrompt'} + 'reference.add', 'reference.update', 'reference.restore', 'reference.remove', 'result.select', 'editor.save', 'director.apply', 'director.storyboard.append', 'director.storyboard.reorder', 'director.storyboard.resize', 'director.storyboard.delete', 'director.camera.delete', 'director.duration.set', 'generationSpec.setPrompt'} class Preview(Contract): @@ -257,6 +257,11 @@ def _validate_editor_locks(before, data): owner = binding.get('objectRef') if binding['role'] == 'editor' else None if (owner and owner['id'] in changed) or any(editor['id'] in changed for editor in item.get('editors', [])): CreationCanvas._editable(current, item['id']) + previous_docs = {str(doc.id): doc.model_dump(mode='json') for doc in before.editorDocuments} + for document in data['editorDocuments']: + old = previous_docs.get(document['id']) + if old and old.get('kind') == 'director' and old != document: + CreationCanvas._validate_director_locks(old, document) def version_counts(self, project_id): # Counting only reads snapshots; copying every record here made the diff --git a/packages/core/src/opendirector/application/creation_media_publication.py b/packages/core/src/opendirector/application/creation_media_publication.py index b8c729395..47fcec82f 100644 --- a/packages/core/src/opendirector/application/creation_media_publication.py +++ b/packages/core/src/opendirector/application/creation_media_publication.py @@ -1,12 +1,63 @@ """Atomic publication of browser-produced media with a fixed editing basis.""" +from math import ceil, isclose + from pydantic import TypeAdapter from opendirector.domain.creation.canvas import CanvasItem +from opendirector.domain.creation.director_output import DirectorOutputPlan +from opendirector.domain.creation.storyboard import storyboard_end, storyboard_issue from opendirector.domain.creation.project import ProjectSnapshot, asset_references from opendirector.domain.creation.validation import ContractError from .creation_canvas import current_asset, asset_ref +DIRECTOR_ASPECTS = { + '16:9': (16, 9), + '2.39:1': (2.39, 1), + '9:16': (9, 16), + '1:1': (1, 1), + '4:3': (4, 3), + '3:4': (3, 4), +} + + +def _director_plan_duration(doc, plan: DirectorOutputPlan): + if plan.cameraSource == 'storyboard': + if plan.cameraId is not None or not doc.data.shots: + raise ContractError( + 'invalid_input', + '导演预演的分镜执行计划无效。 The Director storyboard execution plan is invalid.', + doc.id, + ) + shots = [shot.model_dump() for shot in doc.data.shots] + issue = storyboard_issue(shots, doc.data.duration, [camera.id for camera in doc.data.cameras], object_id=doc.id) + if issue is not None: + raise issue + expected_duration = storyboard_end(shots) + else: + if plan.cameraId is None or not any(camera.id == plan.cameraId for camera in doc.data.cameras): + raise ContractError( + 'invalid_input', + '导演预演引用了不存在的机位。 The Director execution plan references an unknown camera.', + doc.id, + ) + expected_duration = doc.data.duration + width_ratio, height_ratio = DIRECTOR_ASPECTS[doc.data.aspectRatio] + if not isclose(plan.width / plan.height, width_ratio / height_ratio, rel_tol=0.002, abs_tol=0.002): + raise ContractError( + 'invalid_input', + '导演预演输出尺寸与舞台比例不一致。 The Director output size does not match the stage aspect ratio.', + doc.id, + ) + if not isclose(plan.durationSeconds, expected_duration, abs_tol=1e-6): + raise ContractError( + 'invalid_input', + '导演预演执行时长与舞台计划不一致。 The Director execution duration does not match the frozen plan.', + doc.id, + ) + return expected_duration + + def publish_media(service, data, payload): item = service._editable(data, payload.itemId) snapshot = ProjectSnapshot.model_validate(data) @@ -16,13 +67,36 @@ def publish_media(service, data, payload): raise ContractError('invalid_input', '编辑执行快照必须使用新的工程内身份。', doc.id) if doc.inputConnections: raise ContractError('invalid_input', '编辑输出不能伪造装配关系。', doc.id) + history = service.projects.history(snapshot.project.id) + director_evidence = None if doc.kind == 'director': if owner.kind != 'external' or owner.binding.role != 'editor' or owner.binding.objectRef.id != payload.sourceEditorId: raise ContractError('reference_invalid', '导演预演来源已变化。', owner.id) original = next(d for d in snapshot.editorDocuments if d.id == payload.sourceEditorId) if original.kind != 'director' or original.data != doc.data or payload.source is not None: raise ContractError('revision_conflict', '预演输出与已确认的舞台版本不一致。', owner.id) - allowed, sources = {'video'}, [] + # Videos render the whole preview; images flow the pinned stills. + allowed, sources = {'video', 'image'}, [] + director_duration = None + if payload.directorPlan is not None: + director_duration = _director_plan_duration(doc, payload.directorPlan) + accepted_cursor = payload.directorAcceptedAt or snapshot.eventCursor + accepted = snapshot if accepted_cursor == snapshot.eventCursor else next( + (record.snapshot for record in history if record.snapshot.eventCursor == accepted_cursor), None) + if accepted is None or original not in accepted.editorDocuments or owner not in accepted.canvasItems: + raise ContractError( + 'revision_conflict', + '导演预演来源与接受版本不一致。 The Director source differs from the accepted version.', + owner.id, + ) + director_evidence = dict(acceptedProjectCursor=accepted_cursor, sourceEditorId=original.id, + sourceEditorRevision=original.revision, plan=payload.directorPlan) + elif any(output.asset.kind == 'video' for output in payload.outputs): + raise ContractError( + 'invalid_input', + '导演视频发布缺少冻结的输出计划。 Director video publication requires a frozen output plan.', + doc.id, + ) else: actual = current_asset(snapshot, owner) if not actual or payload.source != asset_ref(actual) or doc.data.sourceItems != (owner.id,) or doc.data.sources != (payload.source,): @@ -47,7 +121,7 @@ def publish_media(service, data, payload): raise ContractError('invalid_input', '编辑操作与来源媒体类型不匹配。', actual.id) sources = list(asset_references(doc)) used = {r.assetId for r in asset_references(snapshot)} - historical = {r.assetId for record in service.projects.history(snapshot.project.id) for r in asset_references(record.snapshot)} + historical = {r.assetId for record in history for r in asset_references(record.snapshot)} for ref in sources: service._available(service.assets._reference(snapshot, ref)) for output in payload.outputs: @@ -55,13 +129,66 @@ def publish_media(service, data, payload): if asset.kind not in allowed or asset.provenance.source != 'upload' or asset.id in used | historical: raise ContractError('role_restricted', '输出必须是尚未发布且类型匹配的真实素材。', asset.id) service._available(asset) - if doc.kind == 'director' and (asset.metadata.durationSeconds is None or abs(asset.metadata.durationSeconds - doc.data.duration) > .15): - raise ContractError('invalid_input', '预演视频实际时长与执行快照不一致。', asset.id) + # Verify the actual render matches the frozen plan before publishing it. + if doc.kind == 'director' and asset.kind == 'video': + plan = payload.directorPlan + if plan is None or director_duration is None: + raise ContractError( + 'invalid_input', + '导演视频发布缺少冻结的输出计划。 Director video publication requires a frozen output plan.', + asset.id, + ) + if (asset.metadata.width, asset.metadata.height) != (plan.width, plan.height): + raise ContractError( + 'invalid_input', + '预演视频实际尺寸与执行计划不一致。 The preview video dimensions do not match the execution plan.', + asset.id, + ) + # The probe reports average FPS. A shortened final Storyboard frame + # keeps the requested cadence but raises the whole-file average. + expected_fps = plan.frameRate + fps_tolerance = 0.01 + storyboard = plan.cameraSource == 'storyboard' + if storyboard: + expected_frames = ceil(round(director_duration * 1000) * plan.frameRate / 1000) + expected_fps = expected_frames / director_duration + # The MP4 track timebase can represent the end to within 10 microseconds. + fps_tolerance = max(fps_tolerance, expected_fps * 0.00001 / (director_duration - 0.00001)) + if asset.metadata.frameCount not in {None, expected_frames}: + raise ContractError( + 'invalid_input', + '预演视频实际帧数与执行计划不一致。 The preview video frame count does not match the execution plan.', + asset.id, + ) + if asset.metadata.frameRate is None or not isclose( + asset.metadata.frameRate, expected_fps, rel_tol=0, abs_tol=fps_tolerance + ): + raise ContractError( + 'invalid_input', + '预演视频实际帧率与执行计划不一致。 The preview video frame rate does not match the execution plan.', + asset.id, + ) + tolerance = 0.00002 if storyboard else 0.15 + if asset.metadata.durationSeconds is None or not isclose( + asset.metadata.durationSeconds, director_duration, rel_tol=0, abs_tol=tolerance + ): + raise ContractError( + 'invalid_input', + '预演视频实际时长与执行计划不一致。 The preview video duration does not match the execution plan.', + asset.id, + ) + # An image output must be the very bytes of a still this document + # pinned; a re-import keeps the asset identity fresh but the + # content fingerprint identical. + if doc.kind == 'director' and asset.kind == 'image' and all(still.fingerprint != asset.fingerprint for still in doc.data.stills): + raise ContractError('invalid_input', '图片输出必须是舞台已入库的定格。 Image outputs must be a still this stage pinned.', asset.id) if any(i['id'] == str(output.itemId) for i in data['canvasItems']): raise ContractError('invalid_input', '输出节点身份已存在。', output.itemId) record = service._get(data, 'asset', asset.id) record['provenance'] = dict(source='rendered' if doc.kind == 'director' else 'edited', sourceItemId=str(owner.id), editorDocumentId=str(doc.id), editorRevision=1, sources=[r.model_dump(mode='json') for r in dict((r.assetId, r) for r in sources).values()]) + if doc.kind == 'director' and asset.kind == 'video': + record['provenance']['directorRender'] = director_evidence result = TypeAdapter(CanvasItem).validate_python(dict(id=output.itemId, projectId=snapshot.project.id, kind=asset.kind, title=output.title, position=output.position, width=output.width, height=output.height, binding=dict(role='material', objectRef=output.asset))) data['canvasItems'].append(result.model_dump(mode='json')) diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 72771a219..1ad721e02 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -41,7 +41,8 @@ "generation": "Submit a configured generation task.", "result": "Select a generated result for adoption.", "editor": "Create and save editable media documents.", - "timeline": "Discover resources for editable timelines.", + "director": "Apply authoritative Director Stage documents.", + "timeline": "Discover timeline resources and publish rendered timeline results as project media.", "history": "Undo or redo reversible project operations.", "creation": "Apply multiple project operations atomically.", } diff --git a/packages/core/src/opendirector/domain/creation/assets.py b/packages/core/src/opendirector/domain/creation/assets.py index 5a40ca928..98976c615 100644 --- a/packages/core/src/opendirector/domain/creation/assets.py +++ b/packages/core/src/opendirector/domain/creation/assets.py @@ -6,6 +6,7 @@ from opendirector.domain.rule_facts import PROMPT_MAX_LENGTH from .base import Contract, Fingerprint, MediaKind, NonNegative, Positive, PositiveInt, ProjectEntity, Revision +from .director_output import DirectorRenderEvidence from .models import ModelSnapshot @@ -23,9 +24,13 @@ class MediaMetadata(Contract): height: PositiveInt | None = Field(default=None, description='Height in pixels.') durationSeconds: Positive | None = Field(default=None, description='Duration in seconds.') frameRate: Positive | None = Field(default=None, description='Video frames per second.') + frameCount: PositiveInt | None = Field(default=None, exclude_if=lambda value: value is None, + description='Number of video frames reported by the media container.') hasAudio: bool | None = Field(default=None, description='Whether the media contains an audio stream.') sampleRate: PositiveInt | None = Field(default=None, description='Audio samples per second.') channels: PositiveInt | None = Field(default=None, description='Audio channel count.') + selfContained: bool | None = Field(default=None, description='Whether a model container embeds all its buffers and images.') + animationNames: tuple[str, ...] | None = Field(default=None, description='Animation clip names declared by a parsed model container, in document order.') @model_validator(mode='after') def dimensions(self): @@ -60,6 +65,8 @@ class AssetProvenance(Contract): sourceItemId: UUID | None = Field(default=None, description='Source canvas item ID.') editorDocumentId: UUID | None = Field(default=None, description='Editable document ID.') editorRevision: Revision | None = Field(default=None, description='Expected editable document revision.') + directorRender: DirectorRenderEvidence | None = Field(default=None, exclude_if=lambda value: value is None, + description='Frozen Director video output evidence and source version.') sources: tuple[AssetRef, ...] = Field(default=(), description='Ordered source asset versions.') inputFingerprint: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$', description='Fingerprint of the fixed execution input.') agentRunId: UUID | None = Field(default=None, description='Agent turn ID.') @@ -79,6 +86,8 @@ def evidence(self): if self.source == 'agent_written' and (self.agentRunId is None or not ((self.modelSnapshot is not None and self.modelSnapshot.kind == 'agent') or self.agentRuntime is not None)): raise ValueError('Agent-written documents require a run and an agent model or native runtime') + if self.directorRender is not None and self.source != 'rendered': + raise ValueError('Only rendered assets carry Director output evidence') if self.source in {'edited', 'rendered'} and (self.editorDocumentId is None or self.editorRevision is None): raise ValueError('Edited outputs require their source document version') if (self.editorDocumentId is None) != (self.editorRevision is None): diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index d806f6029..7777386de 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -5,11 +5,13 @@ from pydantic import ConfigDict, Field, TypeAdapter, create_model, model_validator from .assets import AssetRef, MediaMetadata -from .base import Contract, Digest, GenerationKind, MediaKind, ObjectVersion, Point, Positive, Revision, digest, unique +from .base import Contract, Digest, GenerationKind, Identifier, MediaKind, NonNegative, ObjectVersion, Point, Positive, PositiveInt, Revision, digest, unique from .canvas import CanvasItem -from .editors import EditorDocument +from .editors import DirectorDocument, DirectorDocumentWrite, EditorDocument, EditorDocumentWrite from opendirector.domain.rule_facts import PROMPT_MAX_LENGTH +from opendirector.domain.storyboard_errors import StoryboardIssueCode from .generation import GenerationSpec, Job, PromptPart, Reference +from .director_output import DirectorOutputPlan class ProjectCreate(Contract): @@ -150,6 +152,9 @@ class CanvasPublishMedia(Contract): source: AssetRef | None = Field(default=None, description='Input source or recorded provenance.') sourceEditorId: UUID | None = Field(default=None, description='Source editable document ID.') document: EditorDocument = Field(description='Editable document owned by this operation.') + directorPlan: DirectorOutputPlan | None = Field(default=None, description='Frozen Director video output plan, when publishing a stage video.') + directorAcceptedAt: PositiveInt | None = Field(default=None, exclude_if=lambda value: value is None, + description='Project event cursor fixed when the browser accepted a Director video render.') outputs: tuple[MediaPublicationOutput, ...] = Field(min_length=1, max_length=50, description='Ordered published media outputs.') @model_validator(mode='after') @@ -158,6 +163,15 @@ def distinct_outputs(self): unique([output.asset.assetId for output in self.outputs], 'output asset IDs') if self.document.kind not in {'media_edit', 'director'}: raise ValueError('Local publication requires a media edit or director snapshot') + has_director_video = self.document.kind == 'director' and any( + output.asset.kind == 'video' for output in self.outputs + ) + if has_director_video and self.directorPlan is None: + raise ValueError('Director video publications require a frozen output plan. 导演视频发布需要冻结的输出计划。') + if self.directorAcceptedAt is not None and self.directorPlan is None: + raise ValueError('An accepted Director version requires an output plan. 导演预演接受版本需要输出计划。') + if self.document.kind != 'director' and self.directorPlan is not None: + raise ValueError('Only Director publications can carry an output plan. 只有导演发布才能携带输出计划。') return self @@ -236,7 +250,87 @@ class ResultSelect(Contract): class EditorWrite(Contract): - document: EditorDocument = Field(description='Editable document owned by this operation.') + document: EditorDocumentWrite = Field(description='Editable document owned by this operation.') + + +class DirectorApply(Contract): + document: DirectorDocumentWrite = Field(description='Authoritative Director Stage document applied atomically.') + + +class DirectorStoryboardAppend(Contract): + documentId: UUID = Field(description='Director Stage document that receives the Storyboard block.') + cameraId: Identifier = Field(description='Existing stage camera the new block references.') + blockId: Identifier = Field(description='Stable identity of the new Storyboard block; it must not be in use.') + + +class DirectorCameraDelete(Contract): + documentId: UUID = Field(description='Director Stage document that owns the camera.') + cameraId: Identifier = Field(description='Camera to delete with its Storyboard blocks.') + + +class DirectorStoryboardDelete(Contract): + documentId: UUID = Field(description='Director Stage document that owns the Storyboard.') + blockId: Identifier = Field(description='Storyboard block to delete.') + + +class DirectorStoryboardReorder(Contract): + documentId: UUID = Field(description='Director Stage document that owns the Storyboard.') + blockIds: tuple[Identifier, ...] = Field(description='Every Storyboard block ID exactly once, in the desired order.') + + +class DirectorStoryboardResize(Contract): + documentId: UUID = Field(description='Director Stage document that owns the Storyboard.') + blockId: Identifier = Field(description='Block that owns the boundary on its right.') + duration: Annotated[float, Field(strict=True, allow_inf_nan=False)] = Field( + description='New duration of that block in seconds; must leave the Storyboard continuous and within the timeline.') + + +class DirectorStoryboardBlock(Contract): + id: Identifier = Field(description='Stable block identity.') + cameraId: Identifier = Field(description='Stage camera the block references.') + order: Annotated[int, Field(strict=True, ge=0)] = Field(description='Position in the stored Storyboard, starting at zero.') + start: NonNegative = Field(description='Block start in seconds, as stored.') + duration: Positive = Field(description='Block duration in seconds, as stored.') + + +class DirectorSetDuration(Contract): + documentId: UUID = Field(description='Director Stage document whose main timeline will change.') + duration: Positive = Field(description='Requested main timeline duration in seconds.') + + +class DirectorDurationResult(Contract): + documentId: UUID = Field(description='Director Stage document whose main timeline was evaluated.') + requestedDuration: Positive = Field(description='Main timeline duration requested in seconds.') + appliedDuration: Positive = Field(description='Main timeline duration applied in seconds.') + clampReason: Literal['storyboard_end'] | None = Field(description='Stable reason for a limited duration, or null.') + + +class DirectorStoryboardState(Contract): + documentId: UUID = Field(description='Director Stage document that owns the Storyboard.') + version: Revision = Field(description='Current revision of the Director Stage document.') + storyboardEnd: NonNegative = Field(description='End of the last block in seconds; zero when the Storyboard is empty.') + canAppend: bool = Field(description='Whether a block can be appended in the main-timeline time that remains.') + cannotAppendReason: StoryboardIssueCode | None = Field(default=None, description='Stable reason no block can be appended; null when one can.') + blocks: tuple[DirectorStoryboardBlock, ...] = Field(description='Storyboard blocks in stored order, reported as stored.') + + +DirectorStoryboardOperation = Literal[ + 'director.storyboard.append', 'director.storyboard.reorder', 'director.storyboard.resize', + 'director.storyboard.delete', 'director.camera.delete', 'director.duration.set', +] + + +class DirectorStoryboardResult(Contract): + operationIndex: Annotated[int, Field(strict=True, ge=0)] = Field(description='Zero-based position in the command or batch.') + operation: DirectorStoryboardOperation = Field(description='Storyboard or related operation evaluated.') + documentId: UUID = Field(description='Director Stage document that owns the Storyboard.') + version: Revision = Field(description='Committed document revision for the enclosing transaction.') + blocks: tuple[DirectorStoryboardBlock, ...] = Field(description='Block identities, order and stored times after this operation, before subsequent batch operations.') + affectedBlockIds: tuple[Identifier, ...] = Field(description='New or changed surviving block IDs, in resulting order.') + removedBlockIds: tuple[Identifier, ...] = Field(description='Removed block IDs, in their previous order.') + blockId: Identifier | None = Field(default=None, description='Block explicitly targeted by the operation, when applicable.') + cameraId: Identifier | None = Field(default=None, description='Camera explicitly targeted by the operation, when applicable.') + appendLimitReason: Literal['storyboard_tail'] | None = Field(default=None, description='Stable reason a new block is shorter than the default duration, or null.') class HistoryReplay(Contract): @@ -272,9 +366,9 @@ def scope_and_versions(self): raise ValueError('Submission version differs from expected spec version') if self.type == 'timeline.publishRender' and payload.expectedOutputRevision is not None and versions[('canvas_item', payload.outputId)] != payload.expectedOutputRevision: raise ValueError('Output revision differs from its expected version') - if self.type in {'generationSpec.update', 'editor.save', 'reference.update', 'reference.restore'}: + if self.type in {'generationSpec.update', 'editor.save', 'director.apply', 'reference.update', 'reference.restore'}: obj = (payload.spec if self.type == 'generationSpec.update' else - payload.document if self.type == 'editor.save' else payload.reference) + payload.document if self.type in {'editor.save', 'director.apply'} else payload.reference) if versions[required[0]] != obj.revision: raise ValueError('Payload version differs from its expected version') return self @@ -283,7 +377,13 @@ def scope_and_versions(self): def required_versions(self) -> list[tuple[str, UUID]]: payload = self.payload required = [] - if self.type in {'project.rename', 'project.trash', 'project.restore'}: + if self.type == 'creation.batch': + created = {op.payload.document.id for op in payload.operations if op.type == 'editor.create'} + required = list(dict.fromkeys( + ('editor_document', op.payload.documentId) for op in payload.operations + if op.type in {'director.storyboard.reorder', 'director.storyboard.resize', 'director.storyboard.delete', 'director.camera.delete', 'director.duration.set'} + and op.payload.documentId not in created)) + elif self.type in {'project.rename', 'project.trash', 'project.restore'}: required = [('project', self.projectId)] elif self.type == 'canvas.publishMedia': required = [('canvas_item', payload.itemId), *[('asset', o.asset.assetId) for o in payload.outputs]] @@ -315,6 +415,10 @@ def required_versions(self) -> list[tuple[str, UUID]]: required = [('generation_spec', payload.specId)] elif self.type == 'editor.save': required = [('editor_document', payload.document.id)] + elif self.type == 'director.apply': + required = [('editor_document', payload.document.id)] + elif self.type in {'director.storyboard.append', 'director.storyboard.reorder', 'director.storyboard.resize', 'director.storyboard.delete', 'director.camera.delete', 'director.duration.set'}: + required = [('editor_document', payload.documentId)] return required @@ -357,6 +461,13 @@ def required_versions(self) -> list[tuple[str, UUID]]: ('ResultSelectCommand', 'result.select', ResultSelect, 'Adopt an existing generation result.'), ('EditorCreateCommand', 'editor.create', EditorWrite, 'Create an editable document.'), ('EditorSaveCommand', 'editor.save', EditorWrite, 'Save an editable document.'), + ('DirectorApplyCommand', 'director.apply', DirectorApply, 'Apply an authoritative Director Stage document atomically.'), + ('DirectorStoryboardAppendCommand', 'director.storyboard.append', DirectorStoryboardAppend, 'Append an existing camera to the end of the continuous Director Stage Storyboard.'), + ('DirectorStoryboardReorderCommand', 'director.storyboard.reorder', DirectorStoryboardReorder, 'Reorder the continuous Storyboard by block ID, preserving durations and camera references.'), + ('DirectorStoryboardResizeCommand', 'director.storyboard.resize', DirectorStoryboardResize, 'Resize the given block and shift all subsequent blocks, preserving their durations.'), + ('DirectorStoryboardDeleteCommand', 'director.storyboard.delete', DirectorStoryboardDelete, 'Delete a Storyboard block and shift later blocks without changing their durations.'), + ('DirectorSetDurationCommand', 'director.duration.set', DirectorSetDuration, 'Set the Director Stage main timeline duration, preserving the Storyboard and animation.'), + ('DirectorCameraDeleteCommand', 'director.camera.delete', DirectorCameraDelete, 'Delete a non-final Director Stage camera and its Storyboard blocks atomically.'), ('HistoryUndoCommand', 'history.undo', HistoryReplay, 'Undo a recorded reversible command.'), ('HistoryRedoCommand', 'history.redo', HistoryReplay, 'Reapply an undone command.'), ) @@ -369,7 +480,8 @@ def required_versions(self) -> list[tuple[str, UUID]]: _BATCH_TYPES = {'canvas.show', 'canvas.move', 'canvas.update', 'canvas.hide', 'canvas.materialize', 'canvas.applyEdit', 'canvas.configure', 'canvas.attachEditor', 'canvas.detachEditor', 'generationSpec.create', 'generationSpec.update', - 'reference.add', 'reference.update', 'reference.restore', 'reference.remove', 'editor.create', 'editor.save', 'result.select', 'generationSpec.setPrompt'} + 'reference.add', 'reference.update', 'reference.restore', 'reference.remove', 'editor.create', 'editor.save', 'director.apply', 'director.storyboard.reorder', 'director.storyboard.resize', 'director.storyboard.delete', 'director.camera.delete', 'director.duration.set', + 'result.select', 'generationSpec.setPrompt'} _OPERATIONS = tuple(create_model(name + 'Operation', __base__=Contract, __doc__=description, type=(Literal[kind], Field(description='Operation discriminator.')), payload=(payload, Field(description=description))) @@ -401,7 +513,7 @@ def command_fingerprint(command: Command) -> str: from opendirector.domain.timeline_errors import TimelineIssueCode -IssueCode = Literal[TimelineIssueCode, 'invalid_input', 'revision_conflict', 'role_restricted', 'missing_object', 'reference_invalid', 'image_quality_unsupported', +IssueCode = Literal[TimelineIssueCode, StoryboardIssueCode, 'invalid_input', 'revision_conflict', 'role_restricted', 'missing_object', 'reference_invalid', 'image_quality_unsupported', 'bigmodel_video_model', 'bigmodel_video_output', 'bigmodel_video_image', 'bigmodel_video_frames', 'bigmodel_video_prompt', 'bigmodel_video_cancel', 'kling_model', 'kling_mode', 'kling_image', 'kling_frames', 'kling_prompt', 'kling_aspect', 'kling_output', 'kling_cancel', @@ -435,12 +547,14 @@ class CommandReceipt(Contract): changed: tuple[ObjectVersion, ...] = Field(default=(), description='Business objects changed by the operation.') jobIds: tuple[UUID, ...] = Field(default=(), description='Generation jobs associated with this operation.') issues: tuple[ContractIssue, ...] = Field(default=(), description='Validation or execution issues.') + directorDurations: tuple[DirectorDurationResult, ...] = Field(default=(), exclude_if=lambda value: not value, description='Director main timeline results in operation order.') + directorStoryboard: tuple[DirectorStoryboardResult, ...] = Field(default=(), exclude_if=lambda value: not value, description='Storyboard outcomes in command operation order.') eventCursor: int | None = Field(default=None, strict=True, ge=0, description='Latest committed project event cursor.') @model_validator(mode='after') def outcome(self): unique(self.jobIds, 'receipt job IDs') - if self.status == 'rejected' and (self.changed or self.jobIds or not self.issues): + if self.status == 'rejected' and (self.changed or self.jobIds or self.directorStoryboard or not self.issues): raise ValueError('Rejected commands need issues and cannot claim changes') if self.status == 'accepted' and not self.jobIds: raise ValueError('Accepted background work needs a task receipt') @@ -494,8 +608,13 @@ class AssetPreviewQuery(QueryBase): objectId: UUID = Field(description='Asset ID.') +class DirectorStoryboardQuery(QueryBase): + type: Literal['director.storyboard.get'] = Field(description='Read the stored Director Stage Storyboard and whether a block can be appended.') + objectId: UUID = Field(description='Director Stage document ID.') + + Query = Annotated[ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | - CanvasStatusQuery | AssetPreviewQuery, Field(discriminator='type')] + CanvasStatusQuery | AssetPreviewQuery | DirectorStoryboardQuery, Field(discriminator='type')] class ChangedObject(Contract): diff --git a/packages/core/src/opendirector/domain/creation/director_output.py b/packages/core/src/opendirector/domain/creation/director_output.py new file mode 100644 index 000000000..b035fe74e --- /dev/null +++ b/packages/core/src/opendirector/domain/creation/director_output.py @@ -0,0 +1,31 @@ +"""Fixed Director render inputs recorded with the published asset.""" +from typing import Literal +from uuid import UUID + +from pydantic import Field, model_validator + +from .base import Contract, Identifier, Positive, PositiveInt, Revision + + +class DirectorOutputPlan(Contract): + cameraSource: Literal['camera', 'storyboard'] = Field(description='Camera selection strategy fixed for this render.') + cameraId: Identifier | None = Field(default=None, description='Camera rig fixed for a camera render; omitted for storyboard renders.') + width: PositiveInt = Field(description='Expected output width in pixels.') + height: PositiveInt = Field(description='Expected output height in pixels.') + durationSeconds: Positive = Field(description='Expected output duration in seconds.') + frameRate: Positive = Field(description='Expected output frames per second.') + + @model_validator(mode='after') + def camera_selection(self): + if self.cameraSource == 'camera' and self.cameraId is None: + raise ValueError('Camera renders require a camera ID. 相机渲染需要相机 ID。') + if self.cameraSource == 'storyboard' and self.cameraId is not None: + raise ValueError('Storyboard renders cannot select a camera ID. 分镜渲染不能选择相机 ID。') + return self + + +class DirectorRenderEvidence(Contract): + acceptedProjectCursor: PositiveInt = Field(description='Event cursor of the accepted project snapshot.') + sourceEditorId: UUID = Field(description='Editable Director Stage document fixed at acceptance.') + sourceEditorRevision: Revision = Field(description='Source stage revision fixed at acceptance.') + plan: DirectorOutputPlan = Field(description='The accepted camera strategy, output size, duration and frame rate.') diff --git a/packages/core/src/opendirector/domain/creation/editors.py b/packages/core/src/opendirector/domain/creation/editors.py index aff5bdfbe..91098e806 100644 --- a/packages/core/src/opendirector/domain/creation/editors.py +++ b/packages/core/src/opendirector/domain/creation/editors.py @@ -1,9 +1,10 @@ """Typed retained editors. AssetRef replaces transient src/data/blob URLs.""" from math import ceil, floor, isfinite +import re from typing import Annotated, Literal from uuid import UUID -from pydantic import Field, StrictBool, StrictFloat, StrictInt, StrictStr, field_validator, model_validator +from pydantic import ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr, field_validator, model_validator from opendirector.domain.rule_facts import ( TIMELINE_FONT_LIMIT, TIMELINE_OVERLAY_LIMIT, TIMELINE_TEXT_MAX_LENGTH, TIMELINE_TEXT_TOTAL_LENGTH, @@ -12,7 +13,7 @@ from .assets import AssetRef from .base import Contract, Identifier, NonNegative, Number, Point, Positive, PositiveInt, ProjectEntity, unique -Color = Annotated[str, Field(pattern=r'^#[0-9a-fA-F]{6}$')] +Color = Annotated[str, Field(pattern=r'^#[0-9a-fA-F]{6}$', examples=['#000000'])] Unit = Annotated[float, Field(strict=True, ge=0, le=1)] @@ -357,10 +358,23 @@ def positive_scale(self): return self +class StageBezierTransition(Contract): + kind: Literal['bezier'] = Field(description='Cubic Bezier interpolation for the outgoing segment.') + controlPoints: tuple[Unit, Unit, Unit, Unit] = Field(description='Normalized x1, y1, x2 and y2 control points.') + + +class StageTransformTransitions(Contract): + position: StageBezierTransition | None = Field(default=None, description='Outgoing position interpolation.') + rotation: StageBezierTransition | None = Field(default=None, description='Outgoing rotation interpolation.') + scale: StageBezierTransition | None = Field(default=None, description='Outgoing scale interpolation.') + + class TransformFrame(Contract): id: Identifier = Field(description='Stable object ID.') time: NonNegative = Field(description='Keyframe time in seconds.') value: StageTransform = Field(description='Keyframed transform or camera pose.') + keyedChannels: tuple[Literal['position', 'rotation', 'scale'], ...] | None = Field(default=None, description='Transform properties explicitly keyed at this frame.') + transitions: StageTransformTransitions | None = Field(default=None, description='Per-property interpolation for the outgoing segment.') class StageMotion(Contract): @@ -378,17 +392,68 @@ class MotionClip(Contract): class StageObject(StageTransform): id: Identifier = Field(description='Stable object ID.') - kind: Literal['person', 'box', 'sphere'] = Field(description='Business object or media type.') + kind: Literal['person', 'box', 'sphere', 'gltf', 'cylinder', 'cone', 'pyramid', 'torus', 'plane', 'capsule', 'disk', 'arc', 'halfCylinder'] = Field(description='Business object or media type.') name: str = Field(max_length=255, description='User-visible name.') color: Color = Field(description='Serialized display color.') + visible: StrictBool = Field(default=True, description='Whether this object is displayed.') + locked: StrictBool = Field(default=False, description='Whether edits to this object are blocked.') + opacity: Unit = Field(default=1, description='Layer opacity from zero to one.') keyframes: tuple[TransformFrame, ...] = Field(default=(), description='Ordered animation keyframes.') motionClips: tuple[MotionClip, ...] = Field(default=(), description='Ordered procedural motion intervals.') + asset: AssetRef | None = Field(default=None, description='Registered GLB or self-contained GLTF asset for an imported stage object.') + thumbnailAsset: AssetRef | None = Field(default=None, description='Registered image asset used by the stage object card thumbnail.') + role: Literal['character', 'scene'] | None = Field(default=None, description='Imported stage object role.') + format: Literal['glb', 'gltf'] | None = Field(default=None, description='Imported stage asset container format.') + animationNames: tuple[str, ...] = Field(default=(), description='Animation clip names discovered in the imported asset.') + hasAnimation: bool = Field(default=False, description='Whether the imported asset contains animation clips.') + + @model_validator(mode='after') + def imported_asset(self): + imported_fields = (self.asset, self.role, self.format) + if self.animationNames and any(not name.strip() for name in self.animationNames): + raise ValueError('Imported animation names cannot be blank. 导入的动画名称不能为空。') + if self.kind == 'gltf': + if self.asset is None or self.role is None or self.format is None: + raise ValueError( + 'Imported stage objects require a registered asset, role and format. ' + '导入的舞台对象需要已注册的素材、角色和格式。' + ) + if self.asset.kind != 'file': + raise ValueError('Imported stage assets must be file assets. 导入的舞台素材必须是文件素材。') + if self.role == 'scene' and self.motionClips: + raise ValueError('Scene assets cannot have character motion clips. 场景素材不能携带角色动作片段。') + if not self.hasAnimation and self.motionClips: + raise ValueError( + 'Imported characters without animation cannot have motion clips. ' + '没有动画数据的导入人物不能携带动作片段。' + ) + if self.hasAnimation != bool(self.animationNames): + raise ValueError( + 'Imported animation metadata must match animation names. ' + '导入的动画信息必须与动画名称一致。' + ) + elif any(value is not None for value in imported_fields) or self.animationNames or self.hasAnimation: + raise ValueError( + 'Procedural stage objects cannot carry imported asset metadata. ' + '非导入的舞台对象不能携带导入素材信息。' + ) + if self.thumbnailAsset is not None and self.thumbnailAsset.kind != 'image': + raise ValueError('Stage thumbnails must be image assets. 舞台缩略图必须是图片素材。') + return self class StageCamera(Contract): + model_config = ConfigDict(json_schema_extra={'examples': [{ + 'position': {'x': 0, 'y': 0, 'z': 1}, + 'target': {'x': 0, 'y': 0, 'z': 0}, + 'fov': 45, + 'roll': 0, + }]}) + position: Vector3 = Field(description='Position in the owning canvas or stage.') target: Vector3 = Field(description='Camera look-at position.') fov: Annotated[float, Field(strict=True, gt=0, lt=180)] = Field(description='Camera vertical field of view in degrees.') + roll: Annotated[float, Field(strict=True, ge=-3.141592653589793, le=3.141592653589793)] = Field(default=0.0, description='Roll around the view axis in radians.') @model_validator(mode='after') def direction(self): @@ -403,11 +468,58 @@ class CameraFrame(Contract): value: StageCamera = Field(description='Keyframed transform or camera pose.') +class CameraVectorFrame(Contract): + id: Identifier = Field(description='Stable channel keyframe ID.') + time: NonNegative = Field(description='Keyframe time in seconds.') + value: Vector3 = Field(description='Keyframed camera vector.') + transition: StageBezierTransition | None = Field(default=None, description='Interpolation for the outgoing segment.') + + +class CameraNumberFrame(Contract): + id: Identifier = Field(description='Stable channel keyframe ID.') + time: NonNegative = Field(description='Keyframe time in seconds.') + value: Annotated[float, Field(strict=True, gt=0)] = Field(description='Keyframed camera focal length.') + transition: StageBezierTransition | None = Field(default=None, description='Interpolation for the outgoing segment.') + + +class CameraChannels(Contract): + position: tuple[CameraVectorFrame, ...] = Field(default=(), description='Independent camera position channel.') + target: tuple[CameraVectorFrame, ...] = Field(default=(), description='Independent camera target channel.') + up: tuple[CameraVectorFrame, ...] = Field(default=(), description='Independent camera up-vector channel.') + focalLength: tuple[CameraNumberFrame, ...] = Field(default=(), description='Independent camera focal-length channel.') + + class CameraRig(Contract): id: Identifier = Field(description='Stable object ID.') name: str = Field(max_length=255, description='User-visible name.') + aspectRatio: Literal['16:9', '2.39:1', '9:16', '1:1', '4:3', '3:4'] = Field(default='16:9', description='Camera output aspect ratio.') pose: StageCamera = Field(description='Camera position and look-at target.') keyframes: tuple[CameraFrame, ...] = Field(default=(), description='Ordered animation keyframes.') + channels: CameraChannels = Field(default_factory=CameraChannels, description='Independent authoritative camera channels.') + + @model_validator(mode='before') + @classmethod + def migrate_legacy_keyframes(cls, value): + if not isinstance(value, dict) or value.get('channels') is not None: + return value + frames = value.get('keyframes') or () + if any( + not isinstance(frame, dict) + or not isinstance(frame.get('value'), dict) + or not {'id', 'time'} <= set(frame) + or not {'position', 'target', 'fov'} <= set(frame.get('value', {})) + for frame in frames + ): + return value + return { + **value, + 'channels': { + 'position': [dict(id=f['id'], time=f['time'], value=f['value']['position']) for f in frames], + 'target': [dict(id=f['id'], time=f['time'], value=f['value']['target']) for f in frames], + 'up': [dict(id=f['id'], time=f['time'], value={'x': 0, 'y': 1, 'z': 0}) for f in frames], + 'focalLength': [dict(id=f['id'], time=f['time'], value=f['value']['fov']) for f in frames], + }, + } class StageShot(Contract): @@ -417,17 +529,96 @@ class StageShot(Contract): duration: Positive = Field(description='Interval duration in seconds.') -def check_frames(frames, duration): +class StageEnvironment(Contract): + """The named environment used by the retained Director scene.""" + preset: Literal['studio', 'warm-sunset', 'moonlit'] = Field(default='studio', description='Environment preset reference. 环境预设引用。') + groundColor: Color = Field(default='#181818', description='Ground plane color. 地面颜色。') + groundVisible: StrictBool = Field(default=True, description='Whether the ground plane is visible. 是否显示地面。') + exposure: Annotated[float, Field(strict=True, ge=0, le=4)] = Field(default=1.0, description='Scene exposure from zero to four. 场景曝光范围为 0 到 4。') + backgroundAsset: AssetRef | None = Field(default=None, description='Optional registered image asset used as the stage background. 可选的已登记图片背景素材。') + + @model_validator(mode='after') + def background_asset(self): + if self.backgroundAsset and self.backgroundAsset.kind != 'image': + raise ValueError('Stage background assets must be image assets. 舞台背景素材必须是图片素材。') + return self + + @field_validator('preset', mode='before') + @classmethod + def environment_preset(cls, value): + if value not in {'studio', 'warm-sunset', 'moonlit'}: + raise ValueError('Environment preset must be studio, warm-sunset or moonlit. 环境预设必须是 studio、warm-sunset 或 moonlit。') + return value + + @field_validator('exposure', mode='before') + @classmethod + def environment_exposure(cls, value): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value) or not 0 <= value <= 4: + raise ValueError('Environment exposure must be between 0 and 4. 场景曝光必须在 0 到 4 之间。') + return value + + +class StageLight(Contract): + id: Literal['hemisphere', 'key', 'fill'] = Field(description='Stable light role. 稳定灯光角色。') + color: Color = Field(description='Light color in #RRGGBB format. 灯光颜色。') + intensity: Annotated[float, Field(strict=True, ge=0, le=10)] = Field(description='Light intensity from zero to ten. 灯光强度范围为 0 到 10。') + position: Vector3 = Field(description='Light position in stage coordinates. 灯光在舞台坐标中的位置。') + castShadow: StrictBool = Field(default=False, description='Whether the light casts shadows. 是否投射阴影。') + + @field_validator('id', mode='before') + @classmethod + def light_id(cls, value): + if value not in {'hemisphere', 'key', 'fill'}: + raise ValueError('Light role must be hemisphere, key or fill. 灯光角色必须是 hemisphere、key 或 fill。') + return value + + @field_validator('color', mode='before') + @classmethod + def light_color(cls, value): + if not isinstance(value, str) or re.fullmatch(r'#[0-9a-fA-F]{6}', value) is None: + raise ValueError('Light color must use #RRGGBB. 灯光颜色必须使用 #RRGGBB 格式。') + return value + + @field_validator('intensity', mode='before') + @classmethod + def light_intensity(cls, value): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value) or not 0 <= value <= 10: + raise ValueError('Light intensity must be between 0 and 10. 灯光强度必须在 0 到 10 之间。') + return value + + @field_validator('position', mode='before') + @classmethod + def light_position(cls, value): + if isinstance(value, Vector3): + return value + if not isinstance(value, dict) or any(not isinstance(value.get(axis), (int, float)) or isinstance(value.get(axis), bool) or not isfinite(value[axis]) for axis in ('x', 'y', 'z')): + raise ValueError('Light position must contain finite x, y and z values. 灯光位置必须包含有限的 x、y、z 数值。') + return value + + @model_validator(mode='after') + def role_constraints(self): + if self.id == 'hemisphere' and self.castShadow: + raise ValueError('Hemisphere lights cannot cast shadows. 半球光不能投射阴影。') + return self + + +def default_stage_lights() -> tuple[StageLight, ...]: + return ( + StageLight(id='hemisphere', color='#ffffff', intensity=2.4, position=Vector3(x=0, y=1, z=0)), + StageLight(id='key', color='#ffffff', intensity=3.5, position=Vector3(x=5, y=10, z=6), castShadow=True), + StageLight(id='fill', color='#ffffff', intensity=1.6, position=Vector3(x=-6, y=5, z=-5)), + ) + + +def check_frames(frames): unique([frame.id for frame in frames], 'keyframe IDs') unique([frame.time for frame in frames], 'keyframe times') - if any(frame.time > duration for frame in frames): - raise ValueError('Keyframe exceeds stage duration') -def check_intervals(items, duration): +def check_intervals(items, duration=None): unique([item.id for item in items], 'interval IDs') ordered = sorted(items, key=lambda item: item.start) - if any(item.start + item.duration > duration + 1e-8 for item in ordered): + if duration is not None and any(item.start + item.duration > duration + 1e-8 for item in ordered): raise ValueError('Interval exceeds stage duration') if any(a.start + a.duration > b.start + 1e-8 for a, b in zip(ordered, ordered[1:])): raise ValueError('Stage intervals cannot overlap') @@ -437,30 +628,83 @@ class DirectorData(Contract): background: Color = Field(description='Composition background color.') grid: bool = Field(default=True, description='Whether to display the stage grid.') duration: Positive = Field(description='Interval duration in seconds.') - aspectRatio: Literal['16:9', '9:16', '1:1', '4:3', '3:4'] = Field(default='16:9', description='Output width-to-height ratio.') + fps: Literal[24, 25, 30, 50, 60] = Field(default=30, description='Frames per second. 帧率。') + aspectRatio: Literal['16:9', '2.39:1', '9:16', '1:1', '4:3', '3:4'] = Field(default='16:9', description='Output width-to-height ratio.') cameras: tuple[CameraRig, ...] = Field(min_length=1, description='Editable stage cameras.') activeCameraId: Identifier = Field(description='Active stage camera ID.') cameraSource: Literal['camera', 'storyboard'] = Field(default='camera', description='Camera selection strategy.') shots: tuple[StageShot, ...] = Field(default=(), description='Ordered camera shot intervals.') objects: tuple[StageObject, ...] = Field(default=(), description='Editable stage objects.') + environment: StageEnvironment = Field(default_factory=StageEnvironment, description='Authoritative environment reference and ground configuration. 权威环境引用和地面配置。') + lights: tuple[StageLight, ...] = Field(default_factory=default_stage_lights, min_length=3, max_length=3, description='The three retained stage lights. 舞台保留的三盏灯光。') + stills: tuple[AssetRef, ...] = Field(default=(), description='Captured still frames pinned as project image assets, oldest first.') + + @field_validator('fps', mode='before') + @classmethod + def stage_fps(cls, value): + if isinstance(value, bool) or not isinstance(value, int) or value not in {24, 25, 30, 50, 60}: + raise ValueError('Stage FPS must be one of 24, 25, 30, 50 or 60. 舞台帧率必须是 24、25、30、50 或 60。') + return value @model_validator(mode='after') def stage_relations(self): camera_ids = [camera.id for camera in self.cameras] unique(camera_ids, 'camera IDs') unique([obj.id for obj in self.objects], 'stage object IDs') - if self.activeCameraId not in camera_ids or any(shot.cameraId not in camera_ids for shot in self.shots): + light_ids = [light.id for light in self.lights] + if set(light_ids) != {'hemisphere', 'key', 'fill'}: + raise ValueError('Stage lights must contain exactly one hemisphere, key and fill light. 舞台灯光必须各包含一盏半球光、主光和辅光。') + # One asset can back at most one drawer entry; the read path keys + # drawer items by assetId. + unique([still.assetId for still in self.stills], 'stage still asset IDs') + if self.activeCameraId not in camera_ids: raise ValueError('Stage references an unknown camera') - check_intervals(self.shots, self.duration) - if self.cameraSource == 'storyboard' and not self.shots: - raise ValueError('Local camera-shot playback needs shots') + self.check_storyboard(camera_ids) + # A duration edit changes the playback window. Animation outside it remains authored. for camera in self.cameras: - check_frames(camera.keyframes, self.duration) + check_frames(camera.keyframes) + for channel in (camera.channels.position, camera.channels.target, camera.channels.up, camera.channels.focalLength): + check_frames(channel) for obj in self.objects: - check_frames(obj.keyframes, self.duration) - check_intervals(obj.motionClips, self.duration) + check_frames(obj.keyframes) + check_intervals(obj.motionClips) return self + def check_storyboard(self, camera_ids): + """Shot relations of a stored Director Stage document. + + A document entering through a command defers them (see ``DirectorDataWrite``): + the write boundary checks the Storyboard once, on millisecond-normalized times + and with a stable issue code, before the stored model validates the result. + """ + if any(shot.cameraId not in camera_ids for shot in self.shots): + raise ValueError('Stage references an unknown camera') + from .storyboard import storyboard_issue + + # A continuous Storyboard uses millisecond boundaries. Legacy tracks + # that fail continuity can still load under the original interval rules. + shots = [shot.model_dump() for shot in self.shots] + if storyboard_issue(shots, self.duration, camera_ids) is not None: + check_intervals(self.shots, self.duration) + if any(shot.start + shot.duration > self.duration + 1e-8 for shot in self.shots): + raise ValueError('Interval exceeds stage duration') + if self.cameraSource == 'storyboard' and not self.shots: + raise ValueError('Local camera-shot playback needs shots') + + +class DirectorDataWrite(DirectorData): + """A Director Stage document entering the project through a command. + + It has the same fields and dump as the stored ``DirectorData``. Shot relations are + not checked while the command is parsed: both HTTP and Agent entry points parse the + payload before the application service runs, so checking here would reject the write + with a generic code before the write boundary could report the specific one. The + stored model still validates the committed snapshot as the last line of defence. + """ + + def check_storyboard(self, camera_ids): + return None + class ToolSelection(Contract): source: AssetRef = Field(description='Input source or recorded provenance.') @@ -630,6 +874,11 @@ class DirectorDocument(EditorDocumentBase): data: DirectorData = Field(description='Typed editable document contents.') +class DirectorDocumentWrite(EditorDocumentBase): + kind: Literal['director'] = Field(description='Business object or media type.') + data: DirectorDataWrite = Field(description='Typed editable document contents.') + + class MediaEditDocument(EditorDocumentBase): kind: Literal['media_edit'] = Field(description='Business object or media type.') data: MediaEditData = Field(description='Typed editable document contents.') @@ -637,3 +886,6 @@ class MediaEditDocument(EditorDocumentBase): EditorDocument = Annotated[TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument, Field(discriminator='kind')] +# Documents entering the project through editor.create, editor.save and director.apply. +EditorDocumentWrite = Annotated[TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | + ToolDocument | DirectorDocumentWrite | MediaEditDocument, Field(discriminator='kind')] diff --git a/packages/core/src/opendirector/domain/creation/project.py b/packages/core/src/opendirector/domain/creation/project.py index 8f089c182..ed001b0e6 100644 --- a/packages/core/src/opendirector/domain/creation/project.py +++ b/packages/core/src/opendirector/domain/creation/project.py @@ -7,10 +7,12 @@ from .assets import Asset, AssetRef from .base import Contract, NonNegative, ObjectVersion, Point, ProjectEntity, Revision, unique from .canvas import CanvasItem, EditorBinding, GenerationBinding, MaterialBinding, MediaCanvasItem -from .editors import EditorDocument, MediaEditDocument, LayerDocument, StackDocument, SubjectDocument, TimelineDocument +from .editors import DirectorDocument, EditorDocument, MediaEditDocument, LayerDocument, StackDocument, SubjectDocument, TimelineDocument from .generation import FollowingReference, GenerationSpec, Job, PromptReference, Reference, ResultVersion from ..rule_facts import TIMELINE_DURATION_EPSILON +STAGE_MODEL_MIME = {'glb': 'model/gltf-binary', 'gltf': 'model/gltf+json'} + class Project(Contract): id: UUID = Field(description='Stable object ID.') @@ -81,7 +83,7 @@ def project_relations(self): for ref in asset_references(objects): asset = assets.get(ref.assetId) if asset is None or ref.revision > asset.revision or ref.fingerprint != asset.fingerprint or ref.kind != asset.kind: - raise ValueError('Missing or inconsistent pinned asset reference') + raise ValueError('Missing or inconsistent pinned asset reference. 缺失或不一致的固定素材引用。') parents = {} for item in self.canvasItems: if item.parentId: @@ -208,6 +210,20 @@ def project_relations(self): duration = asset.metadata.durationSeconds if asset.kind != 'image' and duration is not None and clip.outPoint > duration + TIMELINE_DURATION_EPSILON: raise ValueError('时间线片段超过素材的实际时长。') + if isinstance(doc, DirectorDocument): + for obj in doc.data.objects: + if obj.kind == 'gltf': + asset = assets[obj.asset.assetId] + if asset.metadata.mimeType != STAGE_MODEL_MIME[obj.format] or asset.metadata.selfContained is not True: + raise ValueError('Imported stage objects require a matching self-contained GLB or GLTF asset. 导入的舞台对象需要匹配的自包含 GLB 或 GLTF 素材。') + # Animation metadata is attested by the client; verify it + # against the names the pinned bytes actually declare. + names = asset.metadata.animationNames or () + if tuple(obj.animationNames) != names or obj.hasAnimation != bool(names): + raise ValueError('Imported animation metadata must match the pinned asset bytes. 导入的动画信息必须与固定素材的实际字节一致。') + for still in doc.data.stills: + if assets[still.assetId].kind != 'image': + raise ValueError('Captured stage stills must pin image assets. 舞台定格必须固定为图片素材。') return self diff --git a/packages/core/src/opendirector/domain/creation/storyboard.py b/packages/core/src/opendirector/domain/creation/storyboard.py new file mode 100644 index 000000000..e19073429 --- /dev/null +++ b/packages/core/src/opendirector/domain/creation/storyboard.py @@ -0,0 +1,144 @@ +"""The continuous Director Stage Storyboard rule: one implementation for every entry point. + +A Storyboard is a single exclusive camera-cut track. It starts at 0, every block starts +where the previous one ends, durations are positive, and its end never passes the main +timeline. These functions are pure: the application write boundary calls them when a +Director Stage document enters or changes project state, and the read model calls them +to report a stored track. Nothing here sorts, compacts or repairs the blocks it is given. +""" +from decimal import Decimal +from math import floor, isfinite +from uuid import UUID + +from opendirector.domain.creation.commands import DirectorStoryboardBlock, DirectorStoryboardState +from opendirector.domain.creation.validation import ContractError +from opendirector.domain.storyboard_errors import STORYBOARD_MESSAGES, StoryboardIssueCode + +# The stored interval checks use this tolerance; the guard judges against the same line +# so a document it accepts is never rejected later by the model. +STORYBOARD_TIME_TOLERANCE = 1e-8 +# Duration of an appended block when at least this much main-timeline time remains. +STORYBOARD_DEFAULT_SECONDS = 2.0 + + +def normalize_storyboard_time(value: float) -> float: + """Seconds rounded to milliseconds: half toward positive infinity, as JavaScript's Math.round. + + Both runtimes first form the same double ``value * 1000``. Rounding that exact value + with decimals avoids Python's banker's ``round``, which sends 1000.5 down to 1000 + where JavaScript sends it up to 1001. + """ + scaled = value * 1000 + return floor(Decimal(scaled) + Decimal(0.5)) / 1000 if isfinite(scaled) else value + + +def storyboard_rejection(code: StoryboardIssueCode, object_id: UUID | None = None, + index: int | None = None) -> ContractError: + """A rejection carrying the Chinese catalog copy; the presentation boundary selects the language by code.""" + return ContractError(code, STORYBOARD_MESSAGES[code][0], object_id, + field=None if index is None else f'data.shots.{index}') + + +def storyboard_issue(shots, duration, camera_ids, *, object_id: UUID | None = None) -> ContractError | None: + """The first continuity violation of a shot list, or None when the list is continuous. + + ``shots`` is read in stored order and never changed. Times are judged after + millisecond normalization, so float noise is neither a gap nor an overlap and a + duration that rounds to nothing is not positive. The caller decides whether a + returned issue rejects a write or is reported for a stored track. + """ + camera_ids = set(camera_ids) + identities: set[str] = set() + previous_end = 0.0 + for index, shot in enumerate(shots): + identity = shot['id'] + if identity in identities: + return storyboard_rejection('storyboard_block_exists', object_id, index) + identities.add(identity) + if shot['cameraId'] not in camera_ids: + return storyboard_rejection('storyboard_camera_unknown', object_id, index) + start = normalize_storyboard_time(shot['start']) + span = normalize_storyboard_time(shot['duration']) + if span <= 0: + return storyboard_rejection('storyboard_duration_invalid', object_id, index) + if index == 0 and start != 0: + return storyboard_rejection('storyboard_leading_gap', object_id, index) + if start > previous_end: + return storyboard_rejection('storyboard_internal_gap', object_id, index) + if start < previous_end: + return storyboard_rejection('storyboard_overlap', object_id, index) + end = normalize_storyboard_time(start + span) + if end - duration > STORYBOARD_TIME_TOLERANCE: + return storyboard_rejection('storyboard_exceeds_duration', object_id, index) + previous_end = end + return None + + +def pack_storyboard(shots): + """Place consecutive blocks from zero, preserving identities and stored durations.""" + start = 0.0 + packed = [] + for shot in shots: + packed.append({**shot, 'start': start}) + start = normalize_storyboard_time(start + normalize_storyboard_time(shot['duration'])) + return packed + + +def delete_storyboard_blocks(shots, block_ids): + """Remove blocks in stored time order; packing applies the cumulative ripple.""" + return (shot for shot in shots if shot['id'] not in block_ids) + + +def storyboard_end(shots): + if not shots: + return 0.0 + last = shots[-1] + return normalize_storyboard_time(normalize_storyboard_time(last['start']) + normalize_storyboard_time(last['duration'])) + + +def appended_block(shots, duration): + """Start and duration of the block appended to a continuous shot list. + + Returns None when no positive usable time remains. A block lasts + ``STORYBOARD_DEFAULT_SECONDS`` and takes all of the remaining time when less than + that is left. The remainder is normalized first, because the block is stored in + milliseconds; when rounding it up would run past a main duration that itself has + sub-millisecond precision, the block gives one millisecond back instead of + exceeding the main timeline. + """ + start = storyboard_end(shots) + remaining = duration - start + span = normalize_storyboard_time(remaining) + if remaining <= 0 or span <= 0: + return None + span = min(STORYBOARD_DEFAULT_SECONDS, span) + if span - remaining > STORYBOARD_TIME_TOLERANCE: + span = normalize_storyboard_time(span - 0.001) + if span <= 0: + return None + return start, span + + +def storyboard_blocks(shots) -> tuple[DirectorStoryboardBlock, ...]: + return tuple(DirectorStoryboardBlock(order=index, **shot) for index, shot in enumerate(shots)) + + +def storyboard_state(document_id, version, shots, duration, camera_ids) -> DirectorStoryboardState: + """The Storyboard of one stored document, reported exactly as stored. + + Blocks are listed in stored order with their stored times; nothing is sorted, compacted + or normalized here. ``canAppend`` is False with the stable reason when the stored track + is not continuous or no positive usable time remains. + """ + issue = storyboard_issue(shots, duration, camera_ids, object_id=document_id) + if issue is not None: + reason = issue.issue.code + elif appended_block(shots, duration) is None: + reason = 'storyboard_exhausted' + else: + reason = None + return DirectorStoryboardState( + documentId=document_id, version=version, + storyboardEnd=storyboard_end(shots), + canAppend=reason is None, cannotAppendReason=reason, + blocks=storyboard_blocks(shots)) diff --git a/packages/core/src/opendirector/domain/creation/validation.py b/packages/core/src/opendirector/domain/creation/validation.py index 8a3a7af9f..0e5bf9408 100644 --- a/packages/core/src/opendirector/domain/creation/validation.py +++ b/packages/core/src/opendirector/domain/creation/validation.py @@ -10,9 +10,9 @@ class ContractError(ValueError): - def __init__(self, code, message, object_id=None): + def __init__(self, code, message, object_id=None, *, field=None): super().__init__(message) - self.issue = ContractIssue(code=code, message=message, objectId=object_id) + self.issue = ContractIssue(code=code, message=message, objectId=object_id, field=field) @classmethod def from_error(cls, error: ValueError | ProjectError, object_id: UUID | None = None) -> 'ContractError': @@ -99,7 +99,9 @@ def get(kind, object_id): if command.type == 'reference.update': if get('reference', payload.reference.id).targetSpecId != payload.reference.targetSpecId: raise ContractError('invalid_input', 'A reference cannot be moved to another generation spec', payload.reference.id) - if command.type == 'editor.save': + if command.type in {'editor.save', 'director.apply'}: current = get('editor_document', payload.document.id) if current.kind != payload.document.kind: raise ContractError('invalid_input', 'Editor document kind cannot change', current.id) + if command.type == 'director.apply' and current.kind != 'director': + raise ContractError('role_restricted', 'director.apply 只能保存 Director Stage 文档。 director.apply only accepts Director Stage documents.', current.id) diff --git a/packages/core/src/opendirector/domain/language.py b/packages/core/src/opendirector/domain/language.py new file mode 100644 index 000000000..a3b6ac088 --- /dev/null +++ b/packages/core/src/opendirector/domain/language.py @@ -0,0 +1,15 @@ +"""Which language a caller reads, as far as the interface is concerned. + +The rule is the one the interface documents: a `zh*` language tag is Chinese and every +other tag is English. It lives in the domain so a code-keyed catalog and the HTTP +boundary cannot drift into two different decisions about the same request. +""" + + +def wants_english_language(value: str | None) -> bool: + """Judge the primary language tag, matching the browser decision. No tag is not English.""" + value = (value or "").strip() + if not value: + return False + primary = value.split(",", 1)[0].split(";", 1)[0].strip().lower() + return not primary.startswith("zh") diff --git a/packages/core/src/opendirector/domain/storyboard_errors.py b/packages/core/src/opendirector/domain/storyboard_errors.py new file mode 100644 index 000000000..0016f92e3 --- /dev/null +++ b/packages/core/src/opendirector/domain/storyboard_errors.py @@ -0,0 +1,90 @@ +"""Stable Director Stage Storyboard diagnostics shared by business and presentation boundaries. + +Every Storyboard rejection carries one code from this catalog. The write boundary +raises the Chinese copy for CLI and Agent traces; the HTTP boundary selects the +caller's language from the same code, so wording never becomes business identity +and one message never carries two languages. +""" +from typing import Literal + +from opendirector.domain.language import wants_english_language + +StoryboardIssueCode = Literal[ + 'storyboard_leading_gap', + 'storyboard_internal_gap', + 'storyboard_overlap', + 'storyboard_exceeds_duration', + 'storyboard_duration_invalid', + 'storyboard_camera_unknown', + 'storyboard_block_invalid', + 'storyboard_block_exists', + 'storyboard_exhausted', + 'storyboard_order_invalid', + 'storyboard_block_unknown', + 'director_camera_unknown', + 'director_camera_required', +] + +# Display copy is selected by code; business identity never depends on wording. +STORYBOARD_MESSAGES = { + 'director_camera_unknown': ( + '要删除的机位不存在。', + 'The camera to delete could not be found.', + ), + 'director_camera_required': ( + '至少保留一个机位。', + 'Keep at least one camera.', + ), + 'storyboard_leading_gap': ( + '分镜必须从 0 秒开始,第一个分镜块之前不能留空。', + 'The Storyboard must start at 0; the first block cannot begin later.', + ), + 'storyboard_internal_gap': ( + '分镜块之间不能留有空隙,请让每个分镜块从前一个分镜块结束的位置开始。', + 'Storyboard blocks cannot leave gaps; start each block where the previous one ends.', + ), + 'storyboard_overlap': ( + '分镜块之间不能重叠,请让每个分镜块从前一个分镜块结束的位置开始。', + 'Storyboard blocks cannot overlap; start each block where the previous one ends.', + ), + 'storyboard_exceeds_duration': ( + '分镜的结束时间不能超过主时间轴时长,请缩短分镜块或延长主时间轴。', + 'The Storyboard cannot end after the main timeline; shorten the blocks or lengthen the main timeline.', + ), + 'storyboard_duration_invalid': ( + '每个分镜块的时长都必须大于 0,请延长该分镜块。', + 'Every Storyboard block needs a duration greater than 0; lengthen this block.', + ), + 'storyboard_camera_unknown': ( + '分镜块引用的机位不存在,请选择已有机位。', + 'A Storyboard block references a camera that does not exist; choose an existing camera.', + ), + 'storyboard_block_invalid': ( + '分镜块标识不能为空。', + 'A Storyboard block needs a non-empty identity.', + ), + 'storyboard_block_exists': ( + '该分镜块标识已被使用,请换一个标识。', + 'This Storyboard block identity is already in use; choose another one.', + ), + 'storyboard_block_unknown': ( + '要编辑的分镜块不存在。', + 'The Storyboard block to edit could not be found.', + ), + 'storyboard_order_invalid': ( + '请在目标顺序中为每个分镜块提供且仅提供一个标识。', + 'Include each Storyboard block ID exactly once in the desired order.', + ), + 'storyboard_exhausted': ( + '主时间轴已没有可用时长,无法再添加分镜块。', + 'No main-timeline time remains for another Storyboard block.', + ), +} + + +def storyboard_error_message(code: str, language: str | None) -> str | None: + messages = STORYBOARD_MESSAGES.get(code) + if messages is None: + return None + # One decision for the whole HTTP boundary: `zh*` is Chinese, anything else English. + return messages[1 if wants_english_language(language) else 0] diff --git a/packages/core/src/opendirector/infrastructure/creation_publication.py b/packages/core/src/opendirector/infrastructure/creation_publication.py index a43ec088a..9627dd6f9 100644 --- a/packages/core/src/opendirector/infrastructure/creation_publication.py +++ b/packages/core/src/opendirector/infrastructure/creation_publication.py @@ -42,7 +42,7 @@ def replay(self, command): def commit(self, command: Command, apply: Callable[[ProjectSnapshot], ProjectSnapshot] | Callable[[ProjectSnapshot, tuple[CommitRecord, ...]], ProjectSnapshot], *, - session=None, source='ui', files=(), deletes=(), with_history=False): + session=None, source='ui', files=(), deletes=(), with_history=False, director_durations=(), director_storyboard=()): if source not in {'ui', 'agent', 'background', 'external'}: raise ProjectError('无效的命令来源。') self._await_current_warm(command.projectId) @@ -89,21 +89,23 @@ def commit(self, command: Command, snapshot, changed = before, [] elif changed: snapshot = ProjectSnapshot.model_validate({**snapshot.model_dump(), 'eventCursor': before.eventCursor + 1}) - record = self._make_record(command, manifest.head, snapshot, changed, source, issue) + record = self._make_record(command, manifest.head, snapshot, changed, source, issue, director_durations, director_storyboard) to_name = snapshot.project.name if command.type == 'project.rename' and changed else path.name return self._publish(CommitIntent(fromName=path.name, toName=to_name, beforeFingerprint=digest(before), record=record, files=files if changed and issue is None else (), deletes=deletes if changed and issue is None else ()), validated_history=True) @staticmethod - def _make_record(command, head, snapshot, changed, source, issue=None): + def _make_record(command, head, snapshot, changed, source, issue=None, director_durations=(), director_storyboard=()): job_ids = tuple(item['version'].id for item in changed if item['version'].objectType == 'job' and item['change'] == 'created' and next(job for job in snapshot.jobs if job.id == item['version'].id).status == 'queued') event = ProjectEvent(projectId=command.projectId, cursor=snapshot.eventCursor, commandId=command.commandId, source=source, changed=changed, jobIds=job_ids) if changed else None receipt = CommandReceipt(commandId=command.commandId, projectId=command.projectId, inputFingerprint=command_fingerprint(command), status='rejected' if issue else 'accepted' if job_ids else 'applied' if changed else 'noop', - changed=[item['version'] for item in changed], jobIds=job_ids, issues=[issue] if issue else [], eventCursor=snapshot.eventCursor) + changed=[item['version'] for item in changed], jobIds=job_ids, issues=[issue] if issue else [], + directorDurations=() if issue else director_durations, + directorStoryboard=() if issue else director_storyboard, eventCursor=snapshot.eventCursor) return CommitRecord(command=command, previousHead=head, snapshot=snapshot, receipt=receipt, event=event) def _journal(self, project_id): diff --git a/packages/core/src/opendirector/infrastructure/creation_uploads.py b/packages/core/src/opendirector/infrastructure/creation_uploads.py index c7c435a4a..1410beb50 100644 --- a/packages/core/src/opendirector/infrastructure/creation_uploads.py +++ b/packages/core/src/opendirector/infrastructure/creation_uploads.py @@ -1,5 +1,6 @@ """Project/session-scoped streaming staging; no project facts before commit.""" import hashlib +import json import os from pathlib import Path import tempfile @@ -14,7 +15,7 @@ from opendirector.domain.creation.base import Contract, Fingerprint, MediaKind from opendirector.domain.projects import ProjectError from opendirector.infrastructure.creation_files import file_identity, upload_directory -from opendirector.ports.files import MAX_CREATION_ASSET_BYTES, MAX_CREATION_TEXT_BYTES +from opendirector.ports.files import MAX_CREATION_ASSET_BYTES, MAX_STAGE_MODEL_BYTES, MAX_CREATION_TEXT_BYTES from opendirector.infrastructure.creation_projects import directory, durable_json, sync_directory from opendirector.infrastructure.local_projects import child, read_json from opendirector.infrastructure.rename import rename_path @@ -30,10 +31,30 @@ def asset_name(value): return value +STAGE_MODEL_TOO_LARGE = '舞台模型文件应不超过 100 MiB,与浏览器导入上限一致。Stage model files must not exceed 100 MiB, matching the browser import limit.' + + def upload_asset_id(project_id, handle): return uuid5(UUID(str(project_id)), 'upload:' + str(handle)) +def _has_external_gltf_resources(document): + entries = [entry for key in ('buffers', 'images') if isinstance(document.get(key), list) for entry in document[key]] + return any(isinstance(entry, dict) and isinstance(entry.get('uri'), str) and not entry['uri'].startswith('data:') + for entry in entries) + + +def _gltf_animation_names(document): + """Names must match what a browser loader derives: declared names + trimmed, unnamed clips falling back to animation_{index}.""" + animations = document.get('animations') + if not isinstance(animations, list): + return () + return tuple((entry.get('name') if isinstance(entry, dict) and isinstance(entry.get('name'), str) else '').strip() + or f'animation_{index}' + for index, entry in enumerate(animations)) + + class UploadOwner(Contract): projectId: UUID = Field(description='Owning project ID.') id: UUID = Field(description='Stable object ID.') @@ -69,7 +90,9 @@ def inspect_file(path: Path, name: str, *, expected_kind=None): raise ProjectError('文件包含非文本内容,请导入 UTF-8 文本。') return 'text', MediaMetadata(size=size, mimeType='text/markdown' if suffix == '.md' else 'text/plain') with path.open('rb') as stream: - prefix = stream.read(16) + # Wide enough to skip leading whitespace before a glTF JSON document; + # image and container magic detection needs only the first 12 bytes. + prefix = stream.read(4096) image_bytes = (prefix.startswith((b'\x89PNG\r\n\x1a\n', b'\xff\xd8\xff', b'GIF87a', b'GIF89a')) or prefix.startswith(b'RIFF') and prefix[8:12] == b'WEBP' or heif_type(prefix)) if suffix in {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.heic', '.heif'} or image_bytes or expected_kind == 'image': @@ -103,6 +126,44 @@ def inspect_file(path: Path, name: str, *, expected_kind=None): return kind, MediaMetadata(size=size, mimeType=mime, **value) except ValueError: raise ProjectError('媒体尺寸、时长或音频信息无效,请检查文件。') from None + if prefix.startswith(b'glTF') and size >= 12: + if size > MAX_STAGE_MODEL_BYTES: + raise ProjectError(STAGE_MODEL_TOO_LARGE, 413) + version, total = int.from_bytes(prefix[4:8], 'little'), int.from_bytes(prefix[8:12], 'little') + if version == 2 and 12 <= total <= size: + document = None + with path.open('rb') as stream: + stream.seek(12) + while len(header := stream.read(8)) == 8: + length = int.from_bytes(header[:4], 'little') + payload = stream.read(length) + if len(payload) < length: + break + if header[4:] == b'JSON': + document = payload + break + try: + parsed = json.loads(document) if document is not None else None + except ValueError: + parsed = None + self_contained = (isinstance(parsed, dict) and isinstance(parsed.get('asset'), dict) + and 'version' in parsed['asset'] and not _has_external_gltf_resources(parsed)) + return 'file', MediaMetadata(size=size, mimeType='model/gltf-binary', selfContained=self_contained, + animationNames=_gltf_animation_names(parsed) if isinstance(parsed, dict) else None) + # Stage models are probed as whole JSON documents, so oversized files are + # rejected up front instead of being fully loaded into memory; oversized + # JSON without a .gltf suffix stays a generic file. + if size <= MAX_STAGE_MODEL_BYTES and (prefix.lstrip()[:1] == b'{' or suffix == '.gltf'): + try: + parsed = json.loads(path.read_text(encoding='utf-8-sig')) + except (UnicodeDecodeError, ValueError): + parsed = None + if isinstance(parsed, dict) and isinstance(parsed.get('asset'), dict) and 'version' in parsed['asset']: + return 'file', MediaMetadata(size=size, mimeType='model/gltf+json', + selfContained=not _has_external_gltf_resources(parsed), + animationNames=_gltf_animation_names(parsed)) + elif suffix == '.gltf': + raise ProjectError(STAGE_MODEL_TOO_LARGE, 413) with path.open('rb') as stream: mime = 'application/pdf' if stream.read(5) == b'%PDF-' else 'application/octet-stream' return 'file', MediaMetadata(size=size, mimeType=mime) diff --git a/packages/core/src/opendirector/media/probe.py b/packages/core/src/opendirector/media/probe.py index 3ea8f02fe..198eab1d5 100644 --- a/packages/core/src/opendirector/media/probe.py +++ b/packages/core/src/opendirector/media/probe.py @@ -83,6 +83,8 @@ def probe_file(file: Path, kind: str, *, include_container=False, include_codecs fps = float(numerator) / float(denominator) if float(denominator) else None if fps is not None and (not math.isfinite(fps) or fps < 0): raise ValueError() + if include_container and (count := str(stream.get("nb_frames", ""))).isdigit() and int(count) > 0: + common["frameCount"] = int(count) return {**common, "width": stream["width"], "height": stream["height"], "frameRate": fps or None, "hasAudio": any(item.get("codec_type") == "audio" for item in value["streams"])} return {**common, "sampleRate": int(stream["sample_rate"]), "channels": stream["channels"]} diff --git a/packages/core/src/opendirector/ports/files.py b/packages/core/src/opendirector/ports/files.py index e4ac7026d..2126e634d 100644 --- a/packages/core/src/opendirector/ports/files.py +++ b/packages/core/src/opendirector/ports/files.py @@ -13,6 +13,7 @@ CHUNK_BYTES = 1024 * 1024 MAX_CREATION_ASSET_BYTES = 512 * 1024 * 1024 MAX_CREATION_TEXT_BYTES = 1024 * 1024 +MAX_STAGE_MODEL_BYTES = 100 * 1024 * 1024 class AssetFileWrite(Contract): diff --git a/public/fonts/NunitoSans-Latin.woff2 b/public/fonts/NunitoSans-Latin.woff2 new file mode 100644 index 000000000..4361be683 Binary files /dev/null and b/public/fonts/NunitoSans-Latin.woff2 differ diff --git a/public/fonts/NunitoSans-OFL.txt b/public/fonts/NunitoSans-OFL.txt new file mode 100644 index 000000000..59f596f91 --- /dev/null +++ b/public/fonts/NunitoSans-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2016 The Nunito Sans Project Authors (https://github.com/Fonthausen/NunitoSans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/scripts/check-browser-locale.mjs b/scripts/check-browser-locale.mjs index 3614fd86e..507526662 100644 --- a/scripts/check-browser-locale.mjs +++ b/scripts/check-browser-locale.mjs @@ -6,7 +6,8 @@ * follows the browser language while no preference is stored. A script that * asserts localized text without pinning `locale` therefore passes on one * machine and times out on another (issue #160). Every page states its - * language — through `newPage({ locale })` or through a stored + * language — through `newPage({ locale })` (including a validated environment- + * backed local variable) or through a stored * `opendirector.locale.v1` preference that the app applies before first * paint — and that language must match the selectors the script asserts. * @@ -78,6 +79,14 @@ function newPageCalls(text) { } } +/** Return the fallback locale for a local variable backed by the suite env. */ +function environmentLocale(text, name) { + const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp( + `\\b(?:const|let|var)\\s+${escaped}\\s*=\\s*process\\.env\\.DIRECTOR_STAGE_LOCALE\\s*\\?\\?\\s*["']([^"']+)["']`, + ).exec(text)?.[1]; +} + const names = (await readdir(browserDir)).filter((name) => name.endsWith(".mjs")); const files = [...names.map((name) => join(browserDir, name)), ...extraScripts]; const problems = []; @@ -99,7 +108,12 @@ for (const file of files) { const expected = assertsChinese ? "zh-CN" : "en-US"; for (const call of calls) { checked += 1; - const found = /locale:\s*"([^"]+)"/.exec(call.args)?.[1]; + const literal = /locale:\s*["']([^"']+)["']/.exec(call.args)?.[1]; + const variable = + /locale:\s*([A-Za-z_$][\w$]*)/.exec(call.args)?.[1] ?? + (/\blocale\s*[,}]/.test(call.args) ? "locale" : undefined); + const found = + literal ?? (variable ? environmentLocale(text, variable) : undefined); if (!found) { if (storesLocale) continue; problems.push( diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index d129f2345..9ecc03720 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -37,6 +37,37 @@ const workflows = [ { name: "session lease", script: "tests/browser/session_lease.mjs" }, { name: "mp4 export", script: "tests/browser/mp4_export.mjs" }, { name: "editor save", script: "tests/browser/editor_save.mjs" }, + { + name: "director stage entry", + script: "tests/browser/director_stage_entry.mjs", + }, + { + name: "director stage entry (zh-CN)", + script: "tests/browser/director_stage_entry.mjs", + env: { DIRECTOR_STAGE_LOCALE: "zh-CN" }, + }, + { + name: "director stage gizmo", + script: "tests/browser/director_stage_gizmo.mjs", + }, + { + name: "director stage gizmo (zh-CN)", + script: "tests/browser/director_stage_gizmo.mjs", + env: { DIRECTOR_STAGE_LOCALE: "zh-CN" }, + }, + { + name: "director stage pointer alignment", + script: "tests/browser/director_stage_pointer_alignment.mjs", + }, + { + name: "director stage storyboard", + script: "tests/browser/director_stage_storyboard.mjs", + }, + { + name: "director stage storyboard (zh-CN)", + script: "tests/browser/director_stage_storyboard.mjs", + env: { DIRECTOR_STAGE_LOCALE: "zh-CN" }, + }, { name: "canvas crop", script: "tests/browser/canvas_crop.mjs" }, { name: "canvas text Markdown", script: "tests/browser/canvas_text_markdown.mjs" }, { diff --git a/src/backend/creationClient.ts b/src/backend/creationClient.ts index f2985dcea..82bfb4d31 100644 --- a/src/backend/creationClient.ts +++ b/src/backend/creationClient.ts @@ -87,14 +87,15 @@ export class CreationClient { constructor(id: string) { this.id = id; // This is a transport outbox, not a second job store. A page reload must - // retain the original command ID when a paid submission's reply is lost. + // retain the original command ID when a generation or asset-import reply + // is lost. try { const pending: [string, Record][] = JSON.parse( sessionStorage.getItem(this.deliveryKey()) ?? "[]", ); for (const [intent, body] of pending) if ( - body.type === "generation.submit" && + (body.type === "generation.submit" || body.type === "asset.import") && body.projectId === id && typeof body.commandId === "string" ) @@ -108,8 +109,8 @@ export class CreationClient { } private saveDeliveries() { try { - const pending = [...this.deliveries].filter( - ([, body]) => body.type === "generation.submit", + const pending = [...this.deliveries].filter(([, body]) => + body.type === "generation.submit" || body.type === "asset.import", ); if (pending.length) sessionStorage.setItem(this.deliveryKey(), JSON.stringify(pending)); diff --git a/src/backend/creationEditorSession.ts b/src/backend/creationEditorSession.ts index 8ae4c671d..d0fcd2ac9 100644 --- a/src/backend/creationEditorSession.ts +++ b/src/backend/creationEditorSession.ts @@ -1,6 +1,8 @@ +import type { BatchPayloadInput } from "../contracts/generated.ts"; import type { CanvasDocument, CanvasNodeData } from "../canvas/model.ts"; import { applyCommand } from "../canvas/model.ts"; import { updateStack } from "../canvas/operations.ts"; +import { ApiError } from "./api.ts"; import { CreationClient, CreationCommandError, @@ -68,9 +70,12 @@ export class CreationEditorSession { /* Do not invalidate a business operation on preference failure. */ } } - async apply(data: Partial) { + async apply( + data: Partial, + afterDraft?: BatchPayloadInput["operations"][number], + ) { if (this.active) throw new Error(tNow("errors.backend.editSaving")); - const key = JSON.stringify(data); + const key = JSON.stringify(afterDraft ? { data, afterDraft } : data); const resolvingPrevious = !!this.pending && this.pending.key !== key; this.active = true; try { @@ -101,6 +106,7 @@ export class CreationEditorSession { ) plan.versions.push(version); } + if (afterDraft) plan.operations.push(afterDraft); if (!plan.operations.length) { plan.operations.push({ type: "canvas.update", @@ -155,10 +161,18 @@ export class CreationEditorSession { throw new Error( tNow("errors.backend.priorEditSaved"), ); + return receipt; } catch (error) { // Only a definitive rejection releases the operation. Its version basis // remains unchanged: retrying must not silently overwrite a newer edit. - if (error instanceof CreationCommandError) { + // This session treats these transport-level 4xx statuses as definitive, + // so a delivery refused at the HTTP boundary (for example one prepared + // by an older schema) is not replayed forever from stored state. + if ( + error instanceof CreationCommandError || + (error instanceof ApiError && + [400, 401, 403, 413, 422].includes(error.status ?? 0)) + ) { this.pending = undefined; this.storePending(); } diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index b544ad4bb..858befe13 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -26,10 +26,12 @@ import { type GenerationSettings, } from "../canvas/model.ts"; import { tNow } from "../i18n/messages.ts"; +import { translateNow } from "../canvas/assistantTranslate.ts"; import { createLocalStage, parseLocalStageValue, } from "../canvas/stageDocument.ts"; +import { assertStageStoryboard } from "../canvas/stageStoryboard.ts"; import { mediaBlobDataUrl } from "../canvas/localMediaRuntime.ts"; import { generationContentPatch } from "../canvas/generationReferenceContent.ts"; import { assemblyResource, staleAssembly } from "../canvas/editorAssembly.ts"; @@ -48,10 +50,39 @@ import { import { sameJsonValue } from "./sameJsonValue.ts"; import { classifyImportFile, readEditorResource } from "../canvas/editorMedia.ts"; +/** + * Stage object names are free display text; the backend upload name must + * stay path-free, control-free and within its 255-character limit. The cut + * counts code points, never splitting a surrogate pair. + */ +export function stageUploadTitle(name: string, format: string): string { + const safe = + Array.from(name.replace(/[/\\\u0000-\u001f]+/g, "_").trim()) + .slice(0, 250) + .join("") || tNow("editors.stage.ui.objectGltf"); + return `${safe}.${format}`; +} + /** Every comparison here is over a document that carries its media inline, so * it reads the values instead of serializing both sides to compare strings. */ const same = sameJsonValue; +/** + * A Director Stage enters or changes the project only with a continuous Storyboard. + * + * This is the frontend write boundary for editor.create and director.apply: a + * discontinuous Storyboard is refused with the localized reason before a command exists, + * and the backend validates the same rule again when the command is applied. + */ +function checkDirectorStoryboard(document: EditorDocumentInput): void { + if (document.kind !== "director") return; + // The command payload may omit the block list, which then means none. + assertStageStoryboard( + { ...document.data, shots: document.data.shots ?? [] }, + translateNow, + ); +} + /** Retained links are compared field by field: the snapshot keeps the original * relation, and the server skips a connection whose value did not change. */ function sameConnection( @@ -136,6 +167,9 @@ export class CreationProjection { fileBytes?: boolean; identity?: string; fresh?: boolean; + /** A publication persists this handle before uploading so a reload can + * retry the same staged bytes instead of creating a new asset identity. */ + uploadHandle?: string; previous?: AssetRef; /** Archive provenance: the backend records an imported source instead of * treating the upload as a plain user file. */ @@ -177,7 +211,10 @@ export class CreationProjection { const name = /\.[\w]+$/.test(resource.title) ? resource.title : `${resource.title}.${suffix}`; - const handle = this.importHandles.get(key) ?? crypto.randomUUID(); + const handle = + resource.uploadHandle ?? + this.importHandles.get(key) ?? + crypto.randomUUID(); this.importHandles.set(key, handle); return this.client.importBlob( blob, @@ -398,14 +435,55 @@ export class CreationProjection { }, }; case "director": + { + const objects = await Promise.all( + doc.data.objects.map(async (object) => { + const source = + object.kind === "gltf" && object.asset + ? await this.client + .mediaUrl(object.asset.assetId) + .catch(() => undefined) + : undefined; + const thumbnailSource = object.thumbnailAsset + ? await this.client + .thumbnailUrl(object.thumbnailAsset.assetId) + .catch(() => undefined) + : undefined; + return { + ...object, + ...(source ? { source } : {}), + ...(thumbnailSource ? { thumbnailSource } : {}), + }; + }), + ); + const stills = await Promise.all( + doc.data.stills.map(async (asset) => ({ + // Drawer-local identity; the contract stores the order itself. + id: asset.assetId, + asset, + // Missing media keeps the pinned identity and shows a recoverable + // placeholder instead of failing the whole projection. + src: await this.client + .mediaUrl(asset.assetId) + .catch(() => undefined), + })), + ); return { external: { externalType: "director-stage" }, - localStage: parseLocalStageValue({ - format: "opendirector-local-stage", - version: 2, - ...doc.data, - }), + localStage: parseLocalStageValue( + { + format: "opendirector-local-stage", + version: 2, + ...doc.data, + objects, + }, + translateNow, + ), + stills, + // The newest still is the canvas poster when its preview URL is usable. + ...(stills.at(-1)?.src ? { src: stills.at(-1)!.src } : {}), }; + } case "layers": return { layers: { @@ -622,6 +700,14 @@ export class CreationProjection { // Export records this so an imported generation node can be rebuilt // with real provenance instead of a fabricated one. const evidence = asset.provenance; + // Only director publications mark a stage preview; timeline renders + // share the 'rendered' source but are ordinary composition outputs. + const stagePreviewDoc = + evidence.source === "rendered" && evidence.editorDocumentId + ? snapshot.editorDocuments.find( + (doc) => doc.id === evidence.editorDocumentId, + ) + : undefined; node.data.generationProvenance = { source: evidence.source, ...(evidence.jobId ? { jobId: evidence.jobId } : {}), @@ -634,6 +720,9 @@ export class CreationProjection { ...(evidence.editorRevision != null ? { editorRevision: evidence.editorRevision } : {}), + ...(stagePreviewDoc?.kind === "director" + ? { stagePreview: true } + : {}), }; node.data.media = { width: asset.metadata.width ?? undefined, @@ -1234,12 +1323,93 @@ export class CreationProjection { }; } case "director": { + const stage = parseLocalStageValue( + node.data.localStage ?? createLocalStage(), + translateNow, + ); + const objects = await Promise.all( + stage.objects.map(async (object) => { + const { + source: _source, + asset: _asset, + thumbnailAsset: _thumbnailAsset, + thumbnailCapture, + thumbnailSource: _thumbnailSource, + role: _role, + format: _format, + animationNames: _animationNames, + hasAnimation: _hasAnimation, + ...base + } = object; + const thumbnailAsset = + _thumbnailAsset ?? + (thumbnailCapture + ? await this.importResource({ + kind: "image", + title: `${node.data.title ?? tNow("errors.backend.directorStageTitle")}-${object.name}-thumbnail`, + src: thumbnailCapture, + }) + : undefined); + if (object.kind !== "gltf") + return { + ...base, + ...(thumbnailAsset ? { thumbnailAsset } : {}), + }; + const asset = + object.asset ?? + (object.source + ? await this.importResource({ + kind: "file", + title: stageUploadTitle(object.name, object.format!), + src: object.source, + }) + : undefined); + if (!asset) + throw new Error(tNow("errors.backend.directorAssetMissing")); + return { + ...base, + asset, + ...(thumbnailAsset ? { thumbnailAsset } : {}), + role: object.role, + format: object.format, + animationNames: object.animationNames, + hasAnimation: object.hasAnimation, + }; + }), + ); + // Captures import in list order so the drawer keeps its sequence; + // items without new bytes keep their pinned asset identity. + // Byte-identical captures collapse to their first pin so one asset + // never backs two drawer entries. + const seenFingerprints = new Set(); + const stills = ( + await Promise.all( + (node.data.stills ?? []).map((item) => + item.capture + ? this.importResource({ + kind: "image", + title: node.data.title ?? "director-stage", + src: item.capture, + fresh: true, + }) + : item.asset, + ), + ) + ).filter((still): still is NonNullable => { + if (!still || seenFingerprints.has(still.fingerprint)) return false; + seenFingerprints.add(still.fingerprint); + return true; + }); const { format: _format, version: _version, ...data - } = node.data.localStage ?? createLocalStage(); - return { ...common, kind, data }; + } = stage; + return { + ...common, + kind, + data: { ...data, objects, stills }, + }; } case "image_crop": { const crop = node.data.imageCrop!; @@ -1540,12 +1710,15 @@ export class CreationProjection { document.edges, [...document.nodes, ...(document.hiddenNodes ?? [])], ); - if (!current) + // Checked here, where the write is produced: a stored stage that is merely on the + // canvas is not written and must not block a save of something else. + if (!current) { + checkDirectorStoryboard(doc); operations.push({ type: "editor.create", payload: { document: doc }, }); - else { + } else { const previous = await this.editorInput( old ?? node, kind as EditorDocument["kind"], @@ -1554,11 +1727,13 @@ export class CreationProjection { [...this.baseline.nodes, ...(this.baseline.hiddenNodes ?? [])], ); if (!same(doc, previous)) { + checkDirectorStoryboard(doc); expect("editor_document", current); - operations.push({ - type: "editor.save", - payload: { document: doc }, - }); + operations.push( + doc.kind === "director" + ? { type: "director.apply", payload: { document: doc } } + : { type: "editor.save", payload: { document: doc } }, + ); } } binding = { diff --git a/src/backend/mediaPublication.ts b/src/backend/mediaPublication.ts index e54faafae..640922796 100644 --- a/src/backend/mediaPublication.ts +++ b/src/backend/mediaPublication.ts @@ -1,5 +1,6 @@ import type { CanvasPublishMediaInput, + DirectorOutputPlanInput, EditorDocument, ProjectSnapshot, MediaEditData, @@ -27,6 +28,19 @@ type Delivery = { key: string; payload: CanvasPublishMediaInput; versions: ReturnType[]; + /** Stable slots are written before the first upload, so a failed later + * upload can resume without changing the already-imported outputs. */ + prepared?: DeliverySlot[]; +}; + +type DeliverySlot = { + itemId: string; + title: string; + position: { x: number; y: number }; + width: number; + height: number; + uploadHandle: string; + asset?: CanvasPublishMediaInput["outputs"][number]["asset"]; }; /** Only command delivery is retained locally; output bytes are owned project assets. */ @@ -75,7 +89,11 @@ export class MediaPublication { /* The open session still owns its original delivery. */ } } - async publish(outputs: readonly LinkedMediaResult[], task?: CanvasToolTask) { + async publish( + outputs: readonly LinkedMediaResult[], + task?: CanvasToolTask, + directorPlan?: DirectorOutputPlanInput, + ) { if (this.active) throw Error(tNow("errors.backend.savingResult")); this.active = true; try { @@ -85,6 +103,7 @@ export class MediaPublication { tool: task?.tool, parameters: task?.parameters, selection: task?.selection, + directorPlan, }), ); const key = [ @@ -94,6 +113,12 @@ export class MediaPublication { .join(""); if (this.confirmed === key) return this.confirmedIds; const resolvingPrevious = !!this.pending && this.pending.key !== key; + if ( + resolvingPrevious && + this.pending?.prepared && + this.pending.payload.outputs.length < this.pending.prepared.length + ) + throw Error(tNow("errors.backend.mediaPreparationPending")); if (!this.pending && this.rejected?.key === key) { this.pending = { ...this.rejected, id: crypto.randomUUID() }; this.remember(); @@ -186,43 +211,84 @@ export class MediaPublication { x: start.x + item.width + 100, y: start.y, }); - const published = []; - for (const [index, output] of outputs.entries()) { - const asset = await this.projection.importResource({ - ...output, - identity: `publication:${document.id}:${index}`, - fresh: true, - }); - versions.push( - objectVersion("asset", { - id: asset.assetId, - revision: asset.revision, - }), - ); - published.push({ - itemId: crypto.randomUUID(), - asset, - title: output.title, - position: placed[index]!.position, - width: placed[index]!.width, - height: placed[index]!.height, - }); - } this.pending = { id: crypto.randomUUID(), key, versions, + prepared: outputs.map((output, index) => { + const placement = placed[index]!; + return { + itemId: crypto.randomUUID(), + title: output.title, + position: placement.position, + width: placement.width, + height: placement.height, + uploadHandle: crypto.randomUUID(), + }; + }), payload: { itemId: item.id, source: source ? assetReference(source) : null, ...(sourceEditorId ? { sourceEditorId } : {}), document, - outputs: published, + ...(directorPlan ? { directorPlan, directorAcceptedAt: this.basis.eventCursor } : {}), + outputs: [], }, }; this.remember(); } - const delivery = this.pending; + let delivery = this.pending; + if (!delivery) throw Error(tNow("errors.backend.savingResult")); + const prepared = delivery.prepared; + if (prepared) { + if (outputs.length !== prepared.length) + throw Error(tNow("errors.backend.mediaPreparationPending")); + for ( + let index = delivery.payload.outputs.length; + index < prepared.length; + index++ + ) { + const slot = prepared[index]!; + const output = outputs[index]!; + const asset = await this.projection.importResource({ + ...output, + identity: `publication:${delivery.payload.document.id}:${index}`, + fresh: true, + uploadHandle: slot.uploadHandle, + }); + delivery = { + ...delivery, + versions: [ + ...delivery.versions, + objectVersion("asset", { + id: asset.assetId, + revision: asset.revision, + }), + ], + payload: { + ...delivery.payload, + outputs: [ + ...delivery.payload.outputs, + { + itemId: slot.itemId, + asset, + title: slot.title, + position: slot.position, + width: slot.width, + height: slot.height, + }, + ], + }, + }; + this.pending = delivery; + this.remember(); + } + } + if ( + delivery.prepared && + delivery.payload.outputs.length !== delivery.prepared.length + ) + throw Error(tNow("errors.backend.mediaPreparationPending")); await this.client.command( "canvas.publishMedia", delivery.payload, diff --git a/src/canvas/DirectorStage.tsx b/src/canvas/DirectorStage.tsx index 98e7a6de9..5dbe62463 100644 --- a/src/canvas/DirectorStage.tsx +++ b/src/canvas/DirectorStage.tsx @@ -1,21 +1,63 @@ +import { StagePanelHeading, StagePanelSearch } from "./DirectorStageChrome"; import { useEditorCommit, type EditorApplyResult } from "./useEditorCommit"; -import { useEffect, useRef, useState } from "react"; +import { + Fragment, + useEffect, + useId, + useMemo, + useReducer, + useRef, + useState, +} from "react"; import * as THREE from "three"; import { OrbitControls } from "three/addons/controls/OrbitControls.js"; -import type { CanvasNode } from "./model"; +import { + TransformControls, + TransformControlsGizmo, +} from "three/addons/controls/TransformControls.js"; +import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; +import { clone as cloneSkinnedObject } from "three/addons/utils/SkeletonUtils.js"; +import type { CanvasNode, CanvasNodeData, StageStillItem } from "./model"; +import type { + Asset, + AssetRef, + DirectorOutputPlanInput, +} from "../contracts/generated.ts"; import { ControlSlider } from "./ControlSlider"; +import { + InspectorColorProperty, + InspectorCompoundProperty, + InspectorPropertyList, + InspectorPropertyRow, + InspectorSection, + InspectorToggleProperty, +} from "./inspector/InspectorPrimitives"; import { createLocalStage, parseLocalStageValue, + parseImportedStageValue, + normalizeLegacyDefaultPersonName, + probeStageAsset, sampleStage, + sampleStageCamera, + sampleStageCameraUp, editStageObjectAt, + editStageObjectPlacement, editStageCameraAt, - captureStageFrame, - stageFrameTimes, - removeStageFrame, + captureStagePreviewFrame, stageOutputSize, + unregisteredStageAssets, + sameLocalStage, defaultStageCamera, + storedStagePreviewSource, + resolveStagePreviewSource, + sampleStagePreview, + sampleStageEditingViewport, + stagePreviewFrameTime, + stagePreviewCameraId, + stageStoryboardBlockAt, STAGE_RATIOS, + STAGE_ASSET_MAX_BYTES, } from "./stageDocument"; import type { LocalStageDocument, @@ -23,59 +65,597 @@ import type { StageSample, StageSampleObject, StageMotionClip, - StageShot, StageObject, StageTransform, + StageAssetRole, + StageTransition, + StageShot, + StagePreviewSource, Vector3Value, } from "./stageDocument"; +import { + createDirectorStageViewState, + directorStageViewReducer, + LAYOUT_LIMITS, +} from "./directorStageViewState"; +import { + groundObject, + groundedPositionY, + STAGE_GROUND_LEVEL, +} from "./stageGrounding.ts"; +import { + formatStageElevation, + layoutStageElevation, + stageElevationHeight, + stageElevationRingPath, + stageElevationRingRadius, + stageElevationScreenPoint, +} from "./stageElevation.ts"; +import type { + DirectorStageLeftTab, + DirectorStageInteractionMode, + DirectorStageResizeTarget, + DirectorStageViewAction, +} from "./directorStageViewState"; import { commitStageHistory, createStageHistory, navigateStageHistory, type StageHistory, } from "./stageHistory"; -import { EditorModal } from "./EditorModal"; import "./director-stage.css"; -import { STAGE_MOTIONS, sampleJointPose } from "./stageMotion"; +import { + STAGE_MOTIONS, + sampleJointPose, + selectStageAnimation, + type StageMotion, +} from "./stageMotion"; import { encodeMp4 } from "./mp4Export"; +import { + projectStageEnvironment, + STAGE_GROUND_NAME, + STAGE_GRID_NAME, + STAGE_LIGHT_NAMES, + STAGE_ENVIRONMENT_PRESETS, + type StageEnvironmentDescriptor, +} from "./stageEnvironment.ts"; +import { updateStageGroundFade } from "./stageGroundFade.ts"; +import { + createStageInfiniteGrid, + updateStageInfiniteGrid, + updateStageInfiniteGridObjects, + type StageInfiniteGrid, +} from "./stageInfiniteGrid.ts"; import { downloadFile, downloadFilename } from "./assets"; +import { assetReference } from "../backend/creationClient.ts"; import { withMediaDuration } from "./editorMedia"; import { mediaBlobDataUrl } from "./localMediaRuntime"; import type { LinkedMediaResult } from "./linkedResults"; import { useI18n } from "../i18n/I18nProvider.tsx"; import type { MessageKey } from "../i18n/types.ts"; +import { + groupStageTimelineTracks, + projectStageTimeline, + stageTimelineIntervals, + stageTimelineIntervalTransition, + stageTimelineRuler, + stageTimeToFrame, + snapStageTimelineTime, + addStageTimelineKeyframeAt, + removeStageTimelineKeyframe, + type StageTimelineChannel, + type StageTimelineTrack, + setStageTimelineIntervalTransition, + type StageTimelineIntervalTarget, + type StageTimelineKeyframeAddTarget, + type StageTimelineKeyframeTarget, + type StageTimelineStoryboardInterval, +} from "./stageTimeline.ts"; +import { + stageExportPlan, + mergeStageStoryboardBlock, + packStageStoryboard, + readStageStoryboard, + sameStageStoryboard, + type StageCutEdit, + type StageCutReceipt, + stageStoryboardIssueMessageKey, +} from "./stageStoryboard.ts"; +import { StageStoryboardChooser } from "./StageStoryboardChooser.tsx"; +import { + StageStoryboardTrack, + type StageStoryboardThumbnailShot, +} from "./StageStoryboardTrack.tsx"; +import { StagePreviewSourceSelect } from "./StagePreviewSourceSelect.tsx"; +import { + captureStageStoryboardThumbnail, + copyStageViewportPixels, + poseStagePreviewCamera, +} from "./stageStoryboardThumbnailRender.ts"; +import { stageStoryboardThumbnailSize } from "./stageStoryboardThumbnail.ts"; export interface DirectorStageProps { node: CanvasNode; onApply: ( stage: LocalStageDocument, - screenshot?: string, + stills?: StageStillItem[], ) => EditorApplyResult; onClose: () => void; onRender: (result: LinkedMediaResult) => boolean | Promise; onPrepareRender?: ( stage: LocalStageDocument, + stills?: StageStillItem[], + directorPlan?: DirectorOutputPlanInput, ) => Promise<(result: LinkedMediaResult) => Promise>; + /** Appends an existing camera to the open stage's Storyboard through the shared + * `director.storyboard.append` command and returns the block as the server stored it. */ + onAppendStoryboard?: (input: { + cameraId: string; + blockId: string; + /** An unsaved draft was just committed through `onApply` before this call. */ + savedDraft?: boolean; + }) => Promise; + onEditStoryboard?: (input: StageCutEdit & { + before: readonly StageShot[]; + draft?: Pick; + }) => Promise; + /** Whether a pinned asset is registered in the currently open project; + * stage JSON imports reject objects pinning assets it reports as absent. */ + isRegisteredAsset?: (asset: AssetRef) => boolean; + backgroundAssets?: readonly Asset[]; + resolveAssetUrl?: (asset: AssetRef) => Promise; + onImportBackground?: (file: File) => Promise; +} + +const STAGE_TIMELINE_RULER_HEIGHT = 27; +const STAGE_TIMELINE_GROUP_ROW_HEIGHT = 22; +const STAGE_TIMELINE_TRACK_ROW_HEIGHT = 20; +/** The Storyboard row is taller than an ordinary one, so a block can hold a thumbnail. + * The track surface receives it as a custom property: the rows the CSS lays out and + * the height this file computes for the surface are the same number. */ +const STAGE_TIMELINE_STORYBOARD_ROW_HEIGHT = 40; +const STAGE_TIMELINE_SURFACE_PADDING = 0; +/** What the split view's Storyboard tab samples: the Storyboard, whatever the preview + * source is. */ +const STORYBOARD_PREVIEW: StagePreviewSource = { kind: "storyboard" }; +const DEFAULT_BEZIER_CONTROL_POINTS: [number, number, number, number] = [ + 0.333, 0.333, 0.667, 0.667, +]; + +function StageTransitionGraph({ transition }: { transition: StageTransition }) { + const [x1, y1, x2, y2] = transition.kind === "bezier" + ? transition.controlPoints + : DEFAULT_BEZIER_CONTROL_POINTS; + const size = 248; + const inset = 8; + const span = size - inset * 2; + const point = (x: number, y: number) => + `${inset + x * span},${inset + (1 - y) * span}`; + return ( + + ); +} + +interface LoadedStageAsset { + scene: THREE.Object3D; + animations: THREE.AnimationClip[]; +} +interface RestPose { + object: THREE.Object3D; + position: THREE.Vector3; + quaternion: THREE.Quaternion; + scale: THREE.Vector3; +} +interface ImportedRuntime { + root: THREE.Group; + clips: THREE.AnimationClip[]; + mixer?: THREE.AnimationMixer; + activeClip?: THREE.AnimationClip; + restPose: RestPose[]; } interface StageRuntime { renderer: THREE.WebGLRenderer; scene: THREE.Scene; camera: THREE.PerspectiveCamera; controls: OrbitControls; + translate: TransformControls; + rotate: TransformControls; + scale: TransformControls; root: THREE.Group; - grid: THREE.GridHelper; + grid: StageInfiniteGrid; + /** Viewport-local helper group (motion paths, height guides). */ + helpers: THREE.Group; + imported: Map; + /** In-flight or resolved loads keyed by pinned asset id or source URL, so + * concurrent effect runs share one load and one set of GPU resources. */ + assetCache: Map>; +} + +const STAGE_UNDERGROUND_GROUND_OPACITY = 0.45; + +function hasBelowGroundObject(root: THREE.Group, bounds: THREE.Box3): boolean { + for (const child of root.children) { + if (!child.visible) continue; + bounds.setFromObject(child); + if (!bounds.isEmpty() && bounds.min.y < STAGE_GROUND_LEVEL - 0.001) + return true; + } + return false; } -const vector = (value: THREE.Vector3): Vector3Value => ({ + +/** + * The ground is opaque during normal output, but the director viewport needs + * to reveal a subject that intersects it. A translucent ground veil keeps the + * below-ground part visible without changing the saved transform or camera + * render. + */ +function setStageGroundReveal(ground: THREE.Mesh, reveal: boolean) { + if (!(ground.material instanceof THREE.MeshStandardMaterial)) return; + const material = ground.material; + const opacity = reveal ? STAGE_UNDERGROUND_GROUND_OPACITY : 1; + const transparent = reveal; + const depthWrite = !reveal; + if ( + material.transparent === transparent && + material.opacity === opacity && + material.depthWrite === depthWrite + ) + return; + material.transparent = transparent; + material.opacity = opacity; + material.depthWrite = depthWrite; + material.needsUpdate = true; +} + +function applyStageEnvironment( + scene: THREE.Scene, + descriptor: StageEnvironmentDescriptor, + groundVisible = descriptor.ground.visible, + renderer?: THREE.WebGLRenderer, +) { + scene.background = new THREE.Color(descriptor.backgroundColor); + if (renderer) { + renderer.toneMapping = THREE.LinearToneMapping; + renderer.toneMappingExposure = descriptor.exposure; + } + const ground = scene.getObjectByName(STAGE_GROUND_NAME); + if (ground instanceof THREE.Mesh && ground.material instanceof THREE.MeshStandardMaterial) { + ground.material.color.set(descriptor.ground.color); + updateStageGroundFade( + ground.material, + descriptor.backgroundColor, + descriptor.backgroundAsset === null, + ); + ground.visible = groundVisible; + } + for (const light of Object.values(descriptor.lights)) { + const object = scene.getObjectByName(STAGE_LIGHT_NAMES[light.id]); + if (!(object instanceof THREE.Light)) continue; + object.color.set(light.color); + object.intensity = light.intensity; + object.position.set(light.position.x, light.position.y, light.position.z); + object.castShadow = light.castShadow; + } +} +async function applyStageBackground( + scene: THREE.Scene, + descriptor: StageEnvironmentDescriptor, + resolveAssetUrl?: (asset: AssetRef) => Promise, + isCurrent: () => boolean = () => true, +) { + scene.background = new THREE.Color(descriptor.backgroundColor); + if (!descriptor.backgroundAsset || !resolveAssetUrl) return false; + try { + const url = await resolveAssetUrl(descriptor.backgroundAsset); + const texture = await new THREE.TextureLoader().loadAsync(url); + if (!isCurrent()) { + texture.dispose(); + return false; + } + texture.colorSpace = THREE.SRGBColorSpace; + texture.userData.stageBackgroundAssetId = descriptor.backgroundAsset.assetId; + scene.background = texture; + return true; + } catch { + return false; + } +} +const vector = (value: THREE.Vector3 | THREE.Euler): Vector3Value => ({ x: value.x, y: value.y, z: value.z, }); +const THUMBNAIL_RENDER_SIZE = { width: 256, height: 192 } as const; +const THUMBNAIL_CROP_SIZE = { width: 192, height: 112 } as const; +const THUMBNAIL_ZERO_TRANSFORM: StageTransform = { + position: { x: 0, y: 0, z: 0 }, + rotation: { x: 0, y: 0, z: 0 }, + scale: { x: 1, y: 1, z: 1 }, +}; + +function cropStageThumbnail(renderer: THREE.WebGLRenderer): string { + const source = renderer.domElement; + const canvas = document.createElement("canvas"); + canvas.width = THUMBNAIL_CROP_SIZE.width; + canvas.height = THUMBNAIL_CROP_SIZE.height; + const context = canvas.getContext("2d"); + if (!context) throw new Error("Stage thumbnail canvas is unavailable"); + const cropX = Math.max( + 0, + Math.floor((source.width - THUMBNAIL_CROP_SIZE.width) / 2), + ); + const cropY = Math.max( + 0, + Math.floor((source.height - THUMBNAIL_CROP_SIZE.height) / 2), + ); + context.drawImage( + source, + cropX, + cropY, + THUMBNAIL_CROP_SIZE.width, + THUMBNAIL_CROP_SIZE.height, + 0, + 0, + THUMBNAIL_CROP_SIZE.width, + THUMBNAIL_CROP_SIZE.height, + ); + return canvas.toDataURL("image/png"); +} + +function renderStageObjectModelThumbnail( + model: THREE.Group, + modelSharesAssetResources: boolean, + frontPortrait = false, +): string | null { + let renderer: THREE.WebGLRenderer | null = null; + let ground: THREE.Mesh | null = null; + try { + renderer = new THREE.WebGLRenderer({ + antialias: true, + alpha: false, + preserveDrawingBuffer: true, + }); + renderer.setPixelRatio(1); + const frameSize = frontPortrait ? THUMBNAIL_CROP_SIZE : THUMBNAIL_RENDER_SIZE; + renderer.setSize(frameSize.width, frameSize.height, false); + renderer.shadowMap.enabled = true; + renderer.shadowMap.type = THREE.PCFShadowMap; + renderer.outputColorSpace = THREE.SRGBColorSpace; + + const scene = new THREE.Scene(); + scene.background = new THREE.Color("#171717"); + scene.add(new THREE.HemisphereLight("#d9e5ff", "#222222", 1.6)); + const keyLight = new THREE.DirectionalLight("#ffffff", 3.2); + keyLight.position.set(3, 5, 4); + keyLight.castShadow = true; + scene.add(keyLight); + const fillLight = new THREE.DirectionalLight("#7190c8", 1.1); + fillLight.position.set(-3, 2, -2); + scene.add(fillLight); + + ground = new THREE.Mesh( + new THREE.PlaneGeometry(8, 8), + new THREE.MeshStandardMaterial({ color: "#242424", roughness: 0.92 }), + ); + ground.rotation.x = -Math.PI / 2; + ground.receiveShadow = true; + scene.add(ground); + + scene.add(model); + scene.updateMatrixWorld(true); + + const bounds = new THREE.Box3().setFromObject(model); + if (frontPortrait) { + // Keep the person centered over the origin with its lowest point on y=0. + model.position.y -= bounds.min.y; + bounds.translate(new THREE.Vector3(0, -bounds.min.y, 0)); + } + const center = bounds.getCenter(new THREE.Vector3()); + const size = bounds.getSize(new THREE.Vector3()); + const extent = Math.max(size.x, size.y, size.z, 0.5); + const camera = new THREE.PerspectiveCamera( + 32, + frameSize.width / frameSize.height, + 0.01, + 100, + ); + const verticalHalfAngle = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)); + if (frontPortrait) { + // Fit the full bounds on the final image, with room around head and feet. + const fit = Math.max(size.y, size.x / camera.aspect); + const distance = size.z / 2 + (fit * 1.2) / (2 * verticalHalfAngle); + camera.position.set(center.x, center.y, center.z + distance); + } else { + const distance = extent / (2 * verticalHalfAngle); + camera.position.set( + center.x + distance * 0.85, + center.y + extent * 0.25, + center.z + distance * 1.15, + ); + } + camera.lookAt(center); + camera.updateProjectionMatrix(); + renderer.render(scene, camera); + return frontPortrait + ? renderer.domElement.toDataURL("image/png") + : cropStageThumbnail(renderer); + } catch { + return null; + } finally { + if (ground) { + ground.geometry.dispose(); + if (ground.material instanceof THREE.Material) ground.material.dispose(); + } + if (!modelSharesAssetResources) disposeObject(model); + renderer?.forceContextLoss(); + renderer?.dispose(); + } +} + +function renderStageObjectThumbnailNow( + value: StageObject, + loaded?: LoadedStageAsset, +): string | null { + const normalized: StageObject = { + ...value, + ...THUMBNAIL_ZERO_TRANSFORM, + }; + if (loaded) { + normalized.source = value.source; + return renderStageObjectModelThumbnail( + cloneImportedAsset(normalized, loaded), + true, + ); + } + return renderStageObjectModelThumbnail( + buildObject(normalized), + false, + value.kind === "person", + ); +} + +function StageObjectPreview({ + object, + portrait, +}: { + portrait?: string; + object: Pick< + StageObject, + "kind" | "color" | "thumbnailCapture" | "thumbnailSource" + >; +}) { + const thumbnail = portrait ?? object.thumbnailCapture ?? object.thumbnailSource; + return ( +