crcbl_hal/device.rs
1//! The two central traits: [`Instance`] and [`Device`].
2//!
3//! ```text
4//! Instance ──adapters()──▶ [AdapterInfo] (who each adapter is; no device opened)
5//! ├──adapter_caps(AdapterId)──▶ DeviceCaps (what one can do; probed once, on demand)
6//! │
7//! ├──create_surface(SurfaceTarget)──▶ SurfaceHandle
8//! └──request_device(DeviceDesc)─────▶ Box<dyn PendingDevice>
9//! │
10//! └──poll()──▶ Pending | Ready(Box<dyn Device>)
11//! │
12//! ├─ resources: buffers, images, views, samplers
13//! ├─ pipelines, layouts, bind groups
14//! ├─ swapchains: create / reconfigure / acquire / present
15//! ├─ command encoders ──▶ Box<dyn CommandEncoder>
16//! └─ submit / wait
17//! ```
18//!
19//! # Device creation is polled, not blocking
20//!
21//! Opening a device is [`Instance::request_device`] →
22//! [`PendingDevice::poll`], the same request/poll pair
23//! [`crate::readback`] already uses, and for the same reason: on WebGPU both
24//! `requestAdapter` and `requestDevice` resolve on a **later turn of the event
25//! loop**, and the browser main thread — where the rAF loop runs — cannot block
26//! waiting for one. A synchronous-only `create_device` was a trait method that
27//! returned [`HalError::Unsupported`] on the target
28//! the browser track most wants to ship to, which is the exact
29//! mistake [`crate::readback`] and [`crate::swapchain`] were shaped to avoid.
30//!
31//! | Step | Vulkan | WebGPU |
32//! | --- | --- | --- |
33//! | request | `vkCreateDevice`, which returns before this call does | call `requestDevice`, keep the promise |
34//! | poll | hand over the already-open device | has the promise resolved? |
35//! | ready | `Box<dyn Device>` | `Box<dyn Device>` around the resolved `GPUDevice` |
36//!
37//! Neither backend has to invent anything, and neither has to block. A backend
38//! whose creation really is synchronous — `crcbl-vk` — does the work in
39//! `request_device` and completes on its **first** poll; it does not fake
40//! latency. [`crate::null`] can be asked to simulate a slow one with
41//! [`Recorder::set_device_latency`](crate::null::Recorder::set_device_latency),
42//! which is what makes a caller's poll *loop* testable with no GPU.
43//!
44//! ## Two deliberate differences from `poll_readback`
45//!
46//! 1. **The payload rides in the variant.** [`poll_readback`](Device::poll_readback)
47//! writes into a caller-supplied `&mut [u8]` and returns a `Copy` state, which
48//! a `Box<dyn Device>` has no equivalent of; an
49//! `&mut Option<Box<dyn Device>>` out-parameter would be strictly worse than
50//! [`DeviceRequestState::Ready`] carrying it. The *discipline* — "call once
51//! per frame, `Pending` means try again, failure is an `Err` and not a third
52//! state" — is identical.
53//! 2. **`poll` takes `&mut self`.** A readback is polled through the shared
54//! `&self` device; a pending device is a single-owner, short-lived object, so
55//! the exclusive borrow is free and lets a backend hold a future without
56//! inventing interior mutability for it.
57//!
58//! ## `create_device` survives as a native-only convenience
59//!
60//! `Instance::create_device` is a **provided** method that requests and then
61//! polls to completion, so every existing native caller — `crcbl screenshot`,
62//! the golden-image tests, `crcbl-render`'s fixtures — is unchanged. It does not
63//! exist on `wasm32` at all: it is `#[cfg(not(target_arch = "wasm32"))]`, so a
64//! browser build that reaches for it fails to *compile* and is pointed at
65//! `request_device`, rather than compiling and returning
66//! [`HalError::Unsupported`] at run time. That is the one place this seam
67//! departs from [`crate::readback`]'s "there is no blocking wrapper" rule, and
68//! it is affordable precisely because the compiler enforces the rule where it
69//! matters.
70//!
71//! # Queues are handles, not a trait
72//!
73//! The seam's original design asked for "`Device` + `Queue`". A `Queue` here
74//! is a [`QueueHandle`] and submission is [`Device::submit`], rather than a
75//! third trait object. Queues carry no state a caller can usefully hold, and
76//! `Device::submit(queue, …)` keeps the number of trait objects in the engine at
77//! three. The plurality that matters — async compute and a dedicated transfer
78//! queue, which stage 2 said must be *modelled* even
79//! though the MVP uses one — is fully expressible: [`Device::queue`] returns a
80//! handle per [`QueueKind`], and [`QueueTransfer`](crate::QueueTransfer)
81//! already carries ownership transfers between them.
82//!
83//! # `&self`, not `&mut self`
84//!
85//! Every method takes `&self`, so a `Device` can be shared behind an `Arc`
86//! across threads (the traits are `Send + Sync`). Backends provide their own
87//! interior synchronisation, which they need regardless: `vkCreateBuffer` is
88//! thread-safe but the underlying suballocator is not, and P8's job system will
89//! upload from worker threads. A `&mut self` seam would have forced an
90//! engine-wide lock on the device just to create a buffer.
91//!
92//! Command *recording* is the exception, and it is expressed in the type: a
93//! [`CommandEncoder`] is [`HalThreadSafe`](crate::threading::HalThreadSafe)
94//! (Send + Sync); two threads cannot record into one because every recording
95//! method takes `&mut self`, which is how Vulkan's external-synchronisation
96//! rule for command buffers is discharged.
97//!
98//! # Destruction is explicit and immediate-looking
99//!
100//! `destroy_*` takes the handle by value and returns nothing. It means "this
101//! handle is dead now"; it does **not** promise the GPU is finished with the
102//! object. Deferring the real free until N frames later — the deletion queue
103//! from stage 2 §2.2 — is the backend's business.
104//! Destroying a resource the GPU is still using is a caller bug that the graph's
105//! lifetime tracking is responsible for preventing, exactly as it is in Vulkan.
106//!
107//! # Object lifetimes — implementation obligations on backends
108//!
109//! `Instance::create_device` returns `Box<dyn Device>`, which is `'static`, so
110//! the type system permits a `Device` to outlive the `Instance` that made it.
111//! In Vulkan that relationship is real and inverted: a `VkDevice` must not
112//! outlive its `VkInstance`, and a `VkSurfaceKHR` is instance-owned while the
113//! swapchain built from it is device-owned. Rather than leave the P1 backend
114//! author to guess, the seam states the rules here. **These are obligations on
115//! backends, not merely descriptions.**
116//!
117//! ## 1. A `Device` may outlive its `Instance`
118//!
119//! A backend **must** keep whatever instance-level state its device needs alive
120//! internally — in practice an `Arc` to the instance's inner data, so dropping
121//! the public `Instance` object does not destroy the underlying one while a
122//! device still exists.
123//!
124//! The two alternatives were both worse:
125//!
126//! * `Box<dyn Device + 'a>` borrowed from the instance would express the truth,
127//! but any struct holding both an instance and a device becomes
128//! self-referential. `crcbl-render`'s renderer is exactly that struct, so the
129//! tax would be paid on every line of the layer this seam exists to serve.
130//! * An unenforced "you must not drop the instance first" rule is the worst of
131//! both: no compile-time help *and* no runtime detection, with
132//! use-after-free as the failure mode.
133//!
134//! Keeping the instance alive internally costs one `Arc` per backend and makes
135//! the `'static` that the type system already promises actually true.
136//!
137//! ## 2. Surfaces are instance-scoped; swapchains are device-scoped
138//!
139//! The legal teardown order is:
140//!
141//! ```text
142//! 1. Device::destroy_swapchain(swapchain)
143//! 2. Instance::destroy_surface(surface)
144//! 3. drop the Device
145//! 4. drop the Instance (and only now may the window close)
146//! ```
147//!
148//! Steps 3 and 4 may be reordered, per rule 1. Steps 1 and 2 may not, and
149//! neither may be skipped while the window is still open — the
150//! [`create_surface`](Instance::create_surface) safety contract requires the
151//! native handles to outlive the surface.
152//!
153//! A caller that gets it wrong must get a **clean error, never undefined
154//! behaviour**. Concretely, a backend must:
155//!
156//! * Invalidate the handle immediately on `destroy_surface`, so a later use
157//! fails the generational lookup and returns [`HalError::InvalidHandle`].
158//! * **Defer** destroying the underlying driver object until the last swapchain
159//! configured on it is destroyed. Calling `vkDestroySurfaceKHR` with a live
160//! swapchain is undefined behaviour in the driver, so "pass it straight down"
161//! is not an option; the deletion queue that already exists for retiring
162//! resources N frames later is the same machinery.
163//!
164//! In short: the handle dies when the caller says so, the object dies when it is
165//! safe. [`crate::null`] enforces the detectable half — a swapchain created from
166//! a destroyed surface, or a present on a destroyed swapchain, is an error and
167//! is covered by tests.
168//!
169//! ## 3. Handles never cross instances or devices
170//!
171//! A [`SurfaceHandle`] from instance A passed to a device created from instance
172//! B is a caller bug, and so is a buffer from device X used on device Y. The
173//! required behaviour is [`HalError::ForeignObject`] — detected, not undefined.
174//!
175//! This one needs a mechanism, because a [`Handle`] cannot carry it: its 32-bit
176//! index and 32-bit generation are fully spoken for, and two instances' pools
177//! genuinely do issue identical bits. Backends **must** therefore stamp an
178//! owner identity into their own side table — one `u64` per tracked object,
179//! compared on every lookup. That is one integer compare on a path that is
180//! already doing a table lookup.
181//!
182//! [`crate::null`] implements exactly this: every object records the id of the
183//! instance or device that created it, and every lookup checks it. Surfaces are
184//! checked against the *instance* id (so any device from that instance may use
185//! them) and everything else against the *device* id.
186
187use std::time::Duration;
188
189use crate::{
190 AcquiredFrame, AdapterId, AdapterInfo, BackendKind, BindGroupDesc, BindGroupHandle,
191 BindGroupLayoutDesc, BindGroupLayoutHandle, BufferDesc, BufferHandle, CommandBufferHandle,
192 CommandEncoder, CommandEncoderDesc, ComputePipelineDesc, ComputePipelineHandle, DeviceCaps,
193 DisplayTiming, Features, GraphicsPipelineDesc, GraphicsPipelineHandle, HalError, ImageDesc,
194 ImageHandle, ImageViewDesc, ImageViewHandle, PipelineLayoutDesc, PipelineLayoutHandle,
195 PresentInfo, QuerySetDesc, QuerySetHandle, ReadbackDesc, ReadbackHandle, ReadbackState,
196 SamplerDesc, SamplerHandle, SemaphoreDesc, SemaphoreHandle, ShaderModuleDesc,
197 ShaderModuleHandle, SubmitInfo, SurfaceCaps, SurfaceError, SurfaceHandle, SwapchainDesc,
198 SwapchainHandle,
199};
200use crcbl_core::{Handle, SurfaceTarget};
201
202/// Marker type for queue handles. Uninhabited.
203#[derive(Debug)]
204pub enum Queue {}
205
206/// A queue on a device.
207pub type QueueHandle = Handle<Queue>;
208
209/// Which class of work a queue accepts.
210///
211/// # Decision: `QueueKind`, not `QueueFamily`
212///
213/// "Queue family" is a Vulkan noun and nothing else's: Metal has one
214/// `MTLCommandQueue` type and no families at all, and DX12 has *command list
215/// types* (`D3D12_COMMAND_LIST_TYPE_DIRECT` / `_COMPUTE` / `_COPY`), which is
216/// exactly this enum's three variants under a different name. Since the HAL
217/// rule in `docs/notes/backends.md` is "no obviously vk-only concept in the
218/// trait names", the noun that maps onto all three APIs is the
219/// one the seam uses, and `Kind` is already this crate's word for it
220/// ([`SemaphoreKind`](crate::SemaphoreKind), [`QueryKind`](crate::QueryKind),
221/// [`BindingKind`](crate::BindingKind), [`BackendKind`]).
222///
223/// A Vulkan backend still maps each variant to a real queue family index; that
224/// is a backend's business and not the seam's vocabulary.
225#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
226pub enum QueueKind {
227 /// Graphics, compute and transfer. Always present; the MVP uses only this
228 /// one.
229 Graphics,
230 /// Compute and transfer, independent of graphics. Present only with
231 /// [`Features::ASYNC_COMPUTE_QUEUE`].
232 Compute,
233 /// Transfer only. Present only with [`Features::TRANSFER_QUEUE`].
234 Transfer,
235}
236
237/// Parameters for device creation.
238#[derive(Clone, Copy, Debug, PartialEq, Eq)]
239pub struct DeviceDesc<'a> {
240 /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
241 pub label: Option<&'a str>,
242 /// Adapter to open, from [`Instance::adapters`].
243 pub adapter: AdapterId,
244 /// Features the caller cannot run without. Creation fails with
245 /// [`HalError::UnsupportedFeatures`] naming the exact gap if the adapter
246 /// lacks any of them.
247 ///
248 /// Keep this to what the caller genuinely cannot render without. Per topic
249 /// 39 a missing feature degrades by default, and naming one here is how a
250 /// caller opts out of that: a game whose whole look is ray traced puts
251 /// [`Features::RAY_QUERY`] here and gets a named failure rather than a
252 /// picture that is quietly a different game.
253 pub required_features: Features,
254 /// Features to enable if available. Absent ones are simply not enabled;
255 /// check [`Device::caps`] afterwards to find out.
256 pub optional_features: Features,
257 /// A surface the device must be able to present to.
258 ///
259 /// Vulkan needs this at device-creation time to choose a present-capable
260 /// queue family, and WebGPU's `requestAdapter` takes a `compatibleSurface`
261 /// for the same reason. `None` for a headless device.
262 pub compatible_surface: Option<SurfaceHandle>,
263}
264
265impl DeviceDesc<'_> {
266 /// A headless device on `adapter`, asking for as little as possible.
267 ///
268 /// The shape a headless render test or `crcbl screenshot` uses. It requires
269 /// only compute and a timeline semaphore — the two nothing in the engine
270 /// can work without, since every pass culls in compute and every frame is
271 /// paced on a monotonic counter — and asks for
272 /// [`Features::GPU_DRIVEN`] on top as *optional*, so the device opens on
273 /// whatever the adapter has and the selectors decide what to record. An
274 /// earlier version required the whole bundle and refused a device over one
275 /// absent flag while it had the rest; topic 39 exists to replace that.
276 #[must_use]
277 pub const fn for_adapter(adapter: AdapterId) -> Self {
278 Self {
279 label: None,
280 adapter,
281 required_features: Features::COMPUTE.union(Features::TIMELINE_SEMAPHORE),
282 optional_features: Features::GPU_DRIVEN,
283 compatible_surface: None,
284 }
285 }
286
287 /// The features a device opened from this request on an adapter with
288 /// `adapter` has: what the adapter has of what was asked for, plus what
289 /// those cannot work without.
290 ///
291 /// **What [`Device::caps`] reports, on every backend that uses it.** A
292 /// feature nobody asked for is not granted even where the adapter has it,
293 /// which is what lets a caller decline one: a renderer opened without
294 /// [`Features::TASK_SHADER`] must not find the task stage on and take it.
295 /// On Vulkan the device could not use it anyway, its extension never
296 /// enabled; on D3D12, which enables nothing, this is the only place the
297 /// request is honoured.
298 ///
299 /// The required features are in the answer even if the adapter lacks them,
300 /// because opening refuses that case first
301 /// ([`HalError::UnsupportedFeatures`]).
302 ///
303 /// # The dependencies
304 ///
305 /// No adapter reports a ray capability without the acceleration structure
306 /// it traverses, nor the task stage without the mesh stage it feeds, so
307 /// every flag added here is one the adapter has. What loses them is the
308 /// intersection with the request: ask for [`Features::RAY_QUERY`] and not
309 /// [`Features::ACCELERATION_STRUCTURE`] and the set carries a dependency it
310 /// cannot stand on. A device reporting `RAY_QUERY` and not
311 /// `ACCELERATION_STRUCTURE` would describe one that cannot exist, and on
312 /// Vulkan enabling `VK_KHR_ray_query` without `VK_KHR_acceleration_structure`
313 /// is invalid usage.
314 #[must_use]
315 pub fn granted(&self, adapter: Features) -> Features {
316 let mut granted = adapter
317 .intersection(self.required_features.union(self.optional_features))
318 .union(self.required_features);
319 if granted.contains(Features::TASK_SHADER) {
320 granted |= Features::MESH_SHADER;
321 }
322 if granted.intersects(Features::RAY_QUERY | Features::RAY_TRACING_PIPELINE) {
323 granted |= Features::ACCELERATION_STRUCTURE;
324 }
325 granted
326 }
327}
328
329/// A backend's entry point: enumerates adapters and opens devices and surfaces.
330///
331/// One instance exists per process per backend. More than one backend may be
332/// instantiated in the same process — that is the whole point of the `dyn`
333/// decision in the crate docs.
334pub trait Instance: core::fmt::Debug + crate::threading::HalThreadSafe {
335 /// Which backend this is. For logs and bug reports — never for behaviour.
336 fn backend(&self) -> BackendKind;
337
338 /// Every adapter this backend can see: who each one is, not what it can
339 /// do.
340 ///
341 /// **Opens no device.** Its capabilities are
342 /// [`adapter_caps`](Instance::adapter_caps)'s to answer, one adapter at a
343 /// time, because D3D12 has no capability query short of creating a driver
344 /// device. Selection ranks this list, then probes in that order and stops
345 /// at the first adapter that serves.
346 ///
347 /// An adapter here is not yet known to open: one the driver lists and
348 /// will not open (a display-only adapter, say) is in the list and fails
349 /// [`adapter_caps`](Instance::adapter_caps).
350 fn adapters(&self) -> Vec<AdapterInfo>;
351
352 /// What `adapter` can do, asked of the driver the first time and
353 /// remembered.
354 ///
355 /// The cost is the backend's: Vulkan, Metal and WebGPU read it off the
356 /// enumeration they already did, and D3D12 creates a device on the adapter
357 /// to ask — the device a following
358 /// [`request_device`](Instance::request_device) on that adapter is then
359 /// handed, so the probe is not paid twice.
360 ///
361 /// # Errors
362 ///
363 /// [`HalError::NoSuchAdapter`] for an id [`adapters`](Instance::adapters)
364 /// did not list, or [`HalError::Backend`] when the driver will not open
365 /// the adapter at all — the answer that sends selection on to the next
366 /// one.
367 fn adapter_caps(&self, adapter: AdapterId) -> Result<DeviceCaps, HalError>;
368
369 /// Creates a presentation surface from a shell's native window handles.
370 ///
371 /// # Safety
372 ///
373 /// The caller must guarantee that:
374 ///
375 /// 1. Every pointer and id in `target` names a **live** platform object of
376 /// exactly the kind the variant says (a `wl_surface*` really is a
377 /// `wl_surface*`, and so on). Nothing in `crcbl-core` validates this;
378 /// only the shell that created the window knows.
379 /// 2. Those objects **outlive** the returned [`SurfaceHandle`] and every
380 /// swapchain configured on it. Destroying the window before calling
381 /// [`Device::destroy_swapchain`] and [`Instance::destroy_surface`] is
382 /// use-after-free inside the driver.
383 /// 3. On platforms with thread-affine window handles (Win32, AppKit), this
384 /// is called from the thread that owns the window.
385 ///
386 /// The obligation lives here rather than at `SurfaceTarget` construction
387 /// because this is the only place the handles are dereferenced; see
388 /// [`crcbl_core::surface`] for the full argument.
389 ///
390 /// # This `unsafe` no longer lands in application code
391 ///
392 /// P0.7 drove the first shell→HAL join (`apps/sandbox`) and found the
393 /// ergonomic cost: obligation 2 above — "the window outlives the surface" —
394 /// can only be discharged by code holding *both* the shell and the device,
395 /// which was every game's own startup path, so every sample carried an
396 /// `unsafe` block in a crate that otherwise contained none.
397 ///
398 /// A safe wrapper *above* the seam is what the obligation permits, and it
399 /// was built: `crcbl::engine::GpuContext` holds the shell's window and the
400 /// device together and calls this from one place. No crate under `apps/`
401 /// contains an `unsafe` block now. The seam did not move for it.
402 ///
403 /// What still hand-rolls the join is `crcbl new`'s generated `main.rs` —
404 /// see `docs/backlog.md`.
405 ///
406 /// # Errors
407 ///
408 /// [`HalError::Unsupported`] if the backend has no support for that
409 /// platform, or [`HalError::Backend`] if the window system refused.
410 unsafe fn create_surface(&self, target: &SurfaceTarget) -> Result<SurfaceHandle, HalError>;
411
412 /// Invalidates `surface`'s handle. **A swapchain already on it goes on
413 /// working.**
414 ///
415 /// The two halves of a surface's lifetime come apart here, deliberately.
416 /// The handle is stale from this call on, so a later
417 /// [`surface_caps`](Instance::surface_caps) with it fails
418 /// [`HalError::InvalidHandle`]. The platform object underneath — a
419 /// `VkSurfaceKHR`, a `CAMetalLayer`, a canvas context — lives until the
420 /// last swapchain configured on it is destroyed. **The caller owes no
421 /// teardown order**: either call may come first.
422 ///
423 /// That is not a courtesy the backends happen to extend, it is what each
424 /// one is built to do. `crcbl-vk` keeps a per-surface swapchain count and a
425 /// zombie list so `vkDestroySurfaceKHR` can be deferred; `crcbl-mtl` lets
426 /// the last swapchain's clone of the layer release it; `crcbl-dx12` has
427 /// nothing to defer, because a swapchain holds its own `HWND` and never
428 /// consults the surface table again; the WebGPU replayer drops its
429 /// reference to the context without unconfiguring the canvas.
430 ///
431 /// What does still bind the caller is obligation 2 on
432 /// [`create_surface`](Instance::create_surface): the *window* must outlive
433 /// both objects. Destroying it early is a use-after-free inside the driver
434 /// whichever order these two calls come in.
435 fn destroy_surface(&self, surface: SurfaceHandle);
436
437 /// What `surface` supports on `adapter`.
438 ///
439 /// # This is also how adapter selection works
440 ///
441 /// [`adapters`](Instance::adapters) enumerates without reference to any
442 /// surface, so **this call is the only way to find out whether a given
443 /// adapter can present to a given window** — and the answer is routinely
444 /// "no". A discrete GPU under an X server with no DRI3 cannot present to it
445 /// while the software rasteriser beside it can; the same is true of the
446 /// second GPU in a hybrid laptop. P1.1 hit exactly that, and taking
447 /// `adapters()[0]` is therefore not a shortcut but a bug that only shows up
448 /// on someone else's machine.
449 ///
450 /// The contract, in both directions:
451 ///
452 /// * **Backends** must report an adapter that cannot present to this
453 /// surface as [`HalError::Unsupported`]. Returning empty
454 /// [`formats`](SurfaceCaps::formats) is **not** an option — it collides
455 /// with [`SurfaceCaps::preferred_format`]'s documented meaning — and nor
456 /// is an empty [`present_modes`](SurfaceCaps::present_modes), which would
457 /// break the promise that [`PresentMode::Fifo`](crate::PresentMode::Fifo)
458 /// is always there.
459 /// * **Callers** doing selection must treat an `Err` from this call as "try
460 /// the next adapter", not as fatal. Only running out of adapters is
461 /// fatal. `crcbl_app::present`'s `Presenter::start_device` is the
462 /// reference implementation.
463 ///
464 /// # Errors
465 ///
466 /// [`HalError::Unsupported`] when the adapter cannot present to this
467 /// surface, [`HalError::InvalidHandle`] for a stale surface,
468 /// [`HalError::NoSuchAdapter`] for an unknown adapter, or a backend error if
469 /// the query failed.
470 fn surface_caps(
471 &self,
472 surface: SurfaceHandle,
473 adapter: AdapterId,
474 ) -> Result<SurfaceCaps, HalError>;
475
476 /// The adapter driving the display `surface`'s window is on, where this
477 /// backend can tell; `Ok(None)` where it cannot.
478 ///
479 /// Adapter selection asks so a window on a display a discrete GPU drives
480 /// renders there rather than copying every frame across from another
481 /// adapter; see `crcbl_app::adapter::rank`. **`None` is an answer, not a
482 /// failure**: an offscreen surface is on no display, a display driven by
483 /// an adapter this backend does not list has no id to give, and a backend
484 /// or platform with no way to ask says so this way. A caller ranks by its
485 /// power preference alone then.
486 ///
487 /// | Backend | Platform | How |
488 /// | --- | --- | --- |
489 /// | `crcbl-dx12` | Win32 | the adapter whose `EnumOutputs` holds `MonitorFromWindow` |
490 /// | `crcbl-vk` | Win32 | the adapter whose `deviceLUID` is the monitor's GDI adapter's |
491 /// | `crcbl-vk` | Wayland | the adapter whose DRM node is the compositor's dmabuf main device |
492 /// | `crcbl-vk` | X11 | the adapter whose DRM node is the device DRI3 `Open` names |
493 /// | `crcbl-mtl` | macOS | `None`, not built yet |
494 /// | `crcbl-webgpu` | browser | `None`: a page cannot know |
495 ///
496 /// # Errors
497 ///
498 /// [`HalError::InvalidHandle`] for a stale surface, or
499 /// [`HalError::ForeignObject`] for another instance's.
500 fn display_adapter(&self, surface: SurfaceHandle) -> Result<Option<AdapterId>, HalError>;
501
502 /// Starts opening a device. The device itself arrives from
503 /// [`PendingDevice::poll`].
504 ///
505 /// **There is no synchronous device creation on every target.** WebGPU's
506 /// `requestDevice` resolves on a later turn of the event loop and cannot be
507 /// blocked on from the browser main thread; see the [module
508 /// docs](crate::device#device-creation-is-polled-not-blocking) for the full
509 /// argument and the per-backend mapping.
510 ///
511 /// Everything a backend can decide *now* is decided now: an unknown adapter,
512 /// a missing required feature, or a foreign surface is an `Err` from this
513 /// call, not a deferred failure. Only what genuinely depends on the driver
514 /// answering — device loss, a browser refusing the request — surfaces from
515 /// [`PendingDevice::poll`].
516 ///
517 /// # Errors
518 ///
519 /// [`HalError::NoSuchAdapter`], [`HalError::UnsupportedFeatures`] naming
520 /// exactly which of `required_features` the adapter lacks, or
521 /// [`HalError::InvalidHandle`] / [`HalError::ForeignObject`] for
522 /// [`DeviceDesc::compatible_surface`].
523 fn request_device(&self, desc: &DeviceDesc<'_>) -> Result<Box<dyn PendingDevice>, HalError>;
524
525 /// Opens a device, blocking until it is ready.
526 ///
527 /// The convenience wrapper over [`request_device`](Instance::request_device)
528 /// for callers that have nothing else to do — start-up, `crcbl screenshot`,
529 /// every headless test. **Absent on `wasm32`**, where blocking the main
530 /// thread is not an option; browser code polls `request_device` from the
531 /// rAF loop instead, and gets a compile error rather than a run-time
532 /// [`HalError::Unsupported`] if it forgets.
533 ///
534 /// Backends do not normally override this: the default is exactly "request,
535 /// then poll until ready".
536 ///
537 /// # Errors
538 ///
539 /// Anything [`request_device`](Instance::request_device) or
540 /// [`PendingDevice::poll`] can report.
541 #[cfg(not(target_arch = "wasm32"))]
542 fn create_device(&self, desc: &DeviceDesc<'_>) -> Result<Box<dyn Device>, HalError> {
543 let mut pending = self.request_device(desc)?;
544 loop {
545 match pending.poll()? {
546 DeviceRequestState::Ready(device) => return Ok(device),
547 // Yield rather than spin: a backend that really is asynchronous
548 // is waiting on another thread or another task, and a hot loop
549 // would starve it on a single-core CI runner.
550 DeviceRequestState::Pending => std::thread::yield_now(),
551 }
552 }
553 }
554}
555
556/// A device request that has been started and has not finished.
557///
558/// Returned by [`Instance::request_device`]; driven by [`poll`](Self::poll) once
559/// per frame (or once per loop iteration at start-up) until it yields the
560/// device. Dropping one abandons the request, which is legal — a browser
561/// promise that later resolves simply has nobody listening.
562///
563/// The trait exists rather than an `async fn` because the seam's traits are
564/// object-safe by design (see the crate docs): `async fn` in a trait is not
565/// object-safe without boxing every call, and `async-trait` would put an
566/// allocation and a `Pin<Box<dyn Future>>` in the seam's vocabulary to serve one
567/// call made once per process.
568pub trait PendingDevice: core::fmt::Debug + crate::threading::HalThreadSafe {
569 /// Which backend this request will produce a device for. For logs and bug
570 /// reports — never for behaviour.
571 fn backend(&self) -> BackendKind;
572
573 /// Advances the request. `Pending` means "ask again"; `Ready` hands over the
574 /// device.
575 ///
576 /// This is a poll, not a wait: it must never block. Polling again after a
577 /// `Ready` is a caller bug — the device was moved out — and reports
578 /// [`HalError::InvalidDescriptor`] rather than producing a second device.
579 ///
580 /// # Errors
581 ///
582 /// [`HalError::DeviceLost`] if the driver or the browser refused the
583 /// request, [`HalError::UnsupportedFeatures`] if the refusal named features,
584 /// or [`HalError::InvalidDescriptor`] for a poll after completion.
585 fn poll(&mut self) -> Result<DeviceRequestState, HalError>;
586}
587
588/// Where a device request has got to — the [`ReadbackState`] of device creation.
589///
590/// [`ReadbackState`]: crate::ReadbackState
591///
592/// Failure is an `Err` from [`PendingDevice::poll`] rather than a third variant,
593/// for the same reason readback has no `Failed`: the reason is the only useful
594/// part of a device-creation failure and a bare state would throw it away.
595#[derive(Debug)]
596pub enum DeviceRequestState {
597 /// Not open yet. Poll again next frame.
598 Pending,
599 /// Open. The device is yours.
600 Ready(Box<dyn Device>),
601}
602
603impl DeviceRequestState {
604 /// Whether the device is available.
605 #[must_use]
606 pub const fn is_ready(&self) -> bool {
607 matches!(self, Self::Ready(_))
608 }
609
610 /// The device, or `None` while the request is still pending.
611 #[must_use]
612 pub fn into_device(self) -> Option<Box<dyn Device>> {
613 match self {
614 Self::Ready(device) => Some(device),
615 Self::Pending => None,
616 }
617 }
618}
619
620/// An open device: creates resources, records and submits work, presents.
621///
622/// See the module docs for why methods take `&self` and why destruction is
623/// explicit.
624pub trait Device: core::fmt::Debug + crate::threading::HalThreadSafe {
625 /// Which backend this device belongs to.
626 fn backend(&self) -> BackendKind;
627
628 /// What this device can do. Drives the path selection; see
629 /// [`DeviceCaps::geometry_path`] and its siblings.
630 fn caps(&self) -> DeviceCaps;
631
632 /// Preferred path for GPU-generated geometry, within this device's caps.
633 ///
634 /// The capability ceiling is the default. A backend may prefer a cheaper
635 /// supported path when the higher-ranked one requires emulation. This does
636 /// not disable capabilities: callers can still use every advertised verb.
637 /// An indirect-per-batch renderer must write zero instances for empty
638 /// buckets, as that path already requires.
639 fn preferred_geometry_path(&self) -> crate::GeometryPath {
640 self.caps().geometry_path()
641 }
642
643 /// Whether this backend performs `capability` on this device, and why not
644 /// when it does not.
645 ///
646 /// **The seam's anti-rot mechanism, and the reason it has no default.** A
647 /// backend answers with an exhaustive `match` over
648 /// [`Capability`](crate::Capability) and no wildcard arm, so a variant added
649 /// to that enum fails to compile in every backend until each has said what
650 /// it does. A default here — or a `_ =>` arm there — would restore exactly
651 /// the silence the enum exists to remove, which is why neither is written.
652 ///
653 /// Costs one virtual call and a jump table; see [`crate::capability`] for
654 /// why this is separate from [`Features`], what it deliberately does not
655 /// model, and how [`DIVERGENCES`](crate::DIVERGENCES) turns the answers into
656 /// a reviewed parity contract.
657 ///
658 /// ```
659 /// use crcbl_hal::null::NullInstance;
660 /// use crcbl_hal::{AdapterId, Capability, DeviceDesc, Instance};
661 ///
662 /// let instance = NullInstance::gpu_driven();
663 /// let device = instance.create_device(&DeviceDesc::for_adapter(AdapterId(0)))?;
664 ///
665 /// // Every capability has an answer, and a refusal always carries a reason.
666 /// for capability in Capability::ALL {
667 /// let support = device.supports(*capability);
668 /// assert_eq!(support.is_yes(), support.reason().is_none());
669 /// }
670 /// # Ok::<(), crcbl_hal::HalError>(())
671 /// ```
672 fn supports(&self, capability: crate::Capability) -> crate::Support;
673
674 /// A queue of the given kind.
675 ///
676 /// Returns `None` when the device has no such queue — check
677 /// [`Features::ASYNC_COMPUTE_QUEUE`] / [`Features::TRANSFER_QUEUE`] first,
678 /// or just fall back to [`QueueKind::Graphics`], which always exists.
679 fn queue(&self, kind: QueueKind) -> Option<QueueHandle>;
680
681 /// Takes the error the driver reported **out of band**, if there is one.
682 ///
683 /// Some backends do not deliver every failure to the call that caused it.
684 /// WebGPU is the case this exists for: a pipeline whose shader will not
685 /// compile is still handed back as an object, and the reason arrives later
686 /// on the device's error channel. A caller that only checks return values
687 /// therefore sees a healthy device, submits command buffers the
688 /// implementation silently discards, and draws nothing — which is exactly
689 /// how the browser's first invalid shader presented, as a black canvas over
690 /// a game that reported itself as playing.
691 ///
692 /// Call it once a frame and log or fail on what comes out; it is the only
693 /// way to notice that class of failure at all. Each error is reported once
694 /// — taking it clears it — and backends that report every failure through
695 /// their return values keep the default and always answer `None`.
696 fn take_error(&self) -> Option<String> {
697 None
698 }
699
700 // --- resources ---
701
702 /// Creates a buffer.
703 ///
704 /// # Errors
705 ///
706 /// [`HalError::OutOfDeviceMemory`], or [`HalError::InvalidDescriptor`] for a
707 /// zero size or a usage/memory combination the backend cannot satisfy.
708 fn create_buffer(&self, desc: &BufferDesc<'_>) -> Result<BufferHandle, HalError>;
709
710 /// Destroys a buffer.
711 fn destroy_buffer(&self, buffer: BufferHandle);
712
713 /// Copies `data` into a mappable buffer at `offset`.
714 ///
715 /// Only valid for [`MemoryLocation::HostUpload`](crate::MemoryLocation::HostUpload).
716 /// Deliberately a copy rather than a `map`/`unmap` pair returning a slice:
717 /// a returned `&mut [u8]` cannot be made sound through a trait object
718 /// without a lifetime the object cannot carry, and every real caller is
719 /// writing a prepared block into a staging ring anyway. If a caller ever
720 /// needs to build data in place, that is a persistent-mapping addition to
721 /// this trait, not a reason to leak a pointer today.
722 ///
723 /// # Errors
724 ///
725 /// [`HalError::InvalidHandle`], or [`HalError::InvalidDescriptor`] if the
726 /// range is out of bounds or the buffer is not host-visible.
727 fn write_buffer(&self, buffer: BufferHandle, offset: u64, data: &[u8]) -> Result<(), HalError>;
728
729 /// Starts a GPU→CPU readback of a range of a host-readable buffer.
730 ///
731 /// **There is no synchronous read.** WebGPU's `mapAsync` completes on a
732 /// later turn of the event loop and cannot be blocked on from the browser
733 /// main thread, so a blocking signature would be unimplementable on the
734 /// target the browser track cares most about. See
735 /// [`crate::readback`] for the full argument and the per-backend mapping.
736 ///
737 /// The result is observed with [`Device::poll_readback`] and released with
738 /// [`Device::destroy_readback`]. A readback covers work already submitted
739 /// when this is called, or the completion point named by
740 /// [`ReadbackDesc::after`].
741 ///
742 /// This is still the *one* readback topic 03 (§3.6)
743 /// permits in the frame loop — culling stats, N frames latent, debug
744 /// builds only. Poll-shaped is what makes "N frames latent" expressible.
745 ///
746 /// # Errors
747 ///
748 /// [`HalError::InvalidHandle`] or [`HalError::ForeignObject`] for the
749 /// buffer, or [`HalError::InvalidDescriptor`] if the range is out of bounds
750 /// or the buffer is not
751 /// [`MemoryLocation::HostReadback`](crate::MemoryLocation::HostReadback).
752 fn request_readback(&self, desc: &ReadbackDesc<'_>) -> Result<ReadbackHandle, HalError>;
753
754 /// Checks whether a readback has completed, writing its bytes into `out` if
755 /// so.
756 ///
757 /// `out` must be exactly [`ReadbackDesc::size`] bytes. It is left untouched
758 /// while the state is [`ReadbackState::Pending`]. Polling again after
759 /// [`ReadbackState::Ready`] is legal and yields the same bytes until the
760 /// readback is destroyed.
761 ///
762 /// Call this at most once per frame per readback; it is a poll, not a wait.
763 ///
764 /// # Errors
765 ///
766 /// [`HalError::InvalidHandle`] or [`HalError::ForeignObject`] for the
767 /// readback, [`HalError::InvalidDescriptor`] if `out` is the wrong length,
768 /// or [`HalError::DeviceLost`] if the work behind it failed. Failure is an
769 /// `Err` rather than a third [`ReadbackState`] so the reason survives.
770 fn poll_readback(
771 &self,
772 readback: ReadbackHandle,
773 out: &mut [u8],
774 ) -> Result<ReadbackState, HalError>;
775
776 /// Releases a readback request, whether or not it completed.
777 ///
778 /// On WebGPU this is the `unmap`; abandoning readbacks without destroying
779 /// them leaks a mapped buffer, which is why this exists rather than being
780 /// implicit.
781 ///
782 /// **Destroying one whose bytes never landed is legal and silent.** The
783 /// request is cancelled, its bytes are never delivered, and the call reports
784 /// nothing — not through a return value it does not have, and not through
785 /// [`take_error`](Self::take_error) either. A caller that stops caring about
786 /// a readback mid-flight is doing the thing this call is for.
787 ///
788 /// The obligation is on the backend, and only one of them has to do
789 /// anything for it. On WebGPU the cancel is `unmap()`, which **rejects** an
790 /// outstanding `mapAsync` with an `AbortError`; filing that rejection as a
791 /// device error is how a cancelled readback came to report
792 /// `could not be mapped: AbortError`, naming a call that did as it was told.
793 /// The backend must tell that rejection apart from a real failure and stay
794 /// quiet. Vulkan, D3D12 and Metal satisfy this by accident — there is no
795 /// promise to reject, so dropping the tracking entry is the whole of it —
796 /// which is exactly why it is written down here and asserted for every
797 /// backend by `destroying_a_readback_before_its_bytes_land_reports_nothing`
798 /// rather than left to three backends continuing to be incidentally right.
799 fn destroy_readback(&self, readback: ReadbackHandle);
800
801 /// Creates an image.
802 ///
803 /// The image is
804 /// [`MemoryLocation::DeviceLocal`](crate::MemoryLocation::DeviceLocal);
805 /// [`ImageDesc`] has no field to ask for anything else, and
806 /// [`MemoryLocation`](crate::MemoryLocation) says why.
807 ///
808 /// # Errors
809 ///
810 /// [`HalError::OutOfDeviceMemory`], or [`HalError::InvalidDescriptor`] if
811 /// the extent, mip count or sample count exceeds [`Device::caps`].
812 fn create_image(&self, desc: &ImageDesc<'_>) -> Result<ImageHandle, HalError>;
813
814 /// Destroys an image. Every view of it must already be destroyed.
815 fn destroy_image(&self, image: ImageHandle);
816
817 /// Creates an image view.
818 ///
819 /// # Errors
820 ///
821 /// [`HalError::InvalidHandle`] for a stale image, or
822 /// [`HalError::InvalidDescriptor`] for an incompatible format or an
823 /// out-of-range subresource.
824 fn create_image_view(&self, desc: &ImageViewDesc<'_>) -> Result<ImageViewHandle, HalError>;
825
826 /// Destroys an image view.
827 fn destroy_image_view(&self, view: ImageViewHandle);
828
829 /// Creates a sampler.
830 ///
831 /// # Errors
832 ///
833 /// [`HalError::InvalidDescriptor`] if
834 /// [`anisotropy`](SamplerDesc::anisotropy) is below `1.0` — the value that
835 /// disables it, so there is nothing below it to ask for — or is a NaN,
836 /// which compares false against every bound and would otherwise reach a
837 /// driver unexamined. Both are
838 /// [`SamplerDesc::check_anisotropy_floor`], which every backend calls.
839 ///
840 /// Also [`HalError::InvalidDescriptor`] if it exceeds
841 /// [`Limits::max_sampler_anisotropy`](crate::Limits::max_sampler_anisotropy)
842 /// — [`SamplerDesc::check_anisotropy_ceiling`] — on every backend **except
843 /// `crcbl-webgpu`**, which reports that limit as `1.0` to mean "no ceiling
844 /// this backend can guarantee" rather than "more than one is refused". See
845 /// that method's own docs, and the backlog entry "Anisotropy: the limit
846 /// says one, the replayer passes more through".
847 fn create_sampler(&self, desc: &SamplerDesc<'_>) -> Result<SamplerHandle, HalError>;
848
849 /// Destroys a sampler.
850 fn destroy_sampler(&self, sampler: SamplerHandle);
851
852 // --- shaders and pipelines ---
853
854 /// Creates a shader module from whichever artifact this backend consumes.
855 ///
856 /// The caller fills in every format it holds and does not choose between
857 /// them; this implementation takes the one it can compile. See
858 /// [`crate::shader`] for the contract in full.
859 ///
860 /// # Errors
861 ///
862 /// [`HalError::ShaderCompilation`] if the artifact is malformed, uses a
863 /// capability the device lacks, or fails to translate. Also — via
864 /// [`ShaderModuleDesc::unusable`] — when the descriptor carries no format
865 /// this backend can compile, including a descriptor that carries none at
866 /// all.
867 fn create_shader_module(
868 &self,
869 desc: &ShaderModuleDesc<'_>,
870 ) -> Result<ShaderModuleHandle, HalError>;
871
872 /// Destroys a shader module. Pipelines built from it stay valid.
873 fn destroy_shader_module(&self, module: ShaderModuleHandle);
874
875 /// Creates a bind-group layout.
876 ///
877 /// # Errors
878 ///
879 /// Whatever
880 /// [`BindGroupLayoutDesc::check_entries`](crate::BindGroupLayoutDesc::check_entries)
881 /// returns — every backend runs it here, and it is where the rules
882 /// [`BindGroupLayoutDesc::entries`](crate::BindGroupLayoutDesc::entries)
883 /// states are enforced. A backend may add [`HalError::InvalidDescriptor`]
884 /// or [`HalError::Unsupported`] of its own for a layout only *it* cannot
885 /// express.
886 fn create_bind_group_layout(
887 &self,
888 desc: &BindGroupLayoutDesc<'_>,
889 ) -> Result<BindGroupLayoutHandle, HalError>;
890
891 /// Destroys a bind-group layout.
892 fn destroy_bind_group_layout(&self, layout: BindGroupLayoutHandle);
893
894 /// Creates a bind group.
895 ///
896 /// # Errors
897 ///
898 /// [`HalError::InvalidHandle`] for a stale layout or resource, or
899 /// [`HalError::InvalidDescriptor`] if an entry does not match the layout —
900 /// including a host-visible buffer filling a writable storage binding,
901 /// which every backend refuses because D3D12 cannot express it. See
902 /// [`MemoryLocation`](crate::MemoryLocation).
903 ///
904 /// Also [`HalError::InvalidDescriptor`] for a buffer range longer than
905 /// [`Limits::max_uniform_buffer_range`](crate::Limits::max_uniform_buffer_range)
906 /// or
907 /// [`Limits::max_storage_buffer_range`](crate::Limits::max_storage_buffer_range),
908 /// whichever the slot names. The range is what the binding covers, so
909 /// [`BindingResource::WHOLE_BUFFER`](crate::BindingResource::WHOLE_BUFFER)
910 /// is the buffer's size less the offset: an over-large buffer bound whole is
911 /// refused, and the same buffer bound in pieces is not. Vulkan states both
912 /// as VUIDs rather than as errors, so this is the seam turning what would be
913 /// undefined behaviour into a refusal a caller can act on. `crcbl-webgpu`
914 /// is the exception on *where* it arrives, as it is for
915 /// [`create_pipeline_layout`](Device::create_pipeline_layout): its device is
916 /// an encoder holding no buffer sizes to measure a `WHOLE_BUFFER` binding
917 /// against, and WebGPU validates the same two limits itself at
918 /// `createBindGroup`, so there the refusal surfaces through
919 /// [`take_error`](Device::take_error).
920 fn create_bind_group(&self, desc: &BindGroupDesc<'_>) -> Result<BindGroupHandle, HalError>;
921
922 /// Updates entries of an existing bind group in place.
923 ///
924 /// The bindless write path: with
925 /// [`BindingFlags::UPDATE_AFTER_BIND`](crate::BindingFlags::UPDATE_AFTER_BIND)
926 /// this may be called while command buffers referencing the group are
927 /// pending, which is what removes per-object descriptor updates from the
928 /// frame loop (topic 03's "zero per-frame descriptor writes in steady
929 /// state" is about the *steady* state; streaming a new texture in still
930 /// writes one entry).
931 ///
932 /// # Errors
933 ///
934 /// [`HalError::InvalidHandle`], or [`HalError::Unsupported`] if the group's
935 /// layout was not created with `UPDATE_AFTER_BIND`.
936 fn update_bind_group(
937 &self,
938 group: BindGroupHandle,
939 entries: &[crate::BindGroupEntry],
940 ) -> Result<(), HalError>;
941
942 /// Destroys a bind group.
943 fn destroy_bind_group(&self, group: BindGroupHandle);
944
945 /// Creates a pipeline layout.
946 ///
947 /// # A layout inside every limit may still be refused
948 ///
949 /// [`Limits`](crate::Limits) bounds each quantity on its own, and D3D12 and
950 /// Metal each spend more than one of them out of a single budget the seam
951 /// has no field for — a root signature's DWORD cost and a per-stage buffer
952 /// argument table respectively, both described on
953 /// [`Limits`](crate::Limits). So
954 /// [`max_bind_groups`](crate::Limits::max_bind_groups) sets *and*
955 /// [`max_push_constant_size`](crate::Limits::max_push_constant_size) bytes
956 /// is a legal request that a device may refuse, and the caller's answer is
957 /// to attempt the creation and handle the refusal rather than to pre-check
958 /// arithmetic that is not the seam's.
959 ///
960 /// **That refusal happens here**, with `InvalidDescriptor` and both sides of
961 /// the arithmetic in the message, rather than at the pipeline that would
962 /// have been built on it or at the draw that would have bound nothing.
963 /// `crcbl-webgpu` is the one backend where it does not: its
964 /// implementation encodes onto a command stream and returns before a browser
965 /// has seen the layout, so it refuses nothing itself and every failure —
966 /// WebGPU's own per-stage binding caps included — arrives later through
967 /// [`take_error`](Device::take_error).
968 ///
969 /// # Errors
970 ///
971 /// [`HalError::InvalidHandle`], or [`HalError::Unsupported`] if it declares
972 /// push constants on a device without
973 /// [`Features::PUSH_CONSTANTS`] — loudly, rather than dropping the writes
974 /// later — or if
975 /// [`PushConstantRange::stages`](crate::PushConstantRange::stages) names a
976 /// mesh or task stage the device does not report, per
977 /// [`ShaderStages::check_supported`](crate::ShaderStages::check_supported).
978 ///
979 /// [`HalError::InvalidDescriptor`] for more bind-group layouts than
980 /// [`Limits::max_bind_groups`](crate::Limits::max_bind_groups), for a range
981 /// ending past
982 /// [`Limits::max_push_constant_size`](crate::Limits::max_push_constant_size),
983 /// and for a layout inside both of those that the backend's own shared
984 /// budget cannot hold.
985 fn create_pipeline_layout(
986 &self,
987 desc: &PipelineLayoutDesc<'_>,
988 ) -> Result<PipelineLayoutHandle, HalError>;
989
990 /// Destroys a pipeline layout.
991 fn destroy_pipeline_layout(&self, layout: PipelineLayoutHandle);
992
993 /// Creates a graphics pipeline.
994 ///
995 /// # Errors
996 ///
997 /// [`HalError::PipelineCreation`] with the driver's message, or
998 /// [`HalError::InvalidHandle`] for a stale layout or shader module.
999 fn create_graphics_pipeline(
1000 &self,
1001 desc: &GraphicsPipelineDesc<'_>,
1002 ) -> Result<GraphicsPipelineHandle, HalError>;
1003
1004 /// Creates a **mesh** pipeline — the primary geometry path, per
1005 /// topic 03 §3.5.
1006 ///
1007 /// It produces a [`GraphicsPipelineHandle`], and is bound and destroyed
1008 /// exactly like one; [`MeshPipelineDesc`](crate::MeshPipelineDesc) explains
1009 /// why a sibling descriptor shares the handle type rather than adding a
1010 /// second one.
1011 ///
1012 /// # Errors
1013 ///
1014 /// [`HalError::Unsupported`] on a device that does not report
1015 /// [`Features::MESH_SHADER`], or whose
1016 /// [`MeshPipelineDesc::task`](crate::MeshPipelineDesc::task) is `Some` on a
1017 /// device without [`Features::TASK_SHADER`]. **Refusing here is the
1018 /// contract**, not an implementation detail: a backend that accepted the
1019 /// descriptor and failed at the draw would put the diagnosis a frame away
1020 /// from the mistake, and topic 39 requires an absent
1021 /// capability to be a named, loud failure rather than a quiet one.
1022 ///
1023 /// Otherwise as [`Device::create_graphics_pipeline`].
1024 fn create_mesh_pipeline(
1025 &self,
1026 desc: &crate::MeshPipelineDesc<'_>,
1027 ) -> Result<GraphicsPipelineHandle, HalError>;
1028
1029 /// Destroys a graphics pipeline. Also destroys a mesh pipeline — see
1030 /// [`Device::create_mesh_pipeline`].
1031 fn destroy_graphics_pipeline(&self, pipeline: GraphicsPipelineHandle);
1032
1033 /// Creates a compute pipeline.
1034 ///
1035 /// # Errors
1036 ///
1037 /// As [`Device::create_graphics_pipeline`].
1038 fn create_compute_pipeline(
1039 &self,
1040 desc: &ComputePipelineDesc<'_>,
1041 ) -> Result<ComputePipelineHandle, HalError>;
1042
1043 /// Destroys a compute pipeline.
1044 fn destroy_compute_pipeline(&self, pipeline: ComputePipelineHandle);
1045
1046 // --- queries ---
1047
1048 /// Creates a query set.
1049 ///
1050 /// # A set of no queries is never created
1051 ///
1052 /// [`QuerySetDesc::count`](crate::QuerySetDesc::count) of zero is refused
1053 /// by every backend, and this is the contract rather than four
1054 /// coincidences: each API forbids it for its own reason — WebGPU's
1055 /// `GPUQuerySetDescriptor.count` has a minimum of one, Metal's
1056 /// `newBufferWithLength:options:` returns nil for a zero-length buffer —
1057 /// and a handle to such a set would be one whose every read is out of
1058 /// range, so the failure would surface at the read rather than at the
1059 /// mistake.
1060 ///
1061 /// Which refusal a caller gets when the device *also* lacks the feature is
1062 /// deliberately not specified: backends check the two in different orders,
1063 /// and both answers are refusals of a set that must not exist.
1064 ///
1065 /// # Errors
1066 ///
1067 /// [`HalError::Unsupported`] if the device lacks the corresponding feature.
1068 /// [`HalError::InvalidDescriptor`] for a `count` of zero on a device that
1069 /// has the feature.
1070 fn create_query_set(&self, desc: &QuerySetDesc<'_>) -> Result<QuerySetHandle, HalError>;
1071
1072 /// Destroys a query set.
1073 fn destroy_query_set(&self, set: QuerySetHandle);
1074
1075 /// Reads query results directly, without a resolve-to-buffer round trip.
1076 ///
1077 /// `out.len()` results are read starting at `first_query`.
1078 ///
1079 /// # A [`QueryKind::Timestamp`](crate::QueryKind::Timestamp) result is **nanoseconds**
1080 ///
1081 /// Not a tick, and not a tick plus a scale factor the caller has to know
1082 /// about. The scale is a different thing in every API — Vulkan reports
1083 /// nanoseconds per tick (`VkPhysicalDeviceLimits::timestampPeriod`), D3D12
1084 /// reports its reciprocal (`ID3D12CommandQueue::GetTimestampFrequency`),
1085 /// WebGPU's `GPUQuerySet` results are already nanoseconds, and Metal has no
1086 /// fixed period at all because `MTLDevice`'s
1087 /// `sampleTimestamps:gpuTimestamp:` correlates the GPU clock to the host at
1088 /// the moment of sampling — so a seam that carried one backend's spelling
1089 /// of it would have two backends inventing a number to fill the field with.
1090 /// The unit is the seam's; each backend converts where the factor is
1091 /// something it actually knows.
1092 ///
1093 /// The value is **rounded to the nearest nanosecond, once, at the source**,
1094 /// so every caller reads the same number rather than each rounding a
1095 /// tick-times-float product its own way.
1096 ///
1097 /// **[`resolve_query_set`](crate::CommandEncoder::resolve_query_set) is the
1098 /// other read path and it does *not* convert** — it is a GPU-side copy, and
1099 /// there is nothing on that side to multiply with. Its destination holds
1100 /// whatever the device writes. See its own documentation.
1101 ///
1102 /// The other kinds count things — samples, invocations, primitives — and
1103 /// have no unit to convert: they come back as the device wrote them.
1104 ///
1105 /// Returns zeros on a device without
1106 /// [`Features::TIMESTAMP_QUERY`] rather than failing — the profiler HUD
1107 /// degrades, it does not break.
1108 ///
1109 /// **On `crcbl-vk` and `crcbl-dx12` it blocks until every submission that
1110 /// names the set has finished**, so what it returns is that work's answer
1111 /// and never a previous use's. A caller that reads a set whose latest
1112 /// submission waits on a semaphore the caller has yet to signal therefore
1113 /// waits forever there: signal first, then read. A caller that must not
1114 /// stall reads a set whose frame is known to have retired, which is the
1115 /// portable rule whatever a backend does.
1116 ///
1117 /// # Errors
1118 ///
1119 /// [`HalError::InvalidHandle`], or [`HalError::InvalidDescriptor`] if the
1120 /// range exceeds the set.
1121 fn query_results(
1122 &self,
1123 set: QuerySetHandle,
1124 first_query: u32,
1125 out: &mut [u64],
1126 ) -> Result<(), HalError>;
1127
1128 /// Reads `out.len()` pipeline-statistics queries starting at
1129 /// `first_query`: what the GPU counted over each pass a
1130 /// [`PassStatisticsWrites`](crate::PassStatisticsWrites) named.
1131 ///
1132 /// The statistics kind's own read, because one of its queries is several
1133 /// counts and [`query_results`](Self::query_results) reads one `u64` per
1134 /// query. It waits as that call does, for every submission that names the
1135 /// set.
1136 ///
1137 /// The default refuses: a backend that counts nothing has nothing to read.
1138 ///
1139 /// # Errors
1140 ///
1141 /// [`HalError::Unsupported`] where the backend counts nothing,
1142 /// [`HalError::InvalidHandle`], or [`HalError::InvalidDescriptor`] for a
1143 /// set of another kind or a range past its end.
1144 fn pipeline_statistics(
1145 &self,
1146 set: QuerySetHandle,
1147 first_query: u32,
1148 out: &mut [crate::PipelineStatistics],
1149 ) -> Result<(), HalError> {
1150 let _ = (set, first_query, out);
1151 Err(HalError::Unsupported {
1152 backend: self.backend(),
1153 what: crate::NO_PIPELINE_STATISTICS,
1154 })
1155 }
1156
1157 /// The GPU's timestamp clock now, on the timebase and in the nanoseconds
1158 /// [`query_results`](Self::query_results) reads a timestamp in: a value a
1159 /// pass's timestamps can be compared with, read from the CPU.
1160 ///
1161 /// A profiler reads it between two reads of its own clock to put the
1162 /// GPU's passes on the CPU's timeline. Nothing waits: it reads the clock,
1163 /// not any work.
1164 ///
1165 /// The default refuses: a backend that does not read the clock has nothing
1166 /// to answer with.
1167 ///
1168 /// # Errors
1169 ///
1170 /// [`HalError::Unsupported`] on a device without
1171 /// [`Features::GPU_CLOCK`] or a backend that does not read the clock, and
1172 /// whatever the API reports for a lost device.
1173 fn gpu_clock(&self) -> Result<u64, HalError> {
1174 Err(HalError::Unsupported {
1175 backend: self.backend(),
1176 what: crate::NO_GPU_CLOCK,
1177 })
1178 }
1179
1180 // --- synchronisation ---
1181
1182 /// Creates a semaphore. See [`crate::sync`] on why timeline is the default.
1183 ///
1184 /// # Errors
1185 ///
1186 /// [`HalError::Unsupported`] for a timeline semaphore on a device without
1187 /// [`Features::TIMELINE_SEMAPHORE`].
1188 fn create_semaphore(&self, desc: &SemaphoreDesc<'_>) -> Result<SemaphoreHandle, HalError>;
1189
1190 /// Destroys a semaphore.
1191 fn destroy_semaphore(&self, semaphore: SemaphoreHandle);
1192
1193 /// The current value of a timeline semaphore.
1194 ///
1195 /// # Errors
1196 ///
1197 /// [`HalError::InvalidHandle`], or [`HalError::Unsupported`] for a binary
1198 /// semaphore, which has no value to read.
1199 fn semaphore_value(&self, semaphore: SemaphoreHandle) -> Result<u64, HalError>;
1200
1201 /// Signals a timeline semaphore to `value` from the **CPU**.
1202 ///
1203 /// The half [`semaphore_value`](Self::semaphore_value) had no counterpart
1204 /// for. It is what lets a submission wait on a value no earlier submission
1205 /// will produce: the caller opens the gate when it is ready, from whatever
1206 /// thread it likes. Every backend's API has it — `vkSignalSemaphore`,
1207 /// `ID3D12Fence::Signal`, `MTLSharedEvent`'s `setSignaledValue:` — and
1208 /// [`Capability::CpuTimelineSignal`](crate::Capability::CpuTimelineSignal)
1209 /// is the claim to perform it.
1210 ///
1211 /// # `value` must move the timeline forwards
1212 ///
1213 /// It must be **strictly greater** than the value the semaphore already
1214 /// holds. Vulkan refuses a lower one; D3D12 and Metal set a fence or an
1215 /// event backwards without any diagnostic at all, and then every waiter past
1216 /// the higher value stops waking on a queue that is otherwise healthy. So
1217 /// the rule is the seam's rather than one backend's, and it is the rule
1218 /// [`SemaphoreSignal::value`](crate::SemaphoreSignal::value) already carries
1219 /// for the submission-side signal.
1220 ///
1221 /// A backend that tracks the values submissions have already been *given* to
1222 /// signal holds `value` above those too, which is stricter than reading the
1223 /// counter: a signal sitting in a queue has not fired yet, so signalling
1224 /// past it would still make the timeline go backwards when it does. That is
1225 /// a caller error everywhere, including on Vulkan — there it is a validation
1226 /// error rather than a returned one.
1227 ///
1228 /// # Errors
1229 ///
1230 /// [`HalError::InvalidHandle`]; [`HalError::Unsupported`] for a binary
1231 /// semaphore, which has no value to signal, and on a backend with no
1232 /// timeline at all — see [`crate::sync`], where WebGPU is the case; and
1233 /// [`HalError::InvalidDescriptor`] when `value` does not move the timeline
1234 /// forwards, because a number the caller can correct is not a capability the
1235 /// backend lacks.
1236 fn signal_semaphore(&self, semaphore: SemaphoreHandle, value: u64) -> Result<(), HalError>;
1237
1238 /// Blocks until every `(semaphore, value)` pair has been reached, or until
1239 /// `timeout_ns` elapses.
1240 ///
1241 /// Returns `Ok(true)` if the waits were satisfied and `Ok(false)` on
1242 /// timeout — a timeout is a normal outcome for a frame-pacing poll, not an
1243 /// error.
1244 ///
1245 /// # Errors
1246 ///
1247 /// [`HalError::InvalidHandle`] or [`HalError::DeviceLost`]; and
1248 /// [`HalError::Unsupported`] both for a **binary** semaphore, which carries
1249 /// no value for a host wait to compare against — the mirror of
1250 /// [`Self::signal_semaphore`]'s refusal, and what every backend here
1251 /// answers — and on a backend with no timeline to block on at all, see
1252 /// [`crate::sync`], where WebGPU is the case. A *timeout* is not an error:
1253 /// that is `Ok(false)`.
1254 fn wait_semaphores(
1255 &self,
1256 waits: &[crate::SemaphoreWait],
1257 timeout_ns: u64,
1258 ) -> Result<bool, HalError>;
1259
1260 /// Blocks until the device has finished everything submitted so far.
1261 ///
1262 /// A shutdown and test primitive. Using it in a frame loop destroys
1263 /// pipelining; the frames-in-flight timeline is the tool for that.
1264 ///
1265 /// # Errors
1266 ///
1267 /// [`HalError::DeviceLost`].
1268 fn wait_idle(&self) -> Result<(), HalError>;
1269
1270 // --- commands ---
1271
1272 /// Creates a command encoder.
1273 ///
1274 /// # One recording encoder per device
1275 ///
1276 /// Once a later encoder has been created on the same device, an earlier
1277 /// one may record nothing more and may not be finished — drop it instead.
1278 /// Finish an encoder before creating the next, or create it at the point
1279 /// it starts recording. `crcbl-webgpu` is why: the seam's recording
1280 /// methods name no encoder, so its stream records every command into the
1281 /// one encoder its browser side created last, and a command for an earlier
1282 /// one lands in the later one or, once that is finished, in none. The
1283 /// native backends allow the overlap; the null backend reports it as
1284 /// [`ValidationError::InterleavedEncoder`](crate::null::ValidationError::InterleavedEncoder),
1285 /// which is where a caller learns of it before a browser does.
1286 fn create_command_encoder(&self, desc: &CommandEncoderDesc<'_>) -> Box<dyn CommandEncoder>;
1287
1288 /// Releases a finished command buffer's resources.
1289 ///
1290 /// Must not be called until the submission that used it has completed.
1291 fn destroy_command_buffer(&self, buffer: CommandBufferHandle);
1292
1293 /// Submits work to a queue.
1294 ///
1295 /// The queue must be the one named in the command buffer's
1296 /// [`CommandEncoderDesc::queue`]: a command buffer is created against a
1297 /// specific queue family, and submitting it to another is a validation
1298 /// error on Vulkan. The null backend does not check the match.
1299 ///
1300 /// # Errors
1301 ///
1302 /// [`HalError::InvalidHandle`] or [`HalError::DeviceLost`].
1303 fn submit(&self, queue: QueueHandle, submit: &SubmitInfo<'_>) -> Result<(), HalError>;
1304
1305 // --- presentation ---
1306
1307 /// Configures a swapchain on a surface.
1308 ///
1309 /// # Errors
1310 ///
1311 /// [`SurfaceError::Lost`], or a [`HalError`] for an unsupported format or
1312 /// present mode.
1313 fn create_swapchain(&self, desc: &SwapchainDesc<'_>) -> Result<SwapchainHandle, SurfaceError>;
1314
1315 /// Reconfigures an existing swapchain — resize, present-mode change, format
1316 /// change.
1317 ///
1318 /// The handle stays valid, so nothing above has to re-fetch it across a
1319 /// resize storm. See the [module docs](crate::swapchain) on why this exists
1320 /// instead of destroy-and-recreate.
1321 ///
1322 /// # Errors
1323 ///
1324 /// [`SurfaceError::Lost`], or a [`HalError`] for an unsupported
1325 /// configuration.
1326 fn reconfigure_swapchain(
1327 &self,
1328 swapchain: SwapchainHandle,
1329 desc: &SwapchainDesc<'_>,
1330 ) -> Result<(), SurfaceError>;
1331
1332 /// Destroys a swapchain.
1333 fn destroy_swapchain(&self, swapchain: SwapchainHandle);
1334
1335 /// Acquires the next image to render into.
1336 ///
1337 /// The returned [`AcquiredFrame`] carries the synchronisation the backend
1338 /// needs, which is `None`/`None` on backends with an implicit acquire —
1339 /// see the [module docs](crate::swapchain) for why the seam is shaped this
1340 /// way rather than taking a caller-supplied semaphore.
1341 ///
1342 /// # Errors
1343 ///
1344 /// [`SurfaceError::OutOfDate`] after a resize — **expected traffic**;
1345 /// reconfigure and retry next frame. [`SurfaceError::Lost`] if the window is
1346 /// gone, [`SurfaceError::Timeout`] if no image became available.
1347 fn acquire_next_frame(&self, swapchain: SwapchainHandle)
1348 -> Result<AcquiredFrame, SurfaceError>;
1349
1350 /// Presents the acquired image.
1351 ///
1352 /// # Errors
1353 ///
1354 /// [`SurfaceError::OutOfDate`] or [`SurfaceError::Lost`], handled as for
1355 /// [`Device::acquire_next_frame`].
1356 fn present(&self, queue: QueueHandle, present: &PresentInfo<'_>) -> Result<(), SurfaceError>;
1357
1358 /// Blocks until the present numbered `present_id` has completed, so the
1359 /// caller can pace itself on the display rather than on a clock.
1360 ///
1361 /// `present_id` is one that was handed to [`present`](Self::present) as
1362 /// [`PresentInfo::present_id`]. **Ask for a frame or more back, never the
1363 /// one just submitted**: waiting on your own present drains the pipeline to
1364 /// a single frame and costs more than not waiting at all.
1365 ///
1366 /// # What "completed" means, and why it is not spelled more precisely
1367 ///
1368 /// The three platforms that can answer this answer slightly different
1369 /// questions — one knows a numbered image reached the display, one only
1370 /// knows that fewer than *n* presents are still outstanding, one calls back
1371 /// once a drawable has been shown. The guarantee the seam takes from all
1372 /// three is the weakest of them and the only one a frame loop needs: **when
1373 /// this returns, the numbered present is no longer waiting to happen**. A
1374 /// caller that needs a timestamp needs a different method, which does not
1375 /// exist yet.
1376 ///
1377 /// # A device without the capability is not an error
1378 ///
1379 /// Returns `Ok(())` immediately, without blocking, on a device that does
1380 /// not advertise [`Features::PRESENT_FEEDBACK`] — "there is nothing here to
1381 /// wait for", not "this call was wrong". The alternative, refusing, would
1382 /// put a branch on every frame of every caller for a condition that never
1383 /// changes after device creation, and a caller that skipped the branch
1384 /// would turn a missing capability into a failed frame. A caller that
1385 /// genuinely wants to know reads the flag once, at start-up.
1386 ///
1387 /// The same answer covers a `present_id` the backend has no record of —
1388 /// never presented, or presented before the last
1389 /// [`reconfigure_swapchain`](Self::reconfigure_swapchain), which restarts
1390 /// the numbering. That frame can no longer be waited for, and blocking
1391 /// until `timeout` for one that will never arrive is the worst of the
1392 /// available answers.
1393 ///
1394 /// # Errors
1395 ///
1396 /// [`SurfaceError::Timeout`] if `timeout` passed with the frame still not
1397 /// up — **expected traffic** on a stalled compositor, and not a reason to
1398 /// abandon the frame; render it and let the next wait catch up.
1399 /// [`SurfaceError::OutOfDate`] or [`SurfaceError::Lost`], handled as for
1400 /// [`Device::acquire_next_frame`].
1401 fn wait_until_presented(
1402 &self,
1403 swapchain: SwapchainHandle,
1404 present_id: u64,
1405 timeout: Duration,
1406 ) -> Result<(), SurfaceError>;
1407
1408 /// Asks what the display is **actually** doing with this swapchain's
1409 /// frames — fixed refresh, adaptive sync, or nothing it will say.
1410 ///
1411 /// [`PresentMode`](crate::PresentMode) is the request side of this: it picks a queueing
1412 /// discipline and tells you nothing about the panel. This is the answer,
1413 /// and it is the only thing in the seam that can tell a 60 Hz panel from a
1414 /// VRR one holding steady at 60 Hz. See [`DisplayTiming`] for what each arm
1415 /// promises.
1416 ///
1417 /// # This is a live query; caching it is a bug
1418 ///
1419 /// The answer changes underneath a swapchain that is running perfectly
1420 /// well, with no reconfigure and no error: the proposal's own example is a
1421 /// laptop entering power-saving mode and dropping the panel's rate, and
1422 /// dragging a window to a second monitor does the same thing. **Ask again**
1423 /// — every frame is fine, the query is a read of driver-side state — rather
1424 /// than reading it once at start-up as a caller may legitimately do with
1425 /// [`DeviceCaps::features`](crate::DeviceCaps::features).
1426 ///
1427 /// # A device without the capability is not an error
1428 ///
1429 /// Returns `Ok(DisplayTiming::Unknown)` on a device that does not advertise
1430 /// [`Features::PRESENT_TIMING`], exactly as
1431 /// [`wait_until_presented`](Self::wait_until_presented) returns `Ok(())`
1432 /// without [`Features::PRESENT_FEEDBACK`] — "there is nothing here to
1433 /// report", not "this call was wrong". [`DisplayTiming::Unknown`] is
1434 /// already an arm every caller must handle, so refusing would buy a second
1435 /// spelling of the same answer and a branch on every use.
1436 ///
1437 /// The same answer covers a swapchain that has never been presented to (the
1438 /// platform may not know yet), one that has no display behind it at all
1439 /// (an offscreen ring), and a platform that reports a cycle length without
1440 /// its dynamics.
1441 ///
1442 /// # Errors
1443 ///
1444 /// [`SurfaceError::Hal`] wrapping [`HalError::ForeignObject`] for a
1445 /// `swapchain` created by a different device, per obligation 3, and
1446 /// [`HalError::InvalidHandle`] for one that has been destroyed —
1447 /// **validated before the capability is consulted**, so a backend that
1448 /// cannot answer still catches the caller bug. [`SurfaceError::Lost`] if
1449 /// the window is gone.
1450 fn display_timing(&self, swapchain: SwapchainHandle) -> Result<DisplayTiming, SurfaceError>;
1451}
1452
1453#[cfg(test)]
1454mod tests {
1455 use super::*;
1456
1457 /// A granted capability drags in what it cannot be enabled without.
1458 ///
1459 /// The case is a caller naming one half of a pair — `RAY_QUERY` without the
1460 /// acceleration structure it traverses, `TASK_SHADER` without the mesh
1461 /// stage it feeds. The adapter never reports those halves apart, so the
1462 /// gap opens at the intersection with the request, and a device created
1463 /// from the gapped set would report caps describing one that cannot exist.
1464 #[test]
1465 fn a_granted_capability_carries_what_it_cannot_be_enabled_without() {
1466 // A request for `asked` alone on an adapter with every feature: what
1467 // comes back beyond `asked` is a dependency the rule added.
1468 let granted_on_everything = |asked: Features| {
1469 DeviceDesc {
1470 optional_features: asked,
1471 required_features: Features::empty(),
1472 ..DeviceDesc::for_adapter(AdapterId(0))
1473 }
1474 .granted(Features::all())
1475 };
1476 assert_eq!(
1477 granted_on_everything(Features::RAY_QUERY),
1478 Features::RAY_QUERY | Features::ACCELERATION_STRUCTURE
1479 );
1480 assert_eq!(
1481 granted_on_everything(Features::RAY_TRACING_PIPELINE),
1482 Features::RAY_TRACING_PIPELINE | Features::ACCELERATION_STRUCTURE
1483 );
1484 assert_eq!(
1485 granted_on_everything(Features::TASK_SHADER),
1486 Features::TASK_SHADER | Features::MESH_SHADER
1487 );
1488
1489 // Nothing is invented in the other direction: an acceleration
1490 // structure on its own is a perfectly good thing to ask for, and a
1491 // mesh stage does not imply a task stage in front of it.
1492 assert_eq!(
1493 granted_on_everything(Features::ACCELERATION_STRUCTURE),
1494 Features::ACCELERATION_STRUCTURE
1495 );
1496 assert_eq!(
1497 granted_on_everything(Features::MESH_SHADER),
1498 Features::MESH_SHADER
1499 );
1500 // And a set with none of them is returned untouched, which is every
1501 // caller that predates this slice.
1502 assert_eq!(
1503 granted_on_everything(Features::GPU_DRIVEN),
1504 Features::GPU_DRIVEN
1505 );
1506 assert_eq!(granted_on_everything(Features::empty()), Features::empty());
1507 }
1508
1509 /// Only what was asked for: a feature the adapter has and nobody asked for
1510 /// is not granted, a required one is, and an asked-for one the adapter
1511 /// lacks is not.
1512 #[test]
1513 fn a_device_is_granted_what_was_asked_of_what_the_adapter_has() {
1514 let desc = DeviceDesc {
1515 required_features: Features::COMPUTE,
1516 optional_features: Features::MESH_SHADER | Features::RAY_QUERY,
1517 ..DeviceDesc::for_adapter(AdapterId(0))
1518 };
1519 let adapter = Features::COMPUTE | Features::MESH_SHADER | Features::TASK_SHADER;
1520 assert_eq!(
1521 desc.granted(adapter),
1522 Features::COMPUTE | Features::MESH_SHADER,
1523 "the task stage was not asked for and the ray query is not there"
1524 );
1525 }
1526
1527 /// The crate's central claim: both traits are usable as trait objects. If
1528 /// anyone adds a generic method, an `impl Trait` return, or a
1529 /// `where Self: Sized`, this stops compiling — which is the point.
1530 #[test]
1531 fn the_seam_is_object_safe() {
1532 const _INSTANCE: Option<&dyn Instance> = None;
1533 const _DEVICE: Option<&dyn Device> = None;
1534 const _ENCODER: Option<&dyn CommandEncoder> = None;
1535 const _PENDING: Option<&dyn PendingDevice> = None;
1536 // Boxing each one is the property that matters; naming all three in a
1537 // single function type only trips `clippy::type_complexity`.
1538 fn boxes_instance(_: Box<dyn Instance>) {}
1539 fn boxes_device(_: Box<dyn Device>) {}
1540 fn boxes_encoder(_: Box<dyn CommandEncoder>) {}
1541 fn boxes_pending(_: Box<dyn PendingDevice>) {}
1542 let _ = (
1543 boxes_instance as fn(_),
1544 boxes_device as fn(_),
1545 boxes_encoder as fn(_),
1546 boxes_pending as fn(_),
1547 );
1548 }
1549
1550 /// `DeviceRequestState` answers two things, not three: the payload rides in
1551 /// `Ready` and failure leaves through `Err`, exactly as `ReadbackState` does.
1552 #[test]
1553 fn a_pending_request_yields_nothing_and_says_so() {
1554 let pending = DeviceRequestState::Pending;
1555 assert!(!pending.is_ready());
1556 assert!(pending.into_device().is_none());
1557 }
1558
1559 #[test]
1560 fn default_device_desc_requires_only_the_unavoidable_and_no_surface() {
1561 let desc = DeviceDesc::for_adapter(AdapterId(0));
1562 assert_eq!(
1563 desc.required_features,
1564 Features::COMPUTE | Features::TIMELINE_SEMAPHORE
1565 );
1566 assert!(
1567 desc.compatible_surface.is_none(),
1568 "the headless shape must not require a window"
1569 );
1570 assert_eq!(desc.optional_features, Features::GPU_DRIVEN);
1571 // The point of the split: everything the GPU-driven path wants beyond
1572 // the two above degrades instead of refusing the device. Named one at a
1573 // time, because a bundle comparison would still pass if one flag leaked
1574 // back across the line.
1575 for optional in [
1576 Features::DESCRIPTOR_INDEXING,
1577 Features::BUFFER_DEVICE_ADDRESS,
1578 Features::DRAW_INDIRECT_COUNT,
1579 Features::MULTI_DRAW_INDIRECT,
1580 ] {
1581 assert!(
1582 !desc.required_features.contains(optional),
1583 "{optional:?} must be optional, not demanded"
1584 );
1585 }
1586 }
1587}