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#
Colour schemes are gradients: 16-bit frames take every level of the gradient
Alexander Graefaa1b8f685590
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8b347db..c51b76b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -90,7 +90,7 @@ SimulationRun: stepping loop + writer threads; IWaveEngine (WaveSimulator CPU |FrameCount, then StateScratchRunner: one kept engine; "frame k of the project as it is now" from step 0, probes sampled; newest requestwins; every request is computed-FramePresenter: CopyLayer -> FrameRenderer (Vector128, 32-row blocks) -> the WriteableBitmap, copied on the pool+FramePresenter: CopyLayer -> FrameRenderer (a table lookup per pixel, 32-row blocks) -> the WriteableBitmap, copied on the poolbetween Lock/Unlock on the UI thread; only the newest request is renderedExportJob (own STA thread): CopyLayer -> FrameRenderer -> outline -> probe boxes/markers -> sinks (PNG, JPEG, MPEG-1, AVI, MP4, MOV)FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDATA%\WaveDudeNext\cache, DeleteOnClose)@@ -126,14 +126,13 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAcache reliance (both wrote at disk speed). Disposed on the thread pool. Full HD, 2500 steps, both planes: 10.4 GBin 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. 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 or- skipped frames make the export run the simulation again at full quality first.+ **8-bit palette index, the default**: the stored samples at the palette's 255 colours and the captured brightness,+ half the store; 16-bit keeps the brightness turnable after a run and shows every level of the gradient. 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 CPU and GPU store the same index bytes (2026-10-19).+ Every export needs the 16-bit samples (2026-10-23, the user's choice, so a picture has every level of the gradient):+ an 8-bit run, a reduced resolution or skipped frames make the export run the simulation again at full quality first.## The app's rules@@ -167,6 +166,10 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAand point handles belong to the current item alone. Probe graph boxes follow their probe while attached, resize by a grip, keep their textsize; an amplitude axis is symmetric about zero; an intensity graph's value axis can be logarithmic (2026-10-20,Jeroen's point 8: `Decades` below the fitted top, zeros on the bottom line, powers-of-ten ticks; the field stays linear).+- **Colour schemes are gradients** (2026-10-23, the user's design): the model holds the stops and no table; how many+ colours are taken is the renderer's (`ColorLut`): 255 at i/254 for 8-bit frames (the author's table, truncated as in+ his Python), and for 16-bit frames a table of the 65,536 half values per layer and brightness, the gradient at each+ value's position, rounded (the 255 entries had left visible patches two to five levels apart in dark gradients).- **Colour schemes** are stop lists in `.wdscheme` XML, shipped ones embedded, user ones in`%LOCALAPPDATA%\WaveDudeNext\ColorSchemes`, project ones in the `.wdproj`; an in-house picker edits stops;renaming a project scheme repoints its layers. **The scene image** is embedded and follows its file on disk;@@ -205,8 +208,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 run of 2500 steps 5.4 s in RAM, bound by-the GPU readback. Renderer per 2880×1080 layer on ten cores: 8-bit 1.0 ms, 16-bit 2.0; vector rows gain 2× per-core over scalar. Presenter about 7 ms a frame quiet, 20 during a run. JPEG 1080p at 4:4:4: WIC 26 ms a frame+the GPU readback. Renderer per 2880×1080 layer on ten cores (2026-10-23, a table lookup per pixel): 16-bit 0.5 ms,+8-bit 0.6; a half table built in 0.4 ms. Presenter about 7 ms a frame quiet, 20 during a run. JPEG 1080p at 4:4:4: WIC 26 ms a framesingle-threaded (9 ms a frame in a sequence job on half the cores), in-house 9.8 ms on ten cores (15 in a job);MP4 job 16 ms a frame. Part painter on a Full HD canvas (ten cores): a 400 × 330 outline 30 ms, a 400 px lens 5, a hexagon 8, an S-bent fibre across the canvas 51 (156 chords on the cell grid; 1.3 s without it);the glowing edges 22 ms; the preview's scene pictures about 100 ms more, so the scene rebuild is coalesced at background priority. Laptop (2 cores, HD 520, HDD): iGPU 4.3 ms a step against CPU 14.7; the balldiff --git a/WaveDudeNext.WPF/Converters/ColorSchemeBrushConverter.cs b/WaveDudeNext.WPF/Converters/ColorSchemeBrushConverter.csindex 639d61b..8f847c0 100644--- a/WaveDudeNext.WPF/Converters/ColorSchemeBrushConverter.cs+++ b/WaveDudeNext.WPF/Converters/ColorSchemeBrushConverter.cs@@ -25,7 +25,7 @@ namespace WaveDudeNext.WPF.Converters;/// <summary>/// A colour scheme (or its stop list, or a plain colour list) as a horizontal gradient brush, the preview/// strip of the picker, the tree and the editor: every stop becomes a gradient stop at its position when-/// there are up to 64, else 64 samples of the interpolated table. Null gives a transparent brush. The+/// there are up to 64, else 64 samples of the gradient. Null gives a transparent brush. The/// brush is frozen./// </summary>public sealed class ColorSchemeBrushConverter : IValueConverterdiff --git a/WaveDudeNext.WPF/MainWindow.Export.cs b/WaveDudeNext.WPF/MainWindow.Export.csindex 6a12bbb..ada27ad 100644--- a/WaveDudeNext.WPF/MainWindow.Export.cs+++ b/WaveDudeNext.WPF/MainWindow.Export.cs@@ -277,7 +277,7 @@ public partial class MainWindow}}}- SimulationRun? run = await EnsureRunForExport(intensity, ExportFormats.IsData(format));+ SimulationRun? run = await EnsureRunForExport(intensity, needsHalves: true);if (run == null){return;@@ -324,7 +324,7 @@ public partial class MainWindowforeach ((FrameLayer layer, string path) in outputs){DisplayLayer settings = layer == FrameLayer.Field ? display.Field : display.Intensity;- int[]? lut = ColorSchemeCatalog.Instance.LutFor(Project, settings.ColorScheme, settings.BlackLevel);+ ColorLut lut = ColorSchemeCatalog.Instance.LutFor(Project, settings.ColorScheme, settings.BlackLevel);Action<int, Memory<int>>? probes = painter?.For(layer == FrameLayer.Field ? ProbeLayer.Field : ProbeLayer.Intensity);Action<int, Memory<int>>? decorate = sources == null ? probes : (frame, pixels) =>{@@ -385,7 +385,7 @@ public partial class MainWindow/// be had (logged, and an error shown when the run could not start)./// </summary>/// <param name="intensity">The run must hold the intensity plane.</param>- /// <param name="needsHalves">The run must hold 16-bit samples (a data export); otherwise the 8-bit index does.</param>+ /// <param name="needsHalves">The run must hold 16-bit samples (every picture or data export); the probe data does with the 8-bit index.</param>private async Task<SimulationRun?> EnsureRunForExport(bool intensity, bool needsHalves){IsExportWaiting = true;@@ -394,12 +394,13 @@ public partial class MainWindowfor (int attempt = 0; attempt < 3; attempt++){SimulationRun? run = Run;- // a reduced preview serves a picture export when only its samples are reduced: the 8-bit index gives the- // same pixels (2026-10-18); a smaller picture or skipped frames never do, and a data export needs the halves+ // a reduced preview never serves a picture or data export: a smaller picture or skipped frames are not the+ // run, and the 8-bit index has only the palette's 255 colours where the 16-bit samples give every level of the+ // gradient (2026-10-23, the user's choice; from 2026-10-18 a picture export had taken an 8-bit run as it was)PreviewQuality? quality = run?.Spec.Quality;bool reduced = quality != null && (quality.ResolutionDivisor != 1 || quality.FrameDivisor != 1 || (quality.Format != FrameFormat.Half && needsHalves));string? reason = run == null ? "no run" : IsRunStale ? "the run is stale" : IsProbesStale ? "the probes were edited since the run"- : reduced ? (quality!.Format != FrameFormat.Half && needsHalves && quality.ResolutionDivisor == 1 && quality.FrameDivisor == 1 ? "a data export needs the 16-bit samples" : "the run is a reduced preview (View menu)")+ : reduced ? (quality!.Format != FrameFormat.Half && needsHalves && quality.ResolutionDivisor == 1 && quality.FrameDivisor == 1 ? "the export needs the 16-bit samples" : "the run is a reduced preview (View menu)"): intensity && !run.Store.Has(FrameLayer.Intensity) ? "the run has no intensity plane" : !run.IsActive && run.State != RunState.Completed ? "the run did not complete" : null;if (reason != null){diff --git a/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs b/WaveDudeNext.WPF/Panes/PreviewPane.xaml.csindex 348a16a..cea5812 100644--- a/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs+++ b/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs@@ -908,7 +908,7 @@ public partial class PreviewPane : UserControlprivate void ApplyLayer(FrameLayer layer){DisplayLayer? settings = layer == FrameLayer.Field ? FieldSettings : IntensitySettings;- int[]? lut = settings == null ? null : ColorSchemeCatalog.Instance.LutFor(Project, settings.ColorScheme, settings.BlackLevel);+ ColorLut lut = settings == null ? ColorLut.Grey : ColorSchemeCatalog.Instance.LutFor(Project, settings.ColorScheme, settings.BlackLevel);_presenter.SetLayer(layer, lut, (float)(settings?.Brightness ?? DisplayLayer.DefaultBrightness), settings?.Preview ?? true);}diff --git a/WaveDudeNext.WPF/Rendering/ColorSchemeCatalog.cs b/WaveDudeNext.WPF/Rendering/ColorSchemeCatalog.csindex a5fefe5..0c86390 100644--- a/WaveDudeNext.WPF/Rendering/ColorSchemeCatalog.cs+++ b/WaveDudeNext.WPF/Rendering/ColorSchemeCatalog.cs@@ -25,10 +25,10 @@ namespace WaveDudeNext.WPF.Rendering;/// The colour schemes available to a project: the project's own (<see cref="Project.ColorSchemes"/>,/// consulted first, so a project scheme shadows a built-in of the same name), then the user's folder/// (<see cref="ColorSchemeStore.UserFolder"/>), then the ones built into the library; the last two-/// are loaded once. Also a cache of the palettes built from the shared schemes for the display-/// settings in use; a project scheme's palette is built on every request, since it may be mid-edit-/// and 255 entries cost nothing. UI thread only; the <c>int[]</c> palettes are immutable and may be-/// handed to rendering threads.+/// are loaded once. Also a cache of the colours built from the shared schemes for the display+/// settings in use (each keeps the half tables it has built); a project scheme's are built on every+/// request, since it may be mid-edit, and a copy of its stops and 255 entries cost nothing (the half+/// tables follow on first use). UI thread only; a <see cref="ColorLut"/> may be handed to rendering threads./// </summary>public sealed class ColorSchemeCatalog{@@ -37,7 +37,7 @@ public sealed class ColorSchemeCatalog/// <summary>The single catalog of the application.</summary>public static ColorSchemeCatalog Instance { get; } = new();- private readonly Dictionary<(string Name, double BlackLevel), int[]?> _luts = new();+ private readonly Dictionary<(string Name, double BlackLevel), ColorLut> _luts = new();private readonly HashSet<string> _warned = new(StringComparer.OrdinalIgnoreCase);private List<ColorScheme>? _schemes;@@ -100,17 +100,17 @@ public sealed class ColorSchemeCatalog}/// <summary>- /// The palette of the scheme called <paramref name="name"/> with the given black level; null (greyscale)+ /// The colours of the scheme called <paramref name="name"/> with the given black level; <see cref="ColorLut.Grey"/>/// when no such scheme exists, which is logged once per name. Shared schemes are cached; a project scheme is built fresh./// </summary>- public int[]? LutFor(Project? project, string name, double blackLevel)+ public ColorLut LutFor(Project? project, string name, double blackLevel){if (project != null && ColorSchemeStore.Find(project.ColorSchemes, name) is { } own){- return ColorLut.Build(own, blackLevel: blackLevel).Argb;+ return ColorLut.Build(own, blackLevel: blackLevel);}(string, double) key = (name, blackLevel);- if (_luts.TryGetValue(key, out int[]? lut))+ if (_luts.TryGetValue(key, out ColorLut? lut)){return lut;}@@ -121,11 +121,11 @@ public sealed class ColorSchemeCatalog{Logger.Warn("Colour scheme '{Name}' not found; showing greyscale", name);}- lut = null;+ lut = ColorLut.Grey;}else{- lut = ColorLut.Build(scheme, blackLevel: blackLevel).Argb;+ lut = ColorLut.Build(scheme, blackLevel: blackLevel);}_luts[key] = lut;return lut;diff --git a/WaveDudeNext.WPF/Rendering/FramePresenter.cs b/WaveDudeNext.WPF/Rendering/FramePresenter.csindex 278c216..639b750 100644--- a/WaveDudeNext.WPF/Rendering/FramePresenter.cs+++ b/WaveDudeNext.WPF/Rendering/FramePresenter.cs@@ -61,7 +61,7 @@ public sealed class FramePresenter/// <summary>Colour and visibility of one layer, as last set through <see cref="SetLayer"/>.</summary>private sealed record LayerSettings{- public int[]? Lut { get; init; }+ public ColorLut Lut { get; init; } = ColorLut.Grey;public float Brightness { get; init; } = 1f;public bool Enabled { get; init; } = true;}@@ -117,10 +117,10 @@ public sealed class FramePresenter/// <summary>Sets how a layer is coloured and whether it is rendered at all; the shown frame is redrawn.</summary>/// <param name="layer">The plane.</param>- /// <param name="lut">Palette, or null for greyscale.</param>- /// <param name="brightness">Gain before the palette lookup.</param>+ /// <param name="lut">The colours (<see cref="ColorLut.Grey"/> for greyscale).</param>+ /// <param name="brightness">Gain before the colour lookup.</param>/// <param name="enabled">False leaves the bitmap untouched (the picture is hidden anyway).</param>- public void SetLayer(FrameLayer layer, int[]? lut, float brightness, bool enabled)+ public void SetLayer(FrameLayer layer, ColorLut lut, float brightness, bool enabled){_settings[(int)layer] = new LayerSettings { Lut = lut, Brightness = brightness, Enabled = enabled };Rebuild();@@ -246,13 +246,10 @@ public sealed class FramePresenter// palette indices: the brightness was applied when the frame was captured, only the palette is looked upFrameRenderer.RenderIndexed(job.Indices, width, height, settings.Lut, job.Pixels);}- else if (layer == FrameLayer.Field)- {- FrameRenderer.RenderField(job.Halves, width, height, settings.Lut, settings.Brightness, job.Pixels);- }else{- FrameRenderer.RenderIntensity(job.Halves, width, height, settings.Lut, settings.Brightness, job.Pixels);+ // 16-bit samples: every level of the gradient (a brightness new to the colours builds the layer's half table first)+ FrameRenderer.Render(job.Halves, width, height, settings.Lut, layer, settings.Brightness, job.Pixels);}_colourClock.Stop();// the copy into the bitmap runs here, on the pool thread, between a lock and an unlock on the UI threaddiff --git a/WaveDudeNext/Engine/GpuWaveSimulator.cs b/WaveDudeNext/Engine/GpuWaveSimulator.csindex 3fa2ee1..3d6e179 100644--- a/WaveDudeNext/Engine/GpuWaveSimulator.cs+++ b/WaveDudeNext/Engine/GpuWaveSimulator.cs@@ -768,8 +768,9 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablesource.AppendLine();// the index mapping of ColorLut.FieldIndex / IntensityIndex: a NaN field gives the centre, a NaN or// 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).+ // index is the palette index of the very half a 16-bit run stores, as the CPU's capture computes it, bit for bit+ // (2026-10-19: an 8-bit run and a 16-bit run of the same project had 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 separatesource.AppendLine("float round_to_half(float f)");diff --git a/WaveDudeNext/Export/ExportJob.cs b/WaveDudeNext/Export/ExportJob.csindex 31491d3..e4895a1 100644--- a/WaveDudeNext/Export/ExportJob.cs+++ b/WaveDudeNext/Export/ExportJob.cs@@ -47,12 +47,12 @@ public enum ExportState/// render thread, once per frame, after the outline, on the frame's packed BGRA32 pixels./// </summary>/// <param name="Layer">Which plane of the store.</param>-/// <param name="Lut">The colour table (<c>ColorLut.Argb</c>), or null for grey levels.</param>+/// <param name="Lut">The colours (<see cref="ColorLut.Grey"/> for grey levels).</param>/// <param name="Brightness">The layer's gain.</param>/// <param name="Edges">The glowing-edges picture (<see cref="GlowingEdges.Compute"/>) to add, or null.</param>/// <param name="EdgeGain">The outline's gain; 0 adds nothing.</param>/// <param name="Decorate">Draws over the rendered frame: the frame index and the pixels; null for none.</param>-public sealed record ExportLayer(FrameLayer Layer, int[]? Lut, float Brightness, byte[]? Edges, double EdgeGain, Action<int, Memory<int>>? Decorate);+public sealed record ExportLayer(FrameLayer Layer, ColorLut Lut, float Brightness, byte[]? Edges, double EdgeGain, Action<int, Memory<int>>? Decorate);/// <summary>/// One output of an export: a layer rendered into a sink. The sink is opened by the job on its sink thread@@ -70,7 +70,7 @@ public sealed record ExportTarget(ExportLayer Layer, string Output, Func<IFrameS/// <summary>/// Renders a range of a run's stored frames into one or more sinks: a render thread reads each target's-/// plane from the <see cref="FrameStore"/>, colours it with <see cref="FrameRenderer"/>, adds the outline+/// plane of 16-bit samples from the <see cref="FrameStore"/>, colours it with <see cref="FrameRenderer"/>, adds the outline/// (<see cref="GlowingEdges.BlendAdditive"/>) and the decoration, and hands the pixels to a sink thread,/// which opens the sinks, encodes and writes; the two overlap, so a frame's encoding costs no rendering time/// (2026-10-14). Progress and the final state are published through the <see cref="SynchronizationContext"/>@@ -107,9 +107,9 @@ public sealed class ExportJob : INotifyPropertyChanged{throw new ArgumentOutOfRangeException(nameof(lastFrame), "The range is empty.");}- // an 8-bit store (palette indices with the brightness baked in) renders to the same pixels as the halves would- // (2026-10-18; until then every export demanded a 16-bit run): the palette and black level still apply at- // render time. Only a data sink (OpenEXR) needs the halves, which Render checks once the sinks are open.+ // every export needs the 16-bit samples (2026-10-23, the user's choice): a picture takes every level of the+ // gradient from them, which an 8-bit store's 255 palette entries cannot give, and a data sink (OpenEXR) writes+ // them. Render refuses a store of palette indices once the sinks are open (from 2026-10-18 it had taken one for pictures)Store = store;FirstFrame = firstFrame;LastFrame = lastFrame;@@ -201,7 +201,7 @@ public sealed class ExportJob : INotifyPropertyChanged/// <summary>A frame for one target: rendered pixels, or the store's halves for a sink that wants them (one of the two is set).</summary>private sealed record Item(int Frame, int Target, int[]? Pixels, Half[]? Values);- /// <summary>The outline and the decoration over a rendered frame, the same for halves and for palette indices.</summary>+ /// <summary>The outline and the decoration over a rendered frame.</summary>private static void Finish(ExportLayer layer, int frame, int[] pixels, int width, int height){if (layer.Edges != null && layer.EdgeGain > 0.0)@@ -308,9 +308,9 @@ public sealed class ExportJob : INotifyPropertyChangedsinksReady.Wait();if (sinkError == null){- if (Store.Format != FrameFormat.Half && Targets.Any(target => target.Sink?.WantsHalves == true))+ if (Store.Format != FrameFormat.Half){- throw new InvalidOperationException("A data export (OpenEXR) needs a 16-bit run; this store holds palette indices.");+ throw new InvalidOperationException("An export needs a 16-bit run; this store holds palette indices.");}int pictureTargets = Targets.Count(target => target.Sink?.WantsHalves != true);for (int i = 0; i < pictureTargets * QueueDepth + 1; i++)@@ -323,7 +323,6 @@ public sealed class ExportJob : INotifyPropertyChanged}}var values = new Half[width * height];- byte[]? indices = Store.Format == FrameFormat.Index ? new byte[width * height] : null;for (int frame = FirstFrame; frame <= LastFrame && sinkError == null; frame++){if (_cancel.IsCancellationRequested)@@ -345,32 +344,12 @@ public sealed class ExportJob : INotifyPropertyChangedqueue.Add(new Item(frame, t, null, plane));continue;}- if (indices != null)- {- // the 8-bit store: the palette index as captured (brightness baked in), coloured through the LUT- if (frame >= Store.Count || !Store.CopyLayer(frame, layer.Layer, indices.AsSpan()))- {- throw new InvalidOperationException($"Frame {frame} is not in the store (it holds {Store.Count}).");- }- int[] indexed = free.Take();- FrameRenderer.RenderIndexed(indices, width, height, layer.Lut, indexed);- Finish(layer, frame, indexed, width, height);- queue.Add(new Item(frame, t, indexed, null));- continue;- }if (frame >= Store.Count || !Store.CopyLayer(frame, layer.Layer, values)){throw new InvalidOperationException($"Frame {frame} is not in the store (it holds {Store.Count}).");}int[] pixels = free.Take();- if (layer.Layer == FrameLayer.Intensity)- {- FrameRenderer.RenderIntensity(values, width, height, layer.Lut, layer.Brightness, pixels);- }- else- {- FrameRenderer.RenderField(values, width, height, layer.Lut, layer.Brightness, pixels);- }+ FrameRenderer.Render(values, width, height, layer.Lut, layer.Layer, layer.Brightness, pixels);Finish(layer, frame, pixels, width, height);queue.Add(new Item(frame, t, pixels, null));}diff --git a/WaveDudeNext/Rendering/ColorLut.cs b/WaveDudeNext/Rendering/ColorLut.csindex cff3889..6b58a1f 100644--- a/WaveDudeNext/Rendering/ColorLut.cs+++ b/WaveDudeNext/Rendering/ColorLut.cs@@ -15,62 +15,100 @@// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or// <https://www.gnu.org/licenses/>.+using WaveDudeNext.Runs;+namespace WaveDudeNext.Rendering;/// <summary>-/// An immutable palette of <see cref="Size"/> opaque ARGB entries built from a-/// <see cref="ColorScheme"/> by <see cref="Build"/> plus the display options of the Python-/// function <c>get_colormap_lut</c> (invert, black level, make symmetric), and the static-/// value-to-index mappings used when colouring frames, which convert field and intensity-/// values to table indices exactly like <c>WaveVisualizer.render_field</c> /-/// <c>render_intensity</c>. Built on the UI thread when the display settings change; the-/// <see cref="Argb"/> array is then read from <see cref="FrameRenderer"/>'s parallel loops without-/// locking (it is never modified after construction).+/// The colours a renderer takes from a <see cref="ColorScheme"/>'s gradient, with the display options of the Python+/// function <c>get_colormap_lut</c> (invert, black level, make symmetric) applied, for the two kinds of stored frame+/// (2026-10-23, the user's design: the scheme is the gradient, how many colours are taken from it is the renderer's+/// business):+/// <list type="bullet">+/// <item>a frame of 8-bit palette indices: <see cref="Argb"/>, <see cref="Size"/> colours at i / 254 like the author's+/// table, looked up by the byte the capture computed (<see cref="FieldIndex"/>, <see cref="IntensityIndex(float, float)"/>,+/// the GPU's <c>capture_index</c>), channels truncated like the Python code;</item>+/// <item>a frame of 16-bit samples: <see cref="HalfTable"/>, a colour for each of the 65,536 values a half can hold, the+/// gradient evaluated at that value's own position and rounded to the nearest level, so a picture has every level the+/// gradient passes through (the 255 entries had left steps of two to five levels in dark gradients, seen as patches).</item>+/// </list>+/// Built on the UI thread from a copy of the stops, then immutable apart from the cache of half tables: read from the+/// presenter's and the export's threads without locking./// </summary>-/// <remarks>-/// The options belong to how a scheme is used (field or intensity), not to the scheme itself, so-/// they are not saved in the scheme file; they live in <see cref="Model.DisplayLayer"/>.-/// </remarks>public sealed class ColorLut{- private ColorLut(int[] argb) => Argb = argb;+ /// <summary>Number of entries in the 8-bit palette, index 0..254: the author's table, and the range of the captured index bytes.</summary>+ public const int Size = 255;++ /// <summary>Number of values a 16-bit sample can hold: the length of a <see cref="HalfTable"/>.</summary>+ public const int HalfValues = 1 << 16;++ private readonly List<ColorStop> _stops;+ private readonly bool _invert;+ private readonly double _blackLevel;+ private readonly bool _makeSymmetric;+ private readonly bool _reverse;+ private HalfTableEntry? _fieldTable;+ private HalfTableEntry? _intensityTable;++ /// <summary>A built half table and the brightness it was built for.</summary>+ private sealed record HalfTableEntry(float Brightness, int[] Argb);++ private ColorLut(List<ColorStop> stops, bool invert, double blackLevel, bool makeSymmetric, bool reverse)+ {+ _stops = stops;+ _invert = invert;+ _blackLevel = blackLevel;+ _makeSymmetric = makeSymmetric;+ _reverse = reverse;+ Argb = BuildPalette();+ }/// <summary>- /// The palette as packed opaque ARGB ints (<c>0xFFRRGGBB</c>, the memory order of BGRA32 pixels),- /// indices 0..<see cref="Size"/>-1. Returns the internal array, not a copy; callers must not modify it.+ /// The 8-bit palette as packed opaque ARGB ints (<c>0xFFRRGGBB</c>, the memory order of BGRA32 pixels), indices+ /// 0..<see cref="Size"/>-1. Returns the internal array, not a copy; callers must not modify it./// </summary>public int[] Argb { get; }- /// <summary>Returns entry <paramref name="index"/> (0..<see cref="Size"/>-1) as a colour.</summary>+ /// <summary>Returns palette entry <paramref name="index"/> (0..<see cref="Size"/>-1) as a colour.</summary>public Rgb ColorAt(int index) => Rgb.FromArgb(Argb[index]);/// <summary>- /// Builds a palette from the <see cref="Size"/> entries of <paramref name="scheme"/>.- /// Transformations are applied in the same order as in Python: <paramref name="reverse"/>- /// (new, optional; entry i is read from entry <c>Size-1-i</c>), <paramref name="invert"/>- /// (each channel becomes <c>1 - channel</c>), <paramref name="makeSymmetric"/> (entry i is- /// read from entry <c>2 * min(i, Size-1-i)</c>, so the palette runs from entry 0 at both- /// ends up to entry 254 in the middle), then <paramref name="blackLevel"/> maps every- /// channel linearly as <c>c * (1 - b) + b</c>, so 0 becomes <paramref name="blackLevel"/>- /// and 1 stays 1. Values are limited to 0..1 and converted to 8 bit by truncation, like- /// the Python code. Alpha is always 255.+ /// The grey levels the Python code shows without a colour table: palette entry i is the level i, 0..254, and a+ /// 16-bit sample the same ramp at its own position. Used when a layer's scheme cannot be found.+ /// </summary>+ public static ColorLut Grey { get; } = new([new ColorStop(0.0, new Rgb(0, 0, 0)), new ColorStop(1.0, new Rgb(254, 254, 254))], false, 0.0, false, false);++ /// <summary>+ /// The colours of <paramref name="scheme"/>'s gradient with the display options, applied in the Python order:+ /// <paramref name="reverse"/> (new, optional; the gradient read from the far end), <paramref name="invert"/>+ /// (each channel becomes <c>1 - channel</c>), <paramref name="makeSymmetric"/> (the gradient squeezed into each half+ /// and mirrored, palette entry i read from entry <c>2 * min(i, Size-1-i)</c>), then <paramref name="blackLevel"/>,+ /// which maps every channel linearly as <c>c * (1 - b) + b</c>, so 0 becomes <paramref name="blackLevel"/> and 1+ /// stays 1. The palette's channels are converted to 8 bit by truncation, like the Python code; alpha is always 255.+ /// UI thread (the scheme's stops are copied)./// </summary>- /// <param name="scheme">Source colours; must have at least <see cref="Size"/> entries.</param>+ /// <param name="scheme">The gradient.</param>/// <param name="invert">Replaces every colour by its complement (1 - colour), like the Python option.</param>/// <param name="blackLevel">Lifts (positive) or lowers (negative) the darkest level; 0 = unchanged.</param>/// <param name="makeSymmetric">Squeezes the whole scheme into each half and mirrors it around the centre.</param>/// <param name="reverse">Reverses the order of the scheme (like matplotlib's <c>_r</c> maps).</param>- public static ColorLut Build(ColorScheme scheme, bool invert = false, double blackLevel = 0.0, bool makeSymmetric = false, bool reverse = false)+ public static ColorLut Build(ColorScheme scheme, bool invert = false, double blackLevel = 0.0, bool makeSymmetric = false, bool reverse = false) =>+ new(scheme.SortedStops(), invert, blackLevel, makeSymmetric, reverse);++ /// <summary>The 8-bit palette: the author's table of the gradient (<see cref="ColorScheme.Interpolate"/>, 255 entries at i / 254) through the display options.</summary>+ private int[] BuildPalette(){+ Rgb[] table = ColorScheme.Interpolate(_stops, Size);double[,] rgb = new double[Size, 3];for (int i = 0; i < Size; i++){- Rgb entry = scheme.GetEntry(reverse ? (Size - 1 - i) : i);+ Rgb entry = table[_reverse ? (Size - 1 - i) : i];rgb[i, 0] = entry.R / 255.0;rgb[i, 1] = entry.G / 255.0;rgb[i, 2] = entry.B / 255.0;}- if (invert)+ if (_invert){for (int i = 0; i < Size; i++){@@ -85,23 +123,94 @@ public sealed class ColorLut{// Python: entries 0..127 = src[0::2] and entries 127..254 = the same list mirrored,// which is entry i = src[2 * min(i, 254 - i)]- int sourceIndex = makeSymmetric ? 2 * Math.Min(i, Size - 1 - i) : i;+ int sourceIndex = _makeSymmetric ? 2 * Math.Min(i, Size - 1 - i) : i;int[] components = new int[3];for (int channel = 0; channel < 3; channel++){- double level = Math.Clamp(rgb[sourceIndex, channel] * (1.0 - blackLevel) + blackLevel, 0.0, 1.0);+ double level = Math.Clamp(rgb[sourceIndex, channel] * (1.0 - _blackLevel) + _blackLevel, 0.0, 1.0);components[channel] = Math.Min(255, (int)(level * 255.0));}argb[i] = new Rgb((byte)components[0], (byte)components[1], (byte)components[2]).ToArgb();}- return new ColorLut(argb);+ return argb;+ }++ /// <summary>+ /// The colour of every value a 16-bit sample can hold, indexed by the half's bits (<see cref="BitConverter.HalfToUInt16Bits"/>):+ /// the value's position on the gradient by the layer's mapping at <paramref name="brightness"/>, the continuous forms+ /// of the palette indices (the field <c>(clamp(value · brightness, −1, 1) + 1) / 2</c>, a zero field and NaN in the+ /// middle; the intensity <c>min(√value · brightness, 1)</c>, 0 for NaN and for values not above zero), the gradient+ /// evaluated there through the display options, each channel rounded to the nearest level. Kept per layer until a+ /// call with another brightness; built on the calling thread (65,536 evaluations, spread over the pool). Any thread:+ /// two threads asking at once may both build it, to the same colours. The array must not be modified.+ /// </summary>+ /// <param name="layer">Which mapping: the signed field or the non-negative intensity.</param>+ /// <param name="brightness">The layer's gain, applied as in <see cref="FieldIndex"/> and <see cref="IntensityIndex(float, float)"/>.</param>+ public int[] HalfTable(FrameLayer layer, float brightness)+ {+ ref HalfTableEntry? slot = ref layer == FrameLayer.Field ? ref _fieldTable : ref _intensityTable;+ HalfTableEntry? cached = Volatile.Read(ref slot);+ if (cached != null && cached.Brightness.Equals(brightness))+ {+ return cached.Argb;+ }+ var table = new int[HalfValues];+ const int Blocks = 16;+ Parallel.For(0, Blocks, block =>+ {+ for (int bits = block * (HalfValues / Blocks); bits < (block + 1) * (HalfValues / Blocks); bits++)+ {+ double value = (double)BitConverter.UInt16BitsToHalf((ushort)bits);+ table[bits] = ColorOf(layer == FrameLayer.Field ? FieldPosition(value, brightness) : IntensityPosition(value, brightness));+ }+ });+ Volatile.Write(ref slot, new HalfTableEntry(brightness, table));+ return table;+ }++ /// <summary>A field sample's position on the gradient: <c>(clamp(value · brightness, −1, 1) + 1) / 2</c>, NaN in the middle.</summary>+ private static double FieldPosition(double value, float brightness)+ {+ double scaled = value * brightness;+ return double.IsNaN(scaled) ? 0.5 : (Math.Clamp(scaled, -1.0, 1.0) + 1.0) / 2.0;+ }++ /// <summary>An intensity sample's position on the gradient: <c>min(√value · brightness, 1)</c>, 0 for NaN and for values not above zero.</summary>+ private static double IntensityPosition(double value, float brightness) =>+ value > 0.0 ? Math.Clamp(Math.Sqrt(value) * brightness, 0.0, 1.0) : 0.0;++ /// <summary>The gradient at a position through the display options (the order of <see cref="Build"/>), as an opaque ARGB int.</summary>+ private int ColorOf(double position)+ {+ if (_makeSymmetric)+ {+ position = 2.0 * Math.Min(position, 1.0 - position);+ }+ if (_reverse)+ {+ position = 1.0 - position;+ }+ (double r, double g, double b) = ColorScheme.Evaluate(_stops, position);+ return unchecked((int)0xFF000000) | (Level(r) << 16) | (Level(g) << 8) | Level(b);+ }++ /// <summary>One channel (0..255, unrounded) through invert and black level, rounded to the nearest level (half away from zero).</summary>+ private int Level(double channel)+ {+ double level = channel / 255.0;+ if (_invert)+ {+ level = 1.0 - level;+ }+ level = Math.Clamp(level * (1.0 - _blackLevel) + _blackLevel, 0.0, 1.0);+ return (int)Math.Round(level * 255.0, MidpointRounding.AwayFromZero);}/// <summary>/// Maps a signed field sample to a palette index, like <c>render_field</c>:/// <c>clip(value * brightness, -1, 1) * 127 + 127</c>, so the result is 0..254 and a zero- /// field gives index 127 (the centre colour). NaN gives 127. Called per pixel from- /// <see cref="FrameRenderer.RenderField"/> on worker threads.+ /// field gives index 127 (the centre colour). NaN gives 127. The index an 8-bit frame stores: computed by the+ /// CPU's capture (<see cref="Engine.FrameShape"/>) and mirrored by the GPU's <c>capture_index</c> kernel./// </summary>/// <param name="value">Raw field amplitude from the engine.</param>/// <param name="brightness">Gain applied before clamping.</param>@@ -116,9 +225,8 @@ public sealed class ColorLut}/// <summary>- /// The square-root case of <see cref="IntensityIndex(float, float, float)"/>, the arithmetic- /// <see cref="FrameRenderer.RenderIntensity"/> uses per pixel: <c>min(sqrt(intensity) · brightness, 1) · 254</c>,- /// 0 for NaN or a non-positive intensity. Also the mapping baked into a <see cref="Engine.FrameFormat.Index"/> frame.+ /// The square-root case of <see cref="IntensityIndex(float, float, float)"/>, the index an 8-bit intensity frame+ /// stores: <c>min(sqrt(intensity) · brightness, 1) · 254</c>, 0 for NaN or a non-positive intensity./// </summary>/// <param name="intensity">Accumulated intensity from the engine.</param>/// <param name="brightness">Gain applied after the square root.</param>@@ -128,15 +236,15 @@ public sealed class ColorLut{return 0;}- // single precision throughout (2026-10-16): what the GPU's capture_index kernel computes and what the- // vectorised renderer reproduces bit for bit; the double arithmetic before differed in the last bit at most+ // single precision throughout (2026-10-16): what the GPU's capture_index kernel computes bit for bit; the+ // double arithmetic before differed in the last bit at mostreturn (int)(MathF.Min(MathF.Sqrt(intensity) * brightness, 1f) * 254f);}/// <summary>/// Maps a non-negative intensity to a palette index 0..254, like <c>render_intensity</c>:/// <c>clip(intensity ^ exponent * brightness, 0, 1) * 254</c>. NaN or non-positive- /// intensity gives 0. <see cref="FrameRenderer.RenderIntensity"/> inlines the square-root case.+ /// intensity gives 0. The captures use the square-root case, <see cref="IntensityIndex(float, float)"/>./// </summary>/// <param name="intensity">Accumulated intensity from the engine.</param>/// <param name="brightness">Gain applied after compression.</param>@@ -154,7 +262,4 @@ public sealed class ColorLut}return (int)(Math.Min(scaled, 1.0) * 254.0);}-- /// <summary>Number of entries in a palette: <see cref="ColorScheme.EntryCount"/> (255).</summary>- public const int Size = ColorScheme.EntryCount;}diff --git a/WaveDudeNext/Rendering/ColorScheme.cs b/WaveDudeNext/Rendering/ColorScheme.csindex fbd440a..07a6a52 100644--- a/WaveDudeNext/Rendering/ColorScheme.cs+++ b/WaveDudeNext/Rendering/ColorScheme.cs@@ -93,34 +93,31 @@ public sealed class ColorStop : ObservableObject}/// <summary>-/// A colour scheme: colour stops at positions 0..1 along the value range, from which the-/// <see cref="EntryCount"/>-entry lookup table is interpolated (<see cref="Interpolate"/>; before the-/// first stop and after the last the end colours hold). This is the consolidated form (2026-10-13):-/// the author's files carried a 255-entry table plus, for the ones made in his editor, 9 evenly spaced-/// stops; every shipped table equals the interpolation of its stops, so those schemes keep the 9 stops-/// and the sampled colormaps keep 255 stops at i/254. Stops may sit anywhere (2026-10-13, the user's-/// call: positions are fractions of the gradient). Serialises to XML as attributes plus one <c>Stop</c> element per-/// stop, both standalone (<c>.wdscheme</c>) and inside a project file. Observable: a stop's edit raises-/// <c>Stops</c> on the scheme. UI thread for edits; the derived table is read by anyone building a LUT.+/// A colour scheme: colour stops at positions 0..1 along the value range, the gradient as specified: linear+/// between neighbouring stops, the end colours before the first stop and after the last (<see cref="Evaluate"/>).+/// The model holds no table (2026-10-23, the user's call): how many colours are taken from the gradient is the+/// renderer's business (<see cref="ColorLut"/>: 255 for a frame of 8-bit palette indices, one for every value a+/// 16-bit sample can hold). This is the consolidated form (2026-10-13): the author's files carried a 255-entry+/// table plus, for the ones made in his editor, 9 evenly spaced stops; every shipped table equals the interpolation+/// of its stops, so those schemes keep the 9 stops and the sampled colormaps keep 255 stops at i/254. Stops may sit+/// anywhere (2026-10-13, the user's call: positions are fractions of the gradient). Serialises to XML as attributes+/// plus one <c>Stop</c> element per stop, both standalone (<c>.wdscheme</c>) and inside a project file. Observable:+/// a stop's edit raises <c>Stops</c> on the scheme. UI thread; a renderer works on a copy (<see cref="SortedStops"/>)./// </summary>[XmlRoot("ColorScheme")]public sealed class ColorScheme : ObservableObject{- /// <summary>Size of the interpolated lookup table (the renderer's index range, 0..254).</summary>- public const int EntryCount = 255;-/// <summary>Number of stops of the author's editable gradient: nine, evenly spaced.</summary>public const int StopCount = 9;private string _name = "";private string _description = "";private ColorSchemeKind _kind;- private Rgb[]? _table;private bool _replacing;/// <summary>/// An empty, nameless scheme: the serializer's starting point (it appends the file's stops to the- /// list, so the list must start empty) and the base of <see cref="Clone"/>. Without stops the table+ /// list, so the list must start empty) and the base of <see cref="Clone"/>. Without stops the gradient/// is the grey ramp; <see cref="Normalize"/> makes that explicit./// </summary>public ColorScheme()@@ -180,7 +177,7 @@ public sealed class ColorScheme : ObservableObject/// <summary>/// The stops, each a colour at a position 0..1; kept in position order by <see cref="Normalize"/>- /// (the table sorts a copy, so an editor may leave them unsorted while typing). Edit a stop, or add and+ /// (a renderer sorts a copy, so an editor may leave them unsorted while typing). Edit a stop, or add and/// remove through <see cref="AddStop"/> / <see cref="RemoveStop"/>; replace all with <see cref="SetStops"/>/// or <see cref="SetColors"/>. Every change raises <see cref="INotifyPropertyChanged.PropertyChanged"/> for <c>Stops</c>./// </summary>@@ -217,31 +214,12 @@ public sealed class ColorScheme : ObservableObject[Browsable(false)]public IEnumerable<Rgb> Colors => Stops.Select(s => s.Color);- /// <summary>The interpolated table, index 0..<see cref="EntryCount"/>-1 (a copy).</summary>- [XmlIgnore]- [Browsable(false)]- public Rgb[] Entries => (Rgb[])Table.Clone();-- /// <summary>One entry of the interpolated table, index 0..<see cref="EntryCount"/>-1.</summary>- public Rgb GetEntry(int index) => Table[index];-- /// <summary>Interpolates the table at a fractional index (clamped to the ends).</summary>- public Rgb SampleAt(double position)- {- Rgb[] table = Table;- if (position <= 0.0)- {- return table[0];- }- if (position >= EntryCount - 1)- {- return table[EntryCount - 1];- }- int index = (int)Math.Floor(position);- return Lerp(table[index], table[index + 1], position - index);- }+ /// <summary>The stops in position order as copies, which a renderer may keep and read on any thread; the grey ramp's when there are none.</summary>+ public List<ColorStop> SortedStops() =>+ Stops.Count > 0 ? [.. Stops.OrderBy(s => s.Position).Select(s => new ColorStop(s.Position, s.Color))] : Spread(Grey());- private Rgb[] Table => _table ??= Stops.Count > 0 ? Interpolate(Stops, EntryCount) : Resample(Grey(), EntryCount);+ /// <summary>The gradient's colour at <paramref name="position"/> (0..1), each channel rounded to the nearest level (half away from zero).</summary>+ public Rgb ColorAt(double position) => Round(Evaluate(SortedStops(), position));/// <summary>Replaces every stop with these colours spread evenly over 0..1 (one change notification); at least one.</summary>/// <exception cref="ArgumentException">No colours.</exception>@@ -252,9 +230,13 @@ public sealed class ColorScheme : ObservableObject{throw new ArgumentException("A color scheme needs at least one color.");}- SetStops(list.Select((color, k) => new ColorStop(list.Count == 1 ? 0.0 : k / (double)(list.Count - 1), color)));+ SetStops(Spread(list));}+ /// <summary>Stops for these colours at k / (n−1), the author's layout; a single colour sits at 0.</summary>+ private static List<ColorStop> Spread(IReadOnlyList<Rgb> colors) =>+ [.. colors.Select((color, k) => new ColorStop(colors.Count == 1 ? 0.0 : k / (double)(colors.Count - 1), color))];+/// <summary>Replaces every stop (copies are taken; one change notification); at least one.</summary>/// <exception cref="ArgumentException">No stops.</exception>public void SetStops(IEnumerable<ColorStop> stops)@@ -304,7 +286,7 @@ public sealed class ColorScheme : ObservableObject{at = 0.0;}- var stop = new ColorStop(at, SampleAt(at * (EntryCount - 1)));+ var stop = new ColorStop(at, ColorAt(at));int index = Stops.Count(s => s.Position <= at);Stops.Insert(index, stop);return stop;@@ -418,7 +400,7 @@ public sealed class ColorScheme : ObservableObject};}- /// <summary>Nine colours from black to white, the default of a new scheme and the table of one without stops.</summary>+ /// <summary>Nine colours from black to white, the default of a new scheme and the gradient of one without stops.</summary>public static Rgb[] Grey(){var stops = new Rgb[StopCount];@@ -431,74 +413,74 @@ public sealed class ColorScheme : ObservableObject}/// <summary>- /// The table of <paramref name="count"/> entries for these stops: entry i sits at t = i / (count−1);- /// before the first stop and after the last the end colours hold, between two stops the colour is- /// interpolated linearly (channels round half away from zero, as the author's Python did). Stops at- /// k / (n−1) reproduce <see cref="Resample"/> exactly, and 255 stops at i / 254 are the table itself.+ /// The gradient at <paramref name="position"/>: between two stops the colour is interpolated linearly, before the+ /// first stop and after the last the end colours hold, at a stop's own position the first stop there (two stops at+ /// one position make a hard edge). Channels on the 0..255 scale, unrounded: how finely the gradient is sampled and+ /// how it is rounded are the renderer's business. Any thread, while <paramref name="sorted"/> is left alone./// </summary>- /// <exception cref="ArgumentException">No stops.</exception>- public static Rgb[] Interpolate(IReadOnlyList<ColorStop> stops, int count)+ /// <param name="sorted">At least one stop, in position order (<see cref="SortedStops"/>).</param>+ /// <param name="position">Where along the gradient, 0..1; NaN gives the first stop's colour.</param>+ public static (double R, double G, double B) Evaluate(IReadOnlyList<ColorStop> sorted, double position){- if (stops.Count == 0)+ if (!(position > sorted[0].Position)){- throw new ArgumentException("A color scheme needs at least one stop.");+ return Channels(sorted[0].Color);}- List<ColorStop> sorted = [.. stops.OrderBy(s => s.Position)];- var result = new Rgb[count];- int k = 0;- for (int i = 0; i < count; i++)+ if (position >= sorted[^1].Position){- double t = i / (double)(count - 1);- if (t <= sorted[0].Position)- {- result[i] = sorted[0].Color;- continue;- }- if (t >= sorted[^1].Position)+ return Channels(sorted[^1].Color);+ }+ // the first stop at or beyond the position, by bisection: a sampled colormap may keep 255 stops+ int low = 1;+ int high = sorted.Count - 1;+ while (low < high)+ {+ int middle = (low + high) / 2;+ if (sorted[middle].Position < position){- result[i] = sorted[^1].Color;- continue;+ low = middle + 1;}- while (sorted[k + 1].Position < t)+ else{- k++;+ high = middle;}- ColorStop a = sorted[k];- ColorStop b = sorted[k + 1];- result[i] = t >= b.Position || b.Position <= a.Position- ? b.Color- : Lerp(a.Color, b.Color, (t - a.Position) / (b.Position - a.Position));}- return result;+ Rgb a = sorted[low - 1].Color;+ Rgb b = sorted[low].Color;+ double t = (position - sorted[low - 1].Position) / (sorted[low].Position - sorted[low - 1].Position);+ return (a.R + (b.R - a.R) * t, a.G + (b.G - a.G) * t, a.B + (b.B - a.B) * t);}/// <summary>- /// Spreads <paramref name="source"/> evenly over <paramref name="count"/> entries with linear- /// interpolation (an identical count copies): the author's Python resampling, kept for the JSON- /// writer and the consolidation test. Entry i sits at position i × (n−1) / (count−1) on the source.+ /// The gradient of these stops sampled at <paramref name="count"/> evenly spaced positions, entry i at+ /// i / (count−1) (<see cref="Evaluate"/>), each channel rounded half away from zero, as the author's Python did:+ /// a gradient brush's samples, the 8-bit palette, the author's JSON table./// </summary>- /// <exception cref="ArgumentException">Fewer than two source colours.</exception>- public static Rgb[] Resample(IReadOnlyList<Rgb> source, int count)+ /// <exception cref="ArgumentException">No stops.</exception>+ public static Rgb[] Interpolate(IReadOnlyList<ColorStop> stops, int count){- if (source.Count < 2)+ if (stops.Count == 0){- throw new ArgumentException("A color scheme needs at least 2 colors.");+ throw new ArgumentException("A color scheme needs at least one stop.");}+ List<ColorStop> sorted = [.. stops.OrderBy(s => s.Position)];var result = new Rgb[count];for (int i = 0; i < count; i++){- double position = (double)(i * (source.Count - 1)) / (count - 1);- int index = (int)Math.Floor(position);- result[i] = index >= source.Count - 1 ? source[^1] : Lerp(source[index], source[index + 1], position - index);+ result[i] = Round(Evaluate(sorted, i / (double)(count - 1)));}return result;}- /// <summary>Whether a table equals the interpolation of these evenly spaced colours exactly (the consolidation test of the store).</summary>- public static bool IsInterpolationOf(IReadOnlyList<Rgb> table, IReadOnlyList<Rgb> stops) =>- table.Count == EntryCount && Resample(stops, EntryCount).SequenceEqual(table);+ private static (double R, double G, double B) Channels(Rgb color) => (color.R, color.G, color.B);++ private static Rgb Round((double R, double G, double B) color) =>+ Rgb.Clamped(RoundChannel(color.R), RoundChannel(color.G), RoundChannel(color.B));++ private static int RoundChannel(double level) => (int)Math.Round(level, MidpointRounding.AwayFromZero);- private static Rgb Lerp(Rgb a, Rgb b, double t) =>+ /// <summary>The straight line between two colours at <paramref name="t"/> (0..1), each channel rounded half away from zero.</summary>+ internal static Rgb Lerp(Rgb a, Rgb b, double t) =>Rgb.Clamped(LerpChannel(a.R, b.R, t), LerpChannel(a.G, b.G, t), LerpChannel(a.B, b.B, t));private static int LerpChannel(int a, int b, double t) => (int)Math.Round(a + (b - a) * t, MidpointRounding.AwayFromZero);@@ -537,7 +519,6 @@ public sealed class ColorScheme : ObservableObjectprivate void Invalidate(){- _table = null;OnPropertyChanged(nameof(Stops));OnPropertyChanged(nameof(IsStopScheme));}diff --git a/WaveDudeNext/Rendering/ColorSchemeStore.cs b/WaveDudeNext/Rendering/ColorSchemeStore.csindex 76ef284..94bac0a 100644--- a/WaveDudeNext/Rendering/ColorSchemeStore.cs+++ b/WaveDudeNext/Rendering/ColorSchemeStore.cs@@ -51,6 +51,9 @@ public static class ColorSchemeStore/// <summary>Prefix of the embedded scheme resources (see the csproj's <c>LogicalName</c>).</summary>private const string ResourcePrefix = "ColorSchemes/";+ /// <summary>Entries of the author's JSON table ("entry_count"): his palette of 255 colours, the part his program reads.</summary>+ private const int AuthorEntryCount = 255;+private static readonly XmlSerializer Serializer = new(typeof(ColorScheme));private static readonly XmlSerializerNamespaces NoNamespaces = new([XmlQualifiedName.Empty]);private static readonly XmlWriterSettings WriterSettings = new()@@ -141,7 +144,7 @@ public static class ColorSchemeStorestops = null;}IReadOnlyList<Rgb> kept;- if (stops != null && (colors == null || colors.Count < 2 || ColorScheme.IsInterpolationOf(colors, stops)))+ if (stops != null && (colors == null || colors.Count < 2 || IsInterpolationOf(colors, stops))){kept = stops;}@@ -159,6 +162,30 @@ public static class ColorSchemeStorereturn scheme;}+ /// <summary>+ /// Whether a table equals the author's Python resampling of these evenly spaced colours exactly (the consolidation+ /// test of <see cref="Parse"/>): entry i at position i × (n−1) / (count−1) on the colours, interpolated linearly,+ /// each channel rounded half away from zero.+ /// </summary>+ private static bool IsInterpolationOf(IReadOnlyList<Rgb> table, IReadOnlyList<Rgb> stops)+ {+ if (table.Count != AuthorEntryCount || stops.Count < 2)+ {+ return false;+ }+ for (int i = 0; i < AuthorEntryCount; i++)+ {+ double position = (double)(i * (stops.Count - 1)) / (AuthorEntryCount - 1);+ int index = (int)Math.Floor(position);+ Rgb expected = index >= stops.Count - 1 ? stops[^1] : ColorScheme.Lerp(stops[index], stops[index + 1], position - index);+ if (expected != table[i])+ {+ return false;+ }+ }+ return true;+ }+/// <summary>Reads a standalone XML scheme file; <see cref="ColorScheme.FilePath"/> is set.</summary>/// <exception cref="InvalidOperationException">The file is not an XML colour scheme.</exception>/// <exception cref="FormatException">A colour is not <c>#RRGGBB</c>.</exception>@@ -274,12 +301,12 @@ public static class ColorSchemeStorejson.AppendLine(" \"scheme_type\": " + Quote(scheme.Kind.ToString().ToLowerInvariant()) + ",");}json.AppendLine(" \"bits_per_channel\": 8,");- json.AppendLine(" \"entry_count\": " + ColorScheme.EntryCount.ToString(CultureInfo.InvariantCulture) + ",");+ json.AppendLine(" \"entry_count\": " + AuthorEntryCount.ToString(CultureInfo.InvariantCulture) + ",");if (scheme.IsStopScheme && scheme.IsEvenlySpaced){json.AppendLine(" \"stops\": [" + string.Join(", ", scheme.Colors.Select(Triplet)) + "],");}- Rgb[] entries = scheme.Entries;+ Rgb[] entries = ColorScheme.Interpolate(scheme.SortedStops(), AuthorEntryCount);json.AppendLine(" \"colors\": [");for (int rowStart = 0; rowStart < entries.Length; rowStart += 8){diff --git a/WaveDudeNext/Rendering/FrameRenderer.cs b/WaveDudeNext/Rendering/FrameRenderer.csindex 886dd9f..6ce4f64 100644--- a/WaveDudeNext/Rendering/FrameRenderer.cs+++ b/WaveDudeNext/Rendering/FrameRenderer.cs@@ -16,20 +16,18 @@// <https://www.gnu.org/licenses/>.using System.Collections.Concurrent;-using System.Numerics.Tensors;-using System.Runtime.Intrinsics;+using System.Runtime.InteropServices;+using WaveDudeNext.Runs;namespace WaveDudeNext.Rendering;/// <summary>/// Static helpers that turn a stored frame (the field or the intensity of one simulation step, width × height-/// values without padding) into packed BGRA32 pixels, like <c>WaveVisualizer.render_field</c> and-/// <c>render_intensity</c> in the Python code: the value is converted to a table index (see-/// <see cref="ColorLut"/>) and the index to a colour. Without a colour table (null) the index itself is used-/// as grey level. Row loops run in parallel (each worker converts its row to floats with the vectorised-/// <see cref="TensorPrimitives.ConvertToSingle"/> first and colours four pixels at a time on 128-bit registers),-/// so the methods are CPU-bound but not thread-affine;-/// the caller owns the buffers and must not touch them while a call is in progress.+/// values without padding) into packed BGRA32 pixels through a <see cref="ColorLut"/>: a frame of 16-bit samples+/// through the colour of every half value (<see cref="ColorLut.HalfTable"/>, the gradient at the sample's own+/// position), a frame of 8-bit palette indices through the 255-colour palette. Either is one table lookup per pixel,+/// rows in parallel blocks, so the methods are CPU-bound but not thread-affine; the caller owns the buffers and must+/// not touch them while a call is in progress./// </summary>public static class FrameRenderer{@@ -40,152 +38,54 @@ public static class FrameRenderer/// </summary>private static OrderablePartitioner<Tuple<int, int>> Blocks(int height) =>Partitioner.Create(0, height, 32);- /// <summary>- /// Renders the wave field: every value is mapped by <see cref="ColorLut.FieldIndex"/>- /// (<c>clip(value · brightness, -1, 1) · 127 + 127</c>) and coloured.- /// </summary>- /// <param name="values">Field values, row-major, <paramref name="width"/> × <paramref name="height"/>.</param>- /// <param name="width">Frame width in pixels.</param>- /// <param name="height">Frame height in pixels.</param>- /// <param name="lut">ARGB palette indexed 0..254 (127 = zero field), or null for greyscale.</param>- /// <param name="brightness">Gain applied before the value is clamped to -1..1.</param>- /// <param name="pixels">Destination, at least <paramref name="width"/> × <paramref name="height"/> packed BGRA32 pixels, row-major.</param>- public static void RenderField(ReadOnlyMemory<Half> values, int width, int height, int[]? lut, float brightness, Memory<int> pixels)- {- Parallel.ForEach(Blocks(height), () => new float[width], (block, _, row) =>- {- for (int y = block.Item1; y < block.Item2; y++)- {- TensorPrimitives.ConvertToSingle(values.Span.Slice(y * width, width), row);- FieldRow(row, lut, brightness, pixels.Span.Slice(y * width, width));- }- return row;- }, _ => { });- }/// <summary>- /// Renders the accumulated intensity: each value is mapped as <c>sqrt(value) · brightness</c> (exponent 0.5,- /// as in the Python code), clamped to 1, then scaled to palette index 0..254 (non-positive values map to 0).+ /// Renders a plane of 16-bit samples: every sample's bits index the layer's half table at+ /// <paramref name="brightness"/>, built first when the brightness is new to <paramref name="lut"/>./// </summary>- /// <param name="values">Intensity values, row-major, <paramref name="width"/> × <paramref name="height"/>.</param>+ /// <param name="values">Samples, row-major, <paramref name="width"/> × <paramref name="height"/>.</param>/// <param name="width">Frame width in pixels.</param>/// <param name="height">Frame height in pixels.</param>- /// <param name="lut">ARGB palette indexed 0..254, or null for greyscale.</param>- /// <param name="brightness">Gain applied after the square-root compression.</param>+ /// <param name="lut">The colours (<see cref="ColorLut.Grey"/> for grey levels).</param>+ /// <param name="layer">Which plane the samples are: the field is signed around the gradient's middle, the intensity runs from its start.</param>+ /// <param name="brightness">The layer's gain.</param>/// <param name="pixels">Destination, at least <paramref name="width"/> × <paramref name="height"/> packed BGRA32 pixels, row-major.</param>- public static void RenderIntensity(ReadOnlyMemory<Half> values, int width, int height, int[]? lut, float brightness, Memory<int> pixels)- {- Parallel.ForEach(Blocks(height), () => new float[width], (block, _, row) =>- {- for (int y = block.Item1; y < block.Item2; y++)- {- TensorPrimitives.ConvertToSingle(values.Span.Slice(y * width, width), row);- IntensityRow(row, lut, brightness, pixels.Span.Slice(y * width, width));- }- return row;- }, _ => { });- }-- /// <summary>- /// One row of the field, four pixels at a time on 128-bit registers (2026-10-16, the width every x64 and ARM64- /// machine accelerates): the same operations in the same order as <see cref="ColorLut.FieldIndex"/>, so the- /// indices are identical bit for bit (the library harness checks it over awkward values); NaN lanes take 127- /// through a mask, so the min/max semantics for NaN never matter. The tail and a machine without acceleration- /// go through the scalar helper.- /// </summary>- internal static void FieldRow(ReadOnlySpan<float> row, int[]? lut, float brightness, Span<int> target)+ public static void Render(ReadOnlyMemory<Half> values, int width, int height, ColorLut lut, FrameLayer layer, float brightness, Memory<int> pixels){- int x = 0;- if (Vector128.IsHardwareAccelerated)+ int[] table = lut.HalfTable(layer, brightness);+ Parallel.ForEach(Blocks(height), block =>{- Vector128<float> gain = Vector128.Create(brightness);- Vector128<float> one = Vector128.Create(1f);- Vector128<float> minusOne = Vector128.Create(-1f);- Vector128<float> scale = Vector128.Create(127f);- Vector128<int> nanIndex = Vector128.Create(127);- for (; x <= row.Length - 4; x += 4)+ int start = block.Item1 * width;+ int count = (block.Item2 - block.Item1) * width;+ ReadOnlySpan<ushort> bits = MemoryMarshal.Cast<Half, ushort>(values.Span.Slice(start, count));+ Span<int> target = pixels.Span.Slice(start, count);+ for (int i = 0; i < bits.Length; i++){- Vector128<float> scaled = Vector128.Create(row.Slice(x, 4)) * gain;- Vector128<int> isNumber = Vector128.Equals(scaled, scaled).AsInt32();- Vector128<float> clamped = Vector128.Min(Vector128.Max(scaled, minusOne), one);- Vector128<int> index = Vector128.ConvertToInt32(clamped * scale + scale);- Store(Vector128.ConditionalSelect(isNumber, index, nanIndex), lut, target.Slice(x, 4));+ target[i] = table[bits[i]];}- }- for (; x < row.Length; x++)- {- target[x] = Colorize(ColorLut.FieldIndex(row[x], brightness), lut);- }- }-- /// <summary>- /// One row of the intensity, four pixels at a time: the operations of <see cref="ColorLut.IntensityIndex(float, float)"/>- /// in the same single precision; lanes that are not positive (zero, negative, NaN) take 0 through a mask.- /// </summary>- internal static void IntensityRow(ReadOnlySpan<float> row, int[]? lut, float brightness, Span<int> target)- {- int x = 0;- if (Vector128.IsHardwareAccelerated)- {- Vector128<float> gain = Vector128.Create(brightness);- Vector128<float> one = Vector128.Create(1f);- Vector128<float> scale = Vector128.Create(254f);- Vector128<float> zero = Vector128<float>.Zero;- for (; x <= row.Length - 4; x += 4)- {- Vector128<float> value = Vector128.Create(row.Slice(x, 4));- Vector128<int> positive = Vector128.GreaterThan(value, zero).AsInt32();- Vector128<float> scaled = Vector128.Sqrt(value) * gain;- Vector128<int> index = Vector128.ConvertToInt32(Vector128.Min(scaled, one) * scale);- Store(Vector128.ConditionalSelect(positive, index, Vector128<int>.Zero), lut, target.Slice(x, 4));- }- }- for (; x < row.Length; x++)- {- target[x] = Colorize(ColorLut.IntensityIndex(row[x], brightness), lut);- }- }-- /// <summary>Four palette indices to four pixels: a lookup each with a palette, else the grey arithmetic on the register.</summary>- private static void Store(Vector128<int> index, int[]? lut, Span<int> target)- {- if (lut != null)- {- target[0] = lut[index[0]];- target[1] = lut[index[1]];- target[2] = lut[index[2]];- target[3] = lut[index[3]];- }- else- {- (index * Vector128.Create(0x010101) | Vector128.Create(unchecked((int)0xFF000000))).CopyTo(target);- }+ });}/// <summary>/// Renders a plane of palette indices (an <see cref="Engine.FrameFormat.Index"/> frame, the brightness already- /// applied when it was captured): every byte is looked up in the palette, nothing else. The cheapest picture there- /// is, a table lookup per pixel.+ /// applied when it was captured): every byte is looked up in the 8-bit palette, nothing else./// </summary>/// <param name="indices">Palette indices 0..254, row-major, <paramref name="width"/> × <paramref name="height"/>.</param>/// <param name="width">Frame width in pixels.</param>/// <param name="height">Frame height in pixels.</param>- /// <param name="lut">ARGB palette indexed 0..254, or null for greyscale.</param>+ /// <param name="lut">The colours (<see cref="ColorLut.Grey"/> for grey levels).</param>/// <param name="pixels">Destination, at least <paramref name="width"/> × <paramref name="height"/> packed BGRA32 pixels, row-major.</param>- public static void RenderIndexed(ReadOnlyMemory<byte> indices, int width, int height, int[]? lut, Memory<int> pixels)+ public static void RenderIndexed(ReadOnlyMemory<byte> indices, int width, int height, ColorLut lut, Memory<int> pixels){+ int[] palette = lut.Argb;Parallel.For(0, height, y =>{ReadOnlySpan<byte> row = indices.Span.Slice(y * width, width);Span<int> target = pixels.Span.Slice(y * width, width);for (int x = 0; x < width; x++){- target[x] = Colorize(Math.Min((int)row[x], ColorLut.Size - 1), lut);+ target[x] = palette[Math.Min((int)row[x], ColorLut.Size - 1)];}});}-- /// <summary>Looks up a palette index in <paramref name="lut"/>, or builds an opaque grey of that level when there is no LUT.</summary>- public static int Colorize(int index, int[]? lut) =>- lut != null ? lut[index] : unchecked((int)0xFF000000) | (index << 16) | (index << 8) | index;}diff --git a/_tools/library_check/ExportChecks.cs b/_tools/library_check/ExportChecks.csindex 96540eb..2a2f852 100644--- a/_tools/library_check/ExportChecks.cs+++ b/_tools/library_check/ExportChecks.cs@@ -484,14 +484,14 @@ internal static class ExportChecksrun.Start();check(run.Completion.Wait(30000) && store.Count == 10, "job: a 10-frame run to export");- int[] lut = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(scheme => scheme.Name == Display.DefaultFieldColorScheme)).Argb;+ ColorLut lut = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(scheme => scheme.Name == Display.DefaultFieldColorScheme));var decorated = new List<int>();var fieldLayer = new ExportLayer(FrameLayer.Field, lut, 30f, null, 0, (frame, pixels) =>{decorated.Add(frame);pixels.Span[0] = unchecked((int)0xFFFF0000); // a red pixel at the top left, to be found in the file});- var intensityLayer = new ExportLayer(FrameLayer.Intensity, null, 30f, null, 0, null);+ var intensityLayer = new ExportLayer(FrameLayer.Intensity, ColorLut.Grey, 30f, null, 0, null);string seqPath = Path.Combine(folder, "field.png");string aviPath = Path.Combine(folder, "intensity.avi");string exrPath = Path.Combine(folder, "data.exr");@@ -526,7 +526,7 @@ internal static class ExportChecksvar values = new Half[64 * 48];var expected = new int[64 * 48];store.CopyLayer(2, FrameLayer.Field, values);- FrameRenderer.RenderField(values, 64, 48, lut, 30f, expected);+ FrameRenderer.Render(values, 64, 48, lut, FrameLayer.Field, 30f, expected);expected[0] = unchecked((int)0xFFFF0000);int[]? first = DecodePng(File.ReadAllBytes(Path.Combine(folder, "field", "field_0002.png")), 64, 48);check(first != null && first.SequenceEqual(expected), "job: field_0002.png is frame 2 as the renderer colours it, with the decoration");@@ -677,7 +677,7 @@ internal static class ExportChecksrun.Completion.Wait();Console.WriteLine(" run: " + run.EngineDescription + ", " + store.Count + " frames");}- int[] lut = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(scheme => scheme.Name == Display.DefaultFieldColorScheme)).Argb;+ ColorLut lut = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(scheme => scheme.Name == Display.DefaultFieldColorScheme));// the MP4 writer alone on the run's real frames, rendered up front: input format and rate control comparedif (OperatingSystem.IsWindows() && ExportFormats.IsAvailable(ExportFormat.Mp4)){@@ -687,7 +687,7 @@ internal static class ExportChecks{var px = new int[w * h];store.CopyLayer(i, FrameLayer.Field, values);- FrameRenderer.RenderField(values, w, h, lut, 30f, px);+ FrameRenderer.Render(values, w, h, lut, FrameLayer.Field, 30f, px);rendered.Add(px);}// the declared frame rate is varied too: if the time per frame tracks it, the encoder paces itself to real timediff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.csindex feadc72..717d71e 100644--- a/_tools/library_check/Program.cs+++ b/_tools/library_check/Program.cs@@ -601,7 +601,7 @@ internal static class Programfield[i] = (Half)(random.NextDouble() * 2 - 1);intensity[i] = (Half)(random.NextDouble() * 1.5);}- int[] lut = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(s => s.Name == Display.DefaultFieldColorScheme)).Argb;+ ColorLut lut = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(s => s.Name == Display.DefaultFieldColorScheme));var pixels = new int[w * h];// the 8-bit preview format: the index the GPU's capture_index kernel computed, the CPU only looks the colour upvar indices = new byte[w * h];@@ -612,10 +612,10 @@ internal static class Programforeach ((string name, Action render) in new (string, Action)[]{("8-bit index", () => FrameRenderer.RenderIndexed(indices, w, h, lut, pixels)),- ("intensity", () => FrameRenderer.RenderIntensity(intensity, w, h, lut, 1f, pixels)),- ("field", () => FrameRenderer.RenderField(field, w, h, lut, 1f, pixels)),- ("field, grey", () => FrameRenderer.RenderField(field, w, h, null, 1f, pixels)),- ("intensity again", () => FrameRenderer.RenderIntensity(intensity, w, h, lut, 1f, pixels)),+ ("intensity", () => FrameRenderer.Render(intensity, w, h, lut, FrameLayer.Intensity, 1f, pixels)),+ ("field", () => FrameRenderer.Render(field, w, h, lut, FrameLayer.Field, 1f, pixels)),+ ("field, grey", () => FrameRenderer.Render(field, w, h, ColorLut.Grey, FrameLayer.Field, 1f, pixels)),+ ("intensity again", () => FrameRenderer.Render(intensity, w, h, lut, FrameLayer.Intensity, 1f, pixels)),}){for (int i = 0; i < 60; i++)@@ -632,29 +632,22 @@ internal static class Programdouble ms = clock.Elapsed.TotalMilliseconds / Runs;Console.WriteLine($" {name,-12} {ms,6:0.00} ms per layer ({ms * 1e6 / (w * (double)h):0.00} ns per pixel)");}- // one core's view: a single row, scalar helpers against the vector rows, no parallel loop and no memory traffic+ // a half table's build, the cost of a brightness the colours have not seen (a drag on the brightness box, Auto){- var row = new float[w];- var got = new int[w];- var rng2 = new Random(3);- for (int i = 0; i < w; i++) { row[i] = (float)(rng2.NextDouble() * 2 - 1); }- foreach ((string name, Action render) in new (string, Action)[]+ ColorLut fresh = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(s => s.Name == "Inferno"));+ float brightness = 1f;+ for (int i = 0; i < 20; i++){- ("field scalar", () => { for (int x = 0; x < w; x++) { got[x] = FrameRenderer.Colorize(ColorLut.FieldIndex(row[x], 1f), lut); } }),- ("field vector", () => FrameRenderer.FieldRow(row, lut, 1f, got)),- ("intensity scalar", () => { for (int x = 0; x < w; x++) { got[x] = FrameRenderer.Colorize(ColorLut.IntensityIndex(row[x], 1f), lut); } }),- ("intensity vector", () => FrameRenderer.IntensityRow(row, lut, 1f, got)),- ("grey scalar", () => { for (int x = 0; x < w; x++) { got[x] = FrameRenderer.Colorize(ColorLut.FieldIndex(row[x], 1f), null); } }),- ("grey vector", () => FrameRenderer.FieldRow(row, null, 1f, got)),- })+ fresh.HalfTable(FrameLayer.Intensity, brightness += 0.01f);+ }+ Thread.Sleep(300);+ var clock = Stopwatch.StartNew();+ const int Builds = 100;+ for (int i = 0; i < Builds; i++){- for (int i = 0; i < 2000; i++) { render(); }- var clock = Stopwatch.StartNew();- const int Rows = 20000;- for (int i = 0; i < Rows; i++) { render(); }- double ns = clock.Elapsed.TotalMilliseconds * 1e6 / Rows / w;- Console.WriteLine($" one thread, {name,-18} {ns:0.00} ns per pixel");+ fresh.HalfTable(i % 2 == 0 ? FrameLayer.Field : FrameLayer.Intensity, brightness += 0.01f);}+ Console.WriteLine($" half table build {clock.Elapsed.TotalMilliseconds / Builds,6:0.00} ms (65,536 colours from Inferno's {ColorSchemeStore.LoadBuiltIn(null).First(s => s.Name == "Inferno").Stops.Count} stops)");}stop.Cancel();if (run != null)@@ -1525,7 +1518,8 @@ internal static class Program}}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+ // an index frame holds the palette index of the very half a 16-bit frame stores: the 8-bit preview shows the+ // stored samples, at the palette's 255 coloursvar halfField = new byte[full.PlaneBytes];FrameConversion.Convert(field, stride + 1, stride, full, false, halfField);ReadOnlySpan<Half> storedHalves = MemoryMarshal.Cast<byte, Half>(halfField);@@ -1534,7 +1528,7 @@ internal static class Program{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");+ Check(rendersAlike, "index shape: every index is the palette index of the half a 16-bit frame of the same floats stores");// the CPU engine's captures of every shape equal the reference conversion of its own floatsforeach (FrameShape shape in new[] { half, third, index, halfIndex })@@ -1633,18 +1627,16 @@ internal static class Programrefused = true;}Check(refused, "index store: the Half read is refused");- // a picture export takes the index store as it is (2026-10-18): the job colours the indices through the LUT, the- // same pixels the renderer makes of them; a data export (OpenEXR) needs the halves and fails on it- int[] indexLut = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(s => s.Name == Display.DefaultFieldColorScheme)).Argb;+ // every export needs the 16-bit samples (2026-10-23): a picture takes every level of the gradient from them, a+ // data export (OpenEXR) writes them; both fail on a store of palette indices, and the application runs again first+ ColorLut indexLut = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(s => s.Name == Display.DefaultFieldColorScheme));var collected = new CollectingSink(32, 24);var indexJob = new ExportJob(store, 0, 2, [new ExportTarget(new ExportLayer(FrameLayer.Field, indexLut, 1f, null, 0, null), "memory", () => collected)], null);indexJob.Start();- var fromIndices = new int[32 * 24];- FrameRenderer.RenderIndexed(expectedField, 32, 24, indexLut, fromIndices);- Check(indexJob.Completion.Wait(30000) && indexJob.State == ExportState.Completed && collected.Frames.Count == 3 && collected.Frames.All(f => f.SequenceEqual(fromIndices)),- "an export of pictures takes a store of palette indices and colours them as the renderer does");+ Check(indexJob.Completion.Wait(30000) && indexJob.State == ExportState.Failed && indexJob.Error?.Message.Contains("16-bit") == true && collected.Frames.Count == 0,+ "an export of pictures from a store of palette indices fails: it needs the 16-bit samples");string exrOnIndex = Path.Combine(Path.GetTempPath(), "library_check-exr-" + Guid.NewGuid().ToString("N") + ".exr");- var dataJob = new ExportJob(store, 0, 0, [new ExportTarget(new ExportLayer(FrameLayer.Field, null, 1f, null, 0, null), exrOnIndex, () => ExportFormats.OpenStill(ExportFormat.Exr, exrOnIndex, 32, 24, 70))], null);+ var dataJob = new ExportJob(store, 0, 0, [new ExportTarget(new ExportLayer(FrameLayer.Field, ColorLut.Grey, 1f, null, 0, null), exrOnIndex, () => ExportFormats.OpenStill(ExportFormat.Exr, exrOnIndex, 32, 24, 70))], null);dataJob.Start();Check(dataJob.Completion.Wait(30000) && dataJob.State == ExportState.Failed && dataJob.Error?.Message.Contains("16-bit") == true,"a data export (OpenEXR) of a store of palette indices fails: it needs the 16-bit samples");@@ -1745,55 +1737,57 @@ internal static class Programprivate static void CheckRenderer(){Console.WriteLine("--- renderer");+ static int Grey(int level) => unchecked((int)0xFF000000) | (level << 16) | (level << 8) | level;+ // 16-bit samples (2026-10-23): the gradient at the sample's own position, rounded; grey is the Python code's 0..254 rampvar values = new Half[4] { (Half)0f, (Half)0.5f, (Half)(-2f), (Half)1f };var pixels = new int[4];- FrameRenderer.RenderField(values, 2, 2, null, 1f, pixels);- Check(pixels[0] == unchecked((int)0xFF7F7F7F) && pixels[2] == unchecked((int)0xFF000000) && pixels[3] == unchecked((int)0xFFFEFEFE), "field without LUT: grey 127 / 0 / 254");- int[] lut = new int[255];- for (int i = 0; i < 255; i++)- {- lut[i] = i;- }- FrameRenderer.RenderField(values, 2, 2, lut, 1f, pixels);- Check(pixels[1] == ColorLut.FieldIndex(0.5f, 1f) && pixels[1] == 190, "field with LUT uses FieldIndex (0.5 -> 190)");+ FrameRenderer.Render(values, 2, 2, ColorLut.Grey, FrameLayer.Field, 1f, pixels);+ Check(pixels[0] == Grey(127) && pixels[1] == Grey(191) && pixels[2] == Grey(0) && pixels[3] == Grey(254),+ "field, grey: 0 -> 127, 0.5 -> 190.5 rounded to 191 (the palette truncates to 190), the clamp -> 0 and 254");var intensities = new Half[4] { (Half)0f, (Half)(-1f), (Half)0.25f, (Half)9f };- FrameRenderer.RenderIntensity(intensities, 2, 2, lut, 1f, pixels);- // the vectorised rows (2026-10-16) equal the scalar helpers bit for bit: awkward values, every brightness, odd widths, with and without a palette- {- float[] awkward = [0f, -0f, 1f, -1f, 0.5f, -0.5f, 1.0001f, -1.0001f, 127f, 1e-7f, -1e-7f, float.NaN, float.PositiveInfinity, float.NegativeInfinity, 6.1e-5f, 65504f, 0.0078125f, 0.99999f];+ FrameRenderer.Render(intensities, 2, 2, ColorLut.Grey, FrameLayer.Intensity, 1f, pixels);+ Check(pixels[0] == Grey(0) && pixels[1] == Grey(0) && pixels[2] == Grey(127) && pixels[3] == Grey(254), "intensity, grey: <= 0 -> 0, sqrt(0.25) -> 127, the clamp -> 254");+ // every value a half can hold, against the gradient worked out here: a ramp from black to blue 250 gets the nearest+ // level to 250 × position, NaN in the field's middle, and every one of the 251 levels is used+ {+ ColorLut ramp = ColorLut.Build(new ColorScheme("ramp", [new Rgb(0, 0, 0), new Rgb(0, 0, 250)]));+ int[] fieldTable = ramp.HalfTable(FrameLayer.Field, 3.5f);+ int[] intensityTable = ramp.HalfTable(FrameLayer.Intensity, 3.5f);+ bool nearest = true;+ for (int bits = 0; bits < ColorLut.HalfValues && nearest; bits++)+ {+ double value = (double)BitConverter.UInt16BitsToHalf((ushort)bits);+ double fieldAt = double.IsNaN(value) ? 0.5 : (Math.Clamp(value * 3.5, -1.0, 1.0) + 1.0) / 2.0;+ double intensityAt = value > 0.0 ? Math.Min(Math.Sqrt(value) * 3.5, 1.0) : 0.0;+ nearest = (fieldTable[bits] & ~0xFF) == unchecked((int)0xFF000000) && Math.Abs((fieldTable[bits] & 0xFF) - 250 * fieldAt) <= 0.5 + 1e-9+ && (intensityTable[bits] & ~0xFF) == unchecked((int)0xFF000000) && Math.Abs((intensityTable[bits] & 0xFF) - 250 * intensityAt) <= 0.5 + 1e-9;+ }+ Check(nearest && fieldTable.Distinct().Count() == 251 && intensityTable.Distinct().Count() == 251,+ "half tables: each of the 65,536 values gets the level nearest the gradient at its position (field and intensity, NaN, infinities, zeros), every level used");+ // the frame: a lookup per sample over several row blocks and an odd widthvar rng = new Random(11);- bool vectorEqual = true;- foreach (int width in new[] { 1, 3, 4, 5, 37 })- {- var row = new float[width];- var got = new int[width];- foreach (float brightness in new[] { 0f, 0.37f, 1f, 3.5f })- {- for (int trial = 0; trial < 200 && vectorEqual; trial++)- {- for (int x = 0; x < width; x++)- {- row[x] = trial % 3 == 0 ? awkward[rng.Next(awkward.Length)] : (float)(rng.NextDouble() * 4 - 2);- }- foreach (int[]? palette in new[] { lut, null })- {- FrameRenderer.FieldRow(row, palette, brightness, got);- for (int x = 0; x < width; x++)- {- vectorEqual &= got[x] == FrameRenderer.Colorize(ColorLut.FieldIndex(row[x], brightness), palette);- }- FrameRenderer.IntensityRow(row, palette, brightness, got);- for (int x = 0; x < width; x++)- {- vectorEqual &= got[x] == FrameRenderer.Colorize(ColorLut.IntensityIndex(row[x], brightness), palette);- }- }- }- }- }- Check(vectorEqual, "the vectorised field and intensity rows equal the scalar helpers bit for bit (NaN, infinities, zeros, the clamp edges, odd widths, grey and palette)");- }- Check(pixels[0] == 0 && pixels[1] == 0 && pixels[2] == 127 && pixels[3] == 254, "intensity: <= 0 -> 0, sqrt(0.25) -> 127, clamp -> 254");+ var frame = new Half[37 * 70];+ for (int i = 0; i < frame.Length; i++)+ {+ frame[i] = BitConverter.UInt16BitsToHalf((ushort)rng.Next(ColorLut.HalfValues));+ }+ var framePixels = new int[frame.Length];+ FrameRenderer.Render(frame, 37, 70, ramp, FrameLayer.Field, 3.5f, framePixels);+ Check(Enumerable.Range(0, frame.Length).All(i => framePixels[i] == fieldTable[BitConverter.HalfToUInt16Bits(frame[i])]), "Render looks every sample up in the half table (37 × 70, three row blocks)");+ }+ // the case that started it (2026-10-23): Inferno's dark start, blue 3 to 33 over its first 15 palette entries,+ // showed as patches two levels apart; the half table has every level between+ ColorScheme infernoScheme = ColorSchemeStore.LoadBuiltIn(null).First(s => s.Name == "Inferno");+ ColorLut inferno = ColorLut.Build(infernoScheme);+ int paletteBlues = Enumerable.Range(0, 16).Select(i => inferno.ColorAt(i).B).Distinct().Count();+ int[] dark = inferno.HalfTable(FrameLayer.Intensity, 1f);+ int halfBlues = Enumerable.Range(0, ColorLut.HalfValues)+ .Where(bits => (double)BitConverter.UInt16BitsToHalf((ushort)bits) is var v && v > 0.0 && Math.Sqrt(v) <= 15 / 254.0)+ .Select(bits => dark[bits] & 0xFF).Distinct().Count();+ Check(paletteBlues == 16 && halfBlues == 31, $"Inferno's dark start: the palette's first 16 entries have {paletteBlues} levels of blue, the half table every one from 3 to 33 ({halfBlues})");+ Check(ReferenceEquals(inferno.HalfTable(FrameLayer.Intensity, 1f), dark) && !ReferenceEquals(inferno.HalfTable(FrameLayer.Field, 1f), dark) && !ReferenceEquals(inferno.HalfTable(FrameLayer.Intensity, 2f), dark),+ "a half table is kept per layer until another brightness asks");+ // the 8-bit palette, as the author's tablevar stops = new Rgb[ColorScheme.StopCount];for (int i = 0; i < stops.Length; i++){@@ -1801,8 +1795,13 @@ internal static class Program}ColorScheme scheme = ColorScheme.FromStops("test", stops);ColorLut built = ColorLut.Build(scheme);- Check(built.ColorAt(0) == stops[0] && built.ColorAt(254) == stops[^1] && built.ColorAt(127) == stops[4], "LUT from a stop scheme hits the stops at 0, 127 and 254");- Check(ColorLut.Build(scheme, blackLevel: 0.5).ColorAt(0).G == 127, "black level 0.5 lifts a 0 channel to 127");+ Check(built.ColorAt(0) == stops[0] && built.ColorAt(254) == stops[^1] && built.ColorAt(127) == stops[4], "the palette of a stop scheme hits the stops at 0, 127 and 254");+ var indexed = new int[4];+ FrameRenderer.RenderIndexed(new byte[] { 0, 127, 254, 255 }, 2, 2, built, indexed);+ Check(indexed.SequenceEqual([built.Argb[0], built.Argb[127], built.Argb[254], built.Argb[254]]), "RenderIndexed looks each byte up in the palette, 255 as 254");+ ColorLut lifted = ColorLut.Build(scheme, blackLevel: 0.5);+ Check(lifted.ColorAt(0).G == 127 && ((lifted.HalfTable(FrameLayer.Intensity, 1f)[0] >> 8) & 0xFF) == 128,+ "black level 0.5 lifts a 0 channel to 127 in the palette (truncated, as in Python) and to 128 in the half table (rounded)");}private static void CheckColorSchemes()@@ -1837,8 +1836,8 @@ internal static class Programvar ramp = new ColorScheme("ramp", Enumerable.Range(0, 255).Select(i => i <= 127 ? new Rgb((byte)(i * 2), 0, 0) : new Rgb(254, (byte)((i - 127) * 2), 0)));int sampled = ramp.Stops.Count;ramp.Simplify(1.0);- Check(sampled == 255 && ramp.Stops.Count == 3 && Math.Abs(ramp.Stops[1].Position - 127 / 254.0) < 1e-9 && ramp.GetEntry(127) == new Rgb(254, 0, 0) && ramp.GetEntry(254) == new Rgb(254, 254, 0),- "Simplify keeps only the bend of a two-segment ramp and the table still hits it");+ Check(sampled == 255 && ramp.Stops.Count == 3 && Math.Abs(ramp.Stops[1].Position - 127 / 254.0) < 1e-9 && ramp.ColorAt(127 / 254.0) == new Rgb(254, 0, 0) && ramp.ColorAt(1.0) == new Rgb(254, 254, 0),+ "Simplify keeps only the bend of a two-segment ramp and the gradient still hits it");Check(Rgb.Parse("#FF8000") == new Rgb(255, 128, 0) && Rgb.Parse("[10, 20, 30]") == new Rgb(10, 20, 30) && new Rgb(1, 2, 3).ToString() == "#010203", "Rgb parses hex and triplets and prints #RRGGBB");if (field != null){@@ -1860,7 +1859,9 @@ internal static class ProgramCheck(back.Name == field.Name && back.Kind == field.Kind && back.Stops.Select(s => (s.Position, s.Color)).SequenceEqual(field.Stops.Select(s => (s.Position, s.Color))), "XML round trip keeps name, kind and the 9 stops with positions");var uneven = new ColorScheme("uneven", [new Rgb(0, 0, 0)]);uneven.SetStops([new ColorStop(0.0, new Rgb(0, 0, 0)), new ColorStop(0.25, new Rgb(255, 255, 255)), new ColorStop(1.0, new Rgb(0, 0, 255))]);- Check(uneven.GetEntry(0) == new Rgb(0, 0, 0) && uneven.GetEntry(127) == new Rgb(170, 170, 255) && uneven.GetEntry(254) == new Rgb(0, 0, 255) && uneven.GetEntry(32) == new Rgb(129, 129, 129), "stops at any position interpolate between their neighbours (0, 0.25, 1)");+ Check(uneven.ColorAt(0.0) == new Rgb(0, 0, 0) && uneven.ColorAt(127 / 254.0) == new Rgb(170, 170, 255) && uneven.ColorAt(1.0) == new Rgb(0, 0, 255) && uneven.ColorAt(32 / 254.0) == new Rgb(129, 129, 129)+ && ColorScheme.Interpolate(uneven.Stops, 255)[32] == new Rgb(129, 129, 129) && uneven.ColorAt(0.25) == new Rgb(255, 255, 255) && uneven.ColorAt(double.NaN) == new Rgb(0, 0, 0),+ "stops at any position interpolate between their neighbours (0, 0.25, 1), a stop's own position gives its colour, the 255-entry sampling the same");ColorStop added = uneven.AddStop();Check(uneven.Stops.Count == 4 && Math.Abs(added.Position - 0.625) < 1e-9 && uneven.Stops.IndexOf(added) == 2, "AddStop fills the widest gap, in position order");bool hsvRoundTrip = true;@@ -1923,7 +1924,7 @@ internal static class Programint changes = 0;edited.PropertyChanged += (_, args) => changes += args.PropertyName == nameof(ColorScheme.Stops) ? 1 : 0;edited.Stops[4].Color = new Rgb(1, 2, 3);- Check(changes == 1 && edited.GetEntry(127) == new Rgb(1, 2, 3), "editing one stop notifies once and rebuilds the table");+ Check(changes == 1 && edited.ColorAt(0.5) == new Rgb(1, 2, 3), "editing one stop notifies once and the gradient follows");}// the author's glowing edges: a vertical black|white step at x = 2 of a 5 x 5 imagevar image = new byte[5 * 5 * 4];