| author | |
| committer | |
| log | 0e0496e04ce4737c013b1a715b37cfe35c4aca31 |
| tree | 1b6deccc7c032c0659784be7e23e03133e6c4dc9 |
| parent | 6ec390a237ca3088ca1802ac5ddc53553a3154ce |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
6 files changed, 1802 insertions(+), 92 deletions(-)
crates/engine/src/bin/render_check.rs+178-4| ... | @@ -1,12 +1,13 @@ | ... | @@ -1,12 +1,13 @@ |
| 1 | //! Headless verification, parity+perf suite runner, and batch PNG sequence renderer for `engine`. | 1 | //! Headless verification, parity+perf suite runner, and batch PNG sequence renderer for `engine`. |
| 2 | 2 | ||
| 3 | use engine::export::{ | 3 | use engine::export::{ |
| 4 | VideoCodec, VideoExportOptions, export_node_png_sequence_with_progress, | 4 | ExrCompression, ExrDepth, VideoCodec, VideoExportOptions, export_node_exr_sequence_with_progress, |
| 5 | export_node_video_ffmpeg, write_png_fast_buffered, | 5 | export_node_frame_exr, export_node_png_sequence_with_progress, export_node_video_ffmpeg, |
| 6 | write_png_fast_buffered, | ||
| 6 | }; | 7 | }; |
| 7 | use engine::media::default_media_cache_budget_mb; | 8 | use engine::media::default_media_cache_budget_mb; |
| 8 | use engine::{CacheMode, Engine, ExportOptions, export_saver_png_sequence}; | 9 | use engine::{CacheMode, Engine, ExportOptions, export_saver_png_sequence}; |
| 9 | use model::Comp; | 10 | use model::{Comp, NodeId, SaverSpec}; |
| 10 | use std::collections::HashMap; | 11 | use std::collections::HashMap; |
| 11 | use std::path::{Path, PathBuf}; | 12 | use std::path::{Path, PathBuf}; |
| 12 | use std::time::Instant; | 13 | use std::time::Instant; |
| ... | @@ -349,6 +350,128 @@ fn run_video_export( | ... | @@ -349,6 +350,128 @@ fn run_video_export( |
| 349 | Ok(()) | 350 | Ok(()) |
| 350 | } | 351 | } |
| 351 | 352 | ||
| 353 | fn run_exr_export( | ||
| 354 | comp_path: &Path, | ||
| 355 | out_path: PathBuf, | ||
| 356 | node_name: Option<&str>, | ||
| 357 | range_str: Option<&str>, | ||
| 358 | depth: ExrDepth, | ||
| 359 | proxy_scale: u32, | ||
| 360 | hiq: bool, | ||
| 361 | ) -> Result<(), Box<dyn std::error::Error>> { | ||
| 362 | let comp = Comp::from_fusion_file(comp_path)?; | ||
| 363 | let target = match node_name { | ||
| 364 | Some(n) => comp.find_node(n).ok_or_else(|| format!("no such node {n}"))?, | ||
| 365 | None => comp.default_output_node().ok_or("comp has no nodes")?, | ||
| 366 | }; | ||
| 367 | let is_exr_file = out_path | ||
| 368 | .extension() | ||
| 369 | .and_then(|e| e.to_str()) | ||
| 370 | .is_some_and(|e| e.eq_ignore_ascii_case("exr")); | ||
| 371 | |||
| 372 | let mut engine = Engine::new_headless()?; | ||
| 373 | engine.set_media_budget_mb(default_media_cache_budget_mb()); | ||
| 374 | engine.proxy_scale = proxy_scale; | ||
| 375 | engine.hiq = hiq; | ||
| 376 | |||
| 377 | let parsed_range: Option<([i64; 2], bool)> = match range_str { | ||
| 378 | Some(r) if !r.is_empty() => { | ||
| 379 | if let Some((a, b)) = r.split_once("..") { | ||
| 380 | Some(([a.parse::<i64>()?, b.parse::<i64>()?], false)) | ||
| 381 | } else { | ||
| 382 | let single = r.parse::<i64>()?; | ||
| 383 | Some(([single, single], true)) | ||
| 384 | } | ||
| 385 | } | ||
| 386 | _ => None, | ||
| 387 | }; | ||
| 388 | |||
| 389 | let t_start = Instant::now(); | ||
| 390 | let depth_label = match depth { | ||
| 391 | ExrDepth::Float16 => "f16", | ||
| 392 | ExrDepth::Float32 => "f32", | ||
| 393 | }; | ||
| 394 | |||
| 395 | if is_exr_file && parsed_range.is_none_or(|(_, single)| single) { | ||
| 396 | let frame = parsed_range.map_or(comp.current_time, |(r, _)| r[0] as f64); | ||
| 397 | let saved = export_node_frame_exr( | ||
| 398 | &mut engine, | ||
| 399 | &comp, | ||
| 400 | target, | ||
| 401 | frame, | ||
| 402 | &out_path, | ||
| 403 | depth, | ||
| 404 | ExrCompression::Zip16, | ||
| 405 | ) | ||
| 406 | .map_err(|e| format!("EXR export failed: {e}"))?; | ||
| 407 | eprintln!( | ||
| 408 | "Exported EXR ({depth_label}) frame {frame} in {:.2}s -> {}", | ||
| 409 | t_start.elapsed().as_secs_f64(), | ||
| 410 | saved.display() | ||
| 411 | ); | ||
| 412 | return Ok(()); | ||
| 413 | } | ||
| 414 | |||
| 415 | let range = parsed_range.map_or(comp.render_range, |(r, _)| r); | ||
| 416 | let label = comp.node(target).name.clone(); | ||
| 417 | let template_saver = is_exr_file.then(|| SaverSpec { | ||
| 418 | node_id: NodeId(0), | ||
| 419 | name: label.clone(), | ||
| 420 | upstream: None, | ||
| 421 | filename: out_path.to_string_lossy().into_owned(), | ||
| 422 | range, | ||
| 423 | sequence_start: None, | ||
| 424 | }); | ||
| 425 | let summary = export_node_exr_sequence_with_progress( | ||
| 426 | &mut engine, | ||
| 427 | &comp, | ||
| 428 | target, | ||
| 429 | range, | ||
| 430 | |frame| { | ||
| 431 | if let Some(s) = &template_saver { | ||
| 432 | Ok(s.frame_path(frame)) | ||
| 433 | } else { | ||
| 434 | Ok(out_path.join(format!("{frame:04}.exr"))) | ||
| 435 | } | ||
| 436 | }, | ||
| 437 | label, | ||
| 438 | hiq, | ||
| 439 | proxy_scale, | ||
| 440 | 0, | ||
| 441 | depth, | ||
| 442 | ExrCompression::Zip16, | ||
| 443 | None, | ||
| 444 | |p| { | ||
| 445 | if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total { | ||
| 446 | let elapsed = t_start.elapsed().as_secs_f64().max(1e-6); | ||
| 447 | let fps = (p.index + 1) as f64 / elapsed; | ||
| 448 | eprintln!( | ||
| 449 | " [{:>4}/{}] {} f{:04} | eval={:.1}ms | avg={fps:.1} fps -> {}", | ||
| 450 | p.index + 1, | ||
| 451 | p.total, | ||
| 452 | p.saver_name, | ||
| 453 | p.frame, | ||
| 454 | p.eval_ms, | ||
| 455 | p.out_path.display() | ||
| 456 | ); | ||
| 457 | } | ||
| 458 | }, | ||
| 459 | ) | ||
| 460 | .map_err(|e| format!("EXR sequence export failed: {e}"))?; | ||
| 461 | let secs = (summary.total_ms / 1000.0).max(1e-6); | ||
| 462 | eprintln!( | ||
| 463 | "Exported {} EXR ({depth_label}) frames via {} in {:.2}s ({:.1} fps)", | ||
| 464 | summary.frames_written, | ||
| 465 | summary.saver_name, | ||
| 466 | secs, | ||
| 467 | summary.frames_written as f64 / secs | ||
| 468 | ); | ||
| 469 | if let (Some(first), Some(last)) = (summary.first_path, summary.last_path) { | ||
| 470 | eprintln!(" range: {} .. {}", first.display(), last.display()); | ||
| 471 | } | ||
| 472 | Ok(()) | ||
| 473 | } | ||
| 474 | |||
| 352 | fn main() -> Result<(), Box<dyn std::error::Error>> { | 475 | fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 353 | let args: Vec<String> = std::env::args().collect(); | 476 | let args: Vec<String> = std::env::args().collect(); |
| 354 | if args.len() >= 3 && args[1] == "--suite" { | 477 | if args.len() >= 3 && args[1] == "--suite" { |
| ... | @@ -357,12 +480,63 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { | ... | @@ -357,12 +480,63 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 357 | } | 480 | } |
| 358 | if args.len() < 3 { | 481 | if args.len() < 3 { |
| 359 | eprintln!( | 482 | eprintln!( |
| 360 | "usage:\n render-check <comp.comp> <frame> [--out <out.png>] [--ref <ref.png>] [--node <name>] [--proxy <1|2|4>] [--fast] [--bench] [--profile]\n render-check <comp.comp> --render <start>..<end> --out-dir <dir> [--node <name>] [--proxy <1|2|4>]\n render-check <comp.comp> --export [--saver <name>] [--range <start>..<end>] [--out-dir <dir>] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --export-mp4 <out.mp4> [--node <name>] [--range <start>..<end>] [--crf <u8>] [--max-height <u32>] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --export-prores <out.mov> [--prores-4444] [--node <name>] [--range <start>..<end>] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --roundtrip <out.comp>\n render-check --suite <private/suite.txt> [--fast]" | 483 | "usage:\n render-check <comp.comp> <frame> [--out <out.png>] [--ref <ref.png>] [--node <name>] [--proxy <1|2|4>] [--fast] [--bench] [--profile]\n render-check <comp.comp> --render <start>..<end> --out-dir <dir> [--node <name>] [--proxy <1|2|4>]\n render-check <comp.comp> --export [--saver <name>] [--range <start>..<end>] [--out-dir <dir>] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --export-exr <out_dir_or_file> [--exr-f32] [--node <name>] [--range <start>..<end>] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --export-mp4 <out.mp4> [--node <name>] [--range <start>..<end>] [--crf <u8>] [--max-height <u32>] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --export-prores <out.mov> [--prores-4444] [--node <name>] [--range <start>..<end>] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --roundtrip <out.comp>\n render-check --suite <private/suite.txt> [--fast]" |
| 361 | ); | 484 | ); |
| 362 | std::process::exit(2); | 485 | std::process::exit(2); |
| 363 | } | 486 | } |
| 364 | 487 | ||
| 365 | let comp_path = PathBuf::from(&args[1]); | 488 | let comp_path = PathBuf::from(&args[1]); |
| 489 | if args[2..].iter().any(|a| a == "--export-exr") { | ||
| 490 | let mut out_path: Option<PathBuf> = None; | ||
| 491 | let mut depth = ExrDepth::Float16; | ||
| 492 | let mut node_name: Option<String> = None; | ||
| 493 | let mut range_str: Option<String> = None; | ||
| 494 | let mut proxy_scale = 1u32; | ||
| 495 | let mut hiq = true; | ||
| 496 | let mut i = 2; | ||
| 497 | while i < args.len() { | ||
| 498 | match args[i].as_str() { | ||
| 499 | "--export-exr" if i + 1 < args.len() => { | ||
| 500 | out_path = Some(PathBuf::from(&args[i + 1])); | ||
| 501 | i += 2; | ||
| 502 | } | ||
| 503 | "--exr-f32" => { | ||
| 504 | depth = ExrDepth::Float32; | ||
| 505 | i += 1; | ||
| 506 | } | ||
| 507 | "--node" if i + 1 < args.len() => { | ||
| 508 | node_name = Some(args[i + 1].clone()); | ||
| 509 | i += 2; | ||
| 510 | } | ||
| 511 | "--range" if i + 1 < args.len() => { | ||
| 512 | range_str = Some(args[i + 1].clone()); | ||
| 513 | i += 2; | ||
| 514 | } | ||
| 515 | "--proxy" if i + 1 < args.len() => { | ||
| 516 | proxy_scale = args[i + 1].parse().unwrap_or(1).max(1); | ||
| 517 | i += 2; | ||
| 518 | } | ||
| 519 | "--fast" => { | ||
| 520 | hiq = false; | ||
| 521 | i += 1; | ||
| 522 | } | ||
| 523 | other => { | ||
| 524 | eprintln!("unexpected argument '{other}'"); | ||
| 525 | std::process::exit(2); | ||
| 526 | } | ||
| 527 | } | ||
| 528 | } | ||
| 529 | let out_path = out_path.ok_or("--export-exr requires an output path or directory")?; | ||
| 530 | return run_exr_export( | ||
| 531 | &comp_path, | ||
| 532 | out_path, | ||
| 533 | node_name.as_deref(), | ||
| 534 | range_str.as_deref(), | ||
| 535 | depth, | ||
| 536 | proxy_scale, | ||
| 537 | hiq, | ||
| 538 | ); | ||
| 539 | } | ||
| 366 | if args[2..].iter().any(|a| a == "--export-mp4" || a == "--export-prores") { | 540 | if args[2..].iter().any(|a| a == "--export-mp4" || a == "--export-prores") { |
| 367 | let mut out_path: Option<PathBuf> = None; | 541 | let mut out_path: Option<PathBuf> = None; |
| 368 | let mut codec = VideoCodec::H264Share; | 542 | let mut codec = VideoCodec::H264Share; |
crates/engine/src/eval/dispatch.rs+248-47| ... | @@ -9,7 +9,7 @@ use web_time::Instant; | ... | @@ -9,7 +9,7 @@ use web_time::Instant; |
| 9 | use bytemuck::{Pod, Zeroable}; | 9 | use bytemuck::{Pod, Zeroable}; |
| 10 | use model::BitDepth; | 10 | use model::BitDepth; |
| 11 | 11 | ||
| 12 | use crate::cache::{CachedTexture, EvalStats}; | 12 | use crate::cache::{AuxChannelTex, CachedTexture, EvalStats}; |
| 13 | 13 | ||
| 14 | use super::registry::{ShaderOp, ShaderRegistry}; | 14 | use super::registry::{ShaderOp, ShaderRegistry}; |
| 15 | use super::{DisplaySettings, Engine}; | 15 | use super::{DisplaySettings, Engine}; |
| ... | @@ -40,8 +40,6 @@ pub struct PendingReadback { | ... | @@ -40,8 +40,6 @@ pub struct PendingReadback { |
| 40 | #[cfg(not(target_arch = "wasm32"))] | 40 | #[cfg(not(target_arch = "wasm32"))] |
| 41 | rx: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>, | 41 | rx: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>, |
| 42 | #[cfg(not(target_arch = "wasm32"))] | 42 | #[cfg(not(target_arch = "wasm32"))] |
| 43 | width: u32, | ||
| 44 | #[cfg(not(target_arch = "wasm32"))] | ||
| 45 | height: u32, | 43 | height: u32, |
| 46 | #[cfg(not(target_arch = "wasm32"))] | 44 | #[cfg(not(target_arch = "wasm32"))] |
| 47 | unpadded_bpr: u32, | 45 | unpadded_bpr: u32, |
| ... | @@ -83,9 +81,8 @@ impl PendingReadback { | ... | @@ -83,9 +81,8 @@ impl PendingReadback { |
| 83 | map_res?; | 81 | map_res?; |
| 84 | let slice = self.buf.slice(..self.required_bytes); | 82 | let slice = self.buf.slice(..self.required_bytes); |
| 85 | let data = slice.get_mapped_range()?; | 83 | let data = slice.get_mapped_range()?; |
| 86 | let total_bytes = (self.width as usize) | 84 | let total_bytes = (self.unpadded_bpr as usize) |
| 87 | .checked_mul(self.height as usize) | 85 | .checked_mul(self.height as usize) |
| 88 | .and_then(|n| n.checked_mul(4)) | ||
| 89 | .ok_or("readback buffer size overflow")?; | 86 | .ok_or("readback buffer size overflow")?; |
| 90 | dst.clear(); | 87 | dst.clear(); |
| 91 | dst.reserve(total_bytes); | 88 | dst.reserve(total_bytes); |
| ... | @@ -311,6 +308,76 @@ impl Engine { | ... | @@ -311,6 +308,76 @@ impl Engine { |
| 311 | } | 308 | } |
| 312 | } | 309 | } |
| 313 | 310 | ||
| 311 | #[cfg(not(target_arch = "wasm32"))] | ||
| 312 | fn encode_and_submit_readback( | ||
| 313 | &self, | ||
| 314 | mut enc: wgpu::CommandEncoder, | ||
| 315 | texture: &wgpu::Texture, | ||
| 316 | size: [u32; 2], | ||
| 317 | bpp: u32, | ||
| 318 | ) -> Result<PendingReadback, Box<dyn std::error::Error>> { | ||
| 319 | let [w, h] = size; | ||
| 320 | let unpadded_bpr = w.checked_mul(bpp).ok_or("readback row size overflow")?; | ||
| 321 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; | ||
| 322 | let padded_bpr = unpadded_bpr | ||
| 323 | .div_ceil(align) | ||
| 324 | .checked_mul(align) | ||
| 325 | .ok_or("readback padded row size overflow")?; | ||
| 326 | let required_bytes = u64::from(padded_bpr) | ||
| 327 | .checked_mul(u64::from(h)) | ||
| 328 | .ok_or("readback buffer size overflow")?; | ||
| 329 | let buf = self | ||
| 330 | .pipelines | ||
| 331 | .borrow_mut() | ||
| 332 | .readback_pool | ||
| 333 | .acquire_buffer(&self.device, required_bytes); | ||
| 334 | |||
| 335 | enc.copy_texture_to_buffer( | ||
| 336 | texture.as_image_copy(), | ||
| 337 | wgpu::TexelCopyBufferInfo { | ||
| 338 | buffer: &buf, | ||
| 339 | layout: wgpu::TexelCopyBufferLayout { | ||
| 340 | offset: 0, | ||
| 341 | bytes_per_row: Some(padded_bpr), | ||
| 342 | rows_per_image: Some(h), | ||
| 343 | }, | ||
| 344 | }, | ||
| 345 | wgpu::Extent3d { | ||
| 346 | width: w, | ||
| 347 | height: h, | ||
| 348 | depth_or_array_layers: 1, | ||
| 349 | }, | ||
| 350 | ); | ||
| 351 | let submission_index = self.queue.submit(Some(enc.finish())); | ||
| 352 | self.reset_uniform_cursors(); | ||
| 353 | |||
| 354 | let slice = buf.slice(..required_bytes); | ||
| 355 | let (tx, rx) = std::sync::mpsc::channel(); | ||
| 356 | slice.map_async(wgpu::MapMode::Read, move |res| { | ||
| 357 | let _ = tx.send(res); | ||
| 358 | }); | ||
| 359 | Ok(PendingReadback { | ||
| 360 | buf, | ||
| 361 | submission_index, | ||
| 362 | rx, | ||
| 363 | height: h, | ||
| 364 | unpadded_bpr, | ||
| 365 | padded_bpr, | ||
| 366 | required_bytes, | ||
| 367 | }) | ||
| 368 | } | ||
| 369 | |||
| 370 | #[cfg(not(target_arch = "wasm32"))] | ||
| 371 | pub(crate) fn begin_readback_raw( | ||
| 372 | &self, | ||
| 373 | texture: &wgpu::Texture, | ||
| 374 | size: [u32; 2], | ||
| 375 | bpp: u32, | ||
| 376 | ) -> Result<PendingReadback, Box<dyn std::error::Error>> { | ||
| 377 | let enc = self.device.create_command_encoder(&Default::default()); | ||
| 378 | self.encode_and_submit_readback(enc, texture, size, bpp) | ||
| 379 | } | ||
| 380 | |||
| 314 | /// Starts an asynchronous GPU-to-CPU RGBA8 readback by encoding any Float16/Float32 -> | 381 | /// Starts an asynchronous GPU-to-CPU RGBA8 readback by encoding any Float16/Float32 -> |
| 315 | /// `Rgba8Unorm` conversion plus `copy_texture_to_buffer` into a pooled staging buffer, | 382 | /// `Rgba8Unorm` conversion plus `copy_texture_to_buffer` into a pooled staging buffer, |
| 316 | /// submitting to the queue, and starting `map_async` without polling. | 383 | /// submitting to the queue, and starting `map_async` without polling. |
| ... | @@ -333,18 +400,6 @@ impl Engine { | ... | @@ -333,18 +400,6 @@ impl Engine { |
| 333 | None | 400 | None |
| 334 | }; | 401 | }; |
| 335 | let src_tex = converted.as_ref().unwrap_or(tex); | 402 | let src_tex = converted.as_ref().unwrap_or(tex); |
| 336 | let [w, h] = src_tex.size; | ||
| 337 | let bpp = 4u32; | ||
| 338 | let unpadded_bpr = w * bpp; | ||
| 339 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; | ||
| 340 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; | ||
| 341 | let required_bytes = u64::from(padded_bpr) * u64::from(h); | ||
| 342 | let buf = self | ||
| 343 | .pipelines | ||
| 344 | .borrow_mut() | ||
| 345 | .readback_pool | ||
| 346 | .acquire_buffer(&self.device, required_bytes); | ||
| 347 | |||
| 348 | let mut enc = self.device.create_command_encoder(&Default::default()); | 403 | let mut enc = self.device.create_command_encoder(&Default::default()); |
| 349 | if let Some(conv) = converted.as_ref() { | 404 | if let Some(conv) = converted.as_ref() { |
| 350 | let mut params = UniformParams::default(); | 405 | let mut params = UniformParams::default(); |
| ... | @@ -360,36 +415,7 @@ impl Engine { | ... | @@ -360,36 +415,7 @@ impl Engine { |
| 360 | &params, | 415 | &params, |
| 361 | ); | 416 | ); |
| 362 | } | 417 | } |
| 363 | enc.copy_texture_to_buffer( | 418 | self.encode_and_submit_readback(enc, &src_tex.texture, src_tex.size, 4) |
| 364 | src_tex.texture.as_image_copy(), | ||
| 365 | wgpu::TexelCopyBufferInfo { | ||
| 366 | buffer: &buf, | ||
| 367 | layout: wgpu::TexelCopyBufferLayout { | ||
| 368 | offset: 0, | ||
| 369 | bytes_per_row: Some(padded_bpr), | ||
| 370 | rows_per_image: Some(h), | ||
| 371 | }, | ||
| 372 | }, | ||
| 373 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, | ||
| 374 | ); | ||
| 375 | let submission_index = self.queue.submit(Some(enc.finish())); | ||
| 376 | self.reset_uniform_cursors(); | ||
| 377 | |||
| 378 | let slice = buf.slice(..required_bytes); | ||
| 379 | let (tx, rx) = std::sync::mpsc::channel(); | ||
| 380 | slice.map_async(wgpu::MapMode::Read, move |res| { | ||
| 381 | let _ = tx.send(res); | ||
| 382 | }); | ||
| 383 | Ok(PendingReadback { | ||
| 384 | buf, | ||
| 385 | submission_index, | ||
| 386 | rx, | ||
| 387 | width: w, | ||
| 388 | height: h, | ||
| 389 | unpadded_bpr, | ||
| 390 | padded_bpr, | ||
| 391 | required_bytes, | ||
| 392 | }) | ||
| 393 | } | 419 | } |
| 394 | } | 420 | } |
| 395 | 421 | ||
| ... | @@ -400,6 +426,181 @@ impl Engine { | ... | @@ -400,6 +426,181 @@ impl Engine { |
| 400 | self.begin_readback_rgba(tex)?.finish(self) | 426 | self.begin_readback_rgba(tex)?.finish(self) |
| 401 | } | 427 | } |
| 402 | 428 | ||
| 429 | #[cfg(not(target_arch = "wasm32"))] | ||
| 430 | pub(crate) fn rgba_f32_bpp(format: wgpu::TextureFormat) -> Result<u32, Box<dyn std::error::Error>> { | ||
| 431 | match format { | ||
| 432 | wgpu::TextureFormat::Rgba32Float => Ok(16), | ||
| 433 | wgpu::TextureFormat::Rgba16Float => Ok(8), | ||
| 434 | wgpu::TextureFormat::Rgba8Unorm => Ok(4), | ||
| 435 | other => Err(format!("unsupported texture format for linear f32 readback: {other:?}").into()), | ||
| 436 | } | ||
| 437 | } | ||
| 438 | |||
| 439 | #[cfg(not(target_arch = "wasm32"))] | ||
| 440 | pub(crate) fn decode_rgba_bytes_into_f32( | ||
| 441 | format: wgpu::TextureFormat, | ||
| 442 | size: [u32; 2], | ||
| 443 | raw: &[u8], | ||
| 444 | out: &mut Vec<f32>, | ||
| 445 | ) -> Result<(), Box<dyn std::error::Error>> { | ||
| 446 | let px_count = (size[0] as usize) | ||
| 447 | .checked_mul(size[1] as usize) | ||
| 448 | .ok_or("readback pixel count overflow")?; | ||
| 449 | let float_count = px_count | ||
| 450 | .checked_mul(4) | ||
| 451 | .ok_or("readback float count overflow")?; | ||
| 452 | out.clear(); | ||
| 453 | out.reserve(float_count); | ||
| 454 | match format { | ||
| 455 | wgpu::TextureFormat::Rgba32Float => { | ||
| 456 | let expected = float_count | ||
| 457 | .checked_mul(4) | ||
| 458 | .ok_or("readback byte count overflow")?; | ||
| 459 | if raw.len() != expected { | ||
| 460 | return Err(format!( | ||
| 461 | "Rgba32Float readback size mismatch: expected {expected} bytes, got {}", | ||
| 462 | raw.len() | ||
| 463 | ) | ||
| 464 | .into()); | ||
| 465 | } | ||
| 466 | for c in raw.chunks_exact(4) { | ||
| 467 | out.push(f32::from_le_bytes([c[0], c[1], c[2], c[3]])); | ||
| 468 | } | ||
| 469 | } | ||
| 470 | wgpu::TextureFormat::Rgba16Float => { | ||
| 471 | let expected = float_count | ||
| 472 | .checked_mul(2) | ||
| 473 | .ok_or("readback byte count overflow")?; | ||
| 474 | if raw.len() != expected { | ||
| 475 | return Err(format!( | ||
| 476 | "Rgba16Float readback size mismatch: expected {expected} bytes, got {}", | ||
| 477 | raw.len() | ||
| 478 | ) | ||
| 479 | .into()); | ||
| 480 | } | ||
| 481 | for c in raw.chunks_exact(2) { | ||
| 482 | let bits = u16::from_le_bytes([c[0], c[1]]); | ||
| 483 | out.push(::exr::prelude::f16::from_bits(bits).to_f32()); | ||
| 484 | } | ||
| 485 | } | ||
| 486 | wgpu::TextureFormat::Rgba8Unorm => { | ||
| 487 | if raw.len() != float_count { | ||
| 488 | return Err(format!( | ||
| 489 | "Rgba8Unorm readback size mismatch: expected {float_count} bytes, got {}", | ||
| 490 | raw.len() | ||
| 491 | ) | ||
| 492 | .into()); | ||
| 493 | } | ||
| 494 | for &b in raw { | ||
| 495 | out.push(f32::from(b) / 255.0); | ||
| 496 | } | ||
| 497 | } | ||
| 498 | other => { | ||
| 499 | return Err( | ||
| 500 | format!("unsupported texture format for linear f32 readback: {other:?}").into(), | ||
| 501 | ); | ||
| 502 | } | ||
| 503 | } | ||
| 504 | Ok(()) | ||
| 505 | } | ||
| 506 | |||
| 507 | #[cfg(not(target_arch = "wasm32"))] | ||
| 508 | pub(crate) fn decode_z_bytes_into_f32( | ||
| 509 | size: [u32; 2], | ||
| 510 | raw: &[u8], | ||
| 511 | out: &mut Vec<f32>, | ||
| 512 | ) -> Result<(), Box<dyn std::error::Error>> { | ||
| 513 | let px_count = (size[0] as usize) | ||
| 514 | .checked_mul(size[1] as usize) | ||
| 515 | .ok_or("Z readback pixel count overflow")?; | ||
| 516 | let expected = px_count | ||
| 517 | .checked_mul(4) | ||
| 518 | .ok_or("Z readback byte count overflow")?; | ||
| 519 | if raw.len() != expected { | ||
| 520 | return Err(format!( | ||
| 521 | "R32Float Z readback size mismatch: expected {expected} bytes, got {}", | ||
| 522 | raw.len() | ||
| 523 | ) | ||
| 524 | .into()); | ||
| 525 | } | ||
| 526 | out.clear(); | ||
| 527 | out.reserve(px_count); | ||
| 528 | for c in raw.chunks_exact(4) { | ||
| 529 | out.push(f32::from_le_bytes([c[0], c[1], c[2], c[3]])); | ||
| 530 | } | ||
| 531 | Ok(()) | ||
| 532 | } | ||
| 533 | |||
| 534 | /// Reads back a `CachedTexture` to CPU linear HDR `f32` RGBA samples (`4 floats/px`), | ||
| 535 | /// preserving full float precision (`> 1.0` and negatives) for `Rgba32Float` and `Rgba16Float`. | ||
| 536 | /// Always `Err` on wasm32: a blocking map would trap the browser main thread. | ||
| 537 | pub fn readback_rgba_f32(&self, tex: &CachedTexture) -> Result<Vec<f32>, Box<dyn std::error::Error>> { | ||
| 538 | #[cfg(target_arch = "wasm32")] | ||
| 539 | { | ||
| 540 | let _ = tex; | ||
| 541 | Err("synchronous GPU readback is unavailable on wasm32".into()) | ||
| 542 | } | ||
| 543 | #[cfg(not(target_arch = "wasm32"))] | ||
| 544 | { | ||
| 545 | let bpp = Self::rgba_f32_bpp(tex.format)?; | ||
| 546 | let raw = self.begin_readback_raw(&tex.texture, tex.size, bpp)?.finish(self)?; | ||
| 547 | let mut out = Vec::new(); | ||
| 548 | Self::decode_rgba_bytes_into_f32(tex.format, tex.size, &raw, &mut out)?; | ||
| 549 | Ok(out) | ||
| 550 | } | ||
| 551 | } | ||
| 552 | |||
| 553 | /// Reads back an `R32Float` auxiliary `Z` texture (`4 bytes/px`) into linear `Vec<f32>`, | ||
| 554 | /// preserving exact `-1e30` empty-sky sentinel and negative eye-space depths. | ||
| 555 | /// Always `Err` on wasm32. | ||
| 556 | pub fn readback_aux_z_f32( | ||
| 557 | &self, | ||
| 558 | z_tex: &AuxChannelTex, | ||
| 559 | ) -> Result<Vec<f32>, Box<dyn std::error::Error>> { | ||
| 560 | #[cfg(target_arch = "wasm32")] | ||
| 561 | { | ||
| 562 | let _ = z_tex; | ||
| 563 | Err("synchronous GPU readback is unavailable on wasm32".into()) | ||
| 564 | } | ||
| 565 | #[cfg(not(target_arch = "wasm32"))] | ||
| 566 | { | ||
| 567 | if z_tex.format != wgpu::TextureFormat::R32Float { | ||
| 568 | return Err(format!( | ||
| 569 | "expected R32Float for Z aux channel, got {:?}", | ||
| 570 | z_tex.format | ||
| 571 | ) | ||
| 572 | .into()); | ||
| 573 | } | ||
| 574 | let raw = self.begin_readback_raw(&z_tex.texture, z_tex.size, 4)?.finish(self)?; | ||
| 575 | let mut out = Vec::new(); | ||
| 576 | Self::decode_z_bytes_into_f32(z_tex.size, &raw, &mut out)?; | ||
| 577 | Ok(out) | ||
| 578 | } | ||
| 579 | } | ||
| 580 | |||
| 581 | /// Reads back an RGBA auxiliary channel texture (e.g. `Normal` / `Vector` `Rgba16Float`) | ||
| 582 | /// into linear `Vec<f32>` (`4 floats/px`). Always `Err` on wasm32. | ||
| 583 | pub fn readback_aux_rgba_f32( | ||
| 584 | &self, | ||
| 585 | aux_tex: &AuxChannelTex, | ||
| 586 | ) -> Result<Vec<f32>, Box<dyn std::error::Error>> { | ||
| 587 | #[cfg(target_arch = "wasm32")] | ||
| 588 | { | ||
| 589 | let _ = aux_tex; | ||
| 590 | Err("synchronous GPU readback is unavailable on wasm32".into()) | ||
| 591 | } | ||
| 592 | #[cfg(not(target_arch = "wasm32"))] | ||
| 593 | { | ||
| 594 | let bpp = Self::rgba_f32_bpp(aux_tex.format)?; | ||
| 595 | let raw = self | ||
| 596 | .begin_readback_raw(&aux_tex.texture, aux_tex.size, bpp)? | ||
| 597 | .finish(self)?; | ||
| 598 | let mut out = Vec::new(); | ||
| 599 | Self::decode_rgba_bytes_into_f32(aux_tex.format, aux_tex.size, &raw, &mut out)?; | ||
| 600 | Ok(out) | ||
| 601 | } | ||
| 602 | } | ||
| 603 | |||
| 403 | #[allow(clippy::too_many_arguments)] | 604 | #[allow(clippy::too_many_arguments)] |
| 404 | fn dispatch_with_registry( | 605 | fn dispatch_with_registry( |
| 405 | &self, | 606 | &self, |
crates/engine/src/export.rs+109-4| ... | @@ -1,13 +1,18 @@ | ... | @@ -1,13 +1,18 @@ |
| 1 | //! Saver-driven pipelined PNG sequence export and ffmpeg video export for `Engine`. | 1 | //! Saver-driven pipelined PNG / OpenEXR sequence export and ffmpeg video export for `Engine`. |
| 2 | //! | 2 | //! |
| 3 | //! Evaluates frames on the GPU while encoding lossless RGBA8 PNG files concurrently | 3 | //! Evaluates frames on the GPU while encoding lossless RGBA8 PNG or linear HDR OpenEXR files |
| 4 | //! across a bounded background worker pool, or piping raw RGBA8 frames into `ffmpeg`. | 4 | //! concurrently across a bounded background worker pool, or piping raw RGBA8 frames into `ffmpeg`. |
| 5 | 5 | ||
| 6 | mod exr; | ||
| 6 | mod png; | 7 | mod png; |
| 7 | #[cfg(test)] | 8 | #[cfg(test)] |
| 8 | mod tests; | 9 | mod tests; |
| 9 | mod video; | 10 | mod video; |
| 10 | 11 | ||
| 12 | pub use exr::{ | ||
| 13 | ExrCompression, ExrDepth, export_node_exr_sequence_with_progress, export_node_frame_exr, | ||
| 14 | export_saver_exr_sequence, export_saver_exr_sequence_with_progress, write_exr_rgba_with_aux, | ||
| 15 | }; | ||
| 11 | pub use png::{ | 16 | pub use png::{ |
| 12 | encode_png_rgba8_into, export_node_frame_png, export_node_png_sequence_with_progress, | 17 | encode_png_rgba8_into, export_node_frame_png, export_node_png_sequence_with_progress, |
| 13 | export_saver_png_sequence, export_saver_png_sequence_with_progress, write_png_fast_buffered, | 18 | export_saver_png_sequence, export_saver_png_sequence_with_progress, write_png_fast_buffered, |
| ... | @@ -15,8 +20,9 @@ pub use png::{ | ... | @@ -15,8 +20,9 @@ pub use png::{ |
| 15 | pub use video::{export_node_video_ffmpeg, export_node_video_ffmpeg_with_progress}; | 20 | pub use video::{export_node_video_ffmpeg, export_node_video_ffmpeg_with_progress}; |
| 16 | 21 | ||
| 17 | use crate::cache::EvalStats; | 22 | use crate::cache::EvalStats; |
| 23 | use crate::eval::Engine; | ||
| 18 | use model::{Comp, NodeId, SaverSpec}; | 24 | use model::{Comp, NodeId, SaverSpec}; |
| 19 | use std::path::PathBuf; | 25 | use std::path::{Path, PathBuf}; |
| 20 | use std::sync::atomic::{AtomicBool, Ordering}; | 26 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 21 | use std::sync::{Arc, Mutex}; | 27 | use std::sync::{Arc, Mutex}; |
| 22 | use std::time::Instant; | 28 | use std::time::Instant; |
| ... | @@ -177,6 +183,105 @@ pub fn select_saver(comp: &Comp, saver_name: Option<&str>) -> Result<SaverSpec, | ... | @@ -177,6 +183,105 @@ pub fn select_saver(comp: &Comp, saver_name: Option<&str>) -> Result<SaverSpec, |
| 177 | Ok(savers[0].clone()) | 183 | Ok(savers[0].clone()) |
| 178 | } | 184 | } |
| 179 | 185 | ||
| 186 | pub(super) fn resolve_output_path_with_ext( | ||
| 187 | saver: &SaverSpec, | ||
| 188 | frame: i64, | ||
| 189 | out_dir_override: Option<&Path>, | ||
| 190 | default_ext: &str, | ||
| 191 | ) -> Result<PathBuf, String> { | ||
| 192 | if saver.filename.is_empty() { | ||
| 193 | let dir = out_dir_override.ok_or_else(|| { | ||
| 194 | format!( | ||
| 195 | "Saver '{}' has no Clip.Filename set (pass an output directory override or configure Clip.Filename)", | ||
| 196 | saver.name | ||
| 197 | ) | ||
| 198 | })?; | ||
| 199 | return Ok(dir.join(format!("{frame:04}.{default_ext}"))); | ||
| 200 | } | ||
| 201 | let frame_path = saver.frame_path(frame); | ||
| 202 | if let Some(dir) = out_dir_override { | ||
| 203 | let fname = frame_path | ||
| 204 | .file_name() | ||
| 205 | .map(PathBuf::from) | ||
| 206 | .unwrap_or_else(|| PathBuf::from(format!("{frame:04}.{default_ext}"))); | ||
| 207 | Ok(dir.join(fname)) | ||
| 208 | } else { | ||
| 209 | Ok(frame_path) | ||
| 210 | } | ||
| 211 | } | ||
| 212 | |||
| 213 | pub(super) fn ensure_parent_dir( | ||
| 214 | path: &Path, | ||
| 215 | last_parent: &mut Option<PathBuf>, | ||
| 216 | ) -> Result<(), String> { | ||
| 217 | if let Some(parent) = path.parent() | ||
| 218 | && !parent.as_os_str().is_empty() | ||
| 219 | && last_parent.as_deref() != Some(parent) | ||
| 220 | { | ||
| 221 | std::fs::create_dir_all(parent) | ||
| 222 | .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?; | ||
| 223 | *last_parent = Some(parent.to_path_buf()); | ||
| 224 | } | ||
| 225 | Ok(()) | ||
| 226 | } | ||
| 227 | |||
| 228 | fn saver_targets_exr(comp: &Comp, saver: &SaverSpec, out_dir_override: Option<&Path>) -> bool { | ||
| 229 | let node = comp.node(saver.node_id); | ||
| 230 | if node | ||
| 231 | .static_str("OutputFormat") | ||
| 232 | .is_some_and(|s| s.eq_ignore_ascii_case("OpenEXRFormat")) | ||
| 233 | { | ||
| 234 | return true; | ||
| 235 | } | ||
| 236 | if node | ||
| 237 | .raw | ||
| 238 | .get_table("Inputs") | ||
| 239 | .and_then(|i| i.get_table("Clip")) | ||
| 240 | .and_then(|c| c.get_table("Value")) | ||
| 241 | .and_then(|v| v.get_str("FormatID")) | ||
| 242 | .is_some_and(|s| s.eq_ignore_ascii_case("OpenEXRFormat")) | ||
| 243 | { | ||
| 244 | return true; | ||
| 245 | } | ||
| 246 | resolve_output_path_with_ext(saver, saver.range[0], out_dir_override, "png").is_ok_and(|p| { | ||
| 247 | p.extension() | ||
| 248 | .and_then(|e| e.to_str()) | ||
| 249 | .is_some_and(|e| e.eq_ignore_ascii_case("exr")) | ||
| 250 | }) | ||
| 251 | } | ||
| 252 | |||
| 253 | /// Renders and writes an image sequence driven by a Fusion `Saver` node, dispatching | ||
| 254 | /// automatically to linear HDR OpenEXR (`OpenEXRFormat` / `.exr`) or lossless PNG. | ||
| 255 | pub fn export_saver_sequence( | ||
| 256 | engine: &mut Engine, | ||
| 257 | comp: &Comp, | ||
| 258 | opts: &ExportOptions, | ||
| 259 | on_progress: impl FnMut(&ExportProgress), | ||
| 260 | ) -> Result<ExportSummary, String> { | ||
| 261 | export_saver_sequence_with_progress(engine, comp, opts, None, on_progress) | ||
| 262 | } | ||
| 263 | |||
| 264 | /// Renders and writes an image sequence driven by a Fusion `Saver` node with cooperative | ||
| 265 | /// cancellation and live progress reporting, dispatching automatically to linear HDR OpenEXR | ||
| 266 | /// (`OpenEXRFormat` / `.exr`) or lossless PNG. | ||
| 267 | pub fn export_saver_sequence_with_progress( | ||
| 268 | engine: &mut Engine, | ||
| 269 | comp: &Comp, | ||
| 270 | opts: &ExportOptions, | ||
| 271 | control: Option<&ExportControl>, | ||
| 272 | on_progress: impl FnMut(&ExportProgress), | ||
| 273 | ) -> Result<ExportSummary, String> { | ||
| 274 | if control.is_some_and(ExportControl::is_cancelled) { | ||
| 275 | return Err("Cancelled".to_owned()); | ||
| 276 | } | ||
| 277 | let saver = select_saver(comp, opts.saver_name.as_deref())?; | ||
| 278 | if saver_targets_exr(comp, &saver, opts.out_dir_override.as_deref()) { | ||
| 279 | exr::export_saver_exr_sequence_with_progress(engine, comp, opts, control, on_progress) | ||
| 280 | } else { | ||
| 281 | png::export_saver_png_only_sequence_with_progress(engine, comp, opts, control, on_progress) | ||
| 282 | } | ||
| 283 | } | ||
| 284 | |||
| 180 | /// Output video codec profile for direct viewer / node ffmpeg export. | 285 | /// Output video codec profile for direct viewer / node ffmpeg export. |
| 181 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 286 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 182 | pub enum VideoCodec { | 287 | pub enum VideoCodec { |
crates/engine/src/export/exr.rs created+742| ... | @@ -0,0 +1,742 @@ | ||
| 1 | //! Linear HDR OpenEXR (`f16` / `f32` + `Z` / `Normal` auxiliary channels) encoding | ||
| 2 | //! and pipelined multi-threaded sequence export. | ||
| 3 | |||
| 4 | use super::{ | ||
| 5 | ExportControl, ExportOptions, ExportProgress, ExportSummary, ensure_parent_dir, make_progress, | ||
| 6 | resolve_output_path_with_ext, select_saver, | ||
| 7 | }; | ||
| 8 | use crate::cache::EvalStats; | ||
| 9 | use crate::eval::{Engine, PendingReadback}; | ||
| 10 | use ::exr::prelude::{ | ||
| 11 | AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, Image, Layer, | ||
| 12 | LayerAttributes, LineOrder, SmallVec, Vec2, WritableImage, f16, | ||
| 13 | }; | ||
| 14 | use model::{Comp, NodeId}; | ||
| 15 | use std::io::Cursor; | ||
| 16 | use std::path::{Path, PathBuf}; | ||
| 17 | use std::sync::atomic::{AtomicBool, Ordering}; | ||
| 18 | use std::sync::{Arc, Mutex, mpsc}; | ||
| 19 | use std::time::Instant; | ||
| 20 | |||
| 21 | /// Sample bit depth for OpenEXR RGBA (and `Normal`) channels, matching Fusion's | ||
| 22 | /// `OpenEXRFormat.Depth` (`0` = Float16 default, `1` = Float32). | ||
| 23 | /// | ||
| 24 | /// Note: auxiliary `Z` depth is always written as `f32` so `-1e30` sky sentinels | ||
| 25 | /// and negative eye-space depths never overflow `f16`. | ||
| 26 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] | ||
| 27 | pub enum ExrDepth { | ||
| 28 | #[default] | ||
| 29 | Float16, | ||
| 30 | Float32, | ||
| 31 | } | ||
| 32 | |||
| 33 | impl ExrDepth { | ||
| 34 | pub fn from_fusion_code(code: i32) -> Self { | ||
| 35 | match code { | ||
| 36 | 1 => Self::Float32, | ||
| 37 | _ => Self::Float16, | ||
| 38 | } | ||
| 39 | } | ||
| 40 | } | ||
| 41 | |||
| 42 | /// OpenEXR scanline compression mode matching Fusion's `OpenEXRFormat.Compression` (`0..=5`). | ||
| 43 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] | ||
| 44 | pub enum ExrCompression { | ||
| 45 | Uncompressed, | ||
| 46 | Rle, | ||
| 47 | Zip1, | ||
| 48 | #[default] | ||
| 49 | Zip16, | ||
| 50 | Piz, | ||
| 51 | Pxr24, | ||
| 52 | } | ||
| 53 | |||
| 54 | impl ExrCompression { | ||
| 55 | pub fn from_fusion_code(code: i32) -> Self { | ||
| 56 | match code { | ||
| 57 | 0 => Self::Uncompressed, | ||
| 58 | 1 => Self::Rle, | ||
| 59 | 2 => Self::Zip1, | ||
| 60 | 3 => Self::Zip16, | ||
| 61 | 4 => Self::Piz, | ||
| 62 | 5 => Self::Pxr24, | ||
| 63 | _ => Self::Zip16, | ||
| 64 | } | ||
| 65 | } | ||
| 66 | |||
| 67 | fn to_exr(self) -> Compression { | ||
| 68 | match self { | ||
| 69 | Self::Uncompressed => Compression::Uncompressed, | ||
| 70 | Self::Rle => Compression::RLE, | ||
| 71 | Self::Zip1 => Compression::ZIP1, | ||
| 72 | Self::Zip16 => Compression::ZIP16, | ||
| 73 | Self::Piz => Compression::PIZ, | ||
| 74 | Self::Pxr24 => Compression::PXR24, | ||
| 75 | } | ||
| 76 | } | ||
| 77 | } | ||
| 78 | |||
| 79 | fn push_strided_channel( | ||
| 80 | channels: &mut SmallVec<[AnyChannel<FlatSamples>; 4]>, | ||
| 81 | name: &'static str, | ||
| 82 | src: &[f32], | ||
| 83 | stride: usize, | ||
| 84 | offset: usize, | ||
| 85 | px_count: usize, | ||
| 86 | depth: ExrDepth, | ||
| 87 | ) { | ||
| 88 | let iter = (0..px_count).map(|i| src[i * stride + offset]); | ||
| 89 | let samples = match depth { | ||
| 90 | ExrDepth::Float16 => FlatSamples::F16(iter.map(f16::from_f32).collect()), | ||
| 91 | ExrDepth::Float32 => FlatSamples::F32(iter.collect()), | ||
| 92 | }; | ||
| 93 | channels.push(AnyChannel::new(name, samples)); | ||
| 94 | } | ||
| 95 | |||
| 96 | #[allow(clippy::too_many_arguments)] | ||
| 97 | fn encode_exr_rgba_with_aux_into( | ||
| 98 | size: [u32; 2], | ||
| 99 | rgba_f32: &[f32], | ||
| 100 | z_f32: Option<&[f32]>, | ||
| 101 | normal_f32: Option<&[f32]>, | ||
| 102 | depth: ExrDepth, | ||
| 103 | compression: ExrCompression, | ||
| 104 | out: &mut Vec<u8>, | ||
| 105 | parallel: bool, | ||
| 106 | ) -> Result<(), String> { | ||
| 107 | let [w, h] = size; | ||
| 108 | if w == 0 || h == 0 { | ||
| 109 | return Err(format!("invalid EXR dimensions {w}x{h}")); | ||
| 110 | } | ||
| 111 | let px_count = (w as usize) | ||
| 112 | .checked_mul(h as usize) | ||
| 113 | .ok_or_else(|| format!("EXR dimensions {w}x{h} overflow"))?; | ||
| 114 | let rgba_len = px_count | ||
| 115 | .checked_mul(4) | ||
| 116 | .ok_or_else(|| format!("EXR RGBA size overflow for {w}x{h}"))?; | ||
| 117 | if rgba_f32.len() != rgba_len { | ||
| 118 | return Err(format!( | ||
| 119 | "EXR RGBA slice length mismatch: expected {rgba_len}, got {}", | ||
| 120 | rgba_f32.len() | ||
| 121 | )); | ||
| 122 | } | ||
| 123 | if let Some(z) = z_f32 | ||
| 124 | && z.len() != px_count | ||
| 125 | { | ||
| 126 | return Err(format!( | ||
| 127 | "EXR Z slice length mismatch: expected {px_count}, got {}", | ||
| 128 | z.len() | ||
| 129 | )); | ||
| 130 | } | ||
| 131 | if let Some(n) = normal_f32 | ||
| 132 | && n.len() != rgba_len | ||
| 133 | { | ||
| 134 | return Err(format!( | ||
| 135 | "EXR Normal slice length mismatch: expected {rgba_len}, got {}", | ||
| 136 | n.len() | ||
| 137 | )); | ||
| 138 | } | ||
| 139 | |||
| 140 | let mut channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new(); | ||
| 141 | for (offset, name) in [(0, "R"), (1, "G"), (2, "B"), (3, "A")] { | ||
| 142 | push_strided_channel(&mut channels, name, rgba_f32, 4, offset, px_count, depth); | ||
| 143 | } | ||
| 144 | if let Some(z) = z_f32 { | ||
| 145 | channels.push(AnyChannel::new("Z", FlatSamples::F32(z.to_vec()))); | ||
| 146 | } | ||
| 147 | if let Some(n) = normal_f32 { | ||
| 148 | for (offset, name) in [(0, "NX"), (1, "NY"), (2, "NZ")] { | ||
| 149 | push_strided_channel(&mut channels, name, n, 4, offset, px_count, depth); | ||
| 150 | } | ||
| 151 | } | ||
| 152 | |||
| 153 | let encoding = Encoding { | ||
| 154 | compression: compression.to_exr(), | ||
| 155 | blocks: Blocks::ScanLines, | ||
| 156 | line_order: LineOrder::Increasing, | ||
| 157 | }; | ||
| 158 | let image = Image::from_layer(Layer::new( | ||
| 159 | Vec2(w as usize, h as usize), | ||
| 160 | LayerAttributes::default(), | ||
| 161 | encoding, | ||
| 162 | AnyChannels::sort(channels), | ||
| 163 | )); | ||
| 164 | |||
| 165 | out.clear(); | ||
| 166 | let mut cursor = Cursor::new(&mut *out); | ||
| 167 | let writer = image.write(); | ||
| 168 | let res = if parallel { | ||
| 169 | writer.to_buffered(&mut cursor) | ||
| 170 | } else { | ||
| 171 | writer.non_parallel().to_buffered(&mut cursor) | ||
| 172 | }; | ||
| 173 | res.map_err(|e| format!("failed to encode OpenEXR: {e}")) | ||
| 174 | } | ||
| 175 | |||
| 176 | #[allow(clippy::too_many_arguments)] | ||
| 177 | fn write_exr_rgba_with_aux_buffered( | ||
| 178 | path: &Path, | ||
| 179 | size: [u32; 2], | ||
| 180 | rgba_f32: &[f32], | ||
| 181 | z_f32: Option<&[f32]>, | ||
| 182 | normal_f32: Option<&[f32]>, | ||
| 183 | depth: ExrDepth, | ||
| 184 | compression: ExrCompression, | ||
| 185 | staging: &mut Vec<u8>, | ||
| 186 | last_parent: &mut Option<PathBuf>, | ||
| 187 | parallel: bool, | ||
| 188 | cancel: Option<&AtomicBool>, | ||
| 189 | ) -> Result<(), String> { | ||
| 190 | encode_exr_rgba_with_aux_into( | ||
| 191 | size, | ||
| 192 | rgba_f32, | ||
| 193 | z_f32, | ||
| 194 | normal_f32, | ||
| 195 | depth, | ||
| 196 | compression, | ||
| 197 | staging, | ||
| 198 | parallel, | ||
| 199 | ) | ||
| 200 | .map_err(|e| format!("{e} ('{}')", path.display()))?; | ||
| 201 | if cancel.is_some_and(|c| c.load(Ordering::Acquire)) { | ||
| 202 | return Ok(()); | ||
| 203 | } | ||
| 204 | ensure_parent_dir(path, last_parent)?; | ||
| 205 | std::fs::write(path, staging.as_slice()) | ||
| 206 | .map_err(|e| format!("failed to write '{}': {e}", path.display())) | ||
| 207 | } | ||
| 208 | |||
| 209 | /// Writes a linear HDR OpenEXR image containing `"R"`, `"G"`, `"B"`, `"A"` (at `depth`), | ||
| 210 | /// optional `"Z"` (`f32`), and optional `"NX"`, `"NY"`, `"NZ"` (at `depth`). | ||
| 211 | pub fn write_exr_rgba_with_aux( | ||
| 212 | path: &Path, | ||
| 213 | size: [u32; 2], | ||
| 214 | rgba_f32: &[f32], | ||
| 215 | z_f32: Option<&[f32]>, | ||
| 216 | normal_f32: Option<&[f32]>, | ||
| 217 | depth: ExrDepth, | ||
| 218 | compression: ExrCompression, | ||
| 219 | ) -> Result<(), String> { | ||
| 220 | let mut staging = Vec::new(); | ||
| 221 | let mut last_parent = None; | ||
| 222 | write_exr_rgba_with_aux_buffered( | ||
| 223 | path, | ||
| 224 | size, | ||
| 225 | rgba_f32, | ||
| 226 | z_f32, | ||
| 227 | normal_f32, | ||
| 228 | depth, | ||
| 229 | compression, | ||
| 230 | &mut staging, | ||
| 231 | &mut last_parent, | ||
| 232 | true, | ||
| 233 | None, | ||
| 234 | ) | ||
| 235 | } | ||
| 236 | |||
| 237 | /// Evaluates `target` at `frame` on GPU and saves a single linear HDR OpenEXR to `out_path`, | ||
| 238 | /// automatically attaching `aux.z` (`"Z"`) and `aux.normal` (`"NX"`, `"NY"`, `"NZ"`) when present. | ||
| 239 | pub fn export_node_frame_exr( | ||
| 240 | engine: &mut Engine, | ||
| 241 | comp: &Comp, | ||
| 242 | target: NodeId, | ||
| 243 | frame: f64, | ||
| 244 | out_path: &Path, | ||
| 245 | depth: ExrDepth, | ||
| 246 | compression: ExrCompression, | ||
| 247 | ) -> Result<PathBuf, String> { | ||
| 248 | if target.0 >= comp.nodes.len() { | ||
| 249 | return Err(format!("invalid target node id {}", target.0)); | ||
| 250 | } | ||
| 251 | let (tex, _) = engine.evaluate(comp, target, frame); | ||
| 252 | let rgba_f32 = engine | ||
| 253 | .readback_rgba_f32(&tex) | ||
| 254 | .map_err(|e| format!("GPU RGBA float readback failed at frame {frame}: {e}"))?; | ||
| 255 | let z_f32 = match tex.aux.as_ref().and_then(|a| a.z.as_ref()) { | ||
| 256 | Some(z_tex) if z_tex.size == tex.size => Some( | ||
| 257 | engine | ||
| 258 | .readback_aux_z_f32(z_tex) | ||
| 259 | .map_err(|e| format!("GPU Z aux readback failed at frame {frame}: {e}"))?, | ||
| 260 | ), | ||
| 261 | _ => None, | ||
| 262 | }; | ||
| 263 | let normal_f32 = match tex.aux.as_ref().and_then(|a| a.normal.as_ref()) { | ||
| 264 | Some(n_tex) if n_tex.size == tex.size => Some( | ||
| 265 | engine | ||
| 266 | .readback_aux_rgba_f32(n_tex) | ||
| 267 | .map_err(|e| format!("GPU Normal aux readback failed at frame {frame}: {e}"))?, | ||
| 268 | ), | ||
| 269 | _ => None, | ||
| 270 | }; | ||
| 271 | write_exr_rgba_with_aux( | ||
| 272 | out_path, | ||
| 273 | tex.size, | ||
| 274 | &rgba_f32, | ||
| 275 | z_f32.as_deref(), | ||
| 276 | normal_f32.as_deref(), | ||
| 277 | depth, | ||
| 278 | compression, | ||
| 279 | )?; | ||
| 280 | Ok(out_path.to_path_buf()) | ||
| 281 | } | ||
| 282 | |||
| 283 | #[derive(Default)] | ||
| 284 | struct RawByteBuffers { | ||
| 285 | rgba: Vec<u8>, | ||
| 286 | z: Vec<u8>, | ||
| 287 | normal: Vec<u8>, | ||
| 288 | } | ||
| 289 | |||
| 290 | struct ExrEncodeJob { | ||
| 291 | path: PathBuf, | ||
| 292 | size: [u32; 2], | ||
| 293 | rgba_fmt: wgpu::TextureFormat, | ||
| 294 | normal_fmt: Option<wgpu::TextureFormat>, | ||
| 295 | has_z: bool, | ||
| 296 | bufs: RawByteBuffers, | ||
| 297 | } | ||
| 298 | |||
| 299 | struct PendingExrFrame { | ||
| 300 | rgba_rb: PendingReadback, | ||
| 301 | rgba_fmt: wgpu::TextureFormat, | ||
| 302 | z_rb: Option<PendingReadback>, | ||
| 303 | normal_rb: Option<(PendingReadback, wgpu::TextureFormat)>, | ||
| 304 | frame: i64, | ||
| 305 | idx: usize, | ||
| 306 | path: PathBuf, | ||
| 307 | size: [u32; 2], | ||
| 308 | stats: EvalStats, | ||
| 309 | } | ||
| 310 | |||
| 311 | fn start_pending_exr_frame( | ||
| 312 | engine: &Engine, | ||
| 313 | tex: &crate::cache::CachedTexture, | ||
| 314 | frame: i64, | ||
| 315 | idx: usize, | ||
| 316 | path: PathBuf, | ||
| 317 | stats: EvalStats, | ||
| 318 | ) -> Result<PendingExrFrame, String> { | ||
| 319 | let rgba_bpp = Engine::rgba_f32_bpp(tex.format) | ||
| 320 | .map_err(|e| format!("GPU RGBA readback setup failed at frame {frame}: {e}"))?; | ||
| 321 | let rgba_rb = engine | ||
| 322 | .begin_readback_raw(&tex.texture, tex.size, rgba_bpp) | ||
| 323 | .map_err(|e| format!("GPU RGBA readback failed at frame {frame}: {e}"))?; | ||
| 324 | let z_rb = match tex.aux.as_ref().and_then(|a| a.z.as_ref()) { | ||
| 325 | Some(z_tex) if z_tex.size == tex.size => { | ||
| 326 | if z_tex.format != wgpu::TextureFormat::R32Float { | ||
| 327 | return Err(format!( | ||
| 328 | "expected R32Float for Z aux channel at frame {frame}, got {:?}", | ||
| 329 | z_tex.format | ||
| 330 | )); | ||
| 331 | } | ||
| 332 | Some( | ||
| 333 | engine | ||
| 334 | .begin_readback_raw(&z_tex.texture, z_tex.size, 4) | ||
| 335 | .map_err(|e| format!("GPU Z aux readback failed at frame {frame}: {e}"))?, | ||
| 336 | ) | ||
| 337 | } | ||
| 338 | _ => None, | ||
| 339 | }; | ||
| 340 | let normal_rb = match tex.aux.as_ref().and_then(|a| a.normal.as_ref()) { | ||
| 341 | Some(n_tex) if n_tex.size == tex.size => { | ||
| 342 | let n_bpp = Engine::rgba_f32_bpp(n_tex.format) | ||
| 343 | .map_err(|e| format!("GPU Normal aux format error at frame {frame}: {e}"))?; | ||
| 344 | let rb = engine | ||
| 345 | .begin_readback_raw(&n_tex.texture, n_tex.size, n_bpp) | ||
| 346 | .map_err(|e| format!("GPU Normal aux readback failed at frame {frame}: {e}"))?; | ||
| 347 | Some((rb, n_tex.format)) | ||
| 348 | } | ||
| 349 | _ => None, | ||
| 350 | }; | ||
| 351 | Ok(PendingExrFrame { | ||
| 352 | rgba_rb, | ||
| 353 | rgba_fmt: tex.format, | ||
| 354 | z_rb, | ||
| 355 | normal_rb, | ||
| 356 | frame, | ||
| 357 | idx, | ||
| 358 | path, | ||
| 359 | size: tex.size, | ||
| 360 | stats, | ||
| 361 | }) | ||
| 362 | } | ||
| 363 | |||
| 364 | fn finish_pending_exr_frame( | ||
| 365 | engine: &Engine, | ||
| 366 | pending: PendingExrFrame, | ||
| 367 | mut bufs: RawByteBuffers, | ||
| 368 | ) -> Result<ExrEncodeJob, String> { | ||
| 369 | pending | ||
| 370 | .rgba_rb | ||
| 371 | .finish_into(engine, &mut bufs.rgba) | ||
| 372 | .map_err(|e| format!("GPU RGBA readback failed at frame {}: {e}", pending.frame))?; | ||
| 373 | let has_z = if let Some(z_rb) = pending.z_rb { | ||
| 374 | z_rb.finish_into(engine, &mut bufs.z) | ||
| 375 | .map_err(|e| format!("GPU Z aux readback failed at frame {}: {e}", pending.frame))?; | ||
| 376 | true | ||
| 377 | } else { | ||
| 378 | bufs.z.clear(); | ||
| 379 | false | ||
| 380 | }; | ||
| 381 | let normal_fmt = if let Some((n_rb, n_fmt)) = pending.normal_rb { | ||
| 382 | n_rb.finish_into(engine, &mut bufs.normal) | ||
| 383 | .map_err(|e| format!("GPU Normal aux readback failed at frame {}: {e}", pending.frame))?; | ||
| 384 | Some(n_fmt) | ||
| 385 | } else { | ||
| 386 | bufs.normal.clear(); | ||
| 387 | None | ||
| 388 | }; | ||
| 389 | Ok(ExrEncodeJob { | ||
| 390 | path: pending.path, | ||
| 391 | size: pending.size, | ||
| 392 | rgba_fmt: pending.rgba_fmt, | ||
| 393 | normal_fmt, | ||
| 394 | has_z, | ||
| 395 | bufs, | ||
| 396 | }) | ||
| 397 | } | ||
| 398 | |||
| 399 | /// Renders and writes a linear HDR OpenEXR sequence for an arbitrary `target` node across | ||
| 400 | /// `range` (`[start, end]` inclusive) using double-buffered async GPU readback, recycled raw | ||
| 401 | /// staging buffers, 12-frame media prefetch, and a bounded background EXR encoder pool. | ||
| 402 | #[allow(clippy::too_many_arguments)] | ||
| 403 | pub fn export_node_exr_sequence_with_progress( | ||
| 404 | engine: &mut Engine, | ||
| 405 | comp: &Comp, | ||
| 406 | target: NodeId, | ||
| 407 | range: [i64; 2], | ||
| 408 | path_for_frame: impl Fn(i64) -> Result<PathBuf, String>, | ||
| 409 | label: String, | ||
| 410 | hiq: bool, | ||
| 411 | proxy_scale: u32, | ||
| 412 | exr_workers: usize, | ||
| 413 | depth: ExrDepth, | ||
| 414 | compression: ExrCompression, | ||
| 415 | control: Option<&ExportControl>, | ||
| 416 | mut on_progress: impl FnMut(&ExportProgress), | ||
| 417 | ) -> Result<ExportSummary, String> { | ||
| 418 | if control.is_some_and(ExportControl::is_cancelled) { | ||
| 419 | return Err("Cancelled".to_owned()); | ||
| 420 | } | ||
| 421 | if target.0 >= comp.nodes.len() { | ||
| 422 | return Err(format!("invalid target node id {}", target.0)); | ||
| 423 | } | ||
| 424 | let [start, end] = range; | ||
| 425 | let total_i128 = i128::from(end) - i128::from(start) + 1; | ||
| 426 | if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) { | ||
| 427 | return Err(format!("invalid export frame range {start}..={end}")); | ||
| 428 | } | ||
| 429 | |||
| 430 | let prev_hiq = engine.hiq; | ||
| 431 | let prev_proxy = engine.proxy_scale; | ||
| 432 | engine.hiq = hiq; | ||
| 433 | engine.proxy_scale = proxy_scale.max(1); | ||
| 434 | |||
| 435 | let total = total_i128 as usize; | ||
| 436 | let workers = if exr_workers > 0 { | ||
| 437 | exr_workers.clamp(1, 24) | ||
| 438 | } else { | ||
| 439 | std::thread::available_parallelism() | ||
| 440 | .map(|n| n.get().clamp(2, 24)) | ||
| 441 | .unwrap_or(4) | ||
| 442 | } | ||
| 443 | .min(total.max(1)); | ||
| 444 | |||
| 445 | let t0 = Instant::now(); | ||
| 446 | let mut first_path: Option<PathBuf> = None; | ||
| 447 | let mut last_path: Option<PathBuf> = None; | ||
| 448 | let mut frames_written: usize = 0; | ||
| 449 | |||
| 450 | let first_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None)); | ||
| 451 | let failed = Arc::new(AtomicBool::new(false)); | ||
| 452 | let cancelled = Arc::new(AtomicBool::new(false)); | ||
| 453 | |||
| 454 | let eval_result: Result<(), String> = std::thread::scope(|scope| { | ||
| 455 | let queue_cap = (workers * 2).clamp(16, 48); | ||
| 456 | let (tx, rx) = mpsc::sync_channel::<ExrEncodeJob>(queue_cap); | ||
| 457 | let (recycle_tx, recycle_rx) = mpsc::sync_channel::<RawByteBuffers>(queue_cap + workers); | ||
| 458 | let shared_rx = Arc::new(Mutex::new(rx)); | ||
| 459 | |||
| 460 | let mut handles = Vec::with_capacity(workers); | ||
| 461 | for _ in 0..workers { | ||
| 462 | let rx_c = Arc::clone(&shared_rx); | ||
| 463 | let recycle_c = recycle_tx.clone(); | ||
| 464 | let err_c = Arc::clone(&first_err); | ||
| 465 | let fail_c = Arc::clone(&failed); | ||
| 466 | let cancel_c = Arc::clone(&cancelled); | ||
| 467 | handles.push(scope.spawn(move || { | ||
| 468 | let mut rgba_f32 = Vec::new(); | ||
| 469 | let mut z_f32 = Vec::new(); | ||
| 470 | let mut normal_f32 = Vec::new(); | ||
| 471 | let mut staging = Vec::new(); | ||
| 472 | let mut last_parent: Option<PathBuf> = None; | ||
| 473 | loop { | ||
| 474 | let job = { | ||
| 475 | let Ok(guard) = rx_c.lock() else { break }; | ||
| 476 | guard.recv() | ||
| 477 | }; | ||
| 478 | let Ok(job) = job else { break }; | ||
| 479 | if fail_c.load(Ordering::Acquire) || cancel_c.load(Ordering::Acquire) { | ||
| 480 | continue; | ||
| 481 | } | ||
| 482 | let decode_res = (|| -> Result<(), String> { | ||
| 483 | Engine::decode_rgba_bytes_into_f32( | ||
| 484 | job.rgba_fmt, | ||
| 485 | job.size, | ||
| 486 | &job.bufs.rgba, | ||
| 487 | &mut rgba_f32, | ||
| 488 | ) | ||
| 489 | .map_err(|e| format!("RGBA float decode failed: {e}"))?; | ||
| 490 | if job.has_z { | ||
| 491 | Engine::decode_z_bytes_into_f32(job.size, &job.bufs.z, &mut z_f32) | ||
| 492 | .map_err(|e| format!("Z aux decode failed: {e}"))?; | ||
| 493 | } | ||
| 494 | if let Some(n_fmt) = job.normal_fmt { | ||
| 495 | Engine::decode_rgba_bytes_into_f32( | ||
| 496 | n_fmt, | ||
| 497 | job.size, | ||
| 498 | &job.bufs.normal, | ||
| 499 | &mut normal_f32, | ||
| 500 | ) | ||
| 501 | .map_err(|e| format!("Normal aux decode failed: {e}"))?; | ||
| 502 | } | ||
| 503 | write_exr_rgba_with_aux_buffered( | ||
| 504 | &job.path, | ||
| 505 | job.size, | ||
| 506 | &rgba_f32, | ||
| 507 | job.has_z.then_some(z_f32.as_slice()), | ||
| 508 | job.normal_fmt.map(|_| normal_f32.as_slice()), | ||
| 509 | depth, | ||
| 510 | compression, | ||
| 511 | &mut staging, | ||
| 512 | &mut last_parent, | ||
| 513 | false, | ||
| 514 | Some(&cancel_c), | ||
| 515 | ) | ||
| 516 | })(); | ||
| 517 | if let Err(e) = decode_res { | ||
| 518 | if let Ok(mut g) = err_c.lock() | ||
| 519 | && g.is_none() | ||
| 520 | { | ||
| 521 | *g = Some(e); | ||
| 522 | } | ||
| 523 | fail_c.store(true, Ordering::Release); | ||
| 524 | } | ||
| 525 | let _ = recycle_c.try_send(job.bufs); | ||
| 526 | } | ||
| 527 | })); | ||
| 528 | } | ||
| 529 | drop(recycle_tx); | ||
| 530 | |||
| 531 | let mut loop_err: Option<String> = None; | ||
| 532 | const PREFETCH_LOOKAHEAD: usize = 12; | ||
| 533 | engine.prewarm_for_depth(comp.depth_full); | ||
| 534 | let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); | ||
| 535 | if start < end { | ||
| 536 | let seed_start = start.saturating_add(1); | ||
| 537 | let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64 - 1).min(end); | ||
| 538 | for (k, f) in (seed_start..=seed_end).enumerate() { | ||
| 539 | prefetch.enqueue_frame( | ||
| 540 | comp, | ||
| 541 | target, | ||
| 542 | k + 1, | ||
| 543 | f as f64, | ||
| 544 | &engine.expr, | ||
| 545 | engine.use_proxy_clips, | ||
| 546 | ); | ||
| 547 | } | ||
| 548 | } | ||
| 549 | |||
| 550 | let mut flush_pending = |engine: &Engine, pend: PendingExrFrame| -> Result<bool, String> { | ||
| 551 | let prev_frame = pend.frame; | ||
| 552 | let prev_idx = pend.idx; | ||
| 553 | let prev_path = pend.path.clone(); | ||
| 554 | let prev_stats = pend.stats.clone(); | ||
| 555 | let bufs = recycle_rx.try_recv().unwrap_or_default(); | ||
| 556 | let job = finish_pending_exr_frame(engine, pend, bufs)?; | ||
| 557 | if control.is_some_and(ExportControl::is_cancelled) { | ||
| 558 | cancelled.store(true, Ordering::Release); | ||
| 559 | return Ok(false); | ||
| 560 | } | ||
| 561 | if first_path.is_none() { | ||
| 562 | first_path = Some(prev_path.clone()); | ||
| 563 | } | ||
| 564 | last_path = Some(prev_path.clone()); | ||
| 565 | let prog = make_progress( | ||
| 566 | prev_frame, | ||
| 567 | prev_idx, | ||
| 568 | total, | ||
| 569 | prev_stats, | ||
| 570 | prev_path, | ||
| 571 | label.clone(), | ||
| 572 | t0, | ||
| 573 | ); | ||
| 574 | if let Some(ctrl) = control { | ||
| 575 | ctrl.update_progress(&prog); | ||
| 576 | } | ||
| 577 | on_progress(&prog); | ||
| 578 | if control.is_some_and(ExportControl::is_cancelled) { | ||
| 579 | cancelled.store(true, Ordering::Release); | ||
| 580 | return Ok(false); | ||
| 581 | } | ||
| 582 | if tx.send(job).is_err() { | ||
| 583 | return Ok(false); | ||
| 584 | } | ||
| 585 | frames_written += 1; | ||
| 586 | Ok(true) | ||
| 587 | }; | ||
| 588 | |||
| 589 | let mut pending: Option<PendingExrFrame> = None; | ||
| 590 | for (idx, frame) in (start..=end).enumerate() { | ||
| 591 | if failed.load(Ordering::Acquire) { | ||
| 592 | break; | ||
| 593 | } | ||
| 594 | if control.is_some_and(ExportControl::is_cancelled) { | ||
| 595 | cancelled.store(true, Ordering::Release); | ||
| 596 | break; | ||
| 597 | } | ||
| 598 | prefetch.set_current_seq(idx); | ||
| 599 | if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) | ||
| 600 | && ahead_frame <= end | ||
| 601 | { | ||
| 602 | prefetch.enqueue_frame( | ||
| 603 | comp, | ||
| 604 | target, | ||
| 605 | idx + PREFETCH_LOOKAHEAD, | ||
| 606 | ahead_frame as f64, | ||
| 607 | &engine.expr, | ||
| 608 | engine.use_proxy_clips, | ||
| 609 | ); | ||
| 610 | } | ||
| 611 | let out_path = match path_for_frame(frame) { | ||
| 612 | Ok(p) => p, | ||
| 613 | Err(e) => { | ||
| 614 | loop_err = Some(e); | ||
| 615 | break; | ||
| 616 | } | ||
| 617 | }; | ||
| 618 | let (tex, stats) = engine.evaluate(comp, target, frame as f64); | ||
| 619 | let next_pend = match start_pending_exr_frame(engine, &tex, frame, idx, out_path, stats) { | ||
| 620 | Ok(p) => p, | ||
| 621 | Err(e) => { | ||
| 622 | loop_err = Some(e); | ||
| 623 | break; | ||
| 624 | } | ||
| 625 | }; | ||
| 626 | if let Some(prev_pend) = pending.replace(next_pend) { | ||
| 627 | match flush_pending(engine, prev_pend) { | ||
| 628 | Ok(true) => {} | ||
| 629 | Ok(false) => break, | ||
| 630 | Err(e) => { | ||
| 631 | loop_err = Some(e); | ||
| 632 | break; | ||
| 633 | } | ||
| 634 | } | ||
| 635 | } | ||
| 636 | } | ||
| 637 | if loop_err.is_none() | ||
| 638 | && !failed.load(Ordering::Acquire) | ||
| 639 | && !cancelled.load(Ordering::Acquire) | ||
| 640 | && let Some(prev_pend) = pending.take() | ||
| 641 | && let Err(e) = flush_pending(engine, prev_pend) | ||
| 642 | { | ||
| 643 | loop_err = Some(e); | ||
| 644 | } | ||
| 645 | |||
| 646 | drop(prefetch); | ||
| 647 | drop(tx); | ||
| 648 | for h in handles { | ||
| 649 | let _ = h.join(); | ||
| 650 | } | ||
| 651 | |||
| 652 | if let Some(e) = loop_err { | ||
| 653 | return Err(e); | ||
| 654 | } | ||
| 655 | if let Ok(mut g) = first_err.lock() | ||
| 656 | && let Some(e) = g.take() | ||
| 657 | { | ||
| 658 | return Err(e); | ||
| 659 | } | ||
| 660 | if cancelled.load(Ordering::Acquire) { | ||
| 661 | return Err("Cancelled".to_owned()); | ||
| 662 | } | ||
| 663 | Ok(()) | ||
| 664 | }); | ||
| 665 | |||
| 666 | engine.hiq = prev_hiq; | ||
| 667 | engine.proxy_scale = prev_proxy; | ||
| 668 | |||
| 669 | eval_result?; | ||
| 670 | |||
| 671 | Ok(ExportSummary { | ||
| 672 | saver_name: label, | ||
| 673 | frames_written, | ||
| 674 | total_ms: t0.elapsed().as_secs_f64() * 1000.0, | ||
| 675 | first_path, | ||
| 676 | last_path, | ||
| 677 | }) | ||
| 678 | } | ||
| 679 | |||
| 680 | /// Renders and writes a linear HDR OpenEXR sequence driven by a Fusion `Saver` node. | ||
| 681 | pub fn export_saver_exr_sequence( | ||
| 682 | engine: &mut Engine, | ||
| 683 | comp: &Comp, | ||
| 684 | opts: &ExportOptions, | ||
| 685 | on_progress: impl FnMut(&ExportProgress), | ||
| 686 | ) -> Result<ExportSummary, String> { | ||
| 687 | export_saver_exr_sequence_with_progress(engine, comp, opts, None, on_progress) | ||
| 688 | } | ||
| 689 | |||
| 690 | /// Renders and writes a linear HDR OpenEXR sequence driven by a Fusion `Saver` node with | ||
| 691 | /// cooperative cancellation and live progress reporting via `ExportControl`. | ||
| 692 | pub fn export_saver_exr_sequence_with_progress( | ||
| 693 | engine: &mut Engine, | ||
| 694 | comp: &Comp, | ||
| 695 | opts: &ExportOptions, | ||
| 696 | control: Option<&ExportControl>, | ||
| 697 | on_progress: impl FnMut(&ExportProgress), | ||
| 698 | ) -> Result<ExportSummary, String> { | ||
| 699 | if control.is_some_and(ExportControl::is_cancelled) { | ||
| 700 | return Err("Cancelled".to_owned()); | ||
| 701 | } | ||
| 702 | let saver = select_saver(comp, opts.saver_name.as_deref())?; | ||
| 703 | let target: NodeId = saver.upstream.unwrap_or(saver.node_id); | ||
| 704 | let range = opts.range_override.unwrap_or(saver.range); | ||
| 705 | let saver_node = comp.node(saver.node_id); | ||
| 706 | let depth = ExrDepth::from_fusion_code( | ||
| 707 | comp.eval_number( | ||
| 708 | saver_node, | ||
| 709 | "OpenEXRFormat.Depth", | ||
| 710 | range[0] as f64, | ||
| 711 | 0.0, | ||
| 712 | &engine.expr, | ||
| 713 | ) | ||
| 714 | .round() as i32, | ||
| 715 | ); | ||
| 716 | let compression = ExrCompression::from_fusion_code( | ||
| 717 | comp.eval_number( | ||
| 718 | saver_node, | ||
| 719 | "OpenEXRFormat.Compression", | ||
| 720 | range[0] as f64, | ||
| 721 | 3.0, | ||
| 722 | &engine.expr, | ||
| 723 | ) | ||
| 724 | .round() as i32, | ||
| 725 | ); | ||
| 726 | let out_dir_override = opts.out_dir_override.as_deref(); | ||
| 727 | export_node_exr_sequence_with_progress( | ||
| 728 | engine, | ||
| 729 | comp, | ||
| 730 | target, | ||
| 731 | range, | ||
| 732 | |frame| resolve_output_path_with_ext(&saver, frame, out_dir_override, "exr"), | ||
| 733 | saver.name.clone(), | ||
| 734 | opts.hiq, | ||
| 735 | opts.proxy_scale, | ||
| 736 | opts.png_workers, | ||
| 737 | depth, | ||
| 738 | compression, | ||
| 739 | control, | ||
| 740 | on_progress, | ||
| 741 | ) | ||
| 742 | } | ||
crates/engine/src/export/png.rs+19-37| ... | @@ -1,42 +1,17 @@ | ... | @@ -1,42 +1,17 @@ |
| 1 | //! Lossless RGBA8 PNG encoding and pipelined multi-threaded PNG sequence export. | 1 | //! Lossless RGBA8 PNG encoding and pipelined multi-threaded PNG sequence export. |
| 2 | 2 | ||
| 3 | use super::{ | 3 | use super::{ |
| 4 | ExportControl, ExportOptions, ExportProgress, ExportSummary, make_progress, select_saver, | 4 | ExportControl, ExportOptions, ExportProgress, ExportSummary, ensure_parent_dir, make_progress, |
| 5 | resolve_output_path_with_ext, select_saver, | ||
| 5 | }; | 6 | }; |
| 6 | use crate::cache::EvalStats; | 7 | use crate::cache::EvalStats; |
| 7 | use crate::eval::Engine; | 8 | use crate::eval::Engine; |
| 8 | use model::{Comp, NodeId, SaverSpec}; | 9 | use model::{Comp, NodeId}; |
| 9 | use std::path::{Path, PathBuf}; | 10 | use std::path::{Path, PathBuf}; |
| 10 | use std::sync::atomic::{AtomicBool, Ordering}; | 11 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 11 | use std::sync::{Arc, Mutex, mpsc}; | 12 | use std::sync::{Arc, Mutex, mpsc}; |
| 12 | use std::time::Instant; | 13 | use std::time::Instant; |
| 13 | 14 | ||
| 14 | fn resolve_output_path( | ||
| 15 | saver: &SaverSpec, | ||
| 16 | frame: i64, | ||
| 17 | out_dir_override: Option<&Path>, | ||
| 18 | ) -> Result<PathBuf, String> { | ||
| 19 | if saver.filename.is_empty() { | ||
| 20 | let dir = out_dir_override.ok_or_else(|| { | ||
| 21 | format!( | ||
| 22 | "Saver '{}' has no Clip.Filename set (pass an output directory override or configure Clip.Filename)", | ||
| 23 | saver.name | ||
| 24 | ) | ||
| 25 | })?; | ||
| 26 | return Ok(dir.join(format!("{frame:04}.png"))); | ||
| 27 | } | ||
| 28 | let frame_path = saver.frame_path(frame); | ||
| 29 | if let Some(dir) = out_dir_override { | ||
| 30 | let fname = frame_path | ||
| 31 | .file_name() | ||
| 32 | .map(PathBuf::from) | ||
| 33 | .unwrap_or_else(|| PathBuf::from(format!("{frame:04}.png"))); | ||
| 34 | Ok(dir.join(fname)) | ||
| 35 | } else { | ||
| 36 | Ok(frame_path) | ||
| 37 | } | ||
| 38 | } | ||
| 39 | |||
| 40 | /// Encodes an RGBA8 image into `out` as a lossless PNG matching Fusion's default | 15 | /// Encodes an RGBA8 image into `out` as a lossless PNG matching Fusion's default |
| 41 | /// libpng compression (`Compression::Balanced` = zlib level 6 + `Filter::Adaptive`). | 16 | /// libpng compression (`Compression::Balanced` = zlib level 6 + `Filter::Adaptive`). |
| 42 | pub fn encode_png_rgba8_into(size: [u32; 2], pixels: &[u8], out: &mut Vec<u8>) -> Result<(), String> { | 17 | pub fn encode_png_rgba8_into(size: [u32; 2], pixels: &[u8], out: &mut Vec<u8>) -> Result<(), String> { |
| ... | @@ -66,13 +41,7 @@ pub fn write_png_fast_buffered( | ... | @@ -66,13 +41,7 @@ pub fn write_png_fast_buffered( |
| 66 | staging: &mut Vec<u8>, | 41 | staging: &mut Vec<u8>, |
| 67 | last_parent: &mut Option<PathBuf>, | 42 | last_parent: &mut Option<PathBuf>, |
| 68 | ) -> Result<(), String> { | 43 | ) -> Result<(), String> { |
| 69 | if let Some(parent) = path.parent() { | 44 | ensure_parent_dir(path, last_parent)?; |
| 70 | if !parent.as_os_str().is_empty() && last_parent.as_deref() != Some(parent) { | ||
| 71 | std::fs::create_dir_all(parent) | ||
| 72 | .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?; | ||
| 73 | *last_parent = Some(parent.to_path_buf()); | ||
| 74 | } | ||
| 75 | } | ||
| 76 | encode_png_rgba8_into(size, pixels, staging) | 45 | encode_png_rgba8_into(size, pixels, staging) |
| 77 | .map_err(|e| format!("{e} ('{}')", path.display()))?; | 46 | .map_err(|e| format!("{e} ('{}')", path.display()))?; |
| 78 | std::fs::write(path, staging.as_slice()) | 47 | std::fs::write(path, staging.as_slice()) |
| ... | @@ -410,14 +379,27 @@ pub fn export_saver_png_sequence( | ... | @@ -410,14 +379,27 @@ pub fn export_saver_png_sequence( |
| 410 | export_saver_png_sequence_with_progress(engine, comp, opts, None, on_progress) | 379 | export_saver_png_sequence_with_progress(engine, comp, opts, None, on_progress) |
| 411 | } | 380 | } |
| 412 | 381 | ||
| 413 | /// Renders and writes a PNG sequence driven by a Fusion `Saver` node with cooperative | 382 | /// Renders and writes an image sequence driven by a Fusion `Saver` node with cooperative |
| 414 | /// cancellation and live progress reporting via `ExportControl`. | 383 | /// cancellation and live progress reporting via `ExportControl`. |
| 384 | /// | ||
| 385 | /// Automatically dispatches to OpenEXR export when the Saver specifies `OutputFormat == "OpenEXRFormat"` | ||
| 386 | /// or resolves to a `.exr` output path. | ||
| 415 | pub fn export_saver_png_sequence_with_progress( | 387 | pub fn export_saver_png_sequence_with_progress( |
| 416 | engine: &mut Engine, | 388 | engine: &mut Engine, |
| 417 | comp: &Comp, | 389 | comp: &Comp, |
| 418 | opts: &ExportOptions, | 390 | opts: &ExportOptions, |
| 419 | control: Option<&ExportControl>, | 391 | control: Option<&ExportControl>, |
| 420 | on_progress: impl FnMut(&ExportProgress), | 392 | on_progress: impl FnMut(&ExportProgress), |
| 393 | ) -> Result<ExportSummary, String> { | ||
| 394 | super::export_saver_sequence_with_progress(engine, comp, opts, control, on_progress) | ||
| 395 | } | ||
| 396 | |||
| 397 | pub(super) fn export_saver_png_only_sequence_with_progress( | ||
| 398 | engine: &mut Engine, | ||
| 399 | comp: &Comp, | ||
| 400 | opts: &ExportOptions, | ||
| 401 | control: Option<&ExportControl>, | ||
| 402 | on_progress: impl FnMut(&ExportProgress), | ||
| 421 | ) -> Result<ExportSummary, String> { | 403 | ) -> Result<ExportSummary, String> { |
| 422 | if control.is_some_and(ExportControl::is_cancelled) { | 404 | if control.is_some_and(ExportControl::is_cancelled) { |
| 423 | return Err("Cancelled".to_owned()); | 405 | return Err("Cancelled".to_owned()); |
| ... | @@ -431,7 +413,7 @@ pub fn export_saver_png_sequence_with_progress( | ... | @@ -431,7 +413,7 @@ pub fn export_saver_png_sequence_with_progress( |
| 431 | comp, | 413 | comp, |
| 432 | target, | 414 | target, |
| 433 | range, | 415 | range, |
| 434 | |frame| resolve_output_path(&saver, frame, out_dir_override), | 416 | |frame| resolve_output_path_with_ext(&saver, frame, out_dir_override, "png"), |
| 435 | saver.name.clone(), | 417 | saver.name.clone(), |
| 436 | opts.hiq, | 418 | opts.hiq, |
| 437 | opts.proxy_scale, | 419 | opts.proxy_scale, |
crates/engine/src/export/tests.rs+506| ... | @@ -1284,3 +1284,509 @@ fn video_export_cancel_on_final_frame_progress_cancels_cleanly() { | ... | @@ -1284,3 +1284,509 @@ fn video_export_cancel_on_final_frame_progress_cancels_cleanly() { |
| 1284 | 1284 | ||
| 1285 | let _ = std::fs::remove_dir_all(&tmp_dir); | 1285 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1286 | } | 1286 | } |
| 1287 | |||
| 1288 | #[test] | ||
| 1289 | fn readback_rgba_f32_preserves_hdr_and_strips_row_padding() { | ||
| 1290 | let Ok(engine) = Engine::new_headless() else { | ||
| 1291 | return; | ||
| 1292 | }; | ||
| 1293 | // Unaligned width 19 forces row padding on Rgba8Unorm (76->256), Rgba16Float (152->256), and Rgba32Float (304->512). | ||
| 1294 | let [w, h] = [19u32, 11u32]; | ||
| 1295 | let px_count = (w * h) as usize; | ||
| 1296 | |||
| 1297 | let upload_and_check = |format: wgpu::TextureFormat, bytes: &[u8], expected: &[f32]| { | ||
| 1298 | let texture = engine.device().create_texture(&wgpu::TextureDescriptor { | ||
| 1299 | label: Some("test-readback-f32"), | ||
| 1300 | size: wgpu::Extent3d { | ||
| 1301 | width: w, | ||
| 1302 | height: h, | ||
| 1303 | depth_or_array_layers: 1, | ||
| 1304 | }, | ||
| 1305 | mip_level_count: 1, | ||
| 1306 | sample_count: 1, | ||
| 1307 | dimension: wgpu::TextureDimension::D2, | ||
| 1308 | format, | ||
| 1309 | usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, | ||
| 1310 | view_formats: &[], | ||
| 1311 | }); | ||
| 1312 | let bpp = match format { | ||
| 1313 | wgpu::TextureFormat::Rgba32Float => 16u32, | ||
| 1314 | wgpu::TextureFormat::Rgba16Float => 8u32, | ||
| 1315 | wgpu::TextureFormat::Rgba8Unorm => 4u32, | ||
| 1316 | _ => unreachable!(), | ||
| 1317 | }; | ||
| 1318 | engine.queue().write_texture( | ||
| 1319 | texture.as_image_copy(), | ||
| 1320 | bytes, | ||
| 1321 | wgpu::TexelCopyBufferLayout { | ||
| 1322 | offset: 0, | ||
| 1323 | bytes_per_row: Some(w * bpp), | ||
| 1324 | rows_per_image: Some(h), | ||
| 1325 | }, | ||
| 1326 | wgpu::Extent3d { | ||
| 1327 | width: w, | ||
| 1328 | height: h, | ||
| 1329 | depth_or_array_layers: 1, | ||
| 1330 | }, | ||
| 1331 | ); | ||
| 1332 | let cached = crate::cache::CachedTexture::from_texture(texture, [w, h], 0); | ||
| 1333 | let got = engine | ||
| 1334 | .readback_rgba_f32(&cached) | ||
| 1335 | .expect("readback_rgba_f32 should succeed"); | ||
| 1336 | assert_eq!(got.len(), px_count * 4); | ||
| 1337 | for (i, (&g, &e)) in got.iter().zip(expected.iter()).enumerate() { | ||
| 1338 | assert!( | ||
| 1339 | (g - e).abs() <= 2e-3, | ||
| 1340 | "{format:?} sample {i}: expected {e}, got {g}" | ||
| 1341 | ); | ||
| 1342 | } | ||
| 1343 | }; | ||
| 1344 | |||
| 1345 | let mut f32_vals = Vec::with_capacity(px_count * 4); | ||
| 1346 | let mut f16_bits = Vec::with_capacity(px_count * 4); | ||
| 1347 | let mut u8_vals = Vec::with_capacity(px_count * 4); | ||
| 1348 | let mut u8_expected = Vec::with_capacity(px_count * 4); | ||
| 1349 | for i in 0..px_count { | ||
| 1350 | let r = 2.5 + (i % 5) as f32 * 0.25; | ||
| 1351 | let g = -0.75 + (i % 3) as f32 * 0.5; | ||
| 1352 | let b = 0.125 * (i % 7) as f32; | ||
| 1353 | let a = 1.0; | ||
| 1354 | f32_vals.extend_from_slice(&[r, g, b, a]); | ||
| 1355 | f16_bits.extend_from_slice(&[ | ||
| 1356 | ::exr::prelude::f16::from_f32(r).to_bits(), | ||
| 1357 | ::exr::prelude::f16::from_f32(g).to_bits(), | ||
| 1358 | ::exr::prelude::f16::from_f32(b).to_bits(), | ||
| 1359 | ::exr::prelude::f16::from_f32(a).to_bits(), | ||
| 1360 | ]); | ||
| 1361 | let r8 = ((i * 17) % 256) as u8; | ||
| 1362 | let g8 = ((i * 31) % 256) as u8; | ||
| 1363 | let b8 = ((i * 53) % 256) as u8; | ||
| 1364 | let a8 = 255u8; | ||
| 1365 | u8_vals.extend_from_slice(&[r8, g8, b8, a8]); | ||
| 1366 | u8_expected.extend_from_slice(&[ | ||
| 1367 | f32::from(r8) / 255.0, | ||
| 1368 | f32::from(g8) / 255.0, | ||
| 1369 | f32::from(b8) / 255.0, | ||
| 1370 | 1.0, | ||
| 1371 | ]); | ||
| 1372 | } | ||
| 1373 | |||
| 1374 | upload_and_check( | ||
| 1375 | wgpu::TextureFormat::Rgba32Float, | ||
| 1376 | bytemuck::cast_slice(&f32_vals), | ||
| 1377 | &f32_vals, | ||
| 1378 | ); | ||
| 1379 | upload_and_check( | ||
| 1380 | wgpu::TextureFormat::Rgba16Float, | ||
| 1381 | bytemuck::cast_slice(&f16_bits), | ||
| 1382 | &f32_vals, | ||
| 1383 | ); | ||
| 1384 | upload_and_check(wgpu::TextureFormat::Rgba8Unorm, &u8_vals, &u8_expected); | ||
| 1385 | } | ||
| 1386 | |||
| 1387 | #[test] | ||
| 1388 | fn exports_exr_hdr_and_aux_roundtrips_through_loader() { | ||
| 1389 | let tmp_dir = std::env::temp_dir().join(format!( | ||
| 1390 | "fission-exr-roundtrip-test-{}", | ||
| 1391 | std::process::id() | ||
| 1392 | )); | ||
| 1393 | let _ = std::fs::remove_dir_all(&tmp_dir); | ||
| 1394 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); | ||
| 1395 | |||
| 1396 | let Ok(mut engine) = Engine::new_headless() else { | ||
| 1397 | let _ = std::fs::remove_dir_all(&tmp_dir); | ||
| 1398 | return; | ||
| 1399 | }; | ||
| 1400 | |||
| 1401 | for (depth_code, expected_sample_type, tag) in [ | ||
| 1402 | (0, ::exr::meta::attribute::SampleType::F16, "f16"), | ||
| 1403 | (1, ::exr::meta::attribute::SampleType::F32, "f32"), | ||
| 1404 | ] { | ||
| 1405 | let saver_path = tmp_dir.join(tag).join("render_0000.exr"); | ||
| 1406 | let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); | ||
| 1407 | // Plane at Z = 0, Camera at Z = 2 => eye-space Z = -2.0; R3D Z + Normal aux channels | ||
| 1408 | // flow through ChangeDepth (Depth=4 Float32) + BrightnessContrast (Gain=2.5 => R=2.5 HDR). | ||
| 1409 | let comp_src = format!( | ||
| 1410 | r#"Composition {{ | ||
| 1411 | 	CurrentTime = 0, | ||
| 1412 | 	RenderRange = {{ 0, 0 }}, | ||
| 1413 | 	GlobalRange = {{ 0, 10 }}, | ||
| 1414 | 	Tools = ordered() {{ | ||
| 1415 | 		Flat = MtlBlinn {{ | ||
| 1416 | 			Inputs = {{ | ||
| 1417 | 				["Diffuse.Color.Red"] = Input {{ Value = 1.0, }}, | ||
| 1418 | 				["Diffuse.Color.Green"] = Input {{ Value = 0.2, }}, | ||
| 1419 | 				["Diffuse.Color.Blue"] = Input {{ Value = 0.1, }}, | ||
| 1420 | 				["Specular.Intensity"] = Input {{ Value = 0, }}, | ||
| 1421 | 			}}, | ||
| 1422 | 		}}, | ||
| 1423 | 		P = Shape3D {{ | ||
| 1424 | 			Inputs = {{ | ||
| 1425 | 				["SurfacePlaneInputs.Width"] = Input {{ Value = 0.5, }}, | ||
| 1426 | 				["SurfacePlaneInputs.Height"] = Input {{ Value = 0.5, }}, | ||
| 1427 | 				["Transform3DOp.Translate.Z"] = Input {{ Value = 0.0, }}, | ||
| 1428 | 				MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, | ||
| 1429 | 			}}, | ||
| 1430 | 		}}, | ||
| 1431 | 		Cam = Camera3D {{ | ||
| 1432 | 			Inputs = {{ | ||
| 1433 | 				ProjectionType = Input {{ Value = FuID {{ "Perspective" }}, }}, | ||
| 1434 | 				["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, | ||
| 1435 | 				ApertureW = Input {{ Value = 1.0, }}, | ||
| 1436 | 				ApertureH = Input {{ Value = 1.0, }}, | ||
| 1437 | 			}}, | ||
| 1438 | 		}}, | ||
| 1439 | 		M = Merge3D {{ | ||
| 1440 | 			Inputs = {{ | ||
| 1441 | 				SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, | ||
| 1442 | 				SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, | ||
| 1443 | 			}}, | ||
| 1444 | 		}}, | ||
| 1445 | 		R = Renderer3D {{ | ||
| 1446 | 			Inputs = {{ | ||
| 1447 | 				Width = Input {{ Value = 64, }}, | ||
| 1448 | 				Height = Input {{ Value = 64, }}, | ||
| 1449 | 				Depth = Input {{ Value = 4, }}, | ||
| 1450 | 				["RendererSoftware.Channels.Z"] = Input {{ Value = 1, }}, | ||
| 1451 | 				["RendererSoftware.Channels.Normal"] = Input {{ Value = 1, }}, | ||
| 1452 | 				SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, | ||
| 1453 | 			}}, | ||
| 1454 | 		}}, | ||
| 1455 | 		CD = ChangeDepth {{ | ||
| 1456 | 			Inputs = {{ | ||
| 1457 | 				Depth = Input {{ Value = 4, }}, | ||
| 1458 | 				Input = Input {{ SourceOp = "R", Source = "Output", }}, | ||
| 1459 | 			}}, | ||
| 1460 | 		}}, | ||
| 1461 | 		BC = BrightnessContrast {{ | ||
| 1462 | 			Inputs = {{ | ||
| 1463 | 				Gain = Input {{ Value = 2.5, }}, | ||
| 1464 | 				Input = Input {{ SourceOp = "CD", Source = "Output", }}, | ||
| 1465 | 			}}, | ||
| 1466 | 		}}, | ||
| 1467 | 		Saver1 = Saver {{ | ||
| 1468 | 			Inputs = {{ | ||
| 1469 | 				OutputFormat = Input {{ Value = FuID {{ "OpenEXRFormat" }}, }}, | ||
| 1470 | 				["OpenEXRFormat.Depth"] = Input {{ Value = {depth_code}, }}, | ||
| 1471 | 				["OpenEXRFormat.Compression"] = Input {{ Value = 3, }}, | ||
| 1472 | 				Clip = Input {{ | ||
| 1473 | 					Value = Clip {{ | ||
| 1474 | 						Filename = "{saver_path_escaped}", | ||
| 1475 | 						FormatID = "OpenEXRFormat", | ||
| 1476 | 						Saving = true, | ||
| 1477 | 					}}, | ||
| 1478 | 				}}, | ||
| 1479 | 				Input = Input {{ SourceOp = "BC", Source = "Output", }}, | ||
| 1480 | 			}}, | ||
| 1481 | 		}}, | ||
| 1482 | 	}}, | ||
| 1483 | 	Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 64, Rate = 24, DepthFull = 4 }} }} }}, | ||
| 1484 | }}"# | ||
| 1485 | ); | ||
| 1486 | |||
| 1487 | let comp = Comp::from_fusion_str(&comp_src).expect("parse EXR Saver comp"); | ||
| 1488 | let summary = export_saver_sequence_with_progress( | ||
| 1489 | &mut engine, | ||
| 1490 | &comp, | ||
| 1491 | &ExportOptions::default(), | ||
| 1492 | None, | ||
| 1493 | |_| {}, | ||
| 1494 | ) | ||
| 1495 | .expect("export EXR via Saver"); | ||
| 1496 | assert_eq!(summary.frames_written, 1); | ||
| 1497 | |||
| 1498 | let out_exr = tmp_dir.join(tag).join("render_0000.exr"); | ||
| 1499 | assert!(out_exr.exists(), "missing exported EXR {}", out_exr.display()); | ||
| 1500 | |||
| 1501 | // Inspect channel metadata & Normal channel values directly in the EXR file. | ||
| 1502 | let meta = ::exr::meta::MetaData::read_from_file(&out_exr, false).expect("read EXR meta"); | ||
| 1503 | let ch_list = &meta.headers[0].channels.list; | ||
| 1504 | let find_ch = |name: &str| { | ||
| 1505 | ch_list | ||
| 1506 | .iter() | ||
| 1507 | .find(|c| c.name.to_string() == name) | ||
| 1508 | .unwrap_or_else(|| panic!("{tag}: missing EXR channel '{name}'")) | ||
| 1509 | }; | ||
| 1510 | for c in ["R", "G", "B", "A", "NX", "NY", "NZ"] { | ||
| 1511 | assert_eq!( | ||
| 1512 | find_ch(c).sample_type, | ||
| 1513 | expected_sample_type, | ||
| 1514 | "{tag}: channel {c} sample type mismatch" | ||
| 1515 | ); | ||
| 1516 | } | ||
| 1517 | assert_eq!( | ||
| 1518 | find_ch("Z").sample_type, | ||
| 1519 | ::exr::meta::attribute::SampleType::F32, | ||
| 1520 | "{tag}: Z channel must always be Float32" | ||
| 1521 | ); | ||
| 1522 | // Verify NX, NY, NZ normal values directly in the exported EXR layer. | ||
| 1523 | let flat_img = ::exr::prelude::read_all_flat_layers_from_file(&out_exr) | ||
| 1524 | .expect("read EXR flat layers"); | ||
| 1525 | let channels = &flat_img.layer_data[0].channel_data.list; | ||
| 1526 | let read_ch_f32 = |name: &str, idx: usize| -> f32 { | ||
| 1527 | let ch = channels | ||
| 1528 | .iter() | ||
| 1529 | .find(|c| c.name.to_string() == name) | ||
| 1530 | .unwrap_or_else(|| panic!("{tag}: missing flat channel '{name}'")); | ||
| 1531 | match &ch.sample_data { | ||
| 1532 | ::exr::prelude::FlatSamples::F16(v) => v[idx].to_f32(), | ||
| 1533 | ::exr::prelude::FlatSamples::F32(v) => v[idx], | ||
| 1534 | ::exr::prelude::FlatSamples::U32(v) => v[idx] as f32, | ||
| 1535 | } | ||
| 1536 | }; | ||
| 1537 | let center_idx = 32 * 64 + 32; | ||
| 1538 | let (nx, ny, nz) = ( | ||
| 1539 | read_ch_f32("NX", center_idx), | ||
| 1540 | read_ch_f32("NY", center_idx), | ||
| 1541 | read_ch_f32("NZ", center_idx), | ||
| 1542 | ); | ||
| 1543 | assert!( | ||
| 1544 | nx.abs() <= 1e-2 && ny.abs() <= 1e-2 && (nz - 1.0).abs() <= 1e-2, | ||
| 1545 | "{tag}: center normal expected ~(0,0,1), got ({nx}, {ny}, {nz})" | ||
| 1546 | ); | ||
| 1547 | assert_eq!( | ||
| 1548 | (read_ch_f32("NX", 0), read_ch_f32("NY", 0), read_ch_f32("NZ", 0)), | ||
| 1549 | (0.0, 0.0, 0.0), | ||
| 1550 | "{tag}: corner normal expected (0,0,0)" | ||
| 1551 | ); | ||
| 1552 | |||
| 1553 | // Reload via Fusion Loader node (media/exr.rs) and verify linear HDR + aux.z! | ||
| 1554 | let out_exr_escaped = out_exr.to_string_lossy().replace('\\', "\\\\"); | ||
| 1555 | let loader_comp_src = format!( | ||
| 1556 | r#"Composition {{ | ||
| 1557 | 	CurrentTime = 0, | ||
| 1558 | 	RenderRange = {{ 0, 0 }}, | ||
| 1559 | 	GlobalRange = {{ 0, 0 }}, | ||
| 1560 | 	Tools = ordered() {{ | ||
| 1561 | 		L = Loader {{ | ||
| 1562 | 			Clips = {{ | ||
| 1563 | 				Clip {{ | ||
| 1564 | 					ID = "Clip1", | ||
| 1565 | 					Filename = "{out_exr_escaped}", | ||
| 1566 | 					FormatID = "OpenEXRFormat", | ||
| 1567 | 					StartFrame = 0, | ||
| 1568 | 					Length = 1, | ||
| 1569 | 					GlobalStart = 0, | ||
| 1570 | 					GlobalEnd = 0, | ||
| 1571 | 				}}, | ||
| 1572 | 			}}, | ||
| 1573 | 		}}, | ||
| 1574 | 	}}, | ||
| 1575 | 	Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 64, Rate = 24, DepthFull = 4 }} }} }}, | ||
| 1576 | }}"# | ||
| 1577 | ); | ||
| 1578 | let loader_comp = Comp::from_fusion_str(&loader_comp_src).expect("parse Loader comp"); | ||
| 1579 | let l_id = loader_comp.find_node("L").expect("find Loader"); | ||
| 1580 | let (loaded_tex, _) = engine.evaluate(&loader_comp, l_id, 0.0); | ||
| 1581 | |||
| 1582 | let rgba = engine | ||
| 1583 | .readback_rgba_f32(&loaded_tex) | ||
| 1584 | .expect("readback reloaded EXR RGBA"); | ||
| 1585 | let center_off = (32 * 64 + 32) * 4; | ||
| 1586 | assert!( | ||
| 1587 | rgba[center_off] > 2.0, | ||
| 1588 | "{tag}: HDR linear R must be preserved (> 2.0), got {}", | ||
| 1589 | rgba[center_off] | ||
| 1590 | ); | ||
| 1591 | assert!( | ||
| 1592 | (rgba[center_off] - 2.5).abs() <= 0.03, | ||
| 1593 | "{tag}: expected R ~ 2.5, got {}", | ||
| 1594 | rgba[center_off] | ||
| 1595 | ); | ||
| 1596 | assert!( | ||
| 1597 | (rgba[center_off + 1] - 0.5).abs() <= 0.03, | ||
| 1598 | "{tag}: expected G ~ 0.5, got {}", | ||
| 1599 | rgba[center_off + 1] | ||
| 1600 | ); | ||
| 1601 | assert!( | ||
| 1602 | (rgba[center_off + 2] - 0.25).abs() <= 0.03, | ||
| 1603 | "{tag}: expected B ~ 0.25, got {}", | ||
| 1604 | rgba[center_off + 2] | ||
| 1605 | ); | ||
| 1606 | assert!((rgba[center_off + 3] - 1.0).abs() <= 0.01); | ||
| 1607 | |||
| 1608 | let aux = loaded_tex | ||
| 1609 | .aux | ||
| 1610 | .as_ref() | ||
| 1611 | .expect("reloaded EXR must carry aux channels"); | ||
| 1612 | let z_tex = aux.z.as_ref().expect("reloaded EXR must carry aux.z"); | ||
| 1613 | let z_vals = engine | ||
| 1614 | .readback_aux_z_f32(z_tex) | ||
| 1615 | .expect("readback reloaded EXR aux.z"); | ||
| 1616 | let center_z = z_vals[32 * 64 + 32]; | ||
| 1617 | let corner_z = z_vals[0]; | ||
| 1618 | assert!( | ||
| 1619 | (center_z - (-2.0)).abs() <= 1e-3, | ||
| 1620 | "{tag}: reloaded center Z expected -2.0, got {center_z}" | ||
| 1621 | ); | ||
| 1622 | assert_eq!( | ||
| 1623 | corner_z, | ||
| 1624 | crate::cache::EMPTY_Z_SENTINEL, | ||
| 1625 | "{tag}: reloaded empty corner Z expected -1e30, got {corner_z}" | ||
| 1626 | ); | ||
| 1627 | } | ||
| 1628 | |||
| 1629 | // Also verify write_exr_rgba_with_aux across all 6 Fusion compression modes. | ||
| 1630 | let rgba_sample = vec![2.5, 0.5, 0.25, 1.0, 0.0, 0.0, 0.0, 0.0]; | ||
| 1631 | let z_sample = vec![-2.0, crate::cache::EMPTY_Z_SENTINEL]; | ||
| 1632 | let n_sample = vec![0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]; | ||
| 1633 | for comp_mode in [ | ||
| 1634 | ExrCompression::Uncompressed, | ||
| 1635 | ExrCompression::Rle, | ||
| 1636 | ExrCompression::Zip1, | ||
| 1637 | ExrCompression::Zip16, | ||
| 1638 | ExrCompression::Piz, | ||
| 1639 | ExrCompression::Pxr24, | ||
| 1640 | ] { | ||
| 1641 | let p = tmp_dir.join(format!("comp_{comp_mode:?}.exr")); | ||
| 1642 | write_exr_rgba_with_aux( | ||
| 1643 | &p, | ||
| 1644 | [2, 1], | ||
| 1645 | &rgba_sample, | ||
| 1646 | Some(&z_sample), | ||
| 1647 | Some(&n_sample), | ||
| 1648 | ExrDepth::Float16, | ||
| 1649 | comp_mode, | ||
| 1650 | ) | ||
| 1651 | .unwrap_or_else(|e| panic!("write EXR {comp_mode:?} failed: {e}")); | ||
| 1652 | assert!(p.exists()); | ||
| 1653 | } | ||
| 1654 | |||
| 1655 | let _ = std::fs::remove_dir_all(&tmp_dir); | ||
| 1656 | } | ||
| 1657 | |||
| 1658 | #[test] | ||
| 1659 | fn exports_exr_saver_sequence_and_stops_cleanly_on_cancel() { | ||
| 1660 | let tmp_dir = std::env::temp_dir().join(format!( | ||
| 1661 | "fission-exr-seq-cancel-test-{}", | ||
| 1662 | std::process::id() | ||
| 1663 | )); | ||
| 1664 | let _ = std::fs::remove_dir_all(&tmp_dir); | ||
| 1665 | |||
| 1666 | let full_dir = tmp_dir.join("full"); | ||
| 1667 | let cancel_dir = tmp_dir.join("cancel"); | ||
| 1668 | |||
| 1669 | let make_comp = |dir: &Path| { | ||
| 1670 | let saver_path = dir.join("shot_0000.exr"); | ||
| 1671 | let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); | ||
| 1672 | let comp_src = format!( | ||
| 1673 | r#"Composition {{ | ||
| 1674 | 	CurrentTime = 10, | ||
| 1675 | 	RenderRange = {{ 10, 15 }}, | ||
| 1676 | 	GlobalRange = {{ 0, 100 }}, | ||
| 1677 | 	Tools = ordered() {{ | ||
| 1678 | 		BG = Background {{ | ||
| 1679 | 			Inputs = {{ | ||
| 1680 | 				Width = Input {{ Value = 64, }}, | ||
| 1681 | 				Height = Input {{ Value = 32, }}, | ||
| 1682 | 				Depth = Input {{ Value = 4, }}, | ||
| 1683 | 				TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, | ||
| 1684 | 				TopLeftGreen = Input {{ Value = 0.25, }}, | ||
| 1685 | 				TopLeftBlue = Input {{ Value = 0.5, }}, | ||
| 1686 | 				TopLeftAlpha = Input {{ Value = 1, }}, | ||
| 1687 | 			}}, | ||
| 1688 | 		}}, | ||
| 1689 | 		BGRed = BezierSpline {{ | ||
| 1690 | 			KeyFrames = {{ | ||
| 1691 | 				[10] = {{ 0.5, Flags = {{ Linear = true }} }}, | ||
| 1692 | 				[15] = {{ 3.0, Flags = {{ Linear = true }} }}, | ||
| 1693 | 			}}, | ||
| 1694 | 		}}, | ||
| 1695 | 		Saver1 = Saver {{ | ||
| 1696 | 			Inputs = {{ | ||
| 1697 | 				OutputFormat = Input {{ Value = FuID {{ "OpenEXRFormat" }}, }}, | ||
| 1698 | 				["OpenEXRFormat.Depth"] = Input {{ Value = 0, }}, | ||
| 1699 | 				["OpenEXRFormat.Compression"] = Input {{ Value = 3, }}, | ||
| 1700 | 				Clip = Input {{ | ||
| 1701 | 					Value = Clip {{ | ||
| 1702 | 						Filename = "{saver_path_escaped}", | ||
| 1703 | 						FormatID = "OpenEXRFormat", | ||
| 1704 | 						Saving = true, | ||
| 1705 | 					}}, | ||
| 1706 | 				}}, | ||
| 1707 | 				Input = Input {{ SourceOp = "BG", Source = "Output", }}, | ||
| 1708 | 			}}, | ||
| 1709 | 		}}, | ||
| 1710 | 	}}, | ||
| 1711 | 	Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, Rate = 24, DepthFull = 4 }} }} }}, | ||
| 1712 | }}"# | ||
| 1713 | ); | ||
| 1714 | Comp::from_fusion_str(&comp_src).expect("parse EXR sequence comp") | ||
| 1715 | }; | ||
| 1716 | |||
| 1717 | let Ok(mut engine) = Engine::new_headless() else { | ||
| 1718 | return; | ||
| 1719 | }; | ||
| 1720 | |||
| 1721 | // 1. Verify export_saver_png_sequence_with_progress automatically dispatches to OpenEXR! | ||
| 1722 | let full_comp = make_comp(&full_dir); | ||
| 1723 | let mut seen_frames = Vec::new(); | ||
| 1724 | let summary = export_saver_png_sequence_with_progress( | ||
| 1725 | &mut engine, | ||
| 1726 | &full_comp, | ||
| 1727 | &ExportOptions::default(), | ||
| 1728 | None, | ||
| 1729 | |p| seen_frames.push(p.frame), | ||
| 1730 | ) | ||
| 1731 | .expect("export EXR sequence via Saver dispatcher"); | ||
| 1732 | assert_eq!(summary.frames_written, 6); | ||
| 1733 | assert_eq!(seen_frames, vec![10, 11, 12, 13, 14, 15]); | ||
| 1734 | for f in 10..=15 { | ||
| 1735 | let p = full_dir.join(format!("shot_{f:04}.exr")); | ||
| 1736 | assert!(p.exists(), "missing EXR frame {}", p.display()); | ||
| 1737 | } | ||
| 1738 | let last_exr = full_dir.join("shot_0015.exr"); | ||
| 1739 | let last_exr_escaped = last_exr.to_string_lossy().replace('\\', "\\\\"); | ||
| 1740 | let loader_comp = Comp::from_fusion_str(&format!( | ||
| 1741 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ | ||
| 1742 | L = Loader {{ Clips = {{ Clip {{ ID = "Clip1", Filename = "{last_exr_escaped}", StartFrame = 0, Length = 1, GlobalStart = 0, GlobalEnd = 0, }} }}, }}, | ||
| 1743 | }}, Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, DepthFull = 4 }} }} }} }}"# | ||
| 1744 | )) | ||
| 1745 | .unwrap(); | ||
| 1746 | let (ltex, _) = engine.evaluate(&loader_comp, loader_comp.find_node("L").unwrap(), 0.0); | ||
| 1747 | let lrgba = engine.readback_rgba_f32(&ltex).unwrap(); | ||
| 1748 | assert!( | ||
| 1749 | (lrgba[0] - 3.0).abs() <= 0.02, | ||
| 1750 | "frame 15 HDR red expected ~3.0, got {}", | ||
| 1751 | lrgba[0] | ||
| 1752 | ); | ||
| 1753 | |||
| 1754 | // 2. Verify cooperative cancellation stops cleanly and leaves zero leaked temp files. | ||
| 1755 | let cancel_comp = make_comp(&cancel_dir); | ||
| 1756 | let control = ExportControl::new(); | ||
| 1757 | let ctrl_cb = control.clone(); | ||
| 1758 | let mut reported = Vec::new(); | ||
| 1759 | let err = export_saver_exr_sequence_with_progress( | ||
| 1760 | &mut engine, | ||
| 1761 | &cancel_comp, | ||
| 1762 | &ExportOptions::default(), | ||
| 1763 | Some(&control), | ||
| 1764 | |p| { | ||
| 1765 | reported.push(p.completed_frames); | ||
| 1766 | if p.completed_frames >= 2 { | ||
| 1767 | ctrl_cb.cancel(); | ||
| 1768 | } | ||
| 1769 | }, | ||
| 1770 | ) | ||
| 1771 | .expect_err("EXR sequence export should cancel early"); | ||
| 1772 | assert_eq!(err, "Cancelled"); | ||
| 1773 | assert_eq!(reported, vec![1, 2]); | ||
| 1774 | assert!(!cancel_dir.join("shot_0015.exr").exists()); | ||
| 1775 | |||
| 1776 | if cancel_dir.exists() { | ||
| 1777 | for entry in std::fs::read_dir(&cancel_dir).expect("read cancel_dir") { | ||
| 1778 | let entry = entry.expect("dir entry"); | ||
| 1779 | let path = entry.path(); | ||
| 1780 | assert_eq!( | ||
| 1781 | path.extension().and_then(|e| e.to_str()), | ||
| 1782 | Some("exr"), | ||
| 1783 | "unexpected leaked temp/partial file: {}", | ||
| 1784 | path.display() | ||
| 1785 | ); | ||
| 1786 | ::exr::meta::MetaData::read_from_file(&path, false) | ||
| 1787 | .unwrap_or_else(|e| panic!("corrupt EXR file {}: {e}", path.display())); | ||
| 1788 | } | ||
| 1789 | } | ||
| 1790 | |||
| 1791 | let _ = std::fs::remove_dir_all(&tmp_dir); | ||
| 1792 | } |