start work on compositing, effects

This commit is contained in:
Skyler Lehmkuhl
2025-12-08 09:30:22 -05:00
parent 420f3bf7b9
commit 7eb61ab0a8
31 changed files with 3172 additions and 150 deletions
@@ -514,6 +514,82 @@ fn shape_color_to_tiny_skia(color: &ShapeColor) -> tiny_skia::Color {
tiny_skia::Color::from_rgba8(color.r, color.g, color.b, color.a)
}
/// Generate a simple effect thumbnail with a pink gradient
fn generate_effect_thumbnail() -> Vec<u8> {
let size = THUMBNAIL_SIZE as usize;
let mut rgba = vec![0u8; size * size * 4];
// Pink gradient background with "FX" visual indicator
for y in 0..size {
for x in 0..size {
let brightness = 1.0 - (y as f32 / size as f32) * 0.3;
let idx = (y * size + x) * 4;
rgba[idx] = (220.0 * brightness) as u8; // R
rgba[idx + 1] = (80.0 * brightness) as u8; // G
rgba[idx + 2] = (160.0 * brightness) as u8; // B
rgba[idx + 3] = 200; // A
}
}
// Draw a simple "FX" pattern in the center using darker pixels
let center = size / 2;
let letter_size = size / 4;
// Draw "F" - vertical bar
for y in (center - letter_size)..(center + letter_size) {
let x = center - letter_size;
let idx = (y * size + x) * 4;
rgba[idx] = 255;
rgba[idx + 1] = 255;
rgba[idx + 2] = 255;
rgba[idx + 3] = 255;
}
// Draw "F" - top horizontal
for x in (center - letter_size)..(center - 2) {
let y = center - letter_size;
let idx = (y * size + x) * 4;
rgba[idx] = 255;
rgba[idx + 1] = 255;
rgba[idx + 2] = 255;
rgba[idx + 3] = 255;
}
// Draw "F" - middle horizontal
for x in (center - letter_size)..(center - 4) {
let y = center;
let idx = (y * size + x) * 4;
rgba[idx] = 255;
rgba[idx + 1] = 255;
rgba[idx + 2] = 255;
rgba[idx + 3] = 255;
}
// Draw "X" - diagonal lines
for i in 0..letter_size {
// Top-left to bottom-right
let x1 = center + 2 + i;
let y1 = center - letter_size + i * 2;
if x1 < size && y1 < size {
let idx = (y1 * size + x1) * 4;
rgba[idx] = 255;
rgba[idx + 1] = 255;
rgba[idx + 2] = 255;
rgba[idx + 3] = 255;
}
// Top-right to bottom-left
let x2 = center + letter_size - i;
let y2 = center - letter_size + i * 2;
if x2 < size && y2 < size {
let idx = (y2 * size + x2) * 4;
rgba[idx] = 255;
rgba[idx + 1] = 255;
rgba[idx + 2] = 255;
rgba[idx + 3] = 255;
}
}
rgba
}
/// Ellipsize a string to fit within a maximum character count
fn ellipsize(s: &str, max_chars: usize) -> String {
if s.chars().count() <= max_chars {
@@ -532,6 +608,7 @@ pub enum AssetCategory {
Video,
Audio,
Images,
Effects,
}
impl AssetCategory {
@@ -542,6 +619,7 @@ impl AssetCategory {
AssetCategory::Video => "Video",
AssetCategory::Audio => "Audio",
AssetCategory::Images => "Images",
AssetCategory::Effects => "Effects",
}
}
@@ -552,6 +630,7 @@ impl AssetCategory {
AssetCategory::Video,
AssetCategory::Audio,
AssetCategory::Images,
AssetCategory::Effects,
]
}
@@ -563,6 +642,7 @@ impl AssetCategory {
AssetCategory::Video => egui::Color32::from_rgb(255, 150, 100), // Orange
AssetCategory::Audio => egui::Color32::from_rgb(100, 255, 150), // Green
AssetCategory::Images => egui::Color32::from_rgb(255, 200, 100), // Yellow/Gold
AssetCategory::Effects => egui::Color32::from_rgb(220, 80, 160), // Pink
}
}
}
@@ -578,6 +658,8 @@ pub struct AssetEntry {
pub duration: f64,
pub dimensions: Option<(f64, f64)>,
pub extra_info: String,
/// True for built-in effects from the registry (not editable/deletable)
pub is_builtin: bool,
}
/// Pending delete confirmation state
@@ -658,6 +740,7 @@ impl AssetLibraryPane {
duration: clip.duration,
dimensions: Some((clip.width, clip.height)),
extra_info: format!("{}x{}", clip.width as u32, clip.height as u32),
is_builtin: false,
});
}
@@ -671,6 +754,7 @@ impl AssetLibraryPane {
duration: clip.duration,
dimensions: Some((clip.width, clip.height)),
extra_info: format!("{:.0}fps", clip.frame_rate),
is_builtin: false,
});
}
@@ -699,6 +783,7 @@ impl AssetLibraryPane {
duration: clip.duration,
dimensions: None,
extra_info,
is_builtin: false,
});
}
@@ -712,9 +797,46 @@ impl AssetLibraryPane {
duration: 0.0, // Images don't have duration
dimensions: Some((asset.width as f64, asset.height as f64)),
extra_info: format!("{}x{}", asset.width, asset.height),
is_builtin: false,
});
}
// Collect built-in effects from registry
for effect_def in lightningbeam_core::effect_registry::EffectRegistry::get_all() {
assets.push(AssetEntry {
id: effect_def.id,
name: effect_def.name.clone(),
category: AssetCategory::Effects,
drag_clip_type: DragClipType::Effect,
duration: 5.0, // Default duration when dropped
dimensions: None,
extra_info: format!("{:?}", effect_def.category),
is_builtin: true, // Built-in from registry
});
}
// Collect user-edited effects from document (that aren't in registry)
let registry_ids: HashSet<Uuid> = lightningbeam_core::effect_registry::EffectRegistry::get_all()
.iter()
.map(|e| e.id)
.collect();
for effect_def in document.effect_definitions.values() {
if !registry_ids.contains(&effect_def.id) {
// User-created/modified effect
assets.push(AssetEntry {
id: effect_def.id,
name: effect_def.name.clone(),
category: AssetCategory::Effects,
drag_clip_type: DragClipType::Effect,
duration: 5.0,
dimensions: None,
extra_info: format!("{:?}", effect_def.category),
is_builtin: false, // User effect
});
}
}
// Sort alphabetically by name
assets.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
@@ -729,8 +851,13 @@ impl AssetLibraryPane {
.iter()
.filter(|asset| {
// Category filter
let category_matches = self.selected_category == AssetCategory::All
|| asset.category == self.selected_category;
let category_matches = if self.selected_category == AssetCategory::All {
// "All" tab: show everything EXCEPT built-in effects
// (built-in effects only appear in the Effects tab)
!(asset.category == AssetCategory::Effects && asset.is_builtin)
} else {
asset.category == self.selected_category
};
// Search filter
let search_matches =
@@ -773,6 +900,15 @@ impl AssetLibraryPane {
}
}
}
lightningbeam_core::layer::AnyLayer::Effect(el) => {
if category == AssetCategory::Effects {
for instance in &el.clip_instances {
if instance.clip_id == asset_id {
return true;
}
}
}
}
}
}
false
@@ -793,6 +929,9 @@ impl AssetLibraryPane {
AssetCategory::Images => {
document.remove_image_asset(&asset_id);
}
AssetCategory::Effects => {
document.effect_definitions.remove(&asset_id);
}
AssetCategory::All => {} // Not a real category for deletion
}
}
@@ -820,6 +959,11 @@ impl AssetLibraryPane {
asset.name = new_name.to_string();
}
}
AssetCategory::Effects => {
if let Some(effect) = document.effect_definitions.get_mut(&asset_id) {
effect.name = new_name.to_string();
}
}
AssetCategory::All => {} // Not a real category for renaming
}
}
@@ -1268,6 +1412,9 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AssetCategory::Effects => {
Some(generate_effect_thumbnail())
}
AssetCategory::All => None,
}
});
@@ -1555,6 +1702,9 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AssetCategory::Effects => {
Some(generate_effect_thumbnail())
}
AssetCategory::All => None,
}
});
@@ -1739,6 +1889,7 @@ impl PaneRenderer for AssetLibraryPane {
if let Some(asset) = all_assets.iter().find(|a| a.id == context_asset_id) {
let asset_name = asset.name.clone();
let asset_category = asset.category;
let asset_is_builtin = asset.is_builtin;
let in_use = Self::is_asset_in_use(
shared.action_executor.document(),
context_asset_id,
@@ -1754,25 +1905,32 @@ impl PaneRenderer for AssetLibraryPane {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.set_min_width(120.0);
if ui.button("Rename").clicked() {
// Start inline rename
self.rename_state = Some(RenameState {
asset_id: context_asset_id,
category: asset_category,
edit_text: asset_name.clone(),
});
self.context_menu = None;
}
// Built-in effects cannot be renamed or deleted
if asset_is_builtin {
ui.label(egui::RichText::new("Built-in effect")
.color(egui::Color32::from_gray(120))
.italics());
} else {
if ui.button("Rename").clicked() {
// Start inline rename
self.rename_state = Some(RenameState {
asset_id: context_asset_id,
category: asset_category,
edit_text: asset_name.clone(),
});
self.context_menu = None;
}
if ui.button("Delete").clicked() {
// Set up pending delete confirmation
self.pending_delete = Some(PendingDelete {
asset_id: context_asset_id,
asset_name: asset_name.clone(),
category: asset_category,
in_use,
});
self.context_menu = None;
if ui.button("Delete").clicked() {
// Set up pending delete confirmation
self.pending_delete = Some(PendingDelete {
asset_id: context_asset_id,
asset_name: asset_name.clone(),
category: asset_category,
in_use,
});
self.context_menu = None;
}
}
});
});
@@ -33,6 +33,8 @@ pub enum DragClipType {
AudioMidi,
/// Static image asset
Image,
/// Effect (shader-based visual effect)
Effect,
}
/// Information about an asset being dragged from the Asset Library
@@ -91,6 +93,7 @@ pub fn layer_matches_clip_type(layer: &lightningbeam_core::layer::AnyLayer, clip
(AnyLayer::Audio(audio), DragClipType::AudioMidi) => {
audio.audio_layer_type == AudioLayerType::Midi
}
(AnyLayer::Effect(_), DragClipType::Effect) => true,
_ => false,
}
}
@@ -98,6 +101,7 @@ pub fn layer_matches_clip_type(layer: &lightningbeam_core::layer::AnyLayer, clip
/// Create a new layer of the appropriate type for a clip
pub fn create_layer_for_clip_type(clip_type: DragClipType, name: &str) -> lightningbeam_core::layer::AnyLayer {
use lightningbeam_core::layer::*;
use lightningbeam_core::effect_layer::EffectLayer;
match clip_type {
DragClipType::Vector => AnyLayer::Vector(VectorLayer::new(name)),
DragClipType::Video => AnyLayer::Video(VideoLayer::new(name)),
@@ -105,6 +109,7 @@ pub fn create_layer_for_clip_type(clip_type: DragClipType, name: &str) -> lightn
DragClipType::AudioMidi => AnyLayer::Audio(AudioLayer::new_midi(name)),
// Images are placed as shapes on vector layers, not their own layer type
DragClipType::Image => AnyLayer::Vector(VectorLayer::new(name)),
DragClipType::Effect => AnyLayer::Effect(EffectLayer::new(name)),
}
}
@@ -6,8 +6,9 @@
use eframe::egui;
use lightningbeam_core::action::Action;
use lightningbeam_core::clip::ClipInstance;
use lightningbeam_core::gpu::{BufferPool, Compositor};
use lightningbeam_core::gpu::{BufferPool, BufferFormat, BufferSpec, Compositor, EffectProcessor, HDR_FORMAT};
use lightningbeam_core::layer::{AnyLayer, AudioLayer, AudioLayerType, VideoLayer, VectorLayer};
use lightningbeam_core::renderer::RenderedLayerType;
use super::{DragClipType, NodePath, PaneRenderer, SharedPaneState};
use std::sync::{Arc, Mutex, OnceLock};
use vello::kurbo::Shape;
@@ -32,6 +33,8 @@ struct SharedVelloResources {
buffer_pool: Mutex<BufferPool>,
/// Compositor for layer blending
compositor: Compositor,
/// Effect processor for GPU shader effects
effect_processor: Mutex<EffectProcessor>,
}
/// Per-instance Vello resources (created for each Stage pane)
@@ -196,7 +199,10 @@ impl SharedVelloResources {
// Use HDR format for internal compositing
let compositor = Compositor::new(device, lightningbeam_core::gpu::HDR_FORMAT);
println!("✅ Vello shared resources initialized (renderer, shaders, and HDR compositor)");
// Initialize effect processor for GPU shader effects
let effect_processor = EffectProcessor::new(device, lightningbeam_core::gpu::HDR_FORMAT);
println!("✅ Vello shared resources initialized (renderer, shaders, HDR compositor, and effect processor)");
Ok(Self {
renderer: Arc::new(Mutex::new(renderer)),
@@ -208,6 +214,7 @@ impl SharedVelloResources {
video_manager,
buffer_pool: Mutex::new(buffer_pool),
compositor,
effect_processor: Mutex::new(effect_processor),
})
}
}
@@ -490,47 +497,144 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
}
buffer_pool.release(bg_handle);
// HDR buffer spec for effect processing
let hdr_spec = BufferSpec::new(width, height, BufferFormat::Rgba16Float);
// Lock effect processor
let mut effect_processor = shared.effect_processor.lock().unwrap();
// Now render and composite each layer incrementally
for rendered_layer in &composite_result.layers {
if !rendered_layer.has_content {
continue;
}
// Acquire a buffer for this layer
let layer_handle = buffer_pool.acquire(device, layer_spec);
match &rendered_layer.layer_type {
RenderedLayerType::Content => {
// Regular content layer - render and composite as before
let layer_handle = buffer_pool.acquire(device, layer_spec);
if let (Some(layer_view), Some(hdr_view)) = (buffer_pool.get_view(layer_handle), &instance_resources.hdr_texture_view) {
// Render layer scene to buffer
if let Ok(mut renderer) = shared.renderer.lock() {
renderer.render_to_texture(device, queue, &rendered_layer.scene, layer_view, &layer_render_params).ok();
if let (Some(layer_view), Some(hdr_view)) = (buffer_pool.get_view(layer_handle), &instance_resources.hdr_texture_view) {
// Render layer scene to buffer
if let Ok(mut renderer) = shared.renderer.lock() {
renderer.render_to_texture(device, queue, &rendered_layer.scene, layer_view, &layer_render_params).ok();
}
// Composite this layer onto the HDR accumulator with its opacity
let compositor_layer = lightningbeam_core::gpu::CompositorLayer::new(
layer_handle,
rendered_layer.opacity,
rendered_layer.blend_mode,
);
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("layer_composite_encoder"),
});
shared.compositor.composite(
device,
queue,
&mut encoder,
&[compositor_layer],
&buffer_pool,
hdr_view,
None, // Don't clear - blend onto existing content
);
queue.submit(Some(encoder.finish()));
}
buffer_pool.release(layer_handle);
}
RenderedLayerType::Effect { effect_instances } => {
// Effect layer - apply effects to the current HDR accumulator
let current_time = self.document.current_time;
// Composite this layer onto the HDR accumulator with its opacity
let compositor_layer = lightningbeam_core::gpu::CompositorLayer::new(
layer_handle,
rendered_layer.opacity,
rendered_layer.blend_mode,
);
for effect_instance in effect_instances {
// Get effect definition from document
let Some(effect_def) = self.document.get_effect_definition(&effect_instance.clip_id) else {
println!("Effect definition not found for clip_id: {:?}", effect_instance.clip_id);
continue;
};
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("layer_composite_encoder"),
});
shared.compositor.composite(
device,
queue,
&mut encoder,
&[compositor_layer],
&buffer_pool,
hdr_view,
None, // Don't clear - blend onto existing content
);
queue.submit(Some(encoder.finish()));
// Compile effect if needed
if !effect_processor.is_compiled(&effect_def.id) {
let success = effect_processor.compile_effect(device, effect_def);
if !success {
eprintln!("Failed to compile effect: {}", effect_def.name);
continue;
}
println!("Compiled effect: {}", effect_def.name);
}
// Create EffectInstance from ClipInstance for the processor
// For now, create a simple effect instance with default parameters
let effect_inst = lightningbeam_core::effect::EffectInstance::new(
effect_def,
effect_instance.timeline_start,
effect_instance.timeline_start + effect_instance.effective_duration(lightningbeam_core::effect::EFFECT_DURATION),
);
// Acquire temp buffer for effect output (HDR format)
let effect_output_handle = buffer_pool.acquire(device, hdr_spec);
if let (Some(hdr_view), Some(effect_output_view)) = (
&instance_resources.hdr_texture_view,
buffer_pool.get_view(effect_output_handle),
) {
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("effect_encoder"),
});
// Apply effect: HDR accumulator → effect output buffer
let applied = effect_processor.apply_effect(
device,
queue,
&mut encoder,
effect_def,
&effect_inst,
hdr_view,
effect_output_view,
width,
height,
current_time,
);
if applied {
queue.submit(Some(encoder.finish()));
// Copy effect output back to HDR accumulator
// We need to blit the effect result back to the HDR texture
let mut copy_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("effect_copy_encoder"),
});
// Use compositor to copy (with opacity 1.0, replacing content)
let effect_layer = lightningbeam_core::gpu::CompositorLayer::normal(
effect_output_handle,
rendered_layer.opacity, // Apply effect layer opacity
);
shared.compositor.composite(
device,
queue,
&mut copy_encoder,
&[effect_layer],
&buffer_pool,
hdr_view,
Some([0.0, 0.0, 0.0, 0.0]), // Clear with transparent (we're replacing)
);
queue.submit(Some(copy_encoder.finish()));
} else {
eprintln!("Effect {} failed to apply", effect_def.name);
}
}
buffer_pool.release(effect_output_handle);
}
}
}
// Release buffer immediately - it can be reused for next layer
buffer_pool.release(layer_handle);
}
drop(effect_processor);
// Advance frame counter for buffer cleanup
buffer_pool.next_frame();
drop(buffer_pool);
@@ -4982,6 +5086,7 @@ impl PaneRenderer for StagePane {
DragClipType::AudioSampled => "Audio",
DragClipType::AudioMidi => "MIDI",
DragClipType::Image => "Image",
DragClipType::Effect => "Effect",
});
let new_layer = super::create_layer_for_clip_type(dragging.clip_type, &layer_name);
@@ -5030,6 +5135,30 @@ impl PaneRenderer for StagePane {
shape_instance,
);
shared.pending_actions.push(Box::new(action));
} else if dragging.clip_type == DragClipType::Effect {
// Handle effect drops specially
// Get effect definition from registry or document
let effect_def = lightningbeam_core::effect_registry::EffectRegistry::get_by_id(&dragging.clip_id)
.or_else(|| shared.action_executor.document().get_effect_definition(&dragging.clip_id).cloned());
if let Some(def) = effect_def {
// Ensure effect definition is in document (copy from registry if built-in)
if shared.action_executor.document().get_effect_definition(&def.id).is_none() {
shared.action_executor.document_mut().add_effect_definition(def.clone());
}
// Create clip instance for effect with 5 second default duration
let clip_instance = ClipInstance::new(def.id)
.with_timeline_start(drop_time)
.with_timeline_duration(5.0);
// Use AddEffectAction for effect layers
let action = lightningbeam_core::actions::AddEffectAction::new(
layer_id,
clip_instance,
);
shared.pending_actions.push(Box::new(action));
}
} else {
// For clips, create a clip instance
let mut clip_instance = ClipInstance::new(dragging.clip_id)
@@ -68,6 +68,7 @@ fn can_drop_on_layer(layer: &AnyLayer, clip_type: DragClipType) -> bool {
(AnyLayer::Audio(audio), DragClipType::AudioMidi) => {
audio.audio_layer_type == AudioLayerType::Midi
}
(AnyLayer::Effect(_), DragClipType::Effect) => true,
_ => false,
}
}
@@ -171,6 +172,7 @@ impl TimelinePane {
lightningbeam_core::layer::AnyLayer::Vector(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Audio(al) => &al.clip_instances,
lightningbeam_core::layer::AnyLayer::Video(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Effect(el) => &el.clip_instances,
};
// Check each clip instance
@@ -185,6 +187,9 @@ impl TimelinePane {
lightningbeam_core::layer::AnyLayer::Video(_) => {
document.get_video_clip(&clip_instance.clip_id).map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Effect(_) => {
Some(lightningbeam_core::effect::EFFECT_DURATION)
}
}?;
let instance_duration = clip_instance.effective_duration(clip_duration);
@@ -860,6 +865,7 @@ impl TimelinePane {
}
}
lightningbeam_core::layer::AnyLayer::Video(_) => ("Video", egui::Color32::from_rgb(180, 100, 255)), // Purple
lightningbeam_core::layer::AnyLayer::Effect(_) => ("Effect", egui::Color32::from_rgb(255, 100, 180)), // Pink
};
// Color indicator bar on the left edge
@@ -1154,6 +1160,7 @@ impl TimelinePane {
lightningbeam_core::layer::AnyLayer::Vector(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Audio(al) => &al.clip_instances,
lightningbeam_core::layer::AnyLayer::Video(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Effect(el) => &el.clip_instances,
};
for clip_instance in clip_instances {
@@ -1171,6 +1178,9 @@ impl TimelinePane {
document.get_video_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Effect(_) => {
Some(lightningbeam_core::effect::EFFECT_DURATION)
}
};
if let Some(clip_duration) = clip_duration {
@@ -1329,6 +1339,10 @@ impl TimelinePane {
egui::Color32::from_rgb(150, 80, 220), // Purple
egui::Color32::from_rgb(200, 150, 255), // Bright purple
),
lightningbeam_core::layer::AnyLayer::Effect(_) => (
egui::Color32::from_rgb(220, 80, 160), // Pink
egui::Color32::from_rgb(255, 120, 200), // Bright pink
),
};
let clip_rect = egui::Rect::from_min_max(
@@ -1552,6 +1566,7 @@ impl TimelinePane {
lightningbeam_core::layer::AnyLayer::Vector(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Audio(al) => &al.clip_instances,
lightningbeam_core::layer::AnyLayer::Video(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Effect(el) => &el.clip_instances,
};
// Check if click is within any clip instance
@@ -1570,6 +1585,9 @@ impl TimelinePane {
document.get_video_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Effect(_) => {
Some(lightningbeam_core::effect::EFFECT_DURATION)
}
};
if let Some(clip_duration) = clip_duration {
@@ -1678,6 +1696,7 @@ impl TimelinePane {
lightningbeam_core::layer::AnyLayer::Vector(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Audio(al) => &al.clip_instances,
lightningbeam_core::layer::AnyLayer::Video(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Effect(el) => &el.clip_instances,
};
// Find selected clip instances in this layer
@@ -1734,6 +1753,9 @@ impl TimelinePane {
lightningbeam_core::layer::AnyLayer::Video(vl) => {
&vl.clip_instances
}
lightningbeam_core::layer::AnyLayer::Effect(el) => {
&el.clip_instances
}
};
// Find selected clip instances in this layer
@@ -1756,6 +1778,9 @@ impl TimelinePane {
.get_video_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Effect(_) => {
Some(lightningbeam_core::effect::EFFECT_DURATION)
}
};
if let Some(clip_duration) = clip_duration {
@@ -2113,6 +2138,7 @@ impl PaneRenderer for TimelinePane {
lightningbeam_core::layer::AnyLayer::Vector(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Audio(al) => &al.clip_instances,
lightningbeam_core::layer::AnyLayer::Video(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Effect(el) => &el.clip_instances,
};
for clip_instance in clip_instances {
@@ -2130,6 +2156,9 @@ impl PaneRenderer for TimelinePane {
document.get_video_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Effect(_) => {
Some(lightningbeam_core::effect::EFFECT_DURATION)
}
};
if let Some(clip_duration) = clip_duration {
@@ -2357,103 +2386,216 @@ impl PaneRenderer for TimelinePane {
let layer_id = layer.id();
let drop_time = self.x_to_time(pointer_pos.x - content_rect.min.x).max(0.0);
// Get document dimensions for centering and create clip instance
let (center_x, center_y, mut clip_instance) = {
let doc = shared.action_executor.document();
let center_x = doc.width / 2.0;
let center_y = doc.height / 2.0;
// Handle effect drops specially
if dragging.clip_type == DragClipType::Effect {
// Get effect definition from registry or document
let effect_def = lightningbeam_core::effect_registry::EffectRegistry::get_by_id(&dragging.clip_id)
.or_else(|| shared.action_executor.document().get_effect_definition(&dragging.clip_id).cloned());
let mut clip_instance = ClipInstance::new(dragging.clip_id)
.with_timeline_start(drop_time);
if let Some(def) = effect_def {
// Ensure effect definition is in document (copy from registry if built-in)
if shared.action_executor.document().get_effect_definition(&def.id).is_none() {
shared.action_executor.document_mut().add_effect_definition(def.clone());
}
// For video clips, scale to fill document dimensions
if dragging.clip_type == DragClipType::Video {
if let Some((video_width, video_height)) = dragging.dimensions {
// Calculate scale to fill document
let scale_x = doc.width / video_width;
let scale_y = doc.height / video_height;
// Create clip instance for effect with 5 second default duration
let clip_instance = ClipInstance::new(def.id)
.with_timeline_start(drop_time)
.with_timeline_duration(5.0);
clip_instance.transform.scale_x = scale_x;
clip_instance.transform.scale_y = scale_y;
// Use AddEffectAction for effect layers
let action = lightningbeam_core::actions::AddEffectAction::new(
layer_id,
clip_instance,
);
shared.pending_actions.push(Box::new(action));
}
// Position at (0, 0) to center the scaled video
// (scaled dimensions = document dimensions, so top-left at origin centers it)
clip_instance.transform.x = 0.0;
clip_instance.transform.y = 0.0;
// Clear drag state
*shared.dragging_asset = None;
} else {
// Get document dimensions for centering and create clip instance
let (center_x, center_y, mut clip_instance) = {
let doc = shared.action_executor.document();
let center_x = doc.width / 2.0;
let center_y = doc.height / 2.0;
let mut clip_instance = ClipInstance::new(dragging.clip_id)
.with_timeline_start(drop_time);
// For video clips, scale to fill document dimensions
if dragging.clip_type == DragClipType::Video {
if let Some((video_width, video_height)) = dragging.dimensions {
// Calculate scale to fill document
let scale_x = doc.width / video_width;
let scale_y = doc.height / video_height;
clip_instance.transform.scale_x = scale_x;
clip_instance.transform.scale_y = scale_y;
// Position at (0, 0) to center the scaled video
// (scaled dimensions = document dimensions, so top-left at origin centers it)
clip_instance.transform.x = 0.0;
clip_instance.transform.y = 0.0;
} else {
// No dimensions available, use document center
clip_instance.transform.x = center_x;
clip_instance.transform.y = center_y;
}
} else {
// No dimensions available, use document center
// Non-video clips: center at document center
clip_instance.transform.x = center_x;
clip_instance.transform.y = center_y;
}
(center_x, center_y, clip_instance)
}; // doc is dropped here
// Save instance ID for potential grouping
let video_instance_id = clip_instance.id;
// Create and queue action for video
let action = lightningbeam_core::actions::AddClipInstanceAction::new(
layer_id,
clip_instance,
);
shared.pending_actions.push(Box::new(action));
// If video has linked audio, auto-place it and create group
if let Some(linked_audio_clip_id) = dragging.linked_audio_clip_id {
eprintln!("DEBUG: Video has linked audio clip: {}", linked_audio_clip_id);
// Find or create sampled audio track where the audio won't overlap
let audio_layer_id = {
let doc = shared.action_executor.document();
let result = find_sampled_audio_track_for_clip(doc, linked_audio_clip_id, drop_time);
if let Some(id) = result {
eprintln!("DEBUG: Found existing audio track without overlap: {}", id);
} else {
eprintln!("DEBUG: No suitable audio track found, will create new one");
}
result
}.unwrap_or_else(|| {
eprintln!("DEBUG: Creating new audio track");
// Create new sampled audio layer
let audio_layer = lightningbeam_core::layer::AudioLayer::new_sampled("Audio Track");
let layer_id = shared.action_executor.document_mut().root.add_child(
lightningbeam_core::layer::AnyLayer::Audio(audio_layer)
);
eprintln!("DEBUG: Created audio layer with ID: {}", layer_id);
layer_id
});
eprintln!("DEBUG: Using audio layer ID: {}", audio_layer_id);
// Create audio clip instance at same timeline position
let audio_instance = ClipInstance::new(linked_audio_clip_id)
.with_timeline_start(drop_time);
let audio_instance_id = audio_instance.id;
eprintln!("DEBUG: Created audio instance: {} for clip: {}", audio_instance_id, linked_audio_clip_id);
// Queue audio action
let audio_action = lightningbeam_core::actions::AddClipInstanceAction::new(
audio_layer_id,
audio_instance,
);
shared.pending_actions.push(Box::new(audio_action));
eprintln!("DEBUG: Queued audio action, total pending: {}", shared.pending_actions.len());
// Create instance group linking video and audio
let mut group = lightningbeam_core::instance_group::InstanceGroup::new();
group.add_member(layer_id, video_instance_id);
group.add_member(audio_layer_id, audio_instance_id);
shared.action_executor.document_mut().add_instance_group(group);
eprintln!("DEBUG: Created instance group");
} else {
// Non-video clips: center at document center
clip_instance.transform.x = center_x;
clip_instance.transform.y = center_y;
eprintln!("DEBUG: Video has NO linked audio clip!");
}
(center_x, center_y, clip_instance)
}; // doc is dropped here
// Clear drag state
*shared.dragging_asset = None;
}
}
} else {
// No existing layer at this position - show "create new layer" indicator
// and handle drop to create a new layer
let layer_y = content_rect.min.y + hovered_layer_index as f32 * LAYER_HEIGHT - self.viewport_scroll_y;
let highlight_rect = egui::Rect::from_min_size(
egui::pos2(content_rect.min.x, layer_y),
egui::vec2(content_rect.width(), LAYER_HEIGHT),
);
// Save instance ID for potential grouping
let video_instance_id = clip_instance.id;
// Blue highlight for "will create new layer"
ui.painter().rect_filled(
highlight_rect,
0.0,
egui::Color32::from_rgba_unmultiplied(100, 150, 255, 40),
);
// Create and queue action for video
let action = lightningbeam_core::actions::AddClipInstanceAction::new(
layer_id,
clip_instance,
// Show drop time indicator
let drop_time = self.x_to_time(pointer_pos.x - content_rect.min.x).max(0.0);
let drop_x = self.time_to_x(drop_time);
if drop_x >= 0.0 && drop_x <= content_rect.width() {
ui.painter().line_segment(
[
egui::pos2(content_rect.min.x + drop_x, layer_y),
egui::pos2(content_rect.min.x + drop_x, layer_y + LAYER_HEIGHT),
],
egui::Stroke::new(2.0, egui::Color32::WHITE),
);
shared.pending_actions.push(Box::new(action));
}
// If video has linked audio, auto-place it and create group
if let Some(linked_audio_clip_id) = dragging.linked_audio_clip_id {
eprintln!("DEBUG: Video has linked audio clip: {}", linked_audio_clip_id);
// Handle drop on mouse release - create new layer
if ui.input(|i| i.pointer.any_released()) {
let drop_time = self.x_to_time(pointer_pos.x - content_rect.min.x).max(0.0);
// Find or create sampled audio track where the audio won't overlap
let audio_layer_id = {
let doc = shared.action_executor.document();
let result = find_sampled_audio_track_for_clip(doc, linked_audio_clip_id, drop_time);
if let Some(id) = result {
eprintln!("DEBUG: Found existing audio track without overlap: {}", id);
} else {
eprintln!("DEBUG: No suitable audio track found, will create new one");
// Create the appropriate layer type
let layer_name = format!("{} Layer", match dragging.clip_type {
DragClipType::Vector => "Vector",
DragClipType::Video => "Video",
DragClipType::AudioSampled => "Audio",
DragClipType::AudioMidi => "MIDI",
DragClipType::Image => "Image",
DragClipType::Effect => "Effect",
});
let new_layer = super::create_layer_for_clip_type(dragging.clip_type, &layer_name);
let new_layer_id = new_layer.id();
// Add the layer
shared.action_executor.document_mut().root.add_child(new_layer);
// Now add the clip to the new layer
if dragging.clip_type == DragClipType::Effect {
// Handle effect drops
let effect_def = lightningbeam_core::effect_registry::EffectRegistry::get_by_id(&dragging.clip_id)
.or_else(|| shared.action_executor.document().get_effect_definition(&dragging.clip_id).cloned());
if let Some(def) = effect_def {
if shared.action_executor.document().get_effect_definition(&def.id).is_none() {
shared.action_executor.document_mut().add_effect_definition(def.clone());
}
result
}.unwrap_or_else(|| {
eprintln!("DEBUG: Creating new audio track");
// Create new sampled audio layer
let audio_layer = lightningbeam_core::layer::AudioLayer::new_sampled("Audio Track");
let layer_id = shared.action_executor.document_mut().root.add_child(
lightningbeam_core::layer::AnyLayer::Audio(audio_layer)
let clip_instance = ClipInstance::new(def.id)
.with_timeline_start(drop_time)
.with_timeline_duration(5.0);
let action = lightningbeam_core::actions::AddEffectAction::new(
new_layer_id,
clip_instance,
);
eprintln!("DEBUG: Created audio layer with ID: {}", layer_id);
layer_id
});
eprintln!("DEBUG: Using audio layer ID: {}", audio_layer_id);
// Create audio clip instance at same timeline position
let audio_instance = ClipInstance::new(linked_audio_clip_id)
.with_timeline_start(drop_time);
let audio_instance_id = audio_instance.id;
eprintln!("DEBUG: Created audio instance: {} for clip: {}", audio_instance_id, linked_audio_clip_id);
// Queue audio action
let audio_action = lightningbeam_core::actions::AddClipInstanceAction::new(
audio_layer_id,
audio_instance,
);
shared.pending_actions.push(Box::new(audio_action));
eprintln!("DEBUG: Queued audio action, total pending: {}", shared.pending_actions.len());
// Create instance group linking video and audio
let mut group = lightningbeam_core::instance_group::InstanceGroup::new();
group.add_member(layer_id, video_instance_id);
group.add_member(audio_layer_id, audio_instance_id);
shared.action_executor.document_mut().add_instance_group(group);
eprintln!("DEBUG: Created instance group");
shared.pending_actions.push(Box::new(action));
}
} else {
eprintln!("DEBUG: Video has NO linked audio clip!");
// Handle other clip types
let clip_instance = ClipInstance::new(dragging.clip_id)
.with_timeline_start(drop_time);
let action = lightningbeam_core::actions::AddClipInstanceAction::new(
new_layer_id,
clip_instance,
);
shared.pending_actions.push(Box::new(action));
}
// Clear drag state