拆分出的前端模块未按 Prettier 格式化导致 CI 格式检查失败;源码断言改为忽略空白差异,导演台引导组件恢复别名导入。同时移除误提交的分析草稿、pnpm 锁文件和调试测试。
930 lines
62 KiB
TypeScript
930 lines
62 KiB
TypeScript
import { cameraMoveOptions, poseOptions, shotSizeOptions, IconButton, PanelTitle, AddMenuButton, SceneRow, QuickAdd, ObjectInspector, LightInspector, ShotInspector } from "./director-inspectors";
|
||
import { snapDirectorTime, advanceDirectorPlayhead, resolveDirectorKeyframeRecord, resolveDirectorObjectTransformEdit, resolveDirectorCameraMoveKeyframes, resolveDirectorCameraAlignment } from "@/lib/canvas/director/director-animation-semantics";
|
||
import { interpolateDirectorTransform, touchDirectorScene, createDirectorObject, createDirectorActor, DIRECTOR_ACTOR_COLORS, createDirectorModel, createDirectorBillboard, createDirectorCamera, createDirectorLight, upsertDirectorBoneKeyframe, removeDirectorSceneKeyframe, setDirectorSceneKeyframeEasing, directorPoseLabel } from "@/lib/canvas/director/director-scene";
|
||
import { type DirectorObject, type DirectorLight, type DirectorShot, type DirectorHumanoidBone, type DirectorQuat, type DirectorKeyframeDeleteTarget, type DirectorKeyframeEasing, type DirectorRig, type DirectorPose, type DirectorShotSize } from "@/types/director";
|
||
import { resolveDirectorPlacementAnchor, resolveDirectorPlacement, type DirectorGroundPoint } from "@/lib/canvas/director/director-placement";
|
||
import { uploadMediaFile } from "@/services/file-storage";
|
||
import { saveRemoteUserDataNow, localSavedRemotePendingMessage } from "@/services/user-data-sync";
|
||
import { Camera, Lightbulb, LampDesk, UserRound, Box, Circle, Cuboid, FileUp, X, Undo2, Redo2, RotateCcw, Video, Save, Plus, MousePointer2, WandSparkles, Focus, BoxSelect, Image as ImageIcon } from "lucide-react";
|
||
import { nanoid } from "nanoid";
|
||
import { type DirectorShortcutAction, resolveDirectorShortcut, blocksDirectorShortcut, releaseDirectorFocusAfterPointer } from "@/lib/canvas/director/director-shortcuts";
|
||
import { type AnimationClip } from "three";
|
||
import { compileDirectorPrompt } from "@/lib/canvas/director/director-prompt-compiler";
|
||
import { Select } from "@/components/ui/base/select";
|
||
import { DirectorViewport } from "./director-viewport";
|
||
import { CanvasDirectorOnboarding } from "@/components/canvas/director/canvas-director-onboarding";
|
||
import { DirectorViewportDock } from "./director-viewport-dock";
|
||
import { DirectorSequencer } from "./director-sequencer";
|
||
import { App, type MenuProps, Input, Button } from "antd";
|
||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||
import { type DirectorViewportHandle } from "@/components/canvas/director/director-viewport";
|
||
import { canvasThemes } from "@/lib/canvas-theme";
|
||
import { type DirectorTransaction, createDirectorTransaction, installDirectorTerminalListeners } from "@/lib/canvas/director/director-gesture-transaction";
|
||
import { recordDirectorDiagnostic } from "@/lib/canvas/director/director-diagnostics-recorder";
|
||
import { directorModeCapabilities, DIRECTOR_MODES } from "@/lib/canvas/director/director-modes";
|
||
import { shouldReinitializeDirectorSession, isDirectorOutputSnapshotCurrent } from "@/lib/canvas/director/director-session";
|
||
import { describeDirectorSaveStatus, shouldOfferDirectorDraftRecovery, shouldBlockDirectorUnload, resolveDirectorCloseOutcome } from "@/lib/canvas/director/director-save-wiring";
|
||
import { useDirectorSaveCoordinator } from "@/components/canvas/director/use-director-save-coordinator";
|
||
import { useAssetStore, type ModelAsset } from "@/stores/use-asset-store";
|
||
import { useDirectorWorkbenchStore } from "@/stores/canvas/use-director-workbench-store";
|
||
import { useActiveTheme } from "@/stores/canvas/use-canvas-theme-store";
|
||
import type { CanvasNodeData } from "@/types/canvas";
|
||
import type { DirectorCameraMove, DirectorRenderMode, DirectorScene, DirectorSceneOutput, DirectorTransform, DirectorVec3 } from "@/types/director";
|
||
export { cameraMoveOptions, poseOptions, shotSizeOptions } from "./director-inspectors";
|
||
|
||
export function CanvasDirectorWorkbench({ open, scene, imageNodes, onboardingScope, onClose, onChange, onApply, onDeleteImageNode, onFlush }: { open: boolean; scene: DirectorScene | null; imageNodes: CanvasNodeData[]; onboardingScope: string; onClose: () => void; onChange: (scene: DirectorScene) => void; onApply: (output: DirectorSceneOutput) => Promise<void>; onDeleteImageNode: (nodeId: string) => void; onFlush?: () => void | Promise<void> }) {
|
||
const { message, modal } = App.useApp();
|
||
const theme = canvasThemes[useActiveTheme()];
|
||
const viewportRef = useRef<DirectorViewportHandle>(null);
|
||
const modelInputRef = useRef<HTMLInputElement>(null);
|
||
const [draft, setDraft] = useState<DirectorScene | null>(null);
|
||
const [history, setHistory] = useState<DirectorScene[]>([]);
|
||
const [future, setFuture] = useState<DirectorScene[]>([]);
|
||
const [saving, setSaving] = useState(false);
|
||
const [recording, setRecording] = useState(false);
|
||
// 默认进入镜头优先的快速工作流,完整的摆场/姿态/动画能力仍保留在高级模式。
|
||
const [quickMode, setQuickMode] = useState(true);
|
||
const [onboardingRestartSignal, setOnboardingRestartSignal] = useState(0);
|
||
const mode = useDirectorWorkbenchStore((state) => state.mode);
|
||
const viewMode = useDirectorWorkbenchStore((state) => state.viewMode);
|
||
const setViewMode = useDirectorWorkbenchStore((state) => state.setViewMode);
|
||
const setMode = useDirectorWorkbenchStore((state) => state.setMode);
|
||
const selectedObjectId = useDirectorWorkbenchStore((state) => state.selectedObjectId);
|
||
const selectedLightId = useDirectorWorkbenchStore((state) => state.selectedLightId);
|
||
const transformMode = useDirectorWorkbenchStore((state) => state.transformMode);
|
||
const renderMode = useDirectorWorkbenchStore((state) => state.renderMode);
|
||
const playhead = useDirectorWorkbenchStore((state) => state.playhead);
|
||
const playing = useDirectorWorkbenchStore((state) => state.playing);
|
||
const selectedBone = useDirectorWorkbenchStore((state) => state.selectedBone);
|
||
const autoKey = useDirectorWorkbenchStore((state) => state.autoKey);
|
||
const sequencerHeight = useDirectorWorkbenchStore((state) => state.sequencerHeight);
|
||
const sequencerVisible = useDirectorWorkbenchStore((state) => state.sequencerVisible);
|
||
const setSelectedObjectId = useDirectorWorkbenchStore((state) => state.setSelectedObjectId);
|
||
const setSelectedLightId = useDirectorWorkbenchStore((state) => state.setSelectedLightId);
|
||
const setTransformMode = useDirectorWorkbenchStore((state) => state.setTransformMode);
|
||
const setRenderMode = useDirectorWorkbenchStore((state) => state.setRenderMode);
|
||
const setPlayhead = useDirectorWorkbenchStore((state) => state.setPlayhead);
|
||
const setPlaying = useDirectorWorkbenchStore((state) => state.setPlaying);
|
||
const setSelectedBone = useDirectorWorkbenchStore((state) => state.setSelectedBone);
|
||
const setAutoKey = useDirectorWorkbenchStore((state) => state.setAutoKey);
|
||
const setSequencerHeight = useDirectorWorkbenchStore((state) => state.setSequencerHeight);
|
||
const setSequencerVisible = useDirectorWorkbenchStore((state) => state.setSequencerVisible);
|
||
const resetWorkbench = useDirectorWorkbenchStore((state) => state.reset);
|
||
const assets = useAssetStore((state) => state.assets);
|
||
const addAsset = useAssetStore((state) => state.addAsset);
|
||
const modelAssets = useMemo(() => assets.filter((asset): asset is ModelAsset => asset.kind === "model"), [assets]);
|
||
|
||
// 模式决定显示什么:时间轴、关键帧、骨骼、摄影机工具与可选渲染视图都从这里派生。
|
||
const capabilities = directorModeCapabilities(mode);
|
||
const renderModeOptions = useMemo(() => DIRECTOR_RENDER_MODE_LABELS.filter((option) => capabilities.renderModes.includes(option.value)), [capabilities.renderModes]);
|
||
|
||
const draftRef = useRef<DirectorScene | null>(null);
|
||
const stagedRef = useRef<DirectorTransaction | null>(null);
|
||
const initializedSceneIdRef = useRef<string | null>(null);
|
||
const onChangeRef = useRef(onChange);
|
||
const onFlushRef = useRef(onFlush);
|
||
useEffect(() => { onChangeRef.current = onChange; onFlushRef.current = onFlush; }, [onChange, onFlush]);
|
||
|
||
const closingRef = useRef(false);
|
||
const recoveryPromptedRef = useRef<string | null>(null);
|
||
const [retrying, setRetrying] = useState(false);
|
||
|
||
// 按 scene.id 持有唯一 coordinator:flush 先把 request.scene 写回项目,再等持久化完成。
|
||
const saveController = useDirectorSaveCoordinator({
|
||
sceneId: scene?.id ?? null,
|
||
initialScene: scene,
|
||
persistScene: (next) => onChangeRef.current(next),
|
||
flushPersistence: () => onFlushRef.current?.(),
|
||
});
|
||
const saveControllerRef = useRef(saveController);
|
||
saveControllerRef.current = saveController;
|
||
const saveIndicator = describeDirectorSaveStatus(saveController.progress);
|
||
|
||
const retrySave = async () => {
|
||
setRetrying(true);
|
||
try {
|
||
if (await saveController.retry()) {
|
||
recordDirectorDiagnostic("DIRECTOR_SAVE_RETRY_RECOVERED", { sceneId: draftRef.current?.id, revision: saveController.progress.revision, userInitiated: true });
|
||
message.success("已保存到项目");
|
||
return;
|
||
}
|
||
// 只有真的存在合法本地候选才敢说草稿已保留。
|
||
const draftStored = Boolean(saveController.restoreCandidate());
|
||
recordDirectorDiagnostic("DIRECTOR_SAVE_RETRY_FAILED", { sceneId: draftRef.current?.id, revision: saveController.progress.revision, draftStored, userInitiated: true });
|
||
if (!draftStored) recordDirectorDiagnostic("DIRECTOR_SAVE_DRAFT_UNAVAILABLE", { sceneId: draftRef.current?.id, revision: saveController.progress.revision });
|
||
if (draftStored) message.error("远端保存失败,本地草稿已保留,可稍后重试");
|
||
else message.error("远端和本地都未保存,请不要关闭导演台并继续重试");
|
||
} finally {
|
||
setRetrying(false);
|
||
}
|
||
};
|
||
|
||
const writeDraft = useCallback((next: DirectorScene | null) => {
|
||
draftRef.current = next;
|
||
setDraft(next);
|
||
}, []);
|
||
|
||
/**
|
||
* 仅镜像当前 draft 到项目 directorScenes,不产生 canonical 提交。
|
||
* 用于取消预览、idle pagehide、卸载兜底 —— 这些都不是新的用户改动。
|
||
*/
|
||
const mirrorDraft = useCallback(() => {
|
||
const current = draftRef.current;
|
||
if (!current || initializedSceneIdRef.current !== current.id) return;
|
||
onChangeRef.current(current);
|
||
}, []);
|
||
|
||
/** 真实 canonical 提交:先交给 coordinator(本地草稿 + 远端保存),再镜像到项目。 */
|
||
const commitDraft = useCallback(() => {
|
||
const current = draftRef.current;
|
||
if (!current || initializedSceneIdRef.current !== current.id) return;
|
||
saveControllerRef.current?.commitScene(current);
|
||
onChangeRef.current(current);
|
||
}, []);
|
||
|
||
const writeAndPublish = useCallback((next: DirectorScene) => {
|
||
writeDraft(next);
|
||
saveControllerRef.current?.commitScene(next);
|
||
onChangeRef.current(next);
|
||
}, [writeDraft]);
|
||
|
||
// 会话初始化只认 scene id:同 id 的父级镜像回流不得重建会话。
|
||
useEffect(() => {
|
||
if (!open || !scene) return;
|
||
if (!shouldReinitializeDirectorSession({ initializedSceneId: initializedSceneIdRef.current, nextSceneId: scene.id })) return;
|
||
const next = structuredClone(scene);
|
||
next.shots = next.shots.map((shot) => ({ ...shot, fps: shot.fps || 24 }));
|
||
stagedRef.current?.end("cancel");
|
||
initializedSceneIdRef.current = scene.id;
|
||
writeDraft(next);
|
||
setHistory([]);
|
||
setFuture([]);
|
||
resetWorkbench();
|
||
}, [open, resetWorkbench, scene, writeDraft]);
|
||
|
||
// 打开会话时检查合法本地恢复候选:同一场景只提示一次,恢复/放弃都必须有明确结果。
|
||
useEffect(() => {
|
||
if (!open || !scene) return;
|
||
if (recoveryPromptedRef.current === scene.id) return;
|
||
recoveryPromptedRef.current = scene.id;
|
||
|
||
const controller = saveControllerRef.current;
|
||
const candidate = controller?.restoreCandidate() ?? null;
|
||
if (!controller || !candidate) return;
|
||
if (!shouldOfferDirectorDraftRecovery({ candidate, authoritativeScene: scene })) return;
|
||
|
||
modal.confirm({
|
||
title: "发现未保存的本地草稿",
|
||
content: `这个镜头存在一份比项目更新的本地草稿(修订 ${candidate.revision})。恢复后会立即写回项目并保存。`,
|
||
okText: "恢复草稿",
|
||
cancelText: "放弃草稿",
|
||
closable: false,
|
||
mask: { closable: false },
|
||
keyboard: false,
|
||
onOk: () => {
|
||
if (!controller.restoreDraft(candidate)) {
|
||
message.error("草稿恢复失败,已保留当前场景");
|
||
return;
|
||
}
|
||
writeDraft(candidate.scene);
|
||
message.success("已恢复本地草稿并写回项目");
|
||
},
|
||
onCancel: () => {
|
||
if (controller.discardDraft()) message.success("已放弃本地草稿");
|
||
else message.error("草稿删除失败,下次打开可能仍会提示");
|
||
},
|
||
});
|
||
}, [message, modal, open, scene, writeDraft]);
|
||
|
||
const activeShot = draft?.shots?.find((item) => item.id === draft.activeShotId) || draft?.shots?.[0] || null;
|
||
const activeCamera = draft?.cameras?.find((item) => item.id === activeShot?.cameraId) || draft?.cameras?.[0] || null;
|
||
const selectedObject = draft?.objects?.find((item) => item.id === selectedObjectId) || null;
|
||
const selectedLight = draft?.lights?.find((item) => item.id === selectedLightId) || null;
|
||
// 写入关键帧的目的时间用吸附值;取值/显示/手势起点一律用 raw playhead,
|
||
// 否则处在两个帧格之间时 AutoKey OFF 的增量会从错误起点计算而产生漂移。
|
||
const snappedPlayhead = snapDirectorTime(playhead, activeShot?.fps || 24);
|
||
const selectedObjectRendered = selectedObject ? interpolateDirectorTransform(selectedObject.transform, selectedObject.keyframes, playhead) : null;
|
||
|
||
useEffect(() => {
|
||
if (!playing || !activeShot) return;
|
||
let frame = 0;
|
||
let last = performance.now();
|
||
let pending = 0;
|
||
const frameInterval = 1 / Math.max(1, Math.min(120, activeShot.fps || 24));
|
||
const tick = (now: number) => {
|
||
pending += Math.max(0, (now - last) / 1000);
|
||
last = now;
|
||
if (pending >= frameInterval) {
|
||
const elapsed = Math.floor(pending / frameInterval) * frameInterval;
|
||
pending -= elapsed;
|
||
setPlayhead(advanceDirectorPlayhead(useDirectorWorkbenchStore.getState().playhead, elapsed, activeShot.duration));
|
||
}
|
||
frame = requestAnimationFrame(tick);
|
||
};
|
||
frame = requestAnimationFrame(tick);
|
||
return () => cancelAnimationFrame(frame);
|
||
}, [activeShot, playing, setPlayhead]);
|
||
|
||
const commit = useCallback((updater: (current: DirectorScene) => DirectorScene) => {
|
||
// 普通提交前先终结暂存手势,避免新动作消费旧 base。
|
||
stagedRef.current?.end("commit");
|
||
const current = draftRef.current;
|
||
if (!current) return;
|
||
setHistory((items) => [...items.slice(-49), structuredClone(current)]);
|
||
setFuture([]);
|
||
writeAndPublish(touchDirectorScene(updater(current)));
|
||
}, [writeAndPublish]);
|
||
|
||
/** 暂存型手势(数值滑杆):实时预览写草稿但不产生历史,也不镜像到项目。 */
|
||
const stagedTransaction = useMemo(() => createDirectorTransaction<DirectorScene>({
|
||
read: () => draftRef.current,
|
||
// 取消:恢复快照且绝不发布被取消的值。
|
||
restore: (snapshot) => writeDraft(snapshot),
|
||
commit: (from) => {
|
||
setHistory((items) => [...items.slice(-49), from]);
|
||
setFuture([]);
|
||
// 手势成功终态是真实 canonical 提交。
|
||
commitDraft();
|
||
},
|
||
setActive: () => undefined,
|
||
}), [commitDraft, writeDraft]);
|
||
stagedRef.current = stagedTransaction;
|
||
|
||
const stageGesture = useCallback((updater: (current: DirectorScene) => DirectorScene) => {
|
||
const current = draftRef.current;
|
||
if (!current) return;
|
||
stagedTransaction.begin();
|
||
writeDraft(touchDirectorScene(updater(current)));
|
||
}, [stagedTransaction, writeDraft]);
|
||
|
||
/** 无历史但持久的变化(标题、rig/motionClips 等)同样要镜像。 */
|
||
const replaceWithoutHistory = useCallback((updater: (current: DirectorScene) => DirectorScene) => {
|
||
const current = draftRef.current;
|
||
if (current) writeAndPublish(touchDirectorScene(updater(current)));
|
||
}, [writeAndPublish]);
|
||
|
||
// 暂存手势的终止生命周期:常驻安装,非活跃时 end 为空操作。
|
||
useEffect(() => installDirectorTerminalListeners(stagedTransaction, {
|
||
window,
|
||
document,
|
||
isHidden: () => document.visibilityState === "hidden",
|
||
}), [stagedTransaction]);
|
||
|
||
// 切换选择/骨骼、关闭或卸载前必须先终止旧手势,不能让新选择消费旧 base。
|
||
useEffect(() => () => stagedTransaction.end("cancel"), [open, selectedBone, selectedObjectId, stagedTransaction]);
|
||
|
||
// 离开页面:active 预览由 end("commit") 完成真实提交,idle 只镜像;落盘统一交给 controller。
|
||
useEffect(() => {
|
||
const onPageHide = () => {
|
||
if (stagedTransaction.active()) stagedTransaction.end("commit");
|
||
else mirrorDraft();
|
||
// 只调用 handlePageHide:dirty 时它自己会 persist + flush,组件再叠一次就是重复落盘。
|
||
void saveControllerRef.current?.handlePageHide();
|
||
};
|
||
// 异步 flush 不可能阻塞卸载:这里只同步声明「仍有未确认改动」,让浏览器自己弹保护。
|
||
const onBeforeUnload = (event: BeforeUnloadEvent) => {
|
||
const controller = saveControllerRef.current;
|
||
if (!controller || !shouldBlockDirectorUnload(controller.progress)) return;
|
||
event.preventDefault();
|
||
event.returnValue = "";
|
||
};
|
||
window.addEventListener("pagehide", onPageHide);
|
||
window.addEventListener("beforeunload", onBeforeUnload);
|
||
return () => {
|
||
window.removeEventListener("pagehide", onPageHide);
|
||
window.removeEventListener("beforeunload", onBeforeUnload);
|
||
};
|
||
}, [mirrorDraft, stagedTransaction]);
|
||
|
||
// 卸载兜底:只把最新 draft 镜像回项目,不制造新的 canonical revision。
|
||
useEffect(() => () => {
|
||
stagedRef.current?.end("cancel");
|
||
mirrorDraft();
|
||
}, [mirrorDraft]);
|
||
|
||
const undo = () => {
|
||
const previous = history.at(-1);
|
||
if (!previous || !draft) return;
|
||
setHistory((items) => items.slice(0, -1));
|
||
setFuture((items) => [structuredClone(draft), ...items].slice(0, 50));
|
||
writeAndPublish(previous);
|
||
};
|
||
const redo = () => {
|
||
const next = future[0];
|
||
if (!next || !draft) return;
|
||
setFuture((items) => items.slice(1));
|
||
setHistory((items) => [...items, structuredClone(draft)].slice(-50));
|
||
writeAndPublish(next);
|
||
};
|
||
|
||
/**
|
||
* 关闭统一入口:取消未结束的预览、镜像当前 draft,再按 prepareClose 决策是否真的退出。
|
||
* 这里只镜像不提交:取消预览不是新的 canonical 变化。
|
||
*/
|
||
const closeWorkbench = () => {
|
||
if (closingRef.current) return;
|
||
closingRef.current = true;
|
||
stagedTransaction.end("cancel");
|
||
mirrorDraft();
|
||
void (async () => {
|
||
let decision;
|
||
try {
|
||
decision = resolveDirectorCloseOutcome(await saveController.prepareClose());
|
||
} catch {
|
||
message.error("关闭前的保存检查失败,已留在导演台");
|
||
closingRef.current = false;
|
||
return;
|
||
}
|
||
|
||
if (decision.kind === "close") {
|
||
onClose();
|
||
return;
|
||
}
|
||
if (decision.kind === "blocked") {
|
||
recordDirectorDiagnostic("DIRECTOR_CLOSE_BLOCKED", { sceneId: draftRef.current?.id, saveOutcome: "stay", revision: saveController.progress.revision, draftStored: saveController.progress.draftStored });
|
||
message.error(decision.message);
|
||
closingRef.current = false;
|
||
return;
|
||
}
|
||
|
||
// 确认框存续期间保持上锁,否则重复点击会叠出多个弹窗。
|
||
modal.confirm({
|
||
title: "远端保存失败",
|
||
content: decision.message,
|
||
okText: "仍然离开",
|
||
cancelText: "留在导演台",
|
||
closable: false,
|
||
mask: { closable: false },
|
||
keyboard: false,
|
||
onOk: () => onClose(),
|
||
onCancel: () => {
|
||
closingRef.current = false;
|
||
},
|
||
});
|
||
})();
|
||
};
|
||
|
||
const updateObject = (id: string, patch: Partial<DirectorObject>) => commit((current) => ({ ...current, objects: current.objects.map((item) => (item.id === id ? { ...item, ...patch } : item)) }));
|
||
const updateLight = (id: string, patch: Partial<DirectorLight>) => commit((current) => ({ ...current, lights: current.lights.map((item) => (item.id === id ? { ...item, ...patch } : item)) }));
|
||
const updateShot = (id: string, patch: Partial<DirectorShot>) => commit((current) => ({ ...current, shots: current.shots.map((item) => (item.id === id ? { ...item, ...patch } : item)) }));
|
||
const removeObject = (id: string) => {
|
||
commit((current) => ({ ...current, objects: current.objects.filter((item) => item.id !== id) }));
|
||
if (selectedObjectId === id) {
|
||
setSelectedObjectId(null);
|
||
setSelectedBone(null);
|
||
}
|
||
};
|
||
const removeLight = (id: string) => {
|
||
commit((current) => ({ ...current, lights: current.lights.filter((item) => item.id !== id) }));
|
||
if (selectedLightId === id) setSelectedLightId(null);
|
||
};
|
||
const removeCamera = (id: string) => {
|
||
if (!draft || draft.cameras.length <= 1) {
|
||
message.warning("至少保留一台摄影机");
|
||
return;
|
||
}
|
||
const fallback = draft.cameras.find((item) => item.id !== id);
|
||
if (!fallback) return;
|
||
commit((current) => ({
|
||
...current,
|
||
cameras: current.cameras.filter((item) => item.id !== id),
|
||
shots: current.shots.map((shot) => shot.cameraId === id ? { ...shot, cameraId: fallback.id } : shot),
|
||
}));
|
||
};
|
||
|
||
/**
|
||
* 所有「新增到场景」的唯一入口。
|
||
* 在 commit 内读取一次 placement intent:因此模型上传等异步路径拿到的是
|
||
* 「点击添加完成那一刻」的意图,而不是发起上传时捕获的过时坐标。
|
||
* 锚点只提供 XZ,Y 严格保留构造器给定值,再交给 resolveDirectorPlacement 做碰撞避让。
|
||
*/
|
||
const addObject = (object: DirectorObject) => {
|
||
commit((current) => {
|
||
const anchored = resolveDirectorPlacementAnchor({
|
||
intent: viewportRef.current?.readPlacementIntent() ?? null,
|
||
fallback: object.transform.position,
|
||
});
|
||
const position = resolveDirectorPlacement({ object: { ...object, transform: { ...object.transform, position: anchored } }, existing: current.objects });
|
||
return { ...current, objects: [...current.objects, { ...object, transform: { ...object.transform, position } }] };
|
||
});
|
||
setSelectedObjectId(object.id);
|
||
};
|
||
|
||
const addPrimitive = (primitive: DirectorObject["primitive"], name: string) => addObject(createDirectorObject(primitive, name));
|
||
|
||
const addActor = () => {
|
||
const actorCount = draft?.objects.filter((item) => item.kind === "actor").length || 0;
|
||
addObject(createDirectorActor(`演员 ${actorCount + 1}`, [0, 0, 0], DIRECTOR_ACTOR_COLORS[actorCount % DIRECTOR_ACTOR_COLORS.length]));
|
||
};
|
||
|
||
const addModelAsset = (asset: ModelAsset) => addObject(createDirectorModel({ name: asset.title, assetId: asset.id, storageKey: asset.data.storageKey, url: asset.data.url, mimeType: asset.data.mimeType }));
|
||
|
||
const uploadModel = async (file?: File) => {
|
||
if (!file || !/\.(glb|gltf)$/i.test(file.name)) return;
|
||
const uploaded = await uploadMediaFile(file, "model");
|
||
const assetId = addAsset({ kind: "model", title: file.name.replace(/\.(glb|gltf)$/i, ""), coverUrl: "", tags: ["3D模型"], source: "导演台", data: { url: uploaded.url, storageKey: uploaded.storageKey, bytes: uploaded.bytes, mimeType: uploaded.mimeType, fileName: file.name }, metadata: { source: "director" } });
|
||
const asset = useAssetStore.getState().assets.find((item): item is ModelAsset => item.id === assetId && item.kind === "model");
|
||
if (asset) addModelAsset(asset);
|
||
try {
|
||
await saveRemoteUserDataNow();
|
||
message.success("3D 模型已加入场景和素材库");
|
||
} catch (error) {
|
||
message.warning(localSavedRemotePendingMessage("3D 模型已加入场景和本机素材库", error));
|
||
}
|
||
};
|
||
|
||
const addBillboard = (node: CanvasNodeData) => {
|
||
if (!node.metadata?.content) return;
|
||
addObject(createDirectorBillboard(node.title, node.metadata.content, node.metadata.storageKey, node.id));
|
||
};
|
||
|
||
const addCamera = () => {
|
||
const camera = createDirectorCamera(`摄影机 ${draft?.cameras.length ? draft.cameras.length + 1 : 1}`);
|
||
commit((current) => ({ ...current, cameras: [...current.cameras, camera] }));
|
||
if (activeShot) updateShot(activeShot.id, { cameraId: camera.id });
|
||
};
|
||
|
||
const addLight = (type: DirectorLight["type"] = "point", label = "灯光", position: DirectorVec3 = [2, 3, 2], intensity = 1.5) => {
|
||
const light = createDirectorLight(type, `${label} ${draft?.lights.length ? draft.lights.length + 1 : 1}`, position, intensity);
|
||
commit((current) => ({ ...current, lights: [...current.lights, light] }));
|
||
setSelectedLightId(light.id);
|
||
};
|
||
|
||
const addCameraMenuItems: MenuProps["items"] = [
|
||
{ key: "camera", icon: <Camera className="size-3.5" />, label: "添加摄影机", onClick: addCamera },
|
||
];
|
||
const addLightMenuItems: MenuProps["items"] = [
|
||
{ key: "directional", icon: <Lightbulb className="size-3.5" />, label: "方向光", onClick: () => addLight("directional", "方向光", [4, 6, 4], 2.4) },
|
||
{ key: "point", icon: <Lightbulb className="size-3.5" />, label: "点光源", onClick: () => addLight("point", "点光源") },
|
||
{ key: "spot", icon: <Lightbulb className="size-3.5" />, label: "聚光灯", onClick: () => addLight("spot", "聚光灯", [2, 4, 2], 2) },
|
||
{ key: "ambient", icon: <LampDesk className="size-3.5" />, label: "环境光", onClick: () => addLight("ambient", "环境光", [0, 0, 0], 0.65) },
|
||
];
|
||
const addObjectMenuItems: MenuProps["items"] = [
|
||
{ key: "actor", icon: <UserRound className="size-3.5" />, label: "演员", onClick: addActor },
|
||
{ key: "box", icon: <Box className="size-3.5" />, label: "立方体", onClick: () => addPrimitive("box", "立方体") },
|
||
{ key: "sphere", icon: <Circle className="size-3.5" />, label: "球体", onClick: () => addPrimitive("sphere", "球体") },
|
||
{ key: "cylinder", icon: <Cuboid className="size-3.5" />, label: "圆柱", onClick: () => addPrimitive("cylinder", "圆柱") },
|
||
{ key: "model", icon: <FileUp className="size-3.5" />, label: "上传模型", onClick: () => modelInputRef.current?.click() },
|
||
];
|
||
|
||
const addShot = () => {
|
||
if (!activeCamera) return;
|
||
const shot: DirectorShot = { id: nanoid(), name: `镜头 ${(draft?.shots.length || 0) + 1}`, cameraId: activeCamera.id, duration: 5, fps: 24, shotSize: "medium", cameraMove: "static", prompt: "" };
|
||
commit((current) => ({ ...current, shots: [...current.shots, shot], activeShotId: shot.id }));
|
||
setPlayhead(0);
|
||
};
|
||
|
||
const addObjectKeyframe = () => {
|
||
if (!selectedObject) return;
|
||
// 取值用 raw playhead(视口真正渲染的时间),写入用 snapped 目的时间。
|
||
const record = resolveDirectorKeyframeRecord({ base: selectedObject.transform, keyframes: selectedObject.keyframes, rawTime: playhead, snappedTime: snappedPlayhead });
|
||
updateObject(selectedObject.id, { keyframes: record.keyframes });
|
||
};
|
||
|
||
const addCameraKeyframe = () => {
|
||
if (!activeCamera) return;
|
||
commit((current) => ({
|
||
...current,
|
||
cameras: current.cameras.map((item) => item.id === activeCamera.id
|
||
? { ...item, keyframes: resolveDirectorKeyframeRecord({ base: item.transform, keyframes: item.keyframes, rawTime: playhead, snappedTime: snappedPlayhead }).keyframes }
|
||
: item),
|
||
}));
|
||
};
|
||
|
||
const recordSelectedKeyframe = () => {
|
||
if (selectedObject && selectedBone) {
|
||
const rotation = selectedObject.boneOverrides?.[selectedBone as DirectorHumanoidBone] || [0, 0, 0, 1] as DirectorQuat;
|
||
updateObject(selectedObject.id, { boneTracks: upsertDirectorBoneKeyframe(selectedObject.boneTracks || [], selectedBone as DirectorHumanoidBone, snappedPlayhead, rotation) });
|
||
return;
|
||
}
|
||
if (selectedObject) addObjectKeyframe();
|
||
else addCameraKeyframe();
|
||
};
|
||
|
||
/**
|
||
* 时间轴删除关键帧的唯一入口。
|
||
*
|
||
* 未命中(对象/摄影机/关键帧已不存在)时 removeDirectorSceneKeyframe 返回同一引用,
|
||
* 此时不进 commit:不记历史、不产生修订、不触发保存。
|
||
*/
|
||
const deleteKeyframe = useCallback((target: DirectorKeyframeDeleteTarget) => {
|
||
const current = draftRef.current;
|
||
if (!current || removeDirectorSceneKeyframe(current, target) === current) return;
|
||
commit((scene) => removeDirectorSceneKeyframe(scene, target));
|
||
}, [commit]);
|
||
|
||
const setKeyframeEasing = useCallback((target: DirectorKeyframeDeleteTarget, easing: DirectorKeyframeEasing) => {
|
||
const current = draftRef.current;
|
||
if (!current || setDirectorSceneKeyframeEasing(current, target, easing) === current) return;
|
||
commit((scene) => setDirectorSceneKeyframeEasing(scene, target, easing));
|
||
}, [commit]);
|
||
|
||
/**
|
||
* 快捷键执行器。放在 ref 里:监听只在 open 变化时注册一次,
|
||
* 但每次渲染都能拿到最新的选择、历史和 draft,避免闭包读到过期状态。
|
||
*
|
||
* 返回值表示「动作真的执行了」,只有执行了才 preventDefault:
|
||
* 没有选中对象时的 Delete 仍然交还给浏览器。
|
||
*/
|
||
const runShortcut = (action: DirectorShortcutAction): boolean => {
|
||
switch (action.kind) {
|
||
case "transform-mode":
|
||
setTransformMode(action.mode);
|
||
return true;
|
||
case "delete-selected":
|
||
if (selectedObject) {
|
||
removeObject(selectedObject.id);
|
||
return true;
|
||
}
|
||
if (selectedLight) {
|
||
removeLight(selectedLight.id);
|
||
return true;
|
||
}
|
||
return false;
|
||
case "undo":
|
||
if (!history.length) return false;
|
||
undo();
|
||
return true;
|
||
case "redo":
|
||
if (!future.length) return false;
|
||
redo();
|
||
return true;
|
||
case "toggle-visibility":
|
||
if (!selectedObject) return false;
|
||
updateObject(selectedObject.id, { visible: !selectedObject.visible });
|
||
return true;
|
||
case "deselect":
|
||
if (!selectedObjectId && !selectedLightId && !selectedBone) return false;
|
||
setSelectedObjectId(null);
|
||
setSelectedLightId(null);
|
||
setSelectedBone(null);
|
||
return true;
|
||
case "toggle-play":
|
||
setPlaying(!playing);
|
||
return true;
|
||
}
|
||
};
|
||
const runShortcutRef = useRef(runShortcut);
|
||
runShortcutRef.current = runShortcut;
|
||
|
||
// 导演台是全屏浮层,快捷键挂在 window;焦点落在任何交互控件内时交还给该控件,
|
||
// 关键帧按钮再额外拦截自己的 Enter/Space/Delete/Backspace。
|
||
useEffect(() => {
|
||
if (!open) return;
|
||
const onKeyDown = (event: KeyboardEvent) => {
|
||
const action = resolveDirectorShortcut({
|
||
key: event.key,
|
||
ctrlKey: event.ctrlKey,
|
||
metaKey: event.metaKey,
|
||
shiftKey: event.shiftKey,
|
||
altKey: event.altKey,
|
||
isInteractiveTarget: blocksDirectorShortcut(event.target),
|
||
});
|
||
if (!action) return;
|
||
if (runShortcutRef.current(action)) event.preventDefault();
|
||
};
|
||
window.addEventListener("keydown", onKeyDown);
|
||
return () => window.removeEventListener("keydown", onKeyDown);
|
||
}, [open]);
|
||
|
||
/** 对象 transform 编辑的唯一入口:gizmo 与检查器共用同一套静态/动画语义。 */
|
||
const handleObjectTransform = useCallback((id: string, from: DirectorTransform, to: DirectorTransform) => {
|
||
commit((current) => ({
|
||
...current,
|
||
objects: current.objects.map((item) => {
|
||
if (item.id !== id) return item;
|
||
const edit = resolveDirectorObjectTransformEdit({ base: item.transform, keyframes: item.keyframes, rendered: from, edited: to, autoKey, time: snappedPlayhead });
|
||
return { ...item, transform: edit.transform, keyframes: edit.keyframes };
|
||
}),
|
||
}));
|
||
}, [autoKey, commit, snappedPlayhead]);
|
||
|
||
/** 骨骼写入语义:静态覆盖 + autoKey 时在吸附播放头补关键帧。gizmo 与数值编辑器共用。 */
|
||
const writeBoneRotation = useCallback((id: string, bone: string, rotation: DirectorQuat, mode: "stage" | "commit") => {
|
||
const write = mode === "stage" ? stageGesture : commit;
|
||
write((current) => ({
|
||
...current,
|
||
objects: current.objects.map((item) => item.id === id ? {
|
||
...item,
|
||
boneOverrides: { ...item.boneOverrides, [bone]: rotation },
|
||
boneTracks: autoKey ? upsertDirectorBoneKeyframe(item.boneTracks || [], bone as DirectorHumanoidBone, snappedPlayhead, rotation) : item.boneTracks,
|
||
} : item),
|
||
}));
|
||
}, [autoKey, commit, snappedPlayhead, stageGesture]);
|
||
|
||
const handleBoneTransform = useCallback((id: string, bone: string, rotation: DirectorQuat) => writeBoneRotation(id, bone, rotation, "commit"), [writeBoneRotation]);
|
||
|
||
const handleActorRigReady = useCallback((id: string, rig: DirectorRig, animations: AnimationClip[]) => {
|
||
replaceWithoutHistory((current) => ({
|
||
...current,
|
||
objects: current.objects.map((item) => {
|
||
if (item.id !== id) return item;
|
||
const existing = item.motionClips || [];
|
||
const motionClips = existing.length ? existing : animations.map((clip) => ({ id: nanoid(), name: clip.name || "动作片段", sourceAnimation: clip.name, start: 0, duration: Math.max(0.1, clip.duration), playbackRate: 1, loop: true }));
|
||
return { ...item, rig, motionClips };
|
||
}),
|
||
}));
|
||
}, [replaceWithoutHistory]);
|
||
|
||
const applyCameraMove = () => {
|
||
if (!activeCamera || !activeShot) return;
|
||
const cameraId = activeCamera.id;
|
||
const move = activeShot.cameraMove;
|
||
const duration = activeShot.duration;
|
||
commit((current) => ({ ...current, cameras: current.cameras.map((item) => item.id === cameraId ? { ...item, keyframes: resolveDirectorCameraMoveKeyframes(item.keyframes, item.transform, cameraMoveTransform(item.transform, move), duration) } : item) }));
|
||
message.success("已更新运镜首尾关键帧,可在动画模式继续编辑");
|
||
};
|
||
|
||
const alignCameraToView = () => {
|
||
if (!activeCamera) return;
|
||
const transform = viewportRef.current?.readCameraTransform();
|
||
if (!transform) return;
|
||
commit((current) => ({ ...current, cameras: current.cameras.map((item) => item.id === activeCamera.id ? resolveDirectorCameraAlignment(item, transform, snappedPlayhead) : item) }));
|
||
message.success("摄影机已对齐当前视图");
|
||
};
|
||
|
||
const applyToCanvas = async () => {
|
||
stagedTransaction.end("commit");
|
||
const current = draftRef.current;
|
||
if (!current || !activeShot || !viewportRef.current) return;
|
||
const expected = { scene: current, shotId: activeShot.id };
|
||
setSaving(true);
|
||
try {
|
||
const beauty = await viewportRef.current.capture("beauty");
|
||
if (!isDirectorOutputSnapshotCurrent(draftRef.current, expected)) throw new Error("输出期间场景或镜头已变化,请重试");
|
||
const prompt = compileDirectorPrompt(current, activeShot);
|
||
// 先镜像最新 scene,再做 canvas 输出;失败时 draft 保留可继续重试。
|
||
const next = touchDirectorScene(current);
|
||
writeAndPublish(next);
|
||
await onApply({ scene: next, shot: activeShot, prompt, beauty });
|
||
message.success("导演台构图已回写画布");
|
||
} catch (error) {
|
||
message.error(error instanceof Error ? error.message : "导演台输出失败");
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const exportClayVideo = async () => {
|
||
stagedTransaction.end("commit");
|
||
const current = draftRef.current;
|
||
if (!current || !activeShot || !viewportRef.current || recording) return;
|
||
const expected = { scene: current, shotId: activeShot.id };
|
||
setRecording(true);
|
||
const wasPlaying = playing;
|
||
const previousPlayhead = playhead;
|
||
setPlayhead(0);
|
||
setPlaying(true);
|
||
try {
|
||
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
|
||
const clayVideo = await viewportRef.current.recordVideo(activeShot.duration, activeShot.fps);
|
||
if (!isDirectorOutputSnapshotCurrent(draftRef.current, expected)) throw new Error("录制期间场景或镜头已变化,请重试");
|
||
const next = touchDirectorScene(draftRef.current || current);
|
||
writeAndPublish(next);
|
||
const beauty = await viewportRef.current.capture("beauty");
|
||
if (!isDirectorOutputSnapshotCurrent(draftRef.current, { scene: next, shotId: expected.shotId })) throw new Error("输出期间场景或镜头已变化,请重试");
|
||
await onApply({ scene: next, shot: activeShot, prompt: compileDirectorPrompt(next, activeShot), beauty, clayVideo, clayVideoMimeType: clayVideo.type });
|
||
message.success("白膜视频已回写画布");
|
||
} catch (error) {
|
||
message.error(error instanceof Error ? error.message : "白膜视频导出失败");
|
||
} finally {
|
||
setPlaying(wasPlaying);
|
||
setPlayhead(previousPlayhead);
|
||
setRecording(false);
|
||
}
|
||
};
|
||
|
||
const quickActors = draft?.objects.filter((item) => item.kind === "actor" || item.primitive === "character") || [];
|
||
const quickSelectedActor = quickActors.find((item) => item.id === selectedObjectId) || quickActors[0] || null;
|
||
const handleQuickGroundClick = useCallback((point: DirectorGroundPoint) => {
|
||
if (!quickSelectedActor) {
|
||
message.info("先添加或选择一个演员");
|
||
return;
|
||
}
|
||
setSelectedObjectId(quickSelectedActor.id);
|
||
handleObjectTransform(quickSelectedActor.id, quickSelectedActor.transform, {
|
||
...quickSelectedActor.transform,
|
||
position: [point.x, quickSelectedActor.transform.position[1], point.z],
|
||
});
|
||
message.success("演员已落位");
|
||
}, [handleObjectTransform, message, quickSelectedActor]);
|
||
const quickPoseOptions: Array<{ value: DirectorPose; label: string }> = [
|
||
{ value: "stand", label: "站立" },
|
||
{ value: "sit", label: "坐下" },
|
||
{ value: "walk", label: "走动" },
|
||
{ value: "wave", label: "挥手" },
|
||
{ value: "think", label: "思考" },
|
||
{ value: "fight", label: "对抗" },
|
||
];
|
||
const applyQuickPose = (pose: DirectorPose) => {
|
||
if (!quickSelectedActor) {
|
||
message.info("先添加或选择一个演员");
|
||
return;
|
||
}
|
||
setSelectedObjectId(quickSelectedActor.id);
|
||
updateObject(quickSelectedActor.id, { pose, activeMotionClipId: undefined, boneOverrides: {} });
|
||
};
|
||
const placeQuickActor = () => {
|
||
if (!quickSelectedActor) {
|
||
message.info("先添加或选择一个演员");
|
||
return;
|
||
}
|
||
const intent = viewportRef.current?.readPlacementIntent();
|
||
const point = intent?.pointer || intent?.orbitTarget;
|
||
if (!point) {
|
||
message.info("先在视口里移动鼠标到地面,或旋转视图后再落位");
|
||
return;
|
||
}
|
||
setSelectedObjectId(quickSelectedActor.id);
|
||
handleObjectTransform(quickSelectedActor.id, quickSelectedActor.transform, { ...quickSelectedActor.transform, position: [point.x, quickSelectedActor.transform.position[1], point.z] });
|
||
};
|
||
const addQuickActor = () => {
|
||
addActor();
|
||
message.success("演员已加入;直接点击视口地面即可落位");
|
||
};
|
||
const selectQuickShotSize = (shotSize: DirectorShotSize) => {
|
||
if (activeShot) updateShot(activeShot.id, { shotSize });
|
||
};
|
||
const selectQuickCameraMove = (move: DirectorCameraMove) => {
|
||
if (activeShot) updateShot(activeShot.id, { cameraMove: move });
|
||
};
|
||
|
||
useEffect(() => {
|
||
const onPreviewRequested = (event: Event) => {
|
||
const detail = (event as CustomEvent<{ sceneId?: string; shotId?: string; duration?: number; fps?: number }>).detail;
|
||
if (!detail || detail.sceneId !== draft?.id || (detail.shotId && detail.shotId !== activeShot?.id)) return;
|
||
void exportClayVideo();
|
||
};
|
||
window.addEventListener("director:preview-requested", onPreviewRequested);
|
||
return () => window.removeEventListener("director:preview-requested", onPreviewRequested);
|
||
}, [activeShot?.id, draft?.id, exportClayVideo]);
|
||
|
||
if (!open || !draft || !activeShot) return null;
|
||
|
||
return (
|
||
<div data-canvas-director-workbench data-canvas-no-zoom className="fixed inset-0 z-[var(--z-toast)] flex min-h-0 flex-col overflow-hidden" style={{ background: theme.canvas.background, color: theme.node.text }}>
|
||
<header className="thin-scrollbar flex h-12 shrink-0 items-center gap-2 overflow-x-auto overflow-y-hidden border-b px-2" style={{ background: theme.toolbar.panel, borderColor: theme.toolbar.border }}>
|
||
<IconButton label="关闭导演台" onClick={closeWorkbench}><X className="size-4" /></IconButton>
|
||
<Input variant="borderless" value={draft.title} className="max-w-56 font-medium" onChange={(event) => replaceWithoutHistory((current) => ({ ...current, title: event.target.value }))} />
|
||
<span className="h-5 w-px" style={{ background: theme.toolbar.border }} />
|
||
<IconButton label="撤销" disabled={!history.length} onClick={undo}><Undo2 className="size-4" /></IconButton>
|
||
<IconButton label="重做" disabled={!future.length} onClick={redo}><Redo2 className="size-4" /></IconButton>
|
||
<span className="h-5 w-px" style={{ background: theme.toolbar.border }} />
|
||
{/* 一级模式切换:小屏也必须可达,因此不加 max-lg:hidden。 */}
|
||
<button
|
||
type="button"
|
||
className={`director-mode-switch-button ${quickMode ? "is-active" : ""}`}
|
||
aria-pressed={quickMode}
|
||
title="用镜头优先的最短路径完成摆位、姿态和预演"
|
||
onClick={() => setQuickMode(true)}
|
||
>
|
||
快速镜头
|
||
</button>
|
||
<button
|
||
type="button"
|
||
className={`director-mode-switch-button ${!quickMode ? "is-active" : ""}`}
|
||
aria-pressed={!quickMode}
|
||
title="打开完整的摆场、姿态、动画和摄影机工具"
|
||
onClick={() => setQuickMode(false)}
|
||
>
|
||
高级工作台
|
||
</button>
|
||
{!quickMode ? <nav className="director-mode-switch" aria-label="导演台模式">
|
||
{DIRECTOR_MODES.map((item) => (
|
||
<button
|
||
key={item.mode}
|
||
type="button"
|
||
data-mode={item.mode}
|
||
className={`director-mode-switch-button ${mode === item.mode ? "is-active" : ""}`}
|
||
aria-pressed={mode === item.mode}
|
||
title={item.hint}
|
||
onClick={(event) => {
|
||
setMode(item.mode);
|
||
// 焦点留在模式按钮上会让守卫吃掉 W/E/R/Delete。
|
||
releaseDirectorFocusAfterPointer(event);
|
||
}}
|
||
>
|
||
{item.label}
|
||
</button>
|
||
))}
|
||
</nav> : null}
|
||
<div className="ml-auto flex items-center gap-2">
|
||
<span
|
||
aria-live="polite"
|
||
className="text-[var(--fs-tiny)]"
|
||
style={{ color: saveIndicator.tone === "danger" ? "var(--status-error)" : undefined, opacity: saveIndicator.tone === "idle" ? 0.55 : 1 }}
|
||
>
|
||
{saveIndicator.label}
|
||
</span>
|
||
{saveIndicator.retryable ? <Button size="small" icon={<RotateCcw className="size-3.5" />} loading={retrying || saveIndicator.busy} onClick={() => void retrySave()}>重试保存</Button> : null}
|
||
</div>
|
||
<div className="flex items-center gap-1">
|
||
{onboardingScope ? <IconButton label="重新开始引导" onClick={() => setOnboardingRestartSignal((value) => value + 1)}><Lightbulb className="size-4" /></IconButton> : null}
|
||
<Select size="small" value={renderMode} className="w-24" options={renderModeOptions} onChange={setRenderMode} />
|
||
<Button size="small" icon={<Video className="size-3.5" />} loading={recording} onClick={() => void exportClayVideo()}>导出白膜</Button>
|
||
<Button size="small" type="primary" icon={<Save className="size-3.5" />} loading={saving} onClick={() => void applyToCanvas()}>应用到镜头</Button>
|
||
</div>
|
||
</header>
|
||
|
||
{quickMode ? <div className="grid min-h-0 flex-1 grid-cols-[minmax(220px,280px)_minmax(0,1fr)_minmax(260px,320px)] max-lg:grid-cols-[180px_minmax(0,1fr)]">
|
||
<aside className="thin-scrollbar min-h-0 overflow-y-auto border-r p-3" style={{ background: theme.node.panel, borderColor: theme.toolbar.border }}>
|
||
<div className="mb-3 flex items-center justify-between">
|
||
<div>
|
||
<div className="text-sm font-semibold">镜头对象</div>
|
||
<div className="text-[var(--fs-tiny)] opacity-55">先解决站位和关系,不先建复杂模型</div>
|
||
</div>
|
||
<Button size="small" type="primary" icon={<Plus className="size-3.5" />} onClick={addQuickActor}>演员</Button>
|
||
</div>
|
||
<div className="space-y-1">
|
||
{quickActors.map((actor) => <button key={actor.id} type="button" className={`flex w-full items-center gap-2 rounded-md border px-2.5 py-2 text-left text-sm transition-colors ${quickSelectedActor?.id === actor.id ? "border-[var(--accent-primary)] bg-[var(--accent-primary)]/10" : "border-transparent hover:bg-black/5 dark:hover:bg-white/5"}`} onClick={() => setSelectedObjectId(actor.id)}>
|
||
<span className="flex size-7 items-center justify-center rounded-full text-white" style={{ background: actor.color }}><UserRound className="size-3.5" /></span>
|
||
<span className="min-w-0 flex-1 truncate">{actor.name}</span>
|
||
<span className="text-[var(--fs-tiny)] opacity-45">{actor.pose ? directorPoseLabel(actor.pose) : "站立"}</span>
|
||
</button>)}
|
||
</div>
|
||
{!quickActors.length ? <div className="rounded-lg border border-dashed p-4 text-center text-xs opacity-60">还没有演员<br />先加一个人偶,再用镜头完成预演</div> : null}
|
||
<div className="mt-5 rounded-lg border p-3" style={{ borderColor: theme.toolbar.border }}>
|
||
<div className="mb-2 flex items-center gap-2 text-sm font-medium"><MousePointer2 className="size-4" />快速落位</div>
|
||
<p className="mb-3 text-xs leading-5 opacity-60">直接点击视口地面即可落位;也可以先移动鼠标,再用按钮落到当前指针位置。无需输入 XYZ。</p>
|
||
<Button block size="small" disabled={!quickSelectedActor} onClick={placeQuickActor}>按当前指针落位</Button>
|
||
</div>
|
||
</aside>
|
||
<main className="relative min-h-0 overflow-hidden bg-neutral-900">
|
||
<DirectorViewport ref={viewportRef} scene={draft} selectedObjectId={quickSelectedActor?.id || null} selectedBone={null} transformMode="translate" renderMode="clay" playhead={0} playing={false} showMotionPaths={false} viewMode={viewMode} onViewModeChange={setViewMode} onSelectObject={setSelectedObjectId} onSelectBone={setSelectedBone} onGroundClick={handleQuickGroundClick} onObjectTransform={handleObjectTransform} onBoneTransform={handleBoneTransform} onActorRigReady={handleActorRigReady} />
|
||
<div className="pointer-events-none absolute left-3 top-3 flex items-center gap-2 rounded-md bg-black/35 px-2.5 py-1.5 text-xs font-medium text-white/80"><WandSparkles className="size-3.5" />{activeShot.name} · {activeCamera?.name || "无摄影机"}</div>
|
||
<div className="absolute bottom-3 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-lg border border-white/10 bg-black/55 p-1.5 text-white shadow-lg">
|
||
<span className="px-2 text-xs text-white/65">白模预演</span>
|
||
<Button size="small" ghost icon={<Video className="size-3.5" />} loading={recording} onClick={() => void exportClayVideo()}>生成预演</Button>
|
||
<Button size="small" type="primary" icon={<Save className="size-3.5" />} loading={saving} onClick={() => void applyToCanvas()}>应用镜头</Button>
|
||
</div>
|
||
</main>
|
||
<aside className="thin-scrollbar min-h-0 overflow-y-auto border-l p-3" style={{ background: theme.node.panel, borderColor: theme.toolbar.border }}>
|
||
<div className="mb-4 flex items-center justify-between"><div><div className="text-sm font-semibold">镜头卡</div><div className="text-[var(--fs-tiny)] opacity-55">用语义参数替代工程参数</div></div><Camera className="size-4 opacity-45" /></div>
|
||
<div className="mb-4 grid grid-cols-3 gap-1.5">{(["wide", "full", "medium", "close_up", "extreme_close_up"] as DirectorShotSize[]).map((size) => <button key={size} type="button" className={`rounded-md border px-2 py-2 text-xs ${activeShot.shotSize === size ? "border-[var(--accent-primary)] bg-[var(--accent-primary)]/10" : "border-transparent bg-black/5 dark:bg-white/5"}`} onClick={() => selectQuickShotSize(size)}>{({ wide: "全景", full: "全身", medium: "中景", close_up: "近景", extreme_close_up: "特写" } as Record<string, string>)[size]}</button>)}</div>
|
||
<div className="mb-4"><div className="mb-2 text-xs font-medium opacity-65">姿态</div><div className="grid grid-cols-3 gap-1.5">{quickPoseOptions.map((option) => <button key={option.value} type="button" disabled={!quickSelectedActor} className={`rounded-md border px-2 py-2 text-xs disabled:cursor-not-allowed disabled:opacity-35 ${quickSelectedActor?.pose === option.value ? "border-[var(--accent-primary)] bg-[var(--accent-primary)]/10" : "border-transparent bg-black/5 dark:bg-white/5"}`} onClick={() => applyQuickPose(option.value)}>{option.label}</button>)}</div></div>
|
||
<div className="mb-4"><div className="mb-2 text-xs font-medium opacity-65">运镜</div><Select className="w-full" size="small" value={activeShot.cameraMove} options={[{ value: "static", label: "固定" }, { value: "push_in", label: "推进" }, { value: "pull_out", label: "拉远" }, { value: "pan_left", label: "左摇" }, { value: "pan_right", label: "右摇" }, { value: "handheld", label: "手持" }]} onChange={selectQuickCameraMove} /></div>
|
||
<div className="space-y-2"><Button block size="small" icon={<Focus className="size-3.5" />} onClick={alignCameraToView}>用当前视图设机位</Button><Button block size="small" onClick={applyCameraMove}>生成运镜</Button></div>
|
||
<div className="mt-5 rounded-lg border p-3 text-xs leading-5 opacity-70" style={{ borderColor: theme.toolbar.border }}><div className="mb-1 font-medium opacity-100">给视频模型的参考</div>白模只负责镜头、动作和空间关系;生成真实人体比例,不沿用白模轮廓。</div>
|
||
</aside>
|
||
</div> : null}
|
||
{!quickMode ? <>
|
||
<div className="grid min-h-0 flex-1 grid-cols-[220px_minmax(0,1fr)_292px] max-lg:grid-cols-[180px_minmax(0,1fr)]">
|
||
<aside className="thin-scrollbar min-h-0 overflow-y-auto border-r" style={{ background: theme.node.panel, borderColor: theme.toolbar.border }}>
|
||
<PanelTitle title="场景对象" action={<AddMenuButton label="添加场景对象" items={addObjectMenuItems} />} />
|
||
<div className="px-2 pb-2">
|
||
{draft.objects.map((object) => <SceneRow key={object.id} active={selectedObjectId === object.id} icon={object.kind === "actor" || object.primitive === "character" ? <UserRound /> : object.kind === "model" ? <BoxSelect /> : object.kind === "billboard" ? <ImageIcon /> : <Cuboid />} label={object.name} onClick={() => setSelectedObjectId(object.id)} onDelete={() => removeObject(object.id)} />)}
|
||
</div>
|
||
<PanelTitle title="摄影机" action={<AddMenuButton label="添加摄影机" items={addCameraMenuItems} />} />
|
||
<div className="px-2 pb-2">{draft.cameras.map((camera) => <SceneRow key={camera.id} active={activeShot.cameraId === camera.id && !selectedObjectId && !selectedLightId} icon={<Camera />} label={camera.name} onClick={() => { setSelectedObjectId(null); setSelectedLightId(null); updateShot(activeShot.id, { cameraId: camera.id }); }} onDelete={() => removeCamera(camera.id)} />)}</div>
|
||
<PanelTitle title="灯光" action={<AddMenuButton label="添加灯光" items={addLightMenuItems} />} />
|
||
<div className="px-2 pb-2">{draft.lights.map((light) => <SceneRow key={light.id} active={selectedLightId === light.id} icon={<Lightbulb />} label={light.name} onClick={() => setSelectedLightId(light.id)} onDelete={() => removeLight(light.id)} />)}</div>
|
||
<PanelTitle title="快速添加" />
|
||
<div className="grid grid-cols-2 gap-1.5 px-2 pb-3">
|
||
<QuickAdd label="演员" icon={<UserRound />} onClick={addActor} />
|
||
<QuickAdd label="立方体" icon={<Box />} onClick={() => addPrimitive("box", "立方体")} />
|
||
<QuickAdd label="球体" icon={<Circle />} onClick={() => addPrimitive("sphere", "球体")} />
|
||
<QuickAdd label="圆柱" icon={<Cuboid />} onClick={() => addPrimitive("cylinder", "圆柱")} />
|
||
<QuickAdd label="上传模型" icon={<FileUp />} onClick={() => modelInputRef.current?.click()} />
|
||
<QuickAdd label="添加灯光" icon={<LampDesk />} onClick={addLight} />
|
||
</div>
|
||
{modelAssets.length ? <><PanelTitle title="3D 素材" /><div className="px-2 pb-3">{modelAssets.map((asset) => <SceneRow key={asset.id} icon={<BoxSelect />} label={asset.title} onClick={() => addModelAsset(asset)} />)}</div></> : null}
|
||
{imageNodes.length ? <><PanelTitle title="画布图片立牌" /><div className="px-2 pb-3">{imageNodes.slice(0, 20).map((node) => <SceneRow key={node.id} icon={<ImageIcon />} label={node.title} onClick={() => addBillboard(node)} onDelete={() => onDeleteImageNode(node.id)} />)}</div></> : null}
|
||
<input ref={modelInputRef} type="file" accept=".glb,.gltf,model/gltf-binary,model/gltf+json" className="hidden" onChange={(event) => { void uploadModel(event.target.files?.[0]); event.currentTarget.value = ""; }} />
|
||
</aside>
|
||
|
||
<main className="relative min-h-0 overflow-hidden bg-neutral-900">
|
||
<DirectorViewport ref={viewportRef} scene={draft} selectedObjectId={selectedObjectId} selectedBone={selectedBone} transformMode={transformMode} renderMode={renderMode} playhead={playhead} playing={playing} showMotionPaths={capabilities.timeline} viewMode={viewMode} onViewModeChange={setViewMode} onSelectObject={setSelectedObjectId} onSelectBone={setSelectedBone} onObjectTransform={handleObjectTransform} onBoneTransform={handleBoneTransform} onActorRigReady={handleActorRigReady} />
|
||
<div className="pointer-events-none absolute left-3 top-3 text-[var(--fs-tiny)] font-medium text-white/70">{activeShot.name} · {activeCamera?.name || "无摄影机"} · {activeShot.duration}s</div>
|
||
<CanvasDirectorOnboarding scope={onboardingScope} open={open} restartSignal={onboardingRestartSignal} className="absolute right-3 top-3 z-[var(--z-popover)] w-[min(360px,calc(100%-24px))]" />
|
||
<DirectorViewportDock transformMode={transformMode} renderMode={renderMode} renderModes={capabilities.renderModes} onTransformModeChange={setTransformMode} onRenderModeChange={setRenderMode} onAddActor={addActor} onAddBox={() => addPrimitive("box", "立方体")} onAddLight={addLight} onAddCamera={addCamera} onAlignCamera={alignCameraToView} />
|
||
</main>
|
||
|
||
<aside className="thin-scrollbar min-h-0 overflow-y-auto border-l max-lg:col-span-2 max-lg:max-h-[40vh] max-lg:border-l-0 max-lg:border-t" style={{ background: theme.node.panel, borderColor: theme.toolbar.border }}>
|
||
{/* 摄影机模式下右栏固定显示 shot/camera 检查器:对齐视图与运镜是这个模式的主入口。 */}
|
||
{selectedObject && !capabilities.cameraTools ? <ObjectInspector object={selectedObject} rendered={selectedObjectRendered || selectedObject.transform} playhead={snappedPlayhead} selectedBone={selectedBone} capabilities={capabilities} onSelectBone={setSelectedBone} onUpdate={(patch) => updateObject(selectedObject.id, patch)} onTransformEdit={(edited) => handleObjectTransform(selectedObject.id, selectedObjectRendered || selectedObject.transform, edited)} onBoneRotationStage={(rotation) => selectedBone && writeBoneRotation(selectedObject.id, selectedBone, rotation, "stage")} onBoneRotationCommit={() => stagedTransaction.end("commit")} onAddKeyframe={recordSelectedKeyframe} onDelete={() => removeObject(selectedObject.id)} /> : selectedLight && !capabilities.cameraTools ? <LightInspector light={selectedLight} onUpdate={(patch) => updateLight(selectedLight.id, patch)} onDelete={() => removeLight(selectedLight.id)} /> : <ShotInspector shot={activeShot} camera={activeCamera} cameras={draft.cameras} capabilities={capabilities} onUpdateShot={(patch) => updateShot(activeShot.id, patch)} onUpdateCamera={(patch) => activeCamera && commit((current) => ({ ...current, cameras: current.cameras.map((item) => item.id === activeCamera.id ? { ...item, ...patch } : item) }))} onAddCameraKeyframe={addCameraKeyframe} onApplyCameraMove={applyCameraMove} onAlignCameraToView={alignCameraToView} onExportClay={() => void exportClayVideo()} recording={recording} />}
|
||
</aside>
|
||
</div>
|
||
|
||
{/* 时间轴只属于动画模式:其他模式下它不渲染,Auto Key 与录制入口一并消失。 */}
|
||
{capabilities.timeline ? <DirectorSequencer scene={draft} shot={activeShot} camera={activeCamera} objects={draft.objects} selectedObjectId={selectedObjectId} selectedBone={selectedBone} playhead={playhead} playing={playing} autoKey={autoKey} height={sequencerHeight} visible={sequencerVisible} onPlayToggle={() => setPlaying(!playing)} onPlayheadChange={setPlayhead} onAutoKeyChange={setAutoKey} onHeightChange={setSequencerHeight} onVisibilityChange={setSequencerVisible} onSelectObject={setSelectedObjectId} onSelectBone={setSelectedBone} onRecordKeyframe={recordSelectedKeyframe} onAddShot={addShot} onDeleteKeyframe={deleteKeyframe} onSetKeyframeEasing={setKeyframeEasing} onSelectShot={(id) => { commit((current) => ({ ...current, activeShotId: id })); setPlayhead(0); }} /> : null}
|
||
</> : null}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** 渲染视图全集。实际可选项由当前模式的 capabilities.renderModes 过滤。 */
|
||
const DIRECTOR_RENDER_MODE_LABELS: Array<{ label: string; value: DirectorRenderMode }> = [
|
||
{ label: "预览", value: "beauty" },
|
||
{ label: "彩色白膜", value: "clay" },
|
||
{ label: "骨骼", value: "pose" },
|
||
{ label: "深度", value: "depth" },
|
||
{ label: "法线", value: "normal" },
|
||
];
|
||
|
||
function cameraMoveTransform(transform: DirectorTransform, move: DirectorCameraMove): DirectorTransform {
|
||
const [x, y, z] = transform.position;
|
||
const offsets: Record<DirectorCameraMove, DirectorVec3> = { static: [0, 0, 0], push_in: [0, 0, -2], pull_out: [0, 0, 2], pan_left: [-2, 0, 0], pan_right: [2, 0, 0], tilt_up: [0, 1.5, 0], tilt_down: [0, -1.2, 0], orbit_left: [-2.5, 0, -1.5], orbit_right: [2.5, 0, -1.5], handheld: [0.18, 0.08, -0.15] };
|
||
const offset = offsets[move];
|
||
return { ...transform, position: [x + offset[0], y + offset[1], z + offset[2]] };
|
||
}
|