Skip to main content

euv_core/game/engine3d/tsr/
impl.rs

1use super::*;
2
3/// Default empty `TsrUpscaler` with identity previous view-projection matrix.
4impl Default for TsrUpscaler {
5    /// Creates an empty `TsrUpscaler` ready to accumulate temporal history on the first frame.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Initialized TSR upscaler.
10    fn default() -> Self {
11        Self {
12            history_width: 0,
13            history_height: 0,
14            has_history: false,
15            prev_view_projection: Mat4::identity(),
16            accumulated_frames: 0,
17            history_rgba: Vec::new(),
18            next_history_rgba: Vec::new(),
19            history_inv_w: Vec::new(),
20            next_inv_w: Vec::new(),
21        }
22    }
23}
24
25/// Color-space helpers and analytical motion-vector temporal reconstruction for `TsrUpscaler`.
26impl TsrUpscaler {
27    /// Invalidates accumulated temporal history cleanly on camera cuts, teleports, or resolution changes.
28    pub fn invalidate_history(&mut self) {
29        self.set_has_history(false);
30        self.set_accumulated_frames(0);
31    }
32
33    /// Multiplies a 3D direction vector (`w = 0`) by a column-major 4x4 projection matrix.
34    ///
35    /// # Arguments
36    ///
37    /// - `&Mat4` - Column-major view-projection matrix.
38    /// - `Vec3` - 3D direction vector.
39    ///
40    /// # Returns
41    ///
42    /// - `[f32; 4]` - Homogeneous directional clip coordinates `(x, y, z, w)`.
43    #[cfg_attr(not(target_arch = "wasm32"), inline)]
44    #[must_use]
45    fn mul_dir4(mat: &Mat4, dir: Vec3) -> [f32; 4] {
46        let elems: [f32; 16] = mat.get_elements();
47        let dx: f32 = dir.get_x();
48        let dy: f32 = dir.get_y();
49        let dz: f32 = dir.get_z();
50        [
51            dx.mul_add(elems[0], dy.mul_add(elems[4], dz * elems[8])),
52            dx.mul_add(elems[1], dy.mul_add(elems[5], dz * elems[9])),
53            dx.mul_add(elems[2], dy.mul_add(elems[6], dz * elems[10])),
54            dx.mul_add(elems[3], dy.mul_add(elems[7], dz * elems[11])),
55        ]
56    }
57
58    /// Folds output viewport pixel scaling directly into a homogeneous clip vector `(cx, cy, _, cw) -> [sx_num, sy_num, cw]`.
59    ///
60    /// # Arguments
61    ///
62    /// - `[f32; 4]` - Homogeneous clip vector.
63    /// - `f32` - Half output width `dst_w * 0.5`.
64    /// - `f32` - Half output height `dst_h * 0.5`.
65    ///
66    /// # Returns
67    ///
68    /// - `[f32; 3]` - Screen-folded `[sx_numerator, sy_numerator, cw]` basis vector.
69    #[cfg_attr(not(target_arch = "wasm32"), inline)]
70    #[must_use]
71    fn fold_screen_basis(clip: [f32; 4], half_dw: f32, half_dh: f32) -> [f32; 3] {
72        let cx: f32 = clip[0];
73        let cy: f32 = clip[1];
74        let cw: f32 = clip[3];
75        [
76            cx.mul_add(half_dw, cw * (half_dw - 0.5)),
77            (-cy).mul_add(half_dh, cw * (half_dh - 0.5)),
78            cw,
79        ]
80    }
81
82    /// Packs RGB channels of an RGBA8 pixel into 16-bit SWAR lanes `0x0000_00BB_00GG_00RR`.
83    ///
84    /// # Arguments
85    ///
86    /// - `&[u8]` - Source RGBA8 buffer.
87    /// - `usize` - Byte offset of the pixel (`idx * 4`).
88    ///
89    /// # Returns
90    ///
91    /// - `u64` - Lane-packed 16-bit RGB word.
92    #[cfg_attr(not(target_arch = "wasm32"), inline)]
93    #[must_use]
94    fn load_swar_rgb(rgba: &[u8], byte_off: usize) -> u64 {
95        (rgba[byte_off] as u64)
96            | ((rgba[byte_off + 1] as u64) << 16)
97            | ((rgba[byte_off + 2] as u64) << 32)
98    }
99
100    /// Samples an RGBA8 image bilinearly via 64-bit SWAR fixed-point arithmetic using precomputed row offsets.
101    ///
102    /// # Arguments
103    ///
104    /// - `&[u8]` - Source RGBA8 buffer.
105    /// - `(usize, usize, u64)` - Precomputed `(row_y0_bytes, row_y1_bytes, wy_256)` row offsets and vertical weight.
106    /// - `(usize, usize, u64)` - `(x0_bytes, x1_bytes, wx_256)` horizontal byte offsets and weight.
107    ///
108    /// # Returns
109    ///
110    /// - `(u32, u32, u32)` - Bilinearly filtered `(r, g, b)` channels in `0..=255`.
111    #[cfg_attr(not(target_arch = "wasm32"), inline)]
112    #[must_use]
113    fn sample_swar_rows(
114        rgba: &[u8],
115        row_info: (usize, usize, u64),
116        col_info: (usize, usize, u64),
117    ) -> (u32, u32, u32) {
118        let (row0, row1, wy): (usize, usize, u64) = row_info;
119        let (x0_b, x1_b, wx): (usize, usize, u64) = col_info;
120        let inv_wx: u64 = 256 - wx;
121        let inv_wy: u64 = 256 - wy;
122        let c00: u64 = Self::load_swar_rgb(rgba, row0 + x0_b);
123        let c10: u64 = Self::load_swar_rgb(rgba, row0 + x1_b);
124        let c01: u64 = Self::load_swar_rgb(rgba, row1 + x0_b);
125        let c11: u64 = Self::load_swar_rgb(rgba, row1 + x1_b);
126        let top: u64 = ((c00 * inv_wx + c10 * wx + 0x0000_0080_0080_0080_u64) >> 8)
127            & 0x0000_00FF_00FF_00FF_u64;
128        let bot: u64 = ((c01 * inv_wx + c11 * wx + 0x0000_0080_0080_0080_u64) >> 8)
129            & 0x0000_00FF_00FF_00FF_u64;
130        let blended: u64 = ((top * inv_wy + bot * wy + 0x0000_0080_0080_0080_u64) >> 8)
131            & 0x0000_00FF_00FF_00FF_u64;
132        (
133            (blended & 0xFF) as u32,
134            ((blended >> 16) & 0xFF) as u32,
135            ((blended >> 32) & 0xFF) as u32,
136        )
137    }
138
139    /// Samples an RGBA8 image bilinearly at fractional pixel coordinates `(fx, fy)` via 64-bit SWAR fixed-point arithmetic.
140    ///
141    /// # Arguments
142    ///
143    /// - `&[u8]` - Source RGBA8 pixel buffer.
144    /// - `(usize, usize)` - Image `(width, height)` in pixels.
145    /// - `(f32, f32)` - Fractional `(fx, fy)` coordinates.
146    ///
147    /// # Returns
148    ///
149    /// - `(u32, u32, u32)` - Bilinearly filtered `(r, g, b)` channels in `0..=255`.
150    #[cfg_attr(not(target_arch = "wasm32"), inline)]
151    #[must_use]
152    fn sample_rgba_bilinear_swar(
153        rgba: &[u8],
154        dims: (usize, usize),
155        coords: (f32, f32),
156    ) -> (u32, u32, u32) {
157        let (width, height): (usize, usize) = dims;
158        let (fx, fy): (f32, f32) = coords;
159        let max_x: usize = width.saturating_sub(1);
160        let max_y: usize = height.saturating_sub(1);
161        let cx: f32 = fx.clamp(0.0, max_x as f32);
162        let cy: f32 = fy.clamp(0.0, max_y as f32);
163        let x0: usize = cx as usize;
164        let y0: usize = cy as usize;
165        let x1: usize = (x0 + 1).min(max_x);
166        let y1: usize = (y0 + 1).min(max_y);
167        let wx: u64 = ((cx - (x0 as f32)) * 256.0) as u64;
168        let wy: u64 = ((cy - (y0 as f32)) * 256.0) as u64;
169        let row_bytes: usize = width * 4;
170        Self::sample_swar_rows(
171            rgba,
172            (y0 * row_bytes, y1 * row_bytes, wy),
173            (x0 * 4, x1 * 4, wx),
174        )
175    }
176
177    /// Reconstructs a full-resolution temporally super-resolved RGBA8 frame from a sub-native render and reverse-Z depth buffer.
178    ///
179    /// # Arguments
180    ///
181    /// - `&[u8]` - Sub-native rendered RGBA8 frame (`src_width * src_height * 4`).
182    /// - `&[f32]` - Sub-native reverse-Z `1/w` depth buffer (`src_width * src_height`).
183    /// - `&TsrFrameParams` - Per-frame camera basis, projection, jitter, and sharpening configuration.
184    /// - `&mut Vec<u8>` - Destination full-resolution RGBA8 output buffer populated in-place without redundant allocations.
185    pub fn upscale_rgba(
186        &mut self,
187        src_rgba: &[u8],
188        src_depth: &[f32],
189        params: &TsrFrameParams,
190        out_rgba: &mut Vec<u8>,
191    ) {
192        let src_w: usize = params.get_src_width().max(1);
193        let src_h: usize = params.get_src_height().max(1);
194        let dst_w: usize = params.get_dst_width().max(1);
195        let dst_h: usize = params.get_dst_height().max(1);
196        let src_pixels: usize = src_w * src_h;
197        let dst_pixels: usize = dst_w * dst_h;
198        let dst_bytes: usize = dst_pixels * 4;
199        if src_rgba.len() < src_pixels * 4 || src_depth.len() < src_pixels {
200            out_rgba.clear();
201            return;
202        }
203        if self.get_history_width() != dst_w || self.get_history_height() != dst_h {
204            self.set_history_width(dst_w);
205            self.set_history_height(dst_h);
206            self.set_has_history(false);
207            self.set_accumulated_frames(0);
208            let Self {
209                history_rgba,
210                next_history_rgba,
211                history_inv_w,
212                next_inv_w,
213                ..
214            } = self;
215            history_rgba.resize(dst_bytes, 0);
216            next_history_rgba.resize(dst_bytes, 0);
217            history_inv_w.resize(dst_pixels, 0.0);
218            next_inv_w.resize(dst_pixels, 0.0);
219        }
220        out_rgba.clear();
221        if out_rgba.capacity() < dst_bytes {
222            out_rgba.reserve_exact(dst_bytes - out_rgba.capacity());
223        }
224        let has_hist: bool = self.get_has_history();
225        let prev_vp: Mat4 = self.get_prev_view_projection();
226        let inv_dst_w: f32 = 1.0 / (dst_w as f32);
227        let inv_dst_h: f32 = 1.0 / (dst_h as f32);
228        let scale_x: f32 = (src_w as f32) * inv_dst_w;
229        let scale_y: f32 = (src_h as f32) * inv_dst_h;
230        let (jit_x, jit_y): (f32, f32) = params.get_jitter_offset();
231        let sharp_i32: i32 = (params.get_sharpness().clamp(0.0, 0.5) * 256.0) as i32;
232        let dst_w_f: f32 = dst_w as f32;
233        let dst_h_f: f32 = dst_h as f32;
234        let half_dw: f32 = dst_w_f * 0.5;
235        let half_dh: f32 = dst_h_f * 0.5;
236        let max_ox: f32 = dst_w_f - 0.5;
237        let max_oy: f32 = dst_h_f - 0.5;
238        let src_w_max: usize = src_w.saturating_sub(1);
239        let src_h_max: usize = src_h.saturating_sub(1);
240        let src_w_max_f: f32 = src_w_max as f32;
241        let src_h_max_f: f32 = src_h_max as f32;
242        let dst_w_max: usize = dst_w.saturating_sub(1);
243        let dst_h_max: usize = dst_h.saturating_sub(1);
244        let src_row_bytes: usize = src_w * 4;
245        let cam_sc: [f32; 3] = Self::fold_screen_basis(
246            prev_vp.mul_point4(params.get_camera_position()),
247            half_dw,
248            half_dh,
249        );
250        let fwd_sc: [f32; 3] = Self::fold_screen_basis(
251            Self::mul_dir4(&prev_vp, params.get_camera_forward()),
252            half_dw,
253            half_dh,
254        );
255        let right_sc: [f32; 3] = Self::fold_screen_basis(
256            Self::mul_dir4(&prev_vp, params.get_camera_right_scaled()),
257            half_dw,
258            half_dh,
259        );
260        let up_sc: [f32; 3] = Self::fold_screen_basis(
261            Self::mul_dir4(&prev_vp, params.get_camera_up_scaled()),
262            half_dw,
263            half_dh,
264        );
265        let step_scale: f32 = 2.0 * inv_dst_w;
266        let step_sc: [f32; 3] = [
267            right_sc[0] * step_scale,
268            right_sc[1] * step_scale,
269            right_sc[2] * step_scale,
270        ];
271        let ndc_x0: f32 = inv_dst_w - 1.0;
272        let base_hist_w: f32 = TSR_BASE_HISTORY_WEIGHT * 256.0;
273        let delta_hist_w: f32 = (TSR_MOTION_HISTORY_WEIGHT - TSR_BASE_HISTORY_WEIGHT) * 256.0;
274        {
275            let Self {
276                history_rgba,
277                next_history_rgba,
278                history_inv_w,
279                next_inv_w,
280                ..
281            } = self;
282            let hist_rgba_ref: &[u8] = history_rgba.as_slice();
283            let hist_depth_ref: &[f32] = history_inv_w.as_slice();
284            let out_base: usize = out_rgba.as_mut_ptr() as usize;
285            let next_hist_base: usize = next_history_rgba.as_mut_ptr() as usize;
286            let next_depth_base: usize = next_inv_w.as_mut_ptr() as usize;
287            parallel_for_ranges(dst_h, TSR_PARALLEL_ROW_GRAIN, |y0: usize, y1: usize| {
288                for dst_y in y0..y1 {
289                    let row_out: usize = dst_y * dst_w;
290                    let ndc_y: f32 = 1.0 - 2.0 * (((dst_y as f32) + 0.5) * inv_dst_h);
291                    let mut ray_sx: f32 = fwd_sc[0] + up_sc[0] * ndc_y + right_sc[0] * ndc_x0;
292                    let mut ray_sy: f32 = fwd_sc[1] + up_sc[1] * ndc_y + right_sc[1] * ndc_x0;
293                    let mut ray_cw: f32 = fwd_sc[2] + up_sc[2] * ndc_y + right_sc[2] * ndc_x0;
294                    let sy_f: f32 =
295                        (((dst_y as f32) + 0.5) * scale_y - 0.5 - jit_y).clamp(0.0, src_h_max_f);
296                    let sy0: usize = sy_f as usize;
297                    let sy1: usize = (sy0 + 1).min(src_h_max);
298                    let wy_src: u64 = ((sy_f - (sy0 as f32)) * 256.0) as u64;
299                    let src_row0_b: usize = sy0 * src_row_bytes;
300                    let src_row1_b: usize = sy1 * src_row_bytes;
301                    let iy: usize = ((sy_f + 0.5) as usize).min(src_h_max);
302                    let row_iy: usize = iy * src_w;
303                    let row_up: usize = iy.saturating_sub(1) * src_w;
304                    let row_dn: usize = (iy + 1).min(src_h_max) * src_w;
305                    let mut sx_f: f32 = 0.5 * scale_x - 0.5 - jit_x;
306                    for dst_x in 0..dst_w {
307                        let clamped_sx: f32 = sx_f.clamp(0.0, src_w_max_f);
308                        let sx0: usize = clamped_sx as usize;
309                        let sx1: usize = (sx0 + 1).min(src_w_max);
310                        let wx_src: u64 = ((clamped_sx - (sx0 as f32)) * 256.0) as u64;
311                        let (mut out_r, mut out_g, mut out_b): (u32, u32, u32) =
312                            Self::sample_swar_rows(
313                                src_rgba,
314                                (src_row0_b, src_row1_b, wy_src),
315                                (sx0 * 4, sx1 * 4, wx_src),
316                            );
317                        let ix: usize = ((clamped_sx + 0.5) as usize).min(src_w_max);
318                        let c_idx: usize = row_iy + ix;
319                        let up_idx: usize = row_up + ix;
320                        let dn_idx: usize = row_dn + ix;
321                        let lt_idx: usize = row_iy + ix.saturating_sub(1);
322                        let rt_idx: usize = row_iy + (ix + 1).min(src_w_max);
323                        let dilated_inv_w: f32 = src_depth[c_idx]
324                            .max(src_depth[up_idx])
325                            .max(src_depth[dn_idx])
326                            .max(src_depth[lt_idx])
327                            .max(src_depth[rt_idx]);
328                        if dilated_inv_w > 1.0e-6 {
329                            let oc: usize = c_idx * 4;
330                            let ou: usize = up_idx * 4;
331                            let od: usize = dn_idx * 4;
332                            let ol: usize = lt_idx * 4;
333                            let or: usize = rt_idx * 4;
334                            let r0: u32 = src_rgba[oc] as u32;
335                            let r1: u32 = src_rgba[ou] as u32;
336                            let r2: u32 = src_rgba[od] as u32;
337                            let r3: u32 = src_rgba[ol] as u32;
338                            let r4: u32 = src_rgba[or] as u32;
339                            let g0: u32 = src_rgba[oc + 1] as u32;
340                            let g1: u32 = src_rgba[ou + 1] as u32;
341                            let g2: u32 = src_rgba[od + 1] as u32;
342                            let g3: u32 = src_rgba[ol + 1] as u32;
343                            let g4: u32 = src_rgba[or + 1] as u32;
344                            let b0: u32 = src_rgba[oc + 2] as u32;
345                            let b1: u32 = src_rgba[ou + 2] as u32;
346                            let b2: u32 = src_rgba[od + 2] as u32;
347                            let b3: u32 = src_rgba[ol + 2] as u32;
348                            let b4: u32 = src_rgba[or + 2] as u32;
349                            let min_r: u32 = r0.min(r1).min(r2).min(r3).min(r4);
350                            let max_r: u32 = r0.max(r1).max(r2).max(r3).max(r4);
351                            let min_g: u32 = g0.min(g1).min(g2).min(g3).min(g4);
352                            let max_g: u32 = g0.max(g1).max(g2).max(g3).max(g4);
353                            let min_b: u32 = b0.min(b1).min(b2).min(b3).min(b4);
354                            let max_b: u32 = b0.max(b1).max(b2).max(b3).max(b4);
355                            if has_hist {
356                                let cw: f32 = cam_sc[2].mul_add(dilated_inv_w, ray_cw);
357                                if cw > 0.15 * dilated_inv_w {
358                                    let inv_cw: f32 = 1.0 / cw;
359                                    let prev_ox: f32 =
360                                        cam_sc[0].mul_add(dilated_inv_w, ray_sx) * inv_cw;
361                                    let prev_oy: f32 =
362                                        cam_sc[1].mul_add(dilated_inv_w, ray_sy) * inv_cw;
363                                    if (-0.5..=max_ox).contains(&prev_ox)
364                                        && (-0.5..=max_oy).contains(&prev_oy)
365                                    {
366                                        let px_i: usize =
367                                            ((prev_ox + 0.5).max(0.0) as usize).min(dst_w_max);
368                                        let py_i: usize =
369                                            ((prev_oy + 0.5).max(0.0) as usize).min(dst_h_max);
370                                        let prev_stored_inv_w: f32 =
371                                            hist_depth_ref[py_i * dst_w + px_i];
372                                        if prev_stored_inv_w > 1.0e-6
373                                            && (dilated_inv_w - prev_stored_inv_w).abs()
374                                                <= dilated_inv_w.max(prev_stored_inv_w)
375                                                    * TSR_DISOCCLUSION_REL_DEPTH
376                                        {
377                                            let (hr, hg, hb): (u32, u32, u32) =
378                                                Self::sample_rgba_bilinear_swar(
379                                                    hist_rgba_ref,
380                                                    (dst_w, dst_h),
381                                                    (prev_ox, prev_oy),
382                                                );
383                                            let clamped_r: u32 = hr.clamp(min_r, max_r);
384                                            let clamped_g: u32 = hg.clamp(min_g, max_g);
385                                            let clamped_b: u32 = hb.clamp(min_b, max_b);
386                                            let motion_px: f32 = (prev_ox - (dst_x as f32))
387                                                .abs()
388                                                .max((prev_oy - (dst_y as f32)).abs());
389                                            let motion_t: f32 = (motion_px * 0.12).clamp(0.0, 1.0);
390                                            let hw: u32 =
391                                                delta_hist_w.mul_add(motion_t, base_hist_w) as u32;
392                                            let cw_i: u32 = 256 - hw;
393                                            out_r = (out_r * cw_i + clamped_r * hw + 128) >> 8;
394                                            out_g = (out_g * cw_i + clamped_g * hw + 128) >> 8;
395                                            out_b = (out_b * cw_i + clamped_b * hw + 128) >> 8;
396                                        }
397                                    }
398                                }
399                            }
400                            if sharp_i32 > 1 {
401                                let avg_r: i32 = ((r0 + r1 + r2 + r3 + r4 + 2) / 5) as i32;
402                                let avg_g: i32 = ((g0 + g1 + g2 + g3 + g4 + 2) / 5) as i32;
403                                let avg_b: i32 = ((b0 + b1 + b2 + b3 + b4 + 2) / 5) as i32;
404                                let sr: i32 =
405                                    (out_r as i32) + ((((out_r as i32) - avg_r) * sharp_i32) >> 8);
406                                let sg: i32 =
407                                    (out_g as i32) + ((((out_g as i32) - avg_g) * sharp_i32) >> 8);
408                                let sb: i32 =
409                                    (out_b as i32) + ((((out_b as i32) - avg_b) * sharp_i32) >> 8);
410                                out_r = sr.clamp(min_r as i32, max_r as i32) as u32;
411                                out_g = sg.clamp(min_g as i32, max_g as i32) as u32;
412                                out_b = sb.clamp(min_b as i32, max_b as i32) as u32;
413                            }
414                        }
415                        let dst_idx: usize = row_out + dst_x;
416                        let out_off: usize = dst_idx * 4;
417                        let packed: [u8; 4] = [out_r as u8, out_g as u8, out_b as u8, 255];
418                        // SAFETY: `parallel_for_ranges` partitions `0..dst_h` into strictly disjoint rows;
419                        // `out_rgba` and `next_history_rgba` have capacity `>= dst_bytes` and `next_inv_w` has length `dst_pixels`.
420                        unsafe {
421                            (out_base as *mut u8)
422                                .add(out_off)
423                                .cast::<[u8; 4]>()
424                                .write(packed);
425                            (next_hist_base as *mut u8)
426                                .add(out_off)
427                                .cast::<[u8; 4]>()
428                                .write(packed);
429                            *(next_depth_base as *mut f32).add(dst_idx) = dilated_inv_w;
430                        }
431                        ray_sx += step_sc[0];
432                        ray_sy += step_sc[1];
433                        ray_cw += step_sc[2];
434                        sx_f += scale_x;
435                    }
436                }
437            });
438            // SAFETY: Every byte in `0..dst_bytes` was initialized by disjoint row bands above.
439            unsafe {
440                out_rgba.set_len(dst_bytes);
441            }
442            swap(history_rgba, next_history_rgba);
443            swap(history_inv_w, next_inv_w);
444        }
445        self.set_prev_view_projection(params.get_view_projection());
446        self.set_has_history(true);
447        self.set_accumulated_frames(self.get_accumulated_frames().saturating_add(1));
448    }
449}
450
451/// Default 60Hz `AdaptiveFrameGovernor`.
452impl Default for AdaptiveFrameGovernor {
453    /// Creates a 60Hz closed-loop frame pacing governor with `[0.50, 1.00]` TSR/DRS scale bounds.
454    ///
455    /// # Returns
456    ///
457    /// - `Self` - Default frame pacing governor.
458    fn default() -> Self {
459        Self::for_target_hz(60.0)
460    }
461}
462
463/// Damped PI + asymmetric hysteresis frame-time stabilization for `AdaptiveFrameGovernor`.
464impl AdaptiveFrameGovernor {
465    /// Creates a closed-loop `AdaptiveFrameGovernor` targeting `target_hz` (`30.0..=1000.0` Hz).
466    ///
467    /// # Arguments
468    ///
469    /// - `f32` - Desired display refresh rate in Hertz.
470    ///
471    /// # Returns
472    ///
473    /// - `Self` - Initialized closed-loop frame governor.
474    #[must_use]
475    pub fn for_target_hz(target_hz: f32) -> Self {
476        let clamped_hz: f32 = if target_hz.is_finite() {
477            target_hz.max(30.0)
478        } else {
479            60.0
480        };
481        let budget_ms: f32 = 1000.0 / clamped_hz;
482        Self {
483            target_hz: clamped_hz,
484            min_scale: TSR_MIN_SCALE,
485            max_scale: TSR_MAX_SCALE,
486            current_scale: 1.0,
487            rt_stride_bias: 0,
488            lod_bias: 1.0,
489            ema_frame_ms: budget_ms * 0.75,
490            ema_jitter_ms: 0.0,
491            p99_est_ms: budget_ms * 0.85,
492            last_frame_ms: budget_ms * 0.75,
493            under_budget_streak: 0,
494            over_budget_streak: 0,
495            hysteresis_frames: GOVERNOR_DEFAULT_HYSTERESIS_FRAMES,
496            total_frames: 0,
497        }
498    }
499
500    /// Configures custom TSR/DRS resolution scale bounds `(min_scale, max_scale)`.
501    ///
502    /// # Arguments
503    ///
504    /// - `f32` - Minimum resolution scale (`0.40..=1.0`).
505    /// - `f32` - Maximum resolution scale (`min_scale..=1.25`).
506    ///
507    /// # Returns
508    ///
509    /// - `Self` - Updated governor.
510    #[must_use]
511    pub fn with_scale_bounds(mut self, min_scale: f32, max_scale: f32) -> Self {
512        let lo: f32 = min_scale.clamp(0.40, 1.0);
513        let hi: f32 = max_scale.clamp(lo, 4.0);
514        self.set_min_scale(lo);
515        self.set_max_scale(hi);
516        self.set_current_scale(self.get_current_scale().clamp(lo, hi));
517        self
518    }
519
520    /// Quantizes a raw resolution scale onto `GOVERNOR_SCALE_QUANTUM` steps to eliminate buffer reallocation churn.
521    ///
522    /// # Arguments
523    ///
524    /// - `f32` - Unquantized resolution scale.
525    /// - `f32` - Minimum scale clamp.
526    /// - `f32` - Maximum scale clamp.
527    ///
528    /// # Returns
529    ///
530    /// - `f32` - Quantized scale within `[min_scale, max_scale]`.
531    #[must_use]
532    fn quantize_scale(raw: f32, min_scale: f32, max_scale: f32) -> f32 {
533        let stepped: f32 = (raw / GOVERNOR_SCALE_QUANTUM).round() * GOVERNOR_SCALE_QUANTUM;
534        stepped.clamp(min_scale, max_scale)
535    }
536
537    /// Observes the completed `frame_ms` duration, updates smoothed telemetry, and smoothly adjusts `config` to lock target FPS without oscillation.
538    ///
539    /// # Arguments
540    ///
541    /// - `f32` - Measured frame duration in milliseconds.
542    /// - `&mut RenderQualityConfig` - Active quality configuration adjusted in-place when dynamic scaling is enabled.
543    ///
544    /// # Returns
545    ///
546    /// - `FramePacingTelemetry3D` - Live pacing, utilization, and stability diagnostics.
547    pub fn record_frame(
548        &mut self,
549        frame_ms: f32,
550        config: &mut RenderQualityConfig,
551    ) -> FramePacingTelemetry3D {
552        let safe_ms: f32 = if frame_ms.is_finite() {
553            frame_ms.clamp(0.05, 250.0)
554        } else {
555            16.67
556        };
557        let target_hz: f32 = self.get_target_hz().max(30.0);
558        let budget_ms: f32 = 1000.0 / target_hz;
559        let frames: u64 = self.get_total_frames();
560        let next_ema: f32 = if frames == 0 {
561            safe_ms
562        } else {
563            self.get_ema_frame_ms() * 0.82 + safe_ms * 0.18
564        };
565        let delta_jitter: f32 = if frames == 0 {
566            0.0
567        } else {
568            (safe_ms - self.get_last_frame_ms()).abs()
569        };
570        let next_jitter: f32 = if frames == 0 {
571            0.0
572        } else {
573            self.get_ema_jitter_ms() * 0.85 + delta_jitter * 0.15
574        };
575        let prev_p99: f32 = self.get_p99_est_ms();
576        let next_p99: f32 = if safe_ms > prev_p99 {
577            prev_p99 * 0.65 + safe_ms * 0.35
578        } else {
579            prev_p99 * 0.96 + safe_ms * 0.04
580        };
581        self.set_ema_frame_ms(next_ema);
582        self.set_ema_jitter_ms(next_jitter);
583        self.set_p99_est_ms(next_p99);
584        self.set_last_frame_ms(safe_ms);
585        self.set_total_frames(frames.saturating_add(1));
586        if config.get_dynamic_resolution() {
587            let min_s: f32 = self.get_min_scale();
588            let max_s: f32 = self.get_max_scale();
589            let mut cur_s: f32 = self.get_current_scale().clamp(min_s, max_s);
590            let mut rt_bias: usize = self.get_rt_stride_bias();
591            let mut lod_b: f32 = self.get_lod_bias();
592            let over_hard: bool = safe_ms > budget_ms * 1.06 || next_ema > budget_ms * 1.01;
593            let under_safe: bool = safe_ms < budget_ms * 0.84 && next_ema < budget_ms * 0.78;
594            if over_hard {
595                self.set_under_budget_streak(0);
596                let next_over: u32 = self.get_over_budget_streak().saturating_add(1);
597                self.set_over_budget_streak(next_over);
598                let pressure: f32 = ((safe_ms.max(next_ema) / budget_ms) - 1.0).clamp(0.02, 1.5);
599                let step_down: f32 = (pressure * 0.12).clamp(GOVERNOR_SCALE_QUANTUM, 0.10);
600                let next_s: f32 = Self::quantize_scale(cur_s - step_down, min_s, max_s);
601                if next_s < cur_s - 1.0e-4 {
602                    cur_s = next_s;
603                } else if next_over >= 3 {
604                    if rt_bias < 3 {
605                        rt_bias += 1;
606                    }
607                    lod_b = (lod_b + 0.10).clamp(0.75, 1.80);
608                }
609            } else if under_safe {
610                self.set_over_budget_streak(0);
611                let next_under: u32 = self.get_under_budget_streak().saturating_add(1);
612                self.set_under_budget_streak(next_under);
613                if next_under >= self.get_hysteresis_frames().max(2) {
614                    self.set_under_budget_streak(0);
615                    if lod_b > 1.02 {
616                        lod_b = (lod_b - 0.08).max(1.0);
617                    } else if rt_bias > 0 {
618                        rt_bias -= 1;
619                    } else {
620                        cur_s = Self::quantize_scale(cur_s + GOVERNOR_SCALE_QUANTUM, min_s, max_s);
621                    }
622                }
623            } else {
624                self.set_over_budget_streak(0);
625                self.set_under_budget_streak(0);
626            }
627            self.set_current_scale(cur_s);
628            self.set_rt_stride_bias(rt_bias);
629            self.set_lod_bias(lod_b);
630            config.set_resolution_scale(cur_s);
631            config.set_lod_bias(lod_b);
632        }
633        let util: f32 = next_ema / budget_ms.max(0.01);
634        let jitter_penalty: f32 = (next_jitter / budget_ms.max(0.01)).clamp(0.0, 1.0);
635        let overrun_penalty: f32 = (util - 1.0).clamp(0.0, 1.0);
636        let stability: f32 = (1.0 - jitter_penalty * 0.65 - overrun_penalty * 0.55).clamp(0.0, 1.0);
637        FramePacingTelemetry3D {
638            budget_ms,
639            ema_frame_ms: next_ema,
640            p99_est_ms: next_p99,
641            budget_utilization: util,
642            effective_resolution_scale: self.get_current_scale(),
643            effective_rt_stride_bias: self.get_rt_stride_bias(),
644            effective_lod_bias: self.get_lod_bias(),
645            stability_score: stability,
646        }
647    }
648}