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 playback clock is a thread timer posted at Render priority; the presenter logs the block's worst frame, wait and gap
Alexander Graef20d9652706c5
diff --git a/CLAUDE.md b/CLAUDE.mdindex f6284e3..35afeff 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -259,7 +259,18 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDApicture (the overlays measure to the uniform fit and remeasure on a canvas change) while `PictureFrame` fills itscell, so the heading stays at the top.- **Play means "show me the simulation"**: it starts an automatic run when needed and holds at the newest frame- until the run catches up. Live follows a running run until the user scrubs; it ends with a last follow to the+ until the run catches up. Space plays or pauses with the focus in the preview, the pane's own binding; a window-level+ Space that took the key wherever the focused element left it alone was built and reverted the same day (2026-11-04,+ the user's decision). **The playback clock is a thread timer whose ticks are posted to the+ UI thread at Render priority** (2026-11-04, the user's report: playback stuttered while the mouse moved, and only a hand+ on the mouse showed it): a `DispatcherTimer` is a Win32 timer message, which Windows delivers only when no input is+ queued, so a mouse reporting a thousand times a second starved the clock and no frame came for seconds (a gap of 3.2 s+ measured under injected moves every millisecond; 63–87 ms at a move every 8 ms); a posted operation is taken before+ input, and the same flood now leaves gaps of 32–47 ms, 68 at a move every tenth of a millisecond. **The presenter's+ log line carries the block's worst** beside its averages, the longest frame, the longest wait at the bitmap and the+ longest gap between two presented frames: a stutter is a gap, which an average over 100 frames hides (it had shown 28+ frames a second across a 3-second freeze). Measured on the way and settled: the app's input handling is not the cost,+ injected moves at ten thousand a second changed the frame times by nothing once the clock was posted. Live follows a running run until the user scrubs; it ends with a last follow to thefinal frame. A replaced project goes to frame 0; a discarded run keeps the position. In/out points are steps.- **A new source, probe or part lands at the centre of the canvas the preview shows** (2026-10-26, Jeroen's report: oneat the corner went unnoticed inside the rim); the model's parameterless adders take the scene's size, the window passes@@ -589,7 +600,13 @@ Wave Dude 2D projects the import checks read (`library_check`, `ImportCheck`, `S`_tools/legacy_examples` (2026-10-31, the user's wish: the root folder `Wave_Dude_Examples` with Jeroen's originalexamples is gone from the repository, in history up to 02d0e2d; `library_check` finds the repository root by thefixtures folder). A harness-sets the persisted settings it expects (split orientation, preview quality). Known flake: a second app start in one+sets the persisted settings it expects (split orientation, preview quality). **A one-off probe may move the real pointer+when the user says so** (2026-11-04, his instruction for a mouse-related report: `SetCursorPos` and `SendInput` from a+probe under `%TEMP%`, no clicks, the pointer put back; posted WM_MOUSEMOVE reproduced nothing, and only `SendInput`+raises the input Windows queues like a device's). **The figure runs can leave a runaway thumbnail cache** (2026-11-04:+a `dllhost.exe` hosting `thumbcache.dll` had used 81,000 s of CPU, 1.3 cores for seventeen hours, after the night's+rewrites of the 38 files under Assets; a sampling of every process's CPU while the user moved the mouse found it; the+user ended it, Windows starts it again when needed). Known flake: a second app start in onescript sometimes comes up active; only the foreground guard fails then. UI Automation files an owned dialog (the messagewindow, the memory warning) under its owner, not among the root's children: find its content below the main window andwalk up to the Window element for its handle (2026-11-03, half an hour lost to a root search).diff --git a/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs b/WaveDudeNext.WPF/Panes/PreviewPane.xaml.csindex 7ae2c27..64886fc 100644--- a/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs+++ b/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs@@ -25,6 +25,7 @@ using System.Windows.Data;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;+using System.Threading;using System.Windows.Threading;using WaveDudeNext.Model;using WaveDudeNext.Rendering;@@ -52,9 +53,10 @@ namespace WaveDudeNext.WPF.Panes;/// While a run is in progress the axis spans the planned frames (<see cref="PlannedLastFrame"/>)/// and <see cref="LastFrame"/> is the last frame that exists so far; <see cref="IsLive"/> keeps/// <see cref="Position"/> on that newest frame until the user scrubs, steps or plays, and the-/// Live button (or F) re-attaches. Playback runs on a <see cref="DispatcherTimer"/> on the UI-/// thread: a speed of 1 advances <see cref="Fps"/> (the project's video frame rate) frames per-/// second of wall-clock time, measured with a stopwatch so that a slow tick does not slow the+/// Live button (or F) re-attaches. Playback runs on a thread timer whose ticks are posted to the UI+/// thread at render priority (not a <see cref="DispatcherTimer"/>, a Win32 timer message, which a stream of+/// mouse moves starves, 2026-11-04): a speed of 1 advances <see cref="Fps"/> (the project's video frame rate)+/// frames per second of wall-clock time, measured with a stopwatch so that a slow tick does not slow the/// clock. Play, Pause and Space (toggle) are the built-in <see cref="MediaCommands"/>./// Keyboard: every transport control is a tab stop (play, pause, scrubber, speed, split, and/// the splitter between the pictures). The split radios are one stop that lands on the checked@@ -277,7 +279,8 @@ public partial class PreviewPane : UserControlpublic static readonly DependencyProperty IntensitySettingsProperty = DependencyProperty.Register(nameof(IntensitySettings), typeof(DisplayLayer), typeof(PreviewPane), new PropertyMetadata(null, (d, e) => ((PreviewPane)d).OnLayerSettingsChanged(FrameLayer.Intensity, e)));- private readonly DispatcherTimer _timer;+ private readonly Timer _ticker;+ private int _tickPending;private readonly DispatcherTimer _busyDelay;private readonly Stopwatch _clock = new();private readonly FramePresenter _presenter;@@ -339,10 +342,23 @@ 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;+ // a thread timer that posts the tick to the UI thread at render priority, not a DispatcherTimer (2026-11-04, the+ // user's report: playback stuttered while the mouse moved; a DispatcherTimer is a Win32 timer message, which+ // Windows delivers only when no input is queued, so a stream of mouse moves starved the clock and no frame came+ // for seconds; a posted operation is taken before input). 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. One tick in flight at a time, so a slow UI thread does not pile them up+ _ticker = new Timer(_ =>+ {+ if (Interlocked.Exchange(ref _tickPending, 1) == 0)+ {+ Dispatcher.BeginInvoke(DispatcherPriority.Render, () =>+ {+ Volatile.Write(ref _tickPending, 0);+ OnTick();+ });+ }+ });_busyDelay = new DispatcherTimer(DispatcherPriority.Normal) { Interval = BusyOverlayDelay };_busyDelay.Tick += (_, _) =>{@@ -1015,11 +1031,11 @@ public partial class PreviewPane : UserControl}pane._carry = 0.0;pane._clock.Restart();- pane._timer.Start();+ pane._ticker.Change(0, TickMilliseconds);}else{- pane._timer.Stop();+ pane._ticker.Change(Timeout.Infinite, Timeout.Infinite);pane._clock.Stop();}CommandManager.InvalidateRequerySuggested();@@ -1047,8 +1063,15 @@ public partial class PreviewPane : UserControl/// Advances <see cref="Position"/> by the frames elapsed since the previous tick. At the out/// point playback stops, or wraps to the in point when <see cref="IsLooping"/>./// </summary>- private void OnTick(object? sender, EventArgs e)+ /// <summary>The ticker's period: 60 ticks a second asked for, what the system timer gives (about 64 a second, or 32 at its coarser resolution); the stopwatch keeps the pace either way.</summary>+ private const int TickMilliseconds = 16;++ private void OnTick(){+ if (!IsPlaying)+ {+ return; // a tick posted just before Pause+ }double seconds = _clock.Elapsed.TotalSeconds;_clock.Restart();_carry += seconds * Fps * Speed;diff --git a/WaveDudeNext.WPF/Rendering/FramePresenter.cs b/WaveDudeNext.WPF/Rendering/FramePresenter.csindex 5a95888..f5d7aad 100644--- a/WaveDudeNext.WPF/Rendering/FramePresenter.cs+++ b/WaveDudeNext.WPF/Rendering/FramePresenter.cs@@ -64,6 +64,10 @@ public sealed class FramePresenterprivate readonly Stopwatch _renderClock = new();private readonly Stopwatch _copyClock = new(), _colourClock = new(), _writeClock = new();private int _renderCount;+ // the worst frame of the block beside the averages (2026-11-04, the user's report of a stutter the averages hid):+ // the longest frame, its longest wait at the bitmap, and the longest gap between two presented frames+ private long _lastPresented;+ private double _longestFrame, _longestWrite, _longestGap;/// <param name="dispatcher">The UI thread's dispatcher, where the bitmaps live.</param>public FramePresenter(Dispatcher dispatcher) => _dispatcher = dispatcher;@@ -302,6 +306,8 @@ public sealed class FramePresenterint width = job.Source.Width;int height = job.Source.Height;Logger.Trace("Presenter render: frame {Frame} of {Source} (job {Job})", frame, job.Source.GetType().Name, job.GetHashCode());+ double renderBefore = _renderClock.Elapsed.TotalMilliseconds;+ double writeBefore = _writeClock.Elapsed.TotalMilliseconds;_renderClock.Start();var locked = new List<(WriteableBitmap Bitmap, Int32Rect Rect, FrameLayer Layer, bool IsNew)>(2);try@@ -419,16 +425,27 @@ public sealed class FramePresenter_renderClock.Stop();_renderedFrame = frame;_renderedJob = job;+ long now = Stopwatch.GetTimestamp();+ _longestFrame = Math.Max(_longestFrame, _renderClock.Elapsed.TotalMilliseconds - renderBefore);+ _longestWrite = Math.Max(_longestWrite, _writeClock.Elapsed.TotalMilliseconds - writeBefore);+ if (_lastPresented != 0)+ {+ _longestGap = Math.Max(_longestGap, Stopwatch.GetElapsedTime(_lastPresented, now).TotalMilliseconds);+ }+ _lastPresented = now;if (++_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} 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)",+ // the cost of one presented frame (copy, colouring, bitmap write), averaged, and the block's worst: for judging+ // the pipeline at full resolution, and a stutter, which is a gap, not an average+ 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); the worst: a frame of {LongestFrame:0.0} ms, a wait at the bitmap of {LongestWrite:0.0}, a gap between frames of {LongestGap:0.0}",width, height, _shownSize.Width, _shownSize.Height, _renderClock.Elapsed.TotalMilliseconds / RenderLogInterval, RenderLogInterval,- _copyClock.Elapsed.TotalMilliseconds / RenderLogInterval, _colourClock.Elapsed.TotalMilliseconds / RenderLogInterval, _writeClock.Elapsed.TotalMilliseconds / RenderLogInterval);+ _copyClock.Elapsed.TotalMilliseconds / RenderLogInterval, _colourClock.Elapsed.TotalMilliseconds / RenderLogInterval, _writeClock.Elapsed.TotalMilliseconds / RenderLogInterval,+ _longestFrame, _longestWrite, _longestGap);_renderClock.Reset();_copyClock.Reset();_colourClock.Reset();_writeClock.Reset();+ _longestFrame = _longestWrite = _longestGap = 0.0;}}}