mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 15:53:26 -10:00
Fall back to half-float rasters where the GPU can't render full floats
This commit is contained in:
1 parent
7bb28460cc
commit
f3edba1603
10 files changed
+84
-35
No files matched your search
Generated
+1
@@ -6953,6 +6953,7 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-application-io",
|
||||
"half",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
|
||||
@@ -33,3 +33,4 @@ web-sys = { workspace = true }
|
||||
vello_gpu = { workspace = true }
|
||||
bytemuck = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
half = { workspace = true }
|
||||
@@ -37,8 +37,10 @@ const TEXTURE_CACHE_SIZE: u64 = 1024 * 1024 * 1024; // 1GB
|
||||
#[cfg(target_family = "wasm")]
|
||||
const TEXTURE_CACHE_SIZE: u64 = 512 * 1024 * 1024; // 512MB
|
||||
|
||||
/// The format of every raster texture, holding linear-light straight-alpha values.
|
||||
/// The preferred format of raster textures, holding linear-light straight-alpha values.
|
||||
pub const RASTER_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float;
|
||||
/// The raster texture format on adapters that can't render to [`RASTER_FORMAT`], or when `GRAPHITE_RASTER_FORMAT=f16` forces it.
|
||||
pub const FALLBACK_RASTER_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
|
||||
|
||||
#[derive(dyn_any::DynAny, Clone)]
|
||||
pub struct WgpuExecutor {
|
||||
@@ -49,12 +51,18 @@ impl WgpuExecutor {
|
||||
pub fn context(&self) -> &WgpuContext {
|
||||
&self.inner.context
|
||||
}
|
||||
|
||||
/// The format of every raster texture this executor creates, either [`RASTER_FORMAT`] or [`FALLBACK_RASTER_FORMAT`].
|
||||
pub fn raster_format(&self) -> wgpu::TextureFormat {
|
||||
self.inner.raster_format
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(dyn_any::DynAny)]
|
||||
pub struct WgpuExecutorInner {
|
||||
context: WgpuContext,
|
||||
texture_cache: std::sync::Mutex<TextureCache>,
|
||||
raster_format: wgpu::TextureFormat,
|
||||
vello_renderer: VelloRenderer,
|
||||
/// The canvas the node graph renders documents on.
|
||||
document_canvas: Mutex<VelloCanvas>,
|
||||
@@ -79,9 +87,9 @@ impl WgpuExecutor {
|
||||
self.render_vello_with_format(size, view, draw, wgpu::TextureFormat::Rgba8Unorm)
|
||||
}
|
||||
|
||||
/// Renders like [`Self::render_vello`], but into a new [`RASTER_FORMAT`] texture holding linear-light values, as a GPU raster's.
|
||||
/// Renders like [`Self::render_vello`], but into a new texture in [`Self::raster_format`] holding linear-light values, as a GPU raster's.
|
||||
pub fn render_vello_raster(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
|
||||
self.render_vello_with_format(size, view, draw, RASTER_FORMAT)
|
||||
self.render_vello_with_format(size, view, draw, self.raster_format())
|
||||
}
|
||||
|
||||
fn render_vello_with_format(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder), format: wgpu::TextureFormat) -> Result<Texture> {
|
||||
@@ -183,7 +191,8 @@ impl WgpuExecutor {
|
||||
}
|
||||
|
||||
pub fn with_context(context: WgpuContext) -> Option<Self> {
|
||||
let vello_renderer = VelloRenderer::new(&context.device);
|
||||
let raster_format = choose_raster_format(&context.adapter);
|
||||
let vello_renderer = VelloRenderer::new(&context.device, raster_format);
|
||||
|
||||
let texture_cache = TextureCache::new(TEXTURE_CACHE_SIZE);
|
||||
|
||||
@@ -191,6 +200,7 @@ impl WgpuExecutor {
|
||||
inner: Arc::new(WgpuExecutorInner {
|
||||
context,
|
||||
texture_cache: texture_cache.into(),
|
||||
raster_format,
|
||||
vello_renderer,
|
||||
document_canvas: Mutex::default(),
|
||||
}),
|
||||
@@ -201,3 +211,16 @@ impl WgpuExecutor {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("No GPU is available")]
|
||||
pub struct NoGpuError;
|
||||
|
||||
fn choose_raster_format(adapter: &wgpu::Adapter) -> wgpu::TextureFormat {
|
||||
if std::env::var("GRAPHITE_RASTER_FORMAT").is_ok_and(|format| format == "f16") {
|
||||
return FALLBACK_RASTER_FORMAT;
|
||||
}
|
||||
|
||||
if adapter.get_texture_format_features(RASTER_FORMAT).allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) {
|
||||
RASTER_FORMAT
|
||||
} else {
|
||||
log::warn!("The GPU can't render to {RASTER_FORMAT:?}, so rasters fall back to {FALLBACK_RASTER_FORMAT:?}");
|
||||
FALLBACK_RASTER_FORMAT
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::ops::{Convert, ConvertAsync};
|
||||
use core_types::transform::Footprint;
|
||||
use half::f16;
|
||||
use raster_types::Image;
|
||||
use raster_types::{CPU, GPU, Raster, Storage};
|
||||
use wgpu::Extent3d;
|
||||
@@ -14,14 +15,21 @@ fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raste
|
||||
return Raster::default();
|
||||
}
|
||||
|
||||
let texture = executor.request_texture_with_format(glam::UVec2::new(image.width, image.height), crate::RASTER_FORMAT);
|
||||
|
||||
let format = executor.raster_format();
|
||||
let texture = executor.request_texture_with_format(glam::UVec2::new(image.width, image.height), format);
|
||||
let half_floats: Vec<[f16; 4]>;
|
||||
let (bytes, bytes_per_pixel) = if format == crate::FALLBACK_RASTER_FORMAT {
|
||||
half_floats = image.data.iter().map(|color| color.to_vec4().to_array().map(f16::from_f32)).collect();
|
||||
(bytemuck::cast_slice(half_floats.as_slice()), 8)
|
||||
} else {
|
||||
(bytemuck::cast_slice(image.data.as_slice()), 16)
|
||||
};
|
||||
queue.write_texture(
|
||||
texture.as_image_copy(),
|
||||
bytemuck::cast_slice(image.data.as_slice()),
|
||||
bytes,
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(16 * image.width),
|
||||
bytes_per_row: Some(bytes_per_pixel * image.width),
|
||||
rows_per_image: Some(image.height),
|
||||
},
|
||||
Extent3d {
|
||||
@@ -37,7 +45,7 @@ fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raste
|
||||
///
|
||||
/// Assumptions:
|
||||
/// - 2D texture, mip level 0
|
||||
/// - 4 bytes-per-pixel RGBA8, or `RASTER_FORMAT`
|
||||
/// - 4 bytes-per-pixel RGBA8, or `RASTER_FORMAT` or `FALLBACK_RASTER_FORMAT`
|
||||
/// - Texture has COPY_SRC usage
|
||||
struct RasterGpuToRasterCpuConverter {
|
||||
buffer: Buffer,
|
||||
@@ -54,7 +62,11 @@ impl RasterGpuToRasterCpuConverter {
|
||||
let width = texture.width();
|
||||
let height = texture.height();
|
||||
let format = texture.format();
|
||||
let bytes_per_pixel = if format == crate::RASTER_FORMAT { 16 } else { 4 };
|
||||
let bytes_per_pixel = match format {
|
||||
crate::RASTER_FORMAT => 16,
|
||||
crate::FALLBACK_RASTER_FORMAT => 8,
|
||||
_ => 4,
|
||||
};
|
||||
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;
|
||||
@@ -142,11 +154,19 @@ impl RasterGpuToRasterCpuConverter {
|
||||
for row in 0..self.height as usize {
|
||||
let start = row * row_stride;
|
||||
let row_slice = &view[start..start + row_bytes];
|
||||
if self.format == crate::RASTER_FORMAT {
|
||||
cpu_data.extend(bytemuck::pod_collect_to_vec::<u8, Color>(row_slice));
|
||||
} else {
|
||||
for px in row_slice.chunks_exact(4) {
|
||||
cpu_data.push(SRGBA8::new(px[0], px[1], px[2], px[3]).into());
|
||||
match self.format {
|
||||
crate::RASTER_FORMAT => cpu_data.extend(bytemuck::pod_collect_to_vec::<u8, Color>(row_slice)),
|
||||
crate::FALLBACK_RASTER_FORMAT => {
|
||||
let pixels = bytemuck::pod_collect_to_vec::<u8, [f16; 4]>(row_slice);
|
||||
cpu_data.extend(pixels.iter().map(|pixel| {
|
||||
let [red, green, blue, alpha] = pixel.map(f16::to_f32);
|
||||
Color::from_rgbaf32_unchecked(red, green, blue, alpha)
|
||||
}));
|
||||
}
|
||||
_ => {
|
||||
for px in row_slice.chunks_exact(4) {
|
||||
cpu_data.push(SRGBA8::new(px[0], px[1], px[2], px[3]).into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ pub struct VelloCanvas {
|
||||
}
|
||||
|
||||
impl VelloRenderer {
|
||||
pub(crate) fn new(device: &wgpu::Device) -> Self {
|
||||
pub(crate) fn new(device: &wgpu::Device, raster_format: wgpu::TextureFormat) -> Self {
|
||||
let render_target_config = RenderTargetConfig {
|
||||
format: TEXTURE_FORMAT,
|
||||
width: 1,
|
||||
@@ -59,11 +59,11 @@ impl VelloRenderer {
|
||||
|
||||
Self {
|
||||
gpu: Mutex::new(Renderer::new_with(device, &render_target_config, settings)),
|
||||
alpha_conversion: AlphaConversion::new(device),
|
||||
alpha_conversion: AlphaConversion::new(device, raster_format),
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target`, a texture of `size` with straight alpha that is either `Rgba8Unorm` holding sRGB values or [`crate::RASTER_FORMAT`] holding linear-light values.
|
||||
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target`, a texture of `size` with straight alpha that is either `Rgba8Unorm` holding sRGB values or the executor's raster format holding linear-light values.
|
||||
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(crate) fn render(
|
||||
@@ -363,7 +363,7 @@ impl ImageTextures {
|
||||
|
||||
if let SceneImage::Texture(source) = image {
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let loads_linear_light = source.format().is_srgb() || source.format() == crate::RASTER_FORMAT;
|
||||
let loads_linear_light = source.format().is_srgb() || matches!(source.format(), crate::RASTER_FORMAT | crate::FALLBACK_RASTER_FORMAT);
|
||||
alpha_conversion.premultiply(device, encoder, &source_view, loads_linear_light, &view);
|
||||
}
|
||||
|
||||
@@ -509,7 +509,7 @@ fn create_texture_with_format(device: &wgpu::Device, label: &str, size: UVec2, f
|
||||
struct AlphaConversion {
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
unpremultiply_pipeline: wgpu::RenderPipeline,
|
||||
/// Unpremultiplies into a linear-light [`crate::RASTER_FORMAT`] target.
|
||||
/// Unpremultiplies into a linear-light target in the executor's raster format.
|
||||
unpremultiply_to_linear_pipeline: wgpu::RenderPipeline,
|
||||
premultiply_pipeline: wgpu::RenderPipeline,
|
||||
/// The parameters for a source whose format stores linear values.
|
||||
@@ -519,7 +519,7 @@ struct AlphaConversion {
|
||||
}
|
||||
|
||||
impl AlphaConversion {
|
||||
fn new(device: &wgpu::Device) -> Self {
|
||||
fn new(device: &wgpu::Device, raster_format: wgpu::TextureFormat) -> Self {
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
let shader = device.create_shader_module(wgpu::include_wgsl!("vello_alpha.wgsl"));
|
||||
@@ -596,7 +596,7 @@ impl AlphaConversion {
|
||||
|
||||
Self {
|
||||
unpremultiply_pipeline: create_pipeline("vello_unpremultiply_pipeline", "unpremultiply", TEXTURE_FORMAT),
|
||||
unpremultiply_to_linear_pipeline: create_pipeline("vello_unpremultiply_to_linear_pipeline", "unpremultiply_to_linear", crate::RASTER_FORMAT),
|
||||
unpremultiply_to_linear_pipeline: create_pipeline("vello_unpremultiply_to_linear_pipeline", "unpremultiply_to_linear", raster_format),
|
||||
premultiply_pipeline: create_pipeline("vello_premultiply_pipeline", "premultiply", TEXTURE_FORMAT),
|
||||
linear_source_parameters: create_parameters("vello_alpha_linear_source", 0),
|
||||
srgb_source_parameters: create_parameters("vello_alpha_srgb_source", 1),
|
||||
@@ -605,10 +605,10 @@ impl AlphaConversion {
|
||||
}
|
||||
|
||||
fn unpremultiply(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, source: &wgpu::TextureView, target: &wgpu::TextureView, target_format: wgpu::TextureFormat) {
|
||||
let pipeline = if target_format == crate::RASTER_FORMAT {
|
||||
&self.unpremultiply_to_linear_pipeline
|
||||
} else {
|
||||
let pipeline = if target_format == TEXTURE_FORMAT {
|
||||
&self.unpremultiply_pipeline
|
||||
} else {
|
||||
&self.unpremultiply_to_linear_pipeline
|
||||
};
|
||||
self.run(device, encoder, pipeline, &self.linear_source_parameters, source, target);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ pub(super) struct Convert {
|
||||
}
|
||||
|
||||
impl Convert {
|
||||
pub(super) fn new(device: &wgpu::Device) -> Self {
|
||||
pub(super) fn new(device: &wgpu::Device, raster_format: wgpu::TextureFormat) -> Self {
|
||||
let shader = device.create_shader_module(wgpu::include_wgsl!("convert.wgsl"));
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("basic_brush_convert_bind_group_layout"),
|
||||
@@ -37,7 +37,7 @@ impl Convert {
|
||||
module: &shader,
|
||||
entry_point: Some("fs_main"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu_executor::RASTER_FORMAT.into())],
|
||||
targets: &[Some(raster_format.into())],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
|
||||
@@ -80,7 +80,7 @@ impl WgpuPipeline for BasicBrushPipeline {
|
||||
Self {
|
||||
scatter: Scatter::new(device),
|
||||
resolve: Resolve::new(device),
|
||||
convert: Convert::new(device),
|
||||
convert: Convert::new(device, executor.raster_format()),
|
||||
kernels: KernelCache::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ pub(super) fn render(pipeline: &BasicBrushPipeline, executor: &WgpuExecutor, fra
|
||||
let updated = (!missing.is_empty()).then(|| executor.request_texture_with_format(crop.size, COMPOSITE_FORMAT));
|
||||
let composite = executor.request_texture_with_format(crop.size, COMPOSITE_FORMAT);
|
||||
let scratch = Field::request(executor, region.size);
|
||||
let output = executor.request_texture_with_format(crop.size, wgpu_executor::RASTER_FORMAT);
|
||||
let output = executor.request_texture_with_format(crop.size, executor.raster_format());
|
||||
let mut recorder = Recorder::new(pipeline, executor, ®ion);
|
||||
|
||||
if let Some(updated) = &updated {
|
||||
|
||||
@@ -40,7 +40,7 @@ async fn dehaze(
|
||||
let dark_channel = run_raster_kernel(&DehazeErode { radius, vertical: true }, vec![dehaze_input(&eroded)], size, pipeline)?;
|
||||
let atmospheric_light = estimate_atmospheric_light(&dark_channel.clone().convert(Footprint::DEFAULT, executor).await);
|
||||
|
||||
// The guided filter's intermediates stay in `wgpu_executor::RASTER_FORMAT` since its variances lose their precision at half-float
|
||||
// The guided filter's intermediates stay in the executor's raster format rather than `FILTERABLE_FORMAT` since its variances lose their precision at half-float
|
||||
let radius = RADIUS as i32;
|
||||
let guide = DehazeGuideHorizontal {
|
||||
radius,
|
||||
|
||||
@@ -409,12 +409,16 @@ fn run<K: ToGpuParams + 'static>(
|
||||
.ok_or_else(|| NodeError::new("A GPU is required to process a GPU raster"))
|
||||
}
|
||||
|
||||
/// Runs `kernel` on its inputs, each placed by the affine from output pixel coordinates to its texel coordinates, into a raster of `output_size`.
|
||||
pub fn run_raster_kernel<K: RasterKernel>(kernel: &K, inputs: Vec<RasterKernelInput<'_>>, output_size: UVec2, pipeline: &WgpuPipelineCache) -> Result<Raster<GPU>, NodeError> {
|
||||
run_raster_kernel_with_format(kernel, inputs, output_size, RASTER_FORMAT, pipeline)
|
||||
fn raster_format(pipeline: &WgpuPipelineCache) -> WgpuTextureFormat {
|
||||
pipeline.executor().map_or(RASTER_FORMAT, WgpuExecutor::raster_format)
|
||||
}
|
||||
|
||||
/// Runs `kernel` like [`run_raster_kernel`] into a texture of `output_format` instead of [`RASTER_FORMAT`], such as a [`FILTERABLE_FORMAT`] intermediate a [`RasterKernel::FILTERED`] kernel can read.
|
||||
/// Runs `kernel` on its inputs, each placed by the affine from output pixel coordinates to its texel coordinates, into a raster of `output_size`.
|
||||
pub fn run_raster_kernel<K: RasterKernel>(kernel: &K, inputs: Vec<RasterKernelInput<'_>>, output_size: UVec2, pipeline: &WgpuPipelineCache) -> Result<Raster<GPU>, NodeError> {
|
||||
run_raster_kernel_with_format(kernel, inputs, output_size, raster_format(pipeline), pipeline)
|
||||
}
|
||||
|
||||
/// Runs `kernel` like [`run_raster_kernel`] into a texture of `output_format` instead of the executor's raster format, such as a [`FILTERABLE_FORMAT`] intermediate a [`RasterKernel::FILTERED`] kernel can read.
|
||||
pub fn run_raster_kernel_with_format<K: RasterKernel>(
|
||||
kernel: &K,
|
||||
inputs: Vec<RasterKernelInput<'_>>,
|
||||
@@ -453,7 +457,7 @@ impl Adjust for Raster<GPU> {
|
||||
raster: &self,
|
||||
output_to_texel: DAffine2::IDENTITY,
|
||||
};
|
||||
run(kernel, map_color_module::<K>, false, vec![input], size, RASTER_FORMAT, pipeline)
|
||||
run(kernel, map_color_module::<K>, false, vec![input], size, raster_format(pipeline), pipeline)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user