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 16-bit intensity as its square root, two OpenEXR entries; preview pictures sized by the canvas
Alexander Graefdc27fe064631
diff --git a/CLAUDE.md b/CLAUDE.mdindex 4029bd4..1b084ea 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -132,11 +132,19 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA- **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 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).+ brightness edit is a simulation edit. The index is computed from the value a 16-bit frame stores, rounded to a half+ (the field, the intensity's root), 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.+ **A 16-bit intensity plane holds √I** (2026-10-23, the user's choice: the renderer colours √I, and as I the dark end+ lay among half's subnormals, below 6.1e-5, up to a palette level between neighbours; as √I the floor is at I =+ 3.7e-9, the brightest parts a bit coarser): `FrameShape.IntensityRoot`, from the run's `PreviewQuality`, produced by+ `FrameConversion` and `capture_half`, reported by every `IFrameSource`; the renderer, the screen path (which blends+ it as energy) and the fit go by its `SampleKind`. Only an OpenEXR export of I makes a run that stores I itself+ (squaring √I back would lose a bit). The 8-bit index is the palette index of that same stored half, √I for the+ intensity (2026-10-23, the user's choice: one rule for both previews; rounding I to a half first had merged the+ darkest indices at a high brightness, 2e-8 at 30 coming out 0 instead of 1).## The app's rules@@ -178,7 +186,9 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAsize and scaled by WPF, as before. 16-bit samples are drawn at each picture's size on screen (`ScreenRenderer`, thepane reports the Image's rounded `RenderSize` in device pixels): resampled in value space, never colours (a box meanwhen shrinking, bilinear when enlarging, so every pixel shows a real value in a gradient colour), then the half- table; the bitmap's DPI makes it measure the canvas, so layout and overlays are unchanged and WPF draws it 1:1.+ table. The pictures are `CanvasImage`s, sized by the canvas and never by their bitmap, so a 16-bit bitmap is plain+ screen pixels drawn 1:1 and a new one never moves the layout (2026-10-23: a resolution set to make the bitmap measure+ the canvas came back from WPF in single precision, the reuse test failed on every frame, and the pane flickered).**Preview dithering** (View menu, user setting, off by default until the user has seen it; only with 16-bit samples):the colours at 16 bits per channel (`DeepHalfTable`) to 8 through a Bayer matrix of 2, 4, 8 or 16 cells a side for10, 12, 14 or 16 bits, fixed to the screen's pixels; preview only, never in an export (a video crushes it; an export@@ -205,7 +215,9 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAat quality 100; 4:4:4 at 90 beat it in every channel at half the size), and**OpenEXR sequences or stills** (2026-10-18, the user's choice for data export to NumPy, MATLAB, Octave add-onsand viewers such as DJV): the stored halves themselves, one uncompressed "Y" channel per file, no colours,- brightness, outline or boxes; a sink that `WantsHalves` gets the plane from the job unrendered. **Source markers**+ brightness, outline or boxes; a sink that `WantsHalves` gets the plane from the job unrendered. Two entries in the+ dialog (2026-10-23): the intensity as I (a run storing I is made first; a scripted `.exr`) or as √I (the preview's+ run as it is); the field the same in both. **Source markers**(2026-10-21, Display, off by default, the user's choices): the preview's marker, a composite source's dots and thename, enabled sources only, scaled like the probe labels, under the probe markers and boxes. Harness hooks:`WAVEDUDE_EXPORT_PATH`, `WAVEDUDE_DISCARD_EDITS=1`.diff --git a/WaveDudeNext.WPF/Controls/CanvasImage.cs b/WaveDudeNext.WPF/Controls/CanvasImage.csnew file mode 100644index 0000000..b0f0ff6--- /dev/null+++ b/WaveDudeNext.WPF/Controls/CanvasImage.cs@@ -0,0 +1,78 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 Alexander Graef <[email protected]>+//+// This file is part of WaveDude Next, a 2D wave simulator.+//+// Based on the work of+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>+// 0x23 (Diffraction Limited), author of WaveSimulator2D+// <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>+//+// WaveDude Next is free software: you can redistribute it and/or modify it under+// the terms of the GNU General Public License as published by the Free Software+// Foundation, either version 3 of the License, or (at your option) any later+// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or+// <https://www.gnu.org/licenses/>.++using System.Windows;+using System.Windows.Controls;++namespace WaveDudeNext.WPF.Controls;++/// <summary>+/// A preview picture that takes its size from the canvas, never from its bitmap (2026-10-23): the canvas, in DIPs,+/// fitted uniformly into the room it is given (the canvas size itself without a bound), and the bitmap drawn into that+/// rectangle, whatever its own pixel size. So a new bitmap never changes the layout: a 16-bit picture rendered at the+/// rectangle's size in screen pixels lands on them 1:1, a picture of palette indices at the store's size is scaled, and+/// no loop runs from the layout to the bitmap's size and back (one had been possible while the layout read the bitmap's+/// size in DIPs, which a resolution kept in single precision put a hair off the canvas). UI thread, like every element.+/// </summary>+public sealed class CanvasImage : Image+{+ /// <summary>Identifies the <see cref="CanvasWidth"/> property.</summary>+ public static readonly DependencyProperty CanvasWidthProperty = DependencyProperty.Register(+ nameof(CanvasWidth), typeof(int), typeof(CanvasImage), new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.AffectsMeasure));++ /// <summary>Identifies the <see cref="CanvasHeight"/> property.</summary>+ public static readonly DependencyProperty CanvasHeightProperty = DependencyProperty.Register(+ nameof(CanvasHeight), typeof(int), typeof(CanvasImage), new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.AffectsMeasure));++ /// <summary>Width of the canvas the picture shows, in canvas pixels (one DIP each at its natural size); at least 1.</summary>+ public int CanvasWidth+ {+ get => (int)GetValue(CanvasWidthProperty);+ set => SetValue(CanvasWidthProperty, value);+ }++ /// <summary>Height of the canvas the picture shows, in canvas pixels; at least 1.</summary>+ public int CanvasHeight+ {+ get => (int)GetValue(CanvasHeightProperty);+ set => SetValue(CanvasHeightProperty, value);+ }++ /// <summary>Width over height of the canvas, the picture's aspect ratio.</summary>+ public double Aspect => Math.Max(1, CanvasWidth) / (double)Math.Max(1, CanvasHeight);++ /// <inheritdoc/>+ protected override Size MeasureOverride(Size constraint) => Fit(constraint);++ /// <inheritdoc/>+ protected override Size ArrangeOverride(Size arrangeSize) => Fit(arrangeSize);++ /// <summary>The canvas fitted uniformly into <paramref name="room"/>; its own size along an unbounded side, or with no bound at all.</summary>+ private Size Fit(Size room)+ {+ double width = Math.Max(1, CanvasWidth);+ double height = Math.Max(1, CanvasHeight);+ bool freeWidth = double.IsInfinity(room.Width);+ bool freeHeight = double.IsInfinity(room.Height);+ if (freeWidth && freeHeight)+ {+ return new Size(width, height);+ }+ double scale = freeWidth ? room.Height / height : freeHeight ? room.Width / width : Math.Min(room.Width / width, room.Height / height);+ return new Size(width * scale, height * scale);+ }+}diff --git a/WaveDudeNext.WPF/Controls/PictureFrame.cs b/WaveDudeNext.WPF/Controls/PictureFrame.csindex 0ead4b1..4e5ba63 100644--- a/WaveDudeNext.WPF/Controls/PictureFrame.cs+++ b/WaveDudeNext.WPF/Controls/PictureFrame.cs@@ -25,9 +25,9 @@ namespace WaveDudeNext.WPF.Controls;/// Lays out a label and a picture so the label takes as little of the picture's room as possible:/// above the picture when the available space is taller than the picture's aspect ratio (spare room/// is above and below anyway), or rotated by 90° on its left when the space is wider (spare room is-/// at the sides). The first child is the label, the second the picture (an <see cref="Image"/> with-/// <see cref="Stretch.Uniform"/>, or a panel holding one under an overlay; its <see cref="Image.Source"/>-/// gives the aspect ratio, 16:9 when there is none). UI thread, like every element.+/// at the sides). The first child is the label, the second the picture (a <see cref="CanvasImage"/>, whose canvas+/// gives the aspect ratio, or an <see cref="Image"/> with <see cref="Stretch.Uniform"/>, whose <see cref="Image.Source"/>+/// gives it, 16:9 when there is none; or a panel holding one under an overlay). UI thread, like every element./// </summary>public sealed class PictureFrame : Panel{@@ -125,11 +125,19 @@ public sealed class PictureFrame : Panelreturn finalSize;}- /// <summary>Width over height of the picture's source, or 16:9 without one. The picture is an <see cref="Image"/>, or a panel whose first <see cref="Image"/> child is it (an overlay on top).</summary>+ /// <summary>+ /// Width over height of the picture: a <see cref="CanvasImage"/>'s canvas, else the source's, or 16:9 without one. The+ /// picture is an <see cref="Image"/>, or a panel whose first <see cref="Image"/> child is it (an overlay on top).+ /// </summary>private static double AspectOf(UIElement picture){Image? image = picture as Image ?? (picture as Panel)?.Children.OfType<Image>().FirstOrDefault();- return image is { Source: { Width: > 0, Height: > 0 } source } ? source.Width / source.Height : DefaultAspect;+ return image switch+ {+ CanvasImage canvas => canvas.Aspect,+ { Source: { Width: > 0, Height: > 0 } source } => source.Width / source.Height,+ _ => DefaultAspect,+ };}private static Transform Freeze(Transform transform)diff --git a/WaveDudeNext.WPF/MainWindow.Display.cs b/WaveDudeNext.WPF/MainWindow.Display.csindex 65ed6c3..80d1238 100644--- a/WaveDudeNext.WPF/MainWindow.Display.cs+++ b/WaveDudeNext.WPF/MainWindow.Display.cs@@ -57,7 +57,7 @@ public partial class MainWindowvar halves = new Half[source.Width * source.Height];if (source.CopyLayer(Math.Clamp(shown, 0, source.Count - 1), plane, halves)){- ApplyFit(layer, BrightnessFit.For(halves, plane), PreviewPosition);+ ApplyFit(layer, BrightnessFit.For(halves, source.KindOf(plane)), PreviewPosition);return;}}@@ -105,7 +105,7 @@ public partial class MainWindowFrameLayer plane = PlaneOf(_fitRequest.Layer);var source = new SnapshotFrameSource(result.Snapshot);var halves = new Half[source.Width * source.Height];- double? fit = source.Has(plane) && source.CopyLayer(0, plane, halves) ? BrightnessFit.For(halves, plane) : null;+ double? fit = source.Has(plane) && source.CopyLayer(0, plane, halves) ? BrightnessFit.For(halves, source.KindOf(plane)) : null;// the runner's engine is released once its result is read (the snapshot belongs to the runner)runner?.Dispose();ApplyFit(_fitRequest.Layer, fit, result.Frame);diff --git a/WaveDudeNext.WPF/MainWindow.Export.cs b/WaveDudeNext.WPF/MainWindow.Export.csindex ada27ad..a63f645 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, needsHalves: true);+ SimulationRun? run = await EnsureRunForExport(intensity, needsHalves: true, intensityRoot: intensity ? ExportFormats.IntensityRootFor(format) : null);if (run == null){return;@@ -344,7 +344,8 @@ public partial class MainWindowtargets.Add(new ExportTarget(exportLayer, output, open));if (ExportFormats.IsData(format)){- Logger.Debug("Export target {Layer}: the stored 16-bit values as OpenEXR (no colours, outline or boxes), to {Output}", layer, output);+ Logger.Debug("Export target {Layer}: the stored 16-bit values as OpenEXR{Samples} (no colours, outline or boxes), to {Output}",+ layer, layer == FrameLayer.Intensity ? (run.Store.IntensityRoot ? ", the intensity's square root" : ", the intensity itself") : "", output);}else{@@ -386,7 +387,8 @@ public partial class MainWindow/// </summary>/// <param name="intensity">The run must hold the intensity plane.</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)+ /// <param name="intensityRoot">What the run's 16-bit intensity must hold for an OpenEXR export of it: its square root (true), the intensity (false), or either (null).</param>+ private async Task<SimulationRun?> EnsureRunForExport(bool intensity, bool needsHalves, bool? intensityRoot = null){IsExportWaiting = true;try@@ -401,11 +403,13 @@ public partial class MainWindowbool 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 ? "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;+ : intensity && !run.Store.Has(FrameLayer.Intensity) ? "the run has no intensity plane"+ : intensityRoot is bool root && run.Store.IntensityRoot != root ? (root ? "the export needs the intensity as its square root" : "the export needs the intensity as I, which the preview stores as its square root")+ : !run.IsActive && run.State != RunState.Completed ? "the run did not complete" : null;if (reason != null){Logger.Debug("Export: a run is started first ({Reason})", reason);- StartRun(automatic: true, trackIntensity: intensity, fullQuality: true);+ StartRun(automatic: true, trackIntensity: intensity, fullQuality: true, intensityRoot: intensityRoot ?? true);run = Run;}else if (run!.IsActive)diff --git a/WaveDudeNext.WPF/MainWindow.Simulation.cs b/WaveDudeNext.WPF/MainWindow.Simulation.csindex 9bec064..b356419 100644--- a/WaveDudeNext.WPF/MainWindow.Simulation.cs+++ b/WaveDudeNext.WPF/MainWindow.Simulation.cs@@ -82,13 +82,14 @@ public partial class MainWindow/// <param name="automatic">Started after an edit rather than by the user: the preview keeps its position.</param>/// <param name="trackIntensity">Store the intensity plane whatever the project needs (an export of the intensity asks for it).</param>/// <param name="fullQuality">Capture every cell of every frame as a half whatever the View menu says (an export needs that).</param>- private void StartRun(bool automatic = false, bool trackIntensity = false, bool fullQuality = false)+ /// <param name="intensityRoot">With <paramref name="fullQuality"/>: store the intensity as its square root, the preview's, or as I (an OpenEXR export of I).</param>+ private void StartRun(bool automatic = false, bool trackIntensity = false, bool fullQuality = false, bool intensityRoot = true){if (!Settings.Default.UseGpu){Logger.Info("Running on the CPU: 'Use the GPU' is off in the Simulation menu");}- PreviewQuality quality = fullQuality ? PreviewQuality.Full : PreviewQualitySetting;+ PreviewQuality quality = fullQuality ? PreviewQuality.Full with { IntensityRoot = intensityRoot } : PreviewQualitySetting;RunSpec spec = RunSpec.Create(Project, LoadSceneImage(), Settings.Default.UseGpu, trackIntensity, quality);// the frames stay in memory up to the budget (the user's share of the RAM, capped by what is free now); only// the rest needs room on the cache drive (2026-10-14). The outgoing run's frames count as free: DiscardRundiff --git a/WaveDudeNext.WPF/Panes/PreviewPane.xaml b/WaveDudeNext.WPF/Panes/PreviewPane.xamlindex 510b4eb..f8b8038 100644--- a/WaveDudeNext.WPF/Panes/PreviewPane.xaml+++ b/WaveDudeNext.WPF/Panes/PreviewPane.xaml@@ -557,8 +557,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</controls:HeaderStrip><!-- the picture with the source/probe handles over it; both fill the same rectangle --><Grid>- <!-- its size on screen is where a 16-bit frame is rendered (OnPictureSizeChanged) -->- <Image Source="{TemplateBinding Content}" Stretch="Uniform" AutomationProperties.AutomationId="{TemplateBinding Tag}" SizeChanged="OnPictureSizeChanged" />+ <!-- sized by the canvas, never by its bitmap; its size on screen is where a 16-bit frame is rendered (OnPictureSizeChanged) -->+ <controls:CanvasImage Source="{TemplateBinding Content}" AutomationProperties.AutomationId="{TemplateBinding Tag}" SizeChanged="OnPictureSizeChanged"+ CanvasWidth="{Binding CanvasWidth, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}}"+ CanvasHeight="{Binding CanvasHeight, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}}" /><!-- the scene outline, a translucent layer of the same pixel size, so it lands exactly on the frame --><Image Source="{Binding Path=(local:PreviewPane.OverlayImage), RelativeSource={RelativeSource TemplatedParent}}"Stretch="Uniform" IsHitTestVisible="False" />diff --git a/WaveDudeNext.WPF/Rendering/FramePresenter.cs b/WaveDudeNext.WPF/Rendering/FramePresenter.csindex 232bfab..504b067 100644--- a/WaveDudeNext.WPF/Rendering/FramePresenter.cs+++ b/WaveDudeNext.WPF/Rendering/FramePresenter.cs@@ -34,7 +34,7 @@ namespace WaveDudeNext.WPF.Rendering;/// indices, the fast preview, is coloured at its own size and WPF scales the picture; a frame of 16-bit samples is/// rendered at the size its picture takes on screen (<see cref="SetTargetSize"/>, <see cref="ScreenRenderer"/>:/// resampled in value space, coloured from the gradient, optionally dithered, <see cref="DitherBits"/>), into a bitmap-/// whose resolution makes it measure the canvas size, so the layout is the same and WPF draws it 1:1. A UI-thread+/// of that many pixels, which the picture (<see cref="Controls.CanvasImage"/>, sized by the canvas) draws 1:1. A UI-thread/// object: <see cref="Source"/>, <see cref="SetLayer"/> and <see cref="Show"/> are called there; the colouring/// runs on the thread pool, one job at a time, and only the newest request is honoured (a scrub that outruns/// the renderer skips frames rather than queueing them). The bitmaps are written on the UI thread.@@ -326,7 +326,7 @@ public sealed class FramePresenterelse{// 16-bit samples: resampled to the picture's size on screen, every level of the gradient, dithered if chosen- Screen(layer, width, height, outWidth, outHeight).Render(job.Halves, settings.Lut, layer, settings.Brightness, job.DitherBits, pixels);+ Screen(layer, width, height, outWidth, outHeight).Render(job.Halves, settings.Lut, job.Source.KindOf(layer), settings.Brightness, job.DitherBits, pixels);}_colourClock.Stop();_shownSize = (outWidth, outHeight);@@ -336,20 +336,20 @@ public sealed class FramePresenter// dependency properties with thread affinity (read from here they threw on every frame, 2026-10-16). Both// layers are unlocked in one call below, one render pass per presented frame instead of two. Render// priority, on purpose: at background priority the calls waited behind every mouse move of a scrub.- // A 16-bit picture of another size is made here and shown once written: its resolution makes it measure- // the canvas, so the layout stays, and its pixels are the picture's on screen+ // A 16-bit picture of another size is made here and shown once written; the picture sizes itself by the canvas+ // (CanvasImage), so its bitmap is plain screen pixels and a new one never moves the layout. It is kept while its+ // pixel size fits (2026-10-23: a resolution set to make it measure the canvas came back from WPF in single+ // precision, a compare with it failed on every frame, and two new pictures a frame made the whole pane flicker)_writeClock.Start();- double dpiX = 96.0 * outWidth / job.Source.CanvasWidth;- double dpiY = 96.0 * outHeight / job.Source.CanvasHeight;(WriteableBitmap? bitmap, bool isNew, IntPtr buffer, int stride) = _dispatcher.Invoke(() =>{WriteableBitmap? target = job.Indices != null ? job.Bitmaps[(int)layer] : layer == FrameLayer.Field ? FieldBitmap : IntensityBitmap;bool fresh = false;- if (job.Indices == null && (target == null || target.PixelWidth != outWidth || target.PixelHeight != outHeight- || Math.Abs(target.DpiX - dpiX) > 1e-9 || Math.Abs(target.DpiY - dpiY) > 1e-9))+ if (job.Indices == null && (target == null || target.PixelWidth != outWidth || target.PixelHeight != outHeight)){- target = NewBitmap(outWidth, outHeight, dpiX, dpiY);+ target = NewBitmap(outWidth, outHeight, 96, 96);fresh = true;+ Logger.Debug("Preview {Layer}: a new 16-bit picture of {Width}×{Height} screen pixels", layer, outWidth, outHeight);}if (target == null){diff --git a/WaveDudeNext.WPF/Strings/Strings.DE.xaml b/WaveDudeNext.WPF/Strings/Strings.DE.xamlindex 80cb93a..e8a0c64 100644--- a/WaveDudeNext.WPF/Strings/Strings.DE.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.DE.xaml@@ -230,11 +230,11 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Ready">Bereit</s:String><!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->- <s:String x:Key="ExportDialogFilter">MP4-Video, H.264 (*.mp4)|*.mp4|MPEG-1-Video (*.mpg)|*.mpg|AVI-Video, unkomprimiert (*.avi)|*.avi|QuickTime-Film, Animation-Codec, verlustfrei (*.mov)|*.mov|QuickTime-Film, PNG-Codec, verlustfrei (*.mov)|*.mov|PNG-Bildfolge (*.png)|*.png|JPEG-Bildfolge (*.jpg)|*.jpg|OpenEXR-Bildfolge, 16-Bit-Gleitkommadaten (*.exr)|*.exr</s:String>+ <s:String x:Key="ExportDialogFilter">MP4-Video, H.264 (*.mp4)|*.mp4|MPEG-1-Video (*.mpg)|*.mpg|AVI-Video, unkomprimiert (*.avi)|*.avi|QuickTime-Film, Animation-Codec, verlustfrei (*.mov)|*.mov|QuickTime-Film, PNG-Codec, verlustfrei (*.mov)|*.mov|PNG-Bildfolge (*.png)|*.png|JPEG-Bildfolge (*.jpg)|*.jpg|OpenEXR-Bildfolge, 16-Bit-Gleitkommadaten, Intensität als I (*.exr)|*.exr|OpenEXR-Bildfolge, 16-Bit-Gleitkommadaten, Intensität als √I (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleField">Feld exportieren</s:String><s:String x:Key="ExportDialogTitleIntensity">Intensität exportieren</s:String><s:String x:Key="ExportDialogTitleBoth">Feld und Intensität exportieren</s:String>- <s:String x:Key="ExportDialogFilterStill">PNG-Bild (*.png)|*.png|JPEG-Bild (*.jpg)|*.jpg|OpenEXR-Bild, 16-Bit-Gleitkommadaten (*.exr)|*.exr</s:String>+ <s:String x:Key="ExportDialogFilterStill">PNG-Bild (*.png)|*.png|JPEG-Bild (*.jpg)|*.jpg|OpenEXR-Bild, 16-Bit-Gleitkommadaten, Intensität als I (*.exr)|*.exr|OpenEXR-Bild, 16-Bit-Gleitkommadaten, Intensität als √I (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleFrame">Bild exportieren</s:String><s:String x:Key="ExportDialogTitleProbeCsv">Sondendaten exportieren</s:String><s:String x:Key="ExportDialogFilterCsv">CSV-Datei (*.csv)|*.csv</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.EN.xaml b/WaveDudeNext.WPF/Strings/Strings.EN.xamlindex ae33fb4..26d90c3 100644--- a/WaveDudeNext.WPF/Strings/Strings.EN.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.EN.xaml@@ -232,11 +232,11 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Ready">Ready</s:String><!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->- <s:String x:Key="ExportDialogFilter">MP4 video, H.264 (*.mp4)|*.mp4|MPEG-1 video (*.mpg)|*.mpg|AVI video, uncompressed (*.avi)|*.avi|QuickTime movie, Animation codec, lossless (*.mov)|*.mov|QuickTime movie, PNG codec, lossless (*.mov)|*.mov|PNG image sequence (*.png)|*.png|JPEG image sequence (*.jpg)|*.jpg|OpenEXR image sequence, 16-bit float data (*.exr)|*.exr</s:String>+ <s:String x:Key="ExportDialogFilter">MP4 video, H.264 (*.mp4)|*.mp4|MPEG-1 video (*.mpg)|*.mpg|AVI video, uncompressed (*.avi)|*.avi|QuickTime movie, Animation codec, lossless (*.mov)|*.mov|QuickTime movie, PNG codec, lossless (*.mov)|*.mov|PNG image sequence (*.png)|*.png|JPEG image sequence (*.jpg)|*.jpg|OpenEXR image sequence, 16-bit float data, intensity as I (*.exr)|*.exr|OpenEXR image sequence, 16-bit float data, intensity as √I (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleField">Export the field</s:String><s:String x:Key="ExportDialogTitleIntensity">Export the intensity</s:String><s:String x:Key="ExportDialogTitleBoth">Export the field and the intensity</s:String>- <s:String x:Key="ExportDialogFilterStill">PNG image (*.png)|*.png|JPEG image (*.jpg)|*.jpg|OpenEXR image, 16-bit float data (*.exr)|*.exr</s:String>+ <s:String x:Key="ExportDialogFilterStill">PNG image (*.png)|*.png|JPEG image (*.jpg)|*.jpg|OpenEXR image, 16-bit float data, intensity as I (*.exr)|*.exr|OpenEXR image, 16-bit float data, intensity as √I (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleFrame">Export the frame</s:String><s:String x:Key="ExportDialogTitleProbeCsv">Export the probe data</s:String><s:String x:Key="ExportDialogFilterCsv">CSV file (*.csv)|*.csv</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.FR.xaml b/WaveDudeNext.WPF/Strings/Strings.FR.xamlindex 0885a44..2c38e3a 100644--- a/WaveDudeNext.WPF/Strings/Strings.FR.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.FR.xaml@@ -230,11 +230,11 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Ready">Prêt</s:String><!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->- <s:String x:Key="ExportDialogFilter">Vidéo MP4, H.264 (*.mp4)|*.mp4|Vidéo MPEG-1 (*.mpg)|*.mpg|Vidéo AVI non compressée (*.avi)|*.avi|Film QuickTime, codec Animation, sans perte (*.mov)|*.mov|Film QuickTime, codec PNG, sans perte (*.mov)|*.mov|Séquence d'images PNG (*.png)|*.png|Séquence d'images JPEG (*.jpg)|*.jpg|Séquence d'images OpenEXR, données flottantes 16 bits (*.exr)|*.exr</s:String>+ <s:String x:Key="ExportDialogFilter">Vidéo MP4, H.264 (*.mp4)|*.mp4|Vidéo MPEG-1 (*.mpg)|*.mpg|Vidéo AVI non compressée (*.avi)|*.avi|Film QuickTime, codec Animation, sans perte (*.mov)|*.mov|Film QuickTime, codec PNG, sans perte (*.mov)|*.mov|Séquence d'images PNG (*.png)|*.png|Séquence d'images JPEG (*.jpg)|*.jpg|Séquence d'images OpenEXR, données flottantes 16 bits, intensité en I (*.exr)|*.exr|Séquence d'images OpenEXR, données flottantes 16 bits, intensité en √I (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleField">Exporter le champ</s:String><s:String x:Key="ExportDialogTitleIntensity">Exporter l'intensité</s:String><s:String x:Key="ExportDialogTitleBoth">Exporter le champ et l'intensité</s:String>- <s:String x:Key="ExportDialogFilterStill">Image PNG (*.png)|*.png|Image JPEG (*.jpg)|*.jpg|Image OpenEXR, données flottantes 16 bits (*.exr)|*.exr</s:String>+ <s:String x:Key="ExportDialogFilterStill">Image PNG (*.png)|*.png|Image JPEG (*.jpg)|*.jpg|Image OpenEXR, données flottantes 16 bits, intensité en I (*.exr)|*.exr|Image OpenEXR, données flottantes 16 bits, intensité en √I (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleFrame">Exporter l'image</s:String><s:String x:Key="ExportDialogTitleProbeCsv">Exporter les données de la sonde</s:String><s:String x:Key="ExportDialogFilterCsv">Fichier CSV (*.csv)|*.csv</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.NL.xaml b/WaveDudeNext.WPF/Strings/Strings.NL.xamlindex ae0db50..66ee0a4 100644--- a/WaveDudeNext.WPF/Strings/Strings.NL.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.NL.xaml@@ -230,11 +230,11 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Ready">Gereed</s:String><!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->- <s:String x:Key="ExportDialogFilter">MP4-video, H.264 (*.mp4)|*.mp4|MPEG-1-video (*.mpg)|*.mpg|AVI-video, ongecomprimeerd (*.avi)|*.avi|QuickTime-film, Animation-codec, verliesvrij (*.mov)|*.mov|QuickTime-film, PNG-codec, verliesvrij (*.mov)|*.mov|PNG-beeldreeks (*.png)|*.png|JPEG-beeldreeks (*.jpg)|*.jpg|OpenEXR-beeldreeks, 16-bits drijvendekommagegevens (*.exr)|*.exr</s:String>+ <s:String x:Key="ExportDialogFilter">MP4-video, H.264 (*.mp4)|*.mp4|MPEG-1-video (*.mpg)|*.mpg|AVI-video, ongecomprimeerd (*.avi)|*.avi|QuickTime-film, Animation-codec, verliesvrij (*.mov)|*.mov|QuickTime-film, PNG-codec, verliesvrij (*.mov)|*.mov|PNG-beeldreeks (*.png)|*.png|JPEG-beeldreeks (*.jpg)|*.jpg|OpenEXR-beeldreeks, 16-bits drijvendekommagegevens, intensiteit als I (*.exr)|*.exr|OpenEXR-beeldreeks, 16-bits drijvendekommagegevens, intensiteit als √I (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleField">Veld exporteren</s:String><s:String x:Key="ExportDialogTitleIntensity">Intensiteit exporteren</s:String><s:String x:Key="ExportDialogTitleBoth">Veld en intensiteit exporteren</s:String>- <s:String x:Key="ExportDialogFilterStill">PNG-beeld (*.png)|*.png|JPEG-beeld (*.jpg)|*.jpg|OpenEXR-beeld, 16-bits drijvendekommagegevens (*.exr)|*.exr</s:String>+ <s:String x:Key="ExportDialogFilterStill">PNG-beeld (*.png)|*.png|JPEG-beeld (*.jpg)|*.jpg|OpenEXR-beeld, 16-bits drijvendekommagegevens, intensiteit als I (*.exr)|*.exr|OpenEXR-beeld, 16-bits drijvendekommagegevens, intensiteit als √I (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleFrame">Beeld exporteren</s:String><s:String x:Key="ExportDialogTitleProbeCsv">Sondegegevens exporteren</s:String><s:String x:Key="ExportDialogFilterCsv">CSV-bestand (*.csv)|*.csv</s:String>diff --git a/WaveDudeNext/Engine/FrameShape.cs b/WaveDudeNext/Engine/FrameShape.csindex 67b39ef..d400d97 100644--- a/WaveDudeNext/Engine/FrameShape.cs+++ b/WaveDudeNext/Engine/FrameShape.cs@@ -24,7 +24,7 @@ namespace WaveDudeNext.Engine;/// <summary>How the samples of a captured frame are stored.</summary>public enum FrameFormat{- /// <summary>One <see cref="System.Half"/> per sample: the raw amplitude or intensity, coloured at display time with any brightness.</summary>+ /// <summary>One <see cref="System.Half"/> per sample: the field's amplitude, the intensity or its square root (<see cref="FrameShape.IntensityRoot"/>), coloured at display time with any brightness.</summary>Half = 0,/// <summary>@@ -49,7 +49,13 @@ public enum FrameFormat/// <param name="Format">The sample format.</param>/// <param name="FieldBrightness">Gain applied to the field before the palette index is taken (<see cref="FrameFormat.Index"/> only).</param>/// <param name="IntensityBrightness">Gain applied to the compressed intensity before the palette index is taken (<see cref="FrameFormat.Index"/> only).</param>-public sealed record FrameShape(int CanvasWidth, int CanvasHeight, int Divisor, FrameFormat Format, float FieldBrightness, float IntensityBrightness)+/// <param name="IntensityRoot">+/// Whether a <see cref="FrameFormat.Half"/> plane of the intensity holds its square root, as the preview keeps it, rather+/// than the intensity itself, which an OpenEXR export of I asks for (2026-10-23). The renderer colours √I: stored as I,+/// the dark end lay among half's subnormals, below 6.1e-5, where neighbouring halves were up to a palette level apart;+/// as √I that floor is at I = 3.7e-9. The field and a frame of palette indices are the same either way.+/// </param>+public sealed record FrameShape(int CanvasWidth, int CanvasHeight, int Divisor, FrameFormat Format, float FieldBrightness, float IntensityBrightness, bool IntensityRoot = true){/// <summary>The full-quality shape of a canvas: every cell as a <see cref="FrameFormat.Half"/>.</summary>public static FrameShape Full(int canvasWidth, int canvasHeight) => new(canvasWidth, canvasHeight, 1, FrameFormat.Half, 1f, 1f);@@ -72,8 +78,8 @@ public sealed record FrameShape(int CanvasWidth, int CanvasHeight, int Divisor,/// <summary>The brightness baked into a plane: the field's or the intensity's.</summary>public float BrightnessOf(bool intensity) => intensity ? IntensityBrightness : FieldBrightness;- /// <summary>Whether frames of this shape and of <paramref name="other"/> have the same size and format (the brightness may differ).</summary>- public bool SameLayoutAs(FrameShape other) => Width == other.Width && Height == other.Height && Format == other.Format;+ /// <summary>Whether frames of this shape and of <paramref name="other"/> have the same size, format and intensity samples (the brightness may differ).</summary>+ public bool SameLayoutAs(FrameShape other) => Width == other.Width && Height == other.Height && Format == other.Format && IntensityRoot == other.IntensityRoot;/// <summary>Validates the record: the canvas at least 1 × 1, the divisor at least 1.</summary>/// <exception cref="ArgumentOutOfRangeException">A dimension or the divisor is below 1.</exception>@@ -97,9 +103,12 @@ public static class FrameConversion/// <summary>/// Converts one plane. For a divisor of 1 a <see cref="FrameFormat.Half"/> plane is the vectorised/// float-to-half conversion; otherwise every block of <see cref="FrameShape.Divisor"/>² cells (fewer at the- /// right and bottom edges) is averaged first, then the sample is taken as a half or as the palette index- /// (<see cref="ColorLut.FieldIndex"/> or <see cref="ColorLut.IntensityIndex(float, float)"/> with the shape's brightness)- /// of the sample rounded to a half, so an index frame holds exactly what a half frame renders to (2026-10-19).+ /// right and bottom edges) is averaged first, then the sample is taken as a half or as the palette index, with the+ /// shape's brightness, of exactly the half a 16-bit frame of the shape stores (2026-10-19; one rule for both since+ /// 2026-10-23): <see cref="ColorLut.FieldIndex"/> of the field, <see cref="ColorLut.IntensityRootIndex"/> of the+ /// intensity's root, or <see cref="ColorLut.IntensityIndex(float, float)"/> of the intensity where the shape keeps I.+ /// The intensity's root is taken when the shape says so (<see cref="FrameShape.IntensityRoot"/>): the block's mean+ /// energy, then the root./// </summary>/// <param name="source">The float values; row y of the canvas starts at <paramref name="offset"/> + y × <paramref name="stride"/>.</param>/// <param name="offset">Index of the canvas's first cell in <paramref name="source"/> (stride + 1 for an engine's padded buffer, 0 for a packed plane).</param>@@ -118,7 +127,8 @@ public static class FrameConversion}int divisor = shape.Divisor;float brightness = shape.BrightnessOf(intensity);- if (divisor == 1 && shape.Format == FrameFormat.Half)+ bool root = intensity && shape.IntensityRoot;+ if (divisor == 1 && shape.Format == FrameFormat.Half && !root){Parallel.For(0, height, y =>TensorPrimitives.ConvertToHalf(source.AsSpan(offset + y * stride, width), MemoryMarshal.Cast<byte, Half>(destination.Span.Slice(y * width * 2, width * 2))));@@ -138,12 +148,24 @@ public static class FrameConversion}if (shape.Format == FrameFormat.Half){+ if (root)+ {+ TensorPrimitives.Sqrt(row, row);+ }TensorPrimitives.ConvertToHalf(row, MemoryMarshal.Cast<byte, Half>(destination.Span.Slice(y * width * 2, width * 2)));}else{Span<byte> target = destination.Span.Slice(y * width, width);- if (intensity)+ if (root)+ {+ // the index of the root as a 16-bit frame stores it: rooted, then rounded to a half+ for (int x = 0; x < width; x++)+ {+ target[x] = (byte)ColorLut.IntensityRootIndex((float)(Half)MathF.Sqrt(row[x]), brightness);+ }+ }+ else if (intensity){for (int x = 0; x < width; x++){diff --git a/WaveDudeNext/Engine/GpuWaveSimulator.cs b/WaveDudeNext/Engine/GpuWaveSimulator.csindex 3d6e179..a936166 100644--- a/WaveDudeNext/Engine/GpuWaveSimulator.cs+++ b/WaveDudeNext/Engine/GpuWaveSimulator.cs@@ -281,7 +281,12 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposableif (shape.Format == FrameFormat.Index){SetFloat(kernel, 8U, shape.BrightnessOf(intensity));- SetInt(kernel, 9U, intensity ? 1 : 0);+ // 0 the field, 1 the intensity, 2 its root (the preview's)+ SetInt(kernel, 9U, intensity ? (shape.IntensityRoot ? 2 : 1) : 0);+ }+ else+ {+ SetInt(kernel, 9U, intensity && shape.IntensityRoot ? 1 : 0);}Enqueue(kernel, _captureGrid!, "capture");OpenClApi.Check(OpenClApi.clEnqueueReadBufferPtr(_queue, staging, 0U, IntPtr.Zero, new IntPtr(plane.Length), FrameSnapshot.AddressOf(plane), 0U, IntPtr.Zero, out IntPtr evt), "clEnqueueReadBuffer (capture)");@@ -758,19 +763,21 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablesource.AppendLine(" return sum / (float)((y1 - y0) * (x1 - x0));");source.AppendLine("}");source.AppendLine();- 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)");+ // 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("{");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(" vstore_half(capture_sample(src, w, h, stride, div, rim, x, y), y * fw + x, dst);");+ source.AppendLine(" float v = 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();- // 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 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 index mapping of ColorLut.FieldIndex / IntensityRootIndex / IntensityIndex: a NaN field gives the centre, a NaN+ // or non-positive intensity 0. The index is that of exactly the half a 16-bit frame stores, rounded as the CPU's+ // capture rounds 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 field, the intensity's root (intensity 2, the preview's since+ // 2026-10-23: rooted, then rounded) or the intensity itself (intensity 1).// 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)");@@ -796,9 +803,12 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposablesource.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 = round_to_half(capture_sample(src, w, h, stride, div, rim, x, y));");+ source.AppendLine(" float raw = 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)");+ source.AppendLine(" if (intensity == 2)");+ source.AppendLine(" index = v > 0.0f ? (int)(fmin(v * brightness, 1.0f) * 254.0f) : 0;");+ source.AppendLine(" else if (intensity == 1)");source.AppendLine(" index = v > 0.0f ? (int)(fmin(sqrt(v) * brightness, 1.0f) * 254.0f) : 0;");source.AppendLine(" else {");source.AppendLine(" float s = v * brightness;");diff --git a/WaveDudeNext/Export/ExportFormat.cs b/WaveDudeNext/Export/ExportFormat.csindex 1d3c862..a9ed218 100644--- a/WaveDudeNext/Export/ExportFormat.cs+++ b/WaveDudeNext/Export/ExportFormat.cs@@ -34,8 +34,18 @@ public enum ExportFormatPng,/// <summary>A JPEG per frame in a folder of its own; the quality setting applies.</summary>Jpeg,- /// <summary>An OpenEXR file per frame in a folder of its own: the stored 16-bit floats themselves, one channel, uncompressed; data, not a rendered picture (2026-10-18).</summary>+ /// <summary>+ /// An OpenEXR file per frame in a folder of its own: 16-bit floats, one channel, uncompressed; data, not a rendered+ /// picture (2026-10-18). The field, and the intensity as I: a run that stores it so is made first (the preview stores its+ /// square root, and squaring that back would lose a bit). What a scripted <c>.exr</c> means.+ /// </summary>Exr,+ /// <summary>+ /// An OpenEXR file per frame like <see cref="Exr"/>, the intensity as its square root, as the preview stores it+ /// (2026-10-23): the dark end at half's full precision, and no extra run after a 16-bit preview. The field is the same.+ /// Shares the extension with <see cref="Exr"/>: the dialog's filter tells them apart.+ /// </summary>+ ExrRoot,}/// <summary>What is known about each <see cref="ExportFormat"/>: extensions, whether it is a sequence, how to open its sink.</summary>@@ -117,17 +127,17 @@ public static class ExportFormats}/// <summary>The formats in filter order: the videos, then the sequences.</summary>- public static readonly ExportFormat[] All = [ExportFormat.Mp4, ExportFormat.Mpeg1, ExportFormat.Avi, ExportFormat.Mov, ExportFormat.MovPng, ExportFormat.Png, ExportFormat.Jpeg, ExportFormat.Exr];+ public static readonly ExportFormat[] All = [ExportFormat.Mp4, ExportFormat.Mpeg1, ExportFormat.Avi, ExportFormat.Mov, ExportFormat.MovPng, ExportFormat.Png, ExportFormat.Jpeg, ExportFormat.Exr, ExportFormat.ExrRoot];/// <summary>The formats a still can take, in the order of the still's filter: the sequence formats.</summary>- public static readonly ExportFormat[] Stills = [ExportFormat.Png, ExportFormat.Jpeg, ExportFormat.Exr];+ public static readonly ExportFormat[] Stills = [ExportFormat.Png, ExportFormat.Jpeg, ExportFormat.Exr, ExportFormat.ExrRoot];- /// <summary>The file extensions a format accepts, with their dots, the first the one it writes; both MOV formats take <c>.mov</c>.</summary>+ /// <summary>The file extensions a format accepts, with their dots, the first the one it writes; both MOV formats take <c>.mov</c>, both OpenEXR ones <c>.exr</c>.</summary>public static string[] Extensions(ExportFormat format) => format switch{ExportFormat.Png => [".png"],ExportFormat.Jpeg => [".jpg", ".jpeg"],- ExportFormat.Exr => [".exr"],+ ExportFormat.Exr or ExportFormat.ExrRoot => [".exr"],ExportFormat.Mpeg1 => [".mpg", ".mpeg", ".m1v"],ExportFormat.Avi => [".avi"],ExportFormat.Mp4 => [".mp4", ".m4v"],@@ -154,8 +164,8 @@ public static class ExportFormats/// <summary>/// The first format in filter order that accepts the path's extension, or null. The extension alone cannot tell- /// the two MOV formats apart (a <c>.mov</c> means the Animation codec here): the dialog's filter decides the- /// format, this serves a scripted path (2026-10-19).+ /// the two MOV formats apart (a <c>.mov</c> means the Animation codec here) nor the two OpenEXR ones (an <c>.exr</c>+ /// holds the intensity as I): the dialog's filter decides the format, this serves a scripted path (2026-10-19)./// </summary>public static ExportFormat? FromPath(string path){@@ -170,10 +180,22 @@ public static class ExportFormats}/// <summary>Whether the format writes one file per frame (these are also the formats a still can take).</summary>- public static bool IsSequence(ExportFormat format) => format is ExportFormat.Png or ExportFormat.Jpeg or ExportFormat.Exr;+ public static bool IsSequence(ExportFormat format) => format is ExportFormat.Png or ExportFormat.Jpeg or ExportFormat.Exr or ExportFormat.ExrRoot;/// <summary>Whether the format holds the stored values rather than a rendered picture (OpenEXR): colours, brightness, outline and boxes do not apply.</summary>- public static bool IsData(ExportFormat format) => format == ExportFormat.Exr;+ public static bool IsData(ExportFormat format) => format is ExportFormat.Exr or ExportFormat.ExrRoot;++ /// <summary>+ /// What the run's 16-bit intensity must hold for an export of the intensity in this format: true for its square root+ /// (<see cref="ExportFormat.ExrRoot"/>), false for the intensity itself (<see cref="ExportFormat.Exr"/>), null when+ /// either serves (a picture is coloured from both alike).+ /// </summary>+ public static bool? IntensityRootFor(ExportFormat format) => format switch+ {+ ExportFormat.Exr => false,+ ExportFormat.ExrRoot => true,+ _ => null,+ };/// <summary>Whether the quality setting means anything to the format.</summary>public static bool UsesQuality(ExportFormat format) => format is ExportFormat.Jpeg or ExportFormat.Mpeg1 or ExportFormat.Mp4;@@ -199,7 +221,7 @@ public static class ExportFormats{ExportFormat.Png => new ImageFileSink(path, width, height, (stream, frame) => PngEncoder.Write(stream, frame.Span, width, height)),ExportFormat.Jpeg => new ImageFileSink(path, width, height, JpegWriter(width, height, quality)),- ExportFormat.Exr => ExrSink.Still(path, width, height),+ ExportFormat.Exr or ExportFormat.ExrRoot => ExrSink.Still(path, width, height),_ => throw new NotSupportedException("A still is a PNG, a JPEG or an OpenEXR file."),};@@ -226,6 +248,7 @@ public static class ExportFormatsreturn new ImageSequenceSink(SequenceFolder(path), Path.GetFileNameWithoutExtension(path), ".jpg", width, height,() => JpegWriter(width, height, quality), SequenceWorkers(encoderIsParallel: PreferredJpeg == null), plannedFrames, firstFrame);case ExportFormat.Exr:+ case ExportFormat.ExrRoot:return ExrSink.Sequence(SequenceFolder(path), Path.GetFileNameWithoutExtension(path), width, height, plannedFrames, firstFrame);case ExportFormat.Mpeg1:return new Mpeg1Writer(path, width, height, fps, quality);diff --git a/WaveDudeNext/Export/ExportJob.cs b/WaveDudeNext/Export/ExportJob.csindex e4895a1..c978f93 100644--- a/WaveDudeNext/Export/ExportJob.cs+++ b/WaveDudeNext/Export/ExportJob.cs@@ -349,7 +349,7 @@ public sealed class ExportJob : INotifyPropertyChangedthrow new InvalidOperationException($"Frame {frame} is not in the store (it holds {Store.Count}).");}int[] pixels = free.Take();- FrameRenderer.Render(values, width, height, layer.Lut, layer.Layer, layer.Brightness, pixels);+ FrameRenderer.Render(values, width, height, layer.Lut, Store.KindOf(layer.Layer), layer.Brightness, pixels);Finish(layer, frame, pixels, width, height);queue.Add(new Item(frame, t, pixels, null));}diff --git a/WaveDudeNext/Rendering/BrightnessFit.cs b/WaveDudeNext/Rendering/BrightnessFit.csindex ef2e0ba..6aade09 100644--- a/WaveDudeNext/Rendering/BrightnessFit.cs+++ b/WaveDudeNext/Rendering/BrightnessFit.cs@@ -15,14 +15,12 @@// 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>/// The display brightness that fits a frame (the preview's Auto, 2026-10-20, Jeroen's point 9): the gain that brings-/// the <see cref="Percentile"/> of the coloured magnitude to the top of the palette, |value| for the field and-/// √value for the intensity (the renderer's own mappings, see <see cref="ColorLut"/>), so the brightest half percent+/// the <see cref="Percentile"/> of the coloured magnitude to the top of the palette, |value| for the field and the+/// square root for the intensity (stored as such in the preview; the renderer's own mappings, see <see cref="ColorLut"/>), so the brightest half percent/// saturates and a source cell, far above the field around it, does not darken the picture. Pure arithmetic; any/// thread./// </summary>@@ -32,13 +30,13 @@ public static class BrightnessFitpublic const double Percentile = 0.995;/// <summary>- /// The brightness that fits <paramref name="samples"/> of <paramref name="layer"/>, rounded to three significant+ /// The brightness that fits <paramref name="samples"/> of that <paramref name="kind"/>, rounded to three significant/// digits and clamped to the model's range (1e-4 to 1e5); null when the frame has nothing to fit (every sample/// zero or not finite)./// </summary>/// <param name="samples">One plane of a frame, as stored.</param>- /// <param name="layer">The plane: the field is coloured by its value, the intensity by its square root.</param>- public static double? For(ReadOnlySpan<Half> samples, FrameLayer layer)+ /// <param name="kind">What the samples are: the field is coloured by its value, the intensity by its square root, which the preview's frames store.</param>+ public static double? For(ReadOnlySpan<Half> samples, SampleKind kind){float[] magnitudes = new float[samples.Length];int count = 0;@@ -47,7 +45,12 @@ public static class BrightnessFitfloat value = (float)sample;if (float.IsFinite(value)){- magnitudes[count++] = layer == FrameLayer.Intensity ? MathF.Sqrt(MathF.Max(0f, value)) : MathF.Abs(value);+ magnitudes[count++] = kind switch+ {+ SampleKind.Field => MathF.Abs(value),+ SampleKind.Intensity => MathF.Sqrt(MathF.Max(0f, value)),+ _ => MathF.Max(0f, value),+ };}}if (count == 0)diff --git a/WaveDudeNext/Rendering/ColorLut.cs b/WaveDudeNext/Rendering/ColorLut.csindex 0f06e19..85c9f78 100644--- a/WaveDudeNext/Rendering/ColorLut.cs+++ b/WaveDudeNext/Rendering/ColorLut.cs@@ -15,8 +15,6 @@// 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>@@ -48,10 +46,10 @@ public sealed class ColorLutprivate readonly double _blackLevel;private readonly bool _makeSymmetric;private readonly bool _reverse;- private TableEntry<int>? _fieldTable;- private TableEntry<int>? _intensityTable;- private TableEntry<ulong>? _fieldDeepTable;- private TableEntry<ulong>? _intensityDeepTable;+ /// <summary>The half tables built, one per <see cref="SampleKind"/>.</summary>+ private readonly TableEntry<int>?[] _tables = new TableEntry<int>?[3];+ /// <summary>The 16-bit half tables built, one per <see cref="SampleKind"/>.</summary>+ private readonly TableEntry<ulong>?[] _deepTables = new TableEntry<ulong>?[3];/// <summary>A built half table and the brightness it was built for.</summary>private sealed record TableEntry<T>(float Brightness, T[] Table);@@ -139,17 +137,18 @@ public sealed class ColorLut/// <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.+ /// the value's position on the gradient by the sample kind'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>, its stored square root <c>min(value · brightness, 1)</c>,+ /// both 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 kind 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="kind">What the samples are: the signed field, the intensity, or its square root.</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) =>- Cached(ref (layer == FrameLayer.Field ? ref _fieldTable : ref _intensityTable), layer, brightness,+ public int[] HalfTable(SampleKind kind, float brightness) =>+ Cached(ref _tables[(int)kind], kind, brightness,(r, g, b) => unchecked((int)0xFF000000) | (Round(r * 255.0) << 16) | (Round(g * 255.0) << 8) | Round(b * 255.0));/// <summary>@@ -157,14 +156,14 @@ public sealed class ColorLut/// as the level times 256, 0..65,280 (<c>round(level · 255 · 256)</c>: the 8-bit level in the high byte, the fraction of/// the next level in the low one), packed as <c>R << 32 | G << 16 | B</c>. Kept and built like the 8-bit table./// </summary>- /// <param name="layer">Which mapping: the signed field or the non-negative intensity.</param>+ /// <param name="kind">What the samples are: the signed field, the intensity, or its square root.</param>/// <param name="brightness">The layer's gain.</param>- public ulong[] DeepHalfTable(FrameLayer layer, float brightness) =>- Cached(ref (layer == FrameLayer.Field ? ref _fieldDeepTable : ref _intensityDeepTable), layer, brightness,+ public ulong[] DeepHalfTable(SampleKind kind, float brightness) =>+ Cached(ref _deepTables[(int)kind], kind, brightness,(r, g, b) => ((ulong)(uint)Round(r * 65280.0) << 32) | ((ulong)(uint)Round(g * 65280.0) << 16) | (uint)Round(b * 65280.0));/// <summary>The table in <paramref name="slot"/> when it was built for this brightness, else a new one, kept there.</summary>- private T[] Cached<T>(ref TableEntry<T>? slot, FrameLayer layer, float brightness, Func<double, double, double, T> pack)+ private T[] Cached<T>(ref TableEntry<T>? slot, SampleKind kind, float brightness, Func<double, double, double, T> pack){TableEntry<T>? cached = Volatile.Read(ref slot);if (cached != null && cached.Brightness.Equals(brightness))@@ -178,7 +177,12 @@ public sealed class ColorLutfor (int bits = block * (HalfValues / Blocks); bits < (block + 1) * (HalfValues / Blocks); bits++){double value = (double)BitConverter.UInt16BitsToHalf((ushort)bits);- (double r, double g, double b) = LevelsAt(layer == FrameLayer.Field ? FieldPosition(value, brightness) : IntensityPosition(value, brightness));+ (double r, double g, double b) = LevelsAt(kind switch+ {+ SampleKind.Field => FieldPosition(value, brightness),+ SampleKind.Intensity => IntensityPosition(value > 0.0 ? Math.Sqrt(value) : 0.0, brightness),+ _ => IntensityPosition(value, brightness),+ });table[bits] = pack(r, g, b);}});@@ -195,9 +199,9 @@ public sealed class ColorLutreturn 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>An intensity's position on the gradient from its square root: <c>min(root · brightness, 1)</c>, 0 for NaN and for values not above zero.</summary>+ private static double IntensityPosition(double root, float brightness) =>+ root > 0.0 ? Math.Clamp(root * brightness, 0.0, 1.0) : 0.0;/// <summary>The gradient at a position through the display options (the order of <see cref="Build"/>): each channel 0..1, unrounded.</summary>private (double R, double G, double B) LevelsAt(double position)@@ -244,8 +248,19 @@ public sealed class ColorLut}/// <summary>- /// 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.+ /// The palette index of an intensity's square root, the index an 8-bit intensity frame stores (2026-10-23, the user's+ /// choice: the index of the very half a 16-bit frame stores, so both previews start from one value, and the darkest+ /// indices stay right at a high brightness, where the intensity rounded to a half had merged them):+ /// <c>min(root · brightness, 1) · 254</c>, 0 for NaN or a root not above zero.+ /// </summary>+ /// <param name="root">The intensity's square root, rounded to a half by the caller.</param>+ /// <param name="brightness">Gain applied to the root.</param>+ public static int IntensityRootIndex(float root, float brightness) =>+ root > 0f ? (int)(MathF.Min(root * brightness, 1f) * 254f) : 0;++ /// <summary>+ /// The square-root case of <see cref="IntensityIndex(float, float, float)"/>: <c>min(sqrt(intensity) · brightness, 1) · 254</c>,+ /// 0 for NaN or a non-positive intensity; the index of a frame whose 16-bit intensity is I itself (<see cref="Engine.FrameShape.IntensityRoot"/>)./// </summary>/// <param name="intensity">Accumulated intensity from the engine.</param>/// <param name="brightness">Gain applied after the square root.</param>diff --git a/WaveDudeNext/Rendering/FrameRenderer.cs b/WaveDudeNext/Rendering/FrameRenderer.csindex 6ce4f64..328653b 100644--- a/WaveDudeNext/Rendering/FrameRenderer.cs+++ b/WaveDudeNext/Rendering/FrameRenderer.cs@@ -17,7 +17,6 @@using System.Collections.Concurrent;using System.Runtime.InteropServices;-using WaveDudeNext.Runs;namespace WaveDudeNext.Rendering;@@ -40,19 +39,19 @@ public static class FrameRendererPartitioner.Create(0, height, 32);/// <summary>- /// Renders a plane of 16-bit samples: every sample's bits index the layer's half table at+ /// Renders a plane of 16-bit samples: every sample's bits index the half table of its kind at/// <paramref name="brightness"/>, built first when the brightness is new to <paramref name="lut"/>./// </summary>/// <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">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="kind">What the samples are: the field is signed around the gradient's middle, the intensity (or its root) 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 Render(ReadOnlyMemory<Half> values, int width, int height, ColorLut lut, FrameLayer layer, float brightness, Memory<int> pixels)+ public static void Render(ReadOnlyMemory<Half> values, int width, int height, ColorLut lut, SampleKind kind, float brightness, Memory<int> pixels){- int[] table = lut.HalfTable(layer, brightness);+ int[] table = lut.HalfTable(kind, brightness);Parallel.ForEach(Blocks(height), block =>{int start = block.Item1 * width;diff --git a/WaveDudeNext/Rendering/SampleKind.cs b/WaveDudeNext/Rendering/SampleKind.csnew file mode 100644index 0000000..31ab67a--- /dev/null+++ b/WaveDudeNext/Rendering/SampleKind.cs@@ -0,0 +1,34 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 Alexander Graef <[email protected]>+//+// This file is part of WaveDude Next, a 2D wave simulator.+//+// Based on the work of+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>+// 0x23 (Diffraction Limited), author of WaveSimulator2D+// <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>+//+// WaveDude Next is free software: you can redistribute it and/or modify it under+// the terms of the GNU General Public License as published by the Free Software+// Foundation, either version 3 of the License, or (at your option) any later+// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or+// <https://www.gnu.org/licenses/>.++namespace WaveDudeNext.Rendering;++/// <summary>+/// What a 16-bit sample holds, which decides its position on the gradient (<see cref="ColorLut.HalfTable"/>); a frame+/// source tells it per plane (<see cref="Runs.FrameSources.KindOf"/>).+/// </summary>+public enum SampleKind+{+ /// <summary>The signed field: <c>(clamp(v · brightness, −1, 1) + 1) / 2</c>, zero in the gradient's middle.</summary>+ Field,++ /// <summary>The intensity itself, as a run for an OpenEXR export of I stores it: <c>min(√v · brightness, 1)</c>.</summary>+ Intensity,++ /// <summary>The intensity's square root, as the preview stores it (2026-10-23): <c>min(v · brightness, 1)</c>.</summary>+ IntensityRoot,+}diff --git a/WaveDudeNext/Rendering/ScreenRenderer.cs b/WaveDudeNext/Rendering/ScreenRenderer.csindex ee69a4d..9e4e03f 100644--- a/WaveDudeNext/Rendering/ScreenRenderer.cs+++ b/WaveDudeNext/Rendering/ScreenRenderer.cs@@ -18,7 +18,6 @@using System.Collections.Concurrent;using System.Numerics.Tensors;using System.Runtime.InteropServices;-using WaveDudeNext.Runs;namespace WaveDudeNext.Rendering;@@ -111,8 +110,9 @@ public sealed class ResampleAxis/// <summary>/// Renders a plane of 16-bit samples at the size it is shown on screen, for the preview (2026-10-23, the user's design):-/// the samples are resampled in value space first (<see cref="ResampleAxis"/>, rows then columns), so every screen pixel-/// shows a value the field or intensity has there, in a colour of the gradient; the value is looked up in the layer's+/// the samples are resampled in value space first (<see cref="ResampleAxis"/>, rows then columns; the intensity's square+/// root as energy), so every screen pixel shows a value the field or intensity has there, in a colour of the+/// gradient; the value is looked up in the layer's/// half table and, with dithering, rounded to 8 bits per channel through a Bayer matrix fixed to the screen pixels. Only/// for the screen: a dithered picture cannot be scaled again, and an export never is one. One instance per picture and/// size, holding the axes and the rows between the passes; one render at a time, on any thread, the rows of each pass@@ -156,11 +156,11 @@ public sealed class ScreenRenderer/// </summary>/// <param name="values">The plane's samples.</param>/// <param name="lut">The colours.</param>- /// <param name="layer">Which mapping the samples take: the signed field or the non-negative intensity.</param>+ /// <param name="kind">What the samples are: the signed field, the intensity, or its square root.</param>/// <param name="brightness">The layer's gain.</param>/// <param name="ditherBits">0 for none (each value's colour rounded to 8 bits, <see cref="ColorLut.HalfTable"/>), else one of <see cref="DitherDepths"/>.</param>/// <param name="pixels">Destination.</param>- public void Render(ReadOnlyMemory<Half> values, ColorLut lut, FrameLayer layer, float brightness, int ditherBits, Memory<int> pixels)+ public void Render(ReadOnlyMemory<Half> values, ColorLut lut, SampleKind kind, float brightness, int ditherBits, Memory<int> pixels){if (ditherBits != 0 && !DitherDepths.Contains(ditherBits)){@@ -169,12 +169,18 @@ public sealed class ScreenRendererint sourceWidth = _x.Source;int targetWidth = _x.Target;float[] rows = _rows;+ // the intensity's square root is blended as energy, its square, and rooted again before the lookup+ bool energy = kind == SampleKind.IntensityRoot;// rows: every sample row to the screen's widthParallel.ForEach(Partitioner.Create(0, _y.Source, 32), () => new float[sourceWidth], (block, _, line) =>{for (int y = block.Item1; y < block.Item2; y++){TensorPrimitives.ConvertToSingle(values.Span.Slice(y * sourceWidth, sourceWidth), line);+ if (energy)+ {+ TensorPrimitives.Multiply(line, line, line);+ }Span<float> target = rows.AsSpan(y * targetWidth, targetWidth);for (int t = 0; t < targetWidth; t++){@@ -190,8 +196,8 @@ public sealed class ScreenRendererreturn line;}, _ => { });// columns: every screen row from the rows it covers, then its colours- int[]? table = ditherBits == 0 ? lut.HalfTable(layer, brightness) : null;- ulong[]? deep = ditherBits == 0 ? null : lut.DeepHalfTable(layer, brightness);+ int[]? table = ditherBits == 0 ? lut.HalfTable(kind, brightness) : null;+ ulong[]? deep = ditherBits == 0 ? null : lut.DeepHalfTable(kind, brightness);int[] thresholds = ditherBits == 0 ? [] : BayerThresholds(ditherBits);int side = ditherBits == 0 ? 1 : 1 << ((ditherBits - 8) / 2);Parallel.ForEach(Partitioner.Create(0, _y.Target, 32), () => (Values: new float[targetWidth], Halves: new Half[targetWidth]), (block, _, buffers) =>@@ -204,6 +210,10 @@ public sealed class ScreenRenderer{TensorPrimitives.MultiplyAdd(rows.AsSpan((first + k) * targetWidth, targetWidth), weights[k], buffers.Values, buffers.Values);}+ if (energy)+ {+ TensorPrimitives.Sqrt(buffers.Values, buffers.Values);+ }TensorPrimitives.ConvertToHalf(buffers.Values, buffers.Halves);ReadOnlySpan<ushort> bits = MemoryMarshal.Cast<Half, ushort>(buffers.Halves);Span<int> target = pixels.Span.Slice(y * targetWidth, targetWidth);diff --git a/WaveDudeNext/Runs/FrameStore.cs b/WaveDudeNext/Runs/FrameStore.csindex 90bb6b0..ee4edcc 100644--- a/WaveDudeNext/Runs/FrameStore.cs+++ b/WaveDudeNext/Runs/FrameStore.cs@@ -49,7 +49,8 @@ namespace WaveDudeNext.Runs;/// them (<see cref="PrepareBlocks"/>): a fresh block costs a page fault per 4 KB on first touch, 8 to 14 ms/// for a full-HD frame, which would make the writer slower than the engine; prepared, a frame is a plain copy./// File layout: a <see cref="HeaderSize"/>-byte header ("WDFS", version, width, height, layers,-/// visualize-every, capacity, first frame in the file, format, divisor, canvas width, canvas height), then one+/// visualize-every, capacity, first frame in the file, format, divisor, canvas width, canvas height, 1 when the+/// intensity is stored as its square root), then one/// <see cref="FrameBytes"/> record per spilled frame; within a frame the planes follow the order of/// <see cref="FrameLayer"/>, only those present./// </remarks>@@ -240,6 +241,9 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable/// <inheritdoc/>public FrameFormat Format => Shape.Format;+ /// <inheritdoc/>+ public bool IntensityRoot => Shape.IntensityRoot;+/// <summary>The planes every frame holds.</summary>public FrameLayers Layers { get; }@@ -616,6 +620,7 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposableBitConverter.TryWriteBytes(header[36..], Shape.Divisor);BitConverter.TryWriteBytes(header[40..], CanvasWidth);BitConverter.TryWriteBytes(header[44..], CanvasHeight);+ BitConverter.TryWriteBytes(header[48..], IntensityRoot ? 1 : 0);RandomAccess.Write(_handle!, header, 0);}}diff --git a/WaveDudeNext/Runs/IFrameSource.cs b/WaveDudeNext/Runs/IFrameSource.csindex 75dddd1..3dadf4b 100644--- a/WaveDudeNext/Runs/IFrameSource.cs+++ b/WaveDudeNext/Runs/IFrameSource.cs@@ -17,6 +17,7 @@using System.Runtime.InteropServices;using WaveDudeNext.Engine;+using WaveDudeNext.Rendering;namespace WaveDudeNext.Runs;@@ -44,6 +45,9 @@ public interface IFrameSource/// <summary>The sample format of every plane.</summary>FrameFormat Format { get; }+ /// <summary>Whether a <see cref="FrameFormat.Half"/> intensity plane holds the intensity's square root, the preview's, rather than the intensity (<see cref="FrameShape.IntensityRoot"/>).</summary>+ bool IntensityRoot { get; }+/// <summary>Frames available: indices 0..Count-1 may be read.</summary>int Count { get; }@@ -58,6 +62,14 @@ public interface IFrameSourcebool CopyLayer(int frame, FrameLayer layer, Span<Half> destination);}+/// <summary>What the planes of a frame source hold, for the renderer and the brightness fit.</summary>+public static class FrameSources+{+ /// <summary>The kind of the 16-bit samples of <paramref name="layer"/>: the field, the intensity, or its square root.</summary>+ public static SampleKind KindOf(this IFrameSource source, FrameLayer layer) =>+ layer == FrameLayer.Field ? SampleKind.Field : source.IntensityRoot ? SampleKind.IntensityRoot : SampleKind.Intensity;+}+/// <summary>A single captured frame as a one-frame <see cref="IFrameSource"/>; every frame index reads the same snapshot.</summary>public sealed class SnapshotFrameSource(FrameSnapshot snapshot) : IFrameSource{@@ -79,6 +91,9 @@ public sealed class SnapshotFrameSource(FrameSnapshot snapshot) : IFrameSource/// <inheritdoc/>public FrameFormat Format => Snapshot.Shape.Format;+ /// <inheritdoc/>+ public bool IntensityRoot => Snapshot.Shape.IntensityRoot;+/// <inheritdoc/>public int Count => 1;diff --git a/WaveDudeNext/Runs/PreviewQuality.cs b/WaveDudeNext/Runs/PreviewQuality.csindex 02d512c..2fcf163 100644--- a/WaveDudeNext/Runs/PreviewQuality.cs+++ b/WaveDudeNext/Runs/PreviewQuality.cs@@ -31,13 +31,14 @@ namespace WaveDudeNext.Runs;/// <param name="ResolutionDivisor">Cells per sample along each axis (1, 2, 4: full, half, quarter resolution).</param>/// <param name="FrameDivisor">Timeline frames per stored frame (1, 2, 4: every frame, every second, every fourth); see <see cref="RunSpec.FrameStride"/>.</param>/// <param name="Format">The sample format; <see cref="FrameFormat.Index"/> bakes the display brightness into the frames.</param>-public sealed record PreviewQuality(int ResolutionDivisor, int FrameDivisor, FrameFormat Format)+/// <param name="IntensityRoot">Whether 16-bit frames hold the intensity's square root, as the preview keeps it, or the intensity itself, for an OpenEXR export of I (<see cref="FrameShape.IntensityRoot"/>).</param>+public sealed record PreviewQuality(int ResolutionDivisor, int FrameDivisor, FrameFormat Format, bool IntensityRoot = true){- /// <summary>Every cell of every frame as a <see cref="FrameFormat.Half"/>: what an export needs and the default.</summary>+ /// <summary>Every cell of every frame as a <see cref="FrameFormat.Half"/>, the intensity as its root: what an export needs and the default.</summary>public static readonly PreviewQuality Full = new(1, 1, FrameFormat.Half);- /// <summary>Whether this is <see cref="Full"/>.</summary>- public bool IsFull => this == Full;+ /// <summary>Whether every cell of every frame is kept as a <see cref="FrameFormat.Half"/>, whatever the intensity's samples are.</summary>+ public bool IsFull => ResolutionDivisor == 1 && FrameDivisor == 1 && Format == FrameFormat.Half;/// <summary>Validates the record: both divisors at least 1.</summary>/// <exception cref="ArgumentOutOfRangeException">A divisor is below 1.</exception>@@ -50,5 +51,6 @@ public sealed record PreviewQuality(int ResolutionDivisor, int FrameDivisor, Fra/// <inheritdoc/>public override string ToString() =>- IsFull ? "full" : $"1/{ResolutionDivisor} resolution, every {FrameDivisor}. frame, {(Format == FrameFormat.Half ? "16-bit" : "8-bit")}";+ (IsFull ? "full" : $"1/{ResolutionDivisor} resolution, every {FrameDivisor}. frame, {(Format == FrameFormat.Half ? "16-bit" : "8-bit")}")+ + (IntensityRoot || Format != FrameFormat.Half ? "" : ", the intensity as I");}diff --git a/WaveDudeNext/Runs/RunSpec.cs b/WaveDudeNext/Runs/RunSpec.csindex 147e48e..04f4c54 100644--- a/WaveDudeNext/Runs/RunSpec.cs+++ b/WaveDudeNext/Runs/RunSpec.cs@@ -46,7 +46,7 @@ public sealed class RunSpecSteps = project.Simulation.Steps;Quality = quality.Validate();VisualizeEvery = Math.Max(1, project.Simulation.VisualizeEvery);- Shape = new FrameShape(width, height, quality.ResolutionDivisor, quality.Format, (float)project.Display.Field.Brightness, (float)project.Display.Intensity.Brightness);+ Shape = new FrameShape(width, height, quality.ResolutionDivisor, quality.Format, (float)project.Display.Field.Brightness, (float)project.Display.Intensity.Brightness, quality.IntensityRoot);PreferGpu = preferGpu;Engine = EngineOptions.From(project.Simulation, project.Scene, trackIntensity);Image = image;diff --git a/WaveDudeNext/Runs/StridedFrameSource.cs b/WaveDudeNext/Runs/StridedFrameSource.csindex 8853b74..b3f66a6 100644--- a/WaveDudeNext/Runs/StridedFrameSource.cs+++ b/WaveDudeNext/Runs/StridedFrameSource.cs@@ -51,6 +51,9 @@ public sealed class StridedFrameSource(FrameStore store, int stride, int frameCo/// <inheritdoc/>public FrameFormat Format => Store.Format;+ /// <inheritdoc/>+ public bool IntensityRoot => Store.IntensityRoot;+/// <summary>Timeline frames that can be shown: every stored frame covers <see cref="Stride"/> of them, never beyond the run's frame count.</summary>public int Count => (int)Math.Min((long)Store.Count * Stride, frameCount);diff --git a/_tools/library_check/ExportChecks.cs b/_tools/library_check/ExportChecks.csindex 2a2f852..54f5615 100644--- a/_tools/library_check/ExportChecks.cs+++ b/_tools/library_check/ExportChecks.cs@@ -390,6 +390,15 @@ internal static class ExportChecksstill.Add(halves);}check(ReadExr(File.ReadAllBytes(exrStill), w, h, out _) is { } stillBack && MemoryMarshal.AsBytes(stillBack.AsSpan()).SequenceEqual(MemoryMarshal.AsBytes(halves.AsSpan())), "formats: an OpenEXR still holds the frame");+ // the two OpenEXR entries (2026-10-23): the intensity as I or as its square root, one extension, the dialog's+ // filter telling them apart; a scripted .exr is I+ using (IFrameSink rootSink = ExportFormats.Open(ExportFormat.ExrRoot, Path.Combine(folder, "root.exr"), w, h, 30, 70, 1))+ {+ check(rootSink.WantsHalves && ExportFormats.IsData(ExportFormat.ExrRoot) && ExportFormats.IsSequence(ExportFormat.ExrRoot) && ExportFormats.Extension(ExportFormat.ExrRoot) == ".exr"+ && ExportFormats.FromPath("data.exr") == ExportFormat.Exr && ExportFormats.IntensityRootFor(ExportFormat.Exr) == false && ExportFormats.IntensityRootFor(ExportFormat.ExrRoot) == true+ && ExportFormats.IntensityRootFor(ExportFormat.Png) == null && ExportFormats.Stills.Contains(ExportFormat.ExrRoot) && ExportFormats.All[^1] == ExportFormat.ExrRoot,+ "formats: OpenEXR of the intensity as I (a scripted .exr) or as its square root, both data, both .exr; pictures take either");+ }bool videoRefused = false;try{@@ -526,7 +535,7 @@ internal static class ExportChecksvar values = new Half[64 * 48];var expected = new int[64 * 48];store.CopyLayer(2, FrameLayer.Field, values);- FrameRenderer.Render(values, 64, 48, lut, FrameLayer.Field, 30f, expected);+ FrameRenderer.Render(values, 64, 48, lut, SampleKind.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");@@ -687,7 +696,7 @@ internal static class ExportChecks{var px = new int[w * h];store.CopyLayer(i, FrameLayer.Field, values);- FrameRenderer.Render(values, w, h, lut, FrameLayer.Field, 30f, px);+ FrameRenderer.Render(values, w, h, lut, SampleKind.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 fce95d2..f61e47a 100644--- a/_tools/library_check/Program.cs+++ b/_tools/library_check/Program.cs@@ -1,4 +1,4 @@-// SPDX-License-Identifier: GPL-3.0-or-later+// SPDX-License-Identifier: GPL-3.0-or-later// Copyright (C) 2026 Alexander Graef <[email protected]>//// This file is part of WaveDude Next, a 2D wave simulator.@@ -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.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)),+ ("intensity", () => FrameRenderer.Render(intensity, w, h, lut, SampleKind.IntensityRoot, 1f, pixels)),+ ("field", () => FrameRenderer.Render(field, w, h, lut, SampleKind.Field, 1f, pixels)),+ ("field, grey", () => FrameRenderer.Render(field, w, h, ColorLut.Grey, SampleKind.Field, 1f, pixels)),+ ("intensity again", () => FrameRenderer.Render(intensity, w, h, lut, SampleKind.IntensityRoot, 1f, pixels)),}){for (int i = 0; i < 60; i++)@@ -638,14 +638,14 @@ internal static class Programfloat brightness = 1f;for (int i = 0; i < 20; i++){- fresh.HalfTable(FrameLayer.Intensity, brightness += 0.01f);+ fresh.HalfTable(SampleKind.IntensityRoot, brightness += 0.01f);}Thread.Sleep(300);var clock = Stopwatch.StartNew();const int Builds = 100;for (int i = 0; i < Builds; i++){- fresh.HalfTable(i % 2 == 0 ? FrameLayer.Field : FrameLayer.Intensity, brightness += 0.01f);+ fresh.HalfTable(i % 2 == 0 ? SampleKind.Field : SampleKind.IntensityRoot, 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)");}@@ -656,14 +656,14 @@ internal static class Programvar shown = new int[tw * th];for (int i = 0; i < 30; i++){- screen.Render(intensity, lut, FrameLayer.Intensity, 1f, bits, shown);+ screen.Render(intensity, lut, SampleKind.IntensityRoot, 1f, bits, shown);}Thread.Sleep(300);var clock = Stopwatch.StartNew();const int Runs = 50;for (int i = 0; i < Runs; i++){- screen.Render(intensity, lut, FrameLayer.Intensity, 1f, bits, shown);+ screen.Render(intensity, lut, SampleKind.IntensityRoot, 1f, bits, shown);}Console.WriteLine($" screen {tw}x{th}{(bits == 0 ? "" : $", dithered from {bits} bits"),-26} {clock.Elapsed.TotalMilliseconds / Runs,6:0.00} ms per layer");}@@ -871,7 +871,9 @@ internal static class Programfloat tolerance = 2e-3f * Math.Max(1f, MaxAbs(at100));Check(a.HasIntensity && !b.HasIntensity, name + ": intensity captured only when asked");Check(MaxDiff(at100, engine.Stride, W, H, a.Field) < tolerance, name + ": deferred capture holds the field of its step (max diff " + MaxDiff(at100, engine.Stride, W, H, a.Field) + ")");- Check(MaxDiff(inten100, engine.Stride, W, H, a.Intensity!) < 2e-3f * Math.Max(1f, MaxAbs(inten100)), name + ": captured intensity matches");+ // a 16-bit capture holds the intensity's square root (2026-10-23)+ float[] root100 = [.. inten100.Select(MathF.Sqrt)];+ Check(MaxDiff(root100, engine.Stride, W, H, a.Intensity!) < 2e-3f * Math.Max(1f, MaxAbs(root100)), name + ": captured intensity matches (its square root)");Check(MaxDiff(at150, engine.Stride, W, H, b.Field) < tolerance, name + ": second capture holds the later step");engine.Reset();engine.CaptureFrame(a, true);@@ -1492,6 +1494,31 @@ internal static class Programvar fullBytes = new byte[full.PlaneBytes];FrameConversion.Convert(field, stride + 1, stride, full, false, fullBytes);Check(MaxDiff(field, stride, W, H, MemoryMarshal.Cast<byte, Half>(fullBytes)) < tolerance, "full shape: the plain half conversion");+ // the intensity as its square root, the preview's, or as itself for an OpenEXR export of I (2026-10-23): each the+ // half of the float, the root correctly rounded first; the field the same either way+ FrameShape linear = full with { IntensityRoot = false };+ var rootBytes = new byte[full.PlaneBytes];+ var linearBytes = new byte[full.PlaneBytes];+ var fieldLinearBytes = new byte[full.PlaneBytes];+ FrameConversion.Convert(inten, stride + 1, stride, full, true, rootBytes);+ FrameConversion.Convert(inten, stride + 1, stride, linear, true, linearBytes);+ FrameConversion.Convert(field, stride + 1, stride, linear, false, fieldLinearBytes);+ bool samples = true;+ for (int y = 0; y < H; y++)+ {+ for (int x = 0; x < W; x++)+ {+ float i = inten[(y + 1) * stride + x + 1];+ samples &= MemoryMarshal.Cast<byte, Half>(rootBytes)[y * W + x] == (Half)MathF.Sqrt(i) && MemoryMarshal.Cast<byte, Half>(linearBytes)[y * W + x] == (Half)i;+ }+ }+ Check(samples && fieldLinearBytes.AsSpan().SequenceEqual(fullBytes) && full.IntensityRoot && !full.SameLayoutAs(linear),+ "the 16-bit intensity: the half of its square root by default, of itself when the shape says so; the field alike; the two layouts differ");+ var rootSource = new SnapshotFrameSource(new FrameSnapshot(full, true));+ var linearSource = new SnapshotFrameSource(new FrameSnapshot(linear, true));+ Check(rootSource.KindOf(FrameLayer.Intensity) == SampleKind.IntensityRoot && linearSource.KindOf(FrameLayer.Intensity) == SampleKind.Intensity+ && linearSource.KindOf(FrameLayer.Field) == SampleKind.Field && RunSpec.Create(new Project(), null, false, quality: PreviewQuality.Full with { IntensityRoot = false }).Shape.IntensityRoot == false,+ "a frame source says what its intensity holds; a run spec takes it from its quality");// a half-size frame holds the 2 x 2 block meansvar halfBytes = new byte[half.PlaneBytes];FrameConversion.Convert(field, stride + 1, stride, half, false, halfBytes);@@ -1528,28 +1555,43 @@ internal static class Programfor (int x = 0; x < W; x++){int at = (y + 1) * stride + x + 1;- if (indexField[y * W + x] != ColorLut.FieldIndex((float)(Half)field[at], 30f) || indexInten[y * W + x] != ColorLut.IntensityIndex((float)(Half)inten[at], 5f))+ if (indexField[y * W + x] != ColorLut.FieldIndex((float)(Half)field[at], 30f) || indexInten[y * W + x] != ColorLut.IntensityRootIndex((float)(Half)MathF.Sqrt(inten[at]), 5f)){same = false;break;}}}- Check(same && indexField.Max() > 127 && indexField.Min() < 127 && indexInten.Max() > 0, "index shape: the renderer's palette index of every cell's half-rounded sample at brightness 30 and 5, both sides of the centre used");- // 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 colours+ Check(same && indexField.Max() > 127 && indexField.Min() < 127 && indexInten.Max() > 0, "index shape: the renderer's palette index of every cell's half-rounded field and intensity root at brightness 30 and 5, both sides of the centre used");+ // an index frame holds the palette index of the very half a 16-bit frame stores, both planes (one rule since+ // 2026-10-23): the 8-bit preview shows the stored samples, at the palette's 255 coloursvar halfField = new byte[full.PlaneBytes];+ var halfRoot = new byte[full.PlaneBytes];FrameConversion.Convert(field, stride + 1, stride, full, false, halfField);+ FrameConversion.Convert(inten, stride + 1, stride, full, true, halfRoot);ReadOnlySpan<Half> storedHalves = MemoryMarshal.Cast<byte, Half>(halfField);+ ReadOnlySpan<Half> storedRoots = MemoryMarshal.Cast<byte, Half>(halfRoot);bool rendersAlike = true;for (int i = 0; i < W * H && rendersAlike; i++){- rendersAlike = indexField[i] == ColorLut.FieldIndex((float)storedHalves[i], 30f);+ rendersAlike = indexField[i] == ColorLut.FieldIndex((float)storedHalves[i], 30f) && indexInten[i] == ColorLut.IntensityRootIndex((float)storedRoots[i], 5f);+ }+ Check(rendersAlike, "index shape: every index is the palette index of the half a 16-bit frame of the same floats stores, field and intensity root");+ // the darkest indices at a high brightness (2026-10-23): an intensity of 2e-8 at brightness 30 is index 1.08, so 1;+ // the intensity rounded to a half first had made it 0 (below half's smallest step, 6e-8), the root keeps it+ {+ FrameShape bright = new(4, 1, 1, FrameFormat.Index, 1f, 30f);+ float[] dim = [2e-8f, 5e-8f, 1e-7f, 1e-6f];+ var dimIndices = new byte[4];+ FrameConversion.Convert(dim, 0, 4, bright, true, dimIndices);+ var oldIndices = dim.Select(i => ColorLut.IntensityIndex((float)(Half)i, 30f)).ToArray();+ var exact = dim.Select(i => (int)(Math.Sqrt(i) * 30 * 254)).ToArray();+ Check(dimIndices.Select(b => (int)b).SequenceEqual(exact) && oldIndices[0] == 0 && exact[0] == 1,+ $"index of dim intensities at brightness 30: {string.Join(" ", dimIndices)}, the exact ones; rounding I to a half first gave {string.Join(" ", oldIndices)}");}- 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 floats- foreach (FrameShape shape in new[] { half, third, index, halfIndex })+ foreach (FrameShape shape in new[] { linear, half, third, index, halfIndex, half with { IntensityRoot = false } }){var expectedField = new byte[shape.PlaneBytes];var expectedInten = new byte[shape.PlaneBytes];@@ -1559,7 +1601,7 @@ internal static class Programcpu.CaptureFrame(snapshot, true);cpu.AwaitFrame(snapshot);Check(snapshot.HasIntensity && snapshot.FieldBytes.AsSpan().SequenceEqual(expectedField) && snapshot.IntensityBytes!.AsSpan().SequenceEqual(expectedInten),- $"CPU capture of 1/{shape.Divisor} {shape.Format} equals the reference conversion");+ $"CPU capture of 1/{shape.Divisor} {shape.Format}{(shape.IntensityRoot ? "" : ", the intensity as I")} equals the reference conversion");}// the GPU's: halves within the tolerance, indices exact where the card's square root rounds correctly (within one elsewhere)GpuWaveSimulator? gpu = GpuWaveSimulator.TryCreate(scene, options, Sources(), out string problems);@@ -1575,7 +1617,7 @@ internal static class Programgpu.PrepareFrame(true, true);float[] gpuField = (float[])gpu.FieldData.Clone();float[] gpuInten = (float[])gpu.IntensityData!.Clone();- foreach (FrameShape shape in new[] { half, third, index, halfIndex })+ foreach (FrameShape shape in new[] { linear, half, third, index, halfIndex, half with { IntensityRoot = false } }){var expectedField = new byte[shape.PlaneBytes];var expectedInten = new byte[shape.PlaneBytes];@@ -1606,7 +1648,7 @@ internal static class Program}int allowed = gpu.Device.CorrectlyRoundedSqrt ? 0 : 1;Check(snapshot.HasIntensity && worstIndex <= allowed && worstHalf < tolerance,- $"GPU capture of 1/{shape.Divisor} {shape.Format} matches the reference conversion (index off by at most {worstIndex} of {allowed} allowed, halves by {worstHalf})");+ $"GPU capture of 1/{shape.Divisor} {shape.Format}{(shape.IntensityRoot ? "" : ", the intensity as I")} matches the reference conversion (index off by at most {worstIndex} of {allowed} allowed, halves by {worstHalf})");}}}@@ -1759,29 +1801,37 @@ internal static class Program// 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.Render(values, 2, 2, ColorLut.Grey, FrameLayer.Field, 1f, pixels);+ FrameRenderer.Render(values, 2, 2, ColorLut.Grey, SampleKind.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.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");+ // the intensity plane holds the square root (2026-10-23)+ var intensities = new Half[4] { (Half)0f, (Half)(-1f), (Half)0.5f, (Half)3f };+ FrameRenderer.Render(intensities, 2, 2, ColorLut.Grey, SampleKind.IntensityRoot, 1f, pixels);+ Check(pixels[0] == Grey(0) && pixels[1] == Grey(0) && pixels[2] == Grey(127) && pixels[3] == Grey(254), "intensity, grey: <= 0 -> 0, a stored root of 0.5 -> 127, the clamp -> 254");+ // a run for an OpenEXR export of I stores the intensity itself, coloured through its square root+ var linearIntensities = new Half[4] { (Half)0f, (Half)(-1f), (Half)0.25f, (Half)9f };+ FrameRenderer.Render(linearIntensities, 2, 2, ColorLut.Grey, SampleKind.Intensity, 1f, pixels);+ Check(pixels[0] == Grey(0) && pixels[1] == Grey(0) && pixels[2] == Grey(127) && pixels[3] == Grey(254), "intensity stored as I, 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);+ int[] fieldTable = ramp.HalfTable(SampleKind.Field, 3.5f);+ int[] intensityTable = ramp.HalfTable(SampleKind.IntensityRoot, 3.5f);+ int[] linearTable = ramp.HalfTable(SampleKind.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;+ double intensityAt = value > 0.0 ? Math.Min(value * 3.5, 1.0) : 0.0;+ double linearAt = 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;+ && (intensityTable[bits] & ~0xFF) == unchecked((int)0xFF000000) && Math.Abs((intensityTable[bits] & 0xFF) - 250 * intensityAt) <= 0.5 + 1e-9+ && (linearTable[bits] & ~0xFF) == unchecked((int)0xFF000000) && Math.Abs((linearTable[bits] & 0xFF) - 250 * linearAt) <= 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");+ Check(nearest && fieldTable.Distinct().Count() == 251 && intensityTable.Distinct().Count() == 251 && linearTable.Distinct().Count() == 251,+ "half tables: each of the 65,536 values gets the level nearest the gradient at its position (field, the intensity's root, the 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);var frame = new Half[37 * 70];@@ -1790,7 +1840,7 @@ internal static class Programframe[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);+ FrameRenderer.Render(frame, 37, 70, ramp, SampleKind.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,@@ -1798,12 +1848,12 @@ internal static class ProgramColorScheme 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[] dark = inferno.HalfTable(SampleKind.IntensityRoot, 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)+ .Where(bits => (double)BitConverter.UInt16BitsToHalf((ushort)bits) is var v && v > 0.0 && 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),+ Check(ReferenceEquals(inferno.HalfTable(SampleKind.IntensityRoot, 1f), dark) && !ReferenceEquals(inferno.HalfTable(SampleKind.Field, 1f), dark) && !ReferenceEquals(inferno.HalfTable(SampleKind.IntensityRoot, 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];@@ -1818,7 +1868,7 @@ internal static class ProgramFrameRenderer.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,+ Check(lifted.ColorAt(0).G == 127 && ((lifted.HalfTable(SampleKind.IntensityRoot, 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)");CheckScreenRenderer(inferno);}@@ -1864,26 +1914,28 @@ internal static class Programplane[i] = (Half)(rng.NextDouble() * 0.2);}var direct = new int[w * h];- FrameRenderer.Render(plane, w, h, lut, FrameLayer.Intensity, 3f, direct);+ FrameRenderer.Render(plane, w, h, lut, SampleKind.IntensityRoot, 3f, direct);var screen = new int[w * h];- new ScreenRenderer(w, h, w, h).Render(plane, lut, FrameLayer.Intensity, 3f, 0, screen);+ new ScreenRenderer(w, h, w, h).Render(plane, lut, SampleKind.IntensityRoot, 3f, 0, screen);Check(screen.SequenceEqual(direct), "screen renderer at the samples' size, no dithering: the half table's picture, bit for bit");- // halved: each pixel the colour of its 2 x 2 block's mean (in value space, before any colour)+ // halved: each pixel the colour of its 2 x 2 block's mean (in value space, before any colour; the intensity, stored as+ // its root, as energy: the root of the mean square)var shrunk = new int[30 * 22];- new ScreenRenderer(60, 44, 30, 22).Render(plane.AsMemory(0, 60 * 44), lut, FrameLayer.Intensity, 3f, 0, shrunk);- int[] table = lut.HalfTable(FrameLayer.Intensity, 3f);+ new ScreenRenderer(60, 44, 30, 22).Render(plane.AsMemory(0, 60 * 44), lut, SampleKind.IntensityRoot, 3f, 0, shrunk);+ int[] table = lut.HalfTable(SampleKind.IntensityRoot, 3f);bool means = true;for (int y = 0; y < 22; y++){for (int x = 0; x < 30; x++){- double mean = ((double)plane[2 * y * 60 + 2 * x] + (double)plane[2 * y * 60 + 2 * x + 1] + (double)plane[(2 * y + 1) * 60 + 2 * x] + (double)plane[(2 * y + 1) * 60 + 2 * x + 1]) / 4;+ double a = (double)plane[2 * y * 60 + 2 * x], b = (double)plane[2 * y * 60 + 2 * x + 1], c = (double)plane[(2 * y + 1) * 60 + 2 * x], d = (double)plane[(2 * y + 1) * 60 + 2 * x + 1];+ double mean = Math.Sqrt((a * a + b * b + c * c + d * d) / 4);// the sums run in single precision (fused or not, by the machine): the half they round to may be the neighbourint bits = BitConverter.HalfToUInt16Bits((Half)mean);means &= shrunk[y * 30 + x] == table[bits] || shrunk[y * 30 + x] == table[bits - 1] || shrunk[y * 30 + x] == table[bits + 1];}}- Check(means, "screen renderer halving: every pixel the colour of its 2 x 2 samples' mean value");+ Check(means, "screen renderer halving: every pixel the colour of its 2 x 2 samples' mean (the intensity's mean energy)");// the field's crest and trough average to zero, the gradient's middle, not to a mix of their coloursvar wave = new Half[4 * 2];for (int i = 0; i < wave.Length; i++)@@ -1891,14 +1943,14 @@ internal static class Programwave[i] = (Half)(i % 2 == 0 ? 0.5f : -0.5f);}var flat = new int[2];- new ScreenRenderer(4, 2, 2, 1).Render(wave, lut, FrameLayer.Field, 1f, 0, flat);- Check(flat.All(p => p == lut.HalfTable(FrameLayer.Field, 1f)[BitConverter.HalfToUInt16Bits((Half)0f)]), "screen renderer: a crest beside a trough shrinks to the colour of zero");+ new ScreenRenderer(4, 2, 2, 1).Render(wave, lut, SampleKind.Field, 1f, 0, flat);+ Check(flat.All(p => p == lut.HalfTable(SampleKind.Field, 1f)[BitConverter.HalfToUInt16Bits((Half)0f)]), "screen renderer: a crest beside a trough shrinks to the colour of zero");// the dither: a flat plane comes out at the colour's two neighbouring 8-bit levels, their mix over one matrix the// 16-bit colour to the depth's bits; without dithering the level rounded- ulong[] deep = lut.DeepHalfTable(FrameLayer.Intensity, 1f);+ ulong[] deep = lut.DeepHalfTable(SampleKind.IntensityRoot, 1f);bool deepRounds = Enumerable.Range(0, ColorLut.HalfValues).All(bits =>{- int argb = lut.HalfTable(FrameLayer.Intensity, 1f)[bits];+ int argb = lut.HalfTable(SampleKind.IntensityRoot, 1f)[bits];ulong d = deep[bits];return Math.Abs(((argb >> 16) & 0xFF) - ((d >> 32) & 0xFFFF) / 256.0) <= 0.5 + 1 / 256.0&& Math.Abs(((argb >> 8) & 0xFF) - ((d >> 16) & 0xFFFF) / 256.0) <= 0.5 + 1 / 256.0@@ -1919,7 +1971,7 @@ internal static class Programvar flatPlane = new Half[32 * 32];Array.Fill(flatPlane, dark);var dithered = new int[32 * 32];- new ScreenRenderer(32, 32, 32, 32).Render(flatPlane, lut, FrameLayer.Intensity, 1f, bits, dithered);+ new ScreenRenderer(32, 32, 32, 32).Render(flatPlane, lut, SampleKind.IntensityRoot, 1f, bits, dithered);int[] blues = [.. dithered.Select(p => p & 0xFF)];double mean = Enumerable.Range(0, side).SelectMany(y => Enumerable.Range(0, side).Select(x => blues[y * 32 + x])).Average();// the fraction to the depth's bits, a half going up (the threshold's tie)@@ -1932,13 +1984,13 @@ internal static class Programvar plain = new int[32 * 32];var plainPlane = new Half[32 * 32];Array.Fill(plainPlane, dark);- new ScreenRenderer(32, 32, 32, 32).Render(plainPlane, lut, FrameLayer.Intensity, 1f, 0, plain);- Check(dithers && plain.All(p => p == lut.HalfTable(FrameLayer.Intensity, 1f)[BitConverter.HalfToUInt16Bits(dark)]),+ new ScreenRenderer(32, 32, 32, 32).Render(plainPlane, lut, SampleKind.IntensityRoot, 1f, 0, plain);+ Check(dithers && plain.All(p => p == lut.HalfTable(SampleKind.IntensityRoot, 1f)[BitConverter.HalfToUInt16Bits(dark)]),"Bayer dither at 10, 12, 14 and 16 bits: a permutation of the matrix's thresholds, only the two neighbouring levels, one tile repeated, its mean the 16-bit colour to the depth's bits; off rounds (" + string.Join(", ", detail) + ")");bool refused = false;try{- new ScreenRenderer(2, 2, 2, 2).Render(new Half[4], lut, FrameLayer.Field, 1f, 11, new int[4]);+ new ScreenRenderer(2, 2, 2, 2).Render(new Half[4], lut, SampleKind.Field, 1f, 11, new int[4]);}catch (ArgumentOutOfRangeException){@@ -3199,20 +3251,26 @@ internal static class Programfield[i] = (Half)((i % 2 == 0 ? 1 : -1) * 0.001f * i);}field[1234] = (Half)50f;- double? fit = BrightnessFit.For(field, FrameLayer.Field);+ double? fit = BrightnessFit.For(field, SampleKind.Field);// the 99.5th percentile of |v| is about 9.95 (the source cell moves it by one rank), so the gain is about 0.1Check(fit is >= 0.099 and <= 0.102, "the field fit brings the 99.5th percentile of |value| to the palette's top, a source cell of 50 aside (" + fit + ")");var intensity = new Half[10_000];for (int i = 0; i < intensity.Length; i++){- intensity[i] = (Half)(0.0001f * i);+ intensity[i] = (Half)MathF.Sqrt(0.0001f * i); // as a 16-bit frame stores it, the square root}- double? intensityFit = BrightnessFit.For(intensity, FrameLayer.Intensity);+ double? intensityFit = BrightnessFit.For(intensity, SampleKind.IntensityRoot);// √(0.0001 × 9949) = 0.9974, its inverse 1.003, three digits- Check(intensityFit == 1.0, "the intensity fit works on the square root, as the renderer colours it (" + intensityFit + ")");- Check(BrightnessFit.For(new Half[100], FrameLayer.Field) == null && BrightnessFit.For([Half.NaN, Half.PositiveInfinity], FrameLayer.Field) == null, "an empty frame has nothing to fit");- Check(BrightnessFit.For([(Half)1e-6f, (Half)1e-6f], FrameLayer.Field) == 1e5, "the fit is clamped to the model's range (1e5 at most)");- double? rounded = BrightnessFit.For([(Half)0.03f, (Half)0.03f], FrameLayer.Field);+ Check(intensityFit == 1.0, "the intensity fit works on the stored square root, as the renderer colours it (" + intensityFit + ")");+ var linearIntensity = new Half[10_000];+ for (int i = 0; i < linearIntensity.Length; i++)+ {+ linearIntensity[i] = (Half)(0.0001f * i); // as a run for an OpenEXR export of I stores it+ }+ Check(BrightnessFit.For(linearIntensity, SampleKind.Intensity) == intensityFit, "the fit of an intensity stored as I takes its square root, to the same brightness");+ Check(BrightnessFit.For(new Half[100], SampleKind.Field) == null && BrightnessFit.For([Half.NaN, Half.PositiveInfinity], SampleKind.Field) == null, "an empty frame has nothing to fit");+ Check(BrightnessFit.For([(Half)1e-6f, (Half)1e-6f], SampleKind.Field) == 1e5, "the fit is clamped to the model's range (1e5 at most)");+ double? rounded = BrightnessFit.For([(Half)0.03f, (Half)0.03f], SampleKind.Field);Check(rounded is { } r && r.ToString(CultureInfo.InvariantCulture).Length <= 4, "the fit is rounded to three significant digits (" + rounded + ")");}