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 painter out of JIT tiering and sampling only near edges; compact scene maps on the card; the preview's abandoned frames logged
Alexander Graef141aea49279e
diff --git a/CLAUDE.md b/CLAUDE.mdindex 721ff9b..3652ae1 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -26,7 +26,11 @@ harnesses run.targeted probe or screenshot for a local change, `library_check` (20 s) for a library change, a UI harness onlywhen its flow changed, **once**. Never loop a harness for a flake, never run the suite after an edit.- **Measure properly**: warm the JIT; never poll UI Automation while measuring (it loads the UI thread it- measures); the app's own log lines are the measurement.+ measures); the app's own log lines are the measurement. **A hot loop measured alone may be a tier-1 figure the app never+ reaches** (2026-11-03: the part painter took 31 ms in a probe and 115–460 ms in the app, the same call; in a busy WPF process+ the runtime kept its per-pixel methods at tier-0 — the probe pinned there with `DOTNET_TC_CallCounting=0` reproduced the+ app's 212 ms): compare a probe against the app's log, and take a hot path out of tiering with+ `[MethodImpl(MethodImplOptions.AggressiveOptimization)]` where the gap is that.- **Harnesses are keyboard-only**: post `WM_KEYDOWN`/`WM_CHAR` to the window, read state through UIA properties,never UIA patterns, the mouse, `SendKeys` or `SetForegroundWindow` (each activates the window). Modifiers cannotbe posted, so every command a harness presses has an unmodified key. Everything a harness needs has an@@ -107,7 +111,7 @@ SimulationRun: stepping loop + writer threads; IWaveEngine (WaveSimulator CPU |CaptureFrame/AwaitFrame -> FrameStore.Write; one heartbeat post (<= 30/s) at Background priority; final post setsFrameCount, then StateScratchRunner: one kept engine; "frame k of the project as it is now" from step 0, probes sampled; newest request- wins; every request is computed+ wins: one superseded while stepping is abandoned within 16 steps (logged), the newest is computed in full, however longFramePresenter: CopyLayer -> 8-bit: FrameRenderer.RenderIndexed at the store's size, WPF scales; 16-bit: ScreenRenderer atthe picture's size on screen -> the WriteableBitmap, copied on the pool between Lock/Unlock on the UI thread; onlythe newest request is rendered@@ -141,7 +145,14 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAswapped into the kept engine: the GPU re-uploads c², damping and the source tables into its buffers and keeps thecompiled program, the sub-steps re-derived; 2026-11-03, the user's choice: the scratch runner uses it, 55 ms forExample 16 against the 180–350 ms OpenCL build every part edit had cost; `library_check` proves a replaced engine- steps like a fresh one on both engines). Numerics are Jeroen's (dx = dt = 1, leapfrog, 9-point or 4th-order+ steps like a fresh one on both engines). The scene reaches the card as compact maps (2026-11-03, the user's choice: the+ step kernel is bound by the card's bandwidth, about 400 GB/s at 84 bytes a cell a step at 4th order with intensity): a+ byte index into the table of the scene's at most 256 distinct c² values (the image's red levels) and a 16-bit index+ into the table of its damping values (the blue levels and the rim's depths, a few hundred; room for 4096, a scene with+ more rebuilds), the tables holding the CPU's floats, so the arithmetic is unchanged; and the intensity's blend of its+ two stages is made where it is read (the captures, the probes, `PrepareFrame`), not written every step: 69 bytes a+ cell, the step 0.47 → 0.38 ms at full HD and 4th order, 0.25 → 0.21 at 9-point. `PrepareFrame`, which no path of the+ app uses, reads both stages and blends on the host. 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,2026-10-18), verified CPU = GPU by the harness; seeds from `Pcg32` make CPU = GPUbit for bit on random gaps. A source's frequency level, amplitude and phase take decimals (2026-10-19, Jeroen's point 10); the@@ -196,7 +207,9 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAof quiet (setting, default on); an automatic run never moves the preview. A probe edit never starts a run: onlythe recordings are stale, the scratch frame refreshes the graph; except that an active probe the run does notrecord (switched on, added) is a simulation edit (2026-10-18). No scratch frame while playback runs. Any run- is paused while a scratch frame computes. Every scratch request is computed, however long.+ is paused while a scratch frame computes. The newest scratch request is computed in full, however long (no time+ budget, 2026-10-16); a request superseded while stepping is abandoned within 16 steps and logged (the word "every" here+ misled a reader into offering that as new, 2026-11-03).- **A picture changes only when a frame for its position arrives**; otherwise the last picture stays. A long waitdims the pictures under a spinner, mirrored on the taskbar.- **Brightness** (2026-10-20, Jeroen's point 9) sits in each picture's header strip (`HeaderStrip`: title, a caption that@@ -426,7 +439,8 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA## Numbers (workstation: 10-core Xeon without AVX2, RTX 2080, 64 GB)-GPU step at 1080p 0.25–0.5 ms, CPU 6–14 ms; OpenCL build 0.3 s; a full-HD frame's capture (both planes as halves, 8.3 MB)+GPU step at 1080p 0.21 ms (9-point) to 0.38 ms (4th order, three sub-steps; 0.25–0.47 before the compact maps and the+deferred intensity blend of 2026-11-03), CPU 6–14 ms; OpenCL build 0.3 s; a full-HD frame's capture (both planes as halves, 8.3 MB)0.9 ms on top of its two steps since the page-locked snapshots (2026-11-03; 2.1 ms before, the stepping thread blocked inthe driver's copy; `bench 1920 1080`: 1.50 → 0.65 ms a step with captures every 2 steps at 4th order, the DMA on its ownqueue), the DMA itself 0.63 ms at 13 GB/s. In the app the default project's run (2500 steps, 1250 frames, 16-bit, both@@ -454,9 +468,22 @@ coalesced update repainted all four rectangles, one the whole canvas, "composedpoint and node lists) and paints on the thread pool, one composition in flight, the newest request after it, the UIthread taking only the finished pixels (20–24 ms a time, measured on a burst of ten nudges: three compositions of 395,212 and 128 ms on the worker); `LoadSceneImage` (a run or scratch request) joins an in-flight composition of the same-inputs rather than painting again. Still open: the painter itself, 35–60 ns a pixel on ten cores even on a plain-rectangle (an interior fast path, a cheaper mirror test; profile first), which sets the picture's refresh rate during a-drag; not an incremental painter, since a coating's band rises from the index beneath it. Laptop (2 cores, HD 520, HDD): iGPU 4.3 ms a step against CPU 14.7; the ball+inputs rather than painting again. **The painter's per-pixel path is out of JIT tiering** (2026-11-03, the user's choice):+alone it took 31 ms for those four parts, in the app 115–460 ms, because the runtime left its methods at tier-0 code in+the busy process (pinned there, the probe took 212 ms); `AggressiveOptimization` on the shape methods a pixel reaches, the+painter's row lambdas and the glowing edges' makes a composition 26–35 ms a background and 10–17 ms a box in the app,+74 ms for the four during a burst of nudges (was 395–460), the pictures 17–32 ms on the UI thread. Each part logs its+paint time, and a composition logs the thread pool's state when it starts. **A pixel is sampled 16 times only where an+edge is within reach** — the outline, the coating band's, or an inner edge the shape reports (`InnerEdgeDistance`: a+fibre's core boundary, a Bragg stack's layer boundaries; the logic gate still says 0, every inside pixel sampled) — where+every pixel of a fibre had been (2026-11-03, after the user's drag of a fibre node: Example 23's three fibres 138/163/398 →+43/50/96 ms, its composition 731 → 218 ms; a graded band's pixels are the centre sample now, as every other coated shape's,+within 0.01 of index where the band curves inside a pixel). A fibre pixel still runs four chord loops (depth, body index,+face, inner edge), sharable for about another factor of two. Left for later, if wanted: a Lipschitz skip+in the rows (the depth is a lower bound on the distance to the outline, so a pixel at depth *d* settles the next+⌈|*d*| − 0.6⌉ pixels: ~20 evaluations a row instead of 600 for a box, the arithmetic itself then a few milliseconds),+and the pictures' glowing edges, now the larger share of the UI thread's time during a drag; not an incremental+painter, since a coating's band rises from the index beneath it. Laptop (2 cores, HD 520, HDD): iGPU 4.3 ms a step against CPU 14.7; the balllens run 105 s full quality (disk-bound), 61 s at half resolution with every second frame, in RAM. Settled by thesenumbers: no GPU JPEG, no OpenCL colouring at presentation, no `Vector256`, no Direct3D display path.diff --git a/WaveDudeNext.WPF/MainWindow.Live.cs b/WaveDudeNext.WPF/MainWindow.Live.csindex ae1fa42..41f99f7 100644--- a/WaveDudeNext.WPF/MainWindow.Live.cs+++ b/WaveDudeNext.WPF/MainWindow.Live.cs@@ -528,6 +528,8 @@ public partial class MainWindowif (!TryCachedScene(key, out ScenePixels? composed)){List<OpticalPart> parts = Project.Parts.Select(part => part.Clone()).ToList();+ // the pool's state, for a report whose compositions take longer than the painter alone (2026-11-03)+ Logger.Debug("Scene composition starts: thread pool {Threads} threads, {Pending} items pending", ThreadPool.ThreadCount, ThreadPool.PendingWorkItemCount);Task<ScenePixels?> task = Task.Run(() => PartPainter.Paint(key.Source, key.Width, key.Height, key.Background, parts));_composition = (key, task);trydiff --git a/WaveDudeNext/Engine/GpuWaveSimulator.cs b/WaveDudeNext/Engine/GpuWaveSimulator.csindex a4a9958..17aa546 100644--- a/WaveDudeNext/Engine/GpuWaveSimulator.cs+++ b/WaveDudeNext/Engine/GpuWaveSimulator.cs@@ -15,7 +15,9 @@// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or// <https://www.gnu.org/licenses/>.+using System.Collections.Concurrent;using System.Globalization;+using System.Runtime.InteropServices;using System.Text;using WaveDudeNext.Model;using WaveDudeNext.Probes;@@ -156,6 +158,8 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable_grid1D = new[] { new IntPtr(Math.Max(1, _sourceCount)) };_hostField = new float[_cells];_hostIntensity = _track ? new float[_cells] : null;+ _hostStage1 = _track ? new float[_cells] : null;+ _hostStage2 = _track ? new float[_cells] : null;_timeDecay = options.TimeDecay;try{@@ -199,7 +203,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablefloat intensityAlpha = WaveSimulator.IntensityRetention(_timeDecay, WaveSimulator.LowestSourceLevel(_levelUsed, sourcesInScene));for (int k = 0; k <= 1; k++){- SetFloat(_stepKernel[k], 10U, intensityAlpha);+ SetFloat(_stepKernel[k], 12U, intensityAlpha);}}@@ -208,7 +212,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable{OpenClApi.Check(OpenClApi.clFinish(_queue), "clFinish");float[] zeros = new float[_cells];- foreach (IntPtr buffer in new[] { _field[0], _field[1], _intensityOutBuffer, _intensityBuffer, _intensityStage1Buffer })+ foreach (IntPtr buffer in new[] { _field[0], _field[1], _intensityBuffer, _intensityStage1Buffer }){if (buffer != IntPtr.Zero){@@ -309,7 +313,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablesnapshot.HasIntensity = needIntensity && _track && snapshot.HasIntensityPlane;if (snapshot.HasIntensity){- EnqueueCapture(_intensityOutBuffer, stagingSet, snapshot.IntensityAddress, snapshot, true);+ EnqueueCapture(_intensityStage1Buffer, stagingSet, snapshot.IntensityAddress, snapshot, true);}// submitted now, for two reasons: the next capture's kernel waits for these reads, which the spec allows only// once their queue is flushed; and NVIDIA's driver holds a small batch back until a blocking call, so with the@@ -336,6 +340,11 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposableIntPtr kernel = shape.Format == FrameFormat.Half ? _captureHalfKernel : _captureIndexKernel;SetMem(kernel, 0U, source);SetMem(kernel, 1U, staging);+ // the intensity is the blend of its two stages, made on the card as it is read (2026-11-03): stage 1 is the source,+ // stage 2 goes beside it with the scale; a field capture blends nothing (scale 0, the source twice)+ bool half = shape.Format == FrameFormat.Half;+ SetMem(kernel, half ? 10U : 11U, intensity ? _intensityBuffer : source);+ SetFloat(kernel, half ? 11U : 12U, intensity ? _intensityScale : 0f);if (shape.Format == FrameFormat.Index){SetFloat(kernel, 8U, shape.BrightnessOf(intensity));@@ -394,16 +403,24 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable{return false;}+ SceneTables maps = SceneMaps(scene);+ if (maps.DTable.Length > _dTableCapacity)+ {+ // more distinct damping values than the table buffer holds: a rebuild sizes it+ return false;+ }OpenClApi.Check(OpenClApi.clFinish(_queue), "clFinish");- (float[] c2, float[] damping, float c2Mult) = SceneMaps(scene);- Upload(_c2Buffer, c2, _cells);- Upload(_dBuffer, damping, _cells);+ _subSteps = maps.SubSteps;+ UploadBytes(_c2IndexBuffer, maps.C2Index);+ UploadShorts(_dIndexBuffer, maps.DIndex);+ Upload(_c2TableBuffer, maps.C2Table, maps.C2Table.Length);+ Upload(_dTableBuffer, maps.DTable, maps.DTable.Length);for (int k = 0; k <= 1; k++){- SetFloat(_stepKernel[k], 9U, c2Mult);+ SetFloat(_stepKernel[k], 11U, maps.C2Mult);if (_openEdges){- SetFloat(_edgeKernel[k], 6U, c2Mult);+ SetFloat(_edgeKernel[k], 7U, maps.C2Mult);}}(int[] indices, int[] levels) = SourceTables(scene);@@ -419,13 +436,18 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable}/// <summary>- /// The scene's per-cell maps in the padded layout (a border of one cell, like the CPU engine), with the sub-steps- /// (<see cref="_subSteps"/>, set here) and their corrections: sub-stepping keeps the 4th-order stencil stable without- /// changing the physical wave speed or damping, and stays at 1 unless the stencil is in use and this scene's highest- /// c² needs it. The damping is pre-scaled to its 1 / sub-steps-th root (unchanged at 1 sub-step), as the CPU engine's,+ /// The scene's per-cell maps for the card: the kernel is bound by the card's memory bandwidth, so a cell carries a byte+ /// index into the table of the scene's distinct c² values (at most 256: they come from the image's red levels) and a+ /// 16-bit index into the table of its distinct damping values (a few hundred: the blue levels and the rim's depths),+ /// 3 bytes instead of 8 (2026-11-03, the user's choice); the tables hold the very floats the CPU engine computes+ /// with, so the arithmetic is unchanged. In the padded layout (a border of one cell, like the CPU engine), with the+ /// sub-steps and their corrections: sub-stepping keeps the 4th-order stencil stable without changing the physical+ /// wave speed or damping, and stays at 1 unless the stencil is in use and this scene's highest c² needs it. The+ /// damping table is pre-scaled to its 1 / sub-steps-th root (unchanged at 1 sub-step), as the CPU engine's cells are,/// and the c² multiplier is 1 / sub-steps², exactly 1f at one sub-step (a bit-for-bit no-op multiply in the kernel)./// </summary>- private (float[] C2, float[] Damping, float C2Mult) SceneMaps(SceneData scene)+ /// <exception cref="InvalidOperationException">The scene has more than 256 distinct c² values.</exception>+ private SceneTables SceneMaps(SceneData scene){float[] c2 = new float[_cells];float[] damping = new float[_cells];@@ -434,20 +456,92 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposableArray.Copy(scene.C2, y * _width, c2, (y + 1) * _stride + 1, _width);Array.Copy(scene.D, y * _width, damping, (y + 1) * _stride + 1, _width);}- _subSteps = _fourthOrder ? WaveSimulator.ComputeSubSteps(WaveSimulator.MaxOf(c2)) : 1;+ float[] c2Table = Distinct(c2);+ float[] dTable = Distinct(damping);+ if (c2Table.Length > 256)+ {+ throw new InvalidOperationException("the scene has more than 256 distinct refractive indices, which a byte index cannot address");+ }+ byte[] c2Index = new byte[_cells];+ ushort[] dIndex = new ushort[_cells];+ Parallel.For(0, _height + 2, row =>+ {+ int start = row * _stride;+ for (int i = start; i < start + _stride; i++)+ {+ c2Index[i] = (byte)Array.BinarySearch(c2Table, c2[i]);+ dIndex[i] = (ushort)Array.BinarySearch(dTable, damping[i]);+ }+ });+ int subSteps = _fourthOrder ? WaveSimulator.ComputeSubSteps(WaveSimulator.MaxOf(c2Table)) : 1;float c2Mult = 1f;- if (_subSteps > 1)+ if (subSteps > 1){// Damping is applied once per sub-step, so take the sub-step root to keep the per-step decay unchanged.- double exponent = 1.0 / _subSteps;- for (int i = 0; i < damping.Length; i++)+ double exponent = 1.0 / subSteps;+ for (int i = 0; i < dTable.Length; i++){- damping[i] = (float)Math.Pow(damping[i], exponent);+ dTable[i] = (float)Math.Pow(dTable[i], exponent);}// A sub-step is 1/subSteps long, so c²·dt² shrinks by 1/subSteps².- c2Mult = 1f / (_subSteps * _subSteps);+ c2Mult = 1f / (subSteps * subSteps);+ }+ return new SceneTables(c2Index, c2Table, dIndex, dTable, subSteps, c2Mult);+ }++ /// <summary>The scene's maps as the card takes them: per-cell indices, the tables they address, the sub-steps and the c² multiplier (<see cref="SceneMaps"/>).</summary>+ private sealed record SceneTables(byte[] C2Index, float[] C2Table, ushort[] DIndex, float[] DTable, int SubSteps, float C2Mult);++ /// <summary>The distinct values of <paramref name="values"/>, sorted, so <see cref="Array.BinarySearch(Array, object)"/> finds a value's index; gathered on every core.</summary>+ private static float[] Distinct(float[] values)+ {+ var all = new HashSet<float>();+ var gate = new Lock();+ Parallel.ForEach(Partitioner.Create(0, values.Length, 1 << 16), () => new HashSet<float>(), (range, _, local) =>+ {+ for (int i = range.Item1; i < range.Item2; i++)+ {+ local.Add(values[i]);+ }+ return local;+ }, local =>+ {+ lock (gate)+ {+ all.UnionWith(local);+ }+ });+ float[] table = [.. all];+ Array.Sort(table);+ return table;+ }++ /// <summary>Blocking upload of a byte array into a device buffer.</summary>+ private void UploadBytes(IntPtr buffer, byte[] data)+ {+ GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);+ try+ {+ OpenClApi.Check(OpenClApi.clEnqueueWriteBufferPtr(_queue, buffer, 1U, IntPtr.Zero, new IntPtr(data.Length), handle.AddrOfPinnedObject(), 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueWriteBuffer (bytes)");+ }+ finally+ {+ handle.Free();+ }+ }++ /// <summary>Blocking upload of a 16-bit array into a device buffer.</summary>+ private void UploadShorts(IntPtr buffer, ushort[] data)+ {+ GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);+ try+ {+ OpenClApi.Check(OpenClApi.clEnqueueWriteBufferPtr(_queue, buffer, 1U, IntPtr.Zero, new IntPtr((long)data.Length * 2L), handle.AddrOfPinnedObject(), 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueWriteBuffer (shorts)");+ }+ finally+ {+ handle.Free();}- return (c2, damping, c2Mult);}/// <summary>The image sources (the green channel of the scene image) as the kernel's tables, cell index and level per source, noting the levels in use in <see cref="_levelUsed"/> afresh.</summary>@@ -467,11 +561,11 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable/// <summary>/// Creates the context and queue, compiles <see cref="KernelSource"/>, uploads every buffer for the scene- /// and binds the kernel arguments. Mirrors the <see cref="WaveSimulator"/> constructor: c² and damping are- /// copied into the padded layout, the sub-step count and the per-sub-step damping / c² corrections are- /// derived for the 4th-order stencil, the sources are indexed, and the intensity averaging constant is set- /// from the lowest source level in use. When intensity is not tracked the three intensity buffers are- /// 1-float dummies so the kernel arguments are still valid. The kernel arguments that change per step+ /// and binds the kernel arguments. Mirrors the <see cref="WaveSimulator"/> constructor: c² and damping become+ /// index maps and tables in the padded layout (<see cref="SceneMaps"/>), the sub-step count and the per-sub-step+ /// damping / c² corrections are derived for the 4th-order stencil, the sources are indexed, and the intensity+ /// averaging constant is set from the lowest source level in use. When intensity is not tracked the two intensity+ /// buffers are 1-float dummies so the kernel arguments are still valid. The kernel arguments that change per step/// (time, per-sub-step track flag) are left to <see cref="AdvanceOneStep"/>./// </summary>/// <param name="scene">Per-cell c² and damping maps plus the image sources.</param>@@ -484,7 +578,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablefloat sourceAmplitude = (float)options.SourceAmplitude;bool use4thOrderLaplacian = options.FourthOrderLaplacian;double timeDecayFactor = options.TimeDecay;- float intensityScale = (float)options.IntensityScale;+ _intensityScale = (float)options.IntensityScale;int err = 0;IntPtr[] contextProperties = { new IntPtr(OpenClApi.ContextPlatformProperty), _device.PlatformId, IntPtr.Zero };IntPtr[] deviceIds = { _device.DeviceId };@@ -496,20 +590,30 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposableOpenClApi.Check(err, "clCreateCommandQueue (transfer)");_scene.Program = BuildProgram(KernelSource(use4thOrderLaplacian), "the program for the GPU");- (float[] c2, float[] damping, float c2Mult) = SceneMaps(scene);- IntPtr c2Buffer = _c2Buffer = CreateBuffer(c2, _scene);- IntPtr dBuffer = _dBuffer = CreateBuffer(damping, _scene);+ SceneTables maps = SceneMaps(scene);+ _subSteps = maps.SubSteps;+ float c2Mult = maps.C2Mult;+ _c2IndexBuffer = CreateBuffer(maps.C2Index, _scene);+ _dIndexBuffer = CreateBuffer(maps.DIndex, _scene);+ // the tables with room: 256 c² values at most; damping values as many as the scene has, at least DTableRoom, so a+ // scene swapped in later (TryReplaceScene) fits unless it has more+ float[] c2Table = new float[256];+ maps.C2Table.CopyTo(c2Table, 0);+ _c2TableBuffer = CreateBuffer(c2Table, _scene);+ _dTableCapacity = Math.Max(DTableRoom, maps.DTable.Length);+ float[] dTable = new float[_dTableCapacity];+ maps.DTable.CopyTo(dTable, 0);+ _dTableBuffer = CreateBuffer(dTable, _scene);float[] zeros = new float[_cells];_field[0] = CreateBuffer(zeros, _scene);_field[1] = CreateBuffer(zeros, _scene);// Not tracked: the kernels still need valid buffer arguments, and they never touch them.float[] intensityInit = _track ? zeros : new float[1];// the two cascaded exponential-filter stages that make up the intensity - see the class summary and- // WaveSimulator._intensity / _intensityStage1 (CPU engine); used only inside wave_step, never read back -- // what is read back/probed is their blend, _intensityOutBuffer (WaveSimulator._intensityOut on the CPU)+ // WaveSimulator._intensity / _intensityStage1 (CPU engine); their blend, WaveSimulator._intensityOut on the CPU,+ // is made where it is read (the captures, the probes, PrepareFrame), not written every step (2026-11-03)IntPtr intensityBuffer = _intensityBuffer = CreateBuffer(intensityInit, _scene);IntPtr intensityStage1Buffer = _intensityStage1Buffer = CreateBuffer(intensityInit, _scene);- _intensityOutBuffer = CreateBuffer(intensityInit, _scene);// the level-to-frequency table (level 0-255 -> frequency), shared by the image sources and the object sourcesfloat[] frequencies = new float[256];@@ -532,29 +636,30 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposableIntPtr step = _stepKernel[k] = CreateKernel(_scene, "wave_step");SetMem(step, 0U, _field[k]);SetMem(step, 1U, _field[1 - k]);- SetMem(step, 2U, c2Buffer);- SetMem(step, 3U, dBuffer);- SetMem(step, 4U, intensityBuffer);- SetInt(step, 5U, _width);- SetInt(step, 6U, _height);- SetInt(step, 7U, _stride);- SetInt(step, 8U, _track ? 1 : 0);- SetFloat(step, 9U, c2Mult);- SetFloat(step, 10U, intensityAlpha);- SetMem(step, 11U, intensityStage1Buffer);- SetMem(step, 12U, _intensityOutBuffer);- SetFloat(step, 13U, intensityScale);+ SetMem(step, 2U, _c2IndexBuffer);+ SetMem(step, 3U, _dIndexBuffer);+ SetMem(step, 4U, _c2TableBuffer);+ SetMem(step, 5U, _dTableBuffer);+ SetMem(step, 6U, intensityBuffer);+ SetInt(step, 7U, _width);+ SetInt(step, 8U, _height);+ SetInt(step, 9U, _stride);+ SetInt(step, 10U, _track ? 1 : 0);+ SetFloat(step, 11U, c2Mult);+ SetFloat(step, 12U, intensityAlpha);+ SetMem(step, 13U, intensityStage1Buffer);if (_openEdges){// the ring after the step, reading the field the step read and writing the one it wroteIntPtr edges = _edgeKernel[k] = CreateKernel(_scene, "open_edges");SetMem(edges, 0U, _field[k]);SetMem(edges, 1U, _field[1 - k]);- SetMem(edges, 2U, c2Buffer);- SetInt(edges, 3U, _width);- SetInt(edges, 4U, _height);- SetInt(edges, 5U, _stride);- SetFloat(edges, 6U, c2Mult);+ SetMem(edges, 2U, _c2IndexBuffer);+ SetMem(edges, 3U, _c2TableBuffer);+ SetInt(edges, 4U, _width);+ SetInt(edges, 5U, _height);+ SetInt(edges, 6U, _stride);+ SetFloat(edges, 7U, c2Mult);}}_stepLocal = WorkGroup2D(_stepKernel[0], _stepKernel[1]);@@ -677,17 +782,18 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable// wave_step: one leapfrog sub-step, one work item per interior cell (x, y in 0..w-1 / 0..h-1).// u current field, padded, stride floats per row; the cell is i = (y + 1) * stride + x + 1// up previous field on entry, overwritten in place with the new value (leapfrog), same layout- // c2, d per-cell c² and per-sub-step damping, same layout+ // c2i, di per-cell indices, a byte and a ushort, same layout, into c2t and dt: the scene's distinct c² values and+ // per-sub-step damping values (2026-11-03: 3 bytes a cell instead of 8, the kernel being bound by the card's bandwidth)// lap 4th-order 5-point-per-axis stencil for cells at least two away from the border (needs// USE_4TH_ORDER), otherwise the 9-point stencil (corners 0.066, edges 0.184, centre -1)// nv = u + (u - up)·d + lap·c2·c2Scale, with c2Scale = 1/subSteps²- // inten1 / inten first and second stage exponential averages of nv², retention intensityAlpha- // intenOut (stage1 + stage2)/2 · intensityScale; the three are only touched when track != 0- source.AppendLine("__kernel void wave_step(__global const float* u, __global float* up, __global const float* c2,");- source.AppendLine(" __global const float* d, __global float* inten,");+ // inten1 / inten first and second stage exponential averages of nv², retention intensityAlpha, only touched+ // when track != 0; their blend (stage1 + stage2)/2 · intensityScale is made where it is read (capture_blend,+ // the probe kernels, PrepareFrame), not written every step (2026-11-03)+ source.AppendLine("__kernel void wave_step(__global const float* u, __global float* up, __global const uchar* c2i,");+ source.AppendLine(" __global const ushort* di, __global const float* c2t, __global const float* dt, __global float* inten,");source.AppendLine(" const int w, const int h, const int stride, const int track, const float c2Scale,");- source.AppendLine(" const float intensityAlpha, __global float* inten1, __global float* intenOut,");- source.AppendLine(" const float intensityScale)");+ source.AppendLine(" const float intensityAlpha, __global float* inten1)");source.AppendLine("{");source.AppendLine(" int x = get_global_id(0);");source.AppendLine(" int y = get_global_id(1);");@@ -711,16 +817,14 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablesource.AppendLine(" lap = 0.066f * (u[i - stride - 1] + u[i - stride + 1] + u[i + stride - 1] + u[i + stride + 1])");source.AppendLine(" + 0.184f * (u[i - 1] + u[i + 1] + u[i - stride] + u[i + stride]) - uc;");source.AppendLine("#endif");- source.AppendLine(" float nv = uc + (uc - up[i]) * d[i] + lap * c2[i] * c2Scale;");+ source.AppendLine(" float nv = uc + (uc - up[i]) * dt[di[i]] + lap * c2t[c2i[i]] * c2Scale;");source.AppendLine(" up[i] = nv;");- // two cascaded one-pole stages, blended (0.5f - see WaveSimulator.IntensityBlend, CPU engine) into what is- // read back/probed (intenOut) instead of using the full 2-stage cascade outright - see the class summary+ // two cascaded one-pole stages; what is read back or probed is their blend (0.5f - see WaveSimulator.IntensityBlend,+ // CPU engine) instead of the full 2-stage cascade outright - see the class summarysource.AppendLine(" if (track != 0) {");source.AppendLine(" float s1 = inten1[i] * intensityAlpha + nv * nv * (1.0f - intensityAlpha);");source.AppendLine(" inten1[i] = s1;");- source.AppendLine(" float s2 = inten[i] * intensityAlpha + s1 * (1.0f - intensityAlpha);");- source.AppendLine(" inten[i] = s2;");- source.AppendLine(" intenOut[i] = (s1 * 0.5f + s2 * 0.5f) * intensityScale;");+ source.AppendLine(" inten[i] = inten[i] * intensityAlpha + s1 * (1.0f - intensityAlpha);");source.AppendLine(" }");source.AppendLine("}");source.AppendLine();@@ -887,13 +991,30 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablesource.AppendLine(" return sum / (float)((y1 - y0) * (x1 - x0));");source.AppendLine("}");source.AppendLine();+ // the intensity as the blend of its two stages, cell for cell as the CPU engine's _intensityOut (its multiply and add kept+ // apart, so no contraction from here on), then the block's mean; a field capture passes a scale of 0 and takes capture_sample+ source.AppendLine("#pragma OPENCL FP_CONTRACT OFF");+ source.AppendLine("float capture_blend(__global const float* s1, __global const float* s2, const float scale, const int w, const int h, const int stride, const int div, const int rim, const int x, const int y)");+ source.AppendLine("{");+ source.AppendLine(" if (div == 1) { int j = (y + 1 + rim) * stride + x + 1 + rim; return (s1[j] * 0.5f + s2[j] * 0.5f) * scale; }");+ source.AppendLine(" int x0 = x * div, y0 = y * div;");+ source.AppendLine(" int x1 = min(w, x0 + div), y1 = min(h, y0 + div);");+ source.AppendLine(" float sum = 0.0f;");+ source.AppendLine(" for (int cy = y0; cy < y1; cy++)");+ source.AppendLine(" for (int cx = x0; cx < x1; cx++) {");+ source.AppendLine(" int j = (cy + 1 + rim) * stride + cx + 1 + rim;");+ source.AppendLine(" sum += (s1[j] * 0.5f + s2[j] * 0.5f) * scale;");+ source.AppendLine(" }");+ source.AppendLine(" return sum / (float)((y1 - y0) * (x1 - x0));");+ source.AppendLine("}");+ source.AppendLine();// the intensity as its square root when the shape says so (2026-10-23, FrameConversion): the block's mean energy, then the root- source.AppendLine("__kernel void capture_half(__global const float* src, __global half* dst, const int w, const int h, const int stride, const int div, const int fw, const int fh, const int rim, const int root)");+ source.AppendLine("__kernel void capture_half(__global const float* src, __global half* dst, const int w, const int h, const int stride, const int div, const int fw, const int fh, const int rim, const int root, __global const float* src2, const float blendScale)");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, rim, x, y);");+ source.AppendLine(" float v = blendScale > 0.0f ? capture_blend(src, src2, blendScale, w, h, stride, div, rim, x, y) : capture_sample(src, w, h, stride, div, rim, x, y);");source.AppendLine(" vstore_half(root ? sqrt(v) : v, y * fw + x, dst);");source.AppendLine("}");source.AppendLine();@@ -922,12 +1043,12 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablesource.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, const int rim)");+ 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, const int rim, __global const float* src2, const float blendScale)");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 raw = capture_sample(src, w, h, stride, div, rim, x, y);");+ source.AppendLine(" float raw = blendScale > 0.0f ? capture_blend(src, src2, blendScale, w, h, stride, div, rim, x, y) : capture_sample(src, w, h, stride, div, rim, x, y);");source.AppendLine(" float v = round_to_half(intensity == 2 ? sqrt(raw) : raw);");source.AppendLine(" int index;");source.AppendLine(" if (intensity == 2)");@@ -944,26 +1065,26 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable// open_edges: Mur's first-order absorbing condition on the ring, WaveSimulator.ApplyOpenEdges cell for cell and// operation for operation (no contraction, see above): one work item per column of the top and bottom rows// (corners take their diagonal neighbour), then one per row of the left and right columns- source.AppendLine("void absorb(__global const float* u, __global float* up, __global const float* c2, const float c2Scale, const int ring, const int inner)");+ source.AppendLine("void absorb(__global const float* u, __global float* up, __global const uchar* c2i, __global const float* c2t, const float c2Scale, const int ring, const int inner)");source.AppendLine("{");- source.AppendLine(" float s = sqrt(c2[inner] * c2Scale) * " + EdgeSpeedFactorLiteral + ";");+ source.AppendLine(" float s = sqrt(c2t[c2i[inner]] * c2Scale) * " + EdgeSpeedFactorLiteral + ";");source.AppendLine(" float k = (s - 1.0f) / (s + 1.0f);");source.AppendLine(" up[ring] = u[inner] + k * (up[inner] - u[ring]);");source.AppendLine("}");source.AppendLine();- source.AppendLine("__kernel void open_edges(__global const float* u, __global float* up, __global const float* c2, const int w, const int h, const int stride, const float c2Scale)");+ source.AppendLine("__kernel void open_edges(__global const float* u, __global float* up, __global const uchar* c2i, __global const float* c2t, const int w, const int h, const int stride, const float c2Scale)");source.AppendLine("{");source.AppendLine(" int id = get_global_id(0);");source.AppendLine(" if (id < w + 2) {");source.AppendLine(" int x = id;");source.AppendLine(" int ix = clamp(x, 1, w);");- source.AppendLine(" absorb(u, up, c2, c2Scale, x, stride + ix);");- source.AppendLine(" absorb(u, up, c2, c2Scale, (h + 1) * stride + x, h * stride + ix);");+ source.AppendLine(" absorb(u, up, c2i, c2t, c2Scale, x, stride + ix);");+ source.AppendLine(" absorb(u, up, c2i, c2t, c2Scale, (h + 1) * stride + x, h * stride + ix);");source.AppendLine(" } else {");source.AppendLine(" int y = id - (w + 2) + 1;");source.AppendLine(" if (y > h) return;");- source.AppendLine(" absorb(u, up, c2, c2Scale, y * stride, y * stride + 1);");- source.AppendLine(" absorb(u, up, c2, c2Scale, y * stride + w + 1, y * stride + w);");+ source.AppendLine(" absorb(u, up, c2i, c2t, c2Scale, y * stride, y * stride + 1);");+ source.AppendLine(" absorb(u, up, c2i, c2t, c2Scale, y * stride + w + 1, y * stride + w);");source.AppendLine(" }");source.AppendLine("}");return source.ToString();@@ -1022,6 +1143,22 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablereturn buffer;}+ /// <summary>Byte counterpart of <see cref="CreateBuffer(float[], Resources)"/>.</summary>+ private IntPtr CreateBuffer(byte[] data, Resources owner)+ {+ IntPtr buffer = CreateBuffer(data.Length, owner);+ UploadBytes(buffer, data);+ return buffer;+ }++ /// <summary>16-bit counterpart of <see cref="CreateBuffer(float[], Resources)"/>.</summary>+ private IntPtr CreateBuffer(ushort[] data, Resources owner)+ {+ IntPtr buffer = CreateBuffer((long)data.Length * 2L, owner);+ UploadShorts(buffer, data);+ return buffer;+ }+/// <summary>Creates the kernel <paramref name="name"/> from <paramref name="owner"/>'s program and registers it there for release.</summary>private static IntPtr CreateKernel(Resources owner, string name) => CreateKernel(owner, owner.Program, name);@@ -1235,7 +1372,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable{if (_subSteps > 1){- SetInt(_stepKernel[current], 8U, subStep == _subSteps && _track ? 1 : 0);+ SetInt(_stepKernel[current], 10U, subStep == _subSteps && _track ? 1 : 0);}Enqueue(_stepKernel[current], _grid2D, _stepLocal, "step");if (_openEdges)@@ -1268,7 +1405,21 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable}if (needIntensity && _hostIntensity != null){- ReadBack(_intensityOutBuffer, _hostIntensity, "intensity");+ // the blend of the two stages, as the captures and probes make it on the card (the kernel no longer writes it every+ // step, 2026-11-03); the CPU engine's expression, multiply and add apart+ ReadBack(_intensityStage1Buffer, _hostStage1!, "intensity stage 1");+ ReadBack(_intensityBuffer, _hostStage2!, "intensity stage 2");+ float[] s1 = _hostStage1!, s2 = _hostStage2!, blend = _hostIntensity;+ float scale = _intensityScale;+ int stride = _stride;+ Parallel.For(0, _height + 2, row =>+ {+ int end = (row + 1) * stride;+ for (int i = row * stride; i < end; i++)+ {+ blend[i] = (s1[i] * 0.5f + s2[i] * 0.5f) * scale;+ }+ });}}@@ -1287,8 +1438,12 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable// info 4 ints per probe: [start in pix, count, 1 = sample inten instead of u, 1 = divide by count];// all 0 for line probes, which therefore write 0// hist ProbeRows × n floats, row-major: hist[row * n + p] receives this step's value+ // the intensity at a cell is the blend of its two stages (inten1, inten; 2026-11-03, no longer written every step by+ // wave_step), the CPU engine's expression with its multiply and add apart, so no contraction in this program+ source.AppendLine("#pragma OPENCL FP_CONTRACT OFF");source.AppendLine("__kernel void probe_sample(__global const float* u, __global const float* inten, __global const int* pix,");- source.AppendLine(" __global const int* info, __global float* hist, const int row, const int n)");+ source.AppendLine(" __global const int* info, __global float* hist, const int row, const int n,");+ source.AppendLine(" __global const float* inten1, const float scale)");source.AppendLine("{");source.AppendLine(" int p = get_global_id(0);");source.AppendLine(" if (p >= n) return;");@@ -1298,7 +1453,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablesource.AppendLine(" int mean = info[p * 4 + 3];");source.AppendLine(" float s = 0.0f;");source.AppendLine(" if (useI != 0) {");- source.AppendLine(" for (int k = 0; k < count; k++) s += inten[pix[start + k]];");+ source.AppendLine(" for (int k = 0; k < count; k++) { int j = pix[start + k]; s += (inten1[j] * 0.5f + inten[j] * 0.5f) * scale; }");source.AppendLine(" } else {");source.AppendLine(" for (int k = 0; k < count; k++) s += u[pix[start + k]];");source.AppendLine(" }");@@ -1314,26 +1469,28 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable// once recording startssource.AppendLine("__kernel void profile_accumulate(__global const float* inten, __global const int* ppix,");source.AppendLine(" __global const int* pmode, __global const int* pStartFlag, __global const int* pStartStep,");- source.AppendLine(" __global float* total, const int step, const int n)");+ source.AppendLine(" __global float* total, const int step, const int n, __global const float* inten1, const float scale)");source.AppendLine("{");source.AppendLine(" int k = get_global_id(0);");source.AppendLine(" if (k >= n) return;");source.AppendLine(" if (pmode[k] != 2) return;");source.AppendLine(" if (pStartFlag[k] != 0 && step < pStartStep[k]) return;");- source.AppendLine(" total[k] += inten[ppix[k]];");+ source.AppendLine(" int j = ppix[k];");+ source.AppendLine(" total[k] += (inten1[j] * 0.5f + inten[j] * 0.5f) * scale;");source.AppendLine("}");source.AppendLine();// profile_gather: one work item per line-probe pixel k < n; same ppix/pmode layout as above.// outv[k] = total[k] (mode 2), inten[ppix[k]] (mode 1) or u[ppix[k]] (mode 0)source.AppendLine("__kernel void profile_gather(__global const float* u, __global const float* inten, __global const int* ppix,");- source.AppendLine(" __global const int* pmode, __global const float* total, __global float* outv, const int n)");+ source.AppendLine(" __global const int* pmode, __global const float* total, __global float* outv, const int n,");+ source.AppendLine(" __global const float* inten1, const float scale)");source.AppendLine("{");source.AppendLine(" int k = get_global_id(0);");source.AppendLine(" if (k >= n) return;");source.AppendLine(" int m = pmode[k];");source.AppendLine(" float v;");source.AppendLine(" if (m == 2) v = total[k];");- source.AppendLine(" else if (m == 1) v = inten[ppix[k]];");+ source.AppendLine(" else if (m == 1) { int j = ppix[k]; v = (inten1[j] * 0.5f + inten[j] * 0.5f) * scale; }");source.AppendLine(" else v = u[ppix[k]];");source.AppendLine(" outv[k] = v;");source.AppendLine("}");@@ -1428,12 +1585,14 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable{IntPtr kernel = _probeKernel[k] = CreateKernel(_probes, _probeProgram, "probe_sample");SetMem(kernel, 0U, _field[k]);- SetMem(kernel, 1U, _intensityOutBuffer);+ SetMem(kernel, 1U, _intensityBuffer);SetMem(kernel, 2U, pixelBuffer);SetMem(kernel, 3U, infoBuffer);SetMem(kernel, 4U, _historyBuffer);SetInt(kernel, 5U, 0);SetInt(kernel, 6U, count);+ SetMem(kernel, 7U, _intensityStage1Buffer);+ SetFloat(kernel, 8U, _intensityScale);}_probeGrid[0] = new IntPtr(count);for (int i = 0; i < count; i++)@@ -1498,17 +1657,19 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable{IntPtr kernel = _gatherKernel[k] = CreateKernel(_probes, _probeProgram, "profile_gather");SetMem(kernel, 0U, _field[k]);- SetMem(kernel, 1U, _intensityOutBuffer);+ SetMem(kernel, 1U, _intensityBuffer);SetMem(kernel, 2U, pixelBuffer);SetMem(kernel, 3U, modeBuffer);SetMem(kernel, 4U, totalBuffer);SetMem(kernel, 5U, _profileOutBuffer);SetInt(kernel, 6U, totalPixels);+ SetMem(kernel, 7U, _intensityStage1Buffer);+ SetFloat(kernel, 8U, _intensityScale);}if (_profileIntegrates){IntPtr kernel = _accumulateKernel = CreateKernel(_probes, _probeProgram, "profile_accumulate");- SetMem(kernel, 0U, _intensityOutBuffer);+ SetMem(kernel, 0U, _intensityBuffer);SetMem(kernel, 1U, pixelBuffer);SetMem(kernel, 2U, modeBuffer);// "start recording at step #" for the integrated line probes: one entry per pixel (same layout as the@@ -1517,6 +1678,8 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposableSetMem(kernel, 4U, CreateBuffer(startSteps, _probes));SetMem(kernel, 5U, totalBuffer);SetInt(kernel, 7U, totalPixels);+ SetMem(kernel, 8U, _intensityStage1Buffer);+ SetFloat(kernel, 9U, _intensityScale);}_profileGrid[0] = new IntPtr(totalPixels);}@@ -1842,9 +2005,19 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable/// <summary>The level-to-frequency table (256 floats), shared by the image and the object sources.</summary>private IntPtr _frequencyBuffer;- /// <summary>The padded c² and pre-scaled damping maps bound to the step and edge kernels; refilled by <see cref="TryReplaceScene"/>.</summary>- private IntPtr _c2Buffer;- private IntPtr _dBuffer;+ /// <summary>Per-cell indices (a byte, a ushort) into the tables of the scene's distinct c² and pre-scaled damping values, bound to the step and edge kernels (<see cref="SceneMaps"/>); refilled by <see cref="TryReplaceScene"/>.</summary>+ private IntPtr _c2IndexBuffer;+ private IntPtr _dIndexBuffer;++ /// <summary>The tables the indices address: 256 floats for c², <see cref="_dTableCapacity"/> for the damping.</summary>+ private IntPtr _c2TableBuffer;+ private IntPtr _dTableBuffer;++ /// <summary>Damping values the table buffer has room for; a scene with more needs a rebuild (<see cref="TryReplaceScene"/> says so).</summary>+ private int _dTableCapacity;++ /// <summary>The least room given to the damping table at <see cref="Build"/>: a scene's blue levels plus a rim's depths come to a few hundred values.</summary>+ private const int DTableRoom = 4096;/// <summary>The image sources' cell indices and levels bound to <c>apply_sources</c> (unset without image sources); refilled by <see cref="TryReplaceScene"/>.</summary>private IntPtr _sourceIndexBuffer;@@ -1904,13 +2077,12 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable/// <summary>The two ping-pong field buffers (padded, <see cref="_cells"/> floats each); the one at <see cref="_current"/> holds the newest field, the other the previous one.</summary>private readonly IntPtr[] _field = new IntPtr[2];- /// <summary>- /// The blend of the two cascaded filter stages (the <c>inten1</c>/<c>inten</c> buffers, which live only- /// inside <c>wave_step</c>), scaled - see the class summary and <c>WaveSimulator._intensityOut</c> (CPU- /// engine). Padded; this is what is actually read back into <see cref="_hostIntensity"/> and sampled by the- /// probe kernels; a 1-float dummy when not tracking.- /// </summary>- private IntPtr _intensityOutBuffer;+ /// <summary>The intensity's scale, applied where the two stages are blended (the captures, the probes, <see cref="PrepareFrame"/>).</summary>+ private float _intensityScale;++ /// <summary>Host copies of the two intensity stages for <see cref="PrepareFrame"/>, which blends them into <see cref="_hostIntensity"/>; null when not tracking.</summary>+ private readonly float[]? _hostStage1;+ private readonly float[]? _hostStage2;/// <summary><c>wave_step</c> kernel per field index k: reads <see cref="_field"/>[k], writes <see cref="_field"/>[1 - k].</summary>private readonly IntPtr[] _stepKernel = new IntPtr[2];@@ -1945,7 +2117,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable/// <summary>Host copy of the newest field, refreshed by <see cref="PrepareFrame"/>; exposed as <see cref="FieldData"/>.</summary>private readonly float[] _hostField;- /// <summary>Host copy of <see cref="_intensityOutBuffer"/>, refreshed by <see cref="PrepareFrame"/>; null when not tracking.</summary>+ /// <summary>Host copy of the scaled intensity, the blend of the two stages, refreshed by <see cref="PrepareFrame"/>; null when not tracking.</summary>private readonly float[]? _hostIntensity;/// <summary>Elapsed time in steps; passed to the source kernels as the float argument <c>t</c>.</summary>diff --git a/WaveDudeNext/Engine/OpenClApi.cs b/WaveDudeNext/Engine/OpenClApi.csindex c6ce6a7..ee67f9a 100644--- a/WaveDudeNext/Engine/OpenClApi.cs+++ b/WaveDudeNext/Engine/OpenClApi.cs@@ -104,6 +104,10 @@ internal static class OpenClApi[DllImport("OpenCL", CharSet = CharSet.Ansi, EntryPoint = "clEnqueueWriteBuffer", ExactSpelling = true, SetLastError = true)]internal static extern int clEnqueueWriteBufferInt(IntPtr queue, IntPtr buffer, uint blocking, IntPtr offset, IntPtr size, int[] data, uint numEvents, IntPtr waitList, IntPtr evt);+ /// <summary>clEnqueueWriteBuffer from memory at <paramref name="ptr"/> (pinned for the call when <paramref name="blocking"/> is 1); <paramref name="offset"/>/<paramref name="size"/> are in bytes.</summary>+ [DllImport("OpenCL", CharSet = CharSet.Ansi, EntryPoint = "clEnqueueWriteBuffer", ExactSpelling = true, SetLastError = true)]+ internal static extern int clEnqueueWriteBufferPtr(IntPtr queue, IntPtr buffer, uint blocking, IntPtr offset, IntPtr size, IntPtr ptr, uint numEvents, IntPtr waitList, IntPtr evt);+/// <summary>clEnqueueReadBuffer into a float array; <paramref name="blocking"/> 1 waits for completion, <paramref name="offset"/>/<paramref name="size"/> are in bytes.</summary>[DllImport("OpenCL", CharSet = CharSet.Ansi, EntryPoint = "clEnqueueReadBuffer", ExactSpelling = true, SetLastError = true)]internal static extern int clEnqueueReadBufferFloat(IntPtr queue, IntPtr buffer, uint blocking, IntPtr offset, IntPtr size, float[] data, uint numEvents, IntPtr waitList, IntPtr evt);diff --git a/WaveDudeNext/Parts/PartPainter.cs b/WaveDudeNext/Parts/PartPainter.csindex 5abdcef..aceb9b7 100644--- a/WaveDudeNext/Parts/PartPainter.cs+++ b/WaveDudeNext/Parts/PartPainter.cs@@ -15,6 +15,8 @@// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or// <https://www.gnu.org/licenses/>.+using System.Diagnostics;+using System.Runtime.CompilerServices;using NLog;using WaveDudeNext.Model;using WaveDudeNext.Runs;@@ -111,18 +113,25 @@ public static class PartPainterLogger.Debug("Part '{Name}' ({Type}) lies outside the canvas", part.Name, part.GetType().Name);return;}- Logger.Debug("Painting part '{Name}' ({Type}) at ({X}, {Y}), {Angle}°, rows {Y0}..{Y1}", part.Name, part.GetType().Name, part.X, part.Y, part.Angle, y0, y1);+ long started = Stopwatch.GetTimestamp();if (shape.Absorption > 0){PaintAbsorption(bgra, stride, shape, x0, y0, x1, y1);}- if (!shape.PaintsIndex)+ if (shape.PaintsIndex){- return;+ PaintIndex(bgra, stride, shape, x0, y0, x1, y1);}+ // what a report needs: which part took how long (2026-11-03, when the app's compositions ran 4-10 times slower than the painter alone)+ Logger.Debug("Painted part '{Name}' ({Type}) at ({X}, {Y}), {Angle}°, rows {Y0}..{Y1} in {Ms:0.0} ms", part.Name, part.GetType().Name, part.X, part.Y, part.Angle, y0, y1, Stopwatch.GetElapsedTime(started).TotalMilliseconds);+ }++ /// <summary>Paints the part's refractive index (red; 0 for a mirror) over the pixel rectangle, supersampling the pixels an edge crosses.</summary>+ private static void PaintIndex(byte[] bgra, int stride, PartShape shape, int x0, int y0, int x1, int y1)+ {if (shape.IsMirror){- Parallel.For(y0, y1 + 1, y =>+ Parallel.For(y0, y1 + 1, [MethodImpl(MethodImplOptions.AggressiveOptimization)] (int y) =>{int row = y * stride;for (int x = x0; x <= x1; x++)@@ -138,14 +147,13 @@ public static class PartPainterconst double step = 1.0 / Supersample;const double half = step / 2.0;int coating = shape.CoatingWidth;- bool innerEdges = shape.HasInnerEdges;- Parallel.For(y0, y1 + 1, y =>+ Parallel.For(y0, y1 + 1, [MethodImpl(MethodImplOptions.AggressiveOptimization)] (int y) =>{int row = y * stride;for (int x = x0; x <= x1; x++){int offset = row + x * 4 + 2;- double depth = shape.DepthAt(x + 0.5, y + 0.5);+ (double depth, double inner) = shape.DepthsAt(x + 0.5, y + 0.5);if (depth < -SampleReach){continue; // every sample outside@@ -154,9 +162,10 @@ public static class PartPainter// red 0 is a mirror the engine reads as index 1000; averaging it in as glass of index 1 is the user's rule,// and a graded band rises from the index the pixel haddouble existing = red == 0 ? 1.0 : red / 100.0;- if (!innerEdges && depth > SampleReach && (coating == 0 || Math.Abs(depth - coating) > SampleReach))+ if (depth > SampleReach && inner > SampleReach && (coating == 0 || Math.Abs(depth - coating) > SampleReach)){- // every sample inside, all in the body or all in the coating band: the centre's index stands for the pixel+ // every sample inside and no edge within reach, neither the outline, an inner edge (a fibre's core, a+ // stack's layer) nor the coating band's: the centre's index stands for the pixelif (shape.IndexAt(x + 0.5, y + 0.5, existing) is { } whole){bgra[offset] = (byte)Math.Clamp((int)Math.Round(whole * 100.0), 1, 255);@@ -204,7 +213,7 @@ public static class PartPainterfloat[] depths = new float[columns * (y1 - y0 + 1)];double deepest = 0.0;var gate = new Lock();- Parallel.For(y0, y1 + 1, () => 0.0, (y, _, local) =>+ Parallel.For(y0, y1 + 1, () => 0.0, [MethodImpl(MethodImplOptions.AggressiveOptimization)] (int y, ParallelLoopState _, double local) =>{int row = (y - y0) * columns;for (int x = x0; x <= x1; x++)@@ -224,7 +233,7 @@ public static class PartPainterdouble ramp = Math.Min(shape.AbsorptionRamp, deepest);int full = shape.Absorption;Logger.Debug("Absorption {Absorption} over a ramp of {Ramp:0.#} px (the part reaches {Deepest:0.#} px deep)", full, ramp, deepest);- Parallel.For(y0, y1 + 1, y =>+ Parallel.For(y0, y1 + 1, [MethodImpl(MethodImplOptions.AggressiveOptimization)] (int y) =>{int row = (y - y0) * columns;for (int x = x0; x <= x1; x++)diff --git a/WaveDudeNext/Parts/PartShape.cs b/WaveDudeNext/Parts/PartShape.csindex d33fc81..f8c3f89 100644--- a/WaveDudeNext/Parts/PartShape.cs+++ b/WaveDudeNext/Parts/PartShape.cs@@ -15,6 +15,7 @@// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or// <https://www.gnu.org/licenses/>.+using System.Runtime.CompilerServices;using WaveDudeNext.Model;namespace WaveDudeNext.Parts;@@ -79,9 +80,11 @@ public abstract class PartShape/// The face nearest the point (x', y') of the part frame. Asked only inside the band of a part that leaves a face/// bare, so a shape without faces to tell apart answers <see cref="Face.Front"/>./// </summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected virtual Face FaceAt(double x, double y) => Face.Front;/// <summary>Whether the band at (x', y') is painted: the flag of the nearest face, without the search when every face is coated.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]private bool Coated(double x, double y) =>_frontCoated && _backCoated && _sidesCoated || FaceAt(x, y) switch { Face.Front => _frontCoated, Face.Back => _backCoated, _ => _sidesCoated };@@ -93,6 +96,7 @@ public abstract class PartShape/// tenths of a percent of the best at two, where the linear ramp reflects three to four times as much./// </summary>/// <param name="t">Depth over thickness; clamped to 0..1.</param>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]public static double GradedProfile(double t){t = Math.Clamp(t, 0.0, 1.0);@@ -143,6 +147,7 @@ public abstract class PartShape/// cubic close behind; the figures are under "Absorption" in OpticalParts.md./// </summary>/// <param name="t">Depth over ramp; clamped to 0..1.</param>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]public static double AbsorptionProfile(double t){t = Math.Clamp(t, 0.0, 1.0);@@ -155,6 +160,7 @@ public abstract class PartShape/// <see cref="AbsorptionProfile"/> of the depth over <paramref name="ramp"/>, rising inward. A shape that absorbs at/// its rim instead (a logic gate's cladding) overrides it./// </summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]public virtual double AbsorptionShareAt(double canvasX, double canvasY, double depth, double ramp) =>AbsorptionProfile(ramp > 0.0 ? depth / ramp : 1.0);@@ -162,19 +168,39 @@ public abstract class PartShapepublic virtual bool PaintsIndex => true;/// <summary>- /// Whether the index steps somewhere inside the outline (a Bragg stack's layers), so a pixel well inside still- /// needs its samples; false where the inside is one index or varies smoothly (the GRIN profile).+ /// Whether the index steps somewhere inside the outline (a Bragg stack's layers, a fibre's core), so a pixel near such+ /// an edge needs its samples (<see cref="InnerEdgeDistance"/> says how near); false where the inside is one index or+ /// varies smoothly (the GRIN profile)./// </summary>public virtual bool HasInnerEdges => false;+ /// <summary>+ /// How far the part-frame point lies from the nearest edge inside the outline where the index steps, in pixels:+ /// infinity for a shape without (<see cref="HasInnerEdges"/> false), so the painter samples a pixel once when neither+ /// the outline nor an inner edge is within reach (2026-11-03: every pixel of a fibre had taken 16 samples, 400 ms for+ /// Example 23's wide fibre). A shape with inner edges that does not say returns 0, which keeps every inside pixel sampled.+ /// </summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]+ protected virtual double InnerEdgeDistance(double x, double y) => HasInnerEdges ? 0.0 : double.PositiveInfinity;+/// <summary>How far inside the outline the canvas point lies, in pixels (negative outside): the exact distance for straight and circular edges, so the painter can tell a pixel wholly inside or outside from one sample.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]public double DepthAt(double canvasX, double canvasY){(double x, double y) = ToFrame(canvasX, canvasY);return Depth(x, y);}+ /// <summary><see cref="DepthAt"/> and the distance to the nearest inner edge (<see cref="InnerEdgeDistance"/>) of the canvas point, in one mapping into the part frame.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]+ public (double Depth, double InnerEdge) DepthsAt(double canvasX, double canvasY)+ {+ (double x, double y) = ToFrame(canvasX, canvasY);+ return (Depth(x, y), InnerEdgeDistance(x, y));+ }+/// <summary>Maps a canvas point into the part frame: the inverse of the composite source's turn (x = dx cos + dy sin, y = dy cos - dx sin), the transpose.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]private (double X, double Y) ToFrame(double canvasX, double canvasY){double ox = canvasX - _centreX;@@ -203,6 +229,7 @@ public abstract class PartShape}/// <summary>The index at a canvas point as <see cref="IndexAt(double, double, double)"/> gives it over a medium of index 1.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]public double? IndexAt(double canvasX, double canvasY) => IndexAt(canvasX, canvasY, 1.0);/// <summary>@@ -214,6 +241,7 @@ public abstract class PartShape/// <param name="canvasX">Canvas x, continuous.</param>/// <param name="canvasY">Canvas y, continuous.</param>/// <param name="outside">The index the pixel had before the part, the medium a graded band rises from.</param>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]public double? IndexAt(double canvasX, double canvasY, double outside){(double x, double y) = ToFrame(canvasX, canvasY);@@ -247,6 +275,7 @@ public abstract class PartShapeprotected static int GuardCoating(int coating) => Math.Clamp(coating, 0, OpticalPart.MaxCoating);/// <summary>Signed distance of (x, y) inside a simple polygon: the distance to the nearest edge, negative outside (even-odd rule).</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected static double PolygonDepth(ReadOnlySpan<(double X, double Y)> vertices, double x, double y){bool inside = false;@@ -269,6 +298,7 @@ public abstract class PartShape}/// <summary>Distance from (x, y) to the segment a–b.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected static double SegmentDistance(double ax, double ay, double bx, double by, double x, double y){double dx = bx - ax;@@ -311,16 +341,20 @@ public abstract class PartShapepublic override int Absorption { get; }public override int AbsorptionRamp { get; }protected override double Extent => _extent;+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double BodyIndex(double x, double y) => _index;/// <summary>How far a surface of radius <paramref name="radius"/> bows out beyond its vertex at the lens edge.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]private double Sag(double radius) => LensPart.Sag(radius, _half);/// <summary>The least of: inside the first surface, inside the second, within the half-diameter.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double Depth(double x, double y) =>Math.Min(Math.Min(SurfaceDepth(x, y, _vertex1, _r1, -1), SurfaceDepth(x, y, _vertex2, _r2, +1)), _half - Math.Abs(y));/// <summary>The nearest of the three: the first surface is the front, the second the back, the rim the sides.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override Face FaceAt(double x, double y){double first = SurfaceDepth(x, y, _vertex1, _r1, -1);@@ -336,6 +370,7 @@ public abstract class PartShape/// radius and side have opposite signs. Distances are to the circle, so the coating band keeps its thickness/// along the normal./// </summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]private static double SurfaceDepth(double x, double y, double vertex, double radius, int side){if (radius == 0.0)@@ -398,6 +433,7 @@ public abstract class PartShape}/// <summary>The face of the edge nearest the point.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override Face FaceAt(double x, double y){int nearest = 0;@@ -419,7 +455,9 @@ public abstract class PartShapepublic override int Absorption { get; }public override int AbsorptionRamp { get; }protected override double Extent => _extent;+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double Depth(double x, double y) => PolygonDepth(_vertices, x, y);+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double BodyIndex(double x, double y) => _index;}@@ -542,6 +580,7 @@ public abstract class PartShape/// outer radius − 2 × band to the peak, and falling the same way to nothing at the outer edge; the depth given by/// the painter is not used, so the band runs up to an end face and stops there instead of wrapping it./// </summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]public override double AbsorptionShareAt(double canvasX, double canvasY, double depth, double ramp){if (_band <= 0.0)@@ -563,6 +602,7 @@ public abstract class PartShape/// The start face is the front, the end face the back, the tube the sides: with flat ends, whichever of the three/// the point is nearest to inside; with round ends, the caps before the start and beyond the end./// </summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override Face FaceAt(double x, double y){int last = _path.Length - 1;@@ -576,11 +616,17 @@ public abstract class PartShapereturn startDepth <= endDepth && startDepth <= side ? Face.Front : endDepth <= side ? Face.Back : Face.Sides;}- /// <summary>The core's edge steps inside the outline, so the painter samples every pixel of the tube (without this the core edge came out unsmoothed, 2026-10-22).</summary>+ /// <summary>The core's edge steps inside the outline, so the painter samples the pixels near it (without this the core edge came out unsmoothed, 2026-10-22; every pixel of the tube until 2026-11-03).</summary>public override bool HasInnerEdges { get; }++ /// <summary>The core boundary's distance, |r − core radius| by the distance from the path; none without a cladding.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]+ protected override double InnerEdgeDistance(double x, double y) => HasInnerEdges ? Math.Abs(PathDistance(x, y) - _coreRadius) : double.PositiveInfinity;protected override double Extent => _extent;+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double BodyIndex(double x, double y) => PathDistance(x, y) <= _coreRadius ? _coreIndex : _claddingIndex;+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double Depth(double x, double y){(int from, int to) = ChordsNear(x, y);@@ -629,6 +675,7 @@ public abstract class PartShape}/// <summary>Distance to the nearest chord of the path among those listed for the point's cell (exact within the tube, where the nearest chord is always listed).</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]private double PathDistance(double x, double y){(int from, int to) = ChordsNear(x, y);@@ -642,6 +689,7 @@ public abstract class PartShape}/// <summary>The range in the chord lists for the cell of (x', y'): empty outside the grid.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]private (int From, int To) ChordsNear(double x, double y){int column = (int)Math.Floor((x - _gridX) / CellSize);@@ -655,12 +703,15 @@ public abstract class PartShape}/// <summary>The cell holding (x', y'), clamped onto the grid.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]private (int Column, int Row) CellOf(double x, double y) =>(Math.Clamp((int)Math.Floor((x - _gridX) / CellSize), 0, _columns - 1), Math.Clamp((int)Math.Floor((y - _gridY) / CellSize), 0, _rows - 1));+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]private static double Square(double v) => v * v;/// <summary>The direction (x, y) as a unit vector, or null for a zero vector.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]private static (double X, double Y)? Unit(double x, double y){double length = Math.Sqrt(x * x + y * y);@@ -691,9 +742,19 @@ public abstract class PartShapeprotected override int Coating => 0;public override bool HasInnerEdges => true;protected override double Extent => Math.Sqrt(_halfLength * _halfLength + _halfWidth * _halfWidth);++ /// <summary>The nearest layer boundary along x': a pair's edges at 0, its first thickness and the period.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]+ protected override double InnerEdgeDistance(double x, double y)+ {+ double along = (x + _halfLength) % _period;+ return Math.Min(along, Math.Min(Math.Abs(along - _thickness1), _period - along));+ }+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double Depth(double x, double y) => Math.Min(_halfLength - Math.Abs(x), _halfWidth - Math.Abs(y));/// <summary>The first layer of a pair starts at -L/2 and the pairs repeat along +x'.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double BodyIndex(double x, double y){double along = (x + _halfLength) % _period;@@ -720,13 +781,16 @@ public abstract class PartShapepublic override bool IsMirror => false;protected override int Coating { get; }protected override double Extent => Math.Sqrt(_halfLength * _halfLength + _halfDiameter * _halfDiameter);+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double Depth(double x, double y) => Math.Min(_halfLength - Math.Abs(x), _halfDiameter - Math.Abs(y));/// <summary>The end faces across the axis are the front (−x') and the back, the long sides the sides.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override Face FaceAt(double x, double y) =>_halfLength - Math.Abs(x) <= _halfDiameter - Math.Abs(y) ? (x < 0.0 ? Face.Front : Face.Back) : Face.Sides;/// <summary>n(y') = n_c − (n_c − n_e)·(y' / (D/2))².</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double BodyIndex(double x, double y){double t = y / _halfDiameter;@@ -764,10 +828,13 @@ public abstract class PartShapepublic override int Absorption => ZonePlatePart.BlockAbsorption;public override int AbsorptionRamp => Math.Max(1, (int)Math.Ceiling(_ramp));protected override double Extent => Math.Sqrt(_halfThickness * _halfThickness + _outerHalfWidth * _outerHalfWidth);+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double Depth(double x, double y) => Math.Min(_halfThickness - Math.Abs(x), _outerHalfWidth - Math.Abs(y));+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double BodyIndex(double x, double y) => 1.0;/// <summary>Nothing in an open zone; in a block or the mount, rising quadratically from the faces across the axis over the ramp.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]public override double AbsorptionShareAt(double canvasX, double canvasY, double depth, double ramp){(double x, double y) = ToFrame(canvasX, canvasY);@@ -835,6 +902,7 @@ public abstract class PartShape/// arm of a switched-off output, rising quadratically from nothing over the output ramp to full at the right end. The/// input ends and an active output do not absorb, so light comes in and goes out./// </summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]public override double AbsorptionShareAt(double canvasX, double canvasY, double depth, double ramp){(double x, double y) = ToFrame(canvasX, canvasY);@@ -850,6 +918,7 @@ public abstract class PartShape}/// <summary>The distance from the nearer arm's centre line, and whether that arm is B (below the axis).</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]private (double Distance, bool ArmB) Nearest(double x, double y){(double offset, double slope) = _design.ArmOffsetAndSlope(x);@@ -857,9 +926,11 @@ public abstract class PartShapereturn (Math.Abs(Math.Abs(y) - offset) * cos, y > 0.0);}+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double Depth(double x, double y) => Math.Min(_halfLength - Math.Abs(x), _outer - Nearest(x, y).Distance);/// <summary>The core, the phase section on its arm, or the cladding; within the coating's thickness of a coated end (the input at −x, the output at +x), √n of it rounded to 0.01.</summary>+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]protected override double BodyIndex(double x, double y){(double distance, bool armB) = Nearest(x, y);diff --git a/WaveDudeNext/Rendering/GlowingEdges.cs b/WaveDudeNext/Rendering/GlowingEdges.csindex 6bb039d..8bd444b 100644--- a/WaveDudeNext/Rendering/GlowingEdges.cs+++ b/WaveDudeNext/Rendering/GlowingEdges.cs@@ -15,6 +15,8 @@// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or// <https://www.gnu.org/licenses/>.+using System.Runtime.CompilerServices;+namespace WaveDudeNext.Rendering;/// <summary>@@ -54,7 +56,7 @@ public static class GlowingEdgesreturn result;}// rows are independent: a Full HD canvas took 60 ms on one core (2026-10-19)- Parallel.For(1, height - 1, y =>+ Parallel.For(1, height - 1, [MethodImpl(MethodImplOptions.AggressiveOptimization)] (int y) =>{int rowUp = (y - 1) * strideBytes;int rowMid = y * strideBytes;diff --git a/WaveDudeNext/Runs/ScratchRunner.cs b/WaveDudeNext/Runs/ScratchRunner.csindex cb8897e..cee0a0a 100644--- a/WaveDudeNext/Runs/ScratchRunner.cs+++ b/WaveDudeNext/Runs/ScratchRunner.cs@@ -181,7 +181,9 @@ public sealed class ScratchRunner : IDisposable{if (i % CheckInterval == 0 && (HasNewerRequest() || token.IsCancellationRequested)){- return; // the loop picks up the newer request+ // the loop picks up the newer request; said in the log, so a report shows the frames that were never finished (2026-11-03)+ Logger.Debug("Preview frame {Frame} abandoned after {Done} of {Steps} steps for a newer request", frame, i, steps);+ return;}engine.AdvanceOneStep();if (sampler != null)