Skip to main content

isomesh_gpu/
error.rs

1//! What can go wrong, reported rather than panicked.
2
3use core::fmt;
4
5/// The result of a fallible `isomesh-gpu` operation.
6pub type Result<T> = core::result::Result<T, Error>;
7
8/// Everything this crate can fail at.
9///
10/// One variant per genuinely distinct cause. There is deliberately no
11/// catch-all `Other(String)`: a caller that cannot tell "no adapter" from
12/// "wrong buffer length" cannot react to either, and a variant that carries a
13/// message is a way of not deciding what the error is.
14#[derive(Debug, Clone, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum Error {
17    /// A grid axis had fewer than two samples, so it contains no cells.
18    DegenerateGrid {
19        /// The offending sample counts.
20        samples: [u32; 3],
21    },
22    /// The cell size was not a finite positive number.
23    InvalidCellSize,
24    /// The grid origin was not finite.
25    InvalidOrigin,
26    /// The grid describes more samples than a `u64` byte count can address.
27    GridTooLarge {
28        /// The offending sample counts.
29        samples: [u32; 3],
30    },
31    /// An upload's slice length disagreed with the grid it is being written to.
32    SampleCountMismatch {
33        /// What the grid says it holds.
34        expected: u64,
35        /// What the caller passed.
36        got: u64,
37    },
38    /// No adapter matched the request. There is no software fallback here on
39    /// purpose: a caller told "GPU extraction is running" while it is on a
40    /// CPU reference driver has been misinformed about the only thing that
41    /// matters.
42    NoAdapter,
43    /// The adapter refused to create a device with the requested limits.
44    DeviceUnavailable,
45    /// Mapping a buffer for read-back failed.
46    MapFailed,
47    /// Timestamp queries were asked for and are not usable on this device.
48    ///
49    /// Ticket: R-069 (P-71). Raised when the device was not created with
50    /// [`wgpu::Features::TIMESTAMP_QUERY`], when the queue reports a timestamp
51    /// period of zero — a driver that advertises the feature and does not
52    /// implement it — or when a resolved pair ends before it begins.
53    ///
54    /// **It refuses rather than degrading, on purpose.** Falling back to
55    /// `Instant::now()` under a GPU-side column name would report a number that
56    /// was named and not measured, which is the failure the experiment harness's
57    /// missing-column panic exists to prevent, arriving by a different door.
58    TimestampsUnsupported,
59    /// The adapter does not advertise a feature the caller asked for.
60    ///
61    /// R-068. `Gpu::open` previously returned [`Self::TimestampsUnsupported`]
62    /// for **any** missing feature, which was correct while timestamps were its
63    /// only caller and became a lie the moment `with_subgroups` existed: a
64    /// device without `SUBGROUP` would have reported that timestamps were
65    /// unavailable. Carrying the missing set means the error names what is
66    /// actually absent, and adding a third capability cannot reintroduce the
67    /// bug.
68    FeaturesUnsupported {
69        /// The features the adapter lacks.
70        missing: wgpu::Features,
71    },
72    /// The device disconnected or a submission never completed.
73    DeviceLost,
74    /// A shader module was included, or composed, but never registered.
75    ShaderModuleMissing {
76        /// The name that was asked for.
77        name: String,
78    },
79    /// A shader module includes itself, through some chain.
80    ShaderCircularInclude {
81        /// The module the cycle closes on.
82        name: String,
83    },
84    /// A preprocessor directive was malformed or unbalanced.
85    ShaderDirective {
86        /// Module the directive is in.
87        module: String,
88        /// One-based line number within that module.
89        line: usize,
90    },
91    /// The device cannot run mesh shaders.
92    ///
93    /// Returned rather than substituting a vertex-buffer pipeline: a caller
94    /// told "drawing" while a different pipeline ran has been misinformed
95    /// about the one thing they asked for.
96    MeshShadersUnavailable,
97    /// A read-back range was not a whole number of elements.
98    UnalignedReadback {
99        /// Bytes asked for.
100        bytes: u64,
101        /// Bytes per element.
102        stride: u64,
103    },
104    /// A scan was asked for more elements than one dispatch can cover.
105    ///
106    /// Level 0 dispatches one workgroup per `PrefixScan::BLOCK` elements, and
107    /// `max_compute_workgroups_per_dimension` caps how many that can be.
108    ScanTooLong {
109        /// Elements the caller asked to scan.
110        elements: u32,
111        /// The most this device will scan in one call.
112        max: u32,
113    },
114    /// [`crate::DeferredGeometry`] was asked to hold one more read-back than it
115    /// has room for.
116    ///
117    /// R-071 (P-71 C3). Its own variant rather than [`Self::DeviceLost`] or a
118    /// silent drop, because it is the one error here that is **not** a failure:
119    /// it is the queue telling a frame-budget scheduler that this frame's
120    /// submissions have caught up with last frame's collections, which is the
121    /// signal a caller uses to stop submitting. A dropped read-back would be a
122    /// chunk of geometry that was extracted, paid for and never delivered, and
123    /// nothing downstream could tell that from a chunk with no surface in it.
124    DeferredQueueFull {
125        /// In-flight read-backs the queue was built to hold.
126        capacity: usize,
127    },
128}
129
130impl fmt::Display for Error {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        match self {
133            Self::DegenerateGrid { samples } => write!(
134                f,
135                "every grid axis needs at least 2 samples to hold a cell, got {samples:?}"
136            ),
137            Self::InvalidCellSize => f.write_str("cell size must be finite and greater than zero"),
138            Self::InvalidOrigin => f.write_str("grid origin must be finite"),
139            Self::GridTooLarge { samples } => {
140                write!(f, "grid {samples:?} does not fit in an addressable buffer")
141            }
142            Self::SampleCountMismatch { expected, got } => {
143                write!(f, "grid holds {expected} samples, got {got}")
144            }
145            Self::NoAdapter => f.write_str("no GPU adapter matched the request"),
146            Self::DeviceUnavailable => f.write_str("the adapter would not create a device"),
147            Self::MapFailed => f.write_str("mapping a buffer for read-back failed"),
148            Self::TimestampsUnsupported => f.write_str(
149                "timestamp queries are not usable on this device: the feature was \
150                 not enabled, the timestamp period is zero, or a span ended before \
151                 it began",
152            ),
153            Self::FeaturesUnsupported { missing } => {
154                write!(f, "the adapter does not advertise {missing:?}")
155            }
156            Self::DeviceLost => f.write_str("the device was lost or a submission never completed"),
157            Self::ShaderModuleMissing { name } => {
158                write!(f, "no shader module registered as `{name}`")
159            }
160            Self::ShaderCircularInclude { name } => {
161                write!(f, "shader module `{name}` includes itself")
162            }
163            Self::ShaderDirective { module, line } => {
164                write!(f, "malformed or unbalanced directive at {module}:{line}")
165            }
166            Self::MeshShadersUnavailable => f.write_str(
167                "mesh shaders need EXPERIMENTAL_MESH_SHADER on a Vulkan device; \
168                 naga compiles WGSL mesh stages for SPIR-V only",
169            ),
170            Self::UnalignedReadback { bytes, stride } => write!(
171                f,
172                "read-back of {bytes} bytes is not a whole number of {stride}-byte elements"
173            ),
174            Self::ScanTooLong { elements, max } => write!(
175                f,
176                "cannot scan {elements} elements; this device dispatches at most {max}"
177            ),
178            Self::DeferredQueueFull { capacity } => {
179                write!(f, "the deferred read-back queue is full at {capacity}")
180            }
181        }
182    }
183}
184
185impl core::error::Error for Error {}