use crate::post_fx_context::{self, PostFXContext, TextureOperationAttribs, draw};
use crate::render_technique::{
DepthStencilStateDesc, PostFXRenderTechnique, Resource, Shader, create_shader,
};
use crate::screen_space_reflection::PostFxExecutionStatus;
use crate::structures::{CameraAttribs, TemporalAntiAliasingAttribs};
use std::collections::HashMap;
use wgpu::util::DeviceExt;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FeatureFlags(pub u32);
impl FeatureFlags {
pub const NONE: Self = Self(0);
pub const GAUSSIAN_WEIGHTING: Self = Self(1 << 0);
pub const BICUBIC_FILTER: Self = Self(1 << 1);
pub const YCOCG_COLOR_SPACE: Self = Self(1 << 2);
pub const MOTION_ADAPTIVE_HISTORY: Self = Self(1 << 3);
pub fn contains(self, flag: Self) -> bool {
self.0 & flag.0 != 0
}
}
impl std::ops::BitOr for FeatureFlags {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
pub struct RenderAttributes<'a, 'p> {
pub device: &'a wgpu::Device,
pub queue: &'a wgpu::Queue,
pub device_context: &'a mut wgpu::CommandEncoder,
pub post_fx_context: &'a mut PostFXContext,
pub color_buffer_srv: &'a wgpu::TextureView,
pub depth_buffer_srv: &'a wgpu::TextureView,
pub motion_vectors_srv: &'a wgpu::TextureView,
pub responsive_masks: &'a [&'a wgpu::TextureView],
pub neighborhood_motion: Option<NeighborhoodMotion<'a>>,
pub taa_attribs: &'a TemporalAntiAliasingAttribs,
pub accumulation_buffer_idx: u32,
pub pass_timestamps: Option<&'a post_fx_context::PassTimestamps<'p>>,
}
#[derive(Clone, Copy, Debug)]
pub struct NeighborhoodMotion<'a> {
pub srv: &'a wgpu::TextureView,
pub tile_size: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum RenderTech {
ComputeTemporalAccumulation,
ComputePlaceholder,
}
const RENDER_TECHS: [RenderTech; 1] = [RenderTech::ComputeTemporalAccumulation];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct RenderTechniqueKey {
render_tech: RenderTech,
feature_flags: FeatureFlags,
reversed_depth: bool,
responsive: Responsive,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
struct Responsive {
masks: u32,
neighborhood_tile: u32,
}
impl Responsive {
fn new(flags: FeatureFlags, masks: usize, neighborhood_tile: Option<u32>) -> Self {
if !flags.contains(FeatureFlags::MOTION_ADAPTIVE_HISTORY) {
return Self::default();
}
Self {
masks: masks as u32,
neighborhood_tile: neighborhood_tile.unwrap_or(0),
}
}
fn of(attribs: &RenderAttributes<'_, '_>, flags: FeatureFlags) -> Self {
Self::new(
flags,
attribs.responsive_masks.len(),
attribs.neighborhood_motion.map(|n| n.tile_size),
)
}
}
const ACCUMULATED_BUFFER_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
fn closest_motion_format(flags: FeatureFlags) -> wgpu::TextureFormat {
if flags.contains(FeatureFlags::MOTION_ADAPTIVE_HISTORY) {
wgpu::TextureFormat::Rgba16Float
} else {
wgpu::TextureFormat::Rg16Float
}
}
struct AccumulationBufferInfo {
constant_buffer: Option<wgpu::Buffer>,
accumulated_buffers: Option<[wgpu::TextureView; 2]>,
closest_motion: Option<[wgpu::TextureView; 2]>,
width: u32,
height: u32,
current_frame_idx: u32,
last_frame_idx: Option<u32>,
feature_flags: FeatureFlags,
shader_attribs: TemporalAntiAliasingAttribs,
}
impl Default for AccumulationBufferInfo {
fn default() -> Self {
Self {
constant_buffer: None,
accumulated_buffers: None,
closest_motion: None,
width: 0,
height: 0,
current_frame_idx: 0,
last_frame_idx: None,
feature_flags: FeatureFlags::NONE,
shader_attribs: TemporalAntiAliasingAttribs::default(),
}
}
}
impl AccumulationBufferInfo {
#[allow(clippy::too_many_arguments)]
fn prepare(
&mut self,
post_fx_context: &PostFXContext,
device: &wgpu::Device,
ctx: &mut wgpu::CommandEncoder,
width: u32,
height: u32,
curr_frame_idx: u32,
feature_flags: FeatureFlags,
) {
let motion_format_changed =
closest_motion_format(self.feature_flags) != closest_motion_format(feature_flags);
self.feature_flags = feature_flags;
self.current_frame_idx = curr_frame_idx;
if self.width == width && self.height == height && !motion_format_changed {
return;
}
self.width = width;
self.height = height;
self.last_frame_idx = None;
if self.constant_buffer.is_none() {
self.constant_buffer = Some(device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
label: Some("TemporalAntiAliasing::ConstantBuffer"),
contents: bytemuck::bytes_of(&self.shader_attribs),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
},
));
}
let mut texture = |label, format| {
let texture = device
.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
})
.create_view(&Default::default());
let clear_color = [0.0, 0.0, 0.0, 0.0];
post_fx_context.clear_render_target(
&mut TextureOperationAttribs {
device,
device_context: ctx,
timestamp_writes: None,
},
&texture,
clear_color,
);
texture
};
self.accumulated_buffers = Some(std::array::from_fn(|_| {
texture(
"TemporalAntiAliasing::AccumulatedBuffer",
ACCUMULATED_BUFFER_FORMAT,
)
}));
self.closest_motion = Some(std::array::from_fn(|_| {
texture(
"TemporalAntiAliasing::ClosestMotion",
closest_motion_format(feature_flags),
)
}));
}
fn update_constant_buffer(
&mut self,
queue: &wgpu::Queue,
attribs: &TemporalAntiAliasingAttribs,
) {
let reset_accumulation = match self.last_frame_idx {
Some(last) if self.current_frame_idx == last => {
self.shader_attribs.reset_accumulation != 0
}
Some(last) => self.current_frame_idx != last.wrapping_add(1),
None => true,
} || attribs.reset_accumulation != 0;
let update_required = reset_accumulation != (self.shader_attribs.reset_accumulation != 0)
|| bytemuck::bytes_of(&self.shader_attribs) != bytemuck::bytes_of(attribs);
if update_required {
self.shader_attribs = *attribs;
self.shader_attribs.reset_accumulation = u32::from(reset_accumulation);
queue.write_buffer(
self.constant_buffer.as_ref().expect("prepared buffer"),
0,
bytemuck::bytes_of(&self.shader_attribs),
);
}
self.last_frame_idx = Some(self.current_frame_idx);
}
fn accumulated_buffer(&self, index: u32) -> &wgpu::TextureView {
&self
.accumulated_buffers
.as_ref()
.expect("TemporalAntiAliasing::PrepareResources")[index as usize]
}
fn closest_motion(&self, index: u32) -> &wgpu::TextureView {
&self
.closest_motion
.as_ref()
.expect("TemporalAntiAliasing::PrepareResources")[index as usize]
}
}
fn reversed_depth(post_fx_context: &PostFXContext) -> bool {
post_fx_context
.get_feature_flags()
.contains(post_fx_context::FeatureFlags::REVERSED_DEPTH)
}
const CAMERA_REST_STEPS: f32 = 8.;
fn eye_magnitude(view: &[f32; 16]) -> f32 {
(0..3)
.map(|axis| {
(0..3)
.map(|row| view[axis * 4 + row] * view[12 + row])
.sum::<f32>()
.abs()
})
.fold(0., f32::max)
}
fn unjittered_projection(mut proj: [f32; 16], jitter: [f32; 2]) -> [f32; 16] {
for column in proj.chunks_exact_mut(4) {
column[0] -= jitter[0] * column[3];
column[1] -= jitter[1] * column[3];
}
proj
}
fn halton_sequence(base: u32, mut index: u32) -> f32 {
let mut result = 0.0f32;
let mut f = 1.0f32;
while index > 0 {
f /= base as f32;
result += f * (index % base) as f32;
index = (index as f32 / base as f32).floor() as u32;
}
result
}
pub struct TemporalAntiAliasing {
render_tech: HashMap<RenderTechniqueKey, PostFXRenderTechnique>,
accumulation_buffers: HashMap<u32, AccumulationBufferInfo>,
all_psos_ready: bool,
linear_clamp: wgpu::Sampler,
}
impl TemporalAntiAliasing {
pub fn new(device: &wgpu::Device) -> Self {
Self {
render_tech: HashMap::new(),
accumulation_buffers: HashMap::new(),
all_psos_ready: false,
linear_clamp: device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Sam_LinearClamp"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
}),
}
}
pub fn get_jitter_offset(&self, accumulation_buffer_idx: u32) -> [f32; 2] {
let Some(acc_buffer) = self.accumulation_buffers.get(&accumulation_buffer_idx) else {
return [0.0, 0.0];
};
if acc_buffer.width == 0 || acc_buffer.height == 0 || !self.all_psos_ready {
return [0.0, 0.0];
}
const SAMPLE_COUNT: u32 = 16;
let jitter_x = (halton_sequence(2, (acc_buffer.current_frame_idx % SAMPLE_COUNT) + 1)
- 0.5)
/ (0.5 * acc_buffer.width as f32);
let jitter_y = (halton_sequence(3, (acc_buffer.current_frame_idx % SAMPLE_COUNT) + 1)
- 0.5)
/ (0.5 * acc_buffer.height as f32);
[jitter_x, jitter_y]
}
pub fn prepare_resources(
&mut self,
device: &wgpu::Device,
device_context: &mut wgpu::CommandEncoder,
post_fx_context: &PostFXContext,
feature_flags: FeatureFlags,
accumulation_buffer_idx: u32,
) {
let frame_desc = *post_fx_context.get_frame_desc();
self.accumulation_buffers
.entry(accumulation_buffer_idx)
.or_default()
.prepare(
post_fx_context,
device,
device_context,
frame_desc.width,
frame_desc.height,
frame_desc.index,
feature_flags,
);
let reversed_depth = reversed_depth(post_fx_context);
self.all_psos_ready = RENDER_TECHS.iter().all(|&render_tech| {
self.render_tech.iter().any(|(key, tech)| {
key.render_tech == render_tech
&& key.feature_flags == feature_flags
&& key.reversed_depth == reversed_depth
&& tech.is_initialized_pso()
})
});
}
pub fn prepare_responsive_variant(
&mut self,
device: &wgpu::Device,
post_fx_context: &PostFXContext,
feature_flags: FeatureFlags,
responsive_masks: usize,
neighborhood_tile: Option<u32>,
) {
assert!(
responsive_masks <= 2,
"TAA reads at most two responsive masks"
);
self.prepare_shaders_and_pso(
device,
feature_flags,
reversed_depth(post_fx_context),
Responsive::new(feature_flags, responsive_masks, neighborhood_tile),
);
}
pub fn execute(
&mut self,
render_attribs: &mut RenderAttributes<'_, '_>,
) -> PostFxExecutionStatus {
let Some(acc_buffer) = self
.accumulation_buffers
.get(&render_attribs.accumulation_buffer_idx)
else {
panic!(
"Accumulation buffer with index {} is not found, which indicates that PrepareResources() method was not called.",
render_attribs.accumulation_buffer_idx
);
};
let feature_flags = acc_buffer.feature_flags;
let motion_format = render_attribs.motion_vectors_srv.texture().format();
assert!(
!feature_flags.contains(FeatureFlags::MOTION_ADAPTIVE_HISTORY)
|| motion_format.components() == 4,
"MOTION_ADAPTIVE_HISTORY reads depth motion from the motion vectors' Z and W, \
which {motion_format:?} lacks"
);
assert!(
render_attribs.responsive_masks.len() <= 2,
"TAA reads at most two responsive masks, not {}",
render_attribs.responsive_masks.len()
);
if let Some(neighborhood) = render_attribs.neighborhood_motion {
let tile = neighborhood.tile_size;
let size = neighborhood.srv.texture().size();
assert!(
tile > 0
&& size.width >= acc_buffer.width.div_ceil(tile)
&& size.height >= acc_buffer.height.div_ceil(tile),
"the neighbourhood motion, {}x{} in tiles of {tile}, does not cover {}x{}",
size.width,
size.height,
acc_buffer.width,
acc_buffer.height
);
}
let responsive = Responsive::of(render_attribs, feature_flags);
self.prepare_shaders_and_pso(
render_attribs.device,
feature_flags,
reversed_depth(render_attribs.post_fx_context),
responsive,
);
let acc_buffer = self
.accumulation_buffers
.get_mut(&render_attribs.accumulation_buffer_idx)
.unwrap();
acc_buffer.update_constant_buffer(render_attribs.queue, render_attribs.taa_attribs);
let all_psos_ready = self.all_psos_ready && render_attribs.post_fx_context.is_psos_ready();
let acc_buffer = &self.accumulation_buffers[&render_attribs.accumulation_buffer_idx];
if all_psos_ready {
self.compute_temporal_accumulation(render_attribs, acc_buffer, responsive);
} else {
self.compute_placeholder_texture(render_attribs, acc_buffer, responsive);
}
if all_psos_ready {
PostFxExecutionStatus::Ready
} else {
PostFxExecutionStatus::Pending
}
}
pub fn get_accumulated_frame_srv(
&self,
is_prev_frame: bool,
accumulation_buffer_idx: u32,
) -> &wgpu::TextureView {
let acc_buffer = self
.accumulation_buffers
.get(&accumulation_buffer_idx)
.unwrap_or_else(|| {
panic!("Accumulation buffer with index {accumulation_buffer_idx} is not found.")
});
let buff_idx = acc_buffer
.current_frame_idx
.wrapping_add(u32::from(is_prev_frame))
& 0x01;
acc_buffer.accumulated_buffer(buff_idx)
}
pub fn camera_moved(current: &CameraAttribs, previous: &CameraAttribs) -> bool {
let projection =
|camera: &CameraAttribs| unjittered_projection(camera.m_proj, camera.f2_jitter);
let eye = eye_magnitude(¤t.m_view).max(eye_magnitude(&previous.m_view));
let agree = |a: &[f32; 16], b: &[f32; 16], translation: f32| {
a.iter().zip(b).enumerate().all(|(i, (&a, &b))| {
let scale = if (12..15).contains(&i) {
translation
} else {
0.
};
(a - b).abs()
<= CAMERA_REST_STEPS * f32::EPSILON * 1f32.max(a.abs()).max(b.abs()).max(scale)
})
};
!(agree(¤t.m_view, &previous.m_view, eye)
&& agree(&projection(current), &projection(previous), 0.))
}
pub fn get_jittered_proj_matrix(mut proj: [f32; 16], jitter: [f32; 2]) -> [f32; 16] {
const M20: usize = 2 * 4;
const M21: usize = 2 * 4 + 1;
const M30: usize = 3 * 4;
const M31: usize = 3 * 4 + 1;
const M33: usize = 3 * 4 + 3;
if proj[M33] == 0.0 {
proj[M20] += jitter[0];
proj[M21] += jitter[1];
} else {
proj[M30] += jitter[0];
proj[M31] += jitter[1];
}
proj
}
fn prepare_shaders_and_pso(
&mut self,
device: &wgpu::Device,
feature_flags: FeatureFlags,
reversed_depth: bool,
responsive: Responsive,
) {
let key = |render_tech| RenderTechniqueKey {
render_tech,
feature_flags,
reversed_depth,
responsive,
};
let tech = self
.render_tech
.entry(key(RenderTech::ComputeTemporalAccumulation))
.or_default();
if !tech.is_initialized_pso() {
let responsive_masks = responsive.masks.to_string();
let neighborhood_tile = responsive.neighborhood_tile.to_string();
let flag = |flag: FeatureFlags| {
if feature_flags.contains(flag) {
"1"
} else {
"0"
}
};
let macros = [
(
"TAA_OPTION_GAUSSIAN_WEIGHTING",
flag(FeatureFlags::GAUSSIAN_WEIGHTING),
),
(
"TAA_OPTION_BICUBIC_FILTER",
flag(FeatureFlags::BICUBIC_FILTER),
),
(
"TAA_OPTION_YCOCG_COLOR_SPACE",
flag(FeatureFlags::YCOCG_COLOR_SPACE),
),
(
"TAA_OPTION_MOTION_ADAPTIVE_HISTORY",
flag(FeatureFlags::MOTION_ADAPTIVE_HISTORY),
),
(
"POSTFX_OPTION_INVERTED_DEPTH",
if reversed_depth { "1" } else { "0" },
),
("TAA_OPTION_RESPONSIVE_MASKS", &responsive_masks),
("TAA_OPTION_NEIGHBORHOOD_MOTION_TILE", &neighborhood_tile),
];
let vs = create_shader(
device,
"FullScreenTriangleVS.fx",
"FullScreenTriangleVS",
&[],
);
let ps = create_shader(
device,
"TAA_ComputeTemporalAccumulation.fx",
"ComputeTemporalAccumulationPS",
¯os,
);
tech.initialize_pso(
device,
"TemporalAntiAliasing::ComputeTemporalAccumulation",
&vs,
&ps,
&[
(0, Resource::ConstantBuffer),
(1, Resource::ConstantBuffer),
(2, Resource::Texture),
(3, Resource::FilterableTexture),
(4, Resource::Texture),
(5, Resource::Texture),
(6, Resource::Texture),
(7, Resource::Sampler { filtering: true }),
(8, Resource::Texture),
(9, Resource::DepthTexture),
]
.into_iter()
.chain((0..responsive.masks).map(|mask| (10 + mask, Resource::Texture)))
.chain((responsive.neighborhood_tile > 0).then_some((12, Resource::Texture)))
.collect::<Vec<_>>(),
&[
ACCUMULATED_BUFFER_FORMAT,
closest_motion_format(feature_flags),
],
None,
DepthStencilStateDesc::DisableDepth,
);
let placeholder_ps = Shader {
module: ps.module,
entry_point: "ComputePlaceholderPS",
};
self.render_tech
.entry(key(RenderTech::ComputePlaceholder))
.or_default()
.initialize_pso(
device,
"TemporalAntiAliasing::ComputePlaceholder",
&vs,
&placeholder_ps,
&[(2, Resource::Texture), (4, Resource::Texture)],
&[
ACCUMULATED_BUFFER_FORMAT,
closest_motion_format(feature_flags),
],
None,
DepthStencilStateDesc::DisableDepth,
);
}
}
fn compute_temporal_accumulation(
&self,
render_attribs: &mut RenderAttributes<'_, '_>,
acc_buff: &AccumulationBufferInfo,
responsive: Responsive,
) {
let ctx = &*render_attribs.post_fx_context;
let tech = &self.render_tech[&RenderTechniqueKey {
render_tech: RenderTech::ComputeTemporalAccumulation,
feature_flags: acc_buff.feature_flags,
reversed_depth: reversed_depth(ctx),
responsive,
}];
let frame_index = ctx.get_frame_desc().index;
let curr_buff_idx = frame_index & 0x01;
let prev_buff_idx = frame_index.wrapping_add(1) & 0x01;
let prev_buffer_srv = acc_buff.accumulated_buffer(prev_buff_idx);
let curr_buffer_rtv = acc_buff.accumulated_buffer(curr_buff_idx);
let texture = wgpu::BindingResource::TextureView;
let mut responsive_entries: Vec<wgpu::BindGroupEntry<'_>> = render_attribs
.responsive_masks
.iter()
.take(responsive.masks as usize)
.zip(10..)
.map(|(&mask, binding)| wgpu::BindGroupEntry {
binding,
resource: texture(mask),
})
.collect();
if responsive.neighborhood_tile > 0
&& let Some(neighborhood) = render_attribs.neighborhood_motion
{
responsive_entries.push(wgpu::BindGroupEntry {
binding: 12,
resource: texture(neighborhood.srv),
});
}
let group = tech.bind_group(
render_attribs.device,
"ComputeTemporalAccumulation",
&[
wgpu::BindGroupEntry {
binding: 0,
resource: ctx.get_camera_attribs_cb().as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: acc_buff
.constant_buffer
.as_ref()
.expect("prepared buffer")
.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: texture(render_attribs.color_buffer_srv),
},
wgpu::BindGroupEntry {
binding: 3,
resource: texture(prev_buffer_srv),
},
wgpu::BindGroupEntry {
binding: 4,
resource: texture(render_attribs.motion_vectors_srv),
},
wgpu::BindGroupEntry {
binding: 5,
resource: texture(ctx.get_reprojected_depth()),
},
wgpu::BindGroupEntry {
binding: 6,
resource: texture(ctx.get_previous_depth()),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::Sampler(&self.linear_clamp),
},
wgpu::BindGroupEntry {
binding: 8,
resource: texture(acc_buff.closest_motion(prev_buff_idx)),
},
wgpu::BindGroupEntry {
binding: 9,
resource: texture(render_attribs.depth_buffer_srv),
},
]
.into_iter()
.chain(responsive_entries)
.collect::<Vec<_>>(),
);
draw(
render_attribs.device_context,
"TemporalAccumulation",
&[curr_buffer_rtv, acc_buff.closest_motion(curr_buff_idx)],
tech,
&group,
0..3,
render_attribs
.pass_timestamps
.and_then(|timestamps| timestamps("TemporalAccumulation")),
);
}
fn compute_placeholder_texture(
&self,
render_attribs: &mut RenderAttributes<'_, '_>,
acc_buff: &AccumulationBufferInfo,
responsive: Responsive,
) {
let buff_idx = acc_buff.current_frame_idx & 0x01;
let tech = &self.render_tech[&RenderTechniqueKey {
render_tech: RenderTech::ComputePlaceholder,
feature_flags: acc_buff.feature_flags,
reversed_depth: reversed_depth(render_attribs.post_fx_context),
responsive,
}];
let group = tech.bind_group(
render_attribs.device,
"ComputePlaceholder",
&[
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(render_attribs.color_buffer_srv),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::TextureView(render_attribs.motion_vectors_srv),
},
],
);
draw(
render_attribs.device_context,
"ComputePlaceholder",
&[
acc_buff.accumulated_buffer(buff_idx),
acc_buff.closest_motion(buff_idx),
],
tech,
&group,
0..3,
render_attribs
.pass_timestamps
.and_then(|timestamps| timestamps("TemporalAccumulation")),
);
}
}
#[cfg(test)]
mod camera_tests {
use super::{CameraAttribs, TemporalAntiAliasing};
const FOV_Y: f32 = 1.;
const ROWS: f32 = 1080.;
fn projection(fov_y: f32) -> [f32; 16] {
let (near, far) = (0.1f32, 100f32);
let y = 1. / (fov_y * 0.5).tan();
let x = y * ROWS / 1920.;
let m22 = far / (far - near);
[
x,
0.,
0.,
0., 0.,
y,
0.,
0., 0.,
0.,
m22,
1., 0.,
0.,
-near * m22,
0.,
]
}
fn view(position: [f32; 3], yaw: f32) -> [f32; 16] {
let (s, c) = yaw.sin_cos();
let [x, y, z] = position;
[
c,
0.,
s,
0., 0.,
1.,
0.,
0., -s,
0.,
c,
0., -(c * x - s * z),
-y,
-(s * x + c * z),
1.,
]
}
fn camera(view: [f32; 16], mut projection: [f32; 16], jitter: [f32; 2]) -> CameraAttribs {
for column in projection.chunks_exact_mut(4) {
column[0] += jitter[0] * column[3];
column[1] += jitter[1] * column[3];
}
CameraAttribs {
f2_jitter: jitter,
m_view: view,
m_proj: projection,
..Default::default()
}
}
fn stepped(mut value: f32, steps: i32) -> f32 {
for _ in 0..steps.unsigned_abs() {
value = if steps > 0 {
value.next_up()
} else {
value.next_down()
};
}
value
}
const POSITIONS: [[f32; 3]; 3] = [
[0.3, 1.2, -0.7],
[83.1, 21.7, -54.9],
[3170.4, 412.9, -4021.6],
];
#[test]
fn a_camera_at_rest_with_rounding_noise_has_not_moved() {
let projection = projection(FOV_Y);
for position in POSITIONS {
let rest = view(position, 0.7);
let previous = camera(rest, projection, [0.3 / 1920., -0.1 / 1080.]);
for (frame, steps) in [1, -2, 3, -3, 2, -1].into_iter().enumerate() {
let mut noisy = rest;
for (i, element) in noisy.iter_mut().enumerate() {
if *element != 0. && *element != 1. {
*element = stepped(*element, if i % 2 == 0 { steps } else { -steps });
}
}
let current = camera(noisy, projection, [-0.2 / 1920., 0.4 / 1080.]);
assert!(
!TemporalAntiAliasing::camera_moved(¤t, &previous),
"a camera at rest at {position:?} with {steps} rounding steps of noise (frame {frame}) moved"
);
}
}
}
#[test]
fn the_smallest_real_camera_changes_move_it() {
let pixel_angle = (2. * (FOV_Y * 0.5).tan() / ROWS).atan();
let scale = 1. + 0.01 / (ROWS * 0.5);
let wider = 2. * ((FOV_Y * 0.5).tan() * scale).atan();
let projection = projection(FOV_Y);
let [x, y, z] = POSITIONS[0];
let translated = camera(view([x + 0.001, y, z], 0.7), projection, [0.; 2]);
let origin = camera(view(POSITIONS[0], 0.7), projection, [0.; 2]);
assert!(
TemporalAntiAliasing::camera_moved(&translated, &origin),
"a 1 mm translation at the render origin did not move the camera"
);
for position in POSITIONS {
let rest = camera(view(position, 0.7), projection, [0.; 2]);
let turned = camera(
view(position, 0.7 + 0.01 * pixel_angle),
projection,
[0.; 2],
);
let widened = camera(view(position, 0.7), self::projection(wider), [0.; 2]);
for (what, current) in [("a turn", turned), ("a wider field", widened)] {
assert!(
TemporalAntiAliasing::camera_moved(¤t, &rest),
"{what} moving pixels by a hundredth at {position:?} did not move the camera"
);
}
}
}
#[test]
fn far_from_the_origin_a_translation_within_the_rounding_bound_is_left_to_the_pixels() {
let projection = projection(FOV_Y);
let position = POSITIONS[2];
let rest = camera(view(position, 0.7), projection, [0.; 2]);
let at = |offset: f32| {
let [x, y, z] = position;
camera(view([x + offset, y, z], 0.7), projection, [0.; 2])
};
assert!(
!TemporalAntiAliasing::camera_moved(&at(0.001), &rest),
"1 mm at 5 km is within the 4.8 mm the rounding tolerance admits there"
);
assert!(
TemporalAntiAliasing::camera_moved(&at(0.01), &rest),
"1 cm at 5 km is beyond the 4.8 mm the rounding tolerance admits there"
);
}
const YAW: f32 = 0.7;
fn right() -> [f32; 3] {
[YAW.cos(), 0., -YAW.sin()]
}
fn forward() -> [f32; 3] {
[-YAW.sin(), 0., -YAW.cos()]
}
fn eye_along(axis: [f32; 3], distance: f32) -> [f32; 3] {
[axis[0] * distance, 1.7, axis[2] * distance]
}
#[test]
fn a_view_rebuilt_from_a_rounded_eye_has_not_moved() {
let projection = projection(FOV_Y);
for (axis, name) in [(forward(), "forward"), (right(), "right")] {
for distance in [100., 5000.] {
let eye = eye_along(axis, distance);
let rest = camera(view(eye, YAW), projection, [0.; 2]);
for steps in [1, -2, 3, -3, 2, -1] {
let noisy = [
stepped(eye[0], steps),
stepped(eye[1], -steps),
stepped(eye[2], steps),
];
let current = camera(view(noisy, YAW), projection, [0.; 2]);
assert!(
!TemporalAntiAliasing::camera_moved(¤t, &rest),
"an eye {distance} m along the {name} axis, {steps} rounding steps off, moved"
);
}
}
}
}
#[test]
fn at_100_m_a_translation_beyond_the_eyes_rounding_moves_the_camera() {
let projection = projection(FOV_Y);
let eye = eye_along(forward(), 100.);
let rest = camera(view(eye, YAW), projection, [0.; 2]);
let at = |offset: f32| {
let [x, y, z] = eye;
camera(view([x + offset, y, z], YAW), projection, [0.; 2])
};
assert!(
!TemporalAntiAliasing::camera_moved(&at(0.00005), &rest),
"0.05 mm at 100 m is within the 73 µm the eye's rounding admits there"
);
assert!(
TemporalAntiAliasing::camera_moved(&at(0.001), &rest),
"1 mm at 100 m is beyond the 73 µm the eye's rounding admits there"
);
}
}