Skip to main content

alpha2_render/
renderer.rs

1use crate::{BlendSpace, Color, RenderError, RenderSize, RenderedTexture};
2use alpha2_gpu::GpuContext;
3use alpha2_gpu::IntermediateFormat;
4use alpha2_gpu::SubmitTimings;
5use std::sync::{Arc, Mutex};
6use std::time::Duration;
7
8/// Renders graphs of sources, effects, transitions and composites on one GPU
9/// device, and owns the pipelines, pools and caches they use.
10#[derive(Debug)]
11pub struct Renderer {
12    pub(crate) gpu: GpuContext,
13    pub(crate) blend_space: BlendSpace,
14    pub(crate) effects: std::sync::RwLock<crate::registry::EffectRegistry>,
15    pub(crate) effect_resources: std::sync::RwLock<crate::effect_resource::EffectResourceRegistry>,
16    pub(crate) textures: crate::Shared<crate::pool::TexturePool>,
17    pub(crate) upload_textures: crate::Shared<crate::pool::UploadTexturePool>,
18    /// Device memory budget in bytes, 0 when unknown.
19    pub(crate) gpu_memory_budget: std::sync::atomic::AtomicU64,
20    requested_texture_budget: std::sync::atomic::AtomicU64,
21    pub(crate) readback_buffers: crate::Shared<crate::pool::ReadbackBufferPool>,
22    pub(crate) uniform_buffers: crate::Shared<crate::uniform::UniformBufferPool>,
23    pub(crate) retirement: crate::Shared<crate::retire::Retirement>,
24    pub(crate) linear_sampler: crate::bind_group::LinearSampler,
25    pub(crate) pipelines: crate::pipeline::PipelineCache,
26    pub(crate) diagnostics: crate::diagnostics::SharedDiagnostics,
27    pub(crate) quality: Mutex<QualityState>,
28    pub(crate) result_cache: Mutex<crate::result_cache::ResultCache>,
29    pub(crate) vector_state: Mutex<crate::vector::VectorState>,
30    pub(crate) timestamp_probe: std::sync::OnceLock<Option<crate::runtime_effect::TimestampProbe>>,
31    /// Timestamp queries for sampled export frames, created on first use.
32    pub(crate) frame_gpu_timer: std::sync::OnceLock<Option<crate::frame_gpu_time::FrameGpuTimer>>,
33    pub(crate) pass_timing: std::sync::atomic::AtomicBool,
34    /// Test-only: composite every layer full-frame as the culling reference.
35    #[cfg(test)]
36    pub(crate) full_frame_layers: std::sync::atomic::AtomicBool,
37    /// Test-only: max layers per composite pass when nonzero (1 = batching reference).
38    #[cfg(test)]
39    pub(crate) composite_batch_limit: std::sync::atomic::AtomicUsize,
40    /// Test-only: tile rows per vector atlas page when nonzero.
41    #[cfg(test)]
42    pub(crate) vector_page_rows: std::sync::atomic::AtomicU32,
43    /// Test-only: composite pipeline log.
44    #[cfg(test)]
45    pub(crate) composite_pipelines: Mutex<crate::composite::CompositePipelineLog>,
46    /// Test-only: the next lazily created composite or effect pipeline fails to create.
47    #[cfg(test)]
48    pub(crate) fail_next_pipeline: std::sync::atomic::AtomicBool,
49    pub(crate) retired_leases: Arc<crate::yuv::RetiredLeases>,
50    pub(crate) gpu_wait_timeout: Duration,
51    /// Read once because every field read crosses into JavaScript on the browser backend.
52    pub(crate) limits: wgpu::Limits,
53    pub(crate) features: wgpu::Features,
54    /// Bound to a generator's unused image inputs.
55    pub(crate) empty_input: wgpu::TextureView,
56    pub(crate) canaries: crate::canary::Canaries,
57    pub(crate) submission_canaries: crate::canary::SubmissionCanaries,
58    /// GPU errors the embedding saw outside the renderer's own scopes.
59    pub(crate) gpu_errors: crate::GpuErrorReports,
60    pub(crate) frame_lock: crate::Shared<FrameLock>,
61    pub(crate) submission_clock: Arc<crate::submission_clock::SubmissionClock>,
62    pub(crate) last_frame_submissions: Mutex<Option<crate::FrameSubmissions>>,
63    pub(crate) calibration: std::sync::OnceLock<crate::registry::RegisteredEffect>,
64}
65
66/// A command encoder open until submitted.
67///
68/// Pooled resources released meanwhile are destroyed only after submission (see
69/// [`crate::retire`]). It also holds the frame's error scopes, so it must stay on the creating
70/// thread, and the [`FrameLock`]. A heavy frame may be split into several command buffers
71/// ([`crate::submission_planner`]); finished ones wait here for the submission.
72#[derive(Debug)]
73pub(crate) struct RenderEncoder {
74    encoder: wgpu::CommandEncoder,
75    finished: Vec<wgpu::CommandBuffer>,
76    planner: crate::submission_planner::SubmissionPlanner,
77    device: wgpu::Device,
78    label: &'static str,
79    errors: crate::gpu_errors::FrameErrorScope,
80    scope: crate::retire::EncodeScope,
81    frame: FrameGuard,
82}
83
84/// Lets one thread at a time record and submit renderer work.
85///
86/// A graph returns intermediates to the pool once their last reader is encoded, while the
87/// passes that wrote them are still unsubmitted. Holding this lock from encoder creation to
88/// submission stops another thread from reusing such a texture and submitting first.
89/// Re-entrant for the holding thread.
90#[derive(Debug, Default)]
91pub(crate) struct FrameLock {
92    owner: Mutex<Option<(std::thread::ThreadId, usize)>>,
93    released: std::sync::Condvar,
94}
95
96#[derive(Debug)]
97pub(crate) struct FrameGuard {
98    lock: crate::Shared<FrameLock>,
99}
100
101impl FrameLock {
102    pub(crate) fn hold(self: &crate::Shared<Self>) -> FrameGuard {
103        let me = std::thread::current().id();
104        let mut owner = self
105            .owner
106            .lock()
107            .unwrap_or_else(std::sync::PoisonError::into_inner);
108        loop {
109            match owner.as_mut() {
110                None => {
111                    *owner = Some((me, 1));
112                    break;
113                }
114                Some((thread, depth)) if *thread == me => {
115                    *depth += 1;
116                    break;
117                }
118                Some(_) => {
119                    owner = self
120                        .released
121                        .wait(owner)
122                        .unwrap_or_else(std::sync::PoisonError::into_inner);
123                }
124            }
125        }
126        drop(owner);
127        FrameGuard {
128            lock: crate::Shared::clone(self),
129        }
130    }
131}
132
133impl Drop for FrameGuard {
134    fn drop(&mut self) {
135        let mut owner = self
136            .lock
137            .owner
138            .lock()
139            .unwrap_or_else(std::sync::PoisonError::into_inner);
140        if let Some((_, depth)) = owner.as_mut() {
141            *depth -= 1;
142            if *depth == 0 {
143                *owner = None;
144                drop(owner);
145                self.lock.released.notify_all();
146            }
147        }
148    }
149}
150
151impl std::ops::Deref for RenderEncoder {
152    type Target = wgpu::CommandEncoder;
153
154    fn deref(&self) -> &Self::Target {
155        &self.encoder
156    }
157}
158
159impl std::ops::DerefMut for RenderEncoder {
160    fn deref_mut(&mut self) -> &mut Self::Target {
161        &mut self.encoder
162    }
163}
164
165impl RenderEncoder {
166    pub(crate) fn finish(self) -> RenderCommands {
167        let mut buffers = self.finished;
168        buffers.push(self.encoder.finish());
169        RenderCommands {
170            buffers,
171            planner: self.planner,
172            errors: self.errors,
173            scope: self.scope,
174            frame: self.frame,
175        }
176    }
177
178    pub(crate) const fn planner(&mut self) -> &mut crate::submission_planner::SubmissionPlanner {
179        &mut self.planner
180    }
181
182    /// Charges a pass doing `work` to the plan and places it, finishing the command buffer first
183    /// when the plan says so; `effect` names the pass in each command buffer it is encoded into.
184    pub(crate) fn place_pass(
185        &mut self,
186        work: crate::FrameCost,
187        region: crate::composite::PixelRect,
188        bandable: bool,
189        pass: Option<alpha2_gpu::PassKey>,
190        effect: Option<&crate::EffectId>,
191    ) -> crate::submission_planner::PassPlacement {
192        let placement = self.planner.pass(work, region, bandable, pass);
193        self.apply(placement, effect);
194        placement
195    }
196
197    pub(crate) fn apply(
198        &mut self,
199        placement: crate::submission_planner::PassPlacement,
200        effect: Option<&crate::EffectId>,
201    ) {
202        if placement.cut_before {
203            self.cut();
204        }
205        self.planner.name_placed(effect);
206    }
207
208    pub(crate) fn encode_pieces(
209        &mut self,
210        placement: crate::submission_planner::PassPlacement,
211        region: crate::composite::PixelRect,
212        mut encode: impl FnMut(&mut wgpu::CommandEncoder, crate::submission_planner::Piece),
213    ) {
214        use crate::submission_planner::Piece;
215        if let Some(rows) = placement.pilot {
216            let rows = crate::composite::PixelRect {
217                height: rows.min(region.height),
218                ..region
219            };
220            encode(&mut self.encoder, Piece::first(Some(rows)));
221            return;
222        }
223        let pieces = placement.pieces;
224        if pieces.count() <= 1 {
225            encode(&mut self.encoder, Piece::first(None));
226            return;
227        }
228        for index in 0..pieces.count() {
229            if index > 0 {
230                self.next_band();
231            }
232            let scissor = pieces.rect(index, region);
233            if index == 0 || scissor.area() > 0 {
234                encode(
235                    &mut self.encoder,
236                    Piece {
237                        scissor: Some(scissor),
238                        first: index == 0,
239                    },
240                );
241            }
242        }
243    }
244
245    pub(crate) fn next_band(&mut self) {
246        self.planner.next_band();
247        self.cut();
248    }
249
250    fn cut(&mut self) {
251        #[allow(clippy::disallowed_methods)]
252        let next = self
253            .device
254            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
255                label: Some(self.label),
256            });
257        let done = std::mem::replace(&mut self.encoder, next);
258        self.finished.push(done.finish());
259    }
260}
261
262pub(crate) trait PassEncoder {
263    fn commands(&mut self) -> &mut wgpu::CommandEncoder;
264
265    fn placed_pass(
266        &mut self,
267        work: crate::FrameCost,
268        region: crate::composite::PixelRect,
269        pass: alpha2_gpu::PassKey,
270        encode: impl FnMut(&mut wgpu::CommandEncoder, crate::submission_planner::Piece),
271    );
272
273    fn place_whole(&mut self, work: crate::FrameCost);
274}
275
276impl PassEncoder for RenderEncoder {
277    fn commands(&mut self) -> &mut wgpu::CommandEncoder {
278        &mut self.encoder
279    }
280
281    fn placed_pass(
282        &mut self,
283        work: crate::FrameCost,
284        region: crate::composite::PixelRect,
285        pass: alpha2_gpu::PassKey,
286        encode: impl FnMut(&mut wgpu::CommandEncoder, crate::submission_planner::Piece),
287    ) {
288        let placement = self.place_pass(work, region, true, Some(pass), None);
289        self.encode_pieces(placement, region, encode);
290    }
291
292    fn place_whole(&mut self, work: crate::FrameCost) {
293        self.place_pass(work, crate::composite::PixelRect::EMPTY, false, None, None);
294    }
295}
296
297impl PassEncoder for wgpu::CommandEncoder {
298    fn commands(&mut self) -> &mut wgpu::CommandEncoder {
299        self
300    }
301
302    fn placed_pass(
303        &mut self,
304        _work: crate::FrameCost,
305        _region: crate::composite::PixelRect,
306        _pass: alpha2_gpu::PassKey,
307        mut encode: impl FnMut(&mut wgpu::CommandEncoder, crate::submission_planner::Piece),
308    ) {
309        encode(self, crate::submission_planner::Piece::first(None));
310    }
311
312    fn place_whole(&mut self, _work: crate::FrameCost) {}
313}
314
315#[derive(Debug)]
316pub(crate) struct RenderCommands {
317    buffers: Vec<wgpu::CommandBuffer>,
318    planner: crate::submission_planner::SubmissionPlanner,
319    errors: crate::gpu_errors::FrameErrorScope,
320    scope: crate::retire::EncodeScope,
321    frame: FrameGuard,
322}
323
324/// Classifies a loss by the submission times of its renderer.
325#[derive(Clone, Debug)]
326pub struct LossClassifier(Arc<crate::submission_clock::SubmissionClock>);
327
328impl LossClassifier {
329    /// Classifies `error` as [`Renderer::classify_loss`] does.
330    #[must_use]
331    pub fn classify(&self, error: RenderError) -> RenderError {
332        match error {
333            RenderError::GpuWorkDropped
334            | RenderError::GpuDeviceLost
335            | RenderError::GpuTimeout
336            | RenderError::ExternalTextureSync(Some(alpha2_media::GpuFault::DeviceLost)) => {
337                self.0.hung().map_or(error, |report| report.hung_error())
338            }
339            error => error,
340        }
341    }
342
343    /// The recent submission that kept the GPU busy longest.
344    #[must_use]
345    pub fn longest_submission(&self) -> Option<crate::SubmissionReport> {
346        self.0.longest()
347    }
348
349    /// The recent submission that makes [`Self::classify`] report a loss as hung, if any.
350    #[must_use]
351    pub fn hung_submission(&self) -> Option<crate::SubmissionReport> {
352        self.0.hung()
353    }
354}
355
356struct SubmittedBuffers {
357    index: wgpu::SubmissionIndex,
358    earlier: Vec<(wgpu::SubmissionIndex, u64)>,
359    timings: SubmitTimings,
360    sequences: std::ops::Range<u64>,
361    first: (web_time::Instant, crate::submission_clock::Recorded),
362}
363
364pub(crate) struct MeasuredSubmit {
365    pub(crate) submission: crate::submission_clock::ClockedSubmission,
366    pub(crate) sequences: std::ops::Range<u64>,
367    pub(crate) queue_idle: bool,
368    pub(crate) timings: SubmitTimings,
369    pub(crate) lease_retire: Duration,
370}
371
372/// Quality controls consumed by pass execution.
373#[derive(Copy, Clone, Debug, Eq, PartialEq)]
374#[non_exhaustive]
375pub struct RenderQualityControls {
376    /// Maximum samples for filter effects and layer minification. Analytic edge coverage stays
377    /// on even with a one-sample budget.
378    pub max_filter_samples: u32,
379}
380
381impl RenderQualityControls {
382    /// Upper bound on filter samples; every pass caps there, so a larger budget changes nothing.
383    pub const MAX_FILTER_SAMPLES: u32 = 64;
384}
385
386impl Default for RenderQualityControls {
387    fn default() -> Self {
388        Self {
389            max_filter_samples: Self::MAX_FILTER_SAMPLES,
390        }
391    }
392}
393
394#[derive(Copy, Clone, Debug)]
395pub(crate) struct QualityState {
396    applied: RenderQualityControls,
397    requested_filter_samples: u32,
398}
399
400impl QualityState {
401    fn new(limit: u32) -> Self {
402        let requested = RenderQualityControls::default();
403        Self {
404            applied: RenderQualityControls {
405                max_filter_samples: requested.max_filter_samples.min(limit),
406            },
407            requested_filter_samples: requested.max_filter_samples,
408        }
409    }
410}
411
412impl Renderer {
413    pub(crate) fn uniform_alignment(&self) -> u64 {
414        u64::from(self.limits.min_uniform_buffer_offset_alignment.max(1))
415    }
416
417    pub(crate) fn validate_size(&self, size: RenderSize) -> Result<(), RenderError> {
418        RenderSize::new(size.width, size.height)?;
419        let maximum = self.limits.max_texture_dimension_2d;
420        if size.width > maximum || size.height > maximum {
421            return Err(RenderError::DimensionTooLarge);
422        }
423        Ok(())
424    }
425
426    /// Creates a renderer that owns the supplied GPU context.
427    #[must_use]
428    pub fn new(gpu: GpuContext) -> Self {
429        #[allow(clippy::disallowed_methods)]
430        let limits = gpu.device().limits();
431        let uniform_alignment = u64::from(limits.min_uniform_buffer_offset_alignment.max(1));
432        let features = gpu.device().features();
433        let filter_sample_limit = crate::filter_sample_limit(gpu.capabilities().tier);
434        let retirement = crate::Shared::new(crate::retire::Retirement::default());
435        let gpu_errors = crate::GpuErrorReports::default();
436        let submission_clock = Arc::new(crate::submission_clock::SubmissionClock::default());
437        let canaries = crate::canary::Canaries::new(
438            gpu_errors.clone(),
439            &retirement,
440            Arc::clone(&submission_clock),
441        );
442        let empty_input =
443            crate::pool::default_view(&gpu.device().create_texture(&wgpu::TextureDescriptor {
444                label: Some("alpha2 generator empty input"),
445                size: wgpu::Extent3d {
446                    width: 1,
447                    height: 1,
448                    depth_or_array_layers: 1,
449                },
450                mip_level_count: 1,
451                sample_count: 1,
452                dimension: wgpu::TextureDimension::D2,
453                format: wgpu::TextureFormat::Rgba8Unorm,
454                usage: wgpu::TextureUsages::TEXTURE_BINDING,
455                view_formats: &[],
456            }));
457        retirement.bind_groups.adopt_texture(empty_input.texture());
458        let linear_sampler =
459            crate::bind_group::LinearSampler::new(gpu.device(), &retirement.bind_groups);
460        let textures = crate::Shared::new(crate::pool::TexturePool::new(crate::Shared::clone(
461            &retirement,
462        )));
463        let requested_texture_budget =
464            std::sync::atomic::AtomicU64::new(textures.stats().budget_bytes);
465        Self {
466            gpu,
467            blend_space: BlendSpace::default(),
468            effects: std::sync::RwLock::default(),
469            effect_resources: std::sync::RwLock::default(),
470            textures,
471            upload_textures: crate::Shared::new(crate::pool::UploadTexturePool::new(
472                crate::Shared::clone(&retirement),
473            )),
474            gpu_memory_budget: std::sync::atomic::AtomicU64::new(0),
475            requested_texture_budget,
476            readback_buffers: crate::Shared::new(crate::pool::ReadbackBufferPool::new(
477                crate::Shared::clone(&retirement),
478            )),
479            uniform_buffers: crate::Shared::new(crate::uniform::UniformBufferPool::new(
480                uniform_alignment,
481                crate::Shared::clone(&retirement),
482            )),
483            retirement,
484            linear_sampler,
485            pipelines: crate::pipeline::PipelineCache::default(),
486            diagnostics: Arc::new(Mutex::new(crate::diagnostics::DiagnosticsState::default())),
487            quality: Mutex::new(QualityState::new(filter_sample_limit)),
488            result_cache: Mutex::new(crate::result_cache::ResultCache::default()),
489            vector_state: Mutex::default(),
490            timestamp_probe: std::sync::OnceLock::new(),
491            frame_gpu_timer: std::sync::OnceLock::new(),
492            pass_timing: std::sync::atomic::AtomicBool::new(false),
493            #[cfg(test)]
494            full_frame_layers: std::sync::atomic::AtomicBool::new(false),
495            #[cfg(test)]
496            composite_batch_limit: std::sync::atomic::AtomicUsize::new(0),
497            #[cfg(test)]
498            vector_page_rows: std::sync::atomic::AtomicU32::new(0),
499            #[cfg(test)]
500            composite_pipelines: Mutex::new(crate::composite::CompositePipelineLog::default()),
501            #[cfg(test)]
502            fail_next_pipeline: std::sync::atomic::AtomicBool::new(false),
503            retired_leases: Arc::new(crate::yuv::RetiredLeases::default()),
504            gpu_wait_timeout: crate::error::DEFAULT_GPU_WAIT_TIMEOUT,
505            limits,
506            features,
507            empty_input,
508            canaries,
509            submission_canaries: crate::canary::SubmissionCanaries::default(),
510            gpu_errors,
511            frame_lock: crate::Shared::default(),
512            submission_clock,
513            last_frame_submissions: Mutex::new(None),
514            calibration: std::sync::OnceLock::new(),
515        }
516    }
517
518    /// `None` on a device without timestamp queries, and in a browser.
519    pub(crate) fn frame_gpu_timer(&self) -> Option<&crate::frame_gpu_time::FrameGpuTimer> {
520        self.frame_gpu_timer
521            .get_or_init(|| {
522                (cfg!(not(target_arch = "wasm32"))
523                    && self.features.contains(wgpu::Features::TIMESTAMP_QUERY))
524                .then(|| {
525                    crate::frame_gpu_time::FrameGpuTimer::new(self.gpu.device(), self.gpu.queue())
526                })
527            })
528            .as_ref()
529    }
530
531    /// GPU time of the export frames sampled since the last call, then resets the totals.
532    ///
533    /// Every eighth frame of [`Self::render_graph_nv12_timed`], of
534    /// [`Self::render_graph_yuv420p_timed`] or of a timed [`Self::render_graph_layout_readback`] is
535    /// timed and read back later without waiting.
536    ///
537    /// # Errors
538    /// The device has no timestamp queries.
539    pub fn take_frame_gpu_times(&self) -> Result<crate::FrameGpuTimes, &'static str> {
540        let timer = self
541            .frame_gpu_timer()
542            .ok_or("the device has no timestamp queries")?;
543        let _ = self.gpu.device().poll(wgpu::PollType::Poll);
544        Ok(timer.take())
545    }
546
547    /// Where an embedding reports errors from its uncaptured-error handler.
548    ///
549    /// Needed only in a browser, where error scopes resolve after the frame returns. After a
550    /// report the renderer drops its cached results and pooled resources, and treats a missing
551    /// readback canary as that error rather than as dropped work.
552    #[must_use]
553    pub fn gpu_error_reports(&self) -> crate::GpuErrorReports {
554        self.gpu_errors.clone()
555    }
556
557    /// This renderer, using `reports` for GPU errors the embedding saw before it existed.
558    #[must_use]
559    pub fn with_gpu_error_reports(mut self, reports: crate::GpuErrorReports) -> Self {
560        self.canaries.clear();
561        self.canaries = crate::canary::Canaries::new(
562            reports.clone(),
563            &self.retirement,
564            Arc::clone(&self.submission_clock),
565        );
566        self.gpu_errors = reports;
567        self
568    }
569
570    pub(crate) fn forget_after_reported_errors(&self) {
571        if self.gpu_errors.take_unhandled() {
572            self.clear_result_cache_for(crate::CacheInvalidation::GpuError);
573            self.forget_untrusted_resources();
574        }
575    }
576
577    /// Drops pooled resources after the GPU reported an error that may involve them.
578    fn forget_untrusted_resources(&self) {
579        self.retirement.doubt();
580        self.textures.clear();
581        self.upload_textures.clear();
582        self.readback_buffers.clear();
583        self.uniform_buffers.clear();
584        self.canaries.clear();
585    }
586
587    /// Tier, intermediate format, adapter and limits of the GPU.
588    #[must_use]
589    pub fn gpu_capabilities(&self) -> &alpha2_gpu::Capabilities {
590        self.gpu.capabilities()
591    }
592
593    /// The device's limits.
594    #[must_use]
595    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
596    pub const fn limits(&self) -> &wgpu::Limits {
597        &self.limits
598    }
599
600    /// Sets how long a native GPU wait may take before [`RenderError::GpuTimeout`].
601    pub fn set_gpu_wait_timeout(&mut self, timeout: Duration) {
602        self.gpu_wait_timeout = timeout;
603    }
604
605    /// Why the device can no longer run work, once known.
606    ///
607    /// Either a readback canary showed dropped work ([`RenderError::GpuWorkDropped`]) or resources
608    /// could no longer be created ([`RenderError::GpuDeviceLost`]). Later readbacks and NV12 packs
609    /// fail with this error; a host should report it and restart the process.
610    #[must_use]
611    pub fn gpu_lost(&self) -> Option<RenderError> {
612        self.canaries.lost()
613    }
614
615    /// Marks the frame later submissions render, for [`RenderError::GpuDeviceHung`] reports.
616    pub fn mark_frame(&self, frame: Option<crate::FrameMark>) {
617        self.submission_clock.mark_frame(frame);
618    }
619
620    /// The recent submission, possibly still running, that kept the GPU busy longest.
621    #[must_use]
622    pub fn longest_submission(&self) -> Option<crate::SubmissionReport> {
623        self.submission_clock.longest()
624    }
625
626    /// The recent submission that makes [`Self::classify_loss`] report a loss as hung, if any.
627    #[must_use]
628    pub fn hung_submission(&self) -> Option<crate::SubmissionReport> {
629        self.submission_clock.hung()
630    }
631
632    /// Classifies `error` using this renderer's submission times.
633    ///
634    /// A device loss or timeout becomes [`RenderError::GpuDeviceHung`] when a recent submission
635    /// ran for at least half the GPU watchdog ([`alpha2_gpu::hung_threshold_ms`]), or submissions
636    /// completed together did and ran more than [`alpha2_gpu::MARGIN`] times their predicted
637    /// time. Other errors pass through.
638    #[must_use]
639    pub fn classify_loss(&self, error: RenderError) -> RenderError {
640        self.loss_classifier().classify(error)
641    }
642
643    /// [`Renderer::classify_loss`] as an owned handle, for readbacks finished on an event loop.
644    #[must_use]
645    pub fn loss_classifier(&self) -> LossClassifier {
646        LossClassifier(Arc::clone(&self.submission_clock))
647    }
648
649    pub(crate) fn ensure_gpu_runs_work(&self) -> Result<(), RenderError> {
650        self.canaries.lost().map_or(Ok(()), Err)
651    }
652
653    /// Checks canaries of earlier NV12 packs and repacks that have mapped, without waiting.
654    pub(crate) fn check_submitted_work(&self) -> Result<(), RenderError> {
655        // Map callbacks run only on poll; a hardware-encoder frame loop may not poll otherwise.
656        let _ = self.gpu.device().poll(wgpu::PollType::Poll);
657        self.submission_canaries.check_mapped()?;
658        self.ensure_gpu_runs_work()
659    }
660
661    /// Waits for every submitted NV12 pack and repack and checks that the GPU ran it.
662    ///
663    /// These submissions read nothing back, so a canary is the only proof the planes were written.
664    /// Exports call this after the last frame. Safe while another thread polls the device (the
665    /// macOS `VideoToolbox` worker does).
666    ///
667    /// # Errors
668    /// [`RenderError::GpuWorkDropped`] when a canary is missing, or [`RenderError::GpuTimeout`]
669    /// when work or a mapping report does not arrive in time.
670    #[cfg(not(target_arch = "wasm32"))]
671    pub fn confirm_gpu_work(&self) -> Result<(), RenderError> {
672        let deadline = web_time::Instant::now() + self.gpu_wait_timeout;
673        self.gpu
674            .device()
675            .poll(wgpu::PollType::Wait {
676                submission_index: None,
677                timeout: Some(self.gpu_wait_timeout),
678            })
679            .map_err(crate::error::poll_error)?;
680        let settled = self.settle(&self.submission_canaries.reports, deadline, || {
681            self.check_submitted_work()?;
682            Ok(self.submission_canaries.outstanding() == 0)
683        })?;
684        if settled {
685            Ok(())
686        } else {
687            Err(RenderError::GpuTimeout)
688        }
689    }
690
691    /// How long a native wait on GPU work may take.
692    #[must_use]
693    pub const fn gpu_wait_timeout(&self) -> Duration {
694        self.gpu_wait_timeout
695    }
696
697    /// Releases every native lease whose GPU work has finished, returning how many.
698    ///
699    /// A decoder surface returns only after the submission sampling it completes, so a caller out
700    /// of surface budget can call this and retry. Unsubmitted work is not waited on.
701    ///
702    /// # Errors
703    /// A readback error if the device cannot be polled.
704    #[cfg(not(target_arch = "wasm32"))]
705    pub fn reclaim_external_leases(&self) -> Result<usize, RenderError> {
706        let deadline = web_time::Instant::now() + self.gpu_wait_timeout;
707        self.gpu
708            .device()
709            .poll(wgpu::PollType::Wait {
710                submission_index: None,
711                timeout: Some(self.gpu_wait_timeout),
712            })
713            .map_err(crate::error::poll_error)?;
714        self.settle(&self.retired_leases.parks, deadline, || {
715            Ok(self.retired_leases.awaited() == 0)
716        })?;
717        Ok(self.retired_leases.drain())
718    }
719
720    /// Submits command buffers, then releases completed native leases.
721    ///
722    /// Leases must not be released inside `wgpu`'s submit: a shared-queue backend holds the decoder
723    /// queue lock there, and freeing a frame takes `FFmpeg`'s frame lock, which `FFmpeg` decode
724    /// threads take in the opposite order.
725    ///
726    /// # Errors
727    /// [`RenderError::Gpu`] when a scope caught an error; then nothing in the submission ran.
728    pub(crate) fn submit<I>(
729        &self,
730        commands: I,
731    ) -> Result<crate::submission_clock::ClockedSubmission, RenderError>
732    where
733        I: IntoIterator<Item = RenderCommands>,
734    {
735        self.submit_measured(commands, false)
736            .map(|submitted| submitted.submission)
737    }
738
739    /// Opens a command encoder and the error scopes its submission closes.
740    ///
741    /// Open it before acquiring the frame's targets so a failed allocation is the frame's error.
742    pub(crate) fn command_encoder(&self, label: &'static str) -> RenderEncoder {
743        self.forget_after_reported_errors();
744        // Wait for other frames before opening any scope of this one.
745        let frame = self.frame_lock.hold();
746        // Open first so nothing the encoder uses can be destroyed under it.
747        let scope = self.retirement.open();
748        let errors = crate::gpu_errors::FrameErrorScope::open(
749            self.gpu.device(),
750            crate::Shared::clone(&self.retirement),
751        );
752        #[allow(clippy::disallowed_methods)] // The one place a renderer encoder is created.
753        let encoder = self
754            .gpu
755            .device()
756            .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some(label) });
757        RenderEncoder {
758            encoder,
759            finished: Vec::new(),
760            planner: crate::submission_planner::SubmissionPlanner::default(),
761            device: self.gpu.device().clone(),
762            label,
763            errors,
764            scope,
765            frame,
766        }
767    }
768
769    pub(crate) fn bind_group(&self, descriptor: &wgpu::BindGroupDescriptor<'_>) -> wgpu::BindGroup {
770        self.retirement.bind_groups.create(
771            self.gpu.device(),
772            descriptor,
773            self.retirement.submitted_frames(),
774        )
775    }
776
777    /// Defers destruction of released pool resources until the returned scope is dropped.
778    pub(crate) fn open_encode(&self) -> crate::retire::EncodeScope {
779        self.retirement.open()
780    }
781
782    /// Submits and reports the queue wait, submit and lease drain times.
783    ///
784    /// With `measure` false every span is zero; the submission clock still records it.
785    ///
786    /// # Errors
787    /// [`RenderError::Gpu`] when a scope caught an error; pooled resources are no longer trusted.
788    pub(crate) fn submit_measured<I>(
789        &self,
790        commands: I,
791        measure: bool,
792    ) -> Result<MeasuredSubmit, RenderError>
793    where
794        I: IntoIterator<Item = RenderCommands>,
795    {
796        let mut command_buffers = Vec::new();
797        let mut errors = Vec::new();
798        let mut scopes = Vec::new();
799        let mut frames = Vec::new();
800        let mut planners = Vec::new();
801        for commands in commands {
802            command_buffers.extend(
803                commands
804                    .buffers
805                    .into_iter()
806                    .map(|buffer| (buffer, None, Vec::new())),
807            );
808            if let Some(buffer_ms) = commands.planner.buffer_ms() {
809                let first = command_buffers.len() - buffer_ms.len();
810                for (slot, ms) in command_buffers[first..].iter_mut().zip(buffer_ms) {
811                    slot.1 = Some(ms);
812                }
813            }
814            let buffer_effects = commands.planner.buffer_effects();
815            let first = command_buffers.len() - buffer_effects.len();
816            for (slot, effects) in command_buffers[first..].iter_mut().zip(buffer_effects) {
817                slot.2 = effects;
818            }
819            planners.push(commands.planner);
820            errors.push(commands.errors);
821            scopes.push(commands.scope);
822            frames.push(commands.frame);
823        }
824        let watch_previous = planners
825            .iter()
826            .any(|planner| planner.is_frame() && planner.is_planned());
827        let submitted = self.submit_buffers(command_buffers, measure, watch_previous);
828        self.note_frame_submissions(&planners, &submitted);
829        let SubmittedBuffers {
830            index,
831            earlier,
832            timings,
833            sequences,
834            first: (_, first),
835        } = submitted;
836        let queue_idle = first.queue_idle;
837        // Scopes close after the submit, in reverse order.
838        let mut caught = None;
839        for scope in errors.into_iter().rev() {
840            caught = match (caught, scope.close()) {
841                (Some(alpha2_gpu::GpuErrorKind::OutOfMemory), _) | (_, None) => caught,
842                (_, kind) => kind,
843            };
844        }
845        drop(scopes);
846        drop(frames);
847        let drain_started = measure.then(web_time::Instant::now);
848        self.retired_leases.drain();
849        if let Some(kind) = caught {
850            self.forget_untrusted_resources();
851            return Err(RenderError::Gpu { kind });
852        }
853        Ok(MeasuredSubmit {
854            submission: crate::submission_clock::ClockedSubmission::new(
855                index,
856                Arc::clone(&self.submission_clock),
857                sequences.end - 1,
858            )
859            .after(earlier),
860            sequences,
861            queue_idle,
862            timings,
863            lease_retire: drain_started.map_or(Duration::ZERO, |started| started.elapsed()),
864        })
865    }
866
867    /// Submits `buffers` in one submission, or one per buffer when the frame was split so the GPU
868    /// can be preempted between them. Every submission is timed for loss classification.
869    fn submit_buffers(
870        &self,
871        buffers: Vec<(wgpu::CommandBuffer, Option<f64>, Vec<String>)>,
872        measure: bool,
873        watch_previous: bool,
874    ) -> SubmittedBuffers {
875        let submit = |buffers: Vec<wgpu::CommandBuffer>,
876                      predicted_ms: Option<f64>,
877                      effects: Vec<String>,
878                      watch_previous: bool| {
879            let (index, timings) = if measure {
880                self.gpu.submit_timed(buffers)
881            } else {
882                (self.gpu.submit(buffers), SubmitTimings::default())
883            };
884            let at = web_time::Instant::now();
885            let recorded = self
886                .submission_clock
887                .record(at, predicted_ms, effects, watch_previous);
888            let sequence = recorded.sequence;
889            let clock = Arc::clone(&self.submission_clock);
890            self.gpu.on_submitted_work_done(move || {
891                let as_it_happens = clock.sees_as_it_happens(sequence);
892                clock.complete(sequence, web_time::Instant::now(), as_it_happens);
893            });
894            (index, timings, sequence, (at, recorded))
895        };
896        if buffers.len() <= 1 || buffers.iter().all(|(_, ms, _)| ms.is_none()) {
897            let predicted_ms = buffers
898                .iter()
899                .filter_map(|(_, ms, _)| *ms)
900                .reduce(|a, b| a + b);
901            let mut effects: Vec<String> = Vec::new();
902            for effect in buffers.iter().flat_map(|(_, _, effects)| effects) {
903                if !effects.contains(effect) {
904                    effects.push(effect.clone());
905                }
906            }
907            let (index, timings, sequence, first) = submit(
908                buffers.into_iter().map(|(buffer, _, _)| buffer).collect(),
909                predicted_ms,
910                effects,
911                watch_previous,
912            );
913            return SubmittedBuffers {
914                index,
915                earlier: Vec::new(),
916                timings,
917                sequences: sequence..sequence + 1,
918                first,
919            };
920        }
921        let mut total = SubmitTimings::default();
922        let mut last: Option<(wgpu::SubmissionIndex, u64)> = None;
923        let mut earlier = Vec::new();
924        let mut first = None;
925        for (buffer, predicted_ms, effects) in buffers {
926            let (index, timings, sequence, started) = submit(
927                vec![buffer],
928                predicted_ms,
929                effects,
930                watch_previous && first.is_none(),
931            );
932            total.queue_lock_wait = total
933                .queue_lock_wait
934                .saturating_add(timings.queue_lock_wait);
935            total.queue_submit = total.queue_submit.saturating_add(timings.queue_submit);
936            first.get_or_insert((sequence, started));
937            earlier.extend(last.replace((index, sequence)));
938        }
939        let (index, last_sequence) = last.expect("at least two buffers");
940        let (first_sequence, first) = first.expect("at least two buffers");
941        SubmittedBuffers {
942            index,
943            earlier,
944            timings: total,
945            sequences: first_sequence..last_sequence + 1,
946            first,
947        }
948    }
949
950    /// Records frame submissions and folds measured GPU time into the device rate on completion.
951    fn note_frame_submissions(
952        &self,
953        planners: &[crate::submission_planner::SubmissionPlanner],
954        submitted: &SubmittedBuffers,
955    ) {
956        let Some(planner) = planners.iter().find(|planner| planner.is_frame()) else {
957            return;
958        };
959        let submissions =
960            u32::try_from(submitted.sequences.end - submitted.sequences.start).unwrap_or(u32::MAX);
961        let buffer_ms = planner.buffer_ms();
962        let report = crate::FrameSubmissions {
963            submissions,
964            predicted_ms: buffer_ms.as_ref().map(|buffers| buffers.iter().sum()),
965            cost: planner.cost(),
966        };
967        crate::diagnostics::record_frame_plan(
968            &self.diagnostics,
969            &report,
970            buffer_ms.as_deref().unwrap_or_default(),
971            planner.planned_at().map(|(_, budget_ms)| budget_ms),
972        );
973        *self
974            .last_frame_submissions
975            .lock()
976            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(report);
977        if let (Some(predicted_ms), Some((planned_ms_per_unit_pixel, budget_ms))) =
978            (report.predicted_ms, planner.planned_at())
979        {
980            let device_rated_ms = planner.device_rated_ms();
981            let clock = Arc::clone(&self.submission_clock);
982            let rate = Arc::clone(self.gpu.rate());
983            let last = submitted.sequences.end - 1;
984            let (submitted_at, first) = submitted.first.clone();
985            self.gpu.on_submitted_work_done(move || {
986                let Some(started) = first.started(submitted_at) else {
987                    return;
988                };
989                let trust = if clock.sees_as_it_happens(last) {
990                    alpha2_gpu::SpanTrust::Exact
991                } else {
992                    alpha2_gpu::SpanTrust::UpperBound
993                };
994                rate.observe(alpha2_gpu::FrameMeasurement {
995                    measured_ms: started.elapsed().as_secs_f64() * 1_000.0,
996                    predicted_ms,
997                    device_rated_ms,
998                    planned_ms_per_unit_pixel,
999                    budget_ms,
1000                    trust,
1001                });
1002            });
1003        }
1004    }
1005
1006    /// How the last frame was submitted; each frame's is returned once.
1007    pub fn take_frame_submissions(&self) -> Option<crate::FrameSubmissions> {
1008        self.last_frame_submissions
1009            .lock()
1010            .unwrap_or_else(std::sync::PoisonError::into_inner)
1011            .take()
1012    }
1013
1014    /// Submission split counts since the last call, then resets them.
1015    pub fn take_gpu_submission_stats(&self) -> crate::GpuSubmissionStats {
1016        crate::diagnostics::take_gpu_submission_stats(&self.diagnostics)
1017    }
1018
1019    /// Returns whether per-pass timing is being collected.
1020    #[must_use]
1021    pub fn pass_timing_enabled(&self) -> bool {
1022        self.pass_timing.load(std::sync::atomic::Ordering::Relaxed)
1023    }
1024
1025    /// Enables or disables per-pass timing collection. Disabled by default.
1026    ///
1027    /// While off, no clock is read and no timestamp resources are created. Turning it off drops
1028    /// the retained timing history. Other diagnostics are always available.
1029    pub fn set_pass_timing_enabled(&self, enabled: bool) {
1030        self.pass_timing
1031            .store(enabled, std::sync::atomic::Ordering::Relaxed);
1032        if !enabled {
1033            crate::diagnostics::end_timing_run(&self.diagnostics);
1034        }
1035    }
1036
1037    /// The timing run a pass encoded now records into, or `None` while timing is off. Read before
1038    /// the flag: a run that ends after this read drops the pass's record.
1039    pub(crate) fn pass_timing_epoch(&self) -> Option<u64> {
1040        let epoch = crate::diagnostics::timing_epoch(&self.diagnostics);
1041        self.pass_timing_enabled().then_some(epoch)
1042    }
1043
1044    /// Capability-negotiated storage precision. Graph images hold premultiplied sRGB; layer blends
1045    /// may use linear light.
1046    #[must_use]
1047    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
1048    pub fn intermediate_format(&self) -> wgpu::TextureFormat {
1049        match self.gpu.capabilities().intermediate_format {
1050            IntermediateFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
1051            _ => wgpu::TextureFormat::Rgba8Unorm,
1052        }
1053    }
1054
1055    /// Returns allocation and reuse counters for intermediate render targets.
1056    #[must_use]
1057    pub fn texture_pool_stats(&self) -> crate::TexturePoolStats {
1058        self.textures.stats()
1059    }
1060
1061    /// Acquires a pooled RGBA8 source-upload texture.
1062    ///
1063    /// Submissions using it must be issued before the handle is dropped so later uploads stay
1064    /// queue-ordered.
1065    ///
1066    /// # Errors
1067    /// The dimensions exceed device limits.
1068    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
1069    pub fn acquire_rgba8_upload_texture(
1070        &self,
1071        size: RenderSize,
1072    ) -> Result<crate::UploadTexture, RenderError> {
1073        self.validate_size(size)?;
1074        Ok(self.upload_textures.acquire(
1075            self.gpu.device(),
1076            size,
1077            wgpu::TextureFormat::Rgba8Unorm,
1078            "alpha2 RGBA upload texture",
1079        ))
1080    }
1081
1082    /// Destroys all currently idle intermediate textures.
1083    pub fn clear_texture_pool(&self) {
1084        self.textures.clear();
1085    }
1086
1087    /// Destroys GPU memory held only for reuse (idle pools and kept graph results) and returns the
1088    /// bytes freed.
1089    ///
1090    /// Resources are destroyed rather than dropped so browser `WebGPU` frees them immediately.
1091    /// Nothing still in use is released, and submitted work completes first, so this is safe
1092    /// between calls.
1093    pub fn release_idle_memory(&self) -> u64 {
1094        let before = self.retirement.retired_bytes();
1095        self.clear_result_cache();
1096        self.textures.clear();
1097        self.upload_textures.clear();
1098        self.readback_buffers.clear();
1099        self.uniform_buffers.clear();
1100        self.canaries.clear();
1101        self.retirement.bind_groups.clear();
1102        self.vector_state
1103            .lock()
1104            .unwrap_or_else(std::sync::PoisonError::into_inner)
1105            .cache
1106            .clear();
1107        self.retirement.retired_bytes().saturating_sub(before)
1108    }
1109
1110    /// Sets the byte budget for idle intermediate textures beyond what recent frames had in use,
1111    /// evicting down to it now.
1112    ///
1113    /// The budget is capped at a quarter of [`Self::gpu_memory_budget`]; a reduction is reported
1114    /// as [`crate::CapabilityDiagnostic::TextureBudgetReduced`].
1115    pub fn set_texture_budget_bytes(&self, budget_bytes: u64) {
1116        self.requested_texture_budget
1117            .store(budget_bytes, std::sync::atomic::Ordering::Relaxed);
1118        self.textures
1119            .set_budget(budget_bytes.min(self.pool_budget_cap()));
1120    }
1121
1122    /// Records the adapter's memory budget (`None` if unreported) and caps idle pools at a quarter
1123    /// of it. A frame whose own textures need more than the budget fails before it draws, with
1124    /// [`RenderError::FrameExceedsGpuMemory`]. Returns whether a pool budget was lowered.
1125    pub fn set_gpu_memory_budget(&self, budget_bytes: Option<u64>) -> bool {
1126        self.gpu_memory_budget.store(
1127            budget_bytes.unwrap_or(0),
1128            std::sync::atomic::Ordering::Relaxed,
1129        );
1130        let cap = self.pool_budget_cap();
1131        let textures = self.textures.stats().budget_bytes;
1132        let uploads = self.upload_textures.stats().budget_bytes;
1133        if textures > cap {
1134            self.textures.set_budget(cap);
1135        }
1136        if uploads > cap {
1137            self.upload_textures.set_budget(cap);
1138        }
1139        textures > cap || uploads > cap
1140    }
1141
1142    /// The adapter's device memory budget, when reported.
1143    #[must_use]
1144    pub fn gpu_memory_budget(&self) -> Option<u64> {
1145        match self
1146            .gpu_memory_budget
1147            .load(std::sync::atomic::Ordering::Relaxed)
1148        {
1149            0 => None,
1150            bytes => Some(bytes),
1151        }
1152    }
1153
1154    /// A quarter of the device memory budget, or unlimited when unknown.
1155    fn pool_budget_cap(&self) -> u64 {
1156        self.gpu_memory_budget().map_or(u64::MAX, |bytes| bytes / 4)
1157    }
1158
1159    /// Applies the filter sample budget.
1160    ///
1161    /// The budget is capped at [`Self::filter_sample_limit`]; a reduction is reported as
1162    /// [`crate::CapabilityDiagnostic::FilterSamplesReduced`]. Kept results are dropped only when
1163    /// the applied budget changes.
1164    pub fn set_quality_controls(&self, max_filter_samples: u32) {
1165        let requested = max_filter_samples.max(1);
1166        let next = RenderQualityControls {
1167            max_filter_samples: requested.min(self.filter_sample_limit()),
1168        };
1169        let mut quality = self
1170            .quality
1171            .lock()
1172            .unwrap_or_else(std::sync::PoisonError::into_inner);
1173        quality.requested_filter_samples = requested;
1174        if quality.applied != next {
1175            quality.applied = next;
1176            self.clear_result_cache_for(crate::CacheInvalidation::Quality);
1177        }
1178    }
1179
1180    /// [`RenderQualityControls::MAX_FILTER_SAMPLES`], or 16 on a Tier-B device.
1181    #[must_use]
1182    pub fn filter_sample_limit(&self) -> u32 {
1183        crate::filter_sample_limit(self.gpu.capabilities().tier)
1184    }
1185
1186    /// Lets kept graph results use up to `budget_bytes` (see
1187    /// [`crate::RenderGraph::set_cache_intent`]); zero, the default, disables the cache. The
1188    /// texture pool budget does not count these results.
1189    pub fn set_result_cache_budget(&self, budget_bytes: u64) {
1190        self.lock_result_cache().set_budget(budget_bytes);
1191    }
1192
1193    /// Drops every kept graph result.
1194    pub fn clear_result_cache(&self) {
1195        self.clear_result_cache_for(crate::CacheInvalidation::Explicit);
1196    }
1197
1198    /// The result cache's counters.
1199    #[must_use]
1200    pub fn result_cache_stats(&self) -> crate::ResultCacheStats {
1201        self.lock_result_cache().stats()
1202    }
1203
1204    /// Changes whenever a graph with an unchanged [`Self::graph_cache_key`] may render differently
1205    /// (any result-cache clear or reported GPU error). Equal keys under an equal epoch mean equal
1206    /// pixels.
1207    #[must_use]
1208    pub fn content_epoch(&self) -> u64 {
1209        self.lock_result_cache()
1210            .clears()
1211            .wrapping_add(self.gpu_errors.count())
1212    }
1213
1214    pub(crate) fn clear_result_cache_for(&self, reason: crate::CacheInvalidation) {
1215        self.lock_result_cache().clear(reason);
1216    }
1217
1218    pub(crate) fn lock_result_cache(
1219        &self,
1220    ) -> std::sync::MutexGuard<'_, crate::result_cache::ResultCache> {
1221        self.result_cache
1222            .lock()
1223            .unwrap_or_else(std::sync::PoisonError::into_inner)
1224    }
1225
1226    /// Returns the active render quality controls.
1227    #[must_use]
1228    pub fn quality_controls(&self) -> RenderQualityControls {
1229        self.quality_state().applied
1230    }
1231
1232    fn quality_state(&self) -> QualityState {
1233        *self
1234            .quality
1235            .lock()
1236            .unwrap_or_else(std::sync::PoisonError::into_inner)
1237    }
1238
1239    fn degradations(&self) -> Vec<crate::CapabilityDiagnostic> {
1240        let mut degradations = Vec::new();
1241        let requested = self
1242            .requested_texture_budget
1243            .load(std::sync::atomic::Ordering::Relaxed);
1244        let applied = self.textures.stats().budget_bytes;
1245        if requested > applied {
1246            degradations
1247                .push(crate::CapabilityDiagnostic::TextureBudgetReduced { requested, applied });
1248        }
1249        let quality = self.quality_state();
1250        let (requested, applied) = (
1251            quality.requested_filter_samples,
1252            quality.applied.max_filter_samples,
1253        );
1254        if requested > applied {
1255            degradations
1256                .push(crate::CapabilityDiagnostic::FilterSamplesReduced { requested, applied });
1257        }
1258        degradations
1259    }
1260
1261    /// Returns a stable snapshot for telemetry or benchmark output.
1262    #[must_use]
1263    pub fn diagnostics(&self) -> crate::RenderDiagnostics {
1264        crate::diagnostics::snapshot(
1265            &self.diagnostics,
1266            self.gpu.capabilities(),
1267            &crate::diagnostics::ResourceDiagnostics {
1268                textures: self.texture_pool_stats(),
1269                upload_textures: self.upload_textures.stats(),
1270                readback_buffers: self.readback_buffers.stats(),
1271                uniform_buffers: self.uniform_buffers.stats(),
1272                pipelines: self.pipeline_cache_stats(),
1273                bind_groups: self.retirement.bind_groups.stats(),
1274                result_cache: self.result_cache_stats(),
1275            },
1276            self.quality_controls().max_filter_samples,
1277            self.degradations(),
1278        )
1279    }
1280
1281    /// Pipeline creations since the last call, oldest first (at most 256), with start and end
1282    /// times.
1283    pub fn take_pipeline_creations(&self) -> Vec<crate::PipelineCreation> {
1284        crate::diagnostics::take_pipeline_creations(&self.diagnostics)
1285    }
1286
1287    /// Records a host presentation outcome without imposing a product clock.
1288    pub fn record_frame_outcome(&self, presented: bool, repeated: bool) {
1289        crate::diagnostics::record_frame(&self.diagnostics, presented, repeated);
1290    }
1291
1292    /// Adds time spent waiting for a host decoder or refill operation.
1293    pub fn record_decoder_wait(&self, duration: Duration) {
1294        crate::diagnostics::record_decoder_wait(&self.diagnostics, duration);
1295    }
1296
1297    /// Returns the number of cached runtime and built-in pipelines.
1298    #[must_use]
1299    pub fn pipeline_cache_stats(&self) -> crate::PipelineCacheStats {
1300        crate::PipelineCacheStats {
1301            runtime_effects: self.effects().len(),
1302            builtins: self.pipelines.builtin_count(),
1303        }
1304    }
1305
1306    /// Selects the single color space used by all layer blending.
1307    #[must_use]
1308    pub const fn with_blend_space(mut self, blend_space: BlendSpace) -> Self {
1309        self.blend_space = blend_space;
1310        self
1311    }
1312
1313    /// Returns the configured layer-compositing color space.
1314    #[must_use]
1315    pub const fn blend_space(&self) -> BlendSpace {
1316        self.blend_space
1317    }
1318
1319    /// Clears an offscreen RGBA texture and submits it to the GPU queue.
1320    ///
1321    /// # Errors
1322    ///
1323    /// Returns [`RenderError`] for an invalid size or color.
1324    pub fn render_solid(
1325        &self,
1326        size: RenderSize,
1327        color: Color,
1328    ) -> Result<RenderedTexture, RenderError> {
1329        self.validate_size(size)?;
1330        if !color.is_valid() {
1331            return Err(RenderError::InvalidColor);
1332        }
1333        let format = self.intermediate_format();
1334        let mut encoder = self.command_encoder("alpha2 solid encoder");
1335        let texture = self.textures.acquire(
1336            self.gpu.device(),
1337            size,
1338            format,
1339            "alpha2 solid render target",
1340        );
1341        {
1342            let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1343                label: Some("alpha2 solid clear pass"),
1344                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1345                    view: texture.view(),
1346                    depth_slice: None,
1347                    resolve_target: None,
1348                    ops: wgpu::Operations {
1349                        load: wgpu::LoadOp::Clear(wgpu::Color {
1350                            r: color.red,
1351                            g: color.green,
1352                            b: color.blue,
1353                            a: color.alpha,
1354                        }),
1355                        store: wgpu::StoreOp::Store,
1356                    },
1357                })],
1358                depth_stencil_attachment: None,
1359                timestamp_writes: None,
1360                occlusion_query_set: None,
1361                multiview_mask: None,
1362            });
1363        }
1364        self.submit([encoder.finish()])?;
1365        Ok(RenderedTexture::pooled(size, format, texture))
1366    }
1367}