| 1 | //! Native ports of Fuses: `SwitchElse`, `CheckerPieceGenerator`, |
| 2 | //! `AlphaWeightedNoise`, `Crystallize`, and `HexagonTiles`. |
| 3 | |
| 4 | use super::*; |
| 5 | |
| 6 | impl Engine { |
| 7 | pub(super) fn eval_switch_else( |
| 8 | &mut self, |
| 9 | comp: &Comp, |
| 10 | node: &Node, |
| 11 | time: f64, |
| 12 | enc: &mut wgpu::CommandEncoder, |
| 13 | visiting: &mut HashSet<(NodeId, i64)>, |
| 14 | stats: &mut EvalStats, |
| 15 | ) -> CachedTexture { |
| 16 | let index = |name: &str, default: f64| comp.eval_number(node, name, time, default, &self.expr).round().max(1.0) as usize; |
| 17 | let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| { |
| 18 | node.connected_node(&format!("Input{i}")).and_then(|s| comp.find_node(s)) |
| 19 | }); |
| 20 | match picked { |
| 21 | Some(id) => self.eval_node(comp, id, time, enc, visiting, stats), |
| 22 | None => self.dummy.clone(), |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | pub(super) fn eval_checker_piece( |
| 27 | &mut self, |
| 28 | comp: &Comp, |
| 29 | node: &Node, |
| 30 | time: f64, |
| 31 | frame_i: i64, |
| 32 | enc: &mut wgpu::CommandEncoder, |
| 33 | stats: &mut EvalStats, |
| 34 | ) -> CachedTexture { |
| 35 | let (full_size, _) = comp.checker_piece_metrics(node, time, &self.expr); |
| 36 | let edge = (full_size / self.proxy_scale.max(1)).max(1); |
| 37 | let flip = comp.eval_number(node, "Flip", time, 0.0, &self.expr) > 0.5; |
| 38 | let color = |suffix: &str, default: [f64; 3]| { |
| 39 | [ |
| 40 | comp.eval_number(node, &format!("R{suffix}"), time, default[0], &self.expr) as f32, |
| 41 | comp.eval_number(node, &format!("G{suffix}"), time, default[1], &self.expr) as f32, |
| 42 | comp.eval_number(node, &format!("B{suffix}"), time, default[2], &self.expr) as f32, |
| 43 | comp.eval_number(node, &format!("A{suffix}"), time, 1.0, &self.expr) as f32, |
| 44 | ] |
| 45 | }; |
| 46 | let (a, b) = (color("1", [0.0; 3]), color("2", [1.0; 3])); |
| 47 | |
| 48 | let mut u = UniformParams::default(); |
| 49 | (u.p[0], u.p[1]) = if flip { (b, a) } else { (a, b) }; |
| 50 | let depth = self.node_depth(comp, node, time, None); |
| 51 | let size = [edge, edge]; |
| 52 | let key = self.make_key(node, "CheckerPiece", size, &[depth as u64], bytemuck::cast_slice(&u.p[..2])); |
| 53 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 54 | stats.cache_hits += 1; |
| 55 | return hit; |
| 56 | } |
| 57 | stats.cache_misses += 1; |
| 58 | stats.nodes_evaluated += 1; |
| 59 | let dst = self.alloc_tex(size, depth, key); |
| 60 | self.dispatch_op(enc, ShaderOp::CheckerPiece, &self.dummy.view, &self.dummy.view, &self.dummy.view, &dst, &u); |
| 61 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 62 | dst |
| 63 | } |
| 64 | |
| 65 | pub(super) fn eval_alpha_weighted_noise( |
| 66 | &mut self, |
| 67 | comp: &Comp, |
| 68 | node: &Node, |
| 69 | time: f64, |
| 70 | frame_i: i64, |
| 71 | enc: &mut wgpu::CommandEncoder, |
| 72 | visiting: &mut HashSet<(NodeId, i64)>, |
| 73 | stats: &mut EvalStats, |
| 74 | ) -> CachedTexture { |
| 75 | let Some(src_id) = node |
| 76 | .connected_node("Image") |
| 77 | .or_else(|| node.connected_node("Input")) |
| 78 | .and_then(|s| comp.find_node(s)) |
| 79 | else { |
| 80 | return self.dummy.clone(); |
| 81 | }; |
| 82 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 83 | let mut u = UniformParams::default(); |
| 84 | u.p[0] = [ |
| 85 | comp.eval_number(node, "RandomSeed", time, 0.0, &self.expr).round().max(0.0) as f32, |
| 86 | comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32, |
| 87 | comp.eval_number(node, "Lift", time, 0.0, &self.expr) as f32, |
| 88 | 0.0, |
| 89 | ]; |
| 90 | u.p[1] = [src.origin[0] as f32, src.origin[1] as f32, 0.0, 0.0]; |
| 91 | let key = self.make_key(node, "AlphaWeightedNoise", src.size, &[src.content_hash], bytemuck::cast_slice(&u.p[..2])); |
| 92 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 93 | stats.cache_hits += 1; |
| 94 | return hit; |
| 95 | } |
| 96 | stats.cache_misses += 1; |
| 97 | stats.nodes_evaluated += 1; |
| 98 | let dst = self.alloc_tex_like(&src, src.depth, key); |
| 99 | self.dispatch_op(enc, ShaderOp::AlphaWeightedNoise, &src.view, &self.dummy.view, &self.dummy.view, &dst, &u); |
| 100 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 101 | dst |
| 102 | } |
| 103 | |
| 104 | pub(super) fn eval_crystallize( |
| 105 | &mut self, |
| 106 | comp: &Comp, |
| 107 | node: &Node, |
| 108 | time: f64, |
| 109 | frame_i: i64, |
| 110 | enc: &mut wgpu::CommandEncoder, |
| 111 | visiting: &mut HashSet<(NodeId, i64)>, |
| 112 | stats: &mut EvalStats, |
| 113 | ) -> CachedTexture { |
| 114 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 115 | return self.dummy.clone(); |
| 116 | }; |
| 117 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 118 | let num = |name: &str, default: f64| comp.eval_number(node, name, time, default, &self.expr); |
| 119 | let size = num("Size", 0.025).max(0.001); |
| 120 | let smooth = num("Smooth", 1.0) >= 0.5; |
| 121 | let width = src.canvas_size[0] as f32; |
| 122 | |
| 123 | let mut u = UniformParams::default(); |
| 124 | u.p[0] = [ |
| 125 | size as f32 * width, |
| 126 | (num("Feathering", 0.0).max(0.0) * 0.2).max(1e-4) as f32, |
| 127 | (num("Seethe", 0.0) + num("SeetheRate", 0.02) * time) as f32, |
| 128 | num("RandomSeed", 0.0) as f32, |
| 129 | ]; |
| 130 | u.p[1] = [ |
| 131 | num("Jitter", 1.0).clamp(0.0, 1.0) as f32, |
| 132 | num("Blades", 2.0).round().clamp(1.0, 3.0) as f32, |
| 133 | src.origin[0] as f32, |
| 134 | src.origin[1] as f32, |
| 135 | ]; |
| 136 | u.p[2] = [src.canvas_size[1] as f32, if smooth { 1.0 } else { 0.0 }, 0.0, 0.0]; |
| 137 | |
| 138 | let key = self.make_key(node, "Crystallize", src.size, &[src.content_hash], bytemuck::cast_slice(&u.p[..3])); |
| 139 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 140 | stats.cache_hits += 1; |
| 141 | return hit; |
| 142 | } |
| 143 | stats.cache_misses += 1; |
| 144 | stats.nodes_evaluated += 1; |
| 145 | |
| 146 | // Box about one facet wide, standing in for the facet's average. |
| 147 | let facet_src = if smooth { self.blur_separable(enc, &src, 0.35 * u.p[0][0], 0.35 * u.p[0][0], 1.0, 1.0) } else { src.clone() }; |
| 148 | |
| 149 | let dst = self.alloc_tex_like(&src, src.depth, key); |
| 150 | self.dispatch_op(enc, ShaderOp::Crystallize, &facet_src.view, &self.dummy.view, &self.dummy.view, &dst, &u); |
| 151 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 152 | dst |
| 153 | } |
| 154 | |
| 155 | #[allow(clippy::too_many_arguments)] |
| 156 | pub(super) fn eval_hexagon_tiles( |
| 157 | &mut self, |
| 158 | comp: &Comp, |
| 159 | node: &Node, |
| 160 | time: f64, |
| 161 | frame_i: i64, |
| 162 | comp_dims: [u32; 2], |
| 163 | enc: &mut wgpu::CommandEncoder, |
| 164 | visiting: &mut HashSet<(NodeId, i64)>, |
| 165 | stats: &mut EvalStats, |
| 166 | ) -> CachedTexture { |
| 167 | let use_ff = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5; |
| 168 | let w = if use_ff { |
| 169 | comp.width |
| 170 | } else { |
| 171 | comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32 |
| 172 | }; |
| 173 | let h = if use_ff { |
| 174 | comp.height |
| 175 | } else { |
| 176 | comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32 |
| 177 | }; |
| 178 | let size = if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) }; |
| 179 | let depth = self.node_depth(comp, node, time, None); |
| 180 | |
| 181 | let proxy = self.proxy_scale.max(1) as f32; |
| 182 | let hex_size = comp.eval_number(node, "Size", time, 5.0, &self.expr) as f32; |
| 183 | let border = comp.eval_number(node, "BorderSize", time, 2.0, &self.expr) as f32; |
| 184 | let xoff = comp.eval_number(node, "XOff", time, 0.0, &self.expr).round() as f32 / proxy; |
| 185 | let yoff = comp.eval_number(node, "YOff", time, 0.0, &self.expr).round() as f32 / proxy; |
| 186 | let r1 = comp.eval_number(node, "Red1", time, 0.2, &self.expr) as f32; |
| 187 | let g1 = comp.eval_number(node, "Green1", time, 0.2, &self.expr) as f32; |
| 188 | let b1 = comp.eval_number(node, "Blue1", time, 0.8, &self.expr) as f32; |
| 189 | let r2 = comp.eval_number(node, "Red2", time, 0.8, &self.expr) as f32; |
| 190 | let g2 = comp.eval_number(node, "Green2", time, 0.2, &self.expr) as f32; |
| 191 | let b2 = comp.eval_number(node, "Blue2", time, 0.2, &self.expr) as f32; |
| 192 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 193 | |
| 194 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); |
| 195 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 196 | |
| 197 | let mut u = UniformParams::default(); |
| 198 | u.p[0] = [hex_size, border, xoff, yoff]; |
| 199 | u.p[1] = [r1, g1, b1, 1.0]; |
| 200 | u.p[2] = [r2, g2, b2, 1.0]; |
| 201 | u.p[3] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0]; |
| 202 | |
| 203 | let key = self.make_key(node, "HexagonTiles", size, &[mask_hash, depth as u64], bytemuck::cast_slice(&u.p[..4])); |
| 204 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 205 | stats.cache_hits += 1; |
| 206 | return hit; |
| 207 | } |
| 208 | stats.cache_misses += 1; |
| 209 | stats.nodes_evaluated += 1; |
| 210 | let dst = self.alloc_tex(size, depth, key); |
| 211 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 212 | self.dispatch_op(enc, ShaderOp::HexagonTiles, &self.dummy.view, &self.dummy.view, mv, &dst, &u); |
| 213 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 214 | dst |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | #[cfg(test)] |
| 219 | mod tests { |
| 220 | use super::*; |
| 221 | |
| 222 | fn comp(tools: &str) -> Comp { |
| 223 | let src = format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ {tools} }} }}"); |
| 224 | Comp::from_fusion_str(&src).expect("parse comp") |
| 225 | } |
| 226 | |
| 227 | fn bg(name: &str, w: u32, inputs: &str) -> String { |
| 228 | format!("{name} = Background {{ Inputs = {{ Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {w}, }}, {inputs} }}, }},") |
| 229 | } |
| 230 | |
| 231 | /// Renders `name` and returns `(size, rgba8 rows top-down)`; `None` without a GPU adapter. |
| 232 | fn render(comp: &Comp, name: &str, time: f64) -> Option<([u32; 2], Vec<u8>)> { |
| 233 | let mut eng = Engine::new_headless().ok()?; |
| 234 | let (tex, _) = eng.evaluate(comp, comp.find_node(name).unwrap(), time); |
| 235 | Some((tex.size, eng.readback_rgba(&tex).unwrap())) |
| 236 | } |
| 237 | |
| 238 | fn px(img: &(Vec<u8>, u32), x: u32, y: u32) -> [u8; 4] { |
| 239 | let i = ((y * img.1 + x) * 4) as usize; |
| 240 | img.0[i..i + 4].try_into().unwrap() |
| 241 | } |
| 242 | |
| 243 | #[test] |
| 244 | fn switch_else_prefers_switch_input_then_else_then_dummy() { |
| 245 | let tools = [ |
| 246 | bg("Red", 16, "TopLeftRed = Input { Value = 1, },"), |
| 247 | bg("Green", 16, "TopLeftGreen = Input { Value = 1, },"), |
| 248 | r#"Both = Fuse.SwitchElse { Inputs = { |
| 249 | Input1 = Input { SourceOp = "Red", Source = "Output", }, |
| 250 | Input2 = Input { SourceOp = "Green", Source = "Output", }, |
| 251 | }, }, |
| 252 | ElseOnly = Fuse.SwitchElse { Inputs = { |
| 253 | Input2 = Input { SourceOp = "Green", Source = "Output", }, |
| 254 | }, }, |
| 255 | Swapped = Fuse.SwitchElse { Inputs = { |
| 256 | Switch = Input { Value = 2, }, |
| 257 | Else = Input { Value = 1, }, |
| 258 | Input1 = Input { SourceOp = "Red", Source = "Output", }, |
| 259 | Input2 = Input { SourceOp = "Green", Source = "Output", }, |
| 260 | }, }, |
| 261 | SwappedElse = Fuse.SwitchElse { Inputs = { |
| 262 | Switch = Input { Value = 2, }, |
| 263 | Else = Input { Value = 1, }, |
| 264 | Input1 = Input { SourceOp = "Red", Source = "Output", }, |
| 265 | }, }, |
| 266 | Dangling = Fuse.SwitchElse { Inputs = { |
| 267 | Input1 = Input { SourceOp = "Missing", Source = "Output", }, |
| 268 | Input2 = Input { SourceOp = "Green", Source = "Output", }, |
| 269 | }, }, |
| 270 | Empty = Fuse.SwitchElse { },"# |
| 271 | .to_string(), |
| 272 | ] |
| 273 | .concat(); |
| 274 | let c = comp(&tools); |
| 275 | let color = |name| render(&c, name, 0.0).map(|(size, p)| (size, [p[0], p[1], p[2]])); |
| 276 | let Some(both) = color("Both") else { return }; |
| 277 | assert_eq!(both, ([16, 16], [255, 0, 0])); |
| 278 | assert_eq!(color("ElseOnly").unwrap(), ([16, 16], [0, 255, 0])); |
| 279 | assert_eq!(color("Swapped").unwrap(), ([16, 16], [0, 255, 0])); |
| 280 | assert_eq!(color("SwappedElse").unwrap(), ([16, 16], [255, 0, 0])); |
| 281 | assert_eq!(color("Dangling").unwrap(), ([16, 16], [0, 255, 0])); |
| 282 | assert_eq!(color("Empty").unwrap().0, [1, 1]); |
| 283 | } |
| 284 | |
| 285 | #[test] |
| 286 | fn checker_piece_is_y_up_nearest_2x2_with_flip_and_colors() { |
| 287 | let c = comp( |
| 288 | r#"Plain = Fuse.CheckerPieceGenerator { Inputs = { |
| 289 | Width = Input { Value = 40, }, |
| 290 | Repeat = Input { Value = 5, }, |
| 291 | }, }, |
| 292 | Flipped = Fuse.CheckerPieceGenerator { Inputs = { |
| 293 | Width = Input { Value = 40, }, |
| 294 | Repeat = Input { Value = 5, }, |
| 295 | Flip = Input { Value = 1, }, |
| 296 | R1 = Input { Value = 1, }, G1 = Input { Value = 0, }, B1 = Input { Value = 0, }, A1 = Input { Value = 1, }, |
| 297 | R2 = Input { Value = 0, }, G2 = Input { Value = 0, }, B2 = Input { Value = 1, }, A2 = Input { Value = 0.5, }, |
| 298 | }, }, |
| 299 | Odd = Fuse.CheckerPieceGenerator { Inputs = { |
| 300 | Width = Input { Value = 100, }, |
| 301 | Repeat = Input { Value = 3, }, |
| 302 | }, }, |
| 303 | Floor = Fuse.CheckerPieceGenerator { Inputs = { |
| 304 | Width = Input { Value = 4, }, |
| 305 | Repeat = Input { Value = 10, }, |
| 306 | }, },"#, |
| 307 | ); |
| 308 | let Some((size, rgba)) = render(&c, "Plain", 0.0) else { return }; |
| 309 | // 40 / 5 = 8 px tiles; A = black bottom-left & top-right, B = white top-left & bottom-right. |
| 310 | assert_eq!(size, [8, 8]); |
| 311 | let img = (rgba, 8); |
| 312 | let [top_left, top_right, bottom_left, bottom_right] = |
| 313 | [(0, 0), (7, 0), (0, 7), (7, 7)].map(|(x, y)| px(&img, x, y)); |
| 314 | assert_eq!([top_left, bottom_right], [[255; 4]; 2]); |
| 315 | assert_eq!([top_right, bottom_left], [[0, 0, 0, 255]; 2]); |
| 316 | // Nearest-neighbor: the quadrant seams sit exactly at the midlines. |
| 317 | assert_eq!([px(&img, 3, 3), px(&img, 4, 3), px(&img, 3, 4), px(&img, 4, 4)], [top_left, top_right, bottom_left, bottom_right]); |
| 318 | |
| 319 | let (_, rgba) = render(&c, "Flipped", 0.0).unwrap(); |
| 320 | let img = (rgba, 8); |
| 321 | // Flip swaps A and B: B (blue, half alpha) now bottom-left & top-right, A (red) top-left & bottom-right. |
| 322 | assert_eq!(px(&img, 0, 0), [255, 0, 0, 255]); |
| 323 | assert_eq!(px(&img, 7, 7), [255, 0, 0, 255]); |
| 324 | assert_eq!(px(&img, 7, 0), [0, 0, 255, 128]); |
| 325 | assert_eq!(px(&img, 0, 7), [0, 0, 255, 128]); |
| 326 | |
| 327 | assert_eq!(render(&c, "Odd", 0.0).unwrap().0, [32, 32]); |
| 328 | assert_eq!(render(&c, "Floor", 0.0).unwrap().0, [2, 2]); |
| 329 | } |
| 330 | |
| 331 | #[test] |
| 332 | fn alpha_weighted_noise_thresholds_alpha_and_unpremultiplies_without_nan() { |
| 333 | let tools = [ |
| 334 | bg("Clear", 64, "TopLeftRed = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 0, },"), |
| 335 | bg("Solid", 64, "TopLeftRed = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 1, },"), |
| 336 | bg("Half", 64, "TopLeftRed = Input { Value = 0.25, }, TopLeftAlpha = Input { Value = 0.5, },"), |
| 337 | r#"ClearNoise = Fuse.AlphaWeightedNoise { Inputs = { |
| 338 | Image = Input { SourceOp = "Clear", Source = "Output", }, |
| 339 | Lift = Input { Value = 1, }, |
| 340 | }, }, |
| 341 | SolidNoise = Fuse.AlphaWeightedNoise { Inputs = { Image = Input { SourceOp = "Solid", Source = "Output", }, }, }, |
| 342 | SolidGone = Fuse.AlphaWeightedNoise { Inputs = { |
| 343 | Image = Input { SourceOp = "Solid", Source = "Output", }, |
| 344 | Gain = Input { Value = 0, }, |
| 345 | }, }, |
| 346 | HalfA = Fuse.AlphaWeightedNoise { Inputs = { Image = Input { SourceOp = "Half", Source = "Output", }, }, }, |
| 347 | HalfAgain = Fuse.AlphaWeightedNoise { Inputs = { Input = Input { SourceOp = "Half", Source = "Output", }, }, }, |
| 348 | HalfB = Fuse.AlphaWeightedNoise { Inputs = { |
| 349 | Image = Input { SourceOp = "Half", Source = "Output", }, |
| 350 | RandomSeed = Input { Value = 7, }, |
| 351 | }, }, |
| 352 | HalfBright = Fuse.AlphaWeightedNoise { Inputs = { |
| 353 | Image = Input { SourceOp = "Half", Source = "Output", }, |
| 354 | Lift = Input { Value = 0.25, }, |
| 355 | }, }, |
| 356 | NoInput = Fuse.AlphaWeightedNoise { },"# |
| 357 | .to_string(), |
| 358 | ] |
| 359 | .concat(); |
| 360 | let c = comp(&tools); |
| 361 | let Some((_, clear)) = render(&c, "ClearNoise", 0.0) else { return }; |
| 362 | assert!(clear.chunks(4).all(|p| p == [0, 0, 0, 255]), "alpha 0 -> 1 has no color to recover, so rgb is 0 rather than NaN"); |
| 363 | assert!(render(&c, "SolidNoise", 0.0).unwrap().1.chunks(4).all(|p| p == [128, 0, 0, 255])); |
| 364 | assert!(render(&c, "SolidGone", 0.0).unwrap().1.chunks(4).all(|p| p == [0, 0, 0, 0])); |
| 365 | |
| 366 | let coverage = |name| { |
| 367 | let (_, px) = render(&c, name, 0.0).unwrap(); |
| 368 | let opaque = px.chunks(4).filter(|p| p[3] == 255).count(); |
| 369 | assert!(px.chunks(4).all(|p| p == [0, 0, 0, 0] || p[3] == 255), "{name}: alpha is binary"); |
| 370 | assert!(px.chunks(4).filter(|p| p[3] == 255).all(|p| p[0] == 128), "{name}: rgb / alpha restored"); |
| 371 | opaque as f32 / 4096.0 |
| 372 | }; |
| 373 | assert!((coverage("HalfA") - 0.5).abs() < 0.05); |
| 374 | assert!((coverage("HalfBright") - 0.75).abs() < 0.05); |
| 375 | let a = render(&c, "HalfA", 0.0).unwrap().1; |
| 376 | assert_eq!(a, render(&c, "HalfA", 1.0).unwrap().1, "deterministic"); |
| 377 | assert_eq!(a, render(&c, "HalfAgain", 0.0).unwrap().1, "`Input` is the fallback main port"); |
| 378 | assert_ne!(a, render(&c, "HalfB", 0.0).unwrap().1, "seed changes the pattern"); |
| 379 | assert_eq!(render(&c, "NoInput", 0.0).unwrap().0, [1, 1]); |
| 380 | } |
| 381 | |
| 382 | fn crystallize_comp(input: &str, crystal: &str) -> Comp { |
| 383 | comp(&format!( |
| 384 | r#"{} Crystal = Fuse.Crystallize {{ Inputs = {{ |
| 385 | Input = Input {{ SourceOp = "Src", Source = "Output", }}, |
| 386 | Size = Input {{ Value = 0.125, }}, |
| 387 | Smooth = Input {{ Value = 0, }}, |
| 388 | Feathering = Input {{ Value = 0, }}, |
| 389 | Jitter = Input {{ Value = 0, }}, |
| 390 | Blades = Input {{ Value = 1, }}, |
| 391 | {crystal} |
| 392 | }}, }},"#, |
| 393 | bg("Src", 64, input) |
| 394 | )) |
| 395 | } |
| 396 | |
| 397 | const H_RAMP: &str = "Type = Input { Value = \"Horizontal\", }, TopRightRed = Input { Value = 1, }, TopRightAlpha = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, },"; |
| 398 | const V_RAMP: &str = "Type = Input { Value = \"Vertical\", }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, BottomLeftAlpha = Input { Value = 1, },"; |
| 399 | |
| 400 | #[test] |
| 401 | fn crystallize_samples_facet_homes_in_fusion_y_up_pixels() { |
| 402 | // 8 px cells, jitter 0: every pixel takes the ramp value at the center of a nearby cell. |
| 403 | for (ramp, horizontal) in [(H_RAMP, true), (V_RAMP, false)] { |
| 404 | let c = crystallize_comp(ramp, ""); |
| 405 | let Some((size, rgba)) = render(&c, "Crystal", 0.0) else { return }; |
| 406 | assert_eq!(size, [64, 64]); |
| 407 | let img = (rgba, 64); |
| 408 | let mut input = std::collections::HashSet::new(); |
| 409 | for y in 12..52 { |
| 410 | for x in 12..52 { |
| 411 | let r = f32::from(px(&img, x, y)[0]) / 255.0; |
| 412 | // Fusion y is up: the vertical ramp is 1 at the top row. |
| 413 | let ramp_at = if horizontal { (x as f32 + 0.5) / 64.0 } else { 1.0 - (y as f32 + 0.5) / 64.0 }; |
| 414 | assert!((r - ramp_at).abs() < 0.2, "({x},{y}) {r} vs {ramp_at}"); |
| 415 | let cell_center = r * 8.0 - 0.5; |
| 416 | assert!((cell_center - cell_center.round()).abs() < 0.05, "({x},{y}) {r} is not a cell center"); |
| 417 | input.insert((r * 255.0).round() as u8); |
| 418 | } |
| 419 | } |
| 420 | assert!(input.len() > 3 && input.len() <= 8, "{} distinct facets", input.len()); |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | #[test] |
| 425 | fn crystallize_seed_seethe_and_blades_change_the_facets() { |
| 426 | let render_with = |extra: &str, time: f64| { |
| 427 | let c = crystallize_comp(H_RAMP, &format!("Jitter = Input {{ Value = 1, }}, SeetheRate = Input {{ Value = 0, }}, {extra}")); |
| 428 | render(&c, "Crystal", time).map(|r| r.1) |
| 429 | }; |
| 430 | let Some(base) = render_with("", 0.0) else { return }; |
| 431 | assert_eq!(base, render_with("", 5.0).unwrap(), "SeetheRate 0 ignores time"); |
| 432 | assert_ne!(base, render_with("RandomSeed = Input { Value = 3, },", 0.0).unwrap()); |
| 433 | assert_ne!(base, render_with("Seethe = Input { Value = 0.3, },", 0.0).unwrap()); |
| 434 | assert_ne!(base, render_with("Blades = Input { Value = 3, },", 0.0).unwrap()); |
| 435 | |
| 436 | let c = crystallize_comp(H_RAMP, "SeetheRate = Input { Value = 0.1, },"); |
| 437 | assert_ne!(render(&c, "Crystal", 0.0).unwrap().1, render(&c, "Crystal", 5.0).unwrap().1, "phase = seethe + rate * time"); |
| 438 | } |
| 439 | |
| 440 | #[test] |
| 441 | fn crystallize_feathering_blends_neighbouring_facets_and_smooth_averages_the_source() { |
| 442 | let c = crystallize_comp(H_RAMP, ""); |
| 443 | let hard = render(&c, "Crystal", 0.0).unwrap().1; |
| 444 | let c = crystallize_comp(H_RAMP, "Feathering = Input { Value = 1, },"); |
| 445 | let feathered = render(&c, "Crystal", 0.0).unwrap().1; |
| 446 | let distinct = |p: &[u8]| p.chunks(4).map(|p| p[0]).collect::<std::collections::HashSet<_>>().len(); |
| 447 | assert!(distinct(&feathered) > distinct(&hard) * 2, "feathering mixes facet colors"); |
| 448 | |
| 449 | // Per-pixel alpha noise: facets sampling one texel stay binary-ish, Smooth averages a facet's worth. |
| 450 | let noisy = |smooth| { |
| 451 | comp(&format!( |
| 452 | r#"{} |
| 453 | Noise = Fuse.AlphaWeightedNoise {{ Inputs = {{ Image = Input {{ SourceOp = "Half", Source = "Output", }}, }}, }}, |
| 454 | Crystal = Fuse.Crystallize {{ Inputs = {{ |
| 455 | Input = Input {{ SourceOp = "Noise", Source = "Output", }}, |
| 456 | Size = Input {{ Value = 0.125, }}, |
| 457 | Smooth = Input {{ Value = {smooth}, }}, |
| 458 | }}, }},"#, |
| 459 | bg("Half", 64, "TopLeftAlpha = Input { Value = 0.5, },") |
| 460 | )) |
| 461 | }; |
| 462 | let spread = |smooth| { |
| 463 | let a: Vec<f32> = render(&noisy(smooth), "Crystal", 0.0).unwrap().1.chunks(4).map(|p| f32::from(p[3]) / 255.0).collect(); |
| 464 | let mean = a.iter().sum::<f32>() / a.len() as f32; |
| 465 | a.iter().map(|v| (v - mean).powi(2)).sum::<f32>() / a.len() as f32 |
| 466 | }; |
| 467 | assert!(spread(1) * 3.0 < spread(0), "smooth {} vs raw {}", spread(1), spread(0)); |
| 468 | } |
| 469 | |
| 470 | #[test] |
| 471 | fn crystallize_preserves_flat_images_and_requires_an_input() { |
| 472 | let c = comp(&format!( |
| 473 | r#"{} Crystal = Fuse.Crystallize {{ Inputs = {{ Input = Input {{ SourceOp = "Src", Source = "Output", }}, }}, }}, Bare = Fuse.Crystallize {{ }},"#, |
| 474 | bg("Src", 32, "TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.25, }, TopLeftAlpha = Input { Value = 1, },") |
| 475 | )); |
| 476 | let Some((size, rgba)) = render(&c, "Crystal", 2.0) else { return }; |
| 477 | assert_eq!(size, [32, 32]); |
| 478 | assert!(rgba.chunks(4).all(|p| p == [128, 64, 0, 255]), "default Smooth/Feathering keep a flat field flat"); |
| 479 | assert_eq!(render(&c, "Bare", 0.0).unwrap().0, [1, 1]); |
| 480 | } |
| 481 | |
| 482 | #[allow(clippy::too_many_arguments)] |
| 483 | fn hexagon_tiles_f64_eval( |
| 484 | w: u32, |
| 485 | h: u32, |
| 486 | col: u32, |
| 487 | row: u32, |
| 488 | size: f64, |
| 489 | border: f64, |
| 490 | xoff: f64, |
| 491 | yoff: f64, |
| 492 | c1: [f64; 3], |
| 493 | c2: [f64; 3], |
| 494 | ) -> ([u8; 4], f64) { |
| 495 | let lua_mod = |a: f64, b: f64| a - (a / b).floor() * b; |
| 496 | let to_u8 = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8; |
| 497 | let fw = f64::from(w); |
| 498 | let fh = f64::from(h); |
| 499 | let img_aspect = fw / fh; |
| 500 | // readback_rgba is top-down; Fusion Image:SetPixel y=0 is bottom row. |
| 501 | let x = f64::from(col); |
| 502 | let y = f64::from(h - 1 - row); |
| 503 | let ix0 = ((x + xoff) / fw * size) * 0.57735 * 2.0; |
| 504 | let iy0 = (((y / img_aspect) + yoff) / fh * size) + (lua_mod(ix0.floor(), 2.0) * 0.5); |
| 505 | let ix = (lua_mod(ix0, 1.0) - 0.5).abs(); |
| 506 | let iy = (lua_mod(iy0, 1.0) - 0.5).abs(); |
| 507 | let h_val = ((ix * 1.5 + iy).max(iy * 2.0) - 1.0).abs(); |
| 508 | let rgb = if h_val > 0.05 * border { c1 } else { c2 }; |
| 509 | ([to_u8(rgb[0]), to_u8(rgb[1]), to_u8(rgb[2]), 255], h_val) |
| 510 | } |
| 511 | |
| 512 | #[allow(clippy::too_many_arguments)] |
| 513 | fn hexagon_tiles_f64_ref( |
| 514 | w: u32, |
| 515 | h: u32, |
| 516 | size: f64, |
| 517 | border: f64, |
| 518 | xoff: f64, |
| 519 | yoff: f64, |
| 520 | c1: [f64; 3], |
| 521 | c2: [f64; 3], |
| 522 | ) -> Vec<u8> { |
| 523 | let mut out = vec![0u8; (w * h * 4) as usize]; |
| 524 | for row in 0..h { |
| 525 | for col in 0..w { |
| 526 | let (px, _) = hexagon_tiles_f64_eval(w, h, col, row, size, border, xoff, yoff, c1, c2); |
| 527 | let idx = ((row * w + col) * 4) as usize; |
| 528 | out[idx..idx + 4].copy_from_slice(&px); |
| 529 | } |
| 530 | } |
| 531 | out |
| 532 | } |
| 533 | |
| 534 | #[test] |
| 535 | fn hexagon_tiles_matches_f64_reference_for_defaults_and_negative_offsets() { |
| 536 | let c = comp( |
| 537 | r#"DefaultHex = Fuse.HexagonTiles { Inputs = { |
| 538 | Width = Input { Value = 128, }, |
| 539 | Height = Input { Value = 96, }, |
| 540 | }, }, |
| 541 | CrazyHex = Fuse.HexagonTiles { Inputs = { |
| 542 | Width = Input { Value = 192, }, |
| 543 | Height = Input { Value = 108, }, |
| 544 | Size = Input { Value = 16.56, }, |
| 545 | BorderSize = Input { Value = 2.0, }, |
| 546 | XOff = Input { Value = -148, }, |
| 547 | YOff = Input { Value = -37, }, |
| 548 | Red1 = Input { Value = 0, }, |
| 549 | Green1 = Input { Value = 0.495, }, |
| 550 | Blue1 = Input { Value = 0.8, }, |
| 551 | Red2 = Input { Value = 0, }, |
| 552 | Green2 = Input { Value = 0.2, }, |
| 553 | Blue2 = Input { Value = 0.2, }, |
| 554 | }, }, |
| 555 | MaskedHex = Fuse.HexagonTiles { Inputs = { |
| 556 | Width = Input { Value = 64, }, |
| 557 | Height = Input { Value = 64, }, |
| 558 | Blend = Input { Value = 0.5, }, |
| 559 | }, },"#, |
| 560 | ); |
| 561 | |
| 562 | let Some((def_size, def_px)) = render(&c, "DefaultHex", 0.0) else { return }; |
| 563 | assert_eq!(def_size, [128, 96]); |
| 564 | let def_ref = hexagon_tiles_f64_ref(128, 96, 5.0, 2.0, 0.0, 0.0, [0.2, 0.2, 0.8], [0.8, 0.2, 0.2]); |
| 565 | assert_eq!(def_px, def_ref, "DefaultHex must match f64 reference pixel-for-pixel"); |
| 566 | |
| 567 | let (crazy_size, crazy_px) = render(&c, "CrazyHex", 0.0).unwrap(); |
| 568 | assert_eq!(crazy_size, [192, 108]); |
| 569 | let crazy_ref = hexagon_tiles_f64_ref(192, 108, 16.56, 2.0, -148.0, -37.0, [0.0, 0.495, 0.8], [0.0, 0.2, 0.2]); |
| 570 | assert_eq!(crazy_px, crazy_ref, "CrazyHex with negative XOff/YOff must match f64 reference pixel-for-pixel"); |
| 571 | |
| 572 | let (mask_size, mask_px) = render(&c, "MaskedHex", 0.0).unwrap(); |
| 573 | assert_eq!(mask_size, [64, 64]); |
| 574 | assert!(mask_px.chunks(4).all(|p| p[3] == 128), "Blend=0.5 scales alpha to 0.5"); |
| 575 | } |
| 576 | |
| 577 | #[test] |
| 578 | fn hexagon_tiles_proxy_scale_scales_xoff_and_yoff_to_match_downsampled_full_res() { |
| 579 | let c = comp( |
| 580 | r#"OffsetHex = Fuse.HexagonTiles { Inputs = { |
| 581 | Width = Input { Value = 192, }, |
| 582 | Height = Input { Value = 108, }, |
| 583 | Size = Input { Value = 16.56, }, |
| 584 | BorderSize = Input { Value = 2.0, }, |
| 585 | XOff = Input { Value = -148, }, |
| 586 | YOff = Input { Value = -37, }, |
| 587 | Red1 = Input { Value = 0, }, |
| 588 | Green1 = Input { Value = 0.495, }, |
| 589 | Blue1 = Input { Value = 0.8, }, |
| 590 | Red2 = Input { Value = 0, }, |
| 591 | Green2 = Input { Value = 0.2, }, |
| 592 | Blue2 = Input { Value = 0.2, }, |
| 593 | }, },"#, |
| 594 | ); |
| 595 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 596 | let id = c.find_node("OffsetHex").unwrap(); |
| 597 | |
| 598 | eng.proxy_scale = 1; |
| 599 | let (full_tex, _) = eng.evaluate(&c, id, 0.0); |
| 600 | assert_eq!(full_tex.size, [192, 108]); |
| 601 | let full_px = eng.readback_rgba(&full_tex).unwrap(); |
| 602 | |
| 603 | eng.proxy_scale = 2; |
| 604 | let (half_tex, _) = eng.evaluate(&c, id, 0.0); |
| 605 | assert_eq!(half_tex.size, [96, 54]); |
| 606 | let half_px = eng.readback_rgba(&half_tex).unwrap(); |
| 607 | |
| 608 | // Fusion Y-up coordinate fy_half = (54 - 1 - row) maps to fy_full = 2 * fy_half, |
| 609 | // which in top-down rows is row_full = 108 - 1 - 2*(53 - row) = 2*row + 1, col_full = 2*col. |
| 610 | let mut diffs = 0usize; |
| 611 | for row in 0..54u32 { |
| 612 | for col in 0..96u32 { |
| 613 | let h_idx = ((row * 96 + col) * 4) as usize; |
| 614 | let f_idx = (((row * 2 + 1) * 192 + col * 2) * 4) as usize; |
| 615 | if half_px[h_idx..h_idx + 4] != full_px[f_idx..f_idx + 4] { |
| 616 | diffs += 1; |
| 617 | } |
| 618 | } |
| 619 | } |
| 620 | assert!(diffs <= 2, "HexagonTiles proxy_scale=2 diverged from downsampled full-res: {diffs} diffs"); |
| 621 | } |
| 622 | |
| 623 | #[test] |
| 624 | fn hexagon_tiles_in_30_ground_is_crazy005_evaluates_with_no_unsupported_nodes() { |
| 625 | let path = std::path::Path::new("/Volumes/Project/trees/fusion/30_ground_is_crazy005.comp"); |
| 626 | if !path.exists() { |
| 627 | return; |
| 628 | } |
| 629 | let comp = Comp::from_fusion_file(path).expect("load 30_ground_is_crazy005.comp"); |
| 630 | let hex_id = comp.find_node("HexagonTiles1").expect("HexagonTiles1 node"); |
| 631 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 632 | let (tex, stats) = eng.evaluate(&comp, hex_id, 3107.0); |
| 633 | assert!(stats.unsupported_nodes.is_empty(), "unexpected unsupported_nodes: {:?}", stats.unsupported_nodes); |
| 634 | assert_eq!(tex.size, [1920, 1080]); |
| 635 | let gpu_px = eng.readback_rgba(&tex).unwrap(); |
| 636 | let hex_node = comp.node(hex_id); |
| 637 | let c1 = [ |
| 638 | comp.eval_number(hex_node, "Red1", 3107.0, 0.2, &eng.expr), |
| 639 | comp.eval_number(hex_node, "Green1", 3107.0, 0.2, &eng.expr), |
| 640 | comp.eval_number(hex_node, "Blue1", 3107.0, 0.8, &eng.expr), |
| 641 | ]; |
| 642 | let c2 = [ |
| 643 | comp.eval_number(hex_node, "Red2", 3107.0, 0.8, &eng.expr), |
| 644 | comp.eval_number(hex_node, "Green2", 3107.0, 0.2, &eng.expr), |
| 645 | comp.eval_number(hex_node, "Blue2", 3107.0, 0.2, &eng.expr), |
| 646 | ]; |
| 647 | let mut diffs = 0usize; |
| 648 | for row in 0..1080u32 { |
| 649 | for col in 0..1920u32 { |
| 650 | let idx = ((row * 1920 + col) * 4) as usize; |
| 651 | let g = &gpu_px[idx..idx + 4]; |
| 652 | let (r, h_val) = hexagon_tiles_f64_eval(1920, 1080, col, row, 16.56, 2.0, -148.0, 0.0, c1, c2); |
| 653 | if g != r { |
| 654 | assert!((h_val - 0.1).abs() < 1e-6, "non-boundary mismatch at ({col}, {row}): h={h_val}, gpu={g:?}, ref={r:?}"); |
| 655 | diffs += 1; |
| 656 | } |
| 657 | } |
| 658 | } |
| 659 | assert!(diffs <= 4, "expected at most 4 f32-ULP boundary diffs across 1920x1080, got {diffs}"); |
| 660 | } |
| 661 | } |