1use crate::effect_cost::{ARITHMETIC_UNITS, EffectCost, FETCH_UNITS, TRANSCENDENTAL_UNITS};
13
14pub(crate) const PLANNING_THRESHOLD_UNIT_PIXELS: f64 = 64.0 * 1_048_576.0;
17
18pub(crate) const MAX_BANDS: u32 = 64;
20
21pub(crate) const COMPOSITE_LAYER_COST: EffectCost = EffectCost::fixed(4, 0);
23pub(crate) const VECTOR_COST: EffectCost = EffectCost::fixed(2, 0);
25
26#[derive(Copy, Clone, Debug, Default, PartialEq)]
28pub struct FrameCost {
29 pub fetches: f64,
31 pub transcendentals: f64,
33 pub arithmetic: f64,
35}
36
37impl FrameCost {
38 #[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#[derive(Copy, Clone, Debug, Default, PartialEq)]
58pub struct FrameSubmissions {
59 pub submissions: u32,
61 pub predicted_ms: Option<f64>,
63 pub cost: FrameCost,
65}
66
67#[derive(Copy, Clone, Debug, PartialEq, Eq)]
68pub(crate) struct PassPlacement {
69 pub(crate) cut_before: bool,
71 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 current_ms: f64,
88 finished_ms: Vec<f64>,
90 band_ms: f64,
92 cost: FrameCost,
93 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 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 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
220const 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 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 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: ¶ms,
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
365pub(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 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 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}