Skip to main content

cadkit_gpu/
lib.rs

1//! `wgpu` renderers for [`cadkit_scene`].
2//!
3//! - [`PlanRenderer`] draws the chunks of a [`cadkit_scene::PlanFrame`]: analytic lines and
4//!   arcs with mitred polyline corners and one-pixel antialiasing, blended premultiplied.
5//!   Chunk buffers are uploaded once per content generation; moving the camera only rewrites
6//!   32 bytes per chunk.
7//! - [`MeshRenderer`] draws a [`cadkit_scene::MeshScene`] with an [`OrbitCamera`], depth
8//!   testing and flat lighting, with incremental mesh and camera updates.
9//! - [`render_texture`], [`render_offscreen`] and [`RenderTargetCache`] render meshes into
10//!   textures or read them back as RGBA.
11//!
12//! The renderers take a [`wgpu::Device`], [`wgpu::Queue`], a target format and a
13//! [`wgpu::RenderPass`]; they do not open windows or depend on a UI toolkit. The `wgpu`
14//! version is part of this crate's API and is re-exported as [`wgpu`].
15//!
16//! GPU validation and out-of-memory errors are captured with error scopes and returned as
17//! [`GpuError`]s.
18
19pub use wgpu;
20
21mod block;
22mod mesh;
23mod plan;
24mod target;
25
26pub use block::block_on;
27pub use mesh::{MeshRenderer, OrbitCamera, PreparedMeshes, mesh_budget};
28pub use plan::{PlanRenderer, PlanTarget};
29pub use target::{
30    AdapterSummary, OffscreenImage, RenderTargetCache, RenderTargetStats, RenderTextureRecycler,
31    RenderedTexture, render_offscreen, render_offscreen_with, render_texture,
32    render_texture_cached,
33};
34
35/// Why a GPU operation failed.
36#[derive(Debug, Clone, PartialEq, thiserror::Error)]
37#[non_exhaustive]
38pub enum GpuError {
39    /// The camera parameters or the aspect ratio are not finite or describe no frustum.
40    #[error("invalid camera: distance, angles and aspect ratio must describe a frustum")]
41    InvalidCamera,
42    /// The camera distance or target offset is outside the representable range.
43    #[error("camera outside the representable range")]
44    CameraRange,
45    /// A scene the caller marked incomplete was given to a path that needs a complete one.
46    #[error("the scene is incomplete")]
47    IncompleteScene,
48    /// The scene has no triangles.
49    #[error("the scene has no triangles")]
50    EmptyScene,
51    /// A mesh is not opaque; translucent surfaces are not supported.
52    #[error("mesh {0:?} is not opaque")]
53    Translucent(cadkit_scene::ObjectId),
54    /// A triangle refers to a vertex the mesh does not have.
55    #[error("mesh {0:?} has a triangle index out of range")]
56    InvalidTriangle(cadkit_scene::ObjectId),
57    /// A vertex is outside the f32 precision budget relative to the scene origin.
58    #[error("mesh {mesh:?}: {source}")]
59    Precision {
60        /// The mesh.
61        mesh: cadkit_scene::ObjectId,
62        /// The precision failure.
63        source: cadkit_scene::SceneError,
64    },
65    /// The scene exceeds a device buffer or index limit.
66    #[error("the scene exceeds the device buffer limit")]
67    BufferLimit,
68    /// The requested texture size is zero or exceeds the device limit.
69    #[error("texture size {0}x{1} is zero or exceeds the device limit")]
70    TextureSize(u32, u32),
71    /// No suitable adapter.
72    #[error("no GPU adapter: {0}")]
73    AdapterUnavailable(String),
74    /// The adapter refused to create a device.
75    #[error("no GPU device: {0}")]
76    DeviceUnavailable(String),
77    /// A captured validation error.
78    #[error("GPU validation error: {0}")]
79    Validation(String),
80    /// A captured out-of-memory error.
81    #[error("GPU out of memory: {0}")]
82    OutOfMemory(String),
83    /// An uncaptured error or a lost device reported by the device callbacks.
84    #[error("GPU device error: {0}")]
85    Device(String),
86    /// Waiting for submitted work failed.
87    #[error("GPU poll failed: {0}")]
88    Poll(String),
89    /// Reading a texture back failed.
90    #[error("GPU readback failed: {0}")]
91    Readback(String),
92}
93
94/// Pops a validation and an out-of-memory scope pushed by [`scopes`], memory first.
95async fn check(
96    validation: wgpu::ErrorScopeGuard,
97    allocation: wgpu::ErrorScopeGuard,
98) -> Result<(), GpuError> {
99    if let Some(error) = allocation.pop().await {
100        return Err(GpuError::OutOfMemory(error.to_string()));
101    }
102    if let Some(error) = validation.pop().await {
103        return Err(GpuError::Validation(error.to_string()));
104    }
105    Ok(())
106}
107
108/// Pushes a validation and an out-of-memory error scope.
109fn scopes(device: &wgpu::Device) -> (wgpu::ErrorScopeGuard, wgpu::ErrorScopeGuard) {
110    let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
111    let allocation = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
112    (validation, allocation)
113}
114
115/// sRGB byte to linear intensity.
116fn linear(byte: u8) -> f64 {
117    let value = f64::from(byte) / 255.;
118    if value <= 0.04045 {
119        value / 12.92
120    } else {
121        ((value + 0.055) / 1.055).powf(2.4)
122    }
123}