mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-24 16:31:02 +01:00
Preserve single rounding for independently returned vector components
This commit is contained in:
1 parent
b583142106
commit
527619231e
6 files changed
+162
-40
No files matched your search
@@ -210,7 +210,8 @@ fn mark_literals(program: &mut Program, mut arguments: BTreeSet<&str>) -> super:
|
||||
if let Some(call) = &mut op.call {
|
||||
let bound = call.inputs.iter().zip(&op.inputs).filter(|(_, index)| literal(index)).map(|(name, _)| name.as_str()).collect();
|
||||
let lanes = mark_literals(&mut call.program, bound);
|
||||
if !call.exports && lanes.iter().any(Option::is_some) {
|
||||
// Returned products read the call's evaluated registers after its assignments have run.
|
||||
if lanes.iter().any(Option::is_some) {
|
||||
returned.insert(index, lanes);
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -7,10 +7,9 @@ enum Addend {
|
||||
Literal(Value),
|
||||
}
|
||||
|
||||
struct Retained {
|
||||
source: Source,
|
||||
addend: Addend,
|
||||
subtract: bool,
|
||||
enum Retained {
|
||||
Argument { source: Source, addend: Addend, subtract: bool },
|
||||
Lanes(super::returned_product::Sum),
|
||||
}
|
||||
|
||||
pub(super) struct ProductSum {
|
||||
@@ -25,25 +24,32 @@ pub(super) struct ProductSum {
|
||||
|
||||
impl ProductSum {
|
||||
/// Evaluate the original call and vector arguments before reading the factors they used.
|
||||
pub(super) fn returned(inputs: &[usize], product_on_right: bool, source: Source) -> Self {
|
||||
let addend = Addend::Argument(usize::from(!product_on_right));
|
||||
let retained = Retained { source, addend, subtract: false };
|
||||
Self { inputs: inputs.to_vec(), product_on_right, negated: false, operation: "mul", literal_divisor: false, retained: Some(Box::new(retained)) }
|
||||
pub(super) fn returned(inputs: &[usize], terms: super::returned_product::Sum) -> Self {
|
||||
Self {
|
||||
inputs: inputs.to_vec(),
|
||||
product_on_right: false,
|
||||
negated: false,
|
||||
operation: "mul",
|
||||
literal_divisor: false,
|
||||
retained: Some(Box::new(Retained::Lanes(terms))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn evaluate(&self, arguments: &[Value], subtract: bool, state: &EvaluationState) -> Result<Value, String> {
|
||||
let subtract = subtract || self.retained.as_ref().is_some_and(|term| term.subtract);
|
||||
let (a, b, c, blend) = if let Some(term) = &self.retained {
|
||||
let (a, b) = term.source.factors(state)?;
|
||||
let c = match &term.addend {
|
||||
if let Some(Retained::Lanes(terms)) = self.retained.as_deref() {
|
||||
return super::returned_product::evaluate_sum(terms, arguments, state);
|
||||
}
|
||||
let (a, b, c, blend, subtract) = if let Some(Retained::Argument { source, addend, subtract }) = self.retained.as_deref() {
|
||||
let (a, b) = source.factors(state)?;
|
||||
let c = match addend {
|
||||
Addend::Argument(i) => arguments.get(*i).ok_or("missing product addend")?,
|
||||
Addend::Literal(value) => value,
|
||||
};
|
||||
(a, b, c, None)
|
||||
(a, b, c, None, *subtract)
|
||||
} else {
|
||||
let [first, second, third, rest @ ..] = arguments else { return Err("missing product-sum operands".into()) };
|
||||
let (a, b, c) = if self.product_on_right { (second, third, first) } else { (first, second, third) };
|
||||
(a, b, c, rest.first())
|
||||
(a, b, c, rest.first(), subtract)
|
||||
};
|
||||
let width = value_type::dimensions(a);
|
||||
if width != value_type::dimensions(c) || (width != value_type::dimensions(b) && !(self.operation == "mulscalar" && value_type::dimensions(b) == 1)) {
|
||||
@@ -114,7 +120,7 @@ fn called_sum(op: &Instruction, instructions: &[Instruction], usage: &[ProductUs
|
||||
return None;
|
||||
}
|
||||
let &[a, b] = product.inputs.as_slice() else { return None };
|
||||
let retained = Retained { source: Source::local([a, b]), addend: addend.clone(), subtract: sum.definition.id == "sub" };
|
||||
let retained = Retained::Argument { source: Source::local([a, b]), addend: addend.clone(), subtract: sum.definition.id == "sub" };
|
||||
Some(ProductSum {
|
||||
inputs: op.inputs.clone(),
|
||||
product_on_right,
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
use super::{EvaluationState, Program, instruction::Instruction, product_sum::ProductSum, value_type};
|
||||
use super::{EvaluationState, Program, arithmetic::flush_subnormal, instruction::Instruction, product_sum::ProductSum, value_type};
|
||||
use materialcraft_core::Value;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Registers of the factors before the scalar product rounded, in the call that evaluated it.
|
||||
/// Registers and components of the factors in the call that evaluated a product.
|
||||
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) struct Source {
|
||||
calls: Vec<usize>,
|
||||
factors: [usize; 2],
|
||||
components: [usize; 2],
|
||||
}
|
||||
|
||||
impl Source {
|
||||
pub(super) fn local(factors: [usize; 2]) -> Self {
|
||||
Self { calls: Vec::new(), factors }
|
||||
Self { calls: Vec::new(), factors, components: [0, 0] }
|
||||
}
|
||||
|
||||
pub(super) fn factors<'a>(&self, mut state: &'a EvaluationState) -> Result<(&'a Value, &'a Value), String> {
|
||||
@@ -24,6 +25,37 @@ impl Source {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Term {
|
||||
source: Source,
|
||||
on_right: bool,
|
||||
}
|
||||
|
||||
pub(super) type Sum = [Option<Term>; 4];
|
||||
|
||||
pub(super) fn evaluate_sum(terms: &Sum, arguments: &[Value], state: &EvaluationState) -> Result<Value, String> {
|
||||
let [left, right] = arguments else { return Err("missing addition operands".into()) };
|
||||
let width = value_type::dimensions(left);
|
||||
if width != value_type::dimensions(right) {
|
||||
return Err("float operands must have the same dimensions".into());
|
||||
}
|
||||
let left = value_type::floats(left)?.map(flush_subnormal);
|
||||
let right = value_type::floats(right)?.map(flush_subnormal);
|
||||
let mut result = [0.0; 4];
|
||||
for (((output, term), left), right) in result.iter_mut().zip(terms).zip(left).zip(right).take(width) {
|
||||
let sum = if let Some(term) = term {
|
||||
let (a, b) = term.source.factors(state)?;
|
||||
let [i, j] = term.source.components;
|
||||
let a = *value_type::floats(a)?.get(i).ok_or("invalid product component")?;
|
||||
let b = *value_type::floats(b)?.get(j).ok_or("invalid product component")?;
|
||||
flush_subnormal(a).mul_add(flush_subnormal(b), if term.on_right { left } else { right })
|
||||
} else {
|
||||
left + right
|
||||
};
|
||||
*output = flush_subnormal(sum);
|
||||
}
|
||||
value_type::intermediate_float_value(result.get(..width).ok_or("invalid addition dimensions")?)
|
||||
}
|
||||
|
||||
pub(super) type Lanes = [Option<Source>; 4];
|
||||
type Origins = [Option<usize>; 4];
|
||||
|
||||
@@ -66,7 +98,8 @@ pub(super) fn identify(program: &mut Program, mut returned: BTreeMap<usize, Lane
|
||||
let empty = || std::array::from_fn(|_| None);
|
||||
// Loop iterations invalidate individual registers. Only retain factors for straight-line lifetimes.
|
||||
if program.instructions.iter().any(|op| op.definition.id == "while")
|
||||
|| (returned.is_empty() && !program.instructions.iter().any(|op| op.definition.id == "mul" && op.type_code == 256 && !op.literal))
|
||||
|| (returned.is_empty()
|
||||
&& !program.instructions.iter().any(|op| matches!(op.definition.id, "mul" | "mulscalar") && float_width(op.type_code) > 0 && !op.literal))
|
||||
{
|
||||
return empty();
|
||||
}
|
||||
@@ -85,25 +118,28 @@ pub(super) fn identify(program: &mut Program, mut returned: BTreeMap<usize, Lane
|
||||
*uses += 1;
|
||||
}
|
||||
}
|
||||
if op.definition.id == "add" && op.type_code == 256 && op.pixel_product_sum.is_none() {
|
||||
let mut candidates = op.inputs.iter().enumerate().filter_map(|(slot, input)| {
|
||||
let input_op = program.instructions.get(*input)?;
|
||||
if !matches!(input_op.definition.id, "swizzle1" | "instance") {
|
||||
return None;
|
||||
}
|
||||
Some((index, origins.get(*input)?[0]?, slot == 1))
|
||||
});
|
||||
if let Some(sum) = candidates.next()
|
||||
&& candidates.next().is_none()
|
||||
{
|
||||
sums.push(sum);
|
||||
let width = float_width(op.type_code);
|
||||
if op.definition.id == "add"
|
||||
&& width > 0
|
||||
&& op.pixel_product_sum.is_none()
|
||||
&& let &[left, right] = op.inputs.as_slice()
|
||||
{
|
||||
let sides = [left, right].map(|i| origins.get(i).copied().unwrap_or([None; 4]));
|
||||
if sides.iter().flatten().any(Option::is_some) {
|
||||
sums.push((index, sides));
|
||||
}
|
||||
}
|
||||
|
||||
let mut lanes = [None; 4];
|
||||
if let ("mul", 256, false, &[a, b]) = (op.definition.id, op.type_code, op.literal, op.inputs.as_slice()) {
|
||||
lanes[0] = Some(products.len());
|
||||
products.push((Source::local([a, b]), 0));
|
||||
if matches!(op.definition.id, "mul" | "mulscalar")
|
||||
&& !op.literal
|
||||
&& let &[a, b] = op.inputs.as_slice()
|
||||
{
|
||||
for (i, lane) in lanes.iter_mut().take(width).enumerate() {
|
||||
*lane = Some(products.len());
|
||||
let j = if op.definition.id == "mulscalar" { 0 } else { i };
|
||||
products.push((Source { components: [i, j], ..Source::local([a, b]) }, 0));
|
||||
}
|
||||
} else if let Some(exports) = returned.remove(&index) {
|
||||
// Two returned lanes can reference the same product. Count their downstream reads together.
|
||||
let mut distinct = BTreeMap::new();
|
||||
@@ -131,11 +167,19 @@ pub(super) fn identify(program: &mut Program, mut returned: BTreeMap<usize, Lane
|
||||
*uses += 1;
|
||||
}
|
||||
}
|
||||
for (index, id, on_right) in sums {
|
||||
if let Some((source, 1)) = products.get(id)
|
||||
for (index, sides) in sums {
|
||||
let terms: Sum = std::array::from_fn(|i| {
|
||||
// A shared lane has already rounded. When both products are free, the left one contracts.
|
||||
sides.iter().enumerate().find_map(|(side, lanes)| {
|
||||
let id = lanes.get(i).copied().flatten()?;
|
||||
let (source, uses) = products.get(id)?;
|
||||
(*uses == 1).then(|| Term { source: source.clone(), on_right: side == 1 })
|
||||
})
|
||||
});
|
||||
if terms.iter().any(Option::is_some)
|
||||
&& let Some(op) = program.instructions.get_mut(index)
|
||||
{
|
||||
op.pixel_product_sum = Some(ProductSum::returned(&op.inputs, on_right, source.clone()));
|
||||
op.pixel_product_sum = Some(ProductSum::returned(&op.inputs, terms));
|
||||
}
|
||||
}
|
||||
exported
|
||||
|
||||
@@ -491,6 +491,61 @@ fn a_pixel_quotient_rounds_with_the_subtraction_in_a_called_function() {
|
||||
assert_eq!(pixel(&graph), Value::Float2([0xbf7f502f, 0x3fe617b8].map(f32::from_bits)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_sums_use_the_unrounded_product_of_each_independently_returned_lane() {
|
||||
use materialcraft_core::{GraphInstance, GraphPort};
|
||||
let mut body = FunctionGraph::default();
|
||||
let [left, right] = ["left", "right"].map(|name| body.add("get_float2", &[], Some(Value::Text(name.into()))));
|
||||
let product = body.add("mul", &[left, right], None);
|
||||
let side = body.add("get_float1", &[], Some(Value::Text("side".into())));
|
||||
let side = body.add("set", &[side], Some(Value::Text("last".into())));
|
||||
body.output = Some(body.add("vector3", &[product, side], None));
|
||||
let source = std::sync::Arc::new(body);
|
||||
let interface = GraphInstance {
|
||||
label: String::new(),
|
||||
package: String::new(),
|
||||
graph: "pair".into(),
|
||||
inputs: [("left", 512), ("right", 512), ("side", 256)].map(|(name, type_code)| GraphPort { identifier: name.into(), type_code }).into(),
|
||||
outputs: Vec::new(),
|
||||
defaults: [("left", Value::Float2([0.0; 2])), ("right", Value::Float2([0.0; 2])), ("side", Value::Float(0.0))].map(|(k, v)| (k.into(), v)).into(),
|
||||
};
|
||||
let mut graph = FunctionGraph::default();
|
||||
let [r, g, b, a] = ["r", "g", "b", "a"].map(|name| graph.add("get_float1", &[], Some(Value::Text(name.into()))));
|
||||
let [rg, ba, gr] = [[r, g], [b, a], [g, r]].map(|xy| graph.add("vector2", &xy, None));
|
||||
let [first, second] = [[rg, ba, a], [ba, gr, r]].map(|arguments| {
|
||||
let call = graph.add("instance", &arguments, None);
|
||||
let node = graph.nodes.last_mut().unwrap();
|
||||
node.instance = Some(interface.clone());
|
||||
node.source = Some(Ok(source.clone()));
|
||||
call
|
||||
});
|
||||
let sum = graph.add("add", &[first, second], None);
|
||||
let variables = ["r", "g", "b", "a"]
|
||||
.map(str::to_owned)
|
||||
.into_iter()
|
||||
.zip([0xc05f3333, 0x40680000, 0x3f600000, 0xbf200000].map(|v| Value::Float(f32::from_bits(v))))
|
||||
.collect();
|
||||
let context = EvaluationContext {
|
||||
image_formats: &[],
|
||||
scope: super::FunctionScope::PixelProcessor,
|
||||
position: [0.5; 2],
|
||||
size: [1.0; 2],
|
||||
images: &[],
|
||||
tile: true,
|
||||
variables: &variables,
|
||||
};
|
||||
for (read, lane, expected) in [
|
||||
(first, 0, [0x3df66660, 0xbdb00000, 0xc083999a, 0xc0434ccd]),
|
||||
(second, 0, [0x3df6666c, 0xbdb00000, 0xc083999a, 0x404b0000]),
|
||||
(first, 2, [0x3df6666c, 0xbdb00000, 0xc083999a, 0xbf200000]),
|
||||
] {
|
||||
let exposed = graph.add("swizzle1", &[read], Some(Value::Int(lane)));
|
||||
graph.output = Some(graph.add("vector4", &[sum, exposed], None));
|
||||
let value = compile(&graph, 0).unwrap().evaluate_pixel(&context, &mut EvaluationState::default()).unwrap();
|
||||
assert_eq!(value, Value::Float4(expected.map(f32::from_bits)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_sums_contract_negated_products_and_preserve_shared_rounded_addends() {
|
||||
let values = [0xc0742acf, 0xbf116093, 0x405370ba, 0x3f3eb229].map(|bits| Value::Float(f32::from_bits(bits)));
|
||||
|
||||
@@ -843,6 +843,22 @@ Nine independent graphs match **158,976/158,976 pixels in 54 renders**, maximum
|
||||
|
||||
A tenth helper that both subtracts the quotient and adds it back internally still matches 16,011/17,664 pixels, maximum one U16 level or .000751018524 in F32. The measured correction covers the single-operation helper.
|
||||
|
||||
### Vector products in the direct-light pass
|
||||
|
||||
| Comparison | Renders | Exact RGBA pixels / compared | Maximum error |
|
||||
|---|---:|---:|---:|
|
||||
| Volume direct light, final output | 46 | 43,264/43,264 | 0 |
|
||||
| Vector products returned through calls | 96 | 282,624/282,624 | 0 |
|
||||
| Sums of two, four and eight returned products | 6 | 3,840/3,840 | 0 |
|
||||
|
||||
All 7,424 U8, 7,424 U16, 10,752 F16 and 17,664 F32 direct-light pixels match. Use the [volume light fields, seeds and parameters](#uniform-powers-of-two-and-volume-lighting). The last differing pixel was red at (2,60) in the changed 64² F32 render. At that pixel the secondary lighting processor now stores .007045745849609375 in F16. Forcing that stage to F32 gives bits 3be6ffff in both engines. The final red now has bits 3c198a4c.
|
||||
|
||||
For the independent graphs, take the upper-left 16², 64² and 32² corners of the signed 128² [four-channel hash field](#3d-linear-gradient), multiply green by .75, and replace the first two texels with (3.25,.3,1,.0625) and (−3.4875,3.625,.875,−.625). Use seeds 47, 223 and 449 respectively, selecting all four formats at 64² and F32 elsewhere. Have a function return ((a,b)×(c,d),d). Call it with (R,G,B,A) and (B,A,G,R), then sum the two returned vectors. Repeat with vector-by-scalar multiplication by c, with the two product lanes swapped, and with an assignment returning d in the third lane. For each version, export the sum, then expose each returned product’s first lane in turn, then expose the first call’s third lane. At the second texel the red sum has F32 bits 3df6666c. Exposing the first product changes the red sum to 3df66660. Reading the other component keeps the first value. Each single-consumer component contracts with its addend using its evaluated factors, including when its sibling performs an assignment. All 594,432 pixels in the [scalar packing and call controls](#pixel-products-carried-through-vector-lanes-and-calls) also match.
|
||||
|
||||
The eight isolated ambient samples explain the original rounding discrepancy. For sample i let aᵢ be its stored alpha and let uᵢ be the F32 product of (1−aᵢ) and channel coefficient 3e5b2d9a, 3ea31892 or 3f800000 (F32 bits). With background b=.03310475870966911, every isolated color channel equals the rounded b×uᵢ. Start the eight-term sum with FMA(b,u₀,round(b×u₁)), apply FMA(b,uᵢ,sum) for i=2 through 7, then multiply by .125. This reconstructs every reference RGB value at 64². MaterialCraft’s normal F16 secondary stage now matches all 12,288 RGB components. At forced F32, 4,088, 4,090 and 4,089 of 4,096 components match in R, G and B.
|
||||
|
||||
A separate difference survives inside the secondary stage. Its normal F16 alpha matches at 3,109/4,096 pixels, maximum .05224609375. In the observed mean, reference alpha equals the eighth ambient sample at all 4,096 pixels. A two-call control returning a pair (set a variable to x, read that variable) reproduces this ordering difference. Explicitly sequencing the write before the read in each call gives matching results. The final direct-light output matches in all 46 cases above.
|
||||
|
||||
### Pixel products carried through vector lanes and calls
|
||||
|
||||
| Comparison | Renders | Exact stored pixels / compared | Maximum error |
|
||||
|
||||
@@ -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 **312 Parity**, **47 In progress** and **187 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 **313 Parity**, **46 In progress** and **187 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)
|
||||
|
||||
@@ -63,7 +63,7 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard
|
||||
| [3d_texture_render.sbs/3d_texture_surface_render_irradiance](../assets/sbs/3d_texture_render.sbs) | 6 | Yes | [Parity · 47,360 exact pixels in 71 renders](parity-fixes.md#surface-irradiance-and-uniform-power) |
|
||||
| [3d_texture_render.sbs/3d_texture_surface_render_position](../assets/sbs/3d_texture_render.sbs) | 1 | Yes | [Parity · 92,928 exact pixels in 39 renders](parity-fixes.md#surface-position-and-signed-pixel-products) |
|
||||
| [3d_texture_render.sbs/3d_texture_volume_render_ibl_pass](../assets/sbs/3d_texture_render.sbs) | 6 | Yes | [In progress · 7,898/31,488 pixels, first dithered step differs](parity-fixes.md#pixel-products-carried-through-vector-lanes-and-calls) |
|
||||
| [3d_texture_render.sbs/3d_texture_volume_render_light_pass](../assets/sbs/3d_texture_render.sbs) | 4 | Yes | [In progress · 43,263/43,264 pixels, one F32 red channel differs](parity-fixes.md#pixel-products-carried-through-vector-lanes-and-calls) |
|
||||
| [3d_texture_render.sbs/3d_texture_volume_render_light_pass](../assets/sbs/3d_texture_render.sbs) | 4 | Yes | [Parity · 46 renders, all 43,264 RGBA pixels exact](parity-fixes.md#vector-products-in-the-direct-light-pass) |
|
||||
| [3d_texture_render.sbs/position_debug](../assets/sbs/3d_texture_render.sbs) | 2 | Yes | [Parity · 14 sphere and plane cases](parity-fixes.md#position-debug) |
|
||||
| [3d_texture_transform.sbs/3d_texture_offset_color](../assets/sbs/3d_texture_transform.sbs) | 1 | No | [Parity: 5 cases](parity-fixes.md#verified-cases) |
|
||||
| [3d_texture_transform.sbs/3d_texture_offset_grayscale](../assets/sbs/3d_texture_transform.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) |
|
||||
|
||||
Reference in new issue
Block a user