Skip to main content

crcbl_hal/
device.rs

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