mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Add the 'Pixels' type and the GPU readback of an image's effects
This commit is contained in:
1 parent
7469ecce35
commit
6f4ef1fe3d
6 files changed
+765
-20
No files matched your search
@@ -312,6 +312,29 @@ mod cpu {
|
||||
}
|
||||
}
|
||||
|
||||
/// An image's pixels as it's drawn, with its effects and fill carried out on its own pixel grid.
|
||||
/// A node input of this type has the compiler read them back from the image wired into it, which carries its effects as attributes until then.
|
||||
#[derive(Clone, Debug, Default, PartialEq, DynAny, core_types::CacheHash)]
|
||||
pub struct Pixels(Raster<CPU>);
|
||||
|
||||
impl Pixels {
|
||||
pub fn new(raster: Raster<CPU>) -> Self {
|
||||
Self(raster)
|
||||
}
|
||||
|
||||
pub fn into_raster(self) -> Raster<CPU> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Pixels {
|
||||
type Target = Image<Color>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.data()
|
||||
}
|
||||
}
|
||||
|
||||
pub use gpu::GPU;
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub use gpu::{Texture, TextureWeakRef};
|
||||
|
||||
@@ -6024,6 +6024,12 @@ pub(crate) fn render_raster_cpu_image_svg(image: &Raster<CPU>, transform: DAffin
|
||||
}
|
||||
}
|
||||
|
||||
/// The adjustments at the start of the image's effects that its render carries out on its own pixels, ahead of the rest.
|
||||
pub fn leading_raster_adjustments(item: &Item<Raster<CPU>>) -> Vec<Adjustment> {
|
||||
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
ItemRef::Item(item).compositing(&RenderParams::default(), transform).leading_adjustments()
|
||||
}
|
||||
|
||||
/// Draws one item of CPU raster content into the Vello scene.
|
||||
fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster<CPU>>, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
|
||||
let Some(image) = item.element() else { return };
|
||||
|
||||
@@ -2,6 +2,7 @@ mod buffer;
|
||||
mod context;
|
||||
mod deferred_svg_images;
|
||||
mod pipeline;
|
||||
mod raster_readback;
|
||||
mod texture_cache;
|
||||
pub mod texture_conversion;
|
||||
mod vello_adjustments;
|
||||
@@ -75,6 +76,19 @@ impl WgpuExecutor {
|
||||
/// Renders the document scene `draw` draws, with its content placed by `view`, into a new texture of `size` with straight alpha.
|
||||
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
||||
pub fn render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
|
||||
Ok(self.render_vello_and_failure(size, view, draw)?.0)
|
||||
}
|
||||
|
||||
/// Like [`Self::render_vello`], but failing rather than leaving transparent a part Vello GPU fails to render, for a render read back as data.
|
||||
pub fn try_render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
|
||||
match self.render_vello_and_failure(size, view, draw)? {
|
||||
(_, Some(failure)) => anyhow::bail!("Vello GPU failed to render: {failure}"),
|
||||
(texture, None) => Ok(texture),
|
||||
}
|
||||
}
|
||||
|
||||
/// The texture [`Self::render_vello`] renders, with the first failure that left part of it transparent.
|
||||
fn render_vello_and_failure(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<(Texture, Option<String>)> {
|
||||
let limit = self.context().device.limits().max_texture_dimension_2d;
|
||||
if size.x > limit || size.y > limit {
|
||||
anyhow::bail!("Render size {size} exceeds the GPU's texture size limit of {limit}");
|
||||
@@ -84,11 +98,12 @@ impl WgpuExecutor {
|
||||
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
|
||||
|
||||
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
self.inner
|
||||
let failure = self
|
||||
.inner
|
||||
.vello_renderer
|
||||
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
|
||||
|
||||
Ok(texture)
|
||||
Ok((texture, failure))
|
||||
}
|
||||
|
||||
/// Renders a scene drawn beforehand, on a canvas the caller owns, into a new texture of the scene's size with straight alpha.
|
||||
|
||||
@@ -0,0 +1,648 @@
|
||||
use crate::WgpuExecutor;
|
||||
use crate::texture_conversion::download_row_bytes;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::effects::{EffectOperation, Effects};
|
||||
use raster_kernels::adjustments::preserves_alpha;
|
||||
use raster_kernels::raster_effects::adjusted_raster;
|
||||
use raster_types::{CPU, Image, Pixels, Raster};
|
||||
use rendering::{Render, RenderOutputType, RenderParams, leading_raster_adjustments};
|
||||
|
||||
/// The most pixels an image may grow to with the margin its effects paint into, beyond which the margin is cut short.
|
||||
const MAX_PIXELS_WITH_MARGIN: f64 = (1 << 24) as f64;
|
||||
|
||||
/// The GPU's limits that a readback's renders and downloads stay within.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ReadbackLimits {
|
||||
/// The most pixels across or down a texture may have, which an image larger than it is downscaled to when uploaded whole.
|
||||
texture_size: u32,
|
||||
/// The most bytes a download buffer may hold.
|
||||
buffer_size: u64,
|
||||
}
|
||||
|
||||
impl ReadbackLimits {
|
||||
fn of(executor: &WgpuExecutor) -> Self {
|
||||
let limits = executor.context().device.limits();
|
||||
Self {
|
||||
texture_size: limits.max_texture_dimension_2d,
|
||||
buffer_size: limits.max_buffer_size,
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest tile, at most `max` pixels across and down, that a texture and its download buffer can hold, or `None` if not even one pixel fits.
|
||||
fn tile_size(&self, max: UVec2) -> Option<UVec2> {
|
||||
// Each row's bytes are padded to 256, which 64 pixels fill
|
||||
let widest_row = (self.buffer_size / wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as u64 * 64).min(u32::MAX as u64) as u32;
|
||||
let width = max.x.min(self.texture_size).min(widest_row);
|
||||
if width == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let height = max.y.min(self.texture_size).min((self.buffer_size / download_row_bytes(width) as u64).min(u32::MAX as u64) as u32);
|
||||
(height > 0).then_some(UVec2::new(width, height))
|
||||
}
|
||||
}
|
||||
|
||||
impl WgpuExecutor {
|
||||
/// The image's pixels as it's drawn, with its effects and fill carried out at its own pixel grid, grown by whole pixels to hold what they paint past its edges.
|
||||
/// The opacity and blend mode stay for whatever draws the result.
|
||||
pub async fn read_back(&self, item: Item<Raster<CPU>>) -> anyhow::Result<Item<Pixels>> {
|
||||
self.read_back_within(item, ReadbackLimits::of(self)).await
|
||||
}
|
||||
|
||||
/// Like [`Self::read_back`], within the GPU `limits`.
|
||||
async fn read_back_within(&self, item: Item<Raster<CPU>>, limits: ReadbackLimits) -> anyhow::Result<Item<Pixels>> {
|
||||
let effects: Effects = item.attribute_cloned_or_default(ATTR_EFFECTS);
|
||||
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.);
|
||||
let size = UVec2::new(item.element().width, item.element().height);
|
||||
|
||||
// Nothing to carry out, or nothing to carry it out on
|
||||
if (effects.change_nothing() && fill >= 1.) || size.cmpeq(UVec2::ZERO).any() || !transform.matrix2.determinant().is_normal() || !transform.is_finite() {
|
||||
let raster = item.element().clone();
|
||||
return Ok(carried_out(item, raster));
|
||||
}
|
||||
|
||||
if let Some(adjusted) = adjusted_without_render(&item, &effects, fill) {
|
||||
return Ok(carried_out(item, adjusted));
|
||||
}
|
||||
|
||||
let reach = effects_reach(&effects, size.as_dvec2());
|
||||
if !reach.is_finite() {
|
||||
anyhow::bail!("The effects on a {} by {} image reach too far to render", size.x, size.y);
|
||||
}
|
||||
let margin = capped_margin(reach, size.as_dvec2());
|
||||
let raster = self.render_at_pixel_grid(&item, &effects, transform, margin, reach, limits).await?;
|
||||
|
||||
let unit_margin = margin / size.as_dvec2();
|
||||
let mut item = carried_out(item, raster);
|
||||
item.set_attribute(
|
||||
ATTR_TRANSFORM,
|
||||
transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin),
|
||||
);
|
||||
Ok(item)
|
||||
}
|
||||
|
||||
/// Renders the raster `item` placed by `transform` with its `effects`, one pixel of the render per pixel of its image, grown by `margin` pixels along each axis.
|
||||
/// A render larger than the GPU's `limits` allow is drawn in tiles. When the whole image is too large to upload, each is drawn from a crop holding the pixels the effects `reach` past it.
|
||||
async fn render_at_pixel_grid(&self, item: &Item<Raster<CPU>>, effects: &Effects, transform: DAffine2, margin: DVec2, reach: DVec2, limits: ReadbackLimits) -> anyhow::Result<Raster<CPU>> {
|
||||
let image = item.element();
|
||||
let size = UVec2::new(image.width, image.height);
|
||||
let grown_size = size + 2 * margin.as_uvec2();
|
||||
let document_to_pixels = DAffine2::from_translation(margin) * DAffine2::from_scale(size.as_dvec2()) * transform.inverse();
|
||||
|
||||
// The content on its own, without the opacity and blend mode that act on its effects' result as a whole
|
||||
let mut content = item.clone();
|
||||
content.remove_attribute::<f64>(ATTR_OPACITY);
|
||||
content.remove_attribute::<BlendMode>(ATTR_BLEND_MODE);
|
||||
|
||||
// Each tile draws a crop of an image too large to upload whole, holding the pixels its effects read, unless they depend on the whole image's extent
|
||||
let too_large_to_upload = size.cmpgt(UVec2::splat(limits.texture_size)).any();
|
||||
let crops = too_large_to_upload && !effects.any_takes_frame() && !effects.reach_depends_on_size();
|
||||
if too_large_to_upload && !crops {
|
||||
log::warn!(
|
||||
"A {} by {} image is read back at a lower resolution, since it's too large for the GPU and its effects depend on its whole extent",
|
||||
size.x,
|
||||
size.y
|
||||
);
|
||||
}
|
||||
// A crop holds what the effects reach on both sides of its tile, which has to leave a texture room for at least a pixel, checked before the reach becomes an integer
|
||||
let max_tile_size = match crops {
|
||||
true => {
|
||||
let room = DVec2::splat(limits.texture_size as f64) - 2. * reach;
|
||||
if !room.cmpge(DVec2::ONE).all() {
|
||||
anyhow::bail!("The effects on a {} by {} image reach too far past each pixel to render it in tiles the GPU can hold", size.x, size.y);
|
||||
}
|
||||
room.floor().as_uvec2()
|
||||
}
|
||||
false => grown_size,
|
||||
};
|
||||
let (margin, reach) = (margin.as_uvec2(), reach.as_uvec2());
|
||||
let Some(tile_size) = limits.tile_size(max_tile_size) else {
|
||||
anyhow::bail!("The GPU's textures and buffers can't hold a tile of a {} by {} image's render with its effects", size.x, size.y);
|
||||
};
|
||||
|
||||
// The raster's render carries out leading adjustments changing alpha on its image's own pixels, which a crop's group can't, so they're carried out first
|
||||
if crops {
|
||||
let leading_adjustments = leading_raster_adjustments(&content);
|
||||
if leading_adjustments.iter().any(|adjustment| !preserves_alpha(adjustment)) {
|
||||
let adjusted = adjusted_raster(content.element(), &leading_adjustments);
|
||||
let (_, attributes) = content.into_parts();
|
||||
content = Item::from_parts(adjusted, attributes);
|
||||
content.set_attribute(ATTR_EFFECTS, effects.after(leading_adjustments.len()));
|
||||
}
|
||||
}
|
||||
|
||||
let whole = List::new_from_item(content.clone());
|
||||
if !crops && grown_size.cmple(tile_size).all() {
|
||||
return self.render_tile(&whole, document_to_pixels, grown_size).await;
|
||||
}
|
||||
|
||||
let mut pixels = Image::try_new(grown_size.x, grown_size.y, Color::TRANSPARENT)?;
|
||||
for tile_y in (0..grown_size.y).step_by(tile_size.y as usize) {
|
||||
for tile_x in (0..grown_size.x).step_by(tile_size.x as usize) {
|
||||
let origin = UVec2::new(tile_x, tile_y);
|
||||
let size_in_tile = (grown_size - origin).min(tile_size);
|
||||
let tile_to_pixels = DAffine2::from_translation(-origin.as_dvec2()) * document_to_pixels;
|
||||
|
||||
let tile = match crops {
|
||||
// The tile spans the image's pixels from `origin - margin`, and its effects read up to their reach past it
|
||||
true => {
|
||||
let start = origin.saturating_sub(margin + reach);
|
||||
let end = (origin + size_in_tile + reach).saturating_sub(margin).min(size);
|
||||
self.render_tile(&cropped(&content, start, end), tile_to_pixels, size_in_tile).await?
|
||||
}
|
||||
false => self.render_tile(&whole, tile_to_pixels, size_in_tile).await?,
|
||||
};
|
||||
|
||||
for row in 0..size_in_tile.y as usize {
|
||||
let start = (origin.y as usize + row) * grown_size.x as usize + origin.x as usize;
|
||||
let tile_row = &tile.data[row * size_in_tile.x as usize..(row + 1) * size_in_tile.x as usize];
|
||||
pixels.data[start..start + size_in_tile.x as usize].copy_from_slice(tile_row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Raster::new_cpu(pixels))
|
||||
}
|
||||
|
||||
/// Renders the `content` into an image of `size` pixels, which `document_to_pixels` places the document in, and reads it back.
|
||||
async fn render_tile(&self, content: &(impl Render + Sync), document_to_pixels: DAffine2, size: UVec2) -> anyhow::Result<Raster<CPU>> {
|
||||
let render_params = RenderParams {
|
||||
render_output_type: RenderOutputType::Vello,
|
||||
footprint: Footprint {
|
||||
transform: document_to_pixels,
|
||||
resolution: size,
|
||||
..Default::default()
|
||||
},
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
};
|
||||
let texture = self.try_render_vello(size, document_to_pixels, &mut |scene| content.render_to_vello(scene, DAffine2::IDENTITY, &render_params))?;
|
||||
|
||||
self.try_download(Raster::new_gpu(texture)).await
|
||||
}
|
||||
}
|
||||
|
||||
/// The `item` with its image replaced by the `raster` its effects and fill are carried out in, without the attributes holding them.
|
||||
fn carried_out(item: Item<Raster<CPU>>, raster: Raster<CPU>) -> Item<Pixels> {
|
||||
let (_, attributes) = item.into_parts();
|
||||
let mut item = Item::from_parts(Pixels::new(raster), attributes);
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
|
||||
item
|
||||
}
|
||||
|
||||
/// The image with its `effects` and `fill` carried out on the CPU if the effects are all adjustments its render carries out on its own pixels, or `None` if any needs a render.
|
||||
/// The CPU keeps the adjustments' full precision, including values past 0 to 1 and colors beneath zero alpha, which an 8-bit download would lose.
|
||||
fn adjusted_without_render(item: &Item<Raster<CPU>>, effects: &Effects, fill: f64) -> Option<Raster<CPU>> {
|
||||
let adjustments = leading_raster_adjustments(item);
|
||||
if adjustments.len() < effects.operations().count() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Under a partial fill, the leading adjustments all keep alpha, so fading after them matches fading before
|
||||
let mut adjusted = adjusted_raster(item.element(), &adjustments);
|
||||
if fill < 1. {
|
||||
adjusted.data_mut().data.iter_mut().for_each(|color| *color = color.with_alpha(color.a() * fill as f32));
|
||||
}
|
||||
Some(adjusted)
|
||||
}
|
||||
|
||||
/// The raster `content` drawn from only its image's pixels from `start` up to `end`, at their own resolution where they lie in the whole image.
|
||||
/// The crop sits within a group taking the content's placement and effects, so the effects measure and place what they draw as for the whole image.
|
||||
fn cropped(content: &Item<Raster<CPU>>, start: UVec2, end: UVec2) -> List<Graphic> {
|
||||
let image = content.element();
|
||||
let (size, crop_size) = (UVec2::new(image.width, image.height), end.saturating_sub(start));
|
||||
if crop_size.cmpeq(UVec2::ZERO).any() {
|
||||
return List::new();
|
||||
}
|
||||
|
||||
let data = (start.y..end.y)
|
||||
.flat_map(|y| {
|
||||
let row = (y * size.x) as usize;
|
||||
image.data[row + start.x as usize..row + end.x as usize].iter().copied()
|
||||
})
|
||||
.collect();
|
||||
let crop = Image {
|
||||
width: crop_size.x,
|
||||
height: crop_size.y,
|
||||
data,
|
||||
};
|
||||
let placement = DAffine2::from_translation(start.as_dvec2() / size.as_dvec2()) * DAffine2::from_scale(crop_size.as_dvec2() / size.as_dvec2());
|
||||
let crop = Item::new_from_element(Raster::new_cpu(crop)).with_attribute(ATTR_TRANSFORM, placement);
|
||||
|
||||
let (_, attributes) = content.clone().into_parts();
|
||||
List::new_from_item(Item::from_parts(Graphic::RasterCPU(Box::new(crop)), attributes))
|
||||
}
|
||||
|
||||
/// How far, in whole pixels along each axis of an image of `size` pixels, its `effects` paint and read past each pixel and its edges.
|
||||
fn effects_reach(effects: &Effects, size: DVec2) -> DVec2 {
|
||||
// The content's unit square spans the image's pixels
|
||||
let content_to_pixels = DAffine2::from_scale(size);
|
||||
let reach = (effects.reach_around(content_to_pixels, [DVec2::ZERO, size], 0.) + effects.read_beyond_painted(content_to_pixels)).ceil();
|
||||
|
||||
// A feather fades the content toward its edges, finding them against the pixels past them
|
||||
match effects.operations().any(|operation| matches!(operation, EffectOperation::Feather { distance } if distance > 0.)) {
|
||||
true => reach.max(DVec2::ONE),
|
||||
false => reach,
|
||||
}
|
||||
}
|
||||
|
||||
/// The margin an image of `size` pixels grows by to hold its effects' `reach`, cut short evenly past [`MAX_PIXELS_WITH_MARGIN`].
|
||||
fn capped_margin(reach: DVec2, size: DVec2) -> DVec2 {
|
||||
if (size + 2. * reach).element_product() <= MAX_PIXELS_WITH_MARGIN {
|
||||
return reach;
|
||||
}
|
||||
|
||||
let margin = (reach * margin_fraction_that_fits(size, reach)).floor();
|
||||
if margin.max_element() < reach.max_element() {
|
||||
log::warn!(
|
||||
"The effects on a {} by {} image end at a hard edge {} pixels past it, short of the {} they reach, since the image can't grow past {MAX_PIXELS_WITH_MARGIN} pixels",
|
||||
size.x,
|
||||
size.y,
|
||||
margin.max_element(),
|
||||
reach.max_element()
|
||||
);
|
||||
}
|
||||
margin
|
||||
}
|
||||
|
||||
/// The fraction of `margin` that grows an image of `size` to [`MAX_PIXELS_WITH_MARGIN`], or 0 if the image alone already reaches it.
|
||||
fn margin_fraction_that_fits(size: DVec2, margin: DVec2) -> f64 {
|
||||
// The positive root of (width + 2 × fraction × margin width) × (height + 2 × fraction × margin height) = the limit
|
||||
let quadratic = 4. * margin.x * margin.y;
|
||||
let linear = 2. * (size.x * margin.y + size.y * margin.x);
|
||||
let constant = size.element_product() - MAX_PIXELS_WITH_MARGIN;
|
||||
if constant >= 0. || linear <= 0. {
|
||||
return 0.;
|
||||
}
|
||||
|
||||
let fraction = match quadratic > 0. {
|
||||
true => (-linear + (linear * linear - 4. * quadratic * constant).sqrt()) / (2. * quadratic),
|
||||
false => -constant / linear,
|
||||
};
|
||||
fraction.clamp(0., 1.)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::ATTR_APPEARANCE;
|
||||
use futures::executor::block_on;
|
||||
use graphic_types::vector_types::vector::style::StrokeAlign;
|
||||
use graphic_types::{Appearance, Coverage, Effect, Graphic, MaskMode, Vector, stamp_effect};
|
||||
use vello_gpu::kurbo::{Rect, Shape};
|
||||
|
||||
/// The executor these tests share, or `None` without a GPU.
|
||||
fn executor() -> Option<&'static WgpuExecutor> {
|
||||
static EXECUTOR: std::sync::OnceLock<Option<WgpuExecutor>> = std::sync::OnceLock::new();
|
||||
EXECUTOR.get_or_init(|| block_on(crate::WgpuContext::for_tests()).and_then(WgpuExecutor::with_context)).as_ref()
|
||||
}
|
||||
|
||||
/// The size in the document of the pixels of an image scaled unevenly, 1 unit wide and 4 tall.
|
||||
const TALL_PIXEL: DVec2 = DVec2::new(1., 4.);
|
||||
|
||||
/// An image of 20 by 20 pixels, each `pixel_size` in the document, colored by `color` at each pixel's column and row, with its corner at (100, 50).
|
||||
fn image_of_pixels(pixel_size: DVec2, color: impl Fn(u32, u32) -> Color, effects: &[EffectOperation]) -> Item<Raster<CPU>> {
|
||||
let data = (0..20 * 20).map(|index| color(index % 20, index / 20)).collect();
|
||||
let transform = DAffine2::from_translation(DVec2::new(100., 50.)) * DAffine2::from_scale(20. * pixel_size);
|
||||
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(Image { width: 20, height: 20, data })).with_attribute(ATTR_TRANSFORM, transform);
|
||||
for effect in effects {
|
||||
stamp_effect(&mut item, Effect::new(effect));
|
||||
}
|
||||
item
|
||||
}
|
||||
|
||||
/// The read-back image's color at a `point` in the document, transparent past its edges.
|
||||
fn color_at(image: &Item<Pixels>, point: DVec2) -> Color {
|
||||
let raster = image.element();
|
||||
let transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let pixel = (transform.inverse().transform_point2(point) * DVec2::new(raster.width as f64, raster.height as f64)).floor();
|
||||
|
||||
let inside = pixel.cmpge(DVec2::ZERO).all() && pixel.x < raster.width as f64 && pixel.y < raster.height as f64;
|
||||
if !inside {
|
||||
return Color::TRANSPARENT;
|
||||
}
|
||||
raster.data[pixel.y as usize * raster.width as usize + pixel.x as usize]
|
||||
}
|
||||
|
||||
fn is_black(color: Color) -> bool {
|
||||
color.a() > 0.98 && color.r().max(color.g()).max(color.b()) < 0.02
|
||||
}
|
||||
|
||||
fn is_white(color: Color) -> bool {
|
||||
color.a() > 0.98 && color.r().min(color.g()).min(color.b()) > 0.98
|
||||
}
|
||||
|
||||
fn is_clear(color: Color) -> bool {
|
||||
color.a() < 0.02
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_without_effects_comes_back_as_it_is() {
|
||||
let Some(executor) = executor() else { return };
|
||||
|
||||
let image = image_of_pixels(TALL_PIXEL, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 0.25), &[]);
|
||||
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
||||
|
||||
assert_eq!(**read_back.element(), *image.element().data());
|
||||
assert_eq!(
|
||||
read_back.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM),
|
||||
image.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM)
|
||||
);
|
||||
}
|
||||
|
||||
/// A fill fades the pixels read back the same whether no effects or an empty list of them is stamped, and goes with the effects while the other attributes stay.
|
||||
#[test]
|
||||
fn a_fill_fades_the_pixels_with_or_without_effects() {
|
||||
let Some(executor) = executor() else { return };
|
||||
|
||||
let mut without_effects = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &[]);
|
||||
without_effects.set_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||
without_effects.set_attribute(ATTR_OPACITY, 0.25);
|
||||
without_effects.set_attribute(ATTR_BLEND_MODE, BlendMode::Multiply);
|
||||
without_effects.set_attribute("unrelated", 7.);
|
||||
let mut with_no_effects = without_effects.clone();
|
||||
with_no_effects.set_attribute(ATTR_EFFECTS, Effects::default());
|
||||
|
||||
for image in [without_effects, with_no_effects] {
|
||||
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
||||
|
||||
let faded: Vec<_> = image.element().data.iter().map(|color| color.with_alpha(0.5)).collect();
|
||||
assert_eq!(read_back.element().data, faded);
|
||||
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
||||
|
||||
assert_eq!(read_back.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 0.25);
|
||||
assert_eq!(read_back.attribute_cloned_or_default::<BlendMode>(ATTR_BLEND_MODE), BlendMode::Multiply);
|
||||
assert_eq!(read_back.attribute_cloned_or::<f64>("unrelated", 0.), 7.);
|
||||
assert_eq!(
|
||||
read_back.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM),
|
||||
image.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Levels adjustment bending each color channel its own way, and alpha by `alpha_midtones`.
|
||||
fn uneven_levels(alpha_midtones: f64) -> graphic_types::Adjustment {
|
||||
use graphic_types::adjustment::{LevelsRecord, LevelsSettings};
|
||||
|
||||
let record = |midtones, output_maximums| LevelsRecord {
|
||||
shadows: 0.,
|
||||
midtones,
|
||||
highlights: 100.,
|
||||
output_minimums: 0.,
|
||||
output_maximums,
|
||||
};
|
||||
graphic_types::Adjustment::Levels(Box::new(LevelsSettings {
|
||||
composite: record(1.4, 100.),
|
||||
red: record(0.7, 90.),
|
||||
green: record(1., 100.),
|
||||
blue: record(1.2, 100.),
|
||||
alpha: record(alpha_midtones, 100.),
|
||||
}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustments_carried_out_on_the_cpu_match_their_render() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// Opaque, so the render's straight alpha keeps every color
|
||||
let operations = [uneven_levels(1.), graphic_types::Adjustment::Invert].map(EffectOperation::Adjustment);
|
||||
let image = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &operations);
|
||||
let (effects, transform) = (image.attribute::<Effects>(ATTR_EFFECTS).unwrap().clone(), image.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||
|
||||
let on_the_cpu = adjusted_without_render(&image, &effects, 1.).expect("adjustments alone need no render");
|
||||
let rendered = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, DVec2::ZERO, limits)).unwrap();
|
||||
|
||||
// The render carries out leading adjustments on the image's own pixels too, then draws them into an 8-bit texture
|
||||
assert_alike(&on_the_cpu, &rendered, ADJUSTMENT_TOLERANCE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustments_alone_are_carried_out_on_the_cpu() {
|
||||
use graphic_types::Adjustment;
|
||||
|
||||
let Some(executor) = executor() else { return };
|
||||
|
||||
let adjustments = [uneven_levels(2.2), Adjustment::Invert];
|
||||
let operations: Vec<_> = adjustments.iter().cloned().map(EffectOperation::Adjustment).collect();
|
||||
|
||||
// A Levels stack bending alpha, with fine steps 8 bits can't hold
|
||||
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 1000., y as f32 / 20., 0.5, (x + y) as f32 / 40.);
|
||||
let image = image_of_pixels(DVec2::ONE, color, &operations);
|
||||
let expected = adjusted_raster(image.element(), &adjustments);
|
||||
let read_back = block_on(executor.read_back(image)).unwrap();
|
||||
assert_eq!(**read_back.element(), *expected.data());
|
||||
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||
|
||||
// Inverting keeps alpha, so a partial fill fades the inverted colors, which stay beneath zero alpha
|
||||
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 20., 0.25, 1., if y < 10 { 0. } else { 0.8 });
|
||||
let mut image = image_of_pixels(DVec2::ONE, color, &[EffectOperation::Adjustment(Adjustment::Invert)]);
|
||||
image.set_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||
let inverted = adjusted_raster(image.element(), &[Adjustment::Invert]);
|
||||
let read_back = block_on(executor.read_back(image)).unwrap();
|
||||
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
||||
for (index, (color, inverted)) in read_back.element().data.iter().zip(&inverted.data().data).enumerate() {
|
||||
assert_eq!(*color, inverted.with_alpha(inverted.a() * 0.5), "pixel {index}");
|
||||
assert!(color.r() + color.g() + color.b() > 0., "pixel {index} lost its color");
|
||||
}
|
||||
|
||||
// Effects past adjustments need a render
|
||||
let outlined = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[outline(2.)]);
|
||||
let effects = outlined.attribute::<Effects>(ATTR_EFFECTS).unwrap();
|
||||
assert!(adjusted_without_render(&outlined, effects, 1.).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_margin_holds_what_a_median_reads_past_the_image() {
|
||||
// A median reads its whole radius and the pixel past it, across the image's pixels of one unit each
|
||||
let image = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[EffectOperation::Median { radius: 2.5 }]);
|
||||
let effects = image.attribute::<Effects>(ATTR_EFFECTS).unwrap();
|
||||
assert_eq!(effects_reach(effects, DVec2::splat(20.)), DVec2::splat(3.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_measure_lengths_in_the_document_across_unevenly_scaled_pixels() {
|
||||
let Some(executor) = executor() else { return };
|
||||
|
||||
// An outline 8 units wide spans 8 of the image's pixels across, but only 2 of them down
|
||||
let outline = EffectOperation::Outline {
|
||||
paint: Color::BLACK.into(),
|
||||
blend_mode: BlendMode::Normal,
|
||||
weight: 8.,
|
||||
align: StrokeAlign::Outside,
|
||||
contour_gradient: false,
|
||||
};
|
||||
let read_back = block_on(executor.read_back(image_of_pixels(TALL_PIXEL, |_, _| Color::WHITE, &[outline]))).unwrap();
|
||||
|
||||
// The content spans from (100, 50) to (120, 130)
|
||||
assert!(is_white(color_at(&read_back, DVec2::new(110., 90.))), "the content");
|
||||
assert!(is_black(color_at(&read_back, DVec2::new(94.5, 90.))), "within the outline, 5.5 units left of the content");
|
||||
assert!(is_clear(color_at(&read_back, DVec2::new(89.5, 90.))), "past the outline, 10.5 units left of the content");
|
||||
assert!(is_black(color_at(&read_back, DVec2::new(110., 44.))), "within the outline, 6 units above the content");
|
||||
assert!(is_clear(color_at(&read_back, DVec2::new(110., 40.))), "past the outline, 10 units above the content");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_masks_shape_the_pixels_read_back() {
|
||||
let Some(executor) = executor() else { return };
|
||||
|
||||
// A mask lies in the content's own space, where the left half of its unit square covers the image's left half
|
||||
let mut left_half = Vector::item_from_bezpath(&Rect::new(0., 0., 0.5, 1.).to_path(0.1));
|
||||
left_half.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::WHITE))));
|
||||
let mask = EffectOperation::Mask {
|
||||
mask: Graphic::Vector(Box::new(left_half)),
|
||||
mode: MaskMode::Alpha,
|
||||
density: 100.,
|
||||
feather: 0.,
|
||||
invert: false,
|
||||
};
|
||||
let read_back = block_on(executor.read_back(image_of_pixels(TALL_PIXEL, |_, _| Color::WHITE, &[mask]))).unwrap();
|
||||
|
||||
assert!(is_white(color_at(&read_back, DVec2::new(105.5, 90.))), "the left half, which the mask shows");
|
||||
assert!(is_clear(color_at(&read_back, DVec2::new(114.5, 90.))), "the right half, which the mask hides");
|
||||
}
|
||||
|
||||
/// An outline of `weight` outside the content, in black.
|
||||
fn outline(weight: f64) -> EffectOperation {
|
||||
EffectOperation::Outline {
|
||||
paint: Color::BLACK.into(),
|
||||
blend_mode: BlendMode::Normal,
|
||||
weight,
|
||||
align: StrokeAlign::Outside,
|
||||
contour_gradient: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The limits of the shared GPU, and its executor, or `None` without a GPU.
|
||||
fn executor_and_limits() -> Option<(&'static WgpuExecutor, ReadbackLimits)> {
|
||||
let executor = executor()?;
|
||||
Some((executor, ReadbackLimits::of(executor)))
|
||||
}
|
||||
|
||||
/// How many 8-bit levels the CPU's adjustments and the render of them may part by, which is the render's rounding to its 8-bit texture.
|
||||
const ADJUSTMENT_TOLERANCE: u8 = 1;
|
||||
|
||||
/// Asserts that two images have the same size and 8-bit pixels within `tolerance` levels of each other.
|
||||
fn assert_alike(actual: &Image<Color>, expected: &Image<Color>, tolerance: u8) {
|
||||
assert_eq!((actual.width, actual.height), (expected.width, expected.height));
|
||||
for (index, (actual, expected)) in actual.data.iter().zip(&expected.data).enumerate() {
|
||||
let (SRGBA8 { red, green, blue, alpha }, wanted) = (SRGBA8::from(*actual), SRGBA8::from(*expected));
|
||||
let differences = [red.abs_diff(wanted.red), green.abs_diff(wanted.green), blue.abs_diff(wanted.blue), alpha.abs_diff(wanted.alpha)];
|
||||
assert!(
|
||||
differences.iter().all(|&difference| difference <= tolerance),
|
||||
"pixel {index} is {actual:?} but {expected:?} in the other"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_small_enough_for_the_download_buffer_match_one_render() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// Square pixels of the document's size keep the effects' working pixels on the render's, so neither render resamples them.
|
||||
// A 2048 byte buffer holds 8 rows of up to 64 pixels, each padded to 256 bytes, so this render is drawn in tiles 8 pixels tall.
|
||||
let image = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &[outline(2.)]);
|
||||
let small_buffer = ReadbackLimits { buffer_size: 2048, ..limits };
|
||||
assert_eq!(small_buffer.tile_size(UVec2::splat(100)), Some(UVec2::new(100, 2048 / 512)));
|
||||
|
||||
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
||||
let tiled = block_on(executor.read_back_within(image, small_buffer)).unwrap();
|
||||
assert_alike(tiled.element(), whole.element(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_too_large_to_upload_whole_keeps_its_own_pixels_in_crops() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// Alternating black and white columns, inverted and outlined, which a downscaled upload would average to gray
|
||||
let columns = |x: u32, _| if x.is_multiple_of(2) { Color::BLACK } else { Color::WHITE };
|
||||
let image = image_of_pixels(DVec2::ONE, columns, &[EffectOperation::Adjustment(graphic_types::Adjustment::Invert), outline(2.)]);
|
||||
let small_textures = ReadbackLimits { texture_size: 16, ..limits };
|
||||
|
||||
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
||||
let cropped = block_on(executor.read_back_within(image, small_textures)).unwrap();
|
||||
assert_alike(cropped.element(), whole.element(), 1);
|
||||
|
||||
for x in 0..20 {
|
||||
let color = color_at(&cropped, DVec2::new(100.5 + x as f64, 60.5));
|
||||
let inverted = if x % 2 == 0 { is_white(color) } else { is_black(color) };
|
||||
assert!(inverted, "column {x} is {color:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits_too_small_for_any_tile_fail_without_panicking() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
let image = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[outline(2.)]);
|
||||
let tiny_buffer = ReadbackLimits { buffer_size: 100, ..limits };
|
||||
assert!(block_on(executor.read_back_within(image, tiny_buffer)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reach_too_far_for_any_crop_fails_without_overflowing() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// A box blur reaching past 2^31 pixels, on an image too wide for the texture limit, at one document unit per pixel
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 2_147_483_647.,
|
||||
box_blur: true,
|
||||
gamma: false,
|
||||
};
|
||||
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(16_384, 64, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(16_384., 64.)));
|
||||
stamp_effect(&mut image, Effect::new(&blur));
|
||||
let small_textures = ReadbackLimits { texture_size: 8192, ..limits };
|
||||
|
||||
assert!(block_on(executor.read_back_within(image, small_textures)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crops_carry_out_leading_adjustments_on_transparent_pixels_as_the_whole_image_does() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// Make Opaque raises the alpha of fully transparent pixels, which only the image's own pixels can carry, and the outline needs a render
|
||||
let make_opaque = EffectOperation::Adjustment(graphic_types::Adjustment::MakeOpaque { strength: 100. });
|
||||
let image = image_of_pixels(DVec2::ONE, |_, _| Color::from_rgbaf32_unchecked(1., 0., 0., 0.), &[make_opaque, outline(2.)]);
|
||||
let small_textures = ReadbackLimits { texture_size: 16, ..limits };
|
||||
|
||||
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
||||
let cropped = block_on(executor.read_back_within(image, small_textures)).unwrap();
|
||||
assert_alike(cropped.element(), whole.element(), 1);
|
||||
let pixels = (0..20).flat_map(|y| (0..20).map(move |x| DVec2::new(100.5 + x as f64, 50.5 + y as f64)));
|
||||
assert!(pixels.map(|point| color_at(&cropped, point)).all(|color| color.a() > 0.99), "the transparent pixels became opaque");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crops_hold_the_pixels_effects_reach_past_a_margin_cut_short() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// A margin cut to nothing, as for an image too large to grow, still leaves the blur its neighbors across the tiles.
|
||||
// The tiles are wide enough next to the blur's reach that its effects group keeps their full resolution.
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 1.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(64, 64, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(64.)));
|
||||
stamp_effect(&mut image, Effect::new(&blur));
|
||||
let (effects, transform) = (image.attribute::<Effects>(ATTR_EFFECTS).unwrap().clone(), image.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||
let reach = effects_reach(&effects, DVec2::splat(64.));
|
||||
assert!(reach.min_element() > 0.);
|
||||
let small_textures = ReadbackLimits { texture_size: 60, ..limits };
|
||||
|
||||
let whole = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, reach, limits)).unwrap();
|
||||
let cropped = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, reach, small_textures)).unwrap();
|
||||
assert_alike(&cropped, &whole, 1);
|
||||
}
|
||||
}
|
||||
@@ -22,23 +22,35 @@ struct RasterGpuToRasterCpuConverter {
|
||||
padded_bytes_per_row: u32,
|
||||
_source: raster_types::Texture,
|
||||
}
|
||||
/// The bytes in each row of a download buffer for an image `width` pixels wide, padded to the alignment copies need.
|
||||
pub(crate) fn download_row_bytes(width: u32) -> u32 {
|
||||
let bytes_per_pixel = 4; // RGBA8
|
||||
(width * bytes_per_pixel).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT
|
||||
}
|
||||
|
||||
/// The buffer a texture of `width` by `height` pixels downloads into.
|
||||
fn download_buffer(executor: &WgpuExecutor, width: u32, height: u32) -> Buffer {
|
||||
executor.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("texture_download_buffer"),
|
||||
size: download_row_bytes(width) as u64 * height as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
|
||||
impl RasterGpuToRasterCpuConverter {
|
||||
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
|
||||
let buffer = download_buffer(executor, data_gpu.data().width(), data_gpu.data().height());
|
||||
Self::with_buffer(encoder, data_gpu, buffer)
|
||||
}
|
||||
|
||||
/// Copies the texture into the `buffer` made for its size, once the `encoder` is submitted.
|
||||
fn with_buffer(encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>, buffer: Buffer) -> Self {
|
||||
let texture = data_gpu.data();
|
||||
let width = texture.width();
|
||||
let height = texture.height();
|
||||
let bytes_per_pixel = 4; // RGBA8
|
||||
let unpadded_bytes_per_row = width * bytes_per_pixel;
|
||||
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
|
||||
let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
|
||||
let buffer_size = padded_bytes_per_row as u64 * height as u64;
|
||||
|
||||
let buffer = executor.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("texture_download_buffer"),
|
||||
size: buffer_size,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let unpadded_bytes_per_row = width * 4;
|
||||
let padded_bytes_per_row = download_row_bytes(width);
|
||||
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
@@ -73,7 +85,7 @@ impl RasterGpuToRasterCpuConverter {
|
||||
}
|
||||
}
|
||||
|
||||
async fn convert(self, device: &wgpu::Device) -> Result<Raster<CPU>, wgpu::BufferAsyncError> {
|
||||
async fn convert(self, device: &wgpu::Device) -> anyhow::Result<Raster<CPU>> {
|
||||
let buffer_slice = self.buffer.slice(..);
|
||||
let (sender, receiver) = futures::channel::oneshot::channel();
|
||||
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
|
||||
@@ -104,9 +116,12 @@ impl RasterGpuToRasterCpuConverter {
|
||||
}
|
||||
};
|
||||
|
||||
map_result.expect("Failed to receive map result")?;
|
||||
let Ok(map_result) = map_result else {
|
||||
anyhow::bail!("The download of a {} by {} image was canceled before the GPU mapped its buffer", self.width, self.height);
|
||||
};
|
||||
map_result?;
|
||||
|
||||
let view = buffer_slice.get_mapped_range().expect("Failed to get mapped range");
|
||||
let view = buffer_slice.get_mapped_range()?;
|
||||
|
||||
let row_stride = self.padded_bytes_per_row as usize;
|
||||
let row_bytes = self.unpadded_bytes_per_row as usize;
|
||||
@@ -230,3 +245,33 @@ impl ConvertAsync<Raster<CPU>, WgpuExecutor> for Raster<GPU> {
|
||||
converter.convert(device).await.expect("Failed to download texture data")
|
||||
}
|
||||
}
|
||||
|
||||
impl WgpuExecutor {
|
||||
/// Downloads the GPU raster's pixels, failing rather than panicking when the GPU can't make or map the buffer they're copied into.
|
||||
pub async fn try_download(&self, raster: Raster<GPU>) -> anyhow::Result<Raster<CPU>> {
|
||||
let device = &self.context().device;
|
||||
let (width, height) = (raster.data().width(), raster.data().height());
|
||||
let buffer_size = download_row_bytes(width) as u64 * height as u64;
|
||||
let limit = device.limits().max_buffer_size;
|
||||
if buffer_size > limit {
|
||||
anyhow::bail!("Downloading a {width} by {height} image takes a {buffer_size} byte buffer, past the GPU's limit of {limit} bytes");
|
||||
}
|
||||
|
||||
// Popped in the reverse order they're pushed, before awaiting either, since the scopes can't be held across an await
|
||||
let out_of_memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let buffer = download_buffer(self, width, height);
|
||||
let (validation, out_of_memory) = (validation.pop(), out_of_memory.pop());
|
||||
if let Some(error) = validation.await.or(out_of_memory.await) {
|
||||
anyhow::bail!("The GPU couldn't make the buffer to download a {width} by {height} image: {error}");
|
||||
}
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("fallible_texture_download_encoder"),
|
||||
});
|
||||
let converter = RasterGpuToRasterCpuConverter::with_buffer(&mut encoder, raster, buffer);
|
||||
self.context().queue.submit([encoder.finish()]);
|
||||
|
||||
converter.convert(device).await
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,8 @@ struct RenderContext<'a> {
|
||||
canvas: &'a mut VelloCanvas,
|
||||
device: &'a wgpu::Device,
|
||||
queue: &'a Queue,
|
||||
/// The first failure that left part of the render transparent.
|
||||
failure: Option<String>,
|
||||
}
|
||||
|
||||
impl VelloRenderer {
|
||||
@@ -120,7 +122,7 @@ impl VelloRenderer {
|
||||
}
|
||||
|
||||
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target` (an `Rgba8Unorm` texture of `size` with straight alpha).
|
||||
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
||||
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into. Gives the first failure that left a part transparent.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(crate) fn render(
|
||||
&self,
|
||||
@@ -131,7 +133,7 @@ impl VelloRenderer {
|
||||
view: Affine,
|
||||
size: UVec2,
|
||||
target: &wgpu::Texture,
|
||||
) -> anyhow::Result<()> {
|
||||
) -> anyhow::Result<Option<String>> {
|
||||
if u16::try_from(size.x).is_err() || u16::try_from(size.y).is_err() {
|
||||
anyhow::bail!("Render size {size} exceeds Vello GPU's limit");
|
||||
}
|
||||
@@ -142,12 +144,14 @@ impl VelloRenderer {
|
||||
canvas,
|
||||
device,
|
||||
queue,
|
||||
failure: None,
|
||||
};
|
||||
context.render_area(draw, view, size, target, TargetAlpha::Straight);
|
||||
let failure = context.failure;
|
||||
canvas.images.free_unused();
|
||||
canvas.effect_textures.finish_render();
|
||||
|
||||
Ok(())
|
||||
Ok(failure)
|
||||
}
|
||||
|
||||
/// Renders a `scene` drawn beforehand on `canvas` into `target` (an `Rgba8Unorm` texture of the scene's size with straight alpha).
|
||||
@@ -160,6 +164,7 @@ impl VelloRenderer {
|
||||
canvas,
|
||||
device,
|
||||
queue,
|
||||
failure: None,
|
||||
};
|
||||
let (scene, images) = scene.finish();
|
||||
if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight, true) {
|
||||
@@ -192,6 +197,7 @@ impl RenderContext<'_> {
|
||||
if !too_much_to_hold || split_depth > MAX_SPLIT_DEPTH || size.max_element() <= 1 {
|
||||
// A failed render leaves its area transparent rather than taking down the editor
|
||||
log::error!("Vello GPU failed to render: {error}");
|
||||
self.failure.get_or_insert_with(|| error.to_string());
|
||||
clear(device, queue, target);
|
||||
return;
|
||||
}
|
||||
@@ -230,6 +236,7 @@ impl RenderContext<'_> {
|
||||
};
|
||||
if halves.iter().all(|(.., rendered)| stalled(rendered)) {
|
||||
log::error!("Vello GPU failed to render: {error}");
|
||||
self.failure.get_or_insert_with(|| error.to_string());
|
||||
clear(device, queue, target);
|
||||
return;
|
||||
}
|
||||
@@ -491,6 +498,7 @@ impl EffectsRenderer for RenderContext<'_> {
|
||||
Ok(()) => Some(backdrop),
|
||||
Err(error) => {
|
||||
log::error!("Vello GPU failed to render what lies beneath content reading it: {error}");
|
||||
self.failure.get_or_insert_with(|| error.to_string());
|
||||
self.canvas.effect_textures.release(backdrop);
|
||||
None
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user