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 window stays responsive during a run; logging levels; a UI thread watchdog
Alexander Graef4cbc18834c86
diff --git a/CLAUDE.md b/CLAUDE.mdindex 1c3ddec..1f8f286 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -44,8 +44,11 @@ WPF shell as it stands:(persisted in settings); the native title bar is darkened via DWM. Use `DynamicResource` for everytheme brush.- Logging: NLog; `Info` and up reach the status bar (`Logging/StatusBarTarget`, Warn/Error coloured),- everything reaches the Messages pane in every build (2026-10-14; the pane hides Trace and Debug by default- in Release, its level toggles show them) and the log file next to the exe (Debug builds; Info and up in+ everything reaches the Messages pane in a Debug build, Debug and up in Release (2026-10-16, the user's rule:+ Trace is a Debug-build affair, the presenter traces every frame it draws and a Release build must not pay for+ entries nobody can see; with no rule for Trace, NLog skips the call; the pane hides Debug by default in Release+ and has no Trace toggle there, its level toggles show the rest) and the log file next to the exe (Debug builds+ everything; Debug and up in Release since 2026-10-16, the user's rule: a bug report comes with the decision lines) and the log file next to the exe (Debug builds; Info and up inRelease). Debug lines say what the application decides: scratch requests and their reason, stale marks,automatic re-runs postponed or skipped and why, discarded runs, every export step (path, format, range,the run decision, each target's colours, outline and boxes). Keep adding them where a decision is made.@@ -97,7 +100,41 @@ WPF shell as it stands:other physics: half the cells per wavelength; the only lever for CPU stepping, which none of the threetouches) and an automatic mode.- **Simulation** (2026-10-09): menu Simulation > Run (F5), Pause/Resume (F6), Stop (Shift+F5, also- Esc). `OnRun` decodes the scene image (`Rendering/SceneImageLoader`, WPF decoders → BGRA bytes),+ Esc). **The window stays responsive during a run** (2026-10-16, after the user found every click and key+ delivered only after the run). The cause, found by `MainWindow.Watchdog.cs`: the run posted its progress at+ normal priority, and since a new frame count was posted the moment the last was handled, one was always pending;+ WPF serves input only when nothing above input priority waits (Input ranks below Normal, DataBind and Render), so+ input starved for the whole run. The fix: the run's context is+ `new DispatcherSynchronizationContext(Dispatcher, DispatcherPriority.Background)`. After it the watchdog logs no+ late tick during a run, and the true key latency (below) is 0 to 31 ms during a full-HD GPU run with Play on.+ **A day was then spent chasing a latency that was mostly the harness**: a timeline-jump measure polled the+ readout through UI Automation every 10 ms, and a UIA query walks the whole element tree through the UI thread it+ measures (5000 to 8000 cross-thread calls a second); the "120 to 470 ms during a run" it reported never came back+ once keys were posted without polling. Lesson, the user's rule: **measure input latency inside the app**+ (`PreviewKeyDown` sees the message's own time stamp; the watchdog logs a second's keys when the worst waited over+ 150 ms) and never poll UIA while measuring. Two more traps met on the way: subscribing+ `CompositionTarget.Rendering` to count render passes forces a pass every vertical sync (sixty a second of pure+ measurement load), and `WriteableBitmap.BackBuffer` is a dependency property, readable on the UI thread only (read+ from the pool it threw on every frame and the preview silently stopped updating; 291 errors in the log before+ anyone read it). Changes that stayed because the app's own counters showed the work: the run's **one heartbeat**+ (steps, frames and the probe batch in a single post at most 30 a second, `SimulationRun.PublishHeartbeat`; before,+ three posts on three schedules were about 60 operations a second, each buying WPF a render pass); the presenter+ copies into the bitmap on the pool thread between a lock and an unlock on the UI thread (the pointer taken inside+ the lock call), both layers unlocked in one call; the timeline's ticks and labels are a cached frozen drawing and+ its labels and pens are cached (a draw fell from 3 ms to 0.4); the probe graph boxes cache their formatted text+ and curve pens (2.3 ms to 1.1 per draw); and **the shown position advances only while the presenter is free**+ (`FramePresenter.IsBusy`, in the playback tick and the live follow): the clock keeps counting, so time stays right,+ and the overlays and the bar are redrawn once per picture that can be shown instead of sixty times a second for+ pictures that never appear (this canvas presents 11 to 14 a second, colouring 61 ms of a 2880 x 1080 frame on the+ pool, which is the next thing worth speeding up). Tried and reverted: the playback timer and the pixel copy at+ background priority (a mouse scrub then lagged behind every move), a fixed ten-frames-a-second cap on the presenter+ while the engine runs (the live follow stuttered), a yield to input priority after each presented frame (no+ effect). The watchdog stays (the user: a user would never know about a stall otherwise): two 100 ms timers at+ normal and input priority gather late ticks into episodes and log one line each, a Warn from a second on (it+ reaches the status bar), a Debug line below that. The dispatcher-operation accounting and the per-draw cost+ scopes (`UiCost`) that found the day's numbers were removed again as noise; the notes above say what to measure. The+ one episode it still reports is about 350 ms at start-up while the scratch runner builds its OpenCL engine+ (not investigated). `OnRun` decodes the scene image (`Rendering/SceneImageLoader`, WPF decoders → BGRA bytes),snapshots the project into a `RunSpec`, checks the cache drive, creates the `FrameStore` andstarts a `SimulationRun` posting to the dispatcher's `SynchronizationContext`; the right statusbar item shows `State: done / total steps, engine` (`RunStatusConverter`, AutomationIddiff --git a/README.md b/README.mdindex e69de29..10cc449 100644--- a/README.md+++ b/README.md@@ -0,0 +1,79 @@+# WaveDude Next++<!-- Anchor for the real text. Facts only, checked against the code on 2026-10-16. Rewrite freely. -->++What it is+- 2D wave simulator for Windows; rewrite of Wave Dude 2D (Jeroen Vleggaar, Huygens Optics).+- Engine, probes and colour schemes descend from his program; UI, project format, live preview are new.+- GPL-3.0-or-later, same as the original.++<!-- screenshot 1: main window, finished run, field + intensity, probes with graphs. docs/main.png -->++Live preview+- Any edit recomputes the frame shown (GPU: usually under a second); after 1.5 s of quiet the full run is redone in the background.+- A running automatic run is cancelled and restarted on an edit.+- Probes update from the recomputed frame, no full run needed.+- Run button = render all frames ahead of time, then scrubbing is instant.+- Runs stay in RAM (budget: free RAM minus 2 GB, cap selectable 10..100 %); beyond that a temp file.+- Full HD, 2500 steps: about 5 s on an RTX 2080.+- Reduced preview for weak hardware: half/quarter resolution, half/quarter of the frames, 8-bit samples. Simulation and export unaffected.++Scene+- An image. Red = refractive index × 100 (100 = 1.0, 150 = 1.5; clamped 0.9..10), green = emitting pixel, blue = damping. Same rules as the original.+- Embedded in the project; the file is watched and re-embedded when it changes.+- Absorbing edge of configurable width.++Sources+- Point or composite array; continuous or pulsed; frequency, amplitude, phase, start/stop step.+- Arrays: pitch, rows/columns, rotation (handle or value), random offsets per emitter.+- Wavelength in pixels shown next to the frequency.++Probes+- Point or line; amplitude (field) or value / integrated value (intensity); start step.+- Graph box drawn on the preview; draggable, resizable, snaps to the probe.++Timeline+- Scrub, play 0.25x..4x (typed values too), step keys, in/out points (export range only), loop.+- Sources and probes draggable in both pictures; click empty space deselects.++Export+- PNG sequence, JPEG sequence, MPG (MPEG-1, I-frames only), AVI uncompressed (OpenDML, >4 GB ok), MP4 H.264 (Windows Media Foundation), MOV Animation codec (lossless RGB; Premiere/FinalCut/Resolve).+- Field, intensity or both; probe graphs and markers burned in (switchable); single frame export.+- Uses the existing run; starts one if needed. No automatic exports.++Project+- One `.wdproj` XML file; scene image and colour schemes embedded.+- Seed in the project: same project, same video.+- Wave Dude 2D `configuration.json` imports.++Colour schemes+- 23 built in (the original gradients, simplified to their bends); own schemes live in the project; colour picker.++Misc+- OpenCL GPU engine, CPU fallback; 9-point or 4th-order Laplacian.+- Keyboard-accessible throughout; dockable panes; dark/light theme; English, German, French, Dutch.+- Help > About shows version, credits, license.++Status+- No release, no installer, no docs yet.+- Planned: portable archive + signed installer; documentation file; curated examples (Jeroen); original version hosted as preserved assets.+- Later: CSV export of probe data; built-in shapes instead of painted PNGs; Avalonia port (Linux/Mac/browser).++<!-- screenshot 2: colour scheme editor with picker, or probe graphs close up. docs/editor.png -->++Build+```+git clone https://github.com/graealex/WaveDude+dotnet publish WaveDudeNext.WPF/WaveDudeNext.WPF.csproj -p:PublishProfile=SingleFile+```+- .NET 10 SDK to build; Windows 10+, .NET 10 desktop runtime to run; OpenCL driver optional; MP4 needs Media Foundation (Media Feature Pack on N editions).+- No external frameworks besides Media Foundation.++Credits (as in the source header)+- JJM Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026+ <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>+- Manuel (0x23, Diffraction Limited), author of WaveSimulator2D+ <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>++License+- GPL-3.0-or-later; full text in LICENSE.md.diff --git a/WaveDudeNext.WPF/App.xaml.cs b/WaveDudeNext.WPF/App.xaml.csindex e911dba..37691d7 100644--- a/WaveDudeNext.WPF/App.xaml.cs+++ b/WaveDudeNext.WPF/App.xaml.cs@@ -107,13 +107,18 @@ public partial class App : Application// (2026-10-14, the user: a Release build had nothing to show there, the messages never got in)var messages = new MessagesTarget { Name = "messages" };config.AddTarget(messages);- config.AddRule(LogLevel.Trace, LogLevel.Fatal, messages);#if DEBUG+ config.AddRule(LogLevel.Trace, LogLevel.Fatal, messages);config.AddRule(LogLevel.Trace, LogLevel.Fatal, fileTarget);config.AddRule(LogLevel.Trace, LogLevel.Fatal, new DebuggerTarget("debugger") { Layout = DebugLayout });config.AddRule(LogLevel.Trace, LogLevel.Fatal, new ColoredConsoleTarget("console") { Layout = DebugLayout });#else- config.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget);+ // Trace is a Debug-build affair (2026-10-16, the user's rule): the presenter traces every frame it draws, and a+ // Release build must not pay for entries nobody can see; with no rule for Trace, NLog skips the call outright+ config.AddRule(LogLevel.Debug, LogLevel.Fatal, messages);+ // the file carries everything the build logs (the user's rule, 2026-10-16): a bug report comes with the+ // decision lines without anyone opening the Messages pane+ config.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget);#endifLogManager.Configuration = config;diff --git a/WaveDudeNext.WPF/Controls/ProbeGraphDrawing.cs b/WaveDudeNext.WPF/Controls/ProbeGraphDrawing.csindex 3bbc0e3..2658b93 100644--- a/WaveDudeNext.WPF/Controls/ProbeGraphDrawing.cs+++ b/WaveDudeNext.WPF/Controls/ProbeGraphDrawing.cs@@ -139,13 +139,43 @@ public static class ProbeGraphDrawing}geometry.Freeze();dc.PushClip(new RectangleGeometry(new Rect(layout.PlotX, layout.PlotY, layout.PlotWidth, layout.PlotHeight)));- dc.DrawGeometry(null, new Pen(CurveBrush, layout.LineWidth) { LineJoin = PenLineJoin.Round }, geometry);+ dc.DrawGeometry(null, CurvePen(layout.LineWidth), geometry);dc.Pop();}/// <summary>One line of text in the graph font.</summary>- public static FormattedText Text(string text, double size, Brush brush, double pixelsPerDip) =>- new(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, Typeface, size, brush, pixelsPerDip) { MaxLineCount = 1 };+ // cached (2026-10-16): built afresh, a draw of the boxes cost over 2 ms per picture, mostly FormattedText, and the+ // boxes are drawn on every position change and probe update; the readout changes per frame, so the cache is+ // cleared when it grows large; the culture is part of the key+ private static readonly Dictionary<(string Text, double Size, Brush Brush, double Dpi, string Culture), FormattedText> TextCache = new();+ private static readonly Dictionary<double, Pen> CurvePens = new();+ private const int TextCacheLimit = 4096;++ public static FormattedText Text(string text, double size, Brush brush, double pixelsPerDip)+ {+ var key = (text, size, brush, pixelsPerDip, CultureInfo.CurrentUICulture.Name);+ if (!TextCache.TryGetValue(key, out FormattedText? formatted))+ {+ if (TextCache.Count >= TextCacheLimit)+ {+ TextCache.Clear();+ }+ formatted = new FormattedText(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, Typeface, size, brush, pixelsPerDip) { MaxLineCount = 1 };+ TextCache[key] = formatted;+ }+ return formatted;+ }++ private static Pen CurvePen(double width)+ {+ if (!CurvePens.TryGetValue(width, out Pen? pen))+ {+ pen = new Pen(CurveBrush, width) { LineJoin = PenLineJoin.Round };+ pen.Freeze();+ CurvePens[width] = pen;+ }+ return pen;+ }private static T Freeze<T>(T freezable) where T : Freezable{diff --git a/WaveDudeNext.WPF/Controls/TimelineBar.cs b/WaveDudeNext.WPF/Controls/TimelineBar.csindex 29c1919..60f9e8c 100644--- a/WaveDudeNext.WPF/Controls/TimelineBar.cs+++ b/WaveDudeNext.WPF/Controls/TimelineBar.cs@@ -273,7 +273,8 @@ public sealed class TimelineBar : FrameworkElement{return;}- var pen = new Pen(TickBrush, 1.0);+ _dpi = VisualTreeHelper.GetDpi(this).PixelsPerDip; // once per draw, not per label+ Pen pen = PenFor(TickBrush);var bar = new Rect(0.5, BarTop + 0.5, w - 1.0, BarHeight - 1.0);dc.DrawRectangle(Background, pen, bar);@@ -296,42 +297,12 @@ public sealed class TimelineBar : FrameworkElementDrawBracket(dc, x0, bar, open: true);DrawBracket(dc, x1, bar, open: false);- // ticks and labels; the labelled interval is the smallest candidate that leaves room for its text+ // ticks and labels, from a cached drawing (2026-10-16): laid out afresh they cost over a millisecond per draw,+ // and the bar is drawn on every position change, sixty times a second during playback; the drawing is rebuilt+ // only when the width, the range, the brushes, the culture or the DPI changeif (Maximum > 0){- double pxPerFrame = TrackWidth / Maximum;- int major = TickCandidates[^1];- foreach (int candidate in TickCandidates)- {- if (candidate * pxPerFrame >= MinLabelSpacing)- {- major = candidate;- break;- }- }- int minor = major >= 10 ? major / 5 : major >= 2 ? 1 : 0;- if (minor > 0)- {- for (int f = 0; f <= Maximum; f += minor)- {- if (f % major != 0)- {- double x = Math.Round(XOf(f)) + 0.5;- dc.DrawLine(pen, new Point(x, bar.Top), new Point(x, bar.Top + 3));- }- }- }- for (int f = 0; f <= Maximum; f += major)- {- double x = Math.Round(XOf(f)) + 0.5;- dc.DrawLine(pen, new Point(x, bar.Top), new Point(x, bar.Top + 6));- FormattedText label = Label(f.ToString(CultureInfo.CurrentCulture), LabelBrush);- double lx = Math.Min(x + 2, w - label.Width - 1);- if (lx + label.Width <= Math.Round(XOf(Value)) - 4 || lx >= Math.Round(XOf(Value)) + 4 + PlayheadLabelWidth())- {- dc.DrawText(label, new Point(lx, 0));- }- }+ dc.DrawDrawing(TicksDrawing(w, bar, pen));}// the frame under the mouse@@ -345,7 +316,7 @@ public sealed class TimelineBar : FrameworkElement// the playhead: a line through the bar, a handle on top, the frame number next to itdouble px = Math.Round(XOf(Value)) + 0.5;- dc.DrawLine(new Pen(Foreground, 1.0), new Point(px, bar.Top), new Point(px, bar.Bottom));+ dc.DrawLine(PenFor(Foreground), new Point(px, bar.Top), new Point(px, bar.Bottom));var handle = new StreamGeometry();using (StreamGeometryContext g = handle.Open()){@@ -356,16 +327,15 @@ public sealed class TimelineBar : FrameworkElementdc.DrawGeometry(Foreground, null, handle);FormattedText playhead = Label(Value.ToString(CultureInfo.CurrentCulture), Foreground, bold: true);double tx = px + 8 + playhead.Width <= w ? px + 8 : px - 8 - playhead.Width;+ dc.DrawRectangle(Background, null, new Rect(tx - 3, 0, playhead.Width + 6, LabelRowHeight)); // over the tick labels under itdc.DrawText(playhead, new Point(tx, 0));if (IsKeyboardFocused){- dc.DrawRectangle(null, new Pen(AccentBrush, 1.0), new Rect(0.5, 0.5, w - 1, h - 1));+ dc.DrawRectangle(null, PenFor(AccentBrush), new Rect(0.5, 0.5, w - 1, h - 1));}}- private double PlayheadLabelWidth() => Label(Value.ToString(CultureInfo.CurrentCulture), Foreground, bold: true).Width + 8;-/// <summary>A bracket at x: a 2 px vertical bar with feet pointing into the range.</summary>private void DrawBracket(DrawingContext dc, double x, Rect bar, bool open){@@ -376,10 +346,95 @@ public sealed class TimelineBar : FrameworkElementdc.DrawRectangle(AccentBrush, null, new Rect(Math.Min(left, left + foot), bar.Bottom - 2, Math.Abs(foot) + 2, 2));}- private FormattedText Label(string text, Brush brush, bool bold = false) =>- new(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight,- bold ? new Typeface(LabelTypeface.FontFamily, FontStyles.Normal, FontWeights.SemiBold, FontStretches.Normal) : LabelTypeface,- 11.0, brush, VisualTreeHelper.GetDpi(this).PixelsPerDip);+ // the labels and pens are cached (2026-10-16): built afresh, a draw of the bar cost 3 ms, mostly FormattedText,+ // and the bar is drawn on every frame-count and position change; the cache is cleared when it grows large+ // (the playhead's label changes per frame) and when the culture or the DPI changes, which the key carries+ private readonly Dictionary<(string Text, bool Bold, Brush Brush, string Culture, double Dpi), FormattedText> _labels = new();+ private readonly Dictionary<Brush, Pen> _pens = new();+ private const int LabelCacheLimit = 2048;++ private double _dpi = 1;++ private FormattedText Label(string text, Brush brush, bool bold = false)+ {+ double dpi = _dpi;+ var key = (text, bold, brush, CultureInfo.CurrentUICulture.Name, dpi);+ if (!_labels.TryGetValue(key, out FormattedText? label))+ {+ if (_labels.Count >= LabelCacheLimit)+ {+ _labels.Clear();+ }+ label = new FormattedText(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight,+ bold ? new Typeface(LabelTypeface.FontFamily, FontStyles.Normal, FontWeights.SemiBold, FontStretches.Normal) : LabelTypeface,+ 11.0, brush, dpi);+ _labels[key] = label;+ }+ return label;+ }++ private DrawingGroup? _ticks;+ private (double Width, int Maximum, Brush Tick, Brush Label, string Culture, double Dpi) _ticksKey;++ /// <summary>The minor and major ticks with their labels as one frozen drawing, rebuilt only when its inputs change.</summary>+ private DrawingGroup TicksDrawing(double w, Rect bar, Pen pen)+ {+ var key = (w, Maximum, TickBrush, LabelBrush, CultureInfo.CurrentCulture.Name, _dpi);+ if (_ticks != null && key == _ticksKey)+ {+ return _ticks;+ }+ var group = new DrawingGroup();+ using (DrawingContext dc = group.Open())+ {+ // the labelled interval is the smallest candidate that leaves room for its text+ double pxPerFrame = TrackWidth / Maximum;+ int major = TickCandidates[^1];+ foreach (int candidate in TickCandidates)+ {+ if (candidate * pxPerFrame >= MinLabelSpacing)+ {+ major = candidate;+ break;+ }+ }+ int minor = major >= 10 ? major / 5 : major >= 2 ? 1 : 0;+ if (minor > 0)+ {+ for (int f = 0; f <= Maximum; f += minor)+ {+ if (f % major != 0)+ {+ double x = Math.Round(XOf(f)) + 0.5;+ dc.DrawLine(pen, new Point(x, bar.Top), new Point(x, bar.Top + 3));+ }+ }+ }+ for (int f = 0; f <= Maximum; f += major)+ {+ double x = Math.Round(XOf(f)) + 0.5;+ dc.DrawLine(pen, new Point(x, bar.Top), new Point(x, bar.Top + 6));+ FormattedText label = Label(f.ToString(CultureInfo.CurrentCulture), LabelBrush);+ dc.DrawText(label, new Point(Math.Min(x + 2, w - label.Width - 1), 0));+ }+ }+ group.Freeze();+ _ticks = group;+ _ticksKey = key;+ return group;+ }++ /// <summary>A frozen one-pixel pen of <paramref name="brush"/>, made once per brush (the theme brushes are shared instances).</summary>+ private Pen PenFor(Brush brush)+ {+ if (!_pens.TryGetValue(brush, out Pen? pen))+ {+ pen = new Pen(brush, 1.0);+ pen.Freeze();+ _pens[brush] = pen;+ }+ return pen;+ }// ---------------------------------------------------------------- mousediff --git a/WaveDudeNext.WPF/MainWindow.Simulation.cs b/WaveDudeNext.WPF/MainWindow.Simulation.csindex ef63020..63fbc6a 100644--- a/WaveDudeNext.WPF/MainWindow.Simulation.cs+++ b/WaveDudeNext.WPF/MainWindow.Simulation.cs@@ -18,6 +18,7 @@using System.IO;using System.Windows;using System.Windows.Input;+using System.Windows.Threading;using WaveDudeNext.Engine;using WaveDudeNext.Model;using WaveDudeNext.Runs;@@ -99,7 +100,11 @@ public partial class MainWindow}DiscardRun();FrameStore store = FrameStore.Create(FrameCache.NewPath(), spec.Shape, spec.Layers, spec.StoredFrameCount, spec.CaptureEvery, budget);- var run = new SimulationRun(spec, store, SynchronizationContext.Current, automatic);+ // the run's progress lands on the UI thread below input priority (2026-10-16): posted at normal priority, the+ // frame counts kept the input queue starved for the whole run, since a new one was posted the moment the last+ // was handled, and every click and key was delivered after the run (the watchdog's input-priority ticks were+ // late, the normal-priority ones on time)+ var run = new SimulationRun(spec, store, new DispatcherSynchronizationContext(Dispatcher, DispatcherPriority.Background), automatic);run.PropertyChanged += (_, args) =>{if (args.PropertyName == nameof(SimulationRun.State))diff --git a/WaveDudeNext.WPF/MainWindow.Watchdog.cs b/WaveDudeNext.WPF/MainWindow.Watchdog.csnew file mode 100644index 0000000..85ef9ab--- /dev/null+++ b/WaveDudeNext.WPF/MainWindow.Watchdog.cs@@ -0,0 +1,92 @@+// 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+// JJM Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>+// Manuel (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.Diagnostics;+using System.Windows.Threading;+using NLog;++namespace WaveDudeNext.WPF;++public partial class MainWindow+{+ /// <summary>How often the watchdog timers tick; a tick that comes much later than this is a stall.</summary>+ private const int WatchdogIntervalMs = 100;+ /// <summary>A tick this much later than due is a stall.</summary>+ private const int StallThresholdMs = 150;+ /// <summary>An episode this long is a warning (it reaches the status bar); shorter ones, the start-up compile among them, are Debug lines.</summary>+ private const double WarnEpisodeSeconds = 1.0;++ private readonly StallEpisode _normalStall = new("normal"), _inputStall = new("input");++ /// <summary>+ /// The UI thread watchdog (2026-10-16, after the user found the window unresponsive during a run): two timers,+ /// one at normal and one at input priority, each noting when its tick arrives more than <see cref="StallThresholdMs"/>+ /// late. A late normal tick means the thread itself was blocked (rendering waiting for a saturated GPU, a long+ /// handler, CPU starvation); a late input tick with the normal one on time means work above input priority is+ /// starving the input queue. Consecutive late ticks are one episode, logged as one line when the ticks are back+ /// on time: its length, the worst lateness, and the run's state when it began; an episode of a second or more is+ /// a warning (the user's call, 2026-10-16: a stall is a fault nobody would otherwise know about), shorter ones+ /// are Debug lines, so the start-up blip while the OpenCL engine compiles stays out of the status bar.+ /// </summary>+ private void StartUiWatchdog()+ {+ var normal = new DispatcherTimer(DispatcherPriority.Normal) { Interval = TimeSpan.FromMilliseconds(WatchdogIntervalMs) };+ normal.Tick += (_, _) => _normalStall.Tick(this);+ normal.Start();+ var input = new DispatcherTimer(DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(WatchdogIntervalMs) };+ input.Tick += (_, _) => _inputStall.Tick(this);+ input.Start();+ }++ /// <summary>One priority's stall bookkeeping: ticks are timed, late ones gathered into an episode, the episode logged once.</summary>+ private sealed class StallEpisode(string priority)+ {+ private long _last = Stopwatch.GetTimestamp();+ private long _began;+ private double _worstMs, _sumMs;+ private int _lateTicks;+ private string _state = "";++ public void Tick(MainWindow window)+ {+ long now = Stopwatch.GetTimestamp();+ double lateMs = (now - _last) * 1000.0 / Stopwatch.Frequency - WatchdogIntervalMs;+ _last = now;+ if (lateMs > StallThresholdMs)+ {+ if (_lateTicks == 0)+ {+ _began = now;+ _worstMs = 0;+ _sumMs = 0;+ _state = $"run {window.Run?.State.ToString() ?? "none"}, scratch frame computing: {window.IsComputingFrame}";+ }+ _lateTicks++;+ _sumMs += lateMs;+ _worstMs = Math.Max(_worstMs, lateMs);+ }+ else if (_lateTicks > 0)+ {+ double seconds = (now - _began) / (double)Stopwatch.Frequency;+ Logger.Log(seconds >= WarnEpisodeSeconds ? LogLevel.Warn : LogLevel.Debug,+ "UI thread: {Priority}-priority ticks late for {Seconds:0.0} s ({Count} ticks, worst {Worst:0} ms, {Sum:0} ms in all; {State} when it began)",+ priority, seconds, _lateTicks, _worstMs, _sumMs, _state);+ _lateTicks = 0;+ }+ }+ }+}diff --git a/WaveDudeNext.WPF/MainWindow.xaml.cs b/WaveDudeNext.WPF/MainWindow.xaml.csindex 2d378bc..ee48264 100644--- a/WaveDudeNext.WPF/MainWindow.xaml.cs+++ b/WaveDudeNext.WPF/MainWindow.xaml.cs@@ -81,6 +81,7 @@ public partial class MainWindow : Window}SourceInitialized += (_, _) => ThemeController.Instance.ApplyTitleBar(this);+ StartUiWatchdog();// texts taken once at construction follow a language change here: the dock titles (plain properties) and the// theme entries (converted headers); everything else is a DynamicResource (2026-10-14)LanguageController.Instance.PropertyChanged += (_, args) =>diff --git a/WaveDudeNext.WPF/Panes/MessagesPane.xaml.cs b/WaveDudeNext.WPF/Panes/MessagesPane.xaml.csindex 86287be..8117f45 100644--- a/WaveDudeNext.WPF/Panes/MessagesPane.xaml.cs+++ b/WaveDudeNext.WPF/Panes/MessagesPane.xaml.cs@@ -54,18 +54,22 @@ public partial class MessagesPane : UserControl, INotifyPropertyChangedprivate bool _autoScroll = true;private Regex? _regex;- /// <summary>Trace and Debug start visible in Debug builds only; Info and above always do.</summary>+ /// <summary>+ /// Trace and Debug start visible in Debug builds only; Info and above always do. A Release build logs no Trace at+ /// all (no rule reaches the pane's target), so its level toggles start at Debug.+ /// </summary>#if DEBUGprivate const bool ShowDiagnosticsByDefault = true;+ private static readonly LogLevel[] PaneLevels = [LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal];#elseprivate const bool ShowDiagnosticsByDefault = false;+ private static readonly LogLevel[] PaneLevels = [LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal];#endifpublic MessagesPane(){Levels = new ObservableCollection<LevelFilter>(- new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal }- .Select(level => new LevelFilter(level, visible: ShowDiagnosticsByDefault || level >= LogLevel.Info)));+ PaneLevels.Select(level => new LevelFilter(level, visible: ShowDiagnosticsByDefault || level >= LogLevel.Info)));foreach (LevelFilter level in Levels){level.PropertyChanged += (_, args) =>diff --git a/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs b/WaveDudeNext.WPF/Panes/PreviewPane.xaml.csindex 0af8351..adc7b0c 100644--- a/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs+++ b/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs@@ -301,6 +301,8 @@ public partial class PreviewPane : UserControlSetBinding(SceneHeightProperty, new Binding($"{nameof(Project)}.{nameof(Model.Project.Scene)}.{nameof(Scene.Height)}") { Source = this, Mode = BindingMode.OneWay });UpdateCanvas();+ // render priority, on purpose (2026-10-16): a try at background priority, to put input first, gained nothing+ // measurable during a run and made the clock wait behind every mouse move while scrubbing_timer = new DispatcherTimer(DispatcherPriority.Render) { Interval = TimeSpan.FromSeconds(1.0 / 60.0) };_timer.Tick += OnTick;_busyDelay = new DispatcherTimer(DispatcherPriority.Normal) { Interval = BusyOverlayDelay };@@ -606,8 +608,10 @@ public partial class PreviewPane : UserControl{case nameof(SimulationRun.FrameCount):UpdateFrames();- if (IsLive)+ if (IsLive && !_presenter.IsBusy){+ // follow the newest frame, but only when the previous picture is done: the next heartbeat (30 a+ // second) follows again, so the position trails the run by one picture at most_following = true;Position = NewestFrame;_following = false;@@ -954,8 +958,12 @@ public partial class PreviewPane : UserControl_clock.Restart();_carry += seconds * Fps * Speed;int frames = (int)Math.Floor(_carry);- if (frames == 0)+ if (frames == 0 || _presenter.IsBusy){+ // nothing due, or the previous picture is still being rendered: the clock keeps counting and the next+ // tick moves by all the frames that fell due meanwhile (2026-10-16: moving the position sixty times a+ // second while eleven pictures a second could be shown redrew the overlays and the bar for nothing and+ // kept the UI thread in render passes, so clicks and keys waited)return;}_carry -= frames;diff --git a/WaveDudeNext.WPF/Rendering/FramePresenter.cs b/WaveDudeNext.WPF/Rendering/FramePresenter.csindex a504e92..c9485d4 100644--- a/WaveDudeNext.WPF/Rendering/FramePresenter.cs+++ b/WaveDudeNext.WPF/Rendering/FramePresenter.cs@@ -16,6 +16,7 @@// <https://www.gnu.org/licenses/>.using System.Diagnostics;+using System.Runtime.InteropServices;using System.Windows;using System.Windows.Media;using System.Windows.Media.Imaging;@@ -51,6 +52,7 @@ public sealed class FramePresenterprivate int _renderedFrame = -1;private Job? _renderedJob;private readonly Stopwatch _renderClock = new();+ private readonly Stopwatch _colourClock = new(), _writeClock = new();private int _renderCount;/// <param name="dispatcher">The UI thread's dispatcher, where the bitmaps live.</param>@@ -121,6 +123,13 @@ public sealed class FramePresenterRebuild();}+ /// <summary>+ /// Whether a frame is being rendered right now (2026-10-16): the pane advances the shown position only when this is+ /// false, so the overlays and the timeline are redrawn once per picture that can be shown, not sixty times a+ /// second for pictures that never appear; on a machine that renders at the display rate nothing changes.+ /// </summary>+ public bool IsBusy => Volatile.Read(ref _busy) == 1;+/// <summary>Requests frame <paramref name="frame"/> (clamped to the frames available); coalesced with pending requests.</summary>public void Show(int frame){@@ -194,34 +203,78 @@ 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();- foreach (FrameLayer layer in new[] { FrameLayer.Field, FrameLayer.Intensity })+ var locked = new List<(WriteableBitmap Bitmap, Int32Rect Rect)>(2);+ try{- LayerSettings settings = job.Settings[(int)layer];- WriteableBitmap? bitmap = job.Bitmaps[(int)layer];- if (!settings.Enabled || bitmap == null || !job.Source.Has(layer))- {- continue;- }- bool copied = job.Indices != null ? job.Source.CopyLayer(frame, layer, job.Indices.AsSpan()) : job.Source.CopyLayer(frame, layer, job.Halves.AsSpan());- if (!copied)- {- continue;- }- 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);- }- else if (layer == FrameLayer.Field)+ foreach (FrameLayer layer in new[] { FrameLayer.Field, FrameLayer.Intensity }){- FrameRenderer.RenderField(job.Halves, width, height, settings.Lut, settings.Brightness, job.Pixels);+ LayerSettings settings = job.Settings[(int)layer];+ WriteableBitmap? bitmap = job.Bitmaps[(int)layer];+ if (!settings.Enabled || bitmap == null || !job.Source.Has(layer))+ {+ continue;+ }+ _colourClock.Start();+ bool copied = job.Indices != null ? job.Source.CopyLayer(frame, layer, job.Indices.AsSpan()) : job.Source.CopyLayer(frame, layer, job.Halves.AsSpan());+ if (!copied)+ {+ _colourClock.Stop();+ continue;+ }+ 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);+ }+ else if (layer == FrameLayer.Field)+ {+ FrameRenderer.RenderField(job.Halves, width, height, settings.Lut, settings.Brightness, job.Pixels);+ }+ else+ {+ FrameRenderer.RenderIntensity(job.Halves, width, height, settings.Lut, settings.Brightness, job.Pixels);+ }+ _colourClock.Stop();+ // 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+ _writeClock.Start();+ (IntPtr buffer, int stride) = _dispatcher.Invoke(() =>+ {+ bitmap.Lock();+ return (bitmap.BackBuffer, bitmap.BackBufferStride);+ }, DispatcherPriority.Render);+ locked.Add((bitmap, new Int32Rect(0, 0, width, height)));+ if (stride == width * 4)+ {+ Marshal.Copy(job.Pixels, 0, buffer, width * height);+ }+ else+ {+ for (int y = 0; y < height; y++)+ {+ Marshal.Copy(job.Pixels, y * width, buffer + y * stride, width);+ }+ }+ _writeClock.Stop();}- else+ }+ finally+ {+ if (locked.Count > 0){- FrameRenderer.RenderIntensity(job.Halves, width, height, settings.Lut, settings.Brightness, job.Pixels);+ _dispatcher.Invoke(() =>+ {+ foreach ((WriteableBitmap bitmap, Int32Rect rect) in locked)+ {+ bitmap.AddDirtyRect(rect);+ bitmap.Unlock();+ }+ }, DispatcherPriority.Render);}- // the bitmap belongs to the UI thread; wait for the copy so the pixel buffer can be reused- _dispatcher.Invoke(() => bitmap.WritePixels(new Int32Rect(0, 0, width, height), job.Pixels, width * 4, 0), DispatcherPriority.Render);}_renderClock.Stop();_renderedFrame = frame;@@ -229,8 +282,12 @@ 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}", width, height, _renderClock.Elapsed.TotalMilliseconds / RenderLogInterval, RenderLogInterval);+ Logger.Debug("Preview: {Width}x{Height}, {Average:0.0} ms per frame over the last {Count} (colouring {Colour:0.0}, copy into the bitmap {Write:0.0}, both on the pool)",+ width, height, _renderClock.Elapsed.TotalMilliseconds / RenderLogInterval, RenderLogInterval,+ _colourClock.Elapsed.TotalMilliseconds / RenderLogInterval, _writeClock.Elapsed.TotalMilliseconds / RenderLogInterval);_renderClock.Reset();+ _colourClock.Reset();+ _writeClock.Reset();}}}diff --git a/WaveDudeNext/Runs/SimulationRun.cs b/WaveDudeNext/Runs/SimulationRun.csindex d66f286..8bf5a04 100644--- a/WaveDudeNext/Runs/SimulationRun.cs+++ b/WaveDudeNext/Runs/SimulationRun.cs@@ -46,10 +46,15 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposableprivate static readonly Logger Logger = LogManager.GetCurrentClassLogger();/// <summary>Least interval between progress (<see cref="StepsDone"/>) posts.</summary>- private const long ProgressIntervalMs = 100;+ /// <summary>+ /// The one heartbeat to the user interface (2026-10-16): steps done, frames stored and the probe batch go in a+ /// single post at most thirty times a second. Separate posts (steps at 10 Hz, frames at 30, probes at 20) were+ /// about 60 operations a second, each buying WPF a full render pass of the window, and with the presenter's and+ /// the pane's own work the UI thread ran over 200 render passes a second and served input late.+ /// </summary>+ private const long HeartbeatIntervalMs = 33;/// <summary>Least interval between probe batches (<see cref="ProbesUpdated"/>).</summary>- private const long ProbeIntervalMs = 50;/// <summary>Snapshots in circulation between the stepping task and the writer: one being captured, one or two being written.</summary>private const int SnapshotPoolSize = 3;@@ -59,7 +64,6 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposableprivate readonly CancellationTokenSource _cancel = new();private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);private int _latestFrameCount;- private int _frameCountPostQueued;private RunState _state = RunState.Created;private int _stepsDone;private int _frameCount;@@ -264,7 +268,6 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposablebool trackIntensity = Spec.TrackIntensity;int frame = 0;long lastProgressMs = 0;- long lastProbeMs = 0;// where the time goes, for the log: stepping the engine, issuing the frame captures, and (on the// writer task) waiting for the captures and storing themlong computeTicks = 0;@@ -311,6 +314,7 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposablePost(() =>{StepsDone = done;+ FrameCount = Volatile.Read(ref _latestFrameCount); // the paced publisher may have skipped the newestState = RunState.Paused;});_gate.Wait(token);@@ -346,23 +350,13 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposableframe++;captureTicks += Stopwatch.GetTimestamp() - t1;}- // the probe values go to the user interface about 20 times a second- if (collector != null && stopwatch.ElapsedMilliseconds - lastProbeMs >= ProbeIntervalMs)- {- lastProbeMs = stopwatch.ElapsedMilliseconds;- PublishProbes(engine, collector, stepsDone);- }- if (stopwatch.ElapsedMilliseconds - lastProgressMs >= ProgressIntervalMs)+ if (stopwatch.ElapsedMilliseconds - lastProgressMs >= HeartbeatIntervalMs){lastProgressMs = stopwatch.ElapsedMilliseconds;- int done = stepsDone;- Post(() => StepsDone = done);+ PublishHeartbeat(engine, collector, stepsDone);}}- if (collector != null)- {- PublishProbes(engine, collector, stepsDone);- }+ PublishHeartbeat(engine, collector, stepsDone);DrainWriter();Logger.Debug("Run timing: {Compute:0.00} s stepping ({PerStep:0.00} ms/step), {Capture:0.00} s issuing captures; writer: {Wait:0.00} s waiting for frames, {Store:0.00} s storing ({PerFrame:0.0} ms/frame)",computeTicks / (double)Stopwatch.Frequency, computeTicks * 1000.0 / Stopwatch.Frequency / Math.Max(1, stepsDone),@@ -426,41 +420,41 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable}/// <summary>Collects the series the engine has (the profiles are collected per frame), takes a batch and applies it to <see cref="Traces"/> on the UI context.</summary>- private void PublishProbes(IWaveEngine engine, ProbeCollector collector, int stepsDone)+ /// <summary>The heartbeat: steps done, the frames the writer has stored so far, and the probe batch, in one post.</summary>+ private void PublishHeartbeat(IWaveEngine engine, ProbeCollector? collector, int stepsDone){- collector.Collect(engine, stepsDone);- ProbeUpdate update = collector.TakeForUi();+ ProbeUpdate? update = null;+ if (collector != null)+ {+ collector.Collect(engine, stepsDone);+ update = collector.TakeForUi();+ }+ int done = stepsDone;Post(() =>{- for (int i = 0; i < Traces.Length && i < update.Samples.Length; i++)+ StepsDone = done;+ FrameCount = Volatile.Read(ref _latestFrameCount);+ if (update != null){- Traces[i].Series.Add(update.Samples[i]);- foreach (float[] profile in update.Profiles[i])+ for (int i = 0; i < Traces.Length && i < update.Samples.Length; i++){- Traces[i].AddProfile(profile, update.Lengths[i]);+ Traces[i].Series.Add(update.Samples[i]);+ foreach (float[] profile in update.Profiles[i])+ {+ Traces[i].AddProfile(profile, update.Lengths[i]);+ }+ Traces[i].StepsSampled = update.StepsDone;}- Traces[i].StepsSampled = update.StepsDone;+ ProbesUpdated?.Invoke(this, update);}- ProbesUpdated?.Invoke(this, update);});}/// <summary>Timeline frames covered by the first <paramref name="stored"/> stored frames: each stands for <see cref="RunSpec.FrameStride"/> of them, never beyond the run.</summary>private int CoveredFrames(int stored) => (int)Math.Min((long)stored * Spec.FrameStride, Spec.FrameCount);- /// <summary>Posts the frame count, coalescing: never more than one post in flight, the handler reads the newest value.</summary>- private void PublishFrameCount(int count)- {- Volatile.Write(ref _latestFrameCount, count);- if (Interlocked.CompareExchange(ref _frameCountPostQueued, 1, 0) == 0)- {- Post(() =>- {- Volatile.Write(ref _frameCountPostQueued, 0);- FrameCount = Volatile.Read(ref _latestFrameCount);- });- }- }+ /// <summary>Records the frames stored so far; the heartbeat, a pause and the end of the run publish it.</summary>+ private void PublishFrameCount(int count) => Volatile.Write(ref _latestFrameCount, count);/// <summary>Runs <paramref name="action"/> on the UI context, or inline when there is none.</summary>private void Post(Action action)