Interactive 2D wave optics simulator. Turn any image into a refractive scene, add sources, watch waves refract, diffract and interfere. Probes, intensity maps, video export.
C#
An 8-bit run exports the same bytes as a 16-bit run: the palette index comes from the half-rounded sample
Alexander Graef796c4a8c81ab
diff --git a/CLAUDE.md b/CLAUDE.mdindex 56f25fc..0db123e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -110,7 +110,11 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAin 16-bit, half in 8-bit.- **Reduced preview** (View menu): resolution 1/2/4, frames 1/2/4 (the timeline never changes), samples 16-bit or**8-bit palette index, the default**: the same pixels at the captured brightness, half the store, half the- colouring; 16-bit keeps the brightness turnable after a run. In 8-bit a brightness edit is a simulation edit.+ colouring; 16-bit keeps the brightness turnable after a run. In 8-bit a brightness edit is a simulation edit. The+ index is computed from the sample rounded to a half, on the CPU and in the kernel (a bit-level rounding there), and+ the GPU program is built with a correctly rounded square root where the card has one, so an 8-bit run exports the+ same bytes as a 16-bit run of the same project (2026-10-19, two such exports had differed by a palette step in half a+ percent of the pixels).A picture export takes an 8-bit run as it is (the same pixels; 2026-10-18); an EXR data export, a reduced resolution orskipped frames make the export run the simulation again at full quality first.diff --git a/WaveDudeNext/Engine/FrameShape.cs b/WaveDudeNext/Engine/FrameShape.csindex bb718f8..67b39ef 100644--- a/WaveDudeNext/Engine/FrameShape.cs+++ b/WaveDudeNext/Engine/FrameShape.cs@@ -98,7 +98,8 @@ public static class FrameConversion/// Converts one plane. For a divisor of 1 a <see cref="FrameFormat.Half"/> plane is the vectorised/// float-to-half conversion; otherwise every block of <see cref="FrameShape.Divisor"/>² cells (fewer at the/// right and bottom edges) is averaged first, then the sample is taken as a half or as the palette index- /// (<see cref="ColorLut.FieldIndex"/> or <see cref="ColorLut.IntensityIndex(float, float)"/> with the shape's brightness).+ /// (<see cref="ColorLut.FieldIndex"/> or <see cref="ColorLut.IntensityIndex(float, float)"/> with the shape's brightness)+ /// of the sample rounded to a half, so an index frame holds exactly what a half frame renders to (2026-10-19)./// </summary>/// <param name="source">The float values; row y of the canvas starts at <paramref name="offset"/> + y × <paramref name="stride"/>.</param>/// <param name="offset">Index of the canvas's first cell in <paramref name="source"/> (stride + 1 for an engine's padded buffer, 0 for a packed plane).</param>@@ -146,14 +147,14 @@ public static class FrameConversion{for (int x = 0; x < width; x++){- target[x] = (byte)ColorLut.IntensityIndex(row[x], brightness);+ target[x] = (byte)ColorLut.IntensityIndex((float)(Half)row[x], brightness);}}else{for (int x = 0; x < width; x++){- target[x] = (byte)ColorLut.FieldIndex(row[x], brightness);+ target[x] = (byte)ColorLut.FieldIndex((float)(Half)row[x], brightness);}}}diff --git a/WaveDudeNext/Engine/GpuDeviceInfo.cs b/WaveDudeNext/Engine/GpuDeviceInfo.csindex d4a7883..2696bc0 100644--- a/WaveDudeNext/Engine/GpuDeviceInfo.cs+++ b/WaveDudeNext/Engine/GpuDeviceInfo.cs@@ -90,6 +90,7 @@ public sealed class GpuDeviceInfoName = name.Length == 0 ? "GPU" : name,Vendor = OpenClApi.DeviceString(id, OpenClApi.DeviceVendor),Discrete = OpenClApi.DeviceNumber(id, OpenClApi.DeviceHostUnifiedMemory) == 0UL,+ CorrectlyRoundedSqrt = (OpenClApi.DeviceNumber(id, OpenClApi.DeviceSingleFpConfig) & OpenClApi.FpCorrectlyRoundedDivideSqrt) != 0UL,Score = computeUnits * Math.Max(1.0, clockMhz),// Mask the sign bit so an odd 64-bit value cannot turn into a negative size.GlobalMemory = (long)(OpenClApi.DeviceNumber(id, OpenClApi.DeviceGlobalMemSize) & 0x7FFFFFFFFFFFFFFFUL),@@ -112,6 +113,13 @@ public sealed class GpuDeviceInfo/// <summary>True for a card with its own memory (the NVIDIA GeForce; CL_DEVICE_HOST_UNIFIED_MEMORY is 0), false for the graphics of the processor (Intel UHD).</summary>public bool Discrete { get; private init; }+ /// <summary>+ /// Whether the device can divide and take square roots correctly rounded in single precision (the OpenCL build+ /// option <c>-cl-fp32-correctly-rounded-divide-sqrt</c>): then the 8-bit palette index it captures equals the one the+ /// CPU renders from a 16-bit frame, bit for bit (2026-10-19). Without it an index at a boundary may differ by one.+ /// </summary>+ public bool CorrectlyRoundedSqrt { get; private init; }+/// <summary>Compute units times clock (MHz, at least 1): a rough measure of the speed.</summary>public double Score { get; private init; }diff --git a/WaveDudeNext/Engine/GpuWaveSimulator.cs b/WaveDudeNext/Engine/GpuWaveSimulator.csindex 38532f4..03c8cd6 100644--- a/WaveDudeNext/Engine/GpuWaveSimulator.cs+++ b/WaveDudeNext/Engine/GpuWaveSimulator.cs@@ -747,14 +747,35 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablesource.AppendLine("}");source.AppendLine();// the index mapping of ColorLut.FieldIndex / IntensityIndex: a NaN field gives the centre, a NaN or- // non-positive intensity 0; the sqrt is the card's single-precision one, so an index may differ by one- // from the host's double at a boundary+ // non-positive intensity 0. The sample is first rounded to half precision, as capture_half stores it, so the+ // index equals the one the CPU renders from a 16-bit frame bit for bit (2026-10-19: an 8-bit run and a 16-bit+ // run of the same project exported pictures that differed by a palette step in half a percent of the pixels).+ // The rounding is done on the float's bits, since a half variable needs an extension; it is round to nearest+ // even, half's subnormals and overflow included. No contraction here: the CPU's multiply and add are separate+ source.AppendLine("float round_to_half(float f)");+ source.AppendLine("{");+ source.AppendLine(" uint u = as_uint(f);");+ source.AppendLine(" uint sign = u & 0x80000000u;");+ source.AppendLine(" uint a = u & 0x7FFFFFFFu;");+ source.AppendLine(" if (a >= 0x7F800000u) return f; // inf or nan");+ source.AppendLine(" if (a >= 0x477FF000u) return as_float(sign | 0x7F800000u); // 65520 and up round to inf");+ source.AppendLine(" if (a < 0x38800000u) { // below 2^-14: a subnormal half, a multiple of 2^-24");+ source.AppendLine(" float q = rint(as_float(a) * 16777216.0f) * 5.9604644775390625e-8f;");+ source.AppendLine(" return as_float(sign | as_uint(q));");+ source.AppendLine(" }");+ source.AppendLine(" uint rest = a & 0x1FFFu; // the 13 bits a half drops");+ source.AppendLine(" uint kept = a & ~0x1FFFu;");+ source.AppendLine(" if (rest > 0x1000u || (rest == 0x1000u && (kept & 0x2000u))) kept += 0x2000u;");+ source.AppendLine(" return as_float(sign | kept);");+ source.AppendLine("}");+ source.AppendLine();+ source.AppendLine("#pragma OPENCL FP_CONTRACT OFF");source.AppendLine("__kernel void capture_index(__global const float* src, __global uchar* dst, const int w, const int h, const int stride, const int div, const int fw, const int fh, const float brightness, const int intensity)");source.AppendLine("{");source.AppendLine(" int x = get_global_id(0);");source.AppendLine(" int y = get_global_id(1);");source.AppendLine(" if (x >= fw || y >= fh) return;");- source.AppendLine(" float v = capture_sample(src, w, h, stride, div, x, y);");+ source.AppendLine(" float v = round_to_half(capture_sample(src, w, h, stride, div, x, y));");source.AppendLine(" int index;");source.AppendLine(" if (intensity)");source.AppendLine(" index = v > 0.0f ? (int)(fmin(sqrt(v) * brightness, 1.0f) * 254.0f) : 0;");@@ -775,7 +796,14 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposableIntPtr program = OpenClApi.clCreateProgramWithSource(_context, 1U, new[] { source }, null, ref err);OpenClApi.Check(err, "clCreateProgramWithSource");IntPtr[] deviceIds = { _device.DeviceId };- err = OpenClApi.clBuildProgram(program, 1U, deviceIds, "", IntPtr.Zero, IntPtr.Zero);+ // a correctly rounded square root where the card has one: the 8-bit index capture then equals the CPU's+ // MathF.Sqrt bit for bit (2026-10-19); the pulse shapes' divisions only come closer to the host's as well+ string options = _device.CorrectlyRoundedSqrt ? "-cl-fp32-correctly-rounded-divide-sqrt" : "";+ if (!_device.CorrectlyRoundedSqrt)+ {+ Logger.Debug("The card's single-precision square root is not correctly rounded: an 8-bit palette index may differ by one from a 16-bit render at a boundary");+ }+ err = OpenClApi.clBuildProgram(program, 1U, deviceIds, options, IntPtr.Zero, IntPtr.Zero);if (err != 0){string buildLog = OpenClApi.BuildLog(program, _device.DeviceId);@@ -860,6 +888,9 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable/// <summary>Engine label for the UI/result: "GPU: <device name> (OpenCL)".</summary>public string Description { get; }+ /// <summary>The card this engine runs on.</summary>+ public GpuDeviceInfo Device => _device;+/// <summary>Scene width in cells (canvas pixels), excluding the padding.</summary>public int Width => _width;@@ -1409,6 +1440,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposableprivate IntPtr _probeProgram;/// <summary>The device the context lives on; needed again to build the probe program.</summary>+ private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();private readonly GpuDeviceInfo _device;/// <summary>Scene width in cells (canvas pixels), without padding.</summary>diff --git a/WaveDudeNext/Engine/OpenClApi.cs b/WaveDudeNext/Engine/OpenClApi.csindex 8c831db..38c44f5 100644--- a/WaveDudeNext/Engine/OpenClApi.cs+++ b/WaveDudeNext/Engine/OpenClApi.cs@@ -360,6 +360,12 @@ internal static class OpenClApi/// <summary>CL_DEVICE_HOST_UNIFIED_MEMORY (0x1035), cl_bool: non-zero for devices sharing host memory (integrated GPUs).</summary>internal const uint DeviceHostUnifiedMemory = 0x1035U;+ /// <summary>CL_DEVICE_SINGLE_FP_CONFIG (0x101B), cl_device_fp_config: the single-precision capabilities as a bit field.</summary>+ internal const uint DeviceSingleFpConfig = 0x101BU;++ /// <summary>CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT (1 << 7): the device can build with <c>-cl-fp32-correctly-rounded-divide-sqrt</c>.</summary>+ internal const ulong FpCorrectlyRoundedDivideSqrt = 1UL << 7;+/// <summary>CL_PROGRAM_BUILD_LOG (0x1183), string.</summary>internal const uint ProgramBuildLog = 0x1183U;}diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.csindex 5b48717..ecdc41c 100644--- a/_tools/library_check/Program.cs+++ b/_tools/library_check/Program.cs@@ -1047,14 +1047,24 @@ internal static class Programfor (int x = 0; x < W; x++){int at = (y + 1) * stride + x + 1;- if (indexField[y * W + x] != ColorLut.FieldIndex(field[at], 30f) || indexInten[y * W + x] != ColorLut.IntensityIndex(inten[at], 5f))+ if (indexField[y * W + x] != ColorLut.FieldIndex((float)(Half)field[at], 30f) || indexInten[y * W + x] != ColorLut.IntensityIndex((float)(Half)inten[at], 5f)){same = false;break;}}}- Check(same && indexField.Max() > 127 && indexField.Min() < 127 && indexInten.Max() > 0, "index shape: the renderer's palette index of every cell at brightness 30 and 5, both sides of the centre used");+ Check(same && indexField.Max() > 127 && indexField.Min() < 127 && indexInten.Max() > 0, "index shape: the renderer's palette index of every cell's half-rounded sample at brightness 30 and 5, both sides of the centre used");+ // an index frame renders to the same pixels as a half frame of the same floats: the rule behind the 8-bit preview+ var halfField = new byte[full.PlaneBytes];+ FrameConversion.Convert(field, stride + 1, stride, full, false, halfField);+ ReadOnlySpan<Half> storedHalves = MemoryMarshal.Cast<byte, Half>(halfField);+ bool rendersAlike = true;+ for (int i = 0; i < W * H && rendersAlike; i++)+ {+ rendersAlike = indexField[i] == ColorLut.FieldIndex((float)storedHalves[i], 30f);+ }+ Check(rendersAlike, "index shape: every index equals the one a 16-bit frame of the same floats renders to");// the CPU engine's captures of every shape equal the reference conversion of its own floatsforeach (FrameShape shape in new[] { half, third, index, halfIndex })@@ -1069,7 +1079,7 @@ internal static class ProgramCheck(snapshot.HasIntensity && snapshot.FieldBytes.AsSpan().SequenceEqual(expectedField) && snapshot.IntensityBytes!.AsSpan().SequenceEqual(expectedInten),$"CPU capture of 1/{shape.Divisor} {shape.Format} equals the reference conversion");}- // the GPU's within the card's arithmetic: halves within the tolerance, indices within one+ // the GPU's: halves within the tolerance, indices exact where the card's square root rounds correctly (within one elsewhere)GpuWaveSimulator? gpu = GpuWaveSimulator.TryCreate(scene, options, Sources(), out string problems);if (gpu == null){@@ -1112,8 +1122,9 @@ internal static class ProgramworstHalf = Math.Max(worstHalf, Math.Max(Math.Abs((float)gotField[i] - (float)wantField[i]), Math.Abs((float)gotInten[i] - (float)wantInten[i])));}}- Check(snapshot.HasIntensity && worstIndex <= 1 && worstHalf < tolerance,- $"GPU capture of 1/{shape.Divisor} {shape.Format} matches the reference conversion (index off by at most {worstIndex}, halves by {worstHalf})");+ int allowed = gpu.Device.CorrectlyRoundedSqrt ? 0 : 1;+ Check(snapshot.HasIntensity && worstIndex <= allowed && worstHalf < tolerance,+ $"GPU capture of 1/{shape.Divisor} {shape.Format} matches the reference conversion (index off by at most {worstIndex} of {allowed} allowed, halves by {worstHalf})");}}}