diff --git a/crates/processing_pyo3/src/graphics.rs b/crates/processing_pyo3/src/graphics.rs index 53d03cc..379cbd0 100644 --- a/crates/processing_pyo3/src/graphics.rs +++ b/crates/processing_pyo3/src/graphics.rs @@ -1196,13 +1196,34 @@ impl Graphics { write_png_file(filename, raw.width, raw.height, &rgba) } - /// Read a single pixel as a `Color` (Processing `get`). - pub fn get(&self, x: i64, y: i64) -> PyResult { - let p = graphics_get_pixel(self.entity, x, y) - .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; - Ok(crate::color::PyColor(bevy::prelude::Color::Srgba( - p.map_or(Srgba::NONE, pixel_to_srgba), - ))) + /// `get(x, y)` reads one pixel as a `Color`; `get(x, y, w, h)` copies a block into a new `Image`. + #[pyo3(signature = (x, y, w=None, h=None))] + pub fn get( + &self, + py: Python<'_>, + x: i64, + y: i64, + w: Option, + h: Option, + ) -> PyResult> { + match (w, h) { + (Some(w), Some(h)) => { + let entity = graphics_get_region(self.entity, x, y, w, h) + .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; + Ok(Py::new(py, Image::wrap(entity))?.into_any()) + } + (None, None) => { + let p = graphics_get_pixel(self.entity, x, y) + .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; + let color = crate::color::PyColor(bevy::prelude::Color::Srgba( + p.map_or(Srgba::NONE, pixel_to_srgba), + )); + Ok(Py::new(py, color)?.into_any()) + } + _ => Err(pyo3::exceptions::PyTypeError::new_err( + "get() takes x, y or x, y, w, h", + )), + } } /// Write a single pixel (Processing `set`); outside the canvas it is dropped. diff --git a/crates/processing_pyo3/src/lib.rs b/crates/processing_pyo3/src/lib.rs index 7826e98..96a4ae3 100644 --- a/crates/processing_pyo3/src/lib.rs +++ b/crates/processing_pyo3/src/lib.rs @@ -2733,9 +2733,15 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module)] - fn get(module: &Bound<'_, PyModule>, x: i64, y: i64) -> PyResult { - graphics!(module).get(x, y) + #[pyo3(pass_module, signature = (x, y, w=None, h=None))] + fn get( + module: &Bound<'_, PyModule>, + x: i64, + y: i64, + w: Option, + h: Option, + ) -> PyResult> { + graphics!(module).get(module.py(), x, y, w, h) } #[pyfunction] diff --git a/crates/processing_render/src/destroy.rs b/crates/processing_render/src/destroy.rs new file mode 100644 index 0000000..7278594 --- /dev/null +++ b/crates/processing_render/src/destroy.rs @@ -0,0 +1,94 @@ +//! Deferred destroy: a destroy waits until every command buffer has drained. + +use bevy::prelude::*; +use processing_core::error::Result; + +use crate::render::command::CommandBuffer; + +type Destroy = Box Result<()> + Send + Sync>; + +/// Destroys waiting for the queued draw commands to run. +#[derive(Resource, Default)] +pub struct PendingDestroys(Vec); + +/// Whether any graphics still has draw commands to run. +fn commands_queued(world: &mut World) -> bool { + world + .query::<&CommandBuffer>() + .iter(world) + .any(|buffer| !buffer.commands.is_empty()) +} + +/// Runs `destroy` now, or once the queued draw commands have run. +pub fn request( + world: &mut World, + destroy: impl FnOnce(&mut World) -> Result<()> + Send + Sync + 'static, +) -> Result<()> { + if commands_queued(world) { + world + .get_resource_or_insert_with(PendingDestroys::default) + .0 + .push(Box::new(destroy)); + Ok(()) + } else { + destroy(world) + } +} + +/// Runs the waiting destroys if no draw command can still reference them. +pub fn run_pending(world: &mut World) { + if !world.contains_resource::() || commands_queued(world) { + return; + } + let pending = std::mem::take(&mut world.resource_mut::().0); + for destroy in pending { + if let Err(error) = destroy(world) { + debug!("deferred destroy failed: {error}"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::render::command::DrawCommand; + + #[derive(Component)] + struct Thing; + + fn despawn(entity: Entity) -> impl FnOnce(&mut World) -> Result<()> + Send + Sync { + move |world| { + world.despawn(entity); + Ok(()) + } + } + + #[test] + fn a_destroy_runs_at_once_when_nothing_is_queued() { + let mut world = World::new(); + world.spawn(CommandBuffer::new()); + let thing = world.spawn(Thing).id(); + request(&mut world, despawn(thing)).unwrap(); + assert!(world.get_entity(thing).is_err()); + } + + #[test] + fn a_destroy_waits_for_queued_commands() { + let mut world = World::new(); + let mut buffer = CommandBuffer::new(); + buffer.push(DrawCommand::NoStroke); + let graphics = world.spawn(buffer).id(); + let thing = world.spawn(Thing).id(); + + request(&mut world, despawn(thing)).unwrap(); + run_pending(&mut world); + assert!( + world.get_entity(thing).is_ok(), + "still referenced by queued commands" + ); + + world.get_mut::(graphics).unwrap().clear(); + run_pending(&mut world); + assert!(world.get_entity(thing).is_err()); + } +} diff --git a/crates/processing_render/src/graphics.rs b/crates/processing_render/src/graphics.rs index dbebd92..8fcf390 100644 --- a/crates/processing_render/src/graphics.rs +++ b/crates/processing_render/src/graphics.rs @@ -762,6 +762,7 @@ pub fn flush(app: &mut App, entity: Entity) -> Result<()> { } } graphics_mut!(app, entity).remove::(); + crate::destroy::run_pending(app.world_mut()); Ok(()) } @@ -875,6 +876,43 @@ fn pixel_scale(app: &App, entity: Entity) -> Result<(u32, u32, f64, f64)> { )) } +/// The color of logical pixel (`lx`, `ly`), an alpha-weighted average of its physical pixels. +fn logical_pixel( + data: &[u8], + format: TextureFormat, + (pw, ph): (usize, usize), + (sx, sy): (f64, f64), + lx: i64, + ly: i64, +) -> Result { + let px_size = pixel_size(format)?; + let px0 = ((lx as f64 * sx) as usize).min(pw - 1); + let py0 = ((ly as f64 * sy) as usize).min(ph - 1); + let px1 = (((lx + 1) as f64 * sx) as usize).clamp(px0 + 1, pw); + let py1 = (((ly + 1) as f64 * sy) as usize).clamp(py0 + 1, ph); + let mut sum = [0.0f32; 4]; + for py in py0..py1 { + for px in px0..px1 { + let at = (py * pw + px) * px_size; + let p = crate::image::decode_pixel(&data[at..at + px_size], format)?; + sum[0] += p.red * p.alpha; + sum[1] += p.green * p.alpha; + sum[2] += p.blue * p.alpha; + sum[3] += p.alpha; + } + } + if sum[3] <= 0.0 { + return Ok(LinearRgba::NONE); + } + let count = ((px1 - px0) * (py1 - py0)) as f32; + Ok(LinearRgba::new( + sum[0] / sum[3], + sum[1] / sum[3], + sum[2] / sum[3], + sum[3] / count, + )) +} + /// The pixel at logical (`x`, `y`); `None` outside the canvas pub fn get_pixel(app: &mut App, entity: Entity, x: i64, y: i64) -> Result> { let (lw, lh, sx, sy) = pixel_scale(app, entity)?; @@ -889,11 +927,60 @@ pub fn get_pixel(app: &mut App, entity: Entity, x: i64, y: i64) -> Result