mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
perf(ui): reuse headless pipelines on the same GPU device
This commit is contained in:
1 parent
12bd597e81
commit
57b57a2785
6 files changed
+1313
-1183
No files matched your search
@@ -11,6 +11,8 @@ use wgpu::TextureFormat;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WgpuContext {
|
||||
#[cfg(all(not(target_family = "wasm"), any(test, feature = "harness")))]
|
||||
pub(crate) headless_pipelines: Arc<super::wgpu_renderer::pipelines::PipelineCache>,
|
||||
pub instance: wgpu::Instance,
|
||||
pub adapter: wgpu::Adapter,
|
||||
pub device: Arc<wgpu::Device>,
|
||||
@@ -294,6 +296,8 @@ impl WgpuContext {
|
||||
let backend = WgpuBackend::Native(adapter.get_info().backend);
|
||||
|
||||
Self {
|
||||
#[cfg(any(test, feature = "harness"))]
|
||||
headless_pipelines: Arc::default(),
|
||||
instance,
|
||||
adapter,
|
||||
device: Arc::new(device),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,442 @@
|
||||
use super::{pipelines::*, *};
|
||||
|
||||
/// GPU resources that must be dropped together during device recovery.
|
||||
pub(crate) struct WgpuResources {
|
||||
pub(crate) device: Arc<wgpu::Device>,
|
||||
pub(crate) queue: Arc<wgpu::Queue>,
|
||||
pub(crate) pipelines: WgpuPipelines,
|
||||
pub(crate) bind_group_layouts: WgpuBindGroupLayouts,
|
||||
pub(crate) atlas_sampler: wgpu::Sampler,
|
||||
pub(crate) globals_buffer: wgpu::Buffer,
|
||||
pub(crate) globals_bind_group: wgpu::BindGroup,
|
||||
pub(crate) path_globals_bind_group: wgpu::BindGroup,
|
||||
pub(crate) instance_data: InstanceData,
|
||||
pub(super) path_intermediate_texture: Option<wgpu::Texture>,
|
||||
pub(crate) path_intermediate_view: Option<wgpu::TextureView>,
|
||||
pub(super) path_msaa_texture: Option<wgpu::Texture>,
|
||||
pub(crate) path_msaa_view: Option<wgpu::TextureView>,
|
||||
}
|
||||
|
||||
impl WgpuResources {
|
||||
pub(super) fn invalidate_intermediate_textures(&mut self) {
|
||||
self.path_intermediate_texture = None;
|
||||
self.path_intermediate_view = None;
|
||||
self.path_msaa_texture = None;
|
||||
self.path_msaa_view = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct WgpuRendererCore {
|
||||
pub(crate) resources: WgpuResources,
|
||||
pub(crate) atlas: Arc<WgpuAtlas>,
|
||||
pub(crate) path_globals_offset: u64,
|
||||
pub(crate) gamma_offset: u64,
|
||||
pub(crate) instance_data_capacity: u64,
|
||||
max_instance_data_size: u64,
|
||||
pub(crate) instance_data_alignment: u64,
|
||||
pub(crate) uses_webgl_instance_data: bool,
|
||||
pub(crate) rendering_params: RenderingParameters,
|
||||
pub(super) is_bgr: bool,
|
||||
pub(super) dual_source_blending: bool,
|
||||
pub(super) adapter_info: wgpu::AdapterInfo,
|
||||
pub(crate) target_format: wgpu::TextureFormat,
|
||||
pub(super) max_texture_size: u32,
|
||||
pub(crate) fast_frame: crate::platform::wgpu::fast::frame::FrameState,
|
||||
}
|
||||
|
||||
impl WgpuRendererCore {
|
||||
fn create_path_texture(
|
||||
device: &wgpu::Device,
|
||||
format: wgpu::TextureFormat,
|
||||
width: u32,
|
||||
height: u32,
|
||||
sample_count: u32,
|
||||
) -> (wgpu::Texture, wgpu::TextureView) {
|
||||
let (label, extra_usage) = if sample_count == 1 {
|
||||
("path_intermediate", wgpu::TextureUsages::TEXTURE_BINDING)
|
||||
} else {
|
||||
("path_msaa", wgpu::TextureUsages::empty())
|
||||
};
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d {
|
||||
width: width.max(1),
|
||||
height: height.max(1),
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | extra_usage,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
(texture, view)
|
||||
}
|
||||
|
||||
/// With `uses_webgl_instance_data`, instance data and path triangles go
|
||||
/// through `Rgba32Uint` textures, as WebGL2 needs.
|
||||
pub(super) fn new(
|
||||
context: &WgpuContext,
|
||||
atlas: Arc<WgpuAtlas>,
|
||||
target_format: wgpu::TextureFormat,
|
||||
alpha_mode: wgpu::CompositeAlphaMode,
|
||||
uses_webgl_instance_data: bool,
|
||||
cache: Option<&PipelineCache>,
|
||||
) -> Self {
|
||||
let device = Arc::clone(&context.device);
|
||||
let rendering_params = RenderingParameters::new(&context.adapter, target_format);
|
||||
let dual_source_blending =
|
||||
context.supports_dual_source_blending() && !uses_webgl_instance_data;
|
||||
let key = PipelineCacheKey {
|
||||
surface_format: target_format,
|
||||
alpha_mode,
|
||||
path_sample_count: rendering_params.path_sample_count,
|
||||
dual_source_blending,
|
||||
uses_webgl_instance_data,
|
||||
};
|
||||
// wgpu pools this layout on the device. Each window owns its clip bindings.
|
||||
let fast_rounded_clip = super::super::fast::rounded_clip::Bindings::new(&device);
|
||||
let build = || {
|
||||
let layouts = Self::create_bind_group_layouts(&device, key.uses_webgl_instance_data);
|
||||
let pipelines =
|
||||
Self::create_pipelines(&device, &layouts, &fast_rounded_clip.layout, key);
|
||||
(layouts, pipelines)
|
||||
};
|
||||
let (layouts, pipelines) = match cache {
|
||||
Some(cache) => cache.lock().entry(key).or_insert_with(build).clone(),
|
||||
None => build(),
|
||||
};
|
||||
let bind_group_layouts = WgpuBindGroupLayouts {
|
||||
fast_rounded_clip,
|
||||
layouts,
|
||||
};
|
||||
let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("atlas_sampler"),
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
..Default::default()
|
||||
});
|
||||
let uniform_alignment = device.limits().min_uniform_buffer_offset_alignment as u64;
|
||||
let globals_size = std::mem::size_of::<GlobalParams>() as u64;
|
||||
let gamma_size = std::mem::size_of::<GammaParams>() as u64;
|
||||
let path_globals_offset = globals_size.next_multiple_of(uniform_alignment);
|
||||
let gamma_offset = (path_globals_offset + globals_size).next_multiple_of(uniform_alignment);
|
||||
let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("globals_buffer"),
|
||||
size: gamma_offset + gamma_size,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let (
|
||||
instance_data,
|
||||
instance_data_capacity,
|
||||
max_instance_data_size,
|
||||
instance_data_alignment,
|
||||
) = if uses_webgl_instance_data {
|
||||
let max_texture_dimension = device.limits().max_texture_dimension_2d;
|
||||
let max_instance_data_size = (u64::from(max_texture_dimension).pow(2)
|
||||
* INSTANCE_TEXTURE_TEXEL_SIZE)
|
||||
.min(MAX_INSTANCE_BUFFER_SIZE);
|
||||
let initial_capacity = (2 * 1024 * 1024).min(max_instance_data_size);
|
||||
let (instance_data, capacity) =
|
||||
Self::create_instance_texture(&device, initial_capacity, max_texture_dimension);
|
||||
(
|
||||
instance_data,
|
||||
capacity,
|
||||
max_instance_data_size,
|
||||
INSTANCE_TEXTURE_TEXEL_SIZE,
|
||||
)
|
||||
} else {
|
||||
let max_buffer_size = device
|
||||
.limits()
|
||||
.max_buffer_size
|
||||
.min(device.limits().max_storage_buffer_binding_size)
|
||||
.min(MAX_INSTANCE_BUFFER_SIZE);
|
||||
let initial_capacity = (2 * 1024 * 1024).min(max_buffer_size);
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("instance_buffer"),
|
||||
size: initial_capacity,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
(
|
||||
InstanceData::Storage(buffer),
|
||||
initial_capacity,
|
||||
max_buffer_size,
|
||||
device.limits().min_storage_buffer_offset_alignment as u64,
|
||||
)
|
||||
};
|
||||
let bind_globals = |label, offset| {
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some(label),
|
||||
layout: &bind_group_layouts.globals,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &globals_buffer,
|
||||
offset,
|
||||
size: NonZeroU64::new(globals_size),
|
||||
}),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &globals_buffer,
|
||||
offset: gamma_offset,
|
||||
size: NonZeroU64::new(gamma_size),
|
||||
}),
|
||||
},
|
||||
],
|
||||
})
|
||||
};
|
||||
let globals_bind_group = bind_globals("globals_bind_group", 0);
|
||||
let path_globals_bind_group = bind_globals("path_globals_bind_group", path_globals_offset);
|
||||
|
||||
Self {
|
||||
resources: WgpuResources {
|
||||
device,
|
||||
queue: Arc::clone(&context.queue),
|
||||
pipelines,
|
||||
bind_group_layouts,
|
||||
atlas_sampler,
|
||||
globals_buffer,
|
||||
globals_bind_group,
|
||||
path_globals_bind_group,
|
||||
instance_data,
|
||||
path_intermediate_texture: None,
|
||||
path_intermediate_view: None,
|
||||
path_msaa_texture: None,
|
||||
path_msaa_view: None,
|
||||
},
|
||||
atlas,
|
||||
path_globals_offset,
|
||||
gamma_offset,
|
||||
instance_data_capacity,
|
||||
max_instance_data_size,
|
||||
instance_data_alignment,
|
||||
uses_webgl_instance_data,
|
||||
rendering_params,
|
||||
is_bgr: false,
|
||||
dual_source_blending,
|
||||
adapter_info: context.adapter.get_info(),
|
||||
target_format,
|
||||
max_texture_size: context.device.limits().max_texture_dimension_2d,
|
||||
fast_frame: crate::platform::wgpu::fast::frame::FrameState::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resources(&self) -> &WgpuResources {
|
||||
&self.resources
|
||||
}
|
||||
|
||||
/// Path rendering goes through an intermediate texture that must match the frame
|
||||
/// target's dimensions, so the textures are keyed by size and rebuilt on mismatch.
|
||||
fn ensure_intermediate_textures(&mut self, size: Size<DevicePixels>) {
|
||||
let width = size.width.0 as u32;
|
||||
let height = size.height.0 as u32;
|
||||
if self
|
||||
.resources
|
||||
.path_intermediate_texture
|
||||
.as_ref()
|
||||
.is_some_and(|texture| texture.width() == width && texture.height() == height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let path_sample_count = self.rendering_params.path_sample_count;
|
||||
let resources = &mut self.resources;
|
||||
|
||||
let (texture, view) =
|
||||
Self::create_path_texture(&resources.device, self.target_format, width, height, 1);
|
||||
resources.path_intermediate_texture = Some(texture);
|
||||
resources.path_intermediate_view = Some(view);
|
||||
|
||||
if path_sample_count > 1 {
|
||||
let (texture, view) = Self::create_path_texture(
|
||||
&resources.device,
|
||||
self.target_format,
|
||||
width,
|
||||
height,
|
||||
path_sample_count,
|
||||
);
|
||||
resources.path_msaa_texture = Some(texture);
|
||||
resources.path_msaa_view = Some(view);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn render_frame(
|
||||
&mut self,
|
||||
scene: &Scene,
|
||||
target_view: &wgpu::TextureView,
|
||||
size: Size<DevicePixels>,
|
||||
premultiplied_alpha: bool,
|
||||
clear_color: wgpu::Color,
|
||||
) -> Result<wgpu::SubmissionIndex> {
|
||||
anyhow::ensure!(
|
||||
size.width.0 > 0 && size.height.0 > 0,
|
||||
"invalid render target size: {size:?}"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
size.width.0 as u32 <= self.max_texture_size
|
||||
&& size.height.0 as u32 <= self.max_texture_size,
|
||||
"render target size {size:?} exceeds maximum texture dimension {}",
|
||||
self.max_texture_size
|
||||
);
|
||||
|
||||
self.atlas.before_frame();
|
||||
self.ensure_intermediate_textures(size);
|
||||
|
||||
let gamma_params = GammaParams {
|
||||
gamma_ratios: self.rendering_params.gamma_ratios,
|
||||
grayscale_enhanced_contrast: self.rendering_params.grayscale_enhanced_contrast,
|
||||
subpixel_enhanced_contrast: self.rendering_params.subpixel_enhanced_contrast,
|
||||
is_bgr: self.is_bgr as u32,
|
||||
_pad: 0,
|
||||
};
|
||||
let globals = GlobalParams {
|
||||
viewport_size: [size.width.0 as f32, size.height.0 as f32],
|
||||
premultiplied_alpha: premultiplied_alpha as u32,
|
||||
pad: 0,
|
||||
};
|
||||
let path_globals = GlobalParams {
|
||||
premultiplied_alpha: 0,
|
||||
..globals
|
||||
};
|
||||
crate::platform::wgpu::fast::globals::write_globals(
|
||||
self,
|
||||
&globals,
|
||||
&path_globals,
|
||||
&gamma_params,
|
||||
);
|
||||
|
||||
self.record_frame(scene, target_view, clear_color)
|
||||
.inspect_err(|_| {
|
||||
// Queue writes are staged before encoding; flush them even if the frame fails.
|
||||
self.resources.queue.submit(std::iter::empty());
|
||||
})
|
||||
}
|
||||
|
||||
fn record_frame(
|
||||
&mut self,
|
||||
scene: &Scene,
|
||||
frame_view: &wgpu::TextureView,
|
||||
clear_color: wgpu::Color,
|
||||
) -> Result<wgpu::SubmissionIndex> {
|
||||
crate::platform::wgpu::fast::frame::record_into(self, scene, frame_view, clear_color)
|
||||
}
|
||||
|
||||
/// Writes `data` at byte `offset` of the WebGL instance texture, and
|
||||
/// returns the `write_texture` calls: none on the storage-buffer path.
|
||||
pub(crate) fn write_instance_texture(
|
||||
resources: &WgpuResources,
|
||||
offset: u64,
|
||||
data: &[u8],
|
||||
) -> usize {
|
||||
let InstanceData::Texture {
|
||||
texture,
|
||||
width,
|
||||
height,
|
||||
..
|
||||
} = &resources.instance_data
|
||||
else {
|
||||
return 0;
|
||||
};
|
||||
crate::platform::wgpu::fast::texels::write(
|
||||
&resources.queue,
|
||||
texture,
|
||||
(*width, *height),
|
||||
offset,
|
||||
data,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn grow_instance_data(&mut self, required: u64) -> Result<()> {
|
||||
let capacity = (self.instance_data_capacity * 2)
|
||||
.max(required.next_power_of_two())
|
||||
.min(self.max_instance_data_size);
|
||||
anyhow::ensure!(
|
||||
capacity >= required,
|
||||
"instance data needs {required} bytes, above the maximum of {}",
|
||||
self.max_instance_data_size
|
||||
);
|
||||
anyhow::ensure!(
|
||||
capacity > self.instance_data_capacity,
|
||||
"frame instance data exceeds the {}-byte maximum",
|
||||
self.max_instance_data_size
|
||||
);
|
||||
log::debug!(
|
||||
"instance data grown from {} to {capacity}",
|
||||
self.instance_data_capacity
|
||||
);
|
||||
// Bind groups created earlier in the frame keep the previous buffer or
|
||||
// texture alive, so allocations written before the grow remain valid;
|
||||
// only subsequent writes land in the new allocation.
|
||||
let uses_webgl_instance_data = self.uses_webgl_instance_data;
|
||||
let resources = &mut self.resources;
|
||||
if uses_webgl_instance_data {
|
||||
let max_texture_dimension = resources.device.limits().max_texture_dimension_2d;
|
||||
let (instance_data, actual_capacity) =
|
||||
Self::create_instance_texture(&resources.device, capacity, max_texture_dimension);
|
||||
resources.instance_data = instance_data;
|
||||
self.instance_data_capacity = actual_capacity;
|
||||
} else {
|
||||
resources.instance_data =
|
||||
InstanceData::Storage(resources.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("instance_buffer"),
|
||||
size: capacity,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
}));
|
||||
self.instance_data_capacity = capacity;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct RenderingParameters {
|
||||
pub(crate) path_sample_count: u32,
|
||||
pub(crate) gamma_ratios: [f32; 4],
|
||||
pub(crate) grayscale_enhanced_contrast: f32,
|
||||
pub(crate) subpixel_enhanced_contrast: f32,
|
||||
}
|
||||
|
||||
impl RenderingParameters {
|
||||
pub(crate) fn new(adapter: &wgpu::Adapter, surface_format: wgpu::TextureFormat) -> Self {
|
||||
use std::env;
|
||||
|
||||
let format_features = adapter.get_texture_format_features(surface_format);
|
||||
let path_sample_count = [4, 2, 1]
|
||||
.into_iter()
|
||||
.find(|&n| format_features.flags.sample_count_supported(n))
|
||||
.unwrap_or(1);
|
||||
|
||||
let gamma = env::var("ZED_FONTS_GAMMA")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(1.8_f32)
|
||||
.clamp(1.0, 2.2);
|
||||
let gamma_ratios = get_gamma_correction_ratios(gamma);
|
||||
|
||||
let grayscale_enhanced_contrast = env::var("ZED_FONTS_GRAYSCALE_ENHANCED_CONTRAST")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(1.0_f32)
|
||||
.max(0.0);
|
||||
|
||||
let subpixel_enhanced_contrast = env::var("ZED_FONTS_SUBPIXEL_ENHANCED_CONTRAST")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(0.5_f32)
|
||||
.max(0.0);
|
||||
|
||||
Self {
|
||||
path_sample_count,
|
||||
gamma_ratios,
|
||||
grayscale_enhanced_contrast,
|
||||
subpixel_enhanced_contrast,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
use super::*;
|
||||
|
||||
struct HeadlessRenderTarget {
|
||||
texture: wgpu::Texture,
|
||||
view: wgpu::TextureView,
|
||||
}
|
||||
|
||||
impl HeadlessRenderTarget {
|
||||
fn size(&self) -> Size<DevicePixels> {
|
||||
Size {
|
||||
width: DevicePixels(self.texture.width() as i32),
|
||||
height: DevicePixels(self.texture.height() as i32),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WgpuHeadlessRenderer {
|
||||
context: WgpuContext,
|
||||
pub(crate) core: WgpuRendererCore,
|
||||
render_target: Option<HeadlessRenderTarget>,
|
||||
observed_error_generation: u64,
|
||||
}
|
||||
|
||||
impl WgpuHeadlessRenderer {
|
||||
pub fn new() -> anyhow::Result<Self> {
|
||||
Self::with_instance_texture(false)
|
||||
}
|
||||
|
||||
/// A renderer that, with `instance_texture`, draws through the WebGL2
|
||||
/// texture transport.
|
||||
pub(crate) fn with_instance_texture(instance_texture: bool) -> anyhow::Result<Self> {
|
||||
let (context, target_format) = WgpuContext::new_headless()?;
|
||||
Ok(Self::with_context(context, target_format, instance_texture))
|
||||
}
|
||||
|
||||
fn with_context(
|
||||
context: WgpuContext,
|
||||
target_format: wgpu::TextureFormat,
|
||||
instance_texture: bool,
|
||||
) -> Self {
|
||||
// The device may be shared with earlier renderers; observe only errors raised from
|
||||
// here on, including any while this renderer builds its pipelines.
|
||||
let observed_error_generation = context.errors().current_generation();
|
||||
let atlas = Arc::new(WgpuAtlas::from_context(&context));
|
||||
let core = WgpuRendererCore::new(
|
||||
&context,
|
||||
atlas,
|
||||
target_format,
|
||||
wgpu::CompositeAlphaMode::Opaque,
|
||||
instance_texture,
|
||||
Some(&context.headless_pipelines),
|
||||
);
|
||||
|
||||
Self {
|
||||
context,
|
||||
core,
|
||||
render_target: None,
|
||||
observed_error_generation,
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_render_target(&mut self, size: Size<DevicePixels>) -> anyhow::Result<()> {
|
||||
anyhow::ensure!(
|
||||
size.width.0 > 0 && size.height.0 > 0,
|
||||
"invalid headless render target size: {size:?}"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
size.width.0 as u32 <= self.core.max_texture_size
|
||||
&& size.height.0 as u32 <= self.core.max_texture_size,
|
||||
"headless render target size {size:?} exceeds maximum texture dimension {}",
|
||||
self.core.max_texture_size
|
||||
);
|
||||
if self
|
||||
.render_target
|
||||
.as_ref()
|
||||
.is_some_and(|target| target.size() == size)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let texture = self
|
||||
.core
|
||||
.resources
|
||||
.device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("headless_render_target"),
|
||||
size: wgpu::Extent3d {
|
||||
width: size.width.0 as u32,
|
||||
height: size.height.0 as u32,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: self.core.target_format,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.render_target = Some(HeadlessRenderTarget { texture, view });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_gpu_errors(&mut self) -> anyhow::Result<()> {
|
||||
anyhow::ensure!(
|
||||
!self.context.device_lost(),
|
||||
"GPU device was lost during headless rendering"
|
||||
);
|
||||
if let Some(error) = self
|
||||
.context
|
||||
.errors()
|
||||
.observe_error(&mut self.observed_error_generation)
|
||||
{
|
||||
anyhow::bail!("GPU error during headless rendering: {error}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn render(&mut self, scene: &Scene, size: Size<DevicePixels>) -> anyhow::Result<()> {
|
||||
self.check_gpu_errors()?;
|
||||
self.ensure_render_target(size)?;
|
||||
let view = self
|
||||
.render_target
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Headless render target was not created"))?
|
||||
.view
|
||||
.clone();
|
||||
self.core
|
||||
.render_frame(scene, &view, size, false, wgpu::Color::BLACK)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copies the current render target back to the CPU. Dimensions come from the
|
||||
/// target texture itself, so the copy can never disagree with what was rendered.
|
||||
fn read_image(&mut self) -> anyhow::Result<image::RgbaImage> {
|
||||
let target = self
|
||||
.render_target
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Headless render target was not created"))?;
|
||||
let width = target.texture.width();
|
||||
let height = target.texture.height();
|
||||
let bytes_per_row = width
|
||||
.checked_mul(4)
|
||||
.ok_or_else(|| anyhow::anyhow!("Headless render target row size overflowed"))?;
|
||||
let padded_bytes_per_row = bytes_per_row
|
||||
.checked_next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
|
||||
.ok_or_else(|| anyhow::anyhow!("Headless padded row size overflowed"))?;
|
||||
let buffer_size = u64::from(padded_bytes_per_row)
|
||||
.checked_mul(u64::from(height))
|
||||
.ok_or_else(|| anyhow::anyhow!("Headless readback buffer size overflowed"))?;
|
||||
anyhow::ensure!(
|
||||
buffer_size <= self.core.resources.device.limits().max_buffer_size,
|
||||
"Headless readback buffer size {buffer_size} exceeds maximum buffer size {}",
|
||||
self.core.resources.device.limits().max_buffer_size
|
||||
);
|
||||
let readback_buffer = self
|
||||
.core
|
||||
.resources
|
||||
.device
|
||||
.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("headless_readback_buffer"),
|
||||
size: buffer_size,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut encoder =
|
||||
self.core
|
||||
.resources
|
||||
.device
|
||||
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("headless_readback_encoder"),
|
||||
});
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &target.texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &readback_buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(padded_bytes_per_row),
|
||||
rows_per_image: Some(height),
|
||||
},
|
||||
},
|
||||
wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
let submission = self
|
||||
.core
|
||||
.resources
|
||||
.queue
|
||||
.submit(std::iter::once(encoder.finish()));
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
readback_buffer
|
||||
.slice(..)
|
||||
.map_async(wgpu::MapMode::Read, move |result| {
|
||||
if sender.send(result).is_err() {
|
||||
log::error!("Headless readback receiver was dropped before mapping completed");
|
||||
}
|
||||
});
|
||||
self.core
|
||||
.resources
|
||||
.device
|
||||
.poll(wgpu::PollType::Wait {
|
||||
submission_index: Some(submission),
|
||||
timeout: Some(std::time::Duration::from_secs(30)),
|
||||
})
|
||||
.map_err(|error| anyhow::anyhow!("Failed to wait for headless rendering: {error}"))?;
|
||||
receiver
|
||||
.recv_timeout(std::time::Duration::from_secs(30))
|
||||
.map_err(|error| anyhow::anyhow!("Failed to receive headless mapping result: {error}"))?
|
||||
.map_err(|error| anyhow::anyhow!("Failed to map headless readback buffer: {error}"))?;
|
||||
self.check_gpu_errors()?;
|
||||
|
||||
let mapped_data = readback_buffer.slice(..).get_mapped_range()?;
|
||||
let pixel_capacity = usize::try_from(u64::from(bytes_per_row) * u64::from(height))
|
||||
.map_err(|_| anyhow::anyhow!("Headless image size exceeds addressable memory"))?;
|
||||
let mut pixels = Vec::with_capacity(pixel_capacity);
|
||||
for row in mapped_data
|
||||
.chunks_exact(padded_bytes_per_row as usize)
|
||||
.take(height as usize)
|
||||
{
|
||||
pixels.extend_from_slice(&row[..bytes_per_row as usize]);
|
||||
}
|
||||
drop(mapped_data);
|
||||
readback_buffer.unmap();
|
||||
|
||||
if self.core.target_format == wgpu::TextureFormat::Bgra8Unorm {
|
||||
for pixel in pixels.chunks_exact_mut(4) {
|
||||
pixel.swap(0, 2);
|
||||
}
|
||||
}
|
||||
|
||||
image::RgbaImage::from_raw(width, height, pixels)
|
||||
.ok_or_else(|| anyhow::anyhow!("Failed to create image from headless pixel data"))
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::PlatformHeadlessRenderer for WgpuHeadlessRenderer {
|
||||
fn render_scene_to_image(
|
||||
&mut self,
|
||||
scene: &Scene,
|
||||
size: Size<DevicePixels>,
|
||||
) -> anyhow::Result<image::RgbaImage> {
|
||||
self.render(scene, size)?;
|
||||
self.read_image()
|
||||
}
|
||||
|
||||
fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> anyhow::Result<()> {
|
||||
self.render(scene, size)
|
||||
}
|
||||
|
||||
fn sprite_atlas(&self) -> Arc<dyn crate::PlatformAtlas> {
|
||||
self.core.atlas.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../../../../tests/wgpu_pipeline_cache/mod.rs"]
|
||||
mod pipeline_cache_tests;
|
||||
@@ -0,0 +1,459 @@
|
||||
use super::*;
|
||||
|
||||
/// Shared WGSL shader logic stored once in `.rodata` and combined with the
|
||||
/// active backend transport at shader-module creation time.
|
||||
const COMMON_SHADERS: &str = include_str!("../shaders.wgsl");
|
||||
|
||||
/// Storage-buffer instance transport for backends with storage buffer support.
|
||||
const STORAGE_TRANSPORT_SHADERS: &str = include_str!("../shaders_storage.wgsl");
|
||||
|
||||
/// Texture-based instance transport for WebGL2, which has no storage buffers.
|
||||
const WEBGL_TRANSPORT_SHADERS: &str = include_str!("../shaders_webgl.wgsl");
|
||||
|
||||
/// Subpixel text rendering extension requiring dual-source blending.
|
||||
const SUBPIXEL_EXTRA_SHADERS: &str = include_str!("../shaders_subpixel.wgsl");
|
||||
|
||||
// The texture format includes its transfer function. Device features are
|
||||
// constant for this cache, and a surface is not a pipeline input.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct PipelineCacheKey {
|
||||
pub(super) surface_format: wgpu::TextureFormat,
|
||||
pub(super) alpha_mode: wgpu::CompositeAlphaMode,
|
||||
pub(super) path_sample_count: u32,
|
||||
pub(super) dual_source_blending: bool,
|
||||
pub(super) uses_webgl_instance_data: bool,
|
||||
}
|
||||
pub(crate) type PipelineCache = parking_lot::Mutex<
|
||||
std::collections::HashMap<PipelineCacheKey, (PipelineLayouts, WgpuPipelines)>,
|
||||
>;
|
||||
|
||||
pub(crate) struct WgpuBindGroupLayouts {
|
||||
pub(crate) fast_rounded_clip: crate::platform::wgpu::fast::rounded_clip::Bindings,
|
||||
pub(super) layouts: PipelineLayouts,
|
||||
}
|
||||
impl std::ops::Deref for WgpuBindGroupLayouts {
|
||||
type Target = PipelineLayouts;
|
||||
fn deref(&self) -> &PipelineLayouts {
|
||||
&self.layouts
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct PipelineLayouts {
|
||||
pub(crate) globals: wgpu::BindGroupLayout,
|
||||
pub(crate) instances: wgpu::BindGroupLayout,
|
||||
pub(crate) texture: wgpu::BindGroupLayout,
|
||||
}
|
||||
|
||||
impl WgpuRendererCore {
|
||||
pub(super) fn create_bind_group_layouts(
|
||||
device: &wgpu::Device,
|
||||
uses_webgl_instance_data: bool,
|
||||
) -> PipelineLayouts {
|
||||
let globals =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("globals_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: NonZeroU64::new(
|
||||
std::mem::size_of::<GlobalParams>() as u64
|
||||
),
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: NonZeroU64::new(
|
||||
std::mem::size_of::<GammaParams>() as u64
|
||||
),
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let instance_data_entry = wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: if uses_webgl_instance_data {
|
||||
wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Uint,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
}
|
||||
} else {
|
||||
wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: true },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
}
|
||||
},
|
||||
count: None,
|
||||
};
|
||||
|
||||
let instances = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("instances_layout"),
|
||||
entries: &[instance_data_entry],
|
||||
});
|
||||
|
||||
let texture = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("texture_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
PipelineLayouts {
|
||||
globals,
|
||||
instances,
|
||||
texture,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_instance_texture(
|
||||
device: &wgpu::Device,
|
||||
requested_capacity: u64,
|
||||
max_texture_dimension: u32,
|
||||
) -> (InstanceData, u64) {
|
||||
let texel_count = requested_capacity.div_ceil(INSTANCE_TEXTURE_TEXEL_SIZE);
|
||||
let width = texel_count.min(u64::from(max_texture_dimension)).max(1) as u32;
|
||||
let height = texel_count
|
||||
.div_ceil(u64::from(width))
|
||||
.min(u64::from(max_texture_dimension))
|
||||
.max(1) as u32;
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("instance_texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba32Uint,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let capacity = u64::from(width) * u64::from(height) * INSTANCE_TEXTURE_TEXEL_SIZE;
|
||||
(
|
||||
InstanceData::Texture {
|
||||
texture,
|
||||
view,
|
||||
width,
|
||||
height,
|
||||
},
|
||||
capacity,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn create_pipelines(
|
||||
device: &wgpu::Device,
|
||||
layouts: &PipelineLayouts,
|
||||
clip_layout: &wgpu::BindGroupLayout,
|
||||
key: PipelineCacheKey,
|
||||
) -> WgpuPipelines {
|
||||
let PipelineCacheKey {
|
||||
surface_format,
|
||||
alpha_mode,
|
||||
path_sample_count,
|
||||
dual_source_blending,
|
||||
uses_webgl_instance_data,
|
||||
} = key;
|
||||
// Diagnostic guard: verify the device actually has
|
||||
// DUAL_SOURCE_BLENDING. We have a crash report (ZED-5G1) where a
|
||||
// feature mismatch caused a wgpu-hal abort, but we haven't
|
||||
// identified the code path that produces the mismatch. This
|
||||
// guard prevents the crash and logs more evidence.
|
||||
// Remove this check once:
|
||||
// a) We find and fix the root cause, or
|
||||
// b) There are no reports of this warning appearing for some time.
|
||||
let device_has_feature = device
|
||||
.features()
|
||||
.contains(wgpu::Features::DUAL_SOURCE_BLENDING);
|
||||
if dual_source_blending && !device_has_feature {
|
||||
log::error!(
|
||||
"BUG: dual_source_blending flag is true but device does not \
|
||||
have DUAL_SOURCE_BLENDING enabled (device features: {:?}). \
|
||||
Falling back to mono text rendering. Please report this at \
|
||||
https://github.com/zed-industries/zed/issues",
|
||||
device.features(),
|
||||
);
|
||||
}
|
||||
let dual_source_blending =
|
||||
dual_source_blending && device_has_feature && !uses_webgl_instance_data;
|
||||
|
||||
let transport_shaders = if uses_webgl_instance_data {
|
||||
WEBGL_TRANSPORT_SHADERS
|
||||
} else {
|
||||
STORAGE_TRANSPORT_SHADERS
|
||||
};
|
||||
let mut shader_source =
|
||||
String::with_capacity(COMMON_SHADERS.len() + transport_shaders.len());
|
||||
shader_source.push_str(COMMON_SHADERS);
|
||||
shader_source.push_str(transport_shaders);
|
||||
let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("gpui_shaders"),
|
||||
source: crate::platform::wgpu::fast::rounded_clip::shader_source(&shader_source),
|
||||
});
|
||||
drop(shader_source);
|
||||
|
||||
let subpixel_shader_module = if dual_source_blending {
|
||||
const ENABLE_DIRECTIVE: &str = "enable dual_source_blending;\n";
|
||||
let mut subpixel_source = String::with_capacity(
|
||||
ENABLE_DIRECTIVE.len()
|
||||
+ COMMON_SHADERS.len()
|
||||
+ STORAGE_TRANSPORT_SHADERS.len()
|
||||
+ SUBPIXEL_EXTRA_SHADERS.len(),
|
||||
);
|
||||
subpixel_source.push_str(ENABLE_DIRECTIVE);
|
||||
subpixel_source.push_str(COMMON_SHADERS);
|
||||
subpixel_source.push_str(STORAGE_TRANSPORT_SHADERS);
|
||||
subpixel_source.push_str(SUBPIXEL_EXTRA_SHADERS);
|
||||
Some(device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("gpui_subpixel_shaders"),
|
||||
source: crate::platform::wgpu::fast::rounded_clip::shader_source(&subpixel_source),
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let blend_mode = match alpha_mode {
|
||||
wgpu::CompositeAlphaMode::PreMultiplied => {
|
||||
wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING
|
||||
}
|
||||
_ => wgpu::BlendState::ALPHA_BLENDING,
|
||||
};
|
||||
|
||||
let color_target = wgpu::ColorTargetState {
|
||||
format: surface_format,
|
||||
blend: Some(blend_mode),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
};
|
||||
|
||||
let create_pipeline = |name: &str,
|
||||
vs_entry: &str,
|
||||
fs_entry: &str,
|
||||
globals_layout: &wgpu::BindGroupLayout,
|
||||
data_layout: &wgpu::BindGroupLayout,
|
||||
texture_layout: Option<&wgpu::BindGroupLayout>,
|
||||
topology: wgpu::PrimitiveTopology,
|
||||
color_targets: &[Option<wgpu::ColorTargetState>],
|
||||
sample_count: u32,
|
||||
module: &wgpu::ShaderModule| {
|
||||
let mut bind_group_layouts = vec![Some(globals_layout), Some(data_layout)];
|
||||
bind_group_layouts.extend(texture_layout.map(Some));
|
||||
bind_group_layouts.resize(3, None);
|
||||
bind_group_layouts.push(Some(clip_layout));
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some(&format!("{name}_layout")),
|
||||
bind_group_layouts: &bind_group_layouts,
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(name),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module,
|
||||
entry_point: Some(vs_entry),
|
||||
buffers: &[],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module,
|
||||
entry_point: Some(fs_entry),
|
||||
targets: color_targets,
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology,
|
||||
strip_index_format: None,
|
||||
front_face: wgpu::FrontFace::Ccw,
|
||||
cull_mode: None,
|
||||
polygon_mode: wgpu::PolygonMode::Fill,
|
||||
unclipped_depth: false,
|
||||
conservative: false,
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState {
|
||||
count: sample_count,
|
||||
mask: !0,
|
||||
alpha_to_coverage_enabled: false,
|
||||
},
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
|
||||
let quads = create_pipeline(
|
||||
"quads",
|
||||
"vs_quad",
|
||||
"fs_quad",
|
||||
&layouts.globals,
|
||||
&layouts.instances,
|
||||
None,
|
||||
wgpu::PrimitiveTopology::TriangleStrip,
|
||||
&[Some(color_target.clone())],
|
||||
1,
|
||||
&shader_module,
|
||||
);
|
||||
|
||||
let shadows = create_pipeline(
|
||||
"shadows",
|
||||
"vs_shadow",
|
||||
"fs_shadow",
|
||||
&layouts.globals,
|
||||
&layouts.instances,
|
||||
None,
|
||||
wgpu::PrimitiveTopology::TriangleStrip,
|
||||
&[Some(color_target.clone())],
|
||||
1,
|
||||
&shader_module,
|
||||
);
|
||||
|
||||
// The path pool has the layout of the instance data.
|
||||
let path_rasterization = create_pipeline(
|
||||
"path_rasterization",
|
||||
"vs_path_rasterization",
|
||||
"fs_path_rasterization",
|
||||
&layouts.globals,
|
||||
&layouts.instances,
|
||||
Some(&layouts.instances),
|
||||
wgpu::PrimitiveTopology::TriangleList,
|
||||
&[Some(wgpu::ColorTargetState {
|
||||
format: surface_format,
|
||||
blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
path_sample_count,
|
||||
&shader_module,
|
||||
);
|
||||
|
||||
let paths = create_pipeline(
|
||||
"paths",
|
||||
"vs_path",
|
||||
"fs_path",
|
||||
&layouts.globals,
|
||||
&layouts.instances,
|
||||
Some(&layouts.texture),
|
||||
wgpu::PrimitiveTopology::TriangleStrip,
|
||||
&[Some(wgpu::ColorTargetState {
|
||||
format: surface_format,
|
||||
blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
1,
|
||||
&shader_module,
|
||||
);
|
||||
|
||||
let underlines = create_pipeline(
|
||||
"underlines",
|
||||
"vs_underline",
|
||||
"fs_underline",
|
||||
&layouts.globals,
|
||||
&layouts.instances,
|
||||
None,
|
||||
wgpu::PrimitiveTopology::TriangleStrip,
|
||||
&[Some(color_target.clone())],
|
||||
1,
|
||||
&shader_module,
|
||||
);
|
||||
|
||||
let mono_sprites = create_pipeline(
|
||||
"mono_sprites",
|
||||
"vs_mono_sprite",
|
||||
"fs_mono_sprite",
|
||||
&layouts.globals,
|
||||
&layouts.instances,
|
||||
Some(&layouts.texture),
|
||||
wgpu::PrimitiveTopology::TriangleStrip,
|
||||
&[Some(color_target.clone())],
|
||||
1,
|
||||
&shader_module,
|
||||
);
|
||||
|
||||
let subpixel_sprites = if let Some(subpixel_module) = &subpixel_shader_module {
|
||||
let subpixel_blend = wgpu::BlendState {
|
||||
color: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::Src1,
|
||||
dst_factor: wgpu::BlendFactor::OneMinusSrc1,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
alpha: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::One,
|
||||
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
};
|
||||
|
||||
Some(create_pipeline(
|
||||
"subpixel_sprites",
|
||||
"vs_subpixel_sprite",
|
||||
"fs_subpixel_sprite",
|
||||
&layouts.globals,
|
||||
&layouts.instances,
|
||||
Some(&layouts.texture),
|
||||
wgpu::PrimitiveTopology::TriangleStrip,
|
||||
&[Some(wgpu::ColorTargetState {
|
||||
format: surface_format,
|
||||
blend: Some(subpixel_blend),
|
||||
write_mask: wgpu::ColorWrites::COLOR,
|
||||
})],
|
||||
1,
|
||||
subpixel_module,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let poly_sprites = create_pipeline(
|
||||
"poly_sprites",
|
||||
"vs_poly_sprite",
|
||||
"fs_poly_sprite",
|
||||
&layouts.globals,
|
||||
&layouts.instances,
|
||||
Some(&layouts.texture),
|
||||
wgpu::PrimitiveTopology::TriangleStrip,
|
||||
&[Some(color_target)],
|
||||
1,
|
||||
&shader_module,
|
||||
);
|
||||
|
||||
WgpuPipelines {
|
||||
quads,
|
||||
shadows,
|
||||
path_rasterization,
|
||||
paths,
|
||||
underlines,
|
||||
mono_sprites,
|
||||
subpixel_sprites,
|
||||
poly_sprites,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
use super::WgpuHeadlessRenderer;
|
||||
use crate::{
|
||||
Bounds, ContentMask, DevicePixels, PlatformHeadlessRenderer, Quad, ScaledPixels, Scene,
|
||||
WgpuContext, point, rgb, size,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use wgpu::TextureFormat;
|
||||
|
||||
fn render(renderer: &mut WgpuHeadlessRenderer, color: u32, edge: i32) -> Vec<u8> {
|
||||
let bounds = Bounds::new(
|
||||
point(ScaledPixels(0.), ScaledPixels(0.)),
|
||||
size(ScaledPixels(edge as f32), ScaledPixels(edge as f32)),
|
||||
);
|
||||
let mask = ContentMask { bounds };
|
||||
let mut scene = Scene::default();
|
||||
scene.insert_primitive(Quad {
|
||||
bounds,
|
||||
background: rgb(color).into(),
|
||||
content_mask: mask,
|
||||
local_content_mask: mask,
|
||||
..Quad::default()
|
||||
});
|
||||
scene.finish();
|
||||
renderer
|
||||
.render_scene_to_image(&scene, size(DevicePixels(edge), DevicePixels(edge)))
|
||||
.unwrap()
|
||||
.into_raw()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_pipeline_cache_isolates_windows_formats_and_devices() -> anyhow::Result<()> {
|
||||
let (context, format) = WgpuContext::create_headless()?;
|
||||
let old_device = Arc::downgrade(&context.device);
|
||||
let old_cache = Arc::downgrade(&context.headless_pipelines);
|
||||
let mut first = WgpuHeadlessRenderer::with_context(context.clone(), format, false);
|
||||
assert_eq!(context.headless_pipelines.lock().len(), 1);
|
||||
let mut second = WgpuHeadlessRenderer::with_context(context.clone(), format, false);
|
||||
assert_eq!(context.headless_pipelines.lock().len(), 1);
|
||||
let first_gpu = &first.core.resources;
|
||||
let second_gpu = &second.core.resources;
|
||||
assert_eq!(first_gpu.pipelines.quads, second_gpu.pipelines.quads);
|
||||
assert_eq!(
|
||||
first_gpu.bind_group_layouts.globals,
|
||||
second_gpu.bind_group_layouts.globals
|
||||
);
|
||||
assert_ne!(first_gpu.globals_buffer, second_gpu.globals_buffer);
|
||||
assert_ne!(first_gpu.globals_bind_group, second_gpu.globals_bind_group);
|
||||
assert!(!Arc::ptr_eq(&first.core.atlas, &second.core.atlas));
|
||||
|
||||
let mut textured = WgpuHeadlessRenderer::with_context(context.clone(), format, true);
|
||||
assert_eq!(context.headless_pipelines.lock().len(), 2);
|
||||
assert_ne!(
|
||||
first.core.resources.pipelines.quads,
|
||||
textured.core.resources.pipelines.quads
|
||||
);
|
||||
let mut srgb =
|
||||
WgpuHeadlessRenderer::with_context(context.clone(), format.add_srgb_suffix(), false);
|
||||
assert_eq!(context.headless_pipelines.lock().len(), 3);
|
||||
assert_ne!(
|
||||
first.core.resources.pipelines.quads,
|
||||
srgb.core.resources.pipelines.quads
|
||||
);
|
||||
|
||||
let scenes = [(0xd04020, 17), (0x1060e0, 23)];
|
||||
let reference: Vec<_> = scenes
|
||||
.into_iter()
|
||||
.map(|(color, edge)| {
|
||||
let (fresh, fresh_format) = WgpuContext::create_headless()?;
|
||||
assert_eq!(fresh.headless_pipelines.lock().len(), 0);
|
||||
let mut renderer = WgpuHeadlessRenderer::with_context(fresh, fresh_format, false);
|
||||
Ok(render(&mut renderer, color, edge))
|
||||
})
|
||||
.collect::<anyhow::Result<_>>()?;
|
||||
assert_eq!(&reference[0][..4], &[208, 64, 32, 255]);
|
||||
assert_eq!(&reference[1][..4], &[16, 96, 224, 255]);
|
||||
for _ in 0..48 {
|
||||
assert_eq!(render(&mut first, scenes[0].0, scenes[0].1), reference[0]);
|
||||
assert_eq!(render(&mut second, scenes[1].0, scenes[1].1), reference[1]);
|
||||
}
|
||||
assert_eq!(
|
||||
render(&mut textured, scenes[0].0, scenes[0].1),
|
||||
reference[0]
|
||||
);
|
||||
assert_ne!(
|
||||
&render(&mut srgb, scenes[0].0, scenes[0].1)[..4],
|
||||
&reference[0][..4]
|
||||
);
|
||||
assert_ne!(
|
||||
first.render_target.as_ref().unwrap().texture,
|
||||
second.render_target.as_ref().unwrap().texture,
|
||||
);
|
||||
assert!(matches!(
|
||||
format,
|
||||
TextureFormat::Rgba8Unorm | TextureFormat::Bgra8Unorm
|
||||
));
|
||||
|
||||
drop((first, second, textured, srgb, context));
|
||||
assert!(old_device.upgrade().is_none());
|
||||
assert!(old_cache.upgrade().is_none());
|
||||
let (fresh, fresh_format) = WgpuContext::create_headless()?;
|
||||
assert!(fresh.headless_pipelines.lock().is_empty());
|
||||
let mut renderer = WgpuHeadlessRenderer::with_context(fresh, fresh_format, false);
|
||||
assert_eq!(
|
||||
render(&mut renderer, scenes[0].0, scenes[0].1),
|
||||
reference[0]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user