diff --git a/Cargo.lock b/Cargo.lock index 3ab655ab39..620d68db4d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8737,6 +8737,7 @@ dependencies = [ "futures", "glam", "graphene-application-io", + "half", "log", "node-macro", "raster-types", diff --git a/node-graph/libraries/wgpu-executor/Cargo.toml b/node-graph/libraries/wgpu-executor/Cargo.toml index e45a852e46..983102b269 100644 --- a/node-graph/libraries/wgpu-executor/Cargo.toml +++ b/node-graph/libraries/wgpu-executor/Cargo.toml @@ -33,3 +33,4 @@ web-sys = { workspace = true } vello_gpu = { workspace = true } bytemuck = { workspace = true } thiserror = { workspace = true } +half = { workspace = true } diff --git a/node-graph/libraries/wgpu-executor/src/lib.rs b/node-graph/libraries/wgpu-executor/src/lib.rs index c49f941067..d59efb53a4 100644 --- a/node-graph/libraries/wgpu-executor/src/lib.rs +++ b/node-graph/libraries/wgpu-executor/src/lib.rs @@ -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, + raster_format: wgpu::TextureFormat, vello_renderer: VelloRenderer, /// The canvas the node graph renders documents on. document_canvas: Mutex, @@ -182,6 +190,7 @@ impl WgpuExecutor { } pub fn with_context(context: WgpuContext) -> Option { + let raster_format = choose_raster_format(&context.adapter); let vello_renderer = VelloRenderer::new(&context.device); let texture_cache = TextureCache::new(TEXTURE_CACHE_SIZE); @@ -190,6 +199,7 @@ impl WgpuExecutor { inner: Arc::new(WgpuExecutorInner { context, texture_cache: texture_cache.into(), + raster_format, vello_renderer, document_canvas: Mutex::default(), }), @@ -200,3 +210,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 + } +} diff --git a/node-graph/libraries/wgpu-executor/src/texture_conversion.rs b/node-graph/libraries/wgpu-executor/src/texture_conversion.rs index e8c60ca135..6a322f7199 100644 --- a/node-graph/libraries/wgpu-executor/src/texture_conversion.rs +++ b/node-graph/libraries/wgpu-executor/src/texture_conversion.rs @@ -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::(row_slice)); - } else { - for &[red, green, blue, alpha] in row_slice.as_chunks::<4>().0 { - cpu_data.push(SRGBA8::new(red, green, blue, alpha).into()); + match self.format { + crate::RASTER_FORMAT => cpu_data.extend(bytemuck::pod_collect_to_vec::(row_slice)), + crate::FALLBACK_RASTER_FORMAT => { + let pixels = bytemuck::pod_collect_to_vec::(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 &[red, green, blue, alpha] in row_slice.as_chunks::<4>().0 { + cpu_data.push(SRGBA8::new(red, green, blue, alpha).into()); + } } } } diff --git a/node-graph/libraries/wgpu-executor/src/vello_render.rs b/node-graph/libraries/wgpu-executor/src/vello_render.rs index 5ed3aff53d..6b84c11bcc 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render.rs @@ -361,7 +361,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); } diff --git a/node-graph/nodes/brush/src/basic_brush/convert.rs b/node-graph/nodes/brush/src/basic_brush/convert.rs index 2f3d5b072a..91ff4f5816 100644 --- a/node-graph/nodes/brush/src/basic_brush/convert.rs +++ b/node-graph/nodes/brush/src/basic_brush/convert.rs @@ -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, diff --git a/node-graph/nodes/brush/src/basic_brush/pipeline.rs b/node-graph/nodes/brush/src/basic_brush/pipeline.rs index 21af38a097..cb8d36b30a 100644 --- a/node-graph/nodes/brush/src/basic_brush/pipeline.rs +++ b/node-graph/nodes/brush/src/basic_brush/pipeline.rs @@ -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(), } } diff --git a/node-graph/nodes/brush/src/basic_brush/render.rs b/node-graph/nodes/brush/src/basic_brush/render.rs index ed6cedec23..7802fe95e1 100644 --- a/node-graph/nodes/brush/src/basic_brush/render.rs +++ b/node-graph/nodes/brush/src/basic_brush/render.rs @@ -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 { diff --git a/node-graph/nodes/raster/src/dehaze.rs b/node-graph/nodes/raster/src/dehaze.rs index 286762acae..b3228a0273 100644 --- a/node-graph/nodes/raster/src/dehaze.rs +++ b/node-graph/nodes/raster/src/dehaze.rs @@ -73,7 +73,7 @@ fn dehaze_input(raster: &Raster) -> RasterKernelInput<'_> { impl DehazeRaster for Raster { /// Runs the CPU's algorithm in float without its 8-bit quantization, downloading the dark channel to choose the atmospheric light exactly as the CPU does. - /// 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. async fn dehaze(image: Item, strength: f64, pipeline: &WgpuPipelineCache) -> Result, NodeError> { if image.element().is_empty() { return Ok(image); diff --git a/node-graph/nodes/raster/src/raster_kernel.rs b/node-graph/nodes/raster/src/raster_kernel.rs index 599c66314f..d653831062 100644 --- a/node-graph/nodes/raster/src/raster_kernel.rs +++ b/node-graph/nodes/raster/src/raster_kernel.rs @@ -411,12 +411,16 @@ fn run( .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(kernel: &K, inputs: Vec>, output_size: UVec2, pipeline: &WgpuPipelineCache) -> Result, 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(kernel: &K, inputs: Vec>, output_size: UVec2, pipeline: &WgpuPipelineCache) -> Result, 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( kernel: &K, inputs: Vec>, @@ -464,7 +468,7 @@ impl Adjust for Raster { raster: &self, output_to_texel: DAffine2::IDENTITY, }; - run(kernel, map_color_module::, false, vec![input], size, RASTER_FORMAT, pipeline) + run(kernel, map_color_module::, false, vec![input], size, raster_format(pipeline), pipeline) } }