Skip to content

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#

Explicit OpenCL work groups, and a log that says what a report needs

Alexander Graefaf9134d86f11
diff --git a/CLAUDE.md b/CLAUDE.md
index 6945ea2..d2d2329 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -65,7 +65,13 @@ harnesses run.
- **C# style**: modern and concise, expression-bodied accessors, no `this.`, no `IDisposable` on interfaces,
`out` not `ref`, tabs, Allman; `///` docs state threading, units and coordinate systems. `grep -E`, not `-P`.
- **Log decisions at Debug** (scratch requests, stale marks, postponed re-runs, export steps). Info and up reach
- the status bar; Trace only in Debug builds. Log messages are not localised.
+ the status bar; Trace only in Debug builds. Log messages are not localised, and their numbers are invariant (NLog's
+ DefaultCultureInfo, 2026-10-27, the user's rule: a report's reader or tool must not trip over a decimal comma). **The log must let a report be
+ diagnosed** (2026-10-27, the user's rule after Jeroen's log named the property edited but not the value, nor the
+ grid): every engine logs its grid, canvas, rim, edges, stride, sub-steps and work groups when built; a GPU device's
+ facts (versions, units, clock, memory, limits) once per process; the scratch request names the newest edit with its
+ value (after the debounce, so a typed number shows as typed); every change at Trace as old → new
+ (`PropertyValueChangedEventArgs` from `SetProperty`, carried by `ProjectChange.Values`, `library_check` proves it).
- **Do not resurrect**: a probe signal lane, timeline tracks, zoom and pan of the axis, thumbnails, a run progress
bar, the scratch budget and its "not computed" note, a GPU JPEG front end, a Direct3D display path, a bent
rotation lever. **Do not change**: the readout showing both frame and step (undecided).
@@ -119,7 +125,7 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA
1 % back from the earlier linear ramp to a tenth at -64, 0.09 % from the quadratic one, 0.03 % at -128; the measuring
method is in `library_check`); a version-1 file loads as
Reflective, a version-2 file without a damping edge with none (its default then; files are version 3 since 2026-10-22), an
- import as Reflective with his band; one driver thread at a time, no locking; captures
+ import as Reflective with his band; one driver thread at a time, no locking; the kernels over the grid and the captures run in explicit 32 × 8 work groups over a global size rounded up to whole groups (2026-10-27, Jeroen's report: left to the driver, the group had to divide the grid, and a prime width, 1789 for a 1725 px canvas with the rim, got groups one cell wide, 13–19× slower on the RTX 2080; every candidate shape from 16 × 16 to 256 × 1 measured the same); captures
deliver planes in the spec's `FrameShape` (halves or palette index bytes, the GPU converting on the card);
`Reset`, `SetEmitters`, `SetProbes`. Numerics are Jeroen's (dx = dt = 1, leapfrog, 9-point or 4th-order
Laplacian, soft sources, EMA intensity; a scene pixel with red 0 is a mirror, n = 1000, his V0.30 rule,
@@ -295,7 +301,7 @@ numbers: no GPU JPEG, no OpenCL colouring at presentation, no `Vector256`, no Di
## Harnesses
-`library_check` (100+ checks: engines, store, renderer, half tables, screen path, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, ranges, XOR gate, zone plate, gate port follower, history, clipboard).
+`library_check` (100+ checks: engines, store, renderer, half tables, screen path, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, work groups on a prime grid, ranges, XOR gate, zone plate, gate port follower, history, clipboard).
UI, all on `Common.ps1`, with their check counts: `PreviewCheck` 43, `RunCheck` 71, `LanguageCheck` 11,
`ProbeGraphCheck` 39, `ImportCheck` 10, `ExportCheck` 38, `PreviewQualityCheck` 35, `SceneImageCheck` 8,
`ColorPickerCheck` 13, `KeyboardCheck` 13, `AboutCheck` 18, `SelectionCheck` 10. Test projects `tiny*.wdproj` sit beside them. A harness
diff --git a/WaveDudeNext.WPF/App.xaml.cs b/WaveDudeNext.WPF/App.xaml.cs
index a43ca26..b25deb7 100644
--- a/WaveDudeNext.WPF/App.xaml.cs
+++ b/WaveDudeNext.WPF/App.xaml.cs
@@ -128,6 +128,10 @@ public partial class App : Application
// decision lines without anyone opening the Messages pane
config.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget);
#endif
+ // every number in every entry with a decimal point, whatever the Windows culture (2026-10-27, the user's rule: a
+ // report's reader, or a tool summarising the log, must not trip over "7,6 s"); the message templates and the
+ // layouts format through this culture when the call names none
+ config.DefaultCultureInfo = CultureInfo.InvariantCulture;
LogManager.Configuration = config;
#if DEBUG
diff --git a/WaveDudeNext.WPF/MainWindow.Live.cs b/WaveDudeNext.WPF/MainWindow.Live.cs
index d8a1c4e..409e057 100644
--- a/WaveDudeNext.WPF/MainWindow.Live.cs
+++ b/WaveDudeNext.WPF/MainWindow.Live.cs
@@ -77,6 +77,9 @@ public partial class MainWindow
private DispatcherTimer? _scratchTimer;
private DispatcherTimer? _rerunTimer;
private (RunSpec Spec, int Frame)? _scratchRequested;
+
+ /// <summary>The newest simulation or probe edit, named with its value on the next scratch request's log line (2026-10-27); null once named.</summary>
+ private ProjectChange? _lastChange;
private (string Path, DateTime Written, ScenePixels Pixels)? _imageCache;
private (byte[] Data, ScenePixels Pixels)? _embeddedCache;
private (ScenePixels? Source, int PartsVersion, int Width, int Height, double Background, ScenePixels? Composed)? _composedCache;
@@ -169,6 +172,11 @@ public partial class MainWindow
private void OnProjectChanged(object? sender, ProjectChange change)
{
+ if (Logger.IsTraceEnabled)
+ {
+ // every change with its value before and after (2026-10-27); Trace, so a Release build pays nothing for it
+ Logger.Trace("Changed ({Item}.{Property}){Values}", change.Item, change.Property ?? "list", change.Values == null ? "" : ": " + change.OldValueText + " → " + change.NewValueText);
+ }
IsDirty = true;
ScheduleRecord();
bool sceneReplaced = change.Item is Project && change.Property == nameof(Project.Scene);
@@ -192,6 +200,7 @@ public partial class MainWindow
Logger.Debug("Probes edited ({Item}.{Property}): the run's recordings are stale", change.Item, change.Property);
IsProbesStale = true;
}
+ _lastChange = change;
ScheduleScratch();
return;
}
@@ -199,6 +208,7 @@ public partial class MainWindow
{
return;
}
+ _lastChange = change;
if (Run != null && !IsRunStale)
{
if (unrecorded)
@@ -351,8 +361,11 @@ public partial class MainWindow
_pausedForScratch = run;
}
int frame = Math.Clamp(PreviewPosition, 0, Math.Max(0, spec.FrameCount - 1));
- Logger.Debug("Preview frame {Frame} requested from scratch ({Reason})", frame,
- Run == null ? "no run" : IsRunStale ? "the run is stale" : IsProbesStale ? "the probes changed" : "the run has not got there yet");
+ // the newest edit with its value (2026-10-27): after the debounce, so a typed number shows as typed, not keystroke by keystroke
+ string edit = _lastChange == null ? "" : ": " + _lastChange.Item + "." + (_lastChange.Property ?? "list") + (_lastChange.Values == null ? "" : " = " + _lastChange.NewValueText);
+ _lastChange = null;
+ Logger.Debug("Preview frame {Frame} requested from scratch ({Reason}{Edit})", frame,
+ Run == null ? "no run" : IsRunStale ? "the run is stale" : IsProbesStale ? "the probes changed" : "the run has not got there yet", edit);
_scratchRequested = (spec, frame);
_scratch.Request(spec, frame);
SetScratchBusy(frame);
diff --git a/WaveDudeNext/Engine/GpuDeviceInfo.cs b/WaveDudeNext/Engine/GpuDeviceInfo.cs
index 2696bc0..7d2be2a 100644
--- a/WaveDudeNext/Engine/GpuDeviceInfo.cs
+++ b/WaveDudeNext/Engine/GpuDeviceInfo.cs
@@ -95,6 +95,12 @@ public sealed class GpuDeviceInfo
// Mask the sign bit so an odd 64-bit value cannot turn into a negative size.
GlobalMemory = (long)(OpenClApi.DeviceNumber(id, OpenClApi.DeviceGlobalMemSize) & 0x7FFFFFFFFFFFFFFFUL),
MaxAllocation = (long)(OpenClApi.DeviceNumber(id, OpenClApi.DeviceMaxMemAllocSize) & 0x7FFFFFFFFFFFFFFFUL),
+ Version = OpenClApi.DeviceString(id, OpenClApi.DeviceVersion),
+ DriverVersion = OpenClApi.DeviceString(id, OpenClApi.DriverVersion),
+ ComputeUnits = (int)computeUnits,
+ ClockMhz = (int)clockMhz,
+ MaxWorkGroupSize = (long)OpenClApi.DeviceNumber(id, OpenClApi.DeviceMaxWorkGroupSize),
+ MaxWorkItemSizes = OpenClApi.DeviceSizes(id, OpenClApi.DeviceMaxWorkItemSizes),
};
}
@@ -128,4 +134,22 @@ public sealed class GpuDeviceInfo
/// <summary>CL_DEVICE_MAX_MEM_ALLOC_SIZE in bytes: the largest single buffer the device allows.</summary>
public long MaxAllocation { get; private init; }
+
+ /// <summary>CL_DEVICE_VERSION ("OpenCL 3.0 CUDA"), or "" when the query fails.</summary>
+ public string Version { get; private init; } = "";
+
+ /// <summary>CL_DRIVER_VERSION as the vendor writes it ("566.03"), or "" when the query fails.</summary>
+ public string DriverVersion { get; private init; } = "";
+
+ /// <summary>CL_DEVICE_MAX_COMPUTE_UNITS, 0 when the query fails.</summary>
+ public int ComputeUnits { get; private init; }
+
+ /// <summary>CL_DEVICE_MAX_CLOCK_FREQUENCY in MHz, 0 when the query fails.</summary>
+ public int ClockMhz { get; private init; }
+
+ /// <summary>CL_DEVICE_MAX_WORK_GROUP_SIZE: the largest work-group of the device (a kernel's own limit may be lower), 0 when the query fails.</summary>
+ public long MaxWorkGroupSize { get; private init; }
+
+ /// <summary>CL_DEVICE_MAX_WORK_ITEM_SIZES: the largest work-group extent per dimension; empty when the query fails.</summary>
+ public ulong[] MaxWorkItemSizes { get; private init; } = [];
}
diff --git a/WaveDudeNext/Engine/GpuWaveSimulator.cs b/WaveDudeNext/Engine/GpuWaveSimulator.cs
index a936166..1eae737 100644
--- a/WaveDudeNext/Engine/GpuWaveSimulator.cs
+++ b/WaveDudeNext/Engine/GpuWaveSimulator.cs
@@ -70,7 +70,9 @@ namespace WaveDudeNext.Engine;
/// The field lives in two ping-pong buffers (<see cref="_field"/>) that take turns as "current field" and
/// "previous field"; every kernel that reads the field exists twice (index 0/1) with the buffers bound in
/// opposite order, so a step merely picks the kernel for <see cref="_current"/> instead of re-binding
-/// arguments. Kernel launches are asynchronous; uploads and read-backs are blocking. Every OpenCL handle
+/// arguments. The kernels over the grid and the captures run in explicit work groups, the global size rounded up
+/// to whole groups (see <see cref="WorkGroup2D"/> for why). Kernel launches are asynchronous; uploads and
+/// read-backs are blocking. Every OpenCL handle
/// created here is registered in <see cref="_scene"/> (the simulation program, kernels and buffers) or
/// <see cref="_probes"/> (everything <see cref="SetProbes"/> creates) and released by <see cref="Dispose"/>,
/// by the constructor when building fails, or — for the probe set — when probes are installed again. The
@@ -108,6 +110,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
{
try
{
+ DescribeOnce(devices, device);
return new GpuWaveSimulator(device, scene, options, emitters);
}
catch (Exception ex)
@@ -147,7 +150,6 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
{
throw new InvalidOperationException("the scene is too large for this GPU");
}
- _grid2D = new[] { new IntPtr(_width), new IntPtr(_height) };
_grid1D = new[] { new IntPtr(Math.Max(1, _sourceCount)) };
_hostField = new float[_cells];
_hostIntensity = _track ? new float[_cells] : null;
@@ -238,6 +240,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
_stagingIntensity = _track ? CreateBuffer((long)_canvasWidth * _canvasHeight * 2, _scene) : IntPtr.Zero;
_captureHalfKernel = CreateKernel(_scene, _scene.Program, "capture_half");
_captureIndexKernel = CreateKernel(_scene, _scene.Program, "capture_index");
+ _captureLocal = WorkGroup2D(_captureHalfKernel, _captureIndexKernel);
foreach (IntPtr kernel in new[] { _captureHalfKernel, _captureIndexKernel })
{
// the canvas, which the captures cover, and where it starts in the grid
@@ -252,7 +255,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
{
// the shape's geometry, set once per shape (every capture of a run shares one)
_captureShape = shape;
- _captureGrid = [new IntPtr(shape.Width), new IntPtr(shape.Height)];
+ _captureGrid = RoundUp([shape.Width, shape.Height], _captureLocal);
foreach (IntPtr kernel in new[] { _captureHalfKernel, _captureIndexKernel })
{
SetInt(kernel, 5U, shape.Divisor);
@@ -288,7 +291,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
{
SetInt(kernel, 9U, intensity && shape.IntensityRoot ? 1 : 0);
}
- Enqueue(kernel, _captureGrid!, "capture");
+ Enqueue(kernel, _captureGrid!, _captureLocal, "capture");
OpenClApi.Check(OpenClApi.clEnqueueReadBufferPtr(_queue, staging, 0U, IntPtr.Zero, new IntPtr(plane.Length), FrameSnapshot.AddressOf(plane), 0U, IntPtr.Zero, out IntPtr evt), "clEnqueueReadBuffer (capture)");
snapshot.Events[snapshot.EventCount++] = evt;
}
@@ -439,7 +442,13 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
SetFloat(edges, 6U, c2Mult);
}
}
- _edgeGrid1D = [new IntPtr(_width + 2 + _height)];
+ _stepLocal = WorkGroup2D(_stepKernel[0], _stepKernel[1]);
+ _grid2D = RoundUp([_width, _height], _stepLocal);
+ _edgeLocal = _openEdges ? WorkGroup1D(_edgeKernel[0], _edgeKernel[1]) : null;
+ _edgeGrid1D = RoundUp([_width + 2 + _height], _edgeLocal);
+ // what a report needs to say (2026-10-27, after a log that could not show the grid): the grid the kernels run over, and how
+ Logger.Debug("OpenCL kernels built on {Device}: grid {Width} × {Height} (canvas {CanvasWidth} × {CanvasHeight}, rim {Rim}, {Edges}), stride {Stride}, work groups {Groups}, {Stencil}",
+ _device.Name, _width, _height, _canvasWidth, _canvasHeight, _rim, _openEdges ? "open" : "reflective", _stride, GroupText(_stepLocal), WaveSimulator.StencilText(use4thOrderLaplacian, _subSteps));
if (_sourceCount > 0)
{
IntPtr indexBuffer = CreateBuffer(indices, _scene);
@@ -929,10 +938,119 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
OpenClApi.Check(OpenClApi.clSetKernelArgFloat(kernel, index, new IntPtr(4), ref value), "clSetKernelArg");
}
- /// <summary>Enqueues <paramref name="kernel"/> with the given global work size; <paramref name="what"/> names the launch in the error message.</summary>
- private void Enqueue(IntPtr kernel, IntPtr[] globalSize, string what)
+ /// <summary>Enqueues <paramref name="kernel"/> with the given global work size, the work-group size left to the driver (the small 1D kernels); <paramref name="what"/> names the launch in the error message.</summary>
+ private void Enqueue(IntPtr kernel, IntPtr[] globalSize, string what) => Enqueue(kernel, globalSize, null, what);
+
+ /// <summary>Enqueues <paramref name="kernel"/> with the given global work size, in groups of <paramref name="localSize"/> (null: the driver's choice); <paramref name="what"/> names the launch in the error message.</summary>
+ private void Enqueue(IntPtr kernel, IntPtr[] globalSize, IntPtr[]? localSize, string what)
+ {
+ OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(_queue, kernel, (uint)globalSize.Length, null, globalSize, localSize, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (" + what + ")");
+ }
+
+ /// <summary>
+ /// The work-group size for the kernels over the grid (<c>wave_step</c>, the captures): 32 × 8 work items, a row
+ /// segment of 32 cells (128 bytes, what a warp or wavefront reads in one go) by 8 rows, so the stencil's
+ /// neighbours above and below come from the group's own cache lines; shrunk to what the kernels can run with on
+ /// this device (CL_KERNEL_WORK_GROUP_SIZE, which allows for the registers they use) and to the device's extents
+ /// per dimension, the rows halved first. Null, leaving the choice to the driver, when a query fails. Left to the
+ /// driver, the group has to divide the global size exactly, and a grid of prime width (1789 cells: a 1725 px
+ /// canvas with the 32 px rim, 2026-10-26) got groups one cell wide, each warp reading a column of scattered
+ /// addresses in place of a row: 13 to 19 times slower on an RTX 2080. With an explicit group the global size is
+ /// rounded up to whole groups (<see cref="RoundUp"/>) and the kernels' own bounds checks drop the surplus work
+ /// items.
+ /// </summary>
+ private IntPtr[]? WorkGroup2D(params IntPtr[] kernels) => FitGroup([32, 8], kernels);
+
+ /// <summary>The work-group size for a kernel over a list (<c>open_edges</c>): 64 work items, shrunk as <see cref="WorkGroup2D"/> shrinks; null when a query fails.</summary>
+ private IntPtr[]? WorkGroup1D(params IntPtr[] kernels) => FitGroup([64], kernels);
+
+ /// <summary><paramref name="preferred"/> shrunk to the limit of every kernel in <paramref name="kernels"/> and to the device's extents, the last dimension halved first; null when a query fails.</summary>
+ private IntPtr[]? FitGroup(int[] preferred, IntPtr[] kernels)
+ {
+ ulong limit = ulong.MaxValue;
+ foreach (IntPtr kernel in kernels)
+ {
+ ulong own = OpenClApi.KernelWorkGroupLimit(kernel, _device.DeviceId);
+ if (own == 0UL)
+ {
+ return null;
+ }
+ limit = Math.Min(limit, own);
+ }
+ ulong[] extents = OpenClApi.DeviceSizes(_device.DeviceId, OpenClApi.DeviceMaxWorkItemSizes);
+ if (extents.Length < preferred.Length)
+ {
+ return null;
+ }
+ int[] size = (int[])preferred.Clone();
+ for (int axis = 0; axis < size.Length; axis++)
+ {
+ while (size[axis] > 1 && (ulong)size[axis] > extents[axis])
+ {
+ size[axis] /= 2;
+ }
+ }
+ for (int axis = size.Length - 1; axis >= 0 && Product(size) > limit;)
+ {
+ if (size[axis] > 1)
+ {
+ size[axis] /= 2;
+ }
+ else
+ {
+ axis--;
+ }
+ }
+ return [.. size.Select(s => new IntPtr(s))];
+
+ static ulong Product(int[] size)
+ {
+ ulong product = 1UL;
+ foreach (int s in size)
+ {
+ product *= (ulong)s;
+ }
+ return product;
+ }
+ }
+
+ /// <summary>A work-group size for the log: "32 × 8", or "the driver's" when the choice is left to the driver.</summary>
+ private static string GroupText(IntPtr[]? local) => local == null ? "the driver's" : string.Join(" × ", local.Select(v => v.ToInt64().ToString(CultureInfo.InvariantCulture)));
+
+ /// <summary>
+ /// Logs, before a device first builds an engine in this process (2026-10-27, the user's wish: a report should say
+ /// which card, driver and limits were at work, and which cards there were): the candidates in the order tried, once,
+ /// then the device's versions, compute units, clock, memory, the largest buffer, the work-group limit and extents,
+ /// and whether its square root is correctly rounded. Before the build, so a build that fails has its device on record.
+ /// </summary>
+ private static void DescribeOnce(List<GpuDeviceInfo> candidates, GpuDeviceInfo device)
+ {
+ lock (_described)
+ {
+ if (_described.Add("*"))
+ {
+ Logger.Debug("GPUs through OpenCL, the first that works is used: {Devices}", string.Join("; ", candidates.Select(d => d.Name + (d.Discrete ? " (discrete)" : " (integrated)"))));
+ }
+ if (!_described.Add(device.Name + "|" + device.DriverVersion))
+ {
+ return;
+ }
+ }
+ Logger.Debug("GPU in use: {Name} ({Vendor}, {Kind}), {Version}, driver {Driver}, {Units} compute units at {Clock} MHz, {Memory:0.0} GB, largest buffer {Allocation:0.0} GB, work groups up to {MaxGroup} ({Extents}), {Sqrt}",
+ device.Name, device.Vendor, device.Discrete ? "discrete" : "integrated", device.Version, device.DriverVersion, device.ComputeUnits, device.ClockMhz, device.GlobalMemory / 1073741824.0, device.MaxAllocation / 1073741824.0,
+ device.MaxWorkGroupSize, string.Join(" × ", device.MaxWorkItemSizes), device.CorrectlyRoundedSqrt ? "correctly rounded sqrt" : "no correctly rounded sqrt");
+ }
+
+ /// <summary>The global work size for <paramref name="items"/> work items per dimension: rounded up to whole groups of <paramref name="local"/>, or as given when the driver chooses the group.</summary>
+ private static IntPtr[] RoundUp(int[] items, IntPtr[]? local)
{
- OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(_queue, kernel, (uint)globalSize.Length, null, globalSize, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (" + what + ")");
+ var global = new IntPtr[items.Length];
+ for (int axis = 0; axis < items.Length; axis++)
+ {
+ int group = local == null ? 1 : (int)local[axis];
+ global[axis] = new IntPtr((items[axis] + group - 1) / group * group);
+ }
+ return global;
}
/// <summary>Blocking device-to-host copy of <paramref name="target"/>.Length floats from <paramref name="buffer"/>; resets the clFinish counter since the read drains the queue.</summary>
@@ -948,6 +1066,9 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
/// <summary>The card this engine runs on.</summary>
public GpuDeviceInfo Device => _device;
+ /// <summary>The work-group size <c>wave_step</c> runs with (see <see cref="WorkGroup2D"/>); (0, 0) when the driver chooses.</summary>
+ public (int Width, int Height) WorkGroup => _stepLocal == null ? (0, 0) : ((int)_stepLocal[0], (int)_stepLocal[1]);
+
/// <summary>Scene width in cells (canvas pixels), excluding the padding.</summary>
public int Width => _canvasWidth;
@@ -1001,10 +1122,10 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
{
SetInt(_stepKernel[current], 8U, subStep == _subSteps && _track ? 1 : 0);
}
- Enqueue(_stepKernel[current], _grid2D, "step");
+ Enqueue(_stepKernel[current], _grid2D, _stepLocal, "step");
if (_openEdges)
{
- Enqueue(_edgeKernel[current], _edgeGrid1D, "edges");
+ Enqueue(_edgeKernel[current], _edgeGrid1D, _edgeLocal, "edges");
}
current = 1 - current;
}
@@ -1503,8 +1624,13 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
/// <summary>The probe program (<see cref="ProbeKernelSource"/>), built on the first <see cref="SetProbes"/> and kept for the engine's life; its kernels and buffers live in <see cref="_probes"/>.</summary>
private IntPtr _probeProgram;
- /// <summary>The device the context lives on; needed again to build the probe program.</summary>
+ /// <summary>The engine's log: the device once per process and the grid of every build, both at Debug.</summary>
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
+
+ /// <summary>The devices described in the log so far, by name and driver version (<see cref="DescribeOnce"/>); locked on itself, as engines are built on several threads.</summary>
+ private static readonly HashSet<string> _described = [];
+
+ /// <summary>The device the context lives on; needed again to build the probe program.</summary>
private readonly GpuDeviceInfo _device;
private readonly int _rim;
private readonly int _canvasWidth;
@@ -1617,8 +1743,17 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
/// <summary>Index (0/1) of the field buffer holding the newest field; flips after every sub-step.</summary>
private int _current;
- /// <summary>Global work size of <c>wave_step</c>: <see cref="_width"/> × <see cref="_height"/> work items, one per interior cell.</summary>
- private readonly IntPtr[] _grid2D;
+ /// <summary>Global work size of <c>wave_step</c>: <see cref="_width"/> × <see cref="_height"/> work items, one per interior cell, rounded up to whole groups of <see cref="_stepLocal"/>; set in <see cref="Build"/>.</summary>
+ private IntPtr[] _grid2D = [new IntPtr(1), new IntPtr(1)];
+
+ /// <summary>Work-group size of <c>wave_step</c> (<see cref="WorkGroup2D"/>); null leaves it to the driver.</summary>
+ private IntPtr[]? _stepLocal;
+
+ /// <summary>Work-group size of <c>open_edges</c> (<see cref="WorkGroup1D"/>); null leaves it to the driver.</summary>
+ private IntPtr[]? _edgeLocal;
+
+ /// <summary>Work-group size of the capture kernels (<see cref="WorkGroup2D"/>); null leaves it to the driver.</summary>
+ private IntPtr[]? _captureLocal;
/// <summary>Global work size of <c>apply_sources</c>: max(1, <see cref="_sourceCount"/>).</summary>
private readonly IntPtr[] _grid1D;
diff --git a/WaveDudeNext/Engine/OpenClApi.cs b/WaveDudeNext/Engine/OpenClApi.cs
index 38c44f5..3f4dcc9 100644
--- a/WaveDudeNext/Engine/OpenClApi.cs
+++ b/WaveDudeNext/Engine/OpenClApi.cs
@@ -74,6 +74,10 @@ internal static class OpenClApi
[DllImport("OpenCL", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
internal static extern IntPtr clCreateKernel(IntPtr program, string kernelName, ref int errcode);
+ /// <summary>clGetKernelWorkGroupInfo: raw bytes of a kernel's property on one device, such as <see cref="KernelWorkGroupSize"/>. Wrapped by <see cref="KernelWorkGroupLimit"/>.</summary>
+ [DllImport("OpenCL", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
+ internal static extern int clGetKernelWorkGroupInfo(IntPtr kernel, IntPtr device, uint paramName, IntPtr paramSize, byte[]? paramValue, ref IntPtr sizeRet);
+
/// <summary>clSetKernelArg for a buffer argument (cl_mem handle; <paramref name="argSize"/> is the pointer size).</summary>
[DllImport("OpenCL", CharSet = CharSet.Ansi, EntryPoint = "clSetKernelArg", ExactSpelling = true, SetLastError = true)]
internal static extern int clSetKernelArgMem(IntPtr kernel, uint argIndex, IntPtr argSize, ref IntPtr argValue);
@@ -116,7 +120,7 @@ internal static class OpenClApi
[DllImport("OpenCL", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
internal static extern int clReleaseEvent(IntPtr evt);
- /// <summary>clEnqueueNDRangeKernel: launches the kernel over a <paramref name="workDim"/>-dimensional range; <paramref name="localSize"/> null lets the driver pick the work-group size.</summary>
+ /// <summary>clEnqueueNDRangeKernel: launches the kernel over a <paramref name="workDim"/>-dimensional range; <paramref name="localSize"/> null lets the driver pick the work-group size, which then has to divide <paramref name="globalSize"/> exactly.</summary>
[DllImport("OpenCL", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
internal static extern int clEnqueueNDRangeKernel(IntPtr queue, IntPtr kernel, uint workDim, IntPtr[]? globalOffset, IntPtr[] globalSize, IntPtr[]? localSize, uint numEvents, IntPtr waitList, IntPtr evt);
@@ -296,6 +300,34 @@ internal static class OpenClApi
return 0UL;
}
+ /// <summary>The <c>size_t</c> values of a device property such as <see cref="DeviceMaxWorkItemSizes"/>; empty when the query fails.</summary>
+ internal static ulong[] DeviceSizes(IntPtr device, uint paramName)
+ {
+ byte[]? bytes = DeviceInfoBytes(device, paramName);
+ if (bytes == null)
+ {
+ return [];
+ }
+ var sizes = new ulong[bytes.Length / IntPtr.Size];
+ for (int i = 0; i < sizes.Length; i++)
+ {
+ sizes[i] = IntPtr.Size == 8 ? BitConverter.ToUInt64(bytes, i * 8) : BitConverter.ToUInt32(bytes, i * 4);
+ }
+ return sizes;
+ }
+
+ /// <summary>The largest work-group <paramref name="kernel"/> can run with on <paramref name="device"/> (CL_KERNEL_WORK_GROUP_SIZE, which allows for the registers it uses); 0 when the query fails.</summary>
+ internal static ulong KernelWorkGroupLimit(IntPtr kernel, IntPtr device)
+ {
+ byte[] value = new byte[IntPtr.Size];
+ IntPtr ignored = IntPtr.Zero;
+ if (clGetKernelWorkGroupInfo(kernel, device, KernelWorkGroupSize, new IntPtr(value.Length), value, ref ignored) != 0)
+ {
+ return 0UL;
+ }
+ return IntPtr.Size == 8 ? BitConverter.ToUInt64(value, 0) : BitConverter.ToUInt32(value, 0);
+ }
+
/// <summary>The compiler log for a program on a device (CL_PROGRAM_BUILD_LOG, trimmed); empty if unavailable or if the query throws.</summary>
internal static string BuildLog(IntPtr program, IntPtr device)
{
@@ -342,6 +374,12 @@ internal static class OpenClApi
/// <summary>CL_DEVICE_MAX_COMPUTE_UNITS (0x1002), cl_uint.</summary>
internal const uint DeviceMaxComputeUnits = 0x1002U;
+ /// <summary>CL_DEVICE_MAX_WORK_GROUP_SIZE (0x1004), size_t: the largest work-group of the device.</summary>
+ internal const uint DeviceMaxWorkGroupSize = 0x1004U;
+
+ /// <summary>CL_DEVICE_MAX_WORK_ITEM_SIZES (0x1005), size_t[]: the largest work-group extent in each dimension.</summary>
+ internal const uint DeviceMaxWorkItemSizes = 0x1005U;
+
/// <summary>CL_DEVICE_MAX_CLOCK_FREQUENCY (0x100C), cl_uint in MHz.</summary>
internal const uint DeviceMaxClockFrequency = 0x100CU;
@@ -357,6 +395,12 @@ internal static class OpenClApi
/// <summary>CL_DEVICE_VENDOR (0x102C), string.</summary>
internal const uint DeviceVendor = 0x102CU;
+ /// <summary>CL_DRIVER_VERSION (0x102D), string: the driver's version as the vendor writes it.</summary>
+ internal const uint DriverVersion = 0x102DU;
+
+ /// <summary>CL_DEVICE_VERSION (0x102F), string: "OpenCL &lt;major&gt;.&lt;minor&gt; &lt;vendor text&gt;".</summary>
+ internal const uint DeviceVersion = 0x102FU;
+
/// <summary>CL_DEVICE_HOST_UNIFIED_MEMORY (0x1035), cl_bool: non-zero for devices sharing host memory (integrated GPUs).</summary>
internal const uint DeviceHostUnifiedMemory = 0x1035U;
@@ -368,4 +412,7 @@ internal static class OpenClApi
/// <summary>CL_PROGRAM_BUILD_LOG (0x1183), string.</summary>
internal const uint ProgramBuildLog = 0x1183U;
+
+ /// <summary>CL_KERNEL_WORK_GROUP_SIZE (0x11B0), size_t: the largest work-group a kernel can run with on a device.</summary>
+ internal const uint KernelWorkGroupSize = 0x11B0U;
}
diff --git a/WaveDudeNext/Engine/WaveSimulator.cs b/WaveDudeNext/Engine/WaveSimulator.cs
index 1c564bf..a0b1721 100644
--- a/WaveDudeNext/Engine/WaveSimulator.cs
+++ b/WaveDudeNext/Engine/WaveSimulator.cs
@@ -87,6 +87,9 @@ namespace WaveDudeNext.Engine;
/// </remarks>
public sealed class WaveSimulator : IWaveEngine, IDisposable
{
+ /// <summary>The engine's log: the grid of every build, at Debug.</summary>
+ private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
+
/// <summary>
/// Copies the scene's c² and damping maps into the padded grid, derives the sub-step count (4th order
/// only, and only when the scene's highest c² needs it) and the matching per-sub-step damping and c²
@@ -167,6 +170,9 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
}
_timeDecay = options.TimeDecay;
+ // the same facts the OpenCL engine logs when its kernels are built (2026-10-27)
+ Logger.Debug("CPU engine built: grid {Width} × {Height} (canvas {CanvasWidth} × {CanvasHeight}, rim {Rim}, {Edges}), stride {Stride}, {Stencil}, {Threads} threads",
+ _width, _height, _canvasWidth, _canvasHeight, _rim, _openEdges ? "open" : "reflective", _stride, StencilText(_use4thOrderLaplacian, _subSteps), Environment.ProcessorCount);
SetEmitters(emitters);
}
@@ -302,6 +308,10 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
/// <summary>Engine label for the UI/result: "CPU (n threads)" with the logical processor count.</summary>
public string Description => "CPU (" + Environment.ProcessorCount.ToString(CultureInfo.InvariantCulture) + " threads)";
+ /// <summary>The stencil for the log, both engines alike: "9-point stencil", or "4th-order stencil, 3 sub-steps".</summary>
+ internal static string StencilText(bool fourthOrder, int subSteps) =>
+ fourthOrder ? "4th-order stencil, " + subSteps.ToString(CultureInfo.InvariantCulture) + (subSteps == 1 ? " sub-step" : " sub-steps") : "9-point stencil";
+
/// <summary>Elapsed simulation time in steps (one per <see cref="AdvanceOneStep"/>).</summary>
public double Time => _time;
diff --git a/WaveDudeNext/Model/ObservableObject.cs b/WaveDudeNext/Model/ObservableObject.cs
index a058180..160e32e 100644
--- a/WaveDudeNext/Model/ObservableObject.cs
+++ b/WaveDudeNext/Model/ObservableObject.cs
@@ -32,7 +32,8 @@ public abstract class ObservableObject : INotifyPropertyChanged
/// <summary>
/// Stores <paramref name="value"/> in <paramref name="field"/> and raises
- /// <see cref="PropertyChanged"/> when it differs; returns whether it did.
+ /// <see cref="PropertyChanged"/> when it differs, with the value before and after
+ /// (<see cref="PropertyValueChangedEventArgs"/>); returns whether it did.
/// </summary>
protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? name = null)
{
@@ -40,8 +41,9 @@ public abstract class ObservableObject : INotifyPropertyChanged
{
return false;
}
+ T old = field;
field = value;
- OnPropertyChanged(name);
+ PropertyChanged?.Invoke(this, new PropertyValueChangedEventArgs(name, old, value));
return true;
}
@@ -60,3 +62,21 @@ public abstract class ObservableObject : INotifyPropertyChanged
return copy;
}
}
+
+/// <summary>
+/// The arguments <see cref="ObservableObject.SetProperty{T}"/> raises: the value before and after the edit, so a
+/// watcher can log "old → new" without a shadow copy of the model (2026-10-27, the user's wish after a report whose
+/// log named the property edited but not the value). A derived property's notification
+/// (<see cref="ObservableObject.OnPropertyChanged"/>) carries the plain arguments.
+/// </summary>
+/// <param name="propertyName">The property that changed.</param>
+/// <param name="oldValue">Its value before the edit.</param>
+/// <param name="newValue">The value set.</param>
+public sealed class PropertyValueChangedEventArgs(string? propertyName, object? oldValue, object? newValue) : PropertyChangedEventArgs(propertyName)
+{
+ /// <summary>The value before the edit.</summary>
+ public object? OldValue { get; } = oldValue;
+
+ /// <summary>The value set.</summary>
+ public object? NewValue { get; } = newValue;
+}
diff --git a/WaveDudeNext/Model/ProjectWatcher.cs b/WaveDudeNext/Model/ProjectWatcher.cs
index bd0af66..3a4b0bb 100644
--- a/WaveDudeNext/Model/ProjectWatcher.cs
+++ b/WaveDudeNext/Model/ProjectWatcher.cs
@@ -18,6 +18,7 @@
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
+using System.Globalization;
using WaveDudeNext.Rendering;
namespace WaveDudeNext.Model;
@@ -25,8 +26,25 @@ namespace WaveDudeNext.Model;
/// <summary>What changed in a watched project: the object and the property, or a list when items were added or removed.</summary>
/// <param name="Item">The object that changed (a <see cref="Scene"/>, <see cref="Source"/>, …) or the collection.</param>
/// <param name="Property">The property name, or null for a collection change.</param>
-public sealed record ProjectChange(object Item, string? Property)
+/// <param name="Values">The value before and after when the edit went through <see cref="ObservableObject.SetProperty{T}"/>; null for a derived property or a list.</param>
+public sealed record ProjectChange(object Item, string? Property, PropertyValueChangedEventArgs? Values = null)
{
+ /// <summary>The value before the edit as the log shows it (<see cref="Format"/>); "" without <see cref="Values"/>.</summary>
+ public string OldValueText => Values == null ? "" : Format(Values.OldValue);
+
+ /// <summary>The value set as the log shows it (<see cref="Format"/>); "" without <see cref="Values"/>.</summary>
+ public string NewValueText => Values == null ? "" : Format(Values.NewValue);
+
+ /// <summary>A value as the log shows it: numbers and enums invariant, a string in quotes, a byte array by its length, null as "null", anything else by its text.</summary>
+ public static string Format(object? value) => value switch
+ {
+ null => "null",
+ string text => "'" + text + "'",
+ byte[] bytes => "byte[" + bytes.Length.ToString(CultureInfo.InvariantCulture) + "]",
+ IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture),
+ _ => value.ToString() ?? "",
+ };
+
/// <summary>
/// Whether the change alters the frames a run computes: the scene, the solver settings, the seed, a source or an
/// optical part (painted into the scene). Display settings, probes (see <see cref="AffectsProbes"/>) and the
@@ -93,7 +111,7 @@ public sealed class ProjectWatcher : IDisposable
{
Resubscribe();
}
- Changed?.Invoke(this, new ProjectChange(_project, e.PropertyName));
+ Changed?.Invoke(this, new ProjectChange(_project, e.PropertyName, e as PropertyValueChangedEventArgs));
}
private void OnItemPropertyChanged(object? sender, PropertyChangedEventArgs e)
@@ -105,7 +123,7 @@ public sealed class ProjectWatcher : IDisposable
}
if (sender != null)
{
- Changed?.Invoke(this, new ProjectChange(sender, e.PropertyName));
+ Changed?.Invoke(this, new ProjectChange(sender, e.PropertyName, e as PropertyValueChangedEventArgs));
}
}
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index 2218e6f..2ec9254 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -270,6 +270,7 @@ internal static class Program
CheckHistory();
CheckClipboard();
CheckOpenEdges(W, H);
+ CheckWorkGroups();
CheckFrameStore(scene);
CheckPreviewQuality(scene, W, H);
CheckRenderer();
@@ -503,9 +504,11 @@ internal static class Program
project.AddSource().X = 12;
history.Record();
List<object> changed = [];
+ List<ProjectChange> changes = [];
using (var watcher = new ProjectWatcher(project))
{
watcher.Changed += (_, change) => changed.Add(change.Item);
+ watcher.Changed += (_, change) => changes.Add(change);
history.Undo();
int seen = changed.Count;
history.Redo();
@@ -514,6 +517,12 @@ internal static class Program
project.Scene.Width += 1;
Check(seen > 0 && changed.Skip(afterRedo).Contains(project.Sources[0]) && changed.Skip(afterRedo).Contains(project.Scene),
$"a step written back reaches the watcher ({seen} changes), and the restored source and scene are watched");
+ // a change carries the value before and after (2026-10-27), for the log
+ ProjectChange width = changes.Last(c => c.Item == project.Scene && c.Property == nameof(Scene.Width));
+ Check(width.Values is { OldValue: int before, NewValue: int after } && after == before + 1 && width.NewValueText == after.ToString() && width.OldValueText == before.ToString()
+ && ProjectChange.Format(1.5) == "1.5" && ProjectChange.Format("a") == "'a'" && ProjectChange.Format(SourceMode.Pulsed) == "Pulsed" && ProjectChange.Format(null) == "null" && ProjectChange.Format(new byte[3]) == "byte[3]"
+ && changes.Last(c => c.Property == nameof(Source.X)).Values is { OldValue: int, NewValue: 13 },
+ "a change carries the value before and after (" + width.OldValueText + " → " + width.NewValueText + "), formatted invariant");
}
}
@@ -1219,6 +1228,70 @@ internal static class Program
}
/// <summary>Max |u| over the canvas columns <paramref name="x0"/>..<paramref name="x1"/> of a padded field.</summary>
+ /// <summary>
+ /// The GPU on a grid prime in both dimensions (a 103 × 67 canvas with a rim of 32: 167 × 131). With the work-group
+ /// size left to the driver it had to divide the global size, so it was one cell wide there (2026-10-26, Jeroen's
+ /// 1725 px canvas: 13 to 19 times slower); the kernels now run in explicit groups over a global size rounded up to
+ /// whole groups, and the surplus work items must change nothing: the field with the open ring, and both capture
+ /// formats, agree with the CPU.
+ /// </summary>
+ private static void CheckWorkGroups()
+ {
+ Console.WriteLine("--- work groups on a prime grid");
+ const int cw = 103, ch = 67, rim = 32;
+ SceneData scene = SceneData.Empty(cw, ch, -rim, 1.0, true);
+ Check(scene.Width == 167 && scene.Height == 131 && scene.Rim == rim && scene.OpenEdges, "a 103 × 67 canvas with a rim of 32 is a 167 × 131 grid, prime in both dimensions, open");
+ // a second source at the canvas's last cell: the work item at the corner, beside the rounded-up surplus
+ List<Emitter> emitters = [Make(cw / 2, ch / 2, 120, 1.0), Make(cw - 1, ch - 1, 200, 0.7)];
+ var options = new EngineOptions(1.0, 1.0, true, false, 10.0, 1.0);
+ var cpu = new WaveSimulator(scene, options, emitters);
+ Run(cpu, 200);
+ GpuWaveSimulator? gpu = GpuWaveSimulator.TryCreate(scene, options, emitters, out string problems);
+ if (gpu == null)
+ {
+ Console.WriteLine(" skip GPU: " + problems);
+ return;
+ }
+ using (gpu)
+ {
+ Check(gpu.WorkGroup.Width >= 32 && gpu.WorkGroup.Height >= 1, $"wave_step runs in groups of {gpu.WorkGroup.Width} × {gpu.WorkGroup.Height}, not in the driver's divisors of 167");
+ Run(gpu, 200);
+ float tolerance = 2e-3f * Math.Max(1f, MaxAbs(cpu.FieldData));
+ float diff = MaxDiff(cpu.FieldData, gpu.FieldData);
+ Check(diff < tolerance, "the GPU agrees with the CPU on the prime grid, rim and open ring included (max diff " + diff + ")");
+ // the captures at the canvas's own prime size, in both formats, against the CPU's conversion of the same field
+ FrameShape full = FrameShape.Full(cw, ch);
+ FrameShape index = full with { Format = FrameFormat.Index, FieldBrightness = 30f, IntensityBrightness = 5f };
+ int origin = (rim + 1) * cpu.Stride + rim + 1;
+ var halves = new FrameSnapshot(full, true);
+ var indices = new FrameSnapshot(index, true);
+ gpu.CaptureFrame(halves, true);
+ gpu.CaptureFrame(indices, true);
+ gpu.AwaitFrame(halves);
+ gpu.AwaitFrame(indices);
+ var halfBytes = new byte[full.PlaneBytes];
+ FrameConversion.Convert(cpu.FieldData, origin, cpu.Stride, full, false, halfBytes);
+ float worst = 0f;
+ ReadOnlySpan<Half> expected = MemoryMarshal.Cast<byte, Half>(halfBytes);
+ for (int i = 0; i < cw * ch; i++)
+ {
+ worst = Math.Max(worst, Math.Abs((float)expected[i] - (float)halves.Field[i]));
+ }
+ Check(worst < tolerance, "the 16-bit capture of the prime canvas matches the CPU's conversion (worst " + worst + ")");
+ var indexField = new byte[index.PlaneBytes];
+ var indexInten = new byte[index.PlaneBytes];
+ FrameConversion.Convert(cpu.FieldData, origin, cpu.Stride, index, false, indexField);
+ FrameConversion.Convert(cpu.IntensityData!, origin, cpu.Stride, index, true, indexInten);
+ int fieldOff = 0, intenOff = 0;
+ for (int i = 0; i < cw * ch; i++)
+ {
+ fieldOff += Math.Abs(indexField[i] - indices.FieldBytes[i]) > 1 ? 1 : 0;
+ intenOff += Math.Abs(indexInten[i] - indices.IntensityBytes![i]) > 1 ? 1 : 0;
+ }
+ Check(fieldOff == 0 && intenOff == 0, "the 8-bit capture of the prime canvas is within a palette step of the CPU's, field and intensity (" + fieldOff + " / " + intenOff + " cells off)");
+ }
+ }
+
private static float MaxAbsColumns(float[] padded, int W, int H, int x0, int x1)
{
int stride = W + 2;