diff --git a/crates/engine/src/cryptomatte.rs b/crates/engine/src/cryptomatte.rs index 49dc293b87a91764fb6949dc2b4099e4d4613b22..9efed30bb0b9de85219a2d27fe97d5515410798e 100644 --- a/crates/engine/src/cryptomatte.rs +++ b/crates/engine/src/cryptomatte.rs @@ -389,6 +389,72 @@ fn parse_hex_literal_token(token: &str) -> Option { u32::from_str_radix(hex, 16).ok() } +#[cfg(not(target_arch = "wasm32"))] +const CRYPTO_PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512; + +fn accumulate_cryptomatte_chunk( + out: &mut [f32], + start: usize, + pairs: &[(&[f32], &[f32])], + target_ids: &HashSet, +) { + let len = out.len(); + for &(ids, covs) in pairs { + let ids_slice = &ids[start..start + len]; + let covs_slice = &covs[start..start + len]; + for i in 0..len { + if target_ids.contains(&ids_slice[i].to_bits()) { + out[i] += covs_slice[i]; + } + } + } + for v in out { + *v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; + } +} + +fn accumulate_cryptomatte_scalar( + pairs: &[(&[f32], &[f32])], + target_ids: &HashSet, + pixel_count: usize, +) -> Vec { + let mut matte = vec![0.0_f32; pixel_count]; + if !target_ids.is_empty() && !pairs.is_empty() { + accumulate_cryptomatte_chunk(&mut matte, 0, pairs, target_ids); + } + matte +} + +/// Accumulates Cryptomatte `(id, coverage)` rank pairs into a clamped `[0.0, 1.0]` matte, +/// splitting across bounded worker threads for `>= 512 * 512` images on native targets. +fn accumulate_cryptomatte_matte( + pairs: &[(&[f32], &[f32])], + target_ids: &HashSet, + pixel_count: usize, +) -> Vec { + if target_ids.is_empty() || pairs.is_empty() { + return vec![0.0_f32; pixel_count]; + } + #[cfg(not(target_arch = "wasm32"))] + if pixel_count >= CRYPTO_PARALLEL_THRESHOLD_PIXELS { + let workers = std::thread::available_parallelism() + .map(|n| n.get().clamp(2, 8)) + .unwrap_or(4); + let chunk_len = pixel_count.div_ceil(workers).max(1); + let mut matte = vec![0.0_f32; pixel_count]; + std::thread::scope(|scope| { + let mut offset = 0usize; + for chunk in matte.chunks_mut(chunk_len) { + let start = offset; + offset += chunk.len(); + scope.spawn(move || accumulate_cryptomatte_chunk(chunk, start, pairs, target_ids)); + } + }); + return matte; + } + accumulate_cryptomatte_scalar(pairs, target_ids, pixel_count) +} + /// Lists Cryptomatte layer names discovered in an OpenEXR file's header metadata /// (falling back to rank-00 channel prefix discovery when metadata is absent). pub fn list_cryptomatte_layers(exr_path: &Path) -> Vec { @@ -573,36 +639,24 @@ pub fn extract_cryptomatte( let (w, h) = dims?; let pixel_count = w * h; - let mut matte = vec![0.0_f32; pixel_count]; - if target_ids.is_empty() { return Some(CryptomatteResult { size: [w as u32, h as u32], - matte, + matte: vec![0.0_f32; pixel_count], }); } // 5. Accumulate coverage across all rank (ID, coverage) pairs. + let mut pairs: Vec<(&[f32], &[f32])> = Vec::with_capacity(ranks.len() * 2); for slots in ranks.values() { if let (Some(ids), Some(covs)) = (&slots[0], &slots[1]) { - for i in 0..pixel_count { - if target_ids.contains(&ids[i].to_bits()) { - matte[i] += covs[i]; - } - } + pairs.push((ids.as_slice(), covs.as_slice())); } if let (Some(ids), Some(covs)) = (&slots[2], &slots[3]) { - for i in 0..pixel_count { - if target_ids.contains(&ids[i].to_bits()) { - matte[i] += covs[i]; - } - } + pairs.push((ids.as_slice(), covs.as_slice())); } } - - for v in &mut matte { - *v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; - } + let matte = accumulate_cryptomatte_matte(&pairs, &target_ids, pixel_count); Some(CryptomatteResult { size: [w as u32, h as u32], @@ -862,4 +916,75 @@ mod tests { assert_eq!(parsed_valid.get("Hero_日本語"), Some(&0xa1b2_c3d4)); assert_eq!(parsed_valid.get("élan_A"), Some(&0x00ff_00ff)); } + + #[test] + fn parallel_cryptomatte_matches_scalar_bit_for_bit() { + let pixel_count = 520 * 520; + let hero_id = crypto_hash_to_float(murmur3_32(b"Hero", 0)); + let prop_id = crypto_hash_to_float(murmur3_32(b"Prop", 0)); + let other_id = crypto_hash_to_float(murmur3_32(b"Other", 0)); + let target_ids: HashSet = [hero_id.to_bits(), prop_id.to_bits()].into_iter().collect(); + + let mut id0 = vec![0.0_f32; pixel_count]; + let mut cov0 = vec![0.0_f32; pixel_count]; + let mut id1 = vec![0.0_f32; pixel_count]; + let mut cov1 = vec![0.0_f32; pixel_count]; + let mut id2 = vec![0.0_f32; pixel_count]; + let mut cov2 = vec![0.0_f32; pixel_count]; + + for i in 0..pixel_count { + match i % 7 { + 0 => { + id0[i] = hero_id; + cov0[i] = 0.65; + id1[i] = prop_id; + cov1[i] = 0.25; + } + 1 => { + id0[i] = other_id; + cov0[i] = 0.9; + id1[i] = hero_id; + cov1[i] = 0.1; + } + 2 => { + // Clamping > 1.0 across multiple matching ranks + id0[i] = hero_id; + cov0[i] = 0.75; + id1[i] = prop_id; + cov1[i] = 0.5; + } + 3 => { + // NaN coverage must sanitize to 0.0 identically + id0[i] = hero_id; + cov0[i] = f32::NAN; + } + 4 => { + id0[i] = other_id; + cov0[i] = 1.0; + id2[i] = prop_id; + cov2[i] = 0.375; + } + _ => {} + } + } + + let pairs: Vec<(&[f32], &[f32])> = vec![ + (&id0, &cov0), + (&id1, &cov1), + (&id2, &cov2), + ]; + let scalar = accumulate_cryptomatte_scalar(&pairs, &target_ids, pixel_count); + let parallel = accumulate_cryptomatte_matte(&pairs, &target_ids, pixel_count); + + assert_eq!(parallel.len(), scalar.len()); + for (i, (&p, &s)) in parallel.iter().zip(scalar.iter()).enumerate() { + assert_eq!( + p.to_bits(), + s.to_bits(), + "bit mismatch at pixel {i}: parallel={p} ({:#x}) vs scalar={s} ({:#x})", + p.to_bits(), + s.to_bits() + ); + } + } } diff --git a/crates/engine/src/scene3d/shader.rs b/crates/engine/src/scene3d/shader.rs index 2d8fbe7d84ec5de758e09ff95af43f65f52c9a1a..f84bc4ff6ba248f0e799c803c7aab7208409e3ec 100644 --- a/crates/engine/src/scene3d/shader.rs +++ b/crates/engine/src/scene3d/shader.rs @@ -400,6 +400,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { var col = u.diffuse_col; var tex_col = vec4(1.0); var uv_samp = uv_xformed; + var tex_straight = vec3(1.0); if (u.flags.x > 0.5) { if (u.dod.z > 0.5 && u.dod.w > 0.5) { let tdims = vec2(textureDimensions(mat_tex)); @@ -410,15 +411,18 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { } } tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0); + if (u.mat_fx.z <= 0.5) { + tex_straight = select(vec3(0.0), tex_col.rgb / max(tex_col.a, 1e-5), tex_col.a > 1e-5); + } col = select(tex_col, vec4(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; } if (col.a <= 0.002) { discard; } + // `u.diffuse_col` is straight (not premultiplied by `u.diffuse_col.a`), while `tex_col` is premultiplied. + let albedo = tex_straight * u.diffuse_col.rgb; if (u.flags.y > 0.5) { - // Premultiplied -> unpremultiplied albedo for lighting - let albedo = select(vec3(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5); var n = normalize(in.world_n); if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) { n = perturb_bump_normal( @@ -484,7 +488,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { col = vec4(clamp(lit, vec3(0.0), vec3(1.0)) * col.a, col.a); } else { - col = vec4(min(col.rgb * u.uv_off_wrap.w, vec3(1.0)), col.a); + col = vec4(min(albedo * u.uv_off_wrap.w, vec3(1.0)) * col.a, col.a); } return col; } diff --git a/crates/engine/src/shaders/blur_glow.wgsl b/crates/engine/src/shaders/blur_glow.wgsl index 370fe3d0c55b22ba85ad069e7c4f028b9994e879..65665cb007712d4da061218c8f7db3be91b1af1a 100644 --- a/crates/engine/src/shaders/blur_glow.wgsl +++ b/crates/engine/src/shaders/blur_glow.wgsl @@ -744,44 +744,49 @@ fn film_grain_op(@builtin(global_invocation_id) gid: vec3) { let mbm = u.p[7].x > 0.5; let fg_xy = vec2(f32(gid.x), f32(gid.y)); - let sz_r = max(vec2(sz_x * u.p[4].x, sz_y * u.p[4].y), vec2(0.25)) * 1.65; - let sz_g = max(vec2(sz_x * u.p[5].x, sz_y * u.p[5].y), vec2(0.25)) * 1.65; - let sz_b = max(vec2(sz_x * u.p[6].x, sz_y * u.p[6].y), vec2(0.25)) * 1.65; - let rough_r = clamp(rough * u.p[4].z, 0.0, 1.0); - let rough_g = clamp(rough * u.p[5].z, 0.0, 1.0); - let rough_b = clamp(rough * u.p[6].z, 0.0, 1.0); + let n_luma = fg_gauss_field(fg_xy / (vec2(sz_x, sz_y) * 1.65), seed, clamp(rough, 0.0, 1.0)); var n_rgb: vec3; + var ch_off: vec3; + var nv: vec3; if (mono) { - n_rgb = vec3( - fg_gauss_field(fg_xy / sz_r, seed, rough_r), - fg_gauss_field(fg_xy / sz_g, seed, rough_g), - fg_gauss_field(fg_xy / sz_b, seed, rough_b), - ); + // Monochrome=1 uses only Master* controls; per-channel R/G/B overrides are ignored. + n_rgb = vec3(n_luma); + ch_off = vec3(master_off); + nv = n_rgb * strength; } else { - let n_luma = fg_gauss_field(fg_xy / (vec2(sz_x, sz_y) * 1.65), seed, clamp(rough, 0.0, 1.0)); + let sz_r = max(vec2(sz_x * u.p[4].x, sz_y * u.p[4].y), vec2(0.25)) * 1.65; + let sz_g = max(vec2(sz_x * u.p[5].x, sz_y * u.p[5].y), vec2(0.25)) * 1.65; + let sz_b = max(vec2(sz_x * u.p[6].x, sz_y * u.p[6].y), vec2(0.25)) * 1.65; + let rough_r = clamp(rough * u.p[4].z, 0.0, 1.0); + let rough_g = clamp(rough * u.p[5].z, 0.0, 1.0); + let rough_b = clamp(rough * u.p[6].z, 0.0, 1.0); let n_indep = vec3( fg_gauss_field(fg_xy / sz_r + vec2(31.7, 11.3), seed + 1009, rough_r), fg_gauss_field(fg_xy / sz_g + vec2(-19.1, 47.9), seed + 2027, rough_g), fg_gauss_field(fg_xy / sz_b + vec2(53.3, -29.7), seed + 3037, rough_b), ); n_rgb = mix(vec3(n_luma), n_indep, color_str); + ch_off = vec3(master_off) + vec3(u.p[4].w, u.p[5].w, u.p[6].w); + nv = n_rgb * vec3(u.p[2].y, u.p[2].z, u.p[2].w) * strength; } - let ch_off = vec3(master_off) + vec3(u.p[4].w, u.p[5].w, u.p[6].w); - let nv = n_rgb * vec3(u.p[2].y, u.p[2].z, u.p[2].w) * strength; var rgb = src.rgb; if (log_proc) { rgb = (src.rgb + ch_off) * exp(nv * 0.55) - ch_off; } else { - rgb = src.rgb + nv * (0.55 + abs(ch_off) * 2.0); + rgb = src.rgb + nv * 0.52; } if (alpha_mult) { rgb = mix(src.rgb, rgb, clamp(src.a, 0.0, 1.0)); } - let m = clamp(read_mask(gid.xy, dims, u.p[1].w, u.p[2].x) * blend, 0.0, 1.0); + let mask_val = read_mask(gid.xy, dims, u.p[1].w, u.p[2].x); let grained = vec4(rgb, src.a); - let res = select(mix(src, grained, m), grained * m, mbm); + let res = select( + mix(src, grained, clamp(mask_val * blend, 0.0, 1.0)), + mix(src, grained, clamp(blend, 0.0, 1.0)) * mask_val, + mbm, + ); store_dst(vec2(gid.xy), select(res, src, u.p[8] > vec4(0.5))); }