| author | |
| committer | |
| log | 902a25b57d4aea1e07151c56306ba0d97db5a278 |
| tree | c2ddbf33196e0cb59e1414cdc27116ae230cd048 |
| parent | 74b962d8ecff3ea6c8c007a1046ebac4f71a7bbc |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
Assisted-by: claude-sonnet-5.59 files changed, 1033 insertions(+), 285 deletions(-)
crates/engine/src/eval/deep_flow/deep_pixel.rs+25-69| ... | @@ -2,8 +2,6 @@ | ... | @@ -2,8 +2,6 @@ |
| 2 | 2 | ||
| 3 | use super::*; | 3 | use super::*; |
| 4 | 4 | ||
| 5 | const LIGHT_TYPES: [&str; 3] = ["Directional", "Point", "Spot"]; | ||
| 6 | |||
| 7 | impl Engine { | 5 | impl Engine { |
| 8 | /// `SSAO`: hemisphere multi-tap ambient occlusion from `aux.z` and `aux.normal` (normals are | 6 | /// `SSAO`: hemisphere multi-tap ambient occlusion from `aux.z` and `aux.normal` (normals are |
| 9 | /// derived from depth when absent). `Mode = Composite` darkens the image, `AO Only` outputs the occlusion term. | 7 | /// derived from depth when absent). `Mode = Composite` darkens the image, `AO Only` outputs the occlusion term. |
| ... | @@ -59,8 +57,10 @@ impl Engine { | ... | @@ -59,8 +57,10 @@ impl Engine { |
| 59 | self.df_run(node, frame_i, pass, &fin, &u, aux, enc, stats) | 57 | self.df_run(node, frame_i, pass, &fin, &u, aux, enc, stats) |
| 60 | } | 58 | } |
| 61 | 59 | ||
| 62 | /// `Shader`: deep-pixel relighting from `aux.normal` (or normals derived from `aux.z` / luminance) | 60 | /// `Shader`: relights from `aux.normal` with a directional light (`EquatorAngle` / `PolarHeight`): |
| 63 | /// with Directional / Point / Spot lights, Blinn-Phong specular and an optional equirectangular reflection map. | 61 | /// `Ambient` + `Diffuse` Lambert, `Specular` highlight tinted by `SpecularRed/Green/Blue`, and |
| 62 | /// `Reflection` of `EnvironmentReflectionMap` (`ReflectionType` = Screen / Spherical / Refraction). | ||
| 63 | /// Without normals only `Ambient` remains. | ||
| 64 | #[allow(clippy::too_many_arguments)] | 64 | #[allow(clippy::too_many_arguments)] |
| 65 | pub(in crate::eval) fn eval_deep_shader( | 65 | pub(in crate::eval) fn eval_deep_shader( |
| 66 | &mut self, | 66 | &mut self, |
| ... | @@ -79,69 +79,23 @@ impl Engine { | ... | @@ -79,69 +79,23 @@ impl Engine { |
| 79 | if blend.0 <= 1e-6 && !blend.1 { | 79 | if blend.0 <= 1e-6 && !blend.1 { |
| 80 | return src; | 80 | return src; |
| 81 | } | 81 | } |
| 82 | let map = self.df_input( | 82 | let map = self.df_input(comp, node, &["EnvironmentReflectionMap"], time, enc, visiting, stats); |
| 83 | comp, | ||
| 84 | node, | ||
| 85 | &["EquirectangularMap", "ReflImage", "ReflectionImage"], | ||
| 86 | time, | ||
| 87 | enc, | ||
| 88 | visiting, | ||
| 89 | stats, | ||
| 90 | ); | ||
| 91 | let aux = src.aux.clone(); | 83 | let aux = src.aux.clone(); |
| 92 | let z = aux.as_ref().and_then(|a| a.z.as_ref()).map(|z| z.view.clone()); | ||
| 93 | let normal = aux.as_ref().and_then(|a| a.normal.as_ref()).map(|n| n.view.clone()); | 84 | let normal = aux.as_ref().and_then(|a| a.normal.as_ref()).map(|n| n.view.clone()); |
| 94 | let fin = self.df_fin(comp, node, time, blend, src.size, enc, visiting, stats); | 85 | let fin = self.df_fin(comp, node, time, blend, src.size, enc, visiting, stats); |
| 95 | 86 | ||
| 96 | let n = |keys: &[&str], d: f64| num_any(comp, node, keys, time, d, &self.expr) as f32; | 87 | let n = |key: &str, d: f64| num_any(comp, node, &[key], time, d, &self.expr) as f32; |
| 97 | let (w, h) = (src.size[0] as f32, src.size[1] as f32); | 88 | let (equator, polar) = (n("EquatorAngle", 45.0).to_radians(), n("PolarHeight", 45.0).to_radians()); |
| 98 | let light_type = enum_idx(comp, node, "LightType", &LIGHT_TYPES, time, 0, &self.expr); | ||
| 99 | // Light placement in y-up pixel space, +Z toward the viewer. | ||
| 100 | let pt = |key: &str| comp.eval_point(node, key, time, [0.5, 0.5], &self.expr); | ||
| 101 | let pos = { | ||
| 102 | let p = pt("LightPosition"); | ||
| 103 | [p[0] as f32 * w, p[1] as f32 * h, n(&["LightHeight"], 0.5) * w] | ||
| 104 | }; | ||
| 105 | let to_light = if light_type == 0 { | ||
| 106 | let (az, el) = (n(&["Angle"], 0.0).to_radians(), n(&["Elevation"], 90.0).to_radians()); | ||
| 107 | [el.cos() * az.cos(), el.cos() * az.sin(), el.sin()] | ||
| 108 | } else { | ||
| 109 | pos | ||
| 110 | }; | ||
| 111 | let axis = { | ||
| 112 | let t = pt("SpotTarget"); | ||
| 113 | let d = [t[0] as f32 * w - pos[0], t[1] as f32 * h - pos[1], -pos[2]]; | ||
| 114 | let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6); | ||
| 115 | [d[0] / len, d[1] / len, d[2] / len] | ||
| 116 | }; | ||
| 117 | |||
| 118 | let mut u = UniformParams::default(); | 89 | let mut u = UniformParams::default(); |
| 119 | u.p[0] = [ | 90 | u.p[0] = [n("Ambient", 0.25), n("Diffuse", 1.0), n("Specular", 1.0), n("Reflection", 1.0)]; |
| 120 | light_type as f32, | 91 | u.p[1] = [b2f(map.is_some()), b2f(normal.is_some()), n("ReflectionType", 0.0).round(), 0.0]; |
| 121 | n(&["Ambient"], 0.2).max(0.0), | 92 | u.p[2] = [polar.cos() * equator.cos(), polar.cos() * equator.sin(), polar.sin(), 0.0]; |
| 122 | n(&["Diffuse"], 0.8).max(0.0), | 93 | u.p[3] = [n("SpecularRed", 1.0), n("SpecularGreen", 1.0), n("SpecularBlue", 1.0), 0.0]; |
| 123 | n(&["Specular"], 0.0).max(0.0), | ||
| 124 | ]; | ||
| 125 | u.p[1] = [ | ||
| 126 | n(&["SpecularExponent"], 32.0).max(1.0), | ||
| 127 | n(&["Reflectivity"], 1.0).max(0.0), | ||
| 128 | b2f(map.is_some()), | ||
| 129 | b2f(normal.is_some()), | ||
| 130 | ]; | ||
| 131 | u.p[2] = [to_light[0], to_light[1], to_light[2], 0.0]; | ||
| 132 | u.p[3] = [axis[0], axis[1], axis[2], n(&["ConeAngle"], 30.0).clamp(1.0, 179.0).to_radians().cos()]; | ||
| 133 | u.p[4] = [ | ||
| 134 | n(&["LightColorRed"], 1.0), | ||
| 135 | n(&["LightColorGreen"], 1.0), | ||
| 136 | n(&["LightColorBlue"], 1.0), | ||
| 137 | n(&["SpotSoftness"], 0.1).max(0.0), | ||
| 138 | ]; | ||
| 139 | u.p[5] = [n(&["ZScale"], 1.0), n(&["BumpHeight"], 10.0), b2f(z.is_some()), 0.0]; | ||
| 140 | 94 | ||
| 141 | let pass = DfPass { | 95 | let pass = DfPass { |
| 142 | tag: "Shader", | 96 | tag: "Shader", |
| 143 | op: DeepFlowOp::Relight, | 97 | op: DeepFlowOp::Relight, |
| 144 | srcs: [Some(&src.view), z.as_deref(), normal.as_deref(), map.as_ref().map(|m| &*m.view)], | 98 | srcs: [Some(&src.view), None, normal.as_deref(), map.as_ref().map(|m| &*m.view)], |
| 145 | hashes: &[src.content_hash, map.as_ref().map_or(0, |m| m.content_hash)], | 99 | hashes: &[src.content_hash, map.as_ref().map_or(0, |m| m.content_hash)], |
| 146 | size: src.size, | 100 | size: src.size, |
| 147 | depth: self.node_depth(comp, node, time, Some(src.depth)), | 101 | depth: self.node_depth(comp, node, time, Some(src.depth)), |
| ... | @@ -149,8 +103,9 @@ impl Engine { | ... | @@ -149,8 +103,9 @@ impl Engine { |
| 149 | self.df_run(node, frame_i, pass, &fin, &u, aux, enc, stats) | 103 | self.df_run(node, frame_i, pass, &fin, &u, aux, enc, stats) |
| 150 | } | 104 | } |
| 151 | 105 | ||
| 152 | /// `Texture`: samples a `Texture` / `TextureImage` through the UV channels (RG) of `Input`, | 106 | /// `Texture`: samples `Texture` through the UV channels (RG) of `Input`: swap, `UScale` / `VScale` / |
| 153 | /// with `UScale` / `VScale` / `UOffset` / `VOffset`; `Input` alpha is the coverage. | 107 | /// `UOffset` / `VOffset`, `Rotate90`, then flips; `Input` alpha is the coverage. Without a `Texture` input |
| 108 | /// the image passes through (Blend, EffectMask and Process* still apply). | ||
| 154 | #[allow(clippy::too_many_arguments)] | 109 | #[allow(clippy::too_many_arguments)] |
| 155 | pub(in crate::eval) fn eval_texture_tool( | 110 | pub(in crate::eval) fn eval_texture_tool( |
| 156 | &mut self, | 111 | &mut self, |
| ... | @@ -166,26 +121,27 @@ impl Engine { | ... | @@ -166,26 +121,27 @@ impl Engine { |
| 166 | return self.dummy.clone(); | 121 | return self.dummy.clone(); |
| 167 | }; | 122 | }; |
| 168 | let blend = self.df_blend(comp, node, time); | 123 | let blend = self.df_blend(comp, node, time); |
| 169 | let Some(tex) = self.df_input(comp, node, &["Texture", "TextureImage"], time, enc, visiting, stats) else { | ||
| 170 | return src; | ||
| 171 | }; | ||
| 172 | if blend.0 <= 1e-6 && !blend.1 { | 124 | if blend.0 <= 1e-6 && !blend.1 { |
| 173 | return src; | 125 | return src; |
| 174 | } | 126 | } |
| 127 | let tex = self.df_input(comp, node, &["Texture", "TextureImage"], time, enc, visiting, stats); | ||
| 175 | let fin = self.df_fin(comp, node, time, blend, src.size, enc, visiting, stats); | 128 | let fin = self.df_fin(comp, node, time, blend, src.size, enc, visiting, stats); |
| 176 | 129 | ||
| 177 | let n = |keys: &[&str], d: f64| num_any(comp, node, keys, time, d, &self.expr) as f32; | 130 | let n = |key: &str, d: f64| num_any(comp, node, &[key], time, d, &self.expr) as f32; |
| 131 | let flag = |key: &str| b2f(n(key, 0.0) > 0.5); | ||
| 178 | let mut u = UniformParams::default(); | 132 | let mut u = UniformParams::default(); |
| 179 | u.p[0] = [n(&["UScale"], 1.0), n(&["VScale"], 1.0), n(&["UOffset"], 0.0), n(&["VOffset"], 0.0)]; | 133 | u.p[0] = [n("UScale", 1.0), n("VScale", 1.0), n("UOffset", 0.0), n("VOffset", 0.0)]; |
| 180 | u.p[1][0] = enum_idx(comp, node, "Edges", &EDGES, time, 2, &self.expr) as f32; | 134 | let edges = enum_idx(comp, node, "Edges", &EDGES, time, 2, &self.expr) as f32; |
| 135 | u.p[1] = [edges, b2f(tex.is_some()), flag("SwapUV0"), flag("Rotate90")]; | ||
| 136 | u.p[2] = [flag("FlipHoriz"), flag("FlipVert"), 0.0, 0.0]; | ||
| 181 | 137 | ||
| 182 | let pass = DfPass { | 138 | let pass = DfPass { |
| 183 | tag: "Texture", | 139 | tag: "Texture", |
| 184 | op: DeepFlowOp::Texture, | 140 | op: DeepFlowOp::Texture, |
| 185 | srcs: [Some(&src.view), Some(&tex.view), None, None], | 141 | srcs: [Some(&src.view), tex.as_ref().map(|t| &*t.view), None, None], |
| 186 | hashes: &[src.content_hash, tex.content_hash], | 142 | hashes: &[src.content_hash, tex.as_ref().map_or(0, |t| t.content_hash)], |
| 187 | size: src.size, | 143 | size: src.size, |
| 188 | depth: self.node_depth(comp, node, time, Some(src.depth.max(tex.depth))), | 144 | depth: self.node_depth(comp, node, time, Some(tex.as_ref().map_or(src.depth, |t| src.depth.max(t.depth)))), |
| 189 | }; | 145 | }; |
| 190 | self.df_run(node, frame_i, pass, &fin, &u, src.aux.clone(), enc, stats) | 146 | self.df_run(node, frame_i, pass, &fin, &u, src.aux.clone(), enc, stats) |
| 191 | } | 147 | } |
crates/engine/src/eval/deep_flow/flow.rs+19-40| ... | @@ -310,9 +310,9 @@ impl Engine { | ... | @@ -310,9 +310,9 @@ impl Engine { |
| 310 | self.df_with_aux(node, frame_i, key, src, aux) | 310 | self.df_with_aux(node, frame_i, key, src, aux) |
| 311 | } | 311 | } |
| 312 | 312 | ||
| 313 | /// `VectorTransform`: flips, inverts, normalizes, scales (`XScale`/`YScale`), rotates (`Angle`) and offsets | 313 | /// `VectorTransform`: scales (`XSize` / `YSize`, or `Size` and `Aspect` with `UseSizeAndAspect`), rotates |
| 314 | /// (`XOffset`/`YOffset`) motion vectors. `Channel` = `Vector` / `BackVector` / `Color` (RG) selects one | 314 | /// (`Angle`) and `SmoothVector`-blurs the `aux.vector` / `aux.back_vector` motion vectors, mixed in by |
| 315 | /// source; the default (`Auto`) transforms every present aux vector, falling back to RG of the image. | 315 | /// `AttenuateVect`. Colour and alpha are untouched; an image without vectors passes through. |
| 316 | #[allow(clippy::too_many_arguments)] | 316 | #[allow(clippy::too_many_arguments)] |
| 317 | pub(in crate::eval) fn eval_vector_transform( | 317 | pub(in crate::eval) fn eval_vector_transform( |
| 318 | &mut self, | 318 | &mut self, |
| ... | @@ -327,56 +327,35 @@ impl Engine { | ... | @@ -327,56 +327,35 @@ impl Engine { |
| 327 | let Some(src) = self.df_input(comp, node, &INPUT_PORTS, time, enc, visiting, stats) else { | 327 | let Some(src) = self.df_input(comp, node, &INPUT_PORTS, time, enc, visiting, stats) else { |
| 328 | return self.dummy.clone(); | 328 | return self.dummy.clone(); |
| 329 | }; | 329 | }; |
| 330 | let blend = self.df_blend(comp, node, time); | 330 | if !src.aux.as_ref().is_some_and(|a| a.vector.is_some() || a.back_vector.is_some()) { |
| 331 | if blend.0 <= 1e-6 && !blend.1 { | ||
| 332 | return src; | ||
| 333 | } | ||
| 334 | let channel = enum_idx(comp, node, "Channel", &["Auto", "Vector", "BackVector", "Color"], time, 0, &self.expr); | ||
| 335 | let aux = src.aux.clone(); | ||
| 336 | let vector = aux.as_ref().and_then(|a| a.vector.clone()).filter(|_| matches!(channel, 0 | 1)); | ||
| 337 | let back = aux.as_ref().and_then(|a| a.back_vector.clone()).filter(|_| matches!(channel, 0 | 2)); | ||
| 338 | let use_color = channel == 3 || (channel == 0 && vector.is_none() && back.is_none()); | ||
| 339 | if vector.is_none() && back.is_none() && !use_color { | ||
| 340 | return src; | 331 | return src; |
| 341 | } | 332 | } |
| 342 | 333 | ||
| 343 | let n = |keys: &[&str], d: f64| num_any(comp, node, keys, time, d, &self.expr) as f32; | 334 | let n = |key: &str, d: f64| num_any(comp, node, &[key], time, d, &self.expr) as f32; |
| 344 | let flag = |key: &str| b2f(num_any(comp, node, &[key], time, 0.0, &self.expr) > 0.5); | 335 | let (x_size, y_size) = if n("UseSizeAndAspect", 0.0) > 0.5 { |
| 345 | let angle = n(&["Angle"], 0.0).to_radians(); | 336 | (n("Size", 1.0), n("Size", 1.0) * n("Aspect", 1.0)) |
| 337 | } else { | ||
| 338 | (n("XSize", 1.0), n("YSize", 1.0)) | ||
| 339 | }; | ||
| 340 | let angle = n("Angle", 0.0).to_radians(); | ||
| 346 | let mut u = UniformParams::default(); | 341 | let mut u = UniformParams::default(); |
| 347 | u.p[0] = [n(&["XScale"], 1.0), n(&["YScale"], 1.0), angle.cos(), angle.sin()]; | 342 | u.p[0] = [x_size, y_size, angle.cos(), angle.sin()]; |
| 348 | u.p[1] = [n(&["XOffset"], 0.0), n(&["YOffset"], 0.0), flag("FlipX"), flag("FlipY")]; | 343 | u.p[1] = [n("AttenuateVect", 1.0).clamp(0.0, 1.0), n("SmoothVector", 0.0).max(0.0), 0.0, 0.0]; |
| 349 | u.p[2] = [flag("Invert"), flag("Normalize"), 0.0, 0.0]; | ||
| 350 | let fin = self.df_fin(comp, node, time, blend, src.size, enc, visiting, stats); | ||
| 351 | 344 | ||
| 352 | if use_color { | 345 | let fin = Fin { blend: 1.0, mbm: false, mask: None, invert: false, skip: [0.0; 4] }; |
| 353 | let pass = DfPass { | 346 | let key = self.make_key(node, "VectorTransform", src.size, &[src.content_hash], bytemuck::cast_slice(&u.p)); |
| 354 | tag: "VectorTransform", | ||
| 355 | op: DeepFlowOp::VectorTransform, | ||
| 356 | srcs: [Some(&src.view), None, None, None], | ||
| 357 | hashes: &[src.content_hash], | ||
| 358 | size: src.size, | ||
| 359 | depth: self.node_depth(comp, node, time, Some(src.depth)), | ||
| 360 | }; | ||
| 361 | return self.df_run(node, frame_i, pass, &fin, &u, aux, enc, stats); | ||
| 362 | } | ||
| 363 | let mut upstream = vec![src.content_hash, fin.mask_hash()]; | ||
| 364 | upstream.push(channel as u64); | ||
| 365 | let mut packed = u; | ||
| 366 | fin.pack(&mut packed); | ||
| 367 | let key = self.make_key(node, "VectorTransformAux", src.size, &upstream, bytemuck::cast_slice(&packed.p)); | ||
| 368 | if let Some(hit) = self.df_hit(key, node, frame_i, stats) { | 347 | if let Some(hit) = self.df_hit(key, node, frame_i, stats) { |
| 369 | return hit; | 348 | return hit; |
| 370 | } | 349 | } |
| 371 | let mut out_aux = src.aux_cloned(); | 350 | let mut out_aux = src.aux_cloned(); |
| 372 | let mut run = |me: &Self, field: &mut Option<AuxChannelTex>, tex: Option<AuxChannelTex>| { | 351 | let mut run = |me: &Self, field: &mut Option<AuxChannelTex>| { |
| 373 | if let Some(t) = tex { | 352 | if let Some(t) = field.take() { |
| 374 | let srcs = [Some(&*t.view), None, None, None]; | 353 | let srcs = [Some(&*t.view), None, None, None]; |
| 375 | *field = Some(me.df_aux_pass(enc, DeepFlowOp::VectorTransform, srcs, &fin, &u, t.size, wgpu::TextureFormat::Rgba16Float)); | 354 | *field = Some(me.df_aux_pass(enc, DeepFlowOp::VectorTransform, srcs, &fin, &u, t.size, wgpu::TextureFormat::Rgba16Float)); |
| 376 | } | 355 | } |
| 377 | }; | 356 | }; |
| 378 | run(self, &mut out_aux.vector, vector); | 357 | run(self, &mut out_aux.vector); |
| 379 | run(self, &mut out_aux.back_vector, back); | 358 | run(self, &mut out_aux.back_vector); |
| 380 | self.df_with_aux(node, frame_i, key, src, out_aux) | 359 | self.df_with_aux(node, frame_i, key, src, out_aux) |
| 381 | } | 360 | } |
| 382 | 361 |
crates/engine/src/eval/deep_flow/tests.rs+88-56| ... | @@ -412,8 +412,17 @@ fn ssao_modes_strength_blend_and_normal_aux() { | ... | @@ -412,8 +412,17 @@ fn ssao_modes_strength_blend_and_normal_aux() { |
| 412 | assert_eq!(px(&no_z, 32, 4, 4), [0.0, 0.0, 1.0, 1.0], "no aux.z passes through"); | 412 | assert_eq!(px(&no_z, 32, 4, 4), [0.0, 0.0, 1.0, 1.0], "no aux.z passes through"); |
| 413 | } | 413 | } |
| 414 | 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 | |||
| 415 | #[test] | 424 | #[test] |
| 416 | fn deep_shader_light_types_specular_reflection_and_depth_normals() { | 425 | fn deep_shader_ambient_diffuse_specular_reflection_and_blend() { |
| 417 | let Some(mut eng) = engine() else { return }; | 426 | let Some(mut eng) = engine() else { return }; |
| 418 | let shader = |input: &str, extra: &[String]| { | 427 | let shader = |input: &str, extra: &[String]| { |
| 419 | let mut v = vec![inp("Input", input)]; | 428 | let mut v = vec![inp("Input", input)]; |
| ... | @@ -421,87 +430,91 @@ fn deep_shader_light_types_specular_reflection_and_depth_normals() { | ... | @@ -421,87 +430,91 @@ fn deep_shader_light_types_specular_reflection_and_depth_normals() { |
| 421 | v | 430 | v |
| 422 | }; | 431 | }; |
| 423 | let tools = [ | 432 | let tools = [ |
| 424 | solid("Flat", 32, 32, [0.5, 0.5, 0.5, 1.0]), | 433 | solid("Flat", 32, 32, [0.5, 0.5, 0.5, 0.5]), |
| 425 | grad("Ramp", 32, 32, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], false), | 434 | // Facing the viewer, and tilted away from the default (45, 45) light. |
| 426 | z_scene("Slope", 32, 32, [0.5, 0.5, 0.5, 1.0], -10.0, -5.0), | 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]), | ||
| 427 | solid("Env", 16, 8, [1.0, 0.0, 0.0, 1.0]), | 437 | solid("Env", 16, 8, [1.0, 0.0, 0.0, 1.0]), |
| 428 | node("Head", "Shader", &shader("Flat", &[])), | 438 | node("NoNormal", "Shader", &shader("Flat", &[])), |
| 429 | node("Grazing", "Shader", &shader("Flat", &[val("Elevation", 0.0)])), | 439 | node("Ambient", "Shader", &shader("Flat", &[val("Ambient", 0.5), val("Diffuse", 0.0)])), |
| 430 | node("Spec", "Shader", &shader("Flat", &[val("Specular", 1.0), val("SpecularExponent", 64.0)])), | 440 | node("Skip", "Shader", &shader("Flat", &[val("ProcessGreen", 0.0)])), |
| 431 | node("Refl", "Shader", &shader("Flat", &[inp("EquirectangularMap", "Env")])), | 441 | node("Half", "Shader", &shader("Flat", &[val("Blend", 0.5)])), |
| 432 | node("Point", "Shader", &shader("Flat", &["LightType = Input { Value = FuID { \"Point\" }, },".into(), val("LightHeight", 0.25)])), | 442 | node("Lit", "Shader", &shader("Facing", &[val("Specular", 0.0)])), |
| 433 | node( | 443 | node("LitAway", "Shader", &shader("Away", &[val("Specular", 0.0)])), |
| 434 | "SpotNode", | 444 | node("Spec", "Shader", &shader("Facing", &[val("Diffuse", 0.0), val("Ambient", 0.0), val("EquatorAngle", 0.0), val("PolarHeight", 90.0)])), |
| 435 | "Shader", | 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)])), |
| 436 | &shader("Flat", &["LightType = Input { Value = 2, },".into(), val("LightHeight", 1.0), val("ConeAngle", 10.0), val("SpotSoftness", 0.01)]), | 446 | node("Refl", "Shader", &shader("Facing", &[inp("EnvironmentReflectionMap", "Env"), val("Specular", 0.0), val("Diffuse", 0.0), val("Ambient", 0.0)])), |
| 437 | ), | 447 | node("Off", "Shader", &shader("Flat", &[val("Blend", 0.0)])), |
| 438 | node("RampRight", "Shader", &shader("Ramp", &[val("Angle", 0.0), val("Elevation", 30.0), val("BumpHeight", 32.0)])), | ||
| 439 | node("RampLeft", "Shader", &shader("Ramp", &[val("Angle", 180.0), val("Elevation", 30.0), val("BumpHeight", 32.0)])), | ||
| 440 | node("SlopeRight", "Shader", &shader("Slope", &[val("Angle", 0.0), val("Elevation", 30.0), val("ZScale", 10.0)])), | ||
| 441 | node("SlopeLeft", "Shader", &shader("Slope", &[val("Angle", 180.0), val("Elevation", 30.0), val("ZScale", 10.0)])), | ||
| 442 | node("Off", "Shader", &shader("Flat", &[val("Elevation", 0.0), val("Blend", 0.0)])), | ||
| 443 | ] | 448 | ] |
| 444 | .concat(); | 449 | .concat(); |
| 445 | let comp = mk_comp(&tools); | 450 | let comp = mk_comp(&tools); |
| 446 | let at = |p: &[f32], x: u32, y: u32| px(p, 32, x, y); | 451 | let at = |p: &[f32]| px(p, 32, 16, 16); |
| 447 | 452 | let run = |eng: &mut Engine, name: &str| at(&eval(eng, &comp, name, 0.0).1); | |
| 448 | let (_, head) = eval(&mut eng, &comp, "Head", 0.0); | 453 | |
| 449 | assert!((at(&head, 16, 16)[0] - 0.5).abs() < 0.01, "head-on light on a flat surface is identity"); | 454 | let flat = run(&mut eng, "NoNormal"); |
| 450 | let (_, graze) = eval(&mut eng, &comp, "Grazing", 0.0); | 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:?}"); |
| 451 | assert!((at(&graze, 16, 16)[0] - 0.1).abs() < 0.01, "grazing light leaves only Ambient * albedo"); | 456 | let ambient = run(&mut eng, "Ambient"); |
| 452 | let (_, spec) = eval(&mut eng, &comp, "Spec", 0.0); | 457 | assert!((ambient[0] - 0.25).abs() < 0.01, "Ambient scales the image: {ambient:?}"); |
| 453 | assert!(at(&spec, 16, 16)[0] > 0.99, "Specular adds a highlight, got {:?}", at(&spec, 16, 16)); | 458 | let skip = run(&mut eng, "Skip"); |
| 454 | 459 | assert!((skip[0] - 0.125).abs() < 0.01 && (skip[1] - 0.5).abs() < 0.01, "ProcessGreen=0 keeps the source green: {skip:?}"); | |
| 455 | let (_, refl) = eval(&mut eng, &comp, "Refl", 0.0); | 460 | let half = run(&mut eng, "Half"); |
| 456 | let r = at(&refl, 16, 16); | 461 | assert!((half[0] - 0.5 * (1.0 + 0.25) / 2.0).abs() < 0.01, "Blend mixes with the source: {half:?}"); |
| 457 | assert!(r[0] > 1.2 && (r[1] - 0.5).abs() < 0.01, "reflection map adds red: {r:?}"); | 462 | assert!((run(&mut eng, "Off")[0] - 0.5).abs() < 1e-4, "Blend=0 keeps the input"); |
| 458 | 463 | ||
| 459 | let (_, point) = eval(&mut eng, &comp, "Point", 0.0); | 464 | let lit = run(&mut eng, "Lit"); |
| 460 | assert!(at(&point, 16, 16)[0] > at(&point, 1, 1)[0] + 0.05, "point light falls off toward the corner"); | 465 | let away = run(&mut eng, "LitAway"); |
| 461 | let (_, spot) = eval(&mut eng, &comp, "SpotNode", 0.0); | 466 | let ndl = 0.5f32.sqrt(); |
| 462 | assert!(at(&spot, 16, 16)[0] > 0.45, "spot centre is lit"); | 467 | assert!((lit[0] - 0.5 * (0.25 + ndl)).abs() < 0.02, "Ambient + Diffuse * N.L for the (45, 45) light: {lit:?}"); |
| 463 | assert!((at(&spot, 1, 1)[0] - 0.1).abs() < 0.01, "outside the cone only ambient remains: {:?}", at(&spot, 1, 1)); | 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:?}"); |
| 464 | 469 | ||
| 465 | let lit = |p: &[f32], albedo: f32| at(p, 16, 16)[0] / albedo; | 470 | let spec = run(&mut eng, "Spec"); |
| 466 | let (_, rr) = eval(&mut eng, &comp, "RampRight", 0.0); | 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:?}"); |
| 467 | let (_, rl) = eval(&mut eng, &comp, "RampLeft", 0.0); | 472 | let spec_blue = run(&mut eng, "SpecBlue"); |
| 468 | let albedo = at(&eval(&mut eng, &comp, "Ramp", 0.0).1, 16, 16)[0]; | 473 | assert!(spec_blue[0] < 0.01 && spec_blue[2] > 0.9, "SpecularRed/Green tint the highlight: {spec_blue:?}"); |
| 469 | assert!(lit(&rl, albedo) > lit(&rr, albedo) + 0.4, "luminance-derived normals tilt toward -X: {} vs {}", lit(&rl, albedo), lit(&rr, albedo)); | 474 | let refl = run(&mut eng, "Refl"); |
| 470 | let (_, sr) = eval(&mut eng, &comp, "SlopeRight", 0.0); | 475 | assert!(refl[0] > 0.9 && refl[1] < 0.01, "Screen reflection of the red map: {refl:?}"); |
| 471 | let (_, sl) = eval(&mut eng, &comp, "SlopeLeft", 0.0); | 476 | |
| 472 | assert!(at(&sl, 16, 16)[0] != at(&sr, 16, 16)[0], "aux.z derived normals respond to the light direction"); | 477 | let (tex, _) = eval(&mut eng, &comp, "Lit", 0.0); |
| 473 | let (tex, _) = eval(&mut eng, &comp, "SlopeLeft", 0.0); | 478 | assert!(tex.aux.as_ref().and_then(|a| a.normal.as_ref()).is_some(), "aux preserved"); |
| 474 | assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "aux preserved"); | ||
| 475 | |||
| 476 | let (_, off) = eval(&mut eng, &comp, "Off", 0.0); | ||
| 477 | assert!((at(&off, 16, 16)[0] - 0.5).abs() < 1e-4, "Blend=0 keeps the input"); | ||
| 478 | } | 479 | } |
| 479 | 480 | ||
| 480 | #[test] | 481 | #[test] |
| 481 | fn texture_uv_remap_scale_offset_edges_and_coverage() { | 482 | fn texture_uv_remap_scale_offset_flips_and_coverage() { |
| 482 | let Some(mut eng) = engine() else { return }; | 483 | let Some(mut eng) = engine() else { return }; |
| 483 | let tex_node = |extra: &[String]| { | 484 | let tex_node = |extra: &[String]| { |
| 484 | let mut v = vec![inp("Input", "UV"), inp("Texture", "Tex")]; | 485 | let mut v = vec![inp("Input", "UV"), inp("Texture", "Tex")]; |
| 485 | v.extend_from_slice(extra); | 486 | v.extend_from_slice(extra); |
| 486 | v | 487 | v |
| 487 | }; | 488 | }; |
| 489 | let edges = |e: &str| format!("Edges = Input {{ Value = FuID {{ \"{e}\" }}, }},"); | ||
| 488 | let tools = [ | 490 | let tools = [ |
| 489 | grad("UV", 32, 32, [0.0, 0.5, 0.0, 1.0], [1.0, 0.5, 0.0, 1.0], false), | 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, },"), | ||
| 490 | grad("Tex", 64, 64, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], false), | 494 | grad("Tex", 64, 64, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], false), |
| 491 | solid("Hole", 32, 32, [0.5, 0.5, 0.0, 0.0]), | 495 | solid("Hole", 32, 32, [0.5, 0.5, 0.0, 0.0]), |
| 492 | node("Def", "Texture", &tex_node(&[])), | 496 | node("Def", "Texture", &tex_node(&[])), |
| 493 | node("Scaled", "Texture", &tex_node(&[val("UScale", 2.0)])), | 497 | node("Scaled", "Texture", &tex_node(&[val("UScale", 2.0)])), |
| 494 | node("Offset", "Texture", &tex_node(&[val("UOffset", 0.25)])), | 498 | node("Offset", "Texture", &tex_node(&[val("UOffset", 0.25)])), |
| 495 | node("Black", "Texture", &tex_node(&[val("UScale", 2.0), "Edges = Input { Value = FuID { \"Black\" }, },".into()])), | 499 | node("Black", "Texture", &tex_node(&[val("UScale", 2.0), edges("Black")])), |
| 496 | node("Dup", "Texture", &tex_node(&[val("UScale", 2.0), "Edges = Input { Value = FuID { \"Duplicate\" }, },".into()])), | 500 | node("Dup", "Texture", &tex_node(&[val("UScale", 2.0), edges("Duplicate")])), |
| 497 | node("Mirror", "Texture", &tex_node(&[val("UScale", 2.0), "Edges = Input { Value = FuID { \"Mirror\" }, },".into()])), | 501 | node("Mirror", "Texture", &tex_node(&[val("UScale", 2.0), edges("Mirror")])), |
| 498 | node("Cover", "Texture", &[inp("Input", "Hole"), inp("Texture", "Tex")]), | 502 | node("Cover", "Texture", &[inp("Input", "Hole"), inp("Texture", "Tex")]), |
| 499 | node("NoTex", "Texture", &[inp("Input", "UV")]), | 503 | node("NoTex", "Texture", &[inp("Input", "UV")]), |
| 500 | node("Half", "Texture", &tex_node(&[val("Blend", 0.5)])), | 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\", }},")]), | ||
| 501 | ] | 513 | ] |
| 502 | .concat(); | 514 | .concat(); |
| 503 | let comp = mk_comp(&tools); | 515 | let comp = mk_comp(&tools); |
| 504 | let at = |p: &[f32], x: u32| px(p, 32, x, 16); | 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); | ||
| 505 | 518 | ||
| 506 | let (_, def) = eval(&mut eng, &comp, "Def", 0.0); | 519 | let (_, def) = eval(&mut eng, &comp, "Def", 0.0); |
| 507 | 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"); | 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"); |
| ... | @@ -509,7 +522,7 @@ fn texture_uv_remap_scale_offset_edges_and_coverage() { | ... | @@ -509,7 +522,7 @@ fn texture_uv_remap_scale_offset_edges_and_coverage() { |
| 509 | let (_, scaled) = eval(&mut eng, &comp, "Scaled", 0.0); | 522 | let (_, scaled) = eval(&mut eng, &comp, "Scaled", 0.0); |
| 510 | assert!(at(&scaled, 16)[0] < 0.15, "UScale=2 wraps u=1.0 back near 0, got {:?}", at(&scaled, 16)); | 523 | assert!(at(&scaled, 16)[0] < 0.15, "UScale=2 wraps u=1.0 back near 0, got {:?}", at(&scaled, 16)); |
| 511 | let (_, off) = eval(&mut eng, &comp, "Offset", 0.0); | 524 | let (_, off) = eval(&mut eng, &comp, "Offset", 0.0); |
| 512 | assert!((at(&off, 16)[0] - 0.75).abs() < 0.06, "UOffset shifts the lookup"); | 525 | assert!((at(&off, 16)[0] - 0.25).abs() < 0.06, "UOffset subtracts from the lookup, got {:?}", at(&off, 16)); |
| 513 | let (_, black) = eval(&mut eng, &comp, "Black", 0.0); | 526 | let (_, black) = eval(&mut eng, &comp, "Black", 0.0); |
| 514 | assert!(at(&black, 24)[3] < 0.01, "Edges=Black is transparent out of range"); | 527 | assert!(at(&black, 24)[3] < 0.01, "Edges=Black is transparent out of range"); |
| 515 | let (_, dup) = eval(&mut eng, &comp, "Dup", 0.0); | 528 | let (_, dup) = eval(&mut eng, &comp, "Dup", 0.0); |
| ... | @@ -522,6 +535,25 @@ fn texture_uv_remap_scale_offset_edges_and_coverage() { | ... | @@ -522,6 +535,25 @@ fn texture_uv_remap_scale_offset_edges_and_coverage() { |
| 522 | assert!((at(&no_tex, 16)[0] - 0.5).abs() < 0.03, "no texture input passes Input through"); | 535 | assert!((at(&no_tex, 16)[0] - 0.5).abs() < 0.03, "no texture input passes Input through"); |
| 523 | let (_, half) = eval(&mut eng, &comp, "Half", 0.0); | 536 | let (_, half) = eval(&mut eng, &comp, "Half", 0.0); |
| 524 | assert!((at(&half, 16)[0] - 0.5).abs() < 0.06, "Blend mixes with the UV image (0.5 either way here)"); | 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"); | ||
| 525 | } | 557 | } |
| 526 | 558 | ||
| 527 | mod flow; | 559 | mod flow; |
crates/engine/src/eval/deep_flow/tests/flow.rs+24-40| ... | @@ -8,7 +8,7 @@ fn vec_scene(name: &str, base: &str, v: [f32; 2], chan: &str) -> String { | ... | @@ -8,7 +8,7 @@ fn vec_scene(name: &str, base: &str, v: [f32; 2], chan: &str) -> String { |
| 8 | } | 8 | } |
| 9 | 9 | ||
| 10 | #[test] | 10 | #[test] |
| 11 | fn vector_transform_aux_color_and_mask() { | 11 | fn vector_transform_scales_rotates_smooths_and_attenuates_aux_vectors() { |
| 12 | let Some(mut eng) = engine() else { return }; | 12 | let Some(mut eng) = engine() else { return }; |
| 13 | let vt = |extra: &[String]| { | 13 | let vt = |extra: &[String]| { |
| 14 | let mut v = vec![inp("Input", "Scene")]; | 14 | let mut v = vec![inp("Input", "Scene")]; |
| ... | @@ -20,63 +20,47 @@ fn vector_transform_aux_color_and_mask() { | ... | @@ -20,63 +20,47 @@ fn vector_transform_aux_color_and_mask() { |
| 20 | solid("FV", 32, 32, [4.0, -2.0, 0.0, 1.0]), | 20 | solid("FV", 32, 32, [4.0, -2.0, 0.0, 1.0]), |
| 21 | solid("BV", 32, 32, [1.0, 1.0, 0.0, 1.0]), | 21 | solid("BV", 32, 32, [1.0, 1.0, 0.0, 1.0]), |
| 22 | aux_chain("Scene", "Base", &[("Vector", "FV"), ("BackVector", "BV")]), | 22 | aux_chain("Scene", "Base", &[("Vector", "FV"), ("BackVector", "BV")]), |
| 23 | rect_mask("RightHalf", [0.75, 0.5], [0.5, 1.0]), | 23 | grad("StepFV", 32, 32, [0.0, 0.0, 0.0, 1.0], [32.0, 0.0, 0.0, 1.0], false), |
| 24 | aux_chain("Step", "Base", &[("Vector", "StepFV")]), | ||
| 24 | node("Ident", "VectorTransform", &vt(&[])), | 25 | node("Ident", "VectorTransform", &vt(&[])), |
| 25 | node("Scale", "VectorTransform", &vt(&[val("XScale", 2.0), val("YScale", 3.0)])), | 26 | node("Size", "VectorTransform", &vt(&[val("XSize", 2.0), val("YSize", 3.0)])), |
| 27 | node("SizeAspect", "VectorTransform", &vt(&[val("UseSizeAndAspect", 1.0), val("Size", 2.0), val("Aspect", 1.5), val("XSize", 9.0)])), | ||
| 26 | node("Rot", "VectorTransform", &vt(&[val("Angle", 90.0)])), | 28 | node("Rot", "VectorTransform", &vt(&[val("Angle", 90.0)])), |
| 27 | node("Inv", "VectorTransform", &vt(&[val("Invert", 1.0)])), | 29 | node("Half", "VectorTransform", &vt(&[val("Angle", 90.0), val("AttenuateVect", 0.5)])), |
| 28 | node("FlipX", "VectorTransform", &vt(&[val("FlipX", 1.0)])), | 30 | node("None", "VectorTransform", &vt(&[val("Angle", 90.0), val("AttenuateVect", 0.0)])), |
| 29 | node("FlipY", "VectorTransform", &vt(&[val("FlipY", 1.0)])), | 31 | node("Smooth", "VectorTransform", &[inp("Input", "Step"), val("SmoothVector", 4.0)]), |
| 30 | node("Norm", "VectorTransform", &vt(&[val("Normalize", 1.0)])), | 32 | node("NoVec", "VectorTransform", &[inp("Input", "Base"), val("Angle", 90.0), val("XSize", 3.0)]), |
| 31 | node("Off", "VectorTransform", &vt(&[val("XOffset", 1.0), val("YOffset", -1.0)])), | ||
| 32 | node("OnlyFwd", "VectorTransform", &vt(&[val("XScale", 2.0), "Channel = Input { Value = FuID { \"Vector\" }, },".into()])), | ||
| 33 | node("Half", "VectorTransform", &vt(&[val("XScale", 3.0), val("Blend", 0.5)])), | ||
| 34 | node("Masked", "VectorTransform", &vt(&[val("Invert", 1.0), inp("EffectMask", "RightHalf").replace("Output", "Mask")])), | ||
| 35 | solid("ColVec", 32, 32, [0.25, -0.5, 0.75, 1.0]), | ||
| 36 | node("Color", "VectorTransform", &[inp("Input", "ColVec"), val("Invert", 1.0)]), | ||
| 37 | node("ColorOnly", "VectorTransform", &vt(&[val("XScale", 0.0), "Channel = Input { Value = FuID { \"Color\" }, },".into()])), | ||
| 38 | node("NoVec", "VectorTransform", &[inp("Input", "Base"), "Channel = Input { Value = 1, },".into()]), | ||
| 39 | ] | 33 | ] |
| 40 | .concat(); | 34 | .concat(); |
| 41 | let comp = mk_comp(&tools); | 35 | let comp = mk_comp(&tools); |
| 42 | let check = |eng: &mut Engine, name: &str, f: [f32; 2], b: [f32; 2]| { | 36 | let vectors = |eng: &mut Engine, name: &str| { |
| 43 | let (tex, _) = eval(eng, &comp, name, 0.0); | 37 | let (tex, _) = eval(eng, &comp, name, 0.0); |
| 44 | let aux = tex.aux.as_ref().unwrap_or_else(|| panic!("{name}: aux missing")); | 38 | let aux = tex.aux.as_ref().unwrap_or_else(|| panic!("{name}: aux missing")); |
| 45 | let fv = aux_at(&aux_px(eng, aux.vector.as_ref().unwrap()), 32, 16, 16); | 39 | (aux_px(eng, aux.vector.as_ref().unwrap()), aux.back_vector.as_ref().map(|b| aux_px(eng, b))) |
| 46 | let bv = aux_at(&aux_px(eng, aux.back_vector.as_ref().unwrap()), 32, 16, 16); | 40 | }; |
| 41 | let check = |eng: &mut Engine, name: &str, f: [f32; 2], b: [f32; 2]| { | ||
| 42 | let (fv, bv) = vectors(eng, name); | ||
| 43 | let (fv, bv) = (aux_at(&fv, 32, 16, 16), aux_at(&bv.unwrap(), 32, 16, 16)); | ||
| 47 | assert!((fv[0] - f[0]).abs() < 0.02 && (fv[1] - f[1]).abs() < 0.02, "{name}: forward {fv:?} != {f:?}"); | 44 | assert!((fv[0] - f[0]).abs() < 0.02 && (fv[1] - f[1]).abs() < 0.02, "{name}: forward {fv:?} != {f:?}"); |
| 48 | assert!((bv[0] - b[0]).abs() < 0.02 && (bv[1] - b[1]).abs() < 0.02, "{name}: back {bv:?} != {b:?}"); | 45 | assert!((bv[0] - b[0]).abs() < 0.02 && (bv[1] - b[1]).abs() < 0.02, "{name}: back {bv:?} != {b:?}"); |
| 49 | }; | 46 | }; |
| 50 | check(&mut eng, "Ident", [4.0, -2.0], [1.0, 1.0]); | 47 | check(&mut eng, "Ident", [4.0, -2.0], [1.0, 1.0]); |
| 51 | check(&mut eng, "Scale", [8.0, -6.0], [2.0, 3.0]); | 48 | check(&mut eng, "Size", [8.0, -6.0], [2.0, 3.0]); |
| 49 | check(&mut eng, "SizeAspect", [8.0, -6.0], [2.0, 3.0]); | ||
| 52 | check(&mut eng, "Rot", [2.0, 4.0], [-1.0, 1.0]); | 50 | check(&mut eng, "Rot", [2.0, 4.0], [-1.0, 1.0]); |
| 53 | check(&mut eng, "Inv", [-4.0, 2.0], [-1.0, -1.0]); | 51 | check(&mut eng, "Half", [3.0, 1.0], [0.0, 1.0]); |
| 54 | check(&mut eng, "FlipX", [-4.0, -2.0], [-1.0, 1.0]); | 52 | check(&mut eng, "None", [4.0, -2.0], [1.0, 1.0]); |
| 55 | check(&mut eng, "FlipY", [4.0, 2.0], [1.0, -1.0]); | ||
| 56 | check(&mut eng, "Norm", [0.894, -0.447], [0.707, 0.707]); | ||
| 57 | check(&mut eng, "Off", [5.0, -3.0], [2.0, 0.0]); | ||
| 58 | check(&mut eng, "OnlyFwd", [8.0, -2.0], [1.0, 1.0]); | ||
| 59 | check(&mut eng, "Half", [8.0, -2.0], [2.0, 1.0]); | ||
| 60 | 53 | ||
| 61 | // RGBA is untouched on the aux path. | 54 | let (tex, p) = eval(&mut eng, &comp, "Size", 0.0); |
| 62 | let (tex, p) = eval(&mut eng, &comp, "Scale", 0.0); | ||
| 63 | assert_eq!(px(&p, 32, 16, 16), [0.1, 0.2, 0.3, 1.0], "colour passes through"); | 55 | assert_eq!(px(&p, 32, 16, 16), [0.1, 0.2, 0.3, 1.0], "colour passes through"); |
| 64 | assert!(tex.aux.is_some()); | 56 | assert!(tex.aux.is_some()); |
| 65 | 57 | ||
| 66 | // EffectMask: left half keeps the original vector, right half is inverted. | 58 | let (ramp, _) = vectors(&mut eng, "Smooth"); |
| 67 | let (tex, _) = eval(&mut eng, &comp, "Masked", 0.0); | 59 | assert!((aux_at(&ramp, 32, 16, 16)[0] - 16.5).abs() < 0.2, "a linear ramp is its own 3-tap average"); |
| 68 | let fwd = aux_px(&eng, tex.aux.as_ref().unwrap().vector.as_ref().unwrap()); | 60 | assert!((aux_at(&ramp, 32, 1, 16)[0] - 2.5).abs() < 0.2, "taps at x-4, x, x+4 clamp to the border: {:?}", aux_at(&ramp, 32, 1, 16)); |
| 69 | assert!((aux_at(&fwd, 32, 4, 16)[0] - 4.0).abs() < 0.02, "outside the mask is unchanged"); | ||
| 70 | assert!((aux_at(&fwd, 32, 28, 16)[0] + 4.0).abs() < 0.02, "inside the mask is transformed"); | ||
| 71 | 61 | ||
| 72 | // Colour RG fallback when no aux vectors exist. | ||
| 73 | let (_, col) = eval(&mut eng, &comp, "Color", 0.0); | ||
| 74 | let c = px(&col, 32, 16, 16); | ||
| 75 | assert!((c[0] + 0.25).abs() < 1e-4 && (c[1] - 0.5).abs() < 1e-4 && (c[2] - 0.75).abs() < 1e-4, "RG inverted, B/A kept: {c:?}"); | ||
| 76 | let (_, col_only) = eval(&mut eng, &comp, "ColorOnly", 0.0); | ||
| 77 | assert!(px(&col_only, 32, 16, 16)[0].abs() < 1e-4, "Channel=Color forces the RG path even when aux exists"); | ||
| 78 | let (_, no_vec) = eval(&mut eng, &comp, "NoVec", 0.0); | 62 | let (_, no_vec) = eval(&mut eng, &comp, "NoVec", 0.0); |
| 79 | assert_eq!(px(&no_vec, 32, 16, 16), [0.1, 0.2, 0.3, 1.0], "nothing to transform"); | 63 | assert_eq!(px(&no_vec, 32, 16, 16), [0.1, 0.2, 0.3, 1.0], "without vectors the image is untouched, RG is never rotated"); |
| 80 | } | 64 | } |
| 81 | 65 | ||
| 82 | #[test] | 66 | #[test] |
crates/engine/src/eval/mod.rs+13-1| ... | @@ -34,6 +34,7 @@ mod fx_fuses; | ... | @@ -34,6 +34,7 @@ mod fx_fuses; |
| 34 | mod archive_fx2; | 34 | mod archive_fx2; |
| 35 | mod surface_fx; | 35 | mod surface_fx; |
| 36 | mod layer_ocio; | 36 | mod layer_ocio; |
| 37 | mod primatte_misc; | ||
| 37 | mod deep_flow; | 38 | mod deep_flow; |
| 38 | mod text_3d; | 39 | mod text_3d; |
| 39 | mod registry; | 40 | mod registry; |
| ... | @@ -90,6 +91,7 @@ pub struct Engine { | ... | @@ -90,6 +91,7 @@ pub struct Engine { |
| 90 | archive_fx2_pipelines: OnceCell<RefCell<archive_fx2::ArchiveFx2Pipelines>>, | 91 | archive_fx2_pipelines: OnceCell<RefCell<archive_fx2::ArchiveFx2Pipelines>>, |
| 91 | pub(crate) surface_fx: OnceCell<RefCell<surface_fx::SurfaceFxPipelines>>, | 92 | pub(crate) surface_fx: OnceCell<RefCell<surface_fx::SurfaceFxPipelines>>, |
| 92 | pub(crate) layer_ocio: OnceCell<RefCell<layer_ocio::LayerOcioPipelines>>, | 93 | pub(crate) layer_ocio: OnceCell<RefCell<layer_ocio::LayerOcioPipelines>>, |
| 94 | pub(crate) primatte_misc: OnceCell<RefCell<primatte_misc::PrimatteMiscPipelines>>, | ||
| 93 | pub(crate) deep_flow: OnceCell<RefCell<deep_flow::DeepFlowPipelines>>, | 95 | pub(crate) deep_flow: OnceCell<RefCell<deep_flow::DeepFlowPipelines>>, |
| 94 | auto_matte_pipelines: OnceCell<RefCell<crate::auto_matte::AutoMattePipelines>>, | 96 | auto_matte_pipelines: OnceCell<RefCell<crate::auto_matte::AutoMattePipelines>>, |
| 95 | pub auto_matte_cache: crate::auto_matte::AutoMatteCache, | 97 | pub auto_matte_cache: crate::auto_matte::AutoMatteCache, |
| ... | @@ -209,6 +211,7 @@ impl Engine { | ... | @@ -209,6 +211,7 @@ impl Engine { |
| 209 | archive_fx2_pipelines: OnceCell::new(), | 211 | archive_fx2_pipelines: OnceCell::new(), |
| 210 | surface_fx: OnceCell::new(), | 212 | surface_fx: OnceCell::new(), |
| 211 | layer_ocio: OnceCell::new(), | 213 | layer_ocio: OnceCell::new(), |
| 214 | primatte_misc: OnceCell::new(), | ||
| 212 | deep_flow: OnceCell::new(), | 215 | deep_flow: OnceCell::new(), |
| 213 | auto_matte_pipelines: OnceCell::new(), | 216 | auto_matte_pipelines: OnceCell::new(), |
| 214 | auto_matte_cache: crate::auto_matte::AutoMatteCache::new(), | 217 | auto_matte_cache: crate::auto_matte::AutoMatteCache::new(), |
| ... | @@ -382,6 +385,9 @@ impl Engine { | ... | @@ -382,6 +385,9 @@ impl Engine { |
| 382 | if let Some(lo) = self.layer_ocio.get() { | 385 | if let Some(lo) = self.layer_ocio.get() { |
| 383 | lo.borrow_mut().reset_uniform_cursor(); | 386 | lo.borrow_mut().reset_uniform_cursor(); |
| 384 | } | 387 | } |
| 388 | if let Some(pm) = self.primatte_misc.get() { | ||
| 389 | pm.borrow_mut().reset_uniform_cursor(); | ||
| 390 | } | ||
| 385 | if let Some(df) = self.deep_flow.get() { | 391 | if let Some(df) = self.deep_flow.get() { |
| 386 | df.borrow_mut().reset_uniform_cursor(); | 392 | df.borrow_mut().reset_uniform_cursor(); |
| 387 | } | 393 | } |
| ... | @@ -426,6 +432,9 @@ impl Engine { | ... | @@ -426,6 +432,9 @@ impl Engine { |
| 426 | if let Some(lo) = self.layer_ocio.get() { | 432 | if let Some(lo) = self.layer_ocio.get() { |
| 427 | lo.borrow_mut().trim_uniform_chunks(2); | 433 | lo.borrow_mut().trim_uniform_chunks(2); |
| 428 | } | 434 | } |
| 435 | if let Some(pm) = self.primatte_misc.get() { | ||
| 436 | pm.borrow_mut().trim_uniform_chunks(2); | ||
| 437 | } | ||
| 429 | if let Some(df) = self.deep_flow.get() { | 438 | if let Some(df) = self.deep_flow.get() { |
| 430 | df.borrow_mut().trim_uniform_chunks(2); | 439 | df.borrow_mut().trim_uniform_chunks(2); |
| 431 | } | 440 | } |
| ... | @@ -1088,7 +1097,10 @@ impl Engine { | ... | @@ -1088,7 +1097,10 @@ impl Engine { |
| 1088 | "LayerRegex" => self.eval_layer_filter(comp, node, time, false, enc, visiting, stats), | 1097 | "LayerRegex" => self.eval_layer_filter(comp, node, time, false, enc, visiting, stats), |
| 1089 | "LayerRemover" => self.eval_layer_filter(comp, node, time, true, enc, visiting, stats), | 1098 | "LayerRemover" => self.eval_layer_filter(comp, node, time, true, enc, visiting, stats), |
| 1090 | "Swizzler" => self.eval_swizzler(comp, node, time, frame_i, enc, visiting, stats), | 1099 | "Swizzler" => self.eval_swizzler(comp, node, time, frame_i, enc, visiting, stats), |
| 1091 | "Dummy" | "Fuse.FLS_CopyMetadata" | "Fuse.SetMetaDataTC" => self.eval_passthrough(comp, node, time, enc, visiting, stats), | 1100 | "Dummy" | "Fuse.FLS_CopyMetadata" | "Fuse.SetMetaDataTC" | "Profiler" | "RunCommand" | "Fuse.ExternalMatteSaver" => { |
| 1101 | self.eval_passthrough(comp, node, time, enc, visiting, stats) | ||
| 1102 | } | ||
| 1103 | "Photron.Primatte4" | "Primatte4" => self.eval_primatte4(comp, node, time, frame_i, enc, visiting, stats), | ||
| 1092 | "MultiText" => self.eval_multi_text(comp, node, time, frame_i, comp_dims, enc, stats), | 1104 | "MultiText" => self.eval_multi_text(comp, node, time, frame_i, comp_dims, enc, stats), |
| 1093 | "Fields" => self.eval_fields(comp, node, time, frame_i, enc, visiting, stats), | 1105 | "Fields" => self.eval_fields(comp, node, time, frame_i, enc, visiting, stats), |
| 1094 | "KeyStretcher" => self.eval_key_stretcher(comp, node, time, frame_i, enc, visiting, stats), | 1106 | "KeyStretcher" => self.eval_key_stretcher(comp, node, time, frame_i, enc, visiting, stats), |
crates/engine/src/eval/primatte_misc.rs created+285| ... | @@ -0,0 +1,285 @@ | ||
| 1 | //! `Photron.Primatte4` (alias `Primatte4`): polyhedral chroma-space keyer on the GPU | ||
| 2 | //! (`primatte_misc.wgsl`: `filterable: false` + `textureLoad`, WriteOnly storage output patched per | ||
| 3 | //! format, no `read_write` storage textures). | ||
| 4 | //! | ||
| 5 | //! `Profiler`, `RunCommand` and `Fuse.ExternalMatteSaver` are lossless passthroughs (`eval_passthrough`); | ||
| 6 | //! `RunCommand` never executes anything, so an untrusted `.comp` cannot run a shell command. | ||
| 7 | |||
| 8 | #[cfg(test)] | ||
| 9 | mod tests; | ||
| 10 | |||
| 11 | use super::*; | ||
| 12 | use std::num::NonZeroU64; | ||
| 13 | |||
| 14 | const PRIMATTE_WGSL: &str = include_str!("../shaders/primatte_misc.wgsl"); | ||
| 15 | const UNIFORM_SLOTS_PER_CHUNK: u32 = 512; | ||
| 16 | const OUTPUT_MODES: [&str; 3] = ["composite", "alpha", "spillsuppressed"]; | ||
| 17 | const KEY_COLOR_DEFAULT: [f64; 3] = [0.0, 1.0, 0.0]; | ||
| 18 | |||
| 19 | struct FormatPipeline { | ||
| 20 | bgl: wgpu::BindGroupLayout, | ||
| 21 | pipeline: wgpu::ComputePipeline, | ||
| 22 | } | ||
| 23 | |||
| 24 | pub(crate) struct PrimatteMiscPipelines { | ||
| 25 | uniform_stride: u32, | ||
| 26 | uniform_chunks: Vec<wgpu::Buffer>, | ||
| 27 | uniform_cursor: u32, | ||
| 28 | by_format: HashMap<(wgpu::TextureFormat, bool), FormatPipeline>, | ||
| 29 | } | ||
| 30 | |||
| 31 | fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { | ||
| 32 | wgpu::BindGroupLayoutEntry { | ||
| 33 | binding, | ||
| 34 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 35 | ty: wgpu::BindingType::Texture { | ||
| 36 | sample_type: wgpu::TextureSampleType::Float { filterable: false }, | ||
| 37 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 38 | multisampled: false, | ||
| 39 | }, | ||
| 40 | count: None, | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | fn patch_storage_format(format: wgpu::TextureFormat, hdr_float: bool) -> String { | ||
| 45 | let storage_fmt = match format { | ||
| 46 | wgpu::TextureFormat::Rgba16Float => "rgba16float", | ||
| 47 | wgpu::TextureFormat::Rgba32Float => "rgba32float", | ||
| 48 | _ => "rgba8unorm", | ||
| 49 | }; | ||
| 50 | let mut src = PRIMATTE_WGSL.replace( | ||
| 51 | "texture_storage_2d<rgba8unorm, write>", | ||
| 52 | &format!("texture_storage_2d<{storage_fmt}, write>"), | ||
| 53 | ); | ||
| 54 | if hdr_float { | ||
| 55 | src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); | ||
| 56 | } | ||
| 57 | src | ||
| 58 | } | ||
| 59 | |||
| 60 | impl PrimatteMiscPipelines { | ||
| 61 | pub(super) fn new(device: &wgpu::Device) -> Self { | ||
| 62 | let uniform_size = std::mem::size_of::<UniformParams>() as u32; | ||
| 63 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); | ||
| 64 | Self { | ||
| 65 | uniform_stride: uniform_size.div_ceil(min_align) * min_align, | ||
| 66 | uniform_chunks: Vec::new(), | ||
| 67 | uniform_cursor: 0, | ||
| 68 | by_format: HashMap::new(), | ||
| 69 | } | ||
| 70 | } | ||
| 71 | |||
| 72 | pub(super) fn reset_uniform_cursor(&mut self) { | ||
| 73 | self.uniform_cursor = 0; | ||
| 74 | } | ||
| 75 | |||
| 76 | pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { | ||
| 77 | self.uniform_cursor = 0; | ||
| 78 | self.uniform_chunks.truncate(max_chunks); | ||
| 79 | } | ||
| 80 | |||
| 81 | fn alloc_uniform_slot(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, params: &UniformParams) -> (usize, u32) { | ||
| 82 | let slot = self.uniform_cursor; | ||
| 83 | let chunk_idx = (slot / UNIFORM_SLOTS_PER_CHUNK) as usize; | ||
| 84 | while chunk_idx >= self.uniform_chunks.len() { | ||
| 85 | self.uniform_chunks.push(device.create_buffer(&wgpu::BufferDescriptor { | ||
| 86 | label: Some("primatte-params-ring"), | ||
| 87 | size: u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride), | ||
| 88 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | ||
| 89 | mapped_at_creation: false, | ||
| 90 | })); | ||
| 91 | } | ||
| 92 | let offset = (slot % UNIFORM_SLOTS_PER_CHUNK) * self.uniform_stride; | ||
| 93 | queue.write_buffer(&self.uniform_chunks[chunk_idx], u64::from(offset), bytemuck::bytes_of(params)); | ||
| 94 | self.uniform_cursor = slot + 1; | ||
| 95 | (chunk_idx, offset) | ||
| 96 | } | ||
| 97 | |||
| 98 | fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { | ||
| 99 | if self.by_format.contains_key(&(format, hdr_float)) { | ||
| 100 | return; | ||
| 101 | } | ||
| 102 | let u_size = std::mem::size_of::<UniformParams>() as u64; | ||
| 103 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { | ||
| 104 | label: Some("primatte-bgl"), | ||
| 105 | entries: &[ | ||
| 106 | unfilterable_tex_entry(0), | ||
| 107 | unfilterable_tex_entry(1), | ||
| 108 | unfilterable_tex_entry(2), | ||
| 109 | unfilterable_tex_entry(3), | ||
| 110 | unfilterable_tex_entry(4), | ||
| 111 | wgpu::BindGroupLayoutEntry { | ||
| 112 | binding: 5, | ||
| 113 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 114 | ty: wgpu::BindingType::StorageTexture { | ||
| 115 | access: wgpu::StorageTextureAccess::WriteOnly, | ||
| 116 | format, | ||
| 117 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 118 | }, | ||
| 119 | count: None, | ||
| 120 | }, | ||
| 121 | wgpu::BindGroupLayoutEntry { | ||
| 122 | binding: 6, | ||
| 123 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 124 | ty: wgpu::BindingType::Buffer { | ||
| 125 | ty: wgpu::BufferBindingType::Uniform, | ||
| 126 | has_dynamic_offset: true, | ||
| 127 | min_binding_size: NonZeroU64::new(u_size), | ||
| 128 | }, | ||
| 129 | count: None, | ||
| 130 | }, | ||
| 131 | ], | ||
| 132 | }); | ||
| 133 | let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { | ||
| 134 | label: Some("primatte-pl"), | ||
| 135 | bind_group_layouts: &[Some(&bgl)], | ||
| 136 | immediate_size: 0, | ||
| 137 | }); | ||
| 138 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { | ||
| 139 | label: Some("primatte-wgsl"), | ||
| 140 | source: wgpu::ShaderSource::Wgsl(patch_storage_format(format, hdr_float).into()), | ||
| 141 | }); | ||
| 142 | let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { | ||
| 143 | label: Some("primatte_op"), | ||
| 144 | layout: Some(&layout), | ||
| 145 | module: &module, | ||
| 146 | entry_point: Some("primatte_op"), | ||
| 147 | compilation_options: Default::default(), | ||
| 148 | cache: None, | ||
| 149 | }); | ||
| 150 | self.by_format.insert((format, hdr_float), FormatPipeline { bgl, pipeline }); | ||
| 151 | } | ||
| 152 | |||
| 153 | fn dispatch( | ||
| 154 | &mut self, | ||
| 155 | device: &wgpu::Device, | ||
| 156 | queue: &wgpu::Queue, | ||
| 157 | enc: &mut wgpu::CommandEncoder, | ||
| 158 | views: [&wgpu::TextureView; 5], | ||
| 159 | dst: &CachedTexture, | ||
| 160 | params: &UniformParams, | ||
| 161 | ) { | ||
| 162 | let hdr_float = dst.depth.is_float(); | ||
| 163 | self.ensure_format(device, dst.format, hdr_float); | ||
| 164 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); | ||
| 165 | let fp = &self.by_format[&(dst.format, hdr_float)]; | ||
| 166 | let mut entries: Vec<wgpu::BindGroupEntry> = views | ||
| 167 | .iter() | ||
| 168 | .enumerate() | ||
| 169 | .map(|(i, v)| wgpu::BindGroupEntry { binding: i as u32, resource: wgpu::BindingResource::TextureView(v) }) | ||
| 170 | .collect(); | ||
| 171 | entries.push(wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&dst.view) }); | ||
| 172 | entries.push(wgpu::BindGroupEntry { | ||
| 173 | binding: 6, | ||
| 174 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { | ||
| 175 | buffer: &self.uniform_chunks[chunk_idx], | ||
| 176 | offset: 0, | ||
| 177 | size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64), | ||
| 178 | }), | ||
| 179 | }); | ||
| 180 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("primatte-bg"), layout: &fp.bgl, entries: &entries }); | ||
| 181 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("primatte-pass"), timestamp_writes: None }); | ||
| 182 | pass.set_pipeline(&fp.pipeline); | ||
| 183 | pass.set_bind_group(0, &bg, &[offset]); | ||
| 184 | pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); | ||
| 185 | } | ||
| 186 | } | ||
| 187 | |||
| 188 | fn b2f(v: bool) -> f32 { | ||
| 189 | if v { 1.0 } else { 0.0 } | ||
| 190 | } | ||
| 191 | |||
| 192 | impl Engine { | ||
| 193 | fn primatte_pipelines(&self) -> &RefCell<PrimatteMiscPipelines> { | ||
| 194 | self.primatte_misc.get_or_init(|| RefCell::new(PrimatteMiscPipelines::new(&self.device))) | ||
| 195 | } | ||
| 196 | |||
| 197 | /// `Photron.Primatte4`: a key polyhedron around the screen colour in chroma space (`BackgroundColor`, else | ||
| 198 | /// `KeyColor`, else green; `AutoCompute` samples it from the image) maps distance to matte. `CleanBackground` | ||
| 199 | /// and `CleanForeground` move the transparent and opaque boundaries, `MatteSponge` / `MatteRestore` / | ||
| 200 | /// `DetailMinus` / `DetailPlus` reshape partial alpha, `SpillSuppression` and `SpillSponge` de-contaminate | ||
| 201 | /// colour, `Deartifacting`, `MatteBlur` (px) and `MatteContractExpand` (px, negative contracts) refine the | ||
| 202 | /// matte, `GarbageMatte` removes and `SolidMatte` forces opacity (their alpha), and `OutputMode` picks | ||
| 203 | /// Composite (over `Background`), Alpha or SpillSuppressed. `Blend`, `EffectMask` and `Process*` apply last. | ||
| 204 | #[allow(clippy::too_many_arguments)] | ||
| 205 | pub(in crate::eval) fn eval_primatte4( | ||
| 206 | &mut self, | ||
| 207 | comp: &Comp, | ||
| 208 | node: &Node, | ||
| 209 | time: f64, | ||
| 210 | frame_i: i64, | ||
| 211 | enc: &mut wgpu::CommandEncoder, | ||
| 212 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 213 | stats: &mut EvalStats, | ||
| 214 | ) -> CachedTexture { | ||
| 215 | let Some(src_id) = ["Input", "Foreground", "Image"].iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s))) else { | ||
| 216 | return self.dummy.clone(); | ||
| 217 | }; | ||
| 218 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | ||
| 219 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 220 | let mbm = self.multiplies_by_mask(comp, node, time); | ||
| 221 | if blend <= 1e-6 && !mbm { | ||
| 222 | return src; | ||
| 223 | } | ||
| 224 | let src = if Self::resolve_effect_mask_id(comp, node).is_some() { self.crop_to_canvas(enc, src) } else { src }; | ||
| 225 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); | ||
| 226 | let skip = self.process_skip(comp, node, time); | ||
| 227 | |||
| 228 | let mut optional = |ports: &[&str]| { | ||
| 229 | let id = ports.iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s)))?; | ||
| 230 | Some(self.eval_node(comp, id, time, enc, visiting, stats)) | ||
| 231 | }; | ||
| 232 | let background = optional(&["Background"]); | ||
| 233 | let garbage = optional(&["GarbageMatte"]); | ||
| 234 | let solid = optional(&["SolidMatte"]); | ||
| 235 | |||
| 236 | let n = |key: &str, d: f64| comp.eval_number(node, key, time, d, &self.expr) as f32; | ||
| 237 | let color = |name: &str| { | ||
| 238 | let has = ["Red", "Green", "Blue"].iter().any(|c| node.inputs.contains_key(&format!("{name}{c}"))); | ||
| 239 | has.then(|| ["Red", "Green", "Blue"].map(|c| comp.eval_number(node, &format!("{name}{c}"), time, 0.0, &self.expr) as f32)) | ||
| 240 | }; | ||
| 241 | let key = color("BackgroundColor").or_else(|| color("KeyColor")).unwrap_or(KEY_COLOR_DEFAULT.map(|v| v as f32)); | ||
| 242 | let mode = match node.static_str("OutputMode") { | ||
| 243 | Some(s) => { | ||
| 244 | let s = s.chars().filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase(); | ||
| 245 | OUTPUT_MODES.iter().position(|m| *m == s).unwrap_or(0) | ||
| 246 | } | ||
| 247 | None => (n("OutputMode", 0.0).round().max(0.0) as usize).min(OUTPUT_MODES.len() - 1), | ||
| 248 | }; | ||
| 249 | |||
| 250 | let mut u = UniformParams::default(); | ||
| 251 | u.p[0] = [key[0], key[1], key[2], b2f(n("AutoCompute", 0.0) > 0.5)]; | ||
| 252 | let unit = |name: &str, d: f64| n(name, d).clamp(0.0, 1.0); | ||
| 253 | u.p[1] = [unit("CleanBackground", 0.0), unit("CleanForeground", 0.0), unit("MatteSponge", 0.0), unit("MatteRestore", 0.0)]; | ||
| 254 | u.p[2] = [unit("SpillSponge", 0.0), unit("DetailMinus", 0.0), unit("DetailPlus", 0.0), unit("SpillSuppression", 0.5)]; | ||
| 255 | u.p[3] = [unit("Deartifacting", 0.0), n("MatteBlur", 0.0).clamp(0.0, 64.0), n("MatteContractExpand", 0.0).clamp(-64.0, 64.0), mode as f32]; | ||
| 256 | u.p[4] = [b2f(background.is_some()), b2f(garbage.is_some()), b2f(solid.is_some()), 0.0]; | ||
| 257 | u.p[14] = [blend, b2f(mask.is_some()), b2f(mask_inv), b2f(mbm)]; | ||
| 258 | u.p[15] = skip; | ||
| 259 | |||
| 260 | let hash = |t: &Option<CachedTexture>| t.as_ref().map_or(0, |t| t.content_hash); | ||
| 261 | let depth = self.node_depth(comp, node, time, Some(src.depth)); | ||
| 262 | let upstream = [src.content_hash, hash(&background), hash(&garbage), hash(&solid), hash(&mask), depth as u64]; | ||
| 263 | let key = self.make_key(node, "Primatte4", src.size, &upstream, bytemuck::cast_slice(&u.p)); | ||
| 264 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 265 | stats.cache_hits += 1; | ||
| 266 | return hit; | ||
| 267 | } | ||
| 268 | stats.cache_misses += 1; | ||
| 269 | stats.nodes_evaluated += 1; | ||
| 270 | let mut dst = self.alloc_tex_like(&src, depth, key); | ||
| 271 | let view = |t: &Option<CachedTexture>| t.as_ref().map_or_else(|| self.dummy.view.clone(), |t| t.view.clone()); | ||
| 272 | let views = [src.view.clone(), view(&background), view(&garbage), view(&solid), view(&mask)]; | ||
| 273 | self.primatte_pipelines().borrow_mut().dispatch( | ||
| 274 | &self.device, | ||
| 275 | &self.queue, | ||
| 276 | enc, | ||
| 277 | [&views[0], &views[1], &views[2], &views[3], &views[4]], | ||
| 278 | &dst, | ||
| 279 | &u, | ||
| 280 | ); | ||
| 281 | dst.set_aux(src.aux.clone()); | ||
| 282 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 283 | dst | ||
| 284 | } | ||
| 285 | } | ||
crates/engine/src/eval/primatte_misc/tests.rs created+276| ... | @@ -0,0 +1,276 @@ | ||
| 1 | //! GPU unit tests for `Photron.Primatte4` and the passthrough utilities. | ||
| 2 | |||
| 3 | use super::*; | ||
| 4 | |||
| 5 | fn comp(tools: &str) -> Comp { | ||
| 6 | let src = format!( | ||
| 7 | "Composition {{ CurrentTime = 0, RenderRange = {{ 0, 10 }}, GlobalRange = {{ 0, 10 }}, Tools = ordered() {{ {tools} }} }}" | ||
| 8 | ); | ||
| 9 | Comp::from_fusion_str(&src).expect("parse comp") | ||
| 10 | } | ||
| 11 | |||
| 12 | /// Float32 solid-colour `Background` named `name`. | ||
| 13 | fn solid(name: &str, w: u32, h: u32, [r, g, b, a]: [f32; 4]) -> String { | ||
| 14 | format!( | ||
| 15 | "{name} = Background {{ Inputs = {{ Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, Depth = Input {{ Value = 4, }}, \ | ||
| 16 | TopLeftRed = Input {{ Value = {r}, }}, TopLeftGreen = Input {{ Value = {g}, }}, TopLeftBlue = Input {{ Value = {b}, }}, TopLeftAlpha = Input {{ Value = {a}, }}, }}, }}," | ||
| 17 | ) | ||
| 18 | } | ||
| 19 | |||
| 20 | fn tool(name: &str, kind: &str, src: &str, extra: &str) -> String { | ||
| 21 | format!("{name} = {kind} {{ Inputs = {{ Input = Input {{ SourceOp = \"{src}\", Source = \"Output\", }}, {extra} }}, }},") | ||
| 22 | } | ||
| 23 | |||
| 24 | fn link(port: &str, op: &str) -> String { | ||
| 25 | format!("{port} = Input {{ SourceOp = \"{op}\", Source = \"Output\", }},") | ||
| 26 | } | ||
| 27 | |||
| 28 | fn with_z(name: &str, src: &str) -> String { | ||
| 29 | tool(name, "Dimension.CopyAux", src, "Channel = Input { Value = FuID { \"Z\" }, }, Mode = Input { Value = 1, },") | ||
| 30 | } | ||
| 31 | |||
| 32 | fn render(c: &Comp, name: &str) -> Option<(CachedTexture, Vec<f32>)> { | ||
| 33 | let mut eng = Engine::new_headless().ok()?; | ||
| 34 | let (tex, stats) = eng.evaluate(c, c.find_node(name).expect("find node"), 0.0); | ||
| 35 | assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); | ||
| 36 | let px = eng.readback_rgba_f32(&tex).unwrap(); | ||
| 37 | Some((tex, px)) | ||
| 38 | } | ||
| 39 | |||
| 40 | fn px(buf: &[f32], w: u32, x: u32, y: u32) -> [f32; 4] { | ||
| 41 | let i = ((y * w + x) * 4) as usize; | ||
| 42 | buf[i..i + 4].try_into().unwrap() | ||
| 43 | } | ||
| 44 | |||
| 45 | fn near(got: f32, want: f32, tol: f32, what: &str) { | ||
| 46 | assert!((got - want).abs() <= tol, "{what}: got {got}, want {want} (±{tol})"); | ||
| 47 | } | ||
| 48 | |||
| 49 | const ALPHA: &str = "OutputMode = Input { Value = FuID { \"Alpha\" }, },"; | ||
| 50 | const GREEN: [f32; 4] = [0.1, 0.8, 0.15, 1.0]; | ||
| 51 | const RED: [f32; 4] = [0.9, 0.1, 0.1, 1.0]; | ||
| 52 | const SEMI: [f32; 4] = [0.45, 0.62, 0.4, 1.0]; | ||
| 53 | |||
| 54 | /// Red left half over a green right half (32x16), via a masked Merge. | ||
| 55 | fn split_scene() -> String { | ||
| 56 | [ | ||
| 57 | solid("SplitG", 32, 16, GREEN), | ||
| 58 | solid("SplitR", 32, 16, RED), | ||
| 59 | "SplitMask = RectangleMask { Inputs = { MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 16, }, \ | ||
| 60 | Center = Input { Value = { 0.25, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, }, }," | ||
| 61 | .to_owned(), | ||
| 62 | "Split = Merge { Inputs = { Background = Input { SourceOp = \"SplitG\", Source = \"Output\", }, \ | ||
| 63 | Foreground = Input { SourceOp = \"SplitR\", Source = \"Output\", }, \ | ||
| 64 | EffectMask = Input { SourceOp = \"SplitMask\", Source = \"Mask\", }, }, }," | ||
| 65 | .to_owned(), | ||
| 66 | ] | ||
| 67 | .concat() | ||
| 68 | } | ||
| 69 | |||
| 70 | fn alpha_of(c: &Comp, name: &str, x: u32, y: u32) -> f32 { | ||
| 71 | let (tex, p) = render(c, name).unwrap(); | ||
| 72 | px(&p, tex.size[0], x, y)[3] | ||
| 73 | } | ||
| 74 | |||
| 75 | #[test] | ||
| 76 | fn primatte4_keys_screen_colour_and_keeps_foreground() { | ||
| 77 | let c = comp(&[ | ||
| 78 | solid("Green", 8, 8, GREEN), | ||
| 79 | solid("Red", 8, 8, RED), | ||
| 80 | solid("Skin", 8, 8, [0.8, 0.6, 0.5, 1.0]), | ||
| 81 | solid("Black", 8, 8, [0.0, 0.0, 0.0, 1.0]), | ||
| 82 | solid("Shadow", 8, 8, [0.02, 0.1, 0.03, 1.0]), | ||
| 83 | tool("KeyGreen", "Photron.Primatte4", "Green", ALPHA), | ||
| 84 | tool("KeyRed", "Primatte4", "Red", ALPHA), | ||
| 85 | tool("KeySkin", "Photron.Primatte4", "Skin", ALPHA), | ||
| 86 | tool("KeyBlack", "Photron.Primatte4", "Black", ALPHA), | ||
| 87 | tool("KeyShadow", "Photron.Primatte4", "Shadow", ALPHA), | ||
| 88 | tool("RedAsKey", "Photron.Primatte4", "Red", &format!("{ALPHA} BackgroundColorRed = Input {{ Value = 0.9, }}, BackgroundColorGreen = Input {{ Value = 0.1, }}, BackgroundColorBlue = Input {{ Value = 0.1, }},")), | ||
| 89 | tool("KeyColorRed", "Photron.Primatte4", "Red", &format!("{ALPHA} KeyColorRed = Input {{ Value = 0.9, }}, KeyColorGreen = Input {{ Value = 0.1, }}, KeyColorBlue = Input {{ Value = 0.1, }},")), | ||
| 90 | ].concat()); | ||
| 91 | let Some((tex, p)) = render(&c, "KeyGreen") else { return }; | ||
| 92 | assert_eq!(px(&p, tex.size[0], 3, 3), [0.0, 0.0, 0.0, 0.0], "the default green screen keys fully transparent"); | ||
| 93 | near(alpha_of(&c, "KeyRed", 3, 3), 1.0, 1e-3, "red foreground"); | ||
| 94 | near(alpha_of(&c, "KeySkin", 3, 3), 1.0, 1e-3, "skin foreground"); | ||
| 95 | near(alpha_of(&c, "KeyBlack", 3, 3), 1.0, 1e-3, "black foreground stays opaque"); | ||
| 96 | near(alpha_of(&c, "KeyShadow", 3, 3), 0.0, 1e-3, "a dark screen shadow follows the chroma cone"); | ||
| 97 | near(alpha_of(&c, "RedAsKey", 3, 3), 0.0, 1e-3, "BackgroundColor picks the screen colour"); | ||
| 98 | near(alpha_of(&c, "KeyColorRed", 3, 3), 0.0, 1e-3, "KeyColor picks the screen colour too"); | ||
| 99 | } | ||
| 100 | |||
| 101 | #[test] | ||
| 102 | fn primatte4_fine_tuning_moves_matte_and_spill() { | ||
| 103 | let c = comp(&[ | ||
| 104 | solid("Semi", 8, 8, SEMI), | ||
| 105 | solid("Spill", 8, 8, [0.7, 0.78, 0.5, 1.0]), | ||
| 106 | tool("Base", "Photron.Primatte4", "Semi", ALPHA), | ||
| 107 | tool("CleanBg", "Photron.Primatte4", "Semi", &format!("{ALPHA} CleanBackground = Input {{ Value = 1, }},")), | ||
| 108 | tool("CleanFg", "Photron.Primatte4", "Semi", &format!("{ALPHA} CleanForeground = Input {{ Value = 1, }},")), | ||
| 109 | tool("Sponge", "Photron.Primatte4", "Semi", &format!("{ALPHA} MatteSponge = Input {{ Value = 1, }},")), | ||
| 110 | tool("Restore", "Photron.Primatte4", "Semi", &format!("{ALPHA} MatteRestore = Input {{ Value = 1, }},")), | ||
| 111 | tool("Minus", "Photron.Primatte4", "Semi", &format!("{ALPHA} DetailMinus = Input {{ Value = 1, }},")), | ||
| 112 | tool("Plus", "Photron.Primatte4", "Semi", &format!("{ALPHA} DetailPlus = Input {{ Value = 1, }},")), | ||
| 113 | tool("NoSpill", "Photron.Primatte4", "Spill", "OutputMode = Input { Value = FuID { \"SpillSuppressed\" }, }, SpillSuppression = Input { Value = 0, },"), | ||
| 114 | tool("Spilled", "Photron.Primatte4", "Spill", "OutputMode = Input { Value = FuID { \"SpillSuppressed\" }, }, SpillSuppression = Input { Value = 1, },"), | ||
| 115 | tool("Sponged", "Photron.Primatte4", "Spill", "OutputMode = Input { Value = FuID { \"SpillSuppressed\" }, }, SpillSuppression = Input { Value = 1, }, SpillSponge = Input { Value = 1, },"), | ||
| 116 | ].concat()); | ||
| 117 | let Some(base) = render(&c, "Base").map(|(t, p)| px(&p, t.size[0], 3, 3)[3]) else { return }; | ||
| 118 | assert!(base > 0.2 && base < 0.9, "a mid-way pixel is partially transparent: {base}"); | ||
| 119 | assert!(alpha_of(&c, "CleanBg", 3, 3) < base - 0.1, "CleanBackground widens the transparent core"); | ||
| 120 | assert!(alpha_of(&c, "CleanFg", 3, 3) > base + 0.1, "CleanForeground widens the opaque shell"); | ||
| 121 | assert!(alpha_of(&c, "Sponge", 3, 3) < base - 0.1, "MatteSponge pushes low alpha to transparent"); | ||
| 122 | assert!(alpha_of(&c, "Restore", 3, 3) > base + 0.1, "MatteRestore recovers opacity"); | ||
| 123 | assert!(alpha_of(&c, "Minus", 3, 3) < base - 0.05, "DetailMinus lowers partial alpha"); | ||
| 124 | assert!(alpha_of(&c, "Plus", 3, 3) > base + 0.05, "DetailPlus raises partial alpha"); | ||
| 125 | |||
| 126 | let pixel = |name: &str| { | ||
| 127 | let (t, p) = render(&c, name).unwrap(); | ||
| 128 | px(&p, t.size[0], 3, 3) | ||
| 129 | }; | ||
| 130 | assert_eq!(pixel("NoSpill"), [0.7, 0.78, 0.5, 1.0], "SpillSuppression=0 leaves the colour alone"); | ||
| 131 | let spilled = pixel("Spilled"); | ||
| 132 | assert!(spilled[1] < 0.78 && spilled[0] > 0.7 && spilled[2] > 0.5, "green lean removed, red and blue lifted: {spilled:?}"); | ||
| 133 | near(0.2126 * spilled[0] + 0.7152 * spilled[1] + 0.0722 * spilled[2], 0.2126 * 0.7 + 0.7152 * 0.78 + 0.0722 * 0.5, 0.01, "luminance preserved"); | ||
| 134 | near(spilled[3], 1.0, 1e-4, "SpillSuppressed keeps the source alpha"); | ||
| 135 | assert!(pixel("Sponged")[1] <= spilled[1] + 1e-4, "SpillSponge widens the suppression"); | ||
| 136 | } | ||
| 137 | |||
| 138 | #[test] | ||
| 139 | fn primatte4_output_modes_composite_over_background() { | ||
| 140 | let c = comp(&[ | ||
| 141 | solid("Green", 8, 8, GREEN), | ||
| 142 | solid("Red", 8, 8, RED), | ||
| 143 | solid("Plate", 8, 8, [0.0, 0.0, 1.0, 1.0]), | ||
| 144 | tool("OverGreen", "Photron.Primatte4", "Green", &link("Background", "Plate")), | ||
| 145 | tool("OverRed", "Photron.Primatte4", "Red", &link("Background", "Plate")), | ||
| 146 | tool("NoPlate", "Photron.Primatte4", "Red", ""), | ||
| 147 | tool("Alpha", "Photron.Primatte4", "Red", ALPHA), | ||
| 148 | tool("AlphaNum", "Photron.Primatte4", "Red", "OutputMode = Input { Value = 1, },"), | ||
| 149 | ].concat()); | ||
| 150 | let Some((tex, p)) = render(&c, "OverGreen") else { return }; | ||
| 151 | let w = tex.size[0]; | ||
| 152 | assert_eq!(px(&p, w, 3, 3), [0.0, 0.0, 1.0, 1.0], "the keyed screen shows the Background"); | ||
| 153 | let (_, p) = render(&c, "OverRed").unwrap(); | ||
| 154 | assert_eq!(px(&p, w, 3, 3), [0.9, 0.1, 0.1, 1.0], "an opaque foreground covers the Background"); | ||
| 155 | let (_, p) = render(&c, "NoPlate").unwrap(); | ||
| 156 | assert_eq!(px(&p, w, 3, 3), [0.9, 0.1, 0.1, 1.0], "Composite without a Background is the premultiplied keyed foreground"); | ||
| 157 | let (_, p) = render(&c, "Alpha").unwrap(); | ||
| 158 | assert_eq!(px(&p, w, 3, 3), [1.0; 4], "Alpha mode outputs the matte as grey + alpha"); | ||
| 159 | let (_, p) = render(&c, "AlphaNum").unwrap(); | ||
| 160 | assert_eq!(px(&p, w, 3, 3), [1.0; 4], "OutputMode also takes the combo index"); | ||
| 161 | } | ||
| 162 | |||
| 163 | #[test] | ||
| 164 | fn primatte4_auto_compute_finds_the_screen() { | ||
| 165 | let c = comp(&[ | ||
| 166 | solid("BlueScreen", 16, 16, [0.1, 0.2, 0.9, 1.0]), | ||
| 167 | tool("Manual", "Photron.Primatte4", "BlueScreen", ALPHA), | ||
| 168 | tool("Auto", "Photron.Primatte4", "BlueScreen", &format!("{ALPHA} AutoCompute = Input {{ Value = 1, }},")), | ||
| 169 | ].concat()); | ||
| 170 | let Some(manual) = render(&c, "Manual").map(|(t, p)| px(&p, t.size[0], 8, 8)[3]) else { return }; | ||
| 171 | near(manual, 1.0, 1e-3, "a blue screen survives the default green key"); | ||
| 172 | near(alpha_of(&c, "Auto", 8, 8), 0.0, 1e-3, "AutoCompute keys the dominant screen colour"); | ||
| 173 | } | ||
| 174 | |||
| 175 | #[test] | ||
| 176 | fn primatte4_garbage_and_solid_mattes() { | ||
| 177 | let c = comp(&[ | ||
| 178 | solid("Green", 8, 8, GREEN), | ||
| 179 | solid("Red", 8, 8, RED), | ||
| 180 | solid("Opaque", 8, 8, [1.0, 1.0, 1.0, 1.0]), | ||
| 181 | solid("Clear", 8, 8, [0.0, 0.0, 0.0, 0.0]), | ||
| 182 | tool("Garbage", "Photron.Primatte4", "Red", &format!("{ALPHA}{}", link("GarbageMatte", "Opaque"))), | ||
| 183 | tool("GarbageClear", "Photron.Primatte4", "Red", &format!("{ALPHA}{}", link("GarbageMatte", "Clear"))), | ||
| 184 | tool("Solid", "Photron.Primatte4", "Green", &format!("{ALPHA}{}", link("SolidMatte", "Opaque"))), | ||
| 185 | tool("SolidClear", "Photron.Primatte4", "Green", &format!("{ALPHA}{}", link("SolidMatte", "Clear"))), | ||
| 186 | ].concat()); | ||
| 187 | let Some(garbage) = render(&c, "Garbage").map(|(t, p)| px(&p, t.size[0], 3, 3)[3]) else { return }; | ||
| 188 | near(garbage, 0.0, 1e-3, "a white garbage matte removes the foreground"); | ||
| 189 | near(alpha_of(&c, "GarbageClear", 3, 3), 1.0, 1e-3, "an empty garbage matte changes nothing"); | ||
| 190 | near(alpha_of(&c, "Solid", 3, 3), 1.0, 1e-3, "a solid matte forces opacity over the screen"); | ||
| 191 | near(alpha_of(&c, "SolidClear", 3, 3), 0.0, 1e-3, "an empty solid matte changes nothing"); | ||
| 192 | } | ||
| 193 | |||
| 194 | #[test] | ||
| 195 | fn primatte4_matte_blur_contract_expand_and_deartifacting() { | ||
| 196 | let c = comp(&[ | ||
| 197 | split_scene(), | ||
| 198 | tool("Edge", "Photron.Primatte4", "Split", ALPHA), | ||
| 199 | tool("Blur", "Photron.Primatte4", "Split", &format!("{ALPHA} MatteBlur = Input {{ Value = 4, }},")), | ||
| 200 | tool("Contract", "Photron.Primatte4", "Split", &format!("{ALPHA} MatteContractExpand = Input {{ Value = -4, }},")), | ||
| 201 | tool("Expand", "Photron.Primatte4", "Split", &format!("{ALPHA} MatteContractExpand = Input {{ Value = 4, }},")), | ||
| 202 | tool("Clean", "Photron.Primatte4", "Split", &format!("{ALPHA} Deartifacting = Input {{ Value = 1, }},")), | ||
| 203 | ].concat()); | ||
| 204 | let at = |name: &str, x: u32| alpha_of(&c, name, x, 8); | ||
| 205 | let Some(edge_in) = render(&c, "Edge").map(|(t, p)| px(&p, t.size[0], 14, 8)[3]) else { return }; | ||
| 206 | near(edge_in, 1.0, 1e-3, "hard edge: opaque left"); | ||
| 207 | near(at("Edge", 17), 0.0, 1e-3, "hard edge: transparent right"); | ||
| 208 | let (blur_in, blur_out) = (at("Blur", 14), at("Blur", 17)); | ||
| 209 | assert!(blur_in < 0.95 && blur_out > 0.05, "MatteBlur softens both sides of the edge: {blur_in} {blur_out}"); | ||
| 210 | assert!(at("Contract", 14) < 0.5 && at("Contract", 2) > 0.99, "negative MatteContractExpand erodes the foreground"); | ||
| 211 | assert!(at("Expand", 17) > 0.5 && at("Expand", 28) < 0.01, "positive MatteContractExpand grows the foreground"); | ||
| 212 | near(at("Clean", 2), 1.0, 1e-3, "Deartifacting leaves solid regions alone"); | ||
| 213 | near(at("Clean", 28), 0.0, 1e-3, "Deartifacting leaves solid regions alone"); | ||
| 214 | } | ||
| 215 | |||
| 216 | #[test] | ||
| 217 | fn primatte4_blend_mask_process_and_missing_input() { | ||
| 218 | let c = comp(&[ | ||
| 219 | split_scene(), | ||
| 220 | solid("Red", 32, 16, RED), | ||
| 221 | "Free = Photron.Primatte4 { },".to_owned(), | ||
| 222 | tool("Off", "Photron.Primatte4", "Red", "Blend = Input { Value = 0, },"), | ||
| 223 | tool("Half", "Photron.Primatte4", "Red", "Blend = Input { Value = 0.5, }, OutputMode = Input { Value = FuID { \"Alpha\" }, },"), | ||
| 224 | tool("SkipAlpha", "Photron.Primatte4", "SplitG", &format!("{ALPHA} ProcessAlpha = Input {{ Value = 0, }},")), | ||
| 225 | tool("Masked", "Photron.Primatte4", "SplitG", &format!("{ALPHA} {}", link("EffectMask", "SplitMask").replace("\"Output\"", "\"Mask\""))), | ||
| 226 | tool("Mult", "Photron.Primatte4", "SplitR", &format!("{ALPHA} MultiplyByMask = Input {{ Value = 1, }}, {}", link("EffectMask", "SplitMask").replace("\"Output\"", "\"Mask\""))), | ||
| 227 | ].concat()); | ||
| 228 | let Some((tex, p)) = render(&c, "Off") else { return }; | ||
| 229 | assert_eq!(px(&p, tex.size[0], 3, 3), RED, "Blend=0 returns the input"); | ||
| 230 | let (_, p) = render(&c, "Half").unwrap(); | ||
| 231 | near(px(&p, 32, 3, 3)[0], (0.9 + 1.0) / 2.0, 1e-3, "Blend=0.5 mixes the source with the keyed result"); | ||
| 232 | assert_eq!(render(&c, "Free").unwrap().0.size, [1, 1], "no input renders the placeholder"); | ||
| 233 | let (_, p) = render(&c, "SkipAlpha").unwrap(); | ||
| 234 | near(px(&p, 32, 3, 3)[3], 1.0, 1e-3, "ProcessAlpha=0 keeps the source alpha over the keyed screen"); | ||
| 235 | let (_, p) = render(&c, "Masked").unwrap(); | ||
| 236 | near(px(&p, 32, 4, 8)[0], 0.0, 1e-3, "inside the EffectMask the key applies"); | ||
| 237 | near(px(&p, 32, 28, 8)[0], GREEN[0], 1e-3, "outside the EffectMask the source stays"); | ||
| 238 | let (_, p) = render(&c, "Mult").unwrap(); | ||
| 239 | assert_eq!(px(&p, 32, 28, 8), [0.0; 4], "MultiplyByMask zeroes outside the mask"); | ||
| 240 | assert_eq!(px(&p, 32, 4, 8), [1.0; 4], "inside the mask the opaque foreground matte remains"); | ||
| 241 | } | ||
| 242 | |||
| 243 | #[test] | ||
| 244 | fn profiler_run_command_and_external_matte_saver_are_lossless_passthroughs() { | ||
| 245 | let c = comp(&[ | ||
| 246 | solid("Src", 16, 16, [0.2, 0.4, 0.6, 1.0]), | ||
| 247 | solid("Hdr", 16, 16, [3.5, -0.25, 0.75, 0.5]), | ||
| 248 | with_z("Deep", "Src"), | ||
| 249 | tool("Prof", "Profiler", "Deep", ""), | ||
| 250 | tool("Run", "RunCommand", "Deep", "Command = Input { Value = \"touch /tmp/fission_run_command_must_not_exist\", }, Mode = Input { Value = 1, },"), | ||
| 251 | tool("Matte", "Fuse.ExternalMatteSaver", "Deep", "Filename = Input { Value = \"/tmp/fission_matte_saver_must_not_exist.exr\", },"), | ||
| 252 | tool("RunHdr", "RunCommand", "Hdr", ""), | ||
| 253 | tool("ProfHdr", "Profiler", "Hdr", ""), | ||
| 254 | tool("MatteHdr", "Fuse.ExternalMatteSaver", "Hdr", ""), | ||
| 255 | "Free = Profiler { }, FreeRun = RunCommand { }, FreeMatte = Fuse.ExternalMatteSaver { },".to_owned(), | ||
| 256 | ].concat()); | ||
| 257 | let Some((deep, deep_px)) = render(&c, "Deep") else { return }; | ||
| 258 | for name in ["Prof", "Run", "Matte"] { | ||
| 259 | let (t, p) = render(&c, name).unwrap(); | ||
| 260 | assert_eq!(p, deep_px, "{name} pixels"); | ||
| 261 | assert_eq!((t.origin, t.canvas_size, t.depth), (deep.origin, deep.canvas_size, deep.depth), "{name} DoD/depth"); | ||
| 262 | assert!(t.aux.as_ref().is_some_and(|a| a.z.is_some()), "{name} keeps aux.z"); | ||
| 263 | } | ||
| 264 | let (_, hdr_px) = render(&c, "Hdr").unwrap(); | ||
| 265 | for name in ["ProfHdr", "RunHdr", "MatteHdr"] { | ||
| 266 | let (t, p) = render(&c, name).unwrap(); | ||
| 267 | assert_eq!(p, hdr_px, "{name} keeps out-of-range float values"); | ||
| 268 | assert!(t.depth.is_float(), "{name} stays float"); | ||
| 269 | } | ||
| 270 | assert_eq!(px(&hdr_px, 16, 4, 4), [3.5, -0.25, 0.75, 0.5]); | ||
| 271 | for name in ["Free", "FreeRun", "FreeMatte"] { | ||
| 272 | assert_eq!(render(&c, name).unwrap().0.size, [1, 1], "{name} disconnected"); | ||
| 273 | } | ||
| 274 | assert!(!std::path::Path::new("/tmp/fission_run_command_must_not_exist").exists(), "RunCommand never executes its command"); | ||
| 275 | assert!(!std::path::Path::new("/tmp/fission_matte_saver_must_not_exist.exr").exists(), "ExternalMatteSaver never writes files"); | ||
| 276 | } | ||
crates/engine/src/shaders/deep_flow.wgsl+67-79| ... | @@ -108,15 +108,12 @@ fn apply_channel_blend( | ... | @@ -108,15 +108,12 @@ fn apply_channel_blend( |
| 108 | skip: vec4<f32>, | 108 | skip: vec4<f32>, |
| 109 | ) -> vec4<f32> { | 109 | ) -> vec4<f32> { |
| 110 | var out_c = mix(orig, effect, eff); | 110 | var out_c = mix(orig, effect, eff); |
| 111 | var kept = orig; | ||
| 111 | if (mbm > 0.5) { | 112 | if (mbm > 0.5) { |
| 112 | out_c = out_c * mask_v; | 113 | out_c = out_c * mask_v; |
| 114 | kept = vec4<f32>(0.0); | ||
| 113 | } | 115 | } |
| 114 | return vec4<f32>( | 116 | return select(out_c, kept, skip > vec4<f32>(0.5)); |
| 115 | select(out_c.r, orig.r, skip.x > 0.5), | ||
| 116 | select(out_c.g, orig.g, skip.y > 0.5), | ||
| 117 | select(out_c.b, orig.b, skip.z > 0.5), | ||
| 118 | select(out_c.a, orig.a, skip.w > 0.5), | ||
| 119 | ); | ||
| 120 | } | 117 | } |
| 121 | 118 | ||
| 122 | // Shared Blend / EffectMask / MultiplyByMask / Process{R,G,B,A} tail of every kernel. | 119 | // Shared Blend / EffectMask / MultiplyByMask / Process{R,G,B,A} tail of every kernel. |
| ... | @@ -379,79 +376,56 @@ fn ssao_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ... | @@ -379,79 +376,56 @@ fn ssao_op(@builtin(global_invocation_id) gid: vec3<u32>) { |
| 379 | } | 376 | } |
| 380 | 377 | ||
| 381 | // ---------------------------------------------------------------------------- | 378 | // ---------------------------------------------------------------------------- |
| 382 | // Shader (deep-pixel relighting). src_a = albedo, src_b = aux.z, src_c = aux.normal, src_d = equirect map | 379 | // Shader. src_a = premultiplied image, src_c = aux.normal, src_d = EnvironmentReflectionMap. |
| 383 | // Lighting runs in y-up pixel space with +Z toward the viewer. | 380 | // p[0] = (ambient, diffuse, specular, reflection), p[1] = (has_map, has_normal, reflection_type, 0) |
| 384 | // p[0] = (light_type 0 dir / 1 point / 2 spot, ambient, diffuse, specular) | 381 | // p[2].xyz = direction to the light, p[3].xyz = specular colour |
| 385 | // p[1] = (spec_exponent, reflectivity, has_map, has_normal) | 382 | // Without normals nothing faces the light: only the ambient term remains. |
| 386 | // p[2].xyz = light direction-to-light (directional) or light position (point/spot) | ||
| 387 | // p[3] = (spot axis xyz pointing away from the light, cos_cone), p[4] = (light rgb, spot_softness) | ||
| 388 | // p[5] = (z_scale, bump_height, has_z, 0) | ||
| 389 | // ---------------------------------------------------------------------------- | 383 | // ---------------------------------------------------------------------------- |
| 390 | fn relight_height(p_in: vec2<i32>, dims: vec2<i32>) -> f32 { | 384 | const SPEC_EXPONENT: f32 = 32.0; |
| 391 | let c = clamp(p_in, vec2<i32>(0), dims - vec2<i32>(1)); | ||
| 392 | if (u.p[5].z > 0.5) { | ||
| 393 | let z = textureLoad(src_b, c, 0).r; | ||
| 394 | return select(0.0, clamp(z, -1.0e6, 1.0e6) * u.p[5].x, z_valid(z)); | ||
| 395 | } | ||
| 396 | return dot(textureLoad(src_a, c, 0).rgb, LUMA_W) * u.p[5].y; | ||
| 397 | } | ||
| 398 | 385 | ||
| 399 | @compute @workgroup_size(8, 8, 1) | 386 | @compute @workgroup_size(8, 8, 1) |
| 400 | fn relight_op(@builtin(global_invocation_id) gid: vec3<u32>) { | 387 | fn relight_op(@builtin(global_invocation_id) gid: vec3<u32>) { |
| 401 | let dims = textureDimensions(dst_tex); | 388 | let dims = textureDimensions(dst_tex); |
| 402 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | 389 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } |
| 403 | let p = vec2<i32>(gid.xy); | 390 | let p = vec2<i32>(gid.xy); |
| 404 | let idims = vec2<i32>(dims); | ||
| 405 | let src = textureLoad(src_a, p, 0); | 391 | let src = textureLoad(src_a, p, 0); |
| 406 | 392 | var lit = src.rgb * u.p[0].x; | |
| 407 | let h = relight_height(p, idims); | 393 | if (u.p[1].y > 0.5) { |
| 408 | var n = vec3<f32>(0.0, 0.0, 1.0); | 394 | var n = textureLoad(src_c, p, 0).xyz; |
| 409 | var have_n = false; | 395 | if (dot(n, n) > 1.0e-6) { |
| 410 | if (u.p[1].w > 0.5) { | 396 | n = normalize(n); |
| 411 | let nr = textureLoad(src_c, p, 0).xyz; | 397 | if (n.z < 0.0) { n = -n; } |
| 412 | if (dot(nr, nr) > 1.0e-6) { | 398 | let l = normalize(u.p[2].xyz); |
| 413 | n = normalize(nr); | 399 | let v = vec3<f32>(0.0, 0.0, 1.0); |
| 414 | have_n = true; | 400 | let ndl = max(dot(n, l), 0.0); |
| 415 | } | 401 | let spec = pow(max(dot(n, normalize(l + v)), 0.0), SPEC_EXPONENT) * select(0.0, 1.0, ndl > 0.0); |
| 416 | } | 402 | lit = src.rgb * (u.p[0].x + u.p[0].y * ndl) + u.p[3].xyz * (u.p[0].z * spec * src.a); |
| 417 | if (!have_n) { | 403 | if (u.p[1].x > 0.5) { |
| 418 | let dhdx = (relight_height(p + vec2<i32>(1, 0), idims) - relight_height(p + vec2<i32>(-1, 0), idims)) * 0.5; | 404 | var uv = vec2<f32>(n.x * 0.5 + 0.5, 0.5 - n.y * 0.5); |
| 419 | let dhdy_up = (relight_height(p + vec2<i32>(0, -1), idims) - relight_height(p + vec2<i32>(0, 1), idims)) * 0.5; | 405 | if (u.p[1].z > 1.5) { |
| 420 | n = normalize(vec3<f32>(-dhdx, -dhdy_up, 1.0)); | 406 | let t = refract(-v, n, 1.0 / 1.5); |
| 421 | } | 407 | uv = vec2<f32>(t.x * 0.5 + 0.5, 0.5 - t.y * 0.5); |
| 422 | if (n.z < 0.0) { n = -n; } | 408 | } else if (u.p[1].z > 0.5) { |
| 423 | 409 | let r = 2.0 * n.z * n - v; | |
| 424 | let light_type = i32(u.p[0].x + 0.5); | 410 | uv = vec2<f32>(fract(atan2(r.x, r.z) / TAU + 0.5), acos(clamp(r.y, -1.0, 1.0)) / PI); |
| 425 | var l = u.p[2].xyz; | 411 | } |
| 426 | var atten = 1.0; | 412 | lit = lit + sample_bilinear_clamped(src_d, uv).rgb * (u.p[0].w * src.a); |
| 427 | if (light_type > 0) { | 413 | } |
| 428 | let pos = vec3<f32>(f32(p.x) + 0.5, f32(idims.y) - (f32(p.y) + 0.5), h); | ||
| 429 | let to_light = u.p[2].xyz - pos; | ||
| 430 | l = normalize(to_light); | ||
| 431 | if (light_type == 2) { | ||
| 432 | let cos_a = dot(-l, normalize(u.p[3].xyz)); | ||
| 433 | atten = smoothstep(u.p[3].w, u.p[3].w + max(u.p[4].w, 1.0e-4), cos_a); | ||
| 434 | } | 414 | } |
| 435 | } | 415 | } |
| 436 | let v = vec3<f32>(0.0, 0.0, 1.0); | 416 | let mask_v = read_mask(gid.xy, dims, u.p[15].y, u.p[15].z); |
| 437 | let ndl = max(dot(n, l), 0.0) * atten; | 417 | var out_c = apply_channel_blend(src, vec4<f32>(lit, src.a), u.p[15].x * mask_v, mask_v, u.p[15].w, u.p[14]); |
| 438 | let hv = normalize(l + v); | 418 | if (!HDR_FLOAT) { |
| 439 | let spec = pow(max(dot(n, hv), 0.0), max(u.p[1].x, 1.0)) * atten * select(0.0, 1.0, ndl > 0.0); | 419 | // Fusion's 8-bit lighting truncates instead of rounding. |
| 440 | let light_rgb = u.p[4].xyz; | 420 | out_c = floor(out_c * 255.0 + 1.0e-3) / 255.0; |
| 441 | |||
| 442 | var lit = src.rgb * (u.p[0].y + u.p[0].z * ndl * light_rgb) + vec3<f32>(u.p[0].w * spec) * light_rgb; | ||
| 443 | if (u.p[1].z > 0.5) { | ||
| 444 | let r = 2.0 * dot(n, v) * n - v; | ||
| 445 | let uv = vec2<f32>(atan2(r.x, r.z) / TAU + 0.5, acos(clamp(r.y, -1.0, 1.0)) / PI); | ||
| 446 | let env = sample_bilinear_clamped(src_d, vec2<f32>(fract(uv.x), uv.y)).rgb; | ||
| 447 | lit = lit + env * u.p[1].y; | ||
| 448 | } | 421 | } |
| 449 | finish(gid.xy, dims, src, vec4<f32>(lit, src.a)); | 422 | store_dst(p, out_c); |
| 450 | } | 423 | } |
| 451 | 424 | ||
| 452 | // ---------------------------------------------------------------------------- | 425 | // ---------------------------------------------------------------------------- |
| 453 | // Texture (UV remap). src_a = image whose RG channels carry UV (A = coverage), src_b = texture | 426 | // Texture (UV remap). src_a = image whose RG channels carry UV (A = coverage), src_b = texture. |
| 454 | // p[0] = (u_scale, v_scale, u_offset, v_offset), p[1].x = edge mode | 427 | // uv = swap -> scale & offset (u * scale - offset) -> rotate 90 -> flip. |
| 428 | // p[0] = (u_scale, v_scale, u_offset, v_offset), p[1] = (edge mode, has_texture, swap_uv, rotate_90), p[2] = (flip_h, flip_v, 0, 0) | ||
| 455 | // ---------------------------------------------------------------------------- | 429 | // ---------------------------------------------------------------------------- |
| 456 | @compute @workgroup_size(8, 8, 1) | 430 | @compute @workgroup_size(8, 8, 1) |
| 457 | fn texture_op(@builtin(global_invocation_id) gid: vec3<u32>) { | 431 | fn texture_op(@builtin(global_invocation_id) gid: vec3<u32>) { |
| ... | @@ -459,7 +433,16 @@ fn texture_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ... | @@ -459,7 +433,16 @@ fn texture_op(@builtin(global_invocation_id) gid: vec3<u32>) { |
| 459 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | 433 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } |
| 460 | let p = vec2<i32>(gid.xy); | 434 | let p = vec2<i32>(gid.xy); |
| 461 | let src = textureLoad(src_a, p, 0); | 435 | let src = textureLoad(src_a, p, 0); |
| 462 | let uv = vec2<f32>(src.r * u.p[0].x + u.p[0].z, src.g * u.p[0].y + u.p[0].w); | 436 | if (u.p[1].y < 0.5) { |
| 437 | finish(gid.xy, dims, src, src); | ||
| 438 | return; | ||
| 439 | } | ||
| 440 | var uv = src.rg; | ||
| 441 | if (u.p[1].z > 0.5) { uv = uv.yx; } | ||
| 442 | uv = uv * u.p[0].xy - u.p[0].zw; | ||
| 443 | if (u.p[1].w > 0.5) { uv = vec2<f32>(uv.y, 1.0 - uv.x); } | ||
| 444 | if (u.p[2].x > 0.5) { uv.x = 1.0 - uv.x; } | ||
| 445 | if (u.p[2].y > 0.5) { uv.y = 1.0 - uv.y; } | ||
| 463 | let tdims = vec2<f32>(textureDimensions(src_b)); | 446 | let tdims = vec2<f32>(textureDimensions(src_b)); |
| 464 | // UV v = 0 is the bottom row of the texture. | 447 | // UV v = 0 is the bottom row of the texture. |
| 465 | let pos = vec2<f32>(uv.x * tdims.x, (1.0 - uv.y) * tdims.y); | 448 | let pos = vec2<f32>(uv.x * tdims.x, (1.0 - uv.y) * tdims.y); |
| ... | @@ -494,8 +477,9 @@ fn vector_warp_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ... | @@ -494,8 +477,9 @@ fn vector_warp_op(@builtin(global_invocation_id) gid: vec3<u32>) { |
| 494 | } | 477 | } |
| 495 | 478 | ||
| 496 | // ---------------------------------------------------------------------------- | 479 | // ---------------------------------------------------------------------------- |
| 497 | // VectorTransform. src_a = vector texel (aux vector or colour RG); only .xy is transformed. | 480 | // VectorTransform. src_a = aux vector texel; only .xy is transformed: smooth, then scale and rotate, |
| 498 | // p[0] = (x_scale, y_scale, cos, sin), p[1] = (x_offset, y_offset, flip_x, flip_y), p[2] = (invert, normalize, 0, 0) | 481 | // mixed in by the attenuation. |
| 482 | // p[0] = (x_size, y_size, cos, sin), p[1] = (attenuate, smooth_radius_px, 0, 0) | ||
| 499 | // ---------------------------------------------------------------------------- | 483 | // ---------------------------------------------------------------------------- |
| 500 | @compute @workgroup_size(8, 8, 1) | 484 | @compute @workgroup_size(8, 8, 1) |
| 501 | fn vector_transform_op(@builtin(global_invocation_id) gid: vec3<u32>) { | 485 | fn vector_transform_op(@builtin(global_invocation_id) gid: vec3<u32>) { |
| ... | @@ -503,18 +487,22 @@ fn vector_transform_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ... | @@ -503,18 +487,22 @@ fn vector_transform_op(@builtin(global_invocation_id) gid: vec3<u32>) { |
| 503 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | 487 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } |
| 504 | let p = vec2<i32>(gid.xy); | 488 | let p = vec2<i32>(gid.xy); |
| 505 | let src = textureLoad(src_a, p, 0); | 489 | let src = textureLoad(src_a, p, 0); |
| 506 | var v = vec2<f32>(clean(src.x, 65504.0), clean(src.y, 65504.0)); | 490 | let idims = vec2<i32>(dims); |
| 507 | if (u.p[1].z > 0.5) { v.x = -v.x; } | 491 | let r = i32(round(u.p[1].y)); |
| 508 | if (u.p[1].w > 0.5) { v.y = -v.y; } | 492 | var v = vec2<f32>(0.0); |
| 509 | if (u.p[2].x > 0.5) { v = -v; } | 493 | var weight = 0.0; |
| 510 | if (u.p[2].y > 0.5) { | 494 | for (var dy = -1; dy <= 1; dy = dy + 1) { |
| 511 | let len = length(v); | 495 | for (var dx = -1; dx <= 1; dx = dx + 1) { |
| 512 | v = select(vec2<f32>(0.0), v / len, len > 1.0e-6); | 496 | let q = clamp(p + vec2<i32>(dx, dy) * r, vec2<i32>(0), idims - vec2<i32>(1)); |
| 497 | let t = textureLoad(src_a, q, 0); | ||
| 498 | v = v + vec2<f32>(clean(t.x, 65504.0), clean(t.y, 65504.0)); | ||
| 499 | weight = weight + 1.0; | ||
| 500 | } | ||
| 513 | } | 501 | } |
| 514 | v = v * u.p[0].xy; | 502 | v = select(vec2<f32>(clean(src.x, 65504.0), clean(src.y, 65504.0)), v / weight, r > 0); |
| 515 | v = vec2<f32>(u.p[0].z * v.x - u.p[0].w * v.y, u.p[0].w * v.x + u.p[0].z * v.y); | 503 | let scaled = v * u.p[0].xy; |
| 516 | v = v + u.p[1].xy; | 504 | let rotated = vec2<f32>(u.p[0].z * scaled.x - u.p[0].w * scaled.y, u.p[0].w * scaled.x + u.p[0].z * scaled.y); |
| 517 | finish(gid.xy, dims, src, vec4<f32>(v, src.z, src.w)); | 505 | finish(gid.xy, dims, src, vec4<f32>(mix(v, rotated, u.p[1].x), src.z, src.w)); |
| 518 | } | 506 | } |
| 519 | 507 | ||
| 520 | // ---------------------------------------------------------------------------- | 508 | // ---------------------------------------------------------------------------- |
crates/engine/src/shaders/primatte_misc.wgsl created+236| ... | @@ -0,0 +1,236 @@ | ||
| 1 | // Photron.Primatte4 compute shader: polyhedral chroma-space keyer. | ||
| 2 | // | ||
| 3 | // WebGPU-safe (`wasm32` compatible): every texture input is `filterable: false` and read via | ||
| 4 | // `textureLoad`; the output is a WriteOnly storage texture (format patched at pipeline build); | ||
| 5 | // no `read_write` storage textures. | ||
| 6 | // | ||
| 7 | // Bindings: tex_a = foreground, tex_b = Background, tex_c = GarbageMatte, tex_d = SolidMatte, mask_tex = EffectMask. | ||
| 8 | // | ||
| 9 | // p[0] = (key rgb, auto_compute) | ||
| 10 | // p[1] = (clean_background, clean_foreground, matte_sponge, matte_restore) | ||
| 11 | // p[2] = (spill_sponge, detail_minus, detail_plus, spill_suppression) | ||
| 12 | // p[3] = (deartifacting, matte_blur_px, contract_expand_px, output_mode: 0 composite / 1 alpha / 2 spill suppressed) | ||
| 13 | // p[4] = (has_background, has_garbage, has_solid, 0) | ||
| 14 | // p[14] = (blend, has_mask, mask_invert, multiply_by_mask), p[15] = per-channel skip (1 = keep source) | ||
| 15 | |||
| 16 | @group(0) @binding(0) var tex_a: texture_2d<f32>; | ||
| 17 | @group(0) @binding(1) var tex_b: texture_2d<f32>; | ||
| 18 | @group(0) @binding(2) var tex_c: texture_2d<f32>; | ||
| 19 | @group(0) @binding(3) var tex_d: texture_2d<f32>; | ||
| 20 | @group(0) @binding(4) var mask_tex: texture_2d<f32>; | ||
| 21 | @group(0) @binding(5) var dst_tex: texture_storage_2d<rgba8unorm, write>; | ||
| 22 | |||
| 23 | struct Params { | ||
| 24 | p: array<vec4<f32>, 16>, | ||
| 25 | }; | ||
| 26 | @group(0) @binding(6) var<uniform> u: Params; | ||
| 27 | |||
| 28 | const HDR_FLOAT: bool = false; | ||
| 29 | const LUMA_709: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722); | ||
| 30 | const TAU: f32 = 6.283185307179586; | ||
| 31 | // Orthonormal basis of the chroma plane (perpendicular to the grey axis). | ||
| 32 | const CHROMA_E1: vec3<f32> = vec3<f32>(0.8164966, -0.4082483, -0.4082483); | ||
| 33 | const CHROMA_E2: vec3<f32> = vec3<f32>(0.0, 0.7071068, -0.7071068); | ||
| 34 | // Polyhedron radii (in key-chroma units) at zero `Clean*` adjustment. | ||
| 35 | const BASE_INNER: f32 = 0.35; | ||
| 36 | const BASE_OUTER: f32 = 0.85; | ||
| 37 | const AUTO_GRID: i32 = 5; | ||
| 38 | |||
| 39 | fn store_dst(p: vec2<i32>, col: vec4<f32>) { | ||
| 40 | if (HDR_FLOAT) { | ||
| 41 | textureStore(dst_tex, p, col); | ||
| 42 | } else { | ||
| 43 | textureStore(dst_tex, p, clamp(col, vec4<f32>(0.0), vec4<f32>(1.0))); | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 47 | fn load_clamped(tex: texture_2d<f32>, p: vec2<i32>) -> vec4<f32> { | ||
| 48 | let dims = vec2<i32>(textureDimensions(tex)); | ||
| 49 | return textureLoad(tex, clamp(p, vec2<i32>(0), max(dims - vec2<i32>(1), vec2<i32>(0))), 0); | ||
| 50 | } | ||
| 51 | |||
| 52 | fn sample_bilinear(tex: texture_2d<f32>, uv: vec2<f32>) -> vec4<f32> { | ||
| 53 | let dims = vec2<i32>(textureDimensions(tex)); | ||
| 54 | let max_c = max(dims - vec2<i32>(1), vec2<i32>(0)); | ||
| 55 | let f = clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0)) * vec2<f32>(dims) - vec2<f32>(0.5); | ||
| 56 | let i0 = clamp(vec2<i32>(floor(f)), vec2<i32>(0), max_c); | ||
| 57 | let i1 = clamp(i0 + vec2<i32>(1), vec2<i32>(0), max_c); | ||
| 58 | let t = clamp(f - floor(f), vec2<f32>(0.0), vec2<f32>(1.0)); | ||
| 59 | let c00 = textureLoad(tex, i0, 0); | ||
| 60 | let c10 = textureLoad(tex, vec2<i32>(i1.x, i0.y), 0); | ||
| 61 | let c01 = textureLoad(tex, vec2<i32>(i0.x, i1.y), 0); | ||
| 62 | let c11 = textureLoad(tex, i1, 0); | ||
| 63 | return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); | ||
| 64 | } | ||
| 65 | |||
| 66 | fn read_mask(gid: vec2<u32>, dims: vec2<u32>) -> f32 { | ||
| 67 | if (u.p[14].y < 0.5) { | ||
| 68 | return 1.0; | ||
| 69 | } | ||
| 70 | let m = sample_bilinear(mask_tex, (vec2<f32>(gid) + vec2<f32>(0.5)) / vec2<f32>(dims)).a; | ||
| 71 | return select(m, 1.0 - m, u.p[14].z > 0.5); | ||
| 72 | } | ||
| 73 | |||
| 74 | /// Blend `res` over `src` by `Blend * EffectMask`; `MultiplyByMask` zeroes outside the mask. | ||
| 75 | fn finish(src: vec4<f32>, res: vec4<f32>, gid: vec2<u32>, dims: vec2<u32>) -> vec4<f32> { | ||
| 76 | let m = clamp(read_mask(gid, dims) * u.p[14].x, 0.0, 1.0); | ||
| 77 | let use_mbm = u.p[14].y > 0.5 && u.p[14].w > 0.5; | ||
| 78 | let out_col = select(mix(src, res, m), res * m, use_mbm); | ||
| 79 | let unproc = select(src, vec4<f32>(0.0), use_mbm); | ||
| 80 | return select(out_col, unproc, u.p[15] > vec4<f32>(0.5)); | ||
| 81 | } | ||
| 82 | |||
| 83 | fn chroma_plane(c: vec3<f32>) -> vec2<f32> { | ||
| 84 | return vec2<f32>(dot(c, CHROMA_E1), dot(c, CHROMA_E2)); | ||
| 85 | } | ||
| 86 | |||
| 87 | /// Chroma scaled by the brightest channel: a key-coloured shadow keeps the key's coordinates (the chroma cone). | ||
| 88 | fn cone_chroma(c: vec3<f32>) -> vec2<f32> { | ||
| 89 | return chroma_plane(c) / max(max(c.r, max(c.g, c.b)), 1.0e-3); | ||
| 90 | } | ||
| 91 | |||
| 92 | /// Regular-hexagon norm, vertices on the x axis: the cross-section of the polyhedron around the key axis. | ||
| 93 | fn hex_norm(v: vec2<f32>) -> f32 { | ||
| 94 | let a = abs(v); | ||
| 95 | return max(0.8660254 * a.x + 0.5 * a.y, a.y); | ||
| 96 | } | ||
| 97 | |||
| 98 | struct Key { | ||
| 99 | rgb: vec3<f32>, | ||
| 100 | cone: vec2<f32>, | ||
| 101 | axis: vec2<f32>, | ||
| 102 | inv_mag: f32, | ||
| 103 | } | ||
| 104 | |||
| 105 | fn make_key(rgb: vec3<f32>) -> Key { | ||
| 106 | let cone = cone_chroma(rgb); | ||
| 107 | let mag = max(length(cone), 1.0e-3); | ||
| 108 | return Key(rgb, cone, cone / mag, 1.0 / mag); | ||
| 109 | } | ||
| 110 | |||
| 111 | /// Distance of `c` from the key in key-chroma units: 0 on the key colour, ~1 for a neutral grey. | ||
| 112 | fn key_distance(c: vec3<f32>, k: Key) -> f32 { | ||
| 113 | let d = cone_chroma(c) - k.cone; | ||
| 114 | return hex_norm(vec2<f32>(dot(d, k.axis), dot(d, vec2<f32>(-k.axis.y, k.axis.x)))) * k.inv_mag; | ||
| 115 | } | ||
| 116 | |||
| 117 | /// Auto-detected key: the average of the grid samples near the most key-like (saturated) one. | ||
| 118 | fn auto_key(dims: vec2<i32>) -> vec3<f32> { | ||
| 119 | var best = vec3<f32>(0.0, 1.0, 0.0); | ||
| 120 | var best_sat = -1.0; | ||
| 121 | for (var j = 0; j < AUTO_GRID; j = j + 1) { | ||
| 122 | for (var i = 0; i < AUTO_GRID; i = i + 1) { | ||
| 123 | let c = load_clamped(tex_a, (vec2<i32>(i, j) * 2 + vec2<i32>(1)) * dims / (2 * AUTO_GRID)).rgb; | ||
| 124 | let sat = length(chroma_plane(c)); | ||
| 125 | if (sat > best_sat) { | ||
| 126 | best_sat = sat; | ||
| 127 | best = c; | ||
| 128 | } | ||
| 129 | } | ||
| 130 | } | ||
| 131 | let seed = make_key(best); | ||
| 132 | var sum = vec3<f32>(0.0); | ||
| 133 | var count = 0.0; | ||
| 134 | for (var j = 0; j < AUTO_GRID; j = j + 1) { | ||
| 135 | for (var i = 0; i < AUTO_GRID; i = i + 1) { | ||
| 136 | let c = load_clamped(tex_a, (vec2<i32>(i, j) * 2 + vec2<i32>(1)) * dims / (2 * AUTO_GRID)).rgb; | ||
| 137 | if (key_distance(c, seed) < BASE_INNER) { | ||
| 138 | sum = sum + c; | ||
| 139 | count = count + 1.0; | ||
| 140 | } | ||
| 141 | } | ||
| 142 | } | ||
| 143 | return sum / max(count, 1.0); | ||
| 144 | } | ||
| 145 | |||
| 146 | /// Matte of one pixel from the key polyhedra, then the sponge / restore / detail adjustments. | ||
| 147 | fn matte_at(p: vec2<i32>, k: Key) -> f32 { | ||
| 148 | let c = load_clamped(tex_a, p).rgb; | ||
| 149 | let inner = BASE_INNER + 0.5 * u.p[1].x; | ||
| 150 | let outer = max(BASE_OUTER - 0.5 * u.p[1].y, inner + 0.05); | ||
| 151 | var a = smoothstep(inner, outer, key_distance(c, k)); | ||
| 152 | a = clamp((a - 0.5 * u.p[1].z) / (1.0 - 0.5 * u.p[1].z), 0.0, 1.0); | ||
| 153 | a = 1.0 - pow(1.0 - a, 1.0 + 2.0 * u.p[1].w); | ||
| 154 | a = mix(a, a * a, u.p[2].y); | ||
| 155 | return mix(a, sqrt(a), u.p[2].z); | ||
| 156 | } | ||
| 157 | |||
| 158 | /// Golden-angle disc tap `i` of `n`, scaled to `radius` pixels. | ||
| 159 | fn disc_tap(i: i32, n: i32, radius: f32) -> vec2<i32> { | ||
| 160 | let r = radius * sqrt((f32(i) + 0.5) / f32(n)); | ||
| 161 | let t = f32(i) * 2.3999632; | ||
| 162 | return vec2<i32>(round(vec2<f32>(cos(t), sin(t)) * r)); | ||
| 163 | } | ||
| 164 | |||
| 165 | @compute @workgroup_size(8, 8) | ||
| 166 | fn primatte_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 167 | let dims = textureDimensions(dst_tex); | ||
| 168 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 169 | let p = vec2<i32>(gid.xy); | ||
| 170 | let src = textureLoad(tex_a, p, 0); | ||
| 171 | var key_rgb = u.p[0].xyz; | ||
| 172 | if (u.p[0].w > 0.5) { | ||
| 173 | key_rgb = auto_key(vec2<i32>(dims)); | ||
| 174 | } | ||
| 175 | let k = make_key(key_rgb); | ||
| 176 | let uv = (vec2<f32>(gid.xy) + vec2<f32>(0.5)) / vec2<f32>(dims); | ||
| 177 | |||
| 178 | var a = matte_at(p, k); | ||
| 179 | let deartifact = u.p[3].x; | ||
| 180 | if (deartifact > 0.0) { | ||
| 181 | var ring = 0.0; | ||
| 182 | for (var i = 0; i < 8; i = i + 1) { | ||
| 183 | ring = ring + matte_at(p + disc_tap(i, 8, 1.5), k); | ||
| 184 | } | ||
| 185 | ring = ring / 8.0; | ||
| 186 | a = mix(a, ring, deartifact * smoothstep(0.25, 0.75, abs(a - ring))); | ||
| 187 | } | ||
| 188 | let blur = u.p[3].y; | ||
| 189 | if (blur > 0.0) { | ||
| 190 | var sum = a; | ||
| 191 | for (var i = 0; i < 16; i = i + 1) { | ||
| 192 | sum = sum + matte_at(p + disc_tap(i, 16, blur), k); | ||
| 193 | } | ||
| 194 | a = sum / 17.0; | ||
| 195 | } | ||
| 196 | let grow = u.p[3].z; | ||
| 197 | if (abs(grow) > 0.0) { | ||
| 198 | var ext = a; | ||
| 199 | for (var i = 0; i < 16; i = i + 1) { | ||
| 200 | let t = matte_at(p + disc_tap(i, 16, abs(grow)), k); | ||
| 201 | ext = select(min(ext, t), max(ext, t), grow > 0.0); | ||
| 202 | } | ||
| 203 | a = ext; | ||
| 204 | } | ||
| 205 | if (u.p[4].y > 0.5) { | ||
| 206 | a = a * (1.0 - sample_bilinear(tex_c, uv).a); | ||
| 207 | } | ||
| 208 | if (u.p[4].z > 0.5) { | ||
| 209 | a = max(a, sample_bilinear(tex_d, uv).a); | ||
| 210 | } | ||
| 211 | |||
| 212 | // Colour: remove the key's share of the partially transparent edge, then its chroma lean, keeping luminance. | ||
| 213 | let d = key_distance(src.rgb, k); | ||
| 214 | let dec = clamp((src.rgb - (1.0 - a) * k.rgb) / max(a, 1.0e-3), vec3<f32>(0.0), vec3<f32>(1.0)); | ||
| 215 | var fg = mix(src.rgb, dec, u.p[2].w * smoothstep(0.0, 0.1, a) * select(0.0, 1.0, a < 0.999)); | ||
| 216 | let reach = max(BASE_OUTER - 0.5 * u.p[1].y, BASE_INNER) * (1.4 + 1.6 * u.p[2].x); | ||
| 217 | let weight = 1.0 - smoothstep(0.6 * BASE_OUTER, reach, d); | ||
| 218 | let lean = max(dot(chroma_plane(fg), k.axis), 0.0); | ||
| 219 | let axis_rgb = CHROMA_E1 * k.axis.x + CHROMA_E2 * k.axis.y; | ||
| 220 | let despilled = fg - axis_rgb * lean * weight * u.p[2].w; | ||
| 221 | fg = max(despilled + (dot(fg, LUMA_709) - dot(despilled, LUMA_709)), vec3<f32>(0.0)); | ||
| 222 | |||
| 223 | var res: vec4<f32>; | ||
| 224 | let mode = i32(u.p[3].w + 0.5); | ||
| 225 | if (mode == 1) { | ||
| 226 | res = vec4<f32>(a, a, a, a); | ||
| 227 | } else if (mode == 2) { | ||
| 228 | res = vec4<f32>(fg, src.a); | ||
| 229 | } else if (u.p[4].x > 0.5) { | ||
| 230 | let bg = sample_bilinear(tex_b, uv); | ||
| 231 | res = vec4<f32>(fg * a + bg.rgb * (1.0 - a), a + bg.a * (1.0 - a)); | ||
| 232 | } else { | ||
| 233 | res = vec4<f32>(fg * a, a); | ||
| 234 | } | ||
| 235 | store_dst(p, finish(src, res, gid.xy, dims)); | ||
| 236 | } | ||