frust-gpu 0.5.1

wgpu adapter, device and surface foundation for Frust: capability probing, surface lifecycle and pooled GPU resources.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Adapter capability probing: [`TierCaps`] and [`DownlevelProfile`].
//!
//! [`TierCaps`] is plain data pulled off a real `wgpu::Adapter` at device-init
//! time ([`TierCaps::probe`]), so downstream tier/pipeline decisions are
//! unit-testable against [`TierCaps::fake`] with no GPU in the loop — the same
//! pure-decision/platform-lookup split `frust-render`'s tier selection follows.
//!
//! [`DownlevelProfile`] tells a caller whether the adapter's limits are the
//! full desktop set or clamped to the GLES-3.0/WebGL2 downlevel defaults,
//! which a browser target (a future host) will always hit and which
//! `FRUST_ENGINE_DOWNLEVEL=1` lets a desktop developer rehearse today.

use std::sync::OnceLock;

/// The GLES-3.0/WebGL2 downlevel default resource-texture ceiling
/// (`wgpu::Limits::downlevel_webgl2_defaults().max_texture_dimension_2d`).
const WEBGL2_MAX_TEXTURE_DIMENSION_2D: u32 = 2048;

/// The desktop (Vulkan/Metal/Dx12) default resource-texture ceiling
/// (`wgpu::Limits::defaults().max_texture_dimension_2d`).
const DESKTOP_MAX_TEXTURE_DIMENSION_2D: u32 = 8192;

/// The ceiling [`TierCaps::resource_texture_dim`] never exceeds regardless of
/// what the adapter itself reports, keeping any texture-pool/atlas sizing
/// decision built on it bounded even on a very generous desktop adapter.
const MAX_RESOURCE_TEXTURE_DIM: u32 = 4096;

/// The texture format a texture atlas is backed by. `Rgba8Unorm` is the one
/// target format used everywhere else a `wgpu::TextureFormat` is chosen in
/// this workspace's GPU backend.
const ATLAS_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;

/// Whether an adapter's usable limits are the full native set, or clamped to
/// the GLES-3.0/WebGL2 downlevel defaults (`wgpu::Limits::downlevel_webgl2_defaults`).
///
/// Derived, never chosen directly by a caller building [`TierCaps::probe`]:
/// `WebGl2` whenever the adapter's backend is [`wgpu::Backend::Gl`], or
/// whenever the process-wide `FRUST_ENGINE_DOWNLEVEL=1` override is set — the
/// latter lets a desktop (Vulkan/Metal/Dx12) adapter rehearse the browser's
/// downlevel ceiling without an actual GL/WebGL2 context.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DownlevelProfile {
    /// Native desktop/mobile limits (Vulkan, Metal, Dx12).
    Full,
    /// Clamped to the GLES-3.0/WebGL2 downlevel default limits.
    WebGl2,
}

impl DownlevelProfile {
    fn resolve(backend: wgpu::Backend) -> Self {
        if backend == wgpu::Backend::Gl || downlevel_override_enabled() {
            DownlevelProfile::WebGl2
        } else {
            DownlevelProfile::Full
        }
    }
}

/// Whether the `FRUST_ENGINE_DOWNLEVEL` process-wide override is set to a
/// non-zero value, checking both the compile-time (`option_env!`) and runtime
/// (`std::env::var`) halves like `frust-render`'s `FRUST_TRACE` knob. Cached:
/// read once per process.
fn downlevel_override_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| {
        env_flag_enabled(
            option_env!("FRUST_ENGINE_DOWNLEVEL"),
            std::env::var("FRUST_ENGINE_DOWNLEVEL").ok(),
        )
    })
}

fn env_flag_enabled(compile_time: Option<&str>, runtime: Option<String>) -> bool {
    fn is_set_non_zero(value: Option<&str>) -> bool {
        matches!(value, Some(v) if v != "0")
    }
    is_set_non_zero(compile_time) || is_set_non_zero(runtime.as_deref())
}

/// Plain-data adapter capabilities the GPU crate's device/pipeline/atlas
/// decisions are built over. Constructed from a real `wgpu::Adapter` via
/// [`TierCaps::probe`], or by hand in host tests via [`TierCaps::fake`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TierCaps {
    /// The adapter's `wgpu::DownlevelCapabilities::flags`.
    pub downlevel_flags: wgpu::DownlevelFlags,
    /// The adapter's `wgpu::AdapterInfo::name`, used only for diagnostics.
    pub adapter_name: String,
    /// The adapter's `wgpu::AdapterInfo::backend`.
    pub backend: wgpu::Backend,
    /// The adapter's `wgpu::Limits::max_texture_dimension_2d`, clamped down to
    /// `wgpu::Limits::downlevel_webgl2_defaults().max_texture_dimension_2d`
    /// when [`Self::downlevel_profile`] is [`DownlevelProfile::WebGl2`].
    pub max_texture_dimension_2d: u32,
    /// The adapter's `wgpu::Limits::max_texture_array_layers`, clamped the
    /// same way as [`Self::max_texture_dimension_2d`].
    pub max_texture_array_layers: u32,
    /// The adapter's `wgpu::Limits::max_bind_groups`, clamped the same way as
    /// [`Self::max_texture_dimension_2d`].
    pub max_bind_groups: u32,
    /// The adapter's `wgpu::Limits::max_uniform_buffer_binding_size`,
    /// saturated into a `u32` (the field is `u64` on `wgpu::Limits`; no
    /// adapter this workspace targets reports a value anywhere near
    /// `u32::MAX`) and clamped the same way as
    /// [`Self::max_texture_dimension_2d`].
    pub max_uniform_buffer_binding_size: u32,
    /// The adapter's `wgpu::Limits::min_uniform_buffer_offset_alignment`,
    /// raised to
    /// `wgpu::Limits::downlevel_webgl2_defaults().min_uniform_buffer_offset_alignment`
    /// (256) when [`Self::downlevel_profile`] is [`DownlevelProfile::WebGl2`]
    /// and the adapter reports a looser (smaller) value — an alignment
    /// requirement is a floor, so it is only ever raised, never lowered.
    pub min_uniform_buffer_offset_alignment: u32,
    /// The adapter's `wgpu::Limits::max_vertex_attributes`, clamped the same
    /// way as [`Self::max_texture_dimension_2d`].
    pub max_vertex_attributes: u32,
    /// Whether the adapter supports storage buffers at all
    /// (`wgpu::Limits::max_storage_buffers_per_shader_stage > 0`) — forced
    /// `false` whenever [`Self::downlevel_profile`] is
    /// [`DownlevelProfile::WebGl2`], since the GLES-3.0/WebGL2 downlevel
    /// default limits report zero storage buffers per shader stage.
    pub has_storage_buffers: bool,
    /// Whether the adapter exposes `wgpu::Features::TIMESTAMP_QUERY`.
    pub has_timestamp_query: bool,
    /// The adapter's `wgpu::AdapterInfo::transient_saves_memory` — whether
    /// adding `wgpu::TextureUsages::TRANSIENT_ATTACHMENT` to a texture (which
    /// itself requires `wgpu::StoreOp::Discard`) reduces memory usage on this
    /// adapter.
    ///
    /// `wgpu` reports this as `Option<bool>`, where `None` means "the adapter
    /// does not say" (only the web backend, which no frust shell targets).
    /// [`Self::probe`] folds `None` to `false`: an unknown answer must not buy
    /// the transient flag, since it is a memory optimization with a hard
    /// clear/discard precondition and no upside when the driver ignores it.
    pub transient_saves_memory: bool,
    /// The texture format a texture atlas is backed by.
    pub atlas_format: wgpu::TextureFormat,
    /// The texture dimension a pooled/atlas resource texture is sized
    /// against: `min(max_texture_dimension_2d, 4096)` against the (possibly
    /// already WebGL2-clamped) [`Self::max_texture_dimension_2d`], so a very
    /// generous desktop adapter's real ceiling never drives an oversized
    /// allocation.
    pub resource_texture_dim: u32,
    /// Whether this adapter's usable limits are the full native set or
    /// clamped to the GLES-3.0/WebGL2 downlevel defaults.
    pub downlevel_profile: DownlevelProfile,
}

impl TierCaps {
    /// Probes a real `wgpu::Adapter` for the capabilities this crate's
    /// device/pipeline/atlas decisions are built over. Synchronous: every
    /// value it reads (`get_info`, `get_downlevel_capabilities`, `limits`,
    /// `features`) is available before device creation.
    ///
    /// When the resolved [`DownlevelProfile`] is [`DownlevelProfile::WebGl2`]
    /// — a real `wgpu::Backend::Gl` adapter, or `FRUST_ENGINE_DOWNLEVEL=1`
    /// rehearsing it against a desktop backend — the probed limits are run
    /// through `clamp_to_webgl2_defaults` and storage buffers are forced
    /// off, so the override actually rehearses the downlevel shape instead of
    /// only relabelling desktop values.
    pub fn probe(adapter: &wgpu::Adapter) -> Self {
        let info = adapter.get_info();
        let downlevel = adapter.get_downlevel_capabilities();
        let limits = adapter.limits();
        let features = adapter.features();
        let downlevel_profile = DownlevelProfile::resolve(info.backend);
        let limits = clamp_to_webgl2_defaults(limits, downlevel_profile);
        let max_texture_dimension_2d = limits.max_texture_dimension_2d;
        Self {
            downlevel_flags: downlevel.flags,
            adapter_name: info.name,
            backend: info.backend,
            max_texture_dimension_2d,
            max_texture_array_layers: limits.max_texture_array_layers,
            max_bind_groups: limits.max_bind_groups,
            max_uniform_buffer_binding_size: saturating_u32(limits.max_uniform_buffer_binding_size),
            min_uniform_buffer_offset_alignment: limits.min_uniform_buffer_offset_alignment,
            max_vertex_attributes: limits.max_vertex_attributes,
            has_storage_buffers: downlevel_profile == DownlevelProfile::Full
                && limits.max_storage_buffers_per_shader_stage > 0,
            has_timestamp_query: features.contains(wgpu::Features::TIMESTAMP_QUERY),
            transient_saves_memory: info.transient_saves_memory.unwrap_or(false),
            atlas_format: ATLAS_FORMAT,
            resource_texture_dim: max_texture_dimension_2d.min(MAX_RESOURCE_TEXTURE_DIM),
            downlevel_profile,
        }
    }

    /// Builds synthetic caps for the given [`DownlevelProfile`] with no
    /// `wgpu::Adapter` at all — the host-test counterpart to [`Self::probe`].
    ///
    /// `Full` mirrors `wgpu::Limits::defaults()`'s desktop values (backend
    /// `Vulkan`, `max_texture_dimension_2d` 8192, storage buffers present);
    /// `WebGl2` mirrors `wgpu::Limits::downlevel_webgl2_defaults()` (backend
    /// `Gl`, `max_texture_dimension_2d` 2048, no storage buffers).
    pub fn fake(profile: DownlevelProfile) -> Self {
        match profile {
            DownlevelProfile::Full => Self {
                downlevel_flags: wgpu::DownlevelFlags::all(),
                adapter_name: "fake-full".to_string(),
                backend: wgpu::Backend::Vulkan,
                max_texture_dimension_2d: DESKTOP_MAX_TEXTURE_DIMENSION_2D,
                max_texture_array_layers: 256,
                max_bind_groups: 4,
                max_uniform_buffer_binding_size: 64 << 10,
                min_uniform_buffer_offset_alignment: 256,
                max_vertex_attributes: 16,
                has_storage_buffers: true,
                has_timestamp_query: true,
                transient_saves_memory: false,
                atlas_format: ATLAS_FORMAT,
                resource_texture_dim: DESKTOP_MAX_TEXTURE_DIMENSION_2D
                    .min(MAX_RESOURCE_TEXTURE_DIM),
                downlevel_profile: DownlevelProfile::Full,
            },
            DownlevelProfile::WebGl2 => Self {
                downlevel_flags: wgpu::DownlevelFlags::empty(),
                adapter_name: "fake-webgl2".to_string(),
                backend: wgpu::Backend::Gl,
                max_texture_dimension_2d: WEBGL2_MAX_TEXTURE_DIMENSION_2D,
                max_texture_array_layers: 256,
                max_bind_groups: 4,
                max_uniform_buffer_binding_size: 16 << 10,
                min_uniform_buffer_offset_alignment: 256,
                max_vertex_attributes: 16,
                has_storage_buffers: false,
                has_timestamp_query: false,
                transient_saves_memory: false,
                atlas_format: ATLAS_FORMAT,
                resource_texture_dim: WEBGL2_MAX_TEXTURE_DIMENSION_2D.min(MAX_RESOURCE_TEXTURE_DIM),
                downlevel_profile: DownlevelProfile::WebGl2,
            },
        }
    }
}

/// Clamps `limits` to the GLES-3.0/WebGL2 downlevel default ceiling on every
/// field [`TierCaps`] tracks, when `profile` is [`DownlevelProfile::WebGl2`];
/// returns `limits` unchanged for [`DownlevelProfile::Full`].
///
/// Each tracked field the WebGL2 defaults constrain is clamped toward that
/// default rather than replaced outright, so a real (non-desktop) `Gl`
/// adapter reporting something even lower than the WebGL2 default is not
/// raised past its own hardware ceiling. `max_texture_dimension_2d`,
/// `max_texture_array_layers`, `max_bind_groups`,
/// `max_uniform_buffer_binding_size` and `max_vertex_attributes` are ceilings
/// (`min` with the default); `min_uniform_buffer_offset_alignment` is a floor
/// (`max` with the default) — never lowered. Fields the WebGL2 defaults do
/// not constrain (e.g. `max_texture_dimension_3d` is unused by this crate)
/// pass through untouched via `..limits`.
fn clamp_to_webgl2_defaults(limits: wgpu::Limits, profile: DownlevelProfile) -> wgpu::Limits {
    if profile != DownlevelProfile::WebGl2 {
        return limits;
    }
    let webgl2 = wgpu::Limits::downlevel_webgl2_defaults();
    wgpu::Limits {
        max_texture_dimension_2d: limits
            .max_texture_dimension_2d
            .min(webgl2.max_texture_dimension_2d),
        max_texture_array_layers: limits
            .max_texture_array_layers
            .min(webgl2.max_texture_array_layers),
        max_bind_groups: limits.max_bind_groups.min(webgl2.max_bind_groups),
        max_uniform_buffer_binding_size: limits
            .max_uniform_buffer_binding_size
            .min(webgl2.max_uniform_buffer_binding_size),
        min_uniform_buffer_offset_alignment: limits
            .min_uniform_buffer_offset_alignment
            .max(webgl2.min_uniform_buffer_offset_alignment),
        max_vertex_attributes: limits
            .max_vertex_attributes
            .min(webgl2.max_vertex_attributes),
        ..limits
    }
}

/// `u64 -> u32` saturating conversion for `wgpu::Limits` fields declared
/// wider than the `u32` this crate's [`TierCaps`] stores them as.
fn saturating_u32(value: u64) -> u32 {
    u32::try_from(value).unwrap_or(u32::MAX)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn full_profile_fake_reports_desktop_defaults() {
        let caps = TierCaps::fake(DownlevelProfile::Full);
        assert_eq!(caps.downlevel_profile, DownlevelProfile::Full);
        assert_eq!(caps.backend, wgpu::Backend::Vulkan);
        assert!(caps.has_storage_buffers);
        assert_eq!(
            caps.max_texture_dimension_2d,
            DESKTOP_MAX_TEXTURE_DIMENSION_2D
        );
        assert_eq!(caps.resource_texture_dim, MAX_RESOURCE_TEXTURE_DIM);
    }

    #[test]
    fn webgl2_profile_fake_reports_clamped_resource_dim_and_no_storage_buffers() {
        let caps = TierCaps::fake(DownlevelProfile::WebGl2);
        assert_eq!(caps.downlevel_profile, DownlevelProfile::WebGl2);
        assert!(caps.resource_texture_dim <= 2048);
        assert!(!caps.has_storage_buffers);
    }

    #[test]
    fn resource_texture_dim_never_exceeds_the_shared_ceiling() {
        let caps = TierCaps::fake(DownlevelProfile::Full);
        assert!(caps.resource_texture_dim <= MAX_RESOURCE_TEXTURE_DIM);
    }

    #[test]
    fn atlas_format_is_set_on_both_profiles() {
        assert_eq!(
            TierCaps::fake(DownlevelProfile::Full).atlas_format,
            ATLAS_FORMAT
        );
        assert_eq!(
            TierCaps::fake(DownlevelProfile::WebGl2).atlas_format,
            ATLAS_FORMAT
        );
    }

    #[test]
    fn saturating_u32_clamps_a_too_large_u64() {
        assert_eq!(saturating_u32(u64::MAX), u32::MAX);
        assert_eq!(saturating_u32(64 << 10), 64 << 10);
    }

    #[test]
    fn full_profile_clamp_is_a_no_op() {
        let desktop = wgpu::Limits::defaults();
        assert_eq!(
            clamp_to_webgl2_defaults(desktop.clone(), DownlevelProfile::Full),
            desktop
        );
    }

    #[test]
    fn webgl2_clamp_of_desktop_limits_matches_the_webgl2_fake_in_every_clamped_field() {
        // Simulates what `FRUST_ENGINE_DOWNLEVEL=1` rehearses: a desktop
        // adapter's full limits run through the same clamp `TierCaps::probe`
        // applies. The clamped fields must land exactly on `fake(WebGl2)`'s
        // values — the rehearsal is worthless if it does not actually
        // reproduce the downlevel shape a real GLES-3.0/WebGL2 host would
        // report.
        let desktop = wgpu::Limits::defaults();
        let clamped = clamp_to_webgl2_defaults(desktop, DownlevelProfile::WebGl2);
        let webgl2_fake = TierCaps::fake(DownlevelProfile::WebGl2);
        assert_eq!(
            clamped.max_texture_dimension_2d,
            webgl2_fake.max_texture_dimension_2d
        );
        assert_eq!(
            clamped.max_texture_array_layers,
            webgl2_fake.max_texture_array_layers
        );
        assert_eq!(clamped.max_bind_groups, webgl2_fake.max_bind_groups);
        assert_eq!(
            saturating_u32(clamped.max_uniform_buffer_binding_size),
            webgl2_fake.max_uniform_buffer_binding_size
        );
        assert_eq!(
            clamped.min_uniform_buffer_offset_alignment,
            webgl2_fake.min_uniform_buffer_offset_alignment
        );
        assert_eq!(
            clamped.max_vertex_attributes,
            webgl2_fake.max_vertex_attributes
        );
    }

    #[test]
    fn webgl2_clamp_never_lowers_the_alignment_floor_below_the_adapters_own_value() {
        let stricter = wgpu::Limits {
            min_uniform_buffer_offset_alignment: 512,
            ..wgpu::Limits::defaults()
        };
        let clamped = clamp_to_webgl2_defaults(stricter, DownlevelProfile::WebGl2);
        assert_eq!(clamped.min_uniform_buffer_offset_alignment, 512);
    }

    #[test]
    fn webgl2_clamp_never_raises_a_real_adapter_ceiling_past_its_own_hardware_limit() {
        // A real (non-desktop) `Gl` adapter reporting something even lower
        // than the WebGL2 default must not be raised past its own hardware
        // ceiling.
        let constrained = wgpu::Limits {
            max_texture_dimension_2d: 1024,
            ..wgpu::Limits::defaults()
        };
        let clamped = clamp_to_webgl2_defaults(constrained, DownlevelProfile::WebGl2);
        assert_eq!(clamped.max_texture_dimension_2d, 1024);
    }

    #[test]
    fn probe_downlevel_override_forces_storage_buffers_off_via_probe_semantics() {
        // `probe` cannot be exercised without a real `wgpu::Adapter`, so this
        // asserts the same has_storage_buffers policy `probe` applies:
        // forced false whenever the resolved profile is WebGl2, regardless of
        // what the underlying (possibly desktop) limits report.
        let desktop = wgpu::Limits::defaults();
        assert!(
            desktop.max_storage_buffers_per_shader_stage > 0,
            "fixture precondition"
        );
        let clamped = clamp_to_webgl2_defaults(desktop, DownlevelProfile::WebGl2);
        // The clamp itself does not touch max_storage_buffers_per_shader_stage
        // (probe's `has_storage_buffers` line is a separate, explicit force);
        // this documents that split so a future edit to the clamp cannot
        // silently reintroduce storage buffers under the override.
        assert!(clamped.max_storage_buffers_per_shader_stage > 0);
    }
}