diff --git a/crates/nodes/src/function/arithmetic.rs b/crates/nodes/src/function/arithmetic.rs index 79f2398a..c80a4a43 100644 --- a/crates/nodes/src/function/arithmetic.rs +++ b/crates/nodes/src/function/arithmetic.rs @@ -4,6 +4,7 @@ use materialcraft_core::Value; pub(crate) fn evaluate(instruction: &super::instruction::Instruction, args: &[Value], random: &mut u32, scope: super::FunctionScope) -> Result { let op = instruction.definition.id; let pixel_math = scope == super::FunctionScope::PixelProcessor && !instruction.literal; + let angle_component = |angle, cosine| super::trigonometry::component(angle, cosine, scope, instruction.literal); let first = args.first().ok_or("missing arithmetic operand")?; let count = dimensions(first); let integer = matches!(first, Value::Int(_) | Value::Int2(_) | Value::Int3(_) | Value::Int4(_)); @@ -69,9 +70,7 @@ pub(crate) fn evaluate(instruction: &super::instruction::Instruction, args: &[Va } let angle = right[0]; - let (cosine, sine) = - if pixel_math { (super::trigonometry::component(angle, true), super::trigonometry::component(angle, false)) } else { (angle.cos(), angle.sin()) }; - return float_value(&[left[0] * cosine, left[0] * sine]); + return float_value(&[left[0] * angle_component(angle, true), left[0] * angle_component(angle, false)]); } let mut result = [0.0; 4]; @@ -96,10 +95,8 @@ pub(crate) fn evaluate(instruction: &super::instruction::Instruction, args: &[Va "log2" => left.log2(), "pow" => left.powf(right), "pow2" => left.exp2(), - "sin" if pixel_math => super::trigonometry::component(left, false), - "cos" if pixel_math => super::trigonometry::component(left, true), - "sin" => left.sin(), - "cos" => left.cos(), + "sin" => angle_component(left, false), + "cos" => angle_component(left, true), "tan" => left.tan(), "lerp" if pixel_math => (right - left).mul_add(factor, left), "lerp" => left + (right - left) * factor, diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index 0edf5a00..741d627a 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -26,6 +26,10 @@ fn operation(name: &str, arguments: &[Value], setting: Option) -> Result< } fn pixel_operation(op: &str, operands: &[Value], literal: bool) -> Value { + scoped_operation(super::FunctionScope::PixelProcessor, op, operands, literal) +} + +fn scoped_operation(scope: super::FunctionScope, op: &str, operands: &[Value], literal: bool) -> Value { let mut graph = FunctionGraph::default(); let mut variables = BTreeMap::new(); let mut inputs = Vec::new(); @@ -40,15 +44,7 @@ fn pixel_operation(op: &str, operands: &[Value], literal: bool) -> Value { inputs.push(input); } graph.output = Some(graph.add(op, &inputs, None)); - let context = EvaluationContext { - image_formats: &[], - scope: super::FunctionScope::PixelProcessor, - position: [0.5; 2], - size: [1.0; 2], - images: &[], - tile: true, - variables: &variables, - }; + let context = EvaluationContext { image_formats: &[], scope, position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; compile(&graph, 0).unwrap().evaluate_pixel(&context, &mut EvaluationState::default()).unwrap() } @@ -88,6 +84,36 @@ fn runtime_pixel_cartesian_multiplies_the_radius_by_each_quarter_wave() { assert_eq!(xy.map(f32::to_bits), [0x3f35a7de, 0x3f030fd1]); } +#[test] +fn parameter_and_value_angles_fold_the_phase_before_the_polynomial() { + use super::FunctionScope::{Node, ValueProcessor}; + for scope in [Node, ValueProcessor] { + for (angle, sine, cosine) in [ + (0.625, 0x3f15c8f2, 0x3f4f9b7a), + (-std::f32::consts::FRAC_PI_4, 0xbf350503, 0x3f350503), + (1e-7, 0x34490fdb, 0x3f800000), + (1e9, 0xbf800000, 0xbf800000), + ] { + for (op, expected) in [("sin", sine), ("cos", cosine)] { + let Value::Float(v) = scoped_operation(scope, op, &[Value::Float(angle)], false) else { panic!("expected a scalar") }; + assert_eq!(v.to_bits(), expected, "{scope:?} {op}({angle})"); + } + } + assert_eq!(scoped_operation(scope, "sin", &[Value::Float(0.625)], true), Value::Float(f32::from_bits(0x3f15c8ef))); + } +} + +#[test] +fn pattern_angles_and_uniform_cartesian_use_the_same_components() { + use super::FunctionScope::{FxMap, Node, ValueProcessor}; + for scope in [Node, ValueProcessor, FxMap] { + let angle = Value::Float(0.625); + assert_eq!(scoped_operation(scope, "cos", std::slice::from_ref(&angle), false), Value::Float(f32::from_bits(0x3f4f9b7a))); + let Value::Float2(result) = scoped_operation(scope, "cartesian", &[Value::Float(0.875), angle], false) else { panic!("expected a coordinate") }; + assert_eq!(result.map(f32::to_bits), [0x3f35a80b, 0x3f030fd4]); + } +} + #[test] fn pixel_product_sums_round_once_unless_the_product_is_also_read() { let values = [0x3fe34b19, 0x400d3c6f, 0xc0732711, 0x3f9665e4].map(|bits| Value::Float(f32::from_bits(bits))); diff --git a/crates/nodes/src/function/trigonometry.rs b/crates/nodes/src/function/trigonometry.rs index 5184466f..d048dbc0 100644 --- a/crates/nodes/src/function/trigonometry.rs +++ b/crates/nodes/src/function/trigonometry.rs @@ -1,4 +1,4 @@ -//! Runtime pixel sine and cosine from a fixed-point quarter wave. +//! Runtime sine and cosine for pixel and uniform function scopes. use super::fixed_point::square_fraction; use std::sync::LazyLock; @@ -50,7 +50,17 @@ fn phase(bits: u32) -> u32 { shifted.unwrap_or(0) & (4 * QUARTER - 1) } -pub(super) fn component(angle: f32, cosine: bool) -> f32 { +pub(super) fn component(angle: f32, cosine: bool, scope: super::FunctionScope, literal: bool) -> f32 { + if literal { + return if cosine { angle.cos() } else { angle.sin() }; + } + match scope { + super::FunctionScope::PixelProcessor => pixel_component(angle, cosine), + super::FunctionScope::Node | super::FunctionScope::ValueProcessor | super::FunctionScope::FxMap => uniform_component(angle, cosine), + } +} + +fn pixel_component(angle: f32, cosine: bool) -> f32 { if !angle.is_finite() { return f32::NAN; } @@ -66,3 +76,19 @@ pub(super) fn component(angle: f32, cosine: bool) -> f32 { let magnitude = if f64::from(nearest) > exact { f32::from_bits(nearest.to_bits().saturating_sub(1)) } else { nearest }; if (phase & (2 * QUARTER) != 0) ^ (!cosine && angle.is_sign_negative()) { -magnitude } else { magnitude } } + +fn uniform_component(angle: f32, cosine: bool) -> f32 { + const QUADRANT: f64 = std::f64::consts::FRAC_PI_2; + const CUBIC: f64 = -QUADRANT * QUADRANT * QUADRANT / 6.0; + const FIFTH: f64 = -CUBIC * QUADRANT * QUADRANT / 20.0; + // The measured seventh-order term targets one minus a float epsilon at the quadrant endpoint. + const SEVENTH: f32 = (1.0 - f32::EPSILON as f64 - QUADRANT - CUBIC - FIFTH) as f32; + let turns = angle * (std::f32::consts::FRAC_1_PI * 0.5) + if cosine { 0.5 } else { 0.25 }; + let x = 4.0 * (turns - turns.round_ties_even()).abs() - 1.0; + let square = x * x; + let cube = x * square; + let fifth = cube * square; + let seventh = fifth * square; + // Each odd power and each sum rounds separately. + x * std::f32::consts::FRAC_PI_2 + cube * CUBIC as f32 + fifth * FIFTH as f32 + seventh * SEVENTH +} diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 7af83e88..8f0f45bc 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -238,6 +238,26 @@ Use the position ramp and original 1024×16 lookup under [basic and ridged 3D Pe Selecting only level 2, 3 or 7 at roughness .7 gives 2,040, 1,871 and 1,841 exact pixels out of 4,096, each with maximum 2.38418579e−7. With the same lookup at 128² and roughness .7, U16, F16 and F32 still match 16,337, 16,380 and 5,160 of 16,384, respectively. +### Uniform angles and planar projection + +The grayscale and color 3D planar projection roots each match **168,960/168,960 pixels in 15 cases**, maximum error zero. Their eight [position-ramp and rotated-texture cases](#grayscale-and-color-3d-planar-projection) match 131,072/131,072 per root including the .125-turn 128² case. An additional seven cases match 37,888/37,888 per root. Replaying both first-pass sizes and the separate [four-format and 32² comparisons](#four-format-inventory-comparison) also matches all 81,920 and 17,408 pixels per root, respectively. + +For the seven cases generate new linear byte fields at each output size N. Position is (floor(255x/(N−1)),floor(255y/(N−1)),128+floor(63sin(2πx/N)cos(2πy/N)),255). World normal is (128+round(24sin(2πx/N)),128+round(24cos(2πy/N)),250,255). Let z=(29x+7y+3xy) mod 256. Grayscale texture is z and color texture is (z,43x−17y,11x+3y,23x+13y+7), reduced modulo 256. Set scale .53 and size (1,.75). Rotate −.1875 turns at 32² F32 seed 41 and 64² U8/U16/F16/F32 seed 71. Rotate .3125 turns at 128² F32 seed 211. At 64² F32 seed 313 set projection input 1, rotation .0675, target position (.375,.625,.5), target normal (.5,.5,1), and normal threshold .1. + +The rotation discrepancy came from computing trigonometry in the processor's output-size parameter. Node parameters, value processors, and pattern parameters use a common runtime approximation. Scale radians by float32(1/(2π)) and add .25 for sine or .5 for cosine. Subtract the nearest even integer, take the absolute value, multiply by four and subtract one to obtain x. Evaluate the odd-power series through x⁷, rounding each product and each sum separately. For k=π/2 the first three coefficients are k, −k³/6 and k⁵/120. The seventh-order coefficient targets 1−2⁻²³ at x=1, using the preceding coefficients before conversion to float32. A literal sine or cosine still uses the ordinary floating-point operation. + +| Original function probe | Measurements | Exact / compared | Maximum error | +|---|---:|---:|---:| +| Output-size parameter computing 128 angles per graph | 94 images at 128², 12,032 angle evaluations | 1,540,096/1,540,096 LUM32F pixels | 0 | +| Single parameter, Cartesian components, and literal expressions | 58 images at 16² | 14,848/14,848 LUM32F pixels | 0 | +| Value processor with the same expressions | 58 typed floats | 58/58 | 0 | +| Pattern opacity, scalar or Cartesian component, with matching gray or color declarations | 52 images at 16² | 13,312/13,312 LUM32F or RGBA32F pixels | 0 | +| Pixel function reading an exposed angle directly | 30 images at 16² | 7,680/7,680 LUM32F pixels | 0 | + +For the 128-column probe compute angle=float32(start+float32(i×step)), with i=0..127. Assign each result to its own variable in the output-size function. In the pixel function return the variable indexed by the output column. Use the nine (start,step) pairs (0,1/80), (0,1/8192), (.75,1/4096), (−16,.25), (float32(π/2)−64/2²⁰,2⁻²⁰), (−64/2²⁴,2⁻²⁴), (−987654,16037.125), (−1.5625,1/80) and (−2π,π/32), seed 41. For each operation initialize NumPy default_rng(431) and draw 32 more starts uniformly on [−20,20), each followed by a step uniformly on [−1,1) for the first 16 or [−.0001,.0001) for the rest. Use seed 257 for the graphs. The remaining six pairs at seed 73 are (2³⁰,65536), (−2³³,2¹⁸), (10²⁰,2×10¹⁷), (0,−2⁻³¹), (.75,2⁻²⁶) and (1.5,2⁻²⁵). Inputs and step constants are float32. + +The single-angle parameter and typed probes use .625, .125, −.125, .38, 0, 1, −.0078125, π/4, −π/4, 2π, −974634.875, 10⁻⁷ and 10⁹ with alternating seeds 42 and 17. Cartesian radius is −1.25. Literal expressions use .625, π/4 or 2π at seed 73. For the pattern, give a single square size (1,1), seed 17 and F32 precision. Set opacity to sine, cosine, or the corresponding Cartesian component with radius .875. Use .125, .625, π/4, 1, 10⁻⁷ and .38, plus literal-only .625. The independent pixel-parameter probes add .7 and π at seed 71 and agree with the [runtime pixel quarter wave](#runtime-pixel-sine-cosine-and-atlas-rotation). A grayscale pattern producer with a color output declaration had incompatible channel counts in a separate control. Its reference output was RGBA32F and MaterialCraft returned one channel. + ### Runtime pixel sine, cosine and atlas rotation Sine and cosine match **1,443,840/1,443,840 LUM32F pixels** across 30 original Pixel Processor cases. Exactness includes signed zero and all 84 nonfinite output components. Maximum finite error is zero. Direct Cartesian coordinates and separately multiplying the radius by the cosine and sine match another **197,632/197,632 component pixels**. With radius −1.25 and angle float32(π/4), the two coordinate components have bits `bf62462e bf624630`. diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index d7144cf9..2b3873e5 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -35,7 +35,7 @@ A graph may accept input pins and still be a root under the dependency criterion Statuses: **Not checked**, **In progress**, **Parity** (exact pixels or typed values for the linked measured cases), or **Too hard** (reason recorded). Function calls do not count as regular graph dependencies. -The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **202 Parity**, **25 In progress** and **319 Too hard**. The November 17 and 18 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons) +The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **204 Parity**, **23 In progress** and **319 Too hard**. The November 17 and 18 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons) [Grayscale sampler measurements](parity-fixes.md#grayscale-sampling-of-color-inputs) · [Value sampling across 240 typed comparisons](parity-fixes.md#value-processor-texture-filtering) @@ -49,8 +49,8 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard | [3d_perlin_noise.sbs/3D_perlin_noise](../assets/sbs/3d_perlin_noise.sbs) | 1 | No | [In progress · shared lookup exact across seven cases, stock lookup differs](parity-fixes.md#pixel-processor-products-and-sums) | | [3d_perlin_noise.sbs/3D_perlin_noise_fractal](../assets/sbs/3d_perlin_noise.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) | | [3d_perlin_noise.sbs/3D_ridged_noise_fractal](../assets/sbs/3d_perlin_noise.sbs) | 1 | No | [In progress · 13 octave controls isolate a one-level roughness difference](parity-fixes.md#ridged-noise-octave-isolation) | -| [3d_planar_projection.sbs/3d_planar_projection](../assets/sbs/3d_planar_projection.sbs) | 3 | No | [In progress · default exact, rotated samples differ](parity-fixes.md#grayscale-and-color-3d-planar-projection) | -| [3d_planar_projection.sbs/3d_planar_projection_color](../assets/sbs/3d_planar_projection.sbs) | 3 | No | [In progress · default RGBA exact, rotated samples differ](parity-fixes.md#grayscale-and-color-3d-planar-projection) | +| [3d_planar_projection.sbs/3d_planar_projection](../assets/sbs/3d_planar_projection.sbs) | 3 | No | [Parity · 15 projection cases, 168,960 exact pixels](parity-fixes.md#uniform-angles-and-planar-projection) | +| [3d_planar_projection.sbs/3d_planar_projection_color](../assets/sbs/3d_planar_projection.sbs) | 3 | No | [Parity · 15 projection cases, 168,960 exact pixels](parity-fixes.md#uniform-angles-and-planar-projection) | | [3d_simplex_noise.sbs/3d_simplex_noise](../assets/sbs/3d_simplex_noise.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) | | [3d_texture_jump_flood.sbs/3d_texture_jump_flood_iteration](../assets/sbs/3d_texture_jump_flood.sbs) | 1 | Yes | [Parity: 5 cases](parity-fixes.md#verified-cases) | | [3d_texture_position.sbs/3d_texture_position](../assets/sbs/3d_texture_position.sbs) | 0 | No | [Parity: native 4K atlas](parity-fixes.md#verified-cases) |