| 1 | use super::*; |
| 2 | |
| 3 | fn engine() -> Option<Engine> { |
| 4 | Engine::new_headless().ok() |
| 5 | } |
| 6 | |
| 7 | fn mk_comp(tools: &str) -> Comp { |
| 8 | let src = format!( |
| 9 | "Composition {{ CurrentTime = 0, RenderRange = {{ 0, 10 }}, GlobalRange = {{ 0, 10 }}, Tools = ordered() {{ {tools} }} }}" |
| 10 | ); |
| 11 | Comp::from_fusion_str(&src).expect("parse deep_flow test comp") |
| 12 | } |
| 13 | |
| 14 | fn eval(eng: &mut Engine, comp: &Comp, name: &str, time: f64) -> (CachedTexture, Vec<f32>) { |
| 15 | let (tex, stats) = eng.evaluate(comp, comp.find_node(name).unwrap_or_else(|| panic!("missing node {name}")), time); |
| 16 | assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); |
| 17 | let px = eng.readback_rgba_f32(&tex).expect("readback"); |
| 18 | (tex, px) |
| 19 | } |
| 20 | |
| 21 | fn px(buf: &[f32], w: u32, x: u32, y: u32) -> [f32; 4] { |
| 22 | let i = ((y * w + x) * 4) as usize; |
| 23 | buf[i..i + 4].try_into().unwrap() |
| 24 | } |
| 25 | |
| 26 | fn f16_to_f32(bits: u16) -> f32 { |
| 27 | let sign = if bits & 0x8000 != 0 { -1.0 } else { 1.0 }; |
| 28 | let (exp, frac) = ((bits >> 10) & 0x1F, (bits & 0x03FF) as f32); |
| 29 | match exp { |
| 30 | 0 => sign * frac * 2f32.powi(-24), |
| 31 | 0x1F => sign * f32::INFINITY, |
| 32 | _ => sign * (1.0 + frac / 1024.0) * 2f32.powi(exp as i32 - 15), |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /// Reads an `R32Float` / `Rgba16Float` aux channel as RGBA texels. |
| 37 | fn aux_px(eng: &Engine, tex: &AuxChannelTex) -> Vec<[f32; 4]> { |
| 38 | let [w, h] = tex.size; |
| 39 | let texel = if tex.format == wgpu::TextureFormat::R32Float { 4 } else { 8 }; |
| 40 | let padded = (w * texel).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 41 | let buf = eng.device.create_buffer(&wgpu::BufferDescriptor { |
| 42 | label: Some("deep-flow-test-readback"), |
| 43 | size: u64::from(padded * h), |
| 44 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 45 | mapped_at_creation: false, |
| 46 | }); |
| 47 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 48 | enc.copy_texture_to_buffer( |
| 49 | tex.texture.as_image_copy(), |
| 50 | wgpu::TexelCopyBufferInfo { |
| 51 | buffer: &buf, |
| 52 | layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(padded), rows_per_image: Some(h) }, |
| 53 | }, |
| 54 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 55 | ); |
| 56 | eng.queue.submit(Some(enc.finish())); |
| 57 | let slice = buf.slice(..); |
| 58 | let (tx, rx) = std::sync::mpsc::channel(); |
| 59 | slice.map_async(wgpu::MapMode::Read, move |r| tx.send(r).unwrap()); |
| 60 | eng.device |
| 61 | .poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(std::time::Duration::from_secs(10)) }) |
| 62 | .unwrap(); |
| 63 | rx.recv().unwrap().unwrap(); |
| 64 | let data = slice.get_mapped_range().unwrap(); |
| 65 | let mut out = Vec::new(); |
| 66 | for y in 0..h as usize { |
| 67 | let row = &data[y * padded as usize..][..(w * texel) as usize]; |
| 68 | for t in row.chunks_exact(texel as usize) { |
| 69 | out.push(if texel == 4 { |
| 70 | [f32::from_le_bytes(t[..4].try_into().unwrap()), 0.0, 0.0, 0.0] |
| 71 | } else { |
| 72 | let c = |i: usize| f16_to_f32(u16::from_le_bytes([t[i * 2], t[i * 2 + 1]])); |
| 73 | [c(0), c(1), c(2), c(3)] |
| 74 | }); |
| 75 | } |
| 76 | } |
| 77 | out |
| 78 | } |
| 79 | |
| 80 | fn aux_at(v: &[[f32; 4]], w: u32, x: u32, y: u32) -> [f32; 4] { |
| 81 | v[(y * w + x) as usize] |
| 82 | } |
| 83 | |
| 84 | /// 32-bit float `Background`; `extra` adds more inputs (corner colours, `Type`, expressions). |
| 85 | fn bg(name: &str, w: u32, h: u32, extra: &str) -> String { |
| 86 | format!( |
| 87 | "{name} = Background {{ Inputs = {{ Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, \ |
| 88 | Depth = Input {{ Value = 4, }}, {extra} }}, }}," |
| 89 | ) |
| 90 | } |
| 91 | |
| 92 | fn solid(name: &str, w: u32, h: u32, c: [f32; 4]) -> String { |
| 93 | bg( |
| 94 | name, |
| 95 | w, |
| 96 | h, |
| 97 | &format!( |
| 98 | "TopLeftRed = Input {{ Value = {}, }}, TopLeftGreen = Input {{ Value = {}, }}, \ |
| 99 | TopLeftBlue = Input {{ Value = {}, }}, TopLeftAlpha = Input {{ Value = {}, }},", |
| 100 | c[0], c[1], c[2], c[3] |
| 101 | ), |
| 102 | ) |
| 103 | } |
| 104 | |
| 105 | /// Left-to-right (or top-to-bottom) gradient from `a` to `b`. |
| 106 | fn grad(name: &str, w: u32, h: u32, a: [f32; 4], b: [f32; 4], vertical: bool) -> String { |
| 107 | let (far, ty) = if vertical { ("BottomLeft", "Vertical") } else { ("TopRight", "Horizontal") }; |
| 108 | bg( |
| 109 | name, |
| 110 | w, |
| 111 | h, |
| 112 | &format!( |
| 113 | "Type = Input {{ Value = FuID {{ \"{ty}\" }}, }}, \ |
| 114 | TopLeftRed = Input {{ Value = {}, }}, TopLeftGreen = Input {{ Value = {}, }}, \ |
| 115 | TopLeftBlue = Input {{ Value = {}, }}, TopLeftAlpha = Input {{ Value = {}, }}, \ |
| 116 | {far}Red = Input {{ Value = {}, }}, {far}Green = Input {{ Value = {}, }}, \ |
| 117 | {far}Blue = Input {{ Value = {}, }}, {far}Alpha = Input {{ Value = {}, }},", |
| 118 | a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3] |
| 119 | ), |
| 120 | ) |
| 121 | } |
| 122 | |
| 123 | fn channel_copy(name: &str, bg: &str, fg: &str) -> String { |
| 124 | format!( |
| 125 | "{name} = ChannelBoolean {{ Inputs = {{ ToRed = Input {{ Value = 0, }}, ToGreen = Input {{ Value = 1, }}, \ |
| 126 | ToBlue = Input {{ Value = 2, }}, ToAlpha = Input {{ Value = 3, }}, \ |
| 127 | Background = Input {{ SourceOp = \"{bg}\", Source = \"Output\", }}, \ |
| 128 | Foreground = Input {{ SourceOp = \"{fg}\", Source = \"Output\", }}, }}, }}," |
| 129 | ) |
| 130 | } |
| 131 | |
| 132 | /// `base` colour plus aux channels, each written from the RG(B) of a colour image: `(channel, value_node)`. |
| 133 | fn aux_chain(name: &str, base: &str, auxes: &[(&str, &str)]) -> String { |
| 134 | let mut out = String::new(); |
| 135 | let mut prev = base.to_owned(); |
| 136 | for (i, (chan, value)) in auxes.iter().enumerate() { |
| 137 | out += &channel_copy(&format!("{name}H{i}"), &prev, value); |
| 138 | out += &format!( |
| 139 | "{name}A{i} = Dimension.CopyAux {{ Inputs = {{ Mode = Input {{ Value = 1, }}, \ |
| 140 | Channel = Input {{ Value = FuID {{ \"{chan}\" }}, }}, \ |
| 141 | Input = Input {{ SourceOp = \"{name}H{i}\", Source = \"Output\", }}, }}, }}," |
| 142 | ); |
| 143 | prev = format!("{name}A{i}"); |
| 144 | } |
| 145 | out + &channel_copy(name, &prev, base) |
| 146 | } |
| 147 | |
| 148 | /// Colour `rgba` image carrying a horizontal `aux.z` ramp `zl..zr`. |
| 149 | fn z_scene(name: &str, w: u32, h: u32, rgba: [f32; 4], zl: f32, zr: f32) -> String { |
| 150 | format!( |
| 151 | "{}{}{}{}", |
| 152 | solid(&format!("{name}Col"), w, h, rgba), |
| 153 | grad(&format!("{name}ZImg"), w, h, [zl, 0.0, 0.0, 1.0], [zr, 0.0, 0.0, 1.0], false), |
| 154 | format_args!( |
| 155 | "{name}ZAux = Dimension.CopyAux {{ Inputs = {{ Mode = Input {{ Value = 1, }}, \ |
| 156 | Channel = Input {{ Value = FuID {{ \"Z\" }}, }}, Input = Input {{ SourceOp = \"{name}ZImg\", Source = \"Output\", }}, }}, }}," |
| 157 | ), |
| 158 | format_args!( |
| 159 | "{name} = ChannelBoolean {{ Inputs = {{ ToRed = Input {{ Value = 5, }}, ToGreen = Input {{ Value = 6, }}, \ |
| 160 | ToBlue = Input {{ Value = 7, }}, ToAlpha = Input {{ Value = 8, }}, EnableExtraChannels = Input {{ Value = 1, }}, \ |
| 161 | ToZBuffer = Input {{ Value = 18, }}, Background = Input {{ SourceOp = \"{name}Col\", Source = \"Output\", }}, \ |
| 162 | Foreground = Input {{ SourceOp = \"{name}ZAux\", Source = \"Output\", }}, }}, }}," |
| 163 | ), |
| 164 | ) |
| 165 | } |
| 166 | |
| 167 | fn inp(port: &str, op: &str) -> String { |
| 168 | format!("{port} = Input {{ SourceOp = \"{op}\", Source = \"Output\", }},") |
| 169 | } |
| 170 | |
| 171 | fn val(name: &str, v: f32) -> String { |
| 172 | format!("{name} = Input {{ Value = {v}, }},") |
| 173 | } |
| 174 | |
| 175 | fn rect_mask(name: &str, center: [f32; 2], size: [f32; 2]) -> String { |
| 176 | format!( |
| 177 | "{name} = RectangleMask {{ Inputs = {{ Center = Input {{ Value = {{ {}, {} }}, }}, Width = Input {{ Value = {}, }}, \ |
| 178 | Height = Input {{ Value = {}, }}, }}, }},", |
| 179 | center[0], center[1], size[0], size[1] |
| 180 | ) |
| 181 | } |
| 182 | |
| 183 | fn node(name: &str, kind: &str, inputs: &[String]) -> String { |
| 184 | format!("{name} = {kind} {{ Inputs = {{ {} }}, }},", inputs.concat()) |
| 185 | } |
| 186 | |
| 187 | /// Camera at the origin looking down -Z with 90 degree vertical FOV: `tan(fov/2) = 1`. |
| 188 | const FOV90: &str = "FOV = Input { Value = 90, },"; |
| 189 | |
| 190 | #[test] |
| 191 | fn z_to_world_pos_unprojects_with_fov_and_camera_and_preserves_aux() { |
| 192 | let Some(mut eng) = engine() else { return }; |
| 193 | let tools = [ |
| 194 | z_scene("Scene", 32, 32, [0.25, 0.5, 0.75, 1.0], -10.0, -10.0), |
| 195 | node("W", "ZtoWorldPos", &[inp("Input", "Scene"), FOV90.into()]), |
| 196 | node("WHalf", "ZtoWorldPos", &[inp("Input", "Scene"), FOV90.into(), val("Blend", 0.5)]), |
| 197 | node("WNoBlend", "ZtoWorldPos", &[inp("Input", "Scene"), FOV90.into(), val("Blend", 0.0)]), |
| 198 | node( |
| 199 | "WClip", |
| 200 | "ZtoWorldPos", |
| 201 | &[inp("Input", "Scene"), FOV90.into(), val("NearClip", 1.0), val("FarClip", 5.0)], |
| 202 | ), |
| 203 | node("Cam", "Camera3D", &["[\"Transform3DOp.Translate.Z\"] = Input { Value = 3, },".into()]), |
| 204 | node("WCam", "ZtoWorldPos", &[inp("Input", "Scene"), inp("Camera", "Cam")]), |
| 205 | ] |
| 206 | .concat(); |
| 207 | let comp = mk_comp(&tools); |
| 208 | let (tex, p) = eval(&mut eng, &comp, "W", 0.0); |
| 209 | // x = ndc.x * tan(45deg) * aspect * depth, y = ndc.y * depth, z = -depth. |
| 210 | let right = px(&p, 32, 31, 16); |
| 211 | assert!((right[0] - 0.96875 * 10.0).abs() < 0.05, "world x {right:?}"); |
| 212 | assert!((right[1] - -0.3125).abs() < 0.05 && (right[2] + 10.0).abs() < 0.01 && right[3] > 0.99, "{right:?}"); |
| 213 | let top = px(&p, 32, 16, 0); |
| 214 | assert!((top[1] - 0.96875 * 10.0).abs() < 0.05, "top row is +Y, got {top:?}"); |
| 215 | assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "aux.z must be preserved"); |
| 216 | |
| 217 | let (_, half) = eval(&mut eng, &comp, "WHalf", 0.0); |
| 218 | assert!((px(&half, 32, 16, 16)[2] - (0.5 * 0.75 + 0.5 * -10.0)).abs() < 0.01, "Blend=0.5 mixes the source blue with world z"); |
| 219 | let (_, orig) = eval(&mut eng, &comp, "Scene", 0.0); |
| 220 | let (_, none) = eval(&mut eng, &comp, "WNoBlend", 0.0); |
| 221 | assert_eq!(px(&none, 32, 8, 8), px(&orig, 32, 8, 8), "Blend=0 passes the input through"); |
| 222 | |
| 223 | let (_, clip) = eval(&mut eng, &comp, "WClip", 0.0); |
| 224 | assert_eq!(px(&clip, 32, 8, 8), [0.0; 4], "depth 10 is beyond FarClip=5 so the position is invalid"); |
| 225 | |
| 226 | let (_, cam) = eval(&mut eng, &comp, "WCam", 0.0); |
| 227 | let c = px(&cam, 32, 16, 16); |
| 228 | assert!((c[2] - -7.0).abs() < 0.01, "camera at z=3 puts depth -10 at world z=-7, got {c:?}"); |
| 229 | } |
| 230 | |
| 231 | #[test] |
| 232 | fn volume_fog_shapes_noise_world_image_and_mask() { |
| 233 | let Some(mut eng) = engine() else { return }; |
| 234 | let sphere = |extra: &[String]| { |
| 235 | let mut v = vec![ |
| 236 | inp("Input", "Scene"), |
| 237 | FOV90.into(), |
| 238 | "[\"Transform3DOp.Translate.Z\"] = Input { Value = -10, },".into(), |
| 239 | "[\"Transform3DOp.Scale.X\"] = Input { Value = 5, },".into(), |
| 240 | val("Density", 60.0), |
| 241 | val("Falloff", 0.0), |
| 242 | ]; |
| 243 | v.extend_from_slice(extra); |
| 244 | v |
| 245 | }; |
| 246 | let tools = [ |
| 247 | z_scene("Scene", 32, 32, [0.0, 0.0, 0.0, 1.0], -10.0, -10.0), |
| 248 | rect_mask("RightHalf", [0.75, 0.5], [0.5, 1.0]), |
| 249 | node("Fog", "VolumeFog", &sphere(&[])), |
| 250 | node("FogHalf", "VolumeFog", &sphere(&[val("Blend", 0.5)])), |
| 251 | node("FogOff", "VolumeFog", &sphere(&[val("Blend", 0.0)])), |
| 252 | node("FogMasked", "VolumeFog", &sphere(&[inp("EffectMask", "RightHalf").replace("Output", "Mask")])), |
| 253 | node( |
| 254 | "FogMaskedInv", |
| 255 | "VolumeFog", |
| 256 | &sphere(&[inp("EffectMask", "RightHalf").replace("Output", "Mask"), val("ApplyMaskInverted", 1.0)]), |
| 257 | ), |
| 258 | node("FogBox", "VolumeFog", &sphere(&["Shape = Input { Value = FuID { \"Box\" }, },".into()])), |
| 259 | node("FogNoise", "VolumeFog", &sphere(&[val("Noise", 1.0), val("Density", 2.0), val("NoiseScale", 1.5)])), |
| 260 | node("FogColor", "VolumeFog", &sphere(&[val("FogRed", 1.0), val("FogGreen", 0.0), val("FogBlue", 0.0)])), |
| 261 | node("WPos", "ZtoWorldPos", &[inp("Input", "Scene"), FOV90.into()]), |
| 262 | node("FogWpp", "VolumeFog", &sphere(&[inp("WorldPosImage", "WPos")])), |
| 263 | node("NoDepth", "VolumeFog", &[inp("Input", "SceneCol"), FOV90.into()]), |
| 264 | ] |
| 265 | .concat(); |
| 266 | let comp = mk_comp(&tools); |
| 267 | let (tex, p) = eval(&mut eng, &comp, "Fog", 0.0); |
| 268 | // Columns 8..23 lie inside the radius-5 sphere centred at z=-10. |
| 269 | assert!(px(&p, 32, 16, 16)[0] > 0.99, "centre fogged white"); |
| 270 | assert!(px(&p, 32, 2, 16)[0] < 0.01, "outside the sphere is untouched"); |
| 271 | assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "aux.z preserved"); |
| 272 | |
| 273 | let (_, half) = eval(&mut eng, &comp, "FogHalf", 0.0); |
| 274 | assert!((px(&half, 32, 16, 16)[0] - 0.5).abs() < 0.02, "Blend=0.5"); |
| 275 | let (_, off) = eval(&mut eng, &comp, "FogOff", 0.0); |
| 276 | assert!(px(&off, 32, 16, 16)[0] < 0.01, "Blend=0"); |
| 277 | |
| 278 | let (_, masked) = eval(&mut eng, &comp, "FogMasked", 0.0); |
| 279 | assert!(px(&masked, 32, 20, 16)[0] > 0.99 && px(&masked, 32, 12, 16)[0] < 0.01, "EffectMask limits fog to the right half"); |
| 280 | let (_, inv) = eval(&mut eng, &comp, "FogMaskedInv", 0.0); |
| 281 | assert!(px(&inv, 32, 12, 16)[0] > 0.99 && px(&inv, 32, 20, 16)[0] < 0.01, "ApplyMaskInverted flips the mask"); |
| 282 | |
| 283 | let (_, bx) = eval(&mut eng, &comp, "FogBox", 0.0); |
| 284 | assert!(px(&bx, 32, 9, 9)[0] > 0.99, "Box covers the corner a sphere would miss"); |
| 285 | assert!(px(&p, 32, 9, 9)[0] < 0.01, "Sphere misses that corner"); |
| 286 | |
| 287 | let (_, nz) = eval(&mut eng, &comp, "FogNoise", 0.0); |
| 288 | let vals: Vec<f32> = (10..22).map(|x| px(&nz, 32, x, 16)[0]).collect(); |
| 289 | let (lo, hi) = vals.iter().fold((f32::MAX, f32::MIN), |(l, h), &v| (l.min(v), h.max(v))); |
| 290 | assert!(hi - lo > 0.05, "fBm turbulence must vary the fog, got {vals:?}"); |
| 291 | |
| 292 | let (_, col) = eval(&mut eng, &comp, "FogColor", 0.0); |
| 293 | let c = px(&col, 32, 16, 16); |
| 294 | assert!(c[0] > 0.99 && c[1] < 0.01 && c[2] < 0.01, "FogRed/Green/Blue tint, got {c:?}"); |
| 295 | |
| 296 | let (_, wpp) = eval(&mut eng, &comp, "FogWpp", 0.0); |
| 297 | assert_eq!(px(&wpp, 32, 16, 16), px(&p, 32, 16, 16), "WorldPosImage from ZtoWorldPos matches the aux.z route"); |
| 298 | assert_eq!(px(&wpp, 32, 2, 16), px(&p, 32, 2, 16)); |
| 299 | |
| 300 | let (_, nd) = eval(&mut eng, &comp, "NoDepth", 0.0); |
| 301 | assert_eq!(px(&nd, 32, 16, 16), [0.0, 0.0, 0.0, 1.0], "no depth source leaves the image unchanged"); |
| 302 | } |
| 303 | |
| 304 | #[test] |
| 305 | fn volume_mask_outputs_invert_softness_and_cylinder() { |
| 306 | let Some(mut eng) = engine() else { return }; |
| 307 | let base = |extra: &[String]| { |
| 308 | let mut v = vec![ |
| 309 | inp("Input", "Scene"), |
| 310 | FOV90.into(), |
| 311 | "[\"Transform3DOp.Translate.Z\"] = Input { Value = -10, },".into(), |
| 312 | "[\"Transform3DOp.Scale.X\"] = Input { Value = 5, },".into(), |
| 313 | ]; |
| 314 | v.extend_from_slice(extra); |
| 315 | v |
| 316 | }; |
| 317 | let tools = [ |
| 318 | z_scene("Scene", 32, 32, [0.2, 0.4, 0.6, 1.0], -10.0, -10.0), |
| 319 | node("Alpha", "VolumeMask", &base(&[])), |
| 320 | node("Mask", "VolumeMask", &base(&["Output = Input { Value = FuID { \"Mask\" }, },".into()])), |
| 321 | node("Inv", "VolumeMask", &base(&[val("Invert", 1.0)])), |
| 322 | node("Soft", "VolumeMask", &base(&[val("Softness", 1.0)])), |
| 323 | node("Cyl", "VolumeMask", &base(&["Shape = Input { Value = FuID { \"Cylinder\" }, },".into(), "Output = Input { Value = 1, },".into()])), |
| 324 | node("Half", "VolumeMask", &base(&[val("Blend", 0.5), "Output = Input { Value = 1, },".into()])), |
| 325 | ] |
| 326 | .concat(); |
| 327 | let comp = mk_comp(&tools); |
| 328 | |
| 329 | let (tex, a) = eval(&mut eng, &comp, "Alpha", 0.0); |
| 330 | let c = px(&a, 32, 16, 16); |
| 331 | assert!((c[0] - 0.2).abs() < 0.01 && (c[3] - 1.0).abs() < 0.01, "Alpha output keeps RGB inside: {c:?}"); |
| 332 | assert!(px(&a, 32, 2, 16)[3] < 0.01, "alpha cut outside the volume"); |
| 333 | assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some()); |
| 334 | |
| 335 | let (_, m) = eval(&mut eng, &comp, "Mask", 0.0); |
| 336 | assert_eq!(px(&m, 32, 16, 16), [1.0; 4], "Mask output is a white RGBA matte inside"); |
| 337 | assert_eq!(px(&m, 32, 2, 16), [0.0; 4], "and black outside"); |
| 338 | |
| 339 | let (_, inv) = eval(&mut eng, &comp, "Inv", 0.0); |
| 340 | assert!(px(&inv, 32, 16, 16)[3] < 0.01 && px(&inv, 32, 2, 16)[3] > 0.99, "Invert flips the matte"); |
| 341 | |
| 342 | let (_, soft) = eval(&mut eng, &comp, "Soft", 0.0); |
| 343 | let edge: Vec<f32> = (23..29).map(|x| px(&soft, 32, x, 16)[3]).collect(); |
| 344 | assert!(edge.windows(2).all(|w| w[0] >= w[1] - 1e-4) && edge.iter().any(|&v| v > 0.02 && v < 0.98), "softness ramps: {edge:?}"); |
| 345 | |
| 346 | // Cylinder axis is Y: a pixel directly above the centre at |y| < 5 is inside, y = 7 is outside. |
| 347 | let (_, cyl) = eval(&mut eng, &comp, "Cyl", 0.0); |
| 348 | assert!(px(&cyl, 32, 16, 12)[3] > 0.99, "inside cylinder height"); |
| 349 | let (_, half) = eval(&mut eng, &comp, "Half", 0.0); |
| 350 | assert!((px(&half, 32, 16, 16)[0] - 0.6).abs() < 0.02, "Blend=0.5 mixes the image (0.2) with the white matte"); |
| 351 | } |
| 352 | |
| 353 | #[test] |
| 354 | fn ssao_modes_strength_blend_and_normal_aux() { |
| 355 | let Some(mut eng) = engine() else { return }; |
| 356 | let patch = format!( |
| 357 | "{}{}{}{}{}", |
| 358 | z_scene("Far", 32, 32, [1.0, 1.0, 1.0, 1.0], -10.0, -10.0), |
| 359 | z_scene("Near", 32, 32, [1.0, 1.0, 1.0, 1.0], -8.0, -8.0), |
| 360 | rect_mask("Mid", [0.5, 0.5], [0.25, 0.25]), |
| 361 | node( |
| 362 | "Scene", |
| 363 | "Merge", |
| 364 | &[inp("Background", "Far"), inp("Foreground", "Near"), inp("EffectMask", "Mid").replace("Output", "Mask"), val("PerformDepthMerge", 1.0)] |
| 365 | ), |
| 366 | solid("NormSrc", 32, 32, [0.0, 0.0, 1.0, 1.0]), |
| 367 | ); |
| 368 | let ssao = |extra: &[String]| { |
| 369 | let mut v = vec![inp("Input", "Scene"), val("Samples", 32.0)]; |
| 370 | v.extend_from_slice(extra); |
| 371 | v |
| 372 | }; |
| 373 | let tools = [ |
| 374 | patch, |
| 375 | aux_chain("SceneN", "Scene", &[("Normal", "NormSrc")]), |
| 376 | node("AoOnly", "SSAO", &ssao(&["Mode = Input { Value = FuID { \"AO Only\" }, },".into()])), |
| 377 | node("Comp", "SSAO", &ssao(&[])), |
| 378 | node("Strong", "SSAO", &ssao(&[val("Strength", 4.0), "Mode = Input { Value = 1, },".into()])), |
| 379 | node("Zero", "SSAO", &ssao(&[val("Strength", 0.0), "Mode = Input { Value = 1, },".into()])), |
| 380 | node("Blend0", "SSAO", &ssao(&[val("Blend", 0.0)])), |
| 381 | node("WithNormal", "SSAO", &[inp("Input", "SceneN"), val("Samples", 32.0), "Mode = Input { Value = 1, },".into()]), |
| 382 | node("NoZ", "SSAO", &[inp("Input", "NormSrc")]), |
| 383 | ] |
| 384 | .concat(); |
| 385 | let comp = mk_comp(&tools); |
| 386 | |
| 387 | let (tex, ao) = eval(&mut eng, &comp, "AoOnly", 0.0); |
| 388 | let near_patch = px(&ao, 32, 10, 16)[0]; |
| 389 | let far_away = px(&ao, 32, 1, 1)[0]; |
| 390 | let on_patch = px(&ao, 32, 16, 16)[0]; |
| 391 | assert!(far_away > 0.99, "open floor is unoccluded, got {far_away}"); |
| 392 | assert!(on_patch > 0.99, "the raised patch top is unoccluded, got {on_patch}"); |
| 393 | assert!(near_patch < far_away - 0.05, "floor beside the patch is occluded: {near_patch} vs {far_away}"); |
| 394 | assert_eq!(px(&ao, 32, 10, 16)[0], px(&ao, 32, 10, 16)[2], "AO Only is grey"); |
| 395 | assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "aux preserved"); |
| 396 | |
| 397 | let (_, c) = eval(&mut eng, &comp, "Comp", 0.0); |
| 398 | assert!((px(&c, 32, 10, 16)[0] - near_patch).abs() < 0.01, "Composite multiplies white by the AO term"); |
| 399 | assert!(px(&c, 32, 1, 1)[0] > 0.99); |
| 400 | |
| 401 | let (_, strong) = eval(&mut eng, &comp, "Strong", 0.0); |
| 402 | assert!(px(&strong, 32, 10, 16)[0] < near_patch - 0.05, "higher Strength darkens more"); |
| 403 | let (_, zero) = eval(&mut eng, &comp, "Zero", 0.0); |
| 404 | assert!(px(&zero, 32, 10, 16)[0] > 0.99, "Strength 0 disables occlusion"); |
| 405 | let (_, b0) = eval(&mut eng, &comp, "Blend0", 0.0); |
| 406 | assert!(px(&b0, 32, 10, 16)[0] > 0.99, "Blend 0 returns the input"); |
| 407 | |
| 408 | let (_, n) = eval(&mut eng, &comp, "WithNormal", 0.0); |
| 409 | assert!(px(&n, 32, 10, 16)[0] < 0.95 && px(&n, 32, 1, 1)[0] > 0.99, "aux.normal drives the same occlusion"); |
| 410 | |
| 411 | let (_, no_z) = eval(&mut eng, &comp, "NoZ", 0.0); |
| 412 | assert_eq!(px(&no_z, 32, 4, 4), [0.0, 0.0, 1.0, 1.0], "no aux.z passes through"); |
| 413 | } |
| 414 | |
| 415 | /// `base` colour carrying a constant `aux.normal` `n` (Rgba16Float `NX NY NZ`). |
| 416 | fn normal_scene(name: &str, rgba: [f32; 4], n: [f32; 3]) -> String { |
| 417 | format!( |
| 418 | "{}{}", |
| 419 | solid(&format!("{name}Col"), 32, 32, rgba), |
| 420 | aux_chain(name, &format!("{name}Col"), &[("Normal", &format!("{name}N"))]), |
| 421 | ) + &solid(&format!("{name}N"), 32, 32, [n[0], n[1], n[2], 1.0]) |
| 422 | } |
| 423 | |
| 424 | #[test] |
| 425 | fn deep_shader_ambient_diffuse_specular_reflection_and_blend() { |
| 426 | let Some(mut eng) = engine() else { return }; |
| 427 | let shader = |input: &str, extra: &[String]| { |
| 428 | let mut v = vec![inp("Input", input)]; |
| 429 | v.extend_from_slice(extra); |
| 430 | v |
| 431 | }; |
| 432 | let tools = [ |
| 433 | solid("Flat", 32, 32, [0.5, 0.5, 0.5, 0.5]), |
| 434 | // Facing the viewer, and tilted away from the default (45, 45) light. |
| 435 | normal_scene("Facing", [0.5, 0.5, 0.5, 1.0], [0.0, 0.0, 1.0]), |
| 436 | normal_scene("Away", [0.5, 0.5, 0.5, 1.0], [-0.7, -0.7, 0.14]), |
| 437 | solid("Env", 16, 8, [1.0, 0.0, 0.0, 1.0]), |
| 438 | node("NoNormal", "Shader", &shader("Flat", &[])), |
| 439 | node("Ambient", "Shader", &shader("Flat", &[val("Ambient", 0.5), val("Diffuse", 0.0)])), |
| 440 | node("Skip", "Shader", &shader("Flat", &[val("ProcessGreen", 0.0)])), |
| 441 | node("Half", "Shader", &shader("Flat", &[val("Blend", 0.5)])), |
| 442 | node("Lit", "Shader", &shader("Facing", &[val("Specular", 0.0)])), |
| 443 | node("LitAway", "Shader", &shader("Away", &[val("Specular", 0.0)])), |
| 444 | node("Spec", "Shader", &shader("Facing", &[val("Diffuse", 0.0), val("Ambient", 0.0), val("EquatorAngle", 0.0), val("PolarHeight", 90.0)])), |
| 445 | node("SpecBlue", "Shader", &shader("Facing", &[val("Diffuse", 0.0), val("Ambient", 0.0), val("PolarHeight", 90.0), val("SpecularRed", 0.0), val("SpecularGreen", 0.0)])), |
| 446 | node("Refl", "Shader", &shader("Facing", &[inp("EnvironmentReflectionMap", "Env"), val("Specular", 0.0), val("Diffuse", 0.0), val("Ambient", 0.0)])), |
| 447 | node("Off", "Shader", &shader("Flat", &[val("Blend", 0.0)])), |
| 448 | ] |
| 449 | .concat(); |
| 450 | let comp = mk_comp(&tools); |
| 451 | let at = |p: &[f32]| px(p, 32, 16, 16); |
| 452 | let run = |eng: &mut Engine, name: &str| at(&eval(eng, &comp, name, 0.0).1); |
| 453 | |
| 454 | let flat = run(&mut eng, "NoNormal"); |
| 455 | assert!((flat[0] - 0.5 * 0.25).abs() < 0.01 && (flat[3] - 0.5).abs() < 1e-4, "no normals: only Ambient (0.25) remains, got {flat:?}"); |
| 456 | let ambient = run(&mut eng, "Ambient"); |
| 457 | assert!((ambient[0] - 0.25).abs() < 0.01, "Ambient scales the image: {ambient:?}"); |
| 458 | let skip = run(&mut eng, "Skip"); |
| 459 | assert!((skip[0] - 0.125).abs() < 0.01 && (skip[1] - 0.5).abs() < 0.01, "ProcessGreen=0 keeps the source green: {skip:?}"); |
| 460 | let half = run(&mut eng, "Half"); |
| 461 | assert!((half[0] - 0.5 * (1.0 + 0.25) / 2.0).abs() < 0.01, "Blend mixes with the source: {half:?}"); |
| 462 | assert!((run(&mut eng, "Off")[0] - 0.5).abs() < 1e-4, "Blend=0 keeps the input"); |
| 463 | |
| 464 | let lit = run(&mut eng, "Lit"); |
| 465 | let away = run(&mut eng, "LitAway"); |
| 466 | let ndl = 0.5f32.sqrt(); |
| 467 | assert!((lit[0] - 0.5 * (0.25 + ndl)).abs() < 0.02, "Ambient + Diffuse * N.L for the (45, 45) light: {lit:?}"); |
| 468 | assert!(away[0] < lit[0] - 0.1 && away[0] >= 0.5 * 0.25 - 0.01, "a surface turned from the light keeps only Ambient: {away:?} vs {lit:?}"); |
| 469 | |
| 470 | let spec = run(&mut eng, "Spec"); |
| 471 | assert!(spec[0] > 0.9 && spec[1] > 0.9 && spec[2] > 0.9, "overhead light on a facing normal adds a white highlight: {spec:?}"); |
| 472 | let spec_blue = run(&mut eng, "SpecBlue"); |
| 473 | assert!(spec_blue[0] < 0.01 && spec_blue[2] > 0.9, "SpecularRed/Green tint the highlight: {spec_blue:?}"); |
| 474 | let refl = run(&mut eng, "Refl"); |
| 475 | assert!(refl[0] > 0.9 && refl[1] < 0.01, "Screen reflection of the red map: {refl:?}"); |
| 476 | |
| 477 | let (tex, _) = eval(&mut eng, &comp, "Lit", 0.0); |
| 478 | assert!(tex.aux.as_ref().and_then(|a| a.normal.as_ref()).is_some(), "aux preserved"); |
| 479 | } |
| 480 | |
| 481 | #[test] |
| 482 | fn texture_uv_remap_scale_offset_flips_and_coverage() { |
| 483 | let Some(mut eng) = engine() else { return }; |
| 484 | let tex_node = |extra: &[String]| { |
| 485 | let mut v = vec![inp("Input", "UV"), inp("Texture", "Tex")]; |
| 486 | v.extend_from_slice(extra); |
| 487 | v |
| 488 | }; |
| 489 | let edges = |e: &str| format!("Edges = Input {{ Value = FuID {{ \"{e}\" }}, }},"); |
| 490 | let tools = [ |
| 491 | grad("UV", 32, 32, [0.0, 0.5, 0.0, 1.0], [1.0, 0.5, 0.0, 1.0], false), |
| 492 | // A 2D UV image: u across, v up. |
| 493 | bg("Corner", 32, 32, "Type = Input { Value = FuID { \"Corner\" }, }, TopLeftGreen = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, TopRightRed = Input { Value = 1, }, TopRightGreen = Input { Value = 1, }, TopRightAlpha = Input { Value = 1, }, BottomLeftAlpha = Input { Value = 1, }, BottomRightRed = Input { Value = 1, }, BottomRightAlpha = Input { Value = 1, },"), |
| 494 | grad("Tex", 64, 64, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], false), |
| 495 | solid("Hole", 32, 32, [0.5, 0.5, 0.0, 0.0]), |
| 496 | node("Def", "Texture", &tex_node(&[])), |
| 497 | node("Scaled", "Texture", &tex_node(&[val("UScale", 2.0)])), |
| 498 | node("Offset", "Texture", &tex_node(&[val("UOffset", 0.25)])), |
| 499 | node("Black", "Texture", &tex_node(&[val("UScale", 2.0), edges("Black")])), |
| 500 | node("Dup", "Texture", &tex_node(&[val("UScale", 2.0), edges("Duplicate")])), |
| 501 | node("Mirror", "Texture", &tex_node(&[val("UScale", 2.0), edges("Mirror")])), |
| 502 | node("Cover", "Texture", &[inp("Input", "Hole"), inp("Texture", "Tex")]), |
| 503 | node("NoTex", "Texture", &[inp("Input", "UV")]), |
| 504 | node("Half", "Texture", &tex_node(&[val("Blend", 0.5)])), |
| 505 | node("FlipH", "Texture", &[inp("Input", "UV"), inp("Texture", "Corner"), val("FlipHoriz", 1.0)]), |
| 506 | node("FlipV", "Texture", &[inp("Input", "Corner"), inp("Texture", "Corner"), val("FlipVert", 1.0)]), |
| 507 | node("Swap", "Texture", &[inp("Input", "Corner"), inp("Texture", "Corner"), val("SwapUV0", 1.0)]), |
| 508 | node("Rot", "Texture", &[inp("Input", "Corner"), inp("Texture", "Corner"), val("Rotate90", 1.0)]), |
| 509 | node("RotOff", "Texture", &[inp("Input", "Corner"), inp("Texture", "Corner"), val("Rotate90", 1.0), val("UOffset", 0.1), val("UScale", 0.5)]), |
| 510 | solid("Wide", 32, 32, [0.0, 0.5, 0.0, 1.0]), |
| 511 | rect_mask("LeftHalf", [0.25, 0.5], [0.5, 1.0]), |
| 512 | node("NoTexMasked", "Texture", &[inp("Input", "UV"), format!("MultiplyByMask = Input {{ Value = 1, }}, ProcessRed = Input {{ Value = 0, }}, EffectMask = Input {{ SourceOp = \"LeftHalf\", Source = \"Mask\", }},")]), |
| 513 | ] |
| 514 | .concat(); |
| 515 | let comp = mk_comp(&tools); |
| 516 | let at = |p: &[f32], x: u32| px(p, 32, x, 16); |
| 517 | let at_y = |p: &[f32], x: u32, y: u32| px(p, 32, x, y); |
| 518 | |
| 519 | let (_, def) = eval(&mut eng, &comp, "Def", 0.0); |
| 520 | assert!((at(&def, 16)[0] - 0.5).abs() < 0.06 && (at(&def, 8)[0] - 0.25).abs() < 0.06, "identity UV samples the texture ramp"); |
| 521 | assert!(at(&def, 16)[3] > 0.99); |
| 522 | let (_, scaled) = eval(&mut eng, &comp, "Scaled", 0.0); |
| 523 | assert!(at(&scaled, 16)[0] < 0.15, "UScale=2 wraps u=1.0 back near 0, got {:?}", at(&scaled, 16)); |
| 524 | let (_, off) = eval(&mut eng, &comp, "Offset", 0.0); |
| 525 | assert!((at(&off, 16)[0] - 0.25).abs() < 0.06, "UOffset subtracts from the lookup, got {:?}", at(&off, 16)); |
| 526 | let (_, black) = eval(&mut eng, &comp, "Black", 0.0); |
| 527 | assert!(at(&black, 24)[3] < 0.01, "Edges=Black is transparent out of range"); |
| 528 | let (_, dup) = eval(&mut eng, &comp, "Dup", 0.0); |
| 529 | assert!(at(&dup, 24)[0] > 0.95 && at(&dup, 24)[3] > 0.99, "Edges=Duplicate clamps to the border"); |
| 530 | let (_, mir) = eval(&mut eng, &comp, "Mirror", 0.0); |
| 531 | assert!((at(&mir, 24)[0] - 0.5).abs() < 0.08, "u=1.5 mirrors to 0.5, got {:?}", at(&mir, 24)); |
| 532 | let (_, cover) = eval(&mut eng, &comp, "Cover", 0.0); |
| 533 | assert_eq!(at(&cover, 16), [0.0; 4], "zero-alpha UV pixels stay transparent"); |
| 534 | let (_, no_tex) = eval(&mut eng, &comp, "NoTex", 0.0); |
| 535 | assert!((at(&no_tex, 16)[0] - 0.5).abs() < 0.03, "no texture input passes Input through"); |
| 536 | let (_, half) = eval(&mut eng, &comp, "Half", 0.0); |
| 537 | assert!((at(&half, 16)[0] - 0.5).abs() < 0.06, "Blend mixes with the UV image (0.5 either way here)"); |
| 538 | |
| 539 | let (_, fh) = eval(&mut eng, &comp, "FlipH", 0.0); |
| 540 | assert!((at(&fh, 8)[0] - 0.75).abs() < 0.04 && (at(&fh, 8)[0] - at(&fh, 24)[0]).abs() > 0.4, "FlipHoriz mirrors u: {:?}", at(&fh, 8)); |
| 541 | let rg = |p: &[f32], x: u32, y: u32| (at_y(p, x, y)[0], at_y(p, x, y)[1]); |
| 542 | let near = |a: (f32, f32), b: (f32, f32)| (a.0 - b.0).abs() < 0.05 && (a.1 - b.1).abs() < 0.05; |
| 543 | // pixel (8, 8) has (u, v) = (0.25, 0.75). |
| 544 | let (_, fv) = eval(&mut eng, &comp, "FlipV", 0.0); |
| 545 | assert!(near(rg(&fv, 8, 8), (0.25, 0.25)), "FlipVert mirrors v: {:?}", rg(&fv, 8, 8)); |
| 546 | let (_, sw) = eval(&mut eng, &comp, "Swap", 0.0); |
| 547 | assert!(near(rg(&sw, 8, 8), (0.75, 0.25)), "SwapUV0 exchanges u and v: {:?}", rg(&sw, 8, 8)); |
| 548 | let (_, rot) = eval(&mut eng, &comp, "Rot", 0.0); |
| 549 | assert!(near(rg(&rot, 8, 8), (0.75, 0.75)), "Rotate90 maps (u, v) to (v, 1 - u): {:?}", rg(&rot, 8, 8)); |
| 550 | let (_, rot_off) = eval(&mut eng, &comp, "RotOff", 0.0); |
| 551 | assert!(near(rg(&rot_off, 8, 8), (0.75, 0.975)), "scale and offset apply before the rotation: {:?}", rg(&rot_off, 8, 8)); |
| 552 | |
| 553 | let (_, masked) = eval(&mut eng, &comp, "NoTexMasked", 0.0); |
| 554 | assert_eq!(at(&masked, 4)[0], 0.0, "MultiplyByMask zeroes an unprocessed channel even without a texture"); |
| 555 | assert!((at(&masked, 4)[1] - 0.5).abs() < 0.03, "processed channels keep the image inside the mask"); |
| 556 | assert_eq!(at(&masked, 28)[1], 0.0, "outside the mask is multiplied away"); |
| 557 | } |
| 558 | |
| 559 | mod flow; |