diff --git a/crates/processing_pyo3/src/color.rs b/crates/processing_pyo3/src/color.rs index a6ed2974..baad62b0 100644 --- a/crates/processing_pyo3/src/color.rs +++ b/crates/processing_pyo3/src/color.rs @@ -69,8 +69,16 @@ pub(crate) fn extract_color_with_mode( Ok(space.gray(v, native[3])) } 2 => { - let v = convert_channel(mode, &args.get_item(0)?, 0)?; + let first = args.get_item(0)?; let a = convert_channel(mode, &args.get_item(1)?, 3)?; + // a color with its alpha replaced, e.g. `fill(c, 128)` + if let Ok(c) = first.extract::>() { + return Ok(c.0.with_alpha(a)); + } + if let Ok(s) = first.extract::() { + return Ok(parse_hex(&s)?.with_alpha(a)); + } + let v = convert_channel(mode, &first, 0)?; Ok(space.gray(v, a)) } 3 => { diff --git a/crates/processing_pyo3/src/graphics.rs b/crates/processing_pyo3/src/graphics.rs index dd1417af..53d03ccf 100644 --- a/crates/processing_pyo3/src/graphics.rs +++ b/crates/processing_pyo3/src/graphics.rs @@ -698,13 +698,34 @@ impl Image { .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } - /// Read a single pixel as a `Color` (Processing `get`); outside the image it is transparent black. - fn get(&self, x: i64, y: i64) -> PyResult { - let p = image_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))] + fn get( + &self, + py: Python<'_>, + x: i64, + y: i64, + w: Option, + h: Option, + ) -> PyResult> { + match (w, h) { + (Some(w), Some(h)) => { + let entity = image_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 = image_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 image it is dropped. Accepts a @@ -1073,9 +1094,32 @@ impl Graphics { self.surface.focused() } - #[getter] - pub fn pixel_density(&self) -> PyResult { - self.surface.pixel_density() + /// `pixel_density()` reads the density, `pixel_density(d)` sets it. + #[pyo3(signature = (density=None))] + pub fn pixel_density(&self, py: Python<'_>, density: Option) -> PyResult> { + let offscreen = image_size(self.surface.entity).is_ok(); + match density { + None if offscreen => Ok(1.0f32.into_pyobject(py)?.into_any().unbind()), + None => Ok(self + .surface + .pixel_density()? + .into_pyobject(py)? + .into_any() + .unbind()), + Some(d) if offscreen => { + if d == 1.0 { + Ok(py.None()) + } else { + Err(PyValueError::new_err( + "an offscreen Graphics has a pixel density of 1", + )) + } + } + Some(d) => { + self.surface.set_pixel_density(d)?; + Ok(py.None()) + } + } } #[getter] @@ -2547,19 +2591,54 @@ impl Graphics { composite_apply(self.entity, src_entity, code, sr, dr, opacity) } - /// Copies a source onto this graphics, replacing pixels (Processing `copy`). - /// `src` may be an `Image`, webcam, or `Graphics`. See `blend` for the - /// `src_rect`/`dst_rect` semantics. - #[pyo3(signature = (src, *, src_rect=None, dst_rect=None))] + /// Copies pixels onto this graphics from an `Image`, webcam, `Graphics` or itself. + #[pyo3(signature = (*args, src_rect=None, dst_rect=None))] pub fn copy( &self, - src: &Bound<'_, PyAny>, + args: &Bound<'_, PyTuple>, src_rect: Option<[f32; 4]>, dst_rect: Option<[f32; 4]>, ) -> PyResult<()> { - let src_entity = src.extract::()?.texture()?; - let sr = normalize_src_rect(src_entity, src_rect)?; + let (src, rects) = match args.len() { + 0 => (None, None), + 1 => (Some(args.get_item(0)?), None), + 8 => (None, Some(args.extract::<[f32; 8]>()?)), + 9 => ( + Some(args.get_item(0)?), + Some(args.get_slice(1, 9).extract::<[f32; 8]>()?), + ), + _ => { + return Err(pyo3::exceptions::PyTypeError::new_err( + "copy() takes src, or sx, sy, sw, sh, dx, dy, dw, dh, or src followed by those eight", + )); + } + }; + let (src_rect, dst_rect) = match rects { + Some([sx, sy, sw, sh, dx, dy, dw, dh]) => { + (Some([sx, sy, sw, sh]), Some([dx, dy, dw, dh])) + } + None => (src_rect, dst_rect), + }; let dr = normalize_rect(dst_rect, self.width as f32, self.height as f32); + + // this graphics as its own source + let own = match &src { + None => true, + Some(src) => src + .extract::>() + .is_ok_and(|g| g.entity == self.entity), + }; + if own { + use shader_value::ShaderValue; + let sr = normalize_rect(src_rect, self.width as f32, self.height as f32); + let filter = filter_copy_region().map_err(rt_err)?; + filter_set(filter, "src_rect", ShaderValue::Float4(sr)).map_err(rt_err)?; + filter_set(filter, "dst_rect", ShaderValue::Float4(dr)).map_err(rt_err)?; + return graphics_apply_filter(self.entity, filter).map_err(rt_err); + } + + let src_entity = src.unwrap().extract::()?.texture()?; + let sr = normalize_src_rect(src_entity, src_rect)?; composite_apply(self.entity, src_entity, COMPOSITE_MODE_REPLACE, sr, dr, 1.0) } diff --git a/crates/processing_pyo3/src/lib.rs b/crates/processing_pyo3/src/lib.rs index 5dfdddcf..7826e980 100644 --- a/crates/processing_pyo3/src/lib.rs +++ b/crates/processing_pyo3/src/lib.rs @@ -2208,14 +2208,14 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module, signature = (src, *, src_rect=None, dst_rect=None))] + #[pyo3(pass_module, signature = (*args, src_rect=None, dst_rect=None))] fn copy( module: &Bound<'_, PyModule>, - src: &Bound<'_, PyAny>, + args: &Bound<'_, PyTuple>, src_rect: Option<[f32; 4]>, dst_rect: Option<[f32; 4]>, ) -> PyResult<()> { - graphics!(module).copy(src, src_rect, dst_rect) + graphics!(module).copy(args, src_rect, dst_rect) } #[pyfunction] diff --git a/crates/processing_render/src/image.rs b/crates/processing_render/src/image.rs index 5183aebe..74a3d847 100644 --- a/crates/processing_render/src/image.rs +++ b/crates/processing_render/src/image.rs @@ -658,6 +658,48 @@ pub fn cpu_pixels(world: &World, entity: Entity) -> Result> { ) } +/// The bytes of a `width` x `height` block at (`x`, `y`) in the image's format. +pub fn cpu_region( + world: &World, + entity: Entity, + x: i64, + y: i64, + width: u32, + height: u32, +) -> Result<(Vec, TextureFormat)> { + let p_image = world + .get::(entity) + .ok_or(ProcessingError::ImageNotFound)?; + let size = p_image.size; + let format = p_image.texture_format; + let data = world + .resource::>() + .get(&p_image.handle) + .and_then(|image| image.data.as_deref()) + .ok_or(ProcessingError::ImageNotFound)?; + let px_size = pixel_size(format)?; + let stride = size.width as usize * px_size; + check_len(data.len(), stride, size, format)?; + + let mut region = vec![0u8; width as usize * height as usize * px_size]; + // the columns of the block that fall inside the image + let x0 = x.clamp(0, size.width as i64); + let x1 = (x + width as i64).clamp(0, size.width as i64); + if x0 < x1 { + let run = (x1 - x0) as usize * px_size; + for row in 0..height as i64 { + let src_y = y + row; + if src_y < 0 || src_y >= size.height as i64 { + continue; + } + let src = src_y as usize * stride + x0 as usize * px_size; + let dst = (row as usize * width as usize + (x0 - x) as usize) * px_size; + region[dst..dst + run].copy_from_slice(&data[src..src + run]); + } + } + Ok((region, format)) +} + /// A CPU buffer that disagrees with the image size would make row math index out of bounds fn check_len(len: usize, stride: usize, size: Extent3d, format: TextureFormat) -> Result<()> { let expected = stride * size.height as usize; diff --git a/crates/processing_render/src/lib.rs b/crates/processing_render/src/lib.rs index 6f4c5a50..bae4f96f 100644 --- a/crates/processing_render/src/lib.rs +++ b/crates/processing_render/src/lib.rs @@ -638,6 +638,7 @@ builtin_filter!(filter_erode, ERODE); builtin_filter!(filter_dilate, DILATE); builtin_filter!(filter_composite, COMPOSITE); builtin_filter!(filter_feedback, FEEDBACK); +builtin_filter!(filter_copy_region, COPY_REGION); pub fn filter_set_passes(entity: Entity, passes: u32) -> error::Result<()> { app_mut(|app| { @@ -1244,6 +1245,34 @@ pub fn image_get_pixel(entity: Entity, x: i64, y: i64) -> error::Result error::Result { + if width == 0 || height == 0 { + return Err(error::ProcessingError::InvalidArgument( + "a sub-image needs a width and height above zero".to_string(), + )); + } + app_mut(|app| { + image::sync_cpu(app, entity)?; + let (data, format) = image::cpu_region(app.world(), entity, x, y, width, height)?; + let size = Extent3d { + width, + height, + depth_or_array_layers: 1, + }; + Ok(app + .world_mut() + .run_system_cached_with(image::create, (size, data, format)) + .unwrap()) + }) +} + /// The image's pixels; served from the CPU copy unless the GPU wrote the texture pub fn image_readback(entity: Entity) -> error::Result> { app_mut(|app| { @@ -2705,21 +2734,17 @@ pub fn font_load(path: &str) -> error::Result { } } -/// Create a font handle from an existing font family name. +/// Create a font handle for a family name; an unknown family falls back to the default font. pub fn font_create(name: &str) -> error::Result { - use text::font::{Font, TextContext}; + use text::font::{DEFAULT_FONT_FAMILY, Font, TextContext}; app_mut(|app| { let text_cx = app.world().resource::().clone(); - if !text_cx.has_font(name) { - return Err(error::ProcessingError::FontNotFound); - } - let entity = app - .world_mut() - .spawn(Font { - family_name: name.to_string(), - }) - .id(); + let family_name = text_cx.resolve_family(name).unwrap_or_else(|| { + warn!("font {name:?} is not installed, using the default font"); + DEFAULT_FONT_FAMILY.to_string() + }); + let entity = app.world_mut().spawn(Font { family_name }).id(); Ok(entity) }) } diff --git a/crates/processing_render/src/render/filter.rs b/crates/processing_render/src/render/filter.rs index 00a2cc7a..c88dd633 100644 --- a/crates/processing_render/src/render/filter.rs +++ b/crates/processing_render/src/render/filter.rs @@ -43,6 +43,7 @@ pub mod builtin { pub const BLUR: &str = include_str!("filters/blur.wgsl"); pub const COMPOSITE: &str = include_str!("filters/composite.wgsl"); pub const FEEDBACK: &str = include_str!("filters/feedback.wgsl"); + pub const COPY_REGION: &str = include_str!("filters/copy_region.wgsl"); } #[derive(Component)] diff --git a/crates/processing_render/src/render/filters/copy_region.wgsl b/crates/processing_render/src/render/filters/copy_region.wgsl new file mode 100644 index 00000000..444f7108 --- /dev/null +++ b/crates/processing_render/src/render/filters/copy_region.wgsl @@ -0,0 +1,20 @@ +// Copies one rectangle of the surface onto another; rects are normalized (x0, y0, x1, y1). +import processing::filter::{sample, FullscreenVertexOutput}; + +struct CopyRegionParams { + src_rect: vec4, + dst_rect: vec4, +} + +@group(1) @binding(0) var copy_region: CopyRegionParams; + +@fragment +fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4 { + let dmin = copy_region.dst_rect.xy; + let dmax = copy_region.dst_rect.zw; + if (in.uv.x < dmin.x || in.uv.y < dmin.y || in.uv.x > dmax.x || in.uv.y > dmax.y) { + return sample(in.uv); + } + let local = (in.uv - dmin) / max(dmax - dmin, vec2(1e-6)); + return sample(mix(copy_region.src_rect.xy, copy_region.src_rect.zw, local)); +} diff --git a/crates/processing_render/src/text/font.rs b/crates/processing_render/src/text/font.rs index e8f31fbb..55afafb7 100644 --- a/crates/processing_render/src/text/font.rs +++ b/crates/processing_render/src/text/font.rs @@ -77,6 +77,18 @@ impl TextContext { let mut inner = self.inner.lock().unwrap(); inner.font_cx.collection.family_id(name).is_some() } + + /// The installed family for a name, resolving generic names such as `sans-serif`. + pub fn resolve_family(&self, name: &str) -> Option { + let mut inner = self.inner.lock().unwrap(); + let collection = &mut inner.font_cx.collection; + if let Some(id) = collection.family_id(name) { + return collection.family_name(id).map(str::to_string); + } + let generic = fontique::GenericFamily::parse(name)?; + let id = collection.generic_families(generic).next()?; + collection.family_name(id).map(str::to_string) + } } impl Default for TextContext {