CultMath: rgb_to_hsv divides by 6 the way Cycles' kernel does (a multiply by 1/6); the ramp is checked by a constant ramp (index) and a linear one (weight); Map Range sockets by their identifiers; the mirror pins 115 functions

Builds. Fixtures and CultMath.Cycles.glsl are still to come.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-12 05:51:30 +02:00
commit 892cfbaa6a
6 changed files with 86 additions and 65 deletions

View file

@ -263,7 +263,7 @@ float3 cultmath_cycles_rgb_to_hsv(float3 rgb)
float s = cmax != 0.0 ? cdelta / cmax : 0.0;
float3 c = (float3(cmax, cmax, cmax) - rgb) / cdelta;
float h = rgb.x == cmax ? c.z - c.y : (rgb.y == cmax ? 2.0 + c.x - c.z : 4.0 + c.y - c.x);
h = h / 6.0;
h = h * 0.16666667; // Cycles' kernel is built with reciprocal math: h /= 6.0f computes h * (1 / 6.0f).
h = h < 0.0 ? h + 1.0 : h;
return float3(s != 0.0 ? h : 0.0, s, cmax);
}

View file

@ -285,7 +285,7 @@ public static partial class math
var s = cmax != 0.0f ? cdelta / cmax : 0.0f;
var c = (new float3(cmax, cmax, cmax) - rgb) / cdelta;
var h = rgb.x == cmax ? c.z - c.y : (rgb.y == cmax ? 2.0f + c.x - c.z : 4.0f + c.y - c.x);
h = h / 6.0f;
h = h * 0.16666667f; // Cycles' kernel is built with reciprocal math: h /= 6.0f computes h * (1 / 6.0f).
h = h < 0.0f ? h + 1.0f : h;
return new float3(s != 0.0f ? h : 0.0f, s, cmax);
}

View file

@ -129,38 +129,56 @@ public sealed class CyclesOracleTests
}
[Fact]
public void RampIndexAndWeightReproduceBlendersLookup()
public void RampIndexNamesTheEntryBlenderReads()
{
var fixture = Load("ramp");
var entry = fixture["functions"]!.AsArray().Single()!;
var entry = Load("ramp")["functions"]!.AsArray().Single(e => (string)e!["node"]!.ToString() == "ShaderNodeValToRGB CONSTANT")!;
var size = (int)entry["table_entries"]!;
var stops = entry["stops"]!.AsArray().Select(stop => (Position: Float((string)stop![0]!), Value: Float((string)stop[1]!))).ToArray();
// A constant ramp's table: the value of the last stop at or before the entry's position.
var table = Enumerable.Range(0, size).Select(i =>
{
var position = (double)i / (size - 1);
var stop = stops.LastOrDefault(s => s.Position <= position);
return stop == default ? stops[0].Value : stop.Value;
}).ToArray();
var cases = entry["cases"]!.AsArray().Select(line => ((string)line!).Split(" -> ")).ToArray();
// The first `size` cases are the table: each t reads its own entry (weight 0), so the result is the entry.
var table = new float[size];
for (var k = 0; k < size; k++)
Assert.True(table.Distinct().Count() > 30, "the constant ramp's table should name 32 entries apart");
foreach (var line in cases)
{
var t = Float(cases[k][0]);
var lookup = math.cycles_ramp_index(t, size);
Assert.Equal((float)k, lookup.x);
Assert.Equal(0.0f, lookup.y);
table[k] = Float(cases[k][1]);
}
var interpolated = 0;
for (var c = size; c < cases.Length; c++)
{
var t = Float(cases[c][0]);
var t = Float(line[0]);
var lookup = math.cycles_ramp_index(t, size);
var index = (int)lookup.x;
Assert.InRange(index, 0, size - 1);
var have = lookup.y > 0.0f ? (1.0f - lookup.y) * table[index] + lookup.y * table[index + 1] : table[index];
interpolated += lookup.y > 0.0f ? 1 : 0;
var want = Float(cases[c][1]);
Assert.True(Distance(want, have) == 0, $"ramp t {cases[c][0]}: index {index}, weight {lookup.y}, got {have}, Blender {want}");
Assert.True(Distance(Float(line[1]), table[index]) == 0, $"ramp t {line[0]}: index {index} reads {table[index]}, Blender {Float(line[1])}");
}
Assert.True(interpolated > 100, "the fixture holds too few interpolated lookups");
// Every stop's value appears in the results at its own boundary, so the cases do cross the entries.
Assert.True(cases.Select(line => line[1]).Distinct().Count() >= 32, "the cases never cross the stops");
}
[Fact]
public void RampWeightBlendsTheEntryWithTheNextOne()
{
// A linear ramp from 0 to 1: entry i holds i / 255 to within the float rounding of Blender's table, and a
// lookup at (index, weight) reads (index + weight) / 255. A weight that is off by a fraction of a
// percent, or an index that is off by one, moves the result by more than the bound.
var entry = Load("ramp")["functions"]!.AsArray().Single(e => (string)e!["node"]!.ToString() == "ShaderNodeValToRGB LINEAR")!;
var size = (int)entry["table_entries"]!;
var worst = 0.0;
var fractional = 0;
foreach (var line in entry["cases"]!.AsArray().Select(line => ((string)line!).Split(" -> ")))
{
var lookup = math.cycles_ramp_index(Float(line[0]), size);
Assert.InRange(lookup.y, 0.0f, 1.0f);
fractional += lookup.y > 0.0f ? 1 : 0;
var expected = (lookup.x + lookup.y) / (size - 1);
worst = Math.Max(worst, Math.Abs(expected - Float(line[1])));
}
Assert.True(fractional > 500, "the cases hold too few interpolated lookups");
Assert.True(worst <= Math.ScaleB(1.0, -22), $"a lookup is {worst} from (index + weight) / 255, more than 2^-22");
}
[Fact]

View file

@ -137,7 +137,7 @@ public sealed class HlslSourceCompatibilityTests
}
Assert.True(mismatches.Count == 0, $"{mismatches.Count} mismatches:{Environment.NewLine}{string.Join(Environment.NewLine, mismatches.Take(12))}");
Assert.Equal(67, compared.Count);
Assert.Equal(115, compared.Count);
}
/// <summary>

View file

@ -311,7 +311,7 @@ def family_map_range():
node.interpolation_type = kind
node.clamp = False
sockets = operand_sockets(tree, imgs, 6)
for k, identifier in enumerate(["Value", "From_Min_FLOAT", "From_Max_FLOAT", "To_Min_FLOAT", "To_Max_FLOAT", "Steps_FLOAT"]):
for k, identifier in enumerate(["Value", "From Min", "From Max", "To Min", "To Max", "Steps"]):
socket = by_identifier(node.inputs, identifier)
tree.links.new(sockets[k], socket)
return [node.outputs["Result"]]
@ -324,7 +324,7 @@ def family_map_range():
node.interpolation_type = kind
node.clamp = True
sockets = operand_sockets(tree, imgs, 6)
for k, identifier in enumerate(["Value", "From_Min_FLOAT", "From_Max_FLOAT", "To_Min_FLOAT", "To_Max_FLOAT", "Steps_FLOAT"]):
for k, identifier in enumerate(["Value", "From Min", "From Max", "To Min", "To Max", "Steps"]):
socket = by_identifier(node.inputs, identifier)
tree.links.new(sockets[k], socket)
return [node.outputs["Result"]]
@ -439,54 +439,57 @@ def family_rgb_to_bw():
RAMP_SIZE = 256
RAMP_STOPS = [(0.0, 0.0), (0.3, 1.0), (1.0, 0.25)]
# A constant ramp whose 32 stops sit half an entry past an entry boundary: its table is the stops' values, so
# a lookup's result names the entry it read.
CONSTANT_STOPS = [((8 * j + 3.5) / (RAMP_SIZE - 1), (j + 1) / 32.0) for j in range(32)]
def family_ramp():
rng = rng_for("ramp")
# The table: one case per entry, at a t whose float32 product with 255 is the entry's index, so the
# lookup returns the entry itself.
table_t = []
for k in range(RAMP_SIZE):
base = np.float32(k) / np.float32(RAMP_SIZE - 1)
found = None
candidate = base
for _ in range(8):
if np.float32(candidate * np.float32(RAMP_SIZE - 1)) == np.float32(k):
found = candidate
break
candidate = np.nextafter(candidate, np.float32(2.0))
if found is None:
candidate = base
for _ in range(8):
candidate = np.nextafter(candidate, np.float32(-1.0))
if np.float32(candidate * np.float32(RAMP_SIZE - 1)) == np.float32(k):
found = candidate
break
if found is None:
raise RuntimeError("no float32 t reads ramp entry %d exactly" % k)
table_t.append(found)
specials = [-0.5, -0.25, -1.0e-7, 0.0, 1.0e-7, 0.001, 0.002, 0.5, 0.25, 0.999, 1.0, 1.0000001, 1.25, 1.5, 0.3, 0.29999998, 0.30000004]
values = list(table_t) + specials
def ramp_cases(rng, boundaries):
"""CASES values of t: the floats around each boundary t = i / 255, the specials, then uniform draws."""
values = []
for i in boundaries:
t = np.float32(i / (RAMP_SIZE - 1))
down = [t]
up = [t]
for _ in range(7):
down.append(np.nextafter(down[-1], np.float32(-1.0)))
up.append(np.nextafter(up[-1], np.float32(2.0)))
values += sorted(set(down + up))
values += [-0.5, -1.0e-7, 0.0, 1.0e-7, 1.0, 1.0000001, 1.5]
while len(values) < CASES:
values.append(float(rng.uniform(-0.25, 1.25)))
column = f32(values[:CASES])
return f32(values[:CASES])
def ramp_entry(label, interpolation, stops, boundaries):
rng = rng_for("ramp-" + label)
column = ramp_cases(rng, boundaries)
images = pack_operands([column])
def build(tree, imgs):
node = tree.nodes.new("ShaderNodeValToRGB")
node.color_ramp.interpolation = "LINEAR"
elements = node.color_ramp.elements
while len(elements) < len(RAMP_STOPS):
elements.new(0.5)
for element, (position, red) in zip(elements, RAMP_STOPS):
element.position = position
ramp = node.color_ramp
ramp.interpolation = interpolation
ramp.elements[0].position = stops[0][0]
ramp.elements[1].position = stops[-1][0]
for position, _ in stops[1:-1]:
ramp.elements.new(position)
for element, (_, red) in zip(ramp.elements, stops):
element.color = (red, 0.0, 0.0, 1.0)
tree.links.new(operand_sockets(tree, imgs, 1)[0], node.inputs["Fac"])
return [node.outputs["Color"]]
return [{"function": "cycles_ramp_index", "node": "ShaderNodeValToRGB LINEAR size %d stops %s" % (RAMP_SIZE, json.dumps(RAMP_STOPS)),
"table_entries": RAMP_SIZE, "cases": encode_cases([column], bake("ramp", images, build, 1))}]
return {"function": "cycles_ramp_index", "node": "ShaderNodeValToRGB " + interpolation, "table_entries": RAMP_SIZE,
"stops": [[bits(position), bits(red)] for position, red in stops],
"cases": encode_cases([column], bake("ramp-" + label, images, build, 1))}
def family_ramp():
boundaries = [8 * j + 4 for j in range(32)]
return [
ramp_entry("constant", "CONSTANT", CONSTANT_STOPS, boundaries),
ramp_entry("linear", "LINEAR", [(0.0, 0.0), (1.0, 1.0)], list(range(1, RAMP_SIZE, 17))),
]
FAMILIES = {

View file

@ -263,7 +263,7 @@ float3 cultmath_cycles_rgb_to_hsv(float3 rgb)
float s = cmax != 0.0 ? cdelta / cmax : 0.0;
float3 c = (float3(cmax, cmax, cmax) - rgb) / cdelta;
float h = rgb.x == cmax ? c.z - c.y : (rgb.y == cmax ? 2.0 + c.x - c.z : 4.0 + c.y - c.x);
h = h / 6.0;
h = h * 0.16666667; // Cycles' kernel is built with reciprocal math: h /= 6.0f computes h * (1 / 6.0f).
h = h < 0.0 ? h + 1.0 : h;
return float3(s != 0.0 ? h : 0.0, s, cmax);
}