#[cfg(not(target_arch = "wasm32"))]
use crcbl_hal::BackendKind;
use crcbl_hal::{ComputePipelineHandle, Device, GraphicsPipelineHandle};
#[cfg(not(target_arch = "wasm32"))]
use crcbl_jobs::{Pool, Spawn};
#[cfg(not(target_arch = "wasm32"))]
const MAX_JOBS_PER_ROUND: usize = 4;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) type Job<'a, R> = dyn Fn() -> R + Sync + 'a;
#[cfg(target_arch = "wasm32")]
pub(crate) type Job<'a, R> = dyn Fn() -> R + 'a;
#[derive(Clone, Copy, Debug)]
pub(crate) enum Pipeline {
Graphics(GraphicsPipelineHandle),
Compute(ComputePipelineHandle),
}
impl Pipeline {
pub(crate) fn graphics(self) -> GraphicsPipelineHandle {
match self {
Self::Graphics(pipeline) => pipeline,
Self::Compute(_) => panic!("a graphics member of the batch made a compute pipeline"),
}
}
pub(crate) fn compute(self) -> ComputePipelineHandle {
match self {
Self::Compute(pipeline) => pipeline,
Self::Graphics(_) => panic!("a compute member of the batch made a graphics pipeline"),
}
}
}
impl From<Pipeline> for crate::partial::Created {
fn from(pipeline: Pipeline) -> Self {
match pipeline {
Pipeline::Graphics(pipeline) => pipeline.into(),
Pipeline::Compute(pipeline) => pipeline.into(),
}
}
}
pub(crate) fn create<R, const N: usize>(
device: &dyn Device,
service: &mut dyn FnMut(),
jobs: [&Job<'_, R>; N],
) -> [R; N]
where
R: crcbl_hal::threading::HalThreadSafe,
{
create_listed(device, service, &jobs)
.try_into()
.unwrap_or_else(|_| unreachable!("one result per job"))
}
pub(crate) fn create_listed<R>(
device: &dyn Device,
service: &mut dyn FnMut(),
jobs: &[&Job<'_, R>],
) -> Vec<R>
where
R: crcbl_hal::threading::HalThreadSafe,
{
#[cfg(not(target_arch = "wasm32"))]
if concurrent(device)
&& let Some(pool) = pool_for(crcbl_jobs::default_spawner().as_ref(), jobs.len())
{
return in_parallel(pool, service, jobs);
}
#[cfg(target_arch = "wasm32")]
let _ = device;
in_order(service, jobs)
}
#[cfg(not(target_arch = "wasm32"))]
fn concurrent(device: &dyn Device) -> bool {
match device.backend() {
BackendKind::Vulkan | BackendKind::Dx12 | BackendKind::Metal => true,
BackendKind::WebGpu | BackendKind::Null => false,
}
}
#[cfg(not(target_arch = "wasm32"))]
fn pool_for(spawner: &dyn Spawn, jobs: usize) -> Option<Pool> {
let workers = jobs
.min(MAX_JOBS_PER_ROUND)
.min(spawner.parallelism().get())
.saturating_sub(1);
if workers == 0 {
return None;
}
Pool::with_workers(spawner, workers)
.ok()
.filter(|pool| pool.workers() > 0)
}
fn in_order<R>(service: &mut dyn FnMut(), jobs: &[&Job<'_, R>]) -> Vec<R> {
jobs.iter()
.map(|job| {
service();
job()
})
.collect()
}
#[cfg(not(target_arch = "wasm32"))]
fn in_parallel<R>(mut pool: Pool, service: &mut dyn FnMut(), jobs: &[&Job<'_, R>]) -> Vec<R>
where
R: Send,
{
let round = (pool.workers() + 1).min(MAX_JOBS_PER_ROUND);
let mut slots: Vec<Option<R>> = jobs.iter().map(|_| None).collect();
for (round_jobs, round_slots) in jobs.chunks(round).zip(slots.chunks_mut(round)) {
service();
pool.par_for(round_slots, 1, |index, slot| {
slot[0] = Some(round_jobs[index]());
});
}
slots
.into_iter()
.map(|slot| slot.unwrap_or_else(|| unreachable!("par_for runs every chunk once")))
.collect()
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use core::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use super::*;
use crate::draw_gen::compute_pipeline;
use crcbl_hal::null::{NullInstance, Recorder};
use crcbl_hal::{
AdapterId, ComputePipelineHandle, DeviceDesc, HalError, Instance, PipelineLayoutDesc,
PipelineLayoutHandle,
};
use crcbl_jobs::SpawnError;
use crcbl_shaders::{CLEAR_COUNTERS, clear_counters};
const OVERLAP_PATIENCE: Duration = Duration::from_secs(10);
fn open() -> (Recorder, Box<dyn Device>) {
let recorder = Recorder::new();
let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
let device = instance
.create_device(&DeviceDesc::for_adapter(AdapterId(0)))
.expect("the null device opens");
(recorder, device)
}
fn layout(device: &dyn Device, label: &str) -> PipelineLayoutHandle {
device
.create_pipeline_layout(&PipelineLayoutDesc {
label: Some(label),
bind_group_layouts: &[],
push_constants: None,
})
.expect("an empty layout is created")
}
fn labelled(
device: &dyn Device,
label: &'static str,
layout: PipelineLayoutHandle,
) -> Result<(&'static str, ComputePipelineHandle), HalError> {
compute_pipeline(
device,
label,
&CLEAR_COUNTERS,
layout,
clear_counters::WORKGROUP_SIZE,
)
.map(|pipeline| (label, pipeline))
}
#[test]
fn the_parallel_path_overlaps_and_keeps_every_success_in_its_slot() {
let (recorder, device) = open();
let device = device.as_ref();
let layout = layout(device, "batch");
let gone = self::layout(device, "gone");
device.destroy_pipeline_layout(gone);
let before = recorder.total_live_objects();
let first_running = AtomicBool::new(false);
let other_beside = AtomicBool::new(false);
let wait_for = |flag: &AtomicBool| {
let deadline = Instant::now() + OVERLAP_PATIENCE;
while !flag.load(Ordering::Acquire) && Instant::now() < deadline {
std::thread::yield_now();
}
flag.load(Ordering::Acquire)
};
let first = || {
first_running.store(true, Ordering::Release);
let overlapped = wait_for(&other_beside);
first_running.store(false, Ordering::Release);
labelled(device, "a", layout).map(|made| (made, overlapped))
};
let other = |label: &'static str, layout| {
let (first_running, other_beside) = (&first_running, &other_beside);
move || {
if label == "b" && wait_for(first_running) {
other_beside.store(true, Ordering::Release);
}
labelled(device, label, layout).map(|made| (made, true))
}
};
let (b, refused, c, d) = (
other("b", layout),
other("refused", gone),
other("c", layout),
other("d", layout),
);
let jobs: [&Job<'_, _>; 5] = [&first, &b, &refused, &c, &d];
let pool = Pool::with_workers(
crcbl_jobs::default_spawner().as_ref(),
MAX_JOBS_PER_ROUND - 1,
)
.expect("the test's pool starts");
assert!(pool.workers() > 0, "this test needs a threaded runtime");
let mut services = 0;
let results = in_parallel(pool, &mut || services += 1, &jobs);
assert_eq!(
services,
jobs.len().div_ceil(MAX_JOBS_PER_ROUND),
"`service` before each round"
);
assert!(
results[0].as_ref().is_ok_and(|(_, overlapped)| *overlapped),
"the first job finished without another having started beside it, \
so the batch ran serially: {results:?}"
);
assert!(
matches!(results[2], Err(HalError::InvalidHandle { .. })),
"the member naming a destroyed layout is refused: {results:?}"
);
let made: Vec<(&str, ComputePipelineHandle)> =
results.iter().flatten().map(|(made, _)| *made).collect();
assert_eq!(
made.iter().map(|(label, _)| *label).collect::<Vec<_>>(),
["a", "b", "c", "d"],
"every other member made its pipeline and is in its own slot"
);
for (_, pipeline) in made {
device.destroy_compute_pipeline(pipeline);
}
assert_eq!(
recorder.total_live_objects(),
before,
"releasing what the batch handed back released everything it made"
);
device.destroy_pipeline_layout(layout);
recorder.assert_valid();
}
#[test]
fn a_batch_of_several_rounds_keeps_every_result_in_its_slot() {
let (recorder, device) = open();
let device = device.as_ref();
let layout = layout(device, "batch");
let job = |label: &'static str| move || labelled(device, label, layout);
let (a, b, c, d, e) = (job("a"), job("b"), job("c"), job("d"), job("e"));
let pool = Pool::with_workers(crcbl_jobs::default_spawner().as_ref(), 1)
.expect("the test's pool starts");
assert_eq!(pool.workers(), 1, "this test needs a threaded runtime");
let mut services = 0;
let results = in_parallel(pool, &mut || services += 1, &[&a, &b, &c, &d, &e]);
assert_eq!(
services, 3,
"rounds of two, three of them, `service` before each"
);
let labels: Vec<&str> = results
.iter()
.map(|result| result.as_ref().expect("each member is created").0)
.collect();
assert_eq!(
labels,
["a", "b", "c", "d", "e"],
"each result in its job's slot"
);
for result in results {
device.destroy_compute_pipeline(result.expect("checked above").1);
}
device.destroy_pipeline_layout(layout);
recorder.assert_valid();
}
#[derive(Debug)]
struct Refuses;
#[derive(Debug)]
struct Unthreaded;
impl Spawn for Unthreaded {
fn threaded(&self) -> bool {
false
}
fn parallelism(&self) -> core::num::NonZeroUsize {
core::num::NonZeroUsize::new(8).expect("eight is not zero")
}
fn spawn(&self, name: &'static str, work: crcbl_jobs::Work) -> Result<(), SpawnError> {
drop(work);
Err(SpawnError::NoThreads(name))
}
}
impl Spawn for Refuses {
fn threaded(&self) -> bool {
true
}
fn parallelism(&self) -> core::num::NonZeroUsize {
core::num::NonZeroUsize::new(8).expect("eight is not zero")
}
fn spawn(&self, name: &'static str, work: crcbl_jobs::Work) -> Result<(), SpawnError> {
drop(work);
Err(SpawnError::NoThreads(name))
}
}
#[test]
fn a_batch_without_threads_falls_back_to_serial() {
assert!(
pool_for(&crcbl_jobs::Inline, 5).is_none(),
"a runtime with no threads"
);
assert!(
pool_for(&Unthreaded, 5).is_none(),
"a runtime with cores and no threads"
);
assert!(pool_for(&Refuses, 5).is_none(), "a refused thread");
let spawner = crcbl_jobs::default_spawner();
assert!(pool_for(spawner.as_ref(), 1).is_none(), "a batch of one");
if spawner.parallelism().get() >= MAX_JOBS_PER_ROUND {
let pool = pool_for(spawner.as_ref(), 5).expect("a threaded runtime gets a pool");
assert_eq!(
pool.workers() + 1,
MAX_JOBS_PER_ROUND,
"the pool is as wide as a round and no wider"
);
}
}
#[test]
fn the_null_device_creates_a_batch_in_order_on_the_calling_thread() {
let (recorder, device) = open();
let device = device.as_ref();
let layout = layout(device, "batch");
let caller = std::thread::current().id();
let job = |label: &'static str| {
move || {
let here = std::thread::current().id() == caller;
labelled(device, label, layout).map(|made| (made, here))
}
};
let (a, b, c) = (job("a"), job("b"), job("c"));
let mut services = 0;
let results = create(device, &mut || services += 1, [&a, &b, &c]);
assert_eq!(services, 3, "`service` before each of the three");
let made: Vec<(&str, bool)> = results
.iter()
.map(|result| {
let ((label, _), here) = result.as_ref().expect("each member is created");
(*label, *here)
})
.collect();
assert_eq!(made, [("a", true), ("b", true), ("c", true)]);
let created: Vec<Option<String>> = recorder
.pipelines_created()
.into_iter()
.map(|record| record.label)
.collect();
assert_eq!(
created,
[Some("a".into()), Some("b".into()), Some("c".into())],
"the device saw them in the jobs' order"
);
for result in results {
let ((_, pipeline), _) = result.expect("checked above");
device.destroy_compute_pipeline(pipeline);
}
device.destroy_pipeline_layout(layout);
recorder.assert_valid();
}
}