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#
The damping rim absorbs on its own: a quadratic ramp to a half, and a 32 px rim as the default
Alexander Graef6a18c6bf1779
diff --git a/CLAUDE.md b/CLAUDE.mdindex f7ef727..0c3a13a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -97,10 +97,17 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA- **Engine contract**: padded grid (`Stride = Width + 2 + 2 × Rim`: a negative damping edge is a rim of that many cellsoutside the canvas, simulated and never shown, the canvas starting at (Rim, Rim); `Scene.Edges` Open puts Mur's- first-order absorbing condition on the ring, Reflective is Jeroen's wall; a new project is Open with no damping edge- (2026-10-19, the user's choice: measured on a pulse, the open ring alone returns 0.05 to 0.09 % of the amplitude, a- rim at its best the same, a rim damped to a standstill 1 %, the reflective box 72 %); a version-1 file loads as- Reflective, an import as Reflective with his band; one driver thread at a time, no locking; captures+ first-order absorbing condition on the ring, Reflective is Jeroen's wall; a new project is Open with a 32 px rim outside+ (2026-10-22, the user's choice, after the rim measurements below; no damping edge from 2026-10-19 until then, when the+ open ring was measured on a long-wave pulse: the open ring alone returns 0.05 to 0.09 % of the+ amplitude, a rim at its best the same, a rim damped to a standstill 1 %, the reflective box 72 %). The rim's loss rises+ with the square of the depth to a half per step at the outer ring (2026-10-22, the user's choice: at wavelengths of a few+ cells, Jeroen's usual, the ring's Mur condition assumes a speed the stencil does not have and reflects almost+ everything, so the rim absorbs alone; measured against a reference canvas too wide to reflect, Example 3's beam got+ 1 % back from the earlier linear ramp to a tenth at -64, 0.09 % from the quadratic one, 0.03 % at -128; the measuring+ method is in `library_check`); a version-1 file loads as+ Reflective, a version-2 file without a damping edge with none (its default then; files are version 3 since 2026-10-22), an+ import as Reflective with his band; one driver thread at a time, no locking; capturesdeliver planes in the spec's `FrameShape` (halves or palette index bytes, the GPU converting on the card);`Reset`, `SetEmitters`, `SetProbes`. Numerics are Jeroen's (dx = dt = 1, leapfrog, 9-point or 4th-orderLaplacian, soft sources, EMA intensity; a scene pixel with red 0 is a mirror, n = 1000, his V0.30 rule,diff --git a/WaveDudeNext/Engine/SceneData.cs b/WaveDudeNext/Engine/SceneData.csindex 579ae90..7d5b9f4 100644--- a/WaveDudeNext/Engine/SceneData.cs+++ b/WaveDudeNext/Engine/SceneData.cs@@ -210,11 +210,15 @@ public sealed class SceneData}/// <summary>- /// The damping of a rim outside the canvas: the loss of velocity per step rises linearly from nothing at the- /// canvas's edge to a tenth at the outer ring. Measured on a pulse (2026-10-19): a rim damped to a standstill, as- /// Jeroen's square-root band is, sent about 1 % of the pulse back, since cells whose velocity is wiped keep their- /// displacement and let it creep back; this mild ramp sends back 0.1 to 0.2 % at 32 cells and 0.06 % at 64, while- /// the open ring alone (<see cref="OpenEdges"/>) returns 0.05 to 0.09 %, so a rim is an option, not the default.+ /// The damping of a rim outside the canvas: the loss of velocity per step rises with the square of the depth, from+ /// nothing at the canvas's edge to a half at the outer ring (2026-10-22, the user's choice). Measured against a+ /// reference canvas so wide that nothing returns from its edges: on Jeroen's Example 3 (an emitter array 185 px from+ /// the edge, a wave under three cells long with the 4th-order stencil, where the stencil's speed is far from what the+ /// open ring assumes and the ring reflects almost everything) a 64 px rim with this ramp lets 0.09 % of the edge+ /// amplitude back, 0.03 % at 128 px; the linear ramp to a tenth it replaces let 1 % back, visible in the beam, and+ /// Jeroen's square-root band inside the canvas 1.4 %. The ramp was chosen linear and mild on 2026-10-19 from a+ /// long-wave pulse on a small canvas, where the open ring (<see cref="OpenEdges"/>) does the work and a rim damped to a+ /// standstill sent 1 % back from its own jump; the quadratic ramp keeps that case within the same bounds./// </summary>/// <param name="d">Damping array of the whole grid, row-major, modified in place.</param>/// <param name="w">Grid width in cells.</param>@@ -224,9 +228,9 @@ public sealed class SceneData{for (int i = 0; i < rim; i++){- // i cells from the outer ring: (rim - i) / rim of the way into the rim, a tenth of that lost per step+ // i cells from the outer ring: (rim - i) / rim of the way into the rim, half of its square lost per stepdouble into = (double)(rim - i) / rim;- float factor = (float)(1.0 - 0.1 * into);+ float factor = (float)(1.0 - 0.5 * into * into);for (int x = i; x <= w - 1 - i; x++){d[i * w + x] = factor;diff --git a/WaveDudeNext/Model/Project.cs b/WaveDudeNext/Model/Project.csindex 60543a5..010f16c 100644--- a/WaveDudeNext/Model/Project.cs+++ b/WaveDudeNext/Model/Project.cs@@ -35,7 +35,7 @@ namespace WaveDudeNext.Model;public sealed class Project : ObservableObject{/// <summary>Format version written to new files; bump when the layout changes incompatibly.</summary>- public const int CurrentVersion = 2;+ public const int CurrentVersion = 3;private int _version = CurrentVersion;private int _seed = NewSeed();@@ -542,8 +542,14 @@ public sealed class Project : ObservableObject// version 1 (until 2026-10-19) knew only reflective edges; the open edges that are the default since must not// reach an old file, which keeps the walls it was made withproject.Scene.Edges = EdgeMode.Reflective;- project.Version = CurrentVersion;}+ if (project.Version < 3 && !project.Scene.DampingEdgeRead)+ {+ // until version 3 (2026-10-22) a file without a damping edge meant none; the rim of 32 that is the default since+ // must not reach it either+ project.Scene.DampingEdge = 0;+ }+ project.Version = CurrentVersion;project.Normalize();Logger.Debug("Loaded project: version {Version}, seed {Seed}, {Sources} sources, {Parts} parts, {Probes} probes", project.Version, project.Seed, project.Sources.Count, project.Parts.Count, project.Probes.Count);return project;diff --git a/WaveDudeNext/Model/Scene.cs b/WaveDudeNext/Model/Scene.csindex cb752a2..ea96363 100644--- a/WaveDudeNext/Model/Scene.cs+++ b/WaveDudeNext/Model/Scene.cs@@ -56,7 +56,7 @@ public sealed class Scene : ObservableObject/// <summary>Largest accepted canvas width or height in pixels.</summary>public const int MaxSize = 16384;/// <summary>Damping frame thickness the editor proposes when the frame is switched on.</summary>- public const int DefaultDampingEdge = 0;+ public const int DefaultDampingEdge = -32;/// <summary>Largest accepted <see cref="DampingEdge"/> in pixels.</summary>public const int MaxDampingEdge = 8192;/// <summary>Default <see cref="ImageSourceScale"/>.</summary>@@ -76,6 +76,7 @@ public sealed class Scene : ObservableObjectprivate int _width = DefaultWidth;private int _height = DefaultHeight;private int _dampingEdge = DefaultDampingEdge;+ private bool _dampingEdgeRead;private EdgeMode _edges = EdgeMode.Open;private double _refractiveIndex = DefaultRefractiveIndex;private bool _imageSources;@@ -205,7 +206,8 @@ public sealed class Scene : ObservableObject/// <summary>/// Thickness of the absorbing frame in pixels: positive inside the canvas, where it shows as a dark margin (Jeroen's/// band), negative outside the canvas, where the engine simulates that much more and shows none of it (2026-10-19,- /// the user's rule for the sign); 0 turns it off.+ /// the user's rule for the sign); 0 turns it off. A new project has a rim of 32 outside (2026-10-22, the user's choice:+ /// at wavelengths of a few cells the open ring alone reflects, see <see cref="Engine.SceneData.ApplyRim"/>)./// </summary>[XmlAttribute][DefaultValue(DefaultDampingEdge)]@@ -216,9 +218,22 @@ public sealed class Scene : ObservableObjectpublic int DampingEdge{get => _dampingEdge;- set => SetProperty(ref _dampingEdge, value);+ set+ {+ _dampingEdgeRead = true;+ SetProperty(ref _dampingEdge, value);+ }}+ /// <summary>+ /// Whether <see cref="DampingEdge"/> has been set since construction: right after a file is read, whether the file+ /// carried the attribute. A version-2 file left it out for 0, its default then, which <see cref="Project.Load(System.IO.Stream)"/>+ /// restores (2026-10-22, when the default became -32).+ /// </summary>+ [XmlIgnore]+ [Browsable(false)]+ internal bool DampingEdgeRead => _dampingEdgeRead;+/// <summary>What the edge of the grid does with a wave: lets it leave, or reflects it.</summary>[XmlAttribute][DefaultValue(EdgeMode.Open)]diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.csindex adadfc9..c21075f 100644--- a/_tools/library_check/Program.cs+++ b/_tools/library_check/Program.cs@@ -844,19 +844,45 @@ internal static class ProgramCheck(rimmed.Width == 16 && rimmed.Height == 16 && rimmed.Rim == 4 && rimmed.CanvasWidth == 8 && rimmed.CanvasHeight == 8 && rimmed.OpenEdges,"a damping edge of -4 grows an 8x8 scene to a 16x16 grid with a rim of 4, open");Check(rimmed.SourceCount == 1 && rimmed.SourceX[0] == 6 && rimmed.SourceY[0] == 7, "the image source moved into grid coordinates");- Check(rimmed.D[0] == 0.9f && rimmed.D[4 * 16 + 4] == 1f && rimmed.C2[0] == rimmed.C2[4 * 16 + 4] && rimmed.C2[0] == 0.25f,- "the rim loses a tenth per step at its outer ring, the canvas nothing, and the rim repeats the canvas's corner cell");+ Check(rimmed.D[0] == 0.5f && Math.Abs(rimmed.D[2 * 16 + 2] - (1f - 0.5f * 0.25f)) < 1e-6f && rimmed.D[4 * 16 + 4] == 1f && rimmed.C2[0] == rimmed.C2[4 * 16 + 4] && rimmed.C2[0] == 0.25f,+ "the rim loses half per step at its outer ring, an eighth halfway in (the square of the depth), the canvas nothing, and the rim repeats the canvas's corner cell");SceneData plain = SceneData.Empty(W, H, 8);Check(plain.Rim == 0 && plain.Width == W && !plain.OpenEdges && plain.D[0] == 0f && plain.D[8 * W + 8] == 1f, "a positive damping edge stays inside the canvas, reflective by default");+ // the default (2026-10-22, the user's choice): open with a 32 px rim outside, format version 3; older files keep what they meant+ var fresh = new Project();+ Check(fresh.Scene.DampingEdge == -32 && fresh.Scene.Edges == EdgeMode.Open && fresh.Version == 3 && fresh.Scene.IsDefault, "a new project is open with a 32 px rim outside, format version 3, its scene element left out of the file");+ static Project LoadXml(string xml)+ {+ using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml));+ return Project.Load(stream);+ }+ Check(LoadXml("<Project Version=\"2\"><Scene Width=\"64\" Height=\"48\" /></Project>").Scene is { DampingEdge: 0, Edges: EdgeMode.Open }, "a version-2 file without a damping edge meant none: it loads as 0, not as the new default");+ Check(LoadXml("<Project Version=\"2\"><Scene DampingEdge=\"-32\" /></Project>").Scene.DampingEdge == -32 && LoadXml("<Project Version=\"3\"><Scene /></Project>").Scene.DampingEdge == -32,+ "an explicit -32 in a version-2 file stays, and a version-3 file without the attribute is -32");+ Check(LoadXml("<Project Version=\"1\"><Scene /></Project>").Scene is { DampingEdge: 0, Edges: EdgeMode.Reflective }, "a version-1 file is reflective without a rim");+ Project saved = LoadXml("<Project Version=\"2\"><Scene /></Project>");+ string savedXml;+ using (var stream = new MemoryStream())+ {+ saved.Save(stream);+ savedXml = System.Text.Encoding.UTF8.GetString(stream.ToArray());+ }+ Check(savedXml.Contains("Version=\"3\"") && savedXml.Contains("DampingEdge=\"0\""), "saved again it is version 3 and says DampingEdge=\"0\" explicitly");// what comes back: a Gaussian pulse from the centre, its peak amplitude on the way out against the largest// amplitude found in the canvas once it has had time to leave (steps 300 to 700)- (string Name, int Edge, bool Open)[] configs = [("reflective, no damping", 0, false), ("reflective, a 24 px band inside", 24, false), ("open, no damping", 0, true), ("open, a 32 px rim outside", -32, true)];+ // both stencils: the 4th-order one runs at the true Laplacian's speed, and its outermost canvas cells, which fall+ // back to the 9-point stencil, ran at 0.56 of it until 2026-10-22, a speed step that sent a fifth of a pulse back+ (string Name, int Edge, bool Open, bool Fourth)[] configs =+ [+ ("reflective, no damping", 0, false, false), ("reflective, a 24 px band inside", 24, false, false), ("open, no damping", 0, true, false), ("open, a 32 px rim outside", -32, true, false),+ ("open, no damping, 4th order", 0, true, true), ("open, a 32 px rim outside, 4th order", -32, true, true),+ ];double[] back = new double[configs.Length];for (int c = 0; c < configs.Length; c++){SceneData scene = SceneData.Empty(W, H, configs[c].Edge, 1.0, configs[c].Open);var pulse = new List<Emitter> { Make(W / 2, H / 2, 120, 1.0) with { Mode = SourceMode.Pulsed, PulseShape = PulseShape.Gaussian, OnWidthCycles = 3, OffWidthCycles = 100000, OffWidthBase = 100000 } };- var cpu = new WaveSimulator(scene, new EngineOptions(1.0, 1.0, false, false, 10.0, 1.0), pulse);+ var cpu = new WaveSimulator(scene, new EngineOptions(1.0, 1.0, false, configs[c].Fourth, 10.0, 1.0), pulse);double peak = 0, returned = 0;for (int step = 1; step <= 700; step++){@@ -880,6 +906,56 @@ internal static class ProgramCheck(back[2] < 0.002, "open edges alone: under 0.2 % of the amplitude comes back");Check(back[3] < 0.005, "open edges with a 32 px rim outside: under half a percent comes back");Check(back[0] > 0.5, "a reflective box without damping sends it all back");+ Check(back[4] < 0.005, "open edges alone with the 4th-order stencil: under half a percent comes back");+ Check(back[5] < 0.005, "open edges with a 32 px rim outside, 4th-order stencil: under half a percent comes back");+ // a wave under three cells long (level 160 at scale 2, aliased, as Jeroen's Example 3 runs) with the 4th-order+ // stencil: the open ring reflects it almost whole, the rim must absorb on its own (2026-10-22: the linear ramp to a+ // tenth let 1 % of Example 3's beam back, the quadratic ramp to a half under 0.1 %). Measured against a reference+ // canvas grown by a margin no reflection crosses within the steps run, from a point source 60 px from the left edge+ const int shortW = 256, shortH = 160, margin = 220, shortSteps = 400;+ var shortOptions = new EngineOptions(2.0, 1.0, false, true, 10.0, 1.0);+ static List<Emitter> ShortPulse(int x, int y) => [Make(x, y, 160, 1.0) with { Mode = SourceMode.Pulsed, PulseShape = PulseShape.Gaussian, OnWidthCycles = 10, OffWidthCycles = 100000, OffWidthBase = 100000 }];+ var referenceEngine = new WaveSimulator(SceneData.Empty(shortW + 2 * margin, shortH + 2 * margin, 0, 1.0, false), shortOptions, ShortPulse(60 + margin, 80 + margin));+ var references = new List<float[]>();+ double edgeAmplitude = 0;+ for (int step = 1; step <= shortSteps; step++)+ {+ referenceEngine.AdvanceOneStep();+ if (step % 20 == 0)+ {+ float[] canvas = CanvasRegion(referenceEngine, margin, shortW, shortH);+ references.Add(canvas);+ for (int y = 0; y < shortH; y++)+ {+ for (int x = 0; x < 40; x++)+ {+ edgeAmplitude = Math.Max(edgeAmplitude, Math.Abs(canvas[y * shortW + x]));+ }+ }+ }+ }+ double[] shortBack = new double[2];+ for (int t = 0; t < 2; t++)+ {+ var engine = new WaveSimulator(SceneData.Empty(shortW, shortH, t == 0 ? 0 : -64, 1.0, true), shortOptions, ShortPulse(60, 80));+ for (int step = 1; step <= shortSteps; step++)+ {+ engine.AdvanceOneStep();+ if (step % 20 == 0)+ {+ float[] canvas = CanvasRegion(engine, 0, shortW, shortH);+ float[] expected = references[step / 20 - 1];+ for (int i = 0; i < canvas.Length; i++)+ {+ shortBack[t] = Math.Max(shortBack[t], Math.Abs(canvas[i] - expected[i]));+ }+ }+ }+ shortBack[t] /= edgeAmplitude;+ }+ Console.WriteLine($" a wave under three cells long, 4th order, against a wide reference: open ring alone {shortBack[0] * 100:0.00} %, with a 64 px rim {shortBack[1] * 100:0.000} % of the edge amplitude comes back");+ Check(shortBack[0] > 0.1, "the open ring alone reflects a wave under three cells long: over a tenth comes back");+ Check(shortBack[1] < 0.003, "a 64 px rim with the quadratic ramp lets under 0.3 % of it back");// CPU = GPU with the rim and the open edgeSceneData openScene = SceneData.Empty(W, H, -32, 1.0, true);var wave = new List<Emitter> { Make(W / 2, H / 2, 120, 1.0) };@@ -899,6 +975,17 @@ internal static class Program}}+ /// <summary>A <paramref name="w"/> × <paramref name="h"/> region of an engine's field at offset (<paramref name="m"/>, <paramref name="m"/>) of its canvas (the rim and padding skipped), row-major.</summary>+ private static float[] CanvasRegion(IWaveEngine engine, int m, int w, int h)+ {+ var region = new float[w * h];+ for (int y = 0; y < h; y++)+ {+ Array.Copy(engine.FieldData, (y + m + 1 + engine.Rim) * engine.Stride + m + 1 + engine.Rim, region, y * w, w);+ }+ return region;+ }+/// <summary>Max |u| over the canvas cells of an engine's field (the rim and padding left out).</summary>private static double CanvasPeak(IWaveEngine engine){