Skip to main content

spatialrust_gpu/
runtime.rs

1#[cfg(not(target_arch = "wasm32"))]
2use std::sync::Arc;
3use std::sync::OnceLock;
4
5#[cfg(feature = "gpu-image")]
6use std::sync::Mutex;
7
8use spatialrust_core::{DeviceKind, SpatialError, SpatialResult, SpatialRuntime};
9
10use crate::pipeline_cache::ComputePipelineCache;
11use crate::resource_cache::GpuResourcePoolStats;
12#[cfg(feature = "gpu-image")]
13use crate::resource_cache::{ResourceCache, DEFAULT_GPU_POOL_BUDGET_BYTES};
14use crate::upload_cache::GpuBufferPool;
15
16/// Headless wgpu runtime for compute-only workloads.
17#[cfg(feature = "gpu-wgpu")]
18pub struct WgpuRuntime {
19    _instance: wgpu::Instance,
20    device: wgpu::Device,
21    queue: wgpu::Queue,
22    pipelines: OnceLock<ComputePipelineCache>,
23    pub(crate) voxel_scan_pipelines: OnceLock<crate::kernels::PrefixScanPipelines>,
24    pub(crate) ransac_plane_pipelines: OnceLock<crate::kernels::RansacPlanePipelines>,
25    pub(crate) cluster_pipelines: OnceLock<crate::kernels::cluster_union::ClusterPipelines>,
26    pub(crate) nearest_pipeline: OnceLock<crate::kernels::nearest::NearestPipeline>,
27    pub(crate) tree_gather_pipeline:
28        OnceLock<crate::kernels::nearest::tree_gpu_gather::TreeGatherPipeline>,
29    pub(crate) neighborhood_pipelines: OnceLock<crate::kernels::nearest::NeighborhoodPipelines>,
30    pub(crate) fpfh_pipelines: OnceLock<crate::kernels::fpfh::FpfhPipelines>,
31    pub(crate) fpfh_sample_pipeline:
32        OnceLock<crate::kernels::fpfh::sample_gather::FpfhSamplePipeline>,
33    pub(crate) iss_pipelines: OnceLock<crate::kernels::iss::IssPipelines>,
34    pub(crate) mls_pipelines: OnceLock<crate::kernels::mls::MlsPipelines>,
35    pub(crate) icp_reduction_pipelines:
36        OnceLock<crate::kernels::icp_reduction::IcpReductionPipelines>,
37    pub(crate) icp_trim_pipelines: OnceLock<crate::kernels::icp_reduction::trim::TrimPipelines>,
38    pub(crate) point_to_plane_reduction_pipelines:
39        OnceLock<crate::kernels::point_to_plane_reduction::PointToPlaneReductionPipelines>,
40    pub(crate) gicp_covariance_pipelines:
41        OnceLock<crate::kernels::gicp_reduction::resident_covariances::GicpCovariancePipelines>,
42    pub(crate) gicp_grid_covariance_pipelines:
43        OnceLock<crate::kernels::gicp_reduction::resident_grid_covariances::GridPipelines>,
44    pub(crate) gicp_reduction_pipelines:
45        OnceLock<crate::kernels::gicp_reduction::GicpReductionPipelines>,
46    pub(crate) point_estimator_pipelines:
47        OnceLock<crate::kernels::point_estimators::PointEstimatorPipelines>,
48    max_gather_channels: u32,
49    upload_pool: GpuBufferPool,
50    pub(crate) scratch_pool: GpuBufferPool,
51    adapter_info: WgpuAdapterInfo,
52    profiling_identity: std::sync::Arc<()>,
53    #[cfg(feature = "gpu-image")]
54    image_texture_pool: Mutex<ResourceCache<(u32, u32), wgpu::Texture>>,
55    #[cfg(feature = "gpu-image")]
56    pub(crate) image_gray_pipeline: OnceLock<crate::image::kernels::gray::GrayPipeline>,
57    #[cfg(feature = "gpu-image")]
58    pub(crate) image_blur_pipeline: OnceLock<crate::image::kernels::box_blur::BlurPipeline>,
59    #[cfg(feature = "gpu-image")]
60    pub(crate) image_gaussian_pipelines:
61        OnceLock<crate::image::kernels::gaussian::GaussianPipelines>,
62    #[cfg(feature = "gpu-image")]
63    pub(crate) image_bilateral_pipeline:
64        OnceLock<crate::image::kernels::bilateral::BilateralPipeline>,
65    #[cfg(feature = "gpu-image")]
66    pub(crate) image_median_pipelines: OnceLock<crate::image::kernels::median::MedianPipelines>,
67    #[cfg(feature = "gpu-image")]
68    pub(crate) image_canny_pipelines: OnceLock<crate::image::canny::CannyPipelines>,
69    #[cfg(feature = "gpu-image")]
70    pub(crate) image_spatial_pipelines: OnceLock<crate::image::kernels::spatial::SpatialPipelines>,
71    #[cfg(feature = "gpu-image")]
72    pub(crate) image_ai_pack_pipeline: OnceLock<crate::image::ai_tensor::AiPackPipeline>,
73    #[cfg(feature = "gpu-image")]
74    pub(crate) image_histogram_pipelines: OnceLock<crate::image::histogram::HistogramPipelines>,
75    #[cfg(feature = "gpu-image")]
76    pub(crate) image_cdf_pipeline: OnceLock<crate::image::histogram::CdfPipeline>,
77    #[cfg(feature = "gpu-image")]
78    pub(crate) image_equalize_pipelines: OnceLock<crate::image::equalize::EqualizePipelines>,
79    #[cfg(feature = "gpu-image")]
80    pub(crate) image_clahe_pipelines: OnceLock<crate::image::clahe::ClahePipelines>,
81}
82
83/// Stable, serializable-friendly identity for the selected wgpu adapter.
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct WgpuAdapterInfo {
86    /// Human-readable adapter name.
87    pub name: String,
88    /// Graphics API backend such as Vulkan, Metal, or DirectX 12.
89    pub backend: String,
90    /// Adapter class such as integrated, discrete, CPU, or virtual GPU.
91    pub device_type: String,
92    /// Driver name reported by wgpu.
93    pub driver: String,
94    /// Additional driver version/details reported by wgpu.
95    pub driver_info: String,
96}
97
98/// Adapter power preference used when creating a headless wgpu runtime.
99#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
100pub enum WgpuPowerPreference {
101    /// Prefer a discrete or otherwise high-performance adapter.
102    #[default]
103    HighPerformance,
104    /// Prefer an integrated or otherwise power-efficient adapter.
105    LowPower,
106}
107
108/// Explicit backend set for a headless runtime.
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
110#[non_exhaustive]
111pub enum WgpuBackendSelection {
112    /// The original primary backend set used by existing constructors.
113    #[default]
114    Primary,
115    /// GL only, requiring platform support for OpenGL or OpenGLES compute.
116    Gl,
117}
118
119impl WgpuBackendSelection {
120    /// Stable requested-backend label for execution receipts.
121    #[must_use]
122    pub const fn as_str(self) -> &'static str {
123        match self {
124            Self::Primary => "primary",
125            Self::Gl => "gl",
126        }
127    }
128
129    const fn backends(self) -> wgpu::Backends {
130        match self {
131            Self::Primary => wgpu::Backends::PRIMARY,
132            Self::Gl => wgpu::Backends::GL,
133        }
134    }
135
136    fn validate_compiled_backends(self, available: wgpu::Backends) -> SpatialResult<()> {
137        // A WebGPU-only browser build ignores the requested instance mask.
138        // Reject before instance creation so an explicit GL request stays GL-only.
139        if self == Self::Gl && !available.contains(wgpu::Backends::GL) {
140            return Err(SpatialError::InvalidArgument(
141                "requested GL backend is not enabled for this build/platform".to_owned(),
142            ));
143        }
144        Ok(())
145    }
146
147    fn validate_compute_support(self, available: wgpu::DownlevelFlags) -> SpatialResult<()> {
148        if self == Self::Gl && !available.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS) {
149            return Err(SpatialError::InvalidArgument(
150                "requested GL adapter does not support compute shaders".to_owned(),
151            ));
152        }
153        Ok(())
154    }
155}
156
157/// Explicit headless selection and optional profiling requests.
158///
159/// Defaults preserve existing primary/high-performance/no-timestamp behavior.
160/// Options constructors create an owned runtime independently of [`WgpuRuntime::shared`].
161#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
162#[non_exhaustive]
163pub struct WgpuRuntimeOptions {
164    /// Requested backend set; GL is an explicit opt-in without backend fallback.
165    pub backend: WgpuBackendSelection,
166    /// Adapter power preference within the selected backend set.
167    pub power_preference: WgpuPowerPreference,
168    /// Request timestamp queries when available; unsupported adapters still initialize.
169    pub request_timestamps: bool,
170}
171
172/// Minimum storage buffers required for the 4-channel gather kernel.
173#[cfg(feature = "gpu-wgpu")]
174pub const MULTI_GATHER4_STORAGE_BUFFERS: u32 = 10;
175
176/// Minimum storage buffers required for the 2-channel gather kernel.
177#[cfg(feature = "gpu-wgpu")]
178pub const MULTI_GATHER2_STORAGE_BUFFERS: u32 = 6;
179
180#[cfg(feature = "gpu-wgpu")]
181#[cfg(not(target_arch = "wasm32"))]
182static SHARED_RUNTIME: OnceLock<Result<Arc<WgpuRuntime>, String>> = OnceLock::new();
183
184#[cfg(feature = "gpu-wgpu")]
185impl WgpuRuntime {
186    /// Creates a headless wgpu runtime preferring a high-performance adapter.
187    ///
188    /// Prefer [`Self::shared`] when running multiple GPU filters in one process.
189    pub fn new_headless() -> SpatialResult<Self> {
190        Self::new_headless_with_preference(WgpuPowerPreference::HighPerformance)
191    }
192
193    /// Creates a headless wgpu runtime with an explicit adapter power preference.
194    pub fn new_headless_with_preference(preference: WgpuPowerPreference) -> SpatialResult<Self> {
195        pollster::block_on(Self::new_headless_async(preference))
196    }
197
198    /// Creates a runtime enabling pass timestamps when supported by the adapter.
199    ///
200    /// Unsupported adapters still initialize; check [`Self::timestamp_queries_enabled`]
201    /// before constructing a profiler. The default constructors request no timestamps.
202    pub fn new_headless_with_timestamps(preference: WgpuPowerPreference) -> SpatialResult<Self> {
203        pollster::block_on(Self::new_headless_with_timestamps_async(preference))
204    }
205
206    /// Creates an owned runtime using explicit backend and profiling options.
207    ///
208    /// GL must be compiled for the target and provide adapter compute shaders.
209    /// An uncompiled GL request fails before instance creation. Admission errors do not
210    /// select another backend. Browser callers should use the async counterpart.
211    pub fn new_headless_with_options(options: WgpuRuntimeOptions) -> SpatialResult<Self> {
212        pollster::block_on(Self::new_headless_with_options_async(options))
213    }
214
215    /// Returns whether this device has optional pass timestamp queries enabled.
216    #[must_use]
217    pub fn timestamp_queries_enabled(&self) -> bool {
218        self.device.features().contains(wgpu::Features::TIMESTAMP_QUERY)
219    }
220
221    pub(crate) fn profiling_identity(&self) -> std::sync::Arc<()> {
222        std::sync::Arc::clone(&self.profiling_identity)
223    }
224
225    /// Returns a process-wide shared headless runtime, initializing it on first use.
226    #[cfg(not(target_arch = "wasm32"))]
227    pub fn shared() -> SpatialResult<Arc<Self>> {
228        match SHARED_RUNTIME.get_or_init(init_shared_runtime) {
229            Ok(runtime) => Ok(Arc::clone(runtime)),
230            Err(message) => Err(SpatialError::InvalidArgument(message.clone())),
231        }
232    }
233
234    /// Returns the underlying wgpu device.
235    #[must_use]
236    pub fn device(&self) -> &wgpu::Device {
237        &self.device
238    }
239
240    /// Returns the underlying wgpu queue.
241    #[must_use]
242    pub fn queue(&self) -> &wgpu::Queue {
243        &self.queue
244    }
245
246    /// Returns the selected adapter/backend receipt.
247    #[must_use]
248    pub const fn adapter_info(&self) -> &WgpuAdapterInfo {
249        &self.adapter_info
250    }
251
252    /// Blocks until all previously submitted work on this device is complete.
253    ///
254    /// Normal device-resident chains do not synchronize implicitly. This is an
255    /// explicit profiling/testing boundary or host-coordination primitive.
256    pub fn wait_idle(&self) {
257        self.device.poll(wgpu::Maintain::Wait);
258    }
259
260    #[cfg(feature = "gpu-image")]
261    pub(crate) fn acquire_image_texture(
262        &self,
263        width: u32,
264        height: u32,
265        label: &'static str,
266    ) -> wgpu::Texture {
267        {
268            let mut pool = self.image_texture_pool.lock().expect("image texture pool poisoned");
269            if let Some(texture) = pool.take(&(width, height)) {
270                return texture;
271            }
272            pool.record_allocation();
273        }
274        self.device.create_texture(&wgpu::TextureDescriptor {
275            label: Some(label),
276            size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
277            mip_level_count: 1,
278            sample_count: 1,
279            dimension: wgpu::TextureDimension::D2,
280            format: wgpu::TextureFormat::Rgba8Uint,
281            usage: wgpu::TextureUsages::COPY_SRC
282                | wgpu::TextureUsages::COPY_DST
283                | wgpu::TextureUsages::TEXTURE_BINDING
284                | wgpu::TextureUsages::STORAGE_BINDING,
285            view_formats: &[],
286        })
287    }
288
289    #[cfg(feature = "gpu-image")]
290    pub(crate) fn recycle_image_texture(&self, width: u32, height: u32, texture: wgpu::Texture) {
291        let mut pool = self.image_texture_pool.lock().expect("image texture pool poisoned");
292        pool.put((width, height), u64::from(width) * u64::from(height) * 4, texture);
293    }
294
295    /// Returns the number of image textures retained for steady-state reuse.
296    #[cfg(feature = "gpu-image")]
297    #[must_use]
298    pub fn cached_image_texture_count(&self) -> usize {
299        self.image_texture_pool_stats().cached_resources
300    }
301
302    /// Returns image-texture retention and lifetime allocation/reuse counters.
303    /// Texel bytes exclude driver overhead and live images; the default is 64 MiB.
304    #[cfg(feature = "gpu-image")]
305    #[must_use]
306    pub fn image_texture_pool_stats(&self) -> GpuResourcePoolStats {
307        self.image_texture_pool.lock().map(|pool| pool.stats()).unwrap_or_default()
308    }
309
310    /// Changes retained RGBA8 texel bytes; zero disables texture retention.
311    /// Shrinking below current retention clears cached textures. Active images
312    /// remain valid and allocations are not capped by the retention budget.
313    #[cfg(feature = "gpu-image")]
314    pub fn set_image_texture_pool_budget(&self, budget_bytes: u64) {
315        if let Ok(mut pool) = self.image_texture_pool.lock() {
316            pool.set_budget(budget_bytes);
317        }
318    }
319
320    /// Drops cached texture handles without affecting live images or counters.
321    #[cfg(feature = "gpu-image")]
322    pub fn clear_image_texture_pool(&self) {
323        if let Ok(mut pool) = self.image_texture_pool.lock() {
324            pool.clear();
325        }
326    }
327
328    /// Returns the number of initialized GPU image pipeline families.
329    #[cfg(feature = "gpu-image")]
330    #[must_use]
331    pub fn initialized_image_pipeline_count(&self) -> usize {
332        usize::from(self.image_gray_pipeline.get().is_some())
333            + usize::from(self.image_blur_pipeline.get().is_some())
334            + usize::from(self.image_gaussian_pipelines.get().is_some())
335            + usize::from(self.image_median_pipelines.get().is_some())
336            + usize::from(self.image_bilateral_pipeline.get().is_some())
337            + usize::from(self.image_canny_pipelines.get().is_some())
338            + usize::from(self.image_spatial_pipelines.get().is_some())
339            + usize::from(self.image_ai_pack_pipeline.get().is_some())
340            + usize::from(self.image_histogram_pipelines.get().is_some())
341            + usize::from(self.image_cdf_pipeline.get().is_some())
342            + usize::from(self.image_equalize_pipelines.get().is_some())
343            + usize::from(self.image_clahe_pipelines.get().is_some())
344    }
345
346    /// Returns cached compute pipelines for this runtime's device.
347    #[must_use]
348    pub fn pipelines(&self) -> &ComputePipelineCache {
349        self.pipelines.get_or_init(|| ComputePipelineCache::new(&self.device))
350    }
351
352    /// Returns the maximum attribute channels gatherable in one multi dispatch.
353    #[must_use]
354    pub fn max_gather_channels(&self) -> u32 {
355        self.max_gather_channels
356    }
357
358    /// Returns the reusable storage-buffer pool owned by this runtime.
359    #[must_use]
360    pub fn buffer_pool(&self) -> &GpuBufferPool {
361        &self.upload_pool
362    }
363
364    /// Returns private point-kernel scratch retention and lifetime counters.
365    /// The default budget is 64 MiB, independent of the public upload pool.
366    #[must_use]
367    pub fn scratch_buffer_pool_stats(&self) -> GpuResourcePoolStats {
368        self.scratch_pool.stats()
369    }
370
371    /// Changes private scratch retention; zero disables reuse. Shrinking below
372    /// current retention clears cached buffers without affecting submitted work.
373    pub fn set_scratch_buffer_pool_budget(&self, budget_bytes: u64) {
374        self.scratch_pool.set_budget(budget_bytes);
375    }
376
377    /// Drops cached scratch handles without changing the budget or counters.
378    pub fn clear_scratch_buffer_pool(&self) {
379        self.scratch_pool.clear();
380    }
381
382    /// Uploads a POD slice into a reusable pooled storage buffer.
383    pub fn upload_pod_storage<T: bytemuck::Pod>(
384        &self,
385        label: &'static str,
386        data: &[T],
387    ) -> SpatialResult<wgpu::Buffer> {
388        self.upload_pool.upload_pod_storage(self, label, data)
389    }
390
391    /// Uploads `f32` values into a reusable pooled storage buffer.
392    pub fn upload_f32_storage(
393        &self,
394        label: &'static str,
395        data: &[f32],
396    ) -> SpatialResult<wgpu::Buffer> {
397        self.upload_pool.upload_f32_storage(self, label, data)
398    }
399
400    /// Uploads `u32` values into a reusable pooled storage buffer.
401    pub fn upload_u32_storage(
402        &self,
403        label: &'static str,
404        data: &[u32],
405    ) -> SpatialResult<wgpu::Buffer> {
406        self.upload_pool.upload_u32_storage(self, label, data)
407    }
408
409    /// Returns a storage buffer to the upload pool for reuse.
410    pub fn recycle_storage(&self, byte_len: u64, buffer: wgpu::Buffer) {
411        self.upload_pool.recycle(byte_len, buffer);
412    }
413
414    /// Clears all buffers cached in the upload pool.
415    pub fn clear_buffer_pool(&self) {
416        self.upload_pool.clear();
417    }
418
419    /// Creates a headless runtime asynchronously.
420    ///
421    /// This is the browser/WebGPU construction path because blocking a WASM
422    /// main thread is not supported. Native callers may also use it from their
423    /// async executor.
424    pub async fn new_headless_async(preference: WgpuPowerPreference) -> SpatialResult<Self> {
425        Self::new_headless_impl(WgpuRuntimeOptions {
426            power_preference: preference,
427            ..Default::default()
428        })
429        .await
430    }
431
432    /// Async counterpart of [`Self::new_headless_with_timestamps`].
433    pub async fn new_headless_with_timestamps_async(
434        preference: WgpuPowerPreference,
435    ) -> SpatialResult<Self> {
436        Self::new_headless_impl(WgpuRuntimeOptions {
437            power_preference: preference,
438            request_timestamps: true,
439            ..Default::default()
440        })
441        .await
442    }
443
444    /// Async counterpart of [`Self::new_headless_with_options`].
445    pub async fn new_headless_with_options_async(
446        options: WgpuRuntimeOptions,
447    ) -> SpatialResult<Self> {
448        Self::new_headless_impl(options).await
449    }
450
451    async fn new_headless_impl(options: WgpuRuntimeOptions) -> SpatialResult<Self> {
452        options.backend.validate_compiled_backends(wgpu::Instance::enabled_backend_features())?;
453        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
454            backends: options.backend.backends(),
455            ..Default::default()
456        });
457
458        let adapter = instance
459            .request_adapter(&wgpu::RequestAdapterOptions {
460                power_preference: match options.power_preference {
461                    WgpuPowerPreference::HighPerformance => wgpu::PowerPreference::HighPerformance,
462                    WgpuPowerPreference::LowPower => wgpu::PowerPreference::LowPower,
463                },
464                compatible_surface: None,
465                force_fallback_adapter: false,
466            })
467            .await
468            .ok_or_else(|| {
469                SpatialError::InvalidArgument(
470                    "no compatible wgpu adapter found for headless compute".to_owned(),
471                )
472            })?;
473
474        options.backend.validate_compute_support(adapter.get_downlevel_capabilities().flags)?;
475
476        let raw_adapter_info = adapter.get_info();
477        let adapter_info = WgpuAdapterInfo {
478            name: raw_adapter_info.name,
479            backend: format!("{:?}", raw_adapter_info.backend),
480            device_type: format!("{:?}", raw_adapter_info.device_type),
481            driver: raw_adapter_info.driver,
482            driver_info: raw_adapter_info.driver_info,
483        };
484        let (device, queue) = adapter
485            .request_device(
486                &wgpu::DeviceDescriptor {
487                    label: Some("spatialrust-wgpu"),
488                    required_features: timestamp_features(
489                        options.request_timestamps,
490                        adapter.features(),
491                    ),
492                    required_limits: adapter.limits(),
493                    memory_hints: wgpu::MemoryHints::Performance,
494                },
495                None,
496            )
497            .await
498            .map_err(|error| {
499                SpatialError::InvalidArgument(format!("failed to create wgpu device: {error}"))
500            })?;
501
502        let max_gather_channels =
503            max_gather_channels_for_limit(device.limits().max_storage_buffers_per_shader_stage);
504
505        Ok(Self {
506            _instance: instance,
507            device,
508            queue,
509            pipelines: OnceLock::new(),
510            voxel_scan_pipelines: OnceLock::new(),
511            ransac_plane_pipelines: OnceLock::new(),
512            cluster_pipelines: OnceLock::new(),
513            nearest_pipeline: OnceLock::new(),
514            tree_gather_pipeline: OnceLock::new(),
515            neighborhood_pipelines: OnceLock::new(),
516            fpfh_pipelines: OnceLock::new(),
517            fpfh_sample_pipeline: OnceLock::new(),
518            iss_pipelines: OnceLock::new(),
519            mls_pipelines: OnceLock::new(),
520            icp_reduction_pipelines: OnceLock::new(),
521            icp_trim_pipelines: OnceLock::new(),
522            gicp_reduction_pipelines: OnceLock::new(),
523            gicp_covariance_pipelines: OnceLock::new(),
524            gicp_grid_covariance_pipelines: OnceLock::new(),
525            point_to_plane_reduction_pipelines: OnceLock::new(),
526            point_estimator_pipelines: OnceLock::new(),
527            max_gather_channels,
528            upload_pool: GpuBufferPool::default(),
529            scratch_pool: GpuBufferPool::default(),
530            adapter_info,
531            profiling_identity: std::sync::Arc::new(()),
532            #[cfg(feature = "gpu-image")]
533            image_texture_pool: Mutex::new(ResourceCache::new(DEFAULT_GPU_POOL_BUDGET_BYTES)),
534            #[cfg(feature = "gpu-image")]
535            image_gray_pipeline: OnceLock::new(),
536            #[cfg(feature = "gpu-image")]
537            image_blur_pipeline: OnceLock::new(),
538            #[cfg(feature = "gpu-image")]
539            image_gaussian_pipelines: OnceLock::new(),
540            #[cfg(feature = "gpu-image")]
541            image_bilateral_pipeline: OnceLock::new(),
542            #[cfg(feature = "gpu-image")]
543            image_median_pipelines: OnceLock::new(),
544            #[cfg(feature = "gpu-image")]
545            image_canny_pipelines: OnceLock::new(),
546            #[cfg(feature = "gpu-image")]
547            image_spatial_pipelines: OnceLock::new(),
548            #[cfg(feature = "gpu-image")]
549            image_ai_pack_pipeline: OnceLock::new(),
550            #[cfg(feature = "gpu-image")]
551            image_histogram_pipelines: OnceLock::new(),
552            #[cfg(feature = "gpu-image")]
553            image_cdf_pipeline: OnceLock::new(),
554            #[cfg(feature = "gpu-image")]
555            image_equalize_pipelines: OnceLock::new(),
556            #[cfg(feature = "gpu-image")]
557            image_clahe_pipelines: OnceLock::new(),
558        })
559    }
560}
561
562#[cfg(feature = "gpu-wgpu")]
563impl SpatialRuntime for WgpuRuntime {
564    fn device_kind(&self) -> DeviceKind {
565        DeviceKind::Wgpu
566    }
567}
568
569#[cfg(feature = "gpu-wgpu")]
570fn max_gather_channels_for_limit(storage_buffers_per_stage: u32) -> u32 {
571    if storage_buffers_per_stage >= MULTI_GATHER4_STORAGE_BUFFERS {
572        4
573    } else if storage_buffers_per_stage >= MULTI_GATHER2_STORAGE_BUFFERS {
574        2
575    } else {
576        1
577    }
578}
579
580fn timestamp_features(requested: bool, available: wgpu::Features) -> wgpu::Features {
581    if requested {
582        available & wgpu::Features::TIMESTAMP_QUERY
583    } else {
584        wgpu::Features::empty()
585    }
586}
587
588#[cfg(feature = "gpu-wgpu")]
589#[cfg(not(target_arch = "wasm32"))]
590fn init_shared_runtime() -> Result<Arc<WgpuRuntime>, String> {
591    WgpuRuntime::new_headless().map(Arc::new).map_err(|error| error.to_string())
592}
593
594#[cfg(all(feature = "gpu-wgpu", test, not(target_arch = "wasm32")))]
595mod tests {
596    use super::WgpuRuntime;
597    use crate::pipeline_cache::ComputePipelineCache;
598    use std::sync::Arc;
599
600    #[test]
601    fn runtime_options_preserve_existing_constructor_policy() {
602        let options = super::WgpuRuntimeOptions::default();
603        assert_eq!(options.backend, super::WgpuBackendSelection::Primary);
604        assert_eq!(options.power_preference, super::WgpuPowerPreference::HighPerformance);
605        assert!(!options.request_timestamps);
606    }
607
608    #[test]
609    fn backend_selection_is_explicit_without_cross_backend_fallback() {
610        let primary = super::WgpuBackendSelection::Primary;
611        let gl = super::WgpuBackendSelection::Gl;
612        assert_eq!(primary.backends(), wgpu::Backends::PRIMARY);
613        assert_eq!(gl.backends(), wgpu::Backends::GL);
614        assert!(!primary.backends().intersects(gl.backends()));
615        assert_eq!((primary.as_str(), gl.as_str()), ("primary", "gl"));
616    }
617
618    #[test]
619    fn explicit_gl_rejects_builds_that_could_select_browser_webgpu() {
620        for available in
621            [wgpu::Backends::BROWSER_WEBGPU, wgpu::Backends::PRIMARY, wgpu::Backends::empty()]
622        {
623            let error = super::WgpuBackendSelection::Gl
624                .validate_compiled_backends(available)
625                .expect_err("explicit GL must not create an instance without GL support");
626            assert!(error.to_string().contains("requested GL backend is not enabled"));
627        }
628    }
629
630    #[test]
631    fn backend_admission_preserves_primary_and_accepts_compiled_gl() {
632        super::WgpuBackendSelection::Primary
633            .validate_compiled_backends(wgpu::Backends::BROWSER_WEBGPU)
634            .expect("original primary browser policy");
635        for available in [wgpu::Backends::GL, wgpu::Backends::GL | wgpu::Backends::BROWSER_WEBGPU] {
636            super::WgpuBackendSelection::Gl
637                .validate_compiled_backends(available)
638                .expect("compiled GL support");
639        }
640    }
641
642    #[test]
643    fn explicit_gl_rejects_adapters_without_compute_shaders() {
644        for available in [wgpu::DownlevelFlags::empty(), wgpu::DownlevelFlags::INDIRECT_EXECUTION] {
645            let error = super::WgpuBackendSelection::Gl
646                .validate_compute_support(available)
647                .expect_err("WebGL or graphics-only GL cannot run compute kernels");
648            assert!(error.to_string().contains("does not support compute shaders"));
649        }
650    }
651
652    #[test]
653    fn compute_admission_preserves_primary_and_accepts_compute_gl() {
654        super::WgpuBackendSelection::Primary
655            .validate_compute_support(wgpu::DownlevelFlags::empty())
656            .expect("original primary admission policy");
657        super::WgpuBackendSelection::Gl
658            .validate_compute_support(wgpu::DownlevelFlags::COMPUTE_SHADERS)
659            .expect("GL adapter with compute shaders");
660    }
661
662    #[test]
663    fn optional_timestamp_features_handle_unsupported_adapters() {
664        let unrelated = wgpu::Features::INDIRECT_FIRST_INSTANCE;
665        let supported = unrelated | wgpu::Features::TIMESTAMP_QUERY;
666        assert_eq!(super::timestamp_features(false, supported), wgpu::Features::empty());
667        assert_eq!(super::timestamp_features(true, unrelated), wgpu::Features::empty());
668        assert_eq!(super::timestamp_features(true, supported), wgpu::Features::TIMESTAMP_QUERY);
669    }
670
671    #[test]
672    fn shared_runtime_is_singleton() {
673        let first = WgpuRuntime::shared().expect("shared runtime");
674        let second = WgpuRuntime::shared().expect("shared runtime");
675        assert!(Arc::ptr_eq(&first, &second));
676    }
677
678    #[test]
679    fn shared_and_headless_use_same_device_type() {
680        let shared = WgpuRuntime::shared().expect("shared runtime");
681        let local = WgpuRuntime::new_headless().expect("local runtime");
682        assert_eq!(
683            shared.device().limits().max_storage_buffers_per_shader_stage,
684            local.device().limits().max_storage_buffers_per_shader_stage
685        );
686    }
687
688    #[test]
689    fn pipeline_cache_is_initialized_once_per_runtime() {
690        let runtime = WgpuRuntime::new_headless().expect("wgpu runtime");
691        let first = runtime.pipelines() as *const ComputePipelineCache;
692        let second = runtime.pipelines() as *const ComputePipelineCache;
693        assert_eq!(first, second);
694    }
695
696    #[test]
697    fn adapter_limits_enable_multi_channel_gather() {
698        let runtime = WgpuRuntime::new_headless().expect("wgpu runtime");
699        let limit = runtime.device().limits().max_storage_buffers_per_shader_stage;
700        assert!(
701            limit >= super::MULTI_GATHER2_STORAGE_BUFFERS,
702            "expected at least {} storage buffers per stage, got {limit}",
703            super::MULTI_GATHER2_STORAGE_BUFFERS
704        );
705        assert!(runtime.max_gather_channels() >= 2);
706        assert_eq!(
707            runtime.max_gather_channels(),
708            runtime.pipelines().voxel_gather.multi_max_channels
709        );
710    }
711}