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#
16-bit preview at screen size with optional Bayer dithering; the theme's Window style on every window
Alexander Graef7a1530d8b2fb
diff --git a/CLAUDE.md b/CLAUDE.mdindex c51b76b..4029bd4 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -48,7 +48,10 @@ harnesses run.string, `XmlSerializer` with sparse XML (attributes, repeated children, `[DefaultValue]`), Segoe UI 9 pt, thednSpy look (its sources are GPL: look, do not copy). Inside a `DataTemplate` reference the string keys directly(`{DynamicResource Hint.Type.Member}`): the `meta:Label`/`meta:Hint` extensions wrap a resource reference a template- rejects for a string property and shows as text for an object one (2026-10-22, found on the fibre's node rows).+ rejects for a string property and shows as text for an object one (2026-10-22, found on the fibre's node rows). An+ implicit style never reaches a class derived from `Window`, so every window names the theme's+ (`Style="{StaticResource {x:Type Window}}"`, 2026-10-23: without its layout rounding the pictures sat at fractional+ pixels and WPF resampled them; its Display text formatting had never applied either).- **Model conventions**: a new property gets its XML attribute with a default, `[Category]`/`[DisplayName]`/`[Description]`, a `///` summary, a clamp in `Normalize()` with the matching `[Range]` beside the default (2026-10-21:the bounds are readable from outside, `library_check` proves each against `Normalize()`; a bound that depends on another@@ -90,8 +93,9 @@ SimulationRun: stepping loop + writer threads; IWaveEngine (WaveSimulator CPU |FrameCount, then StateScratchRunner: one kept engine; "frame k of the project as it is now" from step 0, probes sampled; newest requestwins; every request is computed-FramePresenter: CopyLayer -> FrameRenderer (a table lookup per pixel, 32-row blocks) -> the WriteableBitmap, copied on the pool- between Lock/Unlock on the UI thread; only the newest request is rendered+FramePresenter: CopyLayer -> 8-bit: FrameRenderer.RenderIndexed at the store's size, WPF scales; 16-bit: ScreenRenderer at+ the picture's size on screen -> the WriteableBitmap, copied on the pool between Lock/Unlock on the UI thread; only+ the newest request is renderedExportJob (own STA thread): CopyLayer -> FrameRenderer -> outline -> probe boxes/markers -> sinks (PNG, JPEG, MPEG-1, AVI, MP4, MOV)FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDATA%\WaveDudeNext\cache, DeleteOnClose)```@@ -170,6 +174,15 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAcolours are taken is the renderer's (`ColorLut`): 255 at i/254 for 8-bit frames (the author's table, truncated as inhis Python), and for 16-bit frames a table of the 65,536 half values per layer and brightness, the gradient at eachvalue's position, rounded (the 255 entries had left visible patches two to five levels apart in dark gradients).+- **Two preview paths** (2026-10-23, the user's design): 8-bit samples are the fast preview, coloured at the store's+ size and scaled by WPF, as before. 16-bit samples are drawn at each picture's size on screen (`ScreenRenderer`, the+ pane reports the Image's rounded `RenderSize` in device pixels): resampled in value space, never colours (a box mean+ when 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.+ **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 for+ 10, 12, 14 or 16 bits, fixed to the screen's pixels; preview only, never in an export (a video crushes it; an export+ above 8 bits per channel is a possible future goal). A better algorithm than Bayer may come later.- **Colour schemes** are stop lists in `.wdscheme` XML, shipped ones embedded, user ones in`%LOCALAPPDATA%\WaveDudeNext\ColorSchemes`, project ones in the `.wdproj`; an in-house picker edits stops;renaming a project scheme repoints its layers. **The scene image** is embedded and follows its file on disk;@@ -209,7 +222,9 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAGPU step at 1080p 0.25–0.5 ms, CPU 6–14 ms; OpenCL build 0.3 s; a full-HD run of 2500 steps 5.4 s in RAM, bound bythe GPU readback. Renderer per 2880×1080 layer on ten cores (2026-10-23, a table lookup per pixel): 16-bit 0.5 ms,-8-bit 0.6; a half table built in 0.4 ms. Presenter about 7 ms a frame quiet, 20 during a run. JPEG 1080p at 4:4:4: WIC 26 ms a frame+8-bit 0.6; a half table built in 0.4 ms; the screen path from 1920×1080 to 914×514 1.4 ms, dithered 1.5. Presenter for+Example 7 (2880×1080 in a 458×172 picture, both layers, playing): 16-bit 7.3–8.5 ms a frame, dithered 7.7–9.1, 8-bit+10–11 (its bitmaps are canvas-sized). Presenter about 7 ms a frame quiet, 20 during a run. JPEG 1080p at 4:4:4: WIC 26 ms a framesingle-threaded (9 ms a frame in a sequence job on half the cores), in-house 9.8 ms on ten cores (15 in a job);MP4 job 16 ms a frame. Part painter on a Full HD canvas (ten cores): a 400 × 330 outline 30 ms, a 400 px lens 5, a hexagon 8, an S-bent fibre across the canvas 51 (156 chords on the cell grid; 1.3 s without it);the glowing edges 22 ms; the preview's scene pictures about 100 ms more, so the scene rebuild is coalesced at background priority. Laptop (2 cores, HD 520, HDD): iGPU 4.3 ms a step against CPU 14.7; the balldiff --git a/WaveDudeNext.WPF/Commands/ViewCommands.cs b/WaveDudeNext.WPF/Commands/ViewCommands.csindex db27c8c..1d5af8a 100644--- a/WaveDudeNext.WPF/Commands/ViewCommands.cs+++ b/WaveDudeNext.WPF/Commands/ViewCommands.cs@@ -35,4 +35,7 @@ public static class ViewCommands/// <summary>Sets the preview's sample size: the parameter is the bytes per sample (2 for halves, 1 for palette indices).</summary>public static readonly RoutedUICommand SetPreviewSamples = new("Preview samples", nameof(SetPreviewSamples), typeof(ViewCommands));++ /// <summary>Sets the dithering of the 16-bit pictures (2026-10-23): the parameter is the bits per channel (0 for none, 10, 12, 14 or 16).</summary>+ public static readonly RoutedUICommand SetPreviewDither = new("Preview dithering", nameof(SetPreviewDither), typeof(ViewCommands));}diff --git a/WaveDudeNext.WPF/Dialogs/MessageWindow.xaml b/WaveDudeNext.WPF/Dialogs/MessageWindow.xamlindex d35b8bc..a29de47 100644--- a/WaveDudeNext.WPF/Dialogs/MessageWindow.xaml+++ b/WaveDudeNext.WPF/Dialogs/MessageWindow.xaml@@ -24,7 +24,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file orTitle="{DynamicResource Title}" Icon="/App.ico"Width="440" SizeToContent="Height" ResizeMode="NoResize" ShowInTaskbar="False"WindowStartupLocation="CenterOwner"- Background="{DynamicResource WindowBackground}" Foreground="{DynamicResource WindowForeground}"+ Style="{StaticResource {x:Type Window}}"AutomationProperties.AutomationId="MessageWindow"><!-- the app's own message box: a disc with "!" or "?" in the theme's colours, the wrapped text, and the buttonsthe code-behind adds for the chosen set (Enter takes the default, Esc the cancel button, the underlineddiff --git a/WaveDudeNext.WPF/Help/AboutWindow.xaml b/WaveDudeNext.WPF/Help/AboutWindow.xamlindex 54b3c45..0cc638f 100644--- a/WaveDudeNext.WPF/Help/AboutWindow.xaml+++ b/WaveDudeNext.WPF/Help/AboutWindow.xaml@@ -24,7 +24,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file orTitle="{DynamicResource AboutTitle}" Icon="/App.ico"Width="600" SizeToContent="Height" MinWidth="480" MinHeight="620" ShowInTaskbar="False"WindowStartupLocation="CenterOwner"- Background="{DynamicResource WindowBackground}" Foreground="{DynamicResource WindowForeground}"+ Style="{StaticResource {x:Type Window}}"FocusManager.FocusedElement="{Binding ElementName=closeButton}"AutomationProperties.AutomationId="AboutWindow"><!-- Help > About: identity, the credits word for word as in the source header, the license sentence with the fulldiff --git a/WaveDudeNext.WPF/MainWindow.xaml b/WaveDudeNext.WPF/MainWindow.xamlindex 01c352d..69ce2ac 100644--- a/WaveDudeNext.WPF/MainWindow.xaml+++ b/WaveDudeNext.WPF/MainWindow.xaml@@ -40,8 +40,13 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file orMinWidth="800" MinHeight="500"WindowStartupLocation="CenterScreen"ResizeMode="CanResizeWithGrip"+ Style="{StaticResource {x:Type Window}}"AllowDrop="True" DragOver="OnDragOver" Drop="OnDrop">+ <!-- the theme's Window style named, since an implicit style never reaches a class derived from Window (2026-10-23):+ without its layout rounding the pictures sat at fractional positions and sizes and WPF resampled them, which blurred+ the 16-bit pictures' dither away -->+<Window.Resources><converters:EqualityConverter x:Key="Equality" /><converters:FrameMemoryOptionConverter x:Key="FrameMemoryOption" />@@ -174,6 +179,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<CommandBinding Command="{x:Static commands:ViewCommands.SetPreviewResolution}" Executed="OnSetPreviewResolution" /><CommandBinding Command="{x:Static commands:ViewCommands.SetPreviewFrames}" Executed="OnSetPreviewFrames" /><CommandBinding Command="{x:Static commands:ViewCommands.SetPreviewSamples}" Executed="OnSetPreviewSamples" />+ <CommandBinding Command="{x:Static commands:ViewCommands.SetPreviewDither}" Executed="OnSetPreviewDither" /><!-- the pictures' Auto brightness; handler in MainWindow.Display.cs --><CommandBinding Command="{x:Static commands:DisplayCommands.AutoBrightness}" CanExecute="CanAutoBrightness" Executed="OnAutoBrightness" />@@ -289,6 +295,26 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file orIsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewSampleBytes, Converter={StaticResource IntEquals}, ConverterParameter=1, Mode=OneWay}"AutomationProperties.AutomationId="MenuPreviewSamples1" /></MenuItem>+ <!-- the dithering of the 16-bit pictures (2026-10-23): preview only, at each picture's size on screen; 8-bit samples+ have nothing finer to dither, so the entry waits for 16-bit ones -->+ <MenuItem Header="{DynamicResource MenuViewDither}" controls:MenuIcon.Drawing="PreviewDither" AutomationProperties.AutomationId="MenuPreviewDither"+ IsEnabled="{Binding Source={x:Static p:Settings.Default}, Path=PreviewSampleBytes, Converter={StaticResource IntEquals}, ConverterParameter=2, Mode=OneWay}">+ <MenuItem Header="{DynamicResource MenuViewDitherOff}" Command="{x:Static commands:ViewCommands.SetPreviewDither}" CommandParameter="0"+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewDitherBits, Converter={StaticResource IntEquals}, ConverterParameter=0, Mode=OneWay}"+ AutomationProperties.AutomationId="MenuPreviewDither0" />+ <MenuItem Header="{DynamicResource MenuViewDither10}" Command="{x:Static commands:ViewCommands.SetPreviewDither}" CommandParameter="10"+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewDitherBits, Converter={StaticResource IntEquals}, ConverterParameter=10, Mode=OneWay}"+ AutomationProperties.AutomationId="MenuPreviewDither10" />+ <MenuItem Header="{DynamicResource MenuViewDither12}" Command="{x:Static commands:ViewCommands.SetPreviewDither}" CommandParameter="12"+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewDitherBits, Converter={StaticResource IntEquals}, ConverterParameter=12, Mode=OneWay}"+ AutomationProperties.AutomationId="MenuPreviewDither12" />+ <MenuItem Header="{DynamicResource MenuViewDither14}" Command="{x:Static commands:ViewCommands.SetPreviewDither}" CommandParameter="14"+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewDitherBits, Converter={StaticResource IntEquals}, ConverterParameter=14, Mode=OneWay}"+ AutomationProperties.AutomationId="MenuPreviewDither14" />+ <MenuItem Header="{DynamicResource MenuViewDither16}" Command="{x:Static commands:ViewCommands.SetPreviewDither}" CommandParameter="16"+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewDitherBits, Converter={StaticResource IntEquals}, ConverterParameter=16, Mode=OneWay}"+ AutomationProperties.AutomationId="MenuPreviewDither16" />+ </MenuItem></MenuItem><MenuItem Header="{DynamicResource MenuSimulation}"><MenuItem Command="{x:Static commands:SimulationCommands.Run}" Header="{DynamicResource MenuSimulationRun}" InputGestureText="F5" controls:MenuIcon.Glyph="" />@@ -380,7 +406,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file orIsStale="{Binding IsRunStale}" IsProbesStale="{Binding IsProbesStale}" ScratchFrame="{Binding ScratchFrame}"IsComputing="{Binding IsComputingFrame}"Position="{Binding PreviewPosition, Mode=TwoWay}" IsPlaying="{Binding IsPreviewPlaying, Mode=OneWayToSource}"- Orientation="{Binding Source={x:Static p:Settings.Default}, Path=PreviewOrientation, Mode=TwoWay}" />+ Orientation="{Binding Source={x:Static p:Settings.Default}, Path=PreviewOrientation, Mode=TwoWay}"+ DitherBits="{Binding Source={x:Static p:Settings.Default}, Path=PreviewDitherBits}" /></Border></docking:DockHost.DocumentContent></docking:DockHost>diff --git a/WaveDudeNext.WPF/MainWindow.xaml.cs b/WaveDudeNext.WPF/MainWindow.xaml.csindex 7dd79bf..843768c 100644--- a/WaveDudeNext.WPF/MainWindow.xaml.cs+++ b/WaveDudeNext.WPF/MainWindow.xaml.cs@@ -111,6 +111,14 @@ public partial class MainWindow : WindowLogger.Info("Preview quality: {Quality} (View menu)", PreviewQualitySetting);OnPreviewQualityChanged();}+ else if (args.PropertyName == nameof(Settings.PreviewDitherBits) && Settings.Default.PreviewDitherBits == 0)+ {+ Logger.Info("Preview dithering off (View menu)");+ }+ else if (args.PropertyName == nameof(Settings.PreviewDitherBits))+ {+ Logger.Info("Preview dithering from {Bits} bits per channel (View menu)", Settings.Default.PreviewDitherBits);+ }};Closing += (_, e) =>{@@ -383,6 +391,9 @@ public partial class MainWindow : Window/// <summary>View > Preview samples: the bytes per sample (2 halves, 1 palette indices).</summary>private void OnSetPreviewSamples(object sender, ExecutedRoutedEventArgs e) => SetIntSetting(e, bytes => Settings.Default.PreviewSampleBytes = bytes);+ /// <summary>View > Preview dithering: the bits per channel the 16-bit pictures are dithered from (0 none, 10, 12, 14, 16); the pictures redraw.</summary>+ private void OnSetPreviewDither(object sender, ExecutedRoutedEventArgs e) => SetIntSetting(e, bits => Settings.Default.PreviewDitherBits = bits);+/// <summary>A menu choice carried as a number in the command parameter (an int, or digits as text): stores it and saves the settings.</summary>private static void SetIntSetting(ExecutedRoutedEventArgs e, Action<int> apply){diff --git a/WaveDudeNext.WPF/Panes/PreviewPane.xaml b/WaveDudeNext.WPF/Panes/PreviewPane.xamlindex d51780e..510b4eb 100644--- a/WaveDudeNext.WPF/Panes/PreviewPane.xaml+++ b/WaveDudeNext.WPF/Panes/PreviewPane.xaml@@ -557,7 +557,8 @@ 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>- <Image Source="{TemplateBinding Content}" Stretch="Uniform" AutomationProperties.AutomationId="{TemplateBinding Tag}" />+ <!-- 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" /><!-- 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/Panes/PreviewPane.xaml.cs b/WaveDudeNext.WPF/Panes/PreviewPane.xaml.csindex cea5812..bb0d744 100644--- a/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs+++ b/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs@@ -153,6 +153,10 @@ public partial class PreviewPane : UserControlnameof(Orientation), typeof(Orientation), typeof(PreviewPane),new FrameworkPropertyMetadata(Orientation.Horizontal, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));+ /// <summary>Identifies the <see cref="DitherBits"/> property.</summary>+ public static readonly DependencyProperty DitherBitsProperty = DependencyProperty.Register(+ nameof(DitherBits), typeof(int), typeof(PreviewPane), new PropertyMetadata(0, (d, e) => ((PreviewPane)d)._presenter.DitherBits = (int)e.NewValue));+/// <summary>Identifies the <see cref="FieldImage"/> property.</summary>public static readonly DependencyProperty FieldImageProperty = DependencyProperty.Register(nameof(FieldImage), typeof(ImageSource), typeof(PreviewPane));@@ -291,6 +295,8 @@ public partial class PreviewPane : UserControl{InitializeComponent();_presenter = new FramePresenter(Dispatcher);+ // a 16-bit picture of a new size arrives with its first frame+ _presenter.BitmapsChanged += (_, _) => UpdateCanvas(_presenter.Source);// frames = ceil(steps / visualize every); re-evaluated whenever the project or its settings change. The// timeline is always the project's: a reduced preview (View > Preview frames) stores fewer frames, but@@ -448,6 +454,16 @@ public partial class PreviewPane : UserControlset => SetValue(OrientationProperty, value);}+ /// <summary>+ /// The dithering of the 16-bit pictures (View > Preview dithering, 2026-10-23): 0 for none, else the bits per channel+ /// the colours carry into the Bayer matrix (10, 12, 14, 16). Preview only; the 8-bit pictures are not dithered.+ /// </summary>+ public int DitherBits+ {+ get => (int)GetValue(DitherBitsProperty);+ set => SetValue(DitherBitsProperty, value);+ }+/// <summary>Picture of the field at <see cref="Position"/>; the presenter's bitmap, or a black frame without a run.</summary>public ImageSource? FieldImage{@@ -912,6 +928,21 @@ public partial class PreviewPane : UserControl_presenter.SetLayer(layer, lut, (float)(settings?.Brightness ?? DisplayLayer.DefaultBrightness), settings?.Preview ?? true);}+ /// <summary>+ /// A picture's size on screen changed (the window, the split, one picture or two): the presenter renders a 16-bit+ /// frame at that size in device pixels, the picture's rounded layout size, so its pixels land 1:1 on the screen's.+ /// </summary>+ private void OnPictureSizeChanged(object sender, SizeChangedEventArgs e)+ {+ if (sender is not Image { TemplatedParent: DependencyObject cell } image)+ {+ return;+ }+ DpiScale dpi = VisualTreeHelper.GetDpi(image);+ _presenter.SetTargetSize(GetLayer(cell) == ProbeLayer.Field ? FrameLayer.Field : FrameLayer.Intensity,+ (int)Math.Round(e.NewSize.Width * dpi.DpiScaleX), (int)Math.Round(e.NewSize.Height * dpi.DpiScaleY));+ }+/// <summary>Rebuilds both palettes and redraws: a project colour scheme changed, or the project was replaced.</summary>public void RefreshColors(){diff --git a/WaveDudeNext.WPF/Properties/Settings.Designer.cs b/WaveDudeNext.WPF/Properties/Settings.Designer.csindex 32086b5..197f10e 100644--- a/WaveDudeNext.WPF/Properties/Settings.Designer.cs+++ b/WaveDudeNext.WPF/Properties/Settings.Designer.cs@@ -225,6 +225,18 @@ namespace WaveDudeNext.WPF.Properties {}}+ [global::System.Configuration.UserScopedSettingAttribute()]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Configuration.DefaultSettingValueAttribute("0")]+ public int PreviewDitherBits {+ get {+ return ((int)(this["PreviewDitherBits"]));+ }+ set {+ this["PreviewDitherBits"] = value;+ }+ }+[global::System.Configuration.UserScopedSettingAttribute()][global::System.Diagnostics.DebuggerNonUserCodeAttribute()][global::System.Configuration.DefaultSettingValueAttribute("")]diff --git a/WaveDudeNext.WPF/Properties/Settings.settings b/WaveDudeNext.WPF/Properties/Settings.settingsindex d099549..5a73f8e 100644--- a/WaveDudeNext.WPF/Properties/Settings.settings+++ b/WaveDudeNext.WPF/Properties/Settings.settings@@ -53,6 +53,9 @@<Setting Name="PreviewSampleBytes" Type="System.Int32" Scope="User"><Value Profile="(Default)">1</Value></Setting>+ <Setting Name="PreviewDitherBits" Type="System.Int32" Scope="User">+ <Value Profile="(Default)">0</Value>+ </Setting><Setting Name="LastExportFolder" Type="System.String" Scope="User"><Value Profile="(Default)" /></Setting>diff --git a/WaveDudeNext.WPF/Rendering/FramePresenter.cs b/WaveDudeNext.WPF/Rendering/FramePresenter.csindex 639b750..232bfab 100644--- a/WaveDudeNext.WPF/Rendering/FramePresenter.cs+++ b/WaveDudeNext.WPF/Rendering/FramePresenter.cs@@ -30,8 +30,12 @@ namespace WaveDudeNext.WPF.Rendering;/// <summary>/// Turns frames of an <see cref="IFrameSource"/> (a run's store, or a single scratch frame) into the preview's-/// two <see cref="WriteableBitmap"/>s. A UI-thread object: <see cref="Source"/>, <see cref="SetLayer"/> and-/// <see cref="Show"/> are called there; the colouring+/// two <see cref="WriteableBitmap"/>s, on one of two paths (2026-10-23, the user's design): a frame of 8-bit palette+/// 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+/// 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./// </summary>@@ -44,6 +48,11 @@ public sealed class FramePresenterprivate readonly Dispatcher _dispatcher;private readonly LayerSettings[] _settings = [new(), new()];+ private readonly (int Width, int Height)[] _targets = new (int, int)[2];+ /// <summary>The screen renderer of each layer, kept while the sizes stay; the render thread's alone.</summary>+ private readonly ScreenRenderer?[] _screens = new ScreenRenderer?[2];+ private int _ditherBits;+ private (int Width, int Height) _shownSize;private IFrameSource? _source;private Job? _job;private int _wanted;@@ -67,22 +76,29 @@ public sealed class FramePresenter}/// <summary>An immutable snapshot of everything one render needs, replaced wholesale on every change.</summary>- private sealed class Job(IFrameSource source, WriteableBitmap? field, WriteableBitmap? intensity, LayerSettings[] settings)+ private sealed class Job(IFrameSource source, WriteableBitmap? field, WriteableBitmap? intensity, LayerSettings[] settings, (int Width, int Height)[] targets, int ditherBits){public IFrameSource Source { get; } = source;+ /// <summary>The pictures of palette indices, made with the source; a 16-bit picture is taken (or made) when it is written.</summary>public WriteableBitmap?[] Bitmaps { get; } = [field, intensity];public LayerSettings[] Settings { get; } = settings;+ /// <summary>The size each layer is rendered at: the source's for palette indices, the picture's on screen for 16-bit samples (the source's until it is known).</summary>+ public (int Width, int Height)[] Sizes { get; } = [.. targets.Select(target =>+ source.Format == FrameFormat.Half && target.Width > 0 && target.Height > 0 ? target : (source.Width, source.Height))];+ public int DitherBits { get; } = ditherBits;/// <summary>The plane read from the source as halves (a <see cref="FrameFormat.Half"/> source), else null.</summary>public Half[]? Halves { get; } = source.Format == FrameFormat.Half ? new Half[source.Width * source.Height] : null;/// <summary>The plane read from the source as palette indices (a <see cref="FrameFormat.Index"/> source), else null.</summary>public byte[]? Indices { get; } = source.Format == FrameFormat.Index ? new byte[source.Width * source.Height] : null;- public int[] Pixels { get; } = new int[source.Width * source.Height];+ /// <summary>Each layer's rendered pixels, made on first use by the render thread.</summary>+ public int[]?[] Pixels { get; } = new int[]?[2];}/// <summary>/// The frames to show; null shows nothing. The bitmaps (<see cref="FieldBitmap"/>, <see cref="IntensityBitmap"/>)/// are kept across sources of the same size and planes, so switching between a run's store and a scratch- /// frame does not swap images; a new size creates new ones.+ /// frame does not swap images; a new size creates new ones: at once for palette indices, with the first frame+ /// rendered for 16-bit samples (<see cref="BitmapsChanged"/>)./// </summary>public IFrameSource? Source{@@ -99,11 +115,13 @@ public sealed class FramePresenter_source = value;if (!sameShape){- // the old pictures go first, so their memory can be reclaimed for the new ones+ // the old pictures go first, so their memory can be reclaimed for the new ones; a 16-bit picture is made at+ // its size on screen when its first frame is writtenFieldBitmap = null;IntensityBitmap = null;- FieldBitmap = value != null && value.Has(FrameLayer.Field) ? NewBitmap(value) : null;- IntensityBitmap = value != null && value.Has(FrameLayer.Intensity) ? NewBitmap(value) : null;+ bool indexed = value is { Format: FrameFormat.Index };+ FieldBitmap = indexed && value!.Has(FrameLayer.Field) ? NewBitmap(value.Width, value.Height, 96, 96) : null;+ IntensityBitmap = indexed && value!.Has(FrameLayer.Intensity) ? NewBitmap(value.Width, value.Height, 96, 96) : null;}Rebuild();}@@ -115,6 +133,48 @@ public sealed class FramePresenter/// <summary>The intensity picture of the current store, or null (no store, or no intensity plane).</summary>public WriteableBitmap? IntensityBitmap { get; private set; }+ /// <summary>A picture of 16-bit samples was replaced by one of a new size, with its first frame in it; raised on the UI thread.</summary>+ public event EventHandler? BitmapsChanged;++ /// <summary>+ /// The dithering of 16-bit pictures: 0 for none, else one of <see cref="ScreenRenderer.DitherDepths"/> (any other value+ /// means none). Preview only; a frame of palette indices has nothing finer to dither. A change redraws a 16-bit frame.+ /// </summary>+ public int DitherBits+ {+ get => _ditherBits;+ set+ {+ int bits = ScreenRenderer.DitherDepths.Contains(value) ? value : 0;+ if (bits != _ditherBits)+ {+ _ditherBits = bits;+ RebuildIfScreenSized();+ }+ }+ }++ /// <summary>+ /// The size a layer's picture takes on screen, in device pixels (0 while unknown): where a frame of 16-bit samples is+ /// rendered; palette indices are rendered at their own size and scaled by WPF. A change redraws a 16-bit frame.+ /// </summary>+ public void SetTargetSize(FrameLayer layer, int width, int height)+ {+ if (_targets[(int)layer] != (width, height))+ {+ _targets[(int)layer] = (width, height);+ RebuildIfScreenSized();+ }+ }++ private void RebuildIfScreenSized()+ {+ if (_source is { Format: FrameFormat.Half })+ {+ Rebuild();+ }+ }+/// <summary>Sets how a layer is coloured and whether it is rendered at all; the shown frame is redrawn.</summary>/// <param name="layer">The plane.</param>/// <param name="lut">The colours (<see cref="ColorLut.Grey"/> for greyscale).</param>@@ -141,29 +201,45 @@ public sealed class FramePresenter}/// <summary>- /// A picture of the source's size, or null when Windows has no memory for it (the bitmap is a shared section, which- /// fails at the commit limit as MILERR_WIN32ERROR; it took the application down on 2026-10-19 after a run had- /// filled the memory): logged as an error, the picture then stays empty until a source with a new shape comes.+ /// A picture of that many pixels at that resolution, or null when Windows has no memory for it (the bitmap is a shared+ /// section, which fails at the commit limit as MILERR_WIN32ERROR; it took the application down on 2026-10-19 after a+ /// run had filled the memory): logged as an error, the picture then stays empty until a source with a new shape comes./// </summary>- private static WriteableBitmap? NewBitmap(IFrameSource source)+ private static WriteableBitmap? NewBitmap(int width, int height, double dpiX, double dpiY){try{- return new WriteableBitmap(source.Width, source.Height, 96, 96, PixelFormats.Bgr32, null);+ return new WriteableBitmap(width, height, dpiX, dpiY, PixelFormats.Bgr32, null);}catch (Exception ex) when (ex is COMException or OutOfMemoryException){- Logger.Error(ex, "No memory for a preview picture of {Width}×{Height}: the picture stays empty", source.Width, source.Height);+ Logger.Error(ex, "No memory for a preview picture of {Width}×{Height}: the picture stays empty", width, height);return null;}}private void Rebuild(){- _job = _source == null ? null : new Job(_source, FieldBitmap, IntensityBitmap, [.. _settings]);+ _job = _source == null ? null : new Job(_source, FieldBitmap, IntensityBitmap, [.. _settings], [.. _targets], _ditherBits);Kick();}+ /// <summary>The layer's screen renderer for these sizes, made anew when they changed (logged); render thread.</summary>+ private ScreenRenderer Screen(FrameLayer layer, int sourceWidth, int sourceHeight, int width, int height)+ {+ ScreenRenderer? screen = _screens[(int)layer];+ if (screen == null || screen.SourceWidth != sourceWidth || screen.SourceHeight != sourceHeight || screen.TargetWidth != width || screen.TargetHeight != height)+ {+ screen = new ScreenRenderer(sourceWidth, sourceHeight, width, height);+ _screens[(int)layer] = screen;+ double scale = width / (double)sourceWidth;+ Logger.Debug("Preview {Layer}: 16-bit frames of {SourceWidth}×{SourceHeight} drawn at {Width}×{Height} screen pixels ({How})",+ layer, sourceWidth, sourceHeight, width, height,+ width == sourceWidth && height == sourceHeight ? "1:1" : scale < 1 ? $"{1 / scale:0.##}× smaller, each pixel the mean of the samples it covers" : $"{scale:0.##}× larger, blended between the nearest samples");+ }+ return screen;+ }+/// <summary>Marks a change and starts the render loop unless one is running (it re-checks the version before it ends).</summary>private void Kick(){@@ -222,14 +298,13 @@ public sealed class FramePresenterint height = job.Source.Height;Logger.Trace("Presenter render: frame {Frame} of {Source} (job {Job})", frame, job.Source.GetType().Name, job.GetHashCode());_renderClock.Start();- var locked = new List<(WriteableBitmap Bitmap, Int32Rect Rect)>(2);+ var locked = new List<(WriteableBitmap Bitmap, Int32Rect Rect, FrameLayer Layer, bool IsNew)>(2);try{foreach (FrameLayer layer in new[] { FrameLayer.Field, FrameLayer.Intensity }){LayerSettings settings = job.Settings[(int)layer];- WriteableBitmap? bitmap = job.Bitmaps[(int)layer];- if (!settings.Enabled || bitmap == null || !job.Source.Has(layer))+ if (!settings.Enabled || !job.Source.Has(layer) || (job.Indices != null && job.Bitmaps[(int)layer] == null)){continue;}@@ -240,40 +315,64 @@ public sealed class FramePresenter{continue;}+ (int outWidth, int outHeight) = job.Sizes[(int)layer];+ int[] pixels = job.Pixels[(int)layer] ??= new int[outWidth * outHeight];_colourClock.Start();if (job.Indices != null){// palette indices: the brightness was applied when the frame was captured, only the palette is looked up- FrameRenderer.RenderIndexed(job.Indices, width, height, settings.Lut, job.Pixels);+ FrameRenderer.RenderIndexed(job.Indices, width, height, settings.Lut, pixels);}else{- // 16-bit samples: every level of the gradient (a brightness new to the colours builds the layer's half table first)- FrameRenderer.Render(job.Halves, width, height, settings.Lut, layer, settings.Brightness, job.Pixels);+ // 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);}_colourClock.Stop();+ _shownSize = (outWidth, outHeight);// the copy into the bitmap runs here, on the pool thread, between a lock and an unlock on the UI thread// (2026-10-16): WritePixels did the 8 to 12 MB copy on the UI thread, over 100 ms of every second at eleven// frames. The back buffer's pointer and stride are read inside the lock call, on the UI thread: they are// 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+ // 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_writeClock.Start();- (IntPtr buffer, int stride) = _dispatcher.Invoke(() =>+ 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(() =>{- bitmap.Lock();- return (bitmap.BackBuffer, bitmap.BackBufferStride);+ 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))+ {+ target = NewBitmap(outWidth, outHeight, dpiX, dpiY);+ fresh = true;+ }+ if (target == null)+ {+ return ((WriteableBitmap?)null, false, IntPtr.Zero, 0);+ }+ target.Lock();+ return ((WriteableBitmap?)target, fresh, target.BackBuffer, target.BackBufferStride);}, DispatcherPriority.Render);- locked.Add((bitmap, new Int32Rect(0, 0, width, height)));- if (stride == width * 4)+ if (bitmap == null){- Marshal.Copy(job.Pixels, 0, buffer, width * height);+ _writeClock.Stop();+ continue;+ }+ locked.Add((bitmap, new Int32Rect(0, 0, outWidth, outHeight), layer, isNew));+ if (stride == outWidth * 4)+ {+ Marshal.Copy(pixels, 0, buffer, outWidth * outHeight);}else{- for (int y = 0; y < height; y++)+ for (int y = 0; y < outHeight; y++){- Marshal.Copy(job.Pixels, y * width, buffer + y * stride, width);+ Marshal.Copy(pixels, y * outWidth, buffer + y * stride, outWidth);}}_writeClock.Stop();@@ -285,10 +384,29 @@ public sealed class FramePresenter{_dispatcher.Invoke(() =>{- foreach ((WriteableBitmap bitmap, Int32Rect rect) in locked)+ bool replaced = false;+ foreach ((WriteableBitmap bitmap, Int32Rect rect, FrameLayer layer, bool isNew) in locked){bitmap.AddDirtyRect(rect);bitmap.Unlock();+ // a new 16-bit picture takes its place only while its source is still the one shown (a source of palette+ // indices set meanwhile has pictures of its own)+ if (isNew && ReferenceEquals(job.Source, _source))+ {+ if (layer == FrameLayer.Field)+ {+ FieldBitmap = bitmap;+ }+ else+ {+ IntensityBitmap = bitmap;+ }+ replaced = true;+ }+ }+ if (replaced)+ {+ BitmapsChanged?.Invoke(this, EventArgs.Empty);}}, DispatcherPriority.Render);}@@ -299,8 +417,8 @@ public sealed class FramePresenterif (++_renderCount % RenderLogInterval == 0){// the cost of one presented frame (copy, colouring, bitmap write), averaged; for judging the pipeline at full resolution- Logger.Debug("Preview: {Width}x{Height}, {Average:0.0} ms per frame over the last {Count} (copy out of the store {Copy:0.0}, colouring {Colour:0.0}, copy into the bitmap {Write:0.0}, all on the pool)",- width, height, _renderClock.Elapsed.TotalMilliseconds / RenderLogInterval, RenderLogInterval,+ Logger.Debug("Preview: {Width}x{Height} shown at {ShownWidth}x{ShownHeight}, {Average:0.0} ms per frame over the last {Count} (copy out of the store {Copy:0.0}, colouring {Colour:0.0}, copy into the bitmap {Write:0.0}, all on the pool)",+ width, height, _shownSize.Width, _shownSize.Height, _renderClock.Elapsed.TotalMilliseconds / RenderLogInterval, RenderLogInterval,_copyClock.Elapsed.TotalMilliseconds / RenderLogInterval, _colourClock.Elapsed.TotalMilliseconds / RenderLogInterval, _writeClock.Elapsed.TotalMilliseconds / RenderLogInterval);_renderClock.Reset();_copyClock.Reset();diff --git a/WaveDudeNext.WPF/Strings/Strings.DE.xaml b/WaveDudeNext.WPF/Strings/Strings.DE.xamlindex e7f2270..80cb93a 100644--- a/WaveDudeNext.WPF/Strings/Strings.DE.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.DE.xaml@@ -76,6 +76,12 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="MenuViewSamples">Vorschau_werte</s:String><s:String x:Key="MenuViewSamples16">_16-Bit-Gleitkomma</s:String><s:String x:Key="MenuViewSamples8">_8-Bit-Palettenindex (Helligkeit beim Start des Laufs festgelegt)</s:String>+ <s:String x:Key="MenuViewDither">Vorschau-Dit_hering</s:String>+ <s:String x:Key="MenuViewDitherOff">_Aus</s:String>+ <s:String x:Key="MenuViewDither10">_10 Bit pro Kanal</s:String>+ <s:String x:Key="MenuViewDither12">1_2 Bit pro Kanal</s:String>+ <s:String x:Key="MenuViewDither14">1_4 Bit pro Kanal</s:String>+ <s:String x:Key="MenuViewDither16">1_6 Bit pro Kanal</s:String><s:String x:Key="LanguageSystem">System</s:String><s:String x:Key="MenuSimulation">_Simulation</s:String><s:String x:Key="MenuSimulationRun">_Starten</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.EN.xaml b/WaveDudeNext.WPF/Strings/Strings.EN.xamlindex edb7708..ae33fb4 100644--- a/WaveDudeNext.WPF/Strings/Strings.EN.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.EN.xaml@@ -78,6 +78,12 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="MenuViewSamples">Preview _samples</s:String><s:String x:Key="MenuViewSamples16">_16-bit float</s:String><s:String x:Key="MenuViewSamples8">_8-bit palette index (brightness fixed when the run starts)</s:String>+ <s:String x:Key="MenuViewDither">Preview _dithering</s:String>+ <s:String x:Key="MenuViewDitherOff">_Off</s:String>+ <s:String x:Key="MenuViewDither10">_10 bits per channel</s:String>+ <s:String x:Key="MenuViewDither12">1_2 bits per channel</s:String>+ <s:String x:Key="MenuViewDither14">1_4 bits per channel</s:String>+ <s:String x:Key="MenuViewDither16">1_6 bits per channel</s:String><s:String x:Key="LanguageSystem">System</s:String><s:String x:Key="MenuSimulation">_Simulation</s:String><s:String x:Key="MenuSimulationRun">_Run</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.FR.xaml b/WaveDudeNext.WPF/Strings/Strings.FR.xamlindex 2ecfdae..0885a44 100644--- a/WaveDudeNext.WPF/Strings/Strings.FR.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.FR.xaml@@ -76,6 +76,12 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="MenuViewSamples">Éc_hantillons de l'aperçu</s:String><s:String x:Key="MenuViewSamples16">Flottant _16 bits</s:String><s:String x:Key="MenuViewSamples8">Index de palette _8 bits (luminosité fixée au départ du calcul)</s:String>+ <s:String x:Key="MenuViewDither">Tra_mage de l'aperçu</s:String>+ <s:String x:Key="MenuViewDitherOff">_Désactivé</s:String>+ <s:String x:Key="MenuViewDither10">_10 bits par canal</s:String>+ <s:String x:Key="MenuViewDither12">1_2 bits par canal</s:String>+ <s:String x:Key="MenuViewDither14">1_4 bits par canal</s:String>+ <s:String x:Key="MenuViewDither16">1_6 bits par canal</s:String><s:String x:Key="LanguageSystem">Système</s:String><s:String x:Key="MenuSimulation">_Simulation</s:String><s:String x:Key="MenuSimulationRun">_Lancer</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.NL.xaml b/WaveDudeNext.WPF/Strings/Strings.NL.xamlindex 8826df8..ae0db50 100644--- a/WaveDudeNext.WPF/Strings/Strings.NL.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.NL.xaml@@ -76,6 +76,12 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="MenuViewSamples">Voorbeeld_samples</s:String><s:String x:Key="MenuViewSamples16">_16-bits zwevende komma</s:String><s:String x:Key="MenuViewSamples8">_8-bits paletindex (helderheid vastgelegd bij de start van de run)</s:String>+ <s:String x:Key="MenuViewDither">Voorbeeld_dithering</s:String>+ <s:String x:Key="MenuViewDitherOff">_Uit</s:String>+ <s:String x:Key="MenuViewDither10">_10 bits per kanaal</s:String>+ <s:String x:Key="MenuViewDither12">1_2 bits per kanaal</s:String>+ <s:String x:Key="MenuViewDither14">1_4 bits per kanaal</s:String>+ <s:String x:Key="MenuViewDither16">1_6 bits per kanaal</s:String><s:String x:Key="LanguageSystem">Systeem</s:String><s:String x:Key="MenuSimulation">_Simulatie</s:String><s:String x:Key="MenuSimulationRun">_Starten</s:String>diff --git a/WaveDudeNext.WPF/Themes/Controls.xaml b/WaveDudeNext.WPF/Themes/Controls.xamlindex b29d950..f30334f 100644--- a/WaveDudeNext.WPF/Themes/Controls.xaml+++ b/WaveDudeNext.WPF/Themes/Controls.xaml@@ -52,6 +52,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</DrawingBrush><!-- ===================== window ===================== -->+ <!-- every window of the app is a class derived from Window, which an implicit style never reaches: each names this one+ (Style="{StaticResource {x:Type Window}}", 2026-10-23) --><Style TargetType="{x:Type Window}"><Setter Property="Background" Value="{DynamicResource WindowBackground}" /><Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />@@ -277,6 +279,9 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<StreamGeometry x:Key="IconPreviewFrames">M1.5,3.5 H14.5 V12.5 H1.5 Z M5.5,3.5 V12.5 M10.5,3.5 V12.5</StreamGeometry><!-- a quantisation staircase, the bit depth --><StreamGeometry x:Key="IconPreviewSamples">M1.5,14.5 V11.5 H4.5 V8.5 H7.5 V5.5 H10.5 V2.5 H14.5</StreamGeometry>+ <!-- a checkerboard in a frame, the dither -->+ <StreamGeometry x:Key="IconPreviewDither">M2.5,2.5 H13.5 V13.5 H2.5 Z</StreamGeometry>+ <StreamGeometry x:Key="IconPreviewDitherFill">M3,3 h2.5 v2.5 h-2.5 Z M8,3 h2.5 v2.5 h-2.5 Z M5.5,5.5 h2.5 v2.5 h-2.5 Z M10.5,5.5 h2.5 v2.5 h-2.5 Z M3,8 h2.5 v2.5 h-2.5 Z M8,8 h2.5 v2.5 h-2.5 Z M5.5,10.5 h2.5 v2.5 h-2.5 Z M10.5,10.5 h2.5 v2.5 h-2.5 Z</StreamGeometry><!-- a memory module --><StreamGeometry x:Key="IconFrameMemory">M2.5,4.5 H13.5 V11.5 H2.5 Z M4.5,11.5 V14 M7,11.5 V14 M9,11.5 V14 M11.5,11.5 V14 M5,7 H11 V9 H5 Z</StreamGeometry>diff --git a/WaveDudeNext/Rendering/ColorLut.cs b/WaveDudeNext/Rendering/ColorLut.csindex 6b58a1f..0f06e19 100644--- a/WaveDudeNext/Rendering/ColorLut.cs+++ b/WaveDudeNext/Rendering/ColorLut.cs@@ -48,11 +48,13 @@ public sealed class ColorLutprivate readonly double _blackLevel;private readonly bool _makeSymmetric;private readonly bool _reverse;- private HalfTableEntry? _fieldTable;- private HalfTableEntry? _intensityTable;+ private TableEntry<int>? _fieldTable;+ private TableEntry<int>? _intensityTable;+ private TableEntry<ulong>? _fieldDeepTable;+ private TableEntry<ulong>? _intensityDeepTable;/// <summary>A built half table and the brightness it was built for.</summary>- private sealed record HalfTableEntry(float Brightness, int[] Argb);+ private sealed record TableEntry<T>(float Brightness, T[] Table);private ColorLut(List<ColorStop> stops, bool invert, double blackLevel, bool makeSymmetric, bool reverse){@@ -146,28 +148,46 @@ public sealed class ColorLut/// </summary>/// <param name="layer">Which mapping: the signed field or the non-negative intensity.</param>/// <param name="brightness">The layer's gain, applied as in <see cref="FieldIndex"/> and <see cref="IntensityIndex(float, float)"/>.</param>- public int[] HalfTable(FrameLayer layer, float brightness)+ public int[] HalfTable(FrameLayer layer, float brightness) =>+ Cached(ref (layer == FrameLayer.Field ? ref _fieldTable : ref _intensityTable), layer, brightness,+ (r, g, b) => unchecked((int)0xFF000000) | (Round(r * 255.0) << 16) | (Round(g * 255.0) << 8) | Round(b * 255.0));++ /// <summary>+ /// The colours of <see cref="HalfTable"/> at 16 bits per channel, for the preview's dithering (2026-10-23): each channel+ /// 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="brightness">The layer's gain.</param>+ public ulong[] DeepHalfTable(FrameLayer layer, float brightness) =>+ Cached(ref (layer == FrameLayer.Field ? ref _fieldDeepTable : ref _intensityDeepTable), layer, 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){- ref HalfTableEntry? slot = ref layer == FrameLayer.Field ? ref _fieldTable : ref _intensityTable;- HalfTableEntry? cached = Volatile.Read(ref slot);+ TableEntry<T>? cached = Volatile.Read(ref slot);if (cached != null && cached.Brightness.Equals(brightness)){- return cached.Argb;+ return cached.Table;}- var table = new int[HalfValues];+ var table = new T[HalfValues];const int Blocks = 16;Parallel.For(0, Blocks, block =>{for (int bits = block * (HalfValues / Blocks); bits < (block + 1) * (HalfValues / Blocks); bits++){double value = (double)BitConverter.UInt16BitsToHalf((ushort)bits);- table[bits] = ColorOf(layer == FrameLayer.Field ? FieldPosition(value, brightness) : IntensityPosition(value, brightness));+ (double r, double g, double b) = LevelsAt(layer == FrameLayer.Field ? FieldPosition(value, brightness) : IntensityPosition(value, brightness));+ table[bits] = pack(r, g, b);}});- Volatile.Write(ref slot, new HalfTableEntry(brightness, table));+ Volatile.Write(ref slot, new TableEntry<T>(brightness, table));return table;}+ private static int Round(double value) => (int)Math.Round(value, MidpointRounding.AwayFromZero);+/// <summary>A field sample's position on the gradient: <c>(clamp(value · brightness, −1, 1) + 1) / 2</c>, NaN in the middle.</summary>private static double FieldPosition(double value, float brightness){@@ -179,8 +199,8 @@ public sealed class ColorLutprivate static double IntensityPosition(double value, float brightness) =>value > 0.0 ? Math.Clamp(Math.Sqrt(value) * brightness, 0.0, 1.0) : 0.0;- /// <summary>The gradient at a position through the display options (the order of <see cref="Build"/>), as an opaque ARGB int.</summary>- private int ColorOf(double position)+ /// <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){if (_makeSymmetric){@@ -191,19 +211,18 @@ public sealed class ColorLutposition = 1.0 - position;}(double r, double g, double b) = ColorScheme.Evaluate(_stops, position);- return unchecked((int)0xFF000000) | (Level(r) << 16) | (Level(g) << 8) | Level(b);+ return (Level(r), Level(g), Level(b));}- /// <summary>One channel (0..255, unrounded) through invert and black level, rounded to the nearest level (half away from zero).</summary>- private int Level(double channel)+ /// <summary>One channel (0..255, unrounded) through invert and black level, as a fraction 0..1.</summary>+ private double Level(double channel){double level = channel / 255.0;if (_invert){level = 1.0 - level;}- level = Math.Clamp(level * (1.0 - _blackLevel) + _blackLevel, 0.0, 1.0);- return (int)Math.Round(level * 255.0, MidpointRounding.AwayFromZero);+ return Math.Clamp(level * (1.0 - _blackLevel) + _blackLevel, 0.0, 1.0);}/// <summary>diff --git a/WaveDudeNext/Rendering/ScreenRenderer.cs b/WaveDudeNext/Rendering/ScreenRenderer.csnew file mode 100644index 0000000..ee69a4d--- /dev/null+++ b/WaveDudeNext/Rendering/ScreenRenderer.cs@@ -0,0 +1,269 @@+// 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.Collections.Concurrent;+using System.Numerics.Tensors;+using System.Runtime.InteropServices;+using WaveDudeNext.Runs;++namespace WaveDudeNext.Rendering;++/// <summary>+/// How one axis of a picture is resampled from the samples to the screen: for each target pixel the first sample it+/// takes and the weights of the samples from there on, which sum to 1. Shrinking averages the samples a target pixel+/// covers, each weighted by how much of it the pixel covers (a box over the pixel's footprint); enlarging blends the+/// two samples nearest the pixel's centre linearly; the same count copies. Immutable; any thread.+/// </summary>+public sealed class ResampleAxis+{+ private readonly int[] _first;+ private readonly int[] _offsets;+ private readonly float[] _weights;++ /// <param name="source">Samples along the axis, at least 1.</param>+ /// <param name="target">Pixels along the axis on screen, at least 1.</param>+ public ResampleAxis(int source, int target)+ {+ ArgumentOutOfRangeException.ThrowIfLessThan(source, 1);+ ArgumentOutOfRangeException.ThrowIfLessThan(target, 1);+ Source = source;+ Target = target;+ _first = new int[target];+ _offsets = new int[target + 1];+ var weights = new List<float>(target * 2);+ double scale = source / (double)target;+ for (int t = 0; t < target; t++)+ {+ _offsets[t] = weights.Count;+ if (target == source)+ {+ _first[t] = t;+ weights.Add(1f);+ }+ else if (target < source)+ {+ // the footprint [lo, hi) in samples; each sample weighs the part of it inside, the edges partly+ double lo = t * scale;+ double hi = (t + 1) * scale;+ int first = (int)Math.Floor(lo);+ int last = Math.Min(source - 1, (int)Math.Ceiling(hi) - 1);+ _first[t] = first;+ for (int i = first; i <= last; i++)+ {+ weights.Add((float)((Math.Min(hi, i + 1) - Math.Max(lo, i)) / scale));+ }+ }+ else+ {+ // the pixel's centre in sample coordinates (a sample's centre at i + 0.5); the ends hold the outer samples+ double u = (t + 0.5) * scale - 0.5;+ if (u <= 0.0 || source == 1)+ {+ _first[t] = 0;+ weights.Add(1f);+ }+ else if (u >= source - 1)+ {+ _first[t] = source - 1;+ weights.Add(1f);+ }+ else+ {+ int i = (int)Math.Floor(u);+ float f = (float)(u - i);+ _first[t] = i;+ weights.Add(1f - f);+ weights.Add(f);+ }+ }+ }+ _offsets[target] = weights.Count;+ _weights = [.. weights];+ }++ /// <summary>Samples along the axis.</summary>+ public int Source { get; }++ /// <summary>Pixels along the axis on screen.</summary>+ public int Target { get; }++ /// <summary>The weights of target pixel <paramref name="target"/>, for the samples from <paramref name="first"/> on.</summary>+ public ReadOnlySpan<float> WeightsOf(int target, out int first)+ {+ first = _first[target];+ return _weights.AsSpan(_offsets[target], _offsets[target + 1] - _offsets[target]);+ }+}++/// <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+/// 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+/// in parallel blocks.+/// </summary>+public sealed class ScreenRenderer+{+ /// <summary>The dithering depths offered: 8 bits per channel plus an even number of bits a Bayer matrix of 2, 4, 8 or 16 cells a side carries.</summary>+ public static IReadOnlyList<int> DitherDepths { get; } = [10, 12, 14, 16];++ private readonly ResampleAxis _x;+ private readonly ResampleAxis _y;+ private readonly float[] _rows;++ /// <param name="sourceWidth">Samples per row of the plane.</param>+ /// <param name="sourceHeight">Rows of the plane.</param>+ /// <param name="targetWidth">The picture's width on screen, in device pixels.</param>+ /// <param name="targetHeight">The picture's height on screen, in device pixels.</param>+ public ScreenRenderer(int sourceWidth, int sourceHeight, int targetWidth, int targetHeight)+ {+ _x = new ResampleAxis(sourceWidth, targetWidth);+ _y = new ResampleAxis(sourceHeight, targetHeight);+ _rows = new float[sourceHeight * targetWidth];+ }++ /// <summary>Samples per row of the plane.</summary>+ public int SourceWidth => _x.Source;++ /// <summary>Rows of the plane.</summary>+ public int SourceHeight => _y.Source;++ /// <summary>The picture's width on screen.</summary>+ public int TargetWidth => _x.Target;++ /// <summary>The picture's height on screen.</summary>+ public int TargetHeight => _y.Target;++ /// <summary>+ /// Renders <paramref name="values"/> (<see cref="SourceWidth"/> × <see cref="SourceHeight"/>, row-major) into+ /// <paramref name="pixels"/> (<see cref="TargetWidth"/> × <see cref="TargetHeight"/> packed BGRA32, row-major).+ /// </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="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)+ {+ if (ditherBits != 0 && !DitherDepths.Contains(ditherBits))+ {+ throw new ArgumentOutOfRangeException(nameof(ditherBits), ditherBits, "Dithering takes 0 (none), 10, 12, 14 or 16 bits.");+ }+ int sourceWidth = _x.Source;+ int targetWidth = _x.Target;+ float[] rows = _rows;+ // rows: every sample row to the screen's width+ Parallel.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);+ Span<float> target = rows.AsSpan(y * targetWidth, targetWidth);+ for (int t = 0; t < targetWidth; t++)+ {+ ReadOnlySpan<float> weights = _x.WeightsOf(t, out int first);+ float sum = 0f;+ for (int k = 0; k < weights.Length; k++)+ {+ sum += weights[k] * line[first + k];+ }+ target[t] = sum;+ }+ }+ return 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[] 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) =>+ {+ for (int y = block.Item1; y < block.Item2; y++)+ {+ ReadOnlySpan<float> weights = _y.WeightsOf(y, out int first);+ TensorPrimitives.Multiply(rows.AsSpan(first * targetWidth, targetWidth), weights[0], buffers.Values);+ for (int k = 1; k < weights.Length; k++)+ {+ TensorPrimitives.MultiplyAdd(rows.AsSpan((first + k) * targetWidth, targetWidth), weights[k], 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);+ if (table != null)+ {+ for (int x = 0; x < targetWidth; x++)+ {+ target[x] = table[bits[x]];+ }+ }+ else+ {+ ReadOnlySpan<int> row = thresholds.AsSpan((y & (side - 1)) * side, side);+ for (int x = 0; x < targetWidth; x++)+ {+ ulong color = deep![bits[x]];+ int threshold = row[x & (side - 1)];+ target[x] = unchecked((int)0xFF000000) | (Dither((int)(color >> 32) & 0xFFFF, threshold) << 16)+ | (Dither((int)(color >> 16) & 0xFFFF, threshold) << 8) | Dither((int)color & 0xFFFF, threshold);+ }+ }+ }+ return buffers;+ }, _ => { });+ }++ /// <summary>+ /// One channel to 8 bits: <paramref name="level"/> is the level times 256 (<see cref="ColorLut.DeepHalfTable"/>), its+ /// high byte the 8-bit level, which goes one up where the fraction in the low byte reaches the pixel's threshold.+ /// </summary>+ private static int Dither(int level, int threshold) => (level >> 8) + ((level & 0xFF) * 2 >= threshold ? 1 : 0);++ /// <summary>+ /// The thresholds of the Bayer matrix for <paramref name="bits"/>: the 2^e cells of a matrix 2^(e/2) a side (e the bits+ /// beyond 8) in the order of the recursive Bayer construction, cell value B as <c>(2B + 1) · 2^(8−e)</c> on the scale of+ /// twice the fraction (0..510), so a fraction f in 256ths goes up in round(f · 2^e / 256) of the 2^e cells: the+ /// fraction to e bits, spread over the matrix. Row-major.+ /// </summary>+ /// <param name="bits">One of <see cref="DitherDepths"/>.</param>+ public static int[] BayerThresholds(int bits)+ {+ int extra = bits - 8;+ int side = 1 << (extra / 2);+ int[] matrix = [0];+ for (int size = 1; size < side; size *= 2)+ {+ var next = new int[4 * size * size];+ for (int y = 0; y < size; y++)+ {+ for (int x = 0; x < size; x++)+ {+ int value = 4 * matrix[y * size + x];+ next[y * 2 * size + x] = value;+ next[y * 2 * size + x + size] = value + 2;+ next[(y + size) * 2 * size + x] = value + 3;+ next[(y + size) * 2 * size + x + size] = value + 1;+ }+ }+ matrix = next;+ }+ return [.. matrix.Select(value => (2 * value + 1) << (8 - extra))];+ }+}diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.csindex 717d71e..fce95d2 100644--- a/_tools/library_check/Program.cs+++ b/_tools/library_check/Program.cs@@ -649,6 +649,24 @@ internal static class Program}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)");}+ // the preview's 16-bit path: resampled to the picture's size on screen, coloured, dithered or not+ foreach ((int tw, int th, int bits) in new[] { (w, h, 0), (w, h, 12), (w * 10 / 21, h * 10 / 21, 0), (w * 10 / 21, h * 10 / 21, 16), (w * 3 / 2, h * 3 / 2, 16) })+ {+ var screen = new ScreenRenderer(w, h, tw, th);+ var shown = new int[tw * th];+ for (int i = 0; i < 30; i++)+ {+ screen.Render(intensity, lut, FrameLayer.Intensity, 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);+ }+ Console.WriteLine($" screen {tw}x{th}{(bits == 0 ? "" : $", dithered from {bits} bits"),-26} {clock.Elapsed.TotalMilliseconds / Runs,6:0.00} ms per layer");+ }stop.Cancel();if (run != null){@@ -1802,6 +1820,131 @@ internal static class ProgramColorLut lifted = ColorLut.Build(scheme, blackLevel: 0.5);Check(lifted.ColorAt(0).G == 127 && ((lifted.HalfTable(FrameLayer.Intensity, 1f)[0] >> 8) & 0xFF) == 128,"black level 0.5 lifts a 0 channel to 127 in the palette (truncated, as in Python) and to 128 in the half table (rounded)");+ CheckScreenRenderer(inferno);+ }++ /// <summary>The preview's 16-bit path (2026-10-23): resampling in value space to the screen's size, the 16-bit colours, the Bayer dither.</summary>+ private static void CheckScreenRenderer(ColorLut lut)+ {+ // the axes: every target pixel's weights sum to 1, shrinking covers each sample once in all, the same size copies+ bool sums = true;+ bool covered = true;+ foreach ((int source, int target) in new[] { (1920, 960), (1920, 1000), (37, 5), (64, 640), (64, 97), (5, 5), (1, 7), (7, 1) })+ {+ var axis = new ResampleAxis(source, target);+ var coverage = new double[source];+ for (int t = 0; t < target; t++)+ {+ ReadOnlySpan<float> weights = axis.WeightsOf(t, out int first);+ double sum = 0;+ for (int k = 0; k < weights.Length; k++)+ {+ sum += weights[k];+ coverage[first + k] += weights[k];+ }+ sums &= Math.Abs(sum - 1) < 1e-5 && first >= 0 && first + weights.Length <= source;+ }+ double scale = source / (double)target;+ covered &= target > source || coverage.All(c => Math.Abs(c - 1 / scale) < 1e-4);+ }+ Check(sums && covered, "resampling axes: each pixel's weights sum to 1 within the samples; shrinking weighs every sample alike (shrink, enlarge, odd ratios, 1:1, one sample)");+ var copy = new ResampleAxis(9, 9);+ var half = new ResampleAxis(8, 4);+ var twice = new ResampleAxis(2, 4);+ Check(copy.WeightsOf(4, out int c4).SequenceEqual([1f]) && c4 == 4 && half.WeightsOf(1, out int h1).SequenceEqual([0.5f, 0.5f]) && h1 == 2+ && twice.WeightsOf(1, out int t1).SequenceEqual([0.75f, 0.25f]) && t1 == 0 && twice.WeightsOf(0, out int t0).SequenceEqual([1f]) && t0 == 0,+ "resampling axes: 1:1 copies, halving averages pairs, doubling blends a quarter of the neighbour at the pixel's centre and holds the edge");+ // the frames: at the samples' size without dithering, the screen picture is the half table's, bit for bit+ var rng = new Random(5);+ int w = 61;+ int h = 45;+ var plane = new Half[w * h];+ for (int i = 0; i < plane.Length; i++)+ {+ plane[i] = (Half)(rng.NextDouble() * 0.2);+ }+ var direct = new int[w * h];+ FrameRenderer.Render(plane, w, h, lut, FrameLayer.Intensity, 3f, direct);+ var screen = new int[w * h];+ new ScreenRenderer(w, h, w, h).Render(plane, lut, FrameLayer.Intensity, 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)+ 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);+ 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;+ // the sums run in single precision (fused or not, by the machine): the half they round to may be the neighbour+ int 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");+ // the field's crest and trough average to zero, the gradient's middle, not to a mix of their colours+ var wave = new Half[4 * 2];+ for (int i = 0; i < wave.Length; i++)+ {+ wave[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");+ // 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);+ bool deepRounds = Enumerable.Range(0, ColorLut.HalfValues).All(bits =>+ {+ int argb = lut.HalfTable(FrameLayer.Intensity, 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+ && Math.Abs((argb & 0xFF) - (d & 0xFFFF) / 256.0) <= 0.5 + 1 / 256.0;+ });+ Check(deepRounds, "the 16-bit table rounds to the 8-bit one: each channel within half a level of it");+ Half dark = (Half)0.0007f; // Inferno's dark start: blue between two levels+ ulong colour = deep[BitConverter.HalfToUInt16Bits(dark)];+ int blue16 = (int)(colour & 0xFFFF);+ bool dithers = true;+ var detail = new List<string>();+ foreach (int bits in ScreenRenderer.DitherDepths)+ {+ int side = 1 << ((bits - 8) / 2);+ int[] thresholds = ScreenRenderer.BayerThresholds(bits);+ bool permutation = thresholds.Length == side * side && thresholds.Distinct().Count() == thresholds.Length+ && thresholds.All(t => t > 0 && t < 512 && (t >> (8 - (bits - 8))) % 2 == 1);+ var 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);+ 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)+ double expected = (blue16 >> 8) + Math.Floor((blue16 & 0xFF) / (double)(1 << (16 - bits)) + 0.5) / (1 << (bits - 8));+ bool twoLevels = blues.All(b => b == blue16 >> 8 || b == (blue16 >> 8) + 1);+ bool tiles = Enumerable.Range(0, 32 * 32).All(i => blues[i] == blues[(i / 32 % side) * 32 + i % 32 % side]);+ dithers &= permutation && twoLevels && tiles && Math.Abs(mean - expected) < 1e-9;+ detail.Add($"{bits}: mean {mean:0.####} for {blue16 / 256.0:0.####}");+ }+ var 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)]),+ "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]);+ }+ catch (ArgumentOutOfRangeException)+ {+ refused = true;+ }+ Check(refused, "a dithering depth other than 0, 10, 12, 14 or 16 is refused");}private static void CheckColorSchemes()