authoravatarclover caruso<git@paperclover.net>2026-12-01 15:29:16-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 15:49:39-08:00
log4d054f69bca32d2db45fd0b038b40afd6834054b
tree8d7fda06bfb08c513feb7fe0d639629e30e23328
parentfb8cf0b99d4b4ae93c1a9a612d5ab31e815cd8c5
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(engine): improve FilmGrain and MtlPhong/CookTorrance parity and parallelize Cryptomatte


3 files changed, 171 insertions(+), 37 deletions(-)

crates/engine/src/cryptomatte.rs+142-17
...@@ -389,6 +389,72 @@ fn parse_hex_literal_token(token: &str) -> Option<u32> {...@@ -389,6 +389,72 @@ fn parse_hex_literal_token(token: &str) -> Option<u32> {
389 u32::from_str_radix(hex, 16).ok()389 u32::from_str_radix(hex, 16).ok()
390}390}
391391
392#[cfg(not(target_arch = "wasm32"))]
393const CRYPTO_PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512;
394
395fn accumulate_cryptomatte_chunk(
396 out: &mut [f32],
397 start: usize,
398 pairs: &[(&[f32], &[f32])],
399 target_ids: &HashSet<u32>,
400) {
401 let len = out.len();
402 for &(ids, covs) in pairs {
403 let ids_slice = &ids[start..start + len];
404 let covs_slice = &covs[start..start + len];
405 for i in 0..len {
406 if target_ids.contains(&ids_slice[i].to_bits()) {
407 out[i] += covs_slice[i];
408 }
409 }
410 }
411 for v in out {
412 *v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) };
413 }
414}
415
416fn accumulate_cryptomatte_scalar(
417 pairs: &[(&[f32], &[f32])],
418 target_ids: &HashSet<u32>,
419 pixel_count: usize,
420) -> Vec<f32> {
421 let mut matte = vec![0.0_f32; pixel_count];
422 if !target_ids.is_empty() && !pairs.is_empty() {
423 accumulate_cryptomatte_chunk(&mut matte, 0, pairs, target_ids);
424 }
425 matte
426}
427
428/// Accumulates Cryptomatte `(id, coverage)` rank pairs into a clamped `[0.0, 1.0]` matte,
429/// splitting across bounded worker threads for `>= 512 * 512` images on native targets.
430fn accumulate_cryptomatte_matte(
431 pairs: &[(&[f32], &[f32])],
432 target_ids: &HashSet<u32>,
433 pixel_count: usize,
434) -> Vec<f32> {
435 if target_ids.is_empty() || pairs.is_empty() {
436 return vec![0.0_f32; pixel_count];
437 }
438 #[cfg(not(target_arch = "wasm32"))]
439 if pixel_count >= CRYPTO_PARALLEL_THRESHOLD_PIXELS {
440 let workers = std::thread::available_parallelism()
441 .map(|n| n.get().clamp(2, 8))
442 .unwrap_or(4);
443 let chunk_len = pixel_count.div_ceil(workers).max(1);
444 let mut matte = vec![0.0_f32; pixel_count];
445 std::thread::scope(|scope| {
446 let mut offset = 0usize;
447 for chunk in matte.chunks_mut(chunk_len) {
448 let start = offset;
449 offset += chunk.len();
450 scope.spawn(move || accumulate_cryptomatte_chunk(chunk, start, pairs, target_ids));
451 }
452 });
453 return matte;
454 }
455 accumulate_cryptomatte_scalar(pairs, target_ids, pixel_count)
456}
457
392/// Lists Cryptomatte layer names discovered in an OpenEXR file's header metadata458/// Lists Cryptomatte layer names discovered in an OpenEXR file's header metadata
393/// (falling back to rank-00 channel prefix discovery when metadata is absent).459/// (falling back to rank-00 channel prefix discovery when metadata is absent).
394pub fn list_cryptomatte_layers(exr_path: &Path) -> Vec<String> {460pub fn list_cryptomatte_layers(exr_path: &Path) -> Vec<String> {
...@@ -573,36 +639,24 @@ pub fn extract_cryptomatte(...@@ -573,36 +639,24 @@ pub fn extract_cryptomatte(
573639
574 let (w, h) = dims?;640 let (w, h) = dims?;
575 let pixel_count = w * h;641 let pixel_count = w * h;
576 let mut matte = vec![0.0_f32; pixel_count];
577
578 if target_ids.is_empty() {642 if target_ids.is_empty() {
579 return Some(CryptomatteResult {643 return Some(CryptomatteResult {
580 size: [w as u32, h as u32],644 size: [w as u32, h as u32],
581 matte,645 matte: vec![0.0_f32; pixel_count],
582 });646 });
583 }647 }
584648
585 // 5. Accumulate coverage across all rank (ID, coverage) pairs.649 // 5. Accumulate coverage across all rank (ID, coverage) pairs.
650 let mut pairs: Vec<(&[f32], &[f32])> = Vec::with_capacity(ranks.len() * 2);
586 for slots in ranks.values() {651 for slots in ranks.values() {
587 if let (Some(ids), Some(covs)) = (&slots[0], &slots[1]) {652 if let (Some(ids), Some(covs)) = (&slots[0], &slots[1]) {
588 for i in 0..pixel_count {653 pairs.push((ids.as_slice(), covs.as_slice()));
589 if target_ids.contains(&ids[i].to_bits()) {
590 matte[i] += covs[i];
591 }
592 }
593 }654 }
594 if let (Some(ids), Some(covs)) = (&slots[2], &slots[3]) {655 if let (Some(ids), Some(covs)) = (&slots[2], &slots[3]) {
595 for i in 0..pixel_count {656 pairs.push((ids.as_slice(), covs.as_slice()));
596 if target_ids.contains(&ids[i].to_bits()) {
597 matte[i] += covs[i];
598 }
599 }
600 }657 }
601 }658 }
602659 let matte = accumulate_cryptomatte_matte(&pairs, &target_ids, pixel_count);
603 for v in &mut matte {
604 *v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) };
605 }
606660
607 Some(CryptomatteResult {661 Some(CryptomatteResult {
608 size: [w as u32, h as u32],662 size: [w as u32, h as u32],
...@@ -862,4 +916,75 @@ mod tests {...@@ -862,4 +916,75 @@ mod tests {
862 assert_eq!(parsed_valid.get("Hero_日本語"), Some(&0xa1b2_c3d4));916 assert_eq!(parsed_valid.get("Hero_日本語"), Some(&0xa1b2_c3d4));
863 assert_eq!(parsed_valid.get("élan_A"), Some(&0x00ff_00ff));917 assert_eq!(parsed_valid.get("élan_A"), Some(&0x00ff_00ff));
864 }918 }
919
920 #[test]
921 fn parallel_cryptomatte_matches_scalar_bit_for_bit() {
922 let pixel_count = 520 * 520;
923 let hero_id = crypto_hash_to_float(murmur3_32(b"Hero", 0));
924 let prop_id = crypto_hash_to_float(murmur3_32(b"Prop", 0));
925 let other_id = crypto_hash_to_float(murmur3_32(b"Other", 0));
926 let target_ids: HashSet<u32> = [hero_id.to_bits(), prop_id.to_bits()].into_iter().collect();
927
928 let mut id0 = vec![0.0_f32; pixel_count];
929 let mut cov0 = vec![0.0_f32; pixel_count];
930 let mut id1 = vec![0.0_f32; pixel_count];
931 let mut cov1 = vec![0.0_f32; pixel_count];
932 let mut id2 = vec![0.0_f32; pixel_count];
933 let mut cov2 = vec![0.0_f32; pixel_count];
934
935 for i in 0..pixel_count {
936 match i % 7 {
937 0 => {
938 id0[i] = hero_id;
939 cov0[i] = 0.65;
940 id1[i] = prop_id;
941 cov1[i] = 0.25;
942 }
943 1 => {
944 id0[i] = other_id;
945 cov0[i] = 0.9;
946 id1[i] = hero_id;
947 cov1[i] = 0.1;
948 }
949 2 => {
950 // Clamping > 1.0 across multiple matching ranks
951 id0[i] = hero_id;
952 cov0[i] = 0.75;
953 id1[i] = prop_id;
954 cov1[i] = 0.5;
955 }
956 3 => {
957 // NaN coverage must sanitize to 0.0 identically
958 id0[i] = hero_id;
959 cov0[i] = f32::NAN;
960 }
961 4 => {
962 id0[i] = other_id;
963 cov0[i] = 1.0;
964 id2[i] = prop_id;
965 cov2[i] = 0.375;
966 }
967 _ => {}
968 }
969 }
970
971 let pairs: Vec<(&[f32], &[f32])> = vec![
972 (&id0, &cov0),
973 (&id1, &cov1),
974 (&id2, &cov2),
975 ];
976 let scalar = accumulate_cryptomatte_scalar(&pairs, &target_ids, pixel_count);
977 let parallel = accumulate_cryptomatte_matte(&pairs, &target_ids, pixel_count);
978
979 assert_eq!(parallel.len(), scalar.len());
980 for (i, (&p, &s)) in parallel.iter().zip(scalar.iter()).enumerate() {
981 assert_eq!(
982 p.to_bits(),
983 s.to_bits(),
984 "bit mismatch at pixel {i}: parallel={p} ({:#x}) vs scalar={s} ({:#x})",
985 p.to_bits(),
986 s.to_bits()
987 );
988 }
989 }
865}990}
crates/engine/src/scene3d/shader.rs+7-3
...@@ -400,6 +400,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -400,6 +400,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
400 var col = u.diffuse_col;400 var col = u.diffuse_col;
401 var tex_col = vec4<f32>(1.0);401 var tex_col = vec4<f32>(1.0);
402 var uv_samp = uv_xformed;402 var uv_samp = uv_xformed;
403 var tex_straight = vec3<f32>(1.0);
403 if (u.flags.x > 0.5) {404 if (u.flags.x > 0.5) {
404 if (u.dod.z > 0.5 && u.dod.w > 0.5) {405 if (u.dod.z > 0.5 && u.dod.w > 0.5) {
405 let tdims = vec2<f32>(textureDimensions(mat_tex));406 let tdims = vec2<f32>(textureDimensions(mat_tex));
...@@ -410,15 +411,18 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -410,15 +411,18 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
410 }411 }
411 }412 }
412 tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0);413 tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0);
414 if (u.mat_fx.z <= 0.5) {
415 tex_straight = select(vec3<f32>(0.0), tex_col.rgb / max(tex_col.a, 1e-5), tex_col.a > 1e-5);
416 }
413 col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col;417 col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col;
414 }418 }
415 if (col.a <= 0.002) {419 if (col.a <= 0.002) {
416 discard;420 discard;
417 }421 }
418422
423 // `u.diffuse_col` is straight (not premultiplied by `u.diffuse_col.a`), while `tex_col` is premultiplied.
424 let albedo = tex_straight * u.diffuse_col.rgb;
419 if (u.flags.y > 0.5) {425 if (u.flags.y > 0.5) {
420 // Premultiplied -> unpremultiplied albedo for lighting
421 let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5);
422 var n = normalize(in.world_n);426 var n = normalize(in.world_n);
423 if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) {427 if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) {
424 n = perturb_bump_normal(428 n = perturb_bump_normal(
...@@ -484,7 +488,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -484,7 +488,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
484488
485 col = vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)) * col.a, col.a);489 col = vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)) * col.a, col.a);
486 } else {490 } else {
487 col = vec4<f32>(min(col.rgb * u.uv_off_wrap.w, vec3<f32>(1.0)), col.a);491 col = vec4<f32>(min(albedo * u.uv_off_wrap.w, vec3<f32>(1.0)) * col.a, col.a);
488 }492 }
489 return col;493 return col;
490}494}
crates/engine/src/shaders/blur_glow.wgsl+22-17
...@@ -744,44 +744,49 @@ fn film_grain_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -744,44 +744,49 @@ fn film_grain_op(@builtin(global_invocation_id) gid: vec3<u32>) {
744 let mbm = u.p[7].x > 0.5;744 let mbm = u.p[7].x > 0.5;
745745
746 let fg_xy = vec2<f32>(f32(gid.x), f32(gid.y));746 let fg_xy = vec2<f32>(f32(gid.x), f32(gid.y));
747 let sz_r = max(vec2<f32>(sz_x * u.p[4].x, sz_y * u.p[4].y), vec2<f32>(0.25)) * 1.65;747 let n_luma = fg_gauss_field(fg_xy / (vec2<f32>(sz_x, sz_y) * 1.65), seed, clamp(rough, 0.0, 1.0));
748 let sz_g = max(vec2<f32>(sz_x * u.p[5].x, sz_y * u.p[5].y), vec2<f32>(0.25)) * 1.65;
749 let sz_b = max(vec2<f32>(sz_x * u.p[6].x, sz_y * u.p[6].y), vec2<f32>(0.25)) * 1.65;
750 let rough_r = clamp(rough * u.p[4].z, 0.0, 1.0);
751 let rough_g = clamp(rough * u.p[5].z, 0.0, 1.0);
752 let rough_b = clamp(rough * u.p[6].z, 0.0, 1.0);
753748
754 var n_rgb: vec3<f32>;749 var n_rgb: vec3<f32>;
750 var ch_off: vec3<f32>;
751 var nv: vec3<f32>;
755 if (mono) {752 if (mono) {
756 n_rgb = vec3<f32>(753 // Monochrome=1 uses only Master* controls; per-channel R/G/B overrides are ignored.
757 fg_gauss_field(fg_xy / sz_r, seed, rough_r),754 n_rgb = vec3<f32>(n_luma);
758 fg_gauss_field(fg_xy / sz_g, seed, rough_g),755 ch_off = vec3<f32>(master_off);
759 fg_gauss_field(fg_xy / sz_b, seed, rough_b),756 nv = n_rgb * strength;
760 );
761 } else {757 } else {
762 let n_luma = fg_gauss_field(fg_xy / (vec2<f32>(sz_x, sz_y) * 1.65), seed, clamp(rough, 0.0, 1.0));758 let sz_r = max(vec2<f32>(sz_x * u.p[4].x, sz_y * u.p[4].y), vec2<f32>(0.25)) * 1.65;
759 let sz_g = max(vec2<f32>(sz_x * u.p[5].x, sz_y * u.p[5].y), vec2<f32>(0.25)) * 1.65;
760 let sz_b = max(vec2<f32>(sz_x * u.p[6].x, sz_y * u.p[6].y), vec2<f32>(0.25)) * 1.65;
761 let rough_r = clamp(rough * u.p[4].z, 0.0, 1.0);
762 let rough_g = clamp(rough * u.p[5].z, 0.0, 1.0);
763 let rough_b = clamp(rough * u.p[6].z, 0.0, 1.0);
763 let n_indep = vec3<f32>(764 let n_indep = vec3<f32>(
764 fg_gauss_field(fg_xy / sz_r + vec2<f32>(31.7, 11.3), seed + 1009, rough_r),765 fg_gauss_field(fg_xy / sz_r + vec2<f32>(31.7, 11.3), seed + 1009, rough_r),
765 fg_gauss_field(fg_xy / sz_g + vec2<f32>(-19.1, 47.9), seed + 2027, rough_g),766 fg_gauss_field(fg_xy / sz_g + vec2<f32>(-19.1, 47.9), seed + 2027, rough_g),
766 fg_gauss_field(fg_xy / sz_b + vec2<f32>(53.3, -29.7), seed + 3037, rough_b),767 fg_gauss_field(fg_xy / sz_b + vec2<f32>(53.3, -29.7), seed + 3037, rough_b),
767 );768 );
768 n_rgb = mix(vec3<f32>(n_luma), n_indep, color_str);769 n_rgb = mix(vec3<f32>(n_luma), n_indep, color_str);
770 ch_off = vec3<f32>(master_off) + vec3<f32>(u.p[4].w, u.p[5].w, u.p[6].w);
771 nv = n_rgb * vec3<f32>(u.p[2].y, u.p[2].z, u.p[2].w) * strength;
769 }772 }
770 let ch_off = vec3<f32>(master_off) + vec3<f32>(u.p[4].w, u.p[5].w, u.p[6].w);
771 let nv = n_rgb * vec3<f32>(u.p[2].y, u.p[2].z, u.p[2].w) * strength;
772773
773 var rgb = src.rgb;774 var rgb = src.rgb;
774 if (log_proc) {775 if (log_proc) {
775 rgb = (src.rgb + ch_off) * exp(nv * 0.55) - ch_off;776 rgb = (src.rgb + ch_off) * exp(nv * 0.55) - ch_off;
776 } else {777 } else {
777 rgb = src.rgb + nv * (0.55 + abs(ch_off) * 2.0);778 rgb = src.rgb + nv * 0.52;
778 }779 }
779 if (alpha_mult) {780 if (alpha_mult) {
780 rgb = mix(src.rgb, rgb, clamp(src.a, 0.0, 1.0));781 rgb = mix(src.rgb, rgb, clamp(src.a, 0.0, 1.0));
781 }782 }
782 let m = clamp(read_mask(gid.xy, dims, u.p[1].w, u.p[2].x) * blend, 0.0, 1.0);783 let mask_val = read_mask(gid.xy, dims, u.p[1].w, u.p[2].x);
783 let grained = vec4<f32>(rgb, src.a);784 let grained = vec4<f32>(rgb, src.a);
784 let res = select(mix(src, grained, m), grained * m, mbm);785 let res = select(
786 mix(src, grained, clamp(mask_val * blend, 0.0, 1.0)),
787 mix(src, grained, clamp(blend, 0.0, 1.0)) * mask_val,
788 mbm,
789 );
785 store_dst(vec2<i32>(gid.xy), select(res, src, u.p[8] > vec4<f32>(0.5)));790 store_dst(vec2<i32>(gid.xy), select(res, src, u.p[8] > vec4<f32>(0.5)));
786}791}
787792