Skip to main content

alpha2_render/
submission_planner.rs

1//! Splits one frame's GPU work into submissions that each stay under the watchdog budget.
2//!
3//! A GPU that cannot preempt a long draw resets the device when one submission exceeds the OS
4//! timeout. Each pass's time is predicted from its cost ([`crate::effect_cost`]), covered pixels
5//! and the device rate ([`alpha2_gpu::GpuRate`]); a pass that would push the command buffer past
6//! [`alpha2_gpu::submission_budget_ms`] starts a new submission, and a single pass over budget
7//! is drawn in scissored horizontal bands, one submission each.
8//!
9//! Frames below [`PLANNING_THRESHOLD_UNIT_PIXELS`] stay one command buffer and need no rate.
10//! Splitting never changes pixels, only when the GPU starts each part.
11
12use crate::effect_cost::{ARITHMETIC_UNITS, EffectCost, FETCH_UNITS, TRANSCENDENTAL_UNITS};
13
14/// Frames at most this cost (64 units per pixel over a megapixel) are not planned; well under a
15/// millisecond on the slowest GPU measured.
16pub(crate) const PLANNING_THRESHOLD_UNIT_PIXELS: f64 = 64.0 * 1_048_576.0;
17
18/// The most bands a pass is drawn in.
19pub(crate) const MAX_BANDS: u32 = 64;
20
21/// Per covered pixel of a composite layer: texture read, minification taps and blend.
22pub(crate) const COMPOSITE_LAYER_COST: EffectCost = EffectCost::fixed(4, 0);
23/// Per covered pixel of a vector scene: coverage and paint reads.
24pub(crate) const VECTOR_COST: EffectCost = EffectCost::fixed(2, 0);
25
26/// A frame's predicted cost in unit pixels per kind of work.
27#[derive(Copy, Clone, Debug, Default, PartialEq)]
28pub struct FrameCost {
29    /// Texture reads.
30    pub fetches: f64,
31    /// Transcendental calls.
32    pub transcendentals: f64,
33    /// Other operators and calls.
34    pub arithmetic: f64,
35}
36
37impl FrameCost {
38    /// Weighted sum the rate applies to.
39    #[must_use]
40    #[allow(clippy::cast_precision_loss)]
41    pub fn unit_pixels(&self) -> f64 {
42        self.fetches * FETCH_UNITS as f64
43            + self.transcendentals * TRANSCENDENTAL_UNITS as f64
44            + self.arithmetic * ARITHMETIC_UNITS as f64
45    }
46
47    #[allow(clippy::cast_precision_loss)]
48    pub(crate) fn add(&mut self, cost: EffectCost, pixels: u64) {
49        let pixels = pixels as f64;
50        self.fetches += cost.fetches as f64 * pixels;
51        self.transcendentals += cost.transcendentals as f64 * pixels;
52        self.arithmetic += cost.arithmetic as f64 * pixels;
53    }
54}
55
56/// How one frame was submitted, as the renderer planned it.
57#[derive(Copy, Clone, Debug, Default, PartialEq)]
58pub struct FrameSubmissions {
59    /// Queue submissions the frame went in.
60    pub submissions: u32,
61    /// Predicted GPU time in milliseconds, when planned.
62    pub predicted_ms: Option<f64>,
63    /// The frame's predicted cost.
64    pub cost: FrameCost,
65}
66
67#[derive(Copy, Clone, Debug, PartialEq, Eq)]
68pub(crate) struct PassPlacement {
69    /// The current command buffer is finished before the pass.
70    pub(crate) cut_before: bool,
71    /// Bands the pass is drawn in, each in a command buffer of its own.
72    pub(crate) bands: u32,
73    pub(crate) pilot: Option<u32>,
74}
75
76#[derive(Debug)]
77struct Plan {
78    rate: std::sync::Arc<alpha2_gpu::GpuRate>,
79    ms_per_unit_pixel: f64,
80    budget_ms: f64,
81}
82
83#[derive(Debug, Default)]
84pub(crate) struct SubmissionPlanner {
85    plan: Option<Plan>,
86    /// Predicted milliseconds of the command buffer being recorded.
87    current_ms: f64,
88    /// Predicted milliseconds of each command buffer finished before it.
89    finished_ms: Vec<f64>,
90    /// Time of each remaining band of a banded pass.
91    band_ms: f64,
92    cost: FrameCost,
93    /// Set once a graph was encoded.
94    frame: bool,
95    pilot_rows: Option<u32>,
96}
97
98impl SubmissionPlanner {
99    pub(crate) fn plan(
100        &mut self,
101        rate: std::sync::Arc<alpha2_gpu::GpuRate>,
102        ms_per_unit_pixel: f64,
103        budget_ms: f64,
104    ) {
105        self.plan = Some(Plan {
106            rate,
107            ms_per_unit_pixel,
108            budget_ms: budget_ms.max(f64::MIN_POSITIVE),
109        });
110    }
111
112    pub(crate) const fn mark_frame(&mut self) {
113        self.frame = true;
114    }
115
116    pub(crate) const fn mark_pilot(&mut self, rows: u32) {
117        self.pilot_rows = Some(rows);
118    }
119
120    /// Charges a pass of `cost` over `pixels` and places it, at the rate measured for `pass` when
121    /// that is slower than the device. A pass that is not `bandable` only gets its own command
122    /// buffer.
123    pub(crate) fn pass(
124        &mut self,
125        cost: EffectCost,
126        pixels: u64,
127        bandable: bool,
128        pass: Option<alpha2_gpu::PassKey>,
129    ) -> PassPlacement {
130        self.cost.add(cost, pixels);
131        if let (Some(rows), true) = (self.pilot_rows, bandable) {
132            return PassPlacement {
133                cut_before: false,
134                bands: 1,
135                pilot: Some(rows),
136            };
137        }
138        let Some(plan) = &self.plan else {
139            return PassPlacement {
140                cut_before: false,
141                bands: 1,
142                pilot: None,
143            };
144        };
145        let budget = plan.budget_ms;
146        let rate = plan.rate.planning_rate(plan.ms_per_unit_pixel, pass);
147        #[allow(clippy::cast_precision_loss)]
148        let ms = cost.units() as f64 * pixels as f64 * rate;
149        self.place(ms, budget, bandable)
150    }
151
152    fn place(&mut self, ms: f64, budget: f64, bandable: bool) -> PassPlacement {
153        if ms > budget {
154            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
155            let bands = if bandable {
156                ((ms / budget).ceil() as u32).clamp(1, MAX_BANDS)
157            } else {
158                1
159            };
160            let cut_before = self.current_ms > 0.0;
161            if cut_before {
162                self.finished_ms.push(self.current_ms);
163            }
164            self.band_ms = ms / f64::from(bands);
165            self.current_ms = self.band_ms;
166            return PassPlacement {
167                cut_before,
168                bands,
169                pilot: None,
170            };
171        }
172        let cut_before = self.current_ms > 0.0 && self.current_ms + ms > budget;
173        if cut_before {
174            self.finished_ms.push(self.current_ms);
175            self.current_ms = 0.0;
176        }
177        self.current_ms += ms;
178        PassPlacement {
179            cut_before,
180            bands: 1,
181            pilot: None,
182        }
183    }
184
185    pub(crate) fn next_band(&mut self) {
186        self.finished_ms.push(self.current_ms);
187        self.current_ms = self.band_ms;
188    }
189
190    pub(crate) const fn is_planned(&self) -> bool {
191        self.plan.is_some()
192    }
193
194    pub(crate) const fn is_frame(&self) -> bool {
195        self.frame
196    }
197
198    pub(crate) const fn cost(&self) -> FrameCost {
199        self.cost
200    }
201
202    pub(crate) fn planned_at(&self) -> Option<(f64, f64)> {
203        self.plan
204            .as_ref()
205            .map(|plan| (plan.ms_per_unit_pixel, plan.budget_ms))
206    }
207
208    /// Each command buffer's predicted milliseconds, when planned.
209    pub(crate) fn buffer_ms(&self) -> Option<Vec<f64>> {
210        self.plan.as_ref().map(|_| {
211            let mut buffers = self.finished_ms.clone();
212            buffers.push(self.current_ms);
213            buffers
214        })
215    }
216}
217
218const CALIBRATION_SIDE: u32 = 512;
219
220/// 64 iterations of an offset texture read and a sine, close to heavy effects' per-unit cost.
221const CALIBRATION_BODY: &str = "\
222fn effect(uv: vec2f, src: vec4f) -> vec4f {
223    var acc = src;
224    for (var i = 0u; i < 64u; i++) {
225        let s = sample_src(fract(uv + vec2f(f32(i) * 0.0019, f32(i) * 0.0007)));
226        acc = vec4f(sin(acc.r * 1.37 + s.g), acc.g, acc.b, acc.a);
227    }
228    return acc;
229}
230";
231
232fn calibration_definition() -> crate::EffectDef {
233    crate::EffectDef {
234        id: "alpha2.internal.calibrate".into(),
235        version: 1,
236        kind: crate::EffectKind::Effect,
237        inputs: Vec::new(),
238        params: Vec::new(),
239        resources: Vec::new(),
240        wgsl_body: CALIBRATION_BODY.into(),
241        tier_min: alpha2_gpu::CapabilityTier::TierB,
242        license: None,
243    }
244}
245
246const CALIBRATION_DRAWS: u32 = 4;
247
248impl crate::Renderer {
249    /// Plans the frame when `cost` exceeds [`PLANNING_THRESHOLD_UNIT_PIXELS`], at the device rate
250    /// calibrated by the first such frame and again when frames disagree with it. A browser
251    /// cannot wait for calibration, so it assumes [`alpha2_gpu::UNCALIBRATED_MS_PER_UNIT_PIXEL`]
252    /// meanwhile.
253    pub(crate) fn plan_submissions(
254        &self,
255        encoder: &mut crate::renderer::RenderEncoder,
256        cost: FrameCost,
257    ) {
258        encoder.planner().mark_frame();
259        if cost.unit_pixels() <= PLANNING_THRESHOLD_UNIT_PIXELS {
260            return;
261        }
262        let rate = self.gpu.rate();
263        if rate.begin_calibration() && self.calibrate().is_err() {
264            rate.abandon_calibration();
265        }
266        let ms_per_unit_pixel = rate
267            .ms_per_unit_pixel()
268            .unwrap_or(alpha2_gpu::UNCALIBRATED_MS_PER_UNIT_PIXEL);
269        encoder.planner().plan(
270            std::sync::Arc::clone(rate),
271            ms_per_unit_pixel,
272            f64::from(alpha2_gpu::submission_budget_ms()),
273        );
274    }
275
276    /// Draws the calibration effect [`CALIBRATION_DRAWS`] times at 512x512, one submission each,
277    /// and seeds the device rate on completion.
278    ///
279    /// Natively each draw is waited for and the fastest timed one is kept. A browser cannot
280    /// wait, so it uses the mean of the summed span, cold draw included.
281    fn calibrate(&self) -> Result<(), crate::RenderError> {
282        let effect = self
283            .calibration
284            .get_or_init(|| crate::registry::registered_effect(calibration_definition()));
285        let id = crate::EffectId::new(effect.definition.id.clone(), effect.definition.version);
286        let size = crate::RenderSize::new(CALIBRATION_SIDE, CALIBRATION_SIDE)?;
287        let format = self.intermediate_format();
288        let params = crate::EffectParams::new();
289        let resources = crate::EffectResources::new();
290        #[allow(clippy::cast_precision_loss)]
291        let unit_pixels =
292            effect.cost.units() as f64 * f64::from(CALIBRATION_SIDE) * f64::from(CALIBRATION_SIDE);
293        #[cfg(not(target_arch = "wasm32"))]
294        let mut fastest: Option<f64> = None;
295        #[cfg(target_arch = "wasm32")]
296        let mut sequences: Option<std::ops::Range<u64>> = None;
297        for draw in 0..CALIBRATION_DRAWS {
298            let mut encoder = self.command_encoder("alpha2 calibration encoder");
299            let source =
300                self.textures
301                    .acquire(self.gpu.device(), size, format, "alpha2 calibration source");
302            let target =
303                self.textures
304                    .acquire(self.gpu.device(), size, format, "alpha2 calibration target");
305            let mut uniforms = self.uniform_buffers.acquire(self.gpu.device(), 4096);
306            self.encode_registered_pass(
307                &mut encoder,
308                effect,
309                crate::runtime_effect::EffectPass {
310                    id: &id,
311                    kind: crate::RenderNodeKind::Effect,
312                    source_a: source.view(),
313                    source_b: None,
314                    inputs: &[],
315                    size,
316                    params: &params,
317                    resources: &resources,
318                    runtime: crate::EffectRuntime::default(),
319                    output: target.view(),
320                },
321                &mut uniforms,
322            )?;
323            uniforms.flush(self.gpu.queue());
324            let submitted = self.submit_measured([encoder.finish()], false)?;
325            uniforms.recycle();
326            #[cfg(not(target_arch = "wasm32"))]
327            {
328                submitted
329                    .submission
330                    .wait(&self.gpu, self.gpu_wait_timeout)?;
331                if draw > 0
332                    && let Some(ms) = self.submission_clock.gpu_ms(submitted.sequences.clone())
333                {
334                    fastest = Some(fastest.map_or(ms, |fastest| fastest.min(ms)));
335                }
336            }
337            #[cfg(target_arch = "wasm32")]
338            {
339                let _ = draw;
340                sequences = Some(sequences.map_or(submitted.sequences.clone(), |sequences| {
341                    sequences.start..submitted.sequences.end
342                }));
343            }
344        }
345        let rate = std::sync::Arc::clone(self.gpu.rate());
346        #[cfg(not(target_arch = "wasm32"))]
347        match fastest {
348            Some(ms) => rate.seed(ms / unit_pixels),
349            None => rate.abandon_calibration(),
350        }
351        #[cfg(target_arch = "wasm32")]
352        {
353            let clock = std::sync::Arc::clone(&self.submission_clock);
354            let sequences = sequences.expect("calibration draws");
355            self.gpu
356                .on_submitted_work_done(move || match clock.gpu_ms(sequences) {
357                    Some(ms) => rate.seed(ms / f64::from(CALIBRATION_DRAWS) / unit_pixels),
358                    None => rate.abandon_calibration(),
359                });
360        }
361        Ok(())
362    }
363}
364
365/// Scissor rows of band `band` of `bands` over `height` rows. Edges are on even rows so no 2x2
366/// derivative quad straddles two bands.
367pub(crate) fn band_rows(band: u32, bands: u32, height: u32) -> (u32, u32) {
368    let edge = |index: u32| -> u32 {
369        if index >= bands {
370            return height;
371        }
372        let row = u64::from(height) * u64::from(index) / u64::from(bands);
373        u32::try_from(row).unwrap_or(height) & !1
374    };
375    let top = edge(band);
376    (top, edge(band + 1).saturating_sub(top))
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    fn placed(cut_before: bool, bands: u32) -> PassPlacement {
384        PassPlacement {
385            cut_before,
386            bands,
387            pilot: None,
388        }
389    }
390
391    #[test]
392    fn passes_fill_a_buffer_up_to_the_budget_and_a_heavy_one_is_banded() {
393        let mut planner = SubmissionPlanner::default();
394        let pass = EffectCost {
395            fetches: 0,
396            transcendentals: 0,
397            arithmetic: 10,
398        };
399        assert_eq!(planner.pass(pass, 100, true, None).bands, 1);
400        assert_eq!(planner.buffer_ms(), None);
401        planner.plan(std::sync::Arc::default(), 1.0, 2_500.0);
402        // 1000 ms each: two fit, the third starts a new buffer.
403        assert!(!planner.pass(pass, 100, true, None).cut_before);
404        assert!(!planner.pass(pass, 100, true, None).cut_before);
405        assert!(planner.pass(pass, 100, true, None).cut_before);
406        // 10,000 ms: four bands of 2,500 after a cut.
407        let placement = planner.pass(pass, 1_000, true, None);
408        assert_eq!(placement, placed(true, 4));
409        for _ in 1..placement.bands {
410            planner.next_band();
411        }
412        assert_eq!(planner.pass(pass, 1_000, false, None), placed(true, 1));
413        assert_eq!(
414            planner.buffer_ms(),
415            Some(vec![
416                2_000.0, 1_000.0, 2_500.0, 2_500.0, 2_500.0, 2_500.0, 10_000.0
417            ])
418        );
419        assert!((planner.cost().unit_pixels() - 24_000.0).abs() < 1e-9);
420        assert_eq!(planner.planned_at(), Some((1.0, 2_500.0)));
421    }
422
423    #[test]
424    fn a_pass_measured_slower_than_the_device_is_banded_at_its_own_rate() {
425        let rate = std::sync::Arc::new(alpha2_gpu::GpuRate::default());
426        rate.seed(0.5);
427        let scattered = alpha2_gpu::PassKey::new(1, 100);
428        rate.record_pass_rate(scattered, 5.0);
429        let mut planner = SubmissionPlanner::default();
430        planner.plan(rate, 1.0, 2_500.0);
431        let pass = EffectCost {
432            fetches: 0,
433            transcendentals: 0,
434            arithmetic: 10,
435        };
436        assert_eq!(planner.pass(pass, 100, true, None), placed(false, 1));
437        assert_eq!(
438            planner.pass(pass, 100, true, Some(scattered)),
439            placed(true, 4)
440        );
441    }
442
443    #[test]
444    fn a_pilot_draws_its_rows_alone_and_plans_nothing() {
445        let mut planner = SubmissionPlanner::default();
446        planner.mark_pilot(6);
447        let pass = EffectCost::fixed(1, 0);
448        assert_eq!(
449            planner.pass(pass, 100, true, None),
450            PassPlacement {
451                cut_before: false,
452                bands: 1,
453                pilot: Some(6)
454            }
455        );
456        assert_eq!(planner.pass(pass, 100, false, None), placed(false, 1));
457        assert_eq!(planner.buffer_ms(), None);
458    }
459
460    #[test]
461    fn bands_cover_every_row_once_on_even_edges() {
462        for (bands, height) in [(1, 7), (3, 288), (7, 101), (64, 4320)] {
463            let mut next = 0;
464            for band in 0..bands {
465                let (top, rows) = band_rows(band, bands, height);
466                assert_eq!(top, next);
467                assert_eq!(top % 2, 0);
468                next = top + rows;
469            }
470            assert_eq!(next, height);
471        }
472    }
473}