Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(desktop): add 3D camera timeline track and editor panel
Richie McIlroy96f9ffd7ae54
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsxindex fce6f7a95..08cf05fc7 100644--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx@@ -1,3 +1,4 @@+import { Button } from "@cap/ui-solid";import { NumberField } from "@kobalte/core";import {Collapsible,@@ -31,9 +32,11 @@ import {createSignal,For,Index,+ type JSX,lazy,on,onMount,+ type ParentProps,Show,Suspense,type ValidComponent,@@ -75,15 +78,19 @@ import {type XY,type ZoomSegment,} from "~/utils/tauri";+import IconLucideArrowLeftRight from "~icons/lucide/arrow-left-right";import IconLucideBoxSelect from "~icons/lucide/box-select";import IconLucideColumns2 from "~icons/lucide/columns-2";import IconLucideEyeOff from "~icons/lucide/eye-off";+import IconLucideFlipHorizontal2 from "~icons/lucide/flip-horizontal-2";+import IconLucideFlipVertical2 from "~icons/lucide/flip-vertical-2";import IconLucideGrid from "~icons/lucide/grid";import IconLucideImageOff from "~icons/lucide/image-off";import IconLucideKeyboard from "~icons/lucide/keyboard";import IconLucideLaptop from "~icons/lucide/laptop";import IconLucideMonitor from "~icons/lucide/monitor";import IconLucideMoon from "~icons/lucide/moon";+import IconLucideMoveRight from "~icons/lucide/move-right";import IconLucideMusic from "~icons/lucide/music";import IconLucidePalette from "~icons/lucide/palette";import IconLucideRabbit from "~icons/lucide/rabbit";@@ -130,6 +137,41 @@ import {TEXT_FONT_SIZE_MIN,type TextSegment,} from "./text";+import {+ ANGLE_PRESETS,+ anglePresetMotion,+ anglePresetPose,+ applyMotionTemplate,+ CAMERA3D_BLUR_MODE_SEEDS,+ CAMERA3D_BOKEH_MAX_STRENGTH,+ CAMERA3D_LIMITS,+ CAMERA3D_MIN_SHOT_DURATION,+ CAMERA3D_RESET_POSE,+ CAMERA3D_SCENES,+ CAMERA3D_TRANSITION_LIMITS,+ type Camera3DAnglePreset,+ type Camera3DBlurMode,+ type Camera3DBlurScalarKey,+ type Camera3DFlipAxis,+ type Camera3DMotionEasing,+ type Camera3DMotionTemplate,+ type Camera3DProperties,+ type Camera3DPropertyKey,+ type Camera3DScene,+ type Camera3DSegment,+ camera3DPosesEqual,+ camera3dBlurLimit,+ cssPreviewTransform,+ defaultCamera3DBlur,+ flipCamera3DSegment,+ getEndPose,+ getMotionEasing,+ getStartPose,+ MOTION_EASINGS,+ MOTION_TEMPLATES,+ matchAnglePreset,+ setMotion,+} from "./three-d";import {ComingSoonTooltip,EditorButton,@@ -515,7 +557,8 @@ export function ConfigSidebar() {<KTabsvalue={editorState.timeline.selection ||- editorState.timeline.audioPicker !== null+ editorState.timeline.audioPicker !== null ||+ editorState.timeline.camera3dSetup !== null? undefined: state.selectedTab}@@ -569,6 +612,9 @@ export function ConfigSidebar() {if (editorState.timeline.audioReplace !== null) {setEditorState("timeline", "audioReplace", null);}+ if (editorState.timeline.camera3dSetup !== null) {+ setEditorState("timeline", "camera3dSetup", null);+ }setState("selectedTab", item.id);scrollRef.scrollTo({top: 0,@@ -593,7 +639,8 @@ export function ConfigSidebar() {<Showwhen={!editorState.timeline.selection &&- editorState.timeline.audioPicker === null+ editorState.timeline.audioPicker === null &&+ editorState.timeline.camera3dSetup === null}><KTabs.Indicator class="absolute top-0 left-0 w-full h-full transition-transform duration-200 ease-in-out pointer-events-none will-change-transform">@@ -611,7 +658,8 @@ export function ConfigSidebar() {hidden:!!editorState.timeline.selection ||editorState.timeline.audioPicker !== null ||- editorState.timeline.audioReplace !== null,+ editorState.timeline.audioReplace !== null ||+ editorState.timeline.camera3dSetup !== null,}}><BackgroundConfig@@ -1006,11 +1054,13 @@ export function ConfigSidebar() {hidden:!editorState.timeline.selection &&editorState.timeline.audioPicker === null &&- editorState.timeline.audioReplace === null,+ editorState.timeline.audioReplace === null &&+ editorState.timeline.camera3dSetup === null,"animate-in slide-in-from-bottom-2 fade-in":!!editorState.timeline.selection ||editorState.timeline.audioPicker !== null ||- editorState.timeline.audioReplace !== null,+ editorState.timeline.audioReplace !== null ||+ editorState.timeline.camera3dSetup !== null,}}><Show@@ -1028,6 +1078,22 @@ export function ConfigSidebar() {onClose={() => setEditorState("timeline", "audioPicker", null)}/></Show>+ <Show+ when={+ !editorState.timeline.selection &&+ editorState.timeline.audioPicker === null &&+ editorState.timeline.audioReplace === null+ ? editorState.timeline.camera3dSetup+ : null+ }+ >+ {(setup) => (+ <Camera3DSetupPanel+ setup={setup()}+ onClose={() => setEditorState("timeline", "camera3dSetup", null)}+ />+ )}+ </Show><Showwhen={(() => {const index = editorState.timeline.audioReplace;@@ -1492,6 +1558,79 @@ export function ConfigSidebar() {</div>)}</Show>+ <Show+ when={(() => {+ const camera3dSelection = selection();+ if (camera3dSelection.type !== "3d") return;++ const segments = camera3dSelection.indices+ .map((index) => ({+ index,+ segment: project.timeline?.camera3dSegments?.[index],+ }))+ .filter(+ (+ item,+ ): item is { index: number; segment: Camera3DSegment } =>+ item.segment !== undefined,+ );++ if (segments.length === 0) {+ setEditorState("timeline", "selection", null);+ return;+ }+ return { selection: camera3dSelection, segments };+ })()}+ >+ {(value) => (+ <div class="space-y-4">+ <div class="flex flex-row justify-between items-center">+ <div class="flex gap-2 items-center">+ <EditorButton+ onClick={() =>+ setEditorState("timeline", "selection", null)+ }+ leftIcon={<IconLucideCheck />}+ >+ Done+ </EditorButton>+ <span class="text-sm text-gray-10">+ {value().segments.length} 3D{" "}+ {value().segments.length === 1+ ? "segment"+ : "segments"}{" "}+ selected+ </span>+ </div>+ <EditorButton+ variant="danger"+ onClick={() => {+ projectActions.deleteCamera3DSegments(+ value().segments.map((s) => s.index),+ );+ }}+ leftIcon={<IconCapTrash />}+ >+ Delete+ </EditorButton>+ </div>+ <Show+ when={+ value().segments.length === 1 && value().segments[0]+ }+ >+ {(item) => (+ <div class="p-4 rounded-lg border border-gray-200">+ <Camera3DSegmentConfig+ segment={item().segment}+ segmentIndex={item().index}+ />+ </div>+ )}+ </Show>+ </div>+ )}+ </Show><Showwhen={(() => {const sceneSelection = selection();@@ -4070,6 +4209,910 @@ function MaskSegmentConfig(props: {);}+const CAMERA3D_SLIDERS: Array<{+ key: Camera3DPropertyKey;+ label: string;+ unit: string;+}> = [+ { key: "tiltX", label: "Tilt X", unit: "°" },+ { key: "tiltY", label: "Tilt Y", unit: "°" },+ { key: "roll", label: "Roll", unit: "°" },+ { key: "rotateX", label: "Rotate X", unit: "°" },+ { key: "rotateY", label: "Rotate Y", unit: "°" },+ { key: "fov", label: "Field of view", unit: "°" },+ { key: "zoom", label: "Zoom", unit: "" },+ { key: "panX", label: "Pan X", unit: "" },+ { key: "panY", label: "Pan Y", unit: "" },+];++function camera3dSliderIcon(key: Camera3DPropertyKey) {+ switch (key) {+ case "roll":+ return <IconLucideRotateCw class="size-4" />;+ case "fov":+ return <IconLucideMaximize class="size-4" />;+ case "zoom":+ return <IconLucideSearch class="size-4" />;+ case "panX":+ case "panY":+ return <IconLucideMove class="size-4" />;+ default:+ return <IconLucideRotate3d class="size-4" />;+ }+}++const CAMERA3D_BLUR_MODE_OPTIONS: Array<{+ value: Camera3DBlurMode;+ label: string;+}> = [+ { value: "none", label: "None" },+ { value: "radial", label: "Radial" },+ { value: "directional", label: "Directional" },+ { value: "tiltShift", label: "Tilt Shift" },+];++type Camera3DBlurSlider = {+ key: Camera3DBlurScalarKey;+ label: string;+ unit: string;+};++// Each mode exposes only the parameters it actually reads, in display order.+const CAMERA3D_BLUR_SLIDERS: Record<+ Exclude<Camera3DBlurMode, "none">,+ Camera3DBlurSlider[]+> = {+ radial: [+ { key: "strength", label: "Strength", unit: "" },+ { key: "focusX", label: "Focus X", unit: "" },+ { key: "focusY", label: "Focus Y", unit: "" },+ { key: "focusSize", label: "Focus size", unit: "" },+ { key: "falloff", label: "Falloff", unit: "" },+ ],+ directional: [+ { key: "strength", label: "Strength", unit: "" },+ { key: "angle", label: "Angle", unit: "°" },+ { key: "dirPosition", label: "Position", unit: "" },+ { key: "falloff", label: "Falloff", unit: "" },+ ],+ tiltShift: [+ { key: "strength", label: "Strength", unit: "" },+ { key: "focusY", label: "Scan", unit: "" },+ { key: "focusSize", label: "Focus size", unit: "" },+ { key: "angle", label: "Angle", unit: "°" },+ { key: "falloff", label: "Falloff", unit: "" },+ ],+};++function Camera3DTransitionInput(props: {+ label: string;+ value: number;+ onChange: (value: number) => void;+}) {+ const [text, setText] = createWritableMemo(() => props.value.toString());++ return (+ <div class="flex flex-row justify-between items-center">+ <span class="text-xs text-gray-11">{props.label}</span>+ <div class="flex flex-row gap-1 items-center">+ <NumberField.Root+ value={text()}+ onChange={setText}+ rawValue={props.value}+ onRawValueChange={(value) => {+ if (Number.isNaN(value)) return;+ props.onChange(+ Math.min(+ Math.max(value, CAMERA3D_TRANSITION_LIMITS.min),+ CAMERA3D_TRANSITION_LIMITS.max,+ ),+ );+ }}+ minValue={CAMERA3D_TRANSITION_LIMITS.min}+ maxValue={CAMERA3D_TRANSITION_LIMITS.max}+ step={CAMERA3D_TRANSITION_LIMITS.step}+ >+ <NumberField.Input+ onBlur={() => {+ if (text() === "" || Number.isNaN(props.value)) {+ setText("0");+ props.onChange(0);+ }+ }}+ class="w-20 p-1.5 border rounded-lg bg-gray-1 focus-visible:outline-hidden"+ />+ </NumberField.Root>+ <span class="text-gray-11">s</span>+ </div>+ </div>+ );+}++const CAMERA3D_ANGLE_PREVIEW_HEIGHT = 30;+const CAMERA3D_TEMPLATE_PREVIEW_HEIGHT = 40;+/** Scenes lead the section and are three across, so their cards read taller. */+const CAMERA3D_SCENE_PREVIEW_HEIGHT = 48;+/** The two pose cards are the panel's main control, so they read larger. */+const CAMERA3D_POSE_PREVIEW_HEIGHT = 56;+const CAMERA3D_PREVIEW_TRANSITION = "700ms ease-in-out";++/**+ * A `Field` that folds away. The header keeps the Field rhythm so a closed+ * section reads as one more label in the column, with an optional summary that+ * shows the state without opening it.+ */+function Camera3DSection(+ props: ParentProps<{+ name: string;+ icon: JSX.Element;+ summary?: string;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ }>,+) {+ return (+ <KCollapsible open={props.open} onOpenChange={props.onOpenChange}>+ <KCollapsible.Trigger class="flex flex-row gap-1.5 items-center w-full text-sm font-medium group text-gray-12 outline-hidden">+ {props.icon}+ {props.name}+ <span class="flex flex-row gap-1.5 items-center ml-auto text-xs font-normal text-gray-10">+ {props.summary}+ <IconCapChevronDown class="transition-transform duration-200 size-3.5 group-data-expanded:rotate-180" />+ </span>+ </KCollapsible.Trigger>+ <KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">+ <div class="pt-4">{props.children}</div>+ </KCollapsible.Content>+ </KCollapsible>+ );+}++// A CSS-3D stand-in for the renderer: the perspective distance reproduces the+// field of view at this card height and the rotations run in the renderer's+// order (camera orbit, then the content plane's own fold).+function Camera3DPosePreview(props: {+ pose: Camera3DProperties;+ height: number;+ animate?: boolean;+}) {+ const style = () => cssPreviewTransform(props.pose, props.height);++ return (+ <div+ class="overflow-hidden relative w-full rounded-md bg-gray-3"+ style={{+ height: `${props.height}px`,+ perspective: `${style().perspective}px`,+ transition: props.animate+ ? `perspective ${CAMERA3D_PREVIEW_TRANSITION}`+ : undefined,+ }}+ >+ <div+ class="absolute inset-0 rounded-[3px] border shadow-sm border-gray-6 bg-gray-1 dark:bg-gray-5"+ style={{+ transform: style().transform,+ transition: props.animate+ ? `transform ${CAMERA3D_PREVIEW_TRANSITION}`+ : undefined,+ }}+ />+ </div>+ );+}++/**+ * One scene, as a card: the pose its first shot opens on, drifting to that+ * shot's end pose while hovered. Shared by the panel's Scenes row and the empty+ * track's setup flow, so the two always offer the same thing.+ */+function Camera3DSceneCard(props: {+ scene: Camera3DScene;+ shotCount?: number;+ selected?: boolean;+ onClick: () => void;+}) {+ const [hovered, setHovered] = createSignal(false);+ const shotCount = () => props.shotCount ?? props.scene.shots.length;++ return (+ <button+ type="button"+ onClick={() => props.onClick()}+ onMouseEnter={() => setHovered(true)}+ onMouseLeave={() => setHovered(false)}+ class={cx(+ "flex flex-col gap-1 p-1 rounded-lg border transition-colors outline-hidden",+ props.selected+ ? "border-blue-9 ring-1 ring-blue-9"+ : "border-gray-4 hover:border-gray-7",+ )}+ >+ <div class="relative">+ <Camera3DPosePreview+ animate+ pose={hovered() ? props.scene.shots[0].to : props.scene.shots[0].from}+ height={CAMERA3D_SCENE_PREVIEW_HEIGHT}+ />+ <span class="absolute top-1 right-1 rounded px-1 text-[9px] leading-[14px] bg-gray-1/80 dark:bg-gray-2/80 text-gray-11">+ {shotCount()} {shotCount() === 1 ? "shot" : "shots"}+ </span>+ </div>+ <span class="text-[10px] leading-tight text-center text-gray-11">+ {props.scene.name}+ </span>+ </button>+ );+}++/**+ * The empty 3D track's setup flow: pick a look and how many cuts it makes,+ * with the track drawing the result live underneath. Confirming lays the whole+ * chain down in one step.+ */+function Camera3DSetupPanel(props: {+ setup: { sceneId: string; shots: number };+ onClose: () => void;+}) {+ const { projectActions, setEditorState, totalDuration } = useEditorContext();++ const scene = () =>+ CAMERA3D_SCENES.find((item) => item.id === props.setup.sceneId) ??+ CAMERA3D_SCENES[0];++ // A shot under the minimum is a glitch rather than a cut, so a short video+ // simply offers fewer of them.+ const maxShots = () =>+ Math.max(+ 1,+ Math.min(+ scene().shots.length,+ Math.floor(totalDuration() / CAMERA3D_MIN_SHOT_DURATION),+ ),+ );+ const shots = () => Math.min(props.setup.shots, maxShots());++ const updateSetup = (changes: Partial<{ sceneId: string; shots: number }>) =>+ setEditorState("timeline", "camera3dSetup", (current) =>+ current ? { ...current, ...changes } : current,+ );++ return (+ <div class="flex flex-col gap-4">+ <div class="flex flex-row gap-2 items-center">+ <EditorButton+ onClick={() => props.onClose()}+ leftIcon={<IconLucideX />}+ >+ Close+ </EditorButton>+ <span class="text-sm text-gray-10">New 3D scene</span>+ </div>++ <p class="text-xs text-gray-10">+ Lay a chain of camera moves over the whole video+ </p>++ <Field name="Style" icon={<IconLucideRotate3d class="size-4" />}>+ <div class="grid grid-cols-3 gap-2">+ <For each={CAMERA3D_SCENES}>+ {(item) => (+ <Camera3DSceneCard+ scene={item}+ shotCount={shots()}+ selected={item.id === scene().id}+ onClick={() => updateSetup({ sceneId: item.id })}+ />+ )}+ </For>+ </div>+ </Field>++ <Field name="How many shots?">+ <div class="flex flex-col gap-2">+ <div class="flex flex-row gap-1 p-1 rounded-lg bg-gray-3">+ <For each={scene().shots.map((_, index) => index + 1)}>+ {(count) => {+ const tooShort = () => count > maxShots();+ return (+ // The title lives on the wrapper: a disabled button never+ // hovers, so it would never show its own tooltip.+ <div+ class="flex-1"+ title={tooShort() ? "Video too short" : undefined}+ >+ <button+ type="button"+ disabled={tooShort()}+ onClick={() => updateSetup({ shots: count })}+ class={cx(+ "py-1 w-full text-xs font-medium rounded-md transition-colors outline-hidden",+ shots() === count+ ? "bg-gray-1 dark:bg-gray-5 text-gray-12"+ : "text-gray-11 hover:text-gray-12",+ tooShort() && "opacity-40 cursor-not-allowed",+ )}+ >+ {count}+ </button>+ </div>+ );+ }}+ </For>+ </div>+ <p class="text-xs text-gray-10">+ Shots split the video into separate camera moves.+ </p>+ </div>+ </Field>++ <div class="flex flex-row gap-2 items-center">+ <Button+ variant="primary"+ size="md"+ disabled={totalDuration() <= 0}+ onClick={() => projectActions.addCamera3DScene(scene().id, shots())}+ >+ Add scene+ </Button>+ <Button variant="gray" size="md" onClick={() => props.onClose()}>+ Cancel+ </Button>+ </div>+ </div>+ );+}++function Camera3DSegmentConfig(props: {+ segmentIndex: number;+ segment: Camera3DSegment;+}) {+ const { setProject, setEditorState, projectActions } = useEditorContext();++ const updateSegment = (fn: (segment: Camera3DSegment) => void) => {+ setProject(+ "timeline",+ "camera3dSegments",+ produce((segments) => {+ const target = segments?.[props.segmentIndex];+ if (!target) return;+ fn(target);+ }),+ );+ };++ // A 3D segment is one move: the pose it opens on and the pose it lands on.+ // Everything in this panel reads and writes that pair, and the per-property+ // keyframe tracks underneath are only how the renderer is fed.+ const startPose = () => getStartPose(props.segment);+ const endPose = () => getEndPose(props.segment);+ const isStill = () => camera3DPosesEqual(startPose(), endPose());++ // Which of the two poses the Camera sliders are pointed at.+ const [editingEnd, setEditingEnd] = createSignal(false);+ const selectedPose = () => (editingEnd() ? endPose() : startPose());++ // Selecting another segment reuses this panel, so the card selection has to+ // fall back to Start rather than carry over.+ createEffect(+ on(+ () => props.segmentIndex,+ () => setEditingEnd(false),+ { defer: true },+ ),+ );++ // Parking the playhead on the pose being edited is what makes the canvas+ // show it. The end pose is sampled a hair inside the segment so the playhead+ // stays on this segment instead of falling into the next one.+ const seekToPose = (end: boolean) => {+ const time = end+ ? Math.max(props.segment.end - 0.01, props.segment.start)+ : props.segment.start;+ batch(() => {+ setEditorState("playbackTime", time);+ setEditorState("previewTime", null);+ });+ };++ const selectPose = (end: boolean) =>+ batch(() => {+ setEditingEnd(end);+ seekToPose(end);+ });++ const writeMotion = (+ start: Camera3DProperties,+ end: Camera3DProperties,+ easing = getMotionEasing(props.segment),+ ) => updateSegment((segment) => setMotion(segment, start, end, easing));++ // A camera edit on a still shot moves both ends, so dialling in a hold never+ // turns into an unrequested move. Once the shot moves, each card owns its+ // own pose.+ const writeSelectedPose = (pose: Camera3DProperties) => {+ if (isStill()) writeMotion(pose, pose);+ else if (editingEnd()) writeMotion(startPose(), pose);+ else writeMotion(pose, endPose());+ };++ const setPoseProperty = (key: Camera3DPropertyKey, value: number) =>+ writeSelectedPose({ ...selectedPose(), [key]: value });++ const swapPoses = () => {+ const start = startPose();+ writeMotion(endPose(), start);+ };++ const flipSegment = (axis: Camera3DFlipAxis) =>+ updateSegment((segment) => flipCamera3DSegment(segment, axis));++ const makeStill = () => {+ const start = startPose();+ writeMotion(start, start);+ };++ const resetCamera = () => writeSelectedPose({ ...CAMERA3D_RESET_POSE });++ // The shot's identity is the pose it opens on, so the ring stays put while+ // the end pose is being edited.+ const activeAnglePresetId = () => matchAnglePreset(startPose());++ const [hoveredTemplate, setHoveredTemplate] = createSignal<string | null>(+ null,+ );++ // Templates own the whole camera animation: the existing move is replaced+ // and the playhead returns to the start so the result plays from its+ // first pose.+ const applyTemplate = (template: Camera3DMotionTemplate) => {+ batch(() => {+ updateSegment((segment) => {+ applyMotionTemplate(segment, template);+ });+ setEditingEnd(false);+ setEditorState("playbackTime", props.segment.start);+ setEditorState("previewTime", null);+ });+ };++ // Angle presets are moving shots too, exactly like the motion grid: the+ // shot opens on the named pose and drifts.+ const applyAnglePreset = (preset: Camera3DAnglePreset) =>+ applyTemplate(anglePresetMotion(preset));++ // A scene replaces this one segment with its whole chain of shots, so the+ // panel hands off to the project action that owns the splice.+ const applyScene = (scene: Camera3DScene) =>+ projectActions.applyCamera3DScene(props.segmentIndex, scene.id);++ const motionEasing = () => getMotionEasing(props.segment);++ const blur = () => props.segment.blur;++ const blurSliders = () => {+ const mode = blur().mode;+ return mode === "none" ? [] : CAMERA3D_BLUR_SLIDERS[mode];+ };++ // Blur is on by default now, so the closed section still has to say so.+ const blurSummary = () => {+ const mode = blur().mode;+ if (mode === "none") return "Off";+ const label =+ CAMERA3D_BLUR_MODE_OPTIONS.find((option) => option.value === mode)+ ?.label ?? mode;+ return `${label} ${Math.round(blur().strength)}`;+ };++ // Blur is segment-level and static: it is never part of the move.+ const setBlurValue = (key: Camera3DBlurScalarKey, value: number) =>+ updateSegment((segment) => {+ segment.blur[key] = value;+ });++ const setBlurMode = (mode: Camera3DBlurMode) => {+ if (mode === blur().mode) return;+ updateSegment((segment) => {+ segment.blur.mode = mode;+ const seed = CAMERA3D_BLUR_MODE_SEEDS[mode];+ for (const key of Object.keys(seed) as Camera3DBlurScalarKey[]) {+ const value = seed[key];+ if (value !== undefined) segment.blur[key] = value;+ }+ });+ };++ const setBokeh = (enabled: boolean) => {+ updateSegment((segment) => {+ segment.blur.bokeh = enabled;+ if (!enabled) return;+ // The bokeh kernel tops out at 20, so pull the strength down with the+ // slider's new ceiling.+ segment.blur.strength = Math.min(+ segment.blur.strength,+ CAMERA3D_BOKEH_MAX_STRENGTH,+ );+ });+ };++ const resetBlur = () => {+ updateSegment((segment) => {+ segment.blur = defaultCamera3DBlur();+ });+ };++ // Section state is panel-local: it is how this user is reading the panel+ // right now, not something the project should remember.+ const [cameraOpen, setCameraOpen] = createSignal(false);+ const [blurOpen, setBlurOpen] = createSignal(false);+ const [advancedOpen, setAdvancedOpen] = createSignal(false);++ const poseCard = (label: string, end: boolean) => (+ <button+ type="button"+ onClick={() => selectPose(end)}+ class={cx(+ "flex flex-col flex-1 gap-1 p-1 rounded-lg border transition-colors outline-hidden",+ editingEnd() === end+ ? "border-blue-9 ring-1 ring-blue-9"+ : "border-gray-4 hover:border-gray-7",+ )}+ >+ {/* No transition here: these cards track the sliders live. */}+ <Camera3DPosePreview+ pose={end ? endPose() : startPose()}+ height={CAMERA3D_POSE_PREVIEW_HEIGHT}+ />+ <span class="text-[10px] leading-tight text-center text-gray-11">+ {label}+ </span>+ </button>+ );++ return (+ <div class="space-y-4">+ <Field name="Templates" icon={<IconLucideRotate3d class="size-4" />}>+ <div class="flex flex-col gap-3">+ {/* Scenes lead: one click lays a whole chained sequence over this+ segment's range, where the rows below author a single shot. */}+ <div class="grid grid-cols-3 gap-2">+ <For each={CAMERA3D_SCENES}>+ {(scene) => (+ <Camera3DSceneCard+ scene={scene}+ onClick={() => applyScene(scene)}+ />+ )}+ </For>+ </div>+ <div class="grid grid-cols-5 gap-1.5">+ <For each={ANGLE_PRESETS}>+ {(preset) => (+ <button+ type="button"+ onClick={() => applyAnglePreset(preset)}+ onMouseEnter={() => setHoveredTemplate(`angle-${preset.id}`)}+ onMouseLeave={() =>+ setHoveredTemplate((current) =>+ current === `angle-${preset.id}` ? null : current,+ )+ }+ class={cx(+ "flex flex-col gap-1 p-1 rounded-lg border transition-colors outline-hidden",+ activeAnglePresetId() === preset.id+ ? "border-blue-9 ring-1 ring-blue-9"+ : "border-gray-4 hover:border-gray-7",+ )}+ >+ <Camera3DPosePreview+ animate+ pose={+ hoveredTemplate() === `angle-${preset.id}`+ ? anglePresetMotion(preset).to+ : anglePresetPose(preset)+ }+ height={CAMERA3D_ANGLE_PREVIEW_HEIGHT}+ />+ <span class="text-[10px] leading-tight text-center text-gray-11">+ {preset.name}+ </span>+ </button>+ )}+ </For>+ </div>+ <div class="grid grid-cols-4 gap-2">+ <For each={MOTION_TEMPLATES}>+ {(template) => (+ <button+ type="button"+ onClick={() => applyTemplate(template)}+ onMouseEnter={() => setHoveredTemplate(template.id)}+ onMouseLeave={() =>+ setHoveredTemplate((current) =>+ current === template.id ? null : current,+ )+ }+ class="flex flex-col gap-1 p-1 rounded-lg border transition-colors outline-hidden border-gray-4 hover:border-gray-7"+ >+ <Camera3DPosePreview+ animate+ pose={+ hoveredTemplate() === template.id+ ? template.to+ : template.from+ }+ height={CAMERA3D_TEMPLATE_PREVIEW_HEIGHT}+ />+ <span class="text-[10px] leading-tight text-center text-gray-11">+ {template.name}+ </span>+ </button>+ )}+ </For>+ </div>+ </div>+ </Field>+ <Field name="Motion" icon={<IconLucideMoveRight class="size-4" />}>+ <div class="flex flex-col gap-2">+ <div class="flex flex-row gap-2 items-center">+ {poseCard("Start", false)}+ <EditorButton+ onClick={swapPoses}+ tooltipText="Swap start and end"+ leftIcon={<IconLucideArrowLeftRight class="size-3.5" />}+ />+ {poseCard("End", true)}+ </div>+ <div class="flex flex-row gap-1 items-center">+ <EditorButton+ onClick={() => flipSegment("horizontal")}+ tooltipText="Flip horizontal"+ leftIcon={<IconLucideFlipHorizontal2 class="size-3.5" />}+ />+ <EditorButton+ onClick={() => flipSegment("vertical")}+ tooltipText="Flip vertical"+ leftIcon={<IconLucideFlipVertical2 class="size-3.5" />}+ />+ <Show+ when={!isStill()}+ fallback={+ <p class="text-[11px] text-gray-10">+ Pick a template or edit the end pose to add motion+ </p>+ }+ >+ <button+ type="button"+ onClick={makeStill}+ class="self-start text-[11px] transition-colors outline-hidden text-gray-11 hover:text-gray-12"+ >+ Still shot+ </button>+ </Show>+ </div>+ </div>+ </Field>+ <Camera3DSection+ name="Camera"+ icon={<IconLucideVideo class="size-4" />}+ summary={editingEnd() ? "End pose" : "Start pose"}+ open={cameraOpen()}+ onOpenChange={setCameraOpen}+ >+ <div class="flex flex-col gap-3">+ <For each={CAMERA3D_SLIDERS}>+ {(slider) => (+ <div class="flex flex-col gap-1">+ <span class="flex flex-row gap-1.5 items-center text-xs text-gray-11">+ {camera3dSliderIcon(slider.key)}+ {slider.label}+ </span>+ <Slider+ value={[selectedPose()[slider.key]]}+ onChange={(v) => setPoseProperty(slider.key, v[0])}+ minValue={CAMERA3D_LIMITS[slider.key].min}+ maxValue={CAMERA3D_LIMITS[slider.key].max}+ step={CAMERA3D_LIMITS[slider.key].step}+ formatTooltip={slider.unit}+ />+ </div>+ )}+ </For>+ <EditorButton+ leftIcon={<IconLucideRotateCcw />}+ onClick={resetCamera}+ >+ Reset camera+ </EditorButton>+ </div>+ </Camera3DSection>+ <Camera3DSection+ name="Blur"+ icon={<IconLucideWind class="size-4" />}+ summary={blurSummary()}+ open={blurOpen()}+ onOpenChange={setBlurOpen}+ >+ <div class="flex flex-col gap-3">+ <Subfield name="Mode">+ <div class="w-40">+ <KSelect<{ value: Camera3DBlurMode; label: string }>+ options={CAMERA3D_BLUR_MODE_OPTIONS}+ optionValue="value"+ optionTextValue="label"+ value={CAMERA3D_BLUR_MODE_OPTIONS.find(+ (option) => option.value === blur().mode,+ )}+ onChange={(option) => {+ if (option) setBlurMode(option.value);+ }}+ disallowEmptySelection+ itemComponent={(itemProps) => (+ <MenuItem<typeof KSelect.Item>+ as={KSelect.Item}+ item={itemProps.item}+ >+ <KSelect.ItemLabel class="flex-1">+ {itemProps.item.rawValue.label}+ </KSelect.ItemLabel>+ </MenuItem>+ )}+ >+ <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">+ <KSelect.Value<{+ value: Camera3DBlurMode;+ label: string;+ }> class="flex-1 text-sm text-left truncate text-(--gray-500) font-normal">+ {(state) => <span>{state.selectedOption().label}</span>}+ </KSelect.Value>+ <KSelect.Icon<ValidComponent>+ as={(iconProps) => (+ <IconCapChevronDown+ {...iconProps}+ class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)"+ />+ )}+ />+ </KSelect.Trigger>+ <KSelect.Portal>+ <PopperContent<typeof KSelect.Content>+ as={KSelect.Content}+ class={cx(topSlideAnimateClasses, "z-50")}+ >+ <MenuItemList<typeof KSelect.Listbox>+ class="overflow-y-auto max-h-32"+ as={KSelect.Listbox}+ />+ </PopperContent>+ </KSelect.Portal>+ </KSelect>+ </div>+ </Subfield>+ <Show+ when={blur().mode !== "none"}+ fallback={+ <p class="text-xs text-gray-11">+ Pick a mode to blur everything outside the focus area.+ </p>+ }+ >+ <For each={blurSliders()}>+ {(slider) => {+ const limit = () => camera3dBlurLimit(slider.key, blur());+ return (+ <div class="flex flex-col gap-1">+ <span class="text-xs text-gray-11">{slider.label}</span>+ <Slider+ value={[blur()[slider.key]]}+ onChange={(v) => setBlurValue(slider.key, v[0])}+ minValue={limit().min}+ maxValue={limit().max}+ step={limit().step}+ formatTooltip={slider.unit}+ />+ </div>+ );+ }}+ </For>+ <Subfield name="Bokeh">+ <Toggle checked={blur().bokeh} onChange={setBokeh} />+ </Subfield>+ <EditorButton+ leftIcon={<IconLucideRotateCcw />}+ onClick={resetBlur}+ >+ Turn blur off+ </EditorButton>+ </Show>+ </div>+ </Camera3DSection>+ <Camera3DSection+ name="Advanced"+ icon={<IconLucideTimer class="size-4" />}+ open={advancedOpen()}+ onOpenChange={setAdvancedOpen}+ >+ <div class="flex flex-col gap-3">+ <Subfield name="Motion style">+ <div class="w-40">+ <KSelect<Camera3DMotionEasing>+ options={MOTION_EASINGS}+ optionValue="id"+ optionTextValue="label"+ value={motionEasing()}+ onChange={(option) => {+ if (option) writeMotion(startPose(), endPose(), option);+ }}+ // A still shot has no span to shape, and nowhere to store a+ // curve, so the picker would silently snap back.+ disabled={isStill()}+ disallowEmptySelection+ itemComponent={(itemProps) => (+ <MenuItem<typeof KSelect.Item>+ as={KSelect.Item}+ item={itemProps.item}+ >+ <KSelect.ItemLabel class="flex-1">+ {itemProps.item.rawValue.label}+ </KSelect.ItemLabel>+ </MenuItem>+ )}+ >+ <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">+ <KSelect.Value<Camera3DMotionEasing> class="flex-1 text-sm text-left truncate text-(--gray-500) font-normal">+ {(state) => <span>{state.selectedOption().label}</span>}+ </KSelect.Value>+ <KSelect.Icon<ValidComponent>+ as={(iconProps) => (+ <IconCapChevronDown+ {...iconProps}+ class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)"+ />+ )}+ />+ </KSelect.Trigger>+ <KSelect.Portal>+ <PopperContent<typeof KSelect.Content>+ as={KSelect.Content}+ class={cx(topSlideAnimateClasses, "z-50")}+ >+ <MenuItemList<typeof KSelect.Listbox>+ class="overflow-y-auto max-h-32"+ as={KSelect.Listbox}+ />+ </PopperContent>+ </KSelect.Portal>+ </KSelect>+ </div>+ </Subfield>+ <div class="flex flex-col gap-2">+ <Camera3DTransitionInput+ label="Ease in"+ value={props.segment.transitionIn}+ onChange={(value) =>+ updateSegment((segment) => {+ segment.transitionIn = value;+ })+ }+ />+ <Camera3DTransitionInput+ label="Ease out"+ value={props.segment.transitionOut}+ onChange={(value) =>+ updateSegment((segment) => {+ segment.transitionOut = value;+ })+ }+ />+ </div>+ </div>+ </Camera3DSection>+ </div>+ );+}+function ZoomSegmentPreview(props: {segmentIndex: number;segment: ZoomSegment;diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsxindex f53a293e6..52c839204 100644--- a/apps/desktop/src/routes/editor/Editor.tsx+++ b/apps/desktop/src/routes/editor/Editor.tsx@@ -129,6 +129,13 @@ function getPreviewProjectConfig(};}+ if (!editorState.timeline.tracks["3d"] && config.timeline) {+ config.timeline = {+ ...config.timeline,+ camera3dSegments: [],+ };+ }+return config;}@@ -566,6 +573,7 @@ function Inner() {return {caption: editorState.timeline.tracks.caption,keyboard: editorState.timeline.tracks.keyboard,+ threeD: editorState.timeline.tracks["3d"],};},() => {diff --git a/apps/desktop/src/routes/editor/Timeline/ThreeDTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ThreeDTrack.tsxnew file mode 100644index 000000000..59b18d882--- /dev/null+++ b/apps/desktop/src/routes/editor/Timeline/ThreeDTrack.tsx@@ -0,0 +1,771 @@+import { createEventListenerMap } from "@solid-primitives/event-listener";+import { cx } from "cva";+import { Array, Option } from "effect";+import {+ batch,+ createMemo,+ createRoot,+ createSignal,+ Index,+ Match,+ Show,+ Switch,+} from "solid-js";+import { produce } from "solid-js/store";+import { useEditorContext } from "../context";+import {+ CAMERA3D_SCENES,+ defaultCamera3DSegment,+ fitCamera3DMotionToSegment,+ hasCamera3DMotion,+} from "../three-d";+import {+ useSegmentContext,+ useTimelineContext,+ useTrackContext,+} from "./context";+import {+ SegmentContent,+ SegmentHandle,+ SegmentRoot,+ TrackRoot,+ useSegmentTranslateX,+ useSegmentWidth,+ useSetPreviewTime,+} from "./Track";++export type ThreeDSegmentDragState =+ | { type: "idle" }+ | { type: "movePending" }+ | { type: "moving" };++const MIN_THREE_D_SEGMENT_PIXEL_WIDTH = 40;+const MIN_NEW_SEGMENT_PIXEL_WIDTH = 80;+const MIN_NEW_SEGMENT_SECS_WIDTH = 1;++/** What the setup flow opens on: the full showcase sequence. */+const CAMERA3D_SETUP_SEED = { sceneId: "showcase", shots: 3 };++/**+ * One shot of the scene the setup flow is offering, drawn where it would land.+ * Non-interactive: the whole placeholder area belongs to the open flow.+ */+function Camera3DSetupGhost(props: {+ segment: { start: number; end: number };+ label: string;+}) {+ const translateX = useSegmentTranslateX(() => props.segment);+ const width = useSegmentWidth(() => props.segment);++ return (+ <div+ class="flex absolute inset-y-0 justify-center items-center rounded-xl border border-dashed pointer-events-none"+ style={{+ transform: `translateX(${translateX()}px)`,+ width: `${width()}px`,+ "border-color": "color-mix(in srgb, var(--track-3d) 70%, transparent)",+ background: "color-mix(in srgb, var(--track-3d) 14%, transparent)",+ }}+ >+ <span class="px-2 text-xs truncate text-gray-12">{props.label}</span>+ </div>+ );+}++export function ThreeDTrack(props: {+ onDragStateChanged: (v: ThreeDSegmentDragState) => void;+ handleUpdatePlayhead: (e: MouseEvent) => void;+}) {+ const {+ project,+ setProject,+ projectHistory,+ setEditorState,+ editorState,+ totalDuration,+ projectActions,+ camera3DScenePreview,+ } = useEditorContext();++ const { duration, secsPerPixel } = useTimelineContext();+ const setPreviewTime = useSetPreviewTime();++ const [creatingSegmentViaDrag, setCreatingSegmentViaDrag] =+ createSignal(false);++ const hasCamera3DSegments = () =>+ (project.timeline?.camera3dSegments?.length ?? 0) > 0;++ const setup = () => editorState.timeline.camera3dSetup;++ const setupSegments = createMemo(() => {+ const current = setup();+ if (!current) return [];+ return camera3DScenePreview(current.sceneId, current.shots);+ });++ const setupShotLabel = (index: number) => {+ const current = setup();+ const scene = current+ ? CAMERA3D_SCENES.find((s) => s.id === current.sceneId)+ : undefined;+ return scene?.shots[index]?.name ?? `Shot ${index + 1}`;+ };++ const startSetup = () =>+ batch(() => {+ setEditorState("timeline", "selection", null);+ setEditorState("timeline", "audioPicker", null);+ setEditorState("timeline", "audioReplace", null);+ setEditorState("timeline", "camera3dSetup", { ...CAMERA3D_SETUP_SEED });+ });+ const selectedCamera3DIndices = createMemo(() => {+ const selection = editorState.timeline.selection;+ if (!selection || selection.type !== "3d") return null;+ return new Set(selection.indices);+ });++ const newSegmentMinDuration = () =>+ Math.max(+ MIN_NEW_SEGMENT_PIXEL_WIDTH * secsPerPixel(),+ MIN_NEW_SEGMENT_SECS_WIDTH,+ );++ // Returns a start and end time for a new segment that can be inserted at the+ // current previewTime, if conditions permit+ const newSegmentDetails = () => {+ if (+ creatingSegmentViaDrag() ||+ editorState.timeline.hoveredTrack !== "3d" ||+ editorState.previewTime === null+ )+ return;++ // An empty track belongs to the setup flow, whether it is open or still+ // only offering itself, so nothing is drag-created over it.+ if (!hasCamera3DSegments() || setup()) return;++ const { previewTime } = editorState;++ const nextSegment = Array.findFirstWithIndex(+ project.timeline?.camera3dSegments ?? [],+ (s) => previewTime <= s.start,+ );++ const prevSegment = Array.findLastIndex(+ project.timeline?.camera3dSegments ?? [],+ (s) => previewTime >= s.start,+ ).pipe(+ Option.flatMap((index) =>+ Option.fromNullable(project.timeline?.camera3dSegments?.[index]).pipe(+ Option.map((segment) => [segment, index] as const),+ ),+ ),+ );++ if (+ Option.isSome(prevSegment) &&+ previewTime > prevSegment.value[0].start &&+ previewTime < prevSegment.value[0].end+ )+ return;++ const minDuration = newSegmentMinDuration();++ if (Option.isSome(nextSegment)) {+ if (Option.isSome(prevSegment)) {+ const availableTime =+ nextSegment.value[0].start - prevSegment.value[0].end;++ if (availableTime < minDuration) return;+ }++ if (nextSegment.value[0].start - previewTime < 1)+ return {+ index: nextSegment.value[1],+ start: nextSegment.value[0].start - minDuration,+ end: nextSegment.value[0].start,+ max: nextSegment.value[0].start,+ };+ }++ return {+ index: nextSegment.pipe(Option.map(([_, i]) => i)),+ start: previewTime,+ end: previewTime + minDuration,+ max: nextSegment.pipe(+ Option.map(([s]) => s.start),+ Option.getOrElse(() => totalDuration()),+ ),+ };+ };++ return (+ <TrackRoot+ onMouseEnter={() => setEditorState("timeline", "hoveredTrack", "3d")}+ onMouseLeave={() => setEditorState("timeline", "hoveredTrack", null)}+ onMouseDown={(e) => {+ if (e.button !== 0) return;++ const baseSegment = newSegmentDetails();+ if (!baseSegment) return;++ createRoot((dispose) => {+ let segmentCreated = false;+ let createdSegmentIndex = -1;+ const initialMouseX = e.clientX;+ const initialEndTime = baseSegment.end;++ const minDuration = newSegmentMinDuration;++ const createSegment = (endTime: number) => {+ if (segmentCreated) return;++ batch(() => {+ setProject("timeline", "camera3dSegments", (v) => v ?? []);+ setProject(+ "timeline",+ "camera3dSegments",+ produce((camera3dSegments) => {+ camera3dSegments ??= [];++ let index = 0;++ for (let i = 0; i < camera3dSegments.length; i++) {+ if (camera3dSegments[i].start < baseSegment.start) {+ index = i + 1;+ }+ }++ const minEndTime = baseSegment.start + minDuration();++ camera3dSegments.splice(+ index,+ 0,+ defaultCamera3DSegment(+ baseSegment.start,+ Math.max(minEndTime, endTime),+ ),+ );++ createdSegmentIndex = index;+ }),+ );+ setEditorState("timeline", "selection", {+ type: "3d",+ indices: [createdSegmentIndex],+ });+ });+ segmentCreated = true;+ };++ const updateSegment = (endTime: number) => {+ if (!segmentCreated || createdSegmentIndex === -1) return;++ const minEndTime = baseSegment.start + minDuration();++ setProject(+ "timeline",+ "camera3dSegments",+ createdSegmentIndex,+ "end",+ Math.max(minEndTime, endTime),+ );+ };++ const handleMouseMove = (moveEvent: MouseEvent) => {+ const deltaX = moveEvent.clientX - initialMouseX;+ const deltaTime =+ deltaX * secsPerPixel() - (baseSegment.end - baseSegment.start);+ const newEndTime = initialEndTime + deltaTime;++ const minEndTime = baseSegment.start + minDuration();+ const maxEndTime = baseSegment.max;++ const clampedEndTime = Math.min(+ Math.max(minEndTime, newEndTime),+ maxEndTime,+ );++ if (!segmentCreated) {+ setCreatingSegmentViaDrag(true);+ createSegment(clampedEndTime);+ } else {+ if (deltaTime < 0) return;+ updateSegment(clampedEndTime);+ }+ };++ const handleMouseUp = () => {+ setCreatingSegmentViaDrag(false);+ dispose();++ if (!segmentCreated) {+ createSegment(initialEndTime);+ }+ };++ createEventListenerMap(window, {+ mousemove: handleMouseMove,+ mouseup: handleMouseUp,+ });+ });+ }}+ >+ <Show+ when={hasCamera3DSegments()}+ fallback={+ <Show+ when={setup()}+ fallback={+ // An empty 3D track is the one place a whole scene can land+ // without overwriting anything, so it is offered here.+ <button+ type="button"+ style={{+ "--accent": "var(--track-3d)",+ "--accent-soft":+ "color-mix(in srgb, var(--track-3d) 12%, transparent)",+ }}+ class="group/empty flex gap-2 justify-center items-center w-full text-sm rounded-xl border transition-all duration-200 pointer-events-auto border-dashed border-gray-4/60 bg-gray-3/15 text-(--text-tertiary) hover:border-[var(--accent)] hover:bg-[var(--accent-soft)] hover:text-gray-12"+ onMouseDown={(e) => e.stopPropagation()}+ onClick={(e) => {+ e.stopPropagation();+ startSetup();+ }}+ >+ <span class="flex justify-center items-center rounded-full transition-colors size-6 bg-gray-4/40 text-gray-11 group-hover/empty:bg-[var(--accent)] group-hover/empty:text-white">+ <IconLucidePlus class="size-3.5" />+ </span>+ <span class="font-medium">Add 3D scene</span>+ </button>+ }+ >+ {/* The open flow owns the whole track: the shots it would lay+ down are drawn where they will land, and a click anywhere+ over them leaves the flow alone rather than closing it. */}+ <div+ class="absolute inset-0 pointer-events-auto"+ onMouseDown={(e) => e.stopPropagation()}+ >+ <Index each={setupSegments()}>+ {(ghost, index) => (+ <Camera3DSetupGhost+ segment={ghost()}+ label={setupShotLabel(index)}+ />+ )}+ </Index>+ </div>+ </Show>+ }+ >+ <Index each={project.timeline?.camera3dSegments}>+ {(segment, i) => {+ const { setTrackState } = useTrackContext();++ const camera3dSegments = () =>+ project.timeline?.camera3dSegments ?? [];++ // Double-clicking a handle expands the segment as far as it can go+ // in that direction (up to the neighbouring segment / timeline edge).+ const fillStart = () => {+ const segs = camera3dSegments();+ let minValue = 0;+ for (let j = segs.length - 1; j >= 0; j--) {+ const s = segs[j];+ if (s && s.end <= segment().start) {+ minValue = s.end;+ break;+ }+ }+ setProject(+ "timeline",+ "camera3dSegments",+ produce((s) => {+ const target = s[i];+ if (!target) return;+ target.start = minValue;+ fitCamera3DMotionToSegment(target);+ s.sort((a, b) => a.start - b.start);+ }),+ );+ setPreviewTime(minValue);+ };++ const fillEnd = () => {+ const segs = camera3dSegments();+ let maxValue = totalDuration();+ for (let j = 0; j < segs.length; j++) {+ const s = segs[j];+ if (s && s.start > segment().end) {+ maxValue = s.start;+ break;+ }+ }+ setProject(+ "timeline",+ "camera3dSegments",+ produce((s) => {+ const target = s[i];+ if (!target) return;+ target.end = maxValue;+ fitCamera3DMotionToSegment(target);+ s.sort((a, b) => a.start - b.start);+ }),+ );+ setPreviewTime(maxValue);+ };++ function createMouseDownDrag<T>(+ setup: () => T,+ _update: (e: MouseEvent, v: T, initialMouseX: number) => void,+ ) {+ return (downEvent: MouseEvent) => {+ if (editorState.timeline.interactMode !== "seek") return;++ downEvent.stopPropagation();++ const initial = setup();++ let moved = false;+ let initialMouseX: null | number = null;++ setTrackState("draggingSegment", true);++ const resumeHistory = projectHistory.pause();++ props.onDragStateChanged({ type: "movePending" });++ function finish(e: MouseEvent) {+ resumeHistory();+ if (!moved) {+ e.stopPropagation();++ const currentSelection = editorState.timeline.selection;+ const segmentIndex = i;+ const isMultiSelect = e.ctrlKey || e.metaKey;+ const isRangeSelect = e.shiftKey;++ if (isRangeSelect && currentSelection?.type === "3d") {+ const existingIndices = currentSelection.indices;+ const lastIndex =+ existingIndices[existingIndices.length - 1];+ const start = Math.min(lastIndex, segmentIndex);+ const end = Math.max(lastIndex, segmentIndex);+ const rangeIndices: number[] = [];+ for (let idx = start; idx <= end; idx++) {+ rangeIndices.push(idx);+ }++ setEditorState("timeline", "selection", {+ type: "3d",+ indices: rangeIndices,+ });+ } else if (isMultiSelect) {+ if (currentSelection?.type === "3d") {+ const baseIndices = currentSelection.indices;+ const exists = baseIndices.includes(segmentIndex);+ const newIndices = exists+ ? baseIndices.filter((idx) => idx !== segmentIndex)+ : [...baseIndices, segmentIndex];++ if (newIndices.length > 0) {+ setEditorState("timeline", "selection", {+ type: "3d",+ indices: newIndices,+ });+ } else {+ setEditorState("timeline", "selection", null);+ }+ } else {+ setEditorState("timeline", "selection", {+ type: "3d",+ indices: [segmentIndex],+ });+ }+ } else {+ setEditorState("timeline", "selection", {+ type: "3d",+ indices: [segmentIndex],+ });+ }+ props.handleUpdatePlayhead(e);+ }+ props.onDragStateChanged({ type: "idle" });+ setTrackState("draggingSegment", false);+ }++ function update(event: MouseEvent) {+ if (Math.abs(event.clientX - downEvent.clientX) > 2) {+ if (!moved) {+ moved = true;+ initialMouseX = event.clientX;+ props.onDragStateChanged({+ type: "moving",+ });+ }+ }++ if (initialMouseX === null) return;++ _update(event, initial, initialMouseX);+ }++ createRoot((dispose) => {+ createEventListenerMap(window, {+ mousemove: (e) => {+ update(e);+ },+ mouseup: (e) => {+ update(e);+ finish(e);+ dispose();+ },+ });+ });+ };+ }++ const isSelected = createMemo(() => {+ const indices = selectedCamera3DIndices();+ if (!indices) return false;+ return indices.has(i);+ });++ return (+ <SegmentRoot+ segColor="var(--track-3d)"+ class={cx(+ "border duration-200 transition-colors group",+ isSelected() ? "border-gray-12" : "border-transparent",+ )}+ innerClass="ring-red-5"+ segment={segment()}+ onMouseDown={(e) => {+ e.stopPropagation();++ if (editorState.timeline.interactMode === "split") {+ const rect = e.currentTarget.getBoundingClientRect();+ const fraction = (e.clientX - rect.left) / rect.width;++ const splitTime =+ fraction * (segment().end - segment().start);++ projectActions.splitCamera3DSegment(i, splitTime);+ }+ }}+ >+ <SegmentHandle+ position="start"+ onDblClick={(e) => {+ e.stopPropagation();+ fillStart();+ }}+ onMouseDown={createMouseDownDrag(+ () => {+ const start = segment().start;+ const minDuration = Math.max(+ 1,+ secsPerPixel() * MIN_THREE_D_SEGMENT_PIXEL_WIDTH,+ );++ let minValue = 0;++ const maxValue = segment().end - minDuration;++ for (let j = camera3dSegments().length - 1; j >= 0; j--) {+ const other = camera3dSegments()[j];+ if (!other) continue;+ if (other.end <= start) {+ minValue = other.end;+ break;+ }+ }++ return { start, minValue, maxValue };+ },+ (e, value, initialMouseX) => {+ const newStart =+ value.start ++ (e.clientX - initialMouseX) * secsPerPixel();+ const nextStart = Math.min(+ value.maxValue,+ Math.max(value.minValue, newStart),+ );++ setProject(+ "timeline",+ "camera3dSegments",+ produce((s) => {+ const target = s[i];+ if (!target) return;+ target.start = nextStart;+ fitCamera3DMotionToSegment(target);+ s.sort((a, b) => a.start - b.start);+ }),+ );+ setPreviewTime(nextStart);+ },+ )}+ />+ <SegmentContent+ class="flex justify-center items-center cursor-grab"+ onMouseDown={createMouseDownDrag(+ () => {+ const original = { ...segment() };++ const prevSegment = camera3dSegments()[i - 1];+ const nextSegment = camera3dSegments()[i + 1];++ const minStart = prevSegment?.end ?? 0;+ const maxEnd = nextSegment?.start ?? duration();++ return {+ original,+ minStart,+ maxEnd,+ };+ },+ (e, value, initialMouseX) => {+ const rawDelta =+ (e.clientX - initialMouseX) * secsPerPixel();++ const newStart = value.original.start + rawDelta;+ const newEnd = value.original.end + rawDelta;++ let delta = rawDelta;++ if (newStart < value.minStart)+ delta = value.minStart - value.original.start;+ else if (newEnd > value.maxEnd)+ delta = value.maxEnd - value.original.end;++ setProject("timeline", "camera3dSegments", i, {+ start: value.original.start + delta,+ end: value.original.end + delta,+ });+ },+ )}+ >+ {(() => {+ const ctx = useSegmentContext();++ return (+ <Switch>+ <Match when={ctx.width() < 40}>+ <div class="flex justify-center items-center">+ <IconLucideRotate3d class="size-3.5 text-gray-1 dark:text-gray-12" />+ </div>+ </Match>+ <Match when={ctx.width() < 100}>+ <div class="flex gap-1 items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12">+ <IconLucideRotate3d class="size-3" />+ <span>3D</span>+ </div>+ </Match>+ <Match when={true}>+ <div class="flex flex-col gap-1 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12 animate-in fade-in">+ <span class="opacity-70">+ {ctx.width() >= 140 ? "3D Perspective" : "3D"}+ </span>+ <div class="flex gap-1 items-center text-md">+ <IconLucideRotate3d class="size-3.5" />+ <span>+ {hasCamera3DMotion(segment())+ ? "Motion"+ : "Still"}+ </span>+ {/* Presentation only: the arrow says the shot+ moves from its start pose to its end pose. */}+ <Show when={hasCamera3DMotion(segment())}>+ <IconLucideChevronRight class="size-3 opacity-70" />+ </Show>+ </div>+ </div>+ </Match>+ </Switch>+ );+ })()}+ </SegmentContent>+ <SegmentHandle+ position="end"+ onDblClick={(e) => {+ e.stopPropagation();+ fillEnd();+ }}+ onMouseDown={createMouseDownDrag(+ () => {+ const end = segment().end;+ const minDuration = Math.max(+ 1,+ secsPerPixel() * MIN_THREE_D_SEGMENT_PIXEL_WIDTH,+ );++ const minValue = segment().start + minDuration;++ let maxValue = duration();++ for (let j = 0; j < camera3dSegments().length; j++) {+ const other = camera3dSegments()[j];+ if (!other) continue;+ if (other.start > end) {+ maxValue = other.start;+ break;+ }+ }++ return { end, minValue, maxValue };+ },+ (e, value, initialMouseX) => {+ const newEnd =+ value.end ++ (e.clientX - initialMouseX) * secsPerPixel();+ const nextEnd = Math.min(+ value.maxValue,+ Math.max(value.minValue, newEnd),+ );++ setProject(+ "timeline",+ "camera3dSegments",+ produce((s) => {+ const target = s[i];+ if (!target) return;+ target.end = nextEnd;+ fitCamera3DMotionToSegment(target);+ s.sort((a, b) => a.start - b.start);+ }),+ );+ setPreviewTime(nextEnd);+ },+ )}+ />+ </SegmentRoot>+ );+ }}+ </Index>+ </Show>+ <Show+ when={+ !useTrackContext().trackState.draggingSegment && newSegmentDetails()+ }+ >+ {(details) => (+ <SegmentRoot+ class="pointer-events-none z-0"+ innerClass="ring-red-300"+ segColor="var(--track-3d)"+ segment={details()}+ >+ <SegmentContent class="group">+ <p class="w-full text-center text-gray-1 dark:text-gray-12 text-md text-primary">+ ++ </p>+ </SegmentContent>+ </SegmentRoot>+ )}+ </Show>+ </TrackRoot>+ );+}diff --git a/apps/desktop/src/routes/editor/Timeline/TrackManager.tsx b/apps/desktop/src/routes/editor/Timeline/TrackManager.tsxindex 314659e5a..08971c4f2 100644--- a/apps/desktop/src/routes/editor/Timeline/TrackManager.tsx+++ b/apps/desktop/src/routes/editor/Timeline/TrackManager.tsx@@ -53,6 +53,10 @@ const TRACK_META: Record<TimelineTrackType, TrackMeta> = {description: "Switch layouts between your screen and camera.",unavailableHint: "Record with a camera to use scenes.",},+ "3d": {+ description: "Tilt the scene in 3D perspective.",+ unavailableHint: "",+ },};// Comes straight from the shared `--track-*` CSS variable defined in theme.css,diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsxindex 4919ec4fd..4cd4af158 100644--- a/apps/desktop/src/routes/editor/Timeline/index.tsx+++ b/apps/desktop/src/routes/editor/Timeline/index.tsx@@ -51,6 +51,7 @@ import { type KeyboardSegmentDragState, KeyboardTrack } from "./KeyboardTrack";import { type MaskSegmentDragState, MaskTrack } from "./MaskTrack";import { type SceneSegmentDragState, SceneTrack } from "./SceneTrack";import { type TextSegmentDragState, TextTrack } from "./TextTrack";+import { type ThreeDSegmentDragState, ThreeDTrack } from "./ThreeDTrack";import { TrackIcon, TrackManager } from "./TrackManager";import { type ZoomSegmentDragState, ZoomTrack } from "./ZoomTrack";@@ -71,6 +72,7 @@ const trackIcons: Record<TimelineTrackType, () => JSX.Element> = {zoom: () => <IconLucideSearch class="size-4" />,scene: () => <IconLucideVideo class="size-4" />,audio: () => <IconLucideMusic class="size-4" />,+ "3d": () => <IconLucideRotate3d class="size-4" />,};type TrackDefinition = {@@ -129,6 +131,12 @@ const trackDefinitions: TrackDefinition[] = [icon: trackIcons.scene,locked: false,},+ {+ type: "3d",+ label: "3D",+ icon: trackIcons["3d"],+ locked: false,+ },];function deleteTrackLane<T extends { track?: number }>(@@ -179,6 +187,7 @@ export function Timeline(props: {const openAudioPicker = (laneIndex: number) => {batch(() => {setEditorState("timeline", "selection", null);+ setEditorState("timeline", "camera3dSetup", null);setEditorState("timeline", "audioPicker", laneIndex);});};@@ -187,6 +196,7 @@ export function Timeline(props: {const sceneAvailable = () => meta().hasCamera && !project.camera.hide;const captionTrackVisible = () => trackState().caption;const keyboardTrackVisible = () => trackState().keyboard;+ const threeDTrackVisible = () => trackState()["3d"];const trackOptions = createMemo(() =>trackDefinitions.map((definition) => ({...definition,@@ -197,13 +207,15 @@ export function Timeline(props: {? trackState().keyboard: definition.type === "scene"? trackState().scene- : definition.type === "mask"- ? trackState().mask > 0- : definition.type === "text"- ? trackState().text > 0- : definition.type === "audio"- ? trackState().audio > 0- : true,+ : definition.type === "3d"+ ? trackState()["3d"]+ : definition.type === "mask"+ ? trackState().mask > 0+ : definition.type === "text"+ ? trackState().text > 0+ : definition.type === "audio"+ ? trackState().audio > 0+ : true,available: definition.type === "scene" ? sceneAvailable() : true,supportsMultiple:definition.type === "mask" ||@@ -246,6 +258,7 @@ export function Timeline(props: {textTrackRows().length +maskTrackRows().length +audioTrackRows().length ++ (threeDTrackVisible() ? 1 : 0) +(sceneTrackVisible() ? 1 : 0),);const trackHeight = createMemo(() =>@@ -316,6 +329,19 @@ export function Timeline(props: {return;}+ if (type === "3d") {+ batch(() => {+ setEditorState("timeline", "tracks", "3d", next);+ if (!next && editorState.timeline.selection?.type === "3d") {+ setEditorState("timeline", "selection", null);+ }+ // The setup flow lives on the track it is previewing, so hiding the+ // track takes its sidebar panel with it.+ if (!next) setEditorState("timeline", "camera3dSetup", null);+ });+ return;+ }+if (type === "text") {setEditorState("timeline",@@ -551,6 +577,7 @@ export function Timeline(props: {textSegments: [],captionSegments: [],keyboardSegments: [],+ camera3dSegments: [],transitions: [],};project.timeline.captionSegments = [];@@ -575,6 +602,7 @@ export function Timeline(props: {textSegments: [],captionSegments: [],keyboardSegments: [],+ camera3dSegments: [],transitions: [],};project.timeline.keyboardSegments = [];@@ -587,9 +615,9 @@ export function Timeline(props: {resumeHistory();}- // Zoom and Scene are permanent tracks — deleting from them clears every- // segment on the track instead of hiding the track row itself.- function handleClearTrackSegments(type: "zoom" | "scene") {+ // Zoom, Scene and 3D keep their row once shown, so deleting from them+ // clears every segment on the track instead of hiding the row itself.+ function handleClearTrackSegments(type: "zoom" | "scene" | "3d") {const resumeHistory = projectHistory.pause();batch(() => {@@ -602,6 +630,7 @@ export function Timeline(props: {const timeline = project.timeline;if (!timeline) return;if (type === "zoom") timeline.zoomSegments = [];+ else if (type === "3d") timeline.camera3dSegments = [];else timeline.sceneSegments = [];}),);@@ -647,6 +676,7 @@ export function Timeline(props: {textSegments: [],captionSegments: [],keyboardSegments: [],+ camera3dSegments: [],transitions: [],});resume();@@ -673,7 +703,8 @@ export function Timeline(props: {!project.timeline?.zoomSegments ||project.timeline.zoomSegments.length < 1 ||!project.timeline?.maskSegments ||- !project.timeline?.textSegments+ !project.timeline?.textSegments ||+ !project.timeline?.camera3dSegments) {setProject(produce((project) => {@@ -691,6 +722,7 @@ export function Timeline(props: {textSegments: [],captionSegments: [],keyboardSegments: [],+ camera3dSegments: [],transitions: [],};project.timeline.sceneSegments ??= [];@@ -699,6 +731,7 @@ export function Timeline(props: {project.timeline.maskSegments ??= [];project.timeline.textSegments ??= [];project.timeline.zoomSegments ??= [];+ project.timeline.camera3dSegments ??= [];}),);}@@ -710,6 +743,7 @@ export function Timeline(props: {let audioSegmentDragState = { type: "idle" } as AudioSegmentDragState;let captionSegmentDragState = { type: "idle" } as CaptionSegmentDragState;let keyboardSegmentDragState = { type: "idle" } as KeyboardSegmentDragState;+ let threeDSegmentDragState = { type: "idle" } as ThreeDSegmentDragState;let pendingZoomDelta = 0;let pendingZoomOrigin: number | null = null;@@ -787,7 +821,8 @@ export function Timeline(props: {textSegmentDragState.type !== "moving" &&audioSegmentDragState.type !== "moving" &&captionSegmentDragState.type !== "moving" &&- keyboardSegmentDragState.type !== "moving"+ keyboardSegmentDragState.type !== "moving" &&+ threeDSegmentDragState.type !== "moving") {if (!metrics) return;const rawTime =@@ -850,6 +885,8 @@ export function Timeline(props: {projectActions.deleteTextSegments(selection.indices);} else if (selection.type === "audio") {projectActions.deleteAudioSegments(selection.indices);+ } else if (selection.type === "3d") {+ projectActions.deleteCamera3DSegments(selection.indices);} else if (selection.type === "transition") {projectActions.deleteClipTransition(selection.index);} else if (selection.type === "clip") {@@ -877,6 +914,7 @@ export function Timeline(props: {// Deselect all selected segmentssetEditorState("timeline", "selection", null);setEditorState("timeline", "audioPicker", null);+ setEditorState("timeline", "camera3dSetup", null);}});@@ -990,6 +1028,7 @@ export function Timeline(props: {if (zoomSegmentDragState.type === "idle") {setEditorState("timeline", "selection", null);setEditorState("timeline", "audioPicker", null);+ setEditorState("timeline", "camera3dSetup", null);}});createEventListener(window, "mouseup", () => {@@ -1240,6 +1279,27 @@ export function Timeline(props: {handleUpdatePlayhead={handleUpdatePlayhead}/></TrackRow>+ <Show when={threeDTrackVisible()}>+ <TrackRow+ icon={trackIcons["3d"]}+ label="3D"+ type="3d"+ onDelete={+ (project.timeline?.camera3dSegments?.length ?? 0) > 0+ ? () => handleClearTrackSegments("3d")+ : undefined+ }+ deleteLabel="Clear all"+ deleteTitle="Delete all 3D segments"+ >+ <ThreeDTrack+ onDragStateChanged={(v) => {+ threeDSegmentDragState = v;+ }}+ handleUpdatePlayhead={handleUpdatePlayhead}+ />+ </TrackRow>+ </Show><Show when={sceneTrackVisible()}><TrackRowicon={trackIcons.scene}diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.tsindex ecf69d553..7877d99ed 100644--- a/apps/desktop/src/routes/editor/context.ts+++ b/apps/desktop/src/routes/editor/context.ts@@ -64,6 +64,7 @@ import {type ClipTransition,type ClipTransitionInput,clampTransitionDuration,+ clipDuration,clipTimelineDuration,clipTimelineOffsets,getClipTransition,@@ -76,6 +77,20 @@ import {import type { MaskSegment } from "./masks";import type { SnapGuide } from "./snapping";import type { TextSegment } from "./text";+import {+ applySceneToRange,+ CAMERA3D_SCENES,+ type Camera3DSegment,+ defaultCamera3DTracks,+ evaluatePose,+ getEndPose,+ getMotionEasing,+ getStartPose,+ normalizeCamera3DSegments,+ scaleKeyframeTimes,+ sceneWithShotCount,+ setMotion,+} from "./three-d";import {getUsedTrackCount,normalizeTrackSegments,@@ -156,7 +171,8 @@ export type TimelineTrackType =| "zoom"| "scene"| "mask"- | "audio";+ | "audio"+ | "3d";export const MAX_ZOOM_IN = 3;const PROJECT_SAVE_DEBOUNCE_MS = 250;@@ -185,6 +201,7 @@ type EditorTimelineConfiguration = Omit<| "segments"| "audioSegments"| "transitions"+ | "camera3dSegments"> & {segments: EditorTimelineSegment[];transitions: ClipTransition[];@@ -192,6 +209,7 @@ type EditorTimelineConfiguration = Omit<maskSegments: MaskSegment[];textSegments: TextSegment[];audioSegments?: AudioTrackSegment[];+ camera3dSegments: Camera3DSegment[];};type EditorCaptionsData = NonNullable<ProjectConfiguration["captions"]> & {@@ -269,6 +287,9 @@ export function normalizeProject(}).audioSegments ?? [],),+ camera3dSegments: normalizeCamera3DSegments(+ config.timeline.camera3dSegments,+ ),}: undefined;const captions = config.captions@@ -305,6 +326,7 @@ export function serializeProjectConfiguration(maskSegments: project.timeline.maskSegments ?? [],textSegments: project.timeline.textSegments ?? [],audioSegments: project.timeline.audioSegments ?? [],+ camera3dSegments: project.timeline.camera3dSegments ?? [],}: project.timeline;@@ -372,6 +394,10 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(}if (shift === 0) return;+ const camera3dSegments = timeline.camera3dSegments ?? [];+ const previousCamera3dDurations = camera3dSegments.map(+ (segment) => segment.end - segment.start,+ );const tracks = [timeline.zoomSegments,timeline.sceneSegments ?? [],@@ -380,14 +406,69 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(timeline.captionSegments ?? [],timeline.keyboardSegments ?? [],timeline.audioSegments ?? [],+ camera3dSegments,];for (const track of tracks) {rippleTimelineTrack(track, boundary, shift);}+ for (let index = 0; index < camera3dSegments.length; index++) {+ const camera3dSegment = camera3dSegments[index];+ const previousDuration = previousCamera3dDurations[index];+ // Keyframe times are relative to the segment start, so a+ // segment the ripple resized (the straddling case) has to+ // have them rescaled onto its new length.+ const nextDuration = camera3dSegment.end - camera3dSegment.start;+ if (previousDuration <= 0 || nextDuration === previousDuration)+ continue;+ scaleKeyframeTimes(+ camera3dSegment.tracks,+ nextDuration / previousDuration,+ );+ }}),);};+ // Output-time boundaries of every clip that fall strictly inside a range.+ // A 3D scene lines its cuts up with these so the camera changes shot on+ // the same frame the footage does.+ const camera3DClipCuts = (start: number, end: number) => {+ const timeline = project.timeline;+ if (!timeline) return [];+ const offsets = clipTimelineOffsets(+ timeline.segments,+ timeline.transitions ?? [],+ );+ const cuts: number[] = [];+ for (let index = 0; index < timeline.segments.length; index++) {+ const boundaries = [+ offsets[index],+ offsets[index] + clipDuration(timeline.segments[index]),+ ];+ for (const boundary of boundaries)+ if (boundary > start && boundary < end) cuts.push(boundary);+ }+ return cuts;+ };++ /**+ * The chain a scene would lay over the whole timeline. The setup flow's+ * ghost placeholder and the action that commits it read this same+ * function, so the track previews exactly what lands.+ */+ const camera3DScenePreview = (sceneId: string, shots: number) => {+ const scene = CAMERA3D_SCENES.find((s) => s.id === sceneId);+ if (!scene) return [];++ const end = totalDuration();+ return applySceneToRange(+ sceneWithShotCount(scene, shots),+ 0,+ end,+ camera3DClipCuts(0, end),+ );+ };+const projectActions = {setClipTransition,normalizeClipTransitions: () => {@@ -545,6 +626,124 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(setEditorState("timeline", "selection", null);});},+ splitCamera3DSegment: (index: number, time: number) => {+ setProject(+ "timeline",+ "camera3dSegments",+ produce((segments) => {+ const segment = segments?.[index];+ if (!segment) return;++ const duration = segment.end - segment.start;+ const remaining = duration - time;+ if (time < 1 || remaining < 1) return;++ // A split must not change what plays: both halves meet on the pose+ // the segment held at the cut, so the left half moves start -> mid+ // and the right half picks up mid -> end. Blur is segment-level, so+ // it is simply carried onto both halves.+ const startPose = getStartPose(segment);+ const midPose = evaluatePose(segment, time);+ const endPose = getEndPose(segment);+ const easing = getMotionEasing(segment);++ const right: Camera3DSegment = {+ ...segment,+ start: segment.start + time,+ end: segment.end,+ properties: { ...segment.properties },+ blur: { ...segment.blur },+ tracks: defaultCamera3DTracks(),+ };+ setMotion(right, midPose, endPose, easing);+ segments.splice(index + 1, 0, right);++ const left = segments[index];+ left.end = segment.start + time;+ left.tracks = defaultCamera3DTracks();+ setMotion(left, startPose, midPose, easing);+ sortTrackSegments(segments);+ }),+ );+ },+ deleteCamera3DSegments: (segmentIndices: number[]) => {+ batch(() => {+ setProject(+ "timeline",+ "camera3dSegments",+ produce((segments) => {+ if (!segments) return;+ const sorted = [...new Set(segmentIndices)]+ .filter(+ (i) => Number.isInteger(i) && i >= 0 && i < segments.length,+ )+ .sort((a, b) => b - a);+ if (sorted.length === 0) return;+ for (const i of sorted) segments.splice(i, 1);+ }),+ );+ setEditorState("timeline", "selection", null);+ });+ },+ applyCamera3DScene: (segmentIndex: number, sceneId: string) => {+ const scene = CAMERA3D_SCENES.find((s) => s.id === sceneId);+ const segment = project.timeline?.camera3dSegments?.[segmentIndex];+ if (!scene || !segment) return;++ const { start, end } = segment;+ const generated = applySceneToRange(+ scene,+ start,+ end,+ camera3DClipCuts(start, end),+ );+ if (generated.length === 0) return;++ batch(() => {+ setProject(+ "timeline",+ "camera3dSegments",+ produce((segments) => {+ if (!segments) return;+ segments.splice(segmentIndex, 1, ...generated);+ sortTrackSegments(segments);+ }),+ );+ setEditorState("timeline", "selection", {+ type: "3d",+ indices: generated.map((_, offset) => segmentIndex + offset),+ });+ setEditorState("playbackTime", start);+ setEditorState("previewTime", null);+ });+ },+ addCamera3DScene: (sceneId: string, shots: number) => {+ // Only ever an empty-track offer: the scene owns the whole timeline,+ // so it must not land on top of shots someone has already authored.+ if (!project.timeline) return;+ if ((project.timeline.camera3dSegments?.length ?? 0) > 0) return;++ const generated = camera3DScenePreview(sceneId, shots);+ if (generated.length === 0) return;++ batch(() => {+ setProject("timeline", "camera3dSegments", (v) => v ?? []);+ setProject(+ "timeline",+ "camera3dSegments",+ produce((segments) => {+ if (!segments) return;+ segments.push(...generated);+ sortTrackSegments(segments);+ }),+ );+ setEditorState("timeline", "camera3dSetup", null);+ setEditorState("timeline", "tracks", "3d", true);+ setEditorState("timeline", "selection", { type: "3d", indices: [0] });+ setEditorState("playbackTime", 0);+ setEditorState("previewTime", null);+ });+ },splitMaskSegment: (index: number, time: number) => {setProject("timeline",@@ -957,6 +1156,23 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(keyboardSegment.start += diff(keyboardSegment.start);keyboardSegment.end += diff(keyboardSegment.end);}++ for (const camera3dSegment of timeline.camera3dSegments ?? []) {+ const previousDuration =+ camera3dSegment.end - camera3dSegment.start;+ camera3dSegment.start += diff(camera3dSegment.start);+ camera3dSegment.end += diff(camera3dSegment.end);+ // Keyframe times are relative to the segment start, so they+ // have to follow the segment's new length rather than the+ // absolute shift the other tracks use.+ const nextDuration = camera3dSegment.end - camera3dSegment.start;+ if (previousDuration <= 0 || nextDuration === previousDuration)+ continue;+ scaleKeyframeTimes(+ camera3dSegment.tracks,+ nextDuration / previousDuration,+ );+ }}),);},@@ -1188,6 +1404,8 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider((project.timeline?.captionSegments?.length ?? 0) > 0;const initialKeyboardTrackVisible =project.keyboard?.settings.enabled ?? false;+ const initialCamera3DTrackVisible =+ (project.timeline?.camera3dSegments?.length ?? 0) > 0;const [editorState, setEditorState] = createStore({previewTime: null as number | null,@@ -1217,7 +1435,8 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(| { type: "caption"; indices: number[] }| { type: "keyboard"; indices: number[] }| { type: "text"; indices: number[] }- | { type: "audio"; indices: number[] },+ | { type: "audio"; indices: number[] }+ | { type: "3d"; indices: number[] },transform: {// visible secondszoom: zoomOutLimit(),@@ -1260,6 +1479,7 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(keyboard: initialKeyboardTrackVisible,zoom: true,scene: true,+ "3d": initialCamera3DTrackVisible,mask: initialMaskTrackCount,text: initialTextTrackCount,audio: initialAudioTrackCount,@@ -1269,6 +1489,9 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(hoveredMaskTime: null as number | null,audioPicker: null as number | null,audioReplace: null as number | null,+ // The empty 3D track's setup flow: the scene and shot count the+ // sidebar is currently offering, previewed live on the track.+ camera3dSetup: null as null | { sceneId: string; shots: number },// Index of a just-created text segment that should open its// inline canvas editor as soon as its overlay mounts (set by the// Add-track picker, consumed by TextOverlay).@@ -1478,6 +1701,7 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(project,setProject,projectActions,+ camera3DScenePreview,projectHistory: createStoreHistory(project, setProject),editorState,setEditorState,diff --git a/apps/desktop/src/routes/editor/three-d.test.ts b/apps/desktop/src/routes/editor/three-d.test.tsnew file mode 100644index 000000000..0146d9945--- /dev/null+++ b/apps/desktop/src/routes/editor/three-d.test.ts@@ -0,0 +1,1064 @@+import { describe, expect, it } from "vitest";++import {+ ANGLE_PRESETS,+ anglePresetMotion,+ anglePresetPose,+ applyMotionTemplate,+ applySceneToRange,+ bezierEase,+ CAMERA3D_ANGLE_PRESET_KEYS,+ CAMERA3D_MIN_SHOT_DURATION,+ CAMERA3D_PROPERTY_KEYS,+ CAMERA3D_SCENES,+ CAMERA3D_TRACK_KEYS,+ type Camera3DKeyframe,+ type Camera3DProperties,+ type Camera3DScene,+ type Camera3DSegment,+ camera3DPosesEqual,+ DEFAULT_IN_EASING,+ DEFAULT_OUT_EASING,+ defaultCamera3DSegment,+ defaultCamera3DTracks,+ evaluatePose,+ fitCamera3DMotionToSegment,+ flipCamera3DSegment,+ getEndPose,+ getMotionEasing,+ getStartPose,+ hasCamera3DMotion,+ LINEAR_MOTION_EASING,+ MOTION_EASINGS,+ MOTION_TEMPLATES,+ normalizeCamera3DSegments,+ sampleTrack,+ sceneWithShotCount,+ setMotion,+ showcaseCamera3DBlur,+} from "./three-d";++const key = (+ time: number,+ value: number,+ handles?: Partial<Pick<Camera3DKeyframe, "outEasing" | "inEasing">>,+): Camera3DKeyframe => ({+ time,+ value,+ outEasing: handles?.outEasing ?? null,+ inEasing: handles?.inEasing ?? null,+});++const poseWith = (+ segment: Camera3DSegment,+ overrides: Partial<Camera3DProperties>,+): Camera3DProperties => ({ ...getStartPose(segment), ...overrides });++// Reading a pose back off a track is a lerp landing exactly on an endpoint, so+// the recovered value can differ from the authored one in the last bit.+const expectPose = (+ actual: Camera3DProperties,+ expected: Camera3DProperties,+) => {+ for (const property of CAMERA3D_PROPERTY_KEYS)+ expect(actual[property]).toBeCloseTo(expected[property], 9);+};++describe("sampleTrack", () => {+ it("returns the base value for an empty track", () => {+ expect(sampleTrack(7, [], 0)).toBe(7);+ expect(sampleTrack(7, [], 10)).toBe(7);+ });++ it("holds before the first and after the last keyframe", () => {+ const track = [key(1, 10), key(2, 20)];++ expect(sampleTrack(0, track, -5)).toBe(10);+ expect(sampleTrack(0, track, 1)).toBe(10);+ expect(sampleTrack(0, track, 2)).toBe(20);+ expect(sampleTrack(0, track, 99)).toBe(20);+ });++ it("sorts unsorted keyframes before sampling", () => {+ const track = [key(2, 20), key(1, 10)];++ expect(sampleTrack(0, track, 0)).toBe(10);+ expect(sampleTrack(0, track, 3)).toBe(20);+ });++ it("interpolates linearly with explicit [0,0] / [1,1] handles", () => {+ const track = [+ key(0, 0, { outEasing: [0, 0] }),+ key(1, 100, { inEasing: [1, 1] }),+ ];++ expect(sampleTrack(0, track, 0.25)).toBeCloseTo(25, 6);+ expect(sampleTrack(0, track, 0.5)).toBeCloseTo(50, 6);+ expect(sampleTrack(0, track, 0.75)).toBeCloseTo(75, 6);+ });++ it("falls back to cubic ease in out when handles are absent", () => {+ const track = [key(0, 0), key(1, 100)];++ // cubic-bezier(0.65, 0, 0.35, 1) is symmetric: the midpoint is exact and+ // the quarter points bracket the linear values.+ expect(sampleTrack(0, track, 0.5)).toBeCloseTo(50, 4);+ expect(sampleTrack(0, track, 0.25)).toBeLessThan(25);+ expect(sampleTrack(0, track, 0.75)).toBeGreaterThan(75);+ });++ it("matches an explicit default-handle pair exactly", () => {+ const implicit = [key(0, 0), key(1, 100)];+ const explicit = [+ key(0, 0, { outEasing: [...DEFAULT_OUT_EASING] }),+ key(1, 100, { inEasing: [...DEFAULT_IN_EASING] }),+ ];++ for (const t of [0.1, 0.33, 0.5, 0.8]) {+ expect(sampleTrack(0, implicit, t)).toBeCloseTo(+ sampleTrack(0, explicit, t),+ 10,+ );+ }+ });++ it("reads the split handles from either side of the span", () => {+ const track = [+ key(0, 0, { outEasing: [0, 0] }),+ key(1, 100, { inEasing: [1, 1] }),+ key(2, 0),+ ];++ // First span is explicitly linear, second falls back to the cubic ease.+ expect(sampleTrack(0, track, 0.5)).toBeCloseTo(50, 6);+ expect(sampleTrack(0, track, 1.5)).toBeCloseTo(50, 4);+ });+});++describe("bezierEase", () => {+ it("clamps outside the unit interval", () => {+ expect(bezierEase([0.65, 0], [0.35, 1], -1)).toBe(0);+ expect(bezierEase([0.65, 0], [0.35, 1], 2)).toBe(1);+ });++ it("takes the linear fast path for [0,0] / [1,1]", () => {+ expect(bezierEase([0, 0], [1, 1], 0.31)).toBe(0.31);+ });+});++describe("setMotion", () => {+ it("collapses equal poses to a still shot with no keyframes", () => {+ const segment = defaultCamera3DSegment(2, 6);+ const pose = poseWith(segment, { zoom: 1.4, tiltY: 12 });++ setMotion(segment, pose, { ...pose });++ for (const property of CAMERA3D_PROPERTY_KEYS) {+ expect(segment.tracks[property]).toEqual([]);+ expect(segment.properties[property]).toBe(pose[property]);+ }+ expect(hasCamera3DMotion(segment)).toBe(false);+ });++ it("keys only the properties that actually move", () => {+ const segment = defaultCamera3DSegment(2, 6);+ const start = getStartPose(segment);+ const end = { ...start, zoom: start.zoom + 1 };++ setMotion(segment, start, end);++ expect(segment.tracks.zoom).toHaveLength(2);+ expect(segment.tracks.zoom[0]).toMatchObject({+ time: 0,+ value: start.zoom,+ });+ expect(segment.tracks.zoom[1]).toMatchObject({ time: 4, value: end.zoom });+ expect(segment.tracks.tiltX).toEqual([]);+ expect(hasCamera3DMotion(segment)).toBe(true);+ });++ it("round-trips through getStartPose / getEndPose", () => {+ const segment = defaultCamera3DSegment(1, 5);+ const start = poseWith(segment, { zoom: 0.8, panX: -0.4, fov: 30 });+ const end = poseWith(segment, { zoom: 2.2, panX: 0.5, fov: 60, roll: 8 });++ setMotion(segment, start, end);++ expectPose(getStartPose(segment), start);+ expectPose(getEndPose(segment), end);+ });++ it("recovers the poses of an old multi-keyframe segment and flattens them", () => {+ const segment = defaultCamera3DSegment(0, 4);+ // Three keyframes with a detour in the middle, as the old record-mode UX+ // could author.+ segment.tracks.zoom = [key(0, 1), key(1.5, 3), key(4, 2)];+ segment.tracks.panX = [key(0, -0.5), key(4, 0.5)];++ const start = getStartPose(segment);+ const end = getEndPose(segment);+ expect(start.zoom).toBe(1);+ expect(end.zoom).toBe(2);+ expect(start.panX).toBe(-0.5);+ expect(end.panX).toBe(0.5);++ setMotion(segment, start, end);++ expect(segment.tracks.zoom).toHaveLength(2);+ expectPose(getStartPose(segment), start);+ expectPose(getEndPose(segment), end);+ });++ it("never touches the blur config or its tracks", () => {+ const segment = defaultCamera3DSegment(0, 4);+ segment.tracks.blurStrength = [key(0, 5), key(4, 9)];+ const blur = { ...segment.blur };++ setMotion(+ segment,+ getStartPose(segment),+ poseWith(segment, { zoom: 3 }),+ MOTION_EASINGS[1],+ );++ expect(segment.blur).toEqual(blur);+ expect(segment.tracks.blurStrength).toEqual([key(0, 5), key(4, 9)]);+ });+});++describe("MOTION_EASINGS", () => {+ it("defaults to linear", () => {+ expect(LINEAR_MOTION_EASING).toBe(MOTION_EASINGS[0]);+ expect(LINEAR_MOTION_EASING.out).toEqual([0, 0]);+ expect(LINEAR_MOTION_EASING.in).toEqual([1, 1]);+ expect(MOTION_EASINGS.map((easing) => easing.label)).toEqual([+ "Linear",+ "Smooth",+ "Ease in",+ "Ease out",+ ]);+ });++ it("writes and reads back every style", () => {+ for (const easing of MOTION_EASINGS) {+ const segment = defaultCamera3DSegment(0, 4);+ const start = getStartPose(segment);+ const end = { ...start, zoom: start.zoom + 1 };++ setMotion(segment, start, end, easing);++ expect(segment.tracks.zoom[0].outEasing).toEqual(easing.out);+ expect(segment.tracks.zoom[1].inEasing).toEqual(easing.in);+ expect(getMotionEasing(segment)).toBe(easing);+ }+ });++ it("reads a still shot and an unrecognised curve as linear", () => {+ const still = defaultCamera3DSegment(0, 4);+ expect(getMotionEasing(still)).toBe(LINEAR_MOTION_EASING);++ const custom = defaultCamera3DSegment(0, 4);+ custom.tracks.zoom = [+ key(0, 1, { outEasing: [0.11, 0.22] }),+ key(4, 2, { inEasing: [0.33, 0.44] }),+ ];+ expect(getMotionEasing(custom)).toBe(LINEAR_MOTION_EASING);+ });+});++describe("camera3DPosesEqual", () => {+ it("ignores differences finer than a still shot", () => {+ const segment = defaultCamera3DSegment(0, 4);+ const pose = getStartPose(segment);++ expect(camera3DPosesEqual(pose, { ...pose, zoom: pose.zoom + 1e-6 })).toBe(+ true,+ );+ expect(camera3DPosesEqual(pose, { ...pose, zoom: pose.zoom + 0.01 })).toBe(+ false,+ );+ });+});++describe("ANGLE_PRESETS", () => {+ it("ships the five angle presets", () => {+ expect(ANGLE_PRESETS.map((preset) => preset.id)).toEqual([+ "spotlight",+ "perspective",+ "center",+ "low-angle",+ "close-up",+ ]);+ });++ it("never writes the content plane rotations", () => {+ for (const preset of ANGLE_PRESETS) {+ expect(Object.keys(preset.values).sort()).toEqual(+ [...CAMERA3D_ANGLE_PRESET_KEYS].sort(),+ );+ expect(preset.values).not.toHaveProperty("rotateX");+ expect(preset.values).not.toHaveProperty("rotateY");+ }+ });++ it("every angle preset is a moving shot opening on its named pose", () => {+ for (const preset of ANGLE_PRESETS) {+ const motion = anglePresetMotion(preset);+ expect(motion.from).toEqual(anglePresetPose(preset));+ // The drift only touches pose keys and actually moves something.+ expect(Object.keys(preset.drift).length).toBeGreaterThan(0);+ for (const key of Object.keys(preset.drift))+ expect(CAMERA3D_ANGLE_PRESET_KEYS).toContain(key);+ expect(motion.to).not.toEqual(motion.from);+ expect(motion.to.rotateX).toBe(0);+ expect(motion.to.rotateY).toBe(0);+ }+ });++ it("applying an angle preset writes keyframes like a motion template", () => {+ const preset = ANGLE_PRESETS.find((p) => p.id === "perspective");+ expect(preset).toBeDefined();+ if (!preset) return;++ const segment = defaultCamera3DSegment(2, 6);+ applyMotionTemplate(segment, anglePresetMotion(preset));++ expect(segment.tracks.tiltY).toHaveLength(2);+ expect(segment.tracks.tiltY[0]).toMatchObject({ time: 0, value: 26 });+ expect(segment.tracks.tiltY[1]).toMatchObject({ time: 4, value: 18 });+ expect(segment.tracks.zoom[1].value).toBeCloseTo(1.53);+ expect(segment.transitionIn).toBe(0);+ expect(segment.transitionOut).toBe(0);+ });+});++describe("MOTION_TEMPLATES", () => {+ it("ships eight templates with unique ids", () => {+ expect(MOTION_TEMPLATES).toHaveLength(8);+ expect(new Set(MOTION_TEMPLATES.map((t) => t.id)).size).toBe(8);+ });++ it("writes two explicitly linear keyframes on every moving camera track", () => {+ for (const template of MOTION_TEMPLATES) {+ const segment = defaultCamera3DSegment(2, 6);+ applyMotionTemplate(segment, template);++ expectPose(getStartPose(segment), template.from);+ expectPose(getEndPose(segment), template.to);+ expect(getMotionEasing(segment)).toBe(LINEAR_MOTION_EASING);++ for (const property of CAMERA3D_PROPERTY_KEYS) {+ const track = segment.tracks[property];+ // A property the template holds still carries no keyframes at all.+ if (template.from[property] === template.to[property]) {+ expect(track).toEqual([]);+ expect(segment.properties[property]).toBe(template.from[property]);+ continue;+ }+ expect(track).toHaveLength(2);+ expect(track[0].time).toBe(0);+ expect(track[1].time).toBe(4);+ expect(track[0].value).toBe(template.from[property]);+ expect(track[1].value).toBe(template.to[property]);+ expect(track[0].outEasing).toEqual([0, 0]);+ expect(track[1].inEasing).toEqual([1, 1]);+ }++ // Blur tracks are the user's, so a template must not touch them.+ for (const trackKey of CAMERA3D_TRACK_KEYS) {+ if ((CAMERA3D_PROPERTY_KEYS as readonly string[]).includes(trackKey))+ continue;+ expect(segment.tracks[trackKey]).toEqual([]);+ }+ }+ });++ it("cuts into the move by clearing any transition the segment carried", () => {+ const segment = defaultCamera3DSegment(0, 4);+ segment.transitionIn = 0.3;+ segment.transitionOut = 0.3;++ applyMotionTemplate(segment, MOTION_TEMPLATES[0]);++ expect(segment.transitionIn).toBe(0);+ expect(segment.transitionOut).toBe(0);+ });++ it("samples linearly between the two poses", () => {+ const template = MOTION_TEMPLATES[0];+ const segment = defaultCamera3DSegment(0, 4);+ applyMotionTemplate(segment, template);++ expect(sampleTrack(0, segment.tracks.panX, 2)).toBeCloseTo(+ (template.from.panX + template.to.panX) / 2,+ 6,+ );+ });+});++describe("template blur", () => {+ const cards = () => [+ ...ANGLE_PRESETS.map((preset) => anglePresetMotion(preset)),+ ...MOTION_TEMPLATES,+ ];++ it("gives every card a complete radial look", () => {+ for (const card of cards()) {+ expect(card.blur.mode).toBe("radial");+ expect(card.blur.bokeh).toBe(true);+ expect(card.blur.angle).toBe(0);+ expect(card.blur.dirPosition).toBe(0.5);+ expect(card.blur.strength).toBeGreaterThan(0);+ }+ });++ it("uses the showcase defocus everywhere but the two authored exceptions", () => {+ const detail = {+ mode: "radial",+ strength: 20,+ falloff: 0.76,+ focusX: 0.11,+ focusY: 0.5,+ focusSize: 0.18,+ angle: 0,+ dirPosition: 0.5,+ bokeh: true,+ };+ const overhead = {+ mode: "radial",+ strength: 18,+ falloff: 0.72,+ focusX: 0.03,+ focusY: 0.36,+ focusSize: 0.55,+ angle: 0,+ dirPosition: 0.5,+ bokeh: true,+ };++ for (const card of cards()) {+ if (card.id === "angle-close-up") expect(card.blur).toEqual(detail);+ else if (card.id === "top-down") expect(card.blur).toEqual(overhead);+ else expect(card.blur).toEqual(showcaseCamera3DBlur());+ }+ });++ it("writes the card's blur onto the segment, replacing whatever was there", () => {+ const overhead = MOTION_TEMPLATES.find((t) => t.id === "top-down");+ expect(overhead).toBeDefined();+ if (!overhead) return;++ const segment = defaultCamera3DSegment(0, 4);+ segment.blur = { ...segment.blur, mode: "directional", strength: 3 };++ applyMotionTemplate(segment, overhead);++ expect(segment.blur).toEqual(overhead.blur);+ // A copy, so editing the segment never mutates the template.+ expect(segment.blur).not.toBe(overhead.blur);+ });+});++describe("CAMERA3D_SCENES", () => {+ it("ships three scenes with unique ids and three shots each", () => {+ expect(CAMERA3D_SCENES.map((scene) => scene.id)).toEqual([+ "showcase",+ "product-tour",+ "punch-in",+ ]);+ expect(new Set(CAMERA3D_SCENES.map((scene) => scene.id)).size).toBe(3);+ for (const scene of CAMERA3D_SCENES) expect(scene.shots).toHaveLength(3);+ });++ it("gives every scene weights that fill its range and a blur per shot", () => {+ for (const scene of CAMERA3D_SCENES) {+ const total = scene.shots.reduce((sum, shot) => sum + shot.weight, 0);+ expect(total).toBeCloseTo(1, 6);+ for (const shot of scene.shots) {+ expect(shot.weight).toBeGreaterThan(0);+ expect(shot.blur.mode).toBe("radial");+ expect(shot.blur.bokeh).toBe(true);+ }+ }+ });++ it("matches the reference project's showcase values verbatim", () => {+ const showcase = CAMERA3D_SCENES.find((scene) => scene.id === "showcase");+ expect(showcase).toBeDefined();+ if (!showcase) return;++ const [close, overhead, push] = showcase.shots;++ expect(close.weight).toBe(0.27);+ expect(close.from).toEqual({+ tiltX: 26,+ tiltY: -22,+ roll: 1,+ rotateX: 0,+ rotateY: 0,+ fov: 45,+ zoom: 0.8,+ panX: -0.3,+ panY: -0.4,+ });+ expect(close.to).toEqual({ ...close.from, tiltY: -27, panX: -0.36 });+ expect(close.blur).toEqual({+ mode: "radial",+ strength: 20,+ falloff: 0.76,+ focusX: 0.11,+ focusY: 0.5,+ focusSize: 0.18,+ angle: 0,+ dirPosition: 0.5,+ bokeh: true,+ });++ expect(overhead.weight).toBe(0.25);+ expect(overhead.from).toEqual({+ tiltX: 24.8,+ tiltY: 17.04,+ roll: 0,+ rotateX: -40,+ rotateY: 18,+ fov: 60,+ zoom: 0.5,+ panX: -0.065,+ panY: -0.195,+ });+ expect(overhead.to).toEqual({+ ...overhead.from,+ tiltX: 34.19,+ tiltY: 15.28,+ rotateY: 9,+ panX: -0.217,+ panY: -0.476,+ });+ expect(overhead.blur).toEqual({+ mode: "radial",+ strength: 18,+ falloff: 0.72,+ focusX: 0.03,+ focusY: 0.36,+ focusSize: 0.55,+ angle: 0,+ dirPosition: 0.5,+ bokeh: true,+ });++ expect(push.weight).toBe(0.48);+ expect(push.from).toEqual({+ tiltX: 0,+ tiltY: 0,+ roll: 0,+ rotateX: -14,+ rotateY: 0,+ fov: 45,+ zoom: 0.715,+ panX: 0,+ panY: 0,+ });+ expect(push.to).toEqual({ ...push.from, zoom: 1.6 });+ expect(push.blur).toEqual({+ mode: "radial",+ strength: 19,+ falloff: 0.67,+ focusX: 0.37,+ focusY: 0.52,+ focusSize: 0.4,+ angle: 0,+ dirPosition: 0.5,+ bokeh: true,+ });+ });++ it("builds the derived scenes out of the existing card looks", () => {+ const tour = CAMERA3D_SCENES.find((scene) => scene.id === "product-tour");+ const punch = CAMERA3D_SCENES.find((scene) => scene.id === "punch-in");+ expect(tour).toBeDefined();+ expect(punch).toBeDefined();+ if (!tour || !punch) return;++ const template = (id: string) => {+ const found = MOTION_TEMPLATES.find((t) => t.id === id);+ expect(found).toBeDefined();+ return found;+ };+ const preset = (id: string) => {+ const found = ANGLE_PRESETS.find((p) => p.id === id);+ expect(found).toBeDefined();+ return found ? anglePresetMotion(found) : undefined;+ };++ const expectShot = (+ shot: (typeof tour.shots)[number],+ card: ReturnType<typeof template>,+ weight: number,+ ) => {+ expect(card).toBeDefined();+ if (!card) return;+ expect(shot.weight).toBe(weight);+ expect(shot.from).toEqual(card.from);+ expect(shot.to).toEqual(card.to);+ expect(shot.blur).toEqual(card.blur);+ };++ expectShot(tour.shots[0], template("unfold"), 0.3);+ expectShot(tour.shots[1], preset("perspective"), 0.3);+ expectShot(tour.shots[2], preset("center"), 0.4);++ expectShot(punch.shots[0], preset("spotlight"), 0.3);+ expectShot(punch.shots[1], preset("close-up"), 0.3);+ expectShot(punch.shots[2], template("pull-back"), 0.4);+ });+});++describe("sceneWithShotCount", () => {+ const showcase = CAMERA3D_SCENES[0];++ it("keeps the leading shots and renormalizes their weights", () => {+ const two = sceneWithShotCount(showcase, 2);++ expect(two.shots).toHaveLength(2);+ expect(two.shots[0].weight).toBeCloseTo(0.27 / 0.52, 9);+ expect(two.shots[1].weight).toBeCloseTo(0.25 / 0.52, 9);+ expect(two.shots.reduce((sum, shot) => sum + shot.weight, 0)).toBeCloseTo(+ 1,+ 9,+ );+ // Only the weight changes: the look and the move are the scene's.+ expect(two.shots[0].from).toEqual(showcase.shots[0].from);+ expect(two.shots[0].to).toEqual(showcase.shots[0].to);+ expect(two.shots[1].blur).toEqual(showcase.shots[1].blur);+ expect(two.id).toBe(showcase.id);+ });++ it("gives a single shot the whole range", () => {+ const one = sceneWithShotCount(showcase, 1);++ expect(one.shots).toHaveLength(1);+ expect(one.shots[0].weight).toBeCloseTo(1, 9);+ expect(one.shots[0].from).toEqual(showcase.shots[0].from);+ });++ it("clamps a count outside the scene's shots", () => {+ expect(sceneWithShotCount(showcase, 0).shots).toHaveLength(1);+ expect(sceneWithShotCount(showcase, -3).shots).toHaveLength(1);+ expect(sceneWithShotCount(showcase, 2.7).shots).toHaveLength(2);+ expect(sceneWithShotCount(showcase, 3)).toBe(showcase);+ expect(sceneWithShotCount(showcase, 99)).toBe(showcase);+ });++ it("never mutates the scene it truncates", () => {+ const before = showcase.shots.map((shot) => shot.weight);++ sceneWithShotCount(showcase, 1);+ sceneWithShotCount(showcase, 2);++ expect(showcase.shots.map((shot) => shot.weight)).toEqual(before);+ });+});++describe("applySceneToRange", () => {+ const showcase = CAMERA3D_SCENES[0];++ const boundariesOf = (segments: Camera3DSegment[]) => [+ segments[0].start,+ ...segments.map((segment) => segment.end),+ ];++ it("splits a range by shot weight", () => {+ const segments = applySceneToRange(showcase, 0, 10, []);++ expect(segments).toHaveLength(3);+ const boundaries = boundariesOf(segments);+ expect(boundaries[0]).toBeCloseTo(0, 9);+ expect(boundaries[1]).toBeCloseTo(2.7, 9);+ expect(boundaries[2]).toBeCloseTo(5.2, 9);+ expect(boundaries[3]).toBeCloseTo(10, 9);+ });++ it("lays the shots end to end with no gaps, wherever the range starts", () => {+ const segments = applySceneToRange(showcase, 4, 14, []);++ expect(segments[0].start).toBe(4);+ expect(segments[segments.length - 1].end).toBe(14);+ for (let index = 1; index < segments.length; index++)+ expect(segments[index].start).toBe(segments[index - 1].end);+ });++ it("snaps an interior boundary onto a nearby clip cut", () => {+ const segments = applySceneToRange(showcase, 0, 11.14, [3.03]);++ expect(segments).toHaveLength(3);+ expect(segments[0].end).toBe(3.03);+ expect(segments[1].start).toBe(3.03);+ // The far boundary had no cut within reach, so it stays on its weight.+ expect(segments[1].end).toBeCloseTo(11.14 * 0.52, 9);+ });++ it("ignores a cut further than the snap window away", () => {+ // Window is 15% of the 10s range, and 6.9 is out of reach of both the+ // 2.7 and the 5.2 boundary.+ const segments = applySceneToRange(showcase, 0, 10, [6.9]);++ expect(segments[0].end).toBeCloseTo(2.7, 9);+ expect(segments[1].end).toBeCloseTo(5.2, 9);+ });++ it("drops a snap that would leave a shot under the minimum", () => {+ // Range fits three shots with almost nothing to spare, so the last+ // boundary cannot travel to the cut even though it is within the window.+ const segments = applySceneToRange(showcase, 0, 3.4, [2.45]);++ expect(segments).toHaveLength(3);+ expect(segments[1].end).toBeCloseTo(2, 9);+ for (const segment of segments)+ expect(segment.end - segment.start).toBeGreaterThanOrEqual(+ CAMERA3D_MIN_SHOT_DURATION - 1e-9,+ );+ });++ it("takes a snap that keeps every shot long enough", () => {+ const segments = applySceneToRange(showcase, 0, 3.4, [2.3]);++ expect(segments[1].end).toBe(2.3);+ });++ it("drops trailing shots a short range cannot fit", () => {+ const segments = applySceneToRange(showcase, 0, 2.5, []);++ expect(segments).toHaveLength(2);+ expect(segments[0].start).toBe(0);+ expect(segments[segments.length - 1].end).toBe(2.5);+ for (const segment of segments)+ expect(segment.end - segment.start).toBeGreaterThanOrEqual(+ CAMERA3D_MIN_SHOT_DURATION - 1e-9,+ );+ // The leading shots are kept, re-weighted onto the whole range.+ expectPose(getStartPose(segments[0]), showcase.shots[0].from);+ expectPose(getEndPose(segments[1]), showcase.shots[1].to);+ });++ it("never drops below one shot, and refuses an empty range", () => {+ expect(applySceneToRange(showcase, 0, 0.4, [])).toHaveLength(1);+ expect(applySceneToRange(showcase, 5, 5, [])).toEqual([]);+ expect(applySceneToRange(showcase, 5, 1, [])).toEqual([]);+ });++ it("fills the range with a scene truncated to fewer shots", () => {+ const two = applySceneToRange(sceneWithShotCount(showcase, 2), 0, 10, []);++ expect(two).toHaveLength(2);+ expect(two[0].start).toBe(0);+ expect(two[0].end).toBeCloseTo(10 * (0.27 / 0.52), 9);+ expect(two[1].start).toBe(two[0].end);+ expect(two[1].end).toBe(10);+ expectPose(getStartPose(two[0]), showcase.shots[0].from);+ expectPose(getEndPose(two[1]), showcase.shots[1].to);++ const one = applySceneToRange(sceneWithShotCount(showcase, 1), 0, 10, []);++ expect(one).toHaveLength(1);+ expect(one[0].start).toBe(0);+ expect(one[0].end).toBe(10);+ expectPose(getStartPose(one[0]), showcase.shots[0].from);+ expectPose(getEndPose(one[0]), showcase.shots[0].to);+ });++ it("still truncates a scene the range cannot fit", () => {+ // Two shots asked for, one second of room: the fallback inside+ // applySceneToRange drops the shot that would not read as a cut.+ const segments = applySceneToRange(+ sceneWithShotCount(showcase, 2),+ 0,+ 1.5,+ [],+ );++ expect(segments).toHaveLength(1);+ expect(segments[0].start).toBe(0);+ expect(segments[0].end).toBe(1.5);+ });++ it("writes each shot's move, look and cut for every scene", () => {+ for (const scene of CAMERA3D_SCENES) {+ const segments = applySceneToRange(scene, 0, 30, []);+ expect(segments).toHaveLength(scene.shots.length);++ segments.forEach((segment, index) => {+ const shot = scene.shots[index];++ expect(segment.enabled).toBe(true);+ expect(segment.transitionIn).toBe(0);+ expect(segment.transitionOut).toBe(0);+ expect(segment.blur).toEqual(shot.blur);+ // A copy: editing one shot must not touch the scene data.+ expect(segment.blur).not.toBe(shot.blur);++ expectPose(getStartPose(segment), shot.from);+ expectPose(getEndPose(segment), shot.to);+ expect(hasCamera3DMotion(segment)).toBe(+ !camera3DPosesEqual(shot.from, shot.to),+ );+ if (hasCamera3DMotion(segment))+ expect(getMotionEasing(segment)).toBe(LINEAR_MOTION_EASING);++ // Motion always spans the shot it was written onto.+ for (const property of CAMERA3D_PROPERTY_KEYS) {+ const track = segment.tracks[property];+ if (track.length === 0) continue;+ expect(track[0].time).toBe(0);+ expect(track[1].time).toBeCloseTo(segment.end - segment.start, 9);+ }+ });+ }+ });++ it("holds a still shot as a plain pose", () => {+ const still: Camera3DScene = {+ id: "still",+ name: "Still",+ shots: [+ {+ weight: 1,+ from: anglePresetPose(ANGLE_PRESETS[0]),+ to: anglePresetPose(ANGLE_PRESETS[0]),+ blur: showcaseCamera3DBlur(),+ },+ ],+ };++ const [segment] = applySceneToRange(still, 0, 5, []);++ expect(hasCamera3DMotion(segment)).toBe(false);+ expectPose(getStartPose(segment), anglePresetPose(ANGLE_PRESETS[0]));+ });+});++describe("split continuity", () => {+ // Mirrors projectActions.splitCamera3DSegment: both halves have to meet on+ // the pose the original segment held at the cut.+ const split = (segment: Camera3DSegment, time: number) => {+ const startPose = getStartPose(segment);+ const midPose = evaluatePose(segment, time);+ const endPose = getEndPose(segment);+ const easing = getMotionEasing(segment);++ const right: Camera3DSegment = {+ ...segment,+ start: segment.start + time,+ properties: { ...segment.properties },+ blur: { ...segment.blur },+ tracks: defaultCamera3DTracks(),+ };+ setMotion(right, midPose, endPose, easing);++ const left: Camera3DSegment = {+ ...segment,+ end: segment.start + time,+ properties: { ...segment.properties },+ blur: { ...segment.blur },+ tracks: defaultCamera3DTracks(),+ };+ setMotion(left, startPose, midPose, easing);++ return { left, right, midPose };+ };++ it("keeps the pose at the cut identical on both halves", () => {+ const segment = defaultCamera3DSegment(0, 4);+ applyMotionTemplate(segment, MOTION_TEMPLATES[3]);++ const { left, right, midPose } = split(segment, 1.5);++ expectPose(getEndPose(left), midPose);+ expectPose(getStartPose(right), midPose);+ expectPose(getStartPose(left), getStartPose(segment));+ expectPose(getEndPose(right), getEndPose(segment));+ });++ it("re-times both halves onto their own length", () => {+ const segment = defaultCamera3DSegment(0, 4);+ applyMotionTemplate(segment, MOTION_TEMPLATES[3]);++ const { left, right } = split(segment, 1.5);++ expect(left.tracks.zoom[1].time).toBeCloseTo(1.5, 10);+ expect(right.tracks.zoom[1].time).toBeCloseTo(2.5, 10);+ });++ it("leaves a still shot still on both sides", () => {+ const segment = defaultCamera3DSegment(0, 4);++ const { left, right } = split(segment, 2);++ expect(hasCamera3DMotion(left)).toBe(false);+ expect(hasCamera3DMotion(right)).toBe(false);+ expectPose(getStartPose(right), getStartPose(segment));+ });+});++describe("normalizeCamera3DSegments", () => {+ it("fills every default and gives each track an array", () => {+ const [segment] = normalizeCamera3DSegments([{ start: 1, end: 3 }]);++ expect(segment.enabled).toBe(true);+ expect(segment.properties.fov).toBe(45);+ expect(segment.properties.zoom).toBe(2);+ expect(segment.blur.mode).toBe("none");+ expect(segment.blur.focusX).toBe(0.37);+ // Absent transitions mean a clean cut, matching the renderer's default.+ expect(segment.transitionIn).toBe(0);+ expect(segment.transitionOut).toBe(0);+ for (const trackKey of CAMERA3D_TRACK_KEYS)+ expect(segment.tracks[trackKey]).toEqual([]);+ });++ it("sorts keyframes and normalizes absent handles to null", () => {+ const [segment] = normalizeCamera3DSegments([+ {+ start: 0,+ end: 2,+ tracks: {+ ...defaultCamera3DTracks(),+ zoom: [+ { time: 1, value: 3 },+ { time: 0, value: 1 },+ ],+ },+ },+ ]);++ // Sorted, and the stale 1s span is stretched onto the 2s segment by+ // the fit-on-load invariant.+ expect(segment.tracks.zoom.map((k) => k.time)).toEqual([0, 2]);+ expect(segment.tracks.zoom[0].outEasing).toBeNull();+ expect(segment.tracks.zoom[0].inEasing).toBeNull();+ });+});++describe("defaultCamera3DSegment", () => {+ it("opens on the Angled pose so the 3D look is visible immediately", () => {+ const segment = defaultCamera3DSegment(0, 5);+ const angled = ANGLE_PRESETS.find((preset) => preset.id === "perspective");++ expect(angled).toBeDefined();+ for (const property of CAMERA3D_ANGLE_PRESET_KEYS)+ expect(segment.properties[property]).toBe(angled?.values[property]);+ expect(segment.properties.rotateX).toBe(0);+ expect(segment.properties.rotateY).toBe(0);+ });++ it("opens on the showcase blur so the cinematic look is on by default", () => {+ expect(defaultCamera3DSegment(0, 5).blur).toEqual(showcaseCamera3DBlur());+ expect(showcaseCamera3DBlur()).toMatchObject({+ mode: "radial",+ strength: 19,+ falloff: 0.62,+ bokeh: true,+ focusX: 0.37,+ focusY: 0.5,+ focusSize: 0.4,+ });+ });++ it("is a still shot with no keyframes until something moves it", () => {+ const segment = defaultCamera3DSegment(0, 5);++ expect(hasCamera3DMotion(segment)).toBe(false);+ expectPose(getStartPose(segment), getEndPose(segment));+ });++ it("cuts straight in and out, with no ramp either side", () => {+ const segment = defaultCamera3DSegment(0, 5);++ expect(segment.transitionIn).toBe(0);+ expect(segment.transitionOut).toBe(0);+ });+});++describe("fitCamera3DMotionToSegment", () => {+ it("rescales track times onto the segment duration after a resize", () => {+ const segment = defaultCamera3DSegment(0, 4);+ setMotion(segment, getStartPose(segment), poseWith(segment, { zoom: 3 }));++ // A trim shortened the segment; keyframes still span the old 4s.+ segment.end = 2.5;+ fitCamera3DMotionToSegment(segment);++ expect(segment.tracks.zoom[1].time).toBeCloseTo(2.5, 9);+ // Applying again is a no-op (safe during live drags).+ fitCamera3DMotionToSegment(segment);+ expect(segment.tracks.zoom[1].time).toBeCloseTo(2.5, 9);+ });++ it("repairs stale spans on load through normalize", () => {+ const segment = defaultCamera3DSegment(0, 3.025);+ segment.tracks.tiltY = [+ { time: 0, value: -22, outEasing: [0, 0], inEasing: null },+ { time: 4.8625, value: -27, outEasing: null, inEasing: [1, 1] },+ ];++ const [normalized] = normalizeCamera3DSegments([segment]);+ expect(normalized.tracks.tiltY[1].time).toBeCloseTo(3.025, 9);+ });++ it("leaves still segments alone", () => {+ const segment = defaultCamera3DSegment(0, 4);+ fitCamera3DMotionToSegment(segment);+ for (const track of Object.values(segment.tracks))+ expect(track).toEqual([]);+ });+});++describe("flipCamera3DSegment", () => {+ it("mirrors the pose family, tracks, and blur focus horizontally", () => {+ const segment = defaultCamera3DSegment(0, 4);+ setMotion(+ segment,+ poseWith(segment, { tiltY: 26, roll: 5, panX: 0.37, rotateY: 18 }),+ poseWith(segment, { tiltY: 18, roll: 5, panX: 0.2, rotateY: 9 }),+ );+ segment.blur.focusX = 0.11;+ segment.blur.angle = 30;++ flipCamera3DSegment(segment, "horizontal");++ expect(getStartPose(segment).tiltY).toBeCloseTo(-26, 9);+ expect(getEndPose(segment).tiltY).toBeCloseTo(-18, 9);+ expect(getStartPose(segment).panX).toBeCloseTo(-0.37, 9);+ expect(getStartPose(segment).rotateY).toBeCloseTo(-18, 9);+ expect(getStartPose(segment).roll).toBeCloseTo(-5, 9);+ // Vertical family untouched (the default segment opens on Perspective).+ expect(getStartPose(segment).tiltX).toBeCloseTo(-28, 9);+ expect(segment.blur.focusX).toBeCloseTo(0.89, 9);+ expect(segment.blur.angle).toBeCloseTo(150, 9);++ // Flipping twice restores the original.+ flipCamera3DSegment(segment, "horizontal");+ expect(getStartPose(segment).tiltY).toBeCloseTo(26, 9);+ expect(segment.blur.focusX).toBeCloseTo(0.11, 9);+ expect(segment.blur.angle).toBeCloseTo(30, 9);+ });++ it("mirrors the vertical family and focus Y", () => {+ const segment = defaultCamera3DSegment(0, 4);+ setMotion(+ segment,+ poseWith(segment, { tiltX: -50, panY: -0.4, rotateX: -14 }),+ poseWith(segment, { tiltX: -44, panY: -0.2, rotateX: -14 }),+ );+ segment.blur.focusY = 0.36;++ flipCamera3DSegment(segment, "vertical");++ expect(getStartPose(segment).tiltX).toBeCloseTo(50, 9);+ expect(getEndPose(segment).tiltX).toBeCloseTo(44, 9);+ expect(getStartPose(segment).panY).toBeCloseTo(0.4, 9);+ expect(getStartPose(segment).rotateX).toBeCloseTo(14, 9);+ // Horizontal family untouched.+ expect(getStartPose(segment).tiltY).toBeCloseTo(26, 9);+ expect(segment.blur.focusY).toBeCloseTo(0.64, 9);+ });+});diff --git a/apps/desktop/src/routes/editor/three-d.ts b/apps/desktop/src/routes/editor/three-d.tsnew file mode 100644index 000000000..e2fb93ccf--- /dev/null+++ b/apps/desktop/src/routes/editor/three-d.ts@@ -0,0 +1,1371 @@+import type {+ Camera3DBlurMode,+ Camera3DBlur as RawCamera3DBlur,+ Camera3DKeyframe as RawCamera3DKeyframe,+ Camera3DProperties as RawCamera3DProperties,+ Camera3DSegment as RawCamera3DSegment,+ Camera3DTracks as RawCamera3DTracks,+} from "~/utils/tauri";++export type { Camera3DBlurMode };++/**+ * Local, strict mirrors of the generated schema: every field is required so the+ * editor never has to re-check for absent values while sampling or editing.+ * `normalizeCamera3DSegments` is the one place the loose wire shape is filled in.+ */+export type Camera3DProperties = {+ tiltX: number;+ tiltY: number;+ roll: number;+ rotateX: number;+ rotateY: number;+ fov: number;+ zoom: number;+ panX: number;+ panY: number;+};++export type Camera3DBlur = {+ mode: Camera3DBlurMode;+ strength: number;+ falloff: number;+ focusX: number;+ focusY: number;+ focusSize: number;+ angle: number;+ dirPosition: number;+ bokeh: boolean;+};++export type Camera3DKeyframe = {+ /** Seconds relative to the segment start. */+ time: number;+ value: number;+ /** Bezier P1 for the span leaving this keyframe. */+ outEasing: [number, number] | null;+ /** Bezier P2 for the span entering this keyframe. */+ inEasing: [number, number] | null;+};++export type Camera3DPropertyKey = keyof Camera3DProperties;++export type Camera3DBlurScalarKey =+ | "strength"+ | "falloff"+ | "focusX"+ | "focusY"+ | "focusSize"+ | "angle"+ | "dirPosition";++export type Camera3DTrackKey =+ | Camera3DPropertyKey+ | "blurStrength"+ | "blurFalloff"+ | "blurFocusSize"+ | "blurFocusX"+ | "blurFocusY"+ | "blurAngle"+ | "blurDirPosition";++export type Camera3DTracks = Record<Camera3DTrackKey, Camera3DKeyframe[]>;++export type Camera3DSegment = {+ start: number;+ end: number;+ enabled: boolean;+ properties: Camera3DProperties;+ blur: Camera3DBlur;+ tracks: Camera3DTracks;+ transitionIn: number;+ transitionOut: number;+};++/**+ * Segments cut straight into their pose: shots open already framed, and the+ * renderer defaults to the same 0 (crates/rendering/src/camera3d.rs).+ */+export const DEFAULT_CAMERA3D_TRANSITION = 0;++/**+ * Handles the renderer falls back to when a keyframe carries none: cubic+ * ease-in-out. Mirrors `DEFAULT_OUT_EASING`/`DEFAULT_IN_EASING` in+ * crates/rendering/src/camera3d.rs.+ */+export const DEFAULT_OUT_EASING: [number, number] = [0.65, 0];+export const DEFAULT_IN_EASING: [number, number] = [0.35, 1];++export const CAMERA3D_PROPERTY_KEYS = [+ "tiltX",+ "tiltY",+ "roll",+ "rotateX",+ "rotateY",+ "fov",+ "zoom",+ "panX",+ "panY",+] as const satisfies readonly Camera3DPropertyKey[];++export const CAMERA3D_BLUR_SCALAR_KEYS = [+ "strength",+ "falloff",+ "focusX",+ "focusY",+ "focusSize",+ "angle",+ "dirPosition",+] as const satisfies readonly Camera3DBlurScalarKey[];++export const CAMERA3D_TRACK_KEYS = [+ "tiltX",+ "tiltY",+ "roll",+ "rotateX",+ "rotateY",+ "fov",+ "zoom",+ "panX",+ "panY",+ "blurStrength",+ "blurFalloff",+ "blurFocusSize",+ "blurFocusX",+ "blurFocusY",+ "blurAngle",+ "blurDirPosition",+] as const satisfies readonly Camera3DTrackKey[];++export type Camera3DLimit = { min: number; max: number; step: number };++export const CAMERA3D_LIMITS = {+ tiltX: { min: -70, max: 70, step: 1 },+ tiltY: { min: -60, max: 60, step: 1 },+ roll: { min: -180, max: 180, step: 1 },+ rotateX: { min: -90, max: 90, step: 1 },+ rotateY: { min: -50, max: 50, step: 1 },+ fov: { min: 10, max: 100, step: 1 },+ zoom: { min: 0.5, max: 10, step: 0.05 },+ panX: { min: -3, max: 3, step: 0.01 },+ panY: { min: -3, max: 3, step: 0.01 },+} satisfies Record<Camera3DPropertyKey, Camera3DLimit>;++export const CAMERA3D_BLUR_LIMITS = {+ strength: { min: 0, max: 60, step: 1 },+ falloff: { min: 0, max: 1, step: 0.01 },+ focusX: { min: 0, max: 1, step: 0.01 },+ focusY: { min: 0, max: 1, step: 0.01 },+ focusSize: { min: 0, max: 1, step: 0.01 },+ angle: { min: 0, max: 360, step: 1 },+ dirPosition: { min: 0, max: 1, step: 0.01 },+} satisfies Record<Camera3DBlurScalarKey, Camera3DLimit>;++export const CAMERA3D_BOKEH_MAX_STRENGTH = 20;++/** Bokeh caps strength, and tilt shift narrows both the band and the angle. */+export const camera3dBlurLimit = (+ key: Camera3DBlurScalarKey,+ blur: Pick<Camera3DBlur, "mode" | "bokeh">,+): Camera3DLimit => {+ switch (key) {+ case "strength":+ return {+ min: 0,+ max: blur.bokeh ? CAMERA3D_BOKEH_MAX_STRENGTH : 60,+ step: 1,+ };+ case "focusSize":+ return {+ min: 0,+ max: blur.mode === "tiltShift" ? 0.6 : 1,+ step: 0.01,+ };+ case "angle":+ return { min: 0, max: blur.mode === "tiltShift" ? 180 : 360, step: 1 };+ default:+ return CAMERA3D_BLUR_LIMITS[key];+ }+};++export const CAMERA3D_TRANSITION_LIMITS = { min: 0, max: 2, step: 0.05 };++const clamp = (value: number, min: number, max: number) =>+ Math.min(Math.max(value, min), max);++export const defaultCamera3DProperties = (): Camera3DProperties => ({+ tiltX: 0,+ tiltY: 0,+ roll: 0,+ rotateX: 0,+ rotateY: 0,+ fov: 45,+ zoom: 2,+ panX: 0,+ panY: 0,+});++export const defaultCamera3DBlur = (): Camera3DBlur => ({+ mode: "none",+ strength: 0,+ falloff: 0,+ focusX: 0.37,+ focusY: 0.5,+ focusSize: 0.5,+ angle: 0,+ dirPosition: 0.5,+ bokeh: false,+});++/**+ * Blur a new segment opens with: a showcase defocus, so the cinematic look is+ * there before anyone opens the Blur section.+ */+export const showcaseCamera3DBlur = (): Camera3DBlur => ({+ mode: "radial",+ strength: 19,+ falloff: 0.62,+ focusX: 0.37,+ focusY: 0.5,+ focusSize: 0.4,+ angle: 0,+ dirPosition: 0.5,+ bokeh: true,+});++export const defaultCamera3DTracks = (): Camera3DTracks => ({+ tiltX: [],+ tiltY: [],+ roll: [],+ rotateX: [],+ rotateY: [],+ fov: [],+ zoom: [],+ panX: [],+ panY: [],+ blurStrength: [],+ blurFalloff: [],+ blurFocusSize: [],+ blurFocusX: [],+ blurFocusY: [],+ blurAngle: [],+ blurDirPosition: [],+});++/** Re-seeded parameters when the blur mode changes. */+export const CAMERA3D_BLUR_MODE_SEEDS: Record<+ Camera3DBlurMode,+ Partial<Record<Camera3DBlurScalarKey, number>>+> = {+ none: {},+ radial: { focusX: 0.37, focusY: 0.5, focusSize: 0.5 },+ directional: { dirPosition: 0.5, angle: 0 },+ tiltShift: { focusSize: 0.1, focusY: 0.5, angle: 45 },+};++// -----------------------------------------------------------------------------+// Presets+// -----------------------------------------------------------------------------++/**+ * The seven values an angle preset writes. Content-plane rotation+ * (rotateX/rotateY) is deliberately excluded: presets reframe the camera and+ * leave whatever fold the user has dialled in alone.+ */+export const CAMERA3D_ANGLE_PRESET_KEYS = [+ "tiltX",+ "tiltY",+ "roll",+ "fov",+ "zoom",+ "panX",+ "panY",+] as const;++export type Camera3DAnglePresetKey =+ (typeof CAMERA3D_ANGLE_PRESET_KEYS)[number];++export type Camera3DAnglePreset = {+ id: string;+ name: string;+ values: Record<Camera3DAnglePresetKey, number>;+ /// Every card produces a moving shot: the shot opens on the named pose+ /// (`values`) and drifts toward these overrides.+ drift: Partial<Record<Camera3DAnglePresetKey, number>>;+ /// The defocus the card writes alongside its move. A card is a complete+ /// look, so clicking one never leaves the previous shot's blur behind.+ blur: Camera3DBlur;+};++/**+ * Detail's defocus: a tight, hard-edged focus spot over the close-up, taken+ * from the reference project's opening shot.+ */+const detailCamera3DBlur = (): Camera3DBlur => ({+ mode: "radial",+ strength: 20,+ falloff: 0.76,+ focusX: 0.11,+ focusY: 0.5,+ focusSize: 0.18,+ angle: 0,+ dirPosition: 0.5,+ bokeh: true,+});++/**+ * The overhead shot's defocus: a wide, soft band low and left, taken from the+ * reference project's middle shot.+ */+const overheadCamera3DBlur = (): Camera3DBlur => ({+ mode: "radial",+ strength: 18,+ falloff: 0.72,+ focusX: 0.03,+ focusY: 0.36,+ focusSize: 0.55,+ angle: 0,+ dirPosition: 0.5,+ bokeh: true,+});++/// Cards carry the showcase defocus unless they were authored with their own.+const anglePreset = (+ preset: Omit<Camera3DAnglePreset, "blur"> & { blur?: Camera3DBlur },+): Camera3DAnglePreset => ({+ ...preset,+ blur: preset.blur ?? showcaseCamera3DBlur(),+});++export const ANGLE_PRESETS: Camera3DAnglePreset[] = [+ anglePreset({+ id: "spotlight",+ name: "Spotlight",+ values: {+ tiltX: 0,+ tiltY: 0,+ roll: 0,+ fov: 45,+ zoom: 1.35,+ panX: 0.39,+ panY: -0.4,+ },+ // Slow push in with a slight rise.+ drift: { zoom: 1.22, panY: -0.34 },+ }),+ anglePreset({+ id: "perspective",+ name: "Perspective",+ values: {+ tiltX: -28,+ tiltY: 26,+ roll: 5,+ fov: 45,+ zoom: 1.59,+ panX: 0.37,+ panY: -0.15,+ },+ // Orbit sweep.+ drift: { tiltY: 18, zoom: 1.53 },+ }),+ anglePreset({+ id: "center",+ name: "Center",+ values: {+ tiltX: 0,+ tiltY: 0,+ roll: 0,+ fov: 45,+ zoom: 2,+ panX: 0,+ panY: 0,+ },+ // Slow pull back.+ drift: { zoom: 2.25 },+ }),+ anglePreset({+ id: "low-angle",+ name: "Low angle",+ values: {+ tiltX: -50,+ tiltY: 1,+ roll: 0,+ fov: 45,+ zoom: 1.5,+ panX: 0,+ panY: 0,+ },+ // Low-angle rise.+ drift: { tiltX: -44, panY: -0.12 },+ }),+ anglePreset({+ id: "close-up",+ name: "Close up",+ values: {+ tiltX: 26,+ tiltY: -22,+ roll: 1,+ fov: 45,+ zoom: 0.8,+ panX: -0.3,+ panY: -0.4,+ },+ // Truck across the close-up.+ drift: { tiltY: -27, panX: -0.36 },+ // The close-up is the one card that focuses tight and far left.+ blur: detailCamera3DBlur(),+ }),+];++export const anglePresetPose = (+ preset: Camera3DAnglePreset,+): Camera3DProperties => ({+ ...defaultCamera3DProperties(),+ ...preset.values,+});++/// An angle preset as a motion template: opens on the named pose and drifts.+export const anglePresetMotion = (+ preset: Camera3DAnglePreset,+): Camera3DMotionTemplate => ({+ id: `angle-${preset.id}`,+ name: preset.name,+ from: anglePresetPose(preset),+ to: { ...anglePresetPose(preset), ...preset.drift },+ blur: { ...preset.blur },+});++// A slider cannot express anything finer than one step, so half a step is the+// tightest a pose can be "the same as" a preset and still be reachable.+const presetMatchEpsilon = (key: Camera3DAnglePresetKey) =>+ Math.max(CAMERA3D_LIMITS[key].step / 2, 1e-4);++export const matchAnglePreset = (+ pose: Pick<Camera3DProperties, Camera3DAnglePresetKey>,+): string | null =>+ ANGLE_PRESETS.find((preset) =>+ CAMERA3D_ANGLE_PRESET_KEYS.every(+ (key) =>+ Math.abs(pose[key] - preset.values[key]) <= presetMatchEpsilon(key),+ ),+ )?.id ?? null;++export type Camera3DMotionTemplate = {+ id: string;+ name: string;+ from: Camera3DProperties;+ to: Camera3DProperties;+ /// The defocus the template writes. Clicking a card is a complete look, so+ /// the blur is part of the template rather than whatever was there before.+ blur: Camera3DBlur;+};++const pose = (overrides: Partial<Camera3DProperties>): Camera3DProperties => ({+ ...defaultCamera3DProperties(),+ ...overrides,+});++/// Templates carry the showcase defocus unless authored with their own.+const motionTemplate = (+ template: Omit<Camera3DMotionTemplate, "blur"> & { blur?: Camera3DBlur },+): Camera3DMotionTemplate => ({+ ...template,+ blur: template.blur ?? showcaseCamera3DBlur(),+});++export const MOTION_TEMPLATES: Camera3DMotionTemplate[] = [+ motionTemplate({+ id: "glide-across",+ name: "Glide across",+ from: pose({+ tiltX: -46.65,+ tiltY: 42.49,+ rotateY: -20,+ rotateX: -1,+ zoom: 1.785,+ fov: 24,+ panX: 0.673,+ panY: -0.133,+ }),+ to: pose({+ tiltX: -46.65,+ tiltY: 42.49,+ rotateY: -20,+ rotateX: -1,+ zoom: 1.785,+ fov: 24,+ panX: 0.054,+ panY: -0.31,+ }),+ }),+ motionTemplate({+ id: "drift-down",+ name: "Drift down",+ from: pose({ zoom: 0.8, fov: 45, panX: 0.536, panY: -0.452 }),+ to: pose({ zoom: 0.8, fov: 45, panX: 0.544, panY: 0.5 }),+ }),+ motionTemplate({+ id: "rising-sweep",+ name: "Rising sweep",+ from: pose({+ tiltX: -57.83,+ tiltY: -8.7,+ rotateY: -16,+ zoom: 1.51,+ fov: 29,+ panX: -0.634,+ panY: -0.082,+ }),+ to: pose({+ tiltX: -46.65,+ tiltY: -7.94,+ rotateY: -16,+ zoom: 1.51,+ fov: 25,+ panX: -0.613,+ panY: -0.268,+ }),+ }),+ motionTemplate({+ id: "pull-back",+ name: "Pull back",+ from: pose({ rotateX: -14, zoom: 0.715, fov: 45 }),+ to: pose({ rotateX: -14, zoom: 2.1, fov: 45 }),+ }),+ motionTemplate({+ id: "top-down",+ name: "Top down",+ from: pose({+ tiltX: 24.8,+ tiltY: 17.04,+ rotateY: 18,+ rotateX: -40,+ zoom: 0.5,+ fov: 60,+ panX: -0.065,+ panY: -0.195,+ }),+ to: pose({+ tiltX: 34.19,+ tiltY: 15.28,+ rotateY: 9,+ rotateX: -40,+ zoom: 0.5,+ fov: 60,+ panX: -0.217,+ panY: -0.476,+ }),+ // Looking down at the plane wants a wider, softer band than the rest.+ blur: overheadCamera3DBlur(),+ }),+ motionTemplate({+ id: "tilt-away",+ name: "Tilt away",+ from: pose({ rotateX: -5, zoom: 0.5, fov: 45 }),+ to: pose({ rotateX: -21, zoom: 0.6, fov: 45 }),+ }),+ motionTemplate({+ id: "unfold",+ name: "Unfold",+ from: pose({ rotateX: -42.96, zoom: 2.05, fov: 31 }),+ to: pose({ rotateX: -12.01, zoom: 2, fov: 31, panY: -0.179 }),+ }),+ motionTemplate({+ id: "slide-by",+ name: "Slide by",+ from: pose({+ tiltX: -30.29,+ tiltY: 60,+ rotateY: -24,+ rotateX: -39,+ zoom: 1.99,+ fov: 13,+ panX: 0.238,+ panY: 0.135,+ }),+ to: pose({+ tiltX: -30.29,+ tiltY: 60,+ rotateY: -24,+ rotateX: -39,+ zoom: 1.99,+ fov: 13,+ panX: -0.204,+ panY: 0.039,+ }),+ }),+];++export type Camera3DFlipAxis = "horizontal" | "vertical";++/**+ * Mirrors the whole composition across the given axis while the content stays+ * readable: negating the yaw/roll/pan family is exactly conjugating the+ * camera by the mirror, so a "Close up" on the right becomes the identical+ * shot on the left. Applies to both poses, every motion track, and the blur+ * focus, so a moving shot keeps its drift.+ */+export const flipCamera3DSegment = (+ segment: Camera3DSegment,+ axis: Camera3DFlipAxis,+) => {+ // Roll negates on both axes: a mirror reverses in-plane rotation.+ const negated: Camera3DPropertyKey[] =+ axis === "horizontal"+ ? ["tiltY", "rotateY", "roll", "panX"]+ : ["tiltX", "rotateX", "roll", "panY"];+ for (const key of negated) {+ segment.properties[key] = -segment.properties[key];+ for (const keyframe of segment.tracks[key])+ keyframe.value = -keyframe.value;+ }++ const focusKey = axis === "horizontal" ? "focusX" : "focusY";+ const focusTrack = axis === "horizontal" ? "blurFocusX" : "blurFocusY";+ segment.blur[focusKey] = 1 - segment.blur[focusKey];+ for (const keyframe of segment.tracks[focusTrack])+ keyframe.value = 1 - keyframe.value;++ // Directional/band angles mirror too: (cos, sin) reflected across the+ // axis is 180 - a horizontally, -a vertically.+ const mirrorAngle = (value: number) => {+ const flipped = axis === "horizontal" ? 180 - value : -value;+ return ((flipped % 360) + 360) % 360;+ };+ segment.blur.angle = mirrorAngle(segment.blur.angle);+ for (const keyframe of segment.tracks.blurAngle)+ keyframe.value = mirrorAngle(keyframe.value);+};++/**+ * Replaces the segment's motion with the template's two poses. Linear is the+ * explicit pair the template writes, so the move reads exactly as authored+ * instead of picking up the default cubic ease.+ *+ * The template's defocus goes on with it: a card is one complete look, so what+ * the preview promises is what the segment ends up holding.+ */+export const applyMotionTemplate = (+ segment: Camera3DSegment,+ template: Camera3DMotionTemplate,+) => {+ setMotion(segment, template.from, template.to, LINEAR_MOTION_EASING);+ segment.blur = { ...template.blur };+ // A template owns the whole move, so the segment cuts in and out of it.+ // Segments authored before the 0 default can still carry a ramp.+ segment.transitionIn = 0;+ segment.transitionOut = 0;+};++// -----------------------------------------------------------------------------+// Scenes+// -----------------------------------------------------------------------------++/**+ * One shot of a scene: a move, a look, and the share of the scene's time range+ * it holds. Weights are relative, so a scene reads the same whatever length it+ * is dropped onto.+ */+export type Camera3DSceneShot = {+ /** Fraction of the scene's time range. */+ weight: number;+ /** The card this shot was built from, when it came from one. */+ name?: string;+ from: Camera3DProperties;+ to: Camera3DProperties;+ blur: Camera3DBlur;+};++/** A chained multi-shot sequence: one click, several cuts. */+export type Camera3DScene = {+ id: string;+ name: string;+ shots: Camera3DSceneShot[];+};++const anglePresetById = (id: string) =>+ ANGLE_PRESETS.find((preset) => preset.id === id) ?? ANGLE_PRESETS[0];++const motionTemplateById = (id: string) =>+ MOTION_TEMPLATES.find((template) => template.id === id) ??+ MOTION_TEMPLATES[0];++/// A card's complete look as one shot of a scene.+const templateShot = (+ template: Camera3DMotionTemplate,+ weight: number,+): Camera3DSceneShot => ({+ weight,+ name: template.name,+ from: { ...template.from },+ to: { ...template.to },+ blur: { ...template.blur },+});++export const CAMERA3D_SCENES: Camera3DScene[] = [+ {+ // Transcribed verbatim from the hand-built reference project: a tight+ // close-up truck, a fold-down overhead sweep, then a long push in.+ id: "showcase",+ name: "Showcase",+ shots: [+ {+ weight: 0.27,+ from: pose({+ tiltX: 26,+ tiltY: -22,+ roll: 1,+ fov: 45,+ zoom: 0.8,+ panX: -0.3,+ panY: -0.4,+ }),+ to: pose({+ tiltX: 26,+ tiltY: -27,+ roll: 1,+ fov: 45,+ zoom: 0.8,+ panX: -0.36,+ panY: -0.4,+ }),+ blur: detailCamera3DBlur(),+ },+ {+ weight: 0.25,+ from: pose({+ tiltX: 24.8,+ tiltY: 17.04,+ rotateX: -40,+ rotateY: 18,+ fov: 60,+ zoom: 0.5,+ panX: -0.065,+ panY: -0.195,+ }),+ to: pose({+ tiltX: 34.19,+ tiltY: 15.28,+ rotateX: -40,+ rotateY: 9,+ fov: 60,+ zoom: 0.5,+ panX: -0.217,+ panY: -0.476,+ }),+ blur: overheadCamera3DBlur(),+ },+ {+ weight: 0.48,+ from: pose({ rotateX: -14, fov: 45, zoom: 0.715 }),+ to: pose({ rotateX: -14, fov: 45, zoom: 1.6 }),+ blur: {+ mode: "radial",+ strength: 19,+ falloff: 0.67,+ focusX: 0.37,+ focusY: 0.52,+ focusSize: 0.4,+ angle: 0,+ dirPosition: 0.5,+ bokeh: true,+ },+ },+ ],+ },+ {+ // Reveal, orbit, settle: the shape a product walkthrough wants.+ id: "product-tour",+ name: "Product tour",+ shots: [+ templateShot(motionTemplateById("unfold"), 0.3),+ templateShot(anglePresetMotion(anglePresetById("perspective")), 0.3),+ templateShot(anglePresetMotion(anglePresetById("center")), 0.4),+ ],+ },+ {+ // Push in, hold on the detail, then release.+ id: "punch-in",+ name: "Punch in",+ shots: [+ templateShot(anglePresetMotion(anglePresetById("spotlight")), 0.3),+ templateShot(anglePresetMotion(anglePresetById("close-up")), 0.3),+ templateShot(motionTemplateById("pull-back"), 0.4),+ ],+ },+];++/**+ * The scene's leading `count` shots with their weights renormalized, so a+ * shorter sequence still fills the whole range it is laid onto. Asking for+ * more shots than the scene holds simply returns the scene.+ */+export const sceneWithShotCount = (+ scene: Camera3DScene,+ count: number,+): Camera3DScene => {+ const kept = Math.min(Math.max(Math.floor(count), 1), scene.shots.length);+ if (kept >= scene.shots.length) return scene;++ const shots = scene.shots.slice(0, kept);+ const totalWeight = shots.reduce(+ (sum, shot) => sum + Math.max(shot.weight, 0),+ 0,+ );+ return {+ ...scene,+ shots: shots.map((shot) => ({+ ...shot,+ weight:+ totalWeight > 0+ ? Math.max(shot.weight, 0) / totalWeight+ : 1 / shots.length,+ })),+ };+};++/**+ * No generated shot is shorter than this: below a second a cut reads as a+ * glitch rather than an edit.+ */+export const CAMERA3D_MIN_SHOT_DURATION = 1;++/**+ * How far a shot boundary will travel to land on a clip cut, as a fraction of+ * the scene's range. Cutting the camera exactly where the footage cuts is what+ * makes a generated sequence look authored.+ */+export const CAMERA3D_SCENE_SNAP_FRACTION = 0.15;++const nearestValue = (values: number[], target: number) => {+ let nearest: number | null = null;+ let distance = Number.POSITIVE_INFINITY;+ for (const value of values) {+ const candidate = Math.abs(value - target);+ if (candidate >= distance) continue;+ distance = candidate;+ nearest = value;+ }+ return nearest;+};++/**+ * Lays a scene across [start, end] as a chain of segments.+ *+ * Boundaries come from the shot weights, then each interior one looks for a+ * clip cut to sit on. A snap is dropped rather than forced when it would push a+ * shot under the minimum, and a range too short for the whole scene simply gets+ * its leading shots.+ */+export const applySceneToRange = (+ scene: Camera3DScene,+ start: number,+ end: number,+ clipCuts: number[] = [],+): Camera3DSegment[] => {+ const length = end - start;+ if (!(length > 0) || scene.shots.length === 0) return [];++ const shots = scene.shots.slice(+ 0,+ Math.max(+ 1,+ Math.min(+ scene.shots.length,+ Math.floor(length / CAMERA3D_MIN_SHOT_DURATION),+ ),+ ),+ );+ const totalWeight = shots.reduce(+ (sum, shot) => sum + Math.max(shot.weight, 0),+ 0,+ );+ const share = (shot: Camera3DSceneShot) =>+ totalWeight > 0 ? Math.max(shot.weight, 0) / totalWeight : 1 / shots.length;++ const cuts = clipCuts.filter((cut) => cut > start && cut < end);+ const snapWindow = length * CAMERA3D_SCENE_SNAP_FRACTION;++ const boundaries = [start];+ let cumulative = 0;+ for (let index = 0; index < shots.length - 1; index++) {+ cumulative += share(shots[index]);+ // Every shot still to come needs its own minimum, so this boundary lives+ // in whatever is left once they are reserved.+ const min = boundaries[index] + CAMERA3D_MIN_SHOT_DURATION;+ const max = end - (shots.length - 1 - index) * CAMERA3D_MIN_SHOT_DURATION;+ const weighted = clamp(start + length * cumulative, min, max);+ const cut = nearestValue(cuts, weighted);+ boundaries.push(+ cut !== null &&+ Math.abs(cut - weighted) <= snapWindow &&+ cut >= min &&+ cut <= max+ ? cut+ : weighted,+ );+ }+ boundaries.push(end);++ return shots.map((shot, index) => {+ const segment: Camera3DSegment = {+ start: boundaries[index],+ end: boundaries[index + 1],+ enabled: true,+ properties: defaultCamera3DProperties(),+ blur: { ...shot.blur },+ tracks: defaultCamera3DTracks(),+ transitionIn: 0,+ transitionOut: 0,+ };+ setMotion(segment, shot.from, shot.to, LINEAR_MOTION_EASING);+ return segment;+ });+};++/** Pose the "Reset camera" action writes: a canonical long lens. */+export const CAMERA3D_RESET_POSE: Camera3DProperties = {+ tiltX: 0,+ tiltY: 0,+ roll: 0,+ rotateX: 0,+ rotateY: 0,+ fov: 24,+ zoom: 4.5,+ panX: 0,+ panY: 0,+};++// -----------------------------------------------------------------------------+// Motion easings+// -----------------------------------------------------------------------------++/**+ * One named curve for the whole move: the pair of split bezier handles the two+ * keyframes carry. There is no per-keyframe easing to pick any more, because a+ * segment only ever holds one span.+ */+export type Camera3DMotionEasing = {+ id: string;+ label: string;+ /** Bezier P1, written onto the start keyframe. */+ out: [number, number];+ /** Bezier P2, written onto the end keyframe. */+ in: [number, number];+};++export const MOTION_EASINGS: Camera3DMotionEasing[] = [+ // Linear is the default: it is what every template is authored in.+ { id: "linear", label: "Linear", out: [0, 0], in: [1, 1] },+ { id: "smooth", label: "Smooth", out: [0.65, 0], in: [0.35, 1] },+ { id: "easeIn", label: "Ease in", out: [0.32, 0], in: [1, 1] },+ { id: "easeOut", label: "Ease out", out: [0, 0], in: [0.68, 1] },+];++export const LINEAR_MOTION_EASING = MOTION_EASINGS[0];++// -----------------------------------------------------------------------------+// Normalization+// -----------------------------------------------------------------------------++export const normalizeCamera3DProperties = (+ properties?: RawCamera3DProperties | null,+): Camera3DProperties => {+ const defaults = defaultCamera3DProperties();+ if (!properties) return defaults;+ return {+ tiltX: properties.tiltX ?? defaults.tiltX,+ tiltY: properties.tiltY ?? defaults.tiltY,+ roll: properties.roll ?? defaults.roll,+ rotateX: properties.rotateX ?? defaults.rotateX,+ rotateY: properties.rotateY ?? defaults.rotateY,+ fov: properties.fov ?? defaults.fov,+ zoom: properties.zoom ?? defaults.zoom,+ panX: properties.panX ?? defaults.panX,+ panY: properties.panY ?? defaults.panY,+ };+};++export const normalizeCamera3DBlur = (+ blur?: RawCamera3DBlur | null,+): Camera3DBlur => {+ const defaults = defaultCamera3DBlur();+ if (!blur) return defaults;+ return {+ mode: blur.mode ?? defaults.mode,+ strength: blur.strength ?? defaults.strength,+ falloff: blur.falloff ?? defaults.falloff,+ focusX: blur.focusX ?? defaults.focusX,+ focusY: blur.focusY ?? defaults.focusY,+ focusSize: blur.focusSize ?? defaults.focusSize,+ angle: blur.angle ?? defaults.angle,+ dirPosition: blur.dirPosition ?? defaults.dirPosition,+ bokeh: blur.bokeh ?? defaults.bokeh,+ };+};++const normalizeKeyframes = (+ keyframes?: RawCamera3DKeyframe[] | null,+): Camera3DKeyframe[] =>+ (keyframes ?? [])+ .map((keyframe) => ({+ time: keyframe.time,+ value: keyframe.value,+ outEasing: keyframe.outEasing ?? null,+ inEasing: keyframe.inEasing ?? null,+ }))+ .sort((a, b) => a.time - b.time);++export const normalizeCamera3DTracks = (+ tracks?: RawCamera3DTracks | null,+): Camera3DTracks => {+ const normalized = defaultCamera3DTracks();+ if (!tracks) return normalized;+ for (const key of CAMERA3D_TRACK_KEYS) {+ normalized[key] = normalizeKeyframes(tracks[key]);+ }+ return normalized;+};++/**+ * Motion always spans the whole segment in the start/end model, so after a+ * resize (or when loading a project resized before this invariant existed)+ * every track's keyframe times are rescaled onto the new duration. Repeated+ * application is a fixpoint, so calling it during a live drag is safe.+ */+export const fitCamera3DMotionToSegment = (segment: Camera3DSegment) => {+ const length = Math.max(segment.end - segment.start, 0);+ let span = 0;+ for (const key of CAMERA3D_TRACK_KEYS)+ for (const keyframe of segment.tracks[key])+ span = Math.max(span, keyframe.time);+ if (span < 1e-6 || Math.abs(span - length) < 1e-6) return;+ const scale = length / span;+ for (const key of CAMERA3D_TRACK_KEYS)+ for (const keyframe of segment.tracks[key]) keyframe.time *= scale;+};++export const normalizeCamera3DSegments = (+ segments?: RawCamera3DSegment[] | null,+): Camera3DSegment[] =>+ (segments ?? [])+ .map((segment) => {+ const normalized = {+ start: segment.start,+ end: segment.end,+ enabled: segment.enabled ?? true,+ properties: normalizeCamera3DProperties(segment.properties),+ blur: normalizeCamera3DBlur(segment.blur),+ tracks: normalizeCamera3DTracks(segment.tracks),+ transitionIn: segment.transitionIn ?? DEFAULT_CAMERA3D_TRANSITION,+ transitionOut: segment.transitionOut ?? DEFAULT_CAMERA3D_TRANSITION,+ };+ fitCamera3DMotionToSegment(normalized);+ return normalized;+ })+ .sort((a, b) => a.start - b.start || a.end - b.end);++export const defaultCamera3DSegment = (+ start: number,+ end: number,+): Camera3DSegment => {+ const angled =+ ANGLE_PRESETS.find((preset) => preset.id === "perspective") ??+ ANGLE_PRESETS[0];+ return {+ start,+ end,+ enabled: true,+ // New segments open on a real pose so the 3D look is visible immediately.+ properties: anglePresetPose(angled),+ blur: showcaseCamera3DBlur(),+ tracks: defaultCamera3DTracks(),+ transitionIn: DEFAULT_CAMERA3D_TRANSITION,+ transitionOut: DEFAULT_CAMERA3D_TRANSITION,+ };+};++// -----------------------------------------------------------------------------+// Sampling (mirrors crates/rendering/src/camera3d.rs)+// -----------------------------------------------------------------------------++const bezierComponent = (p1: number, p2: number, t: number) => {+ const inv = 1 - t;+ return 3 * inv * inv * t * p1 + 3 * inv * t * t * p2 + t * t * t;+};++const bezierDerivative = (p1: number, p2: number, t: number) => {+ const a = 1 - 3 * p2 + 3 * p1;+ const b = 3 * p2 - 6 * p1;+ const c = 3 * p1;+ return (3 * a * t + 2 * b) * t + c;+};++/**+ * Cubic-bezier timing with control points P1/P2 (P0 = (0,0), P3 = (1,1)):+ * 8 Newton iterations, then bisection.+ */+export const bezierEase = (+ p1: readonly [number, number],+ p2: readonly [number, number],+ t: number,+) => {+ if (t <= 0) return 0;+ if (t >= 1) return 1;++ const [x1, y1] = p1;+ const [x2, y2] = p2;+ // Linear fast path ([0,0]/[1,1] handles).+ if (x1 === y1 && x2 === y2 && x1 === 0 && x2 === 1) return t;++ let guess = t;+ for (let i = 0; i < 8; i++) {+ const error = bezierComponent(x1, x2, guess) - t;+ if (Math.abs(error) < 1e-5) return bezierComponent(y1, y2, guess);+ const slope = bezierDerivative(x1, x2, guess);+ if (Math.abs(slope) < 1e-6) break;+ guess -= error / slope;+ }++ let lo = 0;+ let hi = 1;+ guess = t;+ for (let i = 0; i < 30; i++) {+ const error = bezierComponent(x1, x2, guess) - t;+ if (Math.abs(error) < 1e-5) break;+ if (error > 0) hi = guess;+ else lo = guess;+ guess = (lo + hi) / 2;+ }+ return bezierComponent(y1, y2, guess);+};++const sortedByTime = (keys: Camera3DKeyframe[]) => {+ for (let i = 1; i < keys.length; i++) {+ if (keys[i].time < keys[i - 1].time)+ return [...keys].sort((a, b) => a.time - b.time);+ }+ return keys;+};++/**+ * Samples one per-property track: base value when empty, hold outside the keyed+ * range, split-handle bezier lerp between neighbours.+ */+export const sampleTrack = (+ base: number,+ keys: Camera3DKeyframe[] | null | undefined,+ time: number,+) => {+ const list = keys ?? [];+ if (list.length === 0) return base;++ const sorted = sortedByTime(list);++ if (time <= sorted[0].time) return sorted[0].value;++ for (let i = 1; i < sorted.length; i++) {+ const prev = sorted[i - 1];+ const next = sorted[i];+ if (time > next.time) continue;+ const span = Math.max(next.time - prev.time, 1e-6);+ const progress = clamp((time - prev.time) / span, 0, 1);+ const eased = bezierEase(+ prev.outEasing ?? DEFAULT_OUT_EASING,+ next.inEasing ?? DEFAULT_IN_EASING,+ progress,+ );+ return prev.value + (next.value - prev.value) * eased;+ }++ return sorted[sorted.length - 1].value;+};++export const evaluatePose = (+ segment: Camera3DSegment,+ relativeTime: number,+): Camera3DProperties => {+ const base = segment.properties;+ const tracks = segment.tracks;+ return {+ tiltX: sampleTrack(base.tiltX, tracks.tiltX, relativeTime),+ tiltY: sampleTrack(base.tiltY, tracks.tiltY, relativeTime),+ roll: sampleTrack(base.roll, tracks.roll, relativeTime),+ rotateX: sampleTrack(base.rotateX, tracks.rotateX, relativeTime),+ rotateY: sampleTrack(base.rotateY, tracks.rotateY, relativeTime),+ fov: sampleTrack(base.fov, tracks.fov, relativeTime),+ zoom: sampleTrack(base.zoom, tracks.zoom, relativeTime),+ panX: sampleTrack(base.panX, tracks.panX, relativeTime),+ panY: sampleTrack(base.panY, tracks.panY, relativeTime),+ };+};++export const evaluateBlur = (+ segment: Camera3DSegment,+ relativeTime: number,+): Camera3DBlur => {+ const base = segment.blur;+ const tracks = segment.tracks;+ return {+ mode: base.mode,+ bokeh: base.bokeh,+ strength: sampleTrack(base.strength, tracks.blurStrength, relativeTime),+ falloff: sampleTrack(base.falloff, tracks.blurFalloff, relativeTime),+ focusX: sampleTrack(base.focusX, tracks.blurFocusX, relativeTime),+ focusY: sampleTrack(base.focusY, tracks.blurFocusY, relativeTime),+ focusSize: sampleTrack(base.focusSize, tracks.blurFocusSize, relativeTime),+ angle: sampleTrack(base.angle, tracks.blurAngle, relativeTime),+ dirPosition: sampleTrack(+ base.dirPosition,+ tracks.blurDirPosition,+ relativeTime,+ ),+ };+};++// -----------------------------------------------------------------------------+// Start pose / end pose+// -----------------------------------------------------------------------------++/**+ * Below this a move is a hold: nothing a slider can express is finer, so two+ * poses this close are stored as a still shot with no keyframes at all.+ */+export const MOTION_STILL_EPSILON = 1e-4;++/** The pose the segment opens on, whatever form its tracks are stored in. */+export const getStartPose = (segment: Camera3DSegment): Camera3DProperties =>+ evaluatePose(segment, 0);++/** The pose the segment lands on, whatever form its tracks are stored in. */+export const getEndPose = (segment: Camera3DSegment): Camera3DProperties =>+ evaluatePose(segment, Math.max(segment.end - segment.start, 0));++export const camera3DPosesEqual = (+ a: Camera3DProperties,+ b: Camera3DProperties,+) =>+ CAMERA3D_PROPERTY_KEYS.every(+ (key) => Math.abs(a[key] - b[key]) < MOTION_STILL_EPSILON,+ );++/** Whether any camera property is animated. Blur is never keyed. */+export const hasCamera3DMotion = (segment: Camera3DSegment) =>+ CAMERA3D_PROPERTY_KEYS.some((key) => segment.tracks[key].length > 0);++/**+ * The one way the editor authors camera animation: a segment is a start pose+ * and an end pose, and this writes that pair into the per-property tracks the+ * renderer reads. A property that does not move keeps no keyframes at all, so+ * a still shot stores as a plain base pose.+ *+ * Blur is never touched here: it is segment-level and static.+ *+ * An older segment carrying a richer track flattens to this form on its first+ * edit, which is intended: it flattens onto the poses it already opened and+ * closed on.+ */+export const setMotion = (+ segment: Camera3DSegment,+ start: Camera3DProperties,+ end: Camera3DProperties,+ easing: Camera3DMotionEasing = LINEAR_MOTION_EASING,+) => {+ const length = Math.max(segment.end - segment.start, 0);+ for (const key of CAMERA3D_PROPERTY_KEYS) {+ const from = start[key];+ const to = end[key];+ // The base pose always carries the start: it is what shows when the track+ // is empty, and what the renderer holds outside the keyed range.+ segment.properties[key] = from;+ if (Math.abs(from - to) < MOTION_STILL_EPSILON) {+ segment.tracks[key] = [];+ continue;+ }+ segment.tracks[key] = [+ { time: 0, value: from, outEasing: [...easing.out], inEasing: null },+ { time: length, value: to, outEasing: null, inEasing: [...easing.in] },+ ];+ }+};++const EASING_MATCH_EPSILON = 1e-3;++const handlesMatch = (+ a: readonly [number, number],+ b: readonly [number, number],+) =>+ Math.abs(a[0] - b[0]) <= EASING_MATCH_EPSILON &&+ Math.abs(a[1] - b[1]) <= EASING_MATCH_EPSILON;++/**+ * The curve the segment's move runs on, read back off its first animated camera+ * track. Anything unrecognised (a hand-keyed segment from before this model)+ * reads as Linear, and picking a style rewrites both handles anyway.+ */+export const getMotionEasing = (+ segment: Camera3DSegment,+): Camera3DMotionEasing => {+ for (const key of CAMERA3D_PROPERTY_KEYS) {+ const track = segment.tracks[key];+ if (track.length < 2) continue;+ const out = track[0].outEasing ?? DEFAULT_OUT_EASING;+ const into = track[track.length - 1].inEasing ?? DEFAULT_IN_EASING;+ return (+ MOTION_EASINGS.find(+ (easing) =>+ handlesMatch(easing.out, out) && handlesMatch(easing.in, into),+ ) ?? LINEAR_MOTION_EASING+ );+ }+ return LINEAR_MOTION_EASING;+};++/** Retimes every track when the segment's length changes. */+export const scaleKeyframeTimes = (tracks: Camera3DTracks, scale: number) => {+ for (const key of CAMERA3D_TRACK_KEYS) {+ for (const keyframe of tracks[key]) keyframe.time *= scale;+ }+};++// -----------------------------------------------------------------------------+// CSS 3D preview+// -----------------------------------------------------------------------------++/**+ * Scale constant: the Flat preset (zoom 2, fov 45) lands at roughly 60% of the+ * preview card, which leaves room for the poses that push in closer.+ */+export const CAMERA3D_PREVIEW_SCALE_K = 0.5;++/**+ * A CSS-3D preview of a pose. The perspective distance reproduces the field+ * of view at this card height, the rotations run camera-then-plane in the+ * renderer's order, and apparent size follows 1 / (zoom * tan(fov/2)) exactly+ * like the real projection. Pan uses half the projected offset so the extreme+ * poses stay legible inside a thumbnail.+ */+export const cssPreviewTransform = (+ props: Camera3DProperties,+ containerHeightPx: number,+) => {+ const tan = Math.tan((clamp(props.fov, 1, 179) * Math.PI) / 360);+ const zoom = Math.max(props.zoom, 0.05);+ const scale = CAMERA3D_PREVIEW_SCALE_K / (zoom * tan);+ const offset = (containerHeightPx / 2) * scale;+ const tx = props.panX * offset;+ const ty = -props.panY * offset;++ return {+ perspective: containerHeightPx / (2 * tan),+ transform: [+ `translate(${tx.toFixed(2)}px, ${ty.toFixed(2)}px)`,+ `rotateY(${props.tiltY}deg)`,+ `rotateX(${-props.tiltX}deg)`,+ `rotateZ(${props.roll}deg)`,+ `rotateY(${props.rotateY}deg)`,+ `rotateX(${-props.rotateX}deg)`,+ `scale(${scale.toFixed(4)})`,+ ].join(" "),+ };+};diff --git a/apps/desktop/src/styles/theme.css b/apps/desktop/src/styles/theme.cssindex 11f488cd1..330b4fd12 100644--- a/apps/desktop/src/styles/theme.css+++ b/apps/desktop/src/styles/theme.css@@ -30,6 +30,7 @@--track-mask: #d2444b; /* red */--track-scene: #975cfa; /* purple */--track-audio: var(--jade-9); /* green */+ --track-3d: #7c6ff0; /* violet */}:root {diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 923a834e7..7ad31e095 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -652,6 +652,114 @@ export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition;* Overrides `position` when set.*/manualPosition: XY<number> | null; size: number; zoomSize: number | null; rounding: number; shadow: number; advancedShadow: ShadowConfiguration | null; shape: CameraShape; roundingType: CornerStyle; scaleDuringZoom?: number; backgroundBlur?: BackgroundBlurConfig }+/**+ * Screen-space focus blur applied over the composed frame while a 3d segment+ * is active (a UV-mask variable blur, not a depth-of-field). `strength` is a+ * blur radius in pixels at 1080p output height; the renderer scales it with+ * output size so preview and export match.+ */+export type Camera3DBlur = { mode?: Camera3DBlurMode; strength?: number;+/**+ * Widens and flattens the sharp-to-blurred transition (0..1).+ */+falloff?: number;+/**+ * Focus center in screen UV (radial mode).+ */+focusX?: number; focusY?: number;+/**+ * Sharp region size: radius (radial) or band width (tilt-shift).+ */+focusSize?: number;+/**+ * Degrees; blur direction (directional) or band angle (tilt-shift).+ */+angle?: number;+/**+ * Where the directional blur begins along its axis (0..1).+ */+dirPosition?: number;+/**+ * Swaps the gaussian kernel for a ring-disc bokeh kernel with highlight+ * gain. Strength is capped at 20 while enabled.+ */+bokeh?: boolean }+export type Camera3DBlurMode = "none" | "radial" | "directional" | "tiltShift"+/**+ * One scalar keyframe on a per-property track. Interpolation between two+ * keyframes is a linear value lerp with time remapped by a cubic bezier whose+ * P1 comes from the left keyframe's `out_easing` and P2 from the right one's+ * `in_easing` (a split-handle model). Absent handles default to+ * cubic ease-in-out: P1 [0.65, 0], P2 [0.35, 1].+ */+export type Camera3DKeyframe = {+/**+ * Seconds relative to the segment start.+ */+time: number; value: number;+/**+ * Bezier P1 for the track segment leaving this keyframe.+ */+outEasing?: [number, number] | null;+/**+ * Bezier P2 for the track segment entering this keyframe.+ */+inEasing?: [number, number] | null }+/**+ * A 3D camera pose for the composed content plane. Angles are degrees.+ *+ * Geometry: the content plane's longest side spans 2 world units, centered at+ * the origin facing +Z. `tilt_x`/`tilt_y`/`roll` orbit the CAMERA (Euler YXZ,+ * roll innermost); `rotate_x`/`rotate_y` rotate the CONTENT plane itself.+ * `zoom` is the camera DISTANCE in world units (larger = further = smaller on+ * screen); `fov` is the vertical field of view with no size compensation, so+ * apparent size ∝ 1 / (zoom · tan(fov/2)). `pan_x`/`pan_y` truck the camera in+ * its own plane (world units; +x moves the subject right, +y up).+ */+export type Camera3DProperties = {+/**+ * Camera orbit pitch.+ */+tiltX?: number;+/**+ * Camera orbit yaw.+ */+tiltY?: number;+/**+ * Camera roll (innermost camera rotation).+ */+roll?: number;+/**+ * Content plane pitch.+ */+rotateX?: number;+/**+ * Content plane yaw.+ */+rotateY?: number; fov?: number;+/**+ * Camera distance in world units.+ */+zoom?: number; panX?: number; panY?: number }+export type Camera3DSegment = { start: number; end: number; enabled?: boolean;+/**+ * Base pose; per-property tracks override individual values.+ */+properties?: Camera3DProperties; blur?: Camera3DBlur; tracks?: Camera3DTracks;+/**+ * Seconds to ease from the flat frame into the pose at the segment start.+ */+transitionIn?: number;+/**+ * Seconds to ease back to the flat frame before the segment end.+ */+transitionOut?: number }+/**+ * Per-property keyframe tracks. A property with an empty track holds the+ * segment's base value; each track holds independently before its first and+ * after its last keyframe.+ */+export type Camera3DTracks = { tiltX: Camera3DKeyframe[]; tiltY: Camera3DKeyframe[]; roll: Camera3DKeyframe[]; rotateX: Camera3DKeyframe[]; rotateY: Camera3DKeyframe[]; fov: Camera3DKeyframe[]; zoom: Camera3DKeyframe[]; panX: Camera3DKeyframe[]; panY: Camera3DKeyframe[]; blurStrength: Camera3DKeyframe[]; blurFalloff: Camera3DKeyframe[]; blurFocusSize: Camera3DKeyframe[]; blurFocusX: Camera3DKeyframe[]; blurFocusY: Camera3DKeyframe[]; blurAngle: Camera3DKeyframe[]; blurDirPosition: Camera3DKeyframe[] }export type CameraDeviceSettings = { width: number | null; height: number | null; frameRate: number | null }export type CameraFormatInfo = { width: number; height: number; frameRate: number }export type CameraInfo = { device_id: string; model_id: ModelIDType | null; display_name: string }@@ -959,7 +1067,7 @@ export type StudioRecordingStatus = { status: "InProgress" } | { status: "NeedsRexport type SystemDiagnostics = { macosVersion: MacOSVersionInfo | null; availableEncoders: string[]; screenCaptureSupported: boolean; metalSupported: boolean; gpuName: string | null }export type TargetUnderCursor = { display_id: DisplayId | null; window: WindowUnderCursor | null }export type TextSegment = { start: number; end: number; track?: number; enabled?: boolean; content?: string; center?: XY<number>; size?: XY<number>; fontFamily?: string; fontSize?: number; fontWeight?: number; italic?: boolean; color?: string; fadeDuration?: number }-export type TimelineConfiguration = { segments: TimelineSegment[]; transitions: ClipTransition[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[]; textSegments?: TextSegment[]; captionSegments?: CaptionTrackSegment[]; keyboardSegments?: KeyboardTrackSegment[]; audioSegments?: AudioTrackSegment[] }+export type TimelineConfiguration = { segments: TimelineSegment[]; transitions: ClipTransition[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[]; textSegments?: TextSegment[]; captionSegments?: CaptionTrackSegment[]; keyboardSegments?: KeyboardTrackSegment[]; audioSegments?: AudioTrackSegment[]; camera3dSegments?: Camera3DSegment[] }export type TimelineSegment = { recordingSegment?: number; timescale: number; start: number; end: number; name?: string | null; speedAudioMode?: ClipSpeedAudioMode | null }export type TranscriptionEngine = "Whisper" | "Parakeet"export type Trigger = "screenshotTaken" | "studioRecordingFinished" | "instantRecordingFinished" | "recordingStarted" | "uploadCompleted" | "videoImported" | "recordingDeleted"diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.tsindex b2277e16c..b51a36aea 100644--- a/packages/ui-solid/src/auto-imports.d.ts+++ b/packages/ui-solid/src/auto-imports.d.ts@@ -75,6 +75,8 @@ declare global {const IconLucideCaptions: typeof import('~icons/lucide/captions.jsx')['default']const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default']const IconLucideChevronDown: typeof import('~icons/lucide/chevron-down.jsx')['default']+ const IconLucideChevronLeft: typeof import('~icons/lucide/chevron-left.jsx')['default']+ const IconLucideChevronRight: typeof import('~icons/lucide/chevron-right.jsx')['default']const IconLucideChevronUp: typeof import('~icons/lucide/chevron-up.jsx')['default']const IconLucideCircleOff: typeof import('~icons/lucide/circle-off.jsx')['default']const IconLucideClapperboard: typeof import('~icons/lucide/clapperboard.jsx')['default']@@ -83,6 +85,8 @@ declare global {const IconLucideEdit: typeof import('~icons/lucide/edit.jsx')['default']const IconLucideEyeOff: typeof import('~icons/lucide/eye-off.jsx')['default']const IconLucideFastForward: typeof import('~icons/lucide/fast-forward.jsx')['default']+ const IconLucideFlipHorizontal2: typeof import('~icons/lucide/flip-horizontal2.jsx')['default']+ const IconLucideFlipVertical2: typeof import('~icons/lucide/flip-vertical2.jsx')['default']const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default']const IconLucideGauge: typeof import('~icons/lucide/gauge.jsx')['default']const IconLucideGift: typeof import('~icons/lucide/gift.jsx')['default']