use std::time::Duration;
use crate::{
AcquiredFrame, AdapterId, AdapterInfo, BackendKind, BindGroupDesc, BindGroupHandle,
BindGroupLayoutDesc, BindGroupLayoutHandle, BufferDesc, BufferHandle, CommandBufferHandle,
CommandEncoder, CommandEncoderDesc, ComputePipelineDesc, ComputePipelineHandle, DeviceCaps,
DisplayTiming, Features, GraphicsPipelineDesc, GraphicsPipelineHandle, HalError, ImageDesc,
ImageHandle, ImageViewDesc, ImageViewHandle, PipelineLayoutDesc, PipelineLayoutHandle,
PresentInfo, QuerySetDesc, QuerySetHandle, ReadbackDesc, ReadbackHandle, ReadbackState,
SamplerDesc, SamplerHandle, SemaphoreDesc, SemaphoreHandle, ShaderModuleDesc,
ShaderModuleHandle, SubmitInfo, SurfaceCaps, SurfaceError, SurfaceHandle, SwapchainDesc,
SwapchainHandle,
};
use crcbl_core::{Handle, SurfaceTarget};
#[derive(Debug)]
pub enum Queue {}
pub type QueueHandle = Handle<Queue>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum QueueKind {
Graphics,
Compute,
Transfer,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DeviceDesc<'a> {
pub label: Option<&'a str>,
pub adapter: AdapterId,
pub required_features: Features,
pub optional_features: Features,
pub compatible_surface: Option<SurfaceHandle>,
}
impl DeviceDesc<'_> {
#[must_use]
pub const fn for_adapter(adapter: AdapterId) -> Self {
Self {
label: None,
adapter,
required_features: Features::COMPUTE.union(Features::TIMELINE_SEMAPHORE),
optional_features: Features::GPU_DRIVEN,
compatible_surface: None,
}
}
#[must_use]
pub fn granted(&self, adapter: Features) -> Features {
let mut granted = adapter
.intersection(self.required_features.union(self.optional_features))
.union(self.required_features);
if granted.contains(Features::TASK_SHADER) {
granted |= Features::MESH_SHADER;
}
if granted.intersects(Features::RAY_QUERY | Features::RAY_TRACING_PIPELINE) {
granted |= Features::ACCELERATION_STRUCTURE;
}
granted
}
}
pub trait Instance: core::fmt::Debug + crate::threading::HalThreadSafe {
fn backend(&self) -> BackendKind;
fn adapters(&self) -> Vec<AdapterInfo>;
fn adapter_caps(&self, adapter: AdapterId) -> Result<DeviceCaps, HalError>;
unsafe fn create_surface(&self, target: &SurfaceTarget) -> Result<SurfaceHandle, HalError>;
fn destroy_surface(&self, surface: SurfaceHandle);
fn surface_caps(
&self,
surface: SurfaceHandle,
adapter: AdapterId,
) -> Result<SurfaceCaps, HalError>;
fn display_adapter(&self, surface: SurfaceHandle) -> Result<Option<AdapterId>, HalError>;
fn request_device(&self, desc: &DeviceDesc<'_>) -> Result<Box<dyn PendingDevice>, HalError>;
#[cfg(not(target_arch = "wasm32"))]
fn create_device(&self, desc: &DeviceDesc<'_>) -> Result<Box<dyn Device>, HalError> {
let mut pending = self.request_device(desc)?;
loop {
match pending.poll()? {
DeviceRequestState::Ready(device) => return Ok(device),
DeviceRequestState::Pending => std::thread::yield_now(),
}
}
}
}
pub trait PendingDevice: core::fmt::Debug + crate::threading::HalThreadSafe {
fn backend(&self) -> BackendKind;
fn poll(&mut self) -> Result<DeviceRequestState, HalError>;
}
#[derive(Debug)]
pub enum DeviceRequestState {
Pending,
Ready(Box<dyn Device>),
}
impl DeviceRequestState {
#[must_use]
pub const fn is_ready(&self) -> bool {
matches!(self, Self::Ready(_))
}
#[must_use]
pub fn into_device(self) -> Option<Box<dyn Device>> {
match self {
Self::Ready(device) => Some(device),
Self::Pending => None,
}
}
}
pub trait Device: core::fmt::Debug + crate::threading::HalThreadSafe {
fn backend(&self) -> BackendKind;
fn caps(&self) -> DeviceCaps;
fn preferred_geometry_path(&self) -> crate::GeometryPath {
self.caps().geometry_path()
}
fn supports(&self, capability: crate::Capability) -> crate::Support;
fn queue(&self, kind: QueueKind) -> Option<QueueHandle>;
fn take_error(&self) -> Option<String> {
None
}
fn create_buffer(&self, desc: &BufferDesc<'_>) -> Result<BufferHandle, HalError>;
fn destroy_buffer(&self, buffer: BufferHandle);
fn write_buffer(&self, buffer: BufferHandle, offset: u64, data: &[u8]) -> Result<(), HalError>;
fn request_readback(&self, desc: &ReadbackDesc<'_>) -> Result<ReadbackHandle, HalError>;
fn poll_readback(
&self,
readback: ReadbackHandle,
out: &mut [u8],
) -> Result<ReadbackState, HalError>;
fn destroy_readback(&self, readback: ReadbackHandle);
fn create_image(&self, desc: &ImageDesc<'_>) -> Result<ImageHandle, HalError>;
fn destroy_image(&self, image: ImageHandle);
fn create_image_view(&self, desc: &ImageViewDesc<'_>) -> Result<ImageViewHandle, HalError>;
fn destroy_image_view(&self, view: ImageViewHandle);
fn create_sampler(&self, desc: &SamplerDesc<'_>) -> Result<SamplerHandle, HalError>;
fn destroy_sampler(&self, sampler: SamplerHandle);
fn create_shader_module(
&self,
desc: &ShaderModuleDesc<'_>,
) -> Result<ShaderModuleHandle, HalError>;
fn destroy_shader_module(&self, module: ShaderModuleHandle);
fn create_bind_group_layout(
&self,
desc: &BindGroupLayoutDesc<'_>,
) -> Result<BindGroupLayoutHandle, HalError>;
fn destroy_bind_group_layout(&self, layout: BindGroupLayoutHandle);
fn create_bind_group(&self, desc: &BindGroupDesc<'_>) -> Result<BindGroupHandle, HalError>;
fn update_bind_group(
&self,
group: BindGroupHandle,
entries: &[crate::BindGroupEntry],
) -> Result<(), HalError>;
fn destroy_bind_group(&self, group: BindGroupHandle);
fn create_pipeline_layout(
&self,
desc: &PipelineLayoutDesc<'_>,
) -> Result<PipelineLayoutHandle, HalError>;
fn destroy_pipeline_layout(&self, layout: PipelineLayoutHandle);
fn create_graphics_pipeline(
&self,
desc: &GraphicsPipelineDesc<'_>,
) -> Result<GraphicsPipelineHandle, HalError>;
fn create_mesh_pipeline(
&self,
desc: &crate::MeshPipelineDesc<'_>,
) -> Result<GraphicsPipelineHandle, HalError>;
fn destroy_graphics_pipeline(&self, pipeline: GraphicsPipelineHandle);
fn create_compute_pipeline(
&self,
desc: &ComputePipelineDesc<'_>,
) -> Result<ComputePipelineHandle, HalError>;
fn destroy_compute_pipeline(&self, pipeline: ComputePipelineHandle);
fn create_query_set(&self, desc: &QuerySetDesc<'_>) -> Result<QuerySetHandle, HalError>;
fn destroy_query_set(&self, set: QuerySetHandle);
fn query_results(
&self,
set: QuerySetHandle,
first_query: u32,
out: &mut [u64],
) -> Result<(), HalError>;
fn pipeline_statistics(
&self,
set: QuerySetHandle,
first_query: u32,
out: &mut [crate::PipelineStatistics],
) -> Result<(), HalError> {
let _ = (set, first_query, out);
Err(HalError::Unsupported {
backend: self.backend(),
what: crate::NO_PIPELINE_STATISTICS,
})
}
fn gpu_clock(&self) -> Result<u64, HalError> {
Err(HalError::Unsupported {
backend: self.backend(),
what: crate::NO_GPU_CLOCK,
})
}
fn create_semaphore(&self, desc: &SemaphoreDesc<'_>) -> Result<SemaphoreHandle, HalError>;
fn destroy_semaphore(&self, semaphore: SemaphoreHandle);
fn semaphore_value(&self, semaphore: SemaphoreHandle) -> Result<u64, HalError>;
fn signal_semaphore(&self, semaphore: SemaphoreHandle, value: u64) -> Result<(), HalError>;
fn wait_semaphores(
&self,
waits: &[crate::SemaphoreWait],
timeout_ns: u64,
) -> Result<bool, HalError>;
fn wait_idle(&self) -> Result<(), HalError>;
fn create_command_encoder(&self, desc: &CommandEncoderDesc<'_>) -> Box<dyn CommandEncoder>;
fn destroy_command_buffer(&self, buffer: CommandBufferHandle);
fn submit(&self, queue: QueueHandle, submit: &SubmitInfo<'_>) -> Result<(), HalError>;
fn create_swapchain(&self, desc: &SwapchainDesc<'_>) -> Result<SwapchainHandle, SurfaceError>;
fn reconfigure_swapchain(
&self,
swapchain: SwapchainHandle,
desc: &SwapchainDesc<'_>,
) -> Result<(), SurfaceError>;
fn destroy_swapchain(&self, swapchain: SwapchainHandle);
fn acquire_next_frame(&self, swapchain: SwapchainHandle)
-> Result<AcquiredFrame, SurfaceError>;
fn present(&self, queue: QueueHandle, present: &PresentInfo<'_>) -> Result<(), SurfaceError>;
fn wait_until_presented(
&self,
swapchain: SwapchainHandle,
present_id: u64,
timeout: Duration,
) -> Result<(), SurfaceError>;
fn display_timing(&self, swapchain: SwapchainHandle) -> Result<DisplayTiming, SurfaceError>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_granted_capability_carries_what_it_cannot_be_enabled_without() {
let granted_on_everything = |asked: Features| {
DeviceDesc {
optional_features: asked,
required_features: Features::empty(),
..DeviceDesc::for_adapter(AdapterId(0))
}
.granted(Features::all())
};
assert_eq!(
granted_on_everything(Features::RAY_QUERY),
Features::RAY_QUERY | Features::ACCELERATION_STRUCTURE
);
assert_eq!(
granted_on_everything(Features::RAY_TRACING_PIPELINE),
Features::RAY_TRACING_PIPELINE | Features::ACCELERATION_STRUCTURE
);
assert_eq!(
granted_on_everything(Features::TASK_SHADER),
Features::TASK_SHADER | Features::MESH_SHADER
);
assert_eq!(
granted_on_everything(Features::ACCELERATION_STRUCTURE),
Features::ACCELERATION_STRUCTURE
);
assert_eq!(
granted_on_everything(Features::MESH_SHADER),
Features::MESH_SHADER
);
assert_eq!(
granted_on_everything(Features::GPU_DRIVEN),
Features::GPU_DRIVEN
);
assert_eq!(granted_on_everything(Features::empty()), Features::empty());
}
#[test]
fn a_device_is_granted_what_was_asked_of_what_the_adapter_has() {
let desc = DeviceDesc {
required_features: Features::COMPUTE,
optional_features: Features::MESH_SHADER | Features::RAY_QUERY,
..DeviceDesc::for_adapter(AdapterId(0))
};
let adapter = Features::COMPUTE | Features::MESH_SHADER | Features::TASK_SHADER;
assert_eq!(
desc.granted(adapter),
Features::COMPUTE | Features::MESH_SHADER,
"the task stage was not asked for and the ray query is not there"
);
}
#[test]
fn the_seam_is_object_safe() {
const _INSTANCE: Option<&dyn Instance> = None;
const _DEVICE: Option<&dyn Device> = None;
const _ENCODER: Option<&dyn CommandEncoder> = None;
const _PENDING: Option<&dyn PendingDevice> = None;
fn boxes_instance(_: Box<dyn Instance>) {}
fn boxes_device(_: Box<dyn Device>) {}
fn boxes_encoder(_: Box<dyn CommandEncoder>) {}
fn boxes_pending(_: Box<dyn PendingDevice>) {}
let _ = (
boxes_instance as fn(_),
boxes_device as fn(_),
boxes_encoder as fn(_),
boxes_pending as fn(_),
);
}
#[test]
fn a_pending_request_yields_nothing_and_says_so() {
let pending = DeviceRequestState::Pending;
assert!(!pending.is_ready());
assert!(pending.into_device().is_none());
}
#[test]
fn default_device_desc_requires_only_the_unavoidable_and_no_surface() {
let desc = DeviceDesc::for_adapter(AdapterId(0));
assert_eq!(
desc.required_features,
Features::COMPUTE | Features::TIMELINE_SEMAPHORE
);
assert!(
desc.compatible_surface.is_none(),
"the headless shape must not require a window"
);
assert_eq!(desc.optional_features, Features::GPU_DRIVEN);
for optional in [
Features::DESCRIPTOR_INDEXING,
Features::BUFFER_DEVICE_ADDRESS,
Features::DRAW_INDIRECT_COUNT,
Features::MULTI_DRAW_INDIRECT,
] {
assert!(
!desc.required_features.contains(optional),
"{optional:?} must be optional, not demanded"
);
}
}
}