use super::*;
impl Default for TsrUpscaler {
fn default() -> Self {
Self {
history_width: 0,
history_height: 0,
has_history: false,
prev_view_projection: Mat4::identity(),
accumulated_frames: 0,
history_rgba: Vec::new(),
next_history_rgba: Vec::new(),
history_inv_w: Vec::new(),
next_inv_w: Vec::new(),
}
}
}
impl TsrUpscaler {
pub fn invalidate_history(&mut self) {
self.set_has_history(false);
self.set_accumulated_frames(0);
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
fn mul_dir4(mat: &Mat4, dir: Vec3) -> [f32; 4] {
let elems: [f32; 16] = mat.get_elements();
let dx: f32 = dir.get_x();
let dy: f32 = dir.get_y();
let dz: f32 = dir.get_z();
[
dx.mul_add(elems[0], dy.mul_add(elems[4], dz * elems[8])),
dx.mul_add(elems[1], dy.mul_add(elems[5], dz * elems[9])),
dx.mul_add(elems[2], dy.mul_add(elems[6], dz * elems[10])),
dx.mul_add(elems[3], dy.mul_add(elems[7], dz * elems[11])),
]
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
fn fold_screen_basis(clip: [f32; 4], half_dw: f32, half_dh: f32) -> [f32; 3] {
let cx: f32 = clip[0];
let cy: f32 = clip[1];
let cw: f32 = clip[3];
[
cx.mul_add(half_dw, cw * (half_dw - 0.5)),
(-cy).mul_add(half_dh, cw * (half_dh - 0.5)),
cw,
]
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
fn load_swar_rgb(rgba: &[u8], byte_off: usize) -> u64 {
(rgba[byte_off] as u64)
| ((rgba[byte_off + 1] as u64) << 16)
| ((rgba[byte_off + 2] as u64) << 32)
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
fn sample_swar_rows(
rgba: &[u8],
row_info: (usize, usize, u64),
col_info: (usize, usize, u64),
) -> (u32, u32, u32) {
let (row0, row1, wy): (usize, usize, u64) = row_info;
let (x0_b, x1_b, wx): (usize, usize, u64) = col_info;
let inv_wx: u64 = 256 - wx;
let inv_wy: u64 = 256 - wy;
let c00: u64 = Self::load_swar_rgb(rgba, row0 + x0_b);
let c10: u64 = Self::load_swar_rgb(rgba, row0 + x1_b);
let c01: u64 = Self::load_swar_rgb(rgba, row1 + x0_b);
let c11: u64 = Self::load_swar_rgb(rgba, row1 + x1_b);
let top: u64 = ((c00 * inv_wx + c10 * wx + 0x0000_0080_0080_0080_u64) >> 8)
& 0x0000_00FF_00FF_00FF_u64;
let bot: u64 = ((c01 * inv_wx + c11 * wx + 0x0000_0080_0080_0080_u64) >> 8)
& 0x0000_00FF_00FF_00FF_u64;
let blended: u64 = ((top * inv_wy + bot * wy + 0x0000_0080_0080_0080_u64) >> 8)
& 0x0000_00FF_00FF_00FF_u64;
(
(blended & 0xFF) as u32,
((blended >> 16) & 0xFF) as u32,
((blended >> 32) & 0xFF) as u32,
)
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
fn sample_rgba_bilinear_swar(
rgba: &[u8],
dims: (usize, usize),
coords: (f32, f32),
) -> (u32, u32, u32) {
let (width, height): (usize, usize) = dims;
let (fx, fy): (f32, f32) = coords;
let max_x: usize = width.saturating_sub(1);
let max_y: usize = height.saturating_sub(1);
let cx: f32 = fx.clamp(0.0, max_x as f32);
let cy: f32 = fy.clamp(0.0, max_y as f32);
let x0: usize = cx as usize;
let y0: usize = cy as usize;
let x1: usize = (x0 + 1).min(max_x);
let y1: usize = (y0 + 1).min(max_y);
let wx: u64 = ((cx - (x0 as f32)) * 256.0) as u64;
let wy: u64 = ((cy - (y0 as f32)) * 256.0) as u64;
let row_bytes: usize = width * 4;
Self::sample_swar_rows(
rgba,
(y0 * row_bytes, y1 * row_bytes, wy),
(x0 * 4, x1 * 4, wx),
)
}
pub fn upscale_rgba(
&mut self,
src_rgba: &[u8],
src_depth: &[f32],
params: &TsrFrameParams,
out_rgba: &mut Vec<u8>,
) {
let src_w: usize = params.get_src_width().max(1);
let src_h: usize = params.get_src_height().max(1);
let dst_w: usize = params.get_dst_width().max(1);
let dst_h: usize = params.get_dst_height().max(1);
let src_pixels: usize = src_w * src_h;
let dst_pixels: usize = dst_w * dst_h;
let dst_bytes: usize = dst_pixels * 4;
if src_rgba.len() < src_pixels * 4 || src_depth.len() < src_pixels {
out_rgba.clear();
return;
}
if self.get_history_width() != dst_w || self.get_history_height() != dst_h {
self.set_history_width(dst_w);
self.set_history_height(dst_h);
self.set_has_history(false);
self.set_accumulated_frames(0);
let Self {
history_rgba,
next_history_rgba,
history_inv_w,
next_inv_w,
..
} = self;
history_rgba.resize(dst_bytes, 0);
next_history_rgba.resize(dst_bytes, 0);
history_inv_w.resize(dst_pixels, 0.0);
next_inv_w.resize(dst_pixels, 0.0);
}
out_rgba.clear();
if out_rgba.capacity() < dst_bytes {
out_rgba.reserve_exact(dst_bytes - out_rgba.capacity());
}
let has_hist: bool = self.get_has_history();
let prev_vp: Mat4 = self.get_prev_view_projection();
let inv_dst_w: f32 = 1.0 / (dst_w as f32);
let inv_dst_h: f32 = 1.0 / (dst_h as f32);
let scale_x: f32 = (src_w as f32) * inv_dst_w;
let scale_y: f32 = (src_h as f32) * inv_dst_h;
let (jit_x, jit_y): (f32, f32) = params.get_jitter_offset();
let sharp_i32: i32 = (params.get_sharpness().clamp(0.0, 0.5) * 256.0) as i32;
let dst_w_f: f32 = dst_w as f32;
let dst_h_f: f32 = dst_h as f32;
let half_dw: f32 = dst_w_f * 0.5;
let half_dh: f32 = dst_h_f * 0.5;
let max_ox: f32 = dst_w_f - 0.5;
let max_oy: f32 = dst_h_f - 0.5;
let src_w_max: usize = src_w.saturating_sub(1);
let src_h_max: usize = src_h.saturating_sub(1);
let src_w_max_f: f32 = src_w_max as f32;
let src_h_max_f: f32 = src_h_max as f32;
let dst_w_max: usize = dst_w.saturating_sub(1);
let dst_h_max: usize = dst_h.saturating_sub(1);
let src_row_bytes: usize = src_w * 4;
let cam_sc: [f32; 3] = Self::fold_screen_basis(
prev_vp.mul_point4(params.get_camera_position()),
half_dw,
half_dh,
);
let fwd_sc: [f32; 3] = Self::fold_screen_basis(
Self::mul_dir4(&prev_vp, params.get_camera_forward()),
half_dw,
half_dh,
);
let right_sc: [f32; 3] = Self::fold_screen_basis(
Self::mul_dir4(&prev_vp, params.get_camera_right_scaled()),
half_dw,
half_dh,
);
let up_sc: [f32; 3] = Self::fold_screen_basis(
Self::mul_dir4(&prev_vp, params.get_camera_up_scaled()),
half_dw,
half_dh,
);
let step_scale: f32 = 2.0 * inv_dst_w;
let step_sc: [f32; 3] = [
right_sc[0] * step_scale,
right_sc[1] * step_scale,
right_sc[2] * step_scale,
];
let ndc_x0: f32 = inv_dst_w - 1.0;
let base_hist_w: f32 = TSR_BASE_HISTORY_WEIGHT * 256.0;
let delta_hist_w: f32 = (TSR_MOTION_HISTORY_WEIGHT - TSR_BASE_HISTORY_WEIGHT) * 256.0;
{
let Self {
history_rgba,
next_history_rgba,
history_inv_w,
next_inv_w,
..
} = self;
let hist_rgba_ref: &[u8] = history_rgba.as_slice();
let hist_depth_ref: &[f32] = history_inv_w.as_slice();
let out_base: usize = out_rgba.as_mut_ptr() as usize;
let next_hist_base: usize = next_history_rgba.as_mut_ptr() as usize;
let next_depth_base: usize = next_inv_w.as_mut_ptr() as usize;
parallel_for_ranges(dst_h, TSR_PARALLEL_ROW_GRAIN, |y0: usize, y1: usize| {
for dst_y in y0..y1 {
let row_out: usize = dst_y * dst_w;
let ndc_y: f32 = 1.0 - 2.0 * (((dst_y as f32) + 0.5) * inv_dst_h);
let mut ray_sx: f32 = fwd_sc[0] + up_sc[0] * ndc_y + right_sc[0] * ndc_x0;
let mut ray_sy: f32 = fwd_sc[1] + up_sc[1] * ndc_y + right_sc[1] * ndc_x0;
let mut ray_cw: f32 = fwd_sc[2] + up_sc[2] * ndc_y + right_sc[2] * ndc_x0;
let sy_f: f32 =
(((dst_y as f32) + 0.5) * scale_y - 0.5 - jit_y).clamp(0.0, src_h_max_f);
let sy0: usize = sy_f as usize;
let sy1: usize = (sy0 + 1).min(src_h_max);
let wy_src: u64 = ((sy_f - (sy0 as f32)) * 256.0) as u64;
let src_row0_b: usize = sy0 * src_row_bytes;
let src_row1_b: usize = sy1 * src_row_bytes;
let iy: usize = ((sy_f + 0.5) as usize).min(src_h_max);
let row_iy: usize = iy * src_w;
let row_up: usize = iy.saturating_sub(1) * src_w;
let row_dn: usize = (iy + 1).min(src_h_max) * src_w;
let mut sx_f: f32 = 0.5 * scale_x - 0.5 - jit_x;
for dst_x in 0..dst_w {
let clamped_sx: f32 = sx_f.clamp(0.0, src_w_max_f);
let sx0: usize = clamped_sx as usize;
let sx1: usize = (sx0 + 1).min(src_w_max);
let wx_src: u64 = ((clamped_sx - (sx0 as f32)) * 256.0) as u64;
let (mut out_r, mut out_g, mut out_b): (u32, u32, u32) =
Self::sample_swar_rows(
src_rgba,
(src_row0_b, src_row1_b, wy_src),
(sx0 * 4, sx1 * 4, wx_src),
);
let ix: usize = ((clamped_sx + 0.5) as usize).min(src_w_max);
let c_idx: usize = row_iy + ix;
let up_idx: usize = row_up + ix;
let dn_idx: usize = row_dn + ix;
let lt_idx: usize = row_iy + ix.saturating_sub(1);
let rt_idx: usize = row_iy + (ix + 1).min(src_w_max);
let dilated_inv_w: f32 = src_depth[c_idx]
.max(src_depth[up_idx])
.max(src_depth[dn_idx])
.max(src_depth[lt_idx])
.max(src_depth[rt_idx]);
if dilated_inv_w > 1.0e-6 {
let oc: usize = c_idx * 4;
let ou: usize = up_idx * 4;
let od: usize = dn_idx * 4;
let ol: usize = lt_idx * 4;
let or: usize = rt_idx * 4;
let r0: u32 = src_rgba[oc] as u32;
let r1: u32 = src_rgba[ou] as u32;
let r2: u32 = src_rgba[od] as u32;
let r3: u32 = src_rgba[ol] as u32;
let r4: u32 = src_rgba[or] as u32;
let g0: u32 = src_rgba[oc + 1] as u32;
let g1: u32 = src_rgba[ou + 1] as u32;
let g2: u32 = src_rgba[od + 1] as u32;
let g3: u32 = src_rgba[ol + 1] as u32;
let g4: u32 = src_rgba[or + 1] as u32;
let b0: u32 = src_rgba[oc + 2] as u32;
let b1: u32 = src_rgba[ou + 2] as u32;
let b2: u32 = src_rgba[od + 2] as u32;
let b3: u32 = src_rgba[ol + 2] as u32;
let b4: u32 = src_rgba[or + 2] as u32;
let min_r: u32 = r0.min(r1).min(r2).min(r3).min(r4);
let max_r: u32 = r0.max(r1).max(r2).max(r3).max(r4);
let min_g: u32 = g0.min(g1).min(g2).min(g3).min(g4);
let max_g: u32 = g0.max(g1).max(g2).max(g3).max(g4);
let min_b: u32 = b0.min(b1).min(b2).min(b3).min(b4);
let max_b: u32 = b0.max(b1).max(b2).max(b3).max(b4);
if has_hist {
let cw: f32 = cam_sc[2].mul_add(dilated_inv_w, ray_cw);
if cw > 0.15 * dilated_inv_w {
let inv_cw: f32 = 1.0 / cw;
let prev_ox: f32 =
cam_sc[0].mul_add(dilated_inv_w, ray_sx) * inv_cw;
let prev_oy: f32 =
cam_sc[1].mul_add(dilated_inv_w, ray_sy) * inv_cw;
if (-0.5..=max_ox).contains(&prev_ox)
&& (-0.5..=max_oy).contains(&prev_oy)
{
let px_i: usize =
((prev_ox + 0.5).max(0.0) as usize).min(dst_w_max);
let py_i: usize =
((prev_oy + 0.5).max(0.0) as usize).min(dst_h_max);
let prev_stored_inv_w: f32 =
hist_depth_ref[py_i * dst_w + px_i];
if prev_stored_inv_w > 1.0e-6
&& (dilated_inv_w - prev_stored_inv_w).abs()
<= dilated_inv_w.max(prev_stored_inv_w)
* TSR_DISOCCLUSION_REL_DEPTH
{
let (hr, hg, hb): (u32, u32, u32) =
Self::sample_rgba_bilinear_swar(
hist_rgba_ref,
(dst_w, dst_h),
(prev_ox, prev_oy),
);
let clamped_r: u32 = hr.clamp(min_r, max_r);
let clamped_g: u32 = hg.clamp(min_g, max_g);
let clamped_b: u32 = hb.clamp(min_b, max_b);
let motion_px: f32 = (prev_ox - (dst_x as f32))
.abs()
.max((prev_oy - (dst_y as f32)).abs());
let motion_t: f32 = (motion_px * 0.12).clamp(0.0, 1.0);
let hw: u32 =
delta_hist_w.mul_add(motion_t, base_hist_w) as u32;
let cw_i: u32 = 256 - hw;
out_r = (out_r * cw_i + clamped_r * hw + 128) >> 8;
out_g = (out_g * cw_i + clamped_g * hw + 128) >> 8;
out_b = (out_b * cw_i + clamped_b * hw + 128) >> 8;
}
}
}
}
if sharp_i32 > 1 {
let avg_r: i32 = ((r0 + r1 + r2 + r3 + r4 + 2) / 5) as i32;
let avg_g: i32 = ((g0 + g1 + g2 + g3 + g4 + 2) / 5) as i32;
let avg_b: i32 = ((b0 + b1 + b2 + b3 + b4 + 2) / 5) as i32;
let sr: i32 =
(out_r as i32) + ((((out_r as i32) - avg_r) * sharp_i32) >> 8);
let sg: i32 =
(out_g as i32) + ((((out_g as i32) - avg_g) * sharp_i32) >> 8);
let sb: i32 =
(out_b as i32) + ((((out_b as i32) - avg_b) * sharp_i32) >> 8);
out_r = sr.clamp(min_r as i32, max_r as i32) as u32;
out_g = sg.clamp(min_g as i32, max_g as i32) as u32;
out_b = sb.clamp(min_b as i32, max_b as i32) as u32;
}
}
let dst_idx: usize = row_out + dst_x;
let out_off: usize = dst_idx * 4;
let packed: [u8; 4] = [out_r as u8, out_g as u8, out_b as u8, 255];
unsafe {
(out_base as *mut u8)
.add(out_off)
.cast::<[u8; 4]>()
.write(packed);
(next_hist_base as *mut u8)
.add(out_off)
.cast::<[u8; 4]>()
.write(packed);
*(next_depth_base as *mut f32).add(dst_idx) = dilated_inv_w;
}
ray_sx += step_sc[0];
ray_sy += step_sc[1];
ray_cw += step_sc[2];
sx_f += scale_x;
}
}
});
unsafe {
out_rgba.set_len(dst_bytes);
}
swap(history_rgba, next_history_rgba);
swap(history_inv_w, next_inv_w);
}
self.set_prev_view_projection(params.get_view_projection());
self.set_has_history(true);
self.set_accumulated_frames(self.get_accumulated_frames().saturating_add(1));
}
}
impl Default for AdaptiveFrameGovernor {
fn default() -> Self {
Self::for_target_hz(60.0)
}
}
impl AdaptiveFrameGovernor {
#[must_use]
pub fn for_target_hz(target_hz: f32) -> Self {
let clamped_hz: f32 = if target_hz.is_finite() {
target_hz.max(30.0)
} else {
60.0
};
let budget_ms: f32 = 1000.0 / clamped_hz;
Self {
target_hz: clamped_hz,
min_scale: TSR_MIN_SCALE,
max_scale: TSR_MAX_SCALE,
current_scale: 1.0,
rt_stride_bias: 0,
lod_bias: 1.0,
ema_frame_ms: budget_ms * 0.75,
ema_jitter_ms: 0.0,
p99_est_ms: budget_ms * 0.85,
last_frame_ms: budget_ms * 0.75,
under_budget_streak: 0,
over_budget_streak: 0,
hysteresis_frames: GOVERNOR_DEFAULT_HYSTERESIS_FRAMES,
total_frames: 0,
}
}
#[must_use]
pub fn with_scale_bounds(mut self, min_scale: f32, max_scale: f32) -> Self {
let lo: f32 = min_scale.clamp(0.40, 1.0);
let hi: f32 = max_scale.clamp(lo, 4.0);
self.set_min_scale(lo);
self.set_max_scale(hi);
self.set_current_scale(self.get_current_scale().clamp(lo, hi));
self
}
#[must_use]
fn quantize_scale(raw: f32, min_scale: f32, max_scale: f32) -> f32 {
let stepped: f32 = (raw / GOVERNOR_SCALE_QUANTUM).round() * GOVERNOR_SCALE_QUANTUM;
stepped.clamp(min_scale, max_scale)
}
pub fn record_frame(
&mut self,
frame_ms: f32,
config: &mut RenderQualityConfig,
) -> FramePacingTelemetry3D {
let safe_ms: f32 = if frame_ms.is_finite() {
frame_ms.clamp(0.05, 250.0)
} else {
16.67
};
let target_hz: f32 = self.get_target_hz().max(30.0);
let budget_ms: f32 = 1000.0 / target_hz;
let frames: u64 = self.get_total_frames();
let next_ema: f32 = if frames == 0 {
safe_ms
} else {
self.get_ema_frame_ms() * 0.82 + safe_ms * 0.18
};
let delta_jitter: f32 = if frames == 0 {
0.0
} else {
(safe_ms - self.get_last_frame_ms()).abs()
};
let next_jitter: f32 = if frames == 0 {
0.0
} else {
self.get_ema_jitter_ms() * 0.85 + delta_jitter * 0.15
};
let prev_p99: f32 = self.get_p99_est_ms();
let next_p99: f32 = if safe_ms > prev_p99 {
prev_p99 * 0.65 + safe_ms * 0.35
} else {
prev_p99 * 0.96 + safe_ms * 0.04
};
self.set_ema_frame_ms(next_ema);
self.set_ema_jitter_ms(next_jitter);
self.set_p99_est_ms(next_p99);
self.set_last_frame_ms(safe_ms);
self.set_total_frames(frames.saturating_add(1));
if config.get_dynamic_resolution() {
let min_s: f32 = self.get_min_scale();
let max_s: f32 = self.get_max_scale();
let mut cur_s: f32 = self.get_current_scale().clamp(min_s, max_s);
let mut rt_bias: usize = self.get_rt_stride_bias();
let mut lod_b: f32 = self.get_lod_bias();
let over_hard: bool = safe_ms > budget_ms * 1.06 || next_ema > budget_ms * 1.01;
let under_safe: bool = safe_ms < budget_ms * 0.84 && next_ema < budget_ms * 0.78;
if over_hard {
self.set_under_budget_streak(0);
let next_over: u32 = self.get_over_budget_streak().saturating_add(1);
self.set_over_budget_streak(next_over);
let pressure: f32 = ((safe_ms.max(next_ema) / budget_ms) - 1.0).clamp(0.02, 1.5);
let step_down: f32 = (pressure * 0.12).clamp(GOVERNOR_SCALE_QUANTUM, 0.10);
let next_s: f32 = Self::quantize_scale(cur_s - step_down, min_s, max_s);
if next_s < cur_s - 1.0e-4 {
cur_s = next_s;
} else if next_over >= 3 {
if rt_bias < 3 {
rt_bias += 1;
}
lod_b = (lod_b + 0.10).clamp(0.75, 1.80);
}
} else if under_safe {
self.set_over_budget_streak(0);
let next_under: u32 = self.get_under_budget_streak().saturating_add(1);
self.set_under_budget_streak(next_under);
if next_under >= self.get_hysteresis_frames().max(2) {
self.set_under_budget_streak(0);
if lod_b > 1.02 {
lod_b = (lod_b - 0.08).max(1.0);
} else if rt_bias > 0 {
rt_bias -= 1;
} else {
cur_s = Self::quantize_scale(cur_s + GOVERNOR_SCALE_QUANTUM, min_s, max_s);
}
}
} else {
self.set_over_budget_streak(0);
self.set_under_budget_streak(0);
}
self.set_current_scale(cur_s);
self.set_rt_stride_bias(rt_bias);
self.set_lod_bias(lod_b);
config.set_resolution_scale(cur_s);
config.set_lod_bias(lod_b);
}
let util: f32 = next_ema / budget_ms.max(0.01);
let jitter_penalty: f32 = (next_jitter / budget_ms.max(0.01)).clamp(0.0, 1.0);
let overrun_penalty: f32 = (util - 1.0).clamp(0.0, 1.0);
let stability: f32 = (1.0 - jitter_penalty * 0.65 - overrun_penalty * 0.55).clamp(0.0, 1.0);
FramePacingTelemetry3D {
budget_ms,
ema_frame_ms: next_ema,
p99_est_ms: next_p99,
budget_utilization: util,
effective_resolution_scale: self.get_current_scale(),
effective_rt_stride_bias: self.get_rt_stride_bias(),
effective_lod_bias: self.get_lod_bias(),
stability_score: stability,
}
}
}