Initial work on movie clips

This commit is contained in:
Skyler Lehmkuhl
2026-02-21 00:54:38 -05:00
parent 3ba6dcb3d2
commit 1892f970c4
17 changed files with 1005 additions and 220 deletions
@@ -133,7 +133,9 @@ pub struct ActionExecutor {
impl ActionExecutor {
/// Create a new action executor with the given document
pub fn new(document: Document) -> Self {
pub fn new(mut document: Document) -> Self {
// Rebuild transient lookup maps (not serialized)
document.rebuild_layer_to_clip_map();
Self {
document: Arc::new(document),
undo_stack: Vec::new(),
@@ -0,0 +1,244 @@
//! Convert to Movie Clip action
//!
//! Wraps selected shapes and/or clip instances into a new VectorClip
//! with is_group = false, giving it a real internal timeline.
//! Works with 1+ selected items (unlike Group which requires 2+).
use crate::action::Action;
use crate::animation::{AnimationCurve, AnimationTarget, Keyframe, TransformProperty};
use crate::clip::{ClipInstance, VectorClip};
use crate::document::Document;
use crate::layer::{AnyLayer, VectorLayer};
use crate::shape::Shape;
use uuid::Uuid;
use vello::kurbo::{Rect, Shape as KurboShape};
pub struct ConvertToMovieClipAction {
layer_id: Uuid,
time: f64,
shape_ids: Vec<Uuid>,
clip_instance_ids: Vec<Uuid>,
instance_id: Uuid,
created_clip_id: Option<Uuid>,
removed_shapes: Vec<Shape>,
removed_clip_instances: Vec<ClipInstance>,
}
impl ConvertToMovieClipAction {
pub fn new(
layer_id: Uuid,
time: f64,
shape_ids: Vec<Uuid>,
clip_instance_ids: Vec<Uuid>,
instance_id: Uuid,
) -> Self {
Self {
layer_id,
time,
shape_ids,
clip_instance_ids,
instance_id,
created_clip_id: None,
removed_shapes: Vec::new(),
removed_clip_instances: Vec::new(),
}
}
}
impl Action for ConvertToMovieClipAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let layer = document
.get_layer(&self.layer_id)
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
let vl = match layer {
AnyLayer::Vector(vl) => vl,
_ => return Err("Convert to Movie Clip is only supported on vector layers".to_string()),
};
// Collect shapes
let shapes_at_time = vl.shapes_at_time(self.time);
let mut collected_shapes: Vec<Shape> = Vec::new();
for id in &self.shape_ids {
if let Some(shape) = shapes_at_time.iter().find(|s| &s.id == id) {
collected_shapes.push(shape.clone());
}
}
// Collect clip instances
let mut collected_clip_instances: Vec<ClipInstance> = Vec::new();
for id in &self.clip_instance_ids {
if let Some(ci) = vl.clip_instances.iter().find(|ci| &ci.id == id) {
collected_clip_instances.push(ci.clone());
}
}
let total_items = collected_shapes.len() + collected_clip_instances.len();
if total_items < 1 {
return Err("Need at least 1 item to convert to movie clip".to_string());
}
// Compute combined bounding box
let mut combined_bbox: Option<Rect> = None;
for shape in &collected_shapes {
let local_bbox = shape.path().bounding_box();
let transform = shape.transform.to_affine();
let transformed_bbox = transform.transform_rect_bbox(local_bbox);
combined_bbox = Some(match combined_bbox {
Some(existing) => existing.union(transformed_bbox),
None => transformed_bbox,
});
}
for ci in &collected_clip_instances {
let content_bounds = if let Some(vector_clip) = document.get_vector_clip(&ci.clip_id) {
let clip_time = ((self.time - ci.timeline_start) * ci.playback_speed) + ci.trim_start;
vector_clip.calculate_content_bounds(document, clip_time)
} else if let Some(video_clip) = document.get_video_clip(&ci.clip_id) {
Rect::new(0.0, 0.0, video_clip.width, video_clip.height)
} else {
continue;
};
let ci_transform = ci.transform.to_affine();
let transformed_bbox = ci_transform.transform_rect_bbox(content_bounds);
combined_bbox = Some(match combined_bbox {
Some(existing) => existing.union(transformed_bbox),
None => transformed_bbox,
});
}
let bbox = combined_bbox.ok_or("Could not compute bounding box")?;
let center_x = (bbox.x0 + bbox.x1) / 2.0;
let center_y = (bbox.y0 + bbox.y1) / 2.0;
// Offset shapes relative to center
let mut clip_shapes: Vec<Shape> = collected_shapes.clone();
for shape in &mut clip_shapes {
shape.transform.x -= center_x;
shape.transform.y -= center_y;
}
let mut clip_instances_inside: Vec<ClipInstance> = collected_clip_instances.clone();
for ci in &mut clip_instances_inside {
ci.transform.x -= center_x;
ci.transform.y -= center_y;
}
// Create VectorClip with real timeline duration
let mut clip = VectorClip::new("Movie Clip", bbox.width(), bbox.height(), document.duration);
// is_group defaults to false — movie clips have real timelines
let clip_id = clip.id;
let mut inner_layer = VectorLayer::new("Layer 1");
for shape in clip_shapes {
inner_layer.add_shape_to_keyframe(shape, 0.0);
}
for ci in clip_instances_inside {
inner_layer.clip_instances.push(ci);
}
clip.layers.add_root(AnyLayer::Vector(inner_layer));
document.add_vector_clip(clip);
self.created_clip_id = Some(clip_id);
// Remove originals from the layer
let layer = document.get_layer_mut(&self.layer_id).unwrap();
let vl = match layer {
AnyLayer::Vector(vl) => vl,
_ => unreachable!(),
};
self.removed_shapes.clear();
for id in &self.shape_ids {
if let Some(shape) = vl.remove_shape_from_keyframe(id, self.time) {
self.removed_shapes.push(shape);
}
}
self.removed_clip_instances.clear();
for id in &self.clip_instance_ids {
if let Some(pos) = vl.clip_instances.iter().position(|ci| &ci.id == id) {
self.removed_clip_instances.push(vl.clip_instances.remove(pos));
}
}
// Place the new ClipInstance
let instance = ClipInstance::with_id(self.instance_id, clip_id)
.with_position(center_x, center_y)
.with_name("Movie Clip");
vl.clip_instances.push(instance);
// Create default animation curves
let props_and_values = [
(TransformProperty::X, center_x),
(TransformProperty::Y, center_y),
(TransformProperty::Rotation, 0.0),
(TransformProperty::ScaleX, 1.0),
(TransformProperty::ScaleY, 1.0),
(TransformProperty::SkewX, 0.0),
(TransformProperty::SkewY, 0.0),
(TransformProperty::Opacity, 1.0),
];
for (prop, value) in props_and_values {
let target = AnimationTarget::Object {
id: self.instance_id,
property: prop,
};
let mut curve = AnimationCurve::new(target.clone(), value);
curve.set_keyframe(Keyframe::linear(0.0, value));
vl.layer.animation_data.set_curve(curve);
}
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
let layer = document
.get_layer_mut(&self.layer_id)
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
if let AnyLayer::Vector(vl) = layer {
// Remove animation curves
for prop in &[
TransformProperty::X, TransformProperty::Y,
TransformProperty::Rotation,
TransformProperty::ScaleX, TransformProperty::ScaleY,
TransformProperty::SkewX, TransformProperty::SkewY,
TransformProperty::Opacity,
] {
let target = AnimationTarget::Object {
id: self.instance_id,
property: *prop,
};
vl.layer.animation_data.remove_curve(&target);
}
// Remove the clip instance
vl.clip_instances.retain(|ci| ci.id != self.instance_id);
// Re-insert removed shapes
for shape in self.removed_shapes.drain(..) {
vl.add_shape_to_keyframe(shape, self.time);
}
// Re-insert removed clip instances
for ci in self.removed_clip_instances.drain(..) {
vl.clip_instances.push(ci);
}
}
// Remove the VectorClip from the document
if let Some(clip_id) = self.created_clip_id.take() {
document.remove_vector_clip(&clip_id);
}
Ok(())
}
fn description(&self) -> String {
let count = self.shape_ids.len() + self.clip_instance_ids.len();
format!("Convert {} object(s) to Movie Clip", count)
}
}
@@ -30,6 +30,7 @@ pub mod remove_clip_instances;
pub mod remove_shapes;
pub mod set_keyframe;
pub mod group_shapes;
pub mod convert_to_movie_clip;
pub use add_clip_instance::AddClipInstanceAction;
pub use add_effect::AddEffectAction;
@@ -58,3 +59,4 @@ pub use remove_clip_instances::RemoveClipInstancesAction;
pub use remove_shapes::RemoveShapesAction;
pub use set_keyframe::SetKeyframeAction;
pub use group_shapes::GroupAction;
pub use convert_to_movie_clip::ConvertToMovieClipAction;
@@ -90,6 +90,30 @@ impl VectorClip {
}
}
/// Calculate the duration of this clip based on its internal keyframe content.
/// Returns the time of the last keyframe across all layers, plus one frame.
/// Falls back to the stored `duration` field if no keyframes exist.
pub fn content_duration(&self, framerate: f64) -> f64 {
let frame_duration = 1.0 / framerate;
let mut last_time: Option<f64> = None;
for layer_node in self.layers.iter() {
if let AnyLayer::Vector(vector_layer) = &layer_node.data {
if let Some(last_kf) = vector_layer.keyframes.last() {
last_time = Some(match last_time {
Some(t) => t.max(last_kf.time),
None => last_kf.time,
});
}
}
}
match last_time {
Some(t) => t + frame_duration,
None => self.duration,
}
}
/// Calculate the bounding box of all content in this clip at a specific time
///
/// This recursively calculates the union of all shape and nested clip bounding boxes
@@ -166,6 +166,11 @@ pub struct Document {
/// Current playback time in seconds
#[serde(skip)]
pub current_time: f64,
/// Reverse lookup: layer_id → clip_id for layers inside vector clips.
/// Enables O(1) lookup in get_layer/get_layer_mut instead of scanning all clips.
#[serde(skip)]
pub layer_to_clip_map: HashMap<Uuid, Uuid>,
}
impl Default for Document {
@@ -195,6 +200,7 @@ impl Default for Document {
ui_layout: None,
ui_layout_base: None,
current_time: 0.0,
layer_to_clip_map: HashMap::new(),
}
}
}
@@ -218,6 +224,27 @@ impl Document {
}
}
/// Rebuild the layer→clip reverse lookup map from all vector clips.
/// Call after deserialization or bulk clip modifications.
pub fn rebuild_layer_to_clip_map(&mut self) {
self.layer_to_clip_map.clear();
for (clip_id, clip) in &self.vector_clips {
for node in &clip.layers.roots {
self.layer_to_clip_map.insert(node.data.id(), *clip_id);
}
}
}
/// Register a layer as belonging to a clip (for O(1) lookup).
pub fn register_layer_in_clip(&mut self, layer_id: Uuid, clip_id: Uuid) {
self.layer_to_clip_map.insert(layer_id, clip_id);
}
/// Unregister a layer from the clip lookup map.
pub fn unregister_layer_from_clip(&mut self, layer_id: &Uuid) {
self.layer_to_clip_map.remove(layer_id);
}
/// Set the background color
pub fn with_background(mut self, color: ShapeColor) -> Self {
self.background_color = color;
@@ -343,9 +370,31 @@ impl Document {
.filter(|layer| layer.layer().visible)
}
/// Get a layer by ID
/// Get visible layers for the current editing context
pub fn context_visible_layers(&self, clip_id: Option<&Uuid>) -> Vec<&AnyLayer> {
self.context_layers(clip_id)
.into_iter()
.filter(|layer| layer.layer().visible)
.collect()
}
/// Get a layer by ID (searches root layers, then clip layers via O(1) map lookup)
pub fn get_layer(&self, id: &Uuid) -> Option<&AnyLayer> {
self.root.get_child(id)
// First check root layers
if let Some(layer) = self.root.get_child(id) {
return Some(layer);
}
// O(1) lookup: check if this layer belongs to a clip
if let Some(clip_id) = self.layer_to_clip_map.get(id) {
if let Some(clip) = self.vector_clips.get(clip_id) {
for node in &clip.layers.roots {
if &node.data.id() == id {
return Some(&node.data);
}
}
}
}
None
}
// === MUTATION METHODS (pub(crate) - only accessible to action module) ===
@@ -358,12 +407,59 @@ impl Document {
&mut self.root
}
/// Get mutable access to a layer by ID
/// Get mutable access to a layer by ID (searches root layers, then clip layers via O(1) map lookup)
///
/// This method is intentionally `pub(crate)` to ensure mutations
/// only happen through the action system.
pub fn get_layer_mut(&mut self, id: &Uuid) -> Option<&mut AnyLayer> {
self.root.get_child_mut(id)
// First check root layers
if self.root.get_child(id).is_some() {
return self.root.get_child_mut(id);
}
// O(1) lookup: check if this layer belongs to a clip
if let Some(clip_id) = self.layer_to_clip_map.get(id).copied() {
if let Some(clip) = self.vector_clips.get_mut(&clip_id) {
for node in &mut clip.layers.roots {
if &node.data.id() == id {
return Some(&mut node.data);
}
}
}
}
None
}
// === EDITING CONTEXT METHODS ===
/// Get the layers for the current editing context.
/// When `clip_id` is None, returns root layers. When Some, returns the clip's layers.
pub fn context_layers(&self, clip_id: Option<&Uuid>) -> Vec<&AnyLayer> {
match clip_id {
None => self.root.children.iter().collect(),
Some(id) => self.vector_clips.get(id)
.map(|clip| clip.layers.root_data())
.unwrap_or_default(),
}
}
/// Get mutable layers for the current editing context.
pub fn context_layers_mut(&mut self, clip_id: Option<&Uuid>) -> Vec<&mut AnyLayer> {
match clip_id {
None => self.root.children.iter_mut().collect(),
Some(id) => self.vector_clips.get_mut(id)
.map(|clip| clip.layers.root_data_mut())
.unwrap_or_default(),
}
}
/// Look up a layer by ID within an editing context.
pub fn get_layer_in_context(&self, clip_id: Option<&Uuid>, layer_id: &Uuid) -> Option<&AnyLayer> {
self.context_layers(clip_id).into_iter().find(|l| &l.id() == layer_id)
}
/// Look up a mutable layer by ID within an editing context.
pub fn get_layer_in_context_mut(&mut self, clip_id: Option<&Uuid>, layer_id: &Uuid) -> Option<&mut AnyLayer> {
self.context_layers_mut(clip_id).into_iter().find(|l| &l.id() == layer_id)
}
// === CLIP LIBRARY METHODS ===
@@ -371,6 +467,10 @@ impl Document {
/// Add a vector clip to the library
pub fn add_vector_clip(&mut self, clip: VectorClip) -> Uuid {
let id = clip.id;
// Register all layers in the clip for O(1) reverse lookup
for node in &clip.layers.roots {
self.layer_to_clip_map.insert(node.data.id(), id);
}
self.vector_clips.insert(id, clip);
id
}
@@ -439,7 +539,15 @@ impl Document {
/// Remove a vector clip from the library
pub fn remove_vector_clip(&mut self, id: &Uuid) -> Option<VectorClip> {
self.vector_clips.remove(id)
if let Some(clip) = self.vector_clips.remove(id) {
// Unregister all layers from the reverse lookup map
for node in &clip.layers.roots {
self.layer_to_clip_map.remove(&node.data.id());
}
Some(clip)
} else {
None
}
}
/// Remove a video clip from the library
@@ -534,7 +642,11 @@ impl Document {
/// have infinite internal duration.
pub fn get_clip_duration(&self, clip_id: &Uuid) -> Option<f64> {
if let Some(clip) = self.vector_clips.get(clip_id) {
Some(clip.duration)
if clip.is_group {
Some(clip.duration)
} else {
Some(clip.content_duration(self.framerate))
}
} else if let Some(clip) = self.video_clips.get(clip_id) {
Some(clip.duration)
} else if let Some(clip) = self.audio_clips.get(clip_id) {
@@ -164,6 +164,13 @@ pub fn hit_test_clip_instances(
timeline_time: f64,
) -> Option<Uuid> {
for clip_instance in clip_instances.iter().rev() {
// Check time bounds: skip clip instances not active at this time
let clip_duration = document.get_clip_duration(&clip_instance.clip_id).unwrap_or(0.0);
let instance_end = clip_instance.timeline_start + clip_instance.effective_duration(clip_duration);
if timeline_time < clip_instance.timeline_start || timeline_time >= instance_end {
continue;
}
let clip_time = ((timeline_time - clip_instance.timeline_start) * clip_instance.playback_speed) + clip_instance.trim_start;
let content_bounds = if let Some(vector_clip) = document.get_vector_clip(&clip_instance.clip_id) {
@@ -196,6 +203,13 @@ pub fn hit_test_clip_instances_in_rect(
let mut hits = Vec::new();
for clip_instance in clip_instances {
// Check time bounds: skip clip instances not active at this time
let clip_duration = document.get_clip_duration(&clip_instance.clip_id).unwrap_or(0.0);
let instance_end = clip_instance.timeline_start + clip_instance.effective_duration(clip_duration);
if timeline_time < clip_instance.timeline_start || timeline_time >= instance_end {
continue;
}
let clip_time = ((timeline_time - clip_instance.timeline_start) * clip_instance.playback_speed) + clip_instance.trim_start;
let content_bounds = if let Some(vector_clip) = document.get_vector_clip(&clip_instance.clip_id) {
@@ -328,48 +328,6 @@ impl VectorLayer {
// === MUTATION METHODS (pub(crate) - only accessible to action module) ===
/// Add a shape to this layer (internal, for actions only)
///
/// This method is intentionally `pub(crate)` to ensure mutations
/// only happen through the action system.
pub(crate) fn add_shape_internal(&mut self, shape: Shape) -> Uuid {
let id = shape.id;
self.shapes.insert(id, shape);
id
}
/// Add an object to this layer (internal, for actions only)
///
/// This method is intentionally `pub(crate)` to ensure mutations
/// only happen through the action system.
pub(crate) fn add_object_internal(&mut self, object: ShapeInstance) -> Uuid {
let id = object.id;
self.shape_instances.push(object);
id
}
/// Remove a shape from this layer (internal, for actions only)
///
/// Returns the removed shape if found.
/// This method is intentionally `pub(crate)` to ensure mutations
/// only happen through the action system.
pub(crate) fn remove_shape_internal(&mut self, id: &Uuid) -> Option<Shape> {
self.shapes.remove(id)
}
/// Remove an object from this layer (internal, for actions only)
///
/// Returns the removed object if found.
/// This method is intentionally `pub(crate)` to ensure mutations
/// only happen through the action system.
pub(crate) fn remove_object_internal(&mut self, id: &Uuid) -> Option<ShapeInstance> {
if let Some(index) = self.shape_instances.iter().position(|o| &o.id == id) {
Some(self.shape_instances.remove(index))
} else {
None
}
}
/// Modify an object in place (internal, for actions only)
///
/// Applies the given function to the object if found.
@@ -110,6 +110,18 @@ impl<T> LayerTree<T> {
}
}
impl<T> LayerTree<T> {
/// Get flat list of references to all root layer data
pub fn root_data(&self) -> Vec<&T> {
self.roots.iter().map(|n| &n.data).collect()
}
/// Get flat list of mutable references to all root layer data
pub fn root_data_mut(&mut self) -> Vec<&mut T> {
self.roots.iter_mut().map(|n| &mut n.data).collect()
}
}
impl<T> Default for LayerTree<T> {
fn default() -> Self {
Self::new()
@@ -373,7 +373,19 @@ pub fn render_document_with_transform(
// 2. Recursively render the root graphics object at current time
let time = document.current_time;
render_graphics_object(document, time, scene, base_transform, image_cache, video_manager, skip_instance_id);
// Check if any layers are soloed
let any_soloed = document.visible_layers().any(|layer| layer.soloed());
for layer in document.visible_layers() {
if any_soloed {
if layer.soloed() {
render_layer(document, time, layer, scene, base_transform, 1.0, image_cache, video_manager, skip_instance_id);
}
} else {
render_layer(document, time, layer, scene, base_transform, 1.0, image_cache, video_manager, skip_instance_id);
}
}
}
/// Draw the document background
@@ -392,35 +404,6 @@ fn render_background(document: &Document, scene: &mut Scene, base_transform: Aff
);
}
/// Recursively render the root graphics object and its children
fn render_graphics_object(
document: &Document,
time: f64,
scene: &mut Scene,
base_transform: Affine,
image_cache: &mut ImageCache,
video_manager: &std::sync::Arc<std::sync::Mutex<crate::video::VideoManager>>,
skip_instance_id: Option<uuid::Uuid>,
) {
// Check if any layers are soloed
let any_soloed = document.visible_layers().any(|layer| layer.soloed());
// Render layers based on solo state
// If any layer is soloed, only render soloed layers
// Otherwise, render all visible layers
// Start with full opacity (1.0)
for layer in document.visible_layers() {
if any_soloed {
// Only render soloed layers when solo is active
if layer.soloed() {
render_layer(document, time, layer, scene, base_transform, 1.0, image_cache, video_manager, skip_instance_id);
}
} else {
// Render all visible layers when no solo is active
render_layer(document, time, layer, scene, base_transform, 1.0, image_cache, video_manager, skip_instance_id);
}
}
}
/// Render a single layer
fn render_layer(
@@ -451,6 +434,42 @@ fn render_layer(
}
}
/// Render a single clip instance by ID to a scene.
/// Used for re-rendering the "focused" clip on top of a dimmed scene when editing inside a clip.
pub fn render_single_clip_instance(
document: &Document,
scene: &mut Scene,
base_transform: Affine,
layer_id: &uuid::Uuid,
instance_id: &uuid::Uuid,
image_cache: &mut ImageCache,
video_manager: &std::sync::Arc<std::sync::Mutex<crate::video::VideoManager>>,
) {
let time = document.current_time;
// Find the layer containing this instance
let Some(layer) = document.get_layer(layer_id) else { return };
let AnyLayer::Vector(vector_layer) = layer else { return };
let layer_opacity = vector_layer.layer.opacity;
// Find the specific clip instance
let Some(clip_instance) = vector_layer.clip_instances.iter().find(|ci| &ci.id == instance_id) else { return };
// Compute group_end_time if needed
let group_end_time = document.vector_clips.get(&clip_instance.clip_id)
.filter(|vc| vc.is_group)
.map(|_| {
let frame_duration = 1.0 / document.framerate;
vector_layer.group_visibility_end(&clip_instance.id, clip_instance.timeline_start, frame_duration)
});
render_clip_instance(
document, time, clip_instance, layer_opacity, scene, base_transform,
&vector_layer.layer.animation_data, image_cache, video_manager, group_end_time,
);
}
/// Render a clip instance (recursive rendering for nested compositions)
fn render_clip_instance(
document: &Document,
@@ -479,7 +498,8 @@ fn render_clip_instance(
}
0.0
} else {
let Some(t) = clip_instance.remap_time(time, vector_clip.duration) else {
let clip_dur = vector_clip.content_duration(document.framerate);
let Some(t) = clip_instance.remap_time(time, clip_dur) else {
return; // Clip instance not active at this time
};
t