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#
Wave_Dude_2D: AVI fix, engine refactor, style pass, VB audit applied
Alexander Graefb9d3d2a6824c
diff --git a/Wave_Dude_2D/AboutForm.cs b/Wave_Dude_2D/AboutForm.csindex 38072d3..264d9ac 100644--- a/Wave_Dude_2D/AboutForm.cs+++ b/Wave_Dude_2D/AboutForm.cs@@ -6,34 +6,38 @@ using _2D_wave_sim_V01.My;namespace _2D_wave_sim_V01{/// <summary>- /// "About" dialog: shows the display version, the assembly copyright and the program icon.- /// Opened modally from the Info menu of <see cref="Form1"/>.+ /// The Info > About window: program name, version and a one-paragraph description.+ /// Designer-editable: the layout lives in <c>AboutForm.Designer.cs</c>; this file only fills in+ /// the two pieces of text that are not fixed at design time (the version, from+ /// <see cref="DisplayVersion"/>, and the copyright string, read from the assembly) and loads the+ /// application icon. Opened modally from <see cref="Form1.AboutToolStripMenuItem_Click"/>./// </summary>public partial class AboutForm : Form{/// <summary>/// Fills in the version and copyright labels and the icon associated with the running- /// executable. The icon is optional: any failure to extract it is swallowed and the- /// picture box stays empty.+ /// executable. The icon is optional: when none is available (e.g. running outside a normal+ /// exe) the failure is swallowed and the picture box just stays empty./// </summary>public AboutForm(){- base.Load += this.AboutForm_Load;- this.InitializeComponent();- this.lblVersion.Text = "Version " + DisplayVersion;- this.lblCopyright.Text = MyProject.Application.Info.Copyright;+ base.Load += AboutForm_Load;+ InitializeComponent();+ lblVersion.Text = "Version " + DisplayVersion;+ lblCopyright.Text = MyProject.Application.Info.Copyright;try{using (Icon icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath)){if (icon != null){- this.picIcon.Image = icon.ToBitmap();+ picIcon.Image = icon.ToBitmap();}}}catch{+ // no icon available (e.g. running outside a normal exe) - the picture box just stays empty}}@@ -42,7 +46,12 @@ namespace _2D_wave_sim_V01{}- /// <summary>Version text shown in the dialog. A hand-maintained literal, not derived from the assembly version.</summary>+ /// <summary>+ /// Version text shown in the dialog. A hand-maintained literal, meant to be kept in sync by+ /// hand with the version in <see cref="Form1"/>'s title bar ("Wave Dude 2D V0.29", set in+ /// <c>Form1.Designer.cs</c>), since <c>AssemblyInfo.cs</c>'s <c>AssemblyVersion</c> is left at+ /// the generic 1.0.0.0 and does not track it. It currently lags behind the title bar.+ /// </summary>private const string DisplayVersion = "0.27";}}diff --git a/Wave_Dude_2D/AppSettings.cs b/Wave_Dude_2D/AppSettings.csindex f4b553d..e7fcb98 100644--- a/Wave_Dude_2D/AppSettings.cs+++ b/Wave_Dude_2D/AppSettings.cs@@ -18,9 +18,9 @@ namespace _2D_wave_sim_V01/// <summary>Starts with all three values empty (no root chosen, no project remembered).</summary>public AppSettings(){- this.LastRootFolder = "";- this.LastProjectName = "";- this.ProjectRoot = "";+ LastRootFolder = "";+ LastProjectName = "";+ ProjectRoot = "";}/// <summary>@@ -36,7 +36,10 @@ namespace _2D_wave_sim_V01public string LastProjectName { get; set; }/// <summary>- /// The folder that contains the user's project folders (File > Choose project root).+ /// The root folder browsed on the Configuration tab (<c>lstAllProjects</c>, File > Choose project+ /// root), i.e. the folder that contains the user's project folders. Distinct from+ /// <see cref="LastRootFolder"/> / <see cref="LastProjectName"/>, which remember the project that was+ /// actually open last, not necessarily the folder being browsed for other projects to switch to./// Empty until the user has chosen one; <see cref="Form1"/> keeps most of the UI disabled/// while it is empty./// </summary>@@ -73,6 +76,7 @@ namespace _2D_wave_sim_V01}catch{+ // use the defaults}return settings;}@@ -88,14 +92,15 @@ namespace _2D_wave_sim_V01string path = AppSettings.SettingsFilePath();Directory.CreateDirectory(Path.GetDirectoryName(path));Dictionary<string, string> values = new Dictionary<string, string>();- values[KeyRootFolder] = this.LastRootFolder;- values[KeyProjectName] = this.LastProjectName;- values[KeyProjectRoot] = this.ProjectRoot;+ values[KeyRootFolder] = LastRootFolder;+ values[KeyProjectName] = LastProjectName;+ values[KeyProjectRoot] = ProjectRoot;JavaScriptSerializer serializer = new JavaScriptSerializer();File.WriteAllText(path, serializer.Serialize(values), new UTF8Encoding(false));}catch{+ // the settings are a convenience only}}diff --git a/Wave_Dude_2D/AviFrameSink.cs b/Wave_Dude_2D/AviFrameSink.csindex e6ae2a8..436a826 100644--- a/Wave_Dude_2D/AviFrameSink.cs+++ b/Wave_Dude_2D/AviFrameSink.cs@@ -8,7 +8,8 @@ namespace _2D_wave_sim_V01/// <summary>/// <see cref="IFrameSink"/> that JPEG-encodes each frame with the GDI+ encoder and appends it to a Motion-JPEG/// AVI through <see cref="AviMjpegWriter"/>. Fallback used by <see cref="SimulationRunner"/> when MP4 is not- /// requested or Media Foundation is unavailable. Used from the worker thread only.+ /// requested or Media Foundation is unavailable: needs no codec on this computer, but Windows' own players do not+ /// play it; VLC does. Used from the worker thread only./// </summary>internal sealed class AviFrameSink : IFrameSink{@@ -20,22 +21,16 @@ namespace _2D_wave_sim_V01/// <param name="quality">JPEG quality 1..100 passed to the GDI+ encoder.</param>public AviFrameSink(string filePath, int width, int height, int framesPerSecond, int quality){- this._buffer = new MemoryStream();- this._jpegQuality = Math.Max(1, Math.Min(100, quality));- this._path = filePath;- this._width = width;- this._height = height;- this._writer = new AviMjpegWriter(filePath, width, height, framesPerSecond);+ _buffer = new MemoryStream();+ _jpegQuality = Math.Max(1, Math.Min(100, quality));+ _path = filePath;+ _width = width;+ _height = height;+ _writer = new AviMjpegWriter(filePath, width, height, framesPerSecond);}/// <summary>The AVI path given to the constructor.</summary>- public string FilePath- {- get- {- return this._path;- }- }+ public string FilePath => _path;/// <summary>/// Wraps the ARGB buffer in a temporary bitmap, JPEG-encodes it into the reusable <see cref="_buffer"/>@@ -43,29 +38,29 @@ namespace _2D_wave_sim_V01/// </summary>public void AddPixels(int[] pixels){- using (Bitmap bitmap = FrameRenderer.ToBitmap(pixels, this._width, this._height))+ using (Bitmap bitmap = FrameRenderer.ToBitmap(pixels, _width, _height)){- this._buffer.SetLength(0L);+ _buffer.SetLength(0L);using (EncoderParameters encoderParameters = new EncoderParameters(1)){- encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, this._jpegQuality);- bitmap.Save(this._buffer, AviFrameSink.JpegCodec, encoderParameters);+ encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, _jpegQuality);+ bitmap.Save(_buffer, AviFrameSink.JpegCodec, encoderParameters);}- this._writer.AddFrame(this._buffer.GetBuffer(), (int)this._buffer.Length);+ _writer.AddFrame(_buffer.GetBuffer(), (int)_buffer.Length);}}/// <summary>Writes the AVI index and header patches and closes the file (idempotent).</summary>public void Close(){- this._writer.Close();+ _writer.Close();}/// <summary>Closes the AVI (if not already) and releases the encode buffer.</summary>public void Dispose(){- this._writer.Close();- this._buffer.Dispose();+ _writer.Close();+ _buffer.Dispose();}/// <summary>Finds the GDI+ JPEG encoder; runs once in the static initializer.</summary>diff --git a/Wave_Dude_2D/AviMjpegWriter.cs b/Wave_Dude_2D/AviMjpegWriter.csindex 3de9ee3..f973870 100644--- a/Wave_Dude_2D/AviMjpegWriter.cs+++ b/Wave_Dude_2D/AviMjpegWriter.cs@@ -6,13 +6,15 @@ using System.Text;namespace _2D_wave_sim_V01{/// <summary>- /// Minimal Motion-JPEG AVI (RIFF) writer, single video stream, no audio. The constructor writes the- /// fixed-size header, <see cref="AddFrame"/> appends one <c>00dc</c> chunk per JPEG to the <c>movi</c>- /// list and <see cref="Close"/> appends the <c>idx1</c> index and patches the size/count fields in the- /// header. Used by <see cref="AviFrameSink"/>. All values are little-endian.+ /// Minimal Motion-JPEG AVI (RIFF) writer, single video stream, no audio. Every frame is given as an+ /// ordinary JPEG image, so no codec or external program is needed; VLC and most video editors play the+ /// file, and a program like ffmpeg can convert it to MP4. The constructor writes the fixed-size header,+ /// <see cref="AddFrame"/> appends one <c>00dc</c> chunk per JPEG to the <c>movi</c> list and+ /// <see cref="Close"/> appends the <c>idx1</c> index and patches the size/count fields in the header.+ /// Used by <see cref="AviFrameSink"/>. All values are little-endian./// </summary>/// <remarks>- /// <para>Intended layout (byte offsets), which is what the <c>Pos*</c> constants encode:</para>+ /// Layout (byte offsets), which is what the <c>Pos*</c> constants encode:/// <list type="table">/// <item><term>0</term><description><c>RIFF</c>, file size - 8 (patched at <see cref="PosRiffSize"/>), <c>AVI </c></description></item>/// <item><term>12</term><description><c>LIST</c> 192 <c>hdrl</c></description></item>@@ -23,12 +25,6 @@ namespace _2D_wave_sim_V01/// <item><term>212</term><description><c>LIST</c> movi size (patched at <see cref="PosMoviSize"/>) <c>movi</c> at <see cref="PosMoviTag"/>, then the frame chunks</description></item>/// <item><term>end</term><description><c>idx1</c>: one 16-byte entry per frame (<c>00dc</c>, flags = AVIIF_KEYFRAME, offset relative to <see cref="PosMoviTag"/>, size)</description></item>/// </list>- /// <para>Note (writes are deliberately left as they are): the constructor emits 236 header bytes rather- /// than 224, because <c>strh</c> is written as 64 bytes (an extra zero DWORD before scale/rate, and- /// rcFrame as two ints plus two ushorts) and <c>strf</c> as 44 bytes (planes and bit count as ints).- /// The <c>Pos*</c> offsets therefore no longer line up with the bytes actually written: the <c>movi</c>- /// tag is really at 232, <see cref="PosMoviSize"/> hits the BITMAPINFOHEADER and the real <c>movi</c>- /// list size stays 0. Odd-length frames are padded with a 4-byte int, not a single byte.</para>/// </remarks>internal sealed class AviMjpegWriter : IDisposable{@@ -39,92 +35,84 @@ namespace _2D_wave_sim_V01/// <param name="framesPerSecond">Playback rate; stored as microseconds per frame in <c>avih</c> and as the rate in <c>strh</c>.</param>public AviMjpegWriter(string filePath, int width, int height, int framesPerSecond){- this._offsets = new List<int>();- this._sizes = new List<int>();- this._stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read);- this._writer = new BinaryWriter(this._stream);+ _stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read);+ _writer = new BinaryWriter(_stream);Encoding ascii = Encoding.ASCII;// RIFF header- this._writer.Write(ascii.GetBytes("RIFF"));- this._writer.Write(0U); // file size - 8, patched in Close- this._writer.Write(ascii.GetBytes("AVI "));+ _writer.Write(ascii.GetBytes("RIFF"));+ _writer.Write(0U); // file size - 8, patched in Close+ _writer.Write(ascii.GetBytes("AVI "));// LIST hdrl- this._writer.Write(ascii.GetBytes("LIST"));- this._writer.Write(192U);- this._writer.Write(ascii.GetBytes("hdrl"));- // avih (MainAVIHeader)- this._writer.Write(ascii.GetBytes("avih"));- this._writer.Write(56U);- this._writer.Write((uint)(1000000 / framesPerSecond)); // dwMicroSecPerFrame- this._writer.Write(0U); // dwMaxBytesPerSec- this._writer.Write(0U); // dwPaddingGranularity- this._writer.Write(16U); // dwFlags = AVIF_HASINDEX- this._writer.Write(0U); // dwTotalFrames, patched in Close- this._writer.Write(0U); // dwInitialFrames- this._writer.Write(1U); // dwStreams- this._writer.Write(0U); // dwSuggestedBufferSize, patched in Close- this._writer.Write((uint)width);- this._writer.Write((uint)height);+ _writer.Write(ascii.GetBytes("LIST"));+ _writer.Write(192U); // 'hdrl' + avih chunk (64) + strl list chunk (124)+ _writer.Write(ascii.GetBytes("hdrl"));+ // avih (MainAVIHeader, 56 bytes)+ _writer.Write(ascii.GetBytes("avih"));+ _writer.Write(56U);+ _writer.Write((uint)(1000000 / framesPerSecond)); // dwMicroSecPerFrame+ _writer.Write(0U); // dwMaxBytesPerSec+ _writer.Write(0U); // dwPaddingGranularity+ _writer.Write(AvifHasIndex); // dwFlags+ _writer.Write(0U); // dwTotalFrames, patched in Close+ _writer.Write(0U); // dwInitialFrames+ _writer.Write(1U); // dwStreams+ _writer.Write(0U); // dwSuggestedBufferSize, patched in Close+ _writer.Write((uint)width);+ _writer.Write((uint)height);for (int i = 0; i < 4; i++){- this._writer.Write(0U); // dwReserved[4]+ _writer.Write(0U); // dwReserved[4]}// LIST strl- this._writer.Write(ascii.GetBytes("LIST"));- this._writer.Write(116U);- this._writer.Write(ascii.GetBytes("strl"));- // strh (AVISTREAMHEADER)- this._writer.Write(ascii.GetBytes("strh"));- this._writer.Write(56U);- this._writer.Write(ascii.GetBytes("vids")); // fccType- this._writer.Write(ascii.GetBytes("MJPG")); // fccHandler- this._writer.Write(0U); // dwFlags- this._writer.Write(0); // wPriority + wLanguage- this._writer.Write(0); // dwInitialFrames- this._writer.Write(0U); // extra DWORD (see class remarks); lands on dwScale- this._writer.Write(1U); // intended dwScale; lands on dwRate- this._writer.Write((uint)framesPerSecond); // intended dwRate; lands on dwStart- this._writer.Write(0U); // dwLength, patched in Close- this._writer.Write(0U); // dwSuggestedBufferSize, patched in Close- this._writer.Write(0U); // dwQuality- this._writer.Write(uint.MaxValue); // dwSampleSize (-1)- this._writer.Write(0U); // rcFrame left/top- this._writer.Write(0); // rcFrame right/bottom- this._writer.Write(0); // extra DWORD (see class remarks)- this._writer.Write((ushort)width); // extra; beyond the declared 56 bytes- this._writer.Write((ushort)height);- // strf (BITMAPINFOHEADER)- this._writer.Write(ascii.GetBytes("strf"));- this._writer.Write(40U);- this._writer.Write(40U); // biSize- this._writer.Write(width); // biWidth- this._writer.Write(height); // biHeight- this._writer.Write(1); // biPlanes (written as a DWORD, should be a WORD)- this._writer.Write(24); // biBitCount (written as a DWORD, should be a WORD)- this._writer.Write(ascii.GetBytes("MJPG")); // biCompression- this._writer.Write((uint)(((long)width * height * 3L) & 0xFFFFFFFFL)); // biSizeImage- this._writer.Write(0); // biXPelsPerMeter- this._writer.Write(0); // biYPelsPerMeter- this._writer.Write(0U); // biClrUsed- this._writer.Write(0U); // biClrImportant+ _writer.Write(ascii.GetBytes("LIST"));+ _writer.Write(116U); // 'strl' + strh chunk (64) + strf chunk (48)+ _writer.Write(ascii.GetBytes("strl"));+ // strh (AVISTREAMHEADER, 56 bytes)+ _writer.Write(ascii.GetBytes("strh"));+ _writer.Write(56U);+ _writer.Write(ascii.GetBytes("vids")); // fccType+ _writer.Write(ascii.GetBytes("MJPG")); // fccHandler+ _writer.Write(0U); // dwFlags+ _writer.Write((ushort)0); // wPriority+ _writer.Write((ushort)0); // wLanguage+ _writer.Write(0U); // dwInitialFrames+ _writer.Write(1U); // dwScale+ _writer.Write((uint)framesPerSecond); // dwRate (frames per second = dwRate / dwScale)+ _writer.Write(0U); // dwStart+ _writer.Write(0U); // dwLength, patched in Close+ _writer.Write(0U); // dwSuggestedBufferSize, patched in Close+ _writer.Write(0xFFFFFFFFU); // dwQuality: -1 = default+ _writer.Write(0U); // dwSampleSize (0 = variable, one frame per chunk)+ _writer.Write((ushort)0); // rcFrame.left+ _writer.Write((ushort)0); // rcFrame.top+ _writer.Write((ushort)width); // rcFrame.right+ _writer.Write((ushort)height); // rcFrame.bottom+ // strf (BITMAPINFOHEADER, 40 bytes)+ _writer.Write(ascii.GetBytes("strf"));+ _writer.Write(40U);+ _writer.Write(40U); // biSize+ _writer.Write(width); // biWidth+ _writer.Write(height); // biHeight+ _writer.Write((ushort)1); // biPlanes+ _writer.Write((ushort)24); // biBitCount+ _writer.Write(ascii.GetBytes("MJPG")); // biCompression+ _writer.Write((uint)(((long)width * height * 3L) & 0xFFFFFFFFL)); // biSizeImage+ _writer.Write(0); // biXPelsPerMeter+ _writer.Write(0); // biYPelsPerMeter+ _writer.Write(0U); // biClrUsed+ _writer.Write(0U); // biClrImportant// LIST movi; frames follow- this._writer.Write(ascii.GetBytes("LIST"));- this._writer.Write(0U); // movi size, patched in Close- this._writer.Write(ascii.GetBytes("movi"));+ _writer.Write(ascii.GetBytes("LIST"));+ _writer.Write(0U); // movi size, patched in Close+ _writer.Write(ascii.GetBytes("movi"));}/// <summary>Number of frames appended so far.</summary>- public int FrameCount- {- get- {- return this._offsets.Count;- }- }+ public int FrameCount => _offsets.Count;/// <summary>/// Appends one JPEG frame as a <c>00dc</c> chunk and records its offset/size for the index. Odd lengths- /// are followed by a pad (written as a 4-byte int, see class remarks).+ /// are followed by one RIFF pad byte./// </summary>/// <param name="data">Buffer holding the JPEG; only the first <paramref name="length"/> bytes are used.</param>/// <param name="length">Number of JPEG bytes.</param>@@ -132,27 +120,27 @@ namespace _2D_wave_sim_V01/// <exception cref="IOException">The frame plus the index that would follow would push the file past <see cref="MaxAviBytes"/>.</exception>public void AddFrame(byte[] data, int length){- if (this._closed)+ if (_closed){throw new InvalidOperationException("The video file is already closed.");}// Reserve room for the idx1 that Close() will append (16 bytes per frame plus slack).- if (this._stream.Position + length + 16L * (this._offsets.Count + 2) + 64L > MaxAviBytes)+ if (_stream.Position + length + 16L * (_offsets.Count + 2) + 64L > MaxAviBytes){throw new IOException("The video file would become larger than 4 GB, which the AVI format does not allow.");}- this._offsets.Add((int)(this._stream.Position - PosMoviTag));- this._sizes.Add(length);- this._writer.Write(Encoding.ASCII.GetBytes("00dc"));- this._writer.Write((uint)length);- this._writer.Write(data, 0, length);+ _offsets.Add((int)(_stream.Position - PosMoviTag));+ _sizes.Add(length);+ _writer.Write(Encoding.ASCII.GetBytes("00dc"));+ _writer.Write((uint)length);+ _writer.Write(data, 0, length);if ((length & 1) == 1){- this._writer.Write(0); // 4-byte pad (int), not the 1-byte RIFF pad+ _writer.Write((byte)0); // RIFF chunks are word-aligned}- if (length > this._largestFrame)+ if (length > _largestFrame){- this._largestFrame = length;+ _largestFrame = length;}}@@ -162,57 +150,57 @@ namespace _2D_wave_sim_V01/// </summary>public void Close(){- if (this._closed)+ if (_closed){return;}- this._closed = true;+ _closed = true;try{- long indexPosition = this._stream.Position;- this._writer.Write(Encoding.ASCII.GetBytes("idx1"));- this._writer.Write((uint)(16 * this._offsets.Count));- for (int i = 0; i < this._offsets.Count; i++)+ long indexPosition = _stream.Position;+ _writer.Write(Encoding.ASCII.GetBytes("idx1"));+ _writer.Write((uint)(16 * _offsets.Count));+ for (int i = 0; i < _offsets.Count; i++){- this._writer.Write(Encoding.ASCII.GetBytes("00dc"));- this._writer.Write(16U); // AVIIF_KEYFRAME- this._writer.Write((uint)this._offsets[i]);- this._writer.Write((uint)this._sizes[i]);+ _writer.Write(Encoding.ASCII.GetBytes("00dc"));+ _writer.Write(AviifKeyframe);+ _writer.Write((uint)_offsets[i]);+ _writer.Write((uint)_sizes[i]);}- long endPosition = this._stream.Position;- this.Patch(PosRiffSize, (uint)(endPosition - 8L));- this.Patch(PosTotalFrames, (uint)this._offsets.Count);- this.Patch(PosBufferSize, (uint)this._largestFrame);- this.Patch(PosStreamLength, (uint)this._offsets.Count);- this.Patch(PosStreamBufferSize, (uint)this._largestFrame);- this.Patch(PosMoviSize, (uint)(indexPosition - PosMoviSize));- this._writer.Flush();+ long endPosition = _stream.Position;+ Patch(PosRiffSize, (uint)(endPosition - 8L));+ Patch(PosTotalFrames, (uint)_offsets.Count);+ Patch(PosBufferSize, (uint)_largestFrame);+ Patch(PosStreamLength, (uint)_offsets.Count);+ Patch(PosStreamBufferSize, (uint)_largestFrame);+ Patch(PosMoviSize, (uint)(indexPosition - PosMoviTag)); // LIST size counts from its fourcc+ _writer.Flush();}finally{- this._writer.Close();- this._stream.Dispose();+ _writer.Close();+ _stream.Dispose();}}/// <summary>Seeks to <paramref name="position"/> and overwrites one DWORD; leaves the stream positioned after it.</summary>private void Patch(long position, uint value){- this._stream.Seek(position, SeekOrigin.Begin);- this._writer.Write(value);+ _stream.Seek(position, SeekOrigin.Begin);+ _writer.Write(value);}/// <summary>Same as <see cref="Close"/>.</summary>- public void Dispose()- {- this.Close();- }+ public void Dispose() => Close();- /// <summary>Hard cap on the file size in bytes, kept safely below the 4 GB RIFF limit.</summary>+ /// <summary>Hard cap on the file size in bytes. AVI files are limited to 4 GB (unsigned 32 bit sizes); this stops safely before that.</summary>private const long MaxAviBytes = 3900000000L;- /// <summary>Unused duplicate of <see cref="MaxAviBytes"/>.</summary>- private const long MaxFileSize = 3900000000L;+ /// <summary>avih.dwFlags: the file has an <c>idx1</c> index.</summary>+ private const uint AvifHasIndex = 0x10;++ /// <summary>idx1 entry flag: the chunk is a key frame (every MJPEG frame is).</summary>+ private const uint AviifKeyframe = 0x10;/// <summary>Offset of the RIFF size DWORD (file size - 8).</summary>private const long PosRiffSize = 4L;@@ -229,23 +217,23 @@ namespace _2D_wave_sim_V01/// <summary>Offset of strh.dwSuggestedBufferSize (largest frame).</summary>private const long PosStreamBufferSize = 144L;- /// <summary>Intended offset of the movi LIST size DWORD (actually written at 228, see class remarks).</summary>+ /// <summary>Offset of the movi LIST size DWORD.</summary>private const long PosMoviSize = 216L;- /// <summary>Intended offset of the <c>movi</c> tag; idx1 offsets are relative to this (the tag is actually written at 232, see class remarks).</summary>+ /// <summary>Offset of the <c>movi</c> fourcc; idx1 chunk offsets are relative to this.</summary>private const long PosMoviTag = 220L;/// <summary>The output file; disposed by <see cref="Close"/>.</summary>- private FileStream _stream;+ private readonly FileStream _stream;/// <summary>Little-endian writer over <see cref="_stream"/>.</summary>- private BinaryWriter _writer;+ private readonly BinaryWriter _writer;/// <summary>Per frame: chunk offset relative to <see cref="PosMoviTag"/>, for idx1.</summary>- private readonly List<int> _offsets;+ private readonly List<int> _offsets = new List<int>();/// <summary>Per frame: JPEG byte count, for idx1.</summary>- private readonly List<int> _sizes;+ private readonly List<int> _sizes = new List<int>();/// <summary>Largest JPEG so far, in bytes; becomes the suggested buffer size.</summary>private int _largestFrame;diff --git a/Wave_Dude_2D/ColorLut.cs b/Wave_Dude_2D/ColorLut.csindex 820226e..de46d50 100644--- a/Wave_Dude_2D/ColorLut.cs+++ b/Wave_Dude_2D/ColorLut.cs@@ -5,51 +5,55 @@ namespace _2D_wave_sim_V01{/// <summary>/// An immutable palette of <see cref="Size"/> opaque ARGB entries built from a- /// <see cref="ColorScheme"/> by <see cref="Build"/>, plus the static value-to-index- /// mappings used when colouring frames. Built on the UI thread when a simulation is- /// started; the <see cref="Argb"/> array is then handed to <see cref="SimulationRunner"/>- /// and read from <see cref="FrameRenderer"/>'s parallel loops without locking (it is- /// never modified after construction).+ /// <see cref="ColorScheme"/> by <see cref="Build"/> plus the display options of the Python+ /// function <c>get_colormap_lut</c> (invert, black level, make symmetric), and the static+ /// value-to-index mappings used when colouring frames, which convert field and intensity+ /// values to table indices exactly like <c>WaveVisualizer.render_field</c> /+ /// <c>render_intensity</c>. Built on the UI thread when a simulation is started; the+ /// <see cref="Argb"/> array is then handed to <see cref="SimulationRunner"/> and read from+ /// <see cref="FrameRenderer"/>'s parallel loops without locking (it is never modified after+ /// construction)./// </summary>+ /// <remarks>+ /// The options belong to how a scheme is used in a simulation (field or intensity), not to+ /// the scheme itself, so they are not saved in the scheme file; they live in+ /// <see cref="SimulationSettings"/> and are applied here at run start.+ /// </remarks>public sealed class ColorLut{private ColorLut(int[] argb){- this._argb = argb;+ _argb = argb;}/// <summary>/// The palette as packed opaque ARGB ints (<see cref="Color.ToArgb"/> layout), indices/// 0..<see cref="Size"/>-1. Returns the internal array, not a copy; callers must not modify it./// </summary>- public int[] Argb- {- get- {- return this._argb;- }- }+ public int[] Argb => _argb;/// <summary>Returns entry <paramref name="index"/> (0..<see cref="Size"/>-1) as a <see cref="Color"/>.</summary>public Color ColorAt(int index){- return Color.FromArgb(this._argb[index]);+ return Color.FromArgb(_argb[index]);}/// <summary>/// Builds a palette from the <see cref="Size"/> entries of <paramref name="scheme"/>.- /// Transformations are applied in this order: <paramref name="reverse"/> (entry i is read- /// from entry <c>Size-1-i</c>), <paramref name="invert"/> (each channel becomes- /// <c>1 - channel</c>), <paramref name="makeSymmetric"/> (entry i is read from entry- /// <c>2 * min(i, Size-1-i)</c>, so the palette runs from entry 0 at both ends up to entry- /// 254 in the middle), then <paramref name="blackLevel"/> lifts every channel linearly so- /// that 0 becomes <paramref name="blackLevel"/> and 1 stays 1, clamped to 0..1. Alpha is always 255.+ /// Transformations are applied in the same order as in Python: <paramref name="reverse"/>+ /// (new, optional; entry i is read from entry <c>Size-1-i</c>), <paramref name="invert"/>+ /// (each channel becomes <c>1 - channel</c>), <paramref name="makeSymmetric"/> (entry i is+ /// read from entry <c>2 * min(i, Size-1-i)</c>, so the palette runs from entry 0 at both+ /// ends up to entry 254 in the middle), then <paramref name="blackLevel"/> maps every+ /// channel linearly as <c>c * (1 - b) + b</c>, so 0 becomes <paramref name="blackLevel"/>+ /// and 1 stays 1. Values are limited to 0..1 and converted to 8 bit by truncation, like+ /// the Python code. Alpha is always 255./// </summary>/// <param name="scheme">Source colours; must have at least <see cref="Size"/> entries.</param>- /// <param name="invert">Invert every channel (negative image).</param>- /// <param name="blackLevel">Minimum channel level 0..1 after lifting (0 = unchanged).</param>- /// <param name="makeSymmetric">Mirror the palette around its centre index.</param>- /// <param name="reverse">Read the scheme back to front.</param>+ /// <param name="invert">Replaces every colour by its complement (1 - colour), like the Python option.</param>+ /// <param name="blackLevel">Lifts (positive) or lowers (negative) the darkest level; 0 = unchanged.</param>+ /// <param name="makeSymmetric">Squeezes the whole scheme into each half and mirrors it around the centre.</param>+ /// <param name="reverse">Reverses the order of the scheme (like matplotlib's <c>_r</c> maps).</param>/// <exception cref="ArgumentNullException"><paramref name="scheme"/> is null.</exception>public static ColorLut Build(ColorScheme scheme, bool invert = false, double blackLevel = 0.0, bool makeSymmetric = false, bool reverse = false){@@ -78,6 +82,8 @@ namespace _2D_wave_sim_V01int[] argb = new int[Size];for (int i = 0; i < Size; i++){+ // Python: entries 0..127 = src[0::2] and entries 127..254 = the same list mirrored,+ // which is entry i = src[2 * min(i, 254 - i)]int sourceIndex = i;if (makeSymmetric){@@ -108,9 +114,10 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Maps a signed field sample to a palette index: <c>value * brightness</c> is clamped to- /// -1..1 and mapped linearly to 0..254 with 0 at index 127. NaN gives 127. Called per- /// pixel from <see cref="FrameRenderer.RenderField"/> on worker threads.+ /// Maps a signed field sample to a palette index, like <c>render_field</c>:+ /// <c>clip(value * brightness, -1, 1) * 127 + 127</c>, so the result is 0..254 and a zero+ /// field gives index 127 (the centre colour). NaN gives 127. Called per pixel from+ /// <see cref="FrameRenderer.RenderField"/> on worker threads./// </summary>/// <param name="value">Raw field amplitude from the engine.</param>/// <param name="brightness">Gain applied before clamping.</param>@@ -133,14 +140,14 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Maps a non-negative intensity to a palette index 0..254: <c>intensity ^ exponent</c>- /// (square root by default) times <paramref name="brightness"/>, clamped to 0..1 and- /// scaled to 254. NaN or non-positive intensity gives 0. Not currently called;- /// <see cref="FrameRenderer.RenderIntensity"/> inlines the equivalent square-root mapping.+ /// Maps a non-negative intensity to a palette index 0..254, like <c>render_intensity</c>:+ /// <c>clip(intensity ^ exponent * brightness, 0, 1) * 254</c>. NaN or non-positive+ /// intensity gives 0. Not currently called; <see cref="FrameRenderer.RenderIntensity"/>+ /// inlines the equivalent square-root mapping./// </summary>/// <param name="intensity">Accumulated intensity from the engine.</param>/// <param name="brightness">Gain applied after compression.</param>- /// <param name="exponent">Compression exponent; 0.5 = square root.</param>+ /// <param name="exponent">Compression exponent; 0.5 (square root) is the Python default.</param>public static int IntensityIndex(float intensity, float brightness, float exponent = 0.5f){if (float.IsNaN(intensity) || intensity <= 0f)@@ -159,8 +166,8 @@ namespace _2D_wave_sim_V01return (int)(scaled * 254.0);}- /// <summary>Number of entries in a palette (255, matching <see cref="ColorScheme.EntryCount"/>).</summary>- public const int Size = 255;+ /// <summary>Number of entries in a palette: <see cref="ColorScheme.EntryCount"/> (255).</summary>+ public const int Size = ColorScheme.EntryCount;/// <summary>The packed opaque ARGB entries; never modified after construction.</summary>private readonly int[] _argb;diff --git a/Wave_Dude_2D/ColorPickerControl.cs b/Wave_Dude_2D/ColorPickerControl.csindex 2e2c6e2..ff683f5 100644--- a/Wave_Dude_2D/ColorPickerControl.cs+++ b/Wave_Dude_2D/ColorPickerControl.cs@@ -16,6 +16,7 @@ namespace _2D_wave_sim_V01/// "More..." button that opens the standard <see cref="ColorDialog"/>. The layout is fixed for a/// 423 x 411 client area. <see cref="ColorChanged"/> is raised for user edits only, not when/// <see cref="SelectedColor"/> is assigned from code. UI thread only.+ /// It is built completely in code, so it has no designer file (hence <c>DesignerCategory("Code")</c>)./// </summary>[DesignerCategory("Code")]public class ColorPickerControl : UserControl@@ -32,37 +33,37 @@ namespace _2D_wave_sim_V01/// </summary>public ColorPickerControl(){- this._svRect = new Rectangle(10, 10, 300, 300);- this._hueRect = new Rectangle(326, 10, 28, 300);- this._newRect = new Rectangle(10, 324, 150, 36);- this._oldRect = new Rectangle(160, 324, 150, 36);- this._lblHex = new Label();- this._txtHex = new TextBox();- this._lblRgb = new Label();- this._btnDialog = new Button();- this._color = Color.Red;- this._original = Color.Gray;- this._svHue = -1.0;+ _svRect = new Rectangle(10, 10, 300, 300);+ _hueRect = new Rectangle(326, 10, 28, 300);+ _newRect = new Rectangle(10, 324, 150, 36);+ _oldRect = new Rectangle(160, 324, 150, 36);+ _lblHex = new Label();+ _txtHex = new TextBox();+ _lblRgb = new Label();+ _btnDialog = new Button();+ _color = Color.Red;+ _original = Color.Gray;+ _svHue = -1.0;base.SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);base.Size = new Size(423, 411);- this._lblHex.Text = "Hex";- this._lblHex.AutoSize = true;- this._lblHex.Location = new Point(10, 377);- this._txtHex.Location = new Point(48, 373);- this._txtHex.Width = 90;- this._txtHex.MaxLength = 7;- this._lblRgb.AutoSize = true;- this._lblRgb.Location = new Point(152, 377);- this._btnDialog.Text = "More...";- this._btnDialog.Location = new Point(326, 324);- this._btnDialog.Size = new Size(90, 36);- base.Controls.Add(this._lblHex);- base.Controls.Add(this._txtHex);- base.Controls.Add(this._lblRgb);- base.Controls.Add(this._btnDialog);- this._txtHex.TextChanged += this.HexTextChanged;- this._btnDialog.Click += this.DialogButtonClick;- this.ApplyColor(Color.Red, false, false);+ _lblHex.Text = "Hex";+ _lblHex.AutoSize = true;+ _lblHex.Location = new Point(10, 377);+ _txtHex.Location = new Point(48, 373);+ _txtHex.Width = 90;+ _txtHex.MaxLength = 7;+ _lblRgb.AutoSize = true;+ _lblRgb.Location = new Point(152, 377);+ _btnDialog.Text = "More...";+ _btnDialog.Location = new Point(326, 324);+ _btnDialog.Size = new Size(90, 36);+ base.Controls.Add(_lblHex);+ base.Controls.Add(_txtHex);+ base.Controls.Add(_lblRgb);+ base.Controls.Add(_btnDialog);+ _txtHex.TextChanged += HexTextChanged;+ _btnDialog.Click += DialogButtonClick;+ ApplyColor(Color.Red, false, false);}/// <summary>@@ -71,26 +72,17 @@ namespace _2D_wave_sim_V01/// </summary>public Color SelectedColor{- get- {- return this._color;- }- set- {- this.ApplyColor(value, false, false);- }+ get => _color;+ set => ApplyColor(value, false, false);}/// <summary>The reference colour shown in the "Old" swatch and restored when it is clicked; alpha is discarded.</summary>public Color OriginalColor{- get- {- return this._original;- }+ get => _original;set{- this._original = Color.FromArgb(value.R, value.G, value.B);+ _original = Color.FromArgb(value.R, value.G, value.B);base.Invalidate();}}@@ -105,22 +97,22 @@ namespace _2D_wave_sim_V01/// <param name="fromHexBox">Leave the hex box untouched because the user is typing in it.</param>private void ApplyColor(Color c, bool raiseChanged, bool fromHexBox){- this._color = Color.FromArgb(c.R, c.G, c.B);+ _color = Color.FromArgb(c.R, c.G, c.B);double hue = 0.0;double saturation = 0.0;double value = 0.0;- ColorPickerControl.RgbToHsv(this._color, ref hue, ref saturation, ref value);+ ColorPickerControl.RgbToHsv(_color, ref hue, ref saturation, ref value);if (saturation > 0.0 && value > 0.0){- this._h = hue;+ _h = hue;}- this._s = saturation;- this._v = value;- this.UpdateTexts(fromHexBox);+ _s = saturation;+ _v = value;+ UpdateTexts(fromHexBox);base.Invalidate();if (raiseChanged){- EventHandler colorChangedEvent = this.ColorChanged;+ EventHandler colorChangedEvent = ColorChanged;if (colorChangedEvent != null){colorChangedEvent(this, EventArgs.Empty);@@ -131,10 +123,10 @@ namespace _2D_wave_sim_V01/// <summary>Recomputes the colour from <see cref="_h"/>/<see cref="_s"/>/<see cref="_v"/> after a drag, updates the texts, repaints and raises <see cref="ColorChanged"/>.</summary>private void SyncFromHsv(){- this._color = ColorPickerControl.HsvToColor(this._h, this._s, this._v);- this.UpdateTexts(false);+ _color = ColorPickerControl.HsvToColor(_h, _s, _v);+ UpdateTexts(false);base.Invalidate();- EventHandler colorChangedEvent = this.ColorChanged;+ EventHandler colorChangedEvent = ColorChanged;if (colorChangedEvent != null){colorChangedEvent(this, EventArgs.Empty);@@ -147,29 +139,29 @@ namespace _2D_wave_sim_V01/// </summary>private void UpdateTexts(bool skipHexBox){- this._updatingText = true;+ _updatingText = true;try{if (!skipHexBox){- this._txtHex.Text = "#" + this._color.R.ToString("X2", CultureInfo.InvariantCulture) + this._color.G.ToString("X2", CultureInfo.InvariantCulture) + this._color.B.ToString("X2", CultureInfo.InvariantCulture);+ _txtHex.Text = "#" + _color.R.ToString("X2", CultureInfo.InvariantCulture) + _color.G.ToString("X2", CultureInfo.InvariantCulture) + _color.B.ToString("X2", CultureInfo.InvariantCulture);}- this._lblRgb.Text = string.Format(CultureInfo.InvariantCulture, "R {0} G {1} B {2}", this._color.R, this._color.G, this._color.B);+ _lblRgb.Text = string.Format(CultureInfo.InvariantCulture, "R {0} G {1} B {2}", _color.R, _color.G, _color.B);}finally{- this._updatingText = false;+ _updatingText = false;}}/// <summary>Typing a complete 6-digit hex colour (optional leading '#') applies it and raises <see cref="ColorChanged"/>; incomplete or invalid text is ignored.</summary>private void HexTextChanged(object sender, EventArgs e){- if (this._updatingText)+ if (_updatingText){return;}- string hex = this._txtHex.Text.Trim().TrimStart('#');+ string hex = _txtHex.Text.Trim().TrimStart('#');if (hex.Length != 6){return;@@ -177,7 +169,7 @@ namespace _2D_wave_sim_V01int rgb;if (int.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out rgb)){- this.ApplyColor(Color.FromArgb((rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255), true, true);+ ApplyColor(Color.FromArgb((rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255), true, true);}}@@ -187,10 +179,10 @@ namespace _2D_wave_sim_V01using (ColorDialog colorDialog = new ColorDialog()){colorDialog.FullOpen = true;- colorDialog.Color = this._color;+ colorDialog.Color = _color;if (colorDialog.ShowDialog(this) == DialogResult.OK){- this.ApplyColor(colorDialog.Color, true, false);+ ApplyColor(colorDialog.Color, true, false);}}}@@ -207,19 +199,19 @@ namespace _2D_wave_sim_V01{return;}- if (this._svRect.Contains(e.Location))+ if (_svRect.Contains(e.Location)){- this._drag = 1;- this.UpdateFromMouse(e.Location);+ _drag = 1;+ UpdateFromMouse(e.Location);}- else if (this._hueRect.Contains(e.Location))+ else if (_hueRect.Contains(e.Location)){- this._drag = 2;- this.UpdateFromMouse(e.Location);+ _drag = 2;+ UpdateFromMouse(e.Location);}- else if (this._oldRect.Contains(e.Location))+ else if (_oldRect.Contains(e.Location)){- this.ApplyColor(this._original, true, false);+ ApplyColor(_original, true, false);}}@@ -227,9 +219,9 @@ namespace _2D_wave_sim_V01protected override void OnMouseMove(MouseEventArgs e){base.OnMouseMove(e);- if (this._drag != 0)+ if (_drag != 0){- this.UpdateFromMouse(e.Location);+ UpdateFromMouse(e.Location);}}@@ -237,7 +229,7 @@ namespace _2D_wave_sim_V01protected override void OnMouseUp(MouseEventArgs e){base.OnMouseUp(e);- this._drag = 0;+ _drag = 0;}/// <summary>@@ -247,20 +239,20 @@ namespace _2D_wave_sim_V01/// </summary>private void UpdateFromMouse(Point p){- if (this._drag == 1)+ if (_drag == 1){- this._s = ColorPickerControl.Clamp01((p.X - this._svRect.X) / (double)(this._svRect.Width - 1));- this._v = 1.0 - ColorPickerControl.Clamp01((p.Y - this._svRect.Y) / (double)(this._svRect.Height - 1));+ _s = ColorPickerControl.Clamp01((p.X - _svRect.X) / (double)(_svRect.Width - 1));+ _v = 1.0 - ColorPickerControl.Clamp01((p.Y - _svRect.Y) / (double)(_svRect.Height - 1));}- else if (this._drag == 2)+ else if (_drag == 2){- this._h = ColorPickerControl.Clamp01((p.Y - this._hueRect.Y) / (double)(this._hueRect.Height - 1)) * 360.0;+ _h = ColorPickerControl.Clamp01((p.Y - _hueRect.Y) / (double)(_hueRect.Height - 1)) * 360.0;}else{return;}- this.SyncFromHsv();+ SyncFromHsv();}/// <summary>@@ -272,42 +264,55 @@ namespace _2D_wave_sim_V01{base.OnPaint(e);Graphics g = e.Graphics;- g.Clear(this.BackColor);- this.EnsureSvBitmap();+ g.Clear(BackColor);++ // saturation / brightness square+ EnsureSvBitmap();g.InterpolationMode = InterpolationMode.HighQualityBilinear;g.PixelOffsetMode = PixelOffsetMode.Half;- g.DrawImage(this._svBitmap, this._svRect);- g.DrawRectangle(Pens.Black, this._svRect.X - 1, this._svRect.Y - 1, this._svRect.Width + 1, this._svRect.Height + 1);- this.EnsureHueBitmap();+ g.DrawImage(_svBitmap, _svRect);+ g.DrawRectangle(Pens.Black, _svRect.X - 1, _svRect.Y - 1, _svRect.Width + 1, _svRect.Height + 1);++ // hue bar+ EnsureHueBitmap();g.InterpolationMode = InterpolationMode.NearestNeighbor;- g.DrawImage(this._hueBitmap, this._hueRect);- g.DrawRectangle(Pens.Black, this._hueRect.X - 1, this._hueRect.Y - 1, this._hueRect.Width + 1, this._hueRect.Height + 1);+ g.DrawImage(_hueBitmap, _hueRect);+ g.DrawRectangle(Pens.Black, _hueRect.X - 1, _hueRect.Y - 1, _hueRect.Width + 1, _hueRect.Height + 1);+g.SmoothingMode = SmoothingMode.AntiAlias;- float svX = (float)(this._svRect.X + this._s * (this._svRect.Width - 1));- float svY = (float)(this._svRect.Y + (1.0 - this._v) * (this._svRect.Height - 1));++ // marker in the square+ float svX = (float)(_svRect.X + _s * (_svRect.Width - 1));+ float svY = (float)(_svRect.Y + (1.0 - _v) * (_svRect.Height - 1));g.DrawEllipse(Pens.Black, svX - 7f, svY - 7f, 14f, 14f);g.DrawEllipse(Pens.White, svX - 6f, svY - 6f, 12f, 12f);- float hueY = (float)(this._hueRect.Y + this._h / 360.0 * (this._hueRect.Height - 1));- g.DrawRectangle(Pens.Black, this._hueRect.X - 3, hueY - 3f, this._hueRect.Width + 5, 6f);- g.DrawRectangle(Pens.White, this._hueRect.X - 2, hueY - 2f, this._hueRect.Width + 3, 4f);++ // marker on the hue bar+ float hueY = (float)(_hueRect.Y + _h / 360.0 * (_hueRect.Height - 1));+ g.DrawRectangle(Pens.Black, _hueRect.X - 3, hueY - 3f, _hueRect.Width + 5, 6f);+ g.DrawRectangle(Pens.White, _hueRect.X - 2, hueY - 2f, _hueRect.Width + 3, 4f);+g.SmoothingMode = SmoothingMode.Default;- using (SolidBrush newBrush = new SolidBrush(this._color))++ // swatches+ using (SolidBrush newBrush = new SolidBrush(_color)){- g.FillRectangle(newBrush, this._newRect);+ g.FillRectangle(newBrush, _newRect);}- using (SolidBrush oldBrush = new SolidBrush(this._original))+ using (SolidBrush oldBrush = new SolidBrush(_original)){- g.FillRectangle(oldBrush, this._oldRect);+ g.FillRectangle(oldBrush, _oldRect);}- g.DrawRectangle(Pens.Black, this._newRect.X, this._newRect.Y, this._newRect.Width - 1, this._newRect.Height - 1);- g.DrawRectangle(Pens.Black, this._oldRect.X, this._oldRect.Y, this._oldRect.Width - 1, this._oldRect.Height - 1);- TextRenderer.DrawText(g, "New", this.Font, this._newRect, ColorPickerControl.ContrastColor(this._color), TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);- TextRenderer.DrawText(g, "Old (click to restore)", this.Font, this._oldRect, ColorPickerControl.ContrastColor(this._original), TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);+ g.DrawRectangle(Pens.Black, _newRect.X, _newRect.Y, _newRect.Width - 1, _newRect.Height - 1);+ g.DrawRectangle(Pens.Black, _oldRect.X, _oldRect.Y, _oldRect.Width - 1, _oldRect.Height - 1);+ TextRenderer.DrawText(g, "New", Font, _newRect, ColorPickerControl.ContrastColor(_color), TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);+ TextRenderer.DrawText(g, "Old (click to restore)", Font, _oldRect, ColorPickerControl.ContrastColor(_original), TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);+if (!base.Enabled){- using (SolidBrush overlayBrush = new SolidBrush(Color.FromArgb(150, this.BackColor)))+ using (SolidBrush veil = new SolidBrush(Color.FromArgb(150, BackColor))){- g.FillRectangle(overlayBrush, base.ClientRectangle);+ g.FillRectangle(veil, base.ClientRectangle);}}}@@ -326,15 +331,15 @@ namespace _2D_wave_sim_V01/// </summary>private void EnsureSvBitmap(){- if (this._svBitmap != null && Math.Abs(this._svHue - this._h) < 0.0001)+ if (_svBitmap != null && Math.Abs(_svHue - _h) < 0.0001){return;}- if (this._svBitmap == null)+ if (_svBitmap == null){- this._svBitmap = new Bitmap(SvResolution, SvResolution, PixelFormat.Format32bppArgb);+ _svBitmap = new Bitmap(SvResolution, SvResolution, PixelFormat.Format32bppArgb);}- Color pure = ColorPickerControl.HsvToColor(this._h, 1.0, 1.0);+ Color pure = ColorPickerControl.HsvToColor(_h, 1.0, 1.0);double pureR = pure.R / 255.0;double pureG = pure.G / 255.0;double pureB = pure.B / 255.0;@@ -351,29 +356,29 @@ namespace _2D_wave_sim_V01pixels[y * SvResolution + x] = Color.FromArgb(255, r, g, b).ToArgb();}}- BitmapData bitmapData = this._svBitmap.LockBits(new Rectangle(0, 0, SvResolution, SvResolution), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);+ BitmapData bitmapData = _svBitmap.LockBits(new Rectangle(0, 0, SvResolution, SvResolution), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);try{Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);}finally{- this._svBitmap.UnlockBits(bitmapData);+ _svBitmap.UnlockBits(bitmapData);}- this._svHue = this._h;+ _svHue = _h;}/// <summary>Creates the 1-pixel-wide hue gradient bitmap (hue 0 at the top, 360 at the bottom) on first use; it never changes afterwards.</summary>private void EnsureHueBitmap(){- if (this._hueBitmap != null)+ if (_hueBitmap != null){return;}- this._hueBitmap = new Bitmap(1, this._hueRect.Height, PixelFormat.Format32bppArgb);- for (int i = 0; i < this._hueRect.Height; i++)+ _hueBitmap = new Bitmap(1, _hueRect.Height, PixelFormat.Format32bppArgb);+ for (int y = 0; y < _hueRect.Height; y++){- this._hueBitmap.SetPixel(0, i, ColorPickerControl.HsvToColor(i / (double)(this._hueRect.Height - 1) * 360.0, 1.0, 1.0));+ _hueBitmap.SetPixel(0, y, ColorPickerControl.HsvToColor(y / (double)(_hueRect.Height - 1) * 360.0, 1.0, 1.0));}}@@ -382,13 +387,13 @@ namespace _2D_wave_sim_V01{if (disposing){- if (this._svBitmap != null)+ if (_svBitmap != null){- this._svBitmap.Dispose();+ _svBitmap.Dispose();}- if (this._hueBitmap != null)+ if (_hueBitmap != null){- this._hueBitmap.Dispose();+ _hueBitmap.Dispose();}}base.Dispose(disposing);diff --git a/Wave_Dude_2D/ColorScheme.cs b/Wave_Dude_2D/ColorScheme.csindex 09810f2..8eb6bd3 100644--- a/Wave_Dude_2D/ColorScheme.cs+++ b/Wave_Dude_2D/ColorScheme.cs@@ -5,12 +5,20 @@ using System.Drawing;namespace _2D_wave_sim_V01{/// <summary>- /// A 255-entry color table, optionally backed by 9 editable gradient stops.+ /// A color scheme: a lookup table of exactly <see cref="EntryCount"/> (255) RGB colors, the same table+ /// size the Python simulator uses, optionally backed by <see cref="StopCount"/> editable gradient stops.+ /// A scheme can be used for the field view or for the intensity view./// </summary>/// <remarks>/// Entry 0 is the start of the scale (field -1 / intensity 0), entry 254 the end (+1 / max), entry 127- /// the centre of a field scheme. Instances are created by <see cref="ColorSchemeStore.Load"/> and the- /// editor on the color scheme tab, live on the UI thread, and are turned into an <c>int[]</c> palette by+ /// the centre of a field scheme. Schemes made in the stop editor also keep their anchor colors+ /// ("stops") so they can be edited again. The stops sit at fixed, equally spaced positions on the+ /// scale: stop 1 is the first entry, the last stop is the last entry and, with an odd number of stops,+ /// the middle stop is exactly the centre entry 127 (the zero-field color); with 9 stops that is+ /// Color 5. All other entries are interpolated linearly in RGB between neighbouring stops. Imported+ /// schemes (matplotlib, seaborn, Python tables) have no stops and are used as they are.+ /// Instances are created by <see cref="ColorSchemeStore.Load"/> and the editor on the color scheme+ /// tab, live on the UI thread, and are turned into an <c>int[]</c> palette by/// <see cref="ColorLut.Build"/> before a simulation starts; the worker thread never touches them./// The <see cref="Entries"/> and <see cref="Stops"/> getters return defensive copies, so the only way to/// change the table is <see cref="SetStop"/>. All colors are opaque RGB; alpha is ignored.@@ -27,8 +35,9 @@ namespace _2D_wave_sim_V01public string Category { get; set; }/// <summary>- /// What the scheme is meant to color: <see cref="SchemeTypeField"/>, <see cref="SchemeTypeIntensity"/>- /// or "" when not specified. Decides which combo box on the simulation tab offers the scheme.+ /// What the scheme is meant for: <see cref="SchemeTypeField"/>, <see cref="SchemeTypeIntensity"/>+ /// or "" when not specified. This is only a label saved in the file (it decides which combo box on+ /// the simulation tab offers the scheme); any scheme can technically be used for either./// </summary>public string SchemeType { get; set; }@@ -49,46 +58,28 @@ namespace _2D_wave_sim_V01{throw new ArgumentNullException("colors");}- this.Name = schemeName;- this.Origin = "";- this.Category = "";- this.SchemeType = "";- this.FilePath = "";- this._entries = ColorScheme.Resample(colors, EntryCount);+ Name = schemeName;+ Origin = "";+ Category = "";+ SchemeType = "";+ FilePath = "";+ _entries = ColorScheme.Resample(colors, EntryCount);}/// <summary>A fresh copy of the full <see cref="EntryCount"/>-entry table (allocates on every call; use <see cref="GetEntry"/> in loops).</summary>- public Color[] Entries- {- get- {- return (Color[])this._entries.Clone();- }- }+ public Color[] Entries => (Color[])_entries.Clone();/// <summary>Returns table entry <paramref name="index"/> (0..254) without copying the table.</summary>public Color GetEntry(int index){- return this._entries[index];+ return _entries[index];}/// <summary>True when the scheme carries <see cref="StopCount"/> editable stops, i.e. <see cref="SetStop"/> may be called.</summary>- public bool HasStops- {- get- {- return this._stops != null;- }- }+ public bool HasStops => _stops != null;/// <summary>A fresh copy of the <see cref="StopCount"/> stops, or null for a table-only scheme.</summary>- public Color[] Stops- {- get- {- return this._stops == null ? null : (Color[])this._stops.Clone();- }- }+ public Color[] Stops => _stops == null ? null : (Color[])_stops.Clone();/// <summary>Linearly interpolates between the table entries at a fractional position 0..254.</summary>/// <param name="position">Position on the entry scale; clamped to the first/last entry outside 0..254.</param>@@ -96,25 +87,26 @@ namespace _2D_wave_sim_V01{if (position <= 0.0){- return this._entries[0];+ return _entries[0];}if (position >= EntryCount - 1){- return this._entries[EntryCount - 1];+ return _entries[EntryCount - 1];}int index = (int)Math.Floor(position);- return ColorScheme.Lerp(this._entries[index], this._entries[index + 1], position - index);+ return ColorScheme.Lerp(_entries[index], _entries[index + 1], position - index);}/// <summary>Returns <see cref="Name"/>, which is what the scheme combo boxes display.</summary>public override string ToString(){- return this.Name;+ return Name;}/// <summary>- /// Creates a stop scheme from exactly <see cref="StopCount"/> stops: the table is interpolated from- /// them, <see cref="Origin"/> says it was made in the editor and <see cref="Category"/> is "custom".+ /// Creates a stop scheme from exactly <see cref="StopCount"/> stops, given in scale order (stop 1+ /// first, the middle stop in the centre, the last stop last): the table is interpolated from them,+ /// <see cref="Origin"/> says it was made in the editor and <see cref="Category"/> is "custom"./// </summary>/// <exception cref="ArgumentException"><paramref name="stops"/> is null or not <see cref="StopCount"/> long.</exception>public static ColorScheme FromStops(string schemeName, IList<Color> stops)@@ -140,7 +132,7 @@ namespace _2D_wave_sim_V01}Color[] copy = new Color[StopCount];stops.CopyTo(copy, 0);- this._stops = copy;+ _stops = copy;}/// <summary>@@ -150,10 +142,10 @@ namespace _2D_wave_sim_V01/// <param name="stopIndex">0..<see cref="StopCount"/>-1.</param>/// <param name="value">New stop color; only R, G and B are used.</param>/// <exception cref="InvalidOperationException">The scheme has no stops (<see cref="HasStops"/> is false).</exception>- /// <exception cref="ArgumentOutOfRangeException"><paramref name="stopIndex"/> is outside 0..8.</exception>+ /// <exception cref="ArgumentOutOfRangeException"><paramref name="stopIndex"/> is outside 0..<see cref="StopCount"/>-1.</exception>public void SetStop(int stopIndex, Color value){- if (this._stops == null)+ if (_stops == null){throw new InvalidOperationException("This scheme has no editable stops. Use ToStopScheme first.");}@@ -161,13 +153,14 @@ namespace _2D_wave_sim_V01{throw new ArgumentOutOfRangeException("stopIndex");}- this._stops[stopIndex] = Color.FromArgb(value.R, value.G, value.B);- this._entries = ColorScheme.InterpolateStops(this._stops);+ _stops[stopIndex] = Color.FromArgb(value.R, value.G, value.B);+ _entries = ColorScheme.InterpolateStops(_stops);}/// <summary>- /// Creates a 9-stop approximation of this scheme by sampling it at evenly spaced positions- /// (k/8 of the 0..254 range). The result keeps this <see cref="SchemeType"/>, gets an+ /// Makes an editable <see cref="StopCount"/>-stop scheme from any scheme by sampling it at the stop+ /// positions (k/(StopCount-1) of the 0..254 range). This is lossy: the copy is a smooth+ /// approximation of the original. The result keeps this <see cref="SchemeType"/>, gets an/// <see cref="Origin"/> naming this scheme, <see cref="Category"/> "custom" and no file path./// </summary>public ColorScheme ToStopScheme(string newName)@@ -175,11 +168,11 @@ namespace _2D_wave_sim_V01Color[] stops = new Color[StopCount];for (int i = 0; i < StopCount; i++){- stops[i] = this.SampleAt((i * 254) / 8.0);+ stops[i] = SampleAt((i * (EntryCount - 1)) / (double)(StopCount - 1));}ColorScheme scheme = ColorScheme.FromStops(newName, stops);- scheme.Origin = StopCount.ToString() + "-stop copy of scheme '" + this.Name + "'";- scheme.SchemeType = this.SchemeType;+ scheme.Origin = StopCount.ToString() + "-stop copy of scheme '" + Name + "'";+ scheme.SchemeType = SchemeType;return scheme;}@@ -189,18 +182,21 @@ namespace _2D_wave_sim_V01/// </summary>public ColorScheme Clone(string newName){- ColorScheme scheme = new ColorScheme(newName, this._entries);- scheme.Origin = this.Origin;- scheme.Category = this.Category;- scheme.SchemeType = this.SchemeType;- if (this._stops != null)+ ColorScheme scheme = new ColorScheme(newName, _entries);+ scheme.Origin = Origin;+ scheme.Category = Category;+ scheme.SchemeType = SchemeType;+ if (_stops != null){- scheme.AttachStops(this._stops);+ scheme.AttachStops(_stops);}return scheme;}- /// <summary>Expands 9 stops into the full 255-entry table by linear RGB interpolation; stop k lands on entry k*254/8.</summary>+ /// <summary>+ /// Builds the <see cref="EntryCount"/> entries from the <see cref="StopCount"/> stops at fixed, equally+ /// spaced positions (linear in RGB); stop k lands on entry k*(EntryCount-1)/(StopCount-1).+ /// </summary>/// <exception cref="ArgumentException"><paramref name="stops"/> is null or not <see cref="StopCount"/> long.</exception>public static Color[] InterpolateStops(IList<Color> stops){@@ -211,12 +207,14 @@ namespace _2D_wave_sim_V01Color[] entries = new Color[EntryCount];for (int i = 0; i < EntryCount; i++){- // Position of entry i in stop units (0..8); the last entry must stay in segment 7.- double position = (i * 8) / 254.0;+ // position on the stop scale: 0.0 (first stop) to StopCount - 1 (last stop);+ // with 9 stops entry 127 is exactly 4.0, the middle stop.+ // The last entry must stay in the last segment (StopCount - 2).+ double position = (i * (StopCount - 1)) / (double)(EntryCount - 1);int segment = (int)Math.Floor(position);- if (segment > 7)+ if (segment > StopCount - 2){- segment = 7;+ segment = StopCount - 2;}entries[i] = ColorScheme.Lerp(stops[segment], stops[segment + 1], position - segment);}@@ -282,7 +280,12 @@ namespace _2D_wave_sim_V01/// <summary>Number of entries in the color table (indices 0..254).</summary>public const int EntryCount = 255;- /// <summary>Number of editable gradient stops of a stop scheme (8 segments).</summary>+ /// <summary>+ /// Number of fixed anchor colors in the stop editor (one Color button each, so this is tied to the+ /// <c>btnColorN</c> buttons in the Form1 Designer): 9 since the Color 8/9 buttons were added to the+ /// Designer (previously upgraded from 5 to 7 the same way). Odd on purpose, so the middle stop is+ /// exactly the centre entry 127; see the class remarks.+ /// </summary>public const int StopCount = 9;/// <summary>The <see cref="EntryCount"/> table entries; replaced wholesale by <see cref="SetStop"/>, never null.</summary>diff --git a/Wave_Dude_2D/ColorSchemeStore.cs b/Wave_Dude_2D/ColorSchemeStore.csindex ee2b2ca..6f8fafc 100644--- a/Wave_Dude_2D/ColorSchemeStore.cs+++ b/Wave_Dude_2D/ColorSchemeStore.cs@@ -10,14 +10,17 @@ using System.Web.Script.Serialization;namespace _2D_wave_sim_V01{/// <summary>- /// Reads and writes <see cref="ColorScheme"/> objects as JSON files in the scheme folder.+ /// Reads and writes <see cref="ColorScheme"/> objects as JSON files (one file per scheme, e.g. in the+ /// scheme folder)./// </summary>/// <remarks>- /// Static-only helper (private constructor). File layout: an object with "name", "origin", optional- /// "category" and "scheme_type", "bits_per_channel" (always 8), "entry_count" (255), an optional "stops"- /// list of 9 <c>[r,g,b]</c> triplets and a "colors" list of triplets. Reading uses- /// <see cref="JavaScriptSerializer"/>; writing emits the text by hand so the file stays human-readable.- /// Called only from the UI thread (color scheme tab and start-up).+ /// Static-only helper (private constructor). File format, the same as the files exported from Python+ /// (e.g. in its <c>color_schemes</c> folder): an object with "name", "origin", optional "category" and+ /// "scheme_type" ("field" or "intensity"), "bits_per_channel" (always 8), "entry_count"+ /// (<see cref="ColorScheme.EntryCount"/>) and a "colors" list of <c>[r,g,b]</c> triplets, plus, only+ /// for schemes made in the stop editor, a "stops" list of <see cref="ColorScheme.StopCount"/> triplets.+ /// Reading uses <see cref="JavaScriptSerializer"/>; writing emits the text by hand so the file stays+ /// human-readable. Called only from the UI thread (color scheme tab and start-up)./// </remarks>public sealed class ColorSchemeStore{@@ -27,13 +30,18 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Returns the ColorSchemeList folder next to the executable, or the one next to the project- /// file when running from the build output. The folder is created if it does not exist.+ /// The program's own color scheme folder. While developing (the exe runs from <c>bin\Debug</c>+ /// inside the solution) this is the <see cref="SchemeFolderName"/> folder of the repository itself,+ /// so edits end up in the project; in a deployed program it is the <see cref="SchemeFolderName"/>+ /// folder next to the exe. The folder is created when it does not exist./// </summary>/// <returns>/// The folder path. It walks up to five directory levels from the base directory looking for a- /// <c>*.vbproj</c> (the original VB.NET project file) and prefers a <see cref="SchemeFolderName"/>- /// folder beside it. Any I/O error is swallowed and the default path is returned uncreated.+ /// <c>*.sln</c> (the solution file at the repository root, which is where the tracked+ /// <see cref="SchemeFolderName"/> lives; the original looked for its <c>*.vbproj</c>, which no+ /// longer exists above the C# exe) and prefers a <see cref="SchemeFolderName"/> folder beside it.+ /// From <c>Wave_Dude_2D\bin\Debug</c> that is three levels up. Any I/O error is swallowed and the+ /// default path is returned, possibly uncreated: the caller checks whether the folder exists./// </returns>public static string FindDefaultFolder(){@@ -41,19 +49,19 @@ namespace _2D_wave_sim_V01string folder = Path.Combine(baseDirectory, SchemeFolderName);try{- DirectoryInfo dir = new DirectoryInfo(baseDirectory);- for (int level = 0; level <= 4 && dir != null; level++)+ DirectoryInfo probe = new DirectoryInfo(baseDirectory);+ for (int level = 0; level <= 4 && probe != null; level++){- if (dir.GetFiles("*.vbproj").Length > 0)+ if (probe.GetFiles("*.sln").Length > 0){- string candidate = Path.Combine(dir.FullName, SchemeFolderName);+ string candidate = Path.Combine(probe.FullName, SchemeFolderName);if (Directory.Exists(candidate)){folder = candidate;}break;}- dir = dir.Parent;+ probe = probe.Parent;}if (!Directory.Exists(folder)){@@ -62,6 +70,7 @@ namespace _2D_wave_sim_V01}catch{+ // the caller checks whether the folder exists}return folder;}@@ -86,7 +95,7 @@ namespace _2D_wave_sim_V01{throw new InvalidDataException("Not a color scheme file (a JSON object was expected).");}- string name = ColorSchemeStore.GetString(root, "name", Path.GetFileNameWithoutExtension(filePath));+ string schemeName = ColorSchemeStore.GetString(root, "name", Path.GetFileNameWithoutExtension(filePath));List<Color> colors = null;if (root.ContainsKey("colors")){@@ -104,11 +113,11 @@ namespace _2D_wave_sim_V01ColorScheme scheme;if (colors != null && colors.Count >= 2){- scheme = new ColorScheme(name, colors);+ scheme = new ColorScheme(schemeName, colors);}else if (stops != null){- scheme = ColorScheme.FromStops(name, stops);+ scheme = ColorScheme.FromStops(schemeName, stops);}else{@@ -221,6 +230,7 @@ namespace _2D_wave_sim_V01{Directory.CreateDirectory(directoryName);}+ // write to a temporary file first so a failed save never leaves a half-written scheme behindstring tempPath = filePath + ".tmp";File.WriteAllText(tempPath, json.ToString(), new UTF8Encoding(false));if (File.Exists(filePath))@@ -387,7 +397,7 @@ namespace _2D_wave_sim_V01return quoted.ToString();}- /// <summary>Name of the scheme folder looked for next to the executable / project: "ColorSchemeList".</summary>+ /// <summary>Name of the folder with the color schemes that belongs to the program, looked for next to the executable / solution: "ColorSchemeList".</summary>public const string SchemeFolderName = "ColorSchemeList";}}diff --git a/Wave_Dude_2D/Form1.Colors.cs b/Wave_Dude_2D/Form1.Colors.csindex e80b41d..9f91755 100644--- a/Wave_Dude_2D/Form1.Colors.cs+++ b/Wave_Dude_2D/Form1.Colors.cs@@ -27,14 +27,14 @@ namespace _2D_wave_sim_V01using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()){folderBrowserDialog.Description = "Choose the folder that contains the color scheme (.json) files";- if (Directory.Exists(this.txtSchemeFolder.Text))+ if (Directory.Exists(txtSchemeFolder.Text)){- folderBrowserDialog.SelectedPath = this.txtSchemeFolder.Text;+ folderBrowserDialog.SelectedPath = txtSchemeFolder.Text;}if (folderBrowserDialog.ShowDialog(this) == DialogResult.OK){- this.txtSchemeFolder.Text = folderBrowserDialog.SelectedPath;- this.LoadSchemeList();+ txtSchemeFolder.Text = folderBrowserDialog.SelectedPath;+ LoadSchemeList();}}}@@ -45,7 +45,7 @@ namespace _2D_wave_sim_V01if (e.KeyCode == Keys.Return){e.SuppressKeyPress = true;- this.LoadSchemeList();+ LoadSchemeList();}}@@ -57,42 +57,42 @@ namespace _2D_wave_sim_V01/// </summary>private void LoadSchemeList(){- string folder = this.txtSchemeFolder.Text.Trim();+ string folder = txtSchemeFolder.Text.Trim();if (!Directory.Exists(folder)){MessageBox.Show(this, "The folder '" + folder + "' does not exist.", "Color schemes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);return;}List<string> errors = new List<string>();- this._schemes = ColorSchemeStore.LoadFolder(folder, errors);- this.SortSchemes(this._schemes, this._schemeSortColumn, this._schemeSortAscending);- this.ListView1.BeginUpdate();+ _schemes = ColorSchemeStore.LoadFolder(folder, errors);+ SortSchemes(_schemes, _schemeSortColumn, _schemeSortAscending);+ ListView1.BeginUpdate();try{- this.ListView1.Items.Clear();- this._thumbs.Images.Clear();- foreach (Bitmap thumb in this._thumbBitmaps)+ ListView1.Items.Clear();+ _thumbs.Images.Clear();+ foreach (Bitmap thumb in _thumbBitmaps){thumb.Dispose();}- this._thumbBitmaps.Clear();- foreach (ColorScheme scheme in this._schemes)+ _thumbBitmaps.Clear();+ foreach (ColorScheme scheme in _schemes){Bitmap thumb = Form1.MakeThumbnail(scheme);- this._thumbBitmaps.Add(thumb);- this._thumbs.Images.Add(thumb);- ListViewItem item = new ListViewItem(scheme.Name, this._thumbs.Images.Count - 1);+ _thumbBitmaps.Add(thumb);+ _thumbs.Images.Add(thumb);+ ListViewItem item = new ListViewItem(scheme.Name, _thumbs.Images.Count - 1);item.SubItems.Add(scheme.HasStops ? (ColorScheme.StopCount.ToString() + "-stop") : "table");item.SubItems.Add(string.IsNullOrEmpty(scheme.SchemeType) ? "-" : scheme.SchemeType);item.Tag = scheme;- this.ListView1.Items.Add(item);+ ListView1.Items.Add(item);}}finally{- this.ListView1.EndUpdate();+ ListView1.EndUpdate();}- this.UpdateSchemeListSortHeaders();+ UpdateSchemeListSortHeaders();if (errors.Count > 0){// Show at most 8 file errors; the rest is summarised as a count.@@ -104,9 +104,9 @@ namespace _2D_wave_sim_V01}MessageBox.Show(this, "Some files could not be read as color schemes:\r\n\r\n" + message, "Color schemes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);}- this.RefreshSchemeCombos();- this._previewScheme = null;- this.RefreshEditorState();+ RefreshSchemeCombos();+ _previewScheme = null;+ RefreshEditorState();}/// <summary>@@ -146,53 +146,53 @@ namespace _2D_wave_sim_V01{return;}- if (e.Column == this._schemeSortColumn)+ if (e.Column == _schemeSortColumn){- this._schemeSortAscending = !this._schemeSortAscending;+ _schemeSortAscending = !_schemeSortAscending;}else{- this._schemeSortColumn = e.Column;- this._schemeSortAscending = true;+ _schemeSortColumn = e.Column;+ _schemeSortAscending = true;}- this.LoadSchemeList();+ LoadSchemeList();}/// <summary>Appends a " ^" / " v" direction marker to the header of the column the list is sorted by.</summary>private void UpdateSchemeListSortHeaders(){- if (this.ListView1.Columns.Count < 3)+ if (ListView1.Columns.Count < 3){return;}- string arrow = this._schemeSortAscending ? " ^" : " v";- this.ListView1.Columns[0].Text = "Scheme" + (this._schemeSortColumn == 0 ? arrow : "");- this.ListView1.Columns[2].Text = "Type" + (this._schemeSortColumn == 2 ? arrow : "");+ string arrow = _schemeSortAscending ? " ^" : " v";+ ListView1.Columns[0].Text = "Scheme" + (_schemeSortColumn == 0 ? arrow : "");+ ListView1.Columns[2].Text = "Type" + (_schemeSortColumn == 2 ? arrow : "");}/// <summary>Selecting a list row previews that scheme in the editor; clearing the selection shows the current scheme again.</summary>private void ListView1_SelectedIndexChanged(object sender, EventArgs e){- this._previewScheme = this.ListView1.SelectedItems.Count == 0 ? null : (ColorScheme)this.ListView1.SelectedItems[0].Tag;- this.RefreshEditorState();+ _previewScheme = ListView1.SelectedItems.Count == 0 ? null : (ColorScheme)ListView1.SelectedItems[0].Tag;+ RefreshEditorState();}/// <summary>Double-clicking a row loads it as the current scheme.</summary>private void ListView1_DoubleClick(object sender, EventArgs e){- this.LoadPreviewedScheme();+ LoadPreviewedScheme();}/// <summary>Loads the previewed scheme as the current one, or asks the user to select a row first.</summary>private void btnLoadScheme_Click(object sender, EventArgs e){- if (this._previewScheme == null)+ if (_previewScheme == null){MessageBox.Show(this, "Select a scheme in the list first.", "Load scheme", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);}else{- this.LoadPreviewedScheme();+ LoadPreviewedScheme();}}@@ -201,7 +201,7 @@ namespace _2D_wave_sim_V01{if (e.KeyCode == Keys.Escape){- this.ListView1.SelectedItems.Clear();+ ListView1.SelectedItems.Clear();e.Handled = true;}}@@ -214,21 +214,21 @@ namespace _2D_wave_sim_V01/// <returns>False if there is no preview or the user kept the unsaved current scheme.</returns>private bool LoadPreviewedScheme(){- if (this._previewScheme == null)+ if (_previewScheme == null){return false;}- if (!this.ConfirmDiscardChanges())+ if (!ConfirmDiscardChanges()){return false;}- ColorScheme previewScheme = this._previewScheme;- this._current = previewScheme.Clone(previewScheme.Name);- this._current.FilePath = previewScheme.FilePath;- this._dirty = false;- this._selectedStop = -1;- this.ListView1.SelectedItems.Clear();- this.RefreshEditorState();+ ColorScheme previewScheme = _previewScheme;+ _current = previewScheme.Clone(previewScheme.Name);+ _current.FilePath = previewScheme.FilePath;+ _dirty = false;+ _selectedStop = -1;+ ListView1.SelectedItems.Clear(); // ends the preview; also refreshes the display+ RefreshEditorState();return true;}@@ -236,49 +236,52 @@ namespace _2D_wave_sim_V01/// <returns>True if there are no unsaved changes or the user answered Yes.</returns>private bool ConfirmDiscardChanges(){- if (!this._dirty)+ if (!_dirty){return true;}- DialogResult answer = MessageBox.Show(this, "The current color scheme '" + this._current.Name + "' has unsaved changes. Discard them?", "Unsaved changes", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);+ DialogResult answer = MessageBox.Show(this, "The current color scheme '" + _current.Name + "' has unsaved changes. Discard them?", "Unsaved changes", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);return answer == DialogResult.Yes;}/// <summary>- /// Clicking one of the nine Color buttons selects that stop for editing and loads its color into the- /// picker. While previewing, the preview is first loaded as the current scheme (may be cancelled).- /// A table-only scheme is converted to an unsaved 9-stop approximation after confirmation.+ /// Clicking one of the <see cref="ColorScheme.StopCount"/> Color buttons selects that stop for editing and+ /// loads its color into the picker. While previewing, the preview is first loaded as the current scheme+ /// (may be cancelled). A table-only scheme is converted to an unsaved+ /// <see cref="ColorScheme.StopCount"/>-stop approximation after confirmation./// </summary>private void StopButton_Click(object sender, EventArgs e){- int stopIndex = Array.IndexOf(this._stopButtons, (Button)sender);+ int stopIndex = Array.IndexOf(_stopButtons, (Button)sender);if (stopIndex < 0){return;}- if (this._previewScheme != null && !this.LoadPreviewedScheme())+ // clicking a Color button while a list item is only previewed loads that scheme first+ if (_previewScheme != null && !LoadPreviewedScheme()){return;}- if (this._current == null)+ if (_current == null){return;}- if (!this._current.HasStops)+ // an imported scheme is a full table without stops: editing it means making a stop-based approximation+ if (!_current.HasStops){- DialogResult answer = MessageBox.Show(this, "The scheme '" + this._current.Name + "' is a full table of 255 colors without " + ColorScheme.StopCount.ToString() + " editable stops.\r\n\r\nEditing it creates a smooth " + ColorScheme.StopCount.ToString() + "-stop approximation as a new, unsaved scheme (the original file stays unchanged). Continue?", "Edit scheme", MessageBoxButtons.YesNo, MessageBoxIcon.Question);+ DialogResult answer = MessageBox.Show(this, "The scheme '" + _current.Name + "' is a full table of 255 colors without " + ColorScheme.StopCount.ToString() + " editable stops.\r\n\r\nEditing it creates a smooth " + ColorScheme.StopCount.ToString() + "-stop approximation as a new, unsaved scheme (the original file stays unchanged). Continue?", "Edit scheme", MessageBoxButtons.YesNo, MessageBoxIcon.Question);if (answer != DialogResult.Yes){return;}- this._current = this._current.ToStopScheme(this._current.Name + " (" + ColorScheme.StopCount.ToString() + "-stop)");- this._dirty = true;- }- this._selectedStop = stopIndex;- Color color = this._current.Stops[stopIndex];- this._picker.OriginalColor = color;- this._picker.SelectedColor = color;- this.RefreshEditorState();+ _current = _current.ToStopScheme(_current.Name + " (" + ColorScheme.StopCount.ToString() + "-stop)");+ _dirty = true;+ }+ _selectedStop = stopIndex;+ Color color = _current.Stops[stopIndex];+ _picker.OriginalColor = color;+ _picker.SelectedColor = color;+ RefreshEditorState();}/// <summary>@@ -288,13 +291,13 @@ namespace _2D_wave_sim_V01/// </summary>private void Picker_ColorChanged(object sender, EventArgs e){- if (this._current == null || !this._current.HasStops || this._selectedStop < 0)+ if (_current == null || !_current.HasStops || _selectedStop < 0){return;}- this._current.SetStop(this._selectedStop, this._picker.SelectedColor);- this._dirty = true;- this.RefreshEditorState();+ _current.SetStop(_selectedStop, _picker.SelectedColor);+ _dirty = true;+ RefreshEditorState();}/// <summary>@@ -303,32 +306,32 @@ namespace _2D_wave_sim_V01/// </summary>private void btnSaveCurrentScheme_Click(object sender, EventArgs e){- if (this._current == null)+ if (_current == null){return;}- if (string.IsNullOrEmpty(this._current.FilePath))+ if (string.IsNullOrEmpty(_current.FilePath)){- this.SaveAsNew();+ SaveAsNew();return;}try{- ColorSchemeStore.Save(this._current, this._current.FilePath);- this._dirty = false;+ ColorSchemeStore.Save(_current, _current.FilePath);+ _dirty = false;}catch (Exception ex){MessageBox.Show(this, "The scheme could not be saved:\r\n" + ex.Message, "Save scheme", MessageBoxButtons.OK, MessageBoxIcon.Hand);return;}- this.ReloadListAfterSave();+ ReloadListAfterSave();}/// <summary>Saves the current scheme under a new name (see <see cref="SaveAsNew"/>).</summary>private void btnSaveAsColorScheme_Click(object sender, EventArgs e){- this.SaveAsNew();+ SaveAsNew();}/// <summary>@@ -338,17 +341,17 @@ namespace _2D_wave_sim_V01/// </summary>private void SaveAsNew(){- if (this._current == null)+ if (_current == null){return;}- string folder = this.txtSchemeFolder.Text.Trim();+ string folder = txtSchemeFolder.Text.Trim();if (!Directory.Exists(folder)){MessageBox.Show(this, "Choose an existing scheme folder first.", "Save scheme", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- string newName = Interaction.InputBox("Name for the new color scheme:", "Save as new scheme", this._current.Name, -1, -1).Trim();+ string newName = Interaction.InputBox("Name for the new color scheme:", "Save as new scheme", _current.Name, -1, -1).Trim();if (newName.Length == 0){return;@@ -364,27 +367,27 @@ namespace _2D_wave_sim_V01}try{- ColorScheme copy = this._current.Clone(newName);+ ColorScheme copy = _current.Clone(newName);if (copy.HasStops && string.IsNullOrEmpty(copy.Category)){copy.Category = "custom";}ColorSchemeStore.Save(copy, targetPath);- this._current = copy;- this._dirty = false;+ _current = copy;+ _dirty = false;}catch (Exception ex){MessageBox.Show(this, "The scheme could not be saved:\r\n" + ex.Message, "Save scheme", MessageBoxButtons.OK, MessageBoxIcon.Hand);return;}- this.ReloadListAfterSave();+ ReloadListAfterSave();}/// <summary>Re-reads the scheme folder after a save so the list and combo boxes show the new file.</summary>private void ReloadListAfterSave(){- this.LoadSchemeList();+ LoadSchemeList();}/// <summary>@@ -394,16 +397,16 @@ namespace _2D_wave_sim_V01/// </summary>private void btnRenameColorScheme_Click(object sender, EventArgs e){- if (this._previewScheme == null)+ if (_previewScheme == null){MessageBox.Show(this, "Select a scheme in the list first.", "Rename color scheme", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- ColorScheme previewScheme = this._previewScheme;+ ColorScheme previewScheme = _previewScheme;string oldName = previewScheme.Name;string oldPath = previewScheme.FilePath;string newName = oldName;- if (!this.PromptForText("Rename color scheme", "New name for '" + oldName + "':", oldName, ref newName))+ if (!PromptForText("Rename color scheme", "New name for '" + oldName + "':", oldName, ref newName)){return;}@@ -412,7 +415,7 @@ namespace _2D_wave_sim_V01{return;}- string folder = string.IsNullOrEmpty(oldPath) ? this.txtSchemeFolder.Text.Trim() : Path.GetDirectoryName(oldPath);+ string folder = string.IsNullOrEmpty(oldPath) ? txtSchemeFolder.Text.Trim() : Path.GetDirectoryName(oldPath);string newPath = ColorSchemeStore.PathFor(folder, newName);if (!string.Equals(newPath, oldPath, StringComparison.OrdinalIgnoreCase) && File.Exists(newPath)){@@ -427,10 +430,10 @@ namespace _2D_wave_sim_V01{File.Delete(oldPath);}- if (this._current != null && !string.IsNullOrEmpty(oldPath) && string.Equals(this._current.FilePath, oldPath, StringComparison.OrdinalIgnoreCase))+ if (_current != null && !string.IsNullOrEmpty(oldPath) && string.Equals(_current.FilePath, oldPath, StringComparison.OrdinalIgnoreCase)){- this._current.Name = newName;- this._current.FilePath = newPath;+ _current.Name = newName;+ _current.FilePath = newPath;}}catch (Exception ex)@@ -438,9 +441,9 @@ namespace _2D_wave_sim_V01MessageBox.Show(this, "The scheme could not be renamed:\r\n" + ex.Message, "Rename color scheme", MessageBoxButtons.OK, MessageBoxIcon.Hand);return;}- this.LoadSchemeList();- this.SelectSchemeInList(newName);- this.ToolStripStatusLabel1.Text = "Color scheme '" + oldName + "' renamed to '" + newName + "'.";+ LoadSchemeList();+ SelectSchemeInList(newName);+ ToolStripStatusLabel1.Text = "Color scheme '" + oldName + "' renamed to '" + newName + "'.";}/// <summary>@@ -449,12 +452,12 @@ namespace _2D_wave_sim_V01/// </summary>private void btnDeleteColorScheme_Click(object sender, EventArgs e){- if (this._previewScheme == null)+ if (_previewScheme == null){MessageBox.Show(this, "Select a scheme in the list first.", "Delete color scheme", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- ColorScheme previewScheme = this._previewScheme;+ ColorScheme previewScheme = _previewScheme;string name = previewScheme.Name;string filePath = previewScheme.FilePath;if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))@@ -476,19 +479,19 @@ namespace _2D_wave_sim_V01MessageBox.Show(this, "The scheme could not be deleted:\r\n" + ex.Message, "Delete color scheme", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);return;}- if (this._current != null && string.Equals(this._current.FilePath, filePath, StringComparison.OrdinalIgnoreCase))+ if (_current != null && string.Equals(_current.FilePath, filePath, StringComparison.OrdinalIgnoreCase)){- this._current.FilePath = null;+ _current.FilePath = null;}- this._previewScheme = null;- this.LoadSchemeList();- this.ToolStripStatusLabel1.Text = "Color scheme '" + name + "' deleted.";+ _previewScheme = null;+ LoadSchemeList();+ ToolStripStatusLabel1.Text = "Color scheme '" + name + "' deleted.";}/// <summary>Selects and scrolls to the first list row whose scheme name matches <paramref name="name"/> (case-insensitive); does nothing if there is none.</summary>private void SelectSchemeInList(string name){- foreach (ListViewItem item in this.ListView1.Items)+ foreach (ListViewItem item in ListView1.Items){ColorScheme scheme = item.Tag as ColorScheme;if (scheme != null && string.Equals(scheme.Name, name, StringComparison.OrdinalIgnoreCase))@@ -502,16 +505,19 @@ namespace _2D_wave_sim_V01/// <summary>/// Checking the "field" or "intensity" radio button changes the type of the current scheme and marks it- /// dirty. Ignored while <see cref="RefreshEditorState"/> is setting the radios programmatically- /// (<c>_updatingRadios</c>), while previewing, and for the radio that just became unchecked.+ /// dirty. The radio buttons say what the current scheme is meant for; the choice is saved in the scheme+ /// file as <c>"scheme_type": "field"</c> or <c>"scheme_type": "intensity"</c>+ /// (<see cref="ColorScheme.SchemeTypeField"/> / <see cref="ColorScheme.SchemeTypeIntensity"/>) and is shown+ /// again when the file is loaded. Ignored while <see cref="RefreshEditorState"/> is setting the radios+ /// programmatically (<c>_updatingRadios</c>), while previewing, and for the radio that just became unchecked./// </summary>private void SchemeType_CheckedChanged(object sender, EventArgs e){- if (this._updatingRadios)+ if (_updatingRadios){return;}- if (this._current == null || this._previewScheme != null)+ if (_current == null || _previewScheme != null){return;}@@ -520,12 +526,12 @@ namespace _2D_wave_sim_V01{return;}- string schemeType = radio == this.radSchemeTypeField ? ColorScheme.SchemeTypeField : ColorScheme.SchemeTypeIntensity;- if (this._current.SchemeType != schemeType)+ string schemeType = radio == radSchemeTypeField ? ColorScheme.SchemeTypeField : ColorScheme.SchemeTypeIntensity;+ if (_current.SchemeType != schemeType){- this._current.SchemeType = schemeType;- this._dirty = true;- this.RefreshEditorState();+ _current.SchemeType = schemeType;+ _dirty = true;+ RefreshEditorState();}}@@ -533,33 +539,33 @@ namespace _2D_wave_sim_V01/// <returns>Null when nothing is previewed and no scheme has been loaded.</returns>private ColorScheme DisplayedScheme(){- return this._previewScheme ?? this._current;+ return _previewScheme ?? _current;}/// <summary>/// Brings every editor control in line with the current/preview state: name box (with an- /// "(unsaved changes)" suffix), the nine stop buttons (color, contrasting text, thick border on the- /// selected stop), picker enabling and caption, Load/Save button enabling, the type radios (set with- /// <c>_updatingRadios</c> raised so <see cref="SchemeType_CheckedChanged"/> ignores it) and finally a- /// repaint of the preview bar.+ /// "(unsaved changes)" suffix), the <see cref="ColorScheme.StopCount"/> stop buttons (color, contrasting+ /// text, thick border on the selected stop), picker enabling and caption, Load/Save button enabling, the+ /// type radios (set with <c>_updatingRadios</c> raised so <see cref="SchemeType_CheckedChanged"/> ignores+ /// it) and finally a repaint of the preview bar./// </summary>private void RefreshEditorState(){- bool previewing = this._previewScheme != null;- ColorScheme scheme = this.DisplayedScheme();- bool hasCurrent = this._current != null;- bool editingStop = hasCurrent && !previewing && this._selectedStop >= 0;+ bool previewing = _previewScheme != null;+ ColorScheme scheme = DisplayedScheme();+ bool hasCurrent = _current != null;+ bool editingStop = hasCurrent && !previewing && _selectedStop >= 0;if (hasCurrent){- this.txtCurrentColorScheme.Text = this._current.Name + (this._dirty ? " (unsaved changes)" : "");+ txtCurrentColorScheme.Text = _current.Name + (_dirty ? " (unsaved changes)" : "");}else{- this.txtCurrentColorScheme.Text = "(none loaded)";+ txtCurrentColorScheme.Text = "(none loaded)";}for (int k = 0; k < ColorScheme.StopCount; k++){- Button button = this._stopButtons[k];+ Button button = _stopButtons[k];button.Enabled = scheme != null;if (scheme != null){@@ -572,52 +578,55 @@ namespace _2D_wave_sim_V01button.BackColor = SystemColors.Control;button.ForeColor = SystemColors.ControlText;}- button.FlatAppearance.BorderSize = (editingStop && k == this._selectedStop) ? 4 : 1;+ button.FlatAppearance.BorderSize = (editingStop && k == _selectedStop) ? 4 : 1;}- this._picker.Enabled = editingStop;+ _picker.Enabled = editingStop;if (editingStop){- this.lblColorPicker.Text = "Color Picker - editing Color " + (this._selectedStop + 1).ToString() + Form1.StopRole(this._selectedStop);+ lblColorPicker.Text = "Color Picker - editing Color " + (_selectedStop + 1).ToString() + Form1.StopRole(_selectedStop);}else{- this.lblColorPicker.Text = "Color Picker (click a Color button to edit it)";+ lblColorPicker.Text = "Color Picker (click a Color button to edit it)";}- this.btnLoadScheme.Enabled = previewing;- this.btnSaveCurrentScheme.Enabled = hasCurrent && this._dirty;- this.btnSaveAsColorScheme.Enabled = hasCurrent;- this._updatingRadios = true;+ btnLoadScheme.Enabled = previewing;+ btnSaveCurrentScheme.Enabled = hasCurrent && _dirty;+ btnSaveAsColorScheme.Enabled = hasCurrent;+ // radio buttons show the type of the displayed scheme; they can only be changed for the current scheme+ _updatingRadios = true;try{string schemeType = scheme == null ? "" : scheme.SchemeType;- this.radSchemeTypeField.Checked = schemeType == ColorScheme.SchemeTypeField;- this.radSchemeTypeIntensity.Checked = schemeType == ColorScheme.SchemeTypeIntensity;- this.radSchemeTypeField.Enabled = hasCurrent && !previewing;- this.radSchemeTypeIntensity.Enabled = hasCurrent && !previewing;+ radSchemeTypeField.Checked = schemeType == ColorScheme.SchemeTypeField;+ radSchemeTypeIntensity.Checked = schemeType == ColorScheme.SchemeTypeIntensity;+ radSchemeTypeField.Enabled = hasCurrent && !previewing;+ radSchemeTypeIntensity.Enabled = hasCurrent && !previewing;}finally{- this._updatingRadios = false;+ _updatingRadios = false;}- this.pnlScheme.Invalidate();+ pnlScheme.Invalidate();}/// <summary>- /// Paints the vertical preview bar: entry 0 at the top, entry 254 at the bottom, stretched from a- /// 1x255 strip without smoothing; white-on-black tick marks at the nine stop positions (a full-width- /// thick line for the stop being edited) and the scale labels for the scheme type ("-1 / 0 / +1" for- /// field, "0 / max" for intensity). A plain light fill when there is nothing to show.+ /// Paints the vertical preview bar: entry 0 (Color 1) at the top, the last entry (last Color) at the+ /// bottom and the middle entry (centre Color) half-way, stretched from a 1 x <see cref="ColorScheme.EntryCount"/>+ /// strip without smoothing; white-on-black tick marks at the <see cref="ColorScheme.StopCount"/> stop+ /// positions (a full-width thick line for the stop being edited) and the scale labels for the scheme type+ /// ("-1 / 0 / +1" for field, "0 / max" for intensity). A plain light fill when there is nothing to show./// </summary>private void pnlScheme_Paint(object sender, PaintEventArgs e){- ColorScheme scheme = this.DisplayedScheme();+ ColorScheme scheme = DisplayedScheme();Graphics g = e.Graphics;- Rectangle bar = this.pnlScheme.ClientRectangle;+ Rectangle bar = pnlScheme.ClientRectangle;if (scheme == null){g.Clear(SystemColors.ControlLight);return;}+ // vertical gradient: top = entry 0 (Color 1), bottom = entry EntryCount - 1 (last Color), middle = entry EntryCount / 2 (centre Color)using (Bitmap strip = new Bitmap(1, ColorScheme.EntryCount, PixelFormat.Format32bppArgb)){for (int i = 0; i < ColorScheme.EntryCount; i++)@@ -628,12 +637,13 @@ namespace _2D_wave_sim_V01g.PixelOffsetMode = PixelOffsetMode.Half;g.DrawImage(strip, bar);}- bool editingStop = this._previewScheme == null && this._selectedStop >= 0;+ // tick marks at the stop positions (dark and light so they show on any color)+ bool editingStop = _previewScheme == null && _selectedStop >= 0;for (int k = 0; k < ColorScheme.StopCount; k++){- // Stop k sits at fraction k/8 of the bar height (9 stops = 8 segments).- int y = (int)Math.Round((k * (bar.Height - 1)) / 8.0);- bool highlighted = editingStop && k == this._selectedStop;+ // Stop k sits at fraction k/(StopCount - 1) of the bar height (StopCount stops = StopCount - 1 segments).+ int y = (int)Math.Round((k * (bar.Height - 1)) / (double)(ColorScheme.StopCount - 1));+ bool highlighted = editingStop && k == _selectedStop;int tickLength = highlighted ? bar.Width : 9;int tickWidth = highlighted ? 3 : 1;using (Pen outline = new Pen(Color.Black, tickWidth + 2))@@ -647,69 +657,77 @@ namespace _2D_wave_sim_V01g.DrawLine(tick, bar.Width - tickLength, y, bar.Width, y);}}+ // scale labels that depend on the scheme typeif (scheme.SchemeType == ColorScheme.SchemeTypeField){- this.DrawScaleLabel(g, bar, "-1", 0, scheme);- this.DrawScaleLabel(g, bar, "0", 127, scheme);- this.DrawScaleLabel(g, bar, "+1", 254, scheme);+ DrawScaleLabel(g, bar, "-1", 0, scheme);+ DrawScaleLabel(g, bar, "0", ColorScheme.EntryCount / 2, scheme);+ DrawScaleLabel(g, bar, "+1", ColorScheme.EntryCount - 1, scheme);}else if (scheme.SchemeType == ColorScheme.SchemeTypeIntensity){- this.DrawScaleLabel(g, bar, "0", 0, scheme);- this.DrawScaleLabel(g, bar, "max", 254, scheme);+ DrawScaleLabel(g, bar, "0", 0, scheme);+ DrawScaleLabel(g, bar, "max", ColorScheme.EntryCount - 1, scheme);}}/// <summary>/// Draws <paramref name="text"/> horizontally centred on the preview bar at the height of table entry- /// <paramref name="entryIndex"/> (0..254 mapped onto the bar height), kept at least 12 px away from the- /// top and bottom edges, in black or white depending on the entry color underneath.+ /// <paramref name="entryIndex"/> (0..<see cref="ColorScheme.EntryCount"/> - 1 mapped onto the bar height),+ /// kept at least 12 px away from the top and bottom edges (clear of the end ticks), in black or white+ /// depending on the entry color underneath, so it is readable on any color./// </summary>/// <param name="g">Target graphics of the preview panel.</param>/// <param name="bar">Client rectangle of the preview panel.</param>/// <param name="text">Label text.</param>- /// <param name="entryIndex">Table entry (0..254) whose vertical position the label is centred on.</param>+ /// <param name="entryIndex">Table entry (0..<see cref="ColorScheme.EntryCount"/> - 1) whose vertical position the label is centred on.</param>/// <param name="scheme">Scheme being painted; used only to pick a contrasting text color.</param>private void DrawScaleLabel(Graphics g, Rectangle bar, string text, int entryIndex, ColorScheme scheme){- Size textSize = TextRenderer.MeasureText(g, text, this.pnlScheme.Font);- int centerY = (int)Math.Round((entryIndex * (bar.Height - 1)) / 254.0);+ Size textSize = TextRenderer.MeasureText(g, text, pnlScheme.Font);+ int centerY = (int)Math.Round((entryIndex * (bar.Height - 1)) / (double)(ColorScheme.EntryCount - 1));int top = centerY - textSize.Height / 2;if (top < 12){- top = 12;+ top = 12; // keep clear of the end ticks}if (top + textSize.Height > bar.Height - 12){top = bar.Height - 12 - textSize.Height;}Rectangle labelBounds = new Rectangle(0, top, bar.Width, textSize.Height);- TextRenderer.DrawText(g, text, this.pnlScheme.Font, labelBounds, Form1.ContrastColor(scheme.GetEntry(entryIndex)), TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);+ TextRenderer.DrawText(g, text, pnlScheme.Font, labelBounds, Form1.ContrastColor(scheme.GetEntry(entryIndex)), TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);}/// <summary>/// Color shown on stop button <paramref name="k"/>: the real stop for a stop scheme, otherwise the table- /// sampled at the position the stop would have (k/8 of the 0..254 range).+ /// sampled at the position the stop would have (k/(<see cref="ColorScheme.StopCount"/> - 1) of the+ /// 0..<see cref="ColorScheme.EntryCount"/> - 1 range)./// </summary>private static Color StopColorOf(ColorScheme scheme, int k){- return scheme.HasStops ? scheme.Stops[k] : scheme.SampleAt((k * 254) / 8.0);+ return scheme.HasStops ? scheme.Stops[k] : scheme.SampleAt((k * (ColorScheme.EntryCount - 1)) / (double)(ColorScheme.StopCount - 1));}- /// <summary>Suffix for the picker caption describing what stop <paramref name="k"/> represents (first, centre, last); empty for the others.</summary>+ /// <summary>+ /// Suffix for the picker caption describing what stop <paramref name="k"/> represents (first, centre, last);+ /// empty for the others. There is a centre stop only while <see cref="ColorScheme.StopCount"/> is odd.+ /// </summary>private static string StopRole(int k){- switch (k)+ if (k == 0){- case 0:return " (start of the scale)";- case 8:+ }+ if (k == ColorScheme.StopCount - 1)+ {return " (end of the scale)";- case 4:+ }+ if (ColorScheme.StopCount % 2 == 1 && k == ColorScheme.StopCount / 2)+ {return " (centre = zero field)";- default:- return "";}+ return "";}/// <summary>Black or white, whichever reads better on top of <paramref name="c"/> (Rec. 601 luma, threshold 140 of 255).</summary>@@ -720,24 +738,25 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Renders a 120x16 horizontal strip of the scheme (entry 0 left, 254 right) with a gray border, for the- /// list view image list. The caller owns the returned bitmap; <see cref="LoadSchemeList"/> keeps them in- /// <c>_thumbBitmaps</c> and disposes them on the next reload.+ /// Renders a <see cref="ThumbWidth"/> x <see cref="ThumbHeight"/> horizontal strip of the scheme (entry 0+ /// left, the last entry right) with a gray border, for the list view image list. The caller owns the+ /// returned bitmap; <see cref="LoadSchemeList"/> keeps them in <c>_thumbBitmaps</c> and disposes them on+ /// the next reload./// </summary>private static Bitmap MakeThumbnail(ColorScheme scheme){- Bitmap thumb = new Bitmap(120, 16, PixelFormat.Format32bppArgb);+ Bitmap thumb = new Bitmap(ThumbWidth, ThumbHeight, PixelFormat.Format32bppArgb);using (Graphics g = Graphics.FromImage(thumb)){- for (int x = 0; x < 120; x++)+ for (int x = 0; x < ThumbWidth; x++){- int entryIndex = (int)Math.Round((x * 254) / 119.0);+ int entryIndex = (int)Math.Round((x * (ColorScheme.EntryCount - 1)) / (double)(ThumbWidth - 1));using (SolidBrush brush = new SolidBrush(scheme.GetEntry(entryIndex))){- g.FillRectangle(brush, x, 0, 1, 16);+ g.FillRectangle(brush, x, 0, 1, ThumbHeight);}}- g.DrawRectangle(Pens.Gray, 0, 0, 119, 15);+ g.DrawRectangle(Pens.Gray, 0, 0, ThumbWidth - 1, ThumbHeight - 1);}return thumb;}diff --git a/Wave_Dude_2D/Form1.Output.cs b/Wave_Dude_2D/Form1.Output.csindex 9e9e15a..5530b42 100644--- a/Wave_Dude_2D/Form1.Output.cs+++ b/Wave_Dude_2D/Form1.Output.cs@@ -26,12 +26,12 @@ namespace _2D_wave_sim_V01/// </summary>private void InitializeOutputsTab(){- this._outputPreviewPic = new PictureBox();- this._outputPreviewPic.Dock = DockStyle.Fill;- this._outputPreviewPic.SizeMode = PictureBoxSizeMode.Zoom;- this.pnlPreview.Controls.Add(this._outputPreviewPic);- this.RefreshOutputProjectList("");- this.UpdateShareWithEditorsButton();+ _outputPreviewPic = new PictureBox();+ _outputPreviewPic.Dock = DockStyle.Fill;+ _outputPreviewPic.SizeMode = PictureBoxSizeMode.Zoom;+ pnlPreview.Controls.Add(_outputPreviewPic);+ RefreshOutputProjectList("");+ UpdateShareWithEditorsButton();}/// <summary>@@ -42,48 +42,48 @@ namespace _2D_wave_sim_V01/// </summary>private void RefreshOutputProjectList(string preferredName = ""){- string selectedName = (preferredName.Length > 0) ? preferredName : this.SelectedProjectName(this.lstAllProjects3);- List<Form1.ProjectListEntry> entries = this.BuildProjectEntries();- this.SortProjectEntries(entries, this._outputProjectSortColumn, this._outputProjectSortAscending);- this.PopulateProjectListView(this.lstAllProjects3, entries);- this.UpdateOutputProjectSortHeaders();- this.SelectProjectInList(this.lstAllProjects3, selectedName);+ string selectedName = (preferredName.Length > 0) ? preferredName : SelectedProjectName(lstAllProjects3);+ List<Form1.ProjectListEntry> entries = BuildProjectEntries();+ SortProjectEntries(entries, _outputProjectSortColumn, _outputProjectSortAscending);+ PopulateProjectListView(lstAllProjects3, entries);+ UpdateOutputProjectSortHeaders();+ SelectProjectInList(lstAllProjects3, selectedName);}/// <summary>Clicking a column header sorts the Outputs-tab project list by it; clicking the current sort column again flips the direction.</summary>private void lstAllProjects3_ColumnClick(object sender, ColumnClickEventArgs e){- if (e.Column == this._outputProjectSortColumn)+ if (e.Column == _outputProjectSortColumn){- this._outputProjectSortAscending = !this._outputProjectSortAscending;+ _outputProjectSortAscending = !_outputProjectSortAscending;}else{- this._outputProjectSortColumn = e.Column;- this._outputProjectSortAscending = true;+ _outputProjectSortColumn = e.Column;+ _outputProjectSortAscending = true;}- this.RefreshOutputProjectList("");+ RefreshOutputProjectList("");}/// <summary>Appends " ^" (ascending) or " v" (descending) to the header of the column the Outputs-tab project list is sorted by.</summary>private void UpdateOutputProjectSortHeaders(){- string arrow = this._outputProjectSortAscending ? " ^" : " v";- this.colProjectName2.Text = "Project name" + ((this._outputProjectSortColumn == 0) ? arrow : "");- this.colLastEdited2.Text = "Last edited" + ((this._outputProjectSortColumn == 1) ? arrow : "");+ string arrow = _outputProjectSortAscending ? " ^" : " v";+ colProjectName2.Text = "Project name" + ((_outputProjectSortColumn == 0) ? arrow : "");+ colLastEdited2.Text = "Last edited" + ((_outputProjectSortColumn == 1) ? arrow : "");}/// <summary>Full folder path of the project selected in the Outputs-tab list, or "" when none is selected.</summary>private string SelectedOutputProjectFolder(){- string name = this.SelectedProjectName(this.lstAllProjects3);- return (name.Length == 0) ? "" : ProjectStore.FolderPathFor(this._settings.ProjectRoot, name);+ string name = SelectedProjectName(lstAllProjects3);+ return (name.Length == 0) ? "" : ProjectStore.FolderPathFor(_settings.ProjectRoot, name);}/// <summary>Selecting a project reloads the three file lists for it.</summary>private void lstAllProjects3_SelectedIndexChanged(object sender, EventArgs e){- this.RefreshOutputFileLists();+ RefreshOutputFileLists();}/// <summary>@@ -94,15 +94,15 @@ namespace _2D_wave_sim_V01/// </summary>private void RefreshOutputFileLists(){- string projectFolder = this.SelectedOutputProjectFolder();- this.FillFileList(this.lstScenes, projectFolder, ProjectStore.SceneImageFolderName, Form1.SceneImageExtensions, this._sceneSortColumn, this._sceneSortAscending);- this.FillFileList(this.lstImages, projectFolder, ProjectStore.OutputFramesFolderName, Form1.OutputImageExtensions, this._imageSortColumn, this._imageSortAscending);- this.FillFileList(this.lstVideo, projectFolder, ProjectStore.OutputVideoFolderName, Form1.OutputVideoExtensions, this._videoSortColumn, this._videoSortAscending);- this.UpdateFileListSortHeaders(this.colSceneName, "Scene file name", this.colSceneCreated, "Created on", this._sceneSortColumn, this._sceneSortAscending);- this.UpdateFileListSortHeaders(this.colImageName, "Image file name", this.colCreatedOn, "Created on", this._imageSortColumn, this._imageSortAscending);- this.UpdateFileListSortHeaders(this.colVideoName, "Video file name", this.colCreatedOn2, "Created on", this._videoSortColumn, this._videoSortAscending);- this.ClearOutputPreview();- this.UpdateCopyToClipboardButton();+ string projectFolder = SelectedOutputProjectFolder();+ FillFileList(lstScenes, projectFolder, ProjectStore.SceneImageFolderName, Form1.SceneImageExtensions, _sceneSortColumn, _sceneSortAscending);+ FillFileList(lstImages, projectFolder, ProjectStore.OutputFramesFolderName, Form1.OutputImageExtensions, _imageSortColumn, _imageSortAscending);+ FillFileList(lstVideo, projectFolder, ProjectStore.OutputVideoFolderName, Form1.OutputVideoExtensions, _videoSortColumn, _videoSortAscending);+ UpdateFileListSortHeaders(colSceneName, "Scene file name", colSceneCreated, "Created on", _sceneSortColumn, _sceneSortAscending);+ UpdateFileListSortHeaders(colImageName, "Image file name", colCreatedOn, "Created on", _imageSortColumn, _imageSortAscending);+ UpdateFileListSortHeaders(colVideoName, "Video file name", colCreatedOn2, "Created on", _videoSortColumn, _videoSortAscending);+ ClearOutputPreview();+ UpdateCopyToClipboardButton();}/// <summary>@@ -202,49 +202,49 @@ namespace _2D_wave_sim_V01/// <summary>Reloads and re-sorts the scene-image list, keeping the selected files selected; used after a header click.</summary>private void RefillSceneList(){- List<string> selected = this.SelectedFilePaths(this.lstScenes);- this.FillFileList(this.lstScenes, this.SelectedOutputProjectFolder(), ProjectStore.SceneImageFolderName, Form1.SceneImageExtensions, this._sceneSortColumn, this._sceneSortAscending);- this.UpdateFileListSortHeaders(this.colSceneName, "Scene file name", this.colSceneCreated, "Created on", this._sceneSortColumn, this._sceneSortAscending);- this.ReselectFiles(this.lstScenes, selected);+ List<string> selected = SelectedFilePaths(lstScenes);+ FillFileList(lstScenes, SelectedOutputProjectFolder(), ProjectStore.SceneImageFolderName, Form1.SceneImageExtensions, _sceneSortColumn, _sceneSortAscending);+ UpdateFileListSortHeaders(colSceneName, "Scene file name", colSceneCreated, "Created on", _sceneSortColumn, _sceneSortAscending);+ ReselectFiles(lstScenes, selected);}/// <summary>Reloads and re-sorts the output-frame list, keeping the selected files selected; used after a header click.</summary>private void RefillImageList(){- List<string> selected = this.SelectedFilePaths(this.lstImages);- this.FillFileList(this.lstImages, this.SelectedOutputProjectFolder(), ProjectStore.OutputFramesFolderName, Form1.OutputImageExtensions, this._imageSortColumn, this._imageSortAscending);- this.UpdateFileListSortHeaders(this.colImageName, "Image file name", this.colCreatedOn, "Created on", this._imageSortColumn, this._imageSortAscending);- this.ReselectFiles(this.lstImages, selected);+ List<string> selected = SelectedFilePaths(lstImages);+ FillFileList(lstImages, SelectedOutputProjectFolder(), ProjectStore.OutputFramesFolderName, Form1.OutputImageExtensions, _imageSortColumn, _imageSortAscending);+ UpdateFileListSortHeaders(colImageName, "Image file name", colCreatedOn, "Created on", _imageSortColumn, _imageSortAscending);+ ReselectFiles(lstImages, selected);}/// <summary>Reloads and re-sorts the video list, keeping the selected files selected; used after a header click.</summary>private void RefillVideoList(){- List<string> selected = this.SelectedFilePaths(this.lstVideo);- this.FillFileList(this.lstVideo, this.SelectedOutputProjectFolder(), ProjectStore.OutputVideoFolderName, Form1.OutputVideoExtensions, this._videoSortColumn, this._videoSortAscending);- this.UpdateFileListSortHeaders(this.colVideoName, "Video file name", this.colCreatedOn2, "Created on", this._videoSortColumn, this._videoSortAscending);- this.ReselectFiles(this.lstVideo, selected);+ List<string> selected = SelectedFilePaths(lstVideo);+ FillFileList(lstVideo, SelectedOutputProjectFolder(), ProjectStore.OutputVideoFolderName, Form1.OutputVideoExtensions, _videoSortColumn, _videoSortAscending);+ UpdateFileListSortHeaders(colVideoName, "Video file name", colCreatedOn2, "Created on", _videoSortColumn, _videoSortAscending);+ ReselectFiles(lstVideo, selected);}/// <summary>Clicking a header sorts the scene-image list by that column (toggling direction on a repeat click).</summary>private void lstScenes_ColumnClick(object sender, ColumnClickEventArgs e){- Form1.ToggleFileSort(ref this._sceneSortColumn, ref this._sceneSortAscending, e.Column);- this.RefillSceneList();+ Form1.ToggleFileSort(ref _sceneSortColumn, ref _sceneSortAscending, e.Column);+ RefillSceneList();}/// <summary>Clicking a header sorts the output-frame list by that column (toggling direction on a repeat click).</summary>private void lstImages_ColumnClick(object sender, ColumnClickEventArgs e){- Form1.ToggleFileSort(ref this._imageSortColumn, ref this._imageSortAscending, e.Column);- this.RefillImageList();+ Form1.ToggleFileSort(ref _imageSortColumn, ref _imageSortAscending, e.Column);+ RefillImageList();}/// <summary>Clicking a header sorts the video list by that column (toggling direction on a repeat click).</summary>private void lstVideo_ColumnClick(object sender, ColumnClickEventArgs e){- Form1.ToggleFileSort(ref this._videoSortColumn, ref this._videoSortAscending, e.Column);- this.RefillVideoList();+ Form1.ToggleFileSort(ref _videoSortColumn, ref _videoSortAscending, e.Column);+ RefillVideoList();}/// <summary>Applies a header click to a sort column/direction pair: the same column flips the direction, a different column becomes the sort column in ascending order.</summary>@@ -262,55 +262,58 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Clears the selection of the two file lists other than <paramref name="active"/>. Sets+ /// Clears the selection of the two file lists other than <paramref name="active"/> (the one the user+ /// just clicked in), so only one of the three ever shows a selection at a time - otherwise it is unclear+ /// which list's item <c>pnlPreview</c> is actually showing. The Projects list (<c>lstAllProjects3</c>) is+ /// not one of these three and keeps its own selection regardless. Sets/// <c>_clearingFileListSelection</c> while doing so, so that their/// <c>SelectedIndexChanged</c> handlers ignore the change and do not clear the preview./// </summary>private void ClearOtherFileListSelections(ListView active){- this._clearingFileListSelection = true;+ _clearingFileListSelection = true;try{- if (active != this.lstScenes)+ if (active != lstScenes){- this.lstScenes.SelectedItems.Clear();+ lstScenes.SelectedItems.Clear();}- if (active != this.lstImages)+ if (active != lstImages){- this.lstImages.SelectedItems.Clear();+ lstImages.SelectedItems.Clear();}- if (active != this.lstVideo)+ if (active != lstVideo){- this.lstVideo.SelectedItems.Clear();+ lstVideo.SelectedItems.Clear();}}finally{- this._clearingFileListSelection = false;+ _clearingFileListSelection = false;}}/// <summary>Selecting a scene image makes it the only selection across the three lists and shows it in the preview; ignored while another list is clearing selections.</summary>private void lstScenes_SelectedIndexChanged(object sender, EventArgs e){- if (this._clearingFileListSelection)+ if (_clearingFileListSelection){return;}- this.ClearOtherFileListSelections(this.lstScenes);- this.ShowOutputPreview(this.lstScenes);+ ClearOtherFileListSelections(lstScenes);+ ShowOutputPreview(lstScenes);}/// <summary>Selecting output frames makes them the only selection across the three lists, previews the first one and updates the copy button; ignored while another list is clearing selections.</summary>private void lstImages_SelectedIndexChanged(object sender, EventArgs e){- if (this._clearingFileListSelection)+ if (_clearingFileListSelection){return;}- this.ClearOtherFileListSelections(this.lstImages);- this.ShowOutputPreview(this.lstImages);- this.UpdateCopyToClipboardButton();+ ClearOtherFileListSelections(lstImages);+ ShowOutputPreview(lstImages);+ UpdateCopyToClipboardButton();}/// <summary>@@ -327,52 +330,56 @@ namespace _2D_wave_sim_V01string path = list.SelectedItems[0].Tag as string;if (string.IsNullOrEmpty(path) || !File.Exists(path)){- this.ClearOutputPreview();+ ClearOutputPreview();return;}try{- this.SetOutputPreviewImage(Form1.LoadImageCopy(path), false);+ SetOutputPreviewImage(Form1.LoadImageCopy(path), false);}catch (Exception){- this.ClearOutputPreview();+ ClearOutputPreview();}}/// <summary>/// Selecting exactly one video makes it the only selection across the three lists and shows- /// the shell thumbnail for it, requested at the preview box's current size (at least 64x64- /// pixels). Any other selection count, a missing file or a shell failure clears the preview.+ /// a thumbnail-sized preview of it, via the operating system's own shell thumbnail cache+ /// (<see cref="GetShellThumbnail"/>, further down) - there is no dependency-free way to decode/draw+ /// an actual video frame with just System.Drawing/System.Windows.Forms. The thumbnail is requested+ /// at the preview box's current size (at least 64x64 pixels). Selecting zero or more than one video+ /// (<c>lstVideo</c> allows multi-select) clears the preview instead, since a single thumbnail cannot+ /// stand in for several files; a missing file or a shell failure clears it too./// Ignored while another list is clearing selections./// </summary>private void lstVideo_SelectedIndexChanged(object sender, EventArgs e){- if (this._clearingFileListSelection)+ if (_clearingFileListSelection){return;}- this.ClearOtherFileListSelections(this.lstVideo);- if (this.lstVideo.SelectedItems.Count != 1)+ ClearOtherFileListSelections(lstVideo);+ if (lstVideo.SelectedItems.Count != 1){- this.ClearOutputPreview();+ ClearOutputPreview();return;}- string path = this.lstVideo.SelectedItems[0].Tag as string;+ string path = lstVideo.SelectedItems[0].Tag as string;if (string.IsNullOrEmpty(path) || !File.Exists(path)){- this.ClearOutputPreview();+ ClearOutputPreview();return;}try{- int width = Math.Max(64, this._outputPreviewPic.ClientSize.Width);- int height = Math.Max(64, this._outputPreviewPic.ClientSize.Height);- this.SetOutputPreviewImage(Form1.GetShellThumbnail(path, width, height), true);+ int width = Math.Max(64, _outputPreviewPic.ClientSize.Width);+ int height = Math.Max(64, _outputPreviewPic.ClientSize.Height);+ SetOutputPreviewImage(Form1.GetShellThumbnail(path, width, height), true);}catch (Exception){- this.ClearOutputPreview();+ ClearOutputPreview();}}@@ -383,22 +390,22 @@ namespace _2D_wave_sim_V01/// </summary>private void SetOutputPreviewImage(Image image, bool isVideo = false){- Image previous = this._outputPreviewPic.Image;- this._outputPreviewPic.Image = image;+ Image previous = _outputPreviewPic.Image;+ _outputPreviewPic.Image = image;if (previous != null){previous.Dispose();}- this._outputPreviewIsVideo = isVideo;- this.UpdateShareWithEditorsButton();+ _outputPreviewIsVideo = isVideo;+ UpdateShareWithEditorsButton();}/// <summary>Removes and disposes the preview image; safe to call before <see cref="InitializeOutputsTab"/> has created the preview box.</summary>private void ClearOutputPreview(){- if (this._outputPreviewPic != null)+ if (_outputPreviewPic != null){- this.SetOutputPreviewImage(null, false);+ SetOutputPreviewImage(null, false);}}@@ -410,15 +417,15 @@ namespace _2D_wave_sim_V01/// </summary>private void btnDeleteScene_Click(object sender, EventArgs e){- if (this.lstScenes.SelectedItems.Count == 0)+ if (lstScenes.SelectedItems.Count == 0){MessageBox.Show(this, "Select a scene image in the list first.", "Delete scene", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- List<string> paths = this.SelectedFilePaths(this.lstScenes);+ List<string> paths = SelectedFilePaths(lstScenes);- bool listShowsOpenProject = this._project != null && string.Equals(this._project.FolderPath, this.SelectedOutputProjectFolder(), StringComparison.OrdinalIgnoreCase);- string currentImagePath = (listShowsOpenProject && this._scene.UseImage) ? SceneSettings.ToFullPath(this._project.FolderPath, this._scene.ImageFile) : "";+ bool listShowsOpenProject = _project != null && string.Equals(_project.FolderPath, SelectedOutputProjectFolder(), StringComparison.OrdinalIgnoreCase);+ string currentImagePath = (listShowsOpenProject && _scene.UseImage) ? SceneSettings.ToFullPath(_project.FolderPath, _scene.ImageFile) : "";bool deletesCurrentImage = currentImagePath.Length > 0 && paths.Exists(p => string.Equals(p, currentImagePath, StringComparison.OrdinalIgnoreCase));string question = (paths.Count == 1)@@ -447,10 +454,10 @@ namespace _2D_wave_sim_V01}if (deletesCurrentImage){- this.radUserDefinedScene.Checked = true;+ radUserDefinedScene.Checked = true;}- this.RefreshOutputFileLists();- this.ShowDeleteErrorsIfAny(errors, "Delete scene");+ RefreshOutputFileLists();+ ShowDeleteErrorsIfAny(errors, "Delete scene");}/// <summary>@@ -460,17 +467,17 @@ namespace _2D_wave_sim_V01/// </summary>private void btnLoadExternal_Click(object sender, EventArgs e){- this.btnLOadSceneImage_Click(sender, e);- if (this._project != null && string.Equals(this._project.FolderPath, this.SelectedOutputProjectFolder(), StringComparison.OrdinalIgnoreCase))+ btnLOadSceneImage_Click(sender, e);+ if (_project != null && string.Equals(_project.FolderPath, SelectedOutputProjectFolder(), StringComparison.OrdinalIgnoreCase)){- this.RefreshOutputFileLists();+ RefreshOutputFileLists();}}/// <summary>Deletes the selected output frames (see <see cref="DeleteSelectedImages"/>).</summary>private void btnDeleteImages_Click(object sender, EventArgs e){- this.DeleteSelectedImages();+ DeleteSelectedImages();}/// <summary>Pressing Delete in the output-frame list deletes the selected frames.</summary>@@ -479,28 +486,28 @@ namespace _2D_wave_sim_V01if (e.KeyCode == Keys.Delete){e.Handled = true;- this.DeleteSelectedImages();+ DeleteSelectedImages();}}/// <summary>Permanently deletes the selected output frame files after confirmation; files that could not be deleted are reported together at the end.</summary>private void DeleteSelectedImages(){- if (this.lstImages.SelectedItems.Count == 0)+ if (lstImages.SelectedItems.Count == 0){MessageBox.Show(this, "Select one or more images in the list first.", "Delete images", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- int count = this.lstImages.SelectedItems.Count;+ int count = lstImages.SelectedItems.Count;string question = (count == 1)- ? "Permanently delete '" + this.lstImages.SelectedItems[0].Text + "'?"+ ? "Permanently delete '" + lstImages.SelectedItems[0].Text + "'?": "Permanently delete these " + count.ToString(CultureInfo.InvariantCulture) + " images?";if (MessageBox.Show(this, question, "Delete images", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes){return;}List<string> errors = new List<string>();- foreach (ListViewItem item in this.lstImages.SelectedItems)+ foreach (ListViewItem item in lstImages.SelectedItems){string path = (string)item.Tag;try@@ -512,18 +519,18 @@ namespace _2D_wave_sim_V01errors.Add(item.Text + ": " + ex.Message);}}- this.RefreshOutputFileLists();- this.ShowDeleteErrorsIfAny(errors, "Delete images");+ RefreshOutputFileLists();+ ShowDeleteErrorsIfAny(errors, "Delete images");}/// <summary>Copies the single selected output frame to the clipboard as a bitmap (the clipboard takes its own copy, so the loaded bitmap is disposed immediately).</summary>private void btnCopyToClipboard_Click(object sender, EventArgs e){- if (this.lstImages.SelectedItems.Count != 1)+ if (lstImages.SelectedItems.Count != 1){return;}- string path = this.lstImages.SelectedItems[0].Tag as string;+ string path = lstImages.SelectedItems[0].Tag as string;if (string.IsNullOrEmpty(path) || !File.Exists(path)){return;@@ -534,7 +541,7 @@ namespace _2D_wave_sim_V01{Clipboard.SetImage(bitmap);}- this.ToolStripStatusLabel1.Text = "Copied '" + Path.GetFileName(path) + "' to the clipboard.";+ ToolStripStatusLabel1.Text = "Copied '" + Path.GetFileName(path) + "' to the clipboard.";}catch (Exception ex){@@ -545,13 +552,13 @@ namespace _2D_wave_sim_V01/// <summary>Enables "Copy to clipboard" only when exactly one output frame is selected.</summary>private void UpdateCopyToClipboardButton(){- this.btnCopyToClipboard.Enabled = this.lstImages.SelectedItems.Count == 1;+ btnCopyToClipboard.Enabled = lstImages.SelectedItems.Count == 1;}/// <summary>Opens the selected project's output_frames folder in Explorer (icon view; the folder is created if missing).</summary>private void btnOpenImageFolder2_Click(object sender, EventArgs e){- string folder = this.SelectedOutputProjectFolder();+ string folder = SelectedOutputProjectFolder();if (folder.Length == 0){MessageBox.Show(this, "Select a project in the list first.", "Open image folder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);@@ -559,7 +566,7 @@ namespace _2D_wave_sim_V01}try{- this.OpenFolderInExplorer(Path.Combine(folder, ProjectStore.OutputFramesFolderName), 1);+ OpenFolderInExplorer(Path.Combine(folder, ProjectStore.OutputFramesFolderName), FVM_ICON);}catch (Exception ex){@@ -570,7 +577,7 @@ namespace _2D_wave_sim_V01/// <summary>Deletes the selected videos (see <see cref="DeleteSelectedVideos"/>).</summary>private void btnDeleteVideos_Click(object sender, EventArgs e){- this.DeleteSelectedVideos();+ DeleteSelectedVideos();}/// <summary>Pressing Delete in the video list deletes the selected videos.</summary>@@ -579,28 +586,28 @@ namespace _2D_wave_sim_V01if (e.KeyCode == Keys.Delete){e.Handled = true;- this.DeleteSelectedVideos();+ DeleteSelectedVideos();}}/// <summary>Permanently deletes the selected video files after confirmation; files that could not be deleted are reported together at the end.</summary>private void DeleteSelectedVideos(){- if (this.lstVideo.SelectedItems.Count == 0)+ if (lstVideo.SelectedItems.Count == 0){MessageBox.Show(this, "Select one or more videos in the list first.", "Delete videos", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- int count = this.lstVideo.SelectedItems.Count;+ int count = lstVideo.SelectedItems.Count;string question = (count == 1)- ? "Permanently delete '" + this.lstVideo.SelectedItems[0].Text + "'?"+ ? "Permanently delete '" + lstVideo.SelectedItems[0].Text + "'?": "Permanently delete these " + count.ToString(CultureInfo.InvariantCulture) + " videos?";if (MessageBox.Show(this, question, "Delete videos", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes){return;}List<string> errors = new List<string>();- foreach (ListViewItem item in this.lstVideo.SelectedItems)+ foreach (ListViewItem item in lstVideo.SelectedItems){string path = (string)item.Tag;try@@ -612,27 +619,27 @@ namespace _2D_wave_sim_V01errors.Add(item.Text + ": " + ex.Message);}}- this.RefreshOutputFileLists();- this.ShowDeleteErrorsIfAny(errors, "Delete videos");+ RefreshOutputFileLists();+ ShowDeleteErrorsIfAny(errors, "Delete videos");}/// <summary>Opens the first selected video in the system's default player.</summary>private void btnViewVIdeoInPlayer2_Click(object sender, EventArgs e){- if (this.lstVideo.SelectedItems.Count == 0)+ if (lstVideo.SelectedItems.Count == 0){MessageBox.Show(this, "Select a video in the list first.", "View in player", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- this.OpenVideo((string)this.lstVideo.SelectedItems[0].Tag);+ OpenVideo((string)lstVideo.SelectedItems[0].Tag);}/// <summary>Double-clicking a video opens it in the system's default player.</summary>private void lstVideo_DoubleClick(object sender, EventArgs e){- if (this.lstVideo.SelectedItems.Count > 0)+ if (lstVideo.SelectedItems.Count > 0){- this.OpenVideo((string)this.lstVideo.SelectedItems[0].Tag);+ OpenVideo((string)lstVideo.SelectedItems[0].Tag);}}@@ -644,15 +651,15 @@ namespace _2D_wave_sim_V01/// </summary>private void btnRenameVideo_Click(object sender, EventArgs e){- if (this.lstVideo.SelectedItems.Count != 1)+ if (lstVideo.SelectedItems.Count != 1){MessageBox.Show(this, "Select a single video in the list first.", "Rename video", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- string oldPath = (string)this.lstVideo.SelectedItems[0].Tag;+ string oldPath = (string)lstVideo.SelectedItems[0].Tag;string fileName = Path.GetFileName(oldPath);string newName = fileName;- if (!this.PromptForText("Rename video", "New name for '" + fileName + "':", fileName, ref newName))+ if (!PromptForText("Rename video", "New name for '" + fileName + "':", fileName, ref newName)){return;}@@ -675,7 +682,7 @@ namespace _2D_wave_sim_V01try{File.Move(oldPath, newPath);- this.RefreshOutputFileLists();+ RefreshOutputFileLists();}catch (Exception ex){@@ -686,7 +693,7 @@ namespace _2D_wave_sim_V01/// <summary>Opens the selected project's output_video folder in Explorer (details view; the folder is created if missing).</summary>private void btnOpenVIdeoFolder2_Click(object sender, EventArgs e){- string folder = this.SelectedOutputProjectFolder();+ string folder = SelectedOutputProjectFolder();if (folder.Length == 0){MessageBox.Show(this, "Select a project in the list first.", "Open video folder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);@@ -694,7 +701,7 @@ namespace _2D_wave_sim_V01}try{- this.OpenFolderInExplorer(Path.Combine(folder, ProjectStore.OutputVideoFolderName), 4);+ OpenFolderInExplorer(Path.Combine(folder, ProjectStore.OutputVideoFolderName), FVM_DETAILS);}catch (Exception ex){@@ -705,13 +712,13 @@ namespace _2D_wave_sim_V01/// <summary>Copies the previewed still image into the Sources and Probes tab preview boxes.</summary>private void btnShareWithEditors_Click(object sender, EventArgs e){- this.CopyPreviewToTabs(this._outputPreviewPic);+ CopyPreviewToTabs(_outputPreviewPic);}/// <summary>Enables "Share with editors" only while the preview shows a still image (not a video thumbnail).</summary>private void UpdateShareWithEditorsButton(){- this.btnShareWithEditors.Enabled = !this._outputPreviewIsVideo && this._outputPreviewPic != null && this._outputPreviewPic.Image != null;+ btnShareWithEditors.Enabled = !_outputPreviewIsVideo && _outputPreviewPic != null && _outputPreviewPic.Image != null;}/// <summary>Shows one message box listing <paramref name="errors"/> (one per line) under <paramref name="title"/>; does nothing for an empty list.</summary>@@ -723,6 +730,15 @@ namespace _2D_wave_sim_V01}}+ // ---- the video preview thumbnail, via the Windows shell (no video codec of our own)+ //+ // Windows shell thumbnail interop (IShellItemImageFactory, declared with NativeSize and ThumbnailOptions in+ // Form1.cs) - plain P/Invoke/COM interop against shell32.dll and gdi32.dll, no NuGet package or project+ // reference needed, but genuine COM interop nonetheless, which could not be exercised on an actual Windows+ // machine while writing it. GetShellThumbnail is written so a wrong detail here surfaces as "no thumbnail+ // for this file" (via the try/catch in lstVideo_SelectedIndexChanged) rather than a crash - if the preview+ // comes out consistently missing for videos, this is the place to revisit.+/// <summary>/// shell32: creates the shell item for a file system path and returns the interface/// identified by <paramref name="riid"/>. <c>PreserveSig = false</c> turns a failing HRESULTdiff --git a/Wave_Dude_2D/Form1.Probes.cs b/Wave_Dude_2D/Form1.Probes.csindex fec1002..b046fe3 100644--- a/Wave_Dude_2D/Form1.Probes.cs+++ b/Wave_Dude_2D/Form1.Probes.cs@@ -15,19 +15,51 @@ namespace _2D_wave_sim_V01/// fed by the simulation worker, and it arrives already marshalled through <c>PostToUi</c>./// </summary>/// <remarks>+ /// <para>+ /// A probe measures the field (amplitude) or the intensity while the simulation runs and shows+ /// the result in a little graph box in the field or intensity picture: a point probe (A) plots+ /// the value at A against the simulation step; a line probe (A-B) plots the values along the+ /// line A-B (position on the line on X) at the current step, so it changes every step. The+ /// settings are kept in <c>_probes</c> and stored in the "probes" section of the project file.+ /// Each probe has its own "On" check box (<see cref="ProbeSettings.Active"/>): when off, the+ /// probe is hidden (its marker, graph box and burned-in overlay are all skipped) but it keeps+ /// being sampled, so switching it back on shows its recorded history rather than starting from+ /// a blank graph.+ /// </para>+ /// <para>+ /// There are two independent probes, Probe 1 and Probe 2, each with its own group of controls+ /// (<c>grpProbe1</c>/<c>grpProbe2</c>). <c>_probeUi</c> holds one <see cref="ProbeControlSet"/>+ /// per group, so the code that reads/writes a probe's settings and the events of its controls+ /// can be shared between the two groups instead of being written out twice.+ /// </para>+ /// <para>+ /// The Probes tab shows a copy of a simulation picture (Preview tab, "Copy Image..." buttons),+ /// shared by both probes. Each group has its own Pick button: it lets the user click in that+ /// picture for that probe's position A, for a line position B, and for the top left corner of+ /// that probe's graph box.+ /// </para>+ /// <para>/// Two coordinate systems are used throughout. Canvas pixels are 0-based cells of the/// simulation grid (size from <c>EffectiveCanvas()</c> while editing, <c>_runCanvas</c> for the/// current/last run); picture-box pixels are client coordinates of a <see cref="PictureBox"/>/// in Zoom mode, where the image is scaled uniformly and centred. <see cref="ZoomedImageRectangle"/>/// gives the image's rectangle in picture-box pixels; <see cref="TryPictureToCanvas"/> and/// <see cref="ToScreen"/> convert between the two.+ /// </para>/// </remarks>public partial class Form1{- /// <summary>The control set for probe <paramref name="index"/>, or null before <see cref="InitializeProbeControls"/> has run (designer-wired handlers can fire that early).</summary>+ /// <summary>+ /// The control set for probe <paramref name="index"/>, or null while the form is still being+ /// constructed: <c>InitializeComponent</c> (which runs before <see cref="InitializeProbeControls"/>)+ /// sets some control values away from their .NET default, such as <c>numRunningWindow</c>'s 500,+ /// and that alone fires the control's change event immediately, before <c>_probeUi</c> exists.+ /// The event handlers below go through this instead of indexing <c>_probeUi</c> directly, so+ /// that early firing is a harmless no-op instead of a <see cref="NullReferenceException"/>.+ /// </summary>private Form1.ProbeControlSet ProbeUi(int index){- return this._probeUi == null ? null : this._probeUi[index];+ return _probeUi == null ? null : _probeUi[index];}/// <summary>Creates the default probe list: <see cref="ProbeCount"/> fresh, inactive probes.</summary>@@ -41,33 +73,34 @@ namespace _2D_wave_sim_V01return probes;}- /// <summary>Pads or truncates <c>_probes</c> to exactly <see cref="ProbeCount"/> entries after loading a project (the config may hold any count).</summary>+ /// <summary>Keeps <c>_probes</c> at exactly <see cref="ProbeCount"/> entries after loading a project: pads with new (default) probes when a saved project has fewer (from before Probe 2 existed), trims extras when it somehow has more.</summary>private void NormalizeProbeCount(){- while (this._probes.Count < Form1.ProbeCount)+ while (_probes.Count < Form1.ProbeCount){- this._probes.Add(new ProbeSettings());+ _probes.Add(new ProbeSettings());}- while (this._probes.Count > Form1.ProbeCount)+ while (_probes.Count > Form1.ProbeCount){- this._probes.RemoveAt(this._probes.Count - 1);+ _probes.RemoveAt(_probes.Count - 1);}}/// <summary>- /// One-time setup from the constructor: binds the designer controls of both probe panels into- /// <c>_probeUi</c>, fills the fixed combo boxes (item order mirrors the enum order because the- /// selected index is cast straight to the enum), sets spinner ranges, hooks the paint and mouse- /// handlers of the probe and preview pictures (which must already exist) and shows the current probes.+ /// One-time setup from <c>Form1_Load</c>: binds the designer controls of both probe panels into+ /// <c>_probeUi</c>, fills the fixed combo boxes (the choices are made here, not in the designer,+ /// in the order of the <see cref="ProbeSettings"/> enumerations because the selected index is+ /// cast straight to the enum), sets spinner ranges, hooks the paint and mouse handlers of the+ /// probe and preview pictures (which must already exist) and shows the current probes./// </summary>private void InitializeProbeControls(){- this._probeUi = new Form1.ProbeControlSet[]+ _probeUi = new Form1.ProbeControlSet[]{- new Form1.ProbeControlSet(0, "Probe 1", this.chkProbeOn1, this.cmbPlaceOn, this.cmbMeasurement, this.cmbProbeType, this.cmbBoxSize, this.numAPosX, this.numAPosY, this.numBPosX, this.numBPosY, this.butPicPositions, this.radRunningScale, this.radFullScale, this.chkAutoScaleX, this.chkAutoScaleY, this.txtMinScaleY, this.txtMaxScaleY, this.chkStartAfterStep, this.txtStartAfterStep, this.numRunningWindow, new Control[] { this.numBPosX, this.numBPosY, this.Label14, this.Label15, this.Label16 }),- new Form1.ProbeControlSet(1, "Probe 2", this.chkProbeOn2, this.cmbPlaceOn2, this.cmbMeasurement2, this.cmbProbeType2, this.cmbBoxSize2, this.numAPosX2, this.numAPosY2, this.numBPosX2, this.numBPosY2, this.butPicPositions2, this.radRunningScale2, this.radFullScale2, this.chkAutoScaleX2, this.chkAutoScaleY2, this.txtMinScaleY2, this.txtMaxScaleY2, this.chkStartAfterStep2, this.txtStartAfterStep2, this.numRunningWindow2, new Control[] { this.numBPosX2, this.numBPosY2, this.Label28, this.Label27, this.Label25 })+ new Form1.ProbeControlSet(0, "Probe 1", chkProbeOn1, cmbPlaceOn, cmbMeasurement, cmbProbeType, cmbBoxSize, numAPosX, numAPosY, numBPosX, numBPosY, butPicPositions, radRunningScale, radFullScale, chkAutoScaleX, chkAutoScaleY, txtMinScaleY, txtMaxScaleY, chkStartAfterStep, txtStartAfterStep, numRunningWindow, new Control[] { numBPosX, numBPosY, Label14, Label15, Label16 }),+ new Form1.ProbeControlSet(1, "Probe 2", chkProbeOn2, cmbPlaceOn2, cmbMeasurement2, cmbProbeType2, cmbBoxSize2, numAPosX2, numAPosY2, numBPosX2, numBPosY2, butPicPositions2, radRunningScale2, radFullScale2, chkAutoScaleX2, chkAutoScaleY2, txtMinScaleY2, txtMaxScaleY2, chkStartAfterStep2, txtStartAfterStep2, numRunningWindow2, new Control[] { numBPosX2, numBPosY2, Label28, Label27, Label25 })};- foreach (Form1.ProbeControlSet ui in this._probeUi)+ foreach (Form1.ProbeControlSet ui in _probeUi){foreach (ComboBox combo in new ComboBox[] { ui.CmbPlaceOn, ui.CmbMeasurement, ui.CmbProbeType, ui.CmbBoxSize }){@@ -84,28 +117,29 @@ namespace _2D_wave_sim_V01position.DecimalPlaces = 0;position.Minimum = 0m;// Placeholder until SetProbeRanges knows the canvas size.- position.Maximum = 16383m;+ position.Maximum = (decimal)(SceneSettings.MaxCanvasSize - 1);}ui.NumRunningWindow.DecimalPlaces = 0;ui.NumRunningWindow.Minimum = 10m;ui.NumRunningWindow.Maximum = ProbeSettings.MaxRunningWindow;}- this._picField.Paint += this.PreviewPicture_Paint;- this._picIntensity.Paint += this.PreviewPicture_Paint;- this._picProbe.Paint += this.ProbePicture_Paint;- this._picProbe.MouseClick += this.ProbePicture_MouseClick;- this._picProbe.MouseMove += this.ProbePicture_MouseMove;- this._picProbe.MouseLeave += this.ProbePicture_MouseLeave;- this.ShowProbesInControls();+ // the graphs and markers are drawn over the pictures (the pictures themselves stay clean)+ _picField.Paint += PreviewPicture_Paint;+ _picIntensity.Paint += PreviewPicture_Paint;+ _picProbe.Paint += ProbePicture_Paint;+ _picProbe.MouseClick += ProbePicture_MouseClick;+ _picProbe.MouseMove += ProbePicture_MouseMove;+ _picProbe.MouseLeave += ProbePicture_MouseLeave;+ ShowProbesInControls();}/// <summary>Cancels any position pick in progress and pushes every probe in <c>_probes</c> into its controls.</summary>private void ShowProbesInControls(){- this.EndPick();- foreach (Form1.ProbeControlSet ui in this._probeUi)+ EndPick();+ foreach (Form1.ProbeControlSet ui in _probeUi){- this.ShowProbeInControls(ui);+ ShowProbeInControls(ui);}}@@ -117,15 +151,15 @@ namespace _2D_wave_sim_V01/// </summary>private void ShowProbeInControls(Form1.ProbeControlSet ui){- ProbeSettings probe = this._probes[ui.Index];+ ProbeSettings probe = _probes[ui.Index];probe.Normalize();- this._loadingProbe = true;+ _loadingProbe = true;try{- this.SetProbeRanges(ui);+ SetProbeRanges(ui);ui.ChkOn.Checked = probe.Active;ui.CmbPlaceOn.SelectedIndex = (int)probe.PlaceOn;- this.FillMeasurementCombo(ui, probe);+ FillMeasurementCombo(ui, probe);ui.CmbProbeType.SelectedIndex = (int)probe.Kind;ui.CmbBoxSize.SelectedIndex = (int)probe.BoxSize;ui.NumAPosX.Value = Form1.ClampToRange(ui.NumAPosX, probe.PosAX);@@ -144,10 +178,10 @@ namespace _2D_wave_sim_V01}finally{- this._loadingProbe = false;+ _loadingProbe = false;}- this.UpdateProbeControlState(ui);- this.InvalidateProbePictures();+ UpdateProbeControlState(ui);+ InvalidateProbePictures();}/// <summary>@@ -188,7 +222,7 @@ namespace _2D_wave_sim_V01/// </summary>private void UpdateProbeControlState(Form1.ProbeControlSet ui){- bool isLine = this._probes[ui.Index].Kind == ProbeKind.Line;+ bool isLine = _probes[ui.Index].Kind == ProbeKind.Line;foreach (Control control in ui.BOnlyControls){control.Enabled = isLine;@@ -205,29 +239,29 @@ namespace _2D_wave_sim_V01/// <summary>Applies <see cref="SetProbeRanges(Form1.ProbeControlSet)"/> to both probes; no-op before the controls are initialized.</summary>private void SetProbeRanges(){- if (this._probeUi == null)+ if (_probeUi == null){return;}- foreach (Form1.ProbeControlSet ui in this._probeUi)+ foreach (Form1.ProbeControlSet ui in _probeUi){- this.SetProbeRanges(ui);+ SetProbeRanges(ui);}}/// <summary>/// Limits the position spinners to the current canvas size (width-1 / height-1 in canvas pixels,- /// or 16383 when the size is unknown). Lowering a maximum can clamp the value and fire- /// ValueChanged, so <c>_loadingProbe</c> is raised meanwhile (and restored to its previous state,- /// since this is also called from inside <see cref="ShowProbeInControls"/>).+ /// or <see cref="SceneSettings.MaxCanvasSize"/> - 1 when the size is unknown). Lowering a maximum+ /// can clamp the value and fire ValueChanged, so <c>_loadingProbe</c> is raised meanwhile (and+ /// restored to its previous state, since this is also called from inside <see cref="ShowProbeInControls"/>)./// </summary>private void SetProbeRanges(Form1.ProbeControlSet ui){- Size canvas = this.EffectiveCanvas();- decimal maxX = new decimal((canvas.Width > 0) ? (canvas.Width - 1) : 16383);- decimal maxY = new decimal((canvas.Height > 0) ? (canvas.Height - 1) : 16383);- bool wasLoading = this._loadingProbe;- this._loadingProbe = true;+ Size canvas = EffectiveCanvas();+ decimal maxX = new decimal((canvas.Width > 0) ? (canvas.Width - 1) : (SceneSettings.MaxCanvasSize - 1));+ decimal maxY = new decimal((canvas.Height > 0) ? (canvas.Height - 1) : (SceneSettings.MaxCanvasSize - 1));+ bool wasLoading = _loadingProbe;+ _loadingProbe = true;try{ui.NumAPosX.Maximum = maxX;@@ -237,7 +271,7 @@ namespace _2D_wave_sim_V01}finally{- this._loadingProbe = wasLoading;+ _loadingProbe = wasLoading;}}@@ -249,7 +283,7 @@ namespace _2D_wave_sim_V01/// </summary>private void ReadProbeControls(Form1.ProbeControlSet ui){- ProbeSettings probe = this._probes[ui.Index];+ ProbeSettings probe = _probes[ui.Index];probe.Active = ui.ChkOn.Checked;if (ui.CmbPlaceOn.SelectedIndex >= 0){@@ -305,121 +339,121 @@ namespace _2D_wave_sim_V01/// <summary>Probe 1: a combo box (place on / measurement / type / box size) changed; see <see cref="HandleProbeComboChanged"/>.</summary>private void ProbeCombo_SelectedIndexChanged(object sender, EventArgs e){- this.HandleProbeComboChanged(this.ProbeUi(0), sender);+ HandleProbeComboChanged(ProbeUi(0), sender);}/// <summary>Probe 1: an A/B position spinner changed; the new canvas position is stored.</summary>private void ProbePosition_ValueChanged(object sender, EventArgs e){- this.HandleProbePositionChanged(this.ProbeUi(0));+ HandleProbePositionChanged(ProbeUi(0));}/// <summary>Probe 1: the "on" check box toggled the probe's active flag.</summary>private void ProbeOn_CheckedChanged(object sender, EventArgs e){- this.HandleProbeOnChanged(this.ProbeUi(0));+ HandleProbeOnChanged(ProbeUi(0));}/// <summary>Probe 1: Enter in a Y-range or start-after text box applies all controls.</summary>private void ProbeTextBox_KeyDown(object sender, KeyEventArgs e){- this.HandleProbeTextBoxKeyDown(this.ProbeUi(0), e);+ HandleProbeTextBoxKeyDown(ProbeUi(0), e);}/// <summary>Probe 1: running/full scale radio button changed.</summary>private void ProbeScaleMode_CheckedChanged(object sender, EventArgs e){- this.HandleProbeScaleModeChanged(this.ProbeUi(0));+ HandleProbeScaleModeChanged(ProbeUi(0));}/// <summary>Probe 1: auto X / auto Y check box changed.</summary>private void ProbeAutoScale_CheckedChanged(object sender, EventArgs e){- this.HandleProbeAutoScaleChanged(this.ProbeUi(0));+ HandleProbeAutoScaleChanged(ProbeUi(0));}/// <summary>Probe 1: a Y-range text box lost focus; all controls are applied.</summary>private void ProbeYRange_Validated(object sender, EventArgs e){- this.HandleProbeControlApplied(this.ProbeUi(0));+ HandleProbeControlApplied(ProbeUi(0));}/// <summary>Probe 1: the "start after step" check box toggled.</summary>private void ProbeStartAfterStep_CheckedChanged(object sender, EventArgs e){- this.HandleProbeStartAfterStepChanged(this.ProbeUi(0));+ HandleProbeStartAfterStepChanged(ProbeUi(0));}/// <summary>Probe 1: the start-after step text box lost focus; all controls are applied.</summary>private void ProbeStartAfterStep_Validated(object sender, EventArgs e){- this.HandleProbeControlApplied(this.ProbeUi(0));+ HandleProbeControlApplied(ProbeUi(0));}/// <summary>Probe 1: the running window spinner changed; all controls are applied.</summary>private void ProbeRunningWindow_ValueChanged(object sender, EventArgs e){- this.HandleProbeControlApplied(this.ProbeUi(0));+ HandleProbeControlApplied(ProbeUi(0));}/// <summary>Probe 2: a combo box changed; see <see cref="HandleProbeComboChanged"/>.</summary>private void ProbeCombo2_SelectedIndexChanged(object sender, EventArgs e){- this.HandleProbeComboChanged(this.ProbeUi(1), sender);+ HandleProbeComboChanged(ProbeUi(1), sender);}/// <summary>Probe 2: an A/B position spinner changed; the new canvas position is stored.</summary>private void ProbePosition2_ValueChanged(object sender, EventArgs e){- this.HandleProbePositionChanged(this.ProbeUi(1));+ HandleProbePositionChanged(ProbeUi(1));}/// <summary>Probe 2: the "on" check box toggled the probe's active flag.</summary>private void ProbeOn2_CheckedChanged(object sender, EventArgs e){- this.HandleProbeOnChanged(this.ProbeUi(1));+ HandleProbeOnChanged(ProbeUi(1));}/// <summary>Probe 2: Enter in a Y-range or start-after text box applies all controls.</summary>private void ProbeTextBox2_KeyDown(object sender, KeyEventArgs e){- this.HandleProbeTextBoxKeyDown(this.ProbeUi(1), e);+ HandleProbeTextBoxKeyDown(ProbeUi(1), e);}/// <summary>Probe 2: running/full scale radio button changed.</summary>private void ProbeScaleMode2_CheckedChanged(object sender, EventArgs e){- this.HandleProbeScaleModeChanged(this.ProbeUi(1));+ HandleProbeScaleModeChanged(ProbeUi(1));}/// <summary>Probe 2: auto X / auto Y check box changed.</summary>private void ProbeAutoScale2_CheckedChanged(object sender, EventArgs e){- this.HandleProbeAutoScaleChanged(this.ProbeUi(1));+ HandleProbeAutoScaleChanged(ProbeUi(1));}/// <summary>Probe 2: a Y-range text box lost focus; all controls are applied.</summary>private void ProbeYRange2_Validated(object sender, EventArgs e){- this.HandleProbeControlApplied(this.ProbeUi(1));+ HandleProbeControlApplied(ProbeUi(1));}/// <summary>Probe 2: the "start after step" check box toggled.</summary>private void ProbeStartAfterStep2_CheckedChanged(object sender, EventArgs e){- this.HandleProbeStartAfterStepChanged(this.ProbeUi(1));+ HandleProbeStartAfterStepChanged(ProbeUi(1));}/// <summary>Probe 2: the start-after step text box lost focus; all controls are applied.</summary>private void ProbeStartAfterStep2_Validated(object sender, EventArgs e){- this.HandleProbeControlApplied(this.ProbeUi(1));+ HandleProbeControlApplied(ProbeUi(1));}/// <summary>Probe 2: the running window spinner changed; all controls are applied.</summary>private void ProbeRunningWindow2_ValueChanged(object sender, EventArgs e){- this.HandleProbeControlApplied(this.ProbeUi(1));+ HandleProbeControlApplied(ProbeUi(1));}/// <summary>@@ -432,61 +466,67 @@ namespace _2D_wave_sim_V01/// <param name="sender">The combo box that raised the event.</param>private void HandleProbeComboChanged(Form1.ProbeControlSet ui, object sender){- if (ui == null || this._loadingProbe)+ if (ui == null || _loadingProbe){return;}- if (sender == ui.CmbProbeType && this._pickStep != 0 && this._pickIndex == ui.Index)+ if (sender == ui.CmbProbeType && _pickStep != 0 && _pickIndex == ui.Index){- this.EndPick();+ // the number of clicks depends on the type; only cancel a pick that belongs to this probe+ EndPick();}if (sender == ui.CmbPlaceOn && ui.CmbPlaceOn.SelectedIndex >= 0){- ProbeSettings probe = this._probes[ui.Index];+ // the measurements that are possible depend on the picture+ ProbeSettings probe = _probes[ui.Index];probe.PlaceOn = (ProbePlaceOn)ui.CmbPlaceOn.SelectedIndex;probe.Normalize();- this._loadingProbe = true;+ _loadingProbe = true;try{- this.FillMeasurementCombo(ui, probe);+ FillMeasurementCombo(ui, probe);}finally{- this._loadingProbe = false;+ _loadingProbe = false;}}- this.ReadProbeControls(ui);- this.UpdateProbeControlState(ui);- this.ProbeSettingsChanged();+ ReadProbeControls(ui);+ UpdateProbeControlState(ui);+ ProbeSettingsChanged();}/// <summary>Stores the four position spinners (canvas pixels) into the probe and marks the project dirty; ignored while loading.</summary>private void HandleProbePositionChanged(Form1.ProbeControlSet ui){- if (ui == null || this._loadingProbe)+ if (ui == null || _loadingProbe){return;}- ProbeSettings probe = this._probes[ui.Index];+ ProbeSettings probe = _probes[ui.Index];probe.PosAX = Convert.ToInt32(ui.NumAPosX.Value);probe.PosAY = Convert.ToInt32(ui.NumAPosY.Value);probe.PosBX = Convert.ToInt32(ui.NumBPosX.Value);probe.PosBY = Convert.ToInt32(ui.NumBPosY.Value);- this.ProbeSettingsChanged();+ ProbeSettingsChanged();}/// <summary>Stores the "on" check box into <see cref="ProbeSettings.Active"/> and marks the project dirty; ignored while loading.</summary>private void HandleProbeOnChanged(Form1.ProbeControlSet ui){- if (ui == null || this._loadingProbe)+ if (ui == null || _loadingProbe){return;}- this._probes[ui.Index].Active = ui.ChkOn.Checked;- this.ProbeSettingsChanged();+ _probes[ui.Index].Active = ui.ChkOn.Checked;+ ProbeSettingsChanged();}- /// <summary>On Enter (and only then): swallows the key so the text box does not beep, then applies all controls of the probe; ignored while loading.</summary>+ /// <summary>+ /// Enter in a probe text box applies the value right away (like losing focus does) instead of+ /// just beeping: the key is swallowed and all controls of the probe are applied. These are+ /// single line boxes, so Enter never inserts an actual line break. Ignored while loading.+ /// </summary>private void HandleProbeTextBoxKeyDown(Form1.ProbeControlSet ui, KeyEventArgs e){if (e.KeyCode != Keys.Return)@@ -495,23 +535,23 @@ namespace _2D_wave_sim_V01}e.SuppressKeyPress = true;e.Handled = true;- if (ui == null || this._loadingProbe)+ if (ui == null || _loadingProbe){return;}- this.ReadProbeControls(ui);- this.ProbeSettingsChanged();+ ReadProbeControls(ui);+ ProbeSettingsChanged();}/// <summary>Stores the scale mode radio buttons into the probe and marks the project dirty; ignored while loading.</summary>private void HandleProbeScaleModeChanged(Form1.ProbeControlSet ui){- if (ui == null || this._loadingProbe)+ if (ui == null || _loadingProbe){return;}- this._probes[ui.Index].ScaleMode = (ui.RadFull.Checked ? ProbeScaleMode.Full : ProbeScaleMode.Running);- this.ProbeSettingsChanged();+ _probes[ui.Index].ScaleMode = (ui.RadFull.Checked ? ProbeScaleMode.Full : ProbeScaleMode.Running);+ ProbeSettingsChanged();}/// <summary>@@ -522,18 +562,19 @@ namespace _2D_wave_sim_V01/// </summary>private void HandleProbeAutoScaleChanged(Form1.ProbeControlSet ui){- if (ui == null || this._loadingProbe)+ if (ui == null || _loadingProbe){return;}- ProbeSettings probe = this._probes[ui.Index];+ ProbeSettings probe = _probes[ui.Index];bool wasAutoY = probe.AutoScaleY;probe.AutoScaleX = ui.ChkAutoX.Checked;probe.AutoScaleY = ui.ChkAutoY.Checked;+ // switching the automatic value axis off keeps the range that is shown now, ready to fine-tune by handif (wasAutoY && !probe.AutoScaleY){- this.FreezeValueRange(ui, probe);- this._loadingProbe = true;+ FreezeValueRange(ui, probe);+ _loadingProbe = true;try{ui.TxtMinY.Text = probe.YMin.ToString("G6", CultureInfo.InvariantCulture);@@ -541,34 +582,34 @@ namespace _2D_wave_sim_V01}finally{- this._loadingProbe = false;+ _loadingProbe = false;}}- this.UpdateProbeControlState(ui);- this.ProbeSettingsChanged();+ UpdateProbeControlState(ui);+ ProbeSettingsChanged();}/// <summary>Generic "commit" used by Validated and ValueChanged events: reads all controls back and marks the project dirty; ignored while loading.</summary>private void HandleProbeControlApplied(Form1.ProbeControlSet ui){- if (ui == null || this._loadingProbe)+ if (ui == null || _loadingProbe){return;}- this.ReadProbeControls(ui);- this.ProbeSettingsChanged();+ ReadProbeControls(ui);+ ProbeSettingsChanged();}/// <summary>Stores the "start after step" check box, enables/disables its text box and marks the project dirty; ignored while loading.</summary>private void HandleProbeStartAfterStepChanged(Form1.ProbeControlSet ui){- if (ui == null || this._loadingProbe)+ if (ui == null || _loadingProbe){return;}- this._probes[ui.Index].UseStartAfterStep = ui.ChkStartAfter.Checked;- this.UpdateProbeControlState(ui);- this.ProbeSettingsChanged();+ _probes[ui.Index].UseStartAfterStep = ui.ChkStartAfter.Checked;+ UpdateProbeControlState(ui);+ ProbeSettingsChanged();}/// <summary>@@ -582,17 +623,18 @@ namespace _2D_wave_sim_V01private void FreezeValueRange(Form1.ProbeControlSet ui, ProbeSettings p){int index = ui.Index;- if (this._probeTraces.Count <= index || this._runProbes == null || this._runProbes.Count <= index)+ if (_probeTraces.Count <= index || _runProbes == null || _runProbes.Count <= index){return;}- if (this._runProbes[index].Kind != p.Kind)+ if (_runProbes[index].Kind != p.Kind){return;}- ProbeTrace trace = this._probeTraces[index];+ ProbeTrace trace = _probeTraces[index];if (p.Kind == ProbeKind.Line){+ // a line probe shows nothing at all before the start step: nothing to freezeif (p.UseStartAfterStep && trace.StepsSampled < p.StartAfterStep){return;@@ -612,7 +654,7 @@ namespace _2D_wave_sim_V01double xMax = 0.0;double yMin = 0.0;double yMax = 0.0;- ProbeGraphPainter.ComputeRanges(autoScaled, trace, this._runSteps, ref xMin, ref xMax, ref yMin, ref yMax);+ ProbeGraphPainter.ComputeRanges(autoScaled, trace, _runSteps, ref xMin, ref xMax, ref yMin, ref yMax);if (yMax > yMin){p.YMin = yMin;@@ -623,24 +665,24 @@ namespace _2D_wave_sim_V01/// <summary>Marks the project dirty (unless a loading flag is set) and repaints all three probe-related pictures.</summary>private void ProbeSettingsChanged(){- this.MarkProjectChanged();- this.InvalidateProbePictures();+ MarkProjectChanged();+ InvalidateProbePictures();}/// <summary>Invalidates the probe picture and the field/intensity previews so markers and graph boxes are redrawn; safe before the pictures exist.</summary>private void InvalidateProbePictures(){- if (this._picProbe != null)+ if (_picProbe != null){- this._picProbe.Invalidate();+ _picProbe.Invalidate();}- if (this._picField != null)+ if (_picField != null){- this._picField.Invalidate();+ _picField.Invalidate();}- if (this._picIntensity != null)+ if (_picIntensity != null){- this._picIntensity.Invalidate();+ _picIntensity.Invalidate();}}@@ -651,24 +693,24 @@ namespace _2D_wave_sim_V01/// </summary>private void ProbeTabChanged(object sender, EventArgs e){- this.EndPick();- this.SetProbeRanges();- if (this.tabMainFunctions.SelectedTab == this.tabProbeList)+ EndPick();+ SetProbeRanges();+ if (tabMainFunctions.SelectedTab == tabProbeList){- this.AutoLoadSceneImageIfEmpty(this._picProbe);+ AutoLoadSceneImageIfEmpty(_picProbe);}}/// <summary>Probe 1 "pick positions" button: starts picking in the probe picture, or cancels it when already picking.</summary>private void butPicPositions_Click(object sender, EventArgs e){- this.StartOrCancelPick(this.ProbeUi(0));+ StartOrCancelPick(ProbeUi(0));}/// <summary>Probe 2 "pick positions" button: starts picking in the probe picture, or cancels it when already picking.</summary>private void butPicPositions2_Click(object sender, EventArgs e){- this.StartOrCancelPick(this.ProbeUi(1));+ StartOrCancelPick(ProbeUi(1));}/// <summary>Toggles pick mode for one probe: cancels a pick in progress (for any probe) and, unless that pick was this probe's, starts a new one.</summary>@@ -678,28 +720,34 @@ namespace _2D_wave_sim_V01{return;}- bool wasPicking = this._pickStep != 0 && this._pickIndex == ui.Index;- this.EndPick();+ bool wasPicking = _pickStep != 0 && _pickIndex == ui.Index;+ EndPick();if (!wasPicking){- this.StartPick(ui);+ StartPick(ui);}}- /// <summary>Gives the probe picture a black bitmap of the canvas size so positions can be picked without a scene image; does nothing when the canvas size is unknown. The bitmap is owned by the picture box.</summary>+ /// <summary>+ /// When there is no picture yet to pick from (no simulation has run), makes a plain black one at+ /// the canvas size that the Configuration tab currently specifies (the scene image's size, or the+ /// user defined width/height), so a probe position can still be picked before ever running a+ /// simulation. Replaced by the real picture as soon as one is copied over from the Preview tab.+ /// Does nothing when the canvas size is unknown. The bitmap is owned by the picture box.+ /// </summary>private void EnsureProbePicture(){- Size canvas = this.EffectiveCanvas();+ Size canvas = EffectiveCanvas();if (canvas.Width <= 0 || canvas.Height <= 0){return;}- Bitmap bitmap = new Bitmap(canvas.Width, canvas.Height);- using (Graphics g = Graphics.FromImage(bitmap))+ Bitmap placeholder = new Bitmap(canvas.Width, canvas.Height);+ using (Graphics g = Graphics.FromImage(placeholder)){g.Clear(Color.Black);}- this._picProbe.Image = bitmap;+ _picProbe.Image = placeholder;}/// <summary>@@ -710,40 +758,40 @@ namespace _2D_wave_sim_V01/// </summary>private void StartPick(Form1.ProbeControlSet ui){- if (this._picProbe.Image == null)+ if (_picProbe.Image == null){- this.EnsureProbePicture();+ EnsureProbePicture();}- if (this._picProbe.Image == null)+ if (_picProbe.Image == null){MessageBox.Show(this, "There is no picture to pick from yet, and the canvas size is not known either\r\n(choose a scene image, or a user defined width and height, on the Configuration tab first).", "Probe positions", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- this._pickIndex = ui.Index;- this._pickStep = 1;- this._pickHover = null;- this._picProbe.Cursor = Cursors.Cross;+ _pickIndex = ui.Index;+ _pickStep = 1;+ _pickHover = null;+ _picProbe.Cursor = Cursors.Cross;ui.ButPick.Text = "Cancel";- this.ShowPickInstruction();+ ShowPickInstruction();}/// <summary>Writes the status-bar instruction for the current pick step (1: position A / the point, 2: position B, 3: top-left corner of the graph box).</summary>private void ShowPickInstruction(){- Form1.ProbeControlSet ui = this._probeUi[this._pickIndex];- switch (this._pickStep)+ Form1.ProbeControlSet ui = _probeUi[_pickIndex];+ switch (_pickStep){case 1:- this.ToolStripStatusLabel1.Text = ((this._probes[this._pickIndex].Kind == ProbeKind.Line) ? (ui.Title + ": click in the picture for position A, the start of the line (press Cancel to stop picking).") : (ui.Title + ": click in the picture for the position of the probe (press Cancel to stop picking)."));+ ToolStripStatusLabel1.Text = ((_probes[_pickIndex].Kind == ProbeKind.Line) ? (ui.Title + ": click in the picture for position A, the start of the line (press Cancel to stop picking).") : (ui.Title + ": click in the picture for the position of the probe (press Cancel to stop picking)."));break;case 2:- this.ToolStripStatusLabel1.Text = ui.Title + ": click in the picture for position B, the end of the line.";+ ToolStripStatusLabel1.Text = ui.Title + ": click in the picture for position B, the end of the line.";break;case 3:- this.ToolStripStatusLabel1.Text = ui.Title + ": click in the picture for the top left corner of the graph box.";+ ToolStripStatusLabel1.Text = ui.Title + ": click in the picture for the top left corner of the graph box.";break;default:- this.ToolStripStatusLabel1.Text = "";+ ToolStripStatusLabel1.Text = "";break;}}@@ -751,21 +799,21 @@ namespace _2D_wave_sim_V01/// <summary>Leaves pick mode: restores the pick button text, clears step and hover, resets the cursor, repaints, and clears the status bar if a pick was active. Safe to call when nothing is being picked or before the probe picture exists.</summary>private void EndPick(){- bool wasPicking = this._pickStep != 0;+ bool wasPicking = _pickStep != 0;if (wasPicking){- this._probeUi[this._pickIndex].ButPick.Text = this._probeUi[this._pickIndex].PickButtonText;+ _probeUi[_pickIndex].ButPick.Text = _probeUi[_pickIndex].PickButtonText;}- this._pickStep = 0;- this._pickHover = null;- if (this._picProbe != null)+ _pickStep = 0;+ _pickHover = null;+ if (_picProbe != null){- this._picProbe.Cursor = Cursors.Default;- this._picProbe.Invalidate();+ _picProbe.Cursor = Cursors.Default;+ _picProbe.Invalidate();}if (wasPicking){- this.ToolStripStatusLabel1.Text = "";+ ToolStripStatusLabel1.Text = "";}}@@ -777,58 +825,58 @@ namespace _2D_wave_sim_V01/// </summary>private void ProbePicture_MouseClick(object sender, MouseEventArgs e){- if (this._pickStep == 0 || e.Button != MouseButtons.Left)+ if (_pickStep == 0 || e.Button != MouseButtons.Left){return;}- Form1.ProbeControlSet ui = this._probeUi[this._pickIndex];+ Form1.ProbeControlSet ui = _probeUi[_pickIndex];int x = 0;int y = 0;- if (!this.TryPictureToCanvas(this._picProbe, e.Location, ref x, ref y))+ if (!TryPictureToCanvas(_picProbe, e.Location, ref x, ref y)){return;}- switch (this._pickStep)+ switch (_pickStep){case 1:ui.NumAPosX.Value = Form1.ClampToRange(ui.NumAPosX, x);ui.NumAPosY.Value = Form1.ClampToRange(ui.NumAPosY, y);- this._pickStep = ((this._probes[this._pickIndex].Kind == ProbeKind.Line) ? 2 : 3);- this.ShowPickInstruction();+ _pickStep = ((_probes[_pickIndex].Kind == ProbeKind.Line) ? 2 : 3);+ ShowPickInstruction();break;case 2:ui.NumBPosX.Value = Form1.ClampToRange(ui.NumBPosX, x);ui.NumBPosY.Value = Form1.ClampToRange(ui.NumBPosY, y);- this._pickStep = 3;- this.ShowPickInstruction();+ _pickStep = 3;+ ShowPickInstruction();break;default:- this._probes[this._pickIndex].BoxX = x;- this._probes[this._pickIndex].BoxY = y;- this.ProbeSettingsChanged();- this.EndPick();+ _probes[_pickIndex].BoxX = x;+ _probes[_pickIndex].BoxY = y;+ ProbeSettingsChanged();+ EndPick();break;}- this._picProbe.Invalidate();+ _picProbe.Invalidate();}/// <summary>During step 3 (graph box placement) remembers the mouse position in picture-box pixels so <see cref="ProbePicture_Paint"/> can preview the box there.</summary>private void ProbePicture_MouseMove(object sender, MouseEventArgs e){- if (this._pickStep == 3)+ if (_pickStep == 3){- this._pickHover = new Point?(e.Location);- this._picProbe.Invalidate();+ _pickHover = new Point?(e.Location);+ _picProbe.Invalidate();}}/// <summary>Drops the box preview position when the mouse leaves the probe picture.</summary>private void ProbePicture_MouseLeave(object sender, EventArgs e){- if (this._pickHover != null)+ if (_pickHover != null){- this._pickHover = null;- this._picProbe.Invalidate();+ _pickHover = null;+ _picProbe.Invalidate();}}@@ -849,7 +897,7 @@ namespace _2D_wave_sim_V01{return false;}- Size canvas = this.EffectiveCanvas();+ Size canvas = EffectiveCanvas();if (canvas.Width <= 0){canvas = box.Image.Size;@@ -902,24 +950,25 @@ namespace _2D_wave_sim_V01private void PreviewPicture_Paint(object sender, PaintEventArgs e){PictureBox picture = (PictureBox)sender;- if (picture.Image == null || this._runProbes == null || this._runCanvas.Width <= 0)+ if (picture.Image == null || _runProbes == null || _runCanvas.Width <= 0){return;}- ProbePlaceOn placeOn = ((picture == this._picField) ? ProbePlaceOn.Field : ProbePlaceOn.Intensity);+ ProbePlaceOn placeOn = ((picture == _picField) ? ProbePlaceOn.Field : ProbePlaceOn.Intensity);RectangleF area = Form1.ZoomedImageRectangle(picture);if (area.Width <= 0f){return;}- float sx = area.Width / this._runCanvas.Width;- float sy = area.Height / this._runCanvas.Height;- for (int i = 0; i < this._runProbes.Count; i++)+ float sx = area.Width / _runCanvas.Width;+ float sy = area.Height / _runCanvas.Height;+ for (int i = 0; i < _runProbes.Count; i++){- ProbeSettings probe = this._runProbes[i].Clone();- if (i < this._probes.Count)+ // what is measured comes from the run; how the graph looks can be changed while it runs+ ProbeSettings probe = _runProbes[i].Clone();+ if (i < _probes.Count){- probe.CopyDisplayFrom(this._probes[i]);+ probe.CopyDisplayFrom(_probes[i]);}if (probe.PlaceOn != placeOn || !probe.Active){@@ -927,76 +976,79 @@ namespace _2D_wave_sim_V01}ProbeGraphPainter.DrawMarkers(e.Graphics, probe, i, area.X, area.Y, sx, sy);ProbeTrace trace = null;- if (i < this._probeTraces.Count)+ if (i < _probeTraces.Count){- trace = this._probeTraces[i];+ trace = _probeTraces[i];}- Rectangle box = Form1.ToScreen(ProbeGraphPainter.BoxInCanvas(probe, this._runCanvas.Width, this._runCanvas.Height), area, sx, sy);- ProbeGraphPainter.DrawGraph(e.Graphics, box, probe.Title(i), probe, trace, this._runSteps);+ Rectangle rect = Form1.ToScreen(ProbeGraphPainter.BoxInCanvas(probe, _runCanvas.Width, _runCanvas.Height), area, sx, sy);+ ProbeGraphPainter.DrawGraph(e.Graphics, rect, probe.Title(i), probe, trace, _runSteps);}}/// <summary>/// Paint overlay for the probe picture on the Probes tab (scaled by <c>EffectiveCanvas()</c>,- /// falling back to the image size): for every active probe, and for the probe currently being- /// picked even if inactive, draws the position markers and a translucent dashed yellow placeholder- /// where the graph box will be, labelled with the probe title. During pick step 3 the placeholder- /// follows the hovered mouse position instead of the stored box position.+ /// falling back to the image size): the markers of both probes, and the graph box outline of+ /// whichever one is being edited or positioned, as a translucent dashed yellow placeholder+ /// labelled with the probe title. A switched off probe ("On" unchecked) is hidden here too; the+ /// only exception is while the user is actively picking its position or graph box, so they can+ /// still see what they are placing. During pick step 3 the placeholder follows the hovered mouse+ /// position instead of the stored box position./// </summary>private void ProbePicture_Paint(object sender, PaintEventArgs e){- if (this._picProbe.Image == null)+ if (_picProbe.Image == null){return;}- Size canvas = this.EffectiveCanvas();+ Size canvas = EffectiveCanvas();if (canvas.Width <= 0){- canvas = this._picProbe.Image.Size;+ canvas = _picProbe.Image.Size;}- RectangleF area = Form1.ZoomedImageRectangle(this._picProbe);+ RectangleF area = Form1.ZoomedImageRectangle(_picProbe);if (area.Width <= 0f){return;}float sx = area.Width / canvas.Width;float sy = area.Height / canvas.Height;- for (int i = 0; i < this._probes.Count; i++)+ for (int i = 0; i < _probes.Count; i++){- ProbeSettings probe = this._probes[i];- bool picking = this._pickStep != 0 && this._pickIndex == i;+ ProbeSettings probe = _probes[i];+ bool picking = _pickStep != 0 && _pickIndex == i;if (!probe.Active && !picking){continue;}ProbeGraphPainter.DrawMarkers(e.Graphics, probe, i, area.X, area.Y, sx, sy);+ // while the corner of this probe's box is being picked, the box follows the mouseProbeSettings shown = probe;- if (this._pickStep == 3 && this._pickIndex == i && this._pickHover != null)+ if (_pickStep == 3 && _pickIndex == i && _pickHover != null){int hoverX = 0;int hoverY = 0;- if (this.TryPictureToCanvas(this._picProbe, this._pickHover.Value, ref hoverX, ref hoverY))+ if (TryPictureToCanvas(_picProbe, _pickHover.Value, ref hoverX, ref hoverY)){shown = probe.Clone();shown.BoxX = hoverX;shown.BoxY = hoverY;}}- Rectangle box = Form1.ToScreen(ProbeGraphPainter.BoxInCanvas(shown, canvas.Width, canvas.Height), area, sx, sy);+ Rectangle rect = Form1.ToScreen(ProbeGraphPainter.BoxInCanvas(shown, canvas.Width, canvas.Height), area, sx, sy);using (SolidBrush fill = new SolidBrush(Color.FromArgb(40, 255, 208, 64))){- e.Graphics.FillRectangle(fill, box);+ e.Graphics.FillRectangle(fill, rect);}using (Pen outline = new Pen(Color.FromArgb(230, 255, 208, 64), 1.5f)){outline.DashStyle = DashStyle.Dash;- e.Graphics.DrawRectangle(outline, box);+ e.Graphics.DrawRectangle(outline, rect);}using (Font font = new Font("Segoe UI", 12f, FontStyle.Bold, GraphicsUnit.Pixel)){using (SolidBrush textBrush = new SolidBrush(Color.FromArgb(240, 255, 208, 64))){- e.Graphics.DrawString(probe.Title(i), font, textBrush, box.X + 4, box.Y + 3);+ e.Graphics.DrawString(probe.Title(i), font, textBrush, rect.X + 4, rect.Y + 3);}}}@@ -1005,31 +1057,31 @@ namespace _2D_wave_sim_V01/// <summary>Replaces <c>_probes</c> with the list from the current project's config (padded/truncated to <see cref="ProbeCount"/>) and shows it; no-op without a project.</summary>private void LoadProbesFromProject(){- if (this._project == null)+ if (_project == null){return;}- this._probes = ProbeSettings.ListFromConfig(this._project.Config);- this.NormalizeProbeCount();- this.ShowProbesInControls();+ _probes = ProbeSettings.ListFromConfig(_project.Config);+ NormalizeProbeCount();+ ShowProbesInControls();}/// <summary>Replaces <c>_probes</c> with defaults (new project) and shows them.</summary>private void ResetProbes(){- this._probes = Form1.NewProbeList();- this.ShowProbesInControls();+ _probes = Form1.NewProbeList();+ ShowProbesInControls();}/// <summary>Commits every control to <c>_probes</c> and returns independent copies for the <c>SimulationJob</c>, so the worker thread never reads the instances the user keeps editing.</summary>private List<ProbeSettings> ProbesForRun(){- foreach (Form1.ProbeControlSet ui in this._probeUi)+ foreach (Form1.ProbeControlSet ui in _probeUi){- this.ReadProbeControls(ui);+ ReadProbeControls(ui);}List<ProbeSettings> copies = new List<ProbeSettings>();- foreach (ProbeSettings probe in this._probes)+ foreach (ProbeSettings probe in _probes){copies.Add(probe.Clone());}@@ -1046,18 +1098,18 @@ namespace _2D_wave_sim_V01/// <param name="steps">Total steps of the run, used for the full-scale X axis.</param>private void BeginProbeRun(List<ProbeSettings> probes, Size canvas, int steps){- this._runProbes = probes;- this._runCanvas = canvas;- this._runSteps = steps;- this._probeTraces.Clear();+ _runProbes = probes;+ _runCanvas = canvas;+ _runSteps = steps;+ _probeTraces.Clear();if (probes != null){for (int i = 0; i < probes.Count; i++){- this._probeTraces.Add(new ProbeTrace());+ _probeTraces.Add(new ProbeTrace());}}- this.InvalidateProbePictures();+ InvalidateProbePictures();}/// <summary>@@ -1069,27 +1121,27 @@ namespace _2D_wave_sim_V01/// </summary>private void ShowProbeSamples(SimulationRunner runner, ProbeUpdate update){- if (runner != this._runner || base.IsDisposed)+ if (runner != _runner || base.IsDisposed){return;}- int count = Math.Min(update.Samples.Length, this._probeTraces.Count);+ int count = Math.Min(update.Samples.Length, _probeTraces.Count);for (int i = 0; i < count; i++){- this._probeTraces[i].Series.Add(update.Samples[i]);+ _probeTraces[i].Series.Add(update.Samples[i]);if (update.Profiles[i] != null){- this._probeTraces[i].SetProfile(update.Profiles[i], update.Lengths[i]);+ _probeTraces[i].SetProfile(update.Profiles[i], update.Lengths[i]);}- this._probeTraces[i].StepsSampled = update.StepsDone;+ _probeTraces[i].StepsSampled = update.StepsDone;}- if (this._picField != null)+ if (_picField != null){- this._picField.Invalidate();+ _picField.Invalidate();}- if (this._picIntensity != null)+ if (_picIntensity != null){- this._picIntensity.Invalidate();+ _picIntensity.Invalidate();}}}diff --git a/Wave_Dude_2D/Form1.Projects.cs b/Wave_Dude_2D/Form1.Projects.csindex 513292b..460ccbc 100644--- a/Wave_Dude_2D/Form1.Projects.cs+++ b/Wave_Dude_2D/Form1.Projects.cs@@ -7,9 +7,15 @@ using System.Windows.Forms;namespace _2D_wave_sim_V01{/// <summary>- /// Projects tab: the sortable list of every project folder found under the configured project- /// root (<see cref="AppSettings.ProjectRoot"/>) and the new/load/delete/rename commands that act- /// on the selected entry. The list-building helpers here (<see cref="BuildProjectEntries"/>,+ /// Projects tab: <c>lstAllProjects</c>, the sortable list of every project folder found directly inside+ /// the configured project root (File > Choose project root, <see cref="AppSettings.ProjectRoot"/>) -+ /// a quick way to switch projects without browsing to their folder every time - and the+ /// new/load/delete/rename commands that act on the selected entry. Two columns, <c>colProjectName</c>+ /// and <c>colLastEdit</c> ("last edited" = the last write time of that project's configuration.json).+ /// Clicking either header sorts by it (<see cref="lstAllProjects_ColumnClick"/>), toggling direction on+ /// a repeat click of the same header - the usual Explorer/Excel convention. Each row's <c>Tag</c> holds+ /// a <see cref="ProjectListEntry"/> so the raw name and date stay available without re-parsing the+ /// displayed text. The list-building helpers here (<see cref="BuildProjectEntries"/>,/// <see cref="SortProjectEntries"/>, <see cref="PopulateProjectListView"/>,/// <see cref="SelectedProjectName"/>, <see cref="SelectProjectInList"/>) are shared with the/// second project list on the Outputs tab (<c>Form1.Output.cs</c>). Everything here runs on@@ -26,9 +32,9 @@ namespace _2D_wave_sim_V01private List<Form1.ProjectListEntry> BuildProjectEntries(){List<Form1.ProjectListEntry> entries = new List<Form1.ProjectListEntry>();- foreach (string name in ProjectStore.ListProjects(this._settings.ProjectRoot))+ foreach (string name in ProjectStore.ListProjects(_settings.ProjectRoot)){- string folder = ProjectStore.FolderPathFor(this._settings.ProjectRoot, name);+ string folder = ProjectStore.FolderPathFor(_settings.ProjectRoot, name);string configPath = Path.Combine(folder, ProjectConfig.FileName);DateTime lastModified = File.Exists(configPath) ? File.GetLastWriteTime(configPath) : Directory.GetLastWriteTime(folder);entries.Add(new Form1.ProjectListEntry(name, lastModified));@@ -121,67 +127,70 @@ namespace _2D_wave_sim_V01/// </summary>private void RefreshProjectList(){- string selectedName = this.SelectedProjectName(this.lstAllProjects);- List<Form1.ProjectListEntry> entries = this.BuildProjectEntries();- this.SortProjectEntries(entries, this._projectSortColumn, this._projectSortAscending);- this.PopulateProjectListView(this.lstAllProjects, entries);- this.UpdateProjectListSortHeaders();- this.SelectProjectInList(this.lstAllProjects, selectedName);- this.UpdateProjectListButtons();+ string selectedName = SelectedProjectName(lstAllProjects);+ List<Form1.ProjectListEntry> entries = BuildProjectEntries();+ SortProjectEntries(entries, _projectSortColumn, _projectSortAscending);+ PopulateProjectListView(lstAllProjects, entries);+ UpdateProjectListSortHeaders();+ SelectProjectInList(lstAllProjects, selectedName);+ UpdateProjectListButtons();}/// <summary>Clicking a column header sorts the project list by it; clicking the current sort column again flips the direction.</summary>private void lstAllProjects_ColumnClick(object sender, ColumnClickEventArgs e){- if (e.Column == this._projectSortColumn)+ if (e.Column == _projectSortColumn){- this._projectSortAscending = !this._projectSortAscending;+ _projectSortAscending = !_projectSortAscending;}else{- this._projectSortColumn = e.Column;- this._projectSortAscending = true;+ _projectSortColumn = e.Column;+ _projectSortAscending = true;}- this.RefreshProjectList();+ RefreshProjectList();}/// <summary>Appends " ^" (ascending) or " v" (descending) to the header text of the column the project list is sorted by.</summary>private void UpdateProjectListSortHeaders(){- string arrow = this._projectSortAscending ? " ^" : " v";- this.colProjectName.Text = "Project name" + ((this._projectSortColumn == 0) ? arrow : "");- this.colLastEdit.Text = "Last edited" + ((this._projectSortColumn == 1) ? arrow : "");+ string arrow = _projectSortAscending ? " ^" : " v";+ colProjectName.Text = "Project name" + ((_projectSortColumn == 0) ? arrow : "");+ colLastEdit.Text = "Last edited" + ((_projectSortColumn == 1) ? arrow : "");}/// <summary>Enables "New" only when a project root is configured, and Load/Delete/Rename only when a project is selected.</summary>private void UpdateProjectListButtons(){- bool hasSelection = this.lstAllProjects.SelectedItems.Count > 0;- this.btnNewProject.Enabled = this._settings != null && this._settings.ProjectRoot.Length > 0;- this.btnLoadProject.Enabled = hasSelection;- this.btnDeleteProject.Enabled = hasSelection;- this.btnRenameProject.Enabled = hasSelection;+ bool hasSelection = lstAllProjects.SelectedItems.Count > 0;+ btnNewProject.Enabled = _settings != null && _settings.ProjectRoot.Length > 0;+ btnLoadProject.Enabled = hasSelection;+ btnDeleteProject.Enabled = hasSelection;+ btnRenameProject.Enabled = hasSelection;}/// <summary>/// Creates a new project (wired to both the "New project" button and File > New): offers/// to save the open project, then asks for a name until it is valid and unused or the prompt- /// is cancelled. On success the editor is reset to defaults, those defaults are written into- /// the new project's configuration.json, and the project becomes the current one.+ /// is cancelled (never overwrites an existing project: a name already used there is refused and+ /// the dialog reopens). On success the editor is reset to defaults, those defaults are written into+ /// the new project's configuration.json, and the project becomes the current one. There is no such+ /// thing as a "new project" until it has actually been named and created here, so File > New no+ /// longer leaves an unnamed, un-saved project open for editing./// </summary>private void btnNewProject2_Click(object sender, EventArgs e){- if (this._settings.ProjectRoot.Length == 0)+ if (_settings.ProjectRoot.Length == 0){MessageBox.Show(this, "Choose a project root folder first (File > Choose project root).", "New project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- if (!this.ConfirmSaveProject())+ if (!ConfirmSaveProject()){return;}string name = "";- while (this.PromptForText("New project", "Name for the new project:", name, ref name))+ while (PromptForText("New project", "Name for the new project:", name, ref name)){name = name.Trim();string error = ProjectStore.ValidateName(name);@@ -190,22 +199,28 @@ namespace _2D_wave_sim_V01MessageBox.Show(this, error, "New project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);continue;}- if (ProjectStore.IsProjectFolder(ProjectStore.FolderPathFor(this._settings.ProjectRoot, name)))+ if (ProjectStore.IsProjectFolder(ProjectStore.FolderPathFor(_settings.ProjectRoot, name))){MessageBox.Show(this, "A project named '" + name + "' already exists in this root folder. Choose a different name.", "New project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);continue;}try{- Project project = ProjectStore.Create(this._settings.ProjectRoot, name);- this.StartNewProject();- this._scene.ToConfig(project.Config);- this._simulation.ToConfig(project.Config);- ProbeSettings.ListToConfig(this._probes, project.Config);- SourceSettings.ListToConfig(this._sources, project.Config);+ Project project = ProjectStore.Create(_settings.ProjectRoot, name);+ StartNewProject();+ // Write the just-computed defaults (StartNewProject read numSimulationSteps/numTimeDecayFactor+ // etc. from their Designer values) into the new project's configuration.json before+ // SetCurrentProject reads it back - otherwise, since a freshly created project has no "steps" or+ // "time_decay_factor" key yet, FromConfig would fall back to its own hardcoded legacy-compatibility+ // defaults (for an older project saved before these settings existed) instead, silently discarding+ // the Designer values StartNewProject just set.+ _scene.ToConfig(project.Config);+ _simulation.ToConfig(project.Config);+ ProbeSettings.ListToConfig(_probes, project.Config);+ SourceSettings.ListToConfig(_sources, project.Config);project.Save();- this.SetCurrentProject(project);- this.ToolStripStatusLabel1.Text = "Project '" + name + "' created.";+ SetCurrentProject(project);+ ToolStripStatusLabel1.Text = "Project '" + name + "' created.";break;}catch (Exception ex)@@ -218,20 +233,20 @@ namespace _2D_wave_sim_V01/// <summary>Changing the selection updates which project buttons are enabled.</summary>private void lstAllProjects_SelectedIndexChanged(object sender, EventArgs e){- this.UpdateProjectListButtons();+ UpdateProjectListButtons();}/// <summary>Double-clicking a project loads it, exactly like the Load button.</summary>private void lstAllProjects_DoubleClick(object sender, EventArgs e){- this.btnLoadProject_Click(sender, e);+ btnLoadProject_Click(sender, e);}/// <summary>Full folder path of the project selected in the Projects-tab list, or "" when none is selected.</summary>private string SelectedProjectFolder(){- string name = this.SelectedProjectName(this.lstAllProjects);- return (name.Length == 0) ? "" : ProjectStore.FolderPathFor(this._settings.ProjectRoot, name);+ string name = SelectedProjectName(lstAllProjects);+ return (name.Length == 0) ? "" : ProjectStore.FolderPathFor(_settings.ProjectRoot, name);}/// <summary>@@ -241,22 +256,22 @@ namespace _2D_wave_sim_V01/// </summary>private bool IsOpenProjectRunning(string folder){- return this._project != null && this._runner != null && string.Equals(this._project.FolderPath, folder, StringComparison.OrdinalIgnoreCase);+ return _project != null && _runner != null && string.Equals(_project.FolderPath, folder, StringComparison.OrdinalIgnoreCase);}/// <summary>Loads the selected project into the editor after offering to save unsaved changes; read errors are shown in a message box.</summary>private void btnLoadProject_Click(object sender, EventArgs e){- string folder = this.SelectedProjectFolder();+ string folder = SelectedProjectFolder();if (folder.Length == 0){return;}try{- if (this.ConfirmSaveProject())+ if (ConfirmSaveProject()){- this.SetCurrentProject(ProjectStore.Open(folder));+ SetCurrentProject(ProjectStore.Open(folder));}}catch (Exception ex)@@ -273,18 +288,20 @@ namespace _2D_wave_sim_V01/// </summary>private void btnDeleteProject_Click(object sender, EventArgs e){- string name = this.SelectedProjectName(this.lstAllProjects);- string folder = this.SelectedProjectFolder();+ string name = SelectedProjectName(lstAllProjects);+ string folder = SelectedProjectFolder();if (folder.Length == 0){return;}- if (this.IsOpenProjectRunning(folder))+ if (IsOpenProjectRunning(folder)){MessageBox.Show(this, "A simulation is running for this project. Stop it first.", "Delete project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}string question = "Permanently delete the project '" + name + "' and everything in its folder?\r\n\r\n" + folder;+ // the assets folder is where the user keeps their own third-party files (e.g. a Photoshop source file) -+ // point this out explicitly, since deleting the project deletes those too, and they have no other copy hereint assetCount = Form1.CountFilesIn(Path.Combine(folder, ProjectStore.AssetsFolderName));if (assetCount > 0){@@ -294,7 +311,7 @@ namespace _2D_wave_sim_V01{return;}- bool deletesOpenProject = this._project != null && string.Equals(this._project.FolderPath, folder, StringComparison.OrdinalIgnoreCase);+ bool deletesOpenProject = _project != null && string.Equals(_project.FolderPath, folder, StringComparison.OrdinalIgnoreCase);try{ProjectStore.Delete(folder);@@ -302,16 +319,16 @@ namespace _2D_wave_sim_V01catch (Exception ex){MessageBox.Show(this, "The project could not be deleted:\r\n\r\n" + ex.Message, "Delete project", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);- this.RefreshProjectList();+ RefreshProjectList();return;}if (deletesOpenProject){- this.StartNewProject();- this.UpdateProjectAccess();+ StartNewProject();+ UpdateProjectAccess();}- this.RefreshProjectList();- this.ToolStripStatusLabel1.Text = "Project '" + name + "' deleted.";+ RefreshProjectList();+ ToolStripStatusLabel1.Text = "Project '" + name + "' deleted.";}/// <summary>Number of files anywhere below <paramref name="folderPath"/>; 0 when the folder is missing or unreadable.</summary>@@ -337,25 +354,26 @@ namespace _2D_wave_sim_V01/// unchanged name is a no-op./// </summary>/// <remarks>- /// When the renamed project is the open one it is re-opened from the new folder so that all- /// project-relative paths stay valid. That re-reads configuration.json, so unsaved edits to- /// the open project are discarded without asking.+ /// When the renamed project is the open one it is re-opened from the new folder so the editor and the+ /// title bar stay in sync and all project-relative paths stay valid (a project's name is always just+ /// its folder name - see <see cref="Project.Name"/>). That re-reads configuration.json, so unsaved+ /// edits to the open project are discarded without asking./// </remarks>private void btnRenameProject_Click(object sender, EventArgs e){- string oldName = this.SelectedProjectName(this.lstAllProjects);- string folder = this.SelectedProjectFolder();+ string oldName = SelectedProjectName(lstAllProjects);+ string folder = SelectedProjectFolder();if (folder.Length == 0){return;}- if (this.IsOpenProjectRunning(folder))+ if (IsOpenProjectRunning(folder)){MessageBox.Show(this, "A simulation is running for this project. Stop it first.", "Rename project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}string newName = oldName;- if (!this.PromptForText("Rename project", "New name for '" + oldName + "':", oldName, ref newName))+ if (!PromptForText("Rename project", "New name for '" + oldName + "':", oldName, ref newName)){return;}@@ -364,17 +382,17 @@ namespace _2D_wave_sim_V01{return;}- bool renamesOpenProject = this._project != null && string.Equals(this._project.FolderPath, folder, StringComparison.OrdinalIgnoreCase);+ bool renamesOpenProject = _project != null && string.Equals(_project.FolderPath, folder, StringComparison.OrdinalIgnoreCase);try{string newFolder = ProjectStore.Rename(folder, newName);if (renamesOpenProject){- this.SetCurrentProject(ProjectStore.Open(newFolder));+ SetCurrentProject(ProjectStore.Open(newFolder));}- this.RefreshProjectList();- this.SelectProjectInList(this.lstAllProjects, newName);- this.ToolStripStatusLabel1.Text = "Project '" + oldName + "' renamed to '" + newName + "'.";+ RefreshProjectList();+ SelectProjectInList(lstAllProjects, newName);+ ToolStripStatusLabel1.Text = "Project '" + oldName + "' renamed to '" + newName + "'.";}catch (Exception ex){diff --git a/Wave_Dude_2D/Form1.Scene.cs b/Wave_Dude_2D/Form1.Scene.csindex ca8e891..e88ac05 100644--- a/Wave_Dude_2D/Form1.Scene.cs+++ b/Wave_Dude_2D/Form1.Scene.cs@@ -21,21 +21,28 @@ namespace _2D_wave_sim_V01{/// <summary>/// Applies the Scene tab control settings that are not in the designer (preview zoom mode,- /// label ellipsis, text lengths, image-source scale range). Called once from the constructor.+ /// label ellipsis, text lengths, image-source scale range). Called once from <c>Form1_Load</c>./// </summary>private void InitializeSceneControls(){- this.picImagePreview.BorderStyle = BorderStyle.FixedSingle;- this.picImagePreview.BackColor = SystemColors.ControlLight;- this.picImagePreview.SizeMode = PictureBoxSizeMode.Zoom;- this.lblImageNameAndSize.AutoSize = false;- this.lblImageNameAndSize.AutoEllipsis = true;- this.lblImageNameAndSize.Size = new Size(470, 20);- this.txtXSize.MaxLength = 5;- this.txtYsize.MaxLength = 5;- this.txtDampingEdgeSize.MaxLength = 4;- this.numScaleImageSource.Minimum = 0m;- this.numScaleImageSource.Maximum = 1000m;+ picImagePreview.BorderStyle = BorderStyle.FixedSingle;+ picImagePreview.BackColor = SystemColors.ControlLight;+ picImagePreview.SizeMode = PictureBoxSizeMode.Zoom;+ lblImageNameAndSize.AutoSize = false;+ lblImageNameAndSize.AutoEllipsis = true;+ lblImageNameAndSize.Size = new Size(470, 20);+ txtXSize.MaxLength = 5;+ txtYsize.MaxLength = 5;+ txtDampingEdgeSize.MaxLength = 4;+ // amplitude factor of the sources in the scene image+ numScaleImageSource.Minimum = 0m;+ numScaleImageSource.Maximum = (decimal)SceneSettings.MaxImageSourceScale;++ // No ShowSceneInControls() here: grpSceneProperties is disabled until a real project exists+ // (UpdateProjectAccess). Populating it now from a blank _scene would overwrite whatever defaults the+ // Designer gave these controls before StartNewProject/SetCurrentProject ever get a chance to read them+ // back out (see the matching comment in InitializeSimulationControls, where this actually matters -+ // numSimulationSteps' Designer default of 3000).}/// <summary>@@ -45,27 +52,28 @@ namespace _2D_wave_sim_V01/// </summary>private void LoadSceneFromProject(){- if (this._project == null)+ if (_project == null){return;}- this._scene = SceneSettings.FromConfig(this._project.Config);- this.ReplaceSceneImage(null);- if (this._scene.ImageFile.Length > 0)+ _scene = SceneSettings.FromConfig(_project.Config);+ ReplaceSceneImage(null);+ if (_scene.ImageFile.Length > 0){- string imagePath = SceneSettings.ToFullPath(this._project.FolderPath, this._scene.ImageFile);+ string imagePath = SceneSettings.ToFullPath(_project.FolderPath, _scene.ImageFile);if (File.Exists(imagePath)){try{- this.ReplaceSceneImage(Form1.LoadImageCopy(imagePath));+ ReplaceSceneImage(Form1.LoadImageCopy(imagePath));}catch (Exception){+ // the image label tells that the image could not be loaded (UpdateImageLabel)}}}- this.ShowSceneInControls();+ ShowSceneInControls();}/// <summary>@@ -75,47 +83,47 @@ namespace _2D_wave_sim_V01/// </summary>private void ShowSceneInControls(){- this._loadingScene = true;+ _loadingScene = true;try{- this.radUseSceneImage.Checked = this._scene.UseImage;- this.radUserDefinedScene.Checked = !this._scene.UseImage;- this.txtXSize.Text = this._scene.UserWidth.ToString(CultureInfo.InvariantCulture);- this.txtYsize.Text = this._scene.UserHeight.ToString(CultureInfo.InvariantCulture);- this.chkDampingEdge.Checked = this._scene.DampingEdgeEnabled;- this.txtDampingEdgeSize.Text = this._scene.DampingEdgeSize.ToString(CultureInfo.InvariantCulture);- this.chkUseImageSources.Checked = this._scene.UseSources;- this.numScaleImageSource.Value = Form1.ClampToRange(this.numScaleImageSource, this._scene.ImageSourceScale);- this.chkUseObjectSources.Checked = this._scene.UseObjectSources;- this.numRefractiveIndex.Value = Form1.ClampToRange(this.numRefractiveIndex, this._scene.BackgroundRefractiveIndex);- this.txtXSize.ForeColor = SystemColors.WindowText;- this.txtYsize.ForeColor = SystemColors.WindowText;+ radUseSceneImage.Checked = _scene.UseImage;+ radUserDefinedScene.Checked = !_scene.UseImage;+ txtXSize.Text = _scene.UserWidth.ToString(CultureInfo.InvariantCulture);+ txtYsize.Text = _scene.UserHeight.ToString(CultureInfo.InvariantCulture);+ chkDampingEdge.Checked = _scene.DampingEdgeEnabled;+ txtDampingEdgeSize.Text = _scene.DampingEdgeSize.ToString(CultureInfo.InvariantCulture);+ chkUseImageSources.Checked = _scene.UseSources;+ numScaleImageSource.Value = Form1.ClampToRange(numScaleImageSource, _scene.ImageSourceScale);+ chkUseObjectSources.Checked = _scene.UseObjectSources;+ numRefractiveIndex.Value = Form1.ClampToRange(numRefractiveIndex, _scene.BackgroundRefractiveIndex);+ txtXSize.ForeColor = SystemColors.WindowText;+ txtYsize.ForeColor = SystemColors.WindowText;}finally{- this._loadingScene = false;+ _loadingScene = false;}- this.UpdateSceneControlState();- this.UpdateScenePreview();- this.ShowDampingValidity();+ UpdateSceneControlState();+ UpdateScenePreview();+ ShowDampingValidity();}/// <summary>Enables or disables the Scene tab controls according to the scene mode (image vs. user-defined size), the damping-edge checkbox and the image-sources checkbox.</summary>private void UpdateSceneControlState(){- bool useImage = this._scene.UseImage;- this.btnLoadSceneImage.Enabled = useImage;- this.lblImageNameAndSize.Enabled = useImage;- this.txtXSize.Enabled = !useImage;- this.txtYsize.Enabled = !useImage;- this.lblX.Enabled = !useImage;- this.lblPix.Enabled = !useImage;- this.numRefractiveIndex.Enabled = !useImage;- this.Label20.Enabled = !useImage;- this.txtDampingEdgeSize.Enabled = this._scene.DampingEdgeEnabled;- this.Label1.Enabled = this._scene.DampingEdgeEnabled;- this.numScaleImageSource.Enabled = this._scene.UseSources;- this.lblScaleImgSourceIntensity.Enabled = this._scene.UseSources;+ bool useImage = _scene.UseImage;+ btnLoadSceneImage.Enabled = useImage;+ lblImageNameAndSize.Enabled = useImage;+ txtXSize.Enabled = !useImage;+ txtYsize.Enabled = !useImage;+ lblX.Enabled = !useImage;+ lblPix.Enabled = !useImage;+ numRefractiveIndex.Enabled = !useImage; // a scene image has its own refractive index per pixel+ Label20.Enabled = !useImage;+ txtDampingEdgeSize.Enabled = _scene.DampingEdgeEnabled;+ Label1.Enabled = _scene.DampingEdgeEnabled;+ numScaleImageSource.Enabled = _scene.UseSources;+ lblScaleImgSourceIntensity.Enabled = _scene.UseSources;}/// <summary>@@ -125,37 +133,38 @@ namespace _2D_wave_sim_V01/// </summary>private void UpdateScenePreview(){- this.UpdateImageLabel();- if (this._scene.UseImage)+ UpdateImageLabel();+ if (_scene.UseImage){- this.picImagePreview.SizeMode = PictureBoxSizeMode.Zoom;- this.picImagePreview.Image = this._sceneImage;- this.DisposeEmptyPreview();+ picImagePreview.SizeMode = PictureBoxSizeMode.Zoom;+ picImagePreview.Image = _sceneImage;+ DisposeEmptyPreview();}else{- this.picImagePreview.SizeMode = PictureBoxSizeMode.CenterImage;- Bitmap preview = this.MakeEmptyCanvasPreview(this._scene.UserWidth, this._scene.UserHeight);- this.picImagePreview.Image = preview;- this.DisposeEmptyPreview();- this._emptyPreview = preview;+ // user defined canvas: an empty picture with the proportions of the canvas+ picImagePreview.SizeMode = PictureBoxSizeMode.CenterImage;+ Bitmap preview = MakeEmptyCanvasPreview(_scene.UserWidth, _scene.UserHeight);+ picImagePreview.Image = preview;+ DisposeEmptyPreview();+ _emptyPreview = preview;}}/// <summary>Sets the image name/size label: no image, image configured but not loadable, or file name with pixel size.</summary>private void UpdateImageLabel(){- if (this._scene.ImageFile.Length == 0)+ if (_scene.ImageFile.Length == 0){- this.lblImageNameAndSize.Text = "(no image loaded)";+ lblImageNameAndSize.Text = "(no image loaded)";}- else if (this._sceneImage == null)+ else if (_sceneImage == null){- this.lblImageNameAndSize.Text = "(image not found or not readable: " + Path.GetFileName(this._scene.ImageFile) + ")";+ lblImageNameAndSize.Text = "(image not found or not readable: " + Path.GetFileName(_scene.ImageFile) + ")";}else{- this.lblImageNameAndSize.Text = Path.GetFileName(this._scene.ImageFile) + " (" + this._sceneImage.Width.ToString(CultureInfo.InvariantCulture) + " x " + this._sceneImage.Height.ToString(CultureInfo.InvariantCulture) + " px)";+ lblImageNameAndSize.Text = Path.GetFileName(_scene.ImageFile) + " (" + _sceneImage.Width.ToString(CultureInfo.InvariantCulture) + " x " + _sceneImage.Height.ToString(CultureInfo.InvariantCulture) + " px)";}}@@ -169,8 +178,8 @@ namespace _2D_wave_sim_V01/// <returns>A new bitmap; the caller stores it in <c>_emptyPreview</c> and disposes it.</returns>private Bitmap MakeEmptyCanvasPreview(int canvasWidth, int canvasHeight){- int maxWidth = Math.Max(16, this.picImagePreview.ClientSize.Width - 8);- int maxHeight = Math.Max(16, this.picImagePreview.ClientSize.Height - 8);+ int maxWidth = Math.Max(16, picImagePreview.ClientSize.Width - 8);+ int maxHeight = Math.Max(16, picImagePreview.ClientSize.Height - 8);double scale = Math.Min((double)maxWidth / canvasWidth, (double)maxHeight / canvasHeight);int previewWidth = Math.Max(2, (int)Math.Round(canvasWidth * scale));int previewHeight = Math.Max(2, (int)Math.Round(canvasHeight * scale));@@ -196,10 +205,10 @@ namespace _2D_wave_sim_V01/// <summary>Disposes the placeholder preview bitmap, if any. Callers assign a new preview image first.</summary>private void DisposeEmptyPreview(){- if (this._emptyPreview != null)+ if (_emptyPreview != null){- this._emptyPreview.Dispose();- this._emptyPreview = null;+ _emptyPreview.Dispose();+ _emptyPreview = null;}}@@ -211,31 +220,37 @@ namespace _2D_wave_sim_V01/// <param name="newImage">The new scene image, or null to unload.</param>private void ReplaceSceneImage(Bitmap newImage){- Bitmap oldImage = this._sceneImage;- this._sceneImage = newImage;+ Bitmap oldImage = _sceneImage;+ _sceneImage = newImage;if (oldImage != null){- if (object.ReferenceEquals(this.picImagePreview.Image, oldImage))+ if (object.ReferenceEquals(picImagePreview.Image, oldImage)){- this.picImagePreview.Image = null;+ picImagePreview.Image = null;}oldImage.Dispose();}- this.UpdateGlowEdgesImage();+ UpdateGlowEdgesImage();}- /// <summary>Disposes the Sobel edge image and its resized cache.</summary>+ /// <summary>+ /// Disposes <c>_glowEdgesImage</c> and its cached resized copy (<see cref="GetGlowOverlayResized"/>) and+ /// sets both to null, without touching <c>_sceneImage</c> - used both by <see cref="UpdateGlowEdgesImage"/>+ /// (about to rebuild it from the scene image) and by <see cref="SceneMode_CheckedChanged"/> (switching to+ /// <c>radUserDefinedScene</c>, where the overlay should disappear even though <c>_sceneImage</c> itself is+ /// kept around in case the user switches back).+ /// </summary>private void ClearGlowEdgesImage(){- if (this._glowEdgesImage != null)+ if (_glowEdgesImage != null){- this._glowEdgesImage.Dispose();- this._glowEdgesImage = null;+ _glowEdgesImage.Dispose();+ _glowEdgesImage = null;}- if (this._glowOverlayCache != null)+ if (_glowOverlayCache != null){- this._glowOverlayCache.Dispose();- this._glowOverlayCache = null;+ _glowOverlayCache.Dispose();+ _glowOverlayCache = null;}}@@ -245,36 +260,46 @@ namespace _2D_wave_sim_V01/// </summary>private void UpdateGlowEdgesImage(){- this.ClearGlowEdgesImage();- if (this._sceneImage != null)+ ClearGlowEdgesImage();+ if (_sceneImage != null){- this._glowEdgesImage = Form1.ComputeGlowingEdges(this._sceneImage);+ _glowEdgesImage = Form1.ComputeGlowingEdges(_sceneImage);}- this.RefreshPreviewOverlay(this._picField, this.FieldOverlayGain());- this.RefreshPreviewOverlay(this._picIntensity, this.IntensityOverlayGain());+ RefreshPreviewOverlay(_picField, FieldOverlayGain());+ RefreshPreviewOverlay(_picIntensity, IntensityOverlayGain());}/// <summary>Overlay gain for the field preview: the brightness box value when the overlay checkbox is on, otherwise 0 (overlay off).</summary>private double FieldOverlayGain(){- return this.chkDiplayOverlayInField.Checked ? Convert.ToDouble(this.numBrightnessFieldOverlay.Value) : 0.0;+ return chkDiplayOverlayInField.Checked ? Convert.ToDouble(numBrightnessFieldOverlay.Value) : 0.0;}/// <summary>Overlay gain for the intensity preview: the brightness box value when the overlay checkbox is on, otherwise 0 (overlay off).</summary>private double IntensityOverlayGain(){- return this.chkDiplayOverlayInIntensity.Checked ? Convert.ToDouble(this.numBrightnessIntensityOverlay.Value) : 0.0;+ return chkDiplayOverlayInIntensity.Checked ? Convert.ToDouble(numBrightnessIntensityOverlay.Value) : 0.0;}/// <summary>- /// Computes a per-channel 3x3 Sobel gradient magnitude (scaled by 0.25, clamped to 255) of- /// <paramref name="source"/> on a black background, used as the glowing-edges preview overlay.- /// The source is first drawn into a 24bpp copy so any pixel format works. The outermost pixel- /// ring is always black, and images smaller than 3 x 3 give an all-black result.+ /// Builds a "glowing edges" picture of <paramref name="source"/>: a same-size picture that is black except+ /// along its edges (fast color changes), where each of the three color channels is set to how sharp the+ /// change in THAT channel is there (a 3x3 Sobel gradient magnitude, scaled and clamped to a byte). This is+ /// deliberately done per channel rather than as a single grayscale edge strength, so e.g. a hard+ /// red-to-black edge lights up mostly in red - keeping a hint of the original colors in the edge lines, the+ /// way Photoshop's "Glowing Edges" filter does. The local <c>GlowScale</c> constant is the one tunable+ /// "how bright" knob - a typical hard (full black-to-white) edge produces a raw Sobel magnitude of up to+ /// about 1442, and <c>GlowScale</c> brings that into the 0-255 byte range without every ordinary edge+ /// saturating to pure white; ask if this should be stronger/weaker. The source is first drawn into a+ /// 24bpp copy so any pixel format works. The outermost ring of pixels is left black (there is no full 3x3+ /// neighborhood there), and images smaller than 3 x 3 give an all-black result. Used as the+ /// glowing-edges overlay of the field / intensity previews and exports./// </summary>/// <returns>A new 24bpp bitmap of the source size, owned by the caller.</returns>private static Bitmap ComputeGlowingEdges(Bitmap source){+ const double GlowScale = 0.25;+int width = source.Width;int height = source.Height;Bitmap edges = new Bitmap(width, height, PixelFormat.Format24bppRgb);@@ -284,8 +309,9 @@ namespace _2D_wave_sim_V01}if (width < 3 || height < 3){- return edges;+ return edges; // too small for a 3x3 kernel - stays plain black}+ // normalize the source into a plain 24bppRgb picture first (it may be indexed, 32bppArgb, ...)using (Bitmap sourceCopy = new Bitmap(width, height, PixelFormat.Format24bppRgb)){using (Graphics g = Graphics.FromImage(sourceCopy))@@ -302,6 +328,7 @@ namespace _2D_wave_sim_V01byte[] sourcePixels = new byte[sourceStride * height];byte[] edgePixels = new byte[edgesStride * height];Marshal.Copy(sourceData.Scan0, sourcePixels, 0, sourcePixels.Length);+ // 24bppRgb stores each pixel as three bytes, in B,G,R orderfor (int y = 1; y < height - 1; y++){int rowAbove = (y - 1) * sourceStride;@@ -310,8 +337,9 @@ namespace _2D_wave_sim_V01int edgeRow = y * edgesStride;for (int x = 1; x < width - 1; x++){+ // offsets of the left-hand pixel of the 3x3 window in each of its three rowsint above = rowAbove + (x - 1) * 3;- int center = row + (x - 1) * 3;+ int middle = row + (x - 1) * 3;int below = rowBelow + (x - 1) * 3;int target = edgeRow + x * 3;for (int channel = 0; channel < 3; channel++)@@ -319,15 +347,14 @@ namespace _2D_wave_sim_V01int topLeft = sourcePixels[above + channel];int top = sourcePixels[above + 3 + channel];int topRight = sourcePixels[above + 6 + channel];- int left = sourcePixels[center + channel];- int right = sourcePixels[center + 6 + channel];+ int left = sourcePixels[middle + channel];+ int right = sourcePixels[middle + 6 + channel];int bottomLeft = sourcePixels[below + channel];int bottom = sourcePixels[below + 3 + channel];int bottomRight = sourcePixels[below + 6 + channel];int gx = topRight + 2 * right + bottomRight - (topLeft + 2 * left + bottomLeft);int gy = bottomLeft + 2 * bottom + bottomRight - (topLeft + 2 * top + topRight);- // 0.25 keeps a full-contrast step edge (gradient 4 * 255) just within the byte range.- double magnitude = Math.Sqrt((double)gx * gx + (double)gy * gy) * 0.25;+ double magnitude = Math.Sqrt((double)gx * gx + (double)gy * gy) * GlowScale;edgePixels[target + channel] = (byte)Math.Round(Math.Min(255.0, magnitude));}}@@ -351,51 +378,58 @@ namespace _2D_wave_sim_V01/// <returns>The cached 24bpp bitmap (owned by the form; do not dispose), or null when there is no scene image.</returns>private Bitmap GetGlowOverlayResized(Size targetSize){- if (this._glowEdgesImage == null)+ if (_glowEdgesImage == null){return null;}- if (this._glowOverlayCache != null && this._glowOverlayCacheSize.Equals(targetSize))+ if (_glowOverlayCache != null && _glowOverlayCacheSize.Equals(targetSize)){- return this._glowOverlayCache;+ return _glowOverlayCache;}- if (this._glowOverlayCache != null)+ if (_glowOverlayCache != null){- this._glowOverlayCache.Dispose();+ _glowOverlayCache.Dispose();}Bitmap resized = new Bitmap(Math.Max(1, targetSize.Width), Math.Max(1, targetSize.Height), PixelFormat.Format24bppRgb);using (Graphics g = Graphics.FromImage(resized)){g.Clear(Color.Black);g.InterpolationMode = InterpolationMode.HighQualityBilinear;- g.DrawImage(this._glowEdgesImage, new Rectangle(Point.Empty, targetSize));+ g.DrawImage(_glowEdgesImage, new Rectangle(Point.Empty, targetSize));}- this._glowOverlayCache = resized;- this._glowOverlayCacheSize = targetSize;+ _glowOverlayCache = resized;+ _glowOverlayCacheSize = targetSize;return resized;}/// <summary>- /// Returns a copy of <paramref name="frame"/> with the glow overlay (resized to the frame)- /// multiplied by <paramref name="gain"/> and added to each RGB channel, saturating at 255.- /// Alpha is left untouched. Frames with fewer than 3 bytes per pixel, or no overlay, give a plain copy.+ /// Returns a copy of <paramref name="frame"/> with the glow-edges overlay (<see cref="ComputeGlowingEdges"/>,+ /// <see cref="GetGlowOverlayResized"/>) additively blended on top, each of the overlay's bytes multiplied by+ /// <paramref name="gain"/> first (<c>numBrightnessFieldOverlay</c>/<c>numBrightnessIntensityOverlay</c> - 1+ /// leaves <see cref="ComputeGlowingEdges"/>' own brightness as is, above 1 brightens the overlay, 0 removes+ /// it entirely). Multiplying (rather than e.g. adding a flat offset) is what keeps a still-black background+ /// black at any gain - 0 times anything is still 0 - while scaling up faint edges where the color change+ /// was small, which is the actual complaint this is for: a plain "brightness" slider that also lifted the+ /// black background to gray would defeat its own purpose here. The overlay's black pixels (no edge there)+ /// leave the frame untouched, and its bright pixels brighten the frame, clamped at 255 per channel; alpha+ /// is left untouched. Frames with fewer than 3 bytes per pixel, or no overlay, give a plain copy./// </summary>- /// <param name="frame">The raw preview frame; not modified.</param>+ /// <param name="frame">The raw preview frame; never modified.</param>/// <param name="gain">Overlay brightness multiplier; negative values count as 0.</param>/// <returns>A new bitmap owned by the caller.</returns>private Bitmap ComposeGlowOverlay(Bitmap frame, double gain){- Bitmap overlay = this.GetGlowOverlayResized(frame.Size);+ Bitmap overlay = GetGlowOverlayResized(frame.Size);Bitmap result = new Bitmap(frame);if (overlay == null){return result;}double overlayGain = Math.Max(0.0, gain);- int bytesPerPixel = Image.GetPixelFormatSize(result.PixelFormat) / 8;- if (bytesPerPixel < 3)+ int bytesPerDstPixel = Image.GetPixelFormatSize(result.PixelFormat) / 8;+ if (bytesPerDstPixel < 3){- return result;+ return result; // an indexed/unexpected format we can't safely blend into}Rectangle bounds = new Rectangle(0, 0, frame.Width, frame.Height);BitmapData resultData = result.LockBits(bounds, ImageLockMode.ReadWrite, result.PixelFormat);@@ -416,8 +450,9 @@ namespace _2D_wave_sim_V01int overlayRow = y * overlayStride;for (int x = 0; x < width; x++){- int resultOffset = resultRow + x * bytesPerPixel;+ int resultOffset = resultRow + x * bytesPerDstPixel;int overlayOffset = overlayRow + x * 3;+ // both layouts are B,G,R... (result may have a 4th, alpha byte - left untouched)resultPixels[resultOffset] = (byte)Math.Round(Math.Min(255.0, resultPixels[resultOffset] + overlayPixels[overlayOffset] * overlayGain));resultPixels[resultOffset + 1] = (byte)Math.Round(Math.Min(255.0, resultPixels[resultOffset + 1] + overlayPixels[overlayOffset + 1] * overlayGain));resultPixels[resultOffset + 2] = (byte)Math.Round(Math.Min(255.0, resultPixels[resultOffset + 2] + overlayPixels[overlayOffset + 2] * overlayGain));@@ -445,7 +480,7 @@ namespace _2D_wave_sim_V01Image oldImage = box.Image;Bitmap oldFrame = box.Tag as Bitmap;box.Tag = frame;- box.Image = ((gain > 0.0 && this._glowEdgesImage != null) ? this.ComposeGlowOverlay(frame, gain) : frame);+ box.Image = ((gain > 0.0 && _glowEdgesImage != null) ? ComposeGlowOverlay(frame, gain) : frame);if (oldImage != null && !object.ReferenceEquals(oldImage, oldFrame)){oldImage.Dispose();@@ -473,7 +508,7 @@ namespace _2D_wave_sim_V01return;}Image oldImage = box.Image;- box.Image = ((gain > 0.0 && this._glowEdgesImage != null) ? this.ComposeGlowOverlay(frame, gain) : frame);+ box.Image = ((gain > 0.0 && _glowEdgesImage != null) ? ComposeGlowOverlay(frame, gain) : frame);if (oldImage != null && !object.ReferenceEquals(oldImage, frame)){oldImage.Dispose();@@ -483,25 +518,31 @@ namespace _2D_wave_sim_V01/// <summary>Toggling the field overlay re-composes the field preview.</summary>private void chkDiplayOverlayInField_CheckedChanged(object sender, EventArgs e){- this.RefreshPreviewOverlay(this._picField, this.FieldOverlayGain());+ RefreshPreviewOverlay(_picField, FieldOverlayGain());}/// <summary>Toggling the intensity overlay re-composes the intensity preview.</summary>private void chkDiplayOverlayInIntensity_CheckedChanged(object sender, EventArgs e){- this.RefreshPreviewOverlay(this._picIntensity, this.IntensityOverlayGain());+ RefreshPreviewOverlay(_picIntensity, IntensityOverlayGain());}- /// <summary>Changing the field overlay brightness re-composes the field preview.</summary>+ /// <summary>+ /// Changing the field overlay brightness re-composes the field preview. <c>numBrightnessFieldOverlay</c> /+ /// <c>numBrightnessIntensityOverlay</c> (Viewer tab, next to the "Display overlay" checkboxes) scale the+ /// glow-edges overlay's own brightness - 1 is the Designer default (no change), higher brightens faint+ /// edges, 0 is the same as unchecking the overlay entirely. See <see cref="ComposeGlowOverlay"/>'s gain+ /// parameter for why a multiplier (not a flat offset) is used.+ /// </summary>private void numBrightnessFieldOverlay_ValueChanged(object sender, EventArgs e){- this.RefreshPreviewOverlay(this._picField, this.FieldOverlayGain());+ RefreshPreviewOverlay(_picField, FieldOverlayGain());}- /// <summary>Changing the intensity overlay brightness re-composes the intensity preview.</summary>+ /// <summary>Changing the intensity overlay brightness re-composes the intensity preview (see <see cref="numBrightnessFieldOverlay_ValueChanged"/> for the gain semantics).</summary>private void numBrightnessIntensityOverlay_ValueChanged(object sender, EventArgs e){- this.RefreshPreviewOverlay(this._picIntensity, this.IntensityOverlayGain());+ RefreshPreviewOverlay(_picIntensity, IntensityOverlayGain());}/// <summary>@@ -523,11 +564,11 @@ namespace _2D_wave_sim_V01/// </summary>private Size EffectiveCanvas(){- if (this._scene.UseImage)+ if (_scene.UseImage){- return (this._sceneImage == null) ? Size.Empty : this._sceneImage.Size;+ return (_sceneImage == null) ? Size.Empty : _sceneImage.Size;}- return new Size(this._scene.UserWidth, this._scene.UserHeight);+ return new Size(_scene.UserWidth, _scene.UserHeight);}/// <summary>@@ -539,26 +580,26 @@ namespace _2D_wave_sim_V01private void ImportSceneImageInto(PictureBox pic){Image oldImage = pic.Image;- Bitmap canvas;- if (this._scene.UseImage && this._sceneImage != null)+ Bitmap fresh;+ if (_scene.UseImage && _sceneImage != null){- canvas = new Bitmap(this._sceneImage);+ fresh = new Bitmap(_sceneImage);}else{- Size size = this.EffectiveCanvas();- if (size.Width <= 0 || size.Height <= 0)+ Size canvas = EffectiveCanvas();+ if (canvas.Width <= 0 || canvas.Height <= 0){MessageBox.Show(this, "The canvas size is not known yet\r\n(choose a scene image, or a user defined width and height, on the Configuration tab first).", "Import scene image", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- canvas = new Bitmap(size.Width, size.Height);- using (Graphics g = Graphics.FromImage(canvas))+ fresh = new Bitmap(canvas.Width, canvas.Height);+ using (Graphics g = Graphics.FromImage(fresh)){g.Clear(Color.Black);}}- pic.Image = canvas;+ pic.Image = fresh;pic.Invalidate();if (oldImage != null){@@ -577,24 +618,24 @@ namespace _2D_wave_sim_V01{return;}- if (this._scene.UseImage && this._sceneImage != null)+ if (_scene.UseImage && _sceneImage != null){- pic.Image = new Bitmap(this._sceneImage);+ pic.Image = new Bitmap(_sceneImage);pic.Invalidate();}else{- Size size = this.EffectiveCanvas();- if (size.Width <= 0 || size.Height <= 0)+ Size canvas = EffectiveCanvas();+ if (canvas.Width <= 0 || canvas.Height <= 0){- return;+ return; // canvas size not known yet - nothing to show}- Bitmap canvas = new Bitmap(size.Width, size.Height);- using (Graphics g = Graphics.FromImage(canvas))+ Bitmap placeholder = new Bitmap(canvas.Width, canvas.Height);+ using (Graphics g = Graphics.FromImage(placeholder)){g.Clear(Color.Black);}- pic.Image = canvas;+ pic.Image = placeholder;pic.Invalidate();}}@@ -614,19 +655,19 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Validates the damping-edge text: it must be a whole number 1..8192 and, when the canvas- /// size is known, less than half of the smaller canvas side.+ /// Validates the damping-edge text: it must be a whole number 1..<see cref="SceneSettings.MaxDampingEdgeSize"/>+ /// and, when the canvas size is known, less than half of the smaller canvas side./// </summary>/// <param name="text">Content of the damping-edge text box.</param>/// <param name="value">Receives the parsed number.</param>/// <returns>An empty string when acceptable, otherwise the message to show the user.</returns>private string DampingProblem(string text, ref int value){- if (!Form1.TryParseInt(text, 1, 8192, ref value))+ if (!Form1.TryParseInt(text, 1, SceneSettings.MaxDampingEdgeSize, ref value)){return "Enter a whole number of pixels, 1 or more.";}- Size size = this.EffectiveCanvas();+ Size size = EffectiveCanvas();int smallerSide = Math.Min(size.Width, size.Height);if (size.Width > 0 && 2 * value >= smallerSide){@@ -639,18 +680,25 @@ namespace _2D_wave_sim_V01private void ShowDampingValidity(){int value = 0;- bool valid = this.DampingProblem(this.txtDampingEdgeSize.Text, ref value).Length == 0;- this.txtDampingEdgeSize.ForeColor = valid ? SystemColors.WindowText : Color.Red;+ bool valid = DampingProblem(txtDampingEdgeSize.Text, ref value).Length == 0;+ txtDampingEdgeSize.ForeColor = valid ? SystemColors.WindowText : Color.Red;}/// <summary>/// Switching between "use scene image" and "user defined" stores the mode, rebuilds or clears/// the glow overlay, updates control enabling, the preview and the damping validation, and/// marks the project changed. Ignored for the radio being unchecked and while <c>_loadingScene</c> is set.+ /// Switching to <c>radUserDefinedScene</c> drops the glow-edges overlay (<see cref="ClearGlowEdgesImage"/>) -+ /// without it, a "Display overlay" checkbox left checked on the Preview tab would otherwise keep showing+ /// the old scene image's overlay, which no longer corresponds to anything in a user-defined scene, and that+ /// stale overlay would then also be baked into any picture shared afterwards into the Sources/Probes tabs+ /// (<see cref="CopyPreviewToTabs"/>). <c>_sceneImage</c> itself is kept (not disposed) so switching back to+ /// <c>radUseSceneImage</c> restores the overlay too, via <see cref="UpdateGlowEdgesImage"/>, without needing+ /// to reload the image file./// </summary>private void SceneMode_CheckedChanged(object sender, EventArgs e){- if (this._loadingScene)+ if (_loadingScene){return;}@@ -659,21 +707,21 @@ namespace _2D_wave_sim_V01{return;}- this._scene.UseImage = object.ReferenceEquals(radio, this.radUseSceneImage);- if (this._scene.UseImage)+ _scene.UseImage = object.ReferenceEquals(radio, radUseSceneImage);+ if (_scene.UseImage){- this.UpdateGlowEdgesImage();+ UpdateGlowEdgesImage();}else{- this.ClearGlowEdgesImage();- this.RefreshPreviewOverlay(this._picField, this.FieldOverlayGain());- this.RefreshPreviewOverlay(this._picIntensity, this.IntensityOverlayGain());+ ClearGlowEdgesImage();+ RefreshPreviewOverlay(_picField, FieldOverlayGain());+ RefreshPreviewOverlay(_picIntensity, IntensityOverlayGain());}- this.UpdateSceneControlState();- this.UpdateScenePreview();- this.ShowDampingValidity();- this.MarkProjectChanged();+ UpdateSceneControlState();+ UpdateScenePreview();+ ShowDampingValidity();+ MarkProjectChanged();}/// <summary>@@ -684,20 +732,20 @@ namespace _2D_wave_sim_V01/// </summary>private void btnLOadSceneImage_Click(object sender, EventArgs e){- string projectFolder = ((this._project == null) ? "" : this._project.FolderPath);+ string projectFolder = ((_project == null) ? "" : _project.FolderPath);using (OpenFileDialog dialog = new OpenFileDialog()){dialog.Title = "Choose the scene image";dialog.Filter = "Images (*.png;*.jpg;*.jpeg;*.bmp;*.tif;*.tiff;*.gif)|*.png;*.jpg;*.jpeg;*.bmp;*.tif;*.tiff;*.gif|All files (*.*)|*.*";- if (this._project != null)+ if (_project != null){- if (Directory.Exists(this._project.SceneImageFolder))+ if (Directory.Exists(_project.SceneImageFolder)){- dialog.InitialDirectory = this._project.SceneImageFolder;+ dialog.InitialDirectory = _project.SceneImageFolder;}else{- dialog.InitialDirectory = this._project.FolderPath;+ dialog.InitialDirectory = _project.FolderPath;}}if (dialog.ShowDialog(this) != DialogResult.OK)@@ -714,76 +762,78 @@ namespace _2D_wave_sim_V01MessageBox.Show(this, "The file could not be read as an image:\r\n\r\n" + ex.Message, "Scene image", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);return;}- this.ReplaceSceneImage(image);+ ReplaceSceneImage(image);+ // an image from outside the project's own folder is copied in, so the project does not depend on a file+ // elsewhere on disk; the copy is what gets used and saved from here onstring imagePath = dialog.FileName;- if (this._project != null && !Form1.IsInsideFolder(imagePath, this._project.FolderPath))+ if (_project != null && !Form1.IsInsideFolder(imagePath, _project.FolderPath)){- imagePath = Form1.CopyIntoSceneImageFolder(this._project, imagePath);+ imagePath = Form1.CopyIntoSceneImageFolder(_project, imagePath);}- this._scene.ImageFile = SceneSettings.ToStoredPath(projectFolder, imagePath);- this._scene.UseImage = true;+ _scene.ImageFile = SceneSettings.ToStoredPath(projectFolder, imagePath);+ _scene.UseImage = true;}- this._loadingScene = true;+ _loadingScene = true;try{- this.radUseSceneImage.Checked = true;+ radUseSceneImage.Checked = true;}finally{- this._loadingScene = false;+ _loadingScene = false;}- this.UpdateSceneControlState();- this.UpdateScenePreview();- this.ShowDampingValidity();- this.MarkProjectChanged();+ UpdateSceneControlState();+ UpdateScenePreview();+ ShowDampingValidity();+ MarkProjectChanged();}/// <summary>- /// Typing a user-defined width or height (8..16384) stores it, refreshes the preview and damping- /// validation and marks the project changed; invalid text turns the box red and shows a tooltip- /// without changing the stored value.+ /// Typing a user-defined width or height (<see cref="SceneSettings.MinCanvasSize"/>..<see cref="SceneSettings.MaxCanvasSize"/>)+ /// stores it, refreshes the preview and damping validation and marks the project changed; invalid text+ /// turns the box red and shows a tooltip without changing the stored value./// </summary>private void CanvasSize_TextChanged(object sender, EventArgs e){- if (this._loadingScene)+ if (_loadingScene){return;}TextBox box = (TextBox)sender;int size = 0;- if (Form1.TryParseInt(box.Text, 8, 16384, ref size))+ if (Form1.TryParseInt(box.Text, SceneSettings.MinCanvasSize, SceneSettings.MaxCanvasSize, ref size)){box.ForeColor = SystemColors.WindowText;- this._sceneTip.Hide(box);- if (object.ReferenceEquals(box, this.txtXSize))+ _sceneTip.Hide(box);+ if (object.ReferenceEquals(box, txtXSize)){- this._scene.UserWidth = size;+ _scene.UserWidth = size;}else{- this._scene.UserHeight = size;+ _scene.UserHeight = size;}- this.UpdateScenePreview();- this.ShowDampingValidity();- this.MarkProjectChanged();+ UpdateScenePreview();+ ShowDampingValidity();+ MarkProjectChanged();}else{box.ForeColor = Color.Red;- this._sceneTip.Show("Enter a whole number of pixels from 8 to 16384.", box, 0, box.Height + 2, 3000);+ _sceneTip.Show("Enter a whole number of pixels from " + SceneSettings.MinCanvasSize.ToString(CultureInfo.InvariantCulture) + " to " + SceneSettings.MaxCanvasSize.ToString(CultureInfo.InvariantCulture) + ".", box, 0, box.Height + 2, 3000);}}/// <summary>Stores the damping-edge on/off flag, enables or disables the size box and marks the project changed.</summary>private void chkDampingEdge_CheckedChanged(object sender, EventArgs e){- if (this._loadingScene)+ if (_loadingScene){return;}- this._scene.DampingEdgeEnabled = this.chkDampingEdge.Checked;- this.UpdateSceneControlState();- this.MarkProjectChanged();+ _scene.DampingEdgeEnabled = chkDampingEdge.Checked;+ UpdateSceneControlState();+ MarkProjectChanged();}/// <summary>@@ -792,23 +842,23 @@ namespace _2D_wave_sim_V01/// </summary>private void DampingSize_TextChanged(object sender, EventArgs e){- if (this._loadingScene)+ if (_loadingScene){return;}int value = 0;- string problem = this.DampingProblem(this.txtDampingEdgeSize.Text, ref value);+ string problem = DampingProblem(txtDampingEdgeSize.Text, ref value);if (problem.Length == 0){- this._scene.DampingEdgeSize = value;- this.txtDampingEdgeSize.ForeColor = SystemColors.WindowText;- this._sceneTip.Hide(this.txtDampingEdgeSize);- this.MarkProjectChanged();+ _scene.DampingEdgeSize = value;+ txtDampingEdgeSize.ForeColor = SystemColors.WindowText;+ _sceneTip.Hide(txtDampingEdgeSize);+ MarkProjectChanged();}else{- this.txtDampingEdgeSize.ForeColor = Color.Red;- this._sceneTip.Show(problem, this.txtDampingEdgeSize, 0, this.txtDampingEdgeSize.Height + 2, 3000);+ txtDampingEdgeSize.ForeColor = Color.Red;+ _sceneTip.Show(problem, txtDampingEdgeSize, 0, txtDampingEdgeSize.Height + 2, 3000);}}@@ -820,74 +870,74 @@ namespace _2D_wave_sim_V01private void SceneText_Leave(object sender, EventArgs e){TextBox box = (TextBox)sender;- this._sceneTip.Hide(box);- this._loadingScene = true;+ _sceneTip.Hide(box);+ _loadingScene = true;try{- if (object.ReferenceEquals(box, this.txtXSize))+ if (object.ReferenceEquals(box, txtXSize)){- box.Text = this._scene.UserWidth.ToString(CultureInfo.InvariantCulture);+ box.Text = _scene.UserWidth.ToString(CultureInfo.InvariantCulture);}- else if (object.ReferenceEquals(box, this.txtYsize))+ else if (object.ReferenceEquals(box, txtYsize)){- box.Text = this._scene.UserHeight.ToString(CultureInfo.InvariantCulture);+ box.Text = _scene.UserHeight.ToString(CultureInfo.InvariantCulture);}else{- box.Text = this._scene.DampingEdgeSize.ToString(CultureInfo.InvariantCulture);+ box.Text = _scene.DampingEdgeSize.ToString(CultureInfo.InvariantCulture);}box.ForeColor = SystemColors.WindowText;}finally{- this._loadingScene = false;+ _loadingScene = false;}- this.ShowDampingValidity();+ ShowDampingValidity();}/// <summary>Stores whether green pixels of the scene image act as sources, enables or disables the scale box and marks the project changed.</summary>private void chkUseSources_CheckedChanged(object sender, EventArgs e){- if (this._loadingScene)+ if (_loadingScene){return;}- this._scene.UseSources = this.chkUseImageSources.Checked;- this.UpdateSceneControlState();- this.MarkProjectChanged();+ _scene.UseSources = chkUseImageSources.Checked;+ UpdateSceneControlState();+ MarkProjectChanged();}/// <summary>Stores whether the object sources from the source list are used and marks the project changed.</summary>private void chkUseObjectSources_CheckedChanged(object sender, EventArgs e){- if (this._loadingScene)+ if (_loadingScene){return;}- this._scene.UseObjectSources = this.chkUseObjectSources.Checked;- this.MarkProjectChanged();+ _scene.UseObjectSources = chkUseObjectSources.Checked;+ MarkProjectChanged();}- /// <summary>Stores the image-source intensity scale (0..1000) and marks the project changed.</summary>+ /// <summary>Stores the image-source intensity scale (0..<see cref="SceneSettings.MaxImageSourceScale"/>) and marks the project changed.</summary>private void ImageSourceScale_ValueChanged(object sender, EventArgs e){- if (this._loadingScene)+ if (_loadingScene){return;}- this._scene.ImageSourceScale = Convert.ToDouble(this.numScaleImageSource.Value);- this.MarkProjectChanged();+ _scene.ImageSourceScale = Convert.ToDouble(numScaleImageSource.Value);+ MarkProjectChanged();}/// <summary>Stores the background refractive index of the user-defined (empty) scene and marks the project changed.</summary>private void RefractiveIndex_ValueChanged(object sender, EventArgs e){- if (this._loadingScene)+ if (_loadingScene){return;}- this._scene.BackgroundRefractiveIndex = Convert.ToDouble(this.numRefractiveIndex.Value);- this.MarkProjectChanged();+ _scene.BackgroundRefractiveIndex = Convert.ToDouble(numRefractiveIndex.Value);+ MarkProjectChanged();}/// <summary>@@ -903,7 +953,7 @@ namespace _2D_wave_sim_V01/// <summary>Jumps to the source list tab.</summary>private void btnEditSourceList_Click(object sender, EventArgs e){- this.tabMainFunctions.SelectedTab = this.tabSourceList;+ tabMainFunctions.SelectedTab = tabSourceList;}}}diff --git a/Wave_Dude_2D/Form1.Simulation.cs b/Wave_Dude_2D/Form1.Simulation.csindex 3c7098f..6a2a3fb 100644--- a/Wave_Dude_2D/Form1.Simulation.cs+++ b/Wave_Dude_2D/Form1.Simulation.cs@@ -12,6 +12,15 @@ using System.Windows.Forms;namespace _2D_wave_sim_V01{+ /// <summary>+ /// Simulation: the settings on the Configuration tab (steps, video export, previews, color schemes) are kept+ /// in <c>_simulation</c> (a <see cref="SimulationSettings"/>) and saved in configuration.json with the+ /// project. "Start simulation" hands a copy of everything to a <see cref="SimulationRunner"/>, which does the+ /// work on a background thread. The runner reports back through events; <see cref="PostToUi"/> passes them+ /// on to this (the UI) thread. Also home to the Preview tab (run/pause/stop, the field / intensity preview+ /// boxes with the glow-edges overlay, sharing pictures with the Sources/Probes tabs, still-frame export,+ /// opening the output folders in Explorer). Everything here runs on the UI thread unless stated otherwise.+ /// </summary>public partial class Form1{/// <summary>@@ -20,47 +29,75 @@ namespace _2D_wave_sim_V01/// </summary>private void InitializeSimulationControls(){- this.numVisualizeEvery.Minimum = 1m;- this.numFieldScaling.Minimum = 0.1m;- this.numFieldScaling.Maximum = 1000m;- this.numIntensityScaling.Minimum = 0.1m;- this.numIntensityScaling.Maximum = 1000m;- this.numFieldScaling2.Minimum = this.numFieldScaling.Minimum;- this.numFieldScaling2.Maximum = this.numFieldScaling.Maximum;- this.numFieldScaling2.DecimalPlaces = this.numFieldScaling.DecimalPlaces;- this.numFieldScaling2.Increment = this.numFieldScaling.Increment;- this.numIntensityScaling2.Minimum = this.numIntensityScaling.Minimum;- this.numIntensityScaling2.Maximum = this.numIntensityScaling.Maximum;- this.numIntensityScaling2.DecimalPlaces = this.numIntensityScaling.DecimalPlaces;- this.numIntensityScaling2.Increment = this.numIntensityScaling.Increment;- foreach (NumericUpDown offsetBox in new NumericUpDown[] { this.numOffsetField, this.numOffsetIntensity })+ numVisualizeEvery.Minimum = 1m;++ // brightness factors of the field and intensity pictures (render_field / render_intensity in the Python code)+ numFieldScaling.Minimum = 0.1m;+ numFieldScaling.Maximum = 1000m;+ numIntensityScaling.Minimum = 0.1m;+ numIntensityScaling.Maximum = 1000m;++ // numFieldScaling2/numIntensityScaling2 (Viewer tab) are a second set of controls for the very same+ // FieldBrightness/IntensityBrightness values as numFieldScaling/numIntensityScaling (Configuration tab) -+ // see numScaleFieldValues_ValueChanged/numScaleIntensity_ValueChanged and their "2" counterparts, which+ // keep both pairs in sync. Match the originals' range/precision so a value entered in either pair means+ // the same thing and is not rejected/rounded differently by the other.+ numFieldScaling2.Minimum = numFieldScaling.Minimum;+ numFieldScaling2.Maximum = numFieldScaling.Maximum;+ numFieldScaling2.DecimalPlaces = numFieldScaling.DecimalPlaces;+ numFieldScaling2.Increment = numFieldScaling.Increment;+ numIntensityScaling2.Minimum = numIntensityScaling.Minimum;+ numIntensityScaling2.Maximum = numIntensityScaling.Maximum;+ numIntensityScaling2.DecimalPlaces = numIntensityScaling.DecimalPlaces;+ numIntensityScaling2.Increment = numIntensityScaling.Increment;++ // offsets (black levels of the color tables): 2 decimals, otherwise the default of -0.05 would be rounded+ foreach (NumericUpDown offsetBox in new NumericUpDown[] { numOffsetField, numOffsetIntensity }){offsetBox.DecimalPlaces = 2;offsetBox.Minimum = -1m;offsetBox.Maximum = 1m;offsetBox.Increment = 0.01m;}- this.numQuality.Minimum = 1m;- this.numQuality.Maximum = 100m;- this.numQuality.DecimalPlaces = 0;- this.StatusStrip1.ShowItemToolTips = true;- this.ToolStripStatusLabel1.Spring = true;- this.ToolStripStatusLabel1.TextAlign = ContentAlignment.MiddleLeft;- this.ToolStripStatusLabel1.Text = "";- this.UpdateRunButtons();- this.btnViewIntensityVideo.Text = "View intensity video in media player";- this.UpdateVideoButtons();- this.cmbFieldColorScheme.DropDownStyle = ComboBoxStyle.DropDownList;- this.cmbIntensityColorScheme.DropDownStyle = ComboBoxStyle.DropDownList;- this._picField = Form1.MakePreviewBox(this.pnlPreviewField);- this._picIntensity = Form1.MakePreviewBox(this.pnlPreviewIntensity);- this._picSource = Form1.MakePreviewBox(this.pnlSourceImage);- this._picProbe = Form1.MakePreviewBox(this.pnlProbeImage);- this.UpdateCopyButtons();- this.lblWarningField.Text = "Field video not exported";- this.lblWarningField.ForeColor = Color.DarkBlue;- this.lblWarningIntensity.Text = "Intensity video not exported";- this.lblWarningIntensity.ForeColor = Color.DarkBlue;++ numQuality.Minimum = 1m;+ numQuality.Maximum = 100m;+ numQuality.DecimalPlaces = 0;++ // the summary of a run is shown in the status bar, its details in the tooltip+ StatusStrip1.ShowItemToolTips = true;+ ToolStripStatusLabel1.Spring = true;+ ToolStripStatusLabel1.TextAlign = ContentAlignment.MiddleLeft;+ ToolStripStatusLabel1.Text = "";++ UpdateRunButtons();++ btnViewIntensityVideo.Text = "View intensity video in media player";+ UpdateVideoButtons();+ cmbFieldColorScheme.DropDownStyle = ComboBoxStyle.DropDownList;+ cmbIntensityColorScheme.DropDownStyle = ComboBoxStyle.DropDownList;++ _picField = Form1.MakePreviewBox(pnlPreviewField);+ _picIntensity = Form1.MakePreviewBox(pnlPreviewIntensity);+ _picSource = Form1.MakePreviewBox(pnlSourceImage);+ _picProbe = Form1.MakePreviewBox(pnlProbeImage);+ UpdateCopyButtons();++ // warn, in lblWarningField/lblWarningIntensity, when the last (or next) run will not export that video -+ // shown/hidden per video in UpdateSimulationControlState; these are Designer labels placed in the clear,+ // not (like the dynamic label this used to be) a control positioned over other controls at runtime+ lblWarningField.Text = "Field video not exported";+ lblWarningField.ForeColor = Color.DarkBlue;+ lblWarningIntensity.Text = "Intensity video not exported";+ lblWarningIntensity.ForeColor = Color.DarkBlue;++ // No ShowSimulationInControls() here: grpSimulationSettings is disabled until a real project exists+ // (UpdateProjectAccess). Steps and TimeDecayFactor have no software default of their own any more (see+ // their comments in SimulationSettings) - populating the controls now, from the blank _simulation this+ // form starts with, would clamp numSimulationSteps/numTimeDecayFactor down from their Designer defaults+ // (3000 and 10) to their Minimum before StartNewProject ever gets a chance to read the Designer value back+ // out of them. StartNewProject/SetCurrentProject call ShowSimulationInControls() themselves once a real+ // project exists.}/// <summary>Creates a black, zoom-to-fit <see cref="PictureBox"/> that fills <paramref name="host"/>.</summary>@@ -82,49 +119,51 @@ namespace _2D_wave_sim_V01/// </summary>private void ShowSimulationInControls(){- this._loadingSim = true;+ _loadingSim = true;try{- int visualizeEvery = Math.Max(Convert.ToInt32(this.numVisualizeEvery.Minimum), Math.Min(Convert.ToInt32(this.numVisualizeEvery.Maximum), this._simulation.VisualizeEvery));- this._simulation.VisualizeEvery = visualizeEvery;- this.numSimulationSteps.Value = Form1.ClampToRange(this.numSimulationSteps, this._simulation.Steps);- this.numVisualizeEvery.Value = visualizeEvery;- this.numFieldScaling.Value = Form1.ClampToRange(this.numFieldScaling, this._simulation.FieldBrightness);- this.numIntensityScaling.Value = Form1.ClampToRange(this.numIntensityScaling, this._simulation.IntensityBrightness);- this.numFieldScaling2.Value = Form1.ClampToRange(this.numFieldScaling2, this._simulation.FieldBrightness);- this.numIntensityScaling2.Value = Form1.ClampToRange(this.numIntensityScaling2, this._simulation.IntensityBrightness);- this.numQuality.Value = Form1.ClampToRange(this.numQuality, this._simulation.VideoQuality);- this.numOffsetField.Value = Form1.ClampToRange(this.numOffsetField, this._simulation.FieldBlackLevel);- this.numOffsetIntensity.Value = Form1.ClampToRange(this.numOffsetIntensity, this._simulation.IntensityBlackLevel);- this.numTimeDecayFactor.Value = Form1.ClampToRange(this.numTimeDecayFactor, this._simulation.TimeDecayFactor);- this.chkExportVideoField.Checked = this._simulation.ExportField;- this.chkExportVideoIntensity.Checked = this._simulation.ExportIntensity;- this.chkExportVideoField2.Checked = this._simulation.ExportField;- this.chkExportVideoIntensity2.Checked = this._simulation.ExportIntensity;- this.chkPreviewVideoField.Checked = this._simulation.PreviewField;- this.chkPreviewVideoIntensity.Checked = this._simulation.PreviewIntensity;- this.chkUseGPU.Checked = this._simulation.UseGpu;- this.chkUse4thOrderLaplacian.Checked = this._simulation.Use4thOrderLaplacian;- this.FillSchemeCombo(this.cmbFieldColorScheme, "field", this._simulation.FieldColorScheme);- this.FillSchemeCombo(this.cmbIntensityColorScheme, "intensity", this._simulation.IntensityColorScheme);+ // the range of the numeric box is set in the designer; keep the settings inside it+ int visualizeEvery = Math.Max(Convert.ToInt32(numVisualizeEvery.Minimum), Math.Min(Convert.ToInt32(numVisualizeEvery.Maximum), _simulation.VisualizeEvery));+ _simulation.VisualizeEvery = visualizeEvery;+ numSimulationSteps.Value = Form1.ClampToRange(numSimulationSteps, _simulation.Steps);+ numVisualizeEvery.Value = visualizeEvery;+ numFieldScaling.Value = Form1.ClampToRange(numFieldScaling, _simulation.FieldBrightness);+ numIntensityScaling.Value = Form1.ClampToRange(numIntensityScaling, _simulation.IntensityBrightness);+ numFieldScaling2.Value = Form1.ClampToRange(numFieldScaling2, _simulation.FieldBrightness);+ numIntensityScaling2.Value = Form1.ClampToRange(numIntensityScaling2, _simulation.IntensityBrightness);+ numQuality.Value = Form1.ClampToRange(numQuality, _simulation.VideoQuality);+ numOffsetField.Value = Form1.ClampToRange(numOffsetField, _simulation.FieldBlackLevel);+ numOffsetIntensity.Value = Form1.ClampToRange(numOffsetIntensity, _simulation.IntensityBlackLevel);+ numTimeDecayFactor.Value = Form1.ClampToRange(numTimeDecayFactor, _simulation.TimeDecayFactor);+ chkExportVideoField.Checked = _simulation.ExportField;+ chkExportVideoIntensity.Checked = _simulation.ExportIntensity;+ chkExportVideoField2.Checked = _simulation.ExportField;+ chkExportVideoIntensity2.Checked = _simulation.ExportIntensity;+ chkPreviewVideoField.Checked = _simulation.PreviewField;+ chkPreviewVideoIntensity.Checked = _simulation.PreviewIntensity;+ chkUseGPU.Checked = _simulation.UseGpu;+ chkUse4thOrderLaplacian.Checked = _simulation.Use4thOrderLaplacian;+ FillSchemeCombo(cmbFieldColorScheme, ColorScheme.SchemeTypeField, _simulation.FieldColorScheme);+ FillSchemeCombo(cmbIntensityColorScheme, ColorScheme.SchemeTypeIntensity, _simulation.IntensityColorScheme);}finally{- this._loadingSim = false;+ _loadingSim = false;}- this.UpdateSimulationControlState();+ UpdateSimulationControlState();}/// <summary>Enables the scheme combos, the quality box and the "not exported" warnings according to the export / preview check boxes.</summary>private void UpdateSimulationControlState(){- this.cmbFieldColorScheme.Enabled = this.chkExportVideoField.Checked || this.chkPreviewVideoField.Checked;- this.cmbIntensityColorScheme.Enabled = this.chkExportVideoIntensity.Checked || this.chkPreviewVideoIntensity.Checked;- bool exporting = this.chkExportVideoField.Checked || this.chkExportVideoIntensity.Checked;- this.numQuality.Enabled = exporting;- this.lblVideoQuality.Enabled = exporting;- this.lblWarningField.Visible = !this.chkExportVideoField.Checked;- this.lblWarningIntensity.Visible = !this.chkExportVideoIntensity.Checked;+ cmbFieldColorScheme.Enabled = chkExportVideoField.Checked || chkPreviewVideoField.Checked;+ cmbIntensityColorScheme.Enabled = chkExportVideoIntensity.Checked || chkPreviewVideoIntensity.Checked;+ // the quality only matters for exported videos+ bool exporting = chkExportVideoField.Checked || chkExportVideoIntensity.Checked;+ numQuality.Enabled = exporting;+ lblVideoQuality.Enabled = exporting;+ lblWarningField.Visible = !chkExportVideoField.Checked;+ lblWarningIntensity.Visible = !chkExportVideoIntensity.Checked;}/// <summary>@@ -133,22 +172,22 @@ namespace _2D_wave_sim_V01/// </summary>private void RefreshSchemeCombos(){- bool loadingSim = this._loadingSim;- this._loadingSim = true;+ bool wasLoading = _loadingSim;+ _loadingSim = true;try{- this.FillSchemeCombo(this.cmbFieldColorScheme, "field", this._simulation.FieldColorScheme);- this.FillSchemeCombo(this.cmbIntensityColorScheme, "intensity", this._simulation.IntensityColorScheme);+ FillSchemeCombo(cmbFieldColorScheme, ColorScheme.SchemeTypeField, _simulation.FieldColorScheme);+ FillSchemeCombo(cmbIntensityColorScheme, ColorScheme.SchemeTypeIntensity, _simulation.IntensityColorScheme);}finally{- this._loadingSim = loadingSim;+ _loadingSim = wasLoading;}}- /// <summary>Fills <paramref name="combo"/> with the schemes of one type and selects the one named <paramref name="selectedName"/> (case-insensitive), or nothing.</summary>+ /// <summary>Fills <paramref name="combo"/> with the schemes of one type and selects the one named <paramref name="selectedName"/> (case-insensitive), or nothing. Schemes without a type are left out.</summary>/// <param name="combo">The field or intensity scheme combo; its items become <see cref="ColorScheme"/> objects.</param>- /// <param name="schemeType">"field" or "intensity".</param>+ /// <param name="schemeType"><see cref="ColorScheme.SchemeTypeField"/> or <see cref="ColorScheme.SchemeTypeIntensity"/>.</param>/// <param name="selectedName">Name of the scheme to select; no selection when it is not in the list.</param>private void FillSchemeCombo(ComboBox combo, string schemeType, string selectedName){@@ -157,7 +196,7 @@ namespace _2D_wave_sim_V01{combo.Items.Clear();ColorScheme selected = null;- foreach (ColorScheme scheme in this._schemes)+ foreach (ColorScheme scheme in _schemes){if (string.Equals(scheme.SchemeType, schemeType, StringComparison.OrdinalIgnoreCase)){@@ -187,7 +226,7 @@ namespace _2D_wave_sim_V01/// <returns>The scheme, or null when no such scheme is loaded.</returns>private ColorScheme FindScheme(string name, string schemeType){- foreach (ColorScheme scheme in this._schemes)+ foreach (ColorScheme scheme in _schemes){if (string.Equals(scheme.Name, name, StringComparison.OrdinalIgnoreCase) && string.Equals(scheme.SchemeType, schemeType, StringComparison.OrdinalIgnoreCase)){@@ -203,77 +242,102 @@ namespace _2D_wave_sim_V01/// </summary>private void tabMainFunctions_SelectedIndexChanged(object sender, EventArgs e){- if (this.tabMainFunctions.SelectedTab == this.tabConfiguration)+ // cmbFieldColorScheme/cmbIntensityColorScheme live on the Configuration tab. Schemes may have been added,+ // renamed or deleted on the Color Scheme tab since these were last filled - or even just added to the+ // folder from outside the app - so re-read the scheme folder from disk (RefreshSchemeCombos alone only+ // refills the combos from the in-memory list, which can be stale) rather than assume it is still current.+ if (tabMainFunctions.SelectedTab == tabConfiguration){- string schemeFolder = this.txtSchemeFolder.Text.Trim();+ string schemeFolder = txtSchemeFolder.Text.Trim();if (Directory.Exists(schemeFolder)){- this.LoadSchemeList();+ LoadSchemeList();}else{- this.RefreshSchemeCombos();+ RefreshSchemeCombos();}}- if (this.tabMainFunctions.SelectedTab == this.tabOutput)+ // lstAllProjects3 (Outputs tab) has the same staleness problem - a project may have appeared, been+ // renamed or been deleted since it was last filled, so re-read it fresh on every arrival too. Default the+ // selection to whichever project is currently open in the editor (falls back to the previous selection,+ // or none, when no project is open - see RefreshOutputProjectList).+ if (tabMainFunctions.SelectedTab == tabOutput){- this.RefreshOutputProjectList((this._project != null) ? this._project.Name : "");+ RefreshOutputProjectList((_project != null) ? _project.Name : "");}}- /// <summary>Stores the number of steps and marks the project dirty.</summary>+ /// <summary>+ /// Stores the number of steps and marks the project dirty. <c>numSimulationSteps</c> replaces the old+ /// <c>cmbSimulationSteps</c> combo box, so the number of steps is no longer limited to a fixed preset list -+ /// the range (currently 1 to 50,000) is set in the Designer, and the control itself never allows an+ /// out-of-range or non-integer value, so unlike the old free-text combo this needs no separate+ /// parsing/validation/error-coloring here.+ /// </summary>private void numSimulationSteps_ValueChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.Steps = Convert.ToInt32(this.numSimulationSteps.Value);- this.MarkProjectChanged();+ _simulation.Steps = Convert.ToInt32(numSimulationSteps.Value);+ MarkProjectChanged();}}/// <summary>Stores how many steps go by between two rendered frames.</summary>private void numVisualizeEvery_ValueChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.VisualizeEvery = Convert.ToInt32(this.numVisualizeEvery.Value);- this.MarkProjectChanged();+ _simulation.VisualizeEvery = Convert.ToInt32(numVisualizeEvery.Value);+ MarkProjectChanged();}}- /// <summary>Mirrors a scaling value into the linked box on the other tab without raising the change handlers.</summary>+ /// <summary>+ /// Copies a value into a NumericUpDown that mirrors another one (<c>numFieldScaling</c>/<c>numFieldScaling2</c>,+ /// <c>numIntensityScaling</c>/<c>numIntensityScaling2</c> - Configuration tab and Viewer tab controls for the+ /// very same setting), without re-triggering that control's own ValueChanged - every simulation control's+ /// ValueChanged already checks <c>_loadingSim</c> first, so reusing it here as the reentrancy guard stops+ /// the two controls from setting each other back and forth.+ /// </summary>private void SetLinkedScalingValue(NumericUpDown box, decimal value){decimal clamped = (value < box.Minimum) ? box.Minimum : ((value > box.Maximum) ? box.Maximum : value);if (box.Value != clamped){- bool loadingSim = this._loadingSim;- this._loadingSim = true;+ bool wasLoading = _loadingSim;+ _loadingSim = true;try{box.Value = clamped;}finally{- this._loadingSim = loadingSim;+ _loadingSim = wasLoading;}}}- /// <summary>Mirrors a check state into the linked box on the other tab without raising its CheckedChanged handler.</summary>+ /// <summary>+ /// Copies a checked state into a CheckBox that mirrors another one (<c>chkExportVideoField</c>/+ /// <c>chkExportVideoField2</c>, <c>chkExportVideoIntensity</c>/<c>chkExportVideoIntensity2</c> - Configuration+ /// tab and Viewer tab controls for the very same setting) - the same <c>_loadingSim</c> reentrancy-guard idea+ /// as <see cref="SetLinkedScalingValue"/>, for a CheckBox's Checked instead of a NumericUpDown's Value.+ /// </summary>private void SetLinkedCheckedValue(CheckBox box, bool value){if (box.Checked != value){- bool loadingSim = this._loadingSim;- this._loadingSim = true;+ bool wasLoading = _loadingSim;+ _loadingSim = true;try{box.Checked = value;}finally{- this._loadingSim = loadingSim;+ _loadingSim = wasLoading;}}}@@ -281,84 +345,84 @@ namespace _2D_wave_sim_V01/// <summary>Stores the field brightness and mirrors it into the viewer-tab box.</summary>private void numScaleFieldValues_ValueChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.FieldBrightness = Convert.ToDouble(this.numFieldScaling.Value);- this.SetLinkedScalingValue(this.numFieldScaling2, this.numFieldScaling.Value);- this.MarkProjectChanged();+ _simulation.FieldBrightness = Convert.ToDouble(numFieldScaling.Value);+ SetLinkedScalingValue(numFieldScaling2, numFieldScaling.Value);+ MarkProjectChanged();}}/// <summary>Viewer-tab copy: stores the field brightness and mirrors it back into the configuration-tab box.</summary>private void numScaleFieldValues2_ValueChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.FieldBrightness = Convert.ToDouble(this.numFieldScaling2.Value);- this.SetLinkedScalingValue(this.numFieldScaling, this.numFieldScaling2.Value);- this.MarkProjectChanged();+ _simulation.FieldBrightness = Convert.ToDouble(numFieldScaling2.Value);+ SetLinkedScalingValue(numFieldScaling, numFieldScaling2.Value);+ MarkProjectChanged();}}/// <summary>Stores the video quality (1..100).</summary>private void numQuality_ValueChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.VideoQuality = Convert.ToInt32(this.numQuality.Value);- this.MarkProjectChanged();+ _simulation.VideoQuality = Convert.ToInt32(numQuality.Value);+ MarkProjectChanged();}}/// <summary>Stores the field black level (-1..1 palette offset).</summary>private void numOffsetField_ValueChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.FieldBlackLevel = Convert.ToDouble(this.numOffsetField.Value);- this.MarkProjectChanged();+ _simulation.FieldBlackLevel = Convert.ToDouble(numOffsetField.Value);+ MarkProjectChanged();}}/// <summary>Stores the intensity black level (-1..1 palette offset).</summary>private void numOffsetIntensity_ValueChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.IntensityBlackLevel = Convert.ToDouble(this.numOffsetIntensity.Value);- this.MarkProjectChanged();+ _simulation.IntensityBlackLevel = Convert.ToDouble(numOffsetIntensity.Value);+ MarkProjectChanged();}}/// <summary>Stores the time decay factor.</summary>private void numTimeDecayFactor_ValueChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.TimeDecayFactor = Convert.ToDouble(this.numTimeDecayFactor.Value);- this.MarkProjectChanged();+ _simulation.TimeDecayFactor = Convert.ToDouble(numTimeDecayFactor.Value);+ MarkProjectChanged();}}/// <summary>Stores the intensity brightness and mirrors it into the viewer-tab box.</summary>private void numScaleIntensity_ValueChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.IntensityBrightness = Convert.ToDouble(this.numIntensityScaling.Value);- this.SetLinkedScalingValue(this.numIntensityScaling2, this.numIntensityScaling.Value);- this.MarkProjectChanged();+ _simulation.IntensityBrightness = Convert.ToDouble(numIntensityScaling.Value);+ SetLinkedScalingValue(numIntensityScaling2, numIntensityScaling.Value);+ MarkProjectChanged();}}/// <summary>Viewer-tab copy: stores the intensity brightness and mirrors it back into the configuration-tab box.</summary>private void numScaleIntensity2_ValueChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.IntensityBrightness = Convert.ToDouble(this.numIntensityScaling2.Value);- this.SetLinkedScalingValue(this.numIntensityScaling, this.numIntensityScaling2.Value);- this.MarkProjectChanged();+ _simulation.IntensityBrightness = Convert.ToDouble(numIntensityScaling2.Value);+ SetLinkedScalingValue(numIntensityScaling, numIntensityScaling2.Value);+ MarkProjectChanged();}}@@ -368,67 +432,67 @@ namespace _2D_wave_sim_V01/// </summary>private void SimulationOption_CheckedChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.ExportField = this.chkExportVideoField.Checked;- this._simulation.ExportIntensity = this.chkExportVideoIntensity.Checked;- this._simulation.PreviewField = this.chkPreviewVideoField.Checked;- this._simulation.PreviewIntensity = this.chkPreviewVideoIntensity.Checked;- this.SetLinkedCheckedValue(this.chkExportVideoField2, this.chkExportVideoField.Checked);- this.SetLinkedCheckedValue(this.chkExportVideoIntensity2, this.chkExportVideoIntensity.Checked);- this.UpdateSimulationControlState();- this.MarkProjectChanged();+ _simulation.ExportField = chkExportVideoField.Checked;+ _simulation.ExportIntensity = chkExportVideoIntensity.Checked;+ _simulation.PreviewField = chkPreviewVideoField.Checked;+ _simulation.PreviewIntensity = chkPreviewVideoIntensity.Checked;+ SetLinkedCheckedValue(chkExportVideoField2, chkExportVideoField.Checked);+ SetLinkedCheckedValue(chkExportVideoIntensity2, chkExportVideoIntensity.Checked);+ UpdateSimulationControlState();+ MarkProjectChanged();}}/// <summary>Viewer-tab copy of the field export box: stores the flag and mirrors it back.</summary>private void chkExportVideoField2_CheckedChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.ExportField = this.chkExportVideoField2.Checked;- this.SetLinkedCheckedValue(this.chkExportVideoField, this.chkExportVideoField2.Checked);- this.UpdateSimulationControlState();- this.MarkProjectChanged();+ _simulation.ExportField = chkExportVideoField2.Checked;+ SetLinkedCheckedValue(chkExportVideoField, chkExportVideoField2.Checked);+ UpdateSimulationControlState();+ MarkProjectChanged();}}/// <summary>Viewer-tab copy of the intensity export box: stores the flag and mirrors it back.</summary>private void chkExportVideoIntensity2_CheckedChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.ExportIntensity = this.chkExportVideoIntensity2.Checked;- this.SetLinkedCheckedValue(this.chkExportVideoIntensity, this.chkExportVideoIntensity2.Checked);- this.UpdateSimulationControlState();- this.MarkProjectChanged();+ _simulation.ExportIntensity = chkExportVideoIntensity2.Checked;+ SetLinkedCheckedValue(chkExportVideoIntensity, chkExportVideoIntensity2.Checked);+ UpdateSimulationControlState();+ MarkProjectChanged();}}/// <summary>Stores whether the OpenCL engine is tried first.</summary>private void chkUseGPU_CheckedChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.UseGpu = this.chkUseGPU.Checked;- this.MarkProjectChanged();+ _simulation.UseGpu = chkUseGPU.Checked;+ MarkProjectChanged();}}/// <summary>Stores the Laplacian order choice.</summary>private void chkUse4thOrderLaplacian_CheckedChanged(object sender, EventArgs e){- if (!this._loadingSim)+ if (!_loadingSim){- this._simulation.Use4thOrderLaplacian = this.chkUse4thOrderLaplacian.Checked;- this.MarkProjectChanged();+ _simulation.Use4thOrderLaplacian = chkUse4thOrderLaplacian.Checked;+ MarkProjectChanged();}}/// <summary>Shared handler of both scheme combos: stores the chosen scheme name in the field or intensity setting, depending on which combo raised it.</summary>private void SchemeCombo_SelectedIndexChanged(object sender, EventArgs e){- if (this._loadingSim)+ if (_loadingSim){return;}@@ -438,50 +502,61 @@ namespace _2D_wave_sim_V01{return;}- if (combo == this.cmbFieldColorScheme)+ if (combo == cmbFieldColorScheme){- this._simulation.FieldColorScheme = scheme.Name;+ _simulation.FieldColorScheme = scheme.Name;}else{- this._simulation.IntensityColorScheme = scheme.Name;+ _simulation.IntensityColorScheme = scheme.Name;}- this.MarkProjectChanged();+ MarkProjectChanged();}/// <summary>Starts a run, or asks the running one to stop (the button doubles as Stop while a run is active).</summary>private void btnStartSimulation_Click(object sender, EventArgs e){- if (this._runner != null)+ if (_runner != null){- this.RequestStop();+ // the button is also a stop button while a simulation runs+ RequestStop();}else{- this.StartSimulation();+ StartSimulation();}}- /// <summary>Loads the scene image into the Sources and Probes picture boxes.</summary>+ /// <summary>+ /// Puts a copy of the current scene image (or the black placeholder when there is none) in+ /// <c>pnlSourceImage</c> and <c>pnlProbeImage</c> - the same picture the "Import scene image" buttons on+ /// those tabs load, just from here instead (<see cref="ImportSceneImageInto"/>).+ /// </summary>private void btnShareSceneImage_Click(object sender, EventArgs e){- this.ImportSceneImageInto(this._picSource);- this.ImportSceneImageInto(this._picProbe);+ ImportSceneImageInto(_picSource);+ ImportSceneImageInto(_picProbe);}/// <summary>Copies the field preview into the Sources and Probes picture boxes.</summary>private void btnShareFieldImage_Click(object sender, EventArgs e){- this.CopyPreviewToTabs(this._picField);+ CopyPreviewToTabs(_picField);}/// <summary>Copies the intensity preview into the Sources and Probes picture boxes.</summary>private void btnShareIntensityImage_Click(object sender, EventArgs e){- this.CopyPreviewToTabs(this._picIntensity);+ CopyPreviewToTabs(_picIntensity);}- /// <summary>Gives <c>_picSource</c> and <c>_picProbe</c> each their own copy of the image in <paramref name="source"/>, disposing what they showed before. Does nothing when there is no image.</summary>+ /// <summary>+ /// Gives <c>_picSource</c> and <c>_picProbe</c> (Sources tab and Probes tab) each their own copy of the image+ /// in <paramref name="source"/>, disposing what they showed before - <c>source.Image</c> exactly as currently+ /// displayed, glow-edges overlay baked in when "Display overlay" happens to be checked for that preview+ /// (<see cref="SetPreviewFrame"/>/<see cref="RefreshPreviewOverlay"/>), and not when it is not. Does nothing+ /// when there is no image.+ /// </summary>private void CopyPreviewToTabs(PictureBox source){Image image = source.Image;@@ -489,7 +564,7 @@ namespace _2D_wave_sim_V01{return;}- foreach (PictureBox target in new PictureBox[] { this._picSource, this._picProbe })+ foreach (PictureBox target in new PictureBox[] { _picSource, _picProbe }){Bitmap copy = new Bitmap(image);Image previous = target.Image;@@ -501,20 +576,30 @@ namespace _2D_wave_sim_V01}}- /// <summary>Enables the share buttons when the matching preview box has an image; also refreshes the export buttons.</summary>+ /// <summary>+ /// The field/intensity share buttons are only on when their preview shows a picture; <c>btnShareSceneImage</c>+ /// is not gated the same way, matching "Import scene image" on the Sources/Probes tabs, which always works+ /// (it falls back to a black placeholder when there is no scene image). Also refreshes the export buttons.+ /// </summary>private void UpdateCopyButtons(){- this.btnShareFieldImage.Enabled = this._picField != null && this._picField.Image != null;- this.btnShareIntensityImage.Enabled = this._picIntensity != null && this._picIntensity.Image != null;- this.UpdateExportButtons();+ btnShareFieldImage.Enabled = _picField != null && _picField.Image != null;+ btnShareIntensityImage.Enabled = _picIntensity != null && _picIntensity.Image != null;+ UpdateExportButtons();}- /// <summary>Enables the frame export buttons when no run is active or it is paused, and a full-size or preview frame exists to export.</summary>+ /// <summary>+ /// The "Export current Field/Intensity frame" buttons are only on while the simulation is not actively+ /// running (paused, or fully stopped) and there is something to export: either a live, paused engine+ /// (<see cref="SimulationRunner.RenderCurrentFrame"/>), a full-resolution snapshot cached from the last run+ /// (<c>_lastFullFieldFrame</c> / <c>_lastFullIntensityFrame</c>), or at least the picture currently shown in+ /// the preview.+ /// </summary>private void UpdateExportButtons(){- bool canExport = this._paused || this._runner == null;- this.btnExportFieldFrame.Enabled = canExport && (this._lastFullFieldFrame != null || (this._picField != null && this._picField.Image != null));- this.btnExportIntensityFrame.Enabled = canExport && (this._lastFullIntensityFrame != null || (this._picIntensity != null && this._picIntensity.Image != null));+ bool canExport = _paused || _runner == null;+ btnExportFieldFrame.Enabled = canExport && (_lastFullFieldFrame != null || (_picField != null && _picField.Image != null));+ btnExportIntensityFrame.Enabled = canExport && (_lastFullIntensityFrame != null || (_picIntensity != null && _picIntensity.Image != null));}/// <summary>@@ -523,51 +608,52 @@ namespace _2D_wave_sim_V01/// </summary>private void btnPauzeResume_Click(object sender, EventArgs e){- if (this._runner == null || this._stopRequested)+ if (_runner == null || _stopRequested){return;}- if (this._paused)+ if (_paused){- this._paused = false;- this._simStatus = this._progressText;- this.ToolStripStatusLabel1.Text = "Simulation running...";- this._runner.ResumeRun();- this.tabMainFunctions.SelectedTab = this.tabViewer;+ _paused = false;+ _simStatus = _progressText;+ ToolStripStatusLabel1.Text = "Simulation running...";+ _runner.ResumeRun();+ // back to the Preview tab, so the user follows the simulation again+ tabMainFunctions.SelectedTab = tabViewer;}else{- this._paused = true;- this._simStatus = "paused - " + this._progressText;- this.ToolStripStatusLabel1.Text = "Simulation paused (press Resume to continue, or Stop to finish and save the videos)";- this._runner.PauseRun();+ _paused = true;+ _simStatus = "paused - " + _progressText;+ ToolStripStatusLabel1.Text = "Simulation paused (press Resume to continue, or Stop to finish and save the videos)";+ _runner.PauseRun();}- this.UpdateRunButtons();- this.UpdateTitle();+ UpdateRunButtons();+ UpdateTitle();}/// <summary>Shows the Configuration tab.</summary>private void btnGotoConfiguration_Click(object sender, EventArgs e){- this.tabMainFunctions.SelectedTab = this.tabConfiguration;+ tabMainFunctions.SelectedTab = tabConfiguration;}/// <summary>Shows the Sources tab.</summary>private void btnGotoSources_Click(object sender, EventArgs e){- this.tabMainFunctions.SelectedTab = this.tabSourceList;+ tabMainFunctions.SelectedTab = tabSourceList;}/// <summary>Shows the Probes tab.</summary>private void btnGotoProbes_Click(object sender, EventArgs e){- this.tabMainFunctions.SelectedTab = this.tabProbeList;+ tabMainFunctions.SelectedTab = tabProbeList;}/// <summary>Shows the viewer tab.</summary>private void btnGotoPreview_Click(object sender, EventArgs e){- this.tabMainFunctions.SelectedTab = this.tabViewer;+ tabMainFunctions.SelectedTab = tabViewer;}/// <summary>@@ -576,28 +662,39 @@ namespace _2D_wave_sim_V01/// </summary>private void RequestStop(){- if (this._runner == null || this._stopRequested)+ if (_runner == null || _stopRequested){return;}- this._stopRequested = true;- this._paused = false;- this._runner.Cancel();- this.btnStartSimulation.Enabled = false;- this.btnStartSimulation.Text = "Stopping...";- this._simStatus = "stopping...";- this.ToolStripStatusLabel1.Text = "Stopping the simulation and closing the video files...";- this.UpdateRunButtons();- this.UpdateTitle();+ _stopRequested = true;+ _paused = false;+ _runner.Cancel();+ btnStartSimulation.Enabled = false;+ btnStartSimulation.Text = "Stopping...";+ _simStatus = "stopping...";+ ToolStripStatusLabel1.Text = "Stopping the simulation and closing the video files...";+ UpdateRunButtons();+ UpdateTitle();}- /// <summary>Greys the pause button when it cannot be used, sets its Pause / Resume caption and refreshes the export buttons.</summary>+ /// <summary>+ /// Greys the pause button when it cannot be used, sets its Pause / Resume caption and refreshes the export+ /// buttons. The pause button on the Preview tab is only usable while a simulation runs.+ /// <c>btnStartSimulation</c> is also the stop/restart button (see its own Click handler) and keeps its own+ /// Text/Enabled state (<see cref="RequestStop"/>, <see cref="StartSimulation"/>,+ /// <see cref="OnSimulationFinished"/>) - there used to be a separate <c>btnStopSimulation</c> for that,+ /// removed as redundant once <c>btnStartSimulation</c> started doing double duty.+ /// </summary>private void UpdateRunButtons(){- bool canPause = this._runner != null && !this._stopRequested;- this.btnPauzeResume.ForeColor = (canPause ? SystemColors.ControlText : Color.Gray);- this.btnPauzeResume.Text = (this._paused ? "Resume simulation" : "Pause simulation");- this.UpdateExportButtons();+ bool canPause = _runner != null && !_stopRequested;+ // Not actually disabling the button here: with its custom Azure BackColor, Windows' own disabled-button+ // rendering draws the text with a strange two-tone (etched) effect instead of plain gray. So the button+ // stays enabled and its color is set by hand instead - btnPauzeResume_Click already ignores clicks while+ // no simulation is running, so behaviorally it is still "disabled".+ btnPauzeResume.ForeColor = (canPause ? SystemColors.ControlText : Color.Gray);+ btnPauzeResume.Text = (_paused ? "Resume simulation" : "Pause simulation");+ UpdateExportButtons();}/// <summary>Shows <paramref name="message"/> in a "Start simulation" message box.</summary>@@ -608,34 +705,36 @@ namespace _2D_wave_sim_V01/// <summary>/// Validates every simulation control and copies it into <c>_simulation</c> (and the image source scale into- /// <c>_scene</c>) just before a run, regardless of <c>_loadingSim</c>.+ /// <c>_scene</c>) just before a run, regardless of <c>_loadingSim</c>, so the run always uses what is on the+ /// screen (also a value that was typed in but not confirmed yet is used - that is what the <c>Validate()</c>+ /// calls are for)./// </summary>private void ReadSimulationControls(){- this.numVisualizeEvery.Validate();- this.numFieldScaling.Validate();- this.numIntensityScaling.Validate();- this.numFieldScaling2.Validate();- this.numIntensityScaling2.Validate();- this.numOffsetField.Validate();- this.numOffsetIntensity.Validate();- this.numQuality.Validate();- this.numScaleImageSource.Validate();- this.numTimeDecayFactor.Validate();- this._simulation.VisualizeEvery = Convert.ToInt32(this.numVisualizeEvery.Value);- this._simulation.FieldBrightness = Convert.ToDouble(this.numFieldScaling.Value);- this._simulation.IntensityBrightness = Convert.ToDouble(this.numIntensityScaling.Value);- this._simulation.FieldBlackLevel = Convert.ToDouble(this.numOffsetField.Value);- this._simulation.IntensityBlackLevel = Convert.ToDouble(this.numOffsetIntensity.Value);- this._simulation.VideoQuality = Convert.ToInt32(this.numQuality.Value);- this._simulation.TimeDecayFactor = Convert.ToDouble(this.numTimeDecayFactor.Value);- this._simulation.ExportField = this.chkExportVideoField.Checked;- this._simulation.ExportIntensity = this.chkExportVideoIntensity.Checked;- this._simulation.PreviewField = this.chkPreviewVideoField.Checked;- this._simulation.PreviewIntensity = this.chkPreviewVideoIntensity.Checked;- this._simulation.UseGpu = this.chkUseGPU.Checked;- this._simulation.Use4thOrderLaplacian = this.chkUse4thOrderLaplacian.Checked;- this._scene.ImageSourceScale = Convert.ToDouble(this.numScaleImageSource.Value);+ numVisualizeEvery.Validate();+ numFieldScaling.Validate();+ numIntensityScaling.Validate();+ numFieldScaling2.Validate();+ numIntensityScaling2.Validate();+ numOffsetField.Validate();+ numOffsetIntensity.Validate();+ numQuality.Validate();+ numScaleImageSource.Validate();+ numTimeDecayFactor.Validate();+ _simulation.VisualizeEvery = Convert.ToInt32(numVisualizeEvery.Value);+ _simulation.FieldBrightness = Convert.ToDouble(numFieldScaling.Value);+ _simulation.IntensityBrightness = Convert.ToDouble(numIntensityScaling.Value);+ _simulation.FieldBlackLevel = Convert.ToDouble(numOffsetField.Value);+ _simulation.IntensityBlackLevel = Convert.ToDouble(numOffsetIntensity.Value);+ _simulation.VideoQuality = Convert.ToInt32(numQuality.Value);+ _simulation.TimeDecayFactor = Convert.ToDouble(numTimeDecayFactor.Value);+ _simulation.ExportField = chkExportVideoField.Checked;+ _simulation.ExportIntensity = chkExportVideoIntensity.Checked;+ _simulation.PreviewField = chkPreviewVideoField.Checked;+ _simulation.PreviewIntensity = chkPreviewVideoIntensity.Checked;+ _simulation.UseGpu = chkUseGPU.Checked;+ _simulation.Use4thOrderLaplacian = chkUse4thOrderLaplacian.Checked;+ _scene.ImageSourceScale = Convert.ToDouble(numScaleImageSource.Value);}/// <summary>@@ -645,72 +744,77 @@ namespace _2D_wave_sim_V01/// </summary>private void StartSimulation(){- this.ReadSimulationControls();- SimulationSettings settings = this._simulation;+ ReadSimulationControls();+ SimulationSettings settings = _simulation;bool wantField = settings.ExportField || settings.PreviewField;bool wantIntensity = settings.ExportIntensity || settings.PreviewIntensity;bool exporting = settings.ExportField || settings.ExportIntensity;bool previewing = settings.PreviewField || settings.PreviewIntensity;if (!wantField && !wantIntensity){- this.ShowSimulationProblem("Nothing to do: tick at least one of the export or preview options.");+ ShowSimulationProblem("Nothing to do: tick at least one of the export or preview options.");return;}- settings.Steps = Convert.ToInt32(this.numSimulationSteps.Value);- if (exporting && this._project == null)+ // numSimulationSteps (a NumericUpDown) never holds an out-of-range or non-integer value, so unlike the old+ // cmbSimulationSteps combo box this needs no parsing/validation here+ settings.Steps = Convert.ToInt32(numSimulationSteps.Value);++ // the videos are written in the output folder of the project, so the project has to exist on disk+ if (exporting && _project == null){DialogResult saveAnswer = MessageBox.Show(this, "The videos are saved in the output folder of the project, so the project must be saved first.\r\n\r\nSave the project now?", "Start simulation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);if (saveAnswer != DialogResult.Yes){return;}- if (!this.SaveProject())+ if (!SaveProject()){return;}// Saving replaces _simulation (SetCurrentProject reloads it from the config), so re-fetch it.- settings = this._simulation;+ settings = _simulation;}- Size canvas = this.EffectiveCanvas();+ Size canvas = EffectiveCanvas();if (canvas.Width <= 0){- this.ShowSimulationProblem("There is no scene yet: load a scene image in the Scene properties, or define a canvas size.");+ ShowSimulationProblem("There is no scene yet: load a scene image in the Scene properties, or define a canvas size.");return;}int dampingEdge = 0;- if (this._scene.DampingEdgeEnabled)+ if (_scene.DampingEdgeEnabled){- string dampingProblem = this.DampingProblem(this.txtDampingEdgeSize.Text, ref dampingEdge);+ string dampingProblem = DampingProblem(txtDampingEdgeSize.Text, ref dampingEdge);if (dampingProblem.Length > 0){- this.ShowSimulationProblem("The damping edge cannot be used: " + dampingProblem);- this.txtDampingEdgeSize.Focus();+ ShowSimulationProblem("The damping edge cannot be used: " + dampingProblem);+ txtDampingEdgeSize.Focus();return;}}- bool useSources = this._scene.UseSources;- bool hasImageSources = this._scene.UseImage && useSources && SceneData.CountSources(this._sceneImage) > 0;- bool hasObjectSources = this._scene.UseObjectSources && this._sources.Count > 0;+ // without any source (image or object) nothing happens+ bool useSources = _scene.UseSources;+ bool hasImageSources = _scene.UseImage && useSources && SceneData.CountSources(_sceneImage) > 0;+ bool hasObjectSources = _scene.UseObjectSources && _sources.Count > 0;string noSourcesWarning = "";if (!hasImageSources && !hasObjectSources){List<string> reasons = new List<string>();- if (this._scene.UseImage)+ if (_scene.UseImage){if (!useSources){reasons.Add("image sources are switched off in the Scene properties");}- else if (SceneData.CountSources(this._sceneImage) == 0)+ else if (SceneData.CountSources(_sceneImage) == 0){reasons.Add("the scene image has no sources (no pixels with a green value above 0)");}}- if (!this._scene.UseObjectSources)+ if (!_scene.UseObjectSources){reasons.Add("object sources are switched off in the Scene properties");}- else if (this._sources.Count == 0)+ else if (_sources.Count == 0){reasons.Add("there are no object sources yet (add one on the Sources tab)");}@@ -724,64 +828,70 @@ namespace _2D_wave_sim_V01return;}}+ // color tablesint[] fieldLut = null;int[] intensityLut = null;if (wantField){- ColorScheme fieldScheme = this.FindScheme(settings.FieldColorScheme, "field");+ ColorScheme fieldScheme = FindScheme(settings.FieldColorScheme, ColorScheme.SchemeTypeField);if (fieldScheme == null){- this.ShowSimulationProblem("Choose a color scheme for the field first.");- this.cmbFieldColorScheme.Focus();+ ShowSimulationProblem("Choose a color scheme for the field first.");+ cmbFieldColorScheme.Focus();return;}fieldLut = ColorLut.Build(fieldScheme, false, settings.FieldBlackLevel, false, false).Argb;}if (wantIntensity){- ColorScheme intensityScheme = this.FindScheme(settings.IntensityColorScheme, "intensity");+ ColorScheme intensityScheme = FindScheme(settings.IntensityColorScheme, ColorScheme.SchemeTypeIntensity);if (intensityScheme == null){- this.ShowSimulationProblem("Choose a color scheme for the intensity first.");- this.cmbIntensityColorScheme.Focus();+ ShowSimulationProblem("Choose a color scheme for the intensity first.");+ cmbIntensityColorScheme.Focus();return;}intensityLut = ColorLut.Build(intensityScheme, false, settings.IntensityBlackLevel, false, false).Argb;}+ // the job: the runner works on copies, so the settings can be edited while it runsSimulationJob job = new SimulationJob();- if (this._scene.UseImage)+ if (_scene.UseImage){- job.Image = new Bitmap(this._sceneImage);+ job.Image = new Bitmap(_sceneImage);}else{job.Width = canvas.Width;job.Height = canvas.Height;- job.BackgroundRefractiveIndex = this._scene.BackgroundRefractiveIndex;+ job.BackgroundRefractiveIndex = _scene.BackgroundRefractiveIndex;}job.UseSources = useSources;- job.SourceAmplitude = this._scene.ImageSourceScale;+ job.SourceAmplitude = _scene.ImageSourceScale;job.DampingEdge = dampingEdge;job.Settings = settings.Clone();job.FieldLut = fieldLut;job.IntensityLut = intensityLut;- this._lastFieldLut = fieldLut;- this._lastIntensityLut = intensityLut;- job.PreviewWidth = Math.Max(16, Math.Min(this.pnlPreviewField.ClientSize.Width, this.pnlPreviewIntensity.ClientSize.Width));- job.PreviewHeight = Math.Max(16, Math.Min(this.pnlPreviewField.ClientSize.Height, this.pnlPreviewIntensity.ClientSize.Height));- job.Probes = this.ProbesForRun();- job.ObjectSources = this.SourcesForRun();- job.FieldOverlayGain = this.FieldOverlayGain();- job.IntensityOverlayGain = this.IntensityOverlayGain();- if (exporting && this._glowEdgesImage != null && (job.FieldOverlayGain > 0.0 || job.IntensityOverlayGain > 0.0))- {- job.GlowOverlay = new Bitmap(this._glowEdgesImage);+ _lastFieldLut = fieldLut;+ _lastIntensityLut = intensityLut;+ job.PreviewWidth = Math.Max(16, Math.Min(pnlPreviewField.ClientSize.Width, pnlPreviewIntensity.ClientSize.Width));+ job.PreviewHeight = Math.Max(16, Math.Min(pnlPreviewField.ClientSize.Height, pnlPreviewIntensity.ClientSize.Height));+ job.Probes = ProbesForRun();+ job.ObjectSources = SourcesForRun();++ // the glow-edges overlay (Viewer tab) is only ever needed by the runner to bake into an exported video -+ // the live preview blends its own copy in locally (ShowPreview/ComposeGlowOverlay), which can track the+ // checkbox/brightness box live while this, like Settings, is frozen at the start of the run+ job.FieldOverlayGain = FieldOverlayGain();+ job.IntensityOverlayGain = IntensityOverlayGain();+ if (exporting && _glowEdgesImage != null && (job.FieldOverlayGain > 0.0 || job.IntensityOverlayGain > 0.0))+ {+ job.GlowOverlay = new Bitmap(_glowEdgesImage);}if (exporting){try{- Directory.CreateDirectory(this._project.OutputVideoFolder);+ Directory.CreateDirectory(_project.OutputVideoFolder);}catch (Exception ex){@@ -793,49 +903,49 @@ namespace _2D_wave_sim_V01{job.GlowOverlay.Dispose();}- this.ShowSimulationProblem("The output folder could not be created:\r\n" + this._project.OutputVideoFolder + "\r\n\r\n" + ex.Message);+ ShowSimulationProblem("The output folder could not be created:\r\n" + _project.OutputVideoFolder + "\r\n\r\n" + ex.Message);return;}- string suffix = this.NextNumericSuffix(this._project.OutputVideoFolder).ToString("D4", CultureInfo.InvariantCulture);+ string suffix = NextNumericSuffix(_project.OutputVideoFolder).ToString("D4", CultureInfo.InvariantCulture);if (settings.ExportField){- job.FieldVideoPath = Path.Combine(this._project.OutputVideoFolder, this._project.Name + "_field_" + suffix + ".mp4");+ job.FieldVideoPath = Path.Combine(_project.OutputVideoFolder, _project.Name + "_field_" + suffix + ".mp4");}if (settings.ExportIntensity){- job.IntensityVideoPath = Path.Combine(this._project.OutputVideoFolder, this._project.Name + "_intensity_" + suffix + ".mp4");+ job.IntensityVideoPath = Path.Combine(_project.OutputVideoFolder, _project.Name + "_intensity_" + suffix + ".mp4");}}- this.ClearPreviews();- this.BeginProbeRun(job.Probes, canvas, settings.Steps);- this._fieldVideoFile = "";- this._intensityVideoFile = "";- this.UpdateVideoButtons();- this._runInfo = "Field: brightness " + settings.FieldBrightness.ToString("0.0#", CultureInfo.CurrentCulture)+ ClearPreviews();+ BeginProbeRun(job.Probes, canvas, settings.Steps);+ _fieldVideoFile = "";+ _intensityVideoFile = "";+ UpdateVideoButtons();+ _runInfo = "Field: brightness " + settings.FieldBrightness.ToString("0.0#", CultureInfo.CurrentCulture)+ ", offset " + settings.FieldBlackLevel.ToString("0.0#", CultureInfo.CurrentCulture)+ "\r\nIntensity: brightness " + settings.IntensityBrightness.ToString("0.0#", CultureInfo.CurrentCulture)+ ", offset " + settings.IntensityBlackLevel.ToString("0.0#", CultureInfo.CurrentCulture)- + "\r\nImage source scale: " + this._scene.ImageSourceScale.ToString("0.0#", CultureInfo.CurrentCulture);+ + "\r\nImage source scale: " + _scene.ImageSourceScale.ToString("0.0#", CultureInfo.CurrentCulture);if (previewing){- this.tabMainFunctions.SelectedTab = this.tabViewer;+ tabMainFunctions.SelectedTab = tabViewer;}SimulationRunner runner = new SimulationRunner(job);- runner.ProgressChanged += (done, total) => this.PostToUi(() => this.ShowProgress(runner, done, total));- runner.EngineReady += (description, note) => this.PostToUi(() => this.ShowEngine(runner, description, note));- runner.ProbesUpdated += update => this.PostToUi(() => this.ShowProbeSamples(runner, update));- runner.PreviewReady += (isField, frame) => this.PostToUi(() => this.ShowPreview(runner, isField, frame));- runner.Finished += result => this.PostToUi(() => this.OnSimulationFinished(runner, result));- this._runner = runner;- this.btnStartSimulation.Text = "Stop Simulation";- this._simStatus = "starting...";- this._progressText = "starting...";- this._paused = false;- this._stopRequested = false;- this.UpdateRunButtons();- this.ToolStripStatusLabel1.Text = "Simulation running...";- this.ToolStripStatusLabel1.ToolTipText = "";- this.UpdateTitle();+ runner.ProgressChanged += (done, total) => PostToUi(() => ShowProgress(runner, done, total));+ runner.EngineReady += (description, note) => PostToUi(() => ShowEngine(runner, description, note));+ runner.ProbesUpdated += update => PostToUi(() => ShowProbeSamples(runner, update));+ runner.PreviewReady += (isField, frame) => PostToUi(() => ShowPreview(runner, isField, frame));+ runner.Finished += result => PostToUi(() => OnSimulationFinished(runner, result));+ _runner = runner;+ btnStartSimulation.Text = "Stop Simulation";+ _simStatus = "starting...";+ _progressText = "starting...";+ _paused = false;+ _stopRequested = false;+ UpdateRunButtons();+ ToolStripStatusLabel1.Text = "Simulation running...";+ ToolStripStatusLabel1.ToolTipText = "";+ UpdateTitle();runner.Start();}@@ -866,21 +976,21 @@ namespace _2D_wave_sim_V01private void ShowProgress(SimulationRunner runner, int done, int total){// A late progress event from the worker must not overwrite the "stopping..." status set by RequestStop.- if (runner != this._runner || string.CompareOrdinal(this._simStatus, "stopping...") == 0)+ if (runner != _runner || string.CompareOrdinal(_simStatus, "stopping...") == 0){return;}- this._lastStepsDone = done;+ _lastStepsDone = done;int percent = (int)(100L * done / Math.Max(1, total)); // long: 100 * steps can exceed int.MaxValue- this._progressText = "step " + done.ToString("N0", CultureInfo.CurrentCulture) + " of " + total.ToString("N0", CultureInfo.CurrentCulture) + " (" + percent.ToString(CultureInfo.InvariantCulture) + "%)";- this._simStatus = (this._paused ? "paused - " : "") + this._progressText;- this.UpdateTitle();+ _progressText = "step " + done.ToString("N0", CultureInfo.CurrentCulture) + " of " + total.ToString("N0", CultureInfo.CurrentCulture) + " (" + percent.ToString(CultureInfo.InvariantCulture) + "%)";+ _simStatus = (_paused ? "paused - " : "") + _progressText;+ UpdateTitle();}/// <summary>UI thread (via <see cref="PostToUi"/>): shows which engine the runner picked, plus the fallback note, in the status bar.</summary>private void ShowEngine(SimulationRunner runner, string description, string note){- if (runner != this._runner || base.IsDisposed)+ if (runner != _runner || base.IsDisposed){return;}@@ -889,8 +999,8 @@ namespace _2D_wave_sim_V01{status = status + " - " + note;}- this.ToolStripStatusLabel1.Text = status;- this.ToolStripStatusLabel1.ToolTipText = status;+ ToolStripStatusLabel1.Text = status;+ ToolStripStatusLabel1.ToolTipText = status;}/// <summary>@@ -900,16 +1010,16 @@ namespace _2D_wave_sim_V01/// </summary>private void ShowPreview(SimulationRunner runner, bool isField, Bitmap frame){- if (runner != this._runner || base.IsDisposed)+ if (runner != _runner || base.IsDisposed){frame.Dispose();runner.PreviewShown();return;}- PictureBox target = (isField ? this._picField : this._picIntensity);- double overlayGain = (isField ? this.FieldOverlayGain() : this.IntensityOverlayGain());- this.SetPreviewFrame(target, frame, overlayGain);- this.UpdateCopyButtons();+ PictureBox target = (isField ? _picField : _picIntensity);+ double overlayGain = (isField ? FieldOverlayGain() : IntensityOverlayGain());+ SetPreviewFrame(target, frame, overlayGain);+ UpdateCopyButtons();runner.PreviewShown();}@@ -920,36 +1030,38 @@ namespace _2D_wave_sim_V01/// </summary>private void OnSimulationFinished(SimulationRunner runner, SimulationResult result){- if (runner != this._runner || base.IsDisposed)+ if (runner != _runner || base.IsDisposed){return;}- this._runner = null;- this._hasRun = true;- this._paused = false;- this._stopRequested = false;- this._lastStepsDone = result.StepsDone;- this.UpdateRunButtons();- this._simStatus = "";- this.btnStartSimulation.Text = "Start Simulation";- this.btnStartSimulation.Enabled = true;- this.UpdateTitle();- this._fieldVideoFile = result.FieldFile;- this._intensityVideoFile = result.IntensityFile;- this.UpdateVideoButtons();- Bitmap previousFieldFrame = this._lastFullFieldFrame;- this._lastFullFieldFrame = result.LastFieldFrame;+ _runner = null;+ _hasRun = true;+ _paused = false;+ _stopRequested = false;+ _lastStepsDone = result.StepsDone;+ UpdateRunButtons();+ _simStatus = "";+ btnStartSimulation.Text = "Start Simulation";+ btnStartSimulation.Enabled = true;+ UpdateTitle();+ _fieldVideoFile = result.FieldFile;+ _intensityVideoFile = result.IntensityFile;+ UpdateVideoButtons();++ // a full-resolution snapshot of the last frame, for a still export once nothing is running any more+ Bitmap previousFieldFrame = _lastFullFieldFrame;+ _lastFullFieldFrame = result.LastFieldFrame;if (previousFieldFrame != null){previousFieldFrame.Dispose();}- Bitmap previousIntensityFrame = this._lastFullIntensityFrame;- this._lastFullIntensityFrame = result.LastIntensityFrame;+ Bitmap previousIntensityFrame = _lastFullIntensityFrame;+ _lastFullIntensityFrame = result.LastIntensityFrame;if (previousIntensityFrame != null){previousIntensityFrame.Dispose();}- this.UpdateExportButtons();+ UpdateExportButtons();string elapsed = result.Elapsed.ToString("hh\\:mm\\:ss", CultureInfo.InvariantCulture);string details = "";if (result.Files.Count > 0)@@ -972,8 +1084,10 @@ namespace _2D_wave_sim_V01details = details + "\r\n" + result.EngineNote;}}- details = details + "\r\n\r\n" + this._runInfo;+ details = details + "\r\n\r\n" + _runInfo;string stepsText = result.StepsDone.ToString("N0", CultureInfo.CurrentCulture);++ // the summary goes in the status bar (the details in its tooltip); only a failure gets a message boxstring summary;switch (result.Status){@@ -1012,8 +1126,8 @@ namespace _2D_wave_sim_V01{summary += " - MP4 (H.264) was not available, the videos are .avi files";}- this.ToolStripStatusLabel1.Text = summary;- this.ToolStripStatusLabel1.ToolTipText = summary + details;+ ToolStripStatusLabel1.Text = summary;+ ToolStripStatusLabel1.ToolTipText = summary + details;if (result.Status == SimulationStatus.Failed){MessageBox.Show(this, "The simulation failed after " + stepsText + " steps:\r\n\r\n" + result.Message + details, "Simulation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);@@ -1023,20 +1137,20 @@ namespace _2D_wave_sim_V01/// <summary>Enables the "view video" buttons when the last run's video files still exist.</summary>private void UpdateVideoButtons(){- this.btnViewFieldVideo.Enabled = this._fieldVideoFile.Length > 0 && File.Exists(this._fieldVideoFile);- this.btnViewIntensityVideo.Enabled = this._intensityVideoFile.Length > 0 && File.Exists(this._intensityVideoFile);+ btnViewFieldVideo.Enabled = _fieldVideoFile.Length > 0 && File.Exists(_fieldVideoFile);+ btnViewIntensityVideo.Enabled = _intensityVideoFile.Length > 0 && File.Exists(_intensityVideoFile);}/// <summary>Opens the last field video in the default media player.</summary>private void btnViewFieldVideo_Click(object sender, EventArgs e){- this.OpenVideo(this._fieldVideoFile);+ OpenVideo(_fieldVideoFile);}/// <summary>Opens the last intensity video in the default media player.</summary>private void btnViewIntensityVideo_Click(object sender, EventArgs e){- this.OpenVideo(this._intensityVideoFile);+ OpenVideo(_intensityVideoFile);}/// <summary>Launches <paramref name="videoFile"/> with the shell's default player; tells the user when the file has gone or cannot be opened.</summary>@@ -1045,7 +1159,7 @@ namespace _2D_wave_sim_V01if (videoFile.Length == 0 || !File.Exists(videoFile)){MessageBox.Show(this, "The video file does not exist (any more):\r\n" + videoFile, "Video", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);- this.UpdateVideoButtons();+ UpdateVideoButtons();return;}try@@ -1064,25 +1178,25 @@ namespace _2D_wave_sim_V01/// <summary>Opens the project's video folder in Explorer.</summary>private void btnOpenVideoFolder_Click(object sender, EventArgs e){- this.OpenVideoFolder();+ OpenVideoFolder();}/// <summary>Opens the project's exported-frames folder in Explorer.</summary>private void btnOpenImageFolder_Click(object sender, EventArgs e){- this.OpenFramesFolder();+ OpenFramesFolder();}/// <summary>Saves the current or last field frame as a PNG.</summary>private void btnExportFieldFrame_Click(object sender, EventArgs e){- this.ExportFrame(true);+ ExportFrame(true);}/// <summary>Saves the current or last intensity frame as a PNG.</summary>private void btnExportIntensityFrame_Click(object sender, EventArgs e){- this.ExportFrame(false);+ ExportFrame(false);}/// <summary>@@ -1095,16 +1209,16 @@ namespace _2D_wave_sim_V01{Bitmap frame = null;bool ownsFrame = false;- if (this._runner != null && this._paused)+ if (_runner != null && _paused){- int[] lut = (isField ? this._lastFieldLut : this._lastIntensityLut);- float brightness = (float)(isField ? this._simulation.FieldBrightness : this._simulation.IntensityBrightness);- frame = this._runner.RenderCurrentFrame(isField, lut, brightness);+ int[] lut = (isField ? _lastFieldLut : _lastIntensityLut);+ float brightness = (float)(isField ? _simulation.FieldBrightness : _simulation.IntensityBrightness);+ frame = _runner.RenderCurrentFrame(isField, lut, brightness);ownsFrame = true;}if (frame == null){- frame = (isField ? this._lastFullFieldFrame : this._lastFullIntensityFrame);+ frame = (isField ? _lastFullFieldFrame : _lastFullIntensityFrame);}if (frame == null){@@ -1113,7 +1227,7 @@ namespace _2D_wave_sim_V01}try{- Directory.CreateDirectory(this._project.OutputFramesFolder);+ Directory.CreateDirectory(_project.OutputFramesFolder);}catch (Exception ex){@@ -1121,25 +1235,25 @@ namespace _2D_wave_sim_V01{frame.Dispose();}- MessageBox.Show(this, "The output folder could not be created:\r\n" + this._project.OutputFramesFolder + "\r\n\r\n" + ex.Message, "Export frame", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ MessageBox.Show(this, "The output folder could not be created:\r\n" + _project.OutputFramesFolder + "\r\n\r\n" + ex.Message, "Export frame", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);return;}string kind = (isField ? "field" : "intensity");- double overlayGain = (isField ? this.FieldOverlayGain() : this.IntensityOverlayGain());+ double overlayGain = (isField ? FieldOverlayGain() : IntensityOverlayGain());Bitmap output = frame;bool ownsOutput = false;- if (overlayGain > 0.0 && this._glowEdgesImage != null)+ if (overlayGain > 0.0 && _glowEdgesImage != null){- output = this.ComposeGlowOverlay(frame, overlayGain);+ output = ComposeGlowOverlay(frame, overlayGain);ownsOutput = true;}- string suffix = this.NextNumericSuffix(this._project.OutputFramesFolder).ToString("D4", CultureInfo.InvariantCulture);- string fileName = this._project.Name + "_" + kind + "_frame" + this._lastStepsDone.ToString(CultureInfo.InvariantCulture) + "_" + suffix + ".png";- string path = Path.Combine(this._project.OutputFramesFolder, fileName);+ string suffix = NextNumericSuffix(_project.OutputFramesFolder).ToString("D4", CultureInfo.InvariantCulture);+ string fileName = _project.Name + "_" + kind + "_frame" + _lastStepsDone.ToString(CultureInfo.InvariantCulture) + "_" + suffix + ".png";+ string path = Path.Combine(_project.OutputFramesFolder, fileName);try{output.Save(path, ImageFormat.Png);- this.ToolStripStatusLabel1.Text = "Frame exported: " + fileName;+ ToolStripStatusLabel1.Text = "Frame exported: " + fileName;}catch (Exception ex){@@ -1158,7 +1272,14 @@ namespace _2D_wave_sim_V01}}- /// <summary>Returns one more than the highest 4-digit numeric suffix among the file names in <paramref name="folder"/>.</summary>+ /// <summary>+ /// Next available 4-digit numeric filename suffix for a file saved into <paramref name="folder"/>: the highest+ /// existing file in the folder whose name (before the extension) ends in exactly 4 digits, plus 1 - starts at+ /// 1 when there is no such file yet. Used for exported frames (<see cref="ExportFrame"/>) and videos+ /// (<see cref="StartSimulation"/>) instead of the previous date/time stamp, which was found to make file+ /// names too long. Formats with "D4" (e.g. "0001"), growing past 4 digits rather than wrapping once the+ /// count passes 9999.+ /// </summary>private int NextNumericSuffix(string folder){int highest = 0;@@ -1181,10 +1302,15 @@ namespace _2D_wave_sim_V01return highest + 1;}- /// <summary>Opens the project's video folder in Explorer (details view); reports when there is no project.</summary>+ /// <summary>+ /// Opens the project's video output folder in Windows Explorer - which already shows video thumbnails and+ /// lets the files be renamed or deleted there, so there is no need to build a picker of our own for that.+ /// Opened in "Details" view (see <see cref="OpenFolderInExplorer"/>) - more useful than thumbnails for a+ /// folder of video files. Reports when there is no project.+ /// </summary>private void OpenVideoFolder(){- string folder = ((this._project == null) ? "" : this._project.OutputVideoFolder);+ string folder = ((_project == null) ? "" : _project.OutputVideoFolder);if (folder.Length == 0){MessageBox.Show(this, "There is no project open yet.", "Open video folder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);@@ -1192,7 +1318,8 @@ namespace _2D_wave_sim_V01}try{- this.OpenFolderInExplorer(folder, 4);+ // so the folder can be opened even before any video has been exported+ OpenFolderInExplorer(folder, FVM_DETAILS);}catch (Exception ex){@@ -1200,10 +1327,15 @@ namespace _2D_wave_sim_V01}}- /// <summary>Opens the project's exported-frames folder in Explorer (icon view); reports when there is no project.</summary>+ /// <summary>+ /// Opens the project's output frames folder (<c>btnOpenImageFolder</c> on the Preview tab) in Windows+ /// Explorer, the same way <see cref="OpenVideoFolder"/> does for the video folder - but in "Large icons"+ /// view (see <see cref="OpenFolderInExplorer"/>), which shows thumbnails of the exported images. Reports+ /// when there is no project.+ /// </summary>private void OpenFramesFolder(){- string folder = ((this._project == null) ? "" : this._project.OutputFramesFolder);+ string folder = ((_project == null) ? "" : _project.OutputFramesFolder);if (folder.Length == 0){MessageBox.Show(this, "There is no project open yet.", "Open image folder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);@@ -1211,7 +1343,8 @@ namespace _2D_wave_sim_V01}try{- this.OpenFolderInExplorer(folder, 1);+ // so the folder can be opened even before any frame has been exported+ OpenFolderInExplorer(folder, FVM_ICON);}catch (Exception ex){@@ -1219,9 +1352,25 @@ namespace _2D_wave_sim_V01}}- /// <summary>Creates <paramref name="folder"/> if needed, opens it in Explorer and tries to apply <paramref name="viewMode"/>; view-mode failures are ignored.</summary>+ /// <summary>+ /// Creates <paramref name="folder"/> if needed, opens it in Windows Explorer and tries to make that window use+ /// the given view mode (one of the <c>FVM_</c> constants in <c>Form1.cs</c>). Explorer has no command-line+ /// switch for this, so the folder is opened as before (explorer.exe on the path) and then, best-effort, the+ /// "Shell.Application" COM automation object is used to find the newly opened window for that exact folder+ /// and set its <c>Document.CurrentViewMode</c> (<see cref="SetExplorerWindowViewMode"/>). This uses late+ /// binding via reflection rather than a direct COM reference, since adding a COM reference to the project+ /// for this alone is more trouble than it is worth.+ /// <para>+ /// This is not fully reliable: if a window for the folder is already open, Explorer reuses it instead of+ /// opening a new one (so its view stays whatever it already was), and Explorer separately remembers, per+ /// folder, whatever view the user leaves it in afterwards - so this only really matters the first time (or+ /// after Explorer has forgotten it). Either way the folder itself always opens; only the requested view can+ /// silently fail to apply, which is why every failure in the view-mode step is swallowed rather than shown+ /// to the user.+ /// </para>+ /// </summary>/// <param name="folder">Folder to open; created when missing (that may throw, unlike the view-mode step).</param>- /// <param name="viewMode">Explorer FOLDERVIEWMODE value: 1 = icons, 4 = details.</param>+ /// <param name="viewMode">Explorer FOLDERVIEWMODE value: <see cref="FVM_ICON"/> or <see cref="FVM_DETAILS"/>.</param>private void OpenFolderInExplorer(string folder, int viewMode){Directory.CreateDirectory(folder);@@ -1231,21 +1380,24 @@ namespace _2D_wave_sim_V01});try{- this.SetExplorerWindowViewMode(folder, viewMode);+ SetExplorerWindowViewMode(folder, viewMode);}catch (Exception){+ // best effort only - the folder is already open regardless of whether this succeeds}}/// <summary>/// Finds the Explorer window that was just opened on <paramref name="folder"/> (polling up to 8 times)- /// through the Shell.Application COM automation object (late bound) and sets its view mode (e.g. 1 = icons, 4 = details).- /// Runs on the UI thread and sleeps 120 ms between polls, so it can block the UI for about a second when the window never shows up.+ /// through the Shell.Application COM automation object (late bound) and sets its view mode+ /// (<see cref="FVM_ICON"/> or <see cref="FVM_DETAILS"/>); see <see cref="OpenFolderInExplorer"/> for why and+ /// for the caveats. Runs on the UI thread and sleeps 120 ms between polls, so it can block the UI for about+ /// a second when the window never shows up./// </summary>private void SetExplorerWindowViewMode(string folder, int viewMode){- string target = Path.GetFullPath(folder).TrimEnd(new char[] { Path.DirectorySeparatorChar });+ string targetPath = Path.GetFullPath(folder).TrimEnd(new char[] { Path.DirectorySeparatorChar });Type shellType = Type.GetTypeFromProgID("Shell.Application");if (shellType == null){@@ -1254,20 +1406,23 @@ namespace _2D_wave_sim_V01object shell = Activator.CreateInstance(shellType);try{+ const BindingFlags memberFlags = BindingFlags.InvokeMethod | BindingFlags.GetProperty;++ // give the freshly launched Explorer window a moment to appearfor (int attempt = 1; attempt <= 8; attempt++){- object windows = shellType.InvokeMember("Windows", BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, shell, null);+ object windows = shellType.InvokeMember("Windows", memberFlags, null, shell, null);Type windowsType = windows.GetType();- int count = Convert.ToInt32(windowsType.InvokeMember("Count", BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, windows, null));+ int count = Convert.ToInt32(windowsType.InvokeMember("Count", memberFlags, null, windows, null));for (int i = 0; i < count; i++){- object window = windowsType.InvokeMember("Item", BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, windows, new object[] { i });+ object window = windowsType.InvokeMember("Item", memberFlags, null, windows, new object[] { i });if (window == null){continue;}Type windowType = window.GetType();- string locationUrl = windowType.InvokeMember("LocationURL", BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, window, null) as string;+ string locationUrl = windowType.InvokeMember("LocationURL", memberFlags, null, window, null) as string;if (string.IsNullOrEmpty(locationUrl)){continue;@@ -1281,9 +1436,9 @@ namespace _2D_wave_sim_V01{continue;}- if (string.Equals(windowPath, target, StringComparison.OrdinalIgnoreCase))+ if (string.Equals(windowPath, targetPath, StringComparison.OrdinalIgnoreCase)){- object document = windowType.InvokeMember("Document", BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, window, null);+ object document = windowType.InvokeMember("Document", memberFlags, null, window, null);if (document != null){document.GetType().InvokeMember("CurrentViewMode", BindingFlags.SetProperty, null, document, new object[] { viewMode });@@ -1306,7 +1461,7 @@ namespace _2D_wave_sim_V01/// </summary>private void ClearPreviews(){- foreach (PictureBox pictureBox in new PictureBox[] { this._picField, this._picIntensity })+ foreach (PictureBox pictureBox in new PictureBox[] { _picField, _picIntensity }){if (pictureBox == null){@@ -1325,19 +1480,26 @@ namespace _2D_wave_sim_V01tagged.Dispose();}}- if (this._lastFullFieldFrame != null)++ // a new run is starting - the cached last-frame snapshots are from the previous run, so drop them+ if (_lastFullFieldFrame != null){- this._lastFullFieldFrame.Dispose();+ _lastFullFieldFrame.Dispose();}- this._lastFullFieldFrame = null;- if (this._lastFullIntensityFrame != null)+ _lastFullFieldFrame = null;+ if (_lastFullIntensityFrame != null){- this._lastFullIntensityFrame.Dispose();+ _lastFullIntensityFrame.Dispose();}- this._lastFullIntensityFrame = null;- this.UpdateCopyButtons();+ _lastFullIntensityFrame = null;+ UpdateCopyButtons();}+ // grpProbe1_Enter/grpProbe2_Enter and Label21/Label22 Click are unused Designer-generated stubs (harmless, left+ // empty). The Pick button, the Sources combo boxes and Button1 (the Probes tab's "Import scene image", still+ // under its Designer default name) are wired in Form1.Sources.cs/Form1.Probes.cs instead, where the rest of+ // those tabs lives.+/// <summary>Wired by the designer to both probe group boxes; intentionally does nothing.</summary>private void grpProbe1_Enter(object sender, EventArgs e){@@ -1356,7 +1518,7 @@ namespace _2D_wave_sim_V01/// <summary>Saves the project (viewer-tab copy of the Save button).</summary>private void btnSaveConfiguration2_Click(object sender, EventArgs e){- this.SaveProject();+ SaveProject();}/// <summary>diff --git a/Wave_Dude_2D/Form1.Sources.cs b/Wave_Dude_2D/Form1.Sources.csindex 8b2d95d..28531e0 100644--- a/Wave_Dude_2D/Form1.Sources.cs+++ b/Wave_Dude_2D/Form1.Sources.cs@@ -16,98 +16,138 @@ namespace _2D_wave_sim_V01/// guards the list selection handler while the list is rebuilt. Everything here runs on/// the UI thread./// </summary>+ /// <remarks>+ /// <para>+ /// An object source is a point (or, for a composite source, an X-Y array of points) that drives+ /// the field directly, as opposed to the image-derived sources (the green channel of the scene+ /// image). Unlike an image source it has its own frequency, amplitude and phase, and it can be+ /// continuous or pulsed (on for a number of cycles, then off for a number of cycles). A composite+ /// source is a set of point sources built from the same base ("single source") parameters,+ /// optionally randomized per element.+ /// </para>+ /// <para>+ /// Editing a source is a two step process. First, <c>txtName</c>/<c>cmbMainType</c>/+ /// <c>grpSingleSource</c>/<c>grpComposite</c> describe the source; the position is typed or+ /// picked with the Pick button in the picture (a copy of a Preview tab picture, "Copy Image to+ /// probe and source tab"). A freshly created source has no position yet+ /// (<see cref="SourceSettings.HasPosition"/> is false): the picture shows no marker for it until+ /// one is picked or typed, so an unpositioned source is never mistaken for one at (0, 0) or+ /// wherever the numeric fields default to. Second, "Save source" resolves those parameters (for a+ /// composite source, including a fresh random draw when "Inherit + randomize" is chosen) into a+ /// fixed list of point-source elements (<c>_editing.Elements</c>), then adds the result to+ /// <c>lstSources</c> (a new source) or updates the selected one. Only saved sources are used in a+ /// simulation (when "Use object sources" is ticked in the scene properties): the engine always+ /// runs the already-generated element list, never re-randomizing, so a run is reproducible.+ /// </para>+ /// <para>+ /// Selecting a source in <c>lstSources</c> loads it straight into the editor (there is no separate+ /// Edit step/button). New and Copy load a (blank, respectively copied) source into the editor and+ /// clear the list selection; neither touches <c>lstSources</c> itself until Save is pressed, which+ /// adds or updates the entry.+ /// </para>+ /// </remarks>public partial class Form1{/// <summary>/// One-time set-up at form load: remembers the "Pick" button text and the save button- /// colour, sets the numeric input limits (positions 0..16383 canvas px, array sizes- /// 1..999 stepping by 2, spacings 0..16384 px), wires dirty tracking and the scene- /// picture events, switches the list to owner drawing and shows the initial source.+ /// colour, sets the numeric input limits (positions 0..<see cref="SceneSettings.MaxCanvasSize"/> - 1+ /// canvas px, array sizes 1..999 stepping by 2, spacings 0..<see cref="SceneSettings.MaxCanvasSize"/> px),+ /// wires dirty tracking and the scene picture events, switches the list to owner drawing and+ /// shows the initial source./// </summary>private void InitializeSourceControls(){- this._pickSourceButtonText = this.btnPickSourcePosition.Text;- this._sourceSaveButtonDefaultBackColor = this.btnSaveSource.BackColor;- this.WireSourceDirtyTracking(this.grpSourceDetails);- this.numSourcePositionX.DecimalPlaces = 0;- this.numSourcePositionX.Minimum = 0m;- this.numSourcePositionX.Maximum = 16383m;- this.numSourcePositionY.DecimalPlaces = 0;- this.numSourcePositionY.Minimum = 0m;- this.numSourcePositionY.Maximum = 16383m;- this.numArraySizeX.DecimalPlaces = 0;- this.numArraySizeX.Minimum = 1m;- this.numArraySizeX.Maximum = 999m;- this.numArraySizeX.Increment = 2m;- this.numArraySizeY.DecimalPlaces = 0;- this.numArraySizeY.Minimum = 1m;- this.numArraySizeY.Maximum = 999m;- this.numArraySizeY.Increment = 2m;- this.numSpacingSizeX.DecimalPlaces = 0;- this.numSpacingSizeX.Minimum = 0m;- this.numSpacingSizeX.Maximum = 16384m;- this.numSpacingSizeY.DecimalPlaces = 0;- this.numSpacingSizeY.Minimum = 0m;- this.numSpacingSizeY.Maximum = 16384m;- this.numAmplitude.DecimalPlaces = 0;- this.numPulseWidthCycles.DecimalPlaces = 0;- if (this.numPulseWidthCycles.Minimum < 1m)- {- this.numPulseWidthCycles.Minimum = 1m;+ _pickSourceButtonText = btnPickSourcePosition.Text;+ _sourceSaveButtonDefaultBackColor = btnSaveSource.BackColor;+ WireSourceDirtyTracking(grpSourceDetails);+ numSourcePositionX.DecimalPlaces = 0;+ numSourcePositionX.Minimum = 0m;+ numSourcePositionX.Maximum = (decimal)(SceneSettings.MaxCanvasSize - 1);+ numSourcePositionY.DecimalPlaces = 0;+ numSourcePositionY.Minimum = 0m;+ numSourcePositionY.Maximum = (decimal)(SceneSettings.MaxCanvasSize - 1);+ // Minimum (1) and Maximum (999) are both odd, and Increment is 2, so the up/down spinner buttons can only+ // ever land on an odd array size - see ArraySize_Validating for what catches an even value typed in+ // directly (the spinner can't produce one, but the keyboard can).+ numArraySizeX.DecimalPlaces = 0;+ numArraySizeX.Minimum = 1m;+ numArraySizeX.Maximum = 999m;+ numArraySizeX.Increment = 2m;+ numArraySizeY.DecimalPlaces = 0;+ numArraySizeY.Minimum = 1m;+ numArraySizeY.Maximum = 999m;+ numArraySizeY.Increment = 2m;+ numSpacingSizeX.DecimalPlaces = 0;+ numSpacingSizeX.Minimum = 0m;+ numSpacingSizeX.Maximum = (decimal)SceneSettings.MaxCanvasSize;+ numSpacingSizeY.DecimalPlaces = 0;+ numSpacingSizeY.Minimum = 0m;+ numSpacingSizeY.Maximum = (decimal)SceneSettings.MaxCanvasSize;+ numAmplitude.DecimalPlaces = 0;+ numPulseWidthCycles.DecimalPlaces = 0;+ if (numPulseWidthCycles.Minimum < 1m)+ {+ numPulseWidthCycles.Minimum = 1m;}// Designer limit is too small for long pulses; widen it without touching the Designer.- if (this.numPulseWidthCycles.Maximum < 100m)- {- this.numPulseWidthCycles.Maximum = 1000000m;- }- this.numOffStateCycles.DecimalPlaces = 0;- this.numRandomizeFrequency.DecimalPlaces = 0;- this.numRandomizeOffWidth.DecimalPlaces = 0;- this.numRandomizePosition.DecimalPlaces = 0;- this.NumRandomizePhase.DecimalPlaces = 0;- this._picSource.Paint += this.SourcePicture_Paint;- this._picSource.MouseClick += this.SourcePicture_MouseClick;- this.lstSources.DrawMode = DrawMode.OwnerDrawFixed;- this.RefreshSourceList();- this.ShowSourceInControls(this._editing);- this.ClearSourceDirty();- this.UpdateListButtonState();+ if (numPulseWidthCycles.Maximum < 100m)+ {+ numPulseWidthCycles.Maximum = 1000000m;+ }+ numOffStateCycles.DecimalPlaces = 0;+ numRandomizeFrequency.DecimalPlaces = 0;+ numRandomizeOffWidth.DecimalPlaces = 0;+ numRandomizePosition.DecimalPlaces = 0;+ NumRandomizePhase.DecimalPlaces = 0;+ _picSource.Paint += SourcePicture_Paint;+ _picSource.MouseClick += SourcePicture_MouseClick;+ // owner-drawn so a switched-off source (chkSourceOn unchecked) can be shown greyed out in the list -+ // it stays fully selectable, only its text color changes (see lstSources_DrawItem)+ lstSources.DrawMode = DrawMode.OwnerDrawFixed;+ RefreshSourceList();+ ShowSourceInControls(_editing);+ ClearSourceDirty();+ UpdateListButtonState();}/// <summary>- /// Replaces the source list with the sources stored in the open project and selects- /// the first one (or an empty editor when the project has none). No-op without a project.+ /// Replaces the source list with the sources stored in the open project and shows the first+ /// one (if any) selected and loaded into the editor, rather than always starting the editor on+ /// a blank "new source" template: opening a project that already has sources shows one of them,+ /// not a to-be-inserted one. "First" is whichever generate/save order the list is in; there is+ /// no separate "last edited" tracking kept across a save/reload to prefer instead. An empty+ /// project gets an empty editor. No-op without a project./// </summary>private void LoadSourcesFromProject(){- if (this._project == null)+ if (_project == null){return;}- this._sources = SourceSettings.ListFromConfig(this._project.Config);- if (this._sources.Count > 0)+ _sources = SourceSettings.ListFromConfig(_project.Config);+ if (_sources.Count > 0){- this._currentSourceIndex = 0;- this._editing = this._sources[0].Clone();+ _currentSourceIndex = 0;+ _editing = _sources[0].Clone();}else{- this._currentSourceIndex = -1;- this._editing = new SourceSettings();+ _currentSourceIndex = -1;+ _editing = new SourceSettings();}- this.RefreshSourceList();- this._syncingSourceList = true;+ RefreshSourceList();+ _syncingSourceList = true;try{- this.lstSources.SelectedIndex = this._currentSourceIndex;+ lstSources.SelectedIndex = _currentSourceIndex;}finally{- this._syncingSourceList = false;+ _syncingSourceList = false;}- this.ShowSourceInControls(this._editing);- this.ClearSourceDirty();- this.UpdateListButtonState();+ ShowSourceInControls(_editing);+ ClearSourceDirty();+ UpdateListButtonState();}/// <summary>@@ -116,16 +156,16 @@ namespace _2D_wave_sim_V01/// </summary>private void ResetSources(){- this._sources = new List<SourceSettings>();- this._currentSourceIndex = -1;- this._editing = new SourceSettings();- this.RefreshSourceList();- if (this._picSource != null)+ _sources = new List<SourceSettings>();+ _currentSourceIndex = -1;+ _editing = new SourceSettings();+ RefreshSourceList();+ if (_picSource != null){- this.ShowSourceInControls(this._editing);- this.ClearSourceDirty();+ ShowSourceInControls(_editing);+ ClearSourceDirty();}- this.UpdateListButtonState();+ UpdateListButtonState();}/// <summary>@@ -137,20 +177,23 @@ namespace _2D_wave_sim_V01/// </summary>private List<SourceElement> SourcesForRun(){- if (this._scene == null || !this._scene.UseObjectSources || this._sources.Count == 0)+ if (_scene == null || !_scene.UseObjectSources || _sources.Count == 0){return null;}List<SourceElement> elements = new List<SourceElement>();- foreach (SourceSettings source in this._sources)+ foreach (SourceSettings source in _sources){+ // switched off (chkSourceOn unchecked): keep the source and its parameters, just leave it out of the+ // run entirely, so it neither drives the field nor gets in the way of waves passing through itif (!source.SourceOn){continue;}if (source.Elements == null || source.Elements.Count == 0){- source.GenerateElements(this._sourceRandom);+ // a source saved before it was ever generated (should not normally happen) - generate it now, once+ source.GenerateElements(_sourceRandom);}elements.AddRange(source.Elements);}@@ -160,23 +203,23 @@ namespace _2D_wave_sim_V01/// <summary>Rebuilds the list box items from <c>_sources</c>, keeping the current selection index when it is still valid; the selection handler is suppressed meanwhile.</summary>private void RefreshSourceList(){- int selectedIndex = this.lstSources.SelectedIndex;- this._syncingSourceList = true;+ int selectedIndex = lstSources.SelectedIndex;+ _syncingSourceList = true;try{- this.lstSources.Items.Clear();- foreach (SourceSettings source in this._sources)+ lstSources.Items.Clear();+ foreach (SourceSettings source in _sources){- this.lstSources.Items.Add(Form1.SourceListText(source));+ lstSources.Items.Add(Form1.SourceListText(source));}- if (selectedIndex >= 0 && selectedIndex < this.lstSources.Items.Count)+ if (selectedIndex >= 0 && selectedIndex < lstSources.Items.Count){- this.lstSources.SelectedIndex = selectedIndex;+ lstSources.SelectedIndex = selectedIndex;}}finally{- this._syncingSourceList = false;+ _syncingSourceList = false;}}@@ -190,213 +233,223 @@ namespace _2D_wave_sim_V01return s.Name + " (single)";}- /// <summary>Owner-draws a list entry, in grey when the source is switched off.</summary>+ /// <summary>Owner-draws a list entry: a switched-off source (<c>chkSourceOn</c> unchecked) is drawn greyed out; it stays fully selectable, only the text colour changes, so the selection highlight still shows normally.</summary>private void lstSources_DrawItem(object sender, DrawItemEventArgs e){- if (e.Index < 0 || e.Index >= this.lstSources.Items.Count)+ if (e.Index < 0 || e.Index >= lstSources.Items.Count){return;}e.DrawBackground();- Color textColor = ((e.Index < this._sources.Count && !this._sources[e.Index].SourceOn) ? Color.Gray : e.ForeColor);+ Color textColor = ((e.Index < _sources.Count && !_sources[e.Index].SourceOn) ? Color.Gray : e.ForeColor);using (SolidBrush brush = new SolidBrush(textColor)){- e.Graphics.DrawString(this.lstSources.Items[e.Index].ToString(), e.Font, brush, e.Bounds);+ e.Graphics.DrawString(lstSources.Items[e.Index].ToString(), e.Font, brush, e.Bounds);}e.DrawFocusRectangle();}/// <summary>- /// Selecting a list entry cancels any position pick and loads a clone of that source into- /// the editor (unsaved edits of the previous source are discarded); deselecting loads an- /// empty source. Ignored while the list is being synchronised programmatically.+ /// Selecting a list entry cancels any position pick and loads a clone of that source straight+ /// into the editor (unsaved edits of the previous source are discarded); clearing the selection+ /// (New/Copy, or the list becoming empty) loads a blank/default source instead. Programmatic+ /// selection changes (<see cref="RefreshSourceList"/>, <see cref="CommitSourceEdits"/>) set+ /// <c>_syncingSourceList</c> first so they do not re-trigger this./// </summary>private void lstSources_SelectedIndexChanged(object sender, EventArgs e){- this.UpdateListButtonState();- if (this._syncingSourceList)+ UpdateListButtonState();+ if (_syncingSourceList){return;}- this.EndSourcePick();- if (this.lstSources.SelectedIndex < 0)+ EndSourcePick();+ if (lstSources.SelectedIndex < 0){- this._currentSourceIndex = -1;- this._editing = new SourceSettings();+ _currentSourceIndex = -1;+ _editing = new SourceSettings();}else{- this._currentSourceIndex = this.lstSources.SelectedIndex;- this._editing = this._sources[this._currentSourceIndex].Clone();+ _currentSourceIndex = lstSources.SelectedIndex;+ _editing = _sources[_currentSourceIndex].Clone();}- this.ShowSourceInControls(this._editing);- this.ClearSourceDirty();- if (this._picSource != null)+ ShowSourceInControls(_editing);+ ClearSourceDirty();+ if (_picSource != null){- this._picSource.Invalidate();+ _picSource.Invalidate();}- this.picPreviewSource.Invalidate();- this.ToolStripStatusLabel1.Text = ((this._currentSourceIndex >= 0) ? ("Editing '" + this._editing.Name + "': press Save source to keep the changes.") : "");+ picPreviewSource.Invalidate();+ ToolStripStatusLabel1.Text = ((_currentSourceIndex >= 0) ? ("Editing '" + _editing.Name + "': press Save source to keep the changes.") : "");}/// <summary>Enables Copy and Delete only while a list entry is selected.</summary>private void UpdateListButtonState(){- bool hasSelection = this.lstSources.SelectedIndex >= 0;- this.btnCopy.Enabled = hasSelection;- this.btnDelete.Enabled = hasSelection;+ bool hasSelection = lstSources.SelectedIndex >= 0;+ btnCopy.Enabled = hasSelection;+ btnDelete.Enabled = hasSelection;}/// <summary>Starts a new, unsaved source named "Source N" in the editor, deselects the list and focuses the name box.</summary>private void btnNew_Click(object sender, EventArgs e){- this.EndSourcePick();- this._syncingSourceList = true;+ EndSourcePick();+ _syncingSourceList = true;try{- this.lstSources.SelectedIndex = -1;+ lstSources.SelectedIndex = -1;}finally{- this._syncingSourceList = false;+ _syncingSourceList = false;}- this._currentSourceIndex = -1;- this._editing = new SourceSettings();- this._editing.Name = "Source " + (this._sources.Count + 1).ToString(CultureInfo.InvariantCulture);- this.ShowSourceInControls(this._editing);- this.MarkSourceDirty();- this.UpdateListButtonState();- if (this._picSource != null)+ _currentSourceIndex = -1;+ _editing = new SourceSettings();+ _editing.Name = "Source " + (_sources.Count + 1).ToString(CultureInfo.InvariantCulture);+ ShowSourceInControls(_editing);+ MarkSourceDirty(); // not saved yet - pressing Save source is what actually adds it+ UpdateListButtonState();+ if (_picSource != null){- this._picSource.Invalidate();+ _picSource.Invalidate();}- this.picPreviewSource.Invalidate();- this.ToolStripStatusLabel1.Text = "New source: fill in its properties, then press Save source.";- this.txtName.Focus();- this.txtName.SelectAll();+ picPreviewSource.Invalidate();+ ToolStripStatusLabel1.Text = "New source: fill in its properties, then press Save source.";+ txtName.Focus();+ txtName.SelectAll();}/// <summary>Loads a clone of the selected source, named "... copy", into the editor as a new unsaved source (it is only added to the list on save).</summary>private void btnCopy_Click(object sender, EventArgs e){- if (this.lstSources.SelectedIndex < 0)+ if (lstSources.SelectedIndex < 0){return;}- this.EndSourcePick();- string originalName = this._sources[this.lstSources.SelectedIndex].Name;- this._editing = this._sources[this.lstSources.SelectedIndex].Clone();- this._editing.Name = this._editing.Name + " copy";- this._syncingSourceList = true;+ EndSourcePick();+ string originalName = _sources[lstSources.SelectedIndex].Name;+ _editing = _sources[lstSources.SelectedIndex].Clone();+ _editing.Name = _editing.Name + " copy";+ _syncingSourceList = true;try{- this.lstSources.SelectedIndex = -1;+ lstSources.SelectedIndex = -1;}finally{- this._syncingSourceList = false;+ _syncingSourceList = false;}- this._currentSourceIndex = -1;- this.ShowSourceInControls(this._editing);- this.MarkSourceDirty();- this.UpdateListButtonState();- if (this._picSource != null)+ _currentSourceIndex = -1;+ ShowSourceInControls(_editing);+ MarkSourceDirty(); // not saved yet - pressing Save source is what actually adds it+ UpdateListButtonState();+ if (_picSource != null){- this._picSource.Invalidate();+ _picSource.Invalidate();}- this.picPreviewSource.Invalidate();- this.ToolStripStatusLabel1.Text = "Copy of '" + originalName + "': change it and press Save source to add it as a new source.";- this.txtName.Focus();- this.txtName.SelectAll();+ picPreviewSource.Invalidate();+ ToolStripStatusLabel1.Text = "Copy of '" + originalName + "': change it and press Save source to add it as a new source.";+ txtName.Focus();+ txtName.SelectAll();}/// <summary>After confirmation, removes the selected source from the list and marks the project dirty; clears the editor if that source was being edited.</summary>private void btnDelete_Click(object sender, EventArgs e){- if (this.lstSources.SelectedIndex < 0)+ if (lstSources.SelectedIndex < 0){return;}- int selectedIndex = this.lstSources.SelectedIndex;- string name = this._sources[selectedIndex].Name;+ int selectedIndex = lstSources.SelectedIndex;+ string name = _sources[selectedIndex].Name;if (MessageBox.Show(this, "Delete the source '" + name + "'?", "Delete source", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes){return;}- this._sources.RemoveAt(selectedIndex);- if (this._currentSourceIndex == selectedIndex)+ _sources.RemoveAt(selectedIndex);+ if (_currentSourceIndex == selectedIndex){- this._currentSourceIndex = -1;- this._editing = new SourceSettings();- this.ShowSourceInControls(this._editing);- this.ClearSourceDirty();+ _currentSourceIndex = -1;+ _editing = new SourceSettings();+ ShowSourceInControls(_editing);+ ClearSourceDirty();}- else if (this._currentSourceIndex > selectedIndex)+ else if (_currentSourceIndex > selectedIndex){- this._currentSourceIndex--;+ _currentSourceIndex--;}- this.RefreshSourceList();- this.UpdateListButtonState();- this.MarkProjectChanged();- if (this._picSource != null)+ RefreshSourceList();+ UpdateListButtonState();+ MarkProjectChanged();+ if (_picSource != null){- this._picSource.Invalidate();+ _picSource.Invalidate();}- this.picPreviewSource.Invalidate();- this.ToolStripStatusLabel1.Text = "Source '" + name + "' deleted.";+ picPreviewSource.Invalidate();+ ToolStripStatusLabel1.Text = "Source '" + name + "' deleted.";}/// <summary>Saves the editor contents into the list (see <see cref="CommitSourceEdits"/>).</summary>private void btnSaveSource_Click(object sender, EventArgs e){- this.CommitSourceEdits();+ CommitSourceEdits();}/// <summary>/// Reads the editor controls into the source being edited, regenerates its elements/// (re-rolling any randomisation) and stores it in the list, replacing the selected entry- /// or appending a new one. Marks the project dirty and leaves the editor on a fresh clone- /// of the saved source. Returns false, without saving, if the source has no name.+ /// or appending a new one, then clears the "unsaved changes" indicator on <c>btnSaveSource</c>.+ /// Shared by "Save source" itself and by completing a position pick for an already-selected+ /// source (see <see cref="SourcePicture_MouseClick"/>), so picking a new position for an+ /// existing source is never left stale until a separate press of Save source. Marks the+ /// project dirty and leaves the editor on a fresh clone of the saved source. Returns false,+ /// without committing anything, if the source has no name yet, the same as "Save source"+ /// always required./// </summary>private bool CommitSourceEdits(){- this.ReadSourceControls(this._editing);- if (this._editing.Name.Trim().Length == 0)+ ReadSourceControls(_editing);+ if (_editing.Name.Trim().Length == 0){MessageBox.Show(this, "Give the source a name first.", "Save source", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);- this.txtName.Focus();+ txtName.Focus();return false;}- this._editing.GenerateElements(this._sourceRandom);- if (this._currentSourceIndex >= 0 && this._currentSourceIndex < this._sources.Count)+ // always (re)generate the elements from the current editor values, so a changed position (or any other+ // parameter) is never left stale in a source that already had elements from an earlier generate/save+ _editing.GenerateElements(_sourceRandom);+ if (_currentSourceIndex >= 0 && _currentSourceIndex < _sources.Count){- this._sources[this._currentSourceIndex] = this._editing;+ _sources[_currentSourceIndex] = _editing;}else{- this._sources.Add(this._editing);- this._currentSourceIndex = this._sources.Count - 1;+ _sources.Add(_editing);+ _currentSourceIndex = _sources.Count - 1;}- this.RefreshSourceList();- this._syncingSourceList = true;+ RefreshSourceList();+ _syncingSourceList = true;try{- this.lstSources.SelectedIndex = this._currentSourceIndex;+ lstSources.SelectedIndex = _currentSourceIndex;}finally{- this._syncingSourceList = false;+ _syncingSourceList = false;}- this.UpdateListButtonState();- this.MarkProjectChanged();- if (this._picSource != null)+ UpdateListButtonState();+ MarkProjectChanged();+ if (_picSource != null){- this._picSource.Invalidate();+ _picSource.Invalidate();}- this.picPreviewSource.Invalidate();- this.ToolStripStatusLabel1.Text = "Source '" + this._editing.Name + "' saved (" + this._editing.Elements.Count.ToString(CultureInfo.InvariantCulture) + " element(s)).";- this._editing = this._editing.Clone();- this.ClearSourceDirty();+ picPreviewSource.Invalidate();+ ToolStripStatusLabel1.Text = "Source '" + _editing.Name + "' saved (" + _editing.Elements.Count.ToString(CultureInfo.InvariantCulture) + " element(s)).";+ // the editor keeps editing the source that was just saved, so pressing Save again updates it in place+ _editing = _editing.Clone();+ ClearSourceDirty();return true;}@@ -411,98 +464,111 @@ namespace _2D_wave_sim_V01private void ShowSourceInControls(SourceSettings s){s.Normalize();- this._loadingSource = true;+ _loadingSource = true;try{- this.txtName.Text = s.Name;- this.cmbMainType.SelectedIndex = (int)s.MainType;- this.chkSourceOn.Checked = s.SourceOn;- this.chkDetachSource.Checked = s.DetachSource;- this.txtDetachAfterSteps.Text = s.DetachAfterSteps.ToString(CultureInfo.InvariantCulture);- this.numSourcePositionX.Value = Form1.ClampToRange(this.numSourcePositionX, s.PosX);- this.numSourcePositionY.Value = Form1.ClampToRange(this.numSourcePositionY, s.PosY);- this.numFrequency.Value = Form1.ClampToRange(this.numFrequency, s.Frequency);- this.numAmplitude.Value = Form1.ClampToRange(this.numAmplitude, s.Amplitude);- this.numPhase.Value = Form1.ClampToRange(this.numPhase, s.PhaseDeg);- this.radModePulsed.Checked = s.Mode == SourceMode.Pulsed;- this.radModeContinuous.Checked = s.Mode == SourceMode.Continuous;- this.cmbPulseShape.SelectedIndex = (int)s.PulseShape;- this.numPulseWidthCycles.Value = Form1.ClampToRange(this.numPulseWidthCycles, s.PulseWidthCycles);- this.numOffStateCycles.Value = Form1.ClampToRange(this.numOffStateCycles, s.OffStateCycles);- this.numArraySizeX.Value = Form1.ClampToRange(this.numArraySizeX, s.ArraySizeX);- this.numArraySizeY.Value = Form1.ClampToRange(this.numArraySizeY, s.ArraySizeY);- this.numSpacingSizeX.Value = Form1.ClampToRange(this.numSpacingSizeX, s.SpacingX);- this.numSpacingSizeY.Value = Form1.ClampToRange(this.numSpacingSizeY, s.SpacingY);- this.UpdateRandomizeLimits();- this.cmbCompositeProperties.SelectedIndex = (int)s.CompositeMode;- this.chkRandomizeFrequency.Checked = s.RandomizeFrequency;- this.numRandomizeFrequency.Value = Form1.ClampToRange(this.numRandomizeFrequency, s.RandomizeFrequencyAmount);- this.chkRandomizePhase.Checked = s.RandomizePhase;- this.NumRandomizePhase.Value = Form1.ClampToRange(this.NumRandomizePhase, s.RandomizePhaseAmount);- this.chkOffWidth.Checked = s.RandomizeOffWidth;- this.numRandomizeOffWidth.Value = Form1.ClampToRange(this.numRandomizeOffWidth, s.RandomizeOffWidthAmount);- this.chkRandomizePosition.Checked = s.RandomizePosition;- this.numRandomizePosition.Value = Form1.ClampToRange(this.numRandomizePosition, s.RandomizePositionAmount);+ txtName.Text = s.Name;+ cmbMainType.SelectedIndex = (int)s.MainType;+ chkSourceOn.Checked = s.SourceOn;+ chkDetachSource.Checked = s.DetachSource;+ txtDetachAfterSteps.Text = s.DetachAfterSteps.ToString(CultureInfo.InvariantCulture);+ numSourcePositionX.Value = Form1.ClampToRange(numSourcePositionX, s.PosX);+ numSourcePositionY.Value = Form1.ClampToRange(numSourcePositionY, s.PosY);+ numFrequency.Value = Form1.ClampToRange(numFrequency, s.Frequency);+ numAmplitude.Value = Form1.ClampToRange(numAmplitude, s.Amplitude);+ numPhase.Value = Form1.ClampToRange(numPhase, s.PhaseDeg);+ radModePulsed.Checked = s.Mode == SourceMode.Pulsed;+ radModeContinuous.Checked = s.Mode == SourceMode.Continuous;+ cmbPulseShape.SelectedIndex = (int)s.PulseShape;+ numPulseWidthCycles.Value = Form1.ClampToRange(numPulseWidthCycles, s.PulseWidthCycles);+ numOffStateCycles.Value = Form1.ClampToRange(numOffStateCycles, s.OffStateCycles);+ numArraySizeX.Value = Form1.ClampToRange(numArraySizeX, s.ArraySizeX);+ numArraySizeY.Value = Form1.ClampToRange(numArraySizeY, s.ArraySizeY);+ numSpacingSizeX.Value = Form1.ClampToRange(numSpacingSizeX, s.SpacingX);+ numSpacingSizeY.Value = Form1.ClampToRange(numSpacingSizeY, s.SpacingY);+ // the three "amount" fields below are clamped against the just-loaded values above (see+ // UpdateRandomizeLimits) - called explicitly here rather than relying only on the ValueChanged handler+ // further down, since a value that happens to equal what a control already shows does not raise that event+ UpdateRandomizeLimits();+ cmbCompositeProperties.SelectedIndex = (int)s.CompositeMode;+ chkRandomizeFrequency.Checked = s.RandomizeFrequency;+ numRandomizeFrequency.Value = Form1.ClampToRange(numRandomizeFrequency, s.RandomizeFrequencyAmount);+ chkRandomizePhase.Checked = s.RandomizePhase;+ NumRandomizePhase.Value = Form1.ClampToRange(NumRandomizePhase, s.RandomizePhaseAmount);+ chkOffWidth.Checked = s.RandomizeOffWidth;+ numRandomizeOffWidth.Value = Form1.ClampToRange(numRandomizeOffWidth, s.RandomizeOffWidthAmount);+ chkRandomizePosition.Checked = s.RandomizePosition;+ numRandomizePosition.Value = Form1.ClampToRange(numRandomizePosition, s.RandomizePositionAmount);}finally{- this._loadingSource = false;+ _loadingSource = false;}- this.UpdateSourceControlState();- this.UpdateLambdaLabel();+ UpdateSourceControlState();+ UpdateLambdaLabel();}- /// <summary>Hooks the change events of every input control below <paramref name="container"/> (recursively) to the dirty marker.</summary>+ /// <summary>+ /// Hooks the change events of every input control below <paramref name="container"/> to+ /// <see cref="MarkSourceDirty"/>, recursively since <c>grpSourceDetails</c> nests+ /// <c>grpSingleSource</c> and <c>grpComposite</c>, so any change the user makes to a source's+ /// properties there turns <c>btnSaveSource</c> orange until the change is saved (see+ /// <see cref="MarkSourceDirty"/>/<see cref="ClearSourceDirty"/>). Called once, from+ /// <see cref="InitializeSourceControls"/>. The source's position (<c>numSourcePositionX</c>/<c>Y</c>,+ /// in <c>grpPlaceSource</c>, not <c>grpSourceDetails</c>) is deliberately not included here:+ /// picking or typing a position is committed through its own path instead+ /// (<see cref="SourcePicture_MouseClick"/>/<see cref="SourcePosition_ValueChanged"/>).+ /// </summary>private void WireSourceDirtyTracking(Control container){foreach (Control control in container.Controls){if (control is TextBox textBox){- textBox.TextChanged += this.SourceDetail_Changed;+ textBox.TextChanged += SourceDetail_Changed;}else if (control is NumericUpDown numericUpDown){- numericUpDown.ValueChanged += this.SourceDetail_Changed;+ numericUpDown.ValueChanged += SourceDetail_Changed;}else if (control is CheckBox checkBox){- checkBox.CheckedChanged += this.SourceDetail_Changed;+ checkBox.CheckedChanged += SourceDetail_Changed;}else if (control is RadioButton radioButton){- radioButton.CheckedChanged += this.SourceDetail_Changed;+ radioButton.CheckedChanged += SourceDetail_Changed;}else if (control is ComboBox comboBox){- comboBox.SelectedIndexChanged += this.SourceDetail_Changed;+ comboBox.SelectedIndexChanged += SourceDetail_Changed;}if (control.HasChildren){- this.WireSourceDirtyTracking(control);+ WireSourceDirtyTracking(control);}}}- /// <summary>Any user edit in the source details marks the editor dirty, unless the controls are being filled programmatically.</summary>+ /// <summary>Common handler for every control wired by <see cref="WireSourceDirtyTracking"/>. Ignored while the code itself is filling the controls (<see cref="ShowSourceInControls"/> sets <c>_loadingSource</c> first), so only an actual user edit counts.</summary>private void SourceDetail_Changed(object sender, EventArgs e){- if (!this._loadingSource)+ if (!_loadingSource){- this.MarkSourceDirty();+ MarkSourceDirty();}}/// <summary>Signals unsaved edits by colouring the save button orange.</summary>private void MarkSourceDirty(){- this.btnSaveSource.BackColor = Color.Orange;+ btnSaveSource.BackColor = Color.Orange;}- /// <summary>Restores the save button to its default colour once the editor matches the saved source.</summary>+ /// <summary>Restores <c>btnSaveSource</c> to its own Designer colour (captured in <c>_sourceSaveButtonDefaultBackColor</c>), once its pending changes are saved or discarded by loading a different/blank source into the editor.</summary>private void ClearSourceDirty(){- this.btnSaveSource.BackColor = this._sourceSaveButtonDefaultBackColor;+ btnSaveSource.BackColor = _sourceSaveButtonDefaultBackColor;}/// <summary>@@ -512,37 +578,37 @@ namespace _2D_wave_sim_V01/// </summary>private void ReadSourceControls(SourceSettings target){- target.Name = this.txtName.Text.Trim();- target.MainType = ((this.cmbMainType.SelectedIndex == 1) ? SourceMainType.Composite : SourceMainType.Simple);- target.SourceOn = this.chkSourceOn.Checked;- target.DetachSource = this.chkDetachSource.Checked;+ target.Name = txtName.Text.Trim();+ target.MainType = ((cmbMainType.SelectedIndex == 1) ? SourceMainType.Composite : SourceMainType.Simple);+ target.SourceOn = chkSourceOn.Checked;+ target.DetachSource = chkDetachSource.Checked;int detachAfterSteps;- if (int.TryParse(this.txtDetachAfterSteps.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out detachAfterSteps) && detachAfterSteps >= 0)+ if (int.TryParse(txtDetachAfterSteps.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out detachAfterSteps) && detachAfterSteps >= 0){target.DetachAfterSteps = detachAfterSteps;}- target.PosX = Convert.ToInt32(this.numSourcePositionX.Value);- target.PosY = Convert.ToInt32(this.numSourcePositionY.Value);- target.Frequency = Convert.ToInt32(this.numFrequency.Value);- target.Amplitude = Convert.ToInt32(this.numAmplitude.Value);- target.PhaseDeg = Convert.ToInt32(this.numPhase.Value);- target.Mode = (this.radModePulsed.Checked ? SourceMode.Pulsed : SourceMode.Continuous);- target.PulseShape = ((this.cmbPulseShape.SelectedIndex == 1) ? SourcePulseShape.SmoothedSquare : SourcePulseShape.Gaussian);- target.PulseWidthCycles = Convert.ToInt32(this.numPulseWidthCycles.Value);- target.OffStateCycles = Convert.ToInt32(this.numOffStateCycles.Value);- target.ArraySizeX = Convert.ToInt32(this.numArraySizeX.Value);- target.ArraySizeY = Convert.ToInt32(this.numArraySizeY.Value);- target.SpacingX = Convert.ToInt32(this.numSpacingSizeX.Value);- target.SpacingY = Convert.ToInt32(this.numSpacingSizeY.Value);- target.CompositeMode = ((this.cmbCompositeProperties.SelectedIndex == 1) ? SourceCompositeMode.InheritAndRandomize : SourceCompositeMode.InheritFromSingle);- target.RandomizeFrequency = this.chkRandomizeFrequency.Checked;- target.RandomizeFrequencyAmount = Convert.ToInt32(this.numRandomizeFrequency.Value);- target.RandomizePhase = this.chkRandomizePhase.Checked;- target.RandomizePhaseAmount = Convert.ToInt32(this.NumRandomizePhase.Value);- target.RandomizeOffWidth = this.chkOffWidth.Checked;- target.RandomizeOffWidthAmount = Convert.ToInt32(this.numRandomizeOffWidth.Value);- target.RandomizePosition = this.chkRandomizePosition.Checked;- target.RandomizePositionAmount = Convert.ToInt32(this.numRandomizePosition.Value);+ target.PosX = Convert.ToInt32(numSourcePositionX.Value);+ target.PosY = Convert.ToInt32(numSourcePositionY.Value);+ target.Frequency = Convert.ToInt32(numFrequency.Value);+ target.Amplitude = Convert.ToInt32(numAmplitude.Value);+ target.PhaseDeg = Convert.ToInt32(numPhase.Value);+ target.Mode = (radModePulsed.Checked ? SourceMode.Pulsed : SourceMode.Continuous);+ target.PulseShape = ((cmbPulseShape.SelectedIndex == 1) ? SourcePulseShape.SmoothedSquare : SourcePulseShape.Gaussian);+ target.PulseWidthCycles = Convert.ToInt32(numPulseWidthCycles.Value);+ target.OffStateCycles = Convert.ToInt32(numOffStateCycles.Value);+ target.ArraySizeX = Convert.ToInt32(numArraySizeX.Value);+ target.ArraySizeY = Convert.ToInt32(numArraySizeY.Value);+ target.SpacingX = Convert.ToInt32(numSpacingSizeX.Value);+ target.SpacingY = Convert.ToInt32(numSpacingSizeY.Value);+ target.CompositeMode = ((cmbCompositeProperties.SelectedIndex == 1) ? SourceCompositeMode.InheritAndRandomize : SourceCompositeMode.InheritFromSingle);+ target.RandomizeFrequency = chkRandomizeFrequency.Checked;+ target.RandomizeFrequencyAmount = Convert.ToInt32(numRandomizeFrequency.Value);+ target.RandomizePhase = chkRandomizePhase.Checked;+ target.RandomizePhaseAmount = Convert.ToInt32(NumRandomizePhase.Value);+ target.RandomizeOffWidth = chkOffWidth.Checked;+ target.RandomizeOffWidthAmount = Convert.ToInt32(numRandomizeOffWidth.Value);+ target.RandomizePosition = chkRandomizePosition.Checked;+ target.RandomizePositionAmount = Convert.ToInt32(numRandomizePosition.Value);target.Normalize();}@@ -554,148 +620,192 @@ namespace _2D_wave_sim_V01/// </summary>private void UpdateSourceControlState(){- bool isComposite = this.cmbMainType.SelectedIndex == 1;- this.grpComposite.Enabled = isComposite;- bool isPulsed = this.radModePulsed.Checked;- this.cmbPulseShape.Enabled = isPulsed;- this.numPulseWidthCycles.Enabled = isPulsed;- this.numOffStateCycles.Enabled = isPulsed;- this.txtDetachAfterSteps.Enabled = this.chkDetachSource.Checked;- bool canRandomize = isComposite && this.cmbCompositeProperties.SelectedIndex == 1;- this.cmbCompositeProperties.Enabled = isComposite;- this.numArraySizeX.Enabled = isComposite;- this.numArraySizeY.Enabled = isComposite;- this.numSpacingSizeX.Enabled = isComposite;- this.numSpacingSizeY.Enabled = isComposite;- this.chkRandomizeFrequency.Enabled = canRandomize;- this.chkRandomizePhase.Enabled = canRandomize;- this.chkOffWidth.Enabled = canRandomize;- this.chkRandomizePosition.Enabled = canRandomize;- this.numRandomizeFrequency.Enabled = canRandomize && this.chkRandomizeFrequency.Checked;- this.NumRandomizePhase.Enabled = canRandomize && this.chkRandomizePhase.Checked;- this.numRandomizeOffWidth.Enabled = canRandomize && this.chkOffWidth.Checked;- this.numRandomizePosition.Enabled = canRandomize && this.chkRandomizePosition.Checked;+ bool isComposite = cmbMainType.SelectedIndex == 1;+ grpComposite.Enabled = isComposite;+ bool isPulsed = radModePulsed.Checked;+ cmbPulseShape.Enabled = isPulsed;+ numPulseWidthCycles.Enabled = isPulsed;+ numOffStateCycles.Enabled = isPulsed;+ txtDetachAfterSteps.Enabled = chkDetachSource.Checked;+ bool canRandomize = isComposite && cmbCompositeProperties.SelectedIndex == 1;+ cmbCompositeProperties.Enabled = isComposite;+ numArraySizeX.Enabled = isComposite;+ numArraySizeY.Enabled = isComposite;+ numSpacingSizeX.Enabled = isComposite;+ numSpacingSizeY.Enabled = isComposite;+ chkRandomizeFrequency.Enabled = canRandomize;+ chkRandomizePhase.Enabled = canRandomize;+ chkOffWidth.Enabled = canRandomize;+ chkRandomizePosition.Enabled = canRandomize;+ numRandomizeFrequency.Enabled = canRandomize && chkRandomizeFrequency.Checked;+ NumRandomizePhase.Enabled = canRandomize && chkRandomizePhase.Checked;+ numRandomizeOffWidth.Enabled = canRandomize && chkOffWidth.Checked;+ numRandomizePosition.Enabled = canRandomize && chkRandomizePosition.Checked;}/// <summary>Changing the main type or the composite mode combo box re-evaluates which inputs are enabled.</summary>private void SourceMainType_SelectedIndexChanged(object sender, EventArgs e){- if (!this._loadingSource)+ if (!_loadingSource){- this.UpdateSourceControlState();+ UpdateSourceControlState();}}/// <summary>Switching between continuous and pulsed enables or disables the pulse inputs.</summary>private void SourceMode_CheckedChanged(object sender, EventArgs e){- if (!this._loadingSource)+ if (!_loadingSource){- this.UpdateSourceControlState();+ UpdateSourceControlState();}}- /// <summary>Changing the frequency updates the wavelength label.</summary>+ /// <summary>Keeps <c>lblLambdaIs</c> in sync with <c>numFrequency</c>. Not guarded by <c>_loadingSource</c>, since it must also refresh when a source is loaded into the editor (<see cref="ShowSourceInControls"/>), not only on a user edit.</summary>private void SourceFrequency_ValueChanged(object sender, EventArgs e){- this.UpdateLambdaLabel();+ UpdateLambdaLabel();}/// <summary>- /// Shows the wavelength in canvas pixels that follows from the frequency input and the- /// simulation settings: angular frequency = level / 255 * 0.5 * SourceFrequencyScale- /// (radians per step), wavelength = WaveSpeedC (px per step) / cycles per step. Falls back- /// to a scale of 2.0 and c = 0.563 before the simulation settings exist.+ /// Shows an estimated wavelength for the current <c>numFrequency</c> value in <c>lblLambdaIs</c>,+ /// as "λ=xx,x px" (using the current culture's decimal separator). lambda = c / f: f is the+ /// cyclic frequency (cycles/step) that a source's level (1-255, the <c>numFrequency</c> control)+ /// maps to via <see cref="SimulationSettings.SourceFrequencyScale"/>, the same formula the engines+ /// use (level / 255 * 0.5 * SourceFrequencyScale is the <em>angular</em> frequency in radians per+ /// step, so dividing by 2π gives cycles/step), and c is the propagation speed set via File >+ /// Set c-value (<see cref="SimulationSettings.WaveSpeedC"/>), in canvas pixels per step. Falls+ /// back to a scale of 2.0 and c = 0.563 before the simulation settings exist. This is only ever+ /// an estimate/display value: the real per-pixel wave speed the simulation actually uses comes+ /// from the scene's refractive index instead (see <see cref="SceneData.C2"/>) and is not+ /// necessarily uniform./// </summary>private void UpdateLambdaLabel(){- if (this.lblLambdaIs == null)+ if (lblLambdaIs == null){return;}- int frequency = Convert.ToInt32(this.numFrequency.Value);- double frequencyScale = ((this._simulation != null) ? this._simulation.SourceFrequencyScale : 2.0);+ int frequency = Convert.ToInt32(numFrequency.Value);+ double frequencyScale = ((_simulation != null) ? _simulation.SourceFrequencyScale : 2.0);double angularFrequency = frequency / 255.0 * 0.5 * frequencyScale;double cyclesPerStep = angularFrequency / (2.0 * Math.PI);if (cyclesPerStep <= 0.0){- this.lblLambdaIs.Text = "λ= - px";+ lblLambdaIs.Text = "λ= - px";}else{- double waveSpeed = ((this._simulation != null) ? this._simulation.WaveSpeedC : 0.563);+ double waveSpeed = ((_simulation != null) ? _simulation.WaveSpeedC : 0.563);double wavelength = waveSpeed / cyclesPerStep;- this.lblLambdaIs.Text = "λ=" + wavelength.ToString("0.0", CultureInfo.CurrentCulture) + " px";+ // the current culture's own decimal separator (a comma in nl-NL, for instance), not a fixed "."+ lblLambdaIs.Text = "λ=" + wavelength.ToString("0.0", CultureInfo.CurrentCulture) + " px";}}/// <summary>Ticking "detach" enables the detach step box.</summary>private void SourceDetach_CheckedChanged(object sender, EventArgs e){- if (!this._loadingSource)+ if (!_loadingSource){- this.UpdateSourceControlState();+ UpdateSourceControlState();}}/// <summary>Ticking one of the randomise checkboxes enables its amount input.</summary>private void SourceRandomizeCheck_CheckedChanged(object sender, EventArgs e){- if (!this._loadingSource)+ if (!_loadingSource){- this.UpdateSourceControlState();+ UpdateSourceControlState();}}- /// <summary>Changing frequency, off-width, array size or spacing recomputes the maxima of the randomise amounts.</summary>+ /// <summary>+ /// Keeps the three randomise "amount" fields' Maximum in step with the single-source values they+ /// are added to (see <see cref="UpdateRandomizeLimits"/>) whenever frequency, off-width, array+ /// size or spacing changes. Not guarded by <c>_loadingSource</c>, since <see cref="ShowSourceInControls"/>+ /// also relies on this to be current before it sets the amount fields' Value (though it+ /// additionally calls <see cref="UpdateRandomizeLimits"/> directly itself, since a value that+ /// happens to already match a control's current Value does not raise ValueChanged).+ /// </summary>private void SourceRandomizeLimitInput_ValueChanged(object sender, EventArgs e){- this.UpdateRandomizeLimits();+ UpdateRandomizeLimits();}/// <summary>- /// Limits the randomise amounts so that randomised values stay within their valid- /// ranges: frequency offset at most the distance to 1 or 255, off-width offset at most- /// off-width - 1 (keeps the gap at least 1 cycle), position jitter at most half the- /// smallest spacing along an axis with more than one element (16384 px for a 1x1 array).- /// Lowering a maximum also clips the current value of that input.+ /// Caps how large a "randomize amount" can be set to, so <see cref="SourceSettings.GenerateElements"/>'+ /// inherited ± amount can never be forced to clip against a hard limit and so end up biased+ /// instead of a true symmetric spread:+ /// <list type="bullet">+ /// <item><description>frequency (<c>numRandomizeFrequency</c>): the source's level must stay within+ /// 1-255, so the amount cannot exceed the smaller of (Frequency - 1) and (255 - Frequency).</description></item>+ /// <item><description>off-width cycles (<c>numRandomizeOffWidth</c>): GenerateElements floors the result+ /// at 1 cycle, so the amount cannot exceed (OffStateCycles - 1).</description></item>+ /// <item><description>position (<c>numRandomizePosition</c>): position has no natural upper/lower bound+ /// the way frequency and off-width do, so instead the amount is capped at half the array's own+ /// spacing along whichever axis (or axes) actually separate elements (ArraySizeX/Y > 1); a+ /// randomized element's jitter can then never overshoot as far as a neighbouring (unrandomized)+ /// grid position. An array that is only one element wide in both directions (no neighbour to+ /// protect against) is left unbounded at <see cref="SceneSettings.MaxCanvasSize"/>.</description></item>+ /// </list>+ /// Phase (<c>NumRandomizePhase</c>) is not limited here: its result is already clamped to -180..180+ /// in GenerateElements, and since ±180° is the same angle either way, that clipping does not+ /// bias the result the way it would for frequency or off-width. Lowering a Maximum below a+ /// field's current Value clamps that Value down to it automatically (standard NumericUpDown+ /// behaviour), so the amount fields never need to be set here, only their Maximum./// </summary>private void UpdateRandomizeLimits(){- int frequency = Convert.ToInt32(this.numFrequency.Value);- this.numRandomizeFrequency.Maximum = new decimal(Math.Max(0, Math.Min(frequency - 1, 255 - frequency)));- int offStateCycles = Convert.ToInt32(this.numOffStateCycles.Value);- this.numRandomizeOffWidth.Maximum = new decimal(Math.Max(0, offStateCycles - 1));- int arraySizeX = Convert.ToInt32(this.numArraySizeX.Value);- int arraySizeY = Convert.ToInt32(this.numArraySizeY.Value);+ int frequency = Convert.ToInt32(numFrequency.Value);+ numRandomizeFrequency.Maximum = new decimal(Math.Max(0, Math.Min(frequency - 1, 255 - frequency)));+ int offStateCycles = Convert.ToInt32(numOffStateCycles.Value);+ numRandomizeOffWidth.Maximum = new decimal(Math.Max(0, offStateCycles - 1));+ int arraySizeX = Convert.ToInt32(numArraySizeX.Value);+ int arraySizeY = Convert.ToInt32(numArraySizeY.Value);if (arraySizeX <= 1 && arraySizeY <= 1){- this.numRandomizePosition.Maximum = 16384m;+ numRandomizePosition.Maximum = (decimal)SceneSettings.MaxCanvasSize;}else{- List<int> spacings = new List<int>();+ // the smallest spacing among the axes that actually separate elements (Count > 1), without relying on+ // System.Linq (not imported by this file) for a two/one-element Min()+ List<int> relevantSpacing = new List<int>();if (arraySizeX > 1){- spacings.Add(Convert.ToInt32(this.numSpacingSizeX.Value));+ relevantSpacing.Add(Convert.ToInt32(numSpacingSizeX.Value));}if (arraySizeY > 1){- spacings.Add(Convert.ToInt32(this.numSpacingSizeY.Value));+ relevantSpacing.Add(Convert.ToInt32(numSpacingSizeY.Value));}- int minSpacing = spacings[0];- for (int i = 1; i < spacings.Count; i++)+ int minSpacing = relevantSpacing[0];+ for (int i = 1; i < relevantSpacing.Count; i++){- if (spacings[i] < minSpacing)+ if (relevantSpacing[i] < minSpacing){- minSpacing = spacings[i];+ minSpacing = relevantSpacing[i];}}- this.numRandomizePosition.Maximum = new decimal(Math.Max(0, minSpacing / 2));+ numRandomizePosition.Maximum = new decimal(Math.Max(0, minSpacing / 2));}}- /// <summary>Leaving an array size input with an even value bumps it to the next odd number (capped at the maximum) and tells the user; the array must have a centre element.</summary>+ /// <summary>+ /// <c>numArraySizeX</c>/<c>numArraySizeY</c> must stay odd: an even-sized array has its centre+ /// between two pixels instead of on one, which (especially at small spacings) places the whole+ /// array off-grid in an irregular way. The spinner buttons can never produce an even value+ /// (Minimum/Maximum are both odd and Increment is 2, see <see cref="InitializeSourceControls"/>),+ /// but typing a value directly can, so this catches that on Validating (the point where a typed+ /// value is finalized: on Tab/click-away, or on Enter via the global <c>NumericUpDown_KeyDown</c>+ /// hook that moves focus off the control) and bumps it up by one (capped at the maximum), with a+ /// warning so the change is not a silent surprise. Not guarded by <c>_loadingSource</c>:+ /// Validating only fires from an actual focus change, never from a plain Value assignment in+ /// code (e.g. <see cref="ShowSourceInControls"/> loading a project), so it can only ever be the+ /// user's own keyboard entry.+ /// </summary>private void ArraySize_Validating(object sender, CancelEventArgs e){NumericUpDown input = (NumericUpDown)sender;@@ -712,97 +822,110 @@ namespace _2D_wave_sim_V01/// <summary>Any main tab change cancels a running position pick; arriving on the source tab loads the scene picture if needed and re-syncs the list selection with the editor.</summary>private void SourceTabChanged(object sender, EventArgs e){- this.EndSourcePick();- if (this.tabMainFunctions.SelectedTab == this.tabSourceList)+ EndSourcePick();+ if (tabMainFunctions.SelectedTab == tabSourceList){- this.AutoLoadSceneImageIfEmpty(this._picSource);- this.SyncSourceListSelectionToEditor();+ AutoLoadSceneImageIfEmpty(_picSource);+ SyncSourceListSelectionToEditor();}}- /// <summary>Makes the list selection match <c>_currentSourceIndex</c> without triggering the selection handler, then reloads the editor from <c>_editing</c>.</summary>+ /// <summary>+ /// Makes <c>lstSources</c>' highlighted item and <c>grpSourceDetails</c> agree with the source+ /// actually loaded in the editor (<c>_editing</c>/<c>_currentSourceIndex</c>, the last source+ /// that was selected or edited) whenever the tab is opened, without triggering the selection+ /// handler. Without this, coming back from another tab could show some list item highlighted+ /// (left over from before, or the list's own default) while the detail controls still showed a+ /// different source, or one that no longer matched the highlighted entry at all.+ /// </summary>private void SyncSourceListSelectionToEditor(){- this._syncingSourceList = true;+ _syncingSourceList = true;try{- if (this._currentSourceIndex >= 0 && this._currentSourceIndex < this.lstSources.Items.Count)+ if (_currentSourceIndex >= 0 && _currentSourceIndex < lstSources.Items.Count){- this.lstSources.SelectedIndex = this._currentSourceIndex;+ lstSources.SelectedIndex = _currentSourceIndex;}else{- this.lstSources.SelectedIndex = -1;+ lstSources.SelectedIndex = -1;}}finally{- this._syncingSourceList = false;+ _syncingSourceList = false;}- this.ShowSourceInControls(this._editing);+ ShowSourceInControls(_editing);}/// <summary>Toggles position picking on the scene picture; the button reads "Cancel" while picking.</summary>private void PickSourcePosition_Click(object sender, EventArgs e){- if (this._sourcePicking)+ if (_sourcePicking){- this.EndSourcePick();+ EndSourcePick();}else{- this.StartSourcePick();+ StartSourcePick();}}/// <summary>Enters pick mode (cross cursor, "Cancel" button, status hint) after making sure the picture box has an image; shows a message and stays idle when the canvas size is unknown.</summary>private void StartSourcePick(){- if (this._picSource.Image == null)+ if (_picSource.Image == null){- this.EnsureSourcePicture();+ EnsureSourcePicture();}- if (this._picSource.Image == null)+ if (_picSource.Image == null){MessageBox.Show(this, "There is no picture to pick from yet, and the canvas size is not known either\r\n(choose a scene image, or a user defined width and height, on the Configuration tab first).", "Source position", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- this._sourcePicking = true;- this._picSource.Cursor = Cursors.Cross;- this.btnPickSourcePosition.Text = "Cancel";- this.ToolStripStatusLabel1.Text = "Click in the picture for the position of the source (press Cancel to stop picking).";+ _sourcePicking = true;+ _picSource.Cursor = Cursors.Cross;+ btnPickSourcePosition.Text = "Cancel";+ ToolStripStatusLabel1.Text = "Click in the picture for the position of the source (press Cancel to stop picking).";}- /// <summary>Creates a black canvas-sized picture when no scene image is loaded yet; the bitmap is owned by the picture box. No-op when the canvas size is unknown.</summary>+ /// <summary>+ /// When there is no picture yet to pick from (no simulation has run), makes a plain black one at+ /// the canvas size that the Configuration tab currently specifies (the scene image's size, or the+ /// user defined width/height), so a source position can still be picked before ever running a+ /// simulation. Replaced by the real picture as soon as one is copied over from the Preview tab.+ /// No-op when the canvas size is unknown. The bitmap is owned by the picture box.+ /// </summary>private void EnsureSourcePicture(){- Size canvas = this.EffectiveCanvas();+ Size canvas = EffectiveCanvas();if (canvas.Width <= 0 || canvas.Height <= 0){return;}- Bitmap bitmap = new Bitmap(canvas.Width, canvas.Height);- using (Graphics g = Graphics.FromImage(bitmap))+ Bitmap placeholder = new Bitmap(canvas.Width, canvas.Height);+ using (Graphics g = Graphics.FromImage(placeholder)){g.Clear(Color.Black);}- this._picSource.Image = bitmap;+ _picSource.Image = placeholder;}/// <summary>Leaves pick mode and restores cursor, button text and status bar; no-op when not picking.</summary>private void EndSourcePick(){- if (!this._sourcePicking)+ if (!_sourcePicking){return;}- this._sourcePicking = false;- this.btnPickSourcePosition.Text = this._pickSourceButtonText;- if (this._picSource != null)+ _sourcePicking = false;+ btnPickSourcePosition.Text = _pickSourceButtonText;+ if (_picSource != null){- this._picSource.Cursor = Cursors.Default;+ _picSource.Cursor = Cursors.Default;}- this.ToolStripStatusLabel1.Text = "";+ ToolStripStatusLabel1.Text = "";}/// <summary>@@ -813,45 +936,52 @@ namespace _2D_wave_sim_V01/// </summary>private void SourcePicture_MouseClick(object sender, MouseEventArgs e){- if (!this._sourcePicking || e.Button != MouseButtons.Left)+ if (!_sourcePicking || e.Button != MouseButtons.Left){return;}int canvasX = 0;int canvasY = 0;- if (!this.TryPictureToCanvas(this._picSource, e.Location, ref canvasX, ref canvasY))+ if (!TryPictureToCanvas(_picSource, e.Location, ref canvasX, ref canvasY)){return;}- this.numSourcePositionX.Value = Form1.ClampToRange(this.numSourcePositionX, canvasX);- this.numSourcePositionY.Value = Form1.ClampToRange(this.numSourcePositionY, canvasY);- if (!this._loadingSource)+ numSourcePositionX.Value = Form1.ClampToRange(numSourcePositionX, canvasX);+ numSourcePositionY.Value = Form1.ClampToRange(numSourcePositionY, canvasY);+ // SourcePosition_ValueChanged updates _editing and invalidates the picture, but not when the values above+ // did not actually change (e.g. clicking back on the same pixel), so do it here too, explicitly+ if (!_loadingSource){- this._editing.PosX = canvasX;- this._editing.PosY = canvasY;- this._editing.HasPosition = true;- this._picSource.Invalidate();+ _editing.PosX = canvasX;+ _editing.PosY = canvasY;+ _editing.HasPosition = true;+ _picSource.Invalidate();}- this.EndSourcePick();- if (this._currentSourceIndex >= 0)+ EndSourcePick();+ // picking a position for a source that is already in the list commits the editor's current data (the+ // picked position and anything else changed since the last save) straight to it, the same as pressing Save+ // source - so the pick is never left stale waiting for a separate save. A brand new/copied source (not+ // selected in the list yet) is left as before: still just a live, unsaved position until Save source is+ // pressed, since adding it here could otherwise silently add an incomplete/unnamed source to the list.+ if (_currentSourceIndex >= 0){- this.CommitSourceEdits();+ CommitSourceEdits();}}- /// <summary>Editing a position input moves the edited source (and flags it as positioned) so its marker follows on the scene picture before saving.</summary>+ /// <summary>Keeps the live marker in the picture in sync while typing a new position, same as picking one does: moves the edited source (and flags it as positioned) so its marker follows on the scene picture before saving.</summary>private void SourcePosition_ValueChanged(object sender, EventArgs e){- if (this._loadingSource)+ if (_loadingSource){return;}- this._editing.PosX = Convert.ToInt32(this.numSourcePositionX.Value);- this._editing.PosY = Convert.ToInt32(this.numSourcePositionY.Value);- this._editing.HasPosition = true;- if (this._picSource != null)+ _editing.PosX = Convert.ToInt32(numSourcePositionX.Value);+ _editing.PosY = Convert.ToInt32(numSourcePositionY.Value);+ _editing.HasPosition = true;+ if (_picSource != null){- this._picSource.Invalidate();+ _picSource.Invalidate();}}@@ -863,34 +993,38 @@ namespace _2D_wave_sim_V01/// </summary>private void SourcePicture_Paint(object sender, PaintEventArgs e){- if (this._picSource.Image == null)+ if (_picSource.Image == null){return;}- Size canvas = this.EffectiveCanvas();+ Size canvas = EffectiveCanvas();if (canvas.Width <= 0){- canvas = this._picSource.Image.Size;+ canvas = _picSource.Image.Size;}- RectangleF imageRect = Form1.ZoomedImageRectangle(this._picSource);+ RectangleF imageRect = Form1.ZoomedImageRectangle(_picSource);if (imageRect.Width <= 0f){return;}float scaleX = imageRect.Width / canvas.Width;float scaleY = imageRect.Height / canvas.Height;- for (int i = 0; i < this._sources.Count; i++)+ for (int i = 0; i < _sources.Count; i++){- bool isCurrent = i == this._currentSourceIndex;- SourceSettings source = (isCurrent ? this._editing : this._sources[i]);- if (source.HasPosition)+ bool isCurrent = i == _currentSourceIndex;+ // the source being edited is shown at its live (not yet saved) position, so moving it in the picture or+ // the X/Y boxes is reflected immediately instead of only after Save source+ SourceSettings shown = (isCurrent ? _editing : _sources[i]);+ if (shown.HasPosition){- Form1.DrawSourceMarker(e.Graphics, source, imageRect, scaleX, scaleY, isCurrent);+ Form1.DrawSourceMarker(e.Graphics, shown, imageRect, scaleX, scaleY, isCurrent);}}- if (this._currentSourceIndex < 0 && this._editing.HasPosition)+ // the source being created or copied (not in _sources yet) is shown too, so its position can be seen while+ // picking - but only once it actually has one (Pick or a typed X/Y), never at the unset default+ if (_currentSourceIndex < 0 && _editing.HasPosition){- Form1.DrawSourceMarker(e.Graphics, this._editing, imageRect, scaleX, scaleY, true);+ Form1.DrawSourceMarker(e.Graphics, _editing, imageRect, scaleX, scaleY, true);}}@@ -923,15 +1057,30 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Draws the generated elements of the source being edited on black, centred in the- /// preview box. With auto-rescale on, the element bounding box is scaled to 70 % of the- /// smaller box dimension and each element is a 6 px dot; otherwise elements are drawn- /// 1:1 as single pixels. Empty until the source has been saved once.+ /// Shows the layout of the source currently loaded in the editor (<c>_editing</c>) as white dots+ /// on a black background, centred in the preview box. The source picture above is at canvas+ /// scale, so a source (especially a composite source's individual elements) can be too small or+ /// too close together to make out there. <c>chkAutoRescaleSourceOn</c> (checked by default) picks+ /// which of two views this shows instead: checked, it zooms in on just the elements themselves+ /// (centred, the element bounding box scaled to fill the box minus a <c>marginFraction</c> margin+ /// on each side, each element shown as a dot of radius <c>dotRadius</c> so it stays visible), so+ /// their relative arrangement is always visible regardless of where the source sits on the canvas+ /// or how tightly its array is spaced; unchecked, the true, unscaled size (one simulation pixel is+ /// one screen pixel, and each element is drawn as exactly that: a single pixel, the same size it+ /// actually is in the simulation), so a composite source's real physical footprint (how many+ /// actual simulation pixels its array spans) can be judged directly. Either way it shows+ /// <c>_editing.Elements</c>, the last generated list, so it is blank for a brand new/copied source+ /// until it is generated by Save source, and otherwise reflects whatever was last saved (or, for+ /// the source just saved, just regenerated). Kept in sync by a <c>picPreviewSource.Invalidate()</c>+ /// call everywhere <c>_editing</c>/the currently edited source changes (loading a different one,+ /// New/Copy/Delete, and Save source), the same places <c>_picSource.Invalidate()</c> is called for+ /// the position marker above, and by <see cref="chkAutoRescaleSourceOn_CheckedChanged"/> when the+ /// view itself is switched./// </summary>private void picPreviewSource_Paint(object sender, PaintEventArgs e){e.Graphics.Clear(Color.Black);- List<SourceElement> elements = ((this._editing != null) ? this._editing.Elements : null);+ List<SourceElement> elements = ((_editing != null) ? _editing.Elements : null);if (elements == null || elements.Count == 0){return;@@ -959,39 +1108,43 @@ namespace _2D_wave_sim_V01maxY = element.PosY;}}- float width = this.picPreviewSource.ClientSize.Width;- float height = this.picPreviewSource.ClientSize.Height;- if (width <= 0f || height <= 0f)+ float boxW = picPreviewSource.ClientSize.Width;+ float boxH = picPreviewSource.ClientSize.Height;+ if (boxW <= 0f || boxH <= 0f){return;}float centerX = (minX + maxX) / 2f;float centerY = (minY + maxY) / 2f;- bool autoRescale = this.chkAutoRescaleSourceOn == null || this.chkAutoRescaleSourceOn.Checked;+ bool autoRescale = chkAutoRescaleSourceOn == null || chkAutoRescaleSourceOn.Checked;float scale;if (autoRescale){+ // a single element (or several coinciding at the same spot) has no span to scale to - fall back to a+ // fixed half-extent instead of dividing by zero, so it still just shows one dot in the middle of the boxfloat halfExtent = Math.Max(maxX - minX, maxY - minY) / 2f;if (halfExtent <= 0f){halfExtent = 1f;}- float targetSize = Math.Min(width, height) * 0.7f;- scale = targetSize / (halfExtent * 2f);+ const float marginFraction = 0.15f; // keeps outer dots from touching/clipping at the edge of the box+ float usable = Math.Min(boxW, boxH) * (1f - 2f * marginFraction);+ scale = usable / (halfExtent * 2f);}else{- scale = 1f;+ scale = 1f; // true size: one simulation pixel is one screen pixel}+ const float dotRadius = 3f;using (SolidBrush brush = new SolidBrush(Color.White)){foreach (SourceElement element in elements){- float px = width / 2f + (element.PosX - centerX) * scale;- float py = height / 2f + (element.PosY - centerY) * scale;+ float px = boxW / 2f + (element.PosX - centerX) * scale;+ float py = boxH / 2f + (element.PosY - centerY) * scale;if (autoRescale){- e.Graphics.FillEllipse(brush, px - 3f, py - 3f, 6f, 6f);+ e.Graphics.FillEllipse(brush, px - dotRadius, py - dotRadius, 2f * dotRadius, 2f * dotRadius);}else{@@ -1001,16 +1154,16 @@ namespace _2D_wave_sim_V01}}- /// <summary>Resizing the preview box repaints it so the elements stay centred.</summary>+ /// <summary>Redraws at the (centred, rescaled) size whenever the box itself is resized, the same as any other owner-drawn control that scales to its client area.</summary>private void picPreviewSource_SizeChanged(object sender, EventArgs e){- this.picPreviewSource.Invalidate();+ picPreviewSource.Invalidate();}/// <summary>Toggling auto-rescale repaints the preview in the other scale mode.</summary>private void chkAutoRescaleSourceOn_CheckedChanged(object sender, EventArgs e){- this.picPreviewSource.Invalidate();+ picPreviewSource.Invalidate();}}}diff --git a/Wave_Dude_2D/Form1.cs b/Wave_Dude_2D/Form1.csindex 4a0ca3f..df81362 100644--- a/Wave_Dude_2D/Form1.cs+++ b/Wave_Dude_2D/Form1.cs@@ -27,47 +27,47 @@ namespace _2D_wave_sim_V01/// </summary>public Form1(){- base.Load += this.Form1_Load;- base.FormClosed += this.Form1_FormClosed;- base.FormClosing += this.Form1_FormClosing;- this._schemes = new List<ColorScheme>();- this._selectedStop = -1;- this._thumbs = new ImageList();- this._projectSortColumn = 1;- this._projectSortAscending = false;- this._outputProjectSortColumn = 1;- this._outputProjectSortAscending = false;- this._schemeSortColumn = 2;- this._schemeSortAscending = true;- this._sceneSortColumn = 1;- this._sceneSortAscending = false;- this._imageSortColumn = 1;- this._imageSortAscending = false;- this._videoSortColumn = 1;- this._videoSortAscending = false;- this._thumbBitmaps = new List<Bitmap>();- this._settings = new AppSettings();- this._rootBlinkTimer = new global::System.Windows.Forms.Timer+ base.Load += Form1_Load;+ base.FormClosed += Form1_FormClosed;+ base.FormClosing += Form1_FormClosing;+ _schemes = new List<ColorScheme>();+ _selectedStop = -1;+ _thumbs = new ImageList();+ _projectSortColumn = 1;+ _projectSortAscending = false;+ _outputProjectSortColumn = 1;+ _outputProjectSortAscending = false;+ _schemeSortColumn = 2;+ _schemeSortAscending = true;+ _sceneSortColumn = 1;+ _sceneSortAscending = false;+ _imageSortColumn = 1;+ _imageSortAscending = false;+ _videoSortColumn = 1;+ _videoSortAscending = false;+ _thumbBitmaps = new List<Bitmap>();+ _settings = new AppSettings();+ _rootBlinkTimer = new global::System.Windows.Forms.Timer{Interval = 700};- this._rootBlinkTimer.Tick += this.RootBlinkTimer_Tick;- this._scene = new SceneSettings();- this._sceneTip = new ToolTip();- this._simulation = new SimulationSettings();- this._simStatus = "";- this._fieldVideoFile = "";- this._intensityVideoFile = "";- this._runInfo = "";- this._progressText = "";- this._probes = Form1.NewProbeList();- this._probeTraces = new List<ProbeTrace>();- this._sources = new List<SourceSettings>();- this._currentSourceIndex = -1;- this._editing = new SourceSettings();- this._pickSourceButtonText = "Pick";- this._sourceRandom = new Random();- this.InitializeComponent();+ _rootBlinkTimer.Tick += RootBlinkTimer_Tick;+ _scene = new SceneSettings();+ _sceneTip = new ToolTip();+ _simulation = new SimulationSettings();+ _simStatus = "";+ _fieldVideoFile = "";+ _intensityVideoFile = "";+ _runInfo = "";+ _progressText = "";+ _probes = Form1.NewProbeList();+ _probeTraces = new List<ProbeTrace>();+ _sources = new List<SourceSettings>();+ _currentSourceIndex = -1;+ _editing = new SourceSettings();+ _pickSourceButtonText = "Pick";+ _sourceRandom = new Random();+ InitializeComponent();}/// <summary>@@ -81,64 +81,84 @@ namespace _2D_wave_sim_V01/// </summary>private void Form1_Load(object sender, EventArgs e){- this._stopButtons = new Button[] { this.btnColor1, this.btnCOlor2, this.btnColor3, this.btnColor4, this.btnColor5, this.btnColor6, this.btnColor7, this.btnColor8, this.btnColor9 };- Debug.Assert(this._stopButtons.Length == 9, "The number of Color buttons must equal ColorScheme.StopCount.");- foreach (Button button in this._stopButtons)+ // one button per stop, in scale order (Color 1 = first entry ... last button = last entry)+ _stopButtons = new Button[] { btnColor1, btnCOlor2, btnColor3, btnColor4, btnColor5, btnColor6, btnColor7, btnColor8, btnColor9 };+ Debug.Assert(_stopButtons.Length == ColorScheme.StopCount, "The number of Color buttons must equal ColorScheme.StopCount.");+ foreach (Button button in _stopButtons){button.UseVisualStyleBackColor = false;button.FlatStyle = FlatStyle.Flat;button.FlatAppearance.BorderSize = 1;button.FlatAppearance.BorderColor = Color.Black;}- this._thumbs.ImageSize = new Size(120, 16);- this._thumbs.ColorDepth = ColorDepth.Depth32Bit;- this.ListView1.View = View.Details;- this.ListView1.FullRowSelect = true;- this.ListView1.MultiSelect = false;- this.ListView1.HideSelection = false;- this.ListView1.HeaderStyle = ColumnHeaderStyle.Clickable;- this.ListView1.SmallImageList = this._thumbs;- this.ListView1.Columns.Clear();- this.ListView1.Columns.Add("Scheme", 250);- this.ListView1.Columns.Add("Kind", 55);- this.ListView1.Columns.Add("Type", 62);- this.UpdateSchemeListSortHeaders();- this.pnlScheme.BorderStyle = BorderStyle.FixedSingle;- this.Panel2.BorderStyle = BorderStyle.FixedSingle;- this._picker = new ColorPickerControl();- this._picker.Dock = DockStyle.Fill;- this.Panel2.Controls.Add(this._picker);- this._picker.ColorChanged += this.Picker_ColorChanged;- this.txtCurrentColorScheme.ReadOnly = true;- this.tabMainFunctions.DrawMode = TabDrawMode.OwnerDrawFixed;- this.UpdateProjectListSortHeaders();- this.txtSchemeFolder.Text = ColorSchemeStore.FindDefaultFolder();- if (Directory.Exists(this.txtSchemeFolder.Text))+ // scheme list: thumbnail + name, grouped by category+ _thumbs.ImageSize = new Size(ThumbWidth, ThumbHeight);+ _thumbs.ColorDepth = ColorDepth.Depth32Bit;+ ListView1.View = View.Details;+ ListView1.FullRowSelect = true;+ ListView1.MultiSelect = false;+ ListView1.HideSelection = false;+ ListView1.HeaderStyle = ColumnHeaderStyle.Clickable;+ ListView1.SmallImageList = _thumbs;+ ListView1.Columns.Clear();+ ListView1.Columns.Add("Scheme", 250);+ ListView1.Columns.Add("Kind", 55);+ ListView1.Columns.Add("Type", 62);+ UpdateSchemeListSortHeaders();+ pnlScheme.BorderStyle = BorderStyle.FixedSingle;+ Panel2.BorderStyle = BorderStyle.FixedSingle;+ _picker = new ColorPickerControl();+ _picker.Dock = DockStyle.Fill;+ Panel2.Controls.Add(_picker);+ _picker.ColorChanged += Picker_ColorChanged;+ txtCurrentColorScheme.ReadOnly = true;+ // tabMainFunctions: owner-drawn only so a disabled tab's own label can be shown in a lighter gray+ // (WinForms does not do this by itself - a disabled TabPage still draws its label at full strength) -+ // see tabMainFunctions_DrawItem.+ tabMainFunctions.DrawMode = TabDrawMode.OwnerDrawFixed;+ // lstAllProjects (Configuration tab project list): sortable by clicking colProjectName/colLastEdit, see+ // lstAllProjects_ColumnClick. Show the initial sort direction in the header the same way a click would.+ UpdateProjectListSortHeaders();+ // the program's own scheme folder (ColorSchemeList in the project, or next to the exe when deployed)+ txtSchemeFolder.Text = ColorSchemeStore.FindDefaultFolder();+ if (Directory.Exists(txtSchemeFolder.Text)){- this.LoadSchemeList();+ LoadSchemeList();}- this.RefreshEditorState();- this.lblInfo.ForeColor = Color.Blue;- this.lblInfo.Cursor = Cursors.Hand;- this.InitializeSceneControls();- this.InitializeSimulationControls();- this.InitializeProbeControls();- this.InitializeSourceControls();- // The designer places btnPickRoot inside grpProjects, but UpdateProjectAccess disables- // that group while no root is chosen - which is exactly when the button is needed.- // Move it to the tab page at the same screen position so it stays enabled.- Point location = this.grpProjects.Location;- location.Offset(this.btnPickRoot.Location);- this.grpProjects.Controls.Remove(this.btnPickRoot);- this.tabConfiguration.Controls.Add(this.btnPickRoot);- this.btnPickRoot.Location = location;- this.btnPickRoot.BringToFront();- this.InitializeProject();- this.InitializeOutputsTab();- this.HookNumericUpDownEnterKey(this);+ RefreshEditorState();+ // lblInfo (Settings tab): a clickable "hyperlink" style label - see lblInfo_Click for what it shows+ lblInfo.ForeColor = Color.Blue;+ lblInfo.Cursor = Cursors.Hand;+ InitializeSceneControls();+ InitializeSimulationControls();+ InitializeProbeControls();+ InitializeSourceControls();+ // btnPickRoot must stay clickable even when no project root is known yet (that is the one situation it+ // exists for), but the Designer put it inside grpProjects, and WinForms disables an enabled child along+ // with a disabled parent - grpProjects.Enabled = false (UpdateProjectAccess, no root) would silently+ // swallow its clicks right when they matter most. Move it onto tabConfiguration itself, in the same+ // screen position, so it is never caught by that.+ Point rootButtonSpot = grpProjects.Location;+ rootButtonSpot.Offset(btnPickRoot.Location);+ grpProjects.Controls.Remove(btnPickRoot);+ tabConfiguration.Controls.Add(btnPickRoot);+ btnPickRoot.Location = rootButtonSpot;+ btnPickRoot.BringToFront();+ InitializeProject();+ InitializeOutputsTab();+ // Enter in a NumericUpDown's edit box otherwise just beeps (Windows beeps on an unhandled Enter+ // keystroke) and leaves the typed value sitting there uncommitted - HookNumericUpDownEnterKey wires+ // every NumericUpDown on the form, wherever it lives, to NumericUpDown_KeyDown instead.+ HookNumericUpDownEnterKey(this);}- /// <summary>Recursively attaches <see cref="NumericUpDown_KeyDown"/> to every <see cref="NumericUpDown"/> below <paramref name="root"/>.</summary>+ /// <summary>+ /// Recursively attaches <see cref="NumericUpDown_KeyDown"/> to every <see cref="NumericUpDown"/> below+ /// <paramref name="root"/> (recursing into GroupBox/TabPage/Panel/... containers), so Enter commits the+ /// typed value and moves on instead of beeping. Called once, from <see cref="Form1_Load"/>, on the whole+ /// form - a plain loop over Controls rather than a fixed list, so it also covers any NumericUpDown added+ /// later without needing to come back and wire it up by hand.+ /// </summary>private void HookNumericUpDownEnterKey(Control root){foreach (Control control in root.Controls)@@ -146,16 +166,21 @@ namespace _2D_wave_sim_V01NumericUpDown numericUpDown = control as NumericUpDown;if (numericUpDown != null){- numericUpDown.KeyDown += this.NumericUpDown_KeyDown;+ numericUpDown.KeyDown += NumericUpDown_KeyDown;}if (control.HasChildren){- this.HookNumericUpDownEnterKey(control);+ HookNumericUpDownEnterKey(control);}}}- /// <summary>Enter in a spinner commits its value by moving focus to the next control (and suppresses the beep).</summary>+ /// <summary>+ /// Enter in a NumericUpDown: stops the beep (<c>e.SuppressKeyPress</c> - Enter is not a character its edit+ /// box accepts, which is what Windows was beeping about) and moves focus on to the next control, the same+ /// as Tab would - which also commits whatever was typed, since a NumericUpDown parses/clamps its text on+ /// losing focus regardless of how focus was lost.+ /// </summary>private void NumericUpDown_KeyDown(object sender, KeyEventArgs e){if (e.KeyCode != Keys.Return)@@ -174,15 +199,15 @@ namespace _2D_wave_sim_V01/// <summary>Disposes every bitmap the form owns: preview frames, scheme thumbnails, the scene image, the empty-canvas placeholder and the output preview.</summary>private void Form1_FormClosed(object sender, FormClosedEventArgs e){- this.ClearPreviews();- foreach (Bitmap bitmap in this._thumbBitmaps)+ ClearPreviews();+ foreach (Bitmap bitmap in _thumbBitmaps){bitmap.Dispose();}- this._thumbBitmaps.Clear();- this.ReplaceSceneImage(null);- this.DisposeEmptyPreview();- this.ClearOutputPreview();+ _thumbBitmaps.Clear();+ ReplaceSceneImage(null);+ DisposeEmptyPreview();+ ClearOutputPreview();}/// <summary>@@ -192,22 +217,23 @@ namespace _2D_wave_sim_V01/// </summary>private void Form1_FormClosing(object sender, FormClosingEventArgs e){- if (!this.ConfirmSaveProject())+ if (!ConfirmSaveProject()){e.Cancel = true;return;}- if (this._runner != null)+ if (_runner != null){if (MessageBox.Show(this, "A simulation is running. Stop it and close the program?", "Simulation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes){e.Cancel = true;return;}- this._runner.Cancel();- this._runner.WaitForExit(15000);+ // the runner closes the video files before it ends+ _runner.Cancel();+ _runner.WaitForExit(15000);}- if (this._dirty)+ if (_dirty){if (MessageBox.Show(this, "The current color scheme has unsaved changes. Close anyway?", "Unsaved changes", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes){@@ -217,52 +243,72 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Enables the project list and output tab only when a project root is chosen (and blinks- /// <c>btnPickRoot</c> while none is), and the editing tabs, buttons and groups only when- /// a project is open. Repaints the tab headers so disabled tabs grey out.+ /// Enables/disables everything that depends on a project root being chosen and/or an actual, named+ /// project being the current one. <c>grpProjects</c> and the Outputs tab (its own project list, not+ /// necessarily the one that is open) only need a root. The scene/simulation groups, the+ /// Sources/Probes/Viewer tabs, most of "Quick navigate to" (all but <c>btnGotoConfiguration</c>, which+ /// jumps to the always-available Configuration tab), "Simulation Control", "Share with source / probe"+ /// and Save all need a real project. The Configuration tab (where the root and the project list+ /// themselves live) and the color scheme tab manage the application's own settings, not a project's,+ /// so they are never restricted. Disabling a TabPage here is not enough by itself to keep the user out+ /// of it - see <see cref="tabMainFunctions_Selecting"/>, which refuses to switch to a disabled tab at+ /// all instead of just showing its (disabled) contents. Blinks <c>btnPickRoot</c> while no root is chosen./// </summary>private void UpdateProjectAccess(){- bool hasRoot = this._settings.ProjectRoot.Length > 0;- bool hasProject = this._project != null;- this.grpProjects.Enabled = hasRoot;- this.tabOutput.Enabled = hasRoot;+ bool hasRoot = _settings.ProjectRoot.Length > 0;+ bool hasProject = _project != null;+ grpProjects.Enabled = hasRoot;+ tabOutput.Enabled = hasRoot;+ // btnPickRoot (moved onto tabConfiguration itself in Form1_Load, so grpProjects.Enabled above cannot+ // disable it) blinks light blue, slowly, for exactly the situation it exists for: no project root known+ // yet - a fresh install on another computer, before AppSettings.ProjectRoot is set and everything else+ // on screen is still disabled.if (hasRoot){- this._rootBlinkTimer.Stop();- this._rootBlinkOn = false;- this.btnPickRoot.UseVisualStyleBackColor = true;+ _rootBlinkTimer.Stop();+ _rootBlinkOn = false;+ btnPickRoot.UseVisualStyleBackColor = true;}else{- this._rootBlinkTimer.Start();+ _rootBlinkTimer.Start();}- this.grpSceneProperties.Enabled = hasProject;- this.grpSimulationSettings.Enabled = hasProject;- this.tabSourceList.Enabled = hasProject;- this.tabProbeList.Enabled = hasProject;- this.tabViewer.Enabled = hasProject;- this.btnGotoPreview.Enabled = hasProject;- this.btnGotoProbes.Enabled = hasProject;- this.btnGotoSources.Enabled = hasProject;- this.grpSimulationControlButtons.Enabled = hasProject;- this.grpShareImage.Enabled = hasProject;- this.btnSaveConfiguration.Enabled = hasProject;- this.btnSaveConfiguration2.Enabled = hasProject;- this.btnSaveAs.Enabled = hasProject;- this.btnDescription.Enabled = hasProject;- this.tabMainFunctions.Invalidate();+ grpSceneProperties.Enabled = hasProject;+ grpSimulationSettings.Enabled = hasProject;+ tabSourceList.Enabled = hasProject;+ tabProbeList.Enabled = hasProject;+ tabViewer.Enabled = hasProject;+ // grpNavigateTabs itself stays enabled: btnGotoConfiguration jumps to the always-available Configuration+ // tab, so only the other three "quick navigate" buttons need a real project.+ btnGotoPreview.Enabled = hasProject;+ btnGotoProbes.Enabled = hasProject;+ btnGotoSources.Enabled = hasProject;+ grpSimulationControlButtons.Enabled = hasProject;+ grpShareImage.Enabled = hasProject;+ btnSaveConfiguration.Enabled = hasProject;+ btnSaveConfiguration2.Enabled = hasProject;+ btnSaveAs.Enabled = hasProject;+ btnDescription.Enabled = hasProject;+ // Changing a TabPage's Enabled does not by itself repaint the tab strip, so a label's color+ // (tabMainFunctions_DrawItem) would otherwise stay stuck at its old, disabled gray until something+ // unrelated forced a redraw (resizing the window, switching tabs, ...) - force it here instead.+ tabMainFunctions.Invalidate();}/// <summary>Every 700 ms while no root is chosen: toggles <c>btnPickRoot</c> between light blue and the normal button colour.</summary>private void RootBlinkTimer_Tick(object sender, EventArgs e){- this._rootBlinkOn = !this._rootBlinkOn;- this.btnPickRoot.UseVisualStyleBackColor = false;- this.btnPickRoot.BackColor = (this._rootBlinkOn ? Color.LightBlue : SystemColors.Control);+ _rootBlinkOn = !_rootBlinkOn;+ btnPickRoot.UseVisualStyleBackColor = false;+ btnPickRoot.BackColor = (_rootBlinkOn ? Color.LightBlue : SystemColors.Control);}- /// <summary>Refuses to switch to a tab that <see cref="UpdateProjectAccess"/> disabled and tells the user to open a project first.</summary>+ /// <summary>+ /// Refuses to switch to a tab that <see cref="UpdateProjectAccess"/> disabled and tells the user to open a+ /// project first. A disabled TabPage still lets itself be clicked into and shows its (disabled) contents+ /// unless refused here - WinForms' TabControl has no built-in notion of a locked tab.+ /// </summary>private void tabMainFunctions_Selecting(object sender, TabControlCancelEventArgs e){if (!e.TabPage.Enabled)@@ -272,45 +318,58 @@ namespace _2D_wave_sim_V01}}- /// <summary>Owner-draws a tab header: window colour for the selected tab, control colour otherwise, silver text when the page is disabled.</summary>+ /// <summary>+ /// Owner-draws a tab header: window colour for the selected tab, control colour otherwise, silver text when+ /// the page is disabled. Needed only so a disabled tab's label can be shown in a lighter gray than an+ /// enabled one's (<see cref="Form1_Load"/> sets <c>tabMainFunctions.DrawMode</c> to OwnerDrawFixed for this).+ /// </summary>private void tabMainFunctions_DrawItem(object sender, DrawItemEventArgs e){- TabPage tabPage = this.tabMainFunctions.TabPages[e.Index];- Rectangle tabRect = this.tabMainFunctions.GetTabRect(e.Index);- Color backColor = ((e.Index == this.tabMainFunctions.SelectedIndex) ? SystemColors.Window : SystemColors.Control);+ TabPage tabPage = tabMainFunctions.TabPages[e.Index];+ Rectangle tabRect = tabMainFunctions.GetTabRect(e.Index);+ // the selected tab a shade lighter than the rest, so which one is open is still visible without the+ // native visual style this drawing replaces+ Color backColor = ((e.Index == tabMainFunctions.SelectedIndex) ? SystemColors.Window : SystemColors.Control);using (SolidBrush brush = new SolidBrush(backColor)){e.Graphics.FillRectangle(brush, tabRect);}Color textColor = (tabPage.Enabled ? SystemColors.ControlText : Color.Silver);TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter;- TextRenderer.DrawText(e.Graphics, tabPage.Text, this.tabMainFunctions.Font, tabRect, textColor, flags);+ TextRenderer.DrawText(e.Graphics, tabPage.Text, tabMainFunctions.Font, tabRect, textColor, flags);}/// <summary>- /// Replaces the placeholder <see cref="_settings"/> with the values read from disk, shows- /// the stored project root, and refreshes access state, title and project list. No- /// project is opened automatically.+ /// Startup: replaces the placeholder <see cref="_settings"/> with the values read from disk, shows+ /// the stored project root, and refreshes access state, title and project list. Nothing from any+ /// previous project is filled into the form: only the chosen project root folder+ /// (<see cref="AppSettings.ProjectRoot"/>) is restored, if one was already chosen on an earlier run -+ /// everything that needs a root or a real project stays disabled until then (<see cref="UpdateProjectAccess"/>)./// </summary>private void InitializeProject(){- this._settings = AppSettings.Load();- this.txtRootFolder.Text = this._settings.ProjectRoot;- this.txtProjectName.Text = "";- this.UpdateProjectAccess();- this.UpdateTitle();- this.RefreshProjectList();+ _settings = AppSettings.Load();+ txtRootFolder.Text = _settings.ProjectRoot;+ txtProjectName.Text = "";+ UpdateProjectAccess();+ UpdateTitle();+ RefreshProjectList();}- /// <summary>File > Open: asks for an existing project folder, offers to save the current project, then opens the chosen one.</summary>+ /// <summary>+ /// File > Open: asks for an existing project folder (browse directly to the main folder of a project,+ /// without going through the project list), offers to save the current project, then opens the chosen one.+ /// Browsing for the project ROOT folder instead is <c>btnBrowseRoot</c> / File > Choose project root /+ /// double-clicking <c>txtRootFolder</c> - see <see cref="ChooseProjectRootToolStripMenuItem_Click"/>.+ /// </summary>private void OpenProject_Click(object sender, EventArgs e){try{- string folder = this.BrowseForFolder("Choose the main folder of the project (the folder that contains configuration.json)", this.txtRootFolder.Text.Trim(), false);- if (folder.Length > 0 && this.ConfirmSaveProject())+ string folder = BrowseForFolder("Choose the main folder of the project (the folder that contains configuration.json)", txtRootFolder.Text.Trim(), false);+ if (folder.Length > 0 && ConfirmSaveProject()){- this.SetCurrentProject(ProjectStore.Open(folder));+ SetCurrentProject(ProjectStore.Open(folder));}}catch (Exception ex)@@ -322,20 +381,26 @@ namespace _2D_wave_sim_V01/// <summary>File > Save and the "Save changes to project" button: saves the open project (see <see cref="SaveProject"/>).</summary>private void SaveProject_Click(object sender, EventArgs e){- this.SaveProject();+ SaveProject();}- /// <summary>"Save as": asks for a new project name and saves the current settings as that project in the current root folder.</summary>+ /// <summary>+ /// "Save as": a simple name prompt (<see cref="PromptForText"/>, the same small dialog <c>btnRenameProject</c>+ /// uses), not a file dialog - the new project always goes into the current root folder (<c>txtRootFolder</c>),+ /// never somewhere else, and there is no file extension to worry about (a project is just a folder, see+ /// <see cref="ProjectStore"/>). Saving under a name that already exists in the root is not refused up front:+ /// <see cref="SaveProjectTo"/> itself asks to overwrite in that case, same as plain Save would for an existing project.+ /// </summary>private void SaveAs_Click(object sender, EventArgs e){- string root = this.txtRootFolder.Text.Trim();+ string root = txtRootFolder.Text.Trim();if (root.Length == 0){MessageBox.Show(this, "Enter a root folder first (double-click the box to browse).", "Save project as", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- string projectName = this.txtProjectName.Text.Trim();- if (!this.PromptForText("Save project as", "New project name (saved in the current root folder):", projectName, ref projectName))+ string projectName = txtProjectName.Text.Trim();+ if (!PromptForText("Save project as", "New project name (saved in the current root folder):", projectName, ref projectName)){return;}@@ -346,23 +411,29 @@ namespace _2D_wave_sim_V01MessageBox.Show(this, error, "Save project as", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);return;}- this.SaveProjectTo(root, projectName);+ SaveProjectTo(root, projectName);}- /// <summary>Opens <see cref="frmDescription"/> for the open project and, on OK, writes the new description to disk at once (without touching <see cref="_projectDirty"/>).</summary>+ /// <summary>+ /// Opens <see cref="frmDescription"/> so the user can add/edit a free-form description of the open project,+ /// stored in the project's own configuration.json (<see cref="ProjectConfig.Description"/>) - written to disk+ /// at once on OK (without touching <see cref="_projectDirty"/>), the same as <c>btnRenameProject</c>'s rename+ /// takes effect right away rather than waiting for "Save project". Only enabled while a real (saved) project+ /// is open (<see cref="UpdateProjectAccess"/>) - a new, unsaved project has no configuration.json yet to hold it.+ /// </summary>private void btnDescription_Click(object sender, EventArgs e){- if (this._project == null)+ if (_project == null){return;}using (frmDescription dialog = new frmDescription()){- dialog.DescriptionText = this._project.Config.Description;+ dialog.DescriptionText = _project.Config.Description;if (dialog.ShowDialog(this) == DialogResult.OK){- this._project.Config.Description = dialog.DescriptionText;- this._project.Save();+ _project.Config.Description = dialog.DescriptionText;+ _project.Save();}}}@@ -392,23 +463,26 @@ namespace _2D_wave_sim_V01}/// <summary>- /// File > Choose project root (also the Browse/Pick root buttons and a double-click on the- /// root text box): asks for a folder, stores it in the user settings immediately and- /// refreshes the project list. The open project, if any, is left as it is.+ /// File > Choose project root, the <c>btnBrowseRoot</c> button, <c>btnPickRoot</c> (the blinking button that+ /// is always reachable even with no root yet - see <see cref="Form1_Load"/>/<see cref="UpdateProjectAccess"/>)+ /// and a double-click on the (read-only) root text box: all four let the user pick the folder that contains+ /// the project folders (<c>txtRootFolder</c> just displays it - <see cref="AppSettings.ProjectRoot"/> is the+ /// real, persisted value, restored again on the next start). Once a root is chosen, <c>grpProjects</c> and+ /// the Outputs tab become usable and the project list is (re)populated. The open project, if any, is left as it is./// </summary>private void ChooseProjectRootToolStripMenuItem_Click(object sender, EventArgs e){- string startFolder = ((this._settings.ProjectRoot.Length > 0) ? this._settings.ProjectRoot : this.txtRootFolder.Text.Trim());- string folder = this.BrowseForFolder("Choose the root folder that contains your project folders", startFolder, true);+ string startFolder = ((_settings.ProjectRoot.Length > 0) ? _settings.ProjectRoot : txtRootFolder.Text.Trim());+ string folder = BrowseForFolder("Choose the root folder that contains your project folders", startFolder, true);if (folder.Length == 0){return;}- this._settings.ProjectRoot = folder;- this._settings.Save();- this.txtRootFolder.Text = folder;- this.UpdateProjectAccess();- this.RefreshProjectList();+ _settings.ProjectRoot = folder;+ _settings.Save();+ txtRootFolder.Text = folder;+ UpdateProjectAccess();+ RefreshProjectList();}/// <summary>Clicking the "(Info)" label shows the explanation of 4th-order processing, dispersion and the c-value.</summary>@@ -420,21 +494,22 @@ namespace _2D_wave_sim_V01/// <summary>/// File > Set c-value: prompts for the wave speed (pixels per step), stores it in/// <see cref="SimulationSettings.WaveSpeedC"/>, marks the project changed if it differs,- /// and refreshes the wavelength read-out on the Sources tab.+ /// and refreshes the wavelength read-out on the Sources tab. c is only used to estimate a+ /// source's wavelength (<c>lblLambdaIs</c> on the Sources tab)./// </summary>private void SetCValueToolStripMenuItem_Click(object sender, EventArgs e){double cValue = 0.0;- if (!this.PromptForCValue(this._simulation.WaveSpeedC, ref cValue))+ if (!PromptForCValue(_simulation.WaveSpeedC, ref cValue)){return;}- if (cValue != this._simulation.WaveSpeedC)+ if (cValue != _simulation.WaveSpeedC){- this._simulation.WaveSpeedC = cValue;- this.MarkProjectChanged();+ _simulation.WaveSpeedC = cValue;+ MarkProjectChanged();}- this.UpdateLambdaLabel();+ UpdateLambdaLabel();}/// <summary>@@ -543,22 +618,22 @@ namespace _2D_wave_sim_V01/// <returns>True when the project was written; false when validation failed, the user cancelled or saving failed.</returns>private bool SaveProject(){- string root = this.txtRootFolder.Text.Trim();- string projectName = this.txtProjectName.Text.Trim();+ string root = txtRootFolder.Text.Trim();+ string projectName = txtProjectName.Text.Trim();if (root.Length == 0){MessageBox.Show(this, "Enter a root folder first (double-click the box to browse).", "Save project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);- this.txtRootFolder.Focus();+ txtRootFolder.Focus();return false;}string error = ProjectStore.ValidateName(projectName);if (error.Length > 0){MessageBox.Show(this, error, "Save project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);- this.txtProjectName.Focus();+ txtProjectName.Focus();return false;}- return this.SaveProjectTo(root, projectName);+ return SaveProjectTo(root, projectName);}/// <summary>@@ -576,7 +651,7 @@ namespace _2D_wave_sim_V01{string rootFolder = ProjectStore.NormalizeFolder(root);string projectFolder = Path.Combine(rootFolder, projectName);- Project previous = this._project;+ Project previous = _project;Project target;if (previous != null && string.Equals(projectFolder, previous.FolderPath, StringComparison.OrdinalIgnoreCase)){@@ -601,13 +676,13 @@ namespace _2D_wave_sim_V01}target = ProjectStore.Create(rootFolder, projectName);}- this.PrepareSceneImageFor(target, previous);- this._scene.ToConfig(target.Config);- this._simulation.ToConfig(target.Config);- ProbeSettings.ListToConfig(this._probes, target.Config);- SourceSettings.ListToConfig(this._sources, target.Config);+ PrepareSceneImageFor(target, previous);+ _scene.ToConfig(target.Config);+ _simulation.ToConfig(target.Config);+ ProbeSettings.ListToConfig(_probes, target.Config);+ SourceSettings.ListToConfig(_sources, target.Config);target.Save();- this.SetCurrentProject(target);+ SetCurrentProject(target);return true;}catch (Exception ex)@@ -622,22 +697,24 @@ namespace _2D_wave_sim_V01/// into <paramref name="target"/>'s scene-image folder (unless it already lies inside the/// target) and rewrites <see cref="SceneSettings.ImageFile"/> as a path stored relative to/// the target. No-op when there is no scene image or the target is the previous project.+ /// This is the same copy that <see cref="btnLOadSceneImage_Click"/> already does when a project+ /// exists; this one catches an image that was picked before the (new) project was ever saved./// </summary>/// <param name="target">The project about to be saved.</param>/// <param name="previous">The project the image path is currently relative to; null for an unsaved project.</param>private void PrepareSceneImageFor(Project target, Project previous){- if (this._scene.ImageFile.Length == 0 || object.ReferenceEquals(target, previous))+ if (_scene.ImageFile.Length == 0 || object.ReferenceEquals(target, previous)){return;}string previousFolder = ((previous == null) ? "" : previous.FolderPath);- string imagePath = SceneSettings.ToFullPath(previousFolder, this._scene.ImageFile);+ string imagePath = SceneSettings.ToFullPath(previousFolder, _scene.ImageFile);if (File.Exists(imagePath) && !Form1.IsInsideFolder(imagePath, target.FolderPath)){imagePath = Form1.CopyIntoSceneImageFolder(target, imagePath);}- this._scene.ImageFile = SceneSettings.ToStoredPath(target.FolderPath, imagePath);+ _scene.ImageFile = SceneSettings.ToStoredPath(target.FolderPath, imagePath);}/// <summary>Case-insensitive test whether <paramref name="fullPath"/> lies below <paramref name="folder"/> (both resolved to full paths); false for an empty folder.</summary>@@ -685,44 +762,56 @@ namespace _2D_wave_sim_V01/// <returns>True when the caller may proceed (nothing to save, saved successfully, or "No"); false on Cancel or a failed save.</returns>private bool ConfirmSaveProject(){- if (this._project == null || !this._projectDirty)+ // Nothing to save when no named project exists yet (a project only exists once it has been loaded from+ // the list or created and named through btnNewProject's dialog) - there is no such thing as an+ // "unsaved new project" to ask about any more.+ if (_project == null || !_projectDirty){return true;}- DialogResult answer = MessageBox.Show(this, "There are unsaved changes in the project '" + this._project.Name + "'. Save them first?", "Unsaved changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);+ DialogResult answer = MessageBox.Show(this, "There are unsaved changes in the project '" + _project.Name + "'. Save them first?", "Unsaved changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);if (answer == DialogResult.Yes){- return this.SaveProject();+ return SaveProject();}return answer == DialogResult.No;}/// <summary>- /// Resets the editor to a fresh, unsaved project: new scene and simulation settings+ /// Resets the in-memory project state to blank defaults: new scene and simulation settings/// (keeping the damping-edge and object-source check boxes and the steps/decay spinners as/// they are), no scene image, default probes, no sources, no video files, not dirty.+ /// Does not touch <c>grpSceneProperties</c>/<c>grpSimulationSettings</c>/<c>grpProjects.Enabled</c> - a+ /// caller that goes on to make a real, named project current (<see cref="SetCurrentProject"/>) re-enables+ /// them there; a caller that ends up with no project at all (e.g. deleting the one that was open) should+ /// instead disable them, since - per the startup design - there is no such thing as an editable "new+ /// project" that does not exist on disk yet./// </summary>private void StartNewProject(){- this._project = null;- this._scene = new SceneSettings();- this._scene.DampingEdgeEnabled = this.chkDampingEdge.Checked;- this._scene.UseObjectSources = this.chkUseObjectSources.Checked;- this.ReplaceSceneImage(null);- this.txtProjectName.Text = "";- this.ShowSceneInControls();- this._simulation = new SimulationSettings();- this._simulation.Steps = Convert.ToInt32(this.numSimulationSteps.Value);- this._simulation.TimeDecayFactor = Convert.ToDouble(this.numTimeDecayFactor.Value);- this.ShowSimulationInControls();- this.ResetProbes();- this.ResetSources();- this._fieldVideoFile = "";- this._intensityVideoFile = "";- this.UpdateVideoButtons();- this._projectDirty = false;- this.UpdateTitle();- this.txtProjectName.Focus();+ _project = null;+ _scene = new SceneSettings();+ // chkDampingEdge and chkUseObjectSources have no software-chosen default of their own (see their+ // docs in SceneSettings) - a new project starts at whatever the controls' own Designer values are+ _scene.DampingEdgeEnabled = chkDampingEdge.Checked;+ _scene.UseObjectSources = chkUseObjectSources.Checked;+ ReplaceSceneImage(null);+ txtProjectName.Text = "";+ ShowSceneInControls();+ _simulation = new SimulationSettings();+ // numSimulationSteps and numTimeDecayFactor have no software-chosen default of their own (see their+ // docs in SimulationSettings) - a new project starts at whatever the controls' own Designer values are+ _simulation.Steps = Convert.ToInt32(numSimulationSteps.Value);+ _simulation.TimeDecayFactor = Convert.ToDouble(numTimeDecayFactor.Value);+ ShowSimulationInControls();+ ResetProbes();+ ResetSources();+ _fieldVideoFile = "";+ _intensityVideoFile = "";+ UpdateVideoButtons();+ _projectDirty = false;+ UpdateTitle();+ txtProjectName.Focus();}/// <summary>@@ -730,30 +819,39 @@ namespace _2D_wave_sim_V01/// them in the user settings, clears the Sources/Probes background pictures when the/// folder differs from the previous project, loads scene, simulation, probes and sources/// from its configuration, clears the dirty flag and refreshes the project list.+ /// Also called by <see cref="SaveProjectTo"/> for a plain "Save project" of the project that is already+ /// open (target and the previous <see cref="_project"/> are then the same folder) - the preview-clearing+ /// must only run when the project is actually changing, or every "Save configuration" would blank the+ /// Sources/Probes tab's picture (see <see cref="ClearPreviewImage"/>) even though nothing about that+ /// picture is out of date./// </summary>private void SetCurrentProject(Project opened){- bool projectChanged = this._project == null || !string.Equals(this._project.FolderPath, opened.FolderPath, StringComparison.OrdinalIgnoreCase);- this._project = opened;- this.txtRootFolder.Text = opened.RootFolder;- this.txtProjectName.Text = opened.Name;- this.UpdateProjectAccess();- this._settings.LastRootFolder = opened.RootFolder;- this._settings.LastProjectName = opened.Name;- this._settings.Save();+ bool projectChanged = _project == null || !string.Equals(_project.FolderPath, opened.FolderPath, StringComparison.OrdinalIgnoreCase);+ _project = opened;+ txtRootFolder.Text = opened.RootFolder;+ txtProjectName.Text = opened.Name;+ UpdateProjectAccess();+ _settings.LastRootFolder = opened.RootFolder;+ _settings.LastProjectName = opened.Name;+ _settings.Save();if (projectChanged){- this.ClearPreviewImage(this._picSource);- this.ClearPreviewImage(this._picProbe);+ // a preview picture (Sources/Probes tab) loaded for the previous project has no relevance to this one -+ // clear it so the tab shows this project's own scene image (or a blank placeholder) the next time it is+ // visited, rather than a leftover picture from whatever was open before (AutoLoadSceneImageIfEmpty only+ // fills a picture that is empty, so a stale one left behind would otherwise never be replaced)+ ClearPreviewImage(_picSource);+ ClearPreviewImage(_picProbe);}- this.LoadSceneFromProject();- this._simulation = SimulationSettings.FromConfig(this._project.Config);- this.ShowSimulationInControls();- this.LoadProbesFromProject();- this.LoadSourcesFromProject();- this._projectDirty = false;- this.UpdateTitle();- this.RefreshProjectList();+ LoadSceneFromProject();+ _simulation = SimulationSettings.FromConfig(_project.Config);+ ShowSimulationInControls();+ LoadProbesFromProject();+ LoadSourcesFromProject();+ _projectDirty = false;+ UpdateTitle();+ RefreshProjectList();}/// <summary>Removes and disposes the image of <paramref name="pic"/>; tolerates a null box or no image.</summary>@@ -775,25 +873,30 @@ namespace _2D_wave_sim_V01/// </summary>private void MarkProjectChanged(){- if (this._loadingScene || this._loadingSim || this._loadingProbe || this._loadingSource)+ if (_loadingScene || _loadingSim || _loadingProbe || _loadingSource){return;}- this._projectDirty = true;- this.UpdateTitle();+ _projectDirty = true;+ UpdateTitle();}/// <summary>Sets the window title to "2D wave simulation - name", with " *" when dirty and the run status appended while a simulation runs.</summary>private void UpdateTitle(){- string projectName = ((this._project == null) ? "(new project)" : this._project.Name);- this.Text = "2D wave simulation - " + projectName + (this._projectDirty ? " *" : "") + ((this._simStatus.Length > 0) ? (" | " + this._simStatus) : "");+ string projectLabel = ((_project == null) ? "(new project)" : _project.Name);+ Text = "2D wave simulation - " + projectLabel + (_projectDirty ? " *" : "") + ((_simStatus.Length > 0) ? (" | " + _simStatus) : "");}/// <summary>- /// Shows a hand-built modal dialog with a path text box, a "Browse..." button (a- /// <see cref="FolderBrowserDialog"/> rooted at My Computer) and OK/Cancel. OK is refused- /// for an empty path, and for a non-existent one unless <paramref name="allowNewFolder"/>.+ /// Lets the user choose a folder: type or paste a full path directly into the box, or click "Browse..."+ /// for the usual Windows tree picker (a <see cref="FolderBrowserDialog"/>) - rooted at "This PC" rather+ /// than the Desktop, so every drive (C:\, D:\, a network drive, anywhere) is one click away instead of+ /// buried under Desktop. This replaces a plain <see cref="FolderBrowserDialog"/> call, which on this+ /// machine shows no address bar to type a path into and makes other drives awkward to reach from its+ /// Desktop-rooted tree. OK is refused for an empty path, and for a non-existent one unless+ /// <paramref name="allowNewFolder"/> (a new, not-yet-created one is then fine - the caller decides+ /// whether/how to create it)./// </summary>/// <param name="description">Text shown above the path box and in the folder browser.</param>/// <param name="startFolder">Initial contents of the path box.</param>@@ -828,6 +931,8 @@ namespace _2D_wave_sim_V01{folderDialog.Description = description;folderDialog.ShowNewFolderButton = allowNewFolder;+ // MyComputer (not the default Desktop) so every drive is a top-level node, reachable in+ // one click instead of nested under Desktop/This PCfolderDialog.RootFolder = Environment.SpecialFolder.MyComputer;if (Directory.Exists(txt.Text.Trim())){@@ -893,7 +998,7 @@ namespace _2D_wave_sim_V01/// <summary>The scheme selected in <c>ListView1</c>, shown read-only in the editor and preview bar; null when nothing is selected.</summary>private ColorScheme _previewScheme;- /// <summary>Index (0..8) of the colour stop of <see cref="_current"/> that the picker is editing; -1 when none.</summary>+ /// <summary>Index (0 to <see cref="ColorScheme.StopCount"/> - 1) of the colour stop of <see cref="_current"/> that the picker is editing; -1 when none.</summary>private int _selectedStop;/// <summary>Re-entrancy guard: set while <see cref="RefreshEditorState"/> programmatically checks the scheme-type radio buttons.</summary>@@ -905,7 +1010,7 @@ namespace _2D_wave_sim_V01/// <summary>The colour picker embedded in <c>Panel2</c> (created in <see cref="Form1_Load"/>).</summary>private ColorPickerControl _picker;- /// <summary>Image list of the 120 x 16 scheme thumbnails shown in <c>ListView1</c>; the bitmaps themselves are owned by <see cref="_thumbBitmaps"/>.</summary>+ /// <summary>Image list of the <see cref="ThumbWidth"/> x <see cref="ThumbHeight"/> scheme thumbnails shown in <c>ListView1</c>; the bitmaps themselves are owned by <see cref="_thumbBitmaps"/>.</summary>private readonly ImageList _thumbs;// ----- Project lists (Form1.Projects.cs / Form1.Output.cs) -----@@ -952,16 +1057,27 @@ namespace _2D_wave_sim_V01/// <summary>Sort direction of the exported-video file list; default descending (newest first).</summary>private bool _videoSortAscending;- /// <summary>Owner of the thumbnail bitmaps added to <see cref="_thumbs"/>; disposed on every reload and on closing.</summary>+ /// <summary>+ /// Owner of the thumbnail bitmaps added to <see cref="_thumbs"/>; disposed on every reload and on closing.+ /// The ImageList keeps using the bitmaps that were added to it (it re-creates its native image list from+ /// them, e.g. after Clear or when the ListView on a hidden tab is created). They must therefore stay+ /// alive until the list is rebuilt or the form is closed, and must not be disposed right after Add.+ /// </summary>private readonly List<Bitmap> _thumbBitmaps;- /// <summary>Nominal scheme thumbnail width in pixels. Not referenced at present: the Colors part uses the literal 120.</summary>+ /// <summary>Scheme thumbnail width in pixels (<see cref="_thumbs"/> image size and <see cref="MakeThumbnail"/>).</summary>private const int ThumbWidth = 120;- /// <summary>Nominal scheme thumbnail height in pixels. Not referenced at present: the Colors part uses the literal 16.</summary>+ /// <summary>Scheme thumbnail height in pixels (<see cref="_thumbs"/> image size and <see cref="MakeThumbnail"/>).</summary>private const int ThumbHeight = 16;// ----- Project state -----+ //+ // A project is a folder inside the root folder; the folder name is the project name (txtProjectName).+ // The main folder of a project holds configuration.json and the standard subfolders (see ProjectStore).+ //+ // The settings on the tabs are kept in memory and only written to configuration.json by "Save project"+ // and "Save as". _project is null for a new project that has not been saved yet./// <summary>The open project; null while editing a new project that has never been saved.</summary>private Project _project;@@ -975,7 +1091,12 @@ namespace _2D_wave_sim_V01/// <summary>Current phase of the <c>btnPickRoot</c> blink (true = highlighted).</summary>private bool _rootBlinkOn;- /// <summary>700 ms timer that blinks <c>btnPickRoot</c> while no project root has been chosen; started/stopped by <see cref="UpdateProjectAccess"/>.</summary>+ /// <summary>+ /// 700 ms timer that blinks <c>btnPickRoot</c> light blue, slowly, while no project root is known yet - e.g.+ /// right after installing on a different computer, when <see cref="AppSettings.ProjectRoot"/> is still empty+ /// and nothing on the Sources/Probes/Viewer tabs works yet. <see cref="UpdateProjectAccess"/> starts/stops+ /// this alongside the rest of the "has a root" state; <see cref="RootBlinkTimer_Tick"/> does the actual blinking.+ /// </summary>private readonly global::System.Windows.Forms.Timer _rootBlinkTimer;// ----- Manage output tab (Form1.Output.cs) -----@@ -1065,7 +1186,12 @@ namespace _2D_wave_sim_V01/// <summary>Sobel edge image of <see cref="_sceneImage"/> at canvas size (owned; see <see cref="ComputeGlowingEdges"/>); null when there is no scene image. Added on top of previews and exports as the "glowing edges" overlay.</summary>private Bitmap _glowEdgesImage;- /// <summary><see cref="_glowEdgesImage"/> resized to <see cref="_glowOverlayCacheSize"/> (owned); null until first requested, rebuilt when the preview size changes.</summary>+ /// <summary>+ /// <see cref="_glowEdgesImage"/> resized to <see cref="_glowOverlayCacheSize"/>, whatever size a preview frame+ /// last asked for (<see cref="GetGlowOverlayResized"/>; owned). Rebuilding this by resampling the full+ /// scene-image-sized picture on every single visualized step of a run would be wasteful, so it is cached+ /// until either the target size or <see cref="_glowEdgesImage"/> itself changes. Null until first requested.+ /// </summary>private Bitmap _glowOverlayCache;/// <summary>Pixel size of <see cref="_glowOverlayCache"/>.</summary>@@ -1077,13 +1203,16 @@ namespace _2D_wave_sim_V01/// <summary>Background picture box on the Probes tab (filling <c>pnlProbeImage</c>). Receives copies of the scene, field or intensity picture via the share buttons; probe markers and graph boxes are painted on top and clicks pick probe positions.</summary>private PictureBox _picProbe;- /// <summary>Set once any simulation has finished. Not read anywhere at present.</summary>+ /// <summary>Set once any simulation has finished (originally meant to turn the stop button into a restart button). Not read anywhere at present.</summary>private bool _hasRun;- /// <summary>Explorer <c>CurrentViewMode</c> value for the icons view (FOLDERVIEWMODE). Not referenced at present: callers of <see cref="OpenFolderInExplorer"/> pass the literal 1.</summary>+ // Windows Explorer's own view-mode numbers (the classic Shell "FOLDERVIEWMODE" enum), used by+ // OpenFolderInExplorer and its callers.++ /// <summary>Explorer <c>CurrentViewMode</c> value for the "Large icons" view (FOLDERVIEWMODE <c>FVM_ICON</c>).</summary>private const int FVM_ICON = 1;- /// <summary>Explorer <c>CurrentViewMode</c> value for the details view (FOLDERVIEWMODE). Not referenced at present: callers of <see cref="OpenFolderInExplorer"/> pass the literal 4.</summary>+ /// <summary>Explorer <c>CurrentViewMode</c> value for the "Details" view (FOLDERVIEWMODE <c>FVM_DETAILS</c>).</summary>private const int FVM_DETAILS = 4;// ----- Probes (Form1.Probes.cs) -----@@ -1147,7 +1276,11 @@ namespace _2D_wave_sim_V01/// <summary>Random generator used when composite sources generate randomised elements.</summary>private readonly Random _sourceRandom;- /// <summary>Normal back colour of <c>btnSaveSource</c>; the button turns orange while the editor has unsaved edits.</summary>+ /// <summary>+ /// <c>btnSaveSource</c>'s own Designer back colour, captured once at startup so <see cref="ClearSourceDirty"/>+ /// can restore exactly that (rather than a hardcoded colour) once the pending changes are saved; the button+ /// turns orange while the editor has unsaved edits.+ /// </summary>private Color _sourceSaveButtonDefaultBackColor;/// <summary>One row of the project list views (stored in the item's <c>Tag</c>).</summary>@@ -1155,8 +1288,8 @@ namespace _2D_wave_sim_V01{public ProjectListEntry(string name, DateTime lastModified){- this.Name = name;- this.LastModified = lastModified;+ Name = name;+ LastModified = lastModified;}/// <summary>Project (folder) name.</summary>@@ -1167,6 +1300,7 @@ namespace _2D_wave_sim_V01}/// <summary>Win32 <c>SIZE</c> structure passed to <see cref="IShellItemImageFactory.GetImage"/>.</summary>+ [StructLayout(LayoutKind.Sequential)]private struct NativeSize{/// <summary>Width in pixels.</summary>@@ -1207,29 +1341,29 @@ namespace _2D_wave_sim_V01{public ProbeControlSet(int index, string title, CheckBox chkOn, ComboBox cmbPlaceOn, ComboBox cmbMeasurement, ComboBox cmbProbeType, ComboBox cmbBoxSize, NumericUpDown numAPosX, NumericUpDown numAPosY, NumericUpDown numBPosX, NumericUpDown numBPosY, Button butPick, RadioButton radRunning, RadioButton radFull, CheckBox chkAutoX, CheckBox chkAutoY, TextBox txtMinY, TextBox txtMaxY, CheckBox chkStartAfter, TextBox txtStartAfter, NumericUpDown numRunningWindow, Control[] bOnlyControls){- this.Index = index;- this.Title = title;- this.ChkOn = chkOn;- this.CmbPlaceOn = cmbPlaceOn;- this.CmbMeasurement = cmbMeasurement;- this.CmbProbeType = cmbProbeType;- this.CmbBoxSize = cmbBoxSize;- this.NumAPosX = numAPosX;- this.NumAPosY = numAPosY;- this.NumBPosX = numBPosX;- this.NumBPosY = numBPosY;- this.ButPick = butPick;- this.RadRunning = radRunning;- this.RadFull = radFull;- this.ChkAutoX = chkAutoX;- this.ChkAutoY = chkAutoY;- this.TxtMinY = txtMinY;- this.TxtMaxY = txtMaxY;- this.ChkStartAfter = chkStartAfter;- this.TxtStartAfter = txtStartAfter;- this.NumRunningWindow = numRunningWindow;- this.BOnlyControls = bOnlyControls;- this.PickButtonText = butPick.Text;+ Index = index;+ Title = title;+ ChkOn = chkOn;+ CmbPlaceOn = cmbPlaceOn;+ CmbMeasurement = cmbMeasurement;+ CmbProbeType = cmbProbeType;+ CmbBoxSize = cmbBoxSize;+ NumAPosX = numAPosX;+ NumAPosY = numAPosY;+ NumBPosX = numBPosX;+ NumBPosY = numBPosY;+ ButPick = butPick;+ RadRunning = radRunning;+ RadFull = radFull;+ ChkAutoX = chkAutoX;+ ChkAutoY = chkAutoY;+ TxtMinY = txtMinY;+ TxtMaxY = txtMaxY;+ ChkStartAfter = chkStartAfter;+ TxtStartAfter = txtStartAfter;+ NumRunningWindow = numRunningWindow;+ BOnlyControls = bOnlyControls;+ PickButtonText = butPick.Text;}/// <summary>Probe index (0 or 1), also the index into <see cref="_probes"/>.</summary>diff --git a/Wave_Dude_2D/FrameRenderer.cs b/Wave_Dude_2D/FrameRenderer.csindex 2aa1abb..389e74d 100644--- a/Wave_Dude_2D/FrameRenderer.cs+++ b/Wave_Dude_2D/FrameRenderer.cs@@ -7,10 +7,14 @@ using System.Threading.Tasks;namespace _2D_wave_sim_V01{/// <summary>- /// Static helpers that turn raw engine field/intensity data into packed ARGB pixel buffers- /// (optionally through a colour LUT), blend a glow overlay on top and wrap the result in a- /// <see cref="Bitmap"/>. Used by <see cref="SimulationRunner"/> (worker thread) and by the video sinks.- /// Row loops run in parallel, so the methods are CPU-bound but not thread-affine.+ /// Static helpers that turn the field or the intensity of a wave engine (CPU or GPU) into packed ARGB+ /// pixel buffers, like <c>WaveVisualizer.render_field</c> and <c>render_intensity</c> in the Python code:+ /// the value is converted to a table index (see <see cref="ColorLut"/>) and the index to a colour. Without+ /// a colour table (null) the index itself is used as grey level. The picture can be smaller than the+ /// simulation (a preview): every picture pixel then takes the nearest simulation pixel. Also blends a glow+ /// overlay on top and wraps the result in a <see cref="Bitmap"/>. Used by <see cref="SimulationRunner"/>+ /// (worker thread) and by the video sinks. Row loops run in parallel, so the methods are CPU-bound but+ /// not thread-affine./// </summary>internal sealed class FrameRenderer{@@ -53,8 +57,8 @@ namespace _2D_wave_sim_V01/// <summary>/// Renders the accumulated intensity, nearest-neighbour scaled to <paramref name="dw"/> x <paramref name="dh"/>.- /// Each value is mapped as <c>sqrt(value) * brightness</c>, clamped to 1, then scaled to palette index 0..254- /// (non-positive values map to 0). Same layout rules as <see cref="RenderField"/>.+ /// Each value is mapped as <c>sqrt(value) * brightness</c> (exponent 0.5, as in the Python code), clamped to 1,+ /// then scaled to palette index 0..254 (non-positive values map to 0). Same layout rules as <see cref="RenderField"/>./// </summary>/// <param name="sim">Engine whose <see cref="IWaveEngine.IntensityData"/> is read (must not be null).</param>/// <param name="lut">ARGB palette indexed 0..254, or null for greyscale.</param>@@ -104,25 +108,29 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Draws <paramref name="bmp"/> unscaled at (0,0) onto a black <paramref name="w"/> x <paramref name="h"/> canvas and- /// returns the canvas as tightly packed 24-bit pixels, 3 bytes per pixel in memory order B,G,R, no row padding.+ /// Reads <paramref name="bmp"/> into a flat array of tightly packed 24-bit pixels, 3 bytes per pixel in memory+ /// order B,G,R, row by row without padding, exactly <paramref name="w"/> x <paramref name="h"/>. The bitmap is+ /// expected to already be that size in the one place this is used (<see cref="SimulationJob.GlowOverlay"/> in+ /// <see cref="SimulationRunner"/>), so this is just a format normalisation, not a real resize: it is drawn+ /// unscaled at (0,0) onto a black <paramref name="w"/> x <paramref name="h"/> bitmap. Used to additively blend+ /// <c>Form1</c>'s "glowing edges" preview overlay into exported video frames, see <see cref="AddOverlay"/>./// </summary>- /// <param name="bmp">Source image (any size; clipped or padded with black to the canvas).</param>- /// <param name="w">Canvas width in pixels.</param>- /// <param name="h">Canvas height in pixels.</param>+ /// <param name="bmp">Source image, normally already <paramref name="w"/> x <paramref name="h"/>.</param>+ /// <param name="w">Width in pixels.</param>+ /// <param name="h">Height in pixels.</param>/// <returns>A new array of <c>w * h * 3</c> bytes.</returns>public static byte[] ToRgbBytes(Bitmap bmp, int w, int h){byte[] rgb = new byte[w * h * 3];- using (Bitmap canvas = new Bitmap(w, h, PixelFormat.Format24bppRgb))+ using (Bitmap normalized = new Bitmap(w, h, PixelFormat.Format24bppRgb)){- using (Graphics g = Graphics.FromImage(canvas))+ using (Graphics g = Graphics.FromImage(normalized)){g.Clear(Color.Black);g.DrawImageUnscaled(bmp, 0, 0);}Rectangle rect = new Rectangle(0, 0, w, h);- BitmapData data = canvas.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);+ BitmapData data = normalized.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);try{int stride = data.Stride;@@ -144,18 +152,22 @@ namespace _2D_wave_sim_V01}finally{- canvas.UnlockBits(data);+ normalized.UnlockBits(data);}}return rgb;}/// <summary>- /// Multiplies every byte of a <see cref="ToRgbBytes"/> buffer by <paramref name="gain"/>, rounded and clamped to 255.+ /// Multiplies every byte of a <see cref="ToRgbBytes"/> buffer by <paramref name="gain"/>, rounded and clamped to 255,+ /// so that <see cref="AddOverlay"/>'s per-frame, per-pixel work is a plain add instead of repeating a floating-point+ /// multiply and a byte conversion on the same bytes for every single exported frame. The gain is fixed for the whole+ /// run (frozen at Start Simulation, like everything else in <see cref="SimulationJob"/>), so there is no reason to+ /// redo this more than once./// </summary>/// <param name="overlayRgb">Packed B,G,R overlay, or null.</param>/// <param name="gain">Multiplier; values <= 0 disable the overlay.</param>- /// <returns>A new scaled copy, or null when the input is null or the gain is <= 0 (nothing to overlay).</returns>+ /// <returns>A new scaled copy, or null (<see cref="AddOverlay"/> then does nothing) when the input is null or the gain is <= 0.</returns>public static byte[] ScaleOverlayRgb(byte[] overlayRgb, double gain){if (overlayRgb == null || gain <= 0.0)@@ -171,8 +183,14 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Additively blends a packed B,G,R overlay (see <see cref="ToRgbBytes"/>) onto ARGB pixels in place, each channel- /// saturating at 255; the alpha byte is kept. Fully black overlay pixels are skipped. No-op when the overlay is null.+ /// Additively blends a gain-prescaled packed B,G,R overlay (see <see cref="ScaleOverlayRgb"/>) onto ARGB pixels+ /// (packed 0xAARRGGBB, as <see cref="RenderField"/>/<see cref="RenderIntensity"/> produce) in place, each channel+ /// saturating at 255: never darkens, never touches the alpha byte, and a black overlay pixel (no edge there) leaves+ /// the pixel untouched. No-op when the overlay is null. Parallelised by row like <see cref="RenderField"/>/+ /// <see cref="RenderIntensity"/>, since this runs once per exported video frame at full simulation resolution and+ /// was the actual cost of the glow-edges overlay on a video export; the live preview (<c>Form1</c>'s own+ /// <c>ComposeGlowOverlay</c>, same multiply-then-add idea, kept separate since it runs on the UI thread against a+ /// <see cref="Bitmap"/>) is comparatively small and only runs a few times a second, so it was never the bottleneck./// </summary>/// <param name="pixels">ARGB buffer of <paramref name="w"/> * <paramref name="h"/> ints, modified in place.</param>/// <param name="scaledOverlayRgb">Overlay of <paramref name="w"/> * <paramref name="h"/> * 3 bytes, or null.</param>diff --git a/Wave_Dude_2D/GpuDeviceInfo.cs b/Wave_Dude_2D/GpuDeviceInfo.csindex 82bf8b3..cc52206 100644--- a/Wave_Dude_2D/GpuDeviceInfo.cs+++ b/Wave_Dude_2D/GpuDeviceInfo.cs@@ -12,8 +12,8 @@ namespace _2D_wave_sim_V01{public GpuDeviceInfo(){- this.Name = "";- this.Vendor = "";+ Name = "";+ Vendor = "";}/// <summary>@@ -103,10 +103,10 @@ namespace _2D_wave_sim_V01/// <summary>CL_DEVICE_VENDOR, or "" when the query fails.</summary>public string Vendor;- /// <summary>True when the device does not share memory with the host (CL_DEVICE_HOST_UNIFIED_MEMORY is 0), i.e. a discrete card.</summary>+ /// <summary>True for a card with its own memory (the NVIDIA GeForce; CL_DEVICE_HOST_UNIFIED_MEMORY is 0), false for the graphics of the processor (Intel UHD).</summary>public bool Discrete;- /// <summary>Rough throughput rank: compute units × max clock in MHz (clock at least 1).</summary>+ /// <summary>Compute units times clock (MHz, at least 1): a rough measure of the speed.</summary>public double Score;/// <summary>CL_DEVICE_GLOBAL_MEM_SIZE in bytes.</summary>diff --git a/Wave_Dude_2D/GpuWaveSimulator.cs b/Wave_Dude_2D/GpuWaveSimulator.csindex 177a152..169e80c 100644--- a/Wave_Dude_2D/GpuWaveSimulator.cs+++ b/Wave_Dude_2D/GpuWaveSimulator.cs@@ -5,39 +5,83 @@ using System.Text;namespace _2D_wave_sim_V01{/// <summary>- /// OpenCL implementation of <see cref="IWaveEngine"/>: the same leapfrog scheme as <see cref="WaveSimulator"/>- /// (padded grid, 9-point or sub-stepped 4th-order Laplacian, soft source blending, two-stage intensity- /// average), with the field, the scene maps, the source tables and the probe buffers all resident on the- /// device. Created through <see cref="TryCreate"/> by <see cref="WaveEngineFactory"/> and driven by+ /// OpenCL implementation of <see cref="IWaveEngine"/>: the 2D wave equation on the graphics card, the same+ /// algorithm as <see cref="WaveSimulator"/> (padded grid with a border of one cell, 9-point or sub-stepped+ /// 4th-order Laplacian, soft source blending, two-stage intensity average), with the field, the scene maps,+ /// the source tables and the probe buffers all resident on the device. Units are those of the CPU engine+ /// (dx = dt = 1, c in cells per step, frequencies in radians per step, time in steps):+ /// <code>+ /// new u = u + (u - previous u) * d + laplacian * c^2 (3x3 kernel 0.066 / 0.184 / -1)+ /// sources: u = u * 0.9 + sin(frequency * t) * amplitude * 0.1+ /// intensity: two cascaded one-pole filters, I1 = I1 * alpha + u^2 * (1 - alpha), I2 = I2 * alpha + I1 * (1 - alpha),+ /// blended (IntensityBlend) into what is shown/exported: Iout = (I1 * (1 - blend) + I2 * blend) * scale+ /// </code>+ /// alpha is derived once per simulation - see the <see cref="WaveSimulator"/> class summary (why two stages+ /// and the blend, not a single, fixed-0.98 filter) and <see cref="SimulationSettings.TimeDecayFactor"/> (why+ /// alpha); scale is <see cref="SimulationSettings.IntensityScale"/> (why it exists). The field, the previous+ /// field, c², d and the intensity stay in the memory of the graphics card; only when a frame is drawn+ /// (<see cref="PrepareFrame"/>) the field and/or intensity are copied back. The arrays have the same layout as+ /// those of the CPU engine, so the same renderer draws both.+ /// Created through <see cref="TryCreate"/> by <see cref="WaveEngineFactory"/> and driven by/// <see cref="SimulationRunner"/> on its worker thread, which is the only thread that enqueues work; the UI/// thread touches only <see cref="PrepareFrame"/>, <see cref="FieldData"/> and <see cref="IntensityData"/>- /// while the runner is paused.+ /// while the runner is paused. Any single thread may drive the engine; it is not safe for concurrent use./// </summary>/// <remarks>- /// The field lives in two ping-pong buffers (<see cref="_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 and uploads are asynchronous;- /// read-backs are blocking. All OpenCL handles are owned by this instance and released by- /// <see cref="Dispose"/> (or by the constructor when building fails); the managed buffers- /// (<see cref="FieldData"/>, <see cref="IntensityData"/>) are plain host copies.+ /// <para>+ /// Optionally (<c>use4thOrderLaplacian</c>), the <c>wave_step</c> kernel instead computes the Laplacian with a+ /// 4th order accurate, 5-point "cross" stencil wherever there is room for it, the same as+ /// <see cref="WaveSimulator"/>'s <c>UpdateField</c> on the CPU (see that class's summary for why). Which form to+ /// use is baked into the generated kernel source as a compile-time <c>#define</c>, not a runtime branch, so+ /// there is no extra cost when it is off.+ /// </para>+ /// <para>+ /// The 4th order stencil needs the same time sub-stepping as the CPU engine to stay stable, for the same+ /// reason (see <see cref="WaveSimulator"/>'s class summary): <see cref="AdvanceOneStep"/> launches+ /// <c>wave_step</c> <see cref="_subSteps"/> times instead of once when <see cref="_subSteps"/> > 1, with c²+ /// scaled by a <c>c2Scale</c> kernel argument (1 / <see cref="_subSteps"/>²) and the d buffer pre-scaled (on+ /// the host, once, at <see cref="Build"/> time) to its 1 / <see cref="_subSteps"/>-th root, so+ /// <see cref="_subSteps"/> kernel launches move the field by exactly the same physical time and damping as+ /// one ordinary launch. The intensity buffer is only updated (via the kernel's <c>track</c> argument) on the+ /// last of the <see cref="_subSteps"/> launches, so its own exponential averaging still runs once per+ /// <see cref="AdvanceOneStep"/> call, matching the CPU engine and its own earlier calibration.+ /// <see cref="_subSteps"/> is 1 (<c>c2Scale</c> exactly 1.0f, an exact no-op multiply, and the d buffer+ /// unchanged) whenever the 3x3 kernel is used or this scene's highest c² does not need sub-stepping - see+ /// <see cref="WaveSimulator.ComputeSubSteps"/>.+ /// </para>+ /// <para>+ /// 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+ /// 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+ /// managed arrays (<see cref="FieldData"/>, <see cref="IntensityData"/>) are plain host copies.+ /// </para>+ /// <para>+ /// Like <see cref="WaveSimulator"/>, portions of this engine are based on WaveSimulator2D by 0x23+ /// (https://github.com/0x23/WaveSimulator2D).+ /// </para>/// </remarks>- internal sealed class GpuWaveSimulator : IWaveEngine+ internal sealed class GpuWaveSimulator : IWaveEngine, IDisposable{/// <summary>- /// Tries to build an engine on each OpenCL GPU reported by <see cref="GpuDeviceInfo.FindAll"/> in turn and- /// returns the first that succeeds. Parameters are those of the <see cref="WaveSimulator"/> constructor.+ /// Tries the GPUs one after the other, the best first (<see cref="GpuDeviceInfo.FindAll"/>), and returns+ /// the first that works. Parameters are those of the <see cref="WaveSimulator"/> constructor./// </summary>/// <param name="scene">Per-cell c² and damping maps plus the image (green-channel) sources.</param>- /// <param name="sourceFrequencyScale">Multiplier in the level-to-angular-frequency mapping; see <see cref="_frequencyBuffer"/>.</param>+ /// <param name="sourceFrequencyScale">Multiplier in the level-to-angular-frequency mapping (level/255 × 0.5 × scale, radians per step).</param>/// <param name="sourceAmplitude">Peak amplitude of the image sources (object sources carry their own).</param>/// <param name="trackIntensity">Whether to allocate and update the intensity buffers; when false <see cref="IntensityData"/> stays null.</param>- /// <param name="use4thOrderLaplacian">Use the 4th-order 5-point-per-axis stencil (with sub-stepping) instead of the 9-point one.</param>- /// <param name="timeDecayFactor">Intensity averaging time in units of 100/level steps; see <see cref="_intensityAlpha"/>.</param>- /// <param name="intensityScale">Multiplier applied to the intensity output.</param>+ /// <param name="use4thOrderLaplacian">Use the 4th-order 5-point-per-axis stencil (with sub-stepping) instead of the 9-point one; see the class summary.</param>+ /// <param name="timeDecayFactor"><see cref="SimulationSettings.TimeDecayFactor"/> - see that property's comment; the retention is derived by <see cref="WaveSimulator.IntensityRetention"/>.</param>+ /// <param name="intensityScale"><see cref="SimulationSettings.IntensityScale"/> - see that property's comment; multiplier applied to the intensity output.</param>/// <param name="problems">Receives "" on success, otherwise why no device worked ("no GPU found …" or the/// per-device failure messages joined by "; ").</param>- /// <param name="objectSources">Interactive sources; those outside the canvas are dropped.</param>+ /// <param name="objectSources">The generated elements of the object sources (Sources tab), or null/empty for none; those outside the canvas are dropped.</param>/// <returns>The engine, or null when no device could be used (see <paramref name="problems"/>).</returns>+ /// <exception cref="DllNotFoundException">There is no OpenCL driver (OpenCL.dll cannot be loaded).</exception>public static GpuWaveSimulator TryCreate(SceneData scene, double sourceFrequencyScale, double sourceAmplitude, bool trackIntensity, bool use4thOrderLaplacian, double timeDecayFactor, double intensityScale, ref string problems, List<SourceElement> objectSources = null){problems = "";@@ -73,52 +117,46 @@ namespace _2D_wave_sim_V01/// throws, everything allocated so far is released before the exception propagates./// </summary>/// <exception cref="InvalidOperationException">The scene is too large for the device, or the OpenCL program could not be built.</exception>- private GpuWaveSimulator(GpuDeviceInfo device, SceneData scene, double sourceFrequencyScale, double sourceAmplitude, bool trackIntensity, bool use4thOrderLaplacian, double timeDecayFactor, double intensityScale, List<SourceElement> objectSources = null)+ private GpuWaveSimulator(GpuDeviceInfo device, SceneData scene, double sourceFrequencyScale, double sourceAmplitude, bool trackIntensity, bool use4thOrderLaplacian, double timeDecayFactor, double intensityScale, List<SourceElement> objectSources){- this._field = new IntPtr[2];- this._stepKernel = new IntPtr[2];- this._sourceKernel = new IntPtr[2];- this._objSourceKernel = new IntPtr[2];- this._objGrid1D = new IntPtr[1];- this._grid2D = new IntPtr[2];- this._grid1D = new IntPtr[1];- this._probeKernel = new IntPtr[2];- this._probeGrid = new IntPtr[1];- this._probeValues = new List<List<float>>();- this._gatherKernel = new IntPtr[2];- this._profileGrid = new IntPtr[1];- this._description = "GPU: " + device.Name + " (OpenCL)";- this._width = scene.Width;- this._height = scene.Height;- this._stride = this._width + 2;- this._cells = this._stride * (this._height + 2);- this._track = trackIntensity;- this._sourceCount = scene.SourceCount;- this._amplitude = (float)sourceAmplitude;- this._use4thOrderLaplacian = use4thOrderLaplacian;- if (device.MaxAllocation > 0L && (long)this._cells * 4L > device.MaxAllocation)+ Description = "GPU: " + device.Name + " (OpenCL)";+ _device = device;+ _width = scene.Width;+ _height = scene.Height;+ _stride = _width + 2;+ _cells = _stride * (_height + 2);+ _track = trackIntensity;+ _sourceCount = scene.SourceCount;+ if (device.MaxAllocation > 0L && (long)_cells * 4L > device.MaxAllocation){throw new InvalidOperationException("the scene is too large for this GPU");}+ // object sources: keep only the elements whose position is inside the canvas (a randomized composite+ // element can fall outside), same filtering as the CPU engine (WaveSimulator)List<SourceElement> sourcesInScene = new List<SourceElement>();if (objectSources != null){foreach (SourceElement source in objectSources){- if (source.PosX >= 0 && source.PosX < this._width && source.PosY >= 0 && source.PosY < this._height)+ if (source.PosX >= 0 && source.PosX < _width && source.PosY >= 0 && source.PosY < _height){sourcesInScene.Add(source);}}}- this._objSourceCount = sourcesInScene.Count;+ _objSourceCount = sourcesInScene.Count;+ _grid2D = new[] { new IntPtr(_width), new IntPtr(_height) };+ _grid1D = new[] { new IntPtr(Math.Max(1, _sourceCount)) };+ _objGrid1D = new[] { new IntPtr(Math.Max(1, _objSourceCount)) };+ _hostField = new float[_cells];+ _hostIntensity = trackIntensity ? new float[_cells] : null;try{- this.Build(device, scene, sourceFrequencyScale, timeDecayFactor, intensityScale, sourcesInScene);+ Build(scene, sourceFrequencyScale, (float)sourceAmplitude, use4thOrderLaplacian, timeDecayFactor, (float)intensityScale, sourcesInScene);}catch{- this.ReleaseAll();+ ReleaseAll();throw;}}@@ -132,274 +170,222 @@ namespace _2D_wave_sim_V01/// 1-float dummies so the kernel arguments are still valid. The kernel arguments that change per step/// (time, per-sub-step track flag) are left to <see cref="AdvanceOneStep"/>./// </summary>- /// <param name="device">The OpenCL device (and its platform) to create the context on.</param>/// <param name="scene">Per-cell c² and damping maps plus the image sources.</param>- /// <param name="sourceFrequencyScale">Multiplier in the level-to-angular-frequency mapping; see <see cref="_frequencyBuffer"/>.</param>- /// <param name="timeDecayFactor">Intensity averaging time in units of 100/level steps; see <see cref="_intensityAlpha"/>.</param>+ /// <param name="sourceFrequencyScale">Multiplier in the level-to-angular-frequency mapping.</param>+ /// <param name="sourceAmplitude">Peak amplitude of the image sources.</param>+ /// <param name="use4thOrderLaplacian">Compile the program with <c>USE_4TH_ORDER</c> and sub-step accordingly.</param>+ /// <param name="timeDecayFactor">Intensity averaging time in units of 100/level steps.</param>/// <param name="intensityScale">Multiplier applied to the intensity output.</param>/// <param name="objectSources">Object sources already filtered to those inside the canvas.</param>/// <exception cref="InvalidOperationException">The OpenCL program could not be built (message includes the build log).</exception>- private void Build(GpuDeviceInfo device, SceneData scene, double sourceFrequencyScale, double timeDecayFactor, double intensityScale, List<SourceElement> objectSources)+ private void Build(SceneData scene, double sourceFrequencyScale, float sourceAmplitude, bool use4thOrderLaplacian, double timeDecayFactor, float intensityScale, List<SourceElement> objectSources){int err = 0;- this._deviceId = device.DeviceId;- IntPtr[] contextProperties = new IntPtr[]- {- new IntPtr(OpenClApi.ContextPlatformProperty),- device.PlatformId,- IntPtr.Zero- };- IntPtr[] deviceIds = new IntPtr[] { device.DeviceId };- this._context = OpenClApi.clCreateContext(contextProperties, 1U, deviceIds, IntPtr.Zero, IntPtr.Zero, ref err);+ IntPtr[] contextProperties = { new IntPtr(OpenClApi.ContextPlatformProperty), _device.PlatformId, IntPtr.Zero };+ IntPtr[] deviceIds = { _device.DeviceId };+ _context = OpenClApi.clCreateContext(contextProperties, 1U, deviceIds, IntPtr.Zero, IntPtr.Zero, ref err);OpenClApi.Check(err, "clCreateContext");- this._queue = OpenClApi.clCreateCommandQueue(this._context, device.DeviceId, 0UL, ref err);+ _queue = OpenClApi.clCreateCommandQueue(_context, _device.DeviceId, 0UL, ref err);OpenClApi.Check(err, "clCreateCommandQueue");- string[] sources = new string[] { GpuWaveSimulator.KernelSource(this._use4thOrderLaplacian) };- this._program = OpenClApi.clCreateProgramWithSource(this._context, 1U, sources, null, ref err);- OpenClApi.Check(err, "clCreateProgramWithSource");- string buildOptions = "";- err = OpenClApi.clBuildProgram(this._program, 1U, deviceIds, ref buildOptions, IntPtr.Zero, IntPtr.Zero);- if (err != 0)- {- string buildLog = OpenClApi.BuildLog(this._program, device.DeviceId);- throw new InvalidOperationException("the program for the GPU could not be built (" + OpenClApi.ErrorName(err) + ")" + ((buildLog.Length > 0) ? (": " + buildLog) : ""));- }- float[] c2 = new float[this._cells];- float[] damping = new float[this._cells];- for (int y = 0; y < this._height; y++)- {- Array.Copy(scene.C2, y * this._width, c2, (y + 1) * this._stride + 1, this._width);- Array.Copy(scene.D, y * this._width, damping, (y + 1) * this._stride + 1, this._width);- }- float maxC2 = 0f;- if (this._use4thOrderLaplacian)+ _scene.Program = BuildProgram(KernelSource(use4thOrderLaplacian), "the program for the GPU");++ // the scene, with a border of one cell like the CPU engine (padded layout)+ float[] c2 = new float[_cells];+ float[] damping = new float[_cells];+ for (int y = 0; y < _height; y++){- for (int i = 0; i < c2.Length; i++)- {- if (c2[i] > maxC2)- {- maxC2 = c2[i];- }- }+ Array.Copy(scene.C2, y * _width, c2, (y + 1) * _stride + 1, _width);+ Array.Copy(scene.D, y * _width, damping, (y + 1) * _stride + 1, _width);}- this._subSteps = (this._use4thOrderLaplacian ? GpuWaveSimulator.ComputeSubSteps(maxC2) : 1);- float[] dampingPerSubStep = damping;- if (this._subSteps > 1)+ // see the class summary: sub-stepping keeps the 4th order stencil stable without changing the physical+ // wave speed or damping - _subSteps stays 1 (no sub-stepping) unless the 4th order stencil is in use and+ // this scene's highest c² actually needs it. The d buffer uploaded below is pre-scaled to match (its+ // 1 / _subSteps-th root, or unchanged when _subSteps = 1), same as WaveSimulator's _dEffective on the CPU.+ _subSteps = use4thOrderLaplacian ? WaveSimulator.ComputeSubSteps(WaveSimulator.MaxOf(c2)) : 1;+ // 1 / _subSteps², or exactly 1f when _subSteps = 1 (a bit-for-bit no-op multiply in the kernel)+ float c2Mult = 1f;+ if (_subSteps > 1){// Damping is applied once per sub-step, so take the sub-step root to keep the per-step decay unchanged.- float[] adjusted = new float[damping.Length];- double exponent = 1.0 / this._subSteps;+ double exponent = 1.0 / _subSteps;for (int i = 0; i < damping.Length; i++){- adjusted[i] = (float)Math.Pow(damping[i], exponent);+ damping[i] = (float)Math.Pow(damping[i], exponent);}- dampingPerSubStep = adjusted;// A sub-step is 1/subSteps long, so c²·dt² shrinks by 1/subSteps².- this._c2Mult = 1f / (float)(this._subSteps * this._subSteps);- }- else- {- this._c2Mult = 1f;- }- this._c2Buffer = this.CreateFloatBuffer(c2);- this._dBuffer = this.CreateFloatBuffer(dampingPerSubStep);- float[] zeros = new float[this._cells];- this._field[0] = this.CreateFloatBuffer(zeros);- this._field[1] = this.CreateFloatBuffer(zeros);- if (this._track)- {- this._intensityBuffer = this.CreateFloatBuffer(zeros);- this._intensityStage1Buffer = this.CreateFloatBuffer(zeros);- this._intensityOutBuffer = this.CreateFloatBuffer(zeros);- }- else- {- // Not tracked: the kernels still need valid buffer arguments, and they never touch them.- this._intensityBuffer = this.CreateFloatBuffer(new float[1]);- this._intensityStage1Buffer = this.CreateFloatBuffer(new float[1]);- this._intensityOutBuffer = this.CreateFloatBuffer(new float[1]);- }- if (this._sourceCount > 0 || this._objSourceCount > 0)+ c2Mult = 1f / (_subSteps * _subSteps);+ }+ IntPtr c2Buffer = CreateBuffer(c2, _scene);+ IntPtr dBuffer = CreateBuffer(damping, _scene);+ float[] zeros = new float[_cells];+ _field[0] = CreateBuffer(zeros, _scene);+ _field[1] = CreateBuffer(zeros, _scene);+ // Not tracked: the kernels still need valid buffer arguments, and they never touch them.+ float[] intensityInit = _track ? zeros : new float[1];+ // the two cascaded exponential-filter stages that make up the intensity - see the class summary and+ // WaveSimulator._intensity / _intensityStage1 (CPU engine); used only inside wave_step, never read back -+ // what is read back/probed is their blend, _intensityOutBuffer (WaveSimulator._intensityOut on the CPU)+ IntPtr intensityBuffer = CreateBuffer(intensityInit, _scene);+ IntPtr intensityStage1Buffer = CreateBuffer(intensityInit, _scene);+ _intensityOutBuffer = CreateBuffer(intensityInit, _scene);++ // the level-to-frequency table (level 0-255 -> frequency), shared by the image sources and the object sources+ IntPtr frequencyBuffer = IntPtr.Zero;+ if (_sourceCount > 0 || _objSourceCount > 0){float[] frequencies = new float[256];for (int level = 0; level <= 255; level++){frequencies[level] = (float)(level / 255.0 * 0.5 * sourceFrequencyScale);}- this._frequencyBuffer = this.CreateFloatBuffer(frequencies);- }- // The intensity decay time is scaled by the lowest (slowest) source level in use; 100 when none has a level.- int minLevel = 0;- for (int i = 0; i < this._sourceCount; i++)- {- int level = scene.SourceLevel[i];- if (level > 0 && (minLevel == 0 || level < minLevel))- {- minLevel = level;- }- }- foreach (SourceElement source in objectSources)- {- if (source.Level > 0 && (minLevel == 0 || source.Level < minLevel))- {- minLevel = source.Level;- }- }- if (minLevel == 0)- {- minLevel = 100;- }- double decaySteps = Math.Max(1.0, timeDecayFactor * 100.0 / (double)minLevel);- this._intensityAlpha = (float)Math.Exp(-1.0 / decaySteps);- this._intensityScale = (float)intensityScale;- if (this._sourceCount > 0)- {- int[] indices = new int[this._sourceCount];- int[] levels = new int[this._sourceCount];- for (int i = 0; i < this._sourceCount; i++)- {- indices[i] = (scene.SourceY[i] + 1) * this._stride + scene.SourceX[i] + 1;- levels[i] = scene.SourceLevel[i];- }- this._indexBuffer = this.CreateIntBuffer(indices);- this._levelBuffer = this.CreateIntBuffer(levels);+ frequencyBuffer = CreateBuffer(frequencies, _scene);}- if (this._objSourceCount > 0)+ // the image sources (from the green channel of the scene image)+ bool[] levelUsed = new bool[256];+ int[] indices = new int[_sourceCount];+ int[] levels = new int[_sourceCount];+ for (int i = 0; i < _sourceCount; i++){- int[] objIndices = new int[this._objSourceCount];- int[] objLevels = new int[this._objSourceCount];- float[] objAmplitudes = new float[this._objSourceCount];- float[] objPhases = new float[this._objSourceCount];- int[] objModes = new int[this._objSourceCount];- int[] objPulseShapes = new int[this._objSourceCount];- int[] objOnWidths = new int[this._objSourceCount];- int[] objOffWidths = new int[this._objSourceCount];- int[] objDetachSteps = new int[this._objSourceCount];- int[] objOffWidthBases = new int[this._objSourceCount];- int[] objRandomizeOffWidthAmounts = new int[this._objSourceCount];- float[] objCycleAnchors = new float[this._objSourceCount];- int[] objRngStates = new int[this._objSourceCount];- Random random = new Random();- for (int i = 0; i < this._objSourceCount; i++)- {- SourceElement source = objectSources[i];- objIndices[i] = (source.PosY + 1) * this._stride + source.PosX + 1;- objLevels[i] = source.Level;- objAmplitudes[i] = (float)source.Amplitude;- objPhases[i] = (float)source.PhaseRad;- objModes[i] = ((source.Mode == SourceMode.Pulsed) ? 1 : 0);- objPulseShapes[i] = ((source.PulseShape == SourcePulseShape.SmoothedSquare) ? 1 : 0);- objOnWidths[i] = source.OnWidthCycles;- objOffWidths[i] = source.OffWidthCycles;- objDetachSteps[i] = source.DetachAfterStep;- objOffWidthBases[i] = source.OffWidthBase;- objRandomizeOffWidthAmounts[i] = source.RandomizeOffWidthAmount;- objCycleAnchors[i] = 0f;- // xorshift32 never leaves state 0, so a zero seed would make the off-width constant.- int seed = random.Next(int.MinValue, int.MaxValue);- if (seed == 0)- {- seed = 1;- }- objRngStates[i] = seed;- }- this._objIndexBuffer = this.CreateIntBuffer(objIndices);- this._objLevelBuffer = this.CreateIntBuffer(objLevels);- this._objAmplitudeBuffer = this.CreateFloatBuffer(objAmplitudes);- this._objPhaseBuffer = this.CreateFloatBuffer(objPhases);- this._objModeBuffer = this.CreateIntBuffer(objModes);- this._objPulseShapeBuffer = this.CreateIntBuffer(objPulseShapes);- this._objOnWidthBuffer = this.CreateIntBuffer(objOnWidths);- this._objOffWidthBuffer = this.CreateIntBuffer(objOffWidths);- this._objDetachStepBuffer = this.CreateIntBuffer(objDetachSteps);- this._objOffWidthBaseBuffer = this.CreateIntBuffer(objOffWidthBases);- this._objRandomizeOffWidthAmountBuffer = this.CreateIntBuffer(objRandomizeOffWidthAmounts);- this._objCycleAnchorBuffer = this.CreateFloatBuffer(objCycleAnchors);- this._objRngStateBuffer = this.CreateIntBuffer(objRngStates);+ indices[i] = (scene.SourceY[i] + 1) * _stride + scene.SourceX[i] + 1;+ levels[i] = scene.SourceLevel[i];+ levelUsed[scene.SourceLevel[i]] = true;}+ // the intensity's averaging time constant scales inversely with the frequency of the slowest active source+ // (image or object; a level of 0 means "no source" and is excluded) - see WaveSimulator's identical+ // computation (CPU engine) and SimulationSettings.TimeDecayFactor's comment for why. This exponential-+ // average decay factor replaces the old fixed 0.98f in the kernel.+ float intensityAlpha = WaveSimulator.IntensityRetention(timeDecayFactor, WaveSimulator.LowestSourceLevel(levelUsed, objectSources));+// Kernel k reads field[k] and writes field[1 - k]; argument 4 (sources) / 11 (object sources) is the// time and argument 8 of wave_step the track flag, both set per launch in AdvanceOneStep.for (int k = 0; k <= 1; k++){- this._stepKernel[k] = this.CreateKernel("wave_step");- GpuWaveSimulator.SetMem(this._stepKernel[k], 0U, this._field[k]);- GpuWaveSimulator.SetMem(this._stepKernel[k], 1U, this._field[1 - k]);- GpuWaveSimulator.SetMem(this._stepKernel[k], 2U, this._c2Buffer);- GpuWaveSimulator.SetMem(this._stepKernel[k], 3U, this._dBuffer);- GpuWaveSimulator.SetMem(this._stepKernel[k], 4U, this._intensityBuffer);- GpuWaveSimulator.SetInt(this._stepKernel[k], 5U, this._width);- GpuWaveSimulator.SetInt(this._stepKernel[k], 6U, this._height);- GpuWaveSimulator.SetInt(this._stepKernel[k], 7U, this._stride);- GpuWaveSimulator.SetInt(this._stepKernel[k], 8U, this._track ? 1 : 0);- GpuWaveSimulator.SetFloat(this._stepKernel[k], 9U, this._c2Mult);- GpuWaveSimulator.SetFloat(this._stepKernel[k], 10U, this._intensityAlpha);- GpuWaveSimulator.SetMem(this._stepKernel[k], 11U, this._intensityStage1Buffer);- GpuWaveSimulator.SetMem(this._stepKernel[k], 12U, this._intensityOutBuffer);- GpuWaveSimulator.SetFloat(this._stepKernel[k], 13U, this._intensityScale);- if (this._sourceCount > 0)+ IntPtr step = _stepKernel[k] = CreateKernel(_scene, "wave_step");+ SetMem(step, 0U, _field[k]);+ SetMem(step, 1U, _field[1 - k]);+ SetMem(step, 2U, c2Buffer);+ SetMem(step, 3U, dBuffer);+ SetMem(step, 4U, intensityBuffer);+ SetInt(step, 5U, _width);+ SetInt(step, 6U, _height);+ SetInt(step, 7U, _stride);+ SetInt(step, 8U, _track ? 1 : 0);+ SetFloat(step, 9U, c2Mult);+ SetFloat(step, 10U, intensityAlpha);+ SetMem(step, 11U, intensityStage1Buffer);+ SetMem(step, 12U, _intensityOutBuffer);+ SetFloat(step, 13U, intensityScale);+ }+ if (_sourceCount > 0)+ {+ IntPtr indexBuffer = CreateBuffer(indices, _scene);+ IntPtr levelBuffer = CreateBuffer(levels, _scene);+ for (int k = 0; k <= 1; k++){- this._sourceKernel[k] = this.CreateKernel("apply_sources");- GpuWaveSimulator.SetMem(this._sourceKernel[k], 0U, this._field[k]);- GpuWaveSimulator.SetMem(this._sourceKernel[k], 1U, this._indexBuffer);- GpuWaveSimulator.SetMem(this._sourceKernel[k], 2U, this._levelBuffer);- GpuWaveSimulator.SetMem(this._sourceKernel[k], 3U, this._frequencyBuffer);- GpuWaveSimulator.SetFloat(this._sourceKernel[k], 5U, this._amplitude);- GpuWaveSimulator.SetInt(this._sourceKernel[k], 6U, this._sourceCount);- }- if (this._objSourceCount > 0)- {- this._objSourceKernel[k] = this.CreateKernel("apply_object_sources");- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 0U, this._field[k]);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 1U, this._objIndexBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 2U, this._objLevelBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 3U, this._objAmplitudeBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 4U, this._objPhaseBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 5U, this._objModeBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 6U, this._objPulseShapeBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 7U, this._objOnWidthBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 8U, this._objOffWidthBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 9U, this._objDetachStepBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 10U, this._frequencyBuffer);- GpuWaveSimulator.SetInt(this._objSourceKernel[k], 12U, this._objSourceCount);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 13U, this._objOffWidthBaseBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 14U, this._objRandomizeOffWidthAmountBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 15U, this._objCycleAnchorBuffer);- GpuWaveSimulator.SetMem(this._objSourceKernel[k], 16U, this._objRngStateBuffer);+ IntPtr kernel = _sourceKernel[k] = CreateKernel(_scene, "apply_sources");+ SetMem(kernel, 0U, _field[k]);+ SetMem(kernel, 1U, indexBuffer);+ SetMem(kernel, 2U, levelBuffer);+ SetMem(kernel, 3U, frequencyBuffer);+ SetFloat(kernel, 5U, sourceAmplitude);+ SetInt(kernel, 6U, _sourceCount);}}- this._grid2D[0] = new IntPtr(this._width);- this._grid2D[1] = new IntPtr(this._height);- this._grid1D[0] = new IntPtr(Math.Max(1, this._sourceCount));- this._objGrid1D[0] = new IntPtr(Math.Max(1, this._objSourceCount));- this._hostField = new float[this._cells];- if (this._track)+ if (_objSourceCount > 0){- this._hostIntensity = new float[this._cells];+ BuildObjectSourceKernels(objectSources, frequencyBuffer);}- this._current = 0;}/// <summary>- /// Number of sub-steps per step needed to keep the 4th-order stencil stable for the largest c² in the- /// scene: the smallest n with c²·λmax/n² ≤ 2, at least 1. Same formula as- /// <see cref="WaveSimulator"/> (λmax = 32/3 for the 2D 4th-order stencil, 2 leaves a margin below the- /// leapfrog bound of 4).+ /// Object sources (Sources tab): the flat list of generated point-source elements that are within the+ /// canvas, one entry per element. Uploads one table per <see cref="SourceElement"/> property (see the+ /// <c>apply_object_sources</c> kernel comment for the layout) and binds the two+ /// <c>apply_object_sources</c> kernels. The frequency table (<paramref name="frequencyBuffer"/>, indexed+ /// by level) is shared with the image sources since both use the same level-to-frequency scale. The cycle+ /// anchors start at 0 and every source gets a non-zero xorshift32 seed./// </summary>- private static int ComputeSubSteps(float maxC2)+ private void BuildObjectSourceKernels(List<SourceElement> objectSources, IntPtr frequencyBuffer){- if (maxC2 <= 0f)+ int n = _objSourceCount;+ int[] index = new int[n], level = new int[n], mode = new int[n], pulseShape = new int[n];+ int[] onWidth = new int[n], offWidth = new int[n], detachStep = new int[n];+ int[] offWidthBase = new int[n], randomizeOffWidthAmount = new int[n], rngState = new int[n];+ float[] amplitude = new float[n], phase = new float[n], cycleAnchor = new float[n];+ // a local, host-side RNG just to seed each element's on-GPU xorshift32 generator - xorshift needs a+ // nonzero starting state, so 0 is never allowed+ Random seedRng = new Random();+ for (int i = 0; i < n; i++)+ {+ SourceElement source = objectSources[i];+ index[i] = (source.PosY + 1) * _stride + source.PosX + 1;+ level[i] = source.Level;+ amplitude[i] = (float)source.Amplitude;+ phase[i] = (float)source.PhaseRad;+ mode[i] = source.Mode == SourceMode.Pulsed ? 1 : 0;+ pulseShape[i] = source.PulseShape == SourcePulseShape.SmoothedSquare ? 1 : 0;+ onWidth[i] = source.OnWidthCycles;+ offWidth[i] = source.OffWidthCycles;+ detachStep[i] = source.DetachAfterStep;+ offWidthBase[i] = source.OffWidthBase;+ randomizeOffWidthAmount[i] = source.RandomizeOffWidthAmount;+ // xorshift32 never leaves state 0, so a zero seed would make the off-width constant.+ int seed = seedRng.Next(int.MinValue, int.MaxValue);+ rngState[i] = seed == 0 ? 1 : seed;+ }+ // Buffer arguments by kernel argument index; 0 is the field (per kernel instance), 11 the time+ // (per launch) and 12 the count (scalar), see the apply_object_sources signature.+ IntPtr[] buffers = new IntPtr[17];+ buffers[1] = CreateBuffer(index, _scene);+ buffers[2] = CreateBuffer(level, _scene);+ buffers[3] = CreateBuffer(amplitude, _scene);+ buffers[4] = CreateBuffer(phase, _scene);+ buffers[5] = CreateBuffer(mode, _scene);+ buffers[6] = CreateBuffer(pulseShape, _scene);+ buffers[7] = CreateBuffer(onWidth, _scene);+ // the off-width currently in effect for each element, in cycles; read-write on the GPU (see+ // apply_object_sources) since an element with RandomizeOffWidthAmount > 0 redraws it there each time it+ // completes a cycle+ buffers[8] = CreateBuffer(offWidth, _scene);+ // "detach source": the step at which each element stops driving the field (releasing its hold on it), or -1 to never+ buffers[9] = CreateBuffer(detachStep, _scene);+ buffers[10] = frequencyBuffer;+ // 13-16 were appended at the end rather than renumbering 0-12, so every SetMem/SetInt call (and the+ // per-launch SetFloat for t at index 11 in AdvanceOneStep) kept its existing, already-correct index.+ // Runtime state for off-width re-randomization (see SourceElement.RandomizeOffWidthAmount): the+ // un-randomized anchor each redraw is centered on, the per-element +/- spread (0 = never redraw), the+ // cycle-clock value at which each element's current off+on cycle started, and a per-element xorshift32+ // PRNG seed (kernel-side reinterpreted as uint - only the entropy bits matter, not signedness)+ buffers[13] = CreateBuffer(offWidthBase, _scene);+ buffers[14] = CreateBuffer(randomizeOffWidthAmount, _scene);+ buffers[15] = CreateBuffer(cycleAnchor, _scene);+ buffers[16] = CreateBuffer(rngState, _scene);+ for (int k = 0; k <= 1; k++){- return 1;+ IntPtr kernel = _objSourceKernel[k] = CreateKernel(_scene, "apply_object_sources");+ SetMem(kernel, 0U, _field[k]);+ for (uint a = 1; a < buffers.Length; a++)+ {+ if (buffers[a] != IntPtr.Zero)+ {+ SetMem(kernel, a, buffers[a]);+ }+ }+ SetInt(kernel, 12U, n);}- // 10.666666984558105 is (double)10.666667f, i.e. the CPU engine's FourthOrderLambdaMax.- double steps = Math.Ceiling(Math.Sqrt(maxC2 * 10.666666984558105 / 2.0));- return Math.Max(1, (int)Math.Round(steps));}/// <summary>/// OpenCL source of the simulation program: <c>wave_step</c>, <c>apply_sources</c> and/// <c>apply_object_sources</c>, each a GPU transcription of the corresponding <see cref="WaveSimulator"/>- /// routine. The stencil is chosen at compile time through the <c>USE_4TH_ORDER</c> define.+ /// routine. <paramref name="use4thOrderLaplacian"/> selects, at compile time (a <c>#define</c>, not a+ /// runtime branch), which form of the Laplacian <c>wave_step</c> uses - see the class summary and+ /// <see cref="WaveSimulator"/>'s <c>UpdateField</c>, whose CPU-side stencils and boundary logic this mirrors+ /// exactly. <c>wave_step</c>'s <c>c2Scale</c> argument is the sub-stepping scale (see the class summary),+ /// and its <c>intensityAlpha</c> argument is the intensity's exponential-average decay factor - both are+ /// runtime kernel arguments rather than a <c>#define</c>, so they need no text formatting/locale handling+ /// here. The only value spliced into the text is <see cref="SourceElement.DetachRampSteps"/>, an integer,+ /// which formats the same in every locale; floats are deliberately never spliced./// </summary>private static string KernelSource(bool use4thOrderLaplacian){@@ -428,6 +414,9 @@ namespace _2D_wave_sim_V01source.AppendLine(" float uc = u[i];");source.AppendLine(" float lap;");source.AppendLine("#if USE_4TH_ORDER");+ // the 4th order 5-point "cross" stencil (reaches 2 cells away along x and along y), only where the domain+ // has that much room - the outermost ring (x = 0, x = w - 1, y = 0, y = h - 1) falls back to the 3x3+ // kernel below, the same boundary rule as WaveSimulator.UpdateField on the CPUsource.AppendLine(" if (x >= 1 && x <= w - 2 && y >= 1 && y <= h - 2) {");source.AppendLine(" lap = (-1.0f / 12.0f) * (u[i - 2] + u[i + 2] + u[i - 2 * stride] + u[i + 2 * stride])");source.AppendLine(" + (4.0f / 3.0f) * (u[i - 1] + u[i + 1] + u[i - stride] + u[i + stride])");@@ -442,6 +431,8 @@ namespace _2D_wave_sim_V01source.AppendLine("#endif");source.AppendLine(" float nv = uc + (uc - up[i]) * d[i] + lap * c2[i] * c2Scale;");source.AppendLine(" up[i] = nv;");+ // two cascaded one-pole stages, blended (0.5f - see WaveSimulator.IntensityBlend, CPU engine) into what is+ // read back/probed (intenOut) instead of using the full 2-stage cascade outright - see the class summarysource.AppendLine(" if (track != 0) {");source.AppendLine(" float s1 = inten1[i] * intensityAlpha + nv * nv * (1.0f - intensityAlpha);");source.AppendLine(" inten1[i] = s1;");@@ -464,7 +455,10 @@ namespace _2D_wave_sim_V01source.AppendLine(" u[p] = u[p] * 0.9f + sin(freq[level[k]] * t) * amp * 0.1f;");source.AppendLine("}");source.AppendLine();- // xorshift32: the per-source random generator for randomized off-widths (state must never be 0).+ // xorshift32: OpenCL has no built-in RNG, so object sources that re-randomize their off-width (see+ // SourceElement.RandomizeOffWidthAmount) carry their own per-element state (rngState, seeded host-side,+ // nonzero) through this. Matches WaveSimulator's use of SourceSettings.RandomInt only in spirit (a uniform+ // draw in [-amount, amount]), not bit-for-bit - the two engines are not expected to reproduce each other.source.AppendLine("inline uint xorshift32(uint x)");source.AppendLine("{");source.AppendLine(" x ^= x << 13;");@@ -473,18 +467,28 @@ namespace _2D_wave_sim_V01source.AppendLine(" return x;");source.AppendLine("}");source.AppendLine();- // apply_object_sources: soft-blends the object sources into the field, one work item per source k < n.+ // apply_object_sources (Sources tab): soft-blends the object sources into the field, one element per+ // work item k < n, same math as WaveSimulator.ApplySources/ComputePulsePosition/PulseEnvelope on the CPU.// All per-source tables are indexed by k:// idx, level, amp, phase cell index, frequency level (into freq), amplitude, phase (radians)- // mode (0 continuous/1 pulsed), pulseShape (0 Gaussian/1 smoothed square), onWidth (cycles)- // offWidth off-width in effect; rewritten here when it is randomized- // detachStep step after which the source fades out linearly over 30 steps (-1 = never);- // work items past the fade return without writing+ // mode 0 = continuous (envelope always 1), 1 = pulsed (Gaussian or smoothed-square+ // envelope, "off" preceding "on" within each onWidth/offWidth cycle of the+ // element's own frequency)+ // pulseShape (0 Gaussian/1 smoothed square), onWidth (cycles)+ // offWidth off-width in effect; read-write: for an element with+ // offWidthRandomizeAmount[k] > 0 this kernel redraws it (uniformly within+ // +/- offWidthRandomizeAmount of offWidthBase) every time that element+ // completes a full off+on cycle, advancing its own cycleAnchor[k] to mark+ // where the new cycle started+ // detachStep step after which the source fades out linearly over+ // SourceElement.DetachRampSteps steps (-1 = never); work items past the+ // fade return without writing// offWidthBase ± offWidthRandomizeAmount range of a randomized off-width (amount <= 0 = fixed)// cycleAnchor, rngState kernel-owned state for the randomized mode: start (cycles) of the- // current period and the xorshift32 state- // The envelope logic is WaveSimulator.ComputePulsePosition + PulseEnvelope; the result is- // u[idx] = 0.9·u + 0.1·sin(phase + f·t)·amp·envelope·detachFade.+ // current period and the xorshift32 state - so, unlike the other+ // object-source buffers, offWidth/cycleAnchor/rngState are genuinely+ // mutated by the GPU across steps+ // The result is u[idx] = 0.9·u + 0.1·sin(phase + f·t)·amp·envelope·detachFade.source.AppendLine("__kernel void apply_object_sources(__global float* u, __global const int* idx, __global const int* level,");source.AppendLine(" __global const float* amp, __global const float* phase, __global const int* mode,");source.AppendLine(" __global const int* pulseShape, __global const int* onWidth, __global int* offWidth,");@@ -495,12 +499,16 @@ namespace _2D_wave_sim_V01source.AppendLine("{");source.AppendLine(" int k = get_global_id(0);");source.AppendLine(" if (k >= n) return;");+ // "detach source": once the run reaches the element's detach step, its drive is faded out linearly over the+ // next DetachRampSteps steps (rather than cut instantly), then it stops driving the field entirely (not even+ // writing towards 0) so it releases its hold and stops diffracting waves through that point - matching+ // WaveSimulator.ApplySources exactly (SourceElement.DetachRampSteps is the single shared constant, spliced+ // into the kernel text).source.AppendLine(" float detachFade = 1.0f;");source.AppendLine(" if (detachStep[k] >= 0) {");- // The 30 below is SourceElement.DetachRampSteps, spliced into the kernel text.source.AppendLine(" float stepsSinceDetach = t - (float)detachStep[k];");- source.AppendLine(" if (stepsSinceDetach >= " + 30.ToString() + ".0f) return;");- source.AppendLine(" if (stepsSinceDetach > 0.0f) detachFade = 1.0f - stepsSinceDetach / " + 30.ToString() + ".0f;");+ source.AppendLine(" if (stepsSinceDetach >= " + SourceElement.DetachRampSteps.ToString() + ".0f) return;");+ source.AppendLine(" if (stepsSinceDetach > 0.0f) detachFade = 1.0f - stepsSinceDetach / " + SourceElement.DetachRampSteps.ToString() + ".0f;");source.AppendLine(" }");source.AppendLine(" float f = freq[level[k]];");source.AppendLine(" float envelope = 1.0f;");@@ -512,6 +520,9 @@ namespace _2D_wave_sim_V01source.AppendLine(" float pos;");source.AppendLine(" int isFirstCycle;");source.AppendLine(" if (offWidthRandomizeAmount[k] <= 0) {");+ // shifted so t = 0 lands at pos = ow (the start of the "on" span), not pos = 0 (the start of an "off" span) -+ // a single/non-randomized source starting silent for its off-width was never the intent (see+ // WaveSimulator.ComputePulsePosition, kept in exact agreement with this kernel)source.AppendLine(" float adjustedClock = cycleClock + (float)ow;");source.AppendLine(" isFirstCycle = (floor(adjustedClock / (float)period) == 0.0f) ? 1 : 0;");source.AppendLine(" pos = adjustedClock - period * floor(adjustedClock / (float)period);");@@ -533,6 +544,8 @@ namespace _2D_wave_sim_V01source.AppendLine(" guard++;");source.AppendLine(" }");source.AppendLine(" if (pos < 0.0f) pos = 0.0f;");+ // the anchor only ever advances (above) once a cycle has actually completed, so it still reading its initial+ // 0 means no cycle has completed yet - we are still in the element's very first (off-first) cyclesource.AppendLine(" isFirstCycle = (cycleAnchor[k] == 0.0f) ? 1 : 0;");source.AppendLine(" }");source.AppendLine(" if (pulseShape[k] == 0) {");@@ -551,6 +564,13 @@ namespace _2D_wave_sim_V01source.AppendLine(" // sits at (very close to) 0 for nearly all of it instead of lingering. The math is");source.AppendLine(" // exactly the on-first formula, fed a coordinate shifted so the on span starts at 0.");source.AppendLine(" float shifted = pos - (float)ow;");+ // wrapping shifted forward by a full period makes it continue the falling tail of the on-span that JUST+ // ended - correct from the second off-span onward, where that on-span really happened. The very first+ // off-span (isFirstCycle) has no real preceding on-emission to continue from, so wrapping there would+ // fabricate one: pos = 0 would land exactly on that phantom falling edge and start the run at envelope ~0.5+ // instead of ~0, emitting a spurious one-cycle "blip" before the source actually goes quiet. Left un-wrapped+ // (deeply negative) instead, dRise/dFall below correctly place it far from both edges, keeping the envelope+ // at (very close to) 0 until the real rising edge - matching WaveSimulator.PulseEnvelope exactly.source.AppendLine(" if (shifted < 0.0f && !isFirstCycle) shifted += (float)period;");source.AppendLine(" float edgeWidth = 0.35f;");source.AppendLine(" float dFall = shifted - (float)onWidth[k];");@@ -569,40 +589,60 @@ namespace _2D_wave_sim_V01return source.ToString();}- /// <summary>Creates a read/write device buffer the size of <paramref name="data"/> and uploads it (blocking). The caller owns the handle and must release it with <see cref="ReleaseMem"/>.</summary>- private IntPtr CreateFloatBuffer(float[] data)+ /// <summary>Compiles <paramref name="source"/> for <see cref="_device"/>; <paramref name="what"/> names the program in the error message.</summary>+ /// <exception cref="InvalidOperationException">The build failed; the message carries the OpenCL error and the build log.</exception>+ private IntPtr BuildProgram(string source, string what)+ {+ int err = 0;+ IntPtr program = OpenClApi.clCreateProgramWithSource(_context, 1U, new[] { source }, null, ref err);+ OpenClApi.Check(err, "clCreateProgramWithSource");+ string buildOptions = "";+ IntPtr[] deviceIds = { _device.DeviceId };+ err = OpenClApi.clBuildProgram(program, 1U, deviceIds, ref buildOptions, IntPtr.Zero, IntPtr.Zero);+ if (err != 0)+ {+ string buildLog = OpenClApi.BuildLog(program, _device.DeviceId);+ OpenClApi.clReleaseProgram(program);+ throw new InvalidOperationException(what + " could not be built (" + OpenClApi.ErrorName(err) + ")" + (buildLog.Length > 0 ? ": " + buildLog : ""));+ }+ return program;+ }++ /// <summary>Creates a read/write device buffer of <paramref name="bytes"/> bytes, registered in <paramref name="owner"/> for release.</summary>+ private IntPtr CreateBuffer(long bytes, Resources owner){- IntPtr size = new IntPtr((long)data.Length * 4L);int err = 0;- IntPtr buffer = OpenClApi.clCreateBuffer(this._context, OpenClApi.MemReadWrite, size, IntPtr.Zero, ref err);+ IntPtr buffer = OpenClApi.clCreateBuffer(_context, OpenClApi.MemReadWrite, new IntPtr(bytes), IntPtr.Zero, ref err);OpenClApi.Check(err, "clCreateBuffer");- OpenClApi.Check(OpenClApi.clEnqueueWriteBufferFloat(this._queue, buffer, 1U, IntPtr.Zero, size, data, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueWriteBuffer");+ owner.Buffers.Add(buffer);return buffer;}- /// <summary>Int counterpart of <see cref="CreateFloatBuffer"/>.</summary>- private IntPtr CreateIntBuffer(int[] data)+ /// <summary>Creates a device buffer the size of <paramref name="data"/>, uploads it (blocking) and registers it in <paramref name="owner"/>.</summary>+ private IntPtr CreateBuffer(float[] data, Resources owner){IntPtr size = new IntPtr((long)data.Length * 4L);- int err = 0;- IntPtr buffer = OpenClApi.clCreateBuffer(this._context, OpenClApi.MemReadWrite, size, IntPtr.Zero, ref err);- OpenClApi.Check(err, "clCreateBuffer");- OpenClApi.Check(OpenClApi.clEnqueueWriteBufferInt(this._queue, buffer, 1U, IntPtr.Zero, size, data, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueWriteBuffer");+ IntPtr buffer = CreateBuffer(size.ToInt64(), owner);+ OpenClApi.Check(OpenClApi.clEnqueueWriteBufferFloat(_queue, buffer, 1U, IntPtr.Zero, size, data, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueWriteBuffer");return buffer;}- /// <summary>Creates a kernel of the simulation program (<see cref="_program"/>).</summary>- private IntPtr CreateKernel(string name)+ /// <summary>Int counterpart of <see cref="CreateBuffer(float[], Resources)"/>.</summary>+ private IntPtr CreateBuffer(int[] data, Resources owner){- return this.CreateKernelFrom(this._program, name);+ IntPtr size = new IntPtr((long)data.Length * 4L);+ IntPtr buffer = CreateBuffer(size.ToInt64(), owner);+ OpenClApi.Check(OpenClApi.clEnqueueWriteBufferInt(_queue, buffer, 1U, IntPtr.Zero, size, data, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueWriteBuffer");+ return buffer;}- /// <summary>Creates the kernel <paramref name="name"/> from <paramref name="program"/>; the caller releases it with <see cref="ReleaseKernel"/>.</summary>- private IntPtr CreateKernelFrom(IntPtr program, string name)+ /// <summary>Creates the kernel <paramref name="name"/> from <paramref name="owner"/>'s program and registers it there for release.</summary>+ private static IntPtr CreateKernel(Resources owner, string name){int err = 0;- IntPtr kernel = OpenClApi.clCreateKernel(program, ref name, ref err);+ IntPtr kernel = OpenClApi.clCreateKernel(owner.Program, ref name, ref err);OpenClApi.Check(err, "clCreateKernel " + name);+ owner.Kernels.Add(kernel);return kernel;}@@ -624,62 +664,39 @@ namespace _2D_wave_sim_V01OpenClApi.Check(OpenClApi.clSetKernelArgFloat(kernel, index, new IntPtr(4), ref value), "clSetKernelArg");}- /// <summary>Engine label for the UI/result: "GPU: <device name> (OpenCL)".</summary>- public string Description+ /// <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){- get- {- return this._description;- }+ OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(_queue, kernel, (uint)globalSize.Length, null, globalSize, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (" + what + ")");}- /// <summary>Scene width in cells (canvas pixels), excluding the padding.</summary>- public int Width+ /// <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>+ private void ReadBack(IntPtr buffer, float[] target, string what){- get- {- return this._width;- }+ OpenClApi.Check(OpenClApi.clEnqueueReadBufferFloat(_queue, buffer, 1U, IntPtr.Zero, new IntPtr((long)target.Length * 4L), target, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueReadBuffer (" + what + ")");+ _sinceFinish = 0;}+ /// <summary>Engine label for the UI/result: "GPU: <device name> (OpenCL)".</summary>+ public string Description { get; }++ /// <summary>Scene width in cells (canvas pixels), excluding the padding.</summary>+ public int Width => _width;+/// <summary>Scene height in cells (canvas pixels), excluding the padding.</summary>- public int Height- {- get- {- return this._height;- }- }+ public int Height => _height;/// <summary>Row pitch of the padded buffers: <see cref="Width"/> + 2.</summary>- public int Stride- {- get- {- return this._stride;- }- }+ public int Stride => _stride;/// <summary>/// Host copy of the field (padded layout). Unlike the CPU engine the array instance never changes, but/// its contents are only as fresh as the last <see cref="PrepareFrame"/> with <c>needField</c>./// </summary>- public float[] FieldData- {- get- {- return this._hostField;- }- }+ public float[] FieldData => _hostField;/// <summary>Host copy of the scaled intensity (padded layout) as of the last <see cref="PrepareFrame"/> with <c>needIntensity</c>; null when the engine was created without intensity tracking.</summary>- public float[] IntensityData- {- get- {- return this._hostIntensity;- }- }+ public float[] IntensityData => _hostIntensity;/// <summary>/// Enqueues one simulation step (nothing is waited for): the source kernels bound to the current field@@ -688,64 +705,60 @@ namespace _2D_wave_sim_V01/// (the leapfrog "previous" field). The track flag is set so only the last sub-step updates the intensity/// (with a single sub-step the flag keeps the value bound in <see cref="Build"/>). Afterwards/// <see cref="_current"/> points at the newest buffer and <see cref="_time"/> advances by one step.- /// Every 16 steps the queue is drained with <c>clFinish</c> so unbounded asynchronous enqueueing cannot- /// exhaust the driver.+ /// Every <see cref="FinishInterval"/> steps the queue is drained with <c>clFinish</c>, so that the commands+ /// do not pile up and errors show up in time./// </summary>public void AdvanceOneStep(){- int current = this._current;- if (this._sourceCount > 0)- {- GpuWaveSimulator.SetFloat(this._sourceKernel[current], 4U, (float)this._time);- OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._sourceKernel[current], 1U, null, this._grid1D, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (sources)");- }- if (this._objSourceCount > 0)+ int current = _current;+ if (_sourceCount > 0){- GpuWaveSimulator.SetFloat(this._objSourceKernel[current], 11U, (float)this._time);- OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._objSourceKernel[current], 1U, null, this._objGrid1D, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (object sources)");+ SetFloat(_sourceKernel[current], 4U, (float)_time);+ Enqueue(_sourceKernel[current], _grid1D, "sources");}- if (this._subSteps <= 1)+ if (_objSourceCount > 0){- OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._stepKernel[current], 2U, null, this._grid2D, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (step)");- current = 1 - current;+ SetFloat(_objSourceKernel[current], 11U, (float)_time);+ Enqueue(_objSourceKernel[current], _objGrid1D, "object sources");}- else+ // _subSteps smaller launches (see the class summary); only the last one updates the intensity buffer, so+ // its own exponential averaging still runs once per AdvanceOneStep call, not _subSteps times. On the+ // single-launch path the "track" argument keeps the value bound once, at Build time.+ for (int subStep = 1; subStep <= _subSteps; subStep++){- for (int i = 1; i <= this._subSteps; i++)+ if (_subSteps > 1){- int trackThisSubStep = ((i == this._subSteps && this._track) ? 1 : 0);- GpuWaveSimulator.SetInt(this._stepKernel[current], 8U, trackThisSubStep);- OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._stepKernel[current], 2U, null, this._grid2D, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (step)");- current = 1 - current;+ SetInt(_stepKernel[current], 8U, subStep == _subSteps && _track ? 1 : 0);}+ Enqueue(_stepKernel[current], _grid2D, "step");+ current = 1 - current;}- this._current = current;- this._time += 1.0;- this._sinceFinish++;- if (this._sinceFinish >= 16)+ // the buffer that received the new values is now the current field+ _current = current;+ _time += 1.0;+ // now and then wait for the card, so that the commands do not pile up and errors show up in time+ if (++_sinceFinish >= FinishInterval){- this._sinceFinish = 0;- OpenClApi.Check(OpenClApi.clFinish(this._queue), "clFinish");+ _sinceFinish = 0;+ OpenClApi.Check(OpenClApi.clFinish(_queue), "clFinish");}}/// <summary>/// Blocking device-to-host copies of the newest field into <see cref="FieldData"/> and/or of the intensity/// into <see cref="IntensityData"/> (the latter only when tracked). Called by the runner before rendering,- /// and from the UI thread while paused. As the reads drain the queue, the clFinish counter is reset.+ /// and from the UI thread while paused./// </summary>public void PrepareFrame(bool needField, bool needIntensity){- IntPtr size = new IntPtr((long)this._cells * 4L);if (needField){- OpenClApi.Check(OpenClApi.clEnqueueReadBufferFloat(this._queue, this._field[this._current], 1U, IntPtr.Zero, size, this._hostField, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueReadBuffer");+ ReadBack(_field[_current], _hostField, "field");}- if (needIntensity && this._track)+ if (needIntensity && _track){- OpenClApi.Check(OpenClApi.clEnqueueReadBufferFloat(this._queue, this._intensityOutBuffer, 1U, IntPtr.Zero, size, this._hostIntensity, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueReadBuffer");+ ReadBack(_intensityOutBuffer, _hostIntensity, "intensity");}- this._sinceFinish = 0;}/// <summary>@@ -756,7 +769,8 @@ namespace _2D_wave_sim_V01private static string ProbeKernelSource(){StringBuilder source = new StringBuilder();- // probe_sample: one work item per probe p < n (n = all probes, line probes included).+ // probe_sample (point probes): the value of the pixel of every probe, into row "row" of the history;+ // one work item per probe p < n (n = all probes, line probes included).// u, inten newest field and the intensity output, padded layout// pix pixel index lists of all point probes concatenated// info 4 ints per probe: [start in pix, count, 1 = sample inten instead of u, 1 = divide by count];@@ -781,9 +795,12 @@ namespace _2D_wave_sim_V01source.AppendLine(" hist[row * n + p] = s;");source.AppendLine("}");source.AppendLine();- // profile_accumulate: one work item per line-probe pixel k < n (all line probes flattened):- // ppix[k] padded cell index; pmode[k] 0 = field, 1 = intensity, 2 = integrated intensity+ // profile_accumulate (line probes): one work item per line-probe pixel k < n (all line probes flattened):+ // ppix[k] padded cell index; pmode[k] 0 = field, 1 = intensity, 2 = intensity totals over the steps// total[k] += inten[ppix[k]] for mode 2 only, and only once step >= pStartStep[k] when pStartFlag[k] is set+ // pStartFlag/pStartStep are the probe's "start recording at step #" (0/1 and the step): before that step+ // the total is left at zero, so intensity that arrived earlier is purged rather than baked into the total+ // once recording startssource.AppendLine("__kernel void profile_accumulate(__global const float* inten, __global const int* ppix,");source.AppendLine(" __global const int* pmode, __global const int* pStartFlag, __global const int* pStartStep,");source.AppendLine(" __global float* total, const int step, const int n)");@@ -813,63 +830,56 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Installs the probe layout: builds the probe program (<see cref="ProbeKernelSource"/>), then uploads the- /// pixel tables and creates the kernels for point probes (<see cref="SetUpSeriesProbes"/>) and line probes- /// (<see cref="SetUpProfileProbes"/>). A null or empty sampler installs nothing and leaves a previously- /// installed one in place. Meant to be called once per engine: a second call overwrites the probe handles- /// without releasing the earlier ones.+ /// Installs the probe layout, replacing any previously installed one (whose device resources are released+ /// first): builds the probe program (<see cref="ProbeKernelSource"/>), then uploads the pixel tables and+ /// creates the kernels for point probes (<see cref="SetUpSeriesProbes"/>) and line probes+ /// (<see cref="SetUpProfileProbes"/>). A null or empty sampler just clears the probes./// </summary>/// <exception cref="InvalidOperationException">The sampler needs intensity but this engine does not track it, or the probe program / buffers could not be created (inner exception has the OpenCL error).</exception>public void SetProbes(ProbeSampler sampler){+ _probes.Release();+ _probeSampler = null;+ _probeValues.Clear();+ _probeRow = 0;+ _profileIntegrates = false;if (sampler == null || sampler.Count == 0){return;}+ if (sampler.NeedsIntensity && !_track)+ {+ throw new InvalidOperationException("the intensity is not tracked");+ }try{- if (sampler.NeedsIntensity && !this._track)- {- throw new InvalidOperationException("the intensity is not tracked");- }- int err = 0;- IntPtr[] deviceIds = new IntPtr[] { this._deviceId };- string[] sources = new string[] { GpuWaveSimulator.ProbeKernelSource() };- this._probeProgram = OpenClApi.clCreateProgramWithSource(this._context, 1U, sources, null, ref err);- OpenClApi.Check(err, "clCreateProgramWithSource (probes)");- string buildOptions = "";- err = OpenClApi.clBuildProgram(this._probeProgram, 1U, deviceIds, ref buildOptions, IntPtr.Zero, IntPtr.Zero);- if (err != 0)- {- string buildLog = OpenClApi.BuildLog(this._probeProgram, this._deviceId);- throw new InvalidOperationException("the probe program for the GPU could not be built (" + OpenClApi.ErrorName(err) + ")" + ((buildLog.Length > 0) ? (": " + buildLog) : ""));- }+ _probes.Program = BuildProgram(ProbeKernelSource(), "the probe program for the GPU");if (sampler.HasSeries){- this.SetUpSeriesProbes(sampler);+ SetUpSeriesProbes(sampler);}if (sampler.HasProfiles){- this.SetUpProfileProbes(sampler);+ SetUpProfileProbes(sampler);}- this._probeSampler = sampler;+ _probeSampler = sampler;}catch (Exception ex){+ _probes.Release();throw new InvalidOperationException("the probes could not be set up on the GPU: " + ex.Message, ex);}}/// <summary>- /// Packs the pixel lists of all point (non-profile) probes into <see cref="_pixelBuffer"/>, describes each- /// probe in <see cref="_infoBuffer"/> (point probes average their pixels, so a single-pixel probe yields- /// that pixel's value like <see cref="ProbeSampler.Compute"/>), allocates the <see cref="ProbeRows"/>-row- /// history buffer and creates the two <c>probe_sample</c> kernels. Resets the host-side sample lists.+ /// Packs the pixel lists of all point (non-profile) probes into one buffer, describes each probe in an info+ /// table (point probes average their pixels, so a single-pixel probe yields that pixel's value like+ /// <see cref="ProbeSampler.Compute"/>), allocates the <see cref="ProbeRows"/>-row history buffer and creates+ /// the two <c>probe_sample</c> kernels./// </summary>private void SetUpSeriesProbes(ProbeSampler sampler){int count = sampler.Count;- int err = 0;int totalPixels = 0;for (int i = 0; i < count; i++){@@ -889,35 +899,31 @@ namespace _2D_wave_sim_V01Array.Copy(probePixels, 0, pixels, offset, probePixels.Length);info[i * 4] = offset;info[i * 4 + 1] = probePixels.Length;- info[i * 4 + 2] = (sampler.UseIntensity[i] ? 1 : 0);+ info[i * 4 + 2] = sampler.UseIntensity[i] ? 1 : 0;info[i * 4 + 3] = 1;offset += probePixels.Length;}}- this._pixelBuffer = this.CreateIntBuffer(pixels);- this._infoBuffer = this.CreateIntBuffer(info);+ IntPtr pixelBuffer = CreateBuffer(pixels, _probes);+ IntPtr infoBuffer = CreateBuffer(info, _probes);// Never uploaded: the kernel writes every row before ReadProbeHistory reads it.- IntPtr historySize = new IntPtr((long)GpuWaveSimulator.ProbeRows * count * 4L);- this._historyBuffer = OpenClApi.clCreateBuffer(this._context, OpenClApi.MemReadWrite, historySize, IntPtr.Zero, ref err);- OpenClApi.Check(err, "clCreateBuffer (probes)");+ _historyBuffer = CreateBuffer((long)ProbeRows * count * 4L, _probes);for (int k = 0; k <= 1; k++){- this._probeKernel[k] = this.CreateKernelFrom(this._probeProgram, "probe_sample");- GpuWaveSimulator.SetMem(this._probeKernel[k], 0U, this._field[k]);- GpuWaveSimulator.SetMem(this._probeKernel[k], 1U, this._intensityOutBuffer);- GpuWaveSimulator.SetMem(this._probeKernel[k], 2U, this._pixelBuffer);- GpuWaveSimulator.SetMem(this._probeKernel[k], 3U, this._infoBuffer);- GpuWaveSimulator.SetMem(this._probeKernel[k], 4U, this._historyBuffer);- GpuWaveSimulator.SetInt(this._probeKernel[k], 5U, 0);- GpuWaveSimulator.SetInt(this._probeKernel[k], 6U, count);+ IntPtr kernel = _probeKernel[k] = CreateKernel(_probes, "probe_sample");+ SetMem(kernel, 0U, _field[k]);+ SetMem(kernel, 1U, _intensityOutBuffer);+ SetMem(kernel, 2U, pixelBuffer);+ SetMem(kernel, 3U, infoBuffer);+ SetMem(kernel, 4U, _historyBuffer);+ SetInt(kernel, 5U, 0);+ SetInt(kernel, 6U, count);}- this._probeGrid[0] = new IntPtr(count);- this._probeValues.Clear();+ _probeGrid[0] = new IntPtr(count);for (int i = 0; i < count; i++){- this._probeValues.Add(new List<float>());+ _probeValues.Add(new List<float>());}- this._probeRow = 0;}/// <summary>@@ -941,62 +947,62 @@ namespace _2D_wave_sim_V01int[] modes = new int[totalPixels];int[] startFlags = new int[totalPixels];int[] startSteps = new int[totalPixels];- this._profileStart = new int[count];- this._profileIntegrates = false;+ _profileStart = new int[count];int offset = 0;for (int i = 0; i < count; i++){- this._profileStart[i] = offset;- if (sampler.IsProfile[i])+ _profileStart[i] = offset;+ if (!sampler.IsProfile[i]){- int[] probePixels = sampler.Pixels[i];- int mode = (sampler.Integrate[i] ? 2 : (sampler.UseIntensity[i] ? 1 : 0));- if (mode == 2)- {- this._profileIntegrates = true;- }- int startFlag = (sampler.UseStartAfterStep[i] ? 1 : 0);- int startStep = sampler.StartAfterStep[i];- for (int k = 0; k < probePixels.Length; k++)- {- pixels[offset + k] = probePixels[k];- modes[offset + k] = mode;- startFlags[offset + k] = startFlag;- startSteps[offset + k] = startStep;- }- offset += probePixels.Length;+ continue;+ }+ int[] probePixels = sampler.Pixels[i];+ int mode = sampler.Integrate[i] ? 2 : (sampler.UseIntensity[i] ? 1 : 0);+ if (mode == 2)+ {+ _profileIntegrates = true;}+ int startFlag = sampler.UseStartAfterStep[i] ? 1 : 0;+ int startStep = sampler.StartAfterStep[i];+ for (int k = 0; k < probePixels.Length; k++)+ {+ pixels[offset + k] = probePixels[k];+ modes[offset + k] = mode;+ startFlags[offset + k] = startFlag;+ startSteps[offset + k] = startStep;+ }+ offset += probePixels.Length;}- this._profileCount = totalPixels;- this._profilePixelBuffer = this.CreateIntBuffer(pixels);- this._profileModeBuffer = this.CreateIntBuffer(modes);- this._profileTotalBuffer = this.CreateFloatBuffer(new float[totalPixels]);- this._profileOutBuffer = this.CreateFloatBuffer(new float[totalPixels]);+ _profileCount = totalPixels;+ IntPtr pixelBuffer = CreateBuffer(pixels, _probes);+ IntPtr modeBuffer = CreateBuffer(modes, _probes);+ IntPtr totalBuffer = CreateBuffer(new float[totalPixels], _probes);+ _profileOutBuffer = CreateBuffer(new float[totalPixels], _probes);for (int k = 0; k <= 1; k++){- this._gatherKernel[k] = this.CreateKernelFrom(this._probeProgram, "profile_gather");- GpuWaveSimulator.SetMem(this._gatherKernel[k], 0U, this._field[k]);- GpuWaveSimulator.SetMem(this._gatherKernel[k], 1U, this._intensityOutBuffer);- GpuWaveSimulator.SetMem(this._gatherKernel[k], 2U, this._profilePixelBuffer);- GpuWaveSimulator.SetMem(this._gatherKernel[k], 3U, this._profileModeBuffer);- GpuWaveSimulator.SetMem(this._gatherKernel[k], 4U, this._profileTotalBuffer);- GpuWaveSimulator.SetMem(this._gatherKernel[k], 5U, this._profileOutBuffer);- GpuWaveSimulator.SetInt(this._gatherKernel[k], 6U, totalPixels);- }- if (this._profileIntegrates)- {- this._profileStartFlagBuffer = this.CreateIntBuffer(startFlags);- this._profileStartStepBuffer = this.CreateIntBuffer(startSteps);- this._accumulateKernel = this.CreateKernelFrom(this._probeProgram, "profile_accumulate");- GpuWaveSimulator.SetMem(this._accumulateKernel, 0U, this._intensityOutBuffer);- GpuWaveSimulator.SetMem(this._accumulateKernel, 1U, this._profilePixelBuffer);- GpuWaveSimulator.SetMem(this._accumulateKernel, 2U, this._profileModeBuffer);- GpuWaveSimulator.SetMem(this._accumulateKernel, 3U, this._profileStartFlagBuffer);- GpuWaveSimulator.SetMem(this._accumulateKernel, 4U, this._profileStartStepBuffer);- GpuWaveSimulator.SetMem(this._accumulateKernel, 5U, this._profileTotalBuffer);- GpuWaveSimulator.SetInt(this._accumulateKernel, 7U, totalPixels);- }- this._profileGrid[0] = new IntPtr(totalPixels);+ IntPtr kernel = _gatherKernel[k] = CreateKernel(_probes, "profile_gather");+ SetMem(kernel, 0U, _field[k]);+ SetMem(kernel, 1U, _intensityOutBuffer);+ SetMem(kernel, 2U, pixelBuffer);+ SetMem(kernel, 3U, modeBuffer);+ SetMem(kernel, 4U, totalBuffer);+ SetMem(kernel, 5U, _profileOutBuffer);+ SetInt(kernel, 6U, totalPixels);+ }+ if (_profileIntegrates)+ {+ IntPtr kernel = _accumulateKernel = CreateKernel(_probes, "profile_accumulate");+ SetMem(kernel, 0U, _intensityOutBuffer);+ SetMem(kernel, 1U, pixelBuffer);+ SetMem(kernel, 2U, modeBuffer);+ // "start recording at step #" for the integrated line probes: one entry per pixel (same layout as the+ // pixel/mode buffers), so profile_accumulate can skip a pixel's contribution before its probe's start step+ SetMem(kernel, 3U, CreateBuffer(startFlags, _probes));+ SetMem(kernel, 4U, CreateBuffer(startSteps, _probes));+ SetMem(kernel, 5U, totalBuffer);+ SetInt(kernel, 7U, totalPixels);+ }+ _profileGrid[0] = new IntPtr(totalPixels);}/// <summary>@@ -1007,88 +1013,88 @@ namespace _2D_wave_sim_V01/// </summary>public void SampleProbes(){- if (this._probeSampler == null)+ if (_probeSampler == null){return;}- int current = this._current;- if (this._probeSampler.HasSeries)+ if (_probeSampler.HasSeries){- if (this._probeRow >= GpuWaveSimulator.ProbeRows)+ if (_probeRow >= ProbeRows){- this.ReadProbeHistory();+ ReadProbeHistory();}- GpuWaveSimulator.SetInt(this._probeKernel[current], 5U, this._probeRow);- OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._probeKernel[current], 1U, null, this._probeGrid, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (probes)");- this._probeRow++;+ SetInt(_probeKernel[_current], 5U, _probeRow);+ Enqueue(_probeKernel[_current], _probeGrid, "probes");+ _probeRow++;}- if (this._profileIntegrates)+ // the intensity totals of the lines that are integrated: add the intensity of this step (unless it is before+ // that probe's "start recording at step #", in which case the kernel leaves the total at zero)+ if (_profileIntegrates){- GpuWaveSimulator.SetInt(this._accumulateKernel, 6U, (int)Math.Round(this._time));- OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._accumulateKernel, 1U, null, this._profileGrid, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (totals)");+ SetInt(_accumulateKernel, 6U, (int)Math.Round(_time));+ Enqueue(_accumulateKernel, _profileGrid, "totals");}}/// <summary>/// Blocking download of the <see cref="_probeRow"/> rows sampled so far from <see cref="_historyBuffer"/>,/// appending each row's point-probe values to <see cref="_probeValues"/> (line-probe columns are skipped)- /// and rewinding the row counter. No-op when no probes are set or no row is pending.+ /// and rewinding the row counter. No-op when no row is pending./// </summary>private void ReadProbeHistory(){- if (this._probeSampler == null || this._probeRow == 0)+ if (_probeRow == 0){return;}- int count = this._probeSampler.Count;- float[] history = new float[this._probeRow * count];- OpenClApi.Check(OpenClApi.clEnqueueReadBufferFloat(this._queue, this._historyBuffer, 1U, IntPtr.Zero, new IntPtr((long)history.Length * 4L), history, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueReadBuffer (probes)");- for (int row = 0; row < this._probeRow; row++)+ int count = _probeSampler.Count;+ float[] history = new float[_probeRow * count];+ ReadBack(_historyBuffer, history, "probes");+ for (int row = 0; row < _probeRow; row++){for (int p = 0; p < count; p++){- if (!this._probeSampler.IsProfile[p])+ if (!_probeSampler.IsProfile[p]){- this._probeValues[p].Add(history[row * count + p]);+ _probeValues[p].Add(history[row * count + p]);}}}- this._probeRow = 0;- this._sinceFinish = 0;+ _probeRow = 0;}/// <summary>Drains the pending history rows from the device, then returns and clears the point-probe values collected since the previous call.</summary>/// <returns>One array per probe, one value per step (empty for line probes); an empty outer array when no sampler is set.</returns>public float[][] TakeProbeSamples(){- if (this._probeSampler == null)+ if (_probeSampler == null){return new float[0][];}- int count = this._probeSampler.Count;+ int count = _probeSampler.Count;float[][] samples = new float[count][];- if (this._probeSampler.HasSeries)+ if (_probeSampler.HasSeries){- this.ReadProbeHistory();+ ReadProbeHistory();}for (int i = 0; i < count; i++){- if (this._probeSampler.IsProfile[i])+ if (_probeSampler.IsProfile[i]){samples[i] = new float[0];}else{- samples[i] = this._probeValues[i].ToArray();- this._probeValues[i].Clear();+ samples[i] = _probeValues[i].ToArray();+ _probeValues[i].Clear();}}return samples;}/// <summary>- /// Runs <c>profile_gather</c> on the newest field and reads the flat result back (blocking), then slices it- /// per line probe; nothing is cleared.+ /// Runs <c>profile_gather</c> on the newest field and reads the flat result back (blocking: this waits for+ /// the card, so do not call it every step), then slices it per line probe; nothing is cleared./// </summary>/// <returns>/// One array per probe in pixel order along the line, holding the integrated intensity totals or the live@@ -1096,28 +1102,26 @@ namespace _2D_wave_sim_V01/// </returns>public float[][] ReadProbeProfiles(){- if (this._probeSampler == null)+ if (_probeSampler == null){return new float[0][];}- int count = this._probeSampler.Count;+ int count = _probeSampler.Count;float[][] profiles = new float[count][];- if (!this._probeSampler.HasProfiles)+ if (!_probeSampler.HasProfiles){return profiles;}- int current = this._current;- OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._gatherKernel[current], 1U, null, this._profileGrid, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (profiles)");- float[] values = new float[this._profileCount];- OpenClApi.Check(OpenClApi.clEnqueueReadBufferFloat(this._queue, this._profileOutBuffer, 1U, IntPtr.Zero, new IntPtr((long)this._profileCount * 4L), values, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueReadBuffer (profiles)");- this._sinceFinish = 0;+ Enqueue(_gatherKernel[_current], _profileGrid, "profiles");+ float[] values = new float[_profileCount];+ ReadBack(_profileOutBuffer, values, "profiles");for (int i = 0; i < count; i++){- if (this._probeSampler.IsProfile[i])+ if (_probeSampler.IsProfile[i]){- int length = this._probeSampler.Pixels[i].Length;+ int length = _probeSampler.Pixels[i].Length;float[] profile = new float[length];- Array.Copy(values, this._profileStart[i], profile, 0, length);+ Array.Copy(values, _profileStart[i], profile, 0, length);profiles[i] = profile;}}@@ -1127,134 +1131,91 @@ namespace _2D_wave_sim_V01/// <summary>Releases every OpenCL handle; called by the runner when the run ends. Safe to call more than once.</summary>public void Dispose(){- this.ReleaseAll();+ ReleaseAll();}/// <summary>- /// Releases all device resources exactly once (guarded by <see cref="_released"/>): drains the queue, then- /// frees kernels and buffers (including the probe ones, if any), the two programs, the queue and finally- /// the context, zeroing every handle. Unset handles are skipped and OpenCL failures are swallowed, so the- /// method is also usable from the constructor after a partial <see cref="Build"/>.+ /// Releases all device resources: drains the queue, then the probe set, the scene set, the queue and+ /// finally the context. OpenCL failures are swallowed, so the method is also usable from the constructor+ /// after a partial <see cref="Build"/>, and a second call finds nothing left to release./// </summary>private void ReleaseAll(){- if (this._released)- {- return;- }- this._released = true;- try+ if (_queue != IntPtr.Zero){- if (this._queue != IntPtr.Zero)- {- OpenClApi.clFinish(this._queue);- }+ // if this fails the driver is gone or in trouble; release what can be released+ Quietly(() => OpenClApi.clFinish(_queue));}- catch+ _probes.Release();+ _scene.Release();+ if (_queue != IntPtr.Zero){+ Quietly(() => OpenClApi.clReleaseCommandQueue(_queue));+ _queue = IntPtr.Zero;}- for (int k = 0; k <= 1; k++)- {- GpuWaveSimulator.ReleaseKernel(ref this._stepKernel[k]);- GpuWaveSimulator.ReleaseKernel(ref this._sourceKernel[k]);- GpuWaveSimulator.ReleaseKernel(ref this._objSourceKernel[k]);- GpuWaveSimulator.ReleaseKernel(ref this._probeKernel[k]);- GpuWaveSimulator.ReleaseKernel(ref this._gatherKernel[k]);- GpuWaveSimulator.ReleaseMem(ref this._field[k]);- }- GpuWaveSimulator.ReleaseKernel(ref this._accumulateKernel);- GpuWaveSimulator.ReleaseMem(ref this._pixelBuffer);- GpuWaveSimulator.ReleaseMem(ref this._infoBuffer);- GpuWaveSimulator.ReleaseMem(ref this._historyBuffer);- GpuWaveSimulator.ReleaseMem(ref this._profilePixelBuffer);- GpuWaveSimulator.ReleaseMem(ref this._profileModeBuffer);- GpuWaveSimulator.ReleaseMem(ref this._profileStartFlagBuffer);- GpuWaveSimulator.ReleaseMem(ref this._profileStartStepBuffer);- GpuWaveSimulator.ReleaseMem(ref this._profileTotalBuffer);- GpuWaveSimulator.ReleaseMem(ref this._profileOutBuffer);- GpuWaveSimulator.ReleaseMem(ref this._c2Buffer);- GpuWaveSimulator.ReleaseMem(ref this._dBuffer);- GpuWaveSimulator.ReleaseMem(ref this._intensityBuffer);- GpuWaveSimulator.ReleaseMem(ref this._intensityStage1Buffer);- GpuWaveSimulator.ReleaseMem(ref this._intensityOutBuffer);- GpuWaveSimulator.ReleaseMem(ref this._indexBuffer);- GpuWaveSimulator.ReleaseMem(ref this._levelBuffer);- GpuWaveSimulator.ReleaseMem(ref this._frequencyBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objIndexBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objLevelBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objAmplitudeBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objPhaseBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objModeBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objPulseShapeBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objOnWidthBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objOffWidthBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objDetachStepBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objOffWidthBaseBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objRandomizeOffWidthAmountBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objCycleAnchorBuffer);- GpuWaveSimulator.ReleaseMem(ref this._objRngStateBuffer);- try- {- if (this._probeProgram != IntPtr.Zero)- {- OpenClApi.clReleaseProgram(this._probeProgram);- }- if (this._program != IntPtr.Zero)- {- OpenClApi.clReleaseProgram(this._program);- }- if (this._queue != IntPtr.Zero)- {- OpenClApi.clReleaseCommandQueue(this._queue);- }- if (this._context != IntPtr.Zero)- {- OpenClApi.clReleaseContext(this._context);- }- }- catch+ if (_context != IntPtr.Zero){+ Quietly(() => OpenClApi.clReleaseContext(_context));+ _context = IntPtr.Zero;}- this._probeProgram = IntPtr.Zero;- this._program = IntPtr.Zero;- this._queue = IntPtr.Zero;- this._context = IntPtr.Zero;}- /// <summary>Releases a buffer handle unless it is <see cref="IntPtr.Zero"/>, ignoring errors, and zeroes it.</summary>- private static void ReleaseMem(ref IntPtr handle)+ /// <summary>Runs an OpenCL release call, ignoring any failure (nothing more can be done; the handle is gone either way).</summary>+ private static void Quietly(Action release){try{- if (handle != IntPtr.Zero)- {- OpenClApi.clReleaseMemObject(handle);- }+ release();}catch{}- handle = IntPtr.Zero;}- /// <summary>Releases a kernel handle unless it is <see cref="IntPtr.Zero"/>, ignoring errors, and zeroes it.</summary>- private static void ReleaseKernel(ref IntPtr handle)+ /// <summary>+ /// A program with the kernels and buffers created from/for it, released together: the scene set lives as+ /// long as the engine, the probe set is replaced by every <see cref="SetProbes"/> call.+ /// </summary>+ private sealed class Resources{- try+ /// <summary>The compiled program, or <see cref="IntPtr.Zero"/> when not (yet) built.</summary>+ public IntPtr Program;++ /// <summary>Kernels created from <see cref="Program"/>.</summary>+ public readonly List<IntPtr> Kernels = new List<IntPtr>();++ /// <summary>Device buffers bound to those kernels.</summary>+ public readonly List<IntPtr> Buffers = new List<IntPtr>();++ /// <summary>Releases kernels, buffers and the program (in that order) and forgets them; failures are ignored.</summary>+ public void Release(){- if (handle != IntPtr.Zero)+ foreach (IntPtr kernel in Kernels){- OpenClApi.clReleaseKernel(handle);+ Quietly(() => OpenClApi.clReleaseKernel(kernel));+ }+ Kernels.Clear();+ foreach (IntPtr buffer in Buffers)+ {+ Quietly(() => OpenClApi.clReleaseMemObject(buffer));+ }+ Buffers.Clear();+ if (Program != IntPtr.Zero)+ {+ Quietly(() => OpenClApi.clReleaseProgram(Program));+ Program = IntPtr.Zero;}}- catch- {- }- handle = IntPtr.Zero;}- /// <summary>Engine label: "GPU: <device name> (OpenCL)".</summary>- private readonly string _description;+ /// <summary>Steps enqueued between two <c>clFinish</c> calls in <see cref="AdvanceOneStep"/>.</summary>+ private const int FinishInterval = 16;++ /// <summary>Rows (steps) the probe history buffer holds before it must be read back to the host.</summary>+ private const int ProbeRows = 2048;++ /// <summary>The device the context lives on; needed again to build the probe program.</summary>+ private readonly GpuDeviceInfo _device;/// <summary>Scene width in cells (canvas pixels), without padding.</summary>private readonly int _width;@@ -1274,116 +1235,56 @@ namespace _2D_wave_sim_V01/// <summary>Number of image (green-channel) sources in the scene.</summary>private readonly int _sourceCount;- /// <summary>Peak amplitude of the image sources (object sources carry their own).</summary>- private readonly float _amplitude;-- /// <summary>Whether the program was compiled with the 4th-order stencil (<c>USE_4TH_ORDER</c>), which implies sub-stepping.</summary>- private readonly bool _use4thOrderLaplacian;+ /// <summary>Number of object sources that lie inside the canvas.</summary>+ private readonly int _objSourceCount;- /// <summary>Leapfrog sub-steps per simulation step; 1 unless the 4th-order stencil is on. Set in <see cref="Build"/>.</summary>+ /// <summary>+ /// Leapfrog sub-steps per simulation step - see the class summary; 1 (no sub-stepping) unless the 4th-order+ /// stencil is on and this scene's highest c² needs it. Set once, in <see cref="Build"/>.+ /// </summary>private int _subSteps;- /// <summary>1/<see cref="_subSteps"/>², scaling c² for the shorter sub-step (kernel argument <c>c2Scale</c>).</summary>- private float _c2Mult;-- /// <summary>Per-step retention of the two intensity averaging stages: exp(-1/decaySteps) with decaySteps = timeDecayFactor·100/lowest source level.</summary>- private float _intensityAlpha;-- /// <summary>Multiplier on the intensity output.</summary>- private float _intensityScale;-/// <summary>OpenCL context on the chosen device; released last in <see cref="ReleaseAll"/>.</summary>private IntPtr _context;- /// <summary>In-order command queue; every launch and transfer goes through it, from the worker thread.</summary>+ /// <summary>In-order command queue; every launch and transfer goes through it.</summary>private IntPtr _queue;- /// <summary>Program built from <see cref="KernelSource"/> (<c>wave_step</c>, <c>apply_sources</c>, <c>apply_object_sources</c>).</summary>- private IntPtr _program;+ /// <summary>Simulation program (<c>wave_step</c>, <c>apply_sources</c>, <c>apply_object_sources</c>) with its kernels and scene buffers.</summary>+ private readonly Resources _scene = new Resources();- /// <summary>The two ping-pong field buffers (padded, <see cref="_cells"/> floats each); the one at <see cref="_current"/> holds the newest field, the other the previous one.</summary>- private readonly IntPtr[] _field;-- /// <summary><c>wave_step</c> kernel per field index k: reads <see cref="_field"/>[k], writes <see cref="_field"/>[1 - k].</summary>- private readonly IntPtr[] _stepKernel;-- /// <summary><c>apply_sources</c> kernel per field index k, bound to <see cref="_field"/>[k]; <see cref="IntPtr.Zero"/> when the scene has no image sources.</summary>- private readonly IntPtr[] _sourceKernel;-- /// <summary>Index (0/1) of the field buffer holding the newest field; flips after every sub-step.</summary>- private int _current;-- /// <summary>Per-cell c² = 1/n² (padded; border cells 0).</summary>- private IntPtr _c2Buffer;-- /// <summary>Per-cell damping (padded), 1 = lossless; already raised to 1/<see cref="_subSteps"/> when sub-stepping.</summary>- private IntPtr _dBuffer;-- /// <summary>Second-stage running average of u² (padded), or a 1-float dummy when not tracking.</summary>- private IntPtr _intensityBuffer;+ /// <summary>+ /// The probes: a second small program (<c>probe_sample</c>, <c>profile_accumulate</c>, <c>profile_gather</c>)+ /// measures them on the card, with its kernels and buffers; empty until probes are set. Point probes: one+ /// value per step; the values wait in <see cref="_historyBuffer"/> until the next+ /// <see cref="TakeProbeSamples"/> (or until the buffer is full). Line probes: the pixels of all lines in one+ /// list; the totals (integrated intensity) are kept on the card, the profiles are gathered into+ /// <see cref="_profileOutBuffer"/> and copied back when they are asked for (<see cref="ReadProbeProfiles"/>).+ /// </summary>+ private readonly Resources _probes = new Resources();- /// <summary>First-stage running average of u² (padded), or a 1-float dummy when not tracking.</summary>- private IntPtr _intensityStage1Buffer;+ /// <summary>The two ping-pong field buffers (padded, <see cref="_cells"/> floats each); the one at <see cref="_current"/> holds the newest field, the other the previous one.</summary>+ private readonly IntPtr[] _field = new IntPtr[2];- /// <summary>Blended and scaled intensity (padded): read back into <see cref="_hostIntensity"/> and sampled by the probe kernels; a 1-float dummy when not tracking.</summary>+ /// <summary>+ /// The blend of the two cascaded filter stages (the <c>inten1</c>/<c>inten</c> buffers, which live only+ /// inside <c>wave_step</c>), scaled - see the class summary and <c>WaveSimulator._intensityOut</c> (CPU+ /// engine). Padded; this is what is actually read back into <see cref="_hostIntensity"/> and sampled by the+ /// probe kernels; a 1-float dummy when not tracking.+ /// </summary>private IntPtr _intensityOutBuffer;- /// <summary>Padded cell index of every image source; unset when there are none.</summary>- private IntPtr _indexBuffer;-- /// <summary>Green level (1..255) of every image source, indexing <see cref="_frequencyBuffer"/>; unset when there are none.</summary>- private IntPtr _levelBuffer;-- /// <summary>256 angular frequencies in radians per step, one per level: level/255 × 0.5 × sourceFrequencyScale. Shared by both source kernels; unset when there are no sources at all.</summary>- private IntPtr _frequencyBuffer;-- /// <summary>Number of object sources that lie inside the canvas.</summary>- private readonly int _objSourceCount;-- /// <summary><c>apply_object_sources</c> kernel per field index k, bound to <see cref="_field"/>[k]; <see cref="IntPtr.Zero"/> when there are no object sources.</summary>- private readonly IntPtr[] _objSourceKernel;-- /// <summary>Per object source: padded cell index.</summary>- private IntPtr _objIndexBuffer;-- /// <summary>Per object source: level, indexing <see cref="_frequencyBuffer"/>.</summary>- private IntPtr _objLevelBuffer;-- /// <summary>Per object source: peak amplitude.</summary>- private IntPtr _objAmplitudeBuffer;-- /// <summary>Per object source: phase offset in radians.</summary>- private IntPtr _objPhaseBuffer;-- /// <summary>Per object source: 0 = continuous, 1 = pulsed.</summary>- private IntPtr _objModeBuffer;-- /// <summary>Per object source: 0 = Gaussian pulse, 1 = smoothed square.</summary>- private IntPtr _objPulseShapeBuffer;-- /// <summary>Per object source: on-width of the pulse in cycles.</summary>- private IntPtr _objOnWidthBuffer;-- /// <summary>Per object source: off-width in cycles currently in effect; rewritten by the kernel when the off-width is randomized.</summary>- private IntPtr _objOffWidthBuffer;-- /// <summary>Per object source: step after which it detaches and fades out over <see cref="SourceElement.DetachRampSteps"/> steps, or -1 (never).</summary>- private IntPtr _objDetachStepBuffer;-- /// <summary>Per object source: base off-width (cycles) a randomized off-width is drawn around.</summary>- private IntPtr _objOffWidthBaseBuffer;-- /// <summary>Per object source: ± range (cycles) of the off-width randomization; 0 or less = fixed off-width.</summary>- private IntPtr _objRandomizeOffWidthAmountBuffer;+ /// <summary><c>wave_step</c> kernel per field index k: reads <see cref="_field"/>[k], writes <see cref="_field"/>[1 - k].</summary>+ private readonly IntPtr[] _stepKernel = new IntPtr[2];- /// <summary>Per object source: start (in cycles) of its current period in randomized mode; kernel-owned state, uploaded as 0.</summary>- private IntPtr _objCycleAnchorBuffer;+ /// <summary><c>apply_sources</c> kernel per field index k, bound to <see cref="_field"/>[k]; unset when the scene has no image sources.</summary>+ private readonly IntPtr[] _sourceKernel = new IntPtr[2];- /// <summary>Per object source: xorshift32 state for drawing off-widths; seeded on the host with a non-zero random int, advanced by the kernel.</summary>- private IntPtr _objRngStateBuffer;+ /// <summary><c>apply_object_sources</c> kernel per field index k, bound to <see cref="_field"/>[k]; unset when there are no object sources.</summary>+ private readonly IntPtr[] _objSourceKernel = new IntPtr[2];- /// <summary>Global work size of <c>apply_object_sources</c>: max(1, <see cref="_objSourceCount"/>).</summary>- private readonly IntPtr[] _objGrid1D;+ /// <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;@@ -1391,41 +1292,26 @@ namespace _2D_wave_sim_V01/// <summary>Global work size of <c>apply_sources</c>: max(1, <see cref="_sourceCount"/>).</summary>private readonly IntPtr[] _grid1D;+ /// <summary>Global work size of <c>apply_object_sources</c>: max(1, <see cref="_objSourceCount"/>).</summary>+ private readonly IntPtr[] _objGrid1D;+/// <summary>Host copy of the newest field, refreshed by <see cref="PrepareFrame"/>; exposed as <see cref="FieldData"/>.</summary>- private float[] _hostField;+ private readonly float[] _hostField;/// <summary>Host copy of <see cref="_intensityOutBuffer"/>, refreshed by <see cref="PrepareFrame"/>; null when not tracking.</summary>- private float[] _hostIntensity;+ private readonly float[] _hostIntensity;/// <summary>Elapsed time in steps; passed to the source kernels as the float argument <c>t</c>.</summary>private double _time;- /// <summary>Steps enqueued since the queue was last drained; <see cref="AdvanceOneStep"/> calls clFinish at 16. Reset by every blocking read, which drains the queue anyway.</summary>+ /// <summary>Steps enqueued since the queue was last drained; reset by every blocking read, which drains the queue anyway.</summary>private int _sinceFinish;- /// <summary>Set by <see cref="ReleaseAll"/> so a second release is a no-op.</summary>- private bool _released;-- /// <summary>Rows (steps) the probe history buffer holds before it must be read back to the host.</summary>- private const int ProbeRows = 2048;-- /// <summary>Device the context was created on; needed again to build the probe program.</summary>- private IntPtr _deviceId;-/// <summary>Probe layout installed by <see cref="SetProbes"/>, or null when no probes are set.</summary>private ProbeSampler _probeSampler;- /// <summary>Program built from <see cref="ProbeKernelSource"/>; <see cref="IntPtr.Zero"/> until probes are set.</summary>- private IntPtr _probeProgram;-/// <summary><c>probe_sample</c> kernel per field index k, bound to <see cref="_field"/>[k]; unset without point probes.</summary>- private readonly IntPtr[] _probeKernel;-- /// <summary>Pixel index lists of all point probes, concatenated (at least 1 int).</summary>- private IntPtr _pixelBuffer;-- /// <summary>Per probe (all probes, 4 ints each): start offset in <see cref="_pixelBuffer"/>, pixel count, sample-intensity flag, average flag; all 0 for line probes.</summary>- private IntPtr _infoBuffer;+ private readonly IntPtr[] _probeKernel = new IntPtr[2];/// <summary>Sample history, <see cref="ProbeRows"/> rows × probe count floats, row-major; row r holds the samples of the r-th step since the last read-back.</summary>private IntPtr _historyBuffer;@@ -1434,32 +1320,17 @@ namespace _2D_wave_sim_V01private int _probeRow;/// <summary>Global work size of <c>probe_sample</c>: one work item per probe.</summary>- private readonly IntPtr[] _probeGrid;+ private readonly IntPtr[] _probeGrid = new IntPtr[1];/// <summary>Point-probe samples read back from the device and not yet taken by <see cref="TakeProbeSamples"/>, one list per probe (stays empty for line probes).</summary>- private readonly List<List<float>> _probeValues;+ private readonly List<List<float>> _probeValues = new List<List<float>>();/// <summary><c>profile_gather</c> kernel per field index k, bound to <see cref="_field"/>[k]; unset without line probes.</summary>- private readonly IntPtr[] _gatherKernel;+ private readonly IntPtr[] _gatherKernel = new IntPtr[2];/// <summary><c>profile_accumulate</c> kernel; created only when some line probe integrates (<see cref="_profileIntegrates"/>).</summary>private IntPtr _accumulateKernel;- /// <summary>Padded cell index of every line-probe pixel, all line probes concatenated (<see cref="_profileCount"/> ints).</summary>- private IntPtr _profilePixelBuffer;-- /// <summary>Per line-probe pixel: 0 = field, 1 = intensity, 2 = integrated intensity.</summary>- private IntPtr _profileModeBuffer;-- /// <summary>Per line-probe pixel: whether integration only starts at <see cref="_profileStartStepBuffer"/>; created only when integrating.</summary>- private IntPtr _profileStartFlagBuffer;-- /// <summary>Per line-probe pixel: step from which integration counts; created only when integrating.</summary>- private IntPtr _profileStartStepBuffer;-- /// <summary>Per line-probe pixel: running intensity total, added to by <c>profile_accumulate</c>.</summary>- private IntPtr _profileTotalBuffer;-/// <summary>Per line-probe pixel: value written by <c>profile_gather</c> and read back by <see cref="ReadProbeProfiles"/>.</summary>private IntPtr _profileOutBuffer;@@ -1473,6 +1344,6 @@ namespace _2D_wave_sim_V01private int[] _profileStart;/// <summary>Global work size of the profile kernels: one work item per line-probe pixel.</summary>- private readonly IntPtr[] _profileGrid;+ private readonly IntPtr[] _profileGrid = new IntPtr[1];}}diff --git a/Wave_Dude_2D/HelpForm.cs b/Wave_Dude_2D/HelpForm.csindex 40466be..32f843e 100644--- a/Wave_Dude_2D/HelpForm.cs+++ b/Wave_Dude_2D/HelpForm.cs@@ -5,87 +5,94 @@ using System.Windows.Forms;namespace _2D_wave_sim_V01{/// <summary>- /// Help window: a read-only <see cref="RichTextBox"/> whose contents are built in code by- /// <see cref="FillHelpText"/> (headings, paragraphs and bullet points). Opened modally from- /// the Info menu of <see cref="Form1"/>.+ /// The Info > Help window: a structured description of what each tab of <c>tabMainFunctions</c>+ /// does, which controls on it matter most, and what those controls influence elsewhere in the+ /// program, plus a dedicated section on the propagation speed c, since its correct value depends+ /// on both the Laplacian order and the source frequency and is easy to get wrong.+ /// Designer-editable: the layout (<c>rtbHelp</c>, the Close button) lives in+ /// <c>HelpForm.Designer.cs</c>; this file only fills <c>rtbHelp</c>'s text, in+ /// <see cref="FillHelpText"/> (headings, paragraphs and bullet points built in code). Opened+ /// modally from <see cref="Form1.HelpToolStripMenuItem_Click"/>./// </summary>public partial class HelpForm : Form{/// <summary>Builds the help text and moves the caret to the top so the box is not scrolled to the end.</summary>public HelpForm(){- base.Load += this.HelpForm_Load;- this.InitializeComponent();- this.FillHelpText(this.rtbHelp);- this.rtbHelp.SelectionStart = 0;- this.rtbHelp.SelectionLength = 0;+ base.Load += HelpForm_Load;+ InitializeComponent();+ FillHelpText(rtbHelp);+ rtbHelp.SelectionStart = 0;+ rtbHelp.SelectionLength = 0;}/// <summary>- /// Appends the whole help text to <paramref name="rtb"/>, one section per tab of the main- /// window in UI order, followed by the explanation of the c-value and the menu.+ /// Writes the actual help text into <paramref name="rtb"/>, one section per tab/topic (the tabs+ /// of the main window in UI order, followed by the explanation of the c-value and the menu),+ /// using <see cref="AppendHeading"/>/<see cref="AppendBody"/>/<see cref="AppendBullet"/> for+ /// simple formatting (bold headings, indented bullets)./// </summary>private void FillHelpText(RichTextBox rtb){- this.AppendHeading(rtb, "Wave Dude 2D - Help");- this.AppendHeading(rtb, "Disclaimer");- this.AppendBody(rtb, "The current software comes with no warranty or support and is used at your own risk. It is intended as a free tool for educational use only. Redistribution for commercial purposes is not allowed. Bugs or suggestions for future improvements can be send to the email address in the 'Info > About' screen");- this.AppendHeading(rtb, "Getting started: the project root");- this.AppendBody(rtb, "Every project, its settings, scene, sources, probes and exported files, lives in its own subfolder under one chosen 'project root' folder. Set it with File > Choose project root, or the 'Browse root' button on the Settings tab; the current root is shown above the tabs.");- this.AppendBody(rtb, "The 'Projects in current root' list (Settings tab) shows every project found there: New project, Load, Rename, Delete and Save as all act on the selected one. File > New / Open / Save and 'Save changes to project' act on whichever project is currently open. Nothing is written to disk until you save your project.Projects can be shared between users by sharing the project folder and copy it to their root folder ");- this.AppendBody(rtb, "Load, Rename, Delete and Save as all act on the selected one. File > New / Open / Save and 'Save changes to project' act on whichever project is currently open. Nothing is written to disk until you save.");- this.AppendHeading(rtb, "Settings tab");- this.AppendBody(rtb, "The main control panel: engine and rendering settings, the medium/scene, and starting a run.");- this.AppendBullet(rtb, "Use GPU (generally faster)", "switches the simulation engine between CPU and GPU (OpenCL). Faster for larger grids or step counts, but needs a working OpenCL GPU; the CPU engine is the safe fallback.");- this.AppendBullet(rtb, "Use 4th order Laplacian + sub-sampling", "switches the numerical scheme used to step the wave equation each frame. It runs somewhat slower but strongly reduces numerical dispersion (see 'Propagation speed c' below) - and changes what c should be set to.");- this.AppendBullet(rtb, "Simulation steps / Visualize every", "how many steps a run performs, and how often (in steps) the live preview and probes are refreshed while it runs. A larger 'visualize every' makes a run finish faster at the cost of a choppier preview.");- this.AppendBullet(rtb, "Intensity decay factor", "how quickly the accumulated Intensity view forgets past field energy, i.e. how 'persistent' the intensity build-up looks.");- this.AppendBullet(rtb, "Field/Intensity color scheme, scale and offset", "which color table renders each view (see the Colors tab), and how the raw field/intensity values are stretched (scale) and shifted (offset) into that table's brightness range before coloring. The same scale controls also appear, linked, on the Preview tab.");- this.AppendBullet(rtb, "Preview video of / Export video of (Field/Intensity)", "which of the two views is shown live while running, and which is written to a video file when the run finishes - independent choices.");- this.AppendBullet(rtb, "Video quality (%)", "the compression quality used when writing exported video files.");- this.AppendBullet(rtb, "Refractive index / Damping edge (Scene properties)", "the refractive index shapes the medium the wave travels through (a higher index locally slows the wave - it is what actually sets the per-pixel propagation speed the simulation uses, not c; see below). Damping edge adds an absorbing border so waves leave the grid instead of reflecting off its edges.");- this.AppendBullet(rtb, "User defined (X/Y) scene vs. Scene image", "whether the medium's layout comes from a simple, hand-set shape or from an imported image (its brightness mapped to refractive index).");- this.AppendBullet(rtb, "Use object sources / Use image sources, Edit source list", "whether wave sources are the ones built on the Sources tab, or amplitude taken from an image; 'Edit source list' jumps to the Sources tab.");- this.AppendBody(rtb, "Found at the bottom of everly screen: Quick navigate (jump to Preview/Probes/Sources/Settings), Simulation control (Start Simulation / Pause-Resume), and Share with source/probe (send the current scene, field or intensity picture into the Sources or Probes tools as a background image).");- this.AppendHeading(rtb, "About Scene Images");- this.AppendBody(rtb, "Currently, scene images can only be created externally in a program like for example Photoshop. Save the images in a lossless format like .png . To add objects to a scene that the waves can interact with, you can use the red and green channels in the image color palette.");- this.AppendBullet(rtb, "Red channel (Refractive index)", "can effectively use values ranging from 100 to 255, which represent refractive index values ranging from 1.00 to 2.55. Values lower than 100 will be set to 100 as a minimum. The red channel can be used to refract or reflect waves and create for example lenses.");- this.AppendBullet(rtb, "Blue channel (Damping)", "reserved for damping - use values between 0 and 255, where zero means no damping and 255 heavy damping. It can be used to create regions that absorb waves like for example borders.");- this.AppendBullet(rtb, "Green channel (Sources)", "reserved for creating wave sources, where the values 1-255 represent the frequency of the waves emitted by a pixel. If you use in-scene sources, do not use anti-aliasing to create them since this can cause the pixels next to a source to also contain a (lower) value in the green channel. When you want to use in-image sources, you must have 'use image sources' checked in the setup tab.");- this.AppendHeading(rtb, "Sources tab");- this.AppendBody(rtb, "Defines every object-type wave source placed in the scene; what Is set here directly drives what the simulation emits. When using ");- this.AppendBullet(rtb, "Main type: Single vs. composite", "a single source is one emitter; a composite source is a whole array of them, laid out with a chosen spacing and array size - useful for e.g. simulating an extended or phased source.");- this.AppendBullet(rtb, "Mode: Continuous vs. Pulsed, Frequency, Amplitude, Phase", "a continuous source oscillates forever at the set frequency; a pulsed one also uses the pulse shape/width to taper on and off. Frequency (via the estimated wavelength label) is one of the two things that determine the right value for c - see below.");- this.AppendBullet(rtb, "Composite array: Spacing, Array size, Randomize (Phase/Position/Frequency/Off state)", "how densely and how far the individual emitters in a composite source are spread, and how much each one's properties should vary at random rather than being identical.");- this.AppendBullet(rtb, "Place current source / Pick / Copy / Delete / Save source data", "positions a source in the scene, duplicates or removes it, and can save its data separately; 'Detach after' stops further edits in this panel from affecting an already-placed source.");- this.AppendHeading(rtb, "Probes tab");- this.AppendBody(rtb, "Two independent probes (Probe 1, Probe 2), each measuring the field or intensity over the course of a run and graphing it.");- this.AppendBullet(rtb, "Place on: Field / Intensity, Measurement / Probe type", "which picture the probe samples, and what it reports from it (e.g. a value at a point, or an integrated quantity over a box).");- this.AppendBullet(rtb, "Position A / Position B, Box size, Pick", "where the probe samples - a single point, or a box defined by two corners - set either numerically or by picking on the preview.");- this.AppendBullet(rtb, "Full scale vs. Running scale, Auto scale X / Y", "whether the probe's graph shows the whole run at once or only a recent 'running' window, and whether its axes rescale automatically as new data comes in.");- this.AppendBullet(rtb, "Start recording at step #", "delays when the probe starts collecting data, useful for skipping an initial transient before the wave pattern settles.");- this.AppendHeading(rtb, "Preview tab");- this.AppendBody(rtb, "Shows the live Field and Intensity pictures while a simulation runs, and is where finished pictures/video are exported.");- this.AppendBullet(rtb, "Field/intensity scale factor", "the same brightness scale as on the Settings tab - the two are linked, so changing one updates the other.");- this.AppendBullet(rtb, "Display overlay, overlay brightness", "blends a 'glowing edges' outline (derived from the scene image) on top of either preview, purely as a visual aid to see the scene layout under the field/intensity. This overlay is also baked into an exported frame or video when it is switched on, not just shown live.");- this.AppendBullet(rtb, "Export video of (Field/Intensity), Export frame as image", "start a video export for the checked view(s) once a run starts, or immediately save the current picture as a PNG. Exported file names end in a plain running number (e.g. _0001) - one higher than the highest such number already in that output folder - rather than a date/time stamp.");- this.AppendBullet(rtb, "Open image/video folder, View video in media player", "quick access to what has already been exported for this project.");- this.AppendHeading(rtb, "Manage output tab");- this.AppendBody(rtb, "An overview of everything a project has produced: scenes, exported images and exported videos, each with its creation date. From here files can be renamed, deleted, previewed, opened in their folder, viewed in the media player, copied to the clipboard, or shared back into the Sources/Probes tabs as a background image; external scene files can also be loaded in.");- this.AppendHeading(rtb, "Colors tab");- this.AppendBody(rtb, "Manages the color schemes used to render the Field and Intensity pictures everywhere else in the program.");- this.AppendBullet(rtb, "Scheme list", "every scheme found in the scheme folder, sortable by clicking the Scheme or Type column header; Type marks whether a scheme is meant for the Field or the Intensity view (the Settings/Preview tabs' color-scheme pickers use this).");- this.AppendBullet(rtb, "Color Scheme Editor: Color 1..9, color picker", "builds a 9-stop scheme by picking a color for each stop; Save, Save As, Rename and Delete act on the scheme currently being edited.");- this.AppendBullet(rtb, "Scheme folder, Choose...", "where schemes are read from and saved to; changing it reloads the list.");- this.AppendHeading(rtb, "Propagation speed (c): the Laplacian order and source frequency");- this.AppendBody(rtb, "c (File > Set c-value, in pixels per simulation step) is only a display/estimate value: it is used solely to compute the estimated wavelength shown next to a source's frequency on the Sources tab (lambda = c / frequency). The wave speed the simulation actually uses at each point comes from the scene's refractive index instead, and can vary from point to point - c does not change how the run itself behaves, only what that wavelength readout says.");- this.AppendBody(rtb, "Getting that readout right, however, depends on both the Laplacian order and the source's frequency, because of numerical dispersion - the standard (3rd order) Laplacian makes longer wavelengths propagate faster through the grid than shorter ones, purely as a numerical artifact of the scheme, not a real physical effect.");- this.AppendBullet(rtb, "4th order Laplacian + sub-sampling (on)", "greatly reduces this dispersion. With it on, set c to 1.00 - the estimate then stays accurate across frequencies.");- this.AppendBullet(rtb, "Standard 3rd order Laplacian (4th order off)", "dispersion is significant, so the correct c depends strongly on frequency: lower frequencies need a higher c, higher frequencies need a lower c. For example, at a source frequency where the true wavelength is 15 pixels, c must be set to about 0.56 (not 1.00) for the readout to show that; leaving c at 1.00 there would read out roughly 9 pixels instead.");- this.AppendBody(rtb, "In short: when 4th order is off, re-check (or reduce) c whenever the source frequency changes noticeably. The '(Info)' label next to the 4th order checkbox on the Settings tab repeats this explanation in the program itself.");- this.AppendHeading(rtb, "Menu");- this.AppendBody(rtb, "File: New, Open, Choose project root, Set c-value, Save, Exit.\r\nInfo: this Help page, and About.");- this.AppendBody(rtb, "Enjoy! Jeroen \r\n");+ AppendHeading(rtb, "Wave Dude 2D - Help");+ AppendHeading(rtb, "Disclaimer");+ AppendBody(rtb, "The current software comes with no warranty or support and is used at your own risk. It is free software, released under the GNU General Public License, version 3 or later: you may use, modify and redistribute it under the terms of that license (see the LICENSE file that comes with the source code). Bugs or suggestions for future improvements can be send to the email address in the 'Info > About' screen");+ AppendHeading(rtb, "Getting started: the project root");+ AppendBody(rtb, "Every project, its settings, scene, sources, probes and exported files, lives in its own subfolder under one chosen 'project root' folder. Set it with File > Choose project root, or the 'Browse root' button on the Settings tab; the current root is shown above the tabs.");+ AppendBody(rtb, "The 'Projects in current root' list (Settings tab) shows every project found there: New project, Load, Rename, Delete and Save as all act on the selected one. File > New / Open / Save and 'Save changes to project' act on whichever project is currently open. Nothing is written to disk until you save your project.Projects can be shared between users by sharing the project folder and copy it to their root folder ");+ AppendBody(rtb, "Load, Rename, Delete and Save as all act on the selected one. File > New / Open / Save and 'Save changes to project' act on whichever project is currently open. Nothing is written to disk until you save.");+ AppendHeading(rtb, "Settings tab");+ AppendBody(rtb, "The main control panel: engine and rendering settings, the medium/scene, and starting a run.");+ AppendBullet(rtb, "Use GPU (generally faster)", "switches the simulation engine between CPU and GPU (OpenCL). Faster for larger grids or step counts, but needs a working OpenCL GPU; the CPU engine is the safe fallback.");+ AppendBullet(rtb, "Use 4th order Laplacian + sub-sampling", "switches the numerical scheme used to step the wave equation each frame. It runs somewhat slower but strongly reduces numerical dispersion (see 'Propagation speed c' below) - and changes what c should be set to.");+ AppendBullet(rtb, "Simulation steps / Visualize every", "how many steps a run performs, and how often (in steps) the live preview and probes are refreshed while it runs. A larger 'visualize every' makes a run finish faster at the cost of a choppier preview.");+ AppendBullet(rtb, "Intensity decay factor", "how quickly the accumulated Intensity view forgets past field energy, i.e. how 'persistent' the intensity build-up looks.");+ AppendBullet(rtb, "Field/Intensity color scheme, scale and offset", "which color table renders each view (see the Colors tab), and how the raw field/intensity values are stretched (scale) and shifted (offset) into that table's brightness range before coloring. The same scale controls also appear, linked, on the Preview tab.");+ AppendBullet(rtb, "Preview video of / Export video of (Field/Intensity)", "which of the two views is shown live while running, and which is written to a video file when the run finishes - independent choices.");+ AppendBullet(rtb, "Video quality (%)", "the compression quality used when writing exported video files.");+ AppendBullet(rtb, "Refractive index / Damping edge (Scene properties)", "the refractive index shapes the medium the wave travels through (a higher index locally slows the wave - it is what actually sets the per-pixel propagation speed the simulation uses, not c; see below). Damping edge adds an absorbing border so waves leave the grid instead of reflecting off its edges.");+ AppendBullet(rtb, "User defined (X/Y) scene vs. Scene image", "whether the medium's layout comes from a simple, hand-set shape or from an imported image (its brightness mapped to refractive index).");+ AppendBullet(rtb, "Use object sources / Use image sources, Edit source list", "whether wave sources are the ones built on the Sources tab, or amplitude taken from an image; 'Edit source list' jumps to the Sources tab.");+ AppendBody(rtb, "Found at the bottom of everly screen: Quick navigate (jump to Preview/Probes/Sources/Settings), Simulation control (Start Simulation / Pause-Resume), and Share with source/probe (send the current scene, field or intensity picture into the Sources or Probes tools as a background image).");+ AppendHeading(rtb, "About Scene Images");+ AppendBody(rtb, "Currently, scene images can only be created externally in a program like for example Photoshop. Save the images in a lossless format like .png . To add objects to a scene that the waves can interact with, you can use the red and green channels in the image color palette.");+ AppendBullet(rtb, "Red channel (Refractive index)", "can effectively use values ranging from 100 to 255, which represent refractive index values ranging from 1.00 to 2.55. Values lower than 100 will be set to 100 as a minimum. The red channel can be used to refract or reflect waves and create for example lenses.");+ AppendBullet(rtb, "Blue channel (Damping)", "reserved for damping - use values between 0 and 255, where zero means no damping and 255 heavy damping. It can be used to create regions that absorb waves like for example borders.");+ AppendBullet(rtb, "Green channel (Sources)", "reserved for creating wave sources, where the values 1-255 represent the frequency of the waves emitted by a pixel. If you use in-scene sources, do not use anti-aliasing to create them since this can cause the pixels next to a source to also contain a (lower) value in the green channel. When you want to use in-image sources, you must have 'use image sources' checked in the setup tab.");+ AppendHeading(rtb, "Sources tab");+ AppendBody(rtb, "Defines every object-type wave source placed in the scene; what Is set here directly drives what the simulation emits. When using ");+ AppendBullet(rtb, "Main type: Single vs. composite", "a single source is one emitter; a composite source is a whole array of them, laid out with a chosen spacing and array size - useful for e.g. simulating an extended or phased source.");+ AppendBullet(rtb, "Mode: Continuous vs. Pulsed, Frequency, Amplitude, Phase", "a continuous source oscillates forever at the set frequency; a pulsed one also uses the pulse shape/width to taper on and off. Frequency (via the estimated wavelength label) is one of the two things that determine the right value for c - see below.");+ AppendBullet(rtb, "Composite array: Spacing, Array size, Randomize (Phase/Position/Frequency/Off state)", "how densely and how far the individual emitters in a composite source are spread, and how much each one's properties should vary at random rather than being identical.");+ AppendBullet(rtb, "Place current source / Pick / Copy / Delete / Save source data", "positions a source in the scene, duplicates or removes it, and can save its data separately; 'Detach after' stops further edits in this panel from affecting an already-placed source.");+ AppendHeading(rtb, "Probes tab");+ AppendBody(rtb, "Two independent probes (Probe 1, Probe 2), each measuring the field or intensity over the course of a run and graphing it.");+ AppendBullet(rtb, "Place on: Field / Intensity, Measurement / Probe type", "which picture the probe samples, and what it reports from it (e.g. a value at a point, or an integrated quantity over a box).");+ AppendBullet(rtb, "Position A / Position B, Box size, Pick", "where the probe samples - a single point, or a box defined by two corners - set either numerically or by picking on the preview.");+ AppendBullet(rtb, "Full scale vs. Running scale, Auto scale X / Y", "whether the probe's graph shows the whole run at once or only a recent 'running' window, and whether its axes rescale automatically as new data comes in.");+ AppendBullet(rtb, "Start recording at step #", "delays when the probe starts collecting data, useful for skipping an initial transient before the wave pattern settles.");+ AppendHeading(rtb, "Preview tab");+ AppendBody(rtb, "Shows the live Field and Intensity pictures while a simulation runs, and is where finished pictures/video are exported.");+ AppendBullet(rtb, "Field/intensity scale factor", "the same brightness scale as on the Settings tab - the two are linked, so changing one updates the other.");+ AppendBullet(rtb, "Display overlay, overlay brightness", "blends a 'glowing edges' outline (derived from the scene image) on top of either preview, purely as a visual aid to see the scene layout under the field/intensity. This overlay is also baked into an exported frame or video when it is switched on, not just shown live.");+ AppendBullet(rtb, "Export video of (Field/Intensity), Export frame as image", "start a video export for the checked view(s) once a run starts, or immediately save the current picture as a PNG. Exported file names end in a plain running number (e.g. _0001) - one higher than the highest such number already in that output folder - rather than a date/time stamp.");+ AppendBullet(rtb, "Open image/video folder, View video in media player", "quick access to what has already been exported for this project.");+ AppendHeading(rtb, "Manage output tab");+ AppendBody(rtb, "An overview of everything a project has produced: scenes, exported images and exported videos, each with its creation date. From here files can be renamed, deleted, previewed, opened in their folder, viewed in the media player, copied to the clipboard, or shared back into the Sources/Probes tabs as a background image; external scene files can also be loaded in.");+ AppendHeading(rtb, "Colors tab");+ AppendBody(rtb, "Manages the color schemes used to render the Field and Intensity pictures everywhere else in the program.");+ AppendBullet(rtb, "Scheme list", "every scheme found in the scheme folder, sortable by clicking the Scheme or Type column header; Type marks whether a scheme is meant for the Field or the Intensity view (the Settings/Preview tabs' color-scheme pickers use this).");+ AppendBullet(rtb, "Color Scheme Editor: Color 1..9, color picker", "builds a 9-stop scheme by picking a color for each stop; Save, Save As, Rename and Delete act on the scheme currently being edited.");+ AppendBullet(rtb, "Scheme folder, Choose...", "where schemes are read from and saved to; changing it reloads the list.");+ AppendHeading(rtb, "Propagation speed (c): the Laplacian order and source frequency");+ AppendBody(rtb, "c (File > Set c-value, in pixels per simulation step) is only a display/estimate value: it is used solely to compute the estimated wavelength shown next to a source's frequency on the Sources tab (lambda = c / frequency). The wave speed the simulation actually uses at each point comes from the scene's refractive index instead, and can vary from point to point - c does not change how the run itself behaves, only what that wavelength readout says.");+ AppendBody(rtb, "Getting that readout right, however, depends on both the Laplacian order and the source's frequency, because of numerical dispersion - the standard (3rd order) Laplacian makes longer wavelengths propagate faster through the grid than shorter ones, purely as a numerical artifact of the scheme, not a real physical effect.");+ AppendBullet(rtb, "4th order Laplacian + sub-sampling (on)", "greatly reduces this dispersion. With it on, set c to 1.00 - the estimate then stays accurate across frequencies.");+ AppendBullet(rtb, "Standard 3rd order Laplacian (4th order off)", "dispersion is significant, so the correct c depends strongly on frequency: lower frequencies need a higher c, higher frequencies need a lower c. For example, at a source frequency where the true wavelength is 15 pixels, c must be set to about 0.56 (not 1.00) for the readout to show that; leaving c at 1.00 there would read out roughly 9 pixels instead.");+ AppendBody(rtb, "In short: when 4th order is off, re-check (or reduce) c whenever the source frequency changes noticeably. The '(Info)' label next to the 4th order checkbox on the Settings tab repeats this explanation in the program itself.");+ AppendHeading(rtb, "Menu");+ AppendBody(rtb, "File: New, Open, Choose project root, Set c-value, Save, Exit.\r\nInfo: this Help page, and About.");+ AppendBody(rtb, "Enjoy! Jeroen \r\n");}/// <summary>Appends a blank line and then <paramref name="text"/> in bold, near-black type, as a section heading.</summary>@@ -109,8 +116,9 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Appends an indented bullet line: a dash, <paramref name="label"/> in bold followed by a- /// colon, then <paramref name="explanation"/> in regular type.+ /// Appends a single indented "- Label: explanation" line: a dash, <paramref name="label"/> in+ /// bold followed by a colon, then <paramref name="explanation"/> in regular type. Used for the+ /// per-control breakdowns within a tab's section./// </summary>private void AppendBullet(RichTextBox rtb, string label, string explanation){diff --git a/Wave_Dude_2D/IMFAttributesNative.cs b/Wave_Dude_2D/IMFAttributesNative.csindex c5877e4..3098012 100644--- a/Wave_Dude_2D/IMFAttributesNative.cs+++ b/Wave_Dude_2D/IMFAttributesNative.cs@@ -5,9 +5,11 @@ namespace _2D_wave_sim_V01{/// <summary>/// Hand-written COM import of Media Foundation's <c>IMFAttributes</c> (IID 2CD2D921-...), used by- /// <see cref="MfVideoWriter"/> to set media-type attributes. The method order mirrors the native vtable and- /// must not change; only the three <c>Set*</c> members that are actually called carry real signatures, the rest- /// are parameterless placeholders that keep the slots aligned (never call them). All methods return an HRESULT.+ /// <see cref="MfVideoWriter"/> to set media-type attributes. Only the order of the methods matters (it is the+ /// order of the entries in the COM method table) and it must not change; only the three <c>Set*</c> members that+ /// are actually called carry real signatures, the rest are parameterless placeholders that keep the slots aligned+ /// (never call them). All methods return an HRESULT. <see cref="IMFSampleNative"/> repeats all 30 of these slots+ /// instead of deriving from this interface, because .NET does not inherit base-interface methods in COM interfaces./// </summary>[Guid("2CD2D921-C447-44A7-A13C-4ADABFC247E3")][InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]diff --git a/Wave_Dude_2D/IMFSampleNative.cs b/Wave_Dude_2D/IMFSampleNative.csindex 40a8ebd..c76f573 100644--- a/Wave_Dude_2D/IMFSampleNative.cs+++ b/Wave_Dude_2D/IMFSampleNative.cs@@ -7,7 +7,10 @@ namespace _2D_wave_sim_V01/// Hand-written COM import of Media Foundation's <c>IMFSample</c> (IID C40A00F2-...), one time-stamped video frame/// handed to the sink writer by <see cref="MfVideoWriter.AddPixels"/>. <c>IMFSample</c> derives from <c>IMFAttributes</c>,/// so the first 30 slots (<c>A01</c>..<c>A30</c>) are placeholders for the inherited attribute methods, followed by the- /// sample's own methods. Vtable order is frozen; all methods return an HRESULT.+ /// sample's own methods. They are repeated here rather than taken from <see cref="IMFAttributesNative"/> because .NET+ /// does not inherit base-interface methods in COM interfaces: a derived <c>ComImport</c> interface's own methods are+ /// numbered from the slot after <c>IUnknown</c>, not after the base interface's methods. Vtable order is frozen;+ /// all methods return an HRESULT./// </summary>[Guid("C40A00F2-B93A-4D80-AE8C-5A1C634F58E4")][InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]diff --git a/Wave_Dude_2D/IWaveEngine.cs b/Wave_Dude_2D/IWaveEngine.csindex 5a7a7ad..77a838b 100644--- a/Wave_Dude_2D/IWaveEngine.cs+++ b/Wave_Dude_2D/IWaveEngine.cs@@ -9,9 +9,9 @@ namespace _2D_wave_sim_V01/// Only <see cref="PrepareFrame"/> and the data properties are also used from the UI thread, and only while the/// runner is paused (see <see cref="SimulationRunner.RenderCurrentFrame"/>)./// </summary>- internal interface IWaveEngine : IDisposable+ internal interface IWaveEngine{- /// <summary>Short name for the status bar and result: "CPU (n threads)" or "GPU: device name (OpenCL)".</summary>+ /// <summary>Where the simulation runs, for the status bar and result: for example "CPU (8 threads)" or "GPU: NVIDIA GeForce MX130 (OpenCL)".</summary>string Description { get; }/// <summary>Scene width in cells (= canvas pixels), without padding.</summary>@@ -20,25 +20,30 @@ namespace _2D_wave_sim_V01/// <summary>Scene height in cells (= canvas pixels), without padding.</summary>int Height { get; }- /// <summary>Row pitch of <see cref="FieldData"/> and <see cref="IntensityData"/>: <see cref="Width"/> + 2.</summary>+ /// <summary>Row pitch of <see cref="FieldData"/> and <see cref="IntensityData"/>: <see cref="Width"/> + 2. Pixel (x, y) is at (y + 1) * Stride + x + 1.</summary>int Stride { get; }/// <summary>- /// Current field amplitude, <see cref="Stride"/> * (<see cref="Height"/> + 2) floats. Valid for reading after- /// <see cref="PrepareFrame"/>; the CPU engine exposes its live buffer (a different array instance after every- /// sub-step, so re-read the property per frame), the GPU engine a host copy.+ /// The field of the last completed step, <see cref="Stride"/> * (<see cref="Height"/> + 2) floats. Valid for+ /// reading after <see cref="PrepareFrame"/>(true, ...); the CPU engine exposes its live buffer (a different+ /// array instance after every sub-step, so re-read the property per frame), the GPU engine a host copy.+ /// Do not change./// </summary>float[] FieldData { get; }- /// <summary>Accumulated intensity, same layout as <see cref="FieldData"/>; null when intensity tracking was not requested.</summary>+ /// <summary>+ /// The averaged intensity, same layout as <see cref="FieldData"/>, valid after <see cref="PrepareFrame"/>(..., true);+ /// null when intensity tracking was not requested. Do not change.+ /// </summary>float[] IntensityData { get; }- /// <summary>Advances the simulation by one time step (internally several sub-steps with the 4th-order Laplacian).</summary>+ /// <summary>One time step: apply the sources, update the field (internally several sub-steps with the 4th-order Laplacian), update the intensity.</summary>void AdvanceOneStep();/// <summary>- /// Makes the requested buffers reflect the current state so the renderer can read them: a no-op on the CPU,- /// a device-to-host copy on the GPU. Call before touching <see cref="FieldData"/> / <see cref="IntensityData"/>.+ /// Makes the requested buffers reflect the current state so the renderer can read them: a no-op on the CPU;+ /// on the GPU the data is copied from the graphics memory, so only ask for what is going to be drawn. Call+ /// before touching <see cref="FieldData"/> / <see cref="IntensityData"/>./// </summary>void PrepareFrame(bool needField, bool needIntensity);@@ -49,17 +54,23 @@ namespace _2D_wave_sim_V01/// <exception cref="InvalidOperationException">A probe needs the intensity but it is not tracked, or the GPU probe kernel cannot be built.</exception>void SetProbes(ProbeSampler sampler);- /// <summary>Records one sample per series probe for the current step and accumulates integrating profiles; call after each <see cref="AdvanceOneStep"/>.</summary>+ /// <summary>+ /// Measures the probes in the state after the last <see cref="AdvanceOneStep"/>: one value per step for every+ /// point probe, and the running totals of the line probes that integrate the intensity.+ /// </summary>void SampleProbes();/// <summary>- /// Returns and clears the series samples gathered since the last call, one array per probe (empty for profile probes).+ /// Returns and clears the values measured for the point probes since the last call, one array per probe (empty for line probes)./// </summary>/// <returns>Empty outer array when no probes are installed.</returns>float[][] TakeProbeSamples();- /// <summary>Reads the current values along each profile probe, one array per profile probe.</summary>- /// <returns>Null entries for non-profile probes; empty outer array when no probes are installed.</returns>+ /// <summary>+ /// The values along the line of every line probe in the current state: the field, the intensity, or the+ /// intensity totals of the steps so far. On the GPU this waits for the card, so do not call it every step.+ /// </summary>+ /// <returns>Null entries for point probes; empty outer array when no probes are installed.</returns>float[][] ReadProbeProfiles();}}diff --git a/Wave_Dude_2D/MfVideoWriter.cs b/Wave_Dude_2D/MfVideoWriter.csindex 1f4b3d3..ddcf9c3 100644--- a/Wave_Dude_2D/MfVideoWriter.cs+++ b/Wave_Dude_2D/MfVideoWriter.cs@@ -6,8 +6,10 @@ namespace _2D_wave_sim_V01/// <summary>/// <see cref="IFrameSink"/> that encodes H.264 MP4 through the Media Foundation sink writer/// (<c>mfplat.dll</c> / <c>mfreadwrite.dll</c>, talked to via the hand-written <c>IMF*Native</c> COM- /// interfaces). Created by <see cref="SimulationRunner"/>; a failing constructor means- /// "no H.264 on this machine" and triggers the AVI fallback. Used from the worker thread only.+ /// interfaces). The H.264 encoder is the one built into Windows, so no codec or other program is needed+ /// and every Windows player opens the file. Created by <see cref="SimulationRunner"/>; a failing+ /// constructor (no Media Foundation or H.264 encoder, size not supported) means "no H.264 on this+ /// machine" and triggers the AVI fallback. Used from the worker thread only./// Media Foundation is started in the constructor and shut down in <see cref="Cleanup"/>./// </summary>internal sealed class MfVideoWriter : IFrameSink@@ -53,70 +55,67 @@ namespace _2D_wave_sim_V01/// <exception cref="COMException">Media Foundation returned a failure HRESULT (no encoder, bad path, ...).</exception>public MfVideoWriter(string filePath, int width, int height, int framesPerSecond, int quality){- this._path = filePath;- this._srcWidth = width;- this._srcHeight = height;- this._width = width & -2;- this._height = height & -2;- this._fps = framesPerSecond;- if (this._width < 16 || this._height < 16)+ _path = filePath;+ _srcWidth = width;+ _srcHeight = height;+ _width = width & ~1; // the encoded size: H.264 needs even sizes+ _height = height & ~1;+ _fps = framesPerSecond;+ if (_width < 16 || _height < 16){throw new NotSupportedException("The canvas is too small for H.264 video.");}- if ((long)this._width * this._height > 9437184L)+ if ((long)_width * _height > 4096L * 2304L){throw new NotSupportedException("The canvas is too large for the H.264 encoder of Windows.");}- if (this._width != this._srcWidth || this._height != this._srcHeight)+ if (_width != _srcWidth || _height != _srcHeight){- this._cropped = new int[this._width * this._height];+ _cropped = new int[_width * _height];}- MfVideoWriter.Check(MfVideoWriter.MFStartup(MfVersion, 0));- this._started = true;+ Check(MFStartup(MfVersion, 0));+ _started = true;try{- MfVideoWriter.Check(MfVideoWriter.MFCreateSinkWriterFromURL(filePath, IntPtr.Zero, IntPtr.Zero, ref this._writerPtr));- this._writer = (IMFSinkWriterNative)Marshal.GetObjectForIUnknown(this._writerPtr);+ Check(MFCreateSinkWriterFromURL(filePath, IntPtr.Zero, IntPtr.Zero, ref _writerPtr));+ _writer = (IMFSinkWriterNative)Marshal.GetObjectForIUnknown(_writerPtr);+ // the quality (1 to 100) sets the bits per pixel of every frame: 0.01 * 50 ^ (quality / 100),+ // which is 0.01 at quality 1, 0.15 at 70 and 0.5 at 100 (1920 x 1080 at 60 frames/s: 1 to 62 Mbit/s)int clampedQuality = Math.Max(1, Math.Min(100, quality));double bitsPerPixel = 0.01 * Math.Pow(50.0, clampedQuality / 100.0);- long bitrate = (long)Math.Round((double)this._width * this._height * this._fps * bitsPerPixel);+ long bitrate = (long)Math.Round((double)_width * _height * _fps * bitsPerPixel);bitrate = Math.Max(300000L, Math.Min(200000000L, bitrate));- IntPtr outputType = this.MakeType(MfVideoWriter.H264Format, (int)bitrate, false);+ IntPtr outputType = MakeType(H264Format, (int)bitrate, false);int streamIndex = 0;try{- MfVideoWriter.Check(this._writer.AddStream(outputType, ref streamIndex));+ Check(_writer.AddStream(outputType, ref streamIndex));}finally{Marshal.Release(outputType);}- IntPtr inputType = this.MakeType(MfVideoWriter.Rgb32Format, 0, true);+ // the pictures are given as 32 bit pixels; the sink writer converts them for the encoder+ IntPtr inputType = MakeType(Rgb32Format, 0, true);try{- MfVideoWriter.Check(this._writer.SetInputMediaType(streamIndex, inputType, IntPtr.Zero));+ Check(_writer.SetInputMediaType(streamIndex, inputType, IntPtr.Zero));}finally{Marshal.Release(inputType);}- MfVideoWriter.Check(this._writer.BeginWriting());+ Check(_writer.BeginWriting());}catch{- this.Cleanup();+ Cleanup();throw;}}/// <summary>The MP4 path given to the constructor.</summary>- public string FilePath- {- get- {- return this._path;- }- }+ public string FilePath => _path;/// <summary>/// Creates a progressive video <c>IMFMediaType</c> for <paramref name="format"/> at the writer's even size,@@ -129,25 +128,25 @@ namespace _2D_wave_sim_V01private IntPtr MakeType(Guid format, int bitrate, bool topDown){IntPtr mediaType = IntPtr.Zero;- MfVideoWriter.Check(MfVideoWriter.MFCreateMediaType(ref mediaType));+ Check(MFCreateMediaType(ref mediaType));try{IMFAttributesNative attributes = (IMFAttributesNative)Marshal.GetObjectForIUnknown(mediaType);try{- MfVideoWriter.Check(attributes.SetGUID(MfVideoWriter.MajorType, MfVideoWriter.VideoType));- MfVideoWriter.Check(attributes.SetGUID(MfVideoWriter.SubType, format));+ Check(attributes.SetGUID(MajorType, VideoType));+ Check(attributes.SetGUID(SubType, format));if (bitrate > 0){- MfVideoWriter.Check(attributes.SetUINT32(MfVideoWriter.AvgBitrate, bitrate));+ Check(attributes.SetUINT32(AvgBitrate, bitrate));}- MfVideoWriter.Check(attributes.SetUINT32(MfVideoWriter.InterlaceMode, 2)); // MFVideoInterlace_Progressive- MfVideoWriter.Check(attributes.SetUINT64(MfVideoWriter.FrameSize, ((ulong)this._width << 32) | (ulong)this._height));- MfVideoWriter.Check(attributes.SetUINT64(MfVideoWriter.FrameRate, ((ulong)this._fps << 32) | 1UL));- MfVideoWriter.Check(attributes.SetUINT64(MfVideoWriter.PixelAspectRatio, 4294967297UL)); // 1:1 packed as (1 << 32) | 1+ Check(attributes.SetUINT32(InterlaceMode, 2)); // MFVideoInterlace_Progressive+ Check(attributes.SetUINT64(FrameSize, ((ulong)_width << 32) | (ulong)_height));+ Check(attributes.SetUINT64(FrameRate, ((ulong)_fps << 32) | 1UL));+ Check(attributes.SetUINT64(PixelAspectRatio, (1UL << 32) | 1UL)); // 1:1if (topDown){- MfVideoWriter.Check(attributes.SetUINT32(MfVideoWriter.DefaultStride, this._width * 4));+ Check(attributes.SetUINT32(DefaultStride, _width * 4));}}finally@@ -174,48 +173,48 @@ namespace _2D_wave_sim_V01/// <exception cref="COMException">A Media Foundation call failed.</exception>public void AddPixels(int[] pixels){- if (this._closed)+ if (_closed){throw new InvalidOperationException("The video file is already closed.");}int[] source = pixels;- if (this._cropped != null)+ if (_cropped != null){- for (int y = 0; y < this._height; y++)+ for (int y = 0; y < _height; y++){- Array.Copy(pixels, y * this._srcWidth, this._cropped, y * this._width, this._width);+ Array.Copy(pixels, y * _srcWidth, _cropped, y * _width, _width);}- source = this._cropped;+ source = _cropped;}- int byteLength = this._width * this._height * 4;+ int byteLength = _width * _height * 4;IntPtr bufferPtr = IntPtr.Zero;IntPtr samplePtr = IntPtr.Zero;IMFMediaBufferNative buffer = null;IMFSampleNative sample = null;try{- MfVideoWriter.Check(MfVideoWriter.MFCreateMemoryBuffer(byteLength, ref bufferPtr));+ Check(MFCreateMemoryBuffer(byteLength, ref bufferPtr));buffer = (IMFMediaBufferNative)Marshal.GetObjectForIUnknown(bufferPtr);IntPtr data = IntPtr.Zero;int maxLength = 0;int currentLength = 0;- MfVideoWriter.Check(buffer.Lock(ref data, ref maxLength, ref currentLength));+ Check(buffer.Lock(ref data, ref maxLength, ref currentLength));try{- Marshal.Copy(source, 0, data, this._width * this._height);+ Marshal.Copy(source, 0, data, _width * _height);}finally{buffer.Unlock();}- MfVideoWriter.Check(buffer.SetCurrentLength(byteLength));- MfVideoWriter.Check(MfVideoWriter.MFCreateSample(ref samplePtr));+ Check(buffer.SetCurrentLength(byteLength));+ Check(MFCreateSample(ref samplePtr));sample = (IMFSampleNative)Marshal.GetObjectForIUnknown(samplePtr);- MfVideoWriter.Check(sample.AddBuffer(bufferPtr));- MfVideoWriter.Check(sample.SetSampleTime(this._frames * 10000000L / this._fps));- MfVideoWriter.Check(sample.SetSampleDuration(10000000L / this._fps));- MfVideoWriter.Check(this._writer.WriteSample(0, samplePtr));- this._frames++;+ Check(sample.AddBuffer(bufferPtr));+ Check(sample.SetSampleTime(_frames * 10000000L / _fps));+ Check(sample.SetSampleDuration(10000000L / _fps));+ Check(_writer.WriteSample(0, samplePtr));+ _frames++;}finally{@@ -246,21 +245,21 @@ namespace _2D_wave_sim_V01/// <exception cref="COMException"><c>Finalize</c> failed; cleanup has still been performed.</exception>public void Close(){- if (this._closed)+ if (_closed){return;}- this._closed = true;+ _closed = true;try{- if (this._writer != null && this._frames > 0)+ if (_writer != null && _frames > 0){- MfVideoWriter.Check(this._writer.FinalizeWriting());+ Check(_writer.FinalizeWriting());}}finally{- this.Cleanup();+ Cleanup();}}@@ -271,27 +270,27 @@ namespace _2D_wave_sim_V01/// </summary>private void Cleanup(){- if (this._writer != null)+ if (_writer != null){- Marshal.ReleaseComObject(this._writer);- this._writer = null;+ Marshal.ReleaseComObject(_writer);+ _writer = null;}- if (this._writerPtr != IntPtr.Zero)+ if (_writerPtr != IntPtr.Zero){- Marshal.Release(this._writerPtr);- this._writerPtr = IntPtr.Zero;+ Marshal.Release(_writerPtr);+ _writerPtr = IntPtr.Zero;}- if (this._started)+ if (_started){- this._started = false;- MfVideoWriter.MFShutdown();+ _started = false;+ MFShutdown();}}/// <summary>Same as <see cref="Close"/>.</summary>public void Dispose(){- this.Close();+ Close();}/// <summary>Throws the matching .NET exception for a failed HRESULT (negative value); succeeds silently otherwise.</summary>@@ -303,8 +302,11 @@ namespace _2D_wave_sim_V01}}- /// <summary><c>MF_VERSION</c> = 0x00020070 (SDK version 2, API version 0x70) passed to <c>MFStartup</c>.</summary>- private const int MfVersion = 131184;+ /// <summary>+ /// The version of Media Foundation that is asked for: <c>MF_VERSION</c> of the Windows 7 and later SDK+ /// (SDK version 2, API version 0x70), passed to <c>MFStartup</c>.+ /// </summary>+ private const int MfVersion = 0x00020070;/// <summary><c>MF_MT_MAJOR_TYPE</c> attribute key.</summary>private static readonly Guid MajorType = new Guid("48eba18e-f8c9-4687-bf11-0a74c9f96a8f");diff --git a/Wave_Dude_2D/OpenClApi.cs b/Wave_Dude_2D/OpenClApi.csindex 453583c..a9b9c97 100644--- a/Wave_Dude_2D/OpenClApi.cs+++ b/Wave_Dude_2D/OpenClApi.cs@@ -6,13 +6,19 @@ using System.Text;namespace _2D_wave_sim_V01{/// <summary>- /// Thin P/Invoke layer over OpenCL.dll (the ICD loader installed with the graphics driver) plus a few query- /// helpers. Used by <see cref="GpuDeviceInfo"/> and <see cref="GpuWaveSimulator"/>; every call returns an- /// OpenCL error code (0 = CL_SUCCESS) that callers route through <see cref="Check"/>. Loading the DLL is- /// deferred to the first call, so <see cref="DllNotFoundException"/> and friends surface there.+ /// The part of the OpenCL 1.2 C interface that the GPU simulation needs, called directly from OpenCL.dll (the+ /// ICD loader) plus a few query helpers. OpenCL.dll is installed with the driver of the graphics card (NVIDIA,+ /// Intel and AMD all install it), so no extra package is needed. Names and parameters follow the C header+ /// (cl.h); <c>size_t</c> is an <see cref="IntPtr"/>, <c>cl_bitfield</c> a <c>ulong</c>, <c>cl_uint</c> a+ /// <c>uint</c> and <c>cl_bool</c> a <c>uint</c>. Used by <see cref="GpuDeviceInfo"/> and+ /// <see cref="GpuWaveSimulator"/>; every call returns an OpenCL error code (0 = CL_SUCCESS) that callers route+ /// through <see cref="Check"/>. Loading the DLL is deferred to the first call, so+ /// <see cref="DllNotFoundException"/> and friends surface there./// </summary>internal sealed class OpenClApi{+ // ---- platforms and devices+/// <summary>clGetPlatformIDs: with <paramref name="platforms"/> null only counts the platforms into <paramref name="numPlatforms"/>.</summary>[DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]internal static extern int clGetPlatformIDs(uint numEntries, IntPtr[] platforms, ref uint numPlatforms);@@ -25,6 +31,8 @@ namespace _2D_wave_sim_V01[DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]internal static extern int clGetDeviceInfo(IntPtr device, uint paramName, IntPtr paramSize, byte[] paramValue, ref IntPtr sizeRet);+ // ---- context, queue, program, kernels+/// <summary>clCreateContext: creates a context for the given devices; <paramref name="properties"/> is a zero-terminated key/value list (see <see cref="ContextPlatformProperty"/>). Release with <see cref="clReleaseContext"/>.</summary>[DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]internal static extern IntPtr clCreateContext(IntPtr[] properties, uint numDevices, IntPtr[] devices, IntPtr notify, IntPtr userData, ref int errcode);@@ -61,6 +69,8 @@ namespace _2D_wave_sim_V01[DllImport("OpenCL.dll", CharSet = CharSet.Ansi, EntryPoint = "clSetKernelArg", ExactSpelling = true, SetLastError = true)]internal static extern int clSetKernelArgFloat(IntPtr kernel, uint argIndex, IntPtr argSize, ref float argValue);+ // ---- memory and execution+/// <summary>clCreateBuffer: a device buffer of <paramref name="size"/> bytes with the given CL_MEM flags (<see cref="MemReadWrite"/>). Release with <see cref="clReleaseMemObject"/>.</summary>[DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]internal static extern IntPtr clCreateBuffer(IntPtr context, ulong flags, IntPtr size, IntPtr hostPtr, ref int errcode);@@ -85,6 +95,8 @@ namespace _2D_wave_sim_V01[DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]internal static extern int clFinish(IntPtr queue);+ // ---- release+/// <summary>clReleaseMemObject: drops a reference to a buffer created by <see cref="clCreateBuffer"/>.</summary>[DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]internal static extern int clReleaseMemObject(IntPtr memObj);@@ -105,6 +117,8 @@ namespace _2D_wave_sim_V01[DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]internal static extern int clReleaseContext(IntPtr context);+ // ---- helpers+/// <summary>Throws if an OpenCL call did not return CL_SUCCESS.</summary>/// <param name="code">Return value or errcode output of the OpenCL call.</param>/// <param name="what">Name of the call, used in the exception message.</param>@@ -282,6 +296,8 @@ namespace _2D_wave_sim_V01}}+ // ---- constants, spelled as in cl.h+/// <summary>CL_DEVICE_TYPE_GPU (1 << 2).</summary>internal const ulong DeviceTypeGpu = 4UL;@@ -289,33 +305,33 @@ namespace _2D_wave_sim_V01internal const ulong MemReadWrite = 1UL;/// <summary>CL_CONTEXT_PLATFORM (0x1084): property key for the platform in <see cref="clCreateContext"/>.</summary>- internal const int ContextPlatformProperty = 4228;+ internal const int ContextPlatformProperty = 0x1084;/// <summary>CL_PLATFORM_NAME (0x0902).</summary>- internal const uint PlatformNameInfo = 2306U;+ internal const uint PlatformNameInfo = 0x902U;/// <summary>CL_DEVICE_MAX_COMPUTE_UNITS (0x1002), cl_uint.</summary>- internal const uint DeviceMaxComputeUnits = 4098U;+ internal const uint DeviceMaxComputeUnits = 0x1002U;/// <summary>CL_DEVICE_MAX_CLOCK_FREQUENCY (0x100C), cl_uint in MHz.</summary>- internal const uint DeviceMaxClockFrequency = 4108U;+ internal const uint DeviceMaxClockFrequency = 0x100CU;/// <summary>CL_DEVICE_MAX_MEM_ALLOC_SIZE (0x1010), cl_ulong bytes.</summary>- internal const uint DeviceMaxMemAllocSize = 4112U;+ internal const uint DeviceMaxMemAllocSize = 0x1010U;/// <summary>CL_DEVICE_GLOBAL_MEM_SIZE (0x101F), cl_ulong bytes.</summary>- internal const uint DeviceGlobalMemSize = 4127U;+ internal const uint DeviceGlobalMemSize = 0x101FU;/// <summary>CL_DEVICE_NAME (0x102B), string.</summary>- internal const uint DeviceName = 4139U;+ internal const uint DeviceName = 0x102BU;/// <summary>CL_DEVICE_VENDOR (0x102C), string.</summary>- internal const uint DeviceVendor = 4140U;+ internal const uint DeviceVendor = 0x102CU;/// <summary>CL_DEVICE_HOST_UNIFIED_MEMORY (0x1035), cl_bool: non-zero for devices sharing host memory (integrated GPUs).</summary>- internal const uint DeviceHostUnifiedMemory = 4149U;+ internal const uint DeviceHostUnifiedMemory = 0x1035U;/// <summary>CL_PROGRAM_BUILD_LOG (0x1183), string.</summary>- internal const uint ProgramBuildLog = 4483U;+ internal const uint ProgramBuildLog = 0x1183U;}}diff --git a/Wave_Dude_2D/ProbeBoxSize.cs b/Wave_Dude_2D/ProbeBoxSize.csindex b98ca03..d13d00f 100644--- a/Wave_Dude_2D/ProbeBoxSize.cs+++ b/Wave_Dude_2D/ProbeBoxSize.cs@@ -9,14 +9,14 @@ namespace _2D_wave_sim_V01public enum ProbeBoxSize{/// <summary>200 x 100 canvas pixels.</summary>- Tiny,+ Tiny = 0,/// <summary>300 x 150 canvas pixels.</summary>- Small,+ Small = 1,/// <summary>400 x 200 canvas pixels (default).</summary>- Medium,+ Medium = 2,/// <summary>500 x 250 canvas pixels.</summary>- Large,+ Large = 3,/// <summary>700 x 350 canvas pixels.</summary>- ExtraLarge+ ExtraLarge = 4}}diff --git a/Wave_Dude_2D/ProbeCollector.cs b/Wave_Dude_2D/ProbeCollector.csindex 4a11035..4a06ab3 100644--- a/Wave_Dude_2D/ProbeCollector.cs+++ b/Wave_Dude_2D/ProbeCollector.cs@@ -17,15 +17,15 @@ namespace _2D_wave_sim_V01/// <summary>Creates one empty <see cref="ProbeTrace"/> and one pending sample list per probe of <paramref name="sampler"/>.</summary>public ProbeCollector(ProbeSampler sampler){- this._pending = new List<List<float>>();- this._sampler = sampler;- this.Traces = new ProbeTrace[sampler.Count];- this._totals = new double[sampler.Count];- this._fresh = new bool[sampler.Count];+ _pending = new List<List<float>>();+ _sampler = sampler;+ Traces = new ProbeTrace[sampler.Count];+ _totals = new double[sampler.Count];+ _fresh = new bool[sampler.Count];for (int i = 0; i < sampler.Count; i++){- this.Traces[i] = new ProbeTrace();- this._pending.Add(new List<float>());+ Traces[i] = new ProbeTrace();+ _pending.Add(new List<float>());}}@@ -40,15 +40,17 @@ namespace _2D_wave_sim_V01/// <param name="stepsDone">Steps completed so far; recorded as <see cref="ProbeTrace.StepsSampled"/>.</param>public void Collect(IWaveEngine engine, int stepsDone){- if (!this._sampler.HasSeries)+ if (!_sampler.HasSeries){return;}float[][] samples = engine.TakeProbeSamples();- int lastStepsDone = this._lastStepsDone;- for (int i = 0; i < this._sampler.Count; i++)+ // the number of steps already processed before this batch, so the absolute step of values[j] can be worked+ // out below (one value per step, in order) - needed to purge a cumulative total from before "start after step"+ int batchStartStep = _lastStepsDone;+ for (int i = 0; i < _sampler.Count; i++){- if (this._sampler.IsProfile[i] || i >= samples.Length)+ if (_sampler.IsProfile[i] || i >= samples.Length){continue;}@@ -57,30 +59,32 @@ namespace _2D_wave_sim_V01{continue;}- if (this._sampler.Cumulative[i])+ if (_sampler.Cumulative[i]){- bool useStartAfterStep = this._sampler.UseStartAfterStep[i];- int startAfterStep = this._sampler.StartAfterStep[i];+ bool useStartAfterStep = _sampler.UseStartAfterStep[i];+ int startAfterStep = _sampler.StartAfterStep[i];for (int j = 0; j < values.Length; j++){- // sample j belongs to step lastStepsDone + j + 1 (one sample per step)- if (useStartAfterStep && lastStepsDone + j + 1 < startAfterStep)+ // sample j belongs to step batchStartStep + j + 1 (one sample per step)+ if (useStartAfterStep && batchStartStep + j + 1 < startAfterStep){- this._totals[i] = 0.0;+ // before recording starts: keep the running total at zero, purging any intensity that+ // arrived earlier, so the total does not jump the moment recording starts+ _totals[i] = 0.0;values[j] = 0f;}else{- this._totals[i] += values[j];- values[j] = (float)this._totals[i];+ _totals[i] += values[j];+ values[j] = (float)_totals[i];}}}- this.Traces[i].Series.Add(values);- this.Traces[i].StepsSampled = stepsDone;- this._pending[i].AddRange(values);+ Traces[i].Series.Add(values);+ Traces[i].StepsSampled = stepsDone;+ _pending[i].AddRange(values);}- this._lastStepsDone = stepsDone;+ _lastStepsDone = stepsDone;}/// <summary>@@ -93,22 +97,22 @@ namespace _2D_wave_sim_V01/// <param name="stepsDone">Steps completed so far; recorded as <see cref="ProbeTrace.StepsSampled"/>.</param>public void CollectProfiles(IWaveEngine engine, int stepsDone){- if (!this._sampler.HasProfiles)+ if (!_sampler.HasProfiles){return;}float[][] profiles = engine.ReadProbeProfiles();- for (int i = 0; i < this._sampler.Count; i++)+ for (int i = 0; i < _sampler.Count; i++){- if (!this._sampler.IsProfile[i] || i >= profiles.Length || profiles[i] == null)+ if (!_sampler.IsProfile[i] || i >= profiles.Length || profiles[i] == null){continue;}- this.Traces[i].SetProfile(profiles[i], this._sampler.Lengths[i]);- this.Traces[i].StepsSampled = stepsDone;- this._fresh[i] = true;+ Traces[i].SetProfile(profiles[i], _sampler.Lengths[i]);+ Traces[i].StepsSampled = stepsDone;+ _fresh[i] = true;}- this._lastStepsDone = stepsDone;+ _lastStepsDone = stepsDone;}/// <summary>@@ -119,20 +123,20 @@ namespace _2D_wave_sim_V01/// <returns>A batch covering everything since the previous call; never null.</returns>public ProbeUpdate TakeForUi(){- int count = this._sampler.Count;- float[][] series = new float[count][];+ int count = _sampler.Count;+ float[][] samples = new float[count][];float[][] profiles = new float[count][];for (int i = 0; i < count; i++){- series[i] = this._pending[i].ToArray();- this._pending[i].Clear();- if (this._fresh[i])+ samples[i] = _pending[i].ToArray();+ _pending[i].Clear();+ if (_fresh[i]){- profiles[i] = this.Traces[i].Profile;- this._fresh[i] = false;+ profiles[i] = Traces[i].Profile;+ _fresh[i] = false;}}- return new ProbeUpdate(series, profiles, this._sampler.Lengths, this._lastStepsDone);+ return new ProbeUpdate(samples, profiles, _sampler.Lengths, _lastStepsDone);}/// <summary>Worker-side trace per probe (index parallel to the sampler). Read by <see cref="ProbeOverlay.Burn"/> when burning graphs into exported frames.</summary>diff --git a/Wave_Dude_2D/ProbeGraphPainter.cs b/Wave_Dude_2D/ProbeGraphPainter.csindex f4f91db..d8ee942 100644--- a/Wave_Dude_2D/ProbeGraphPainter.cs+++ b/Wave_Dude_2D/ProbeGraphPainter.cs@@ -8,7 +8,11 @@ using System.Globalization;namespace _2D_wave_sim_V01{/// <summary>- /// GDI+ rendering of probe graphs (time series / line profiles) and of the probe position markers.+ /// GDI+ rendering of probe graphs (a little box with axes and the measured curve) and of the probe position markers:+ /// <list type="bullet">+ /// <item><description>Point probe: value (Y) against the simulation step (X).</description></item>+ /// <item><description>Line probe: value (Y) against the position on the line A-B in pixels (X), at the current step.</description></item>+ /// </list>/// Stateless: every call draws onto the <see cref="Graphics"/> it is given. Used on the UI thread by the/// main form's paint handlers (painting the form's own copies of the traces onto the picture boxes) and on/// the simulation worker thread by <see cref="ProbeOverlay"/> (painting the collector's traces into an@@ -97,6 +101,9 @@ namespace _2D_wave_sim_V01/// (AutoScaleX) or to the run length. Running mode shows a window of <c>RunningWindow</c> (at least 10)/// steps that slides with the data; with AutoScaleX it starts narrow and grows to full width, otherwise it/// is full width from the start. With AutoScaleY the y range is fitted to the samples inside the x range.+ /// When "start after step" is used, the values from before that step are trimmed off: xMin never goes+ /// below it, so the visible range starts there (with more room for the data that follows, especially with+ /// the full scale, which would otherwise show mostly empty space before the data starts)./// </summary>/// <param name="probe">Settings that select scale mode, running window, fixed y range and auto-scaling.</param>/// <param name="series">Sampled values; null is treated as empty.</param>@@ -135,7 +142,8 @@ namespace _2D_wave_sim_V01}yMin = probe.YMin;yMax = probe.YMax;- if (yMax <= yMin)+ // written this way round so a NaN limit also falls back+ if (!(yMax > yMin)){yMin = -1.0;yMax = 1.0;@@ -193,7 +201,8 @@ namespace _2D_wave_sim_V01xMax = (profileLength > 0.0) ? profileLength : 1.0;yMin = probe.YMin;yMax = probe.YMax;- if (yMax <= yMin)+ // written this way round so a NaN limit also falls back+ if (!(yMax > yMin)){yMin = -1.0;yMax = 1.0;@@ -219,6 +228,7 @@ namespace _2D_wave_sim_V01}if (lo <= hi){+ // an intensity starts at zeroProbeGraphPainter.FitRange(lo, hi, probe.Measurement != ProbeMeasurement.Amplitude && lo >= 0.0, ref yMin, ref yMax);}}@@ -258,7 +268,8 @@ namespace _2D_wave_sim_V01{List<double> ticks = new List<double>();double span = hi - lo;- if (span <= 0.0 || double.IsInfinity(span))+ // written this way round so a NaN span also yields no ticks+ if (!(span > 0.0) || double.IsInfinity(span)){return ticks;}@@ -284,12 +295,12 @@ namespace _2D_wave_sim_V01}step *= magnitude;double tick = Math.Ceiling(lo / step) * step;- int tickCount = 0;- while (tick <= hi + step * 1E-09 && tickCount < 40)+ int guard = 0;+ while (tick <= hi + step * 1E-09 && guard < 40){ticks.Add((Math.Abs(tick) < step * 1E-09) ? 0.0 : tick);tick += step;- tickCount++;+ guard++;}return ticks;}@@ -350,27 +361,34 @@ namespace _2D_wave_sim_V01{return;}+ // a line probe (a profile of the current instant) has nothing meaningful to show before the start step is+ // reached, so it stays blank until then; a point probe (a series) is trimmed instead, see SeriesRangesbool isLine = probe.Kind == ProbeKind.Line;- ProbeTrace gatedTrace = (!probe.UseStartAfterStep || trace == null || trace.StepsSampled >= probe.StartAfterStep) ? trace : null;+ bool started = !probe.UseStartAfterStep || trace == null || trace.StepsSampled >= probe.StartAfterStep;+ ProbeTrace shownTrace = started ? trace : null;+ // a point probe's own range/autoscale must see the real trace (it is trimmed by "start after step" inside+ // ComputeRanges/SeriesRanges, not hidden); only a line probe uses shownTrace, to stay blank until it startsdouble xMin = 0.0;double xMax = 0.0;double yMin = 0.0;double yMax = 0.0;- ProbeGraphPainter.ComputeRanges(probe, isLine ? gatedTrace : trace, totalSteps, ref xMin, ref xMax, ref yMin, ref yMax);+ ProbeGraphPainter.ComputeRanges(probe, isLine ? shownTrace : trace, totalSteps, ref xMin, ref xMax, ref yMin, ref yMax);ProbeGraphPainter.DrawAxes(g, font, fontPx, bounds, plot, xMin, xMax, yMin, yMax);float lineWidth = Math.Max(1.2f, bounds.Height / 110f);if (isLine){- if (gatedTrace != null)+ if (shownTrace != null){- ProbeGraphPainter.DrawProfile(g, plot, gatedTrace.Profile, yMin, yMax, lineWidth);+ ProbeGraphPainter.DrawProfile(g, plot, shownTrace.Profile, yMin, yMax, lineWidth);}}else if (trace != null){+ // a point probe is trimmed (xMin), not hidden: its curve is drawn up to the current value even before+ // the start step is reached (the range is then just very small)ProbeGraphPainter.DrawCurve(g, plot, trace.Series, xMin, xMax, yMin, yMax, lineWidth);}- ProbeGraphPainter.DrawTitle(g, font, bounds, title, ProbeGraphPainter.ValueText(isLine, isLine ? gatedTrace : trace), fontPx);+ ProbeGraphPainter.DrawTitle(g, font, bounds, title, ProbeGraphPainter.ValueText(isLine, isLine ? shownTrace : trace), fontPx);}}finally@@ -450,12 +468,14 @@ namespace _2D_wave_sim_V01yLabelFormat.FormatFlags = StringFormatFlags.NoWrap;xLabelFormat.Alignment = StringAlignment.Center;xLabelFormat.FormatFlags = StringFormatFlags.NoWrap;+ // value axisforeach (double tick in ProbeGraphPainter.NiceTicks(yMin, yMax, 4)){float py = ProbeGraphPainter.ToPixelY(tick, plot, yMin, yMax);g.DrawLine((tick == 0.0) ? zeroPen : gridPen, (float)plot.Left, py, (float)plot.Right, py);g.DrawString(ProbeGraphPainter.FormatTick(tick), font, labelBrush, new RectangleF(bounds.X + 1, py - fontPx * 0.7f, plot.Left - bounds.X - 4, fontPx * 1.4f), yLabelFormat);}+ // step axis (point probe) or position on the line (line probe)foreach (double tick in ProbeGraphPainter.NiceTicks(xMin, xMax, 5)){float px = (float)(plot.Left + (tick - xMin) / (xMax - xMin) * plot.Width);@@ -523,6 +543,7 @@ namespace _2D_wave_sim_V01double xScale = plot.Width / (xMax - xMin);if (visibleCount <= plot.Width * 2){+ // every value gets its own point (value i belongs to step i + 1)for (int i = firstIndex; i <= lastIndex; i++){float value = values[i];@@ -597,8 +618,8 @@ namespace _2D_wave_sim_V01float value = profile[i];if (!float.IsNaN(value) && !float.IsInfinity(value)){- double t = (count > 1) ? (i / (count - 1.0)) : 0.0;- points.Add(new PointF((float)(plot.Left + t * plot.Width), ProbeGraphPainter.ToPixelY(value, plot, yMin, yMax)));+ double fraction = (count > 1) ? (i / (count - 1.0)) : 0.0;+ points.Add(new PointF((float)(plot.Left + fraction * plot.Width), ProbeGraphPainter.ToPixelY(value, plot, yMin, yMax)));}}}@@ -762,6 +783,7 @@ namespace _2D_wave_sim_V01{using (SolidBrush textBrush = new SolidBrush(Color.White)){+ // a line probe has two ends, so each is labelled with the probe number and which end it isif (isLine){ProbeGraphPainter.DrawNumber(g, font, shadowBrush, textBrush, label + "A", ax, ay);@@ -781,13 +803,14 @@ namespace _2D_wave_sim_V01}}- /// <summary>Draws a plus-shaped cross with 7-pixel arms centred on (x, y): the wide dark pen first as outline, then the thin light pen on top.</summary>+ /// <summary>Draws a plus-shaped cross with arm-length arms centred on (x, y): the wide dark pen first as outline, then the thin light pen on top.</summary>private static void DrawCross(Graphics g, Pen dark, Pen light, float x, float y){- g.DrawLine(dark, x - 7f, y, x + 7f, y);- g.DrawLine(dark, x, y - 7f, x, y + 7f);- g.DrawLine(light, x - 7f, y, x + 7f, y);- g.DrawLine(light, x, y - 7f, x, y + 7f);+ const float arm = 7f;+ g.DrawLine(dark, x - arm, y, x + arm, y);+ g.DrawLine(dark, x, y - arm, x, y + arm);+ g.DrawLine(light, x - arm, y, x + arm, y);+ g.DrawLine(light, x, y - arm, x, y + arm);}/// <summary>Draws a marker label above and to the right of (x, y) with a 1-pixel dark drop shadow.</summary>diff --git a/Wave_Dude_2D/ProbeKind.cs b/Wave_Dude_2D/ProbeKind.csindex 55ee133..4ff9b4f 100644--- a/Wave_Dude_2D/ProbeKind.cs+++ b/Wave_Dude_2D/ProbeKind.cs@@ -7,8 +7,8 @@ namespace _2D_wave_sim_V01public enum ProbeKind{/// <summary>Samples the single canvas pixel at position A once per simulation step, producing a time series.</summary>- Point,+ Point = 0,/// <summary>Samples every pixel on the Bresenham line from A to B, producing a profile along the line (no time axis).</summary>- Line+ Line = 1}}diff --git a/Wave_Dude_2D/ProbeMeasurement.cs b/Wave_Dude_2D/ProbeMeasurement.csindex 6358e14..aeabfc7 100644--- a/Wave_Dude_2D/ProbeMeasurement.cs+++ b/Wave_Dude_2D/ProbeMeasurement.cs@@ -2,20 +2,22 @@ namespace _2D_wave_sim_V01{/// <summary>/// The quantity a probe records. Which values are allowed depends on <see cref="ProbePlaceOn"/>- /// (see <see cref="ProbeSettings.Normalize"/>). The engine treats every value above- /// <see cref="Amplitude"/> as "read from the intensity buffer" (<c>ProbeSampler.UseIntensity</c>).+ /// (see <see cref="ProbeSettings.Normalize"/>): amplitude only on the field picture, the two intensity+ /// measurements only on the intensity picture. Every value other than <see cref="Amplitude"/> is read from+ /// the intensity buffer (<c>ProbeSampler.UseIntensity</c>). The numeric value is the index of the+ /// "measurement" combo box on the Probes tab./// </summary>public enum ProbeMeasurement{/// <summary>The instantaneous field value (wave amplitude, signed) at the probe pixel(s).</summary>- Amplitude,+ Amplitude = 0,/// <summary>The current value of the engine's running (exponentially decayed) intensity buffer at the probe pixel(s).</summary>- Intensity,+ Intensity = 1,/// <summary>/// Intensity summed over simulation steps. For a point probe the running sum is formed in/// <c>ProbeCollector</c>; for a line probe the engine keeps per-pixel totals. Accumulation/// starts at <see cref="ProbeSettings.StartAfterStep"/> when that option is enabled./// </summary>- IntegratedIntensity+ IntegratedIntensity = 2}}diff --git a/Wave_Dude_2D/ProbeOverlay.cs b/Wave_Dude_2D/ProbeOverlay.csindex c8c2e12..60cdbfc 100644--- a/Wave_Dude_2D/ProbeOverlay.cs+++ b/Wave_Dude_2D/ProbeOverlay.cs@@ -24,7 +24,8 @@ namespace _2D_wave_sim_V01/// <summary>/// Draws the markers and, where the box is at least 60 x 30 pixels, the graph of every active probe placed- /// on <paramref name="placeOn"/> into <paramref name="pixels"/>. Graphs are rendered by+ /// on <paramref name="placeOn"/> into <paramref name="pixels"/>. The frame is the whole scene, so the box+ /// is where the probe says (in scene pixels). Graphs are rendered by/// <see cref="ProbeGraphPainter.DrawGraph"/> into a temporary premultiplied bitmap and alpha-blended in./// </summary>/// <param name="pixels">Opaque ARGB frame, row-major, index y * w + x; modified in place.</param>@@ -72,28 +73,29 @@ namespace _2D_wave_sim_V01try{int[] row = new int[bmp.Width];- for (int i = 0; i < bmp.Height; i++)+ // (x, y) is a bitmap pixel, (frameX, frameY) the frame pixel it lands on+ for (int y = 0; y < bmp.Height; y++){- int y = rect.Y + i;- if (y < 0 || y >= h)+ int frameY = rect.Y + y;+ if (frameY < 0 || frameY >= h){continue;}- Marshal.Copy(IntPtr.Add(data.Scan0, i * data.Stride), row, 0, bmp.Width);- for (int j = 0; j < bmp.Width; j++)+ Marshal.Copy(IntPtr.Add(data.Scan0, y * data.Stride), row, 0, bmp.Width);+ for (int x = 0; x < bmp.Width; x++){- int x = rect.X + j;- if (x < 0 || x >= w)+ int frameX = rect.X + x;+ if (frameX < 0 || frameX >= w){continue;}- int src = row[j];+ int src = row[x];int alpha = (src >> 24) & 255;if (alpha == 0){continue;}- int index = y * w + x;+ int index = frameY * w + frameX;if (alpha == 255){pixels[index] = src | unchecked((int)0xFF000000);@@ -131,6 +133,7 @@ namespace _2D_wave_sim_V01{int arm = Math.Max(6, h / 120);bool isLine = probe.Kind == ProbeKind.Line;+ // black underneath, white on topfor (int pass = 0; pass <= 1; pass++){int color = (pass == 0) ? unchecked((int)0xFF000000) : unchecked((int)0xFFFFFFFF);@@ -145,6 +148,7 @@ namespace _2D_wave_sim_V01ProbeOverlay.DrawCrossPixels(pixels, w, h, probe.PosBX, probe.PosBY, arm, color, radius);}}+ // the number of the probe next to the cross; a line probe's two ends are labelled with which end they arestring label = (index + 1).ToString(CultureInfo.InvariantCulture);float fontPx = Math.Max(12f, h / 60f);if (isLine)@@ -233,7 +237,7 @@ namespace _2D_wave_sim_V01int stepX = (x0 < x1) ? 1 : -1;int stepY = (y0 < y1) ? 1 : -1;int error = dx + dy;- int iterations = 0;+ int guard = 0;while (true){for (int oy = -radius; oy <= radius; oy++)@@ -248,11 +252,11 @@ namespace _2D_wave_sim_V01}}}- if ((x0 == x1 && y0 == y1) || iterations > 100000)+ if ((x0 == x1 && y0 == y1) || guard > 100000){break;}- iterations++;+ guard++;int error2 = 2 * error;if (error2 >= dy){diff --git a/Wave_Dude_2D/ProbePlaceOn.cs b/Wave_Dude_2D/ProbePlaceOn.csindex 1b6c810..41af884 100644--- a/Wave_Dude_2D/ProbePlaceOn.cs+++ b/Wave_Dude_2D/ProbePlaceOn.cs@@ -8,8 +8,8 @@ namespace _2D_wave_sim_V01public enum ProbePlaceOn{/// <summary>The wave field (amplitude) output. Only <see cref="ProbeMeasurement.Amplitude"/> is valid here.</summary>- Field,+ Field = 0,/// <summary>The intensity output. Allows <see cref="ProbeMeasurement.Intensity"/> and <see cref="ProbeMeasurement.IntegratedIntensity"/>.</summary>- Intensity+ Intensity = 1}}diff --git a/Wave_Dude_2D/ProbeSampler.cs b/Wave_Dude_2D/ProbeSampler.csindex 9479e42..d0e43d8 100644--- a/Wave_Dude_2D/ProbeSampler.cs+++ b/Wave_Dude_2D/ProbeSampler.cs@@ -4,9 +4,16 @@ using System.Collections.Generic;namespace _2D_wave_sim_V01{/// <summary>- /// Precomputed per-probe pixel indices (into the padded field grid, see <see cref="IWaveEngine"/>) and- /// sampling flags. Built once per run by <see cref="Build"/> on the simulation worker thread from the run's- /// probe list and canvas size, then handed to the engine (<see cref="IWaveEngine.SetProbes"/>) and to the+ /// What a simulation engine has to measure for the probes: precomputed per-probe pixel indices (into the+ /// padded field grid, see <see cref="IWaveEngine"/>) and what is read there, the field or the intensity.+ /// <list type="bullet">+ /// <item><description>Point probe: one pixel; the engine measures its value at every step (a series).</description></item>+ /// <item><description>Point, integrated: the same, but the values are added up over time (done by <see cref="ProbeCollector"/>).</description></item>+ /// <item><description>Line probe: the pixels on the line A-B; the engine gives the values along the line when asked (a profile).</description></item>+ /// <item><description>Line, integrated: the engine adds the intensity of every pixel of the line up over the steps.</description></item>+ /// </list>+ /// Built once per run by <see cref="Build"/> on the simulation worker thread from the run's probe list and+ /// canvas size, then handed to the engine (<see cref="IWaveEngine.SetProbes"/>) and to the/// <see cref="ProbeCollector"/>. All per-probe arrays are indexed by the probe's position in that list./// Immutable after construction, so it may be read from any thread./// </summary>@@ -15,28 +22,28 @@ namespace _2D_wave_sim_V01/// <summary>Stores the per-probe arrays and derives the aggregate <see cref="NeedsIntensity"/>, <see cref="HasSeries"/> and <see cref="HasProfiles"/> flags.</summary>private ProbeSampler(int[][] pixels, bool[] isProfile, bool[] useIntensity, bool[] cumulative, bool[] integrate, double[] lengths, bool[] useStartAfterStep, int[] startAfterStep){- this.Count = pixels.Length;- this.Pixels = pixels;- this.IsProfile = isProfile;- this.UseIntensity = useIntensity;- this.Cumulative = cumulative;- this.Integrate = integrate;- this.Lengths = lengths;- this.UseStartAfterStep = useStartAfterStep;- this.StartAfterStep = startAfterStep;- for (int i = 0; i < this.Count; i++)+ Count = pixels.Length;+ Pixels = pixels;+ IsProfile = isProfile;+ UseIntensity = useIntensity;+ Cumulative = cumulative;+ Integrate = integrate;+ Lengths = lengths;+ UseStartAfterStep = useStartAfterStep;+ StartAfterStep = startAfterStep;+ for (int i = 0; i < Count; i++){if (useIntensity[i]){- this.NeedsIntensity = true;+ NeedsIntensity = true;}if (isProfile[i]){- this.HasProfiles = true;+ HasProfiles = true;}else{- this.HasSeries = true;+ HasSeries = true;}}}@@ -84,7 +91,7 @@ namespace _2D_wave_sim_V01cumulative[i] = isIntegrated;}// Intensity and IntegratedIntensity both read the intensity buffer.- useIntensity[i] = probe.Measurement > ProbeMeasurement.Amplitude;+ useIntensity[i] = probe.Measurement != ProbeMeasurement.Amplitude;useStartAfterStep[i] = probe.UseStartAfterStep;startAfterStep[i] = probe.StartAfterStep;}@@ -150,7 +157,7 @@ namespace _2D_wave_sim_V01/// <returns>The value at the probe's first pixel, or 0 when <paramref name="data"/> is null.</returns>public float Compute(int probeIndex, float[] data){- return (data == null) ? 0f : data[this.Pixels[probeIndex][0]];+ return (data == null) ? 0f : data[Pixels[probeIndex][0]];}/// <summary>Number of probes; the length of every per-probe array.</summary>@@ -183,10 +190,16 @@ namespace _2D_wave_sim_V01/// <summary>True when at least one line probe exists.</summary>public readonly bool HasProfiles;- /// <summary>Per probe: whether integrated measurements only start counting at <see cref="StartAfterStep"/>.</summary>+ /// <summary>+ /// Per probe: whether "start recording at step #" is on. Used to purge (never accumulate) the running+ /// total of an integrated (cumulative) probe from before <see cref="StartAfterStep"/>, so the total shown+ /// once recording starts is not inflated by intensity that arrived before it - see+ /// <see cref="ProbeCollector.Collect"/>, <see cref="WaveSimulator.SampleProbes"/> and+ /// <see cref="GpuWaveSimulator"/>'s <c>profile_accumulate</c> kernel.+ /// </summary>public readonly bool[] UseStartAfterStep;- /// <summary>Per probe: step number before which integrated measurements are ignored; only meaningful when <see cref="UseStartAfterStep"/> is set.</summary>+ /// <summary>Per probe: the step at which recording starts (the total before it is purged); only meaningful when <see cref="UseStartAfterStep"/> is set.</summary>public readonly int[] StartAfterStep;}}diff --git a/Wave_Dude_2D/ProbeScaleMode.cs b/Wave_Dude_2D/ProbeScaleMode.csindex 0e9533b..68e4f65 100644--- a/Wave_Dude_2D/ProbeScaleMode.cs+++ b/Wave_Dude_2D/ProbeScaleMode.cs@@ -8,8 +8,8 @@ namespace _2D_wave_sim_V01public enum ProbeScaleMode{/// <summary>Shows a sliding window of the last <see cref="ProbeSettings.RunningWindow"/> steps.</summary>- Running,+ Running = 0,/// <summary>Shows the whole run: from the start step to the total step count (or to the samples so far when <see cref="ProbeSettings.AutoScaleX"/> is set).</summary>- Full+ Full = 1}}diff --git a/Wave_Dude_2D/ProbeSeries.cs b/Wave_Dude_2D/ProbeSeries.csindex 75dcfa3..19ed392 100644--- a/Wave_Dude_2D/ProbeSeries.cs+++ b/Wave_Dude_2D/ProbeSeries.cs@@ -3,45 +3,28 @@ using System;namespace _2D_wave_sim_V01{/// <summary>- /// Growable buffer of sampled probe values, one per simulation step, in step order. Not thread-safe: each- /// instance belongs to one <see cref="ProbeTrace"/> and is only touched by that trace's owning thread.+ /// The measured values of one point probe: a growable buffer with one value per simulation step, in step+ /// order (value i belongs to step i + 1). Not thread-safe: each instance belongs to one+ /// <see cref="ProbeTrace"/> and is only touched by that trace's owning thread./// </summary>internal sealed class ProbeSeries{public ProbeSeries(){- this._values = new float[1024];+ _values = new float[1024];}/// <summary>Number of valid values; only the first <see cref="Count"/> entries of <see cref="Values"/> are meaningful.</summary>- public int Count- {- get- {- return this._count;- }- }+ public int Count => _count;/// <summary>/// Backing array, exposed without copying. Its length is the capacity, not the sample count, so read only- /// indices below <see cref="Count"/>. The reference changes whenever the buffer grows.+ /// indices below <see cref="Count"/>. The reference changes whenever the buffer grows. Do not change./// </summary>- public float[] Values- {- get- {- return this._values;- }- }+ public float[] Values => _values;/// <summary>Most recently added value, or NaN when the series is empty.</summary>- public float LastValue- {- get- {- return this._count == 0 ? float.NaN : this._values[this._count - 1];- }- }+ public float LastValue => _count == 0 ? float.NaN : _values[_count - 1];/// <summary>Appends values in step order, at least doubling the backing array when it is full. Null or empty input is ignored.</summary>public void Add(float[] items)@@ -50,21 +33,21 @@ namespace _2D_wave_sim_V01{return;}- int newCount = this._count + items.Length;- if (newCount > this._values.Length)+ int newCount = _count + items.Length;+ if (newCount > _values.Length){- float[] grown = new float[Math.Max(newCount, this._values.Length * 2)];- Array.Copy(this._values, grown, this._count);- this._values = grown;+ float[] grown = new float[Math.Max(newCount, _values.Length * 2)];+ Array.Copy(_values, grown, _count);+ _values = grown;}- Array.Copy(items, 0, this._values, this._count, items.Length);- this._count = newCount;+ Array.Copy(items, 0, _values, _count, items.Length);+ _count = newCount;}/// <summary>Discards all values but keeps the allocated storage.</summary>public void Clear(){- this._count = 0;+ _count = 0;}/// <summary>Backing storage; starts at 1024 entries, grows by at least doubling and never shrinks.</summary>diff --git a/Wave_Dude_2D/ProbeSettings.cs b/Wave_Dude_2D/ProbeSettings.csindex 8ef053f..20cd378 100644--- a/Wave_Dude_2D/ProbeSettings.cs+++ b/Wave_Dude_2D/ProbeSettings.cs@@ -17,25 +17,25 @@ namespace _2D_wave_sim_V01/// <summary>Creates an inactive point probe on the field at (100,100) with a medium graph box at (450,20) and auto scaling on both axes.</summary>public ProbeSettings(){- this.PlaceOn = ProbePlaceOn.Field;- this.Measurement = ProbeMeasurement.Amplitude;- this.Kind = ProbeKind.Point;- this.PosAX = 100;- this.PosAY = 100;- this.PosBX = 300;- this.PosBY = 100;- this.BoxSize = ProbeBoxSize.Medium;- this.BoxX = 450;- this.BoxY = 20;- this.Active = false;- this.ScaleMode = ProbeScaleMode.Running;- this.AutoScaleX = true;- this.AutoScaleY = true;- this.YMin = -1.0;- this.YMax = 1.0;- this.RunningWindow = ProbeSettings.DefaultRunningWindow;- this.UseStartAfterStep = false;- this.StartAfterStep = 0;+ PlaceOn = ProbePlaceOn.Field;+ Measurement = ProbeMeasurement.Amplitude;+ Kind = ProbeKind.Point;+ PosAX = 100;+ PosAY = 100;+ PosBX = 300;+ PosBY = 100;+ BoxSize = ProbeBoxSize.Medium;+ BoxX = 450;+ BoxY = 20;+ Active = false;+ ScaleMode = ProbeScaleMode.Running;+ AutoScaleX = true;+ AutoScaleY = true;+ YMin = -1.0;+ YMax = 1.0;+ RunningWindow = ProbeSettings.DefaultRunningWindow;+ UseStartAfterStep = false;+ StartAfterStep = 0;}/// <summary>Gets or sets the output (field or intensity) the probe samples and is drawn on.</summary>@@ -68,7 +68,14 @@ namespace _2D_wave_sim_V01/// <summary>Gets or sets the top edge of the graph box in canvas pixels (clamped by the painter like <see cref="BoxX"/>).</summary>public int BoxY { get; set; }- /// <summary>Gets or sets whether the probe is sampled and drawn at all.</summary>+ /// <summary>+ /// Gets or sets whether the probe is switched on: when false it is not sampled or shown in a simulation,+ /// but its settings are kept ("On" checkbox). Off by default (the constructor's default, used for both+ /// probes of a new project - see <c>NewProbeList</c> in <c>Form1.Probes.cs</c>). A probe loaded from a+ /// project saved before <c>active</c> was written for it still comes back on (<see cref="FromDictionary"/>'s+ /// own separate, hard-coded fallback), so that project keeps its exact previous behaviour instead of+ /// silently picking up the new-project default.+ /// </summary>public bool Active { get; set; }/// <summary>Gets or sets how the step axis of a point probe's time series is chosen; ignored for line probes.</summary>@@ -89,10 +96,15 @@ namespace _2D_wave_sim_V01/// <summary>Gets or sets the width of the sliding step window for <see cref="ProbeScaleMode.Running"/>, in simulation steps (10 .. <see cref="MaxRunningWindow"/>).</summary>public int RunningWindow { get; set; }- /// <summary>Gets or sets whether sampling/accumulation and the graph are gated until <see cref="StartAfterStep"/> is reached.</summary>+ /// <summary>+ /// Gets or sets whether the graph shows no data from before step <see cref="StartAfterStep"/> (0 = from the+ /// start). Sampling itself is not gated: the probe keeps being sampled, a point probe's graph is trimmed to+ /// start there and a line probe's stays blank until then (see <see cref="ProbeGraphPainter.DrawGraph"/>),+ /// and the running total of an integrated probe is kept at zero before it (<see cref="ProbeCollector.Collect"/>).+ /// </summary>public bool UseStartAfterStep { get; set; }- /// <summary>Gets or sets the simulation step (0-based, never negative) at which recording starts when <see cref="UseStartAfterStep"/> is set.</summary>+ /// <summary>Gets or sets the simulation step (0-based, never negative) at which recording starts when <see cref="UseStartAfterStep"/> is set (0 = from the start).</summary>public int StartAfterStep { get; set; }/// <summary>Returns an independent copy. All members are value types, so the memberwise clone is a full copy.</summary>@@ -109,60 +121,61 @@ namespace _2D_wave_sim_V01/// </summary>public void CopyDisplayFrom(ProbeSettings other){- this.Active = other.Active;- this.BoxSize = other.BoxSize;- this.BoxX = other.BoxX;- this.BoxY = other.BoxY;- this.ScaleMode = other.ScaleMode;- this.AutoScaleX = other.AutoScaleX;- this.AutoScaleY = other.AutoScaleY;- this.YMin = other.YMin;- this.YMax = other.YMax;- this.RunningWindow = other.RunningWindow;- this.UseStartAfterStep = other.UseStartAfterStep;- this.StartAfterStep = other.StartAfterStep;+ Active = other.Active;+ BoxSize = other.BoxSize;+ BoxX = other.BoxX;+ BoxY = other.BoxY;+ ScaleMode = other.ScaleMode;+ AutoScaleX = other.AutoScaleX;+ AutoScaleY = other.AutoScaleY;+ YMin = other.YMin;+ YMax = other.YMax;+ RunningWindow = other.RunningWindow;+ UseStartAfterStep = other.UseStartAfterStep;+ StartAfterStep = other.StartAfterStep;}/// <summary>/// Forces the settings into a consistent state: the field only allows/// <see cref="ProbeMeasurement.Amplitude"/>, the intensity output never does (amplitude is- /// turned into <see cref="ProbeMeasurement.Intensity"/>); an empty or inverted Y range becomes+ /// turned into <see cref="ProbeMeasurement.Intensity"/>); an empty, inverted or NaN Y range becomes/// -1..1; <see cref="RunningWindow"/> is clamped to 10..<see cref="MaxRunningWindow"/> and/// <see cref="StartAfterStep"/> to zero or more./// </summary>public void Normalize(){- if (this.PlaceOn == ProbePlaceOn.Field)+ if (PlaceOn == ProbePlaceOn.Field){- this.Measurement = ProbeMeasurement.Amplitude;+ Measurement = ProbeMeasurement.Amplitude;}- else if (this.Measurement == ProbeMeasurement.Amplitude)+ else if (Measurement == ProbeMeasurement.Amplitude){- this.Measurement = ProbeMeasurement.Intensity;+ Measurement = ProbeMeasurement.Intensity;}- if (this.YMax <= this.YMin)+ // written this way round so a NaN limit also falls back+ if (!(YMax > YMin)){- this.YMin = -1.0;- this.YMax = 1.0;+ YMin = -1.0;+ YMax = 1.0;}- if (this.RunningWindow < 10)+ if (RunningWindow < 10){- this.RunningWindow = 10;+ RunningWindow = 10;}- if (this.RunningWindow > ProbeSettings.MaxRunningWindow)+ if (RunningWindow > ProbeSettings.MaxRunningWindow){- this.RunningWindow = ProbeSettings.MaxRunningWindow;+ RunningWindow = ProbeSettings.MaxRunningWindow;}- if (this.StartAfterStep < 0)+ if (StartAfterStep < 0){- this.StartAfterStep = 0;+ StartAfterStep = 0;}}/// <summary>The UI label of <see cref="Measurement"/> ("Amplitude", "Intensity" or "Integrated intensity").</summary>public string MeasurementText(){- switch (this.Measurement)+ switch (Measurement){case ProbeMeasurement.Amplitude:return "Amplitude";@@ -173,11 +186,11 @@ namespace _2D_wave_sim_V01}}- /// <summary>Title shown in the graph box, e.g. "Probe 1 - Amplitude".</summary>+ /// <summary>Title shown in the graph box, e.g. "Probe 1 - Amplitude". The number is also drawn at the probe in the picture.</summary>/// <param name="index">0-based probe index; the title shows it 1-based.</param>public string Title(int index){- return "Probe " + (index + 1).ToString(CultureInfo.InvariantCulture) + " - " + this.MeasurementText();+ return "Probe " + (index + 1).ToString(CultureInfo.InvariantCulture) + " - " + MeasurementText();}/// <summary>@@ -238,9 +251,9 @@ namespace _2D_wave_sim_V01private Dictionary<string, object> ToDictionary(){Dictionary<string, object> values = new Dictionary<string, object>();- values["active"] = this.Active;- values["place_on"] = ((this.PlaceOn == ProbePlaceOn.Field) ? "field" : "intensity");- switch (this.Measurement)+ values["active"] = Active;+ values["place_on"] = ((PlaceOn == ProbePlaceOn.Field) ? "field" : "intensity");+ switch (Measurement){case ProbeMeasurement.Amplitude:values["measurement"] = "amplitude";@@ -252,12 +265,12 @@ namespace _2D_wave_sim_V01values["measurement"] = "intensity";break;}- values["probe_type"] = ((this.Kind == ProbeKind.Line) ? "line" : "point");- values["ax"] = this.PosAX;- values["ay"] = this.PosAY;- values["bx"] = this.PosBX;- values["by"] = this.PosBY;- switch (this.BoxSize)+ values["probe_type"] = ((Kind == ProbeKind.Line) ? "line" : "point");+ values["ax"] = PosAX;+ values["ay"] = PosAY;+ values["bx"] = PosBX;+ values["by"] = PosBY;+ switch (BoxSize){case ProbeBoxSize.Tiny:values["box_size"] = "tiny";@@ -275,16 +288,16 @@ namespace _2D_wave_sim_V01values["box_size"] = "medium";break;}- values["box_x"] = this.BoxX;- values["box_y"] = this.BoxY;- values["scale_mode"] = ((this.ScaleMode == ProbeScaleMode.Full) ? "full" : "running");- values["auto_scale_x"] = this.AutoScaleX;- values["auto_scale_y"] = this.AutoScaleY;- values["y_min"] = this.YMin;- values["y_max"] = this.YMax;- values["running_window"] = this.RunningWindow;- values["use_start_after_step"] = this.UseStartAfterStep;- values["start_after_step"] = this.StartAfterStep;+ values["box_x"] = BoxX;+ values["box_y"] = BoxY;+ values["scale_mode"] = ((ScaleMode == ProbeScaleMode.Full) ? "full" : "running");+ values["auto_scale_x"] = AutoScaleX;+ values["auto_scale_y"] = AutoScaleY;+ values["y_min"] = YMin;+ values["y_max"] = YMax;+ values["running_window"] = RunningWindow;+ values["use_start_after_step"] = UseStartAfterStep;+ values["start_after_step"] = StartAfterStep;return values;}@@ -385,6 +398,7 @@ namespace _2D_wave_sim_V01}catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException){+ // use the fallback}}return fallback;@@ -406,6 +420,7 @@ namespace _2D_wave_sim_V01}catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException){+ // use the fallback}}return fallback;diff --git a/Wave_Dude_2D/ProbeTrace.cs b/Wave_Dude_2D/ProbeTrace.csindex 060d072..26524d7 100644--- a/Wave_Dude_2D/ProbeTrace.cs+++ b/Wave_Dude_2D/ProbeTrace.cs@@ -11,37 +11,25 @@ namespace _2D_wave_sim_V01{public ProbeTrace(){- this.Series = new ProbeSeries();+ Series = new ProbeSeries();}/// <summary>Number of simulation steps completed when this trace was last updated; used to gate "start after step" line probes in the painter.</summary>public int StepsSampled { get; set; }/// <summary>Latest line-probe profile (one value per pixel along the line, A to B), or null until the first profile arrives and always for point probes.</summary>- public float[] Profile- {- get- {- return this._profile;- }- }+ public float[] Profile => _profile;/// <summary>Length of the probe line in canvas pixels (distance A to B); 0 for point probes. Used as the x-axis span of the profile graph.</summary>- public double ProfileLength- {- get- {- return this._profileLength;- }- }+ public double ProfileLength => _profileLength;/// <summary>Replaces the current profile. The array is kept by reference, not copied, so callers must not modify it afterwards.</summary>/// <param name="values">Sampled values along the line, A to B.</param>/// <param name="length">Line length in canvas pixels.</param>public void SetProfile(float[] values, double length){- this._profile = values;- this._profileLength = length;+ _profile = values;+ _profileLength = length;}/// <summary>Latest profile array; null until <see cref="SetProfile"/> is first called.</summary>diff --git a/Wave_Dude_2D/ProbeUpdate.cs b/Wave_Dude_2D/ProbeUpdate.csindex ddcd556..a12cbb1 100644--- a/Wave_Dude_2D/ProbeUpdate.cs+++ b/Wave_Dude_2D/ProbeUpdate.cs@@ -10,10 +10,10 @@ namespace _2D_wave_sim_V01{public ProbeUpdate(float[][] samples, float[][] profiles, double[] lengths, int stepsDone){- this.Samples = samples;- this.Profiles = profiles;- this.Lengths = lengths;- this.StepsDone = stepsDone;+ Samples = samples;+ Profiles = profiles;+ Lengths = lengths;+ StepsDone = stepsDone;}/// <summary>diff --git a/Wave_Dude_2D/Project.cs b/Wave_Dude_2D/Project.csindex 9707687..bbc1ed2 100644--- a/Wave_Dude_2D/Project.cs+++ b/Wave_Dude_2D/Project.cs@@ -21,91 +21,42 @@ namespace _2D_wave_sim_V01/// <param name="config">The configuration loaded from, or to be written to, that folder.</param>internal Project(string folderPath, ProjectConfig config){- this._folderPath = folderPath;- this._config = config;- this._config.ProjectName = this.Name;+ _folderPath = folderPath;+ _config = config;+ // the folder name is the one and only project name+ _config.ProjectName = Name;}/// <summary>Project name, i.e. the name of the project folder.</summary>- public string Name- {- get- {- return Path.GetFileName(this._folderPath);- }- }+ public string Name => Path.GetFileName(_folderPath);/// <summary>Full path of the project folder.</summary>- public string FolderPath- {- get- {- return this._folderPath;- }- }+ public string FolderPath => _folderPath;/// <summary>Parent of the project folder (the project root), or an empty string when the folder has no parent.</summary>- public string RootFolder- {- get- {- return Path.GetDirectoryName(this._folderPath) ?? "";- }- }+ public string RootFolder => Path.GetDirectoryName(_folderPath) ?? "";/// <summary>The configuration loaded from (or to be written to) <see cref="ConfigFilePath"/>; mutable, shared with the editor.</summary>- public ProjectConfig Config- {- get- {- return this._config;- }- }+ public ProjectConfig Config => _config;- /// <summary>Full path of the <c>configuration.json</c> file inside the project folder.</summary>- public string ConfigFilePath- {- get- {- return Path.Combine(this._folderPath, "configuration.json");- }- }+ /// <summary>Full path of the configuration file (<see cref="ProjectConfig.FileName"/>) inside the project folder.</summary>+ public string ConfigFilePath => Path.Combine(_folderPath, ProjectConfig.FileName);- /// <summary>The <c>assets</c> sub-folder (user files kept with the project).</summary>- public string AssetsFolder- {- get- {- return Path.Combine(this._folderPath, "assets");- }- }+ /// <summary>+ /// The <see cref="ProjectStore.AssetsFolderName"/> sub-folder: where the user can keep any third-party+ /// files used by the project (e.g. the original Photoshop file of a scene image). Not read or written by+ /// the simulator itself.+ /// </summary>+ public string AssetsFolder => Path.Combine(_folderPath, ProjectStore.AssetsFolderName);- /// <summary>The <c>output_frames</c> sub-folder where exported PNG frames are written.</summary>- public string OutputFramesFolder- {- get- {- return Path.Combine(this._folderPath, "output_frames");- }- }+ /// <summary>The <see cref="ProjectStore.OutputFramesFolderName"/> sub-folder where exported PNG frames are written.</summary>+ public string OutputFramesFolder => Path.Combine(_folderPath, ProjectStore.OutputFramesFolderName);- /// <summary>The <c>output_video</c> sub-folder where exported videos are written.</summary>- public string OutputVideoFolder- {- get- {- return Path.Combine(this._folderPath, "output_video");- }- }+ /// <summary>The <see cref="ProjectStore.OutputVideoFolderName"/> sub-folder where exported videos are written.</summary>+ public string OutputVideoFolder => Path.Combine(_folderPath, ProjectStore.OutputVideoFolderName);- /// <summary>The <c>scene_images</c> sub-folder into which scene images chosen from elsewhere are copied.</summary>- public string SceneImageFolder- {- get- {- return Path.Combine(this._folderPath, "scene_images");- }- }+ /// <summary>The <see cref="ProjectStore.SceneImageFolderName"/> sub-folder into which scene images chosen from elsewhere are copied.</summary>+ public string SceneImageFolder => Path.Combine(_folderPath, ProjectStore.SceneImageFolderName);/// <summary>/// Re-stamps the project name and writes <see cref="Config"/> to <see cref="ConfigFilePath"/>@@ -113,8 +64,8 @@ namespace _2D_wave_sim_V01/// </summary>public void Save(){- this._config.ProjectName = this.Name;- this._config.Save(this.ConfigFilePath);+ _config.ProjectName = Name;+ _config.Save(ConfigFilePath);}/// <summary>Full path of the project folder; its last segment is the project name.</summary>diff --git a/Wave_Dude_2D/ProjectConfig.cs b/Wave_Dude_2D/ProjectConfig.csindex 29be3c5..5552dfc 100644--- a/Wave_Dude_2D/ProjectConfig.cs+++ b/Wave_Dude_2D/ProjectConfig.cs@@ -10,10 +10,19 @@ namespace _2D_wave_sim_V01{/// <summary>/// The contents of a project's configuration.json: a flat dictionary of top-level values- /// (format version, project name, created/modified timestamps, description) plus named+ /// (format version, project name, created/modified timestamps, description; always present) plus named/// sub-dictionaries ("sections") that <see cref="SceneSettings"/>, <see cref="SimulationSettings"/>,/// <see cref="ProbeSettings"/> and <see cref="SourceSettings"/> read and write through- /// <see cref="GetSection"/>. Owned by a <see cref="Project"/>; created by <see cref="ProjectStore"/>.+ /// <see cref="GetSection"/>. Every tab that gets functionality later stores its own settings as a section+ /// the same way, for example:+ /// <code>+ /// var section = project.Config.GetSection("probes");+ /// section["count"] = 3;+ /// project.Save();+ /// </code>+ /// Forward compatibility: keys that this version of the program does not know are kept and written back+ /// unchanged, so a file written by a newer version is not damaged by an older one (it is refused when its+ /// format_version is newer). Owned by a <see cref="Project"/>; created by <see cref="ProjectStore"/>./// Reading uses <see cref="JavaScriptSerializer"/>; writing is done by hand so the file stays/// stable, indented and human-readable. Values are stored as the serializer produces them/// (string, int, long, decimal, double, bool, nested dictionaries and object arrays), so the@@ -25,87 +34,57 @@ namespace _2D_wave_sim_V01public ProjectConfig(string projectName){string now = ProjectConfig.Timestamp(DateTime.UtcNow);- this._values = new Dictionary<string, object>();- this._values[KeyFormatVersion] = CurrentFormatVersion;- this._values[KeyProjectName] = projectName;- this._values[KeyCreated] = now;- this._values[KeyModified] = now;+ _values = new Dictionary<string, object>();+ _values[KeyFormatVersion] = CurrentFormatVersion;+ _values[KeyProjectName] = projectName;+ _values[KeyCreated] = now;+ _values[KeyModified] = now;}/// <summary>Wraps a deserialised dictionary (used by <see cref="Load"/>); adds the format version if the file had none.</summary>private ProjectConfig(Dictionary<string, object> values){- this._values = values;- if (!this._values.ContainsKey(KeyFormatVersion))+ _values = values;+ if (!_values.ContainsKey(KeyFormatVersion)){- this._values[KeyFormatVersion] = CurrentFormatVersion;+ _values[KeyFormatVersion] = CurrentFormatVersion;}}/// <summary>Format version stored in the file; <see cref="CurrentFormatVersion"/> when missing or unreadable.</summary>- public int FormatVersion- {- get- {- return this.GetInteger(KeyFormatVersion, CurrentFormatVersion);- }- }+ public int FormatVersion => GetInteger(KeyFormatVersion, CurrentFormatVersion);/// <summary>Gets or sets the project name ("" when missing). <see cref="Project.Save"/> overwrites it with the folder name before saving.</summary>public string ProjectName{- get- {- return this.GetString(KeyProjectName, "");- }- set- {- this._values[KeyProjectName] = value;- }+ get => GetString(KeyProjectName, "");+ set => _values[KeyProjectName] = value;}/// <summary>UTC creation timestamp as "yyyy-MM-ddTHH:mm:ssZ", or "" when missing.</summary>- public string Created- {- get- {- return this.GetString(KeyCreated, "");- }- }+ public string Created => GetString(KeyCreated, "");/// <summary>UTC timestamp of the last <see cref="Save"/> as "yyyy-MM-ddTHH:mm:ssZ", or "" when missing.</summary>- public string Modified- {- get- {- return this.GetString(KeyModified, "");- }- }+ public string Modified => GetString(KeyModified, "");- /// <summary>Gets or sets the free-text project description ("" when missing).</summary>+ /// <summary>Gets or sets the free-text project description (Form1's <c>btnDescription</c> / <see cref="frmDescription"/>); "" when none was set.</summary>public string Description{- get- {- return this.GetString(KeyDescription, "");- }- set- {- this._values[KeyDescription] = value;- }+ get => GetString(KeyDescription, "");+ set => _values[KeyDescription] = value;}/// <summary>True when a top-level value or section named <paramref name="key"/> exists (even if its value is null).</summary>public bool ContainsKey(string key){- return this._values.ContainsKey(key);+ return _values.ContainsKey(key);}/// <summary>Top-level value <paramref name="key"/> converted to a string with the invariant culture, or <paramref name="fallback"/> when missing or null.</summary>public string GetString(string key, string fallback){object value;- if (this._values.TryGetValue(key, out value) && value != null)+ if (_values.TryGetValue(key, out value) && value != null){return Convert.ToString(value, CultureInfo.InvariantCulture);}@@ -116,7 +95,7 @@ namespace _2D_wave_sim_V01public int GetInteger(string key, int fallback){object value;- if (this._values.TryGetValue(key, out value) && value != null)+ if (_values.TryGetValue(key, out value) && value != null){try{@@ -130,10 +109,10 @@ namespace _2D_wave_sim_V01return fallback;}- /// <summary>Sets (or replaces) the top-level value <paramref name="key"/>; a dictionary value becomes a section.</summary>+ /// <summary>Sets (or replaces) the top-level value <paramref name="key"/>; a dictionary value becomes a section. Allowed values: string, bool, numbers, null, a <c>Dictionary<string, object></c>, or a list or array of these.</summary>public void SetValue(string key, object value){- this._values[key] = value;+ _values[key] = value;}/// <summary>@@ -143,7 +122,7 @@ namespace _2D_wave_sim_V01public Dictionary<string, object> GetSection(string name){object existing;- if (this._values.TryGetValue(name, out existing))+ if (_values.TryGetValue(name, out existing)){Dictionary<string, object> section = existing as Dictionary<string, object>;if (section != null)@@ -152,7 +131,7 @@ namespace _2D_wave_sim_V01}}Dictionary<string, object> created = new Dictionary<string, object>();- this._values[name] = created;+ _values[name] = created;return created;}@@ -192,16 +171,17 @@ namespace _2D_wave_sim_V01/// </summary>public void Save(string filePath){- this._values[KeyFormatVersion] = CurrentFormatVersion;- this._values[KeyModified] = ProjectConfig.Timestamp(DateTime.UtcNow);+ _values[KeyFormatVersion] = CurrentFormatVersion;+ _values[KeyModified] = ProjectConfig.Timestamp(DateTime.UtcNow);StringBuilder sb = new StringBuilder();- ProjectConfig.WriteObject(sb, this._values, 0);+ ProjectConfig.WriteObject(sb, _values, 0);sb.AppendLine();string directory = Path.GetDirectoryName(filePath);if (!string.IsNullOrEmpty(directory)){Directory.CreateDirectory(directory);}+ // write to a temporary file first so a failed save never leaves a half-written configuration behindstring tempPath = filePath + ".tmp";File.WriteAllText(tempPath, sb.ToString(), new UTF8Encoding(false));if (File.Exists(filePath))@@ -433,7 +413,7 @@ namespace _2D_wave_sim_V01/// <summary>File name of the pre-JSON configuration; an empty one marks a legacy project folder that <see cref="ProjectStore.Open"/> upgrades.</summary>public const string LegacyFileName = "Configuration.txt";- /// <summary>Format version this build writes; files with a higher version are refused by <see cref="Load"/>.</summary>+ /// <summary>Version of the file layout that this build writes; files with a higher version are refused by <see cref="Load"/>. Increase it when a change makes old files incompatible.</summary>public const int CurrentFormatVersion = 1;/// <summary>JSON key of the format version (int).</summary>@@ -451,7 +431,7 @@ namespace _2D_wave_sim_V01/// <summary>JSON key of the description (string).</summary>private const string KeyDescription = "description";- /// <summary>The top-level JSON object: scalar values and section dictionaries keyed by name. Never null; shared by reference with the sections handed out by <see cref="GetSection"/>.</summary>+ /// <summary>The top-level JSON object: scalar values and section dictionaries keyed by name. Never null; shared by reference with the sections handed out by <see cref="GetSection"/>. Insertion ordered in practice, so the file keeps a stable, readable order.</summary>private readonly Dictionary<string, object> _values;}}diff --git a/Wave_Dude_2D/ProjectStore.cs b/Wave_Dude_2D/ProjectStore.csindex 64836fb..32965f9 100644--- a/Wave_Dude_2D/ProjectStore.cs+++ b/Wave_Dude_2D/ProjectStore.cs@@ -9,8 +9,13 @@ namespace _2D_wave_sim_V01/// Static helper that creates, opens, lists, renames and deletes project folders under a root/// folder, and is the only code that constructs <see cref="Project"/> instances. A project folder/// is any folder directly below the root that contains a configuration.json (or an empty legacy- /// Configuration.txt, which <see cref="Open"/> upgrades in place). Used by the Projects and- /// Outputs tabs and by the File menu; all methods are synchronous and do their own disk I/O.+ /// Configuration.txt, which <see cref="Open"/> upgrades in place); the folder name is the project name.+ /// The main folder of a project contains configuration.json and the sub-folders+ /// <see cref="AssetsFolderName"/>, <see cref="OutputFramesFolderName"/>, <see cref="OutputVideoFolderName"/>+ /// and <see cref="SceneImageFolderName"/>. The configuration is entirely in configuration.json; assets is+ /// instead where the user can keep any third-party files used by the project, such as the original+ /// Photoshop file of a scene image. Used by the Projects and Outputs tabs and by the File menu; all+ /// methods are synchronous and do their own disk I/O./// </summary>public sealed class ProjectStore{@@ -24,6 +29,7 @@ namespace _2D_wave_sim_V01/// blank, no surrounding whitespace, no trailing dot, at most <see cref="MaxNameLength"/>/// characters, no characters from <see cref="Path.GetInvalidFileNameChars"/>, and not a/// reserved device name (CON, NUL, COM1, ...; the part before the first dot is checked).+ /// The name is never changed silently./// </summary>/// <returns>A user-facing error message, or "" when the name is acceptable.</returns>public static string ValidateName(string projectName)@@ -45,16 +51,15 @@ namespace _2D_wave_sim_V01return "The project name is too long (at most " + ProjectStore.MaxNameLength.ToString() + " characters).";}char[] invalidChars = Path.GetInvalidFileNameChars();- for (int i = 0; i < projectName.Length; i++)+ foreach (char ch in projectName){- char c = projectName[i];- if (Array.IndexOf(invalidChars, c) >= 0)+ if (Array.IndexOf(invalidChars, ch) >= 0){- if (c < ' ')+ if (ch < ' '){return "The project name contains a control character.";}- return "The project name contains the character '" + c.ToString() + "', which is not allowed in a folder name.";+ return "The project name contains the character '" + ch.ToString() + "', which is not allowed in a folder name.";}}string baseName = projectName.Split('.')[0].ToUpperInvariant();@@ -108,11 +113,11 @@ namespace _2D_wave_sim_V01{if (!File.Exists(legacyPath)){- throw new InvalidDataException("The folder '" + Path.GetFileName(folder) + "' is not a project folder: it contains no configuration.json.");+ throw new InvalidDataException("The folder '" + Path.GetFileName(folder) + "' is not a project folder: it contains no " + ProjectConfig.FileName + ".");}if (File.ReadAllText(legacyPath).Trim().Length > 0){- throw new InvalidDataException("The file Configuration.txt is not empty and has no known format, so it was not replaced.");+ throw new InvalidDataException("The file " + ProjectConfig.LegacyFileName + " is not empty and has no known format, so it was not replaced.");}project = new Project(folder, new ProjectConfig(Path.GetFileName(folder)));project.Save();@@ -222,6 +227,7 @@ namespace _2D_wave_sim_V01string newFolder = ProjectStore.FolderPathFor(rootFolder, newProjectName);if (string.Equals(folder, newFolder, StringComparison.OrdinalIgnoreCase)){+ // only a case change, or unchangedreturn folder;}if (Directory.Exists(newFolder) || File.Exists(newFolder))@@ -232,7 +238,7 @@ namespace _2D_wave_sim_V01return newFolder;}- /// <summary>Creates the standard sub-folders (<see cref="SubFolderNames"/>) inside a project folder; I/O and access errors are ignored.</summary>+ /// <summary>Creates the standard sub-folders (<see cref="SubFolderNames"/>) inside a project folder; I/O and access errors are not fatal here.</summary>private static void EnsureSubFolders(string folder){try@@ -244,6 +250,7 @@ namespace _2D_wave_sim_V01}catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException){+ // not fatal: a folder that cannot be created is reported when it is needed}}@@ -266,7 +273,7 @@ namespace _2D_wave_sim_V01return path;}- /// <summary>Sub-folder for user files that belong to the project (counted in the delete warning).</summary>+ /// <summary>Sub-folder where the user keeps any third-party files that belong to the project, such as the original Photoshop file of a scene image; never read or written by the simulator itself (counted in the delete warning).</summary>public const string AssetsFolderName = "assets";/// <summary>Sub-folder the simulation writes rendered PNG frames into.</summary>@@ -284,7 +291,7 @@ namespace _2D_wave_sim_V01/// <summary>The sub-folders every project folder gets, in creation order.</summary>private static readonly string[] SubFolderNames = new string[] { AssetsFolderName, OutputFramesFolderName, OutputVideoFolderName, SceneImageFolderName };- /// <summary>Windows device names that cannot be used as a folder name (compared upper-case against the part before the first dot).</summary>+ /// <summary>Names that Windows does not allow for a file or folder (compared upper-case against the part before the first dot).</summary>private static readonly string[] ReservedNames = new string[]{"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6",diff --git a/Wave_Dude_2D/SceneData.cs b/Wave_Dude_2D/SceneData.csindex 9e7c34e..7dd2fcb 100644--- a/Wave_Dude_2D/SceneData.cs+++ b/Wave_Dude_2D/SceneData.cs@@ -7,10 +7,15 @@ using System.Runtime.InteropServices;namespace _2D_wave_sim_V01{/// <summary>- /// Per-pixel simulation input derived from a scene image: squared wave speed (<see cref="C2"/>),- /// damping factor (<see cref="D"/>) and the positions / levels of image-defined sources.- /// Red channel = refractive index * 100 (clamped to 0.9..10), green = source level (0 = none),- /// blue = damping strength (0 = none, 255 = full; stored as <c>D = 1 - blue / 255</c>).+ /// Per-pixel simulation input derived from a scene image: squared wave speed (<see cref="C2"/>,+ /// <c>(1 / refractive index)^2</c>; the time step is 1), damping factor (<see cref="D"/>, the factor on the+ /// velocity: 1 = no damping, 0 = the wave is stopped) and the positions / levels of image-defined sources+ /// (the value of the green channel sets the frequency).+ /// The rules are those of the Python classes <c>StaticImageScene</c>, <c>StaticRefractiveIndex</c> and+ /// <c>StaticDampening</c>: red channel = refractive index * 100 (clamped to 0.9..10), green = every pixel+ /// above 0 is a sinusoidal source whose level is the green value, blue = damping strength (0 = none,+ /// 255 = full; stored as <c>D = 1 - blue / 255</c>), damping edge = a border of the given thickness with+ /// damping factor <c>sqrt(i / thickness)</c> at i pixels from the edge./// Created by <see cref="SimulationRunner"/> on its worker thread/// via <see cref="FromImage"/> or <see cref="Empty"/> and then copied into the padded grids of/// <see cref="WaveSimulator"/> / <see cref="GpuWaveSimulator"/>. The arrays are row-major@@ -20,23 +25,17 @@ namespace _2D_wave_sim_V01{private SceneData(int w, int h, float[] c2, float[] d, int[] srcX, int[] srcY, byte[] srcLevel){- this.Width = w;- this.Height = h;- this.C2 = c2;- this.D = d;- this.SourceX = srcX;- this.SourceY = srcY;- this.SourceLevel = srcLevel;+ Width = w;+ Height = h;+ C2 = c2;+ D = d;+ SourceX = srcX;+ SourceY = srcY;+ SourceLevel = srcLevel;}/// <summary>Number of image-defined source pixels (length of <see cref="SourceX"/>, <see cref="SourceY"/> and <see cref="SourceLevel"/>).</summary>- public int SourceCount- {- get- {- return this.SourceX.Length;- }- }+ public int SourceCount => SourceX.Length;/// <summary>/// Decodes <paramref name="image"/> (any pixel format; read as 32bpp ARGB) into per-pixel squared@@ -67,6 +66,7 @@ namespace _2D_wave_sim_V01for (int x = 0; x < width; x++){int offset = x * 4;+ // Format32bppArgb is stored as B, G, R, Aint blue = row[offset];int green = row[offset + 1];int red = row[offset + 2];@@ -101,14 +101,14 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Creates a uniform <paramref name="w"/> x <paramref name="h"/> scene without sources: the+ /// Creates a uniform, user defined <paramref name="w"/> x <paramref name="h"/> scene without sources: the/// speed is derived from <paramref name="refractiveIndex"/> (clamped to 0.9..10) and the damping/// factor is 1 (none) everywhere except in the <paramref name="dampingEdge"/> border./// </summary>/// <param name="w">Canvas width in pixels.</param>/// <param name="h">Canvas height in pixels.</param>/// <param name="dampingEdge">Thickness of the absorbing border in pixels; 0 or less for none.</param>- /// <param name="refractiveIndex">Background refractive index (1 = vacuum speed).</param>+ /// <param name="refractiveIndex">Background refractive index (1.0 by default, the same rule as a scene image's red channel: index = red / 100).</param>public static SceneData Empty(int w, int h, int dampingEdge, double refractiveIndex = 1.0){double clampedIndex = refractiveIndex;@@ -166,10 +166,11 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Overwrites the damping factor in a frame of <paramref name="thickness"/> pixels (capped at- /// half the smaller side) around the edge of the <paramref name="w"/> x <paramref name="h"/>- /// grid with <c>sqrt(i / border)</c>, where i is the distance from the edge: 0 on the outermost- /// ring, rising towards 1 at the inner edge of the frame. Does nothing for a thickness of 0 or less.+ /// Damping edge, as in <c>StaticDampening</c>: overwrites the damping factor in a frame of+ /// <paramref name="thickness"/> pixels (capped at half the smaller side) around the edge of the+ /// <paramref name="w"/> x <paramref name="h"/> grid with <c>sqrt(i / thickness)</c>, where i is the+ /// distance from the edge, so the outermost ring stops the wave completely and the factor rises to 1+ /// inside. Does nothing for a thickness of 0 or less./// </summary>/// <param name="d">Damping array, row-major, modified in place.</param>/// <param name="w">Grid width in pixels.</param>diff --git a/Wave_Dude_2D/SceneSettings.cs b/Wave_Dude_2D/SceneSettings.csindex b451e50..ab01482 100644--- a/Wave_Dude_2D/SceneSettings.cs+++ b/Wave_Dude_2D/SceneSettings.cs@@ -6,29 +6,38 @@ using System.IO;namespace _2D_wave_sim_V01{/// <summary>- /// The "scene" section of a project: where the canvas comes from (an image or a blank user-sized canvas),- /// the damping border and the source options. Edited by <c>Form1</c> on the UI thread and persisted through- /// <see cref="ProjectConfig"/>; the runner turns it into a <see cref="SceneData"/> when a run starts.+ /// The "scene" section of a project (Configuration tab): where the canvas comes from (an image or a blank+ /// user-sized canvas), the damping border and the source options. Edited by <c>Form1</c> on the UI thread and+ /// persisted through <see cref="ProjectConfig"/>; the runner turns it into a <see cref="SceneData"/> when a run+ /// starts. The size of a scene image is not stored: it is read from the image itself. There is no scene-level+ /// "use probes" switch: each probe has its own "On" checkbox (<see cref="ProbeSettings.Active"/>) instead./// </summary>public sealed class SceneSettings{- /// <summary>Creates settings with the defaults: a blank 1920 × 1080 canvas, 64 px damping edge, no sources.</summary>+ /// <summary>+ /// Creates settings with the defaults of the Python example: a blank 1920 × 1080 canvas, 64 px damping+ /// edge, no sources. <see cref="DampingEdgeEnabled"/> and <see cref="UseObjectSources"/> deliberately have+ /// no software-chosen default of their own and stay false here, the same as+ /// <see cref="SimulationSettings.Steps"/> / <see cref="SimulationSettings.TimeDecayFactor"/>: a new project+ /// starts at whatever the Designer Checked value of <c>chkDampingEdge</c> / <c>chkUseObjectSources</c> is,+ /// which <c>StartNewProject</c> (Form1) reads right after creating this instance.+ /// </summary>public SceneSettings(){- this.UseImage = false;- this.ImageFile = "";- this.UserWidth = DefaultWidth;- this.UserHeight = DefaultHeight;- this.DampingEdgeSize = DefaultDampingEdgeSize;- this.UseSources = false;- this.ImageSourceScale = DefaultImageSourceScale;- this.BackgroundRefractiveIndex = DefaultBackgroundRefractiveIndex;+ UseImage = false;+ ImageFile = "";+ UserWidth = DefaultWidth;+ UserHeight = DefaultHeight;+ DampingEdgeSize = DefaultDampingEdgeSize;+ UseSources = false;+ ImageSourceScale = DefaultImageSourceScale;+ BackgroundRefractiveIndex = DefaultBackgroundRefractiveIndex;}/// <summary>True to build the canvas from <see cref="ImageFile"/>; false for a blank <see cref="UserWidth"/> × <see cref="UserHeight"/> canvas.</summary>public bool UseImage { get; set; }- /// <summary>Scene image path as stored in the project (relative to the project folder when inside it; see <see cref="ToStoredPath"/>), or "".</summary>+ /// <summary>Scene image path as stored in the project: relative to the project folder when inside it (forward slashes; see <see cref="ToStoredPath"/>), otherwise a full path; "" when none.</summary>public string ImageFile { get; set; }/// <summary>Width in canvas pixels of a user-defined canvas.</summary>@@ -37,7 +46,13 @@ namespace _2D_wave_sim_V01/// <summary>Height in canvas pixels of a user-defined canvas.</summary>public int UserHeight { get; set; }- /// <summary>Whether a damping frame is applied around the canvas edge.</summary>+ /// <summary>+ /// Whether a damping frame is applied around the canvas edge. No software-chosen default of its own, the+ /// same as <see cref="SimulationSettings.Steps"/> / <see cref="SimulationSettings.TimeDecayFactor"/>: a new+ /// project starts at whatever <c>chkDampingEdge</c>'s own Designer Checked value is (see+ /// <c>StartNewProject</c>, Form1). The false used by <see cref="FromConfig"/> is only the fallback for an+ /// existing project saved before this setting existed.+ /// </summary>public bool DampingEdgeEnabled { get; set; }/// <summary>Thickness of the damping frame in canvas pixels.</summary>@@ -46,18 +61,25 @@ namespace _2D_wave_sim_V01/// <summary>Whether green pixels of the scene image act as wave sources.</summary>public bool UseSources { get; set; }- /// <summary>Peak amplitude of the image sources (passed to the engine as the source amplitude).</summary>+ /// <summary>Peak amplitude of the image sources (passed to the engine as the source amplitude; <c>source_amplitude</c> of <c>StaticImageScene</c> in the Python code).</summary>public double ImageSourceScale { get; set; }- /// <summary>Whether the interactive object sources of the project are used in the run.</summary>+ /// <summary>+ /// Whether the object sources of the source list are used in the run. No software-chosen default of its+ /// own, the same as <see cref="DampingEdgeEnabled"/>: a new project starts at whatever+ /// <c>chkUseObjectSources</c>' own Designer Checked value is (see <c>StartNewProject</c>, Form1); the false+ /// used by <see cref="FromConfig"/> is only the fallback for a project saved before this setting existed.+ /// </summary>public bool UseObjectSources { get; set; }- /// <summary>Refractive index of a user-defined canvas (c = 1/n cells per step); 1.0 to 2.55.</summary>+ /// <summary>Refractive index of a user-defined canvas's background (c = 1/n cells per step), 1.0 to 2.55 (a red channel value of 100 to 255, as in a scene image, which has its own value per pixel from its red channel).</summary>public double BackgroundRefractiveIndex { get; set; }/// <summary>/// Reads the "scene" section of <paramref name="config"/>. Missing keys and out-of-range values fall back to- /// the defaults; a missing section yields a default instance.+ /// the defaults; a missing section yields a default instance. The false fallbacks for+ /// <c>damping_edge_enabled</c> and <c>use_object_sources</c> are deliberate: they keep a project saved before+ /// those keys existed at its previous behaviour (see <see cref="DampingEdgeEnabled"/>)./// </summary>public static SceneSettings FromConfig(ProjectConfig config){@@ -84,16 +106,16 @@ namespace _2D_wave_sim_V01public void ToConfig(ProjectConfig config){Dictionary<string, object> section = config.GetSection(SectionName);- section["mode"] = (this.UseImage ? ModeImage : ModeUserDefined);- section["image_file"] = this.ImageFile;- section["user_width"] = this.UserWidth;- section["user_height"] = this.UserHeight;- section["damping_edge_enabled"] = this.DampingEdgeEnabled;- section["damping_edge_size_px"] = this.DampingEdgeSize;- section["use_sources"] = this.UseSources;- section["image_source_scale"] = this.ImageSourceScale;- section["use_object_sources"] = this.UseObjectSources;- section["background_refractive_index"] = this.BackgroundRefractiveIndex;+ section["mode"] = (UseImage ? ModeImage : ModeUserDefined);+ section["image_file"] = ImageFile;+ section["user_width"] = UserWidth;+ section["user_height"] = UserHeight;+ section["damping_edge_enabled"] = DampingEdgeEnabled;+ section["damping_edge_size_px"] = DampingEdgeSize;+ section["use_sources"] = UseSources;+ section["image_source_scale"] = ImageSourceScale;+ section["use_object_sources"] = UseObjectSources;+ section["background_refractive_index"] = BackgroundRefractiveIndex;}/// <summary>@@ -179,6 +201,7 @@ namespace _2D_wave_sim_V01}catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException){+ // use the fallback}}return fallback;@@ -203,6 +226,7 @@ namespace _2D_wave_sim_V01}catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException){+ // use the fallback}}return fallback;@@ -217,6 +241,8 @@ namespace _2D_wave_sim_V01/// <summary>Value of the "mode" key for a blank user-sized canvas.</summary>public const string ModeUserDefined = "user_defined";+ // the defaults are those of the Python example (1920 x 1080 canvas, 64 px damping edge)+/// <summary>Default <see cref="UserWidth"/> in canvas pixels.</summary>public const int DefaultWidth = 1920;@@ -241,7 +267,7 @@ namespace _2D_wave_sim_V01/// <summary>Largest accepted <see cref="ImageSourceScale"/>.</summary>public const double MaxImageSourceScale = 1000.0;- /// <summary>Default <see cref="BackgroundRefractiveIndex"/>.</summary>+ /// <summary>Default <see cref="BackgroundRefractiveIndex"/> of a user-defined (image-less) scene's background; the range is 1.0 to 2.55 (a red channel value of 100 to 255, as in a scene image).</summary>public const double DefaultBackgroundRefractiveIndex = 1.0;/// <summary>Smallest accepted <see cref="BackgroundRefractiveIndex"/>.</summary>diff --git a/Wave_Dude_2D/SimulationJob.cs b/Wave_Dude_2D/SimulationJob.csindex 1578136..0359d92 100644--- a/Wave_Dude_2D/SimulationJob.cs+++ b/Wave_Dude_2D/SimulationJob.cs@@ -12,10 +12,10 @@ namespace _2D_wave_sim_V01{public SimulationJob(){- this.BackgroundRefractiveIndex = 1.0;- this.SourceAmplitude = 1.0;- this.FieldVideoPath = "";- this.IntensityVideoPath = "";+ BackgroundRefractiveIndex = 1.0;+ SourceAmplitude = 1.0;+ FieldVideoPath = "";+ IntensityVideoPath = "";}/// <summary>@@ -45,10 +45,10 @@ namespace _2D_wave_sim_V01/// <summary>Snapshot (clone) of the simulation settings, so later edits in the UI do not affect the running job.</summary>public SimulationSettings Settings;- /// <summary>ARGB palette of <see cref="ColorLut.Size"/> entries for field frames; null when neither field export nor field preview is wanted.</summary>+ /// <summary>Colour table (<see cref="ColorLut.Size"/> packed ARGB values) for field frames, or null for grey levels (<see cref="FrameRenderer"/> then uses the table index itself as the grey level).</summary>public int[] FieldLut;- /// <summary>ARGB palette of <see cref="ColorLut.Size"/> entries for intensity frames; null when neither intensity export nor preview is wanted.</summary>+ /// <summary>Colour table (<see cref="ColorLut.Size"/> packed ARGB values) for intensity frames, or null for grey levels.</summary>public int[] IntensityLut;/// <summary>Full path of the field video to write (.mp4, may fall back to .avi); empty = do not export the field.</summary>@@ -70,15 +70,27 @@ namespace _2D_wave_sim_V01public int PreviewHeight;/// <summary>- /// Glowing-edges image of the scene, canvas sized, to add onto the exported video frames; null when not exporting or both gains are 0.- /// The runner converts and disposes it before the first step.+ /// The Viewer tab's "glowing edges" overlay (<c>Form1</c>'s <c>_glowEdgesImage</c>), exactly the size of the simulation+ /// canvas; null when there is none (no scene image), or when both gains below are 0 (the overlay is switched off for+ /// both Field and Intensity). Frozen at the start of the run, the same as <see cref="Settings"/>; the runner owns and+ /// disposes it (converted to bytes before the first step). See <see cref="FrameRenderer.AddOverlay"/>./// </summary>public Bitmap GlowOverlay;- /// <summary>Brightness multiplier for <see cref="GlowOverlay"/> on field frames; 0 = no overlay.</summary>+ /// <summary>+ /// How strongly to blend <see cref="GlowOverlay"/> into the Field video, frozen at the start of the run from+ /// <c>Form1</c>'s <c>numBrightnessFieldOverlay</c> and <c>chkDiplayOverlayInField</c> (0 when unchecked, see+ /// <c>Form1.FieldOverlayGain</c>). Only affects the exported videos: the live preview keeps blending its own copy of the+ /// overlay in on the UI thread (<c>Form1.ShowPreview</c>/<c>ComposeGlowOverlay</c>), which can track the checkbox/brightness+ /// box live; a running export cannot, so it uses whatever these were at the moment Start Simulation was pressed.+ /// </summary>public double FieldOverlayGain;- /// <summary>Brightness multiplier for <see cref="GlowOverlay"/> on intensity frames; 0 = no overlay.</summary>+ /// <summary>+ /// How strongly to blend <see cref="GlowOverlay"/> into the Intensity video, frozen at the start of the run from+ /// <c>numBrightnessIntensityOverlay</c> and <c>chkDiplayOverlayInIntensity</c> (0 when unchecked); see+ /// <see cref="FieldOverlayGain"/> for why only the exported video is affected.+ /// </summary>public double IntensityOverlayGain;}}diff --git a/Wave_Dude_2D/SimulationResult.cs b/Wave_Dude_2D/SimulationResult.csindex dd6a0fd..252bc04 100644--- a/Wave_Dude_2D/SimulationResult.cs+++ b/Wave_Dude_2D/SimulationResult.cs@@ -14,12 +14,12 @@ namespace _2D_wave_sim_V01{public SimulationResult(){- this.Message = "";- this.Files = new List<string>();- this.FieldFile = "";- this.IntensityFile = "";- this.Engine = "";- this.EngineNote = "";+ Message = "";+ Files = new List<string>();+ FieldFile = "";+ IntensityFile = "";+ Engine = "";+ EngineNote = "";}/// <summary>How the run ended.</summary>@@ -46,16 +46,27 @@ namespace _2D_wave_sim_V01/// <summary>Full path of the intensity video, or empty when the intensity was not exported.</summary>public string IntensityFile;- /// <summary><see cref="IWaveEngine.Description"/> of the engine that ran; empty when engine creation itself failed.</summary>+ /// <summary>+ /// Where the simulation ran, the <see cref="IWaveEngine.Description"/> of the engine ("CPU (8 threads)",+ /// "GPU: NVIDIA GeForce MX130 (OpenCL)"); empty when engine creation itself failed.+ /// </summary>public string Engine;- /// <summary>Note from <see cref="WaveEngineFactory.Create"/> about why the GPU was not used; empty when there is none.</summary>+ /// <summary>Note from <see cref="WaveEngineFactory.Create"/>: why the GPU was not used when it was asked for; empty when there is none.</summary>public string EngineNote;- /// <summary>Full-size field frame of the final state (with probe overlays burned in); null when no engine was created or rendering failed.</summary>+ /// <summary>+ /// A full simulation-resolution snapshot of the field (with probe overlays burned in), rendered right before the engine+ /// was closed down, so a still export (the Preview tab's "Export current Field/Intensity frame" buttons) has something to+ /// save even once the run has fully stopped and the live engine no longer exists. Null when the run failed before an+ /// engine was created or rendering failed. The receiver owns the bitmap.+ /// </summary>public Bitmap LastFieldFrame;- /// <summary>Full-size intensity frame of the final state; null when the intensity was not tracked or rendering failed.</summary>+ /// <summary>+ /// The same snapshot of the intensity; null when the intensity was not tracked for this run (or, as for+ /// <see cref="LastFieldFrame"/>, no engine was created or rendering failed). The receiver owns the bitmap.+ /// </summary>public Bitmap LastIntensityFrame;}}diff --git a/Wave_Dude_2D/SimulationRunner.cs b/Wave_Dude_2D/SimulationRunner.csindex 0e6e7f1..9c33b36 100644--- a/Wave_Dude_2D/SimulationRunner.cs+++ b/Wave_Dude_2D/SimulationRunner.cs@@ -7,10 +7,11 @@ using System.Threading;namespace _2D_wave_sim_V01{/// <summary>- /// Runs a <see cref="SimulationJob"/> on a dedicated background thread ("Wave simulation"),- /// writing video frames, collecting probe data and raising progress / preview events as it goes.- /// Created and started by <c>Form1</c> (one instance per run); the form keeps the reference in- /// <c>_runner</c> so stale callbacks from an older run can be ignored.+ /// Runs a <see cref="SimulationJob"/> on a dedicated background thread ("Wave simulation"), as the loop+ /// in <c>main_curr.py</c>: for every step update the scene (sources), update the field and the intensity;+ /// every N steps render a frame for the previews and the videos, collecting probe data and raising+ /// progress / preview events as it goes. Created and started by <c>Form1</c> (one instance per run);+ /// the form keeps the reference in <c>_runner</c> so stale callbacks from an older run can be ignored./// </summary>/// <remarks>/// <para><b>Event contract.</b> Every event (<see cref="ProgressChanged"/>, <see cref="EngineReady"/>,@@ -49,8 +50,9 @@ namespace _2D_wave_sim_V01public event SimulationRunner.EngineReadyEventHandler EngineReady;/// <summary>- /// Raised on the worker thread at most every 50 ms (and once at the end) with the probe samples- /// drained since the previous update. Only raised when the job has probes.+ /// Raised on the worker thread at most every 50 ms (and once at the end) with the new probe measurements+ /// drained since the previous update: the new values of the point probes and the last profile of the line+ /// probes. The receiver owns the arrays. Only raised when the job has probes./// </summary>public event SimulationRunner.ProbesUpdatedEventHandler ProbesUpdated;@@ -71,43 +73,44 @@ namespace _2D_wave_sim_V01/// <summary>Stores the job and creates the pause gate in the "running" (set) state.</summary>public SimulationRunner(SimulationJob job){- this._gate = new ManualResetEventSlim(true);- this._job = job;+ _gate = new ManualResetEventSlim(true);+ _job = job;}/// <summary>Starts the background worker thread; returns immediately. Call once.</summary>public void Start(){- this._thread = new Thread(new ThreadStart(this.Run));- this._thread.IsBackground = true;- this._thread.Name = "Wave simulation";- this._thread.Start();+ _thread = new Thread(new ThreadStart(Run));+ _thread.IsBackground = true;+ _thread.Name = "Wave simulation";+ _thread.Start();}/// <summary>- /// Requests cancellation (thread-safe, callable from the UI thread). Also opens the pause gate so a- /// paused run can wake up and finish; the run then ends with <see cref="SimulationStatus.Cancelled"/>- /// and <see cref="Finished"/> is still raised.+ /// Asks the run to stop after the current step (thread-safe, callable from the UI thread). Also opens+ /// the pause gate so a paused run can wake up and finish; the run then ends with+ /// <see cref="SimulationStatus.Cancelled"/>, the videos are closed properly and <see cref="Finished"/>+ /// is still raised./// </summary>public void Cancel(){- Interlocked.Exchange(ref this._cancel, 1);- this._gate.Set();+ Interlocked.Exchange(ref _cancel, 1);+ _gate.Set(); // a paused run must wake up to stop}/// <summary>- /// Closes the gate so the worker blocks before its next step (it finishes the step in progress- /// first). While paused, <see cref="RenderCurrentFrame"/> may be used.+ /// Holds the run before the next step: closes the gate so the worker blocks (it finishes the step in+ /// progress first). The videos stay open. While paused, <see cref="RenderCurrentFrame"/> may be used./// </summary>public void PauseRun(){- this._gate.Reset();+ _gate.Reset();}/// <summary>Opens the gate so a paused worker continues.</summary>public void ResumeRun(){- this._gate.Set();+ _gate.Set();}/// <summary>@@ -116,7 +119,7 @@ namespace _2D_wave_sim_V01/// </summary>public void PreviewShown(){- Interlocked.Decrement(ref this._previewPending);+ Interlocked.Decrement(ref _previewPending);}/// <summary>@@ -125,14 +128,15 @@ namespace _2D_wave_sim_V01/// <returns><c>true</c> if the thread ended (or was never started), <c>false</c> on timeout.</returns>public bool WaitForExit(int milliseconds){- Thread thread = this._thread;+ Thread thread = _thread;return thread == null || thread.Join(milliseconds);}/// <summary>- /// Renders the current field or intensity frame at full engine resolution, with probe markers burned- /// in but without the glow overlay. Intended for the UI thread while the run is paused: it reads the- /// engine buffers directly, which is only safe because the worker is parked on the gate.+ /// Renders the current field or intensity frame at full engine resolution on demand (for a still-image+ /// export), with probe markers burned in but without the glow overlay. Intended for the UI thread, and+ /// only while the run is paused: it reads the engine buffers directly, which is only safe because the+ /// worker is then guaranteed to be parked on the gate and not touching the engine's arrays./// </summary>/// <param name="isField"><c>true</c> for the wave field, <c>false</c> for the intensity.</param>/// <param name="lut">ARGB palette with at least 255 entries, or null for greyscale.</param>@@ -143,11 +147,11 @@ namespace _2D_wave_sim_V01/// </returns>public Bitmap RenderCurrentFrame(bool isField, int[] lut, float brightness){- if (this._gate.IsSet)+ if (_gate.IsSet){- return null;+ return null; // running (not paused): unsafe to read}- IWaveEngine sim = this._sim;+ IWaveEngine sim = _sim;if (sim == null){return null;@@ -163,17 +167,17 @@ namespace _2D_wave_sim_V01if (isField){FrameRenderer.RenderField(sim, lut, brightness, pixels, width, height);- if (this._collector != null)+ if (_collector != null){- ProbeOverlay.Burn(pixels, width, height, this._job.Probes, this._collector.Traces, ProbePlaceOn.Field, this._job.Settings.Steps);+ ProbeOverlay.Burn(pixels, width, height, _job.Probes, _collector.Traces, ProbePlaceOn.Field, _job.Settings.Steps);}}else{FrameRenderer.RenderIntensity(sim, lut, brightness, pixels, width, height);- if (this._collector != null)+ if (_collector != null){- ProbeOverlay.Burn(pixels, width, height, this._job.Probes, this._collector.Traces, ProbePlaceOn.Intensity, this._job.Settings.Steps);+ ProbeOverlay.Burn(pixels, width, height, _job.Probes, _collector.Traces, ProbePlaceOn.Intensity, _job.Settings.Steps);}}return FrameRenderer.ToBitmap(pixels, width, height);@@ -193,31 +197,36 @@ namespace _2D_wave_sim_V01IFrameSink fieldSink = null;IFrameSink intensitySink = null;IWaveEngine engine = null;+ // declared here, outside the try, because finally also needs them for the last-frame probe overlayProbeCollector collector = null;int totalSteps = 0;try{- SimulationSettings settings = this._job.Settings;- bool writeField = this._job.FieldVideoPath.Length > 0;- bool writeIntensity = this._job.IntensityVideoPath.Length > 0;+ SimulationSettings settings = _job.Settings;+ bool writeField = _job.FieldVideoPath.Length > 0;+ bool writeIntensity = _job.IntensityVideoPath.Length > 0;bool needIntensity = writeIntensity || settings.PreviewIntensity;++ // the scene and the simulatorSceneData scene;- if (this._job.Image != null)+ if (_job.Image != null){- scene = SceneData.FromImage(this._job.Image, this._job.UseSources, this._job.DampingEdge);- this._job.Image.Dispose();- this._job.Image = null;+ scene = SceneData.FromImage(_job.Image, _job.UseSources, _job.DampingEdge);+ _job.Image.Dispose();+ _job.Image = null;}else{- scene = SceneData.Empty(this._job.Width, this._job.Height, this._job.DampingEdge, this._job.BackgroundRefractiveIndex);+ scene = SceneData.Empty(_job.Width, _job.Height, _job.DampingEdge, _job.BackgroundRefractiveIndex);}int width = scene.Width;int height = scene.Height;++ // the probesProbeSampler sampler = null;- if (this._job.Probes != null && this._job.Probes.Count > 0)+ if (_job.Probes != null && _job.Probes.Count > 0){- sampler = ProbeSampler.Build(this._job.Probes, width, height);+ sampler = ProbeSampler.Build(_job.Probes, width, height);collector = new ProbeCollector(sampler);if (sampler.NeedsIntensity){@@ -225,56 +234,61 @@ namespace _2D_wave_sim_V01}}string engineNote = "";- engine = WaveEngineFactory.Create(scene, settings, this._job.SourceAmplitude, needIntensity, ref engineNote, this._job.ObjectSources);- this._sim = engine;- this._collector = collector;+ engine = WaveEngineFactory.Create(scene, settings, _job.SourceAmplitude, needIntensity, ref engineNote, _job.ObjectSources);+ _sim = engine;+ _collector = collector;result.Engine = engine.Description;result.EngineNote = engineNote;- this.EngineReady?.Invoke(engine.Description, engineNote);+ EngineReady?.Invoke(engine.Description, engineNote);if (sampler != null){engine.SetProbes(sampler);}++ // videosif (writeField){- fieldSink = SimulationRunner.OpenSink(this._job.FieldVideoPath, width, height, settings.VideoFps, settings.VideoQuality, result);+ fieldSink = SimulationRunner.OpenSink(_job.FieldVideoPath, width, height, settings.VideoFps, settings.VideoQuality, result);result.Files.Add(fieldSink.FilePath);result.FieldFile = fieldSink.FilePath;}if (writeIntensity){- intensitySink = SimulationRunner.OpenSink(this._job.IntensityVideoPath, width, height, settings.VideoFps, settings.VideoQuality, result);+ intensitySink = SimulationRunner.OpenSink(_job.IntensityVideoPath, width, height, settings.VideoFps, settings.VideoQuality, result);result.Files.Add(intensitySink.FilePath);result.IntensityFile = intensitySink.FilePath;}- int[] framePixels = null;+ int[] fullPixels = null;if (writeField || writeIntensity){- framePixels = new int[width * height];+ fullPixels = new int[width * height];}- byte[] fieldOverlay = null;- byte[] intensityOverlay = null;- if (this._job.GlowOverlay != null && (writeField || writeIntensity))+ // the "glowing edges" overlay for the videos (FrameRenderer.AddOverlay): converted to a plain RGB+ // byte array and gain-prescaled (FrameRenderer.ScaleOverlayRgb) once, up front, rather than redoing+ // either on every single exported frame; this was the actual cost of the overlay on a video export+ byte[] fieldOverlayScaled = null;+ byte[] intensityOverlayScaled = null;+ if (_job.GlowOverlay != null && (writeField || writeIntensity)){- byte[] overlayRgb = FrameRenderer.ToRgbBytes(this._job.GlowOverlay, width, height);+ byte[] overlayRgb = FrameRenderer.ToRgbBytes(_job.GlowOverlay, width, height);if (writeField){- fieldOverlay = FrameRenderer.ScaleOverlayRgb(overlayRgb, this._job.FieldOverlayGain);+ fieldOverlayScaled = FrameRenderer.ScaleOverlayRgb(overlayRgb, _job.FieldOverlayGain);}if (writeIntensity){- intensityOverlay = FrameRenderer.ScaleOverlayRgb(overlayRgb, this._job.IntensityOverlayGain);+ intensityOverlayScaled = FrameRenderer.ScaleOverlayRgb(overlayRgb, _job.IntensityOverlayGain);}}- if (this._job.GlowOverlay != null)+ if (_job.GlowOverlay != null){- this._job.GlowOverlay.Dispose();- this._job.GlowOverlay = null;+ _job.GlowOverlay.Dispose();+ _job.GlowOverlay = null;}- // Preview is shrunk (never enlarged) to fit the preview box, keeping the aspect ratio.+ // previews are made small enough to fit the preview area: shrunk (never enlarged), keeping the aspect ratioint previewWidth = width;int previewHeight = height;- double previewScale = Math.Min((double)this._job.PreviewWidth / width, (double)this._job.PreviewHeight / height);+ double previewScale = Math.Min((double)_job.PreviewWidth / width, (double)_job.PreviewHeight / height);if (previewScale < 1.0){previewWidth = Math.Max(1, (int)Math.Floor(width * previewScale));@@ -295,15 +309,15 @@ namespace _2D_wave_sim_V01result.Status = SimulationStatus.Completed;for (int i = 0; i < totalSteps; i++){- if (!this._gate.IsSet)+ if (!_gate.IsSet){- // Paused: report the exact step count and exclude the wait from the elapsed time.+ // paused: report the exact step count; the time of the pause does not countstopwatch.Stop();- this.ProgressChanged?.Invoke(result.StepsDone, totalSteps);- this._gate.Wait();+ ProgressChanged?.Invoke(result.StepsDone, totalSteps);+ _gate.Wait();stopwatch.Start();}- if (Thread.VolatileRead(ref this._cancel) != 0)+ if (Thread.VolatileRead(ref _cancel) != 0){result.Status = SimulationStatus.Cancelled;break;@@ -316,6 +330,7 @@ namespace _2D_wave_sim_V01result.StepsDone = i + 1;if (i % visualizeEvery == 0){+ // the probe values up to this step (the graphs in the videos need them)if (collector != null){collector.Collect(engine, result.StepsDone);@@ -324,68 +339,86 @@ namespace _2D_wave_sim_V01collector.CollectProfiles(engine, result.StepsDone);}}+ // previews are only made when the pictures of the last preview have all been shown, and not+ // more often than roughly PreviewIntervalMs. The second condition is the fix for a real bug:+ // without it, this was gated purely by _previewPending (whether the UI thread has finished+ // showing the last one, via ShowPreview/PreviewShown) - and on a GPU engine, PrepareFrame+ // below is where the actual cost is (a full-resolution GPU->host readback, not just the small+ // preview picture), so the GPU run's speed ended up riding on how fast the UI happened to be.+ // With the "display overlay" checkboxes off, SetPreviewFrame is cheap and _previewPending+ // clears almost immediately, so a readback fired on nearly every eligible step; with them on,+ // ComposeGlowOverlay's per-pixel blend made the UI side slow enough to skip most of those+ // readbacks "by accident", which is why turning the overlay on made the run go faster rather+ // than slower. Pacing previews by elapsed time keeps the readback rate steady and no longer+ // dependent on a checkbox that was never meant to affect simulation throughput. Exporting a+ // video already forces a readback every eligible step regardless (see writeField/+ // writeIntensity below), which is why the slowdown was never visible with video export on.bool previewDue = stopwatch.ElapsedMilliseconds - lastPreviewMs >= PreviewIntervalMs;- bool doPreview = previewPixels != null && previewDue && Thread.VolatileRead(ref this._previewPending) <= 0;+ bool doPreview = previewPixels != null && previewDue && Thread.VolatileRead(ref _previewPending) <= 0;if (doPreview){lastPreviewMs = stopwatch.ElapsedMilliseconds;}+ // a GPU engine copies only the data that is going to be drawnengine.PrepareFrame(writeField || (doPreview && settings.PreviewField), writeIntensity || (doPreview && settings.PreviewIntensity));if (writeField){- FrameRenderer.RenderField(engine, this._job.FieldLut, fieldBrightness, framePixels, width, height);- FrameRenderer.AddOverlay(framePixels, fieldOverlay, width, height);+ FrameRenderer.RenderField(engine, _job.FieldLut, fieldBrightness, fullPixels, width, height);+ FrameRenderer.AddOverlay(fullPixels, fieldOverlayScaled, width, height);if (collector != null){- ProbeOverlay.Burn(framePixels, width, height, this._job.Probes, collector.Traces, ProbePlaceOn.Field, totalSteps);+ ProbeOverlay.Burn(fullPixels, width, height, _job.Probes, collector.Traces, ProbePlaceOn.Field, totalSteps);}- fieldSink.AddPixels(framePixels);+ fieldSink.AddPixels(fullPixels);}if (writeIntensity){- FrameRenderer.RenderIntensity(engine, this._job.IntensityLut, intensityBrightness, framePixels, width, height);- FrameRenderer.AddOverlay(framePixels, intensityOverlay, width, height);+ FrameRenderer.RenderIntensity(engine, _job.IntensityLut, intensityBrightness, fullPixels, width, height);+ FrameRenderer.AddOverlay(fullPixels, intensityOverlayScaled, width, height);if (collector != null){- ProbeOverlay.Burn(framePixels, width, height, this._job.Probes, collector.Traces, ProbePlaceOn.Intensity, totalSteps);+ ProbeOverlay.Burn(fullPixels, width, height, _job.Probes, collector.Traces, ProbePlaceOn.Intensity, totalSteps);}- intensitySink.AddPixels(framePixels);+ intensitySink.AddPixels(fullPixels);}if (doPreview){// Set the outstanding count before raising, so PreviewShown() cannot race it to 0.int previewCount = (settings.PreviewField ? 1 : 0) + (settings.PreviewIntensity ? 1 : 0);- Interlocked.Exchange(ref this._previewPending, previewCount);+ Interlocked.Exchange(ref _previewPending, previewCount);if (settings.PreviewField){- FrameRenderer.RenderField(engine, this._job.FieldLut, fieldBrightness, previewPixels, previewWidth, previewHeight);- this.PreviewReady?.Invoke(true, FrameRenderer.ToBitmap(previewPixels, previewWidth, previewHeight));+ FrameRenderer.RenderField(engine, _job.FieldLut, fieldBrightness, previewPixels, previewWidth, previewHeight);+ PreviewReady?.Invoke(true, FrameRenderer.ToBitmap(previewPixels, previewWidth, previewHeight));}if (settings.PreviewIntensity){- FrameRenderer.RenderIntensity(engine, this._job.IntensityLut, intensityBrightness, previewPixels, previewWidth, previewHeight);- this.PreviewReady?.Invoke(false, FrameRenderer.ToBitmap(previewPixels, previewWidth, previewHeight));+ FrameRenderer.RenderIntensity(engine, _job.IntensityLut, intensityBrightness, previewPixels, previewWidth, previewHeight);+ PreviewReady?.Invoke(false, FrameRenderer.ToBitmap(previewPixels, previewWidth, previewHeight));}}}+ // the probe values go to the user interface about 20 times a secondif (collector != null && stopwatch.ElapsedMilliseconds - lastProbeMs >= 50L){lastProbeMs = stopwatch.ElapsedMilliseconds;collector.Collect(engine, result.StepsDone);collector.CollectProfiles(engine, result.StepsDone);- this.ProbesUpdated?.Invoke(collector.TakeForUi());+ ProbesUpdated?.Invoke(collector.TakeForUi());}if (stopwatch.ElapsedMilliseconds - lastProgressMs >= 100L){lastProgressMs = stopwatch.ElapsedMilliseconds;- this.ProgressChanged?.Invoke(i + 1, totalSteps);+ ProgressChanged?.Invoke(i + 1, totalSteps);}}++ // the last probe valuesif (collector != null){collector.Collect(engine, result.StepsDone);collector.CollectProfiles(engine, result.StepsDone);- this.ProbesUpdated?.Invoke(collector.TakeForUi());+ ProbesUpdated?.Invoke(collector.TakeForUi());}}catch (OutOfMemoryException)@@ -400,6 +433,7 @@ namespace _2D_wave_sim_V01}finally{+ // close the videos, also after a stop or an error, so that the files can be playedtry{if (fieldSink != null)@@ -409,6 +443,7 @@ namespace _2D_wave_sim_V01}catch (Exception){+ // nothing more can be done}try{@@ -419,59 +454,64 @@ namespace _2D_wave_sim_V01}catch (Exception){+ // nothing more can be done}if (engine != null){try{- // Capture the final full-size frames for the UI / frame export before the engine goes away.+ // one last full-resolution snapshot, so a still export still has something to save once the run+ // has fully stopped and the engine itself is gone (see SimulationResult.LastFieldFrame/LastIntensityFrame)int[] lastPixels = new int[engine.Width * engine.Height];bool hasIntensity = engine.IntensityData != null;engine.PrepareFrame(true, hasIntensity);- FrameRenderer.RenderField(engine, this._job.FieldLut, (float)this._job.Settings.FieldBrightness, lastPixels, engine.Width, engine.Height);+ FrameRenderer.RenderField(engine, _job.FieldLut, (float)_job.Settings.FieldBrightness, lastPixels, engine.Width, engine.Height);if (collector != null){- ProbeOverlay.Burn(lastPixels, engine.Width, engine.Height, this._job.Probes, collector.Traces, ProbePlaceOn.Field, totalSteps);+ ProbeOverlay.Burn(lastPixels, engine.Width, engine.Height, _job.Probes, collector.Traces, ProbePlaceOn.Field, totalSteps);}result.LastFieldFrame = FrameRenderer.ToBitmap(lastPixels, engine.Width, engine.Height);if (hasIntensity){- FrameRenderer.RenderIntensity(engine, this._job.IntensityLut, (float)this._job.Settings.IntensityBrightness, lastPixels, engine.Width, engine.Height);+ FrameRenderer.RenderIntensity(engine, _job.IntensityLut, (float)_job.Settings.IntensityBrightness, lastPixels, engine.Width, engine.Height);if (collector != null){- ProbeOverlay.Burn(lastPixels, engine.Width, engine.Height, this._job.Probes, collector.Traces, ProbePlaceOn.Intensity, totalSteps);+ ProbeOverlay.Burn(lastPixels, engine.Width, engine.Height, _job.Probes, collector.Traces, ProbePlaceOn.Intensity, totalSteps);}result.LastIntensityFrame = FrameRenderer.ToBitmap(lastPixels, engine.Width, engine.Height);}}catch (Exception){+ // no still frame this time - not fatal, the export buttons just won't have anything to save}try{- engine.Dispose();+ (engine as IDisposable)?.Dispose();}catch (Exception){+ // nothing more can be done}- this._sim = null;- this._collector = null;+ _sim = null;+ _collector = null;}- if (this._job.Image != null)+ if (_job.Image != null){- this._job.Image.Dispose();+ _job.Image.Dispose();}}stopwatch.Stop();result.Elapsed = stopwatch.Elapsed;- this.ProgressChanged?.Invoke(result.StepsDone, this._job.Settings.Steps);- this.Finished?.Invoke(result);+ ProgressChanged?.Invoke(result.StepsDone, _job.Settings.Steps);+ Finished?.Invoke(result);}/// <summary>- /// Opens an H.264 MP4 writer for .mp4 paths, falling back to a Motion JPEG .avi (same name, .avi- /// extension) when the Media Foundation encoder cannot be set up; any partial .mp4 is deleted and- /// the reason is stored in <see cref="SimulationResult.Message"/>. Other extensions always get AVI.+ /// Opens a video file. An .mp4 path is written as H.264 with the encoder of Windows (Media Foundation),+ /// falling back to a Motion JPEG .avi (same name, .avi extension) when that is not possible (no Media+ /// Foundation, size not supported); any partial .mp4 is deleted and the reason is stored in+ /// <see cref="SimulationResult.Message"/>. Other extensions always get AVI./// </summary>/// <param name="filePath">Requested output path; the extension decides the container.</param>/// <param name="w">Frame width in pixels.</param>@@ -498,6 +538,7 @@ namespace _2D_wave_sim_V01}catch (Exception){+ // an empty leftover file does no harm}}result.Message = "MP4 (H.264) video could not be made on this computer (" + ex.Message.Trim() + "). The videos were written as Motion JPEG .avi files instead; play them with VLC.";@@ -510,7 +551,13 @@ namespace _2D_wave_sim_V01/// <summary>Unused leftover; the JPEG quality actually comes from <see cref="SimulationSettings.VideoQuality"/>.</summary>private const long JpegQuality = 90L;- /// <summary>Minimum time between two preview frames, in stopwatch milliseconds (about 30 fps).</summary>+ /// <summary>+ /// Minimum time between two preview frames, in stopwatch milliseconds (about 30 fps). See its use in+ /// <see cref="Run"/> for why this exists: it keeps a GPU engine's readback rate steady and independent of+ /// how fast the UI thread happens to be at displaying the previous one (e.g. with/without the "display+ /// overlay" checkboxes), rather than implicitly riding on <see cref="_previewPending"/> alone. ~30 fps is+ /// already faster than a picture box is usefully watchable at.+ /// </summary>private const long PreviewIntervalMs = 33L;/// <summary>The job to run; its bitmaps are consumed and disposed by the worker.</summary>@@ -528,10 +575,19 @@ namespace _2D_wave_sim_V01/// <summary>Pause gate: set = running, reset = paused. The worker waits on it at the top of each step.</summary>private readonly ManualResetEventSlim _gate;- /// <summary>The live engine, published for <see cref="RenderCurrentFrame"/>; null before creation and after the run ends.</summary>+ /// <summary>+ /// The live engine, set once at the start of <see cref="Run"/> and cleared just before it is disposed at the+ /// end; read from the UI thread (<see cref="RenderCurrentFrame"/>) only while paused, when the worker thread+ /// is parked at <c>_gate.Wait()</c> and is not touching it.+ /// </summary>private IWaveEngine _sim;- /// <summary>The live probe collector (null when the job has no probes or after the run ends); used by <see cref="RenderCurrentFrame"/>.</summary>+ /// <summary>+ /// The probe collector for this run (null when there are no probes, or after the run ends), set alongside+ /// <see cref="_sim"/> so <see cref="RenderCurrentFrame"/> can also burn the probe markers/graphs onto a still+ /// export: the video export loop in <see cref="Run"/> already did this (<see cref="ProbeOverlay.Burn"/>) but+ /// <see cref="RenderCurrentFrame"/> did not, which left probe data out of exported still frames.+ /// </summary>private ProbeCollector _collector;/// <summary>Handler for <see cref="ProgressChanged"/>: steps completed so far and the total step count.</summary>diff --git a/Wave_Dude_2D/SimulationSettings.cs b/Wave_Dude_2D/SimulationSettings.csindex b4df11c..13db241 100644--- a/Wave_Dude_2D/SimulationSettings.cs+++ b/Wave_Dude_2D/SimulationSettings.cs@@ -5,36 +5,52 @@ using System.Globalization;namespace _2D_wave_sim_V01{/// <summary>- /// The "simulation" section of a project: step count, visualisation and export options, and solver- /// parameters. Edited by <c>Form1</c> on the UI thread, persisted through <see cref="ProjectConfig"/> and- /// handed to the runner as a <see cref="Clone"/> inside the <see cref="SimulationJob"/>.+ /// The "simulation" section of a project (Configuration tab): step count, visualisation and export options,+ /// and solver parameters. Edited by <c>Form1</c> on the UI thread, persisted through <see cref="ProjectConfig"/>+ /// and handed to the runner as a <see cref="Clone"/> inside the <see cref="SimulationJob"/>.+ /// A few keys have no control on the screen yet but can be edited in the file: <c>field_brightness</c>,+ /// <c>intensity_brightness</c>, <c>field_black_level</c>, <c>intensity_black_level</c>,+ /// <c>source_frequency_scale</c>, <c>video_fps</c>. The defaults are those of the Python example+ /// (<c>main_curr.py</c>)./// </summary>public sealed class SimulationSettings{- /// <summary>Creates settings with the UI defaults (preview on, export off, 4th-order stencil, CPU engine); <see cref="Steps"/> and <see cref="TimeDecayFactor"/> stay 0.</summary>+ /// <summary>+ /// Creates settings with the defaults for a new project (preview on, export off, 4th-order stencil, CPU+ /// engine). <see cref="Steps"/> and <see cref="TimeDecayFactor"/> deliberately have no software-chosen+ /// default and stay 0: a new project starts at whatever the Designer value of <c>numSimulationSteps</c> /+ /// <c>numTimeDecayFactor</c> is, which <c>StartNewProject</c> (Form1) reads right after creating this+ /// instance. <see cref="DefaultSteps"/> is only the <see cref="FromConfig"/> fallback for a project saved+ /// before the key existed.+ /// </summary>public SimulationSettings(){- this.VisualizeEvery = 2;- this.ExportField = false;- this.ExportIntensity = false;- this.PreviewField = true;- this.PreviewIntensity = true;- this.FieldColorScheme = "Default_Field";- this.IntensityColorScheme = "Default_intensity";- this.FieldBrightness = 30.0;- this.IntensityBrightness = 30.0;- this.FieldBlackLevel = -0.05;- this.IntensityBlackLevel = 0.0;- this.SourceFrequencyScale = 2.0;- this.VideoFps = 60;- this.VideoQuality = DefaultVideoQuality;- this.UseGpu = false;- this.Use4thOrderLaplacian = true;- this.WaveSpeedC = 1.0;- this.IntensityScale = 1.0;+ VisualizeEvery = 2;+ ExportField = false;+ ExportIntensity = false;+ PreviewField = true;+ PreviewIntensity = true;+ FieldColorScheme = "Default_Field";+ IntensityColorScheme = "Default_intensity";+ FieldBrightness = 30.0;+ IntensityBrightness = 30.0;+ FieldBlackLevel = -0.05;+ IntensityBlackLevel = 0.0;+ SourceFrequencyScale = 2.0;+ VideoFps = 60;+ VideoQuality = DefaultVideoQuality;+ UseGpu = false;+ Use4thOrderLaplacian = true;+ WaveSpeedC = 1.0;+ IntensityScale = 1.0;}- /// <summary>Total number of simulation steps to run.</summary>+ /// <summary>+ /// Total number of simulation steps to run. No software-chosen default of its own, the same as+ /// <see cref="TimeDecayFactor"/>: a new project starts at whatever <c>numSimulationSteps</c>' own Designer+ /// value is (see <c>StartNewProject</c>'s <c>new SimulationSettings()</c>); <see cref="DefaultSteps"/> is+ /// only the fallback for an existing project saved before "steps" existed (<see cref="FromConfig"/>).+ /// </summary>public int Steps { get; set; }/// <summary>Render, export and collect probe data every this many steps.</summary>@@ -52,16 +68,25 @@ namespace _2D_wave_sim_V01/// <summary>Whether to show the intensity in the live preview.</summary>public bool PreviewIntensity { get; set; }- /// <summary>Name of the <see cref="ColorScheme"/> used for field frames.</summary>+ /// <summary>+ /// Name of the <see cref="ColorScheme"/> used for field frames (empty: grey levels). The name a new project+ /// starts with is selected by <c>FillSchemeCombo</c> (Form1) only when a scheme with that exact name+ /// (case-insensitive) and matching <see cref="ColorScheme.SchemeType"/> exists; otherwise the combo just+ /// shows nothing selected, the same as for any other scheme name that is not found.+ /// </summary>public string FieldColorScheme { get; set; }- /// <summary>Name of the <see cref="ColorScheme"/> used for intensity frames.</summary>+ /// <summary>Name of the <see cref="ColorScheme"/> used for intensity frames (empty: grey levels); see <see cref="FieldColorScheme"/> for how the name is matched.</summary>public string IntensityColorScheme { get; set; }- /// <summary>Display gain for field frames (multiplies the field value before the colour lookup).</summary>+ /// <summary>+ /// Display gain for field frames (multiplies the field value before the colour lookup). This is+ /// <c>render_field(7)</c> in the Python example; 30.0 here is high enough to see a single source in the+ /// simulation, which is what <c>numFieldScaling</c>'s own Designer default also shows for a new source.+ /// </summary>public double FieldBrightness { get; set; }- /// <summary>Display gain for intensity frames (multiplies the square root of the intensity before the colour lookup).</summary>+ /// <summary>Display gain for intensity frames (multiplies the square root of the intensity before the colour lookup); <c>render_intensity(7)</c> in the Python example, see <see cref="FieldBrightness"/>.</summary>public double IntensityBrightness { get; set; }/// <summary>Offset baked into the field colour LUT (the "offset" spinner in the UI); see <see cref="ColorLut.Build"/>.</summary>@@ -70,34 +95,85 @@ namespace _2D_wave_sim_V01/// <summary>Offset baked into the intensity colour LUT (the "offset" spinner in the UI); see <see cref="ColorLut.Build"/>.</summary>public double IntensityBlackLevel { get; set; }- /// <summary>Multiplier in the source level-to-frequency mapping: angular frequency = level/255 × 0.5 × this, in radians per step.</summary>+ /// <summary>Multiplies the frequency of the sources that come from the green channel of the scene image (and of the object sources, which use the same level scale): angular frequency = level/255 × 0.5 × this, in radians per step.</summary>public double SourceFrequencyScale { get; set; }/// <summary>Frame rate of the exported videos.</summary>public int VideoFps { get; set; }- /// <summary>Encoder quality of the exported videos, 1..100.</summary>+ /// <summary>Encoder quality of the exported videos, 1 (small files) to 100 (best picture, large files).</summary>public int VideoQuality { get; set; }- /// <summary>Prefer the OpenCL engine; the CPU engine is used when no usable GPU is found.</summary>+ /// <summary>Run the simulation on the graphics card (OpenCL); falls back to the processor when that is not possible.</summary>public bool UseGpu { get; set; }- /// <summary>Use the 4th-order Laplacian stencil (with sub-stepping) instead of the 9-point one.</summary>+ /// <summary>+ /// Use a 4th-order accurate discrete Laplacian (a 5-point "cross" in each of x and y, reaching 2 cells away)+ /// instead of the standard 3x3 kernel, everywhere it is safe to (see <c>WaveSimulator.UpdateField</c> /+ /// <c>GpuWaveSimulator.KernelSource</c>; the outermost ring of the domain still falls back to the 3x3 kernel,+ /// since it does not have 2 cells of margin). This reduces numerical dispersion (short wavelengths,+ /// under-resolved by the grid, are otherwise slowed down relative to long ones; see <see cref="WaveSpeedC"/>,+ /// whose legacy fallback is itself a symptom of this) at the cost of roughly twice the memory reads per step.+ /// On by default for a new project (the constructor). An existing project saved before this property existed+ /// still loads as Off (<see cref="FromConfig"/>'s own separate, hardcoded fallback), so it keeps its exact+ /// previous behaviour instead of silently picking up the new project default.+ /// </summary>public bool Use4thOrderLaplacian { get; set; }/// <summary>- /// Nominal wave speed c in canvas pixels per step, used only to estimate a source's wavelength in the UI- /// (λ = c / frequency); the engines derive the actual speed from the refractive index map.+ /// The propagation speed of waves through the medium, in canvas pixels per step (λ = c / frequency). Set+ /// from the "Set c-value" entry on the File menu. This is only used to estimate and display a source's+ /// wavelength (<c>lblLambdaIs</c> on the Sources tab); it does not affect the simulation itself, which+ /// derives the real, per-pixel wave speed from the scene's refractive index (the red channel of the scene+ /// image; see <c>SceneData.C2</c>) instead, and can vary from pixel to pixel while this single value cannot.+ /// A new project starts at 1.0, the solver's own default speed for a uniform medium (the constructor). An+ /// existing project saved before this field existed still loads at 0.563 instead (<see cref="FromConfig"/>'s+ /// own separate, hardcoded fallback): that value was found experimentally to be the correct one at around+ /// a source frequency of 100, and is kept only so such a project's displayed wavelength estimate does not+ /// change out from under it. Like every other property here, this belongs to one project's settings and is+ /// saved/loaded with it (<c>wave_speed_c</c>); it is not a global setting, so different projects can each+ /// keep their own value./// </summary>public double WaveSpeedC { get; set; }- /// <summary>Intensity averaging time factor: the engines average over timeDecayFactor × 100 / (lowest source level) steps.</summary>+ /// <summary>+ /// "Intensity decay factor" (Configuration tab, <c>numTimeDecayFactor</c>): the intensity shown/exported is+ /// not the raw field², it is an exponential running average of it (see <c>WaveSimulator.UpdateField</c> /+ /// <c>GpuWaveSimulator.KernelSource</c>), because a source oscillates every step and the raw squared+ /// amplitude would flicker at twice the source frequency instead of showing a steady intensity. The+ /// averaging needs a time constant of at least a few periods of the slowest active source, or that flicker+ /// "prints through"; a fixed time constant long enough for a low-frequency source is unnecessarily long for+ /// a high-frequency one and shows as a visible trail behind anything that moves. Both engines therefore+ /// scale the time constant inversely with the frequency of the slowest active source (image or object)+ /// instead of using one fixed value, and this property is the number of steps that time constant works out+ /// to at a nominal medium source (green level <c>WaveSimulator.NominalDecayLevel</c>, 100). Raising it+ /// lengthens the trail on every source (helps a low-frequency source avoid print-through); lowering it+ /// shortens the trail (helps a high-frequency source look crisp) at the cost of print-through if a+ /// low-frequency source is also present in the same scene.+ /// This class does not itself pick a number for a new project; that would just be a second, competing+ /// default fighting the one already set on <c>numTimeDecayFactor</c> in the Designer. <c>StartNewProject</c>+ /// (Form1) instead reads the control's own value right after creating a new instance, and that is the only+ /// place a new project's starting value is decided; changing it means changing <c>numTimeDecayFactor</c>'s+ /// Value in the Designer. The 10.0 in <see cref="FromConfig"/> is only the fallback for a project saved+ /// before the key existed.+ /// </summary>public double TimeDecayFactor { get; set; }- /// <summary>Multiplier applied to the intensity values produced by the engine.</summary>+ /// <summary>+ /// A plain multiplier on the tracked intensity itself (not just how it is displayed): both engines apply it+ /// to every intensity value they compute, so it changes the actual numbers in the preview, the exported+ /// videos, the probe data and any exported files, unlike <see cref="FieldBrightness"/> /+ /// <see cref="IntensityBrightness"/>, which only scale how an image is drawn from the numbers and leave+ /// the numbers themselves alone. It exists because, with the filtering <see cref="TimeDecayFactor"/>+ /// controls, the raw intensity ends up landing around 1e-5 for typical scenes (an inconvenient scale for an+ /// axis or a data file), and the right multiplier to bring that into a convenient range depends on the+ /// source amplitudes and pulse shapes actually used, which this class has no way to predict. The default+ /// of 1.0 leaves the raw numbers exactly as computed; <c>numIntensityScale</c> (Configuration tab) lets the+ /// value be tuned by eye once the actual scale in use is visible.+ /// </summary>public double IntensityScale { get; set; }- /// <summary>Shallow copy; all members are value types or immutable strings, so the copy is independent.</summary>+ /// <summary>Shallow copy that a running simulation can keep while the user goes on editing; all members are value types or immutable strings, so the copy is independent.</summary>public SimulationSettings Clone(){return (SimulationSettings)base.MemberwiseClone();@@ -108,8 +184,12 @@ namespace _2D_wave_sim_V01/// back to per-key defaults; a missing section yields a default instance./// </summary>/// <remarks>- /// The per-key fallbacks differ from the constructor defaults for some keys (steps 2500 vs 0,- /// use_4th_order_laplacian false vs true, wave_speed_c 0.563 vs 1.0, time_decay_factor 10 vs 0).+ /// The per-key fallbacks are deliberately separate from the constructor defaults and differ for four keys+ /// (steps 2500 vs 0, use_4th_order_laplacian false vs true, wave_speed_c 0.563 vs 1.0, time_decay_factor+ /// 10 vs 0): an existing project saved before a key existed keeps its exact previous behaviour, while a new+ /// project takes the constructor / Designer values via <c>StartNewProject</c> (Form1). See+ /// <see cref="Steps"/>, <see cref="Use4thOrderLaplacian"/>, <see cref="WaveSpeedC"/> and+ /// <see cref="TimeDecayFactor"/> for the reasoning behind each./// </remarks>public static SimulationSettings FromConfig(ProjectConfig config){@@ -146,26 +226,26 @@ namespace _2D_wave_sim_V01public void ToConfig(ProjectConfig config){Dictionary<string, object> section = config.GetSection(SectionName);- section["steps"] = this.Steps;- section["visualize_every"] = this.VisualizeEvery;- section["export_field"] = this.ExportField;- section["export_intensity"] = this.ExportIntensity;- section["preview_field"] = this.PreviewField;- section["preview_intensity"] = this.PreviewIntensity;- section["field_color_scheme"] = this.FieldColorScheme;- section["intensity_color_scheme"] = this.IntensityColorScheme;- section["field_brightness"] = this.FieldBrightness;- section["intensity_brightness"] = this.IntensityBrightness;- section["field_black_level"] = this.FieldBlackLevel;- section["intensity_black_level"] = this.IntensityBlackLevel;- section["source_frequency_scale"] = this.SourceFrequencyScale;- section["video_fps"] = this.VideoFps;- section["video_quality"] = this.VideoQuality;- section["use_gpu"] = this.UseGpu;- section["use_4th_order_laplacian"] = this.Use4thOrderLaplacian;- section["wave_speed_c"] = this.WaveSpeedC;- section["time_decay_factor"] = this.TimeDecayFactor;- section["intensity_scale"] = this.IntensityScale;+ section["steps"] = Steps;+ section["visualize_every"] = VisualizeEvery;+ section["export_field"] = ExportField;+ section["export_intensity"] = ExportIntensity;+ section["preview_field"] = PreviewField;+ section["preview_intensity"] = PreviewIntensity;+ section["field_color_scheme"] = FieldColorScheme;+ section["intensity_color_scheme"] = IntensityColorScheme;+ section["field_brightness"] = FieldBrightness;+ section["intensity_brightness"] = IntensityBrightness;+ section["field_black_level"] = FieldBlackLevel;+ section["intensity_black_level"] = IntensityBlackLevel;+ section["source_frequency_scale"] = SourceFrequencyScale;+ section["video_fps"] = VideoFps;+ section["video_quality"] = VideoQuality;+ section["use_gpu"] = UseGpu;+ section["use_4th_order_laplacian"] = Use4thOrderLaplacian;+ section["wave_speed_c"] = WaveSpeedC;+ section["time_decay_factor"] = TimeDecayFactor;+ section["intensity_scale"] = IntensityScale;}/// <summary>The value under <paramref name="key"/> converted to text (invariant culture), or the fallback when absent or null.</summary>@@ -209,6 +289,7 @@ namespace _2D_wave_sim_V01}catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException){+ // use the fallback}}return fallback;@@ -233,6 +314,7 @@ namespace _2D_wave_sim_V01}catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException){+ // use the fallback}}return fallback;@@ -241,7 +323,12 @@ namespace _2D_wave_sim_V01/// <summary>Name of this section in the project file.</summary>public const string SectionName = "simulation";- /// <summary>Fallback for <see cref="Steps"/> when the key is missing from a project file.</summary>+ /// <summary>+ /// Only the <see cref="FromConfig"/> fallback for an existing project saved before "steps" existed.+ /// <see cref="Steps"/> itself has no software-chosen default of its own, the same as+ /// <see cref="TimeDecayFactor"/>: a new project starts at whatever <c>numSimulationSteps</c>' own Designer+ /// value is (see <c>StartNewProject</c>'s <c>new SimulationSettings()</c>).+ /// </summary>public const int DefaultSteps = 2500;/// <summary>Largest accepted <see cref="Steps"/>.</summary>diff --git a/Wave_Dude_2D/SourceCompositeMode.cs b/Wave_Dude_2D/SourceCompositeMode.csindex 0d4676a..2a17493 100644--- a/Wave_Dude_2D/SourceCompositeMode.cs+++ b/Wave_Dude_2D/SourceCompositeMode.cs@@ -3,15 +3,15 @@ using System;namespace _2D_wave_sim_V01{/// <summary>- /// How the elements of a <see cref="SourceMainType.Composite"/> array derive their properties- /// from the single-source settings. Ignored for simple sources. Stored in the project as- /// <c>"inherit"</c> / <c>"randomize"</c>.+ /// How the elements of a <see cref="SourceMainType.Composite"/> array get their+ /// frequency/phase/off-width/position: all the same as the single source, or randomised around it.+ /// Ignored for simple sources. Stored in the project as <c>"inherit"</c> / <c>"randomize"</c>./// </summary>public enum SourceCompositeMode{/// <summary>Every element is an exact copy of the single-source settings; only its position differs.</summary>- InheritFromSingle,+ InheritFromSingle = 0,/// <summary>Elements inherit the settings, and each enabled "randomize" option (frequency, phase, off-width, position) adds an independent random offset per element when the elements are generated.</summary>- InheritAndRandomize+ InheritAndRandomize = 1}}diff --git a/Wave_Dude_2D/SourceElement.cs b/Wave_Dude_2D/SourceElement.csindex 34158ce..873fb43 100644--- a/Wave_Dude_2D/SourceElement.cs+++ b/Wave_Dude_2D/SourceElement.cs@@ -10,23 +10,24 @@ namespace _2D_wave_sim_V01/// <c>SimulationJob.ObjectSources</c>, where <c>WaveSimulator</c> / <c>GpuWaveSimulator</c>/// read it from the <c>SimulationRunner</c> worker thread. The engines never write to it/// (they keep their own per-element off-width state), so it must simply not be mutated- /// while a run is in progress.+ /// while a run is in progress. Generating rolls the randomisation once, so a run is+ /// reproducible: the engine never re-randomises the elements themselves./// </summary>public sealed class SourceElement{/// <summary>Creates an element at (0, 0) with the fallback values: level 100, amplitude 0.5, no phase, continuous, 10-cycle on/off widths, never detached.</summary>public SourceElement(){- this.Level = 100;- this.Amplitude = 0.5;- this.PhaseRad = 0.0;- this.Mode = SourceMode.Continuous;- this.PulseShape = SourcePulseShape.Gaussian;- this.OnWidthCycles = 10;- this.OffWidthCycles = 10;- this.OffWidthBase = 10;- this.RandomizeOffWidthAmount = 0;- this.DetachAfterStep = -1;+ Level = 100;+ Amplitude = 0.5;+ PhaseRad = 0.0;+ Mode = SourceMode.Continuous;+ PulseShape = SourcePulseShape.Gaussian;+ OnWidthCycles = 10;+ OffWidthCycles = 10;+ OffWidthBase = 10;+ RandomizeOffWidthAmount = 0;+ DetachAfterStep = -1;}/// <summary>X position in canvas pixels (0 = left edge). Elements outside the canvas are dropped by the engines.</summary>@@ -72,7 +73,12 @@ namespace _2D_wave_sim_V01/// <summary>Half-range in cycles of the per-period random off-width offset (gap = max(1, OffWidthBase +/- amount)); 0 keeps <see cref="OffWidthCycles"/> fixed.</summary>public int RandomizeOffWidthAmount { get; set; }- /// <summary>Simulation step after which the source is switched off, fading out linearly over <see cref="DetachRampSteps"/> steps; -1 means it stays on for the whole run.</summary>+ /// <summary>+ /// Simulation step at which this element stops driving the field (releasing its hold on it, so it no+ /// longer diffracts waves passing through its position), fading out linearly over+ /// <see cref="DetachRampSteps"/> steps; -1 means it stays on for the whole run. Copied from the parent+ /// <see cref="SourceSettings.DetachSource"/> / <see cref="SourceSettings.DetachAfterSteps"/> at generate time.+ /// </summary>public int DetachAfterStep { get; set; }/// <summary>Shallow copy; sufficient because every property is a value type.</summary>@@ -82,9 +88,11 @@ namespace _2D_wave_sim_V01}/// <summary>- /// Number of steps over which a detached source fades from full amplitude to zero.- /// Documents the value the engines use; both <c>WaveSimulator</c> and the OpenCL kernel- /// currently hard-code 30 rather than referencing this constant.+ /// Number of simulation steps over which a detaching element's drive is faded out (linearly, down to 0)+ /// rather than cut instantly at <see cref="DetachAfterStep"/>: an abrupt cutoff otherwise leaves a small+ /// kink in the forcing at that point, which can ring. Shared by both engines+ /// (<c>WaveSimulator.ApplySources</c> and the <c>apply_object_sources</c> kernel in+ /// <c>GpuWaveSimulator</c>, which splices it into the kernel text), so the two stay in exact agreement./// </summary>public const int DetachRampSteps = 30;}diff --git a/Wave_Dude_2D/SourceMainType.cs b/Wave_Dude_2D/SourceMainType.csindex 809ea9a..941609f 100644--- a/Wave_Dude_2D/SourceMainType.cs+++ b/Wave_Dude_2D/SourceMainType.cs@@ -3,15 +3,16 @@ using System;namespace _2D_wave_sim_V01{/// <summary>- /// Whether a <see cref="SourceSettings"/> entry describes one point source or a rectangular- /// array of identical point sources. Selected with the "main type" combo box on the source- /// tab and stored in the project as <c>"single"</c> / <c>"composite"</c>.+ /// Whether a <see cref="SourceSettings"/> entry describes one point source (or line, in a future version)+ /// or a rectangular array of identical point sources. Selected with the "main type" combo box on the source+ /// tab (the numeric values are the combo-box indices) and stored in the project as <c>"single"</c> /+ /// <c>"composite"</c>./// </summary>public enum SourceMainType{- /// <summary>A single point source at (PosX, PosY); generates exactly one <see cref="SourceElement"/>.</summary>- Simple,+ /// <summary>A single point source at (PosX, PosY); generates exactly one <see cref="SourceElement"/>. Named Simple (not Single) because Single is a reserved VB keyword (the floating-point type) in the original source.</summary>+ Simple = 0,/// <summary>An ArraySizeX x ArraySizeY grid of point sources centred on (PosX, PosY), optionally randomised per element.</summary>- Composite+ Composite = 1}}diff --git a/Wave_Dude_2D/SourceMode.cs b/Wave_Dude_2D/SourceMode.csindex 34db81c..52b351c 100644--- a/Wave_Dude_2D/SourceMode.cs+++ b/Wave_Dude_2D/SourceMode.cs@@ -3,15 +3,16 @@ using System;namespace _2D_wave_sim_V01{/// <summary>- /// Time behaviour of a point source. Chosen with the mode radio buttons on the source tab,+ /// Time behaviour of a point source (or of an element of a composite source): always on, or switching on+ /// and off in cycles of its own frequency. Chosen with the mode radio buttons on the source tab,/// copied into every generated <see cref="SourceElement"/> and evaluated by the wave engines/// on each simulation step./// </summary>public enum SourceMode{/// <summary>The source emits a steady sine wave for the whole run (envelope is always 1).</summary>- Continuous,+ Continuous = 0,/// <summary>The sine wave is gated by a repeating on/off envelope whose shape is a <see cref="SourcePulseShape"/> and whose on and off lengths are given in cycles.</summary>- Pulsed+ Pulsed = 1}}diff --git a/Wave_Dude_2D/SourcePulseShape.cs b/Wave_Dude_2D/SourcePulseShape.csindex 14eaade..2f6ed30 100644--- a/Wave_Dude_2D/SourcePulseShape.cs+++ b/Wave_Dude_2D/SourcePulseShape.cs@@ -9,8 +9,8 @@ namespace _2D_wave_sim_V01public enum SourcePulseShape{/// <summary>Gaussian bell centred in the on-window; its sigma is one sixth of the on-width, so the burst is essentially zero at both edges.</summary>- Gaussian,+ Gaussian = 0,/// <summary>Flat-topped burst with smoothed rising and falling edges that spans the whole on-width.</summary>- SmoothedSquare+ SmoothedSquare = 1}}diff --git a/Wave_Dude_2D/SourceSettings.cs b/Wave_Dude_2D/SourceSettings.csindex 0799095..d3d42f3 100644--- a/Wave_Dude_2D/SourceSettings.cs+++ b/Wave_Dude_2D/SourceSettings.cs@@ -6,12 +6,16 @@ using System.Globalization;namespace _2D_wave_sim_V01{/// <summary>- /// User-editable description of one wave source (single or composite array) plus the- /// generated <see cref="SourceElement"/> list that the simulation actually consumes.- /// Edited on the source tab of <c>Form1</c> (UI thread only), persisted in the- /// <see cref="SectionName"/> section of the project config, and expanded into elements by- /// <see cref="GenerateElements"/> whenever the user saves the source. Units are the ones- /// shown in the UI: positions in canvas pixels, frequency as a 1..255 level, amplitude in+ /// User-editable description of one wave source (single point source or composite array of point sources+ /// built from the same base parameters, optionally randomised) plus the generated+ /// <see cref="SourceElement"/> list that the simulation actually consumes.+ /// Edited on the source tab of <c>Form1</c> (UI thread only) and persisted in the+ /// <see cref="SectionName"/> section of the project config. "Generate composite source" resolves the+ /// current parameters (and, for a composite source, a fresh random draw) into a fixed list of elements via+ /// <see cref="GenerateElements"/>, which is what the simulation runs; "Save source" keeps both the+ /// authoring parameters (so the source can be reopened and edited or regenerated) and that generated list+ /// (so a saved project runs exactly what was generated, even before it is regenerated again). Units are the+ /// ones shown in the UI: positions in canvas pixels, frequency as a 1..255 level, amplitude in/// percent, phase in degrees, pulse widths in cycles, detach time in simulation steps./// </summary>public sealed class SourceSettings@@ -19,35 +23,35 @@ namespace _2D_wave_sim_V01/// <summary>Creates a source with the editor defaults: "Source 1", simple, continuous Gaussian at (100, 100) but not yet positioned, frequency level 100, 100 % amplitude, 10-cycle widths, 1x1 array with 10 px spacing, nothing randomised, no elements.</summary>public SourceSettings(){- this.Name = "Source 1";- this.MainType = SourceMainType.Simple;- this.PosX = 100;- this.PosY = 100;- this.HasPosition = false;- this.SourceOn = true;- this.DetachSource = false;- this.DetachAfterSteps = 1000;- this.Frequency = 100;- this.Amplitude = 100;- this.PhaseDeg = 0;- this.Mode = SourceMode.Continuous;- this.PulseShape = SourcePulseShape.Gaussian;- this.PulseWidthCycles = 10;- this.OffStateCycles = 10;- this.ArraySizeX = 1;- this.ArraySizeY = 1;- this.SpacingX = 10;- this.SpacingY = 10;- this.CompositeMode = SourceCompositeMode.InheritFromSingle;- this.RandomizeFrequency = false;- this.RandomizeFrequencyAmount = 0;- this.RandomizePhase = false;- this.RandomizePhaseAmount = 0;- this.RandomizeOffWidth = false;- this.RandomizeOffWidthAmount = 0;- this.RandomizePosition = false;- this.RandomizePositionAmount = 0;- this.Elements = new List<SourceElement>();+ Name = "Source 1";+ MainType = SourceMainType.Simple;+ PosX = 100;+ PosY = 100;+ HasPosition = false;+ SourceOn = true;+ DetachSource = false;+ DetachAfterSteps = 1000;+ Frequency = 100;+ Amplitude = 100;+ PhaseDeg = 0;+ Mode = SourceMode.Continuous;+ PulseShape = SourcePulseShape.Gaussian;+ PulseWidthCycles = 10;+ OffStateCycles = 10;+ ArraySizeX = 1;+ ArraySizeY = 1;+ SpacingX = 10;+ SpacingY = 10;+ CompositeMode = SourceCompositeMode.InheritFromSingle;+ RandomizeFrequency = false;+ RandomizeFrequencyAmount = 0;+ RandomizePhase = false;+ RandomizePhaseAmount = 0;+ RandomizeOffWidth = false;+ RandomizeOffWidthAmount = 0;+ RandomizePosition = false;+ RandomizePositionAmount = 0;+ Elements = new List<SourceElement>();}/// <summary>Display name shown in the source list and next to the marker on the scene picture; must be non-blank to save.</summary>@@ -56,26 +60,38 @@ namespace _2D_wave_sim_V01/// <summary>Single point source or composite array.</summary>public SourceMainType MainType { get; set; }- /// <summary>X position in canvas pixels of the source, or of the array centre for a composite source.</summary>+ /// <summary>X position in canvas pixels of the source, or of the array centre for a composite source. Only meaningful once <see cref="HasPosition"/> is true; until then it is just the unset default and the Sources tab must not draw a marker for it.</summary>public int PosX { get; set; }- /// <summary>Y position in canvas pixels of the source, or of the array centre for a composite source.</summary>+ /// <summary>Y position in canvas pixels of the source, or of the array centre for a composite source; see <see cref="PosX"/>.</summary>public int PosY { get; set; }/// <summary>/// True once the user has placed the source (by picking on the picture or editing the- /// position inputs); only sources with a position get a marker drawn on the scene picture.- /// Defaults to false for a new source but to true when loaded from a project without the key.+ /// position inputs) rather than still holding the default; only sources with a position get+ /// a marker drawn on the scene picture. Defaults to false for a new source but to true when+ /// loaded from a project saved before this flag existed (see <see cref="FromDictionary"/>),+ /// since its sources were positioned under the old rules./// </summary>public bool HasPosition { get; set; }- /// <summary>Whether the source takes part in simulation runs; disabled sources are listed in grey and skipped.</summary>+ /// <summary>+ /// Whether the source interacts with the simulation at all; a new source starts on. Switching it off+ /// keeps every parameter (it can still be edited, and switched back on) but the source takes no part+ /// in a run: it is listed in grey and <c>SourcesForRun</c> leaves it out entirely, so it neither drives+ /// the field nor gets in the way of waves passing through its position.+ /// </summary>public bool SourceOn { get; set; }- /// <summary>Whether the source is switched off during the run after <see cref="DetachAfterSteps"/>.</summary>+ /// <summary>+ /// When true, the source stops driving the field after <see cref="DetachAfterSteps"/> simulation steps+ /// (it runs normally up to that point). A source that keeps driving the field also holds it at a fixed+ /// value there, which diffracts waves that later pass through that point; detaching releases that hold+ /// once the source has done its job, so the field becomes free of it again for the rest of the run.+ /// </summary>public bool DetachSource { get; set; }- /// <summary>Simulation step at which the source starts fading out when <see cref="DetachSource"/> is set; 0 or greater.</summary>+ /// <summary>Simulation step (0-based) at which the source detaches and starts fading out (over <see cref="SourceElement.DetachRampSteps"/> steps) when <see cref="DetachSource"/> is set; 0 or greater.</summary>public int DetachAfterSteps { get; set; }/// <summary>@@ -85,7 +101,7 @@ namespace _2D_wave_sim_V01/// </summary>public int Frequency { get; set; }- /// <summary>Amplitude in percent, 0..100; becomes 0..1 on the element.</summary>+ /// <summary>Amplitude in percent of the source amplitude, 0..100; becomes 0..1 on the element. 100 matches <c>numAmplitude</c>'s own Designer default for a new source.</summary>public int Amplitude { get; set; }/// <summary>Phase offset in degrees, -180..180; converted to radians on the element.</summary>@@ -154,7 +170,7 @@ namespace _2D_wave_sim_V01{SourceSettings copy = (SourceSettings)base.MemberwiseClone();copy.Elements = new List<SourceElement>();- foreach (SourceElement element in this.Elements)+ foreach (SourceElement element in Elements){copy.Elements.Add(element.Clone());}@@ -168,49 +184,49 @@ namespace _2D_wave_sim_V01/// </summary>public void Normalize(){- if (this.Frequency < 1)+ if (Frequency < 1){- this.Frequency = 1;+ Frequency = 1;}- if (this.Frequency > 255)+ if (Frequency > 255){- this.Frequency = 255;+ Frequency = 255;}- if (this.Amplitude < 0)+ if (Amplitude < 0){- this.Amplitude = 0;+ Amplitude = 0;}- if (this.Amplitude > 100)+ if (Amplitude > 100){- this.Amplitude = 100;+ Amplitude = 100;}- if (this.PhaseDeg < -180)+ if (PhaseDeg < -180){- this.PhaseDeg = -180;+ PhaseDeg = -180;}- if (this.PhaseDeg > 180)+ if (PhaseDeg > 180){- this.PhaseDeg = 180;+ PhaseDeg = 180;}- if (this.PulseWidthCycles < 1)+ if (PulseWidthCycles < 1){- this.PulseWidthCycles = 1;+ PulseWidthCycles = 1;}- if (this.OffStateCycles < 1)+ if (OffStateCycles < 1){- this.OffStateCycles = 1;+ OffStateCycles = 1;}- if (this.ArraySizeX < 1)+ if (ArraySizeX < 1){- this.ArraySizeX = 1;+ ArraySizeX = 1;}- if (this.ArraySizeY < 1)+ if (ArraySizeY < 1){- this.ArraySizeY = 1;+ ArraySizeY = 1;}- if (this.DetachAfterSteps < 0)+ if (DetachAfterSteps < 0){- this.DetachAfterSteps = 0;+ DetachAfterSteps = 0;}}@@ -228,49 +244,49 @@ namespace _2D_wave_sim_V01/// <param name="rng">Random generator for the per-element offsets; may be any instance when nothing is randomised.</param>public void GenerateElements(Random rng){- this.Normalize();+ Normalize();List<SourceElement> elements = new List<SourceElement>();- if (this.MainType == SourceMainType.Simple)+ if (MainType == SourceMainType.Simple){- elements.Add(this.MakeBaseElement(this.PosX, this.PosY));+ elements.Add(MakeBaseElement(PosX, PosY));}else{- int arraySizeX = this.ArraySizeX;- int arraySizeY = this.ArraySizeY;- bool randomize = this.CompositeMode == SourceCompositeMode.InheritAndRandomize;- for (int i = 0; i < arraySizeY; i++)+ int cols = ArraySizeX;+ int rows = ArraySizeY;+ bool randomize = CompositeMode == SourceCompositeMode.InheritAndRandomize;+ for (int row = 0; row < rows; row++){- for (int j = 0; j < arraySizeX; j++)+ for (int col = 0; col < cols; col++){- // Grid is centred on (PosX, PosY); with an even size the centre falls between two elements.- int x = this.PosX + (int)Math.Round((j - (arraySizeX - 1) / 2.0) * this.SpacingX);- int y = this.PosY + (int)Math.Round((i - (arraySizeY - 1) / 2.0) * this.SpacingY);- if (randomize && this.RandomizePosition && this.RandomizePositionAmount > 0)+ // The array is centred on (PosX, PosY), not anchored at a corner; with an even size the centre falls between two elements.+ int x = PosX + (int)Math.Round((col - (cols - 1) / 2.0) * SpacingX);+ int y = PosY + (int)Math.Round((row - (rows - 1) / 2.0) * SpacingY);+ if (randomize && RandomizePosition && RandomizePositionAmount > 0){- x += SourceSettings.RandomInt(rng, this.RandomizePositionAmount);- y += SourceSettings.RandomInt(rng, this.RandomizePositionAmount);+ x += SourceSettings.RandomInt(rng, RandomizePositionAmount);+ y += SourceSettings.RandomInt(rng, RandomizePositionAmount);}- SourceElement element = this.MakeBaseElement(x, y);- if (randomize && this.RandomizeFrequency && this.RandomizeFrequencyAmount > 0)+ SourceElement element = MakeBaseElement(x, y);+ if (randomize && RandomizeFrequency && RandomizeFrequencyAmount > 0){- element.Level = SourceSettings.Clamp(this.Frequency + SourceSettings.RandomInt(rng, this.RandomizeFrequencyAmount), 1, 255);+ element.Level = SourceSettings.Clamp(Frequency + SourceSettings.RandomInt(rng, RandomizeFrequencyAmount), 1, 255);}- if (randomize && this.RandomizePhase && this.RandomizePhaseAmount > 0)+ if (randomize && RandomizePhase && RandomizePhaseAmount > 0){- int phaseDeg = SourceSettings.Clamp(this.PhaseDeg + SourceSettings.RandomInt(rng, this.RandomizePhaseAmount), -180, 180);+ int phaseDeg = SourceSettings.Clamp(PhaseDeg + SourceSettings.RandomInt(rng, RandomizePhaseAmount), -180, 180);element.PhaseRad = phaseDeg * Math.PI / 180.0;}- if (randomize && this.RandomizeOffWidth && this.RandomizeOffWidthAmount > 0)+ if (randomize && RandomizeOffWidth && RandomizeOffWidthAmount > 0){- element.OffWidthCycles = Math.Max(1, this.OffStateCycles + SourceSettings.RandomInt(rng, this.RandomizeOffWidthAmount));- element.RandomizeOffWidthAmount = this.RandomizeOffWidthAmount;+ element.OffWidthCycles = Math.Max(1, OffStateCycles + SourceSettings.RandomInt(rng, RandomizeOffWidthAmount));+ element.RandomizeOffWidthAmount = RandomizeOffWidthAmount;}elements.Add(element);}}}- this.Elements = elements;+ Elements = elements;}/// <summary>@@ -284,16 +300,16 @@ namespace _2D_wave_sim_V01{PosX = x,PosY = y,- Level = this.Frequency,- Amplitude = this.Amplitude / 100.0,- PhaseRad = this.PhaseDeg * Math.PI / 180.0,- Mode = this.Mode,- PulseShape = this.PulseShape,- OnWidthCycles = this.PulseWidthCycles,- OffWidthCycles = this.OffStateCycles,- OffWidthBase = this.OffStateCycles,+ Level = Frequency,+ Amplitude = Amplitude / 100.0,+ PhaseRad = PhaseDeg * Math.PI / 180.0,+ Mode = Mode,+ PulseShape = PulseShape,+ OnWidthCycles = PulseWidthCycles,+ OffWidthCycles = OffStateCycles,+ OffWidthBase = OffStateCycles,RandomizeOffWidthAmount = 0,- DetachAfterStep = this.DetachSource ? this.DetachAfterSteps : -1+ DetachAfterStep = DetachSource ? DetachAfterSteps : -1};}@@ -360,36 +376,36 @@ namespace _2D_wave_sim_V01private Dictionary<string, object> ToDictionary(){Dictionary<string, object> data = new Dictionary<string, object>();- data["name"] = this.Name;- data["main_type"] = ((this.MainType == SourceMainType.Composite) ? "composite" : "single");- data["x"] = this.PosX;- data["y"] = this.PosY;- data["has_position"] = this.HasPosition;- data["source_on"] = this.SourceOn;- data["detach_source"] = this.DetachSource;- data["detach_after_steps"] = this.DetachAfterSteps;- data["frequency"] = this.Frequency;- data["amplitude"] = this.Amplitude;- data["phase_deg"] = this.PhaseDeg;- data["mode"] = ((this.Mode == SourceMode.Pulsed) ? "pulsed" : "continuous");- data["pulse_shape"] = ((this.PulseShape == SourcePulseShape.SmoothedSquare) ? "smoothed_square" : "gaussian");- data["pulse_width_cycles"] = this.PulseWidthCycles;- data["off_state_cycles"] = this.OffStateCycles;- data["array_size_x"] = this.ArraySizeX;- data["array_size_y"] = this.ArraySizeY;- data["spacing_x"] = this.SpacingX;- data["spacing_y"] = this.SpacingY;- data["composite_mode"] = ((this.CompositeMode == SourceCompositeMode.InheritAndRandomize) ? "randomize" : "inherit");- data["randomize_frequency"] = this.RandomizeFrequency;- data["randomize_frequency_amount"] = this.RandomizeFrequencyAmount;- data["randomize_phase"] = this.RandomizePhase;- data["randomize_phase_amount"] = this.RandomizePhaseAmount;- data["randomize_off_width"] = this.RandomizeOffWidth;- data["randomize_off_width_amount"] = this.RandomizeOffWidthAmount;- data["randomize_position"] = this.RandomizePosition;- data["randomize_position_amount"] = this.RandomizePositionAmount;+ data["name"] = Name;+ data["main_type"] = ((MainType == SourceMainType.Composite) ? "composite" : "single");+ data["x"] = PosX;+ data["y"] = PosY;+ data["has_position"] = HasPosition;+ data["source_on"] = SourceOn;+ data["detach_source"] = DetachSource;+ data["detach_after_steps"] = DetachAfterSteps;+ data["frequency"] = Frequency;+ data["amplitude"] = Amplitude;+ data["phase_deg"] = PhaseDeg;+ data["mode"] = ((Mode == SourceMode.Pulsed) ? "pulsed" : "continuous");+ data["pulse_shape"] = ((PulseShape == SourcePulseShape.SmoothedSquare) ? "smoothed_square" : "gaussian");+ data["pulse_width_cycles"] = PulseWidthCycles;+ data["off_state_cycles"] = OffStateCycles;+ data["array_size_x"] = ArraySizeX;+ data["array_size_y"] = ArraySizeY;+ data["spacing_x"] = SpacingX;+ data["spacing_y"] = SpacingY;+ data["composite_mode"] = ((CompositeMode == SourceCompositeMode.InheritAndRandomize) ? "randomize" : "inherit");+ data["randomize_frequency"] = RandomizeFrequency;+ data["randomize_frequency_amount"] = RandomizeFrequencyAmount;+ data["randomize_phase"] = RandomizePhase;+ data["randomize_phase_amount"] = RandomizePhaseAmount;+ data["randomize_off_width"] = RandomizeOffWidth;+ data["randomize_off_width_amount"] = RandomizeOffWidthAmount;+ data["randomize_position"] = RandomizePosition;+ data["randomize_position_amount"] = RandomizePositionAmount;List<object> elements = new List<object>();- foreach (SourceElement element in this.Elements)+ foreach (SourceElement element in Elements){Dictionary<string, object> elementData = new Dictionary<string, object>();elementData["x"] = element.PosX;@@ -412,7 +428,8 @@ namespace _2D_wave_sim_V01/// <summary>/// Inverse of <see cref="ToDictionary"/>. Missing or out-of-range values fall back to the- /// constructor defaults, except <c>has_position</c> which defaults to true; unknown enum+ /// constructor defaults, except <c>has_position</c> which defaults to true (see the comments in the+ /// body for the keys that were added after the first projects were saved); unknown enum/// strings map to the first enum value. Stored elements are restored as they are (they are/// not regenerated), with a 0.5 amplitude fallback and the phase range left wide open./// </summary>@@ -423,7 +440,11 @@ namespace _2D_wave_sim_V01s.MainType = ((SourceSettings.ReadText(d, "main_type", "single") == "composite") ? SourceMainType.Composite : SourceMainType.Simple);s.PosX = SourceSettings.ReadInt(d, "x", s.PosX, -1000000, 1000000);s.PosY = SourceSettings.ReadInt(d, "y", s.PosY, -1000000, 1000000);+ // a project saved before HasPosition existed has no "has_position" entry - default to true, since its+ // sources were positioned under the old rules (there was no "unset" state back then)s.HasPosition = SourceSettings.ReadBool(d, "has_position", true);+ // a project saved before SourceOn/DetachSource existed has no entries for them either - default to the+ // same behaviour it always had: on, and never detachings.SourceOn = SourceSettings.ReadBool(d, "source_on", true);s.DetachSource = SourceSettings.ReadBool(d, "detach_source", false);s.DetachAfterSteps = SourceSettings.ReadInt(d, "detach_after_steps", s.DetachAfterSteps, 0, 1000000000);@@ -470,6 +491,9 @@ namespace _2D_wave_sim_V01element.PulseShape = ((SourceSettings.ReadText(elementDict, "pulse_shape", "gaussian") == "smoothed_square") ? SourcePulseShape.SmoothedSquare : SourcePulseShape.Gaussian);element.OnWidthCycles = SourceSettings.ReadInt(elementDict, "on_width_cycles", 10, 1, 1000000);element.OffWidthCycles = SourceSettings.ReadInt(elementDict, "off_width_cycles", 10, 1, 1000000);+ // a project saved before off-width re-randomisation existed has no "off_width_base" entry -+ // default to this element's own off_width_cycles (already read above), which is exactly its+ // anchor under the old, always-static behaviourelement.OffWidthBase = SourceSettings.ReadInt(elementDict, "off_width_base", element.OffWidthCycles, 1, 1000000);element.RandomizeOffWidthAmount = SourceSettings.ReadInt(elementDict, "randomize_off_width_amount", 0, 0, 1000000);element.DetachAfterStep = SourceSettings.ReadInt(elementDict, "detach_after_step", -1, -1, 1000000000);@@ -509,6 +533,7 @@ namespace _2D_wave_sim_V01}catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException){+ // use the fallback}}return fallback;@@ -529,6 +554,7 @@ namespace _2D_wave_sim_V01}catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException){+ // use the fallback}}return fallback;diff --git a/Wave_Dude_2D/WaveEngineFactory.cs b/Wave_Dude_2D/WaveEngineFactory.csindex 1134eb0..818a113 100644--- a/Wave_Dude_2D/WaveEngineFactory.cs+++ b/Wave_Dude_2D/WaveEngineFactory.cs@@ -19,6 +19,7 @@ namespace _2D_wave_sim_V01/// <see cref="GpuWaveSimulator.TryCreate"/>, translating the usual OpenCL loader failures (missing, wrong-bitness or/// incomplete OpenCL.dll) into a readable reason; any failure falls back to the CPU <see cref="WaveSimulator"/>./// Never throws for GPU problems, but CPU engine construction may still throw (e.g. out of memory).+ /// Object sources (the Sources tab) run on either engine, the same as the image sources./// </summary>/// <param name="scene">Per-pixel speed, damping and image sources of the canvas; the engine copies it into its padded grid.</param>/// <param name="settings">Supplies <see cref="SimulationSettings.UseGpu"/> and the physics options passed to the engine (frequency scale, Laplacian order, time decay, intensity scale).</param>@@ -30,7 +31,7 @@ namespace _2D_wave_sim_V01/// The "the first choice failed - ..." form is only produced if <c>TryCreate</c> ever returns an engine together with a/// message, which it does not at present./// </param>- /// <param name="objectSources">Object sources to drive in addition to the image sources; may be null.</param>+ /// <param name="objectSources">The generated elements of the object sources (Sources tab) to drive in addition to the image sources; may be null.</param>/// <returns>A ready engine; the caller owns and must dispose it.</returns>public static IWaveEngine Create(SceneData scene, SimulationSettings settings, double sourceAmplitude, bool trackIntensity, ref string note, List<SourceElement> objectSources = null){diff --git a/Wave_Dude_2D/WaveSimulator.cs b/Wave_Dude_2D/WaveSimulator.csindex b65103d..d1692fb 100644--- a/Wave_Dude_2D/WaveSimulator.cs+++ b/Wave_Dude_2D/WaveSimulator.cs@@ -7,218 +7,201 @@ namespace _2D_wave_sim_V01{/// <summary>/// CPU implementation of <see cref="IWaveEngine"/>: an explicit leapfrog finite-difference solver for the- /// scalar 2D wave equation on a grid padded by one cell on each side. Created by+ /// scalar 2D wave equation on a grid padded by one cell on each side, a port of the Python class+ /// WaveSimulator2D (which runs on the GPU with CuPy). Created by/// <see cref="WaveEngineFactory"/> on the <see cref="SimulationRunner"/> worker thread, which is the only/// thread that advances it; the UI thread reads <see cref="FieldData"/> / <see cref="IntensityData"/> only- /// while the run is paused.+ /// while the run is paused. The engine has no thread affinity of its own: any single thread may drive it./// </summary>/// <remarks>+ /// <para>/// Units: grid spacing and time step are both 1, so the wave speed c is in cells (canvas pixels) per step,/// the per-cell <c>c2</c> is c² = 1/n² for refractive index n, and <see cref="Time"/> counts steps. Source/// frequencies are angular frequencies in radians per step (<see cref="_levelFrequency"/>).- /// Per step: the sources are blended into the field once (<see cref="ApplySources"/>), then the field is- /// advanced by <see cref="_subSteps"/> leapfrog sub-steps (<see cref="UpdateField"/>), the last of which also- /// updates the running intensity. The 4th-order stencil needs a shorter time step to stay stable, hence- /// the sub-stepping; the 9-point stencil always runs a single sub-step.+ /// </para>+ /// <para>+ /// The scheme: laplacian = 3x3 convolution with [[0.066, 0.184, 0.066], [0.184, -1, 0.184], [0.066, 0.184, 0.066]],+ /// new u = u + (u - previous u) * d + laplacian * c², with the field outside the domain fixed at 0. The sources+ /// are applied before each step as in update_scene / StaticImageScene.update_field:+ /// u = u * 0.9 + sin(frequency * t) * 0.1 (<see cref="ApplySources"/>). The field is then advanced by+ /// <see cref="_subSteps"/> leapfrog sub-steps (<see cref="UpdateField"/>), the last of which also updates the+ /// running intensity. The arrays have a border of one cell (which always stays 0) so that the step needs no edge+ /// tests. The rows are divided over all processor cores.+ /// </para>+ /// <para>+ /// The intensity is no longer a single exponential average of WaveVisualizer.update (I = I * 0.98 + u² * 0.02):+ /// a single-pole filter like that only rolls off at 6 dB/octave, so it never fully removes the ripple at the+ /// source's own oscillation frequency, just delays it - lengthening its time constant mostly adds trail without+ /// buying much extra ripple suppression. Instead the same one-pole filter (I = I * alpha + x * (1 - alpha)) is run+ /// twice in a row (<see cref="_intensityStage1"/>, then <see cref="_intensity"/>), a critically-damped 2-pole+ /// low-pass that rolls off at 12 dB/octave, so for the same responsiveness it suppresses the ripple far more+ /// without needing to know the local frequency at every pixel. Two full stages turned out to add more delay than+ /// wanted at low frequencies (a short pulse can come and go before the second stage has caught up, understating+ /// its peak) for not that much extra benefit over one, so what is actually shown/exported+ /// (<see cref="_intensityOut"/>) is a blend of the one-stage and two-stage outputs (<see cref="IntensityBlend"/>) -+ /// roughly the middle ground between the two (about 9, not 6 or 12, dB/octave), still well ahead of a single+ /// stage at rejecting the ripple but reacting closer to as fast. alpha (<see cref="_intensityAlpha"/>) is derived+ /// once per simulation so the time constant of each stage scales inversely with the frequency of the slowest+ /// active source, times the user's <see cref="SimulationSettings.TimeDecayFactor"/> - see that property's doc+ /// for why.+ /// </para>+ /// <para>+ /// Optionally (<see cref="SimulationSettings.Use4thOrderLaplacian"/>), the Laplacian is instead computed with a+ /// 4th order accurate, 5-point "cross" stencil (reaching 2 cells away along x and along y) wherever there is+ /// room for it - see <see cref="UpdateField"/>. This reduces numerical dispersion (short, under-resolved+ /// wavelengths otherwise travel slower than long ones - see the <see cref="SimulationSettings.WaveSpeedC"/> doc)+ /// at roughly twice the memory reads per step. The outermost ring of the domain still uses the original 3x3+ /// kernel, since it only has the usual one cell of border to read from, not the two the wider stencil needs.+ /// </para>+ /// <para>+ /// The 4th order stencil's coefficients (-1/12, 4/3, -5) reach much further from zero than the 3x3 kernel's+ /// (0.066, 0.184, -1) - about 7 times further at the highest spatial frequency the grid can represent - so the+ /// same c² that is safely stable with the 3x3 kernel can be wildly unstable with the 4th order one (the field+ /// blows up: everywhere saturates except at object edges, which is what an invalid/unstable Laplacian looks+ /// like). To stay stable without changing the physical wave speed, <see cref="AdvanceOneStep"/> instead takes+ /// <see cref="_subSteps"/> smaller time steps per call when the 4th order stencil is used: c² is scaled by+ /// 1 / _subSteps² (matching a time step _subSteps times smaller) and the damping factor d by its _subSteps-th+ /// root (so _subSteps applications of it compound back to the original d), so the net effect after _subSteps+ /// steps is exactly the same physical propagation and damping as one ordinary step - just spread over more,+ /// individually stable, time steps. _subSteps is computed once per scene from its highest c²+ /// (<see cref="ComputeSubSteps"/>) and is 1 (no sub-stepping, and a multiply by the exact literal 1.0F)+ /// whenever the 3x3 kernel is used or the scene's c² does not need it.+ /// </para>/// </remarks>- internal sealed class WaveSimulator : IWaveEngine+ internal sealed class WaveSimulator : IWaveEngine, IDisposable{/// <summary>/// Copies the scene's c² and damping maps into the padded grid, derives the sub-step count (4th order- /// only) and the matching per-sub-step damping and c² corrections, indexes the image and object sources,- /// and sets the intensity averaging constant from the slowest source level in use.+ /// only, and only when the scene's highest c² needs it) and the matching per-sub-step damping and c²+ /// corrections, indexes the image and object sources, and sets the intensity averaging constant from the+ /// slowest source level in use./// </summary>- /// <param name="scene">Per-cell c² and damping maps plus the image (green-channel) sources.</param>- /// <param name="sourceFrequencyScale">Multiplier in the level-to-angular-frequency mapping; see <see cref="_levelFrequency"/>.</param>- /// <param name="sourceAmplitude">Peak amplitude of the image sources (object sources carry their own).</param>- /// <param name="trackIntensity">Whether to allocate and update the intensity buffers; when false <see cref="IntensityData"/> stays null.</param>- /// <param name="use4thOrderLaplacian">Use the 4th-order 5-point-per-axis stencil (with sub-stepping) instead of the 9-point one.</param>- /// <param name="timeDecayFactor">Intensity averaging time in units of 100/level steps; see <see cref="_intensityAlpha"/>.</param>- /// <param name="intensityScale">Multiplier applied to the intensity output.</param>- /// <param name="objectSources">Interactive sources; those positioned outside the canvas are dropped.</param>+ /// <param name="scene">Per-cell c² and damping maps plus the image (green-channel) sources; its arrays are copied.</param>+ /// <param name="sourceFrequencyScale">Frequency of a source = green value / 255 × 0.5 × this value; see <see cref="_levelFrequency"/>.</param>+ /// <param name="sourceAmplitude">Peak amplitude of the image sources (1 = the value of the Python code; object sources carry their own).</param>+ /// <param name="trackIntensity">Whether to allocate and update the intensity buffers (it costs extra time in every step); when false <see cref="IntensityData"/> stays null.</param>+ /// <param name="use4thOrderLaplacian">Use the 4th-order 5-point-per-axis stencil (with sub-stepping) instead of the 9-point one; see the class remarks.</param>+ /// <param name="timeDecayFactor"><see cref="SimulationSettings.TimeDecayFactor"/>: intensity averaging time in units of <see cref="NominalDecayLevel"/>/level steps; see that property's doc and <see cref="_intensityAlpha"/>.</param>+ /// <param name="intensityScale"><see cref="SimulationSettings.IntensityScale"/>, the multiplier applied to the intensity output; see that property's doc.</param>+ /// <param name="objectSources">The generated elements of the object sources (Sources tab), or null/empty for none; those positioned outside the canvas are dropped.</param>public WaveSimulator(SceneData scene, double sourceFrequencyScale, double sourceAmplitude, bool trackIntensity, bool use4thOrderLaplacian, double timeDecayFactor, double intensityScale, List<SourceElement> objectSources = null){- this._levelFrequency = new double[256];- this._levelUsed = new bool[256];- this._levelValue = new float[256];- this._objRandom = new Random();- this._probeValues = new List<List<float>>();- this._sourceAmplitude = sourceAmplitude;- this._use4thOrderLaplacian = use4thOrderLaplacian;- this._intensityScale = (float)intensityScale;- this._width = scene.Width;- this._height = scene.Height;- this._stride = this._width + 2;- int cellCount = this._stride * (this._height + 2);- this._u = new float[cellCount];- this._uPrev = new float[cellCount];- this._c2 = new float[cellCount];- this._d = new float[cellCount];+ _sourceAmplitude = sourceAmplitude;+ _use4thOrderLaplacian = use4thOrderLaplacian;+ _intensityScale = (float)intensityScale;+ _width = scene.Width;+ _height = scene.Height;+ _stride = _width + 2;+ int cellCount = _stride * (_height + 2);+ _u = new float[cellCount];+ _uPrev = new float[cellCount];+ _c2 = new float[cellCount];+ float[] damping = new float[cellCount];if (trackIntensity){- this._intensity = new float[cellCount];- this._intensityStage1 = new float[cellCount];- this._intensityOut = new float[cellCount];+ _intensity = new float[cellCount];+ _intensityStage1 = new float[cellCount];+ _intensityOut = new float[cellCount];}- for (int y = 0; y < this._height; y++)+ for (int y = 0; y < _height; y++){- Array.Copy(scene.C2, y * this._width, this._c2, (y + 1) * this._stride + 1, this._width);- Array.Copy(scene.D, y * this._width, this._d, (y + 1) * this._stride + 1, this._width);+ Array.Copy(scene.C2, y * _width, _c2, (y + 1) * _stride + 1, _width);+ Array.Copy(scene.D, y * _width, damping, (y + 1) * _stride + 1, _width);}- if (use4thOrderLaplacian)- {- float maxC2 = 0f;- for (int i = 0; i < this._c2.Length; i++)- {- if (this._c2[i] > maxC2)- {- maxC2 = this._c2[i];- }- }- this._subSteps = WaveSimulator.ComputeSubSteps(maxC2);- }- else- {- this._subSteps = 1;- }- if (this._subSteps > 1)++ // see the class remarks: sub-stepping keeps the 4th order stencil stable without changing the physical+ // wave speed or damping - _subSteps stays 1 (no sub-stepping) unless the 4th order stencil is in use and+ // this scene's highest c² actually needs it+ _subSteps = use4thOrderLaplacian ? ComputeSubSteps(MaxOf(_c2)) : 1;+ if (_subSteps > 1){- // Damping is applied once per sub-step, so take the sub-step root to keep the per-step decay unchanged.- float[] dEffective = new float[this._d.Length];- double exponent = 1.0 / this._subSteps;- for (int i = 0; i < this._d.Length; i++)+ // Damping is applied once per sub-step, so take the sub-step root to keep the per-step decay unchanged+ // (_subSteps applications of it compound back to the original d).+ _damping = new float[cellCount];+ double exponent = 1.0 / _subSteps;+ for (int i = 0; i < cellCount; i++){- dEffective[i] = (float)Math.Pow(this._d[i], exponent);+ _damping[i] = (float)Math.Pow(damping[i], exponent);}- this._dEffective = dEffective;// A sub-step is 1/subSteps long, so c²·dt² shrinks by 1/subSteps².- this._c2Mult = 1f / (float)(this._subSteps * this._subSteps);+ _c2Mult = 1f / (_subSteps * _subSteps);}else{- this._dEffective = this._d;- this._c2Mult = 1f;+ _damping = damping;+ _c2Mult = 1f;}+int sourceCount = scene.SourceCount;- this._sourceIndex = new int[sourceCount];- this._sourceLevel = new byte[sourceCount];+ _sourceIndex = new int[sourceCount];+ _sourceLevel = new byte[sourceCount];for (int i = 0; i < sourceCount; i++){- this._sourceIndex[i] = (scene.SourceY[i] + 1) * this._stride + scene.SourceX[i] + 1;- this._sourceLevel[i] = scene.SourceLevel[i];- this._levelUsed[scene.SourceLevel[i]] = true;+ _sourceIndex[i] = (scene.SourceY[i] + 1) * _stride + scene.SourceX[i] + 1;+ _sourceLevel[i] = scene.SourceLevel[i];+ _levelUsed[scene.SourceLevel[i]] = true;}for (int level = 0; level <= 255; level++){- this._levelFrequency[level] = level / 255.0 * 0.5 * sourceFrequencyScale;+ _levelFrequency[level] = level / 255.0 * 0.5 * sourceFrequencyScale;}- if (objectSources == null)- {- this._objSources = Array.Empty<SourceElement>();- this._objIndex = Array.Empty<int>();- }- else++ // object sources: keep only the elements whose position is inside the canvas (a randomized composite+ // element can fall outside)+ List<SourceElement> insideSources = new List<SourceElement>();+ List<int> insideIndices = new List<int>();+ if (objectSources != null){- List<SourceElement> insideSources = new List<SourceElement>();- List<int> insideIndices = new List<int>();foreach (SourceElement source in objectSources){- if (source.PosX >= 0 && source.PosX < this._width && source.PosY >= 0 && source.PosY < this._height)+ if (source.PosX >= 0 && source.PosX < _width && source.PosY >= 0 && source.PosY < _height){insideSources.Add(source);- insideIndices.Add((source.PosY + 1) * this._stride + source.PosX + 1);+ insideIndices.Add((source.PosY + 1) * _stride + source.PosX + 1);}}- this._objSources = insideSources.ToArray();- this._objIndex = insideIndices.ToArray();}- // The intensity decay time is scaled by the lowest (slowest) source level in use.- int lowestLevel = 0;- for (int level = 1; level <= 255; level++)+ _objSources = insideSources.ToArray();+ _objIndex = insideIndices.ToArray();+ _objCycleAnchor = new double[_objSources.Length];+ _objCurrentOffWidth = new int[_objSources.Length];+ for (int i = 0; i < _objSources.Length; i++){- if (this._levelUsed[level])- {- lowestLevel = level;- break;- }- }- foreach (SourceElement source in this._objSources)- {- if (source.Level > 0 && (lowestLevel == 0 || source.Level < lowestLevel))- {- lowestLevel = source.Level;- }- }- if (lowestLevel == 0)- {- lowestLevel = NominalDecayLevel;- }- double decaySteps = Math.Max(1.0, timeDecayFactor * 100.0 / lowestLevel);- this._intensityAlpha = (float)Math.Exp(-1.0 / decaySteps);- this._objCycleAnchor = new double[this._objSources.Length];- this._objCurrentOffWidth = new int[this._objSources.Length];- for (int i = 0; i < this._objSources.Length; i++)- {- this._objCurrentOffWidth[i] = this._objSources[i].OffWidthCycles;+ // the very first cycle uses the off-width already rolled once at "Generate composite source" time;+ // later cycles (for elements that opt into it) redraw from OffWidthBase - see ComputePulsePosition+ _objCurrentOffWidth[i] = _objSources[i].OffWidthCycles;}++ // the intensity's averaging time constant scales inversely with the frequency of the slowest active+ // source (image or object) - see TimeDecayFactor's doc (SimulationSettings) for why, and+ // NominalDecayLevel's doc for the calibration this reproduces+ _intensityAlpha = IntensityRetention(timeDecayFactor, LowestSourceLevel(_levelUsed, _objSources));}/// <summary>Scene width in cells (canvas pixels), excluding the padding.</summary>- public int Width- {- get- {- return this._width;- }- }+ public int Width => _width;/// <summary>Scene height in cells (canvas pixels), excluding the padding.</summary>- public int Height- {- get- {- return this._height;- }- }+ public int Height => _height;- /// <summary>Row pitch of the padded buffers: <see cref="Width"/> + 2.</summary>- public int Stride- {- get- {- return this._stride;- }- }+ /// <summary>Row pitch of the padded buffers: <see cref="Width"/> + 2. Pixel (x, y) is at (y + 1) * Stride + x + 1.</summary>+ public int Stride => _stride;/// <summary>- /// The current field u (padded layout). The array instance changes every sub-step because the two- /// field buffers are swapped, so callers must re-read this property per frame rather than cache the array.+ /// The current field u of the last completed step (padded layout). The array instance changes every sub-step+ /// because the two field buffers are swapped, so callers must re-read this property per frame rather than+ /// cache the array. Do not change./// </summary>- public float[] FieldData- {- get- {- return this._u;- }- }+ public float[] FieldData => _u;- /// <summary>Scaled running intensity (padded layout), or null when the engine was created without intensity tracking.</summary>- public float[] IntensityData- {- get- {- return this._intensityOut;- }- }+ /// <summary>Scaled running intensity (padded layout), or null when the engine was created without intensity tracking. Do not change.</summary>+ public float[] IntensityData => _intensityOut;/// <summary>Engine label for the UI/result: "CPU (n threads)" with the logical processor count.</summary>- public string Description- {- get- {- return "CPU (" + Environment.ProcessorCount.ToString(CultureInfo.InvariantCulture) + " threads)";- }- }+ public string Description => "CPU (" + Environment.ProcessorCount.ToString(CultureInfo.InvariantCulture) + " threads)";++ /// <summary>Elapsed simulation time in steps (one per <see cref="AdvanceOneStep"/>).</summary>+ public double Time => _time;/// <summary>No-op: the CPU buffers are always host-resident and up to date.</summary>public void PrepareFrame(bool needField, bool needIntensity)@@ -230,6 +213,20 @@ namespace _2D_wave_sim_V01{}+ /// <summary>+ /// Advances the simulation by one step: blends the sources in once, runs <see cref="_subSteps"/> leapfrog+ /// sub-steps (the intensity is updated on the last one only) and increments <see cref="Time"/>.+ /// </summary>+ public void AdvanceOneStep()+ {+ ApplySources();+ for (int subStep = 1; subStep <= _subSteps; subStep++)+ {+ UpdateField(subStep == _subSteps);+ }+ _time += 1.0;+ }+/// <summary>/// Installs the probe layout (or clears it when <paramref name="sampler"/> is null or empty), discarding any/// pending samples and integrated totals, and allocates the per-pixel totals for integrated line probes.@@ -237,25 +234,25 @@ namespace _2D_wave_sim_V01/// <exception cref="InvalidOperationException">The sampler needs intensity but this engine does not track it.</exception>public void SetProbes(ProbeSampler sampler){- this._probeValues.Clear();- this._profileTotals = null;+ _probeValues.Clear();+ _profileTotals = null;if (sampler == null || sampler.Count == 0){- this._sampler = null;+ _sampler = null;return;}- if (sampler.NeedsIntensity && this._intensityOut == null)+ if (sampler.NeedsIntensity && _intensityOut == null){throw new InvalidOperationException("the intensity is not tracked");}- this._sampler = sampler;- this._profileTotals = new double[sampler.Count][];+ _sampler = sampler;+ _profileTotals = new double[sampler.Count][];for (int i = 0; i < sampler.Count; i++){- this._probeValues.Add(new List<float>());+ _probeValues.Add(new List<float>());if (sampler.Integrate[i]){- this._profileTotals[i] = new double[sampler.Pixels[i].Length];+ _profileTotals[i] = new double[sampler.Pixels[i].Length];}}}@@ -267,30 +264,32 @@ namespace _2D_wave_sim_V01/// </summary>public void SampleProbes(){- if (this._sampler == null)+ if (_sampler == null){return;}- int step = (int)Math.Round(this._time);- for (int i = 0; i < this._sampler.Count; i++)+ int step = (int)Math.Round(_time);+ for (int p = 0; p < _sampler.Count; p++){- if (!this._sampler.IsProfile[i])+ if (!_sampler.IsProfile[p]){- float[] source = this._sampler.UseIntensity[i] ? this._intensityOut : this._u;- this._probeValues[i].Add(this._sampler.Compute(i, source));+ float[] data = _sampler.UseIntensity[p] ? _intensityOut : _u;+ _probeValues[p].Add(_sampler.Compute(p, data));}- else if (this._sampler.Integrate[i])+ else if (_sampler.Integrate[p]){- if (this._sampler.UseStartAfterStep[i] && step < this._sampler.StartAfterStep[i])+ // before "start after step" the totals are simply never added to, so they stay at zero: any+ // intensity that arrived earlier is purged rather than being baked into the total once recording starts+ if (_sampler.UseStartAfterStep[p] && step < _sampler.StartAfterStep[p]){continue;}- int[] pixels = this._sampler.Pixels[i];- double[] totals = this._profileTotals[i];- float[] intensityOut = this._intensityOut;- for (int j = 0; j < pixels.Length; j++)+ // the intensity that has passed every point of the line, added up over the steps+ int[] pixels = _sampler.Pixels[p];+ double[] totals = _profileTotals[p];+ for (int k = 0; k < pixels.Length; k++){- totals[j] += intensityOut[pixels[j]];+ totals[k] += _intensityOut[pixels[k]];}}}@@ -300,15 +299,15 @@ namespace _2D_wave_sim_V01/// <returns>One array per probe, one value per step (empty for line probes); an empty outer array when no sampler is set.</returns>public float[][] TakeProbeSamples(){- if (this._sampler == null)+ if (_sampler == null){return new float[0][];}- float[][] samples = new float[this._sampler.Count][];- for (int i = 0; i < this._sampler.Count; i++)+ float[][] samples = new float[_sampler.Count][];+ for (int p = 0; p < _sampler.Count; p++){- samples[i] = this._probeValues[i].ToArray();- this._probeValues[i].Clear();+ samples[p] = _probeValues[p].ToArray();+ _probeValues[p].Clear();}return samples;}@@ -320,54 +319,46 @@ namespace _2D_wave_sim_V01/// </returns>public float[][] ReadProbeProfiles(){- if (this._sampler == null)+ if (_sampler == null){return new float[0][];}- float[][] profiles = new float[this._sampler.Count][];- for (int i = 0; i < this._sampler.Count; i++)+ float[][] profiles = new float[_sampler.Count][];+ for (int p = 0; p < _sampler.Count; p++){- if (!this._sampler.IsProfile[i])+ if (!_sampler.IsProfile[p]){continue;}- int[] pixels = this._sampler.Pixels[i];+ int[] pixels = _sampler.Pixels[p];float[] profile = new float[pixels.Length];- if (this._sampler.Integrate[i])+ if (_sampler.Integrate[p]){- double[] totals = this._profileTotals[i];- for (int j = 0; j < pixels.Length; j++)+ double[] totals = _profileTotals[p];+ for (int k = 0; k < pixels.Length; k++){- profile[j] = (float)totals[j];+ profile[k] = (float)totals[k];}}else{- float[] source = this._sampler.UseIntensity[i] ? this._intensityOut : this._u;- for (int j = 0; j < pixels.Length; j++)+ float[] data = _sampler.UseIntensity[p] ? _intensityOut : _u;+ for (int k = 0; k < pixels.Length; k++){- profile[j] = source[pixels[j]];+ profile[k] = data[pixels[k]];}}- profiles[i] = profile;+ profiles[p] = profile;}return profiles;}- /// <summary>Elapsed simulation time in steps (one per <see cref="AdvanceOneStep"/>).</summary>- public double Time- {- get- {- return this._time;- }- }-/// <summary>/// Number of sub-steps per time step needed to keep the 4th-order stencil stable for the largest c² in the- /// scene: the smallest n with c²·λmax/n² ≤ <see cref="SubStepTargetLimit"/>, at least 1.+ /// scene: the smallest n with c²·λmax/n² ≤ <see cref="SubStepTargetLimit"/>, at least 1. Shared with+ /// <see cref="GpuWaveSimulator"/>./// </summary>- private static int ComputeSubSteps(float maxC2)+ internal static int ComputeSubSteps(float maxC2){if (maxC2 <= 0f){@@ -377,18 +368,59 @@ namespace _2D_wave_sim_V01return Math.Max(1, (int)Math.Round(subSteps));}+ /// <summary>Largest value in <paramref name="values"/>, or 0 for an empty or all-negative array.</summary>+ internal static float MaxOf(float[] values)+ {+ float max = 0f;+ foreach (float value in values)+ {+ if (value > max)+ {+ max = value;+ }+ }+ return max;+ }+/// <summary>- /// Advances the simulation by one step: blends the sources in once, runs <see cref="_subSteps"/> leapfrog- /// sub-steps (the intensity is updated on the last one only) and increments <see cref="Time"/>.+ /// The lowest (slowest) source level in use, image or object (a level of 0 means "no source" and is+ /// excluded), or <see cref="NominalDecayLevel"/> when no source has a level above 0. Shared with+ /// <see cref="GpuWaveSimulator"/>./// </summary>- public void AdvanceOneStep()+ /// <param name="levelUsed">Per level 0..255: whether an image source uses it.</param>+ /// <param name="objectSources">Object sources to consider as well.</param>+ internal static int LowestSourceLevel(bool[] levelUsed, IEnumerable<SourceElement> objectSources){- this.ApplySources();- for (int i = 1; i <= this._subSteps; i++)+ int minActiveLevel = 0;+ for (int level = 1; level <= 255; level++)+ {+ if (levelUsed[level])+ {+ minActiveLevel = level;+ break;+ }+ }+ foreach (SourceElement source in objectSources){- this.UpdateField(this._dEffective, this._c2Mult, i == this._subSteps);+ if (source.Level > 0 && (minActiveLevel == 0 || source.Level < minActiveLevel))+ {+ minActiveLevel = source.Level;+ }}- this._time += 1.0;+ return minActiveLevel == 0 ? NominalDecayLevel : minActiveLevel;+ }++ /// <summary>+ /// Per-step retention factor of the intensity averages: exp(-1/tauSteps) with+ /// tauSteps = <paramref name="timeDecayFactor"/>·<see cref="NominalDecayLevel"/>/<paramref name="lowestLevel"/>,+ /// at least 1 step, so the time constant scales inversely with the slowest source's frequency and+ /// <see cref="SimulationSettings.TimeDecayFactor"/> counts steps at a nominal source level of+ /// <see cref="NominalDecayLevel"/>. Shared with <see cref="GpuWaveSimulator"/>.+ /// </summary>+ internal static float IntensityRetention(double timeDecayFactor, int lowestLevel)+ {+ double tauSteps = Math.Max(1.0, timeDecayFactor * NominalDecayLevel / lowestLevel);+ return (float)Math.Exp(-1.0 / tauSteps);}/// <summary>@@ -399,75 +431,88 @@ namespace _2D_wave_sim_V01/// </summary>private void ApplySources(){- float[] u = this._u;- if (this._sourceIndex.Length > 0)+ float[] u = _u;+ if (_sourceIndex.Length > 0){+ // sin(phase + frequency * t) * amplitude is the same for all sources with the same green value:+ // one sine per level in use, not per source pixelfor (int level = 1; level <= 255; level++){- if (this._levelUsed[level])+ if (_levelUsed[level]){- this._levelValue[level] = (float)(Math.Sin(this._levelFrequency[level] * this._time) * this._sourceAmplitude);+ _levelValue[level] = (float)(Math.Sin(_levelFrequency[level] * _time) * _sourceAmplitude);}}- for (int i = 0; i < this._sourceIndex.Length; i++)+ for (int i = 0; i < _sourceIndex.Length; i++){- int idx = this._sourceIndex[i];- u[idx] = u[idx] * SourceOpacity + this._levelValue[this._sourceLevel[i]] * (1f - SourceOpacity);+ int idx = _sourceIndex[i];+ u[idx] = u[idx] * SourceOpacity + _levelValue[_sourceLevel[i]] * (1f - SourceOpacity);}}- for (int i = 0; i < this._objSources.Length; i++)+ for (int i = 0; i < _objSources.Length; i++){- SourceElement source = this._objSources[i];- float fade = 1f;+ SourceElement source = _objSources[i];+ // "detach source": once the run reaches the source's detach step, its drive is faded out linearly over+ // the next DetachRampSteps steps (rather than cut instantly), then it stops driving the field entirely+ // (not even towards 0) so it releases its hold and stops diffracting waves through that point. A hard+ // cutoff would otherwise leave a small kink in the forcing right at the detach step, which can ring.+ float detachFade = 1f;if (source.DetachAfterStep >= 0){- // Linear fade to zero over 30 steps (SourceElement.DetachRampSteps) after the detach step.- double sinceDetach = this._time - source.DetachAfterStep;- if (sinceDetach >= 30.0)+ double stepsSinceDetach = _time - source.DetachAfterStep;+ if (stepsSinceDetach >= SourceElement.DetachRampSteps){continue;}- if (sinceDetach > 0.0)+ if (stepsSinceDetach > 0.0){- fade = (float)(1.0 - sinceDetach / 30.0);+ detachFade = (float)(1.0 - stepsSinceDetach / SourceElement.DetachRampSteps);}}- double freq = this._levelFrequency[source.Level];- double envelope;- if (source.Mode == SourceMode.Continuous)+ double freq = _levelFrequency[source.Level];+ double envelope = 1.0;+ if (source.Mode != SourceMode.Continuous){- envelope = 1.0;+ double pulsePos = ComputePulsePosition(i, source, freq, out int offWidth, out bool isFirstCycle);+ envelope = PulseEnvelope(source, pulsePos, offWidth, isFirstCycle);}- else- {- int offWidth = 0;- bool isFirstCycle = false;- double pulsePos = this.ComputePulsePosition(i, source, freq, ref offWidth, ref isFirstCycle);- envelope = this.PulseEnvelope(source, pulsePos, offWidth, isFirstCycle);- }- float value = (float)(Math.Sin(source.PhaseRad + freq * this._time) * source.Amplitude * envelope) * fade;- int idx = this._objIndex[i];+ float value = (float)(Math.Sin(source.PhaseRad + freq * _time) * source.Amplitude * envelope) * detachFade;+ int idx = _objIndex[i];u[idx] = u[idx] * SourceOpacity + value * (1f - SourceOpacity);}}/// <summary>- /// Position (in cycles of the source frequency) of a pulsed source within its current on/off period. Also- /// reports the off-width in effect for that period and whether the source is still in its first period.- /// With a fixed off-width the period is phase-shifted by the off-width so the on-phase starts at step 0.- /// With a randomized off-width the position is measured from the anchor of the current period (which- /// begins with its off-phase); whenever a period completes the anchor moves on and a fresh off-width is- /// drawn from <c>OffWidthBase ± RandomizeOffWidthAmount</c> (at least 1), at most- /// <see cref="CycleAdvanceGuard"/> periods at a time.+ /// Returns the element's position within its current off+on cycle (0 = the very start of the "off" span, up+ /// to but not including its current period, in cycles of the source frequency), and reports the off-width+ /// in effect for that cycle via <paramref name="offWidth"/>. For most elements+ /// (<see cref="SourceElement.RandomizeOffWidthAmount"/> <= 0) the off-width never changes, so this is a+ /// pure, stateless function of <see cref="_time"/> - except that the cycle clock is shifted by the+ /// off-width, so the run starts already at the beginning of the "on" span (pos = offWidth) instead of at the+ /// start of an off span: a single/non-randomized source sitting silent for its off-width at the very start of+ /// a run was never the intent, only ever a side effect of the cycle position formula happening to start at 0.+ /// An element with RandomizeOffWidthAmount > 0 (only ever a composite source with "Randomize off-width"+ /// ticked) keeps the original start-in-off-state behavior instead, since there the elements are meant to+ /// desynchronize from a common starting point rather than all begin already mid-pulse. For such an element+ /// this also owns its runtime state (<see cref="_objCycleAnchor"/>, <see cref="_objCurrentOffWidth"/>): each+ /// time <see cref="_time"/> has advanced far enough to complete the current cycle, it advances the element's+ /// cycle anchor and redraws a fresh off-width (uniformly within ± RandomizeOffWidthAmount of+ /// <see cref="SourceElement.OffWidthBase"/>, at least 1, at most <see cref="CycleAdvanceGuard"/> cycles at a+ /// time) before computing the position - so every source keeps its own, independently-drifting rhythm+ /// instead of staying locked to whatever it rolled once at generate time.+ /// <paramref name="isFirstCycle"/> reports whether pos falls within the element's very first off+on cycle+ /// since the run began - see <see cref="PulseEnvelope"/> for why that matters for the SmoothedSquare shape./// </summary>/// <param name="i">Index of the source in <see cref="_objSources"/> (selects its anchor/off-width slot).</param>/// <param name="el">The source whose pulse timing is evaluated.</param>/// <param name="freq">Angular frequency of the source in radians per step.</param>/// <param name="offWidth">Receives the off-width (cycles) in effect for the current period.</param>/// <param name="isFirstCycle">Receives whether the source is still in its first period.</param>- private double ComputePulsePosition(int i, SourceElement el, double freq, ref int offWidth, ref bool isFirstCycle)+ private double ComputePulsePosition(int i, SourceElement el, double freq, out int offWidth, out bool isFirstCycle){- double cycles = freq * this._time / (2.0 * Math.PI);+ // cycles of the source's own frequency elapsed since t = 0 (not folding in the phase, so the on/off timing+ // does not shift when only the phase of the wave itself is changed)+ double cycleClock = freq * _time / (2.0 * Math.PI);if (el.RandomizeOffWidthAmount <= 0){offWidth = el.OffWidthCycles;@@ -477,51 +522,59 @@ namespace _2D_wave_sim_V01isFirstCycle = true;return 0.0;}- double shifted = cycles + offWidth;- isFirstCycle = Math.Floor(shifted / period) == 0.0;- return shifted - period * Math.Floor(shifted / period);+ // shifted so cycleClock = 0 lands at pos = offWidth (the start of the "on" span), not pos = 0 (the start+ // of an "off" span) - see the summary above+ double adjustedClock = cycleClock + offWidth;+ isFirstCycle = Math.Floor(adjustedClock / period) == 0.0;+ return adjustedClock - period * Math.Floor(adjustedClock / period); // 0 .. period}else{- offWidth = this._objCurrentOffWidth[i];- int period = el.OnWidthCycles + offWidth;- if (period <= 0)+ offWidth = _objCurrentOffWidth[i];+ int dynPeriod = el.OnWidthCycles + offWidth;+ if (dynPeriod <= 0){isFirstCycle = true;return 0.0;}- double sinceAnchor = cycles - this._objCycleAnchor[i];+ double sinceAnchor = cycleClock - _objCycleAnchor[i];int guard = 0;- while (sinceAnchor >= period && guard < CycleAdvanceGuard)+ while (sinceAnchor >= dynPeriod && guard < CycleAdvanceGuard){- this._objCycleAnchor[i] += period;- sinceAnchor -= period;- offWidth = Math.Max(1, el.OffWidthBase + SourceSettings.RandomInt(this._objRandom, el.RandomizeOffWidthAmount));- this._objCurrentOffWidth[i] = offWidth;- period = el.OnWidthCycles + offWidth;+ _objCycleAnchor[i] += dynPeriod;+ sinceAnchor -= dynPeriod;+ offWidth = Math.Max(1, el.OffWidthBase + SourceSettings.RandomInt(_objRandom, el.RandomizeOffWidthAmount));+ _objCurrentOffWidth[i] = offWidth;+ dynPeriod = el.OnWidthCycles + offWidth;guard++;}if (sinceAnchor < 0.0){- sinceAnchor = 0.0;+ sinceAnchor = 0.0; // should not happen (_time only increases), guarded for safety}- isFirstCycle = this._objCycleAnchor[i] == 0.0;+ // the anchor only ever advances (above) once a cycle has actually completed, so it still reading its+ // initial 0 means no cycle has completed yet - we are still in the element's very first (off-first) cycle+ isFirstCycle = _objCycleAnchor[i] == 0.0;return sinceAnchor;}}/// <summary>- /// Amplitude envelope (0..1) of a pulsed source at the given position within its on/off period (a- /// non-positive period yields 1). Gaussian: zero during the off-phase, then a bell centred in the on-window- /// with σ = on-width/6. Smoothed square: the product of an arctan rise at the start and an arctan fall at- /// the end of the on-window (softness 0.35 cycles); positions are wrapped so the tails of neighbouring- /// periods blend smoothly, except in the first period so the pulse does not start mid-tail.+ /// Amplitude envelope (0..1) of a pulsed source: the source is "off" for <paramref name="offWidth"/> cycles+ /// of its own frequency, then "on" for <see cref="SourceElement.OnWidthCycles"/> cycles, repeating (off+ /// precedes on so that, at the start of a run, every source is silent for its own off-width before its first+ /// pulse, rather than every source firing simultaneously at t = 0; a non-positive period yields 1). Within+ /// the "on" span the amplitude is shaped by the pulse shape: Gaussian tapers smoothly to (about) 0 at both+ /// ends of the "on" span (a bell centred in the on-window with σ = on-width/6), and SmoothedSquare rises and+ /// falls quickly (an atan-smoothed square wave, avoiding a hard on/off step that would ring the field).+ /// <paramref name="pos"/> and <paramref name="offWidth"/> come from <see cref="ComputePulsePosition"/>, as+ /// does <paramref name="isFirstCycle"/> - see the SmoothedSquare branch for why that one matters./// </summary>/// <param name="el">The source; supplies the pulse shape and on-width.</param>/// <param name="pos">Position within the period in cycles, as returned by <see cref="ComputePulsePosition"/>.</param>/// <param name="offWidth">Off-width (cycles) in effect for this period.</param>/// <param name="isFirstCycle">Whether this is the first period (suppresses the tail wrapping of the smoothed square).</param>- private double PulseEnvelope(SourceElement el, double pos, int offWidth, bool isFirstCycle)+ private static double PulseEnvelope(SourceElement el, double pos, int offWidth, bool isFirstCycle){int onWidthCycles = el.OnWidthCycles;int period = onWidthCycles + offWidth;@@ -529,35 +582,42 @@ namespace _2D_wave_sim_V01{return 1.0;}+ double onPos = pos - offWidth; // 0 .. onWidth, position within the "on" spanif (el.PulseShape == SourcePulseShape.Gaussian){- if (pos < offWidth)+ if (onPos < 0.0){return 0.0;}- double onPos = pos - offWidth;double center = onWidthCycles / 2.0;double sigma = Math.Max(onWidthCycles / 6.0, 1E-06);double z = (onPos - center) / sigma;return Math.Exp(-0.5 * z * z);}- else- {- double onPos = pos - offWidth;- if (onPos < 0.0 && !isFirstCycle)- {- onPos += period;- }- double fallArg = onPos - onWidthCycles;- double riseArg = onPos;- if (riseArg > period / 2.0)- {- riseArg -= period;- }- double rise = 0.5 + Math.Atan(riseArg / 0.35) / Math.PI;- double fall = 0.5 - Math.Atan(fallArg / 0.35) / Math.PI;- return rise * fall;- }+ // a flat-topped pulse (envelope 1 while "on", 0 while "off") with a short, FIXED-width (in cycles, not a+ // fraction of the on/off span) smoothed edge at the rise and the fall, evaluated on a coordinate shifted+ // so the "on" span starts at 0 (folding around the period).+ if (onPos < 0.0 && !isFirstCycle)+ {+ // wrapping onPos forward by a full period makes it continue the falling tail of the on-span that+ // JUST ended - correct from the second off-span onward, where that on-span really happened. A+ // source's very first off-span (isFirstCycle) has no real preceding on-emission to continue from, so+ // wrapping there would fabricate one: pos = 0 would land exactly on that phantom falling edge and+ // start the run at envelope ~0.5 instead of ~0, emitting a spurious one-cycle "blip" before the+ // source actually goes quiet. Left un-wrapped (deeply negative) instead, riseArg/fallArg below+ // correctly place it far from both edges, so the envelope is (very close to) 0 until the real rising edge.+ onPos += period;+ }+ const double EdgeWidth = 0.35;+ double fallArg = onPos - onWidthCycles; // 0 at the falling edge, grows past it+ double riseArg = onPos; // 0 at the rising edge+ if (riseArg > period / 2.0)+ {+ riseArg -= period; // signed distance to the *nearest* rising edge+ }+ double rise = 0.5 + Math.Atan(riseArg / EdgeWidth) / Math.PI;+ double fall = 0.5 - Math.Atan(fallArg / EdgeWidth) / Math.PI;+ return rise * fall;}/// <summary>@@ -571,28 +631,33 @@ namespace _2D_wave_sim_V01/// buffers are swapped. Border cells are never written and stay 0./// When tracking, the intensity is a cascade of two exponential moving averages of u² (retention/// <see cref="_intensityAlpha"/>); the output mixes both stages (<see cref="IntensityBlend"/>) times- /// <see cref="_intensityScale"/>.+ /// <see cref="_intensityScale"/>. The damping array is <see cref="_damping"/> (the scene's d itself when+ /// <see cref="_subSteps"/> = 1, otherwise its 1/_subSteps-th root) and c² is scaled by+ /// <see cref="_c2Mult"/> (1.0F, an exact no-op, when _subSteps = 1)./// </summary>- /// <param name="dArray">Damping map to use, already corrected for the sub-step length.</param>- /// <param name="c2Mult">Factor on c² for the sub-step length (1/subSteps²).</param>- /// <param name="updateIntensity">Whether to update the intensity buffers in this sub-step (last sub-step only).</param>- private void UpdateField(float[] dArray, float c2Mult, bool updateIntensity)+ /// <param name="updateIntensity">+ /// Whether to update the intensity buffers in this sub-step: only on the last one, so that its own exponential+ /// averaging still runs once per <see cref="AdvanceOneStep"/> call, from the field after all of its sub-steps,+ /// matching its calibration (<see cref="_intensityAlpha"/>) regardless of how many sub-steps that call takes.+ /// </param>+ private void UpdateField(bool updateIntensity){- float[] u = this._u;- float[] uPrev = this._uPrev;- float[] c2 = this._c2;- float[] d = dArray;- float[] intensity = this._intensity;- float[] stage1 = this._intensityStage1;- float[] intensityOut = this._intensityOut;+ // Local copies for the parallel loop: the lambda should not touch fields.+ float[] u = _u;+ float[] uPrev = _uPrev;+ float[] c2 = _c2;+ float[] d = _damping;+ float[] intensity = _intensity;+ float[] stage1 = _intensityStage1;+ float[] intensityOut = _intensityOut;bool track = intensity != null && updateIntensity;- int stride = this._stride;- int w = this._width;- int h = this._height;- bool use4th = this._use4thOrderLaplacian;- float mult = c2Mult;- float alpha = this._intensityAlpha;- float scale = this._intensityScale;+ int stride = _stride;+ int w = _width;+ int h = _height;+ bool use4th = _use4thOrderLaplacian;+ float mult = _c2Mult;+ float alpha = _intensityAlpha;+ float scale = _intensityScale;int bands = Math.Min(h, Environment.ProcessorCount * 4);Parallel.For(0, bands, band =>@@ -602,7 +667,9 @@ namespace _2D_wave_sim_V01for (int y = rowStart; y <= rowEnd; y++){int idx = (y + 1) * stride + 1;- // The 4th-order stencil reaches two cells out, but the padding is only one cell wide.+ // the 4th order stencil reaches 2 cells away, so it is only safe for domain rows/columns that+ // have that much room before the (1 cell wide) border - the outermost ring of the domain (y = 0,+ // y = h - 1, and, per column below, x = 0, x = w - 1) falls back to the original 3x3 kernelbool rowAllows4th = use4th && y >= 1 && y <= h - 2;for (int x = 0; x < w; x++){@@ -620,10 +687,14 @@ namespace _2D_wave_sim_V01+ KernelEdge * (u[idx - 1] + u[idx + 1] + u[idx - stride] + u[idx + stride])- center;}+ // the new value replaces the previous one (each cell only reads its own previous value)float next = center + (center - uPrev[idx]) * d[idx] + laplacian * c2[idx] * mult;uPrev[idx] = next;if (track){+ // two cascaded one-pole stages (see the class remarks), blended with the 1-stage+ // result (IntensityBlend) for the shown/exported intensity rather than using the full+ // 2-stage cascade outrightfloat s1 = stage1[idx] * alpha + next * next * (1f - alpha);stage1[idx] = s1;float s2 = intensity[idx] * alpha + s1 * (1f - alpha);@@ -635,9 +706,9 @@ namespace _2D_wave_sim_V01}});- // uPrev now holds the new field; swap buffers.- this._uPrev = u;- this._u = uPrev;+ // the array that received the new values is now the current field+ _uPrev = u;+ _u = uPrev;}/// <summary>Weight of the four diagonal neighbours in the 9-point Laplacian.</summary>@@ -649,27 +720,49 @@ namespace _2D_wave_sim_V01/// <summary>Fraction of the old field value kept when a source value is blended in (soft source injection).</summary>private const float SourceOpacity = 0.9f;- /// <summary>Source level assumed for the intensity decay time when no source has a level above 0.</summary>- private const int NominalDecayLevel = 100;+ /// <summary>+ /// Nominal source level (of 255) that <see cref="SimulationSettings.TimeDecayFactor"/>'s steps count is+ /// calibrated against - see that property's doc and <see cref="IntensityRetention"/>; also the level assumed+ /// when no source has a level above 0 (<see cref="LowestSourceLevel"/>).+ /// </summary>+ internal const int NominalDecayLevel = 100;- /// <summary>Mix of the two intensity averaging stages in the output: 0 = first stage only, 1 = second stage only.</summary>+ /// <summary>+ /// How much of the fully cascaded (2-stage, 12 dB/octave) intensity is blended into the shown/exported value+ /// versus the 1-stage (6 dB/octave) intensity (0 = first stage only, 1 = second stage only) - see the class+ /// remarks; 0.5 is the middle ground, about 9 dB/octave.+ /// </summary>private const float IntensityBlend = 0.5f;- /// <summary>4th-order stencil weight of the nearest neighbours (4/3).</summary>- private const float FourthOrderNear = 1.3333334f;+ // the 4th order "cross" stencil's coefficients: (-f(-2) + 16f(-1) - 30f(0) + 16f(+1) - f(+2)) / 12 per axis,+ // the two axes' center terms combined into one (-60/12 = -5) since both apply to the same center pixel++ /// <summary>4th-order stencil weight of the nearest neighbours (16 / 12).</summary>+ private const float FourthOrderNear = 4.0f / 3.0f;- /// <summary>4th-order stencil weight of the second-nearest neighbours (-1/12).</summary>- private const float FourthOrderFar = -0.083333336f;+ /// <summary>4th-order stencil weight of the second-nearest neighbours (-1 / 12).</summary>+ private const float FourthOrderFar = -1.0f / 12.0f;- /// <summary>4th-order stencil centre weight (2 × -5/2 for the two axes).</summary>+ /// <summary>4th-order stencil centre weight (-60 / 12, the two axes' centre terms combined).</summary>private const float FourthOrderCenter = -5f;- /// <summary>Largest eigenvalue magnitude of the 2D 4th-order stencil (2 × 16/3), for the stability estimate in <see cref="ComputeSubSteps"/>.</summary>- private const float FourthOrderLambdaMax = 10.666667f;+ /// <summary>+ /// The 4th order stencil's largest |eigenvalue| (at the grid's highest spatial frequency, kx = ky = π):+ /// 2 * (-1/12 * cos(2k) + 4/3 * cos(k) - 5/2)|k=π per axis, summed over x and y = -32/3. Used by the+ /// stability estimate in <see cref="ComputeSubSteps"/>.+ /// </summary>+ private const float FourthOrderLambdaMax = 32.0f / 3.0f;- /// <summary>Allowed c²·λmax·dt² per sub-step; 2 keeps a margin below the leapfrog stability bound of 4.</summary>+ /// <summary>+ /// How far below the hard stability limit (c² * |λmax| <= 4) sub-stepping aims to stay - chosen to give+ /// roughly the same safety margin the 3x3 kernel already has in practice (its own c² * |λmax| is about 1.8+ /// at the highest c² the app allows, i.e. about 2.2 times under the limit of 4).+ /// </summary>private const float SubStepTargetLimit = 2f;+ /// <summary>Upper bound on the periods <see cref="ComputePulsePosition"/> advances at once (guards against a tiny period).</summary>+ private const int CycleAdvanceGuard = 1000;+/// <summary>Scene width in cells.</summary>private readonly int _width;@@ -682,19 +775,29 @@ namespace _2D_wave_sim_V01/// <summary>Whether interior cells use the 4th-order stencil.</summary>private readonly bool _use4thOrderLaplacian;- /// <summary>Leapfrog sub-steps per simulation step; 1 unless the 4th-order stencil is on.</summary>+ /// <summary>+ /// Leapfrog sub-steps per simulation step (see the class remarks); 1 (no sub-stepping) unless the 4th-order+ /// stencil is on and this scene's highest c² needs it.+ /// </summary>private readonly int _subSteps;- /// <summary>Damping map applied per sub-step: <see cref="_d"/> raised to 1/<see cref="_subSteps"/>, or <see cref="_d"/> itself without sub-stepping.</summary>- private readonly float[] _dEffective;+ /// <summary>+ /// Per-cell damping applied per sub-step (padded), 1 = lossless: the scene's map itself when+ /// <see cref="_subSteps"/> = 1 (same array, so multiplying by it is bit-for-bit identical to before),+ /// otherwise a separate array of it raised to the power 1/<see cref="_subSteps"/>.+ /// </summary>+ private readonly float[] _damping;- /// <summary>1/<see cref="_subSteps"/>², scaling c² for the shorter sub-step.</summary>+ /// <summary>1/<see cref="_subSteps"/>², scaling c² for the shorter sub-step (or exactly 1.0F when _subSteps = 1, a bit-for-bit no-op multiply).</summary>private readonly float _c2Mult;- /// <summary>Per-step retention of the intensity averages: exp(-1/decaySteps) with decaySteps = timeDecayFactor·100/lowest source level.</summary>+ /// <summary>+ /// The intensity's exponential-average decay factor for this simulation (replaces the old fixed 0.98F) - see+ /// <see cref="SimulationSettings.TimeDecayFactor"/>'s doc and <see cref="IntensityRetention"/>.+ /// </summary>private readonly float _intensityAlpha;- /// <summary>Multiplier on the intensity output.</summary>+ /// <summary><see cref="SimulationSettings.IntensityScale"/>, the multiplier on the intensity output - see that property's doc.</summary>private readonly float _intensityScale;/// <summary>Current field (padded); exchanged with <see cref="_uPrev"/> after every sub-step.</summary>@@ -706,16 +809,24 @@ namespace _2D_wave_sim_V01/// <summary>Per-cell c² = 1/n² (padded; border cells 0).</summary>private readonly float[] _c2;- /// <summary>Per-cell damping from the scene (padded), 1 = lossless; source of <see cref="_dEffective"/>.</summary>- private readonly float[] _d;-- /// <summary>Second-stage running average of u² (padded), or null when intensity is not tracked.</summary>+ /// <summary>+ /// Second-stage running average of u² (padded): the 2-stage cascade's internal recursive state (12 dB/octave),+ /// no longer what is shown/exported - see <see cref="_intensityOut"/> and the class remarks. Null when+ /// intensity is not tracked.+ /// </summary>private readonly float[] _intensity;- /// <summary>First-stage running average of u² (padded), or null when intensity is not tracked.</summary>+ /// <summary>+ /// The first of the two cascaded exponential-filter stages that make up the intensity (padded; see the class+ /// remarks), or null when intensity is not tracked, same as <see cref="_intensity"/>.+ /// </summary>private readonly float[] _intensityStage1;- /// <summary>Blended and scaled intensity exposed as <see cref="IntensityData"/>, or null when not tracked.</summary>+ /// <summary>+ /// The blend of <see cref="_intensityStage1"/> and <see cref="_intensity"/> (<see cref="IntensityBlend"/>)+ /// times <see cref="_intensityScale"/> that is actually shown/exported as <see cref="IntensityData"/>, or null+ /// when not tracked.+ /// </summary>private readonly float[] _intensityOut;/// <summary>Padded cell index of every image source.</summary>@@ -725,13 +836,17 @@ namespace _2D_wave_sim_V01private readonly byte[] _sourceLevel;/// <summary>Angular frequency in radians per step for each level 0..255: level/255 × 0.5 × sourceFrequencyScale.</summary>- private readonly double[] _levelFrequency;+ private readonly double[] _levelFrequency = new double[256];/// <summary>Which levels have at least one image source; only those get a value computed per step.</summary>- private readonly bool[] _levelUsed;+ private readonly bool[] _levelUsed = new bool[256];- /// <summary>Image source value for the current step, per level.</summary>- private readonly float[] _levelValue;+ /// <summary>+ /// Scratch for <see cref="ApplySources"/>: the source value of each level in use for the current step,+ /// computed once per level and shared by every image source of that level. Kept as a field so it is not+ /// re-allocated every step; written and read only by the driving thread.+ /// </summary>+ private readonly float[] _levelValue = new float[256];/// <summary>Peak amplitude of the image sources.</summary>private readonly double _sourceAmplitude;@@ -742,18 +857,21 @@ namespace _2D_wave_sim_V01/// <summary>Padded cell index of every entry in <see cref="_objSources"/>.</summary>private readonly int[] _objIndex;- /// <summary>Random generator for randomized off-widths; used on the worker thread only.</summary>- private readonly Random _objRandom;+ /// <summary>Random generator for randomized off-widths; used by the driving thread only.</summary>+ private readonly Random _objRandom = new Random();- /// <summary>Per object source: start (in cycles) of its current period; used in randomized off-width mode only.</summary>+ /// <summary>+ /// Per object source (parallel to <see cref="_objSources"/>): the cycle-clock value (in cycles of the+ /// element's own frequency) at which its current off+on cycle started. Runtime state for pulsed sources+ /// whose off-width is re-randomized at runtime (<see cref="SourceElement.RandomizeOffWidthAmount"/>);+ /// elements that never re-randomize (the common case) never touch it: their position within the cycle is+ /// a pure function of <see cref="_time"/>, exactly as before.+ /// </summary>private readonly double[] _objCycleAnchor;- /// <summary>Per object source: off-width (cycles) in effect for its current period.</summary>+ /// <summary>Per object source (parallel to <see cref="_objSources"/>): off-width (cycles) in effect for its current period; see <see cref="_objCycleAnchor"/>.</summary>private readonly int[] _objCurrentOffWidth;- /// <summary>Upper bound on the periods <see cref="ComputePulsePosition"/> advances at once (guards against a tiny period).</summary>- private const int CycleAdvanceGuard = 1000;-/// <summary>Elapsed time in steps.</summary>private double _time;@@ -761,7 +879,7 @@ namespace _2D_wave_sim_V01private ProbeSampler _sampler;/// <summary>Point-probe samples gathered since the last <see cref="TakeProbeSamples"/>, one list per probe.</summary>- private readonly List<List<float>> _probeValues;+ private readonly List<List<float>> _probeValues = new List<List<float>>();/// <summary>Running per-pixel intensity sums for integrated line probes (null entries for other probes); null without a sampler.</summary>private double[][] _profileTotals;diff --git a/Wave_Dude_2D/Wave_Dude_2D.csproj b/Wave_Dude_2D/Wave_Dude_2D.csprojindex 9947a98..2361b8a 100644--- a/Wave_Dude_2D/Wave_Dude_2D.csproj+++ b/Wave_Dude_2D/Wave_Dude_2D.csproj@@ -67,24 +67,31 @@</Compile><Compile Include="Form1.Projects.cs"><DependentUpon>Form1.cs</DependentUpon>+ <SubType>Form</SubType></Compile><Compile Include="Form1.Output.cs"><DependentUpon>Form1.cs</DependentUpon>+ <SubType>Form</SubType></Compile><Compile Include="Form1.Scene.cs"><DependentUpon>Form1.cs</DependentUpon>+ <SubType>Form</SubType></Compile><Compile Include="Form1.Colors.cs"><DependentUpon>Form1.cs</DependentUpon>+ <SubType>Form</SubType></Compile><Compile Include="Form1.Simulation.cs"><DependentUpon>Form1.cs</DependentUpon>+ <SubType>Form</SubType></Compile><Compile Include="Form1.Probes.cs"><DependentUpon>Form1.cs</DependentUpon>+ <SubType>Form</SubType></Compile><Compile Include="Form1.Sources.cs"><DependentUpon>Form1.cs</DependentUpon>+ <SubType>Form</SubType></Compile><Compile Include="FrameRenderer.cs" /><Compile Include="frmDescription.cs">diff --git a/Wave_Dude_2D/frmDescription.cs b/Wave_Dude_2D/frmDescription.csindex a396054..29dc615 100644--- a/Wave_Dude_2D/frmDescription.cs+++ b/Wave_Dude_2D/frmDescription.cs@@ -4,29 +4,26 @@ using System.Windows.Forms;namespace _2D_wave_sim_V01{/// <summary>- /// Small modal dialog for editing a project's free-text description. <see cref="Form1"/>- /// opens it from the "Description" button, pre-fills <see cref="DescriptionText"/> and reads- /// it back when the dialog closes with <see cref="DialogResult.OK"/>.+ /// Small modal dialog that lets the user type or edit a free-form description of the current+ /// project. Opened modally from <see cref="Form1.btnDescription_Click"/>, which sets+ /// <see cref="DescriptionText"/> before <c>ShowDialog</c> and reads it back (and saves it to the+ /// project) only when the dialog returns <see cref="DialogResult.OK"/>+ /// (<see cref="btnSaveDescription_Click"/>); <see cref="btnCancelDescription_Click"/> discards+ /// any typing./// </summary>public partial class frmDescription : Form{/// <summary>Creates the dialog with an empty description.</summary>public frmDescription(){- this.InitializeComponent();+ InitializeComponent();}- /// <summary>Gets or sets the description text shown in the text box.</summary>+ /// <summary>The text being edited (the text box contents). <see cref="Form1"/> sets this before showing the dialog and reads it back after a <see cref="DialogResult.OK"/>.</summary>public string DescriptionText{- get- {- return this.TextBox1.Text;- }- set- {- this.TextBox1.Text = value;- }+ get => TextBox1.Text;+ set => TextBox1.Text = value;}/// <summary>Closes the dialog with <see cref="DialogResult.OK"/>; the edited text stays in <see cref="DescriptionText"/>.</summary>diff --git a/_tools/VB_SOURCE_AUDIT.md b/_tools/VB_SOURCE_AUDIT.mdnew file mode 100644index 0000000..84a7f99--- /dev/null+++ b/_tools/VB_SOURCE_AUDIT.md@@ -0,0 +1,253 @@+# Audit: original VB source (`2D_wave_sim_V01/`) vs the C# port (`Wave_Dude_2D/`)++Date: 2026-10-08. **Status: acted upon the same day.** The reasoning comments, doc corrections,+constant unfolds, local renames and the behaviour restorations in "Semantic differences (accidental)"+have been applied to the C# (see CLAUDE.md, "Fixed on 2026-10-08"). Deliberately not applied: the+GPL/attribution headers and `AssemblyCopyright` (the C# tree is temporary), and the decompiler+artefacts listed under "cosmetic". The line numbers below are from before those edits.++Read-only comparison of every VB file against its C# counterpart(s), looking for+what decompilation strips (comments, XML docs, local names, folded constants, `Debug.Assert`,+conditional code) and for behavioural drift. Line numbers refer to the files as they were on that date.++## Headline findings++1. **The VB source is newer than the binary that was decompiled.** The source has a GPL-3.0-or-later+ header on 31 of 38 files, `AssemblyCopyright("Copyright © 2026 JJM Vleggaar (Huygens Optics)")`,+ and a Help-tab disclaimer that says "free software, released under the GNU General Public License,+ version 3 or later". The decompiled Help text (`HelpForm.cs:32`) still says "educational use only.+ Redistribution for commercial purposes is not allowed", and `Properties/AssemblyInfo.cs:13` has+ `"Copyright © 2026"` with no author. Every other Help paragraph is string-identical, so the author+ relicensed and added headers after that build. The header text refers to "the LICENSE file that+ comes with the source code"; no LICENSE/COPYING file is in `2D_wave_sim_V01/`.+2. **Provenance lost.** Five files (`WaveSimulator`, `GpuWaveSimulator`, `FrameRenderer`, `SceneData`,+ `ColorLut`) carry "Portions of this file are based on WaveSimulator2D by 0x23+ <https://github.com/0x23/WaveSimulator2D>". That repository is Python/CuPy and has no licence file+ (checked 2026-10-08), so the note is the author's attribution, not an inherited obligation. The C#+ docs also dropped every reference to the Python original (`main_curr.py`, `WaveVisualizer.render_field`+ / `render_intensity`, `get_colormap_lut`, `StaticImageScene` / `StaticRefractiveIndex` /+ `StaticDampening`, matplotlib `_r` maps), which is where several magic numbers come from.+3. **Code is faithful.** No logic bug was introduced by decompilation. The divergences found are listed+ under "Semantic differences"; all are small, and most are deliberate post-decompile fixes.+4. **Two CLAUDE.md "known issues" are wrong.** The differing `FromConfig` fallbacks and the+ `Use4thOrderLaplacian`/`WaveSpeedC` defaults are documented by the author as deliberate+ old-project compatibility (see `SimulationSettings.vb:47-49, 92-103, 106-119`). The GpuWaveSimulator+ `TryCreate` doc in the VB overstates its own code, which is the root of the "dead branch in+ `WaveEngineFactory.Create`" entry.+5. **What was stripped**: 1,409 lines of `'''` XML docs and 1,242 `'` comments in the VB. The C# docs+ were written fresh and are often more complete on threading and layout, but the author's *rationale*+ (why a formula, why a workaround, why a default is absent) is largely gone. Roughly 150 comment sites+ are listed below with the C# location they belong at. Nothing else was stripped: the VB has no+ `#If` blocks, one `Debug.Assert` (kept), no `Obsolete`, no `Static` locals, and all `Optional`+ defaults survived.++## Semantic differences (code)++Accidental, original behaviour is the VB:++| C# location | VB location | Difference |+|---|---|---|+| `AviMjpegWriter.cs:82` | `AviMjpegWriter.vb:108` | strh `dwQuality` written as `0U`; VB writes `&HFFFFFFFF` ("default"). C# comment says "(default)" which is wrong for 0. Readers ignore it for MJPG. `avi_check` does not test offset 148. |+| `WaveSimulator.cs:372` | `WaveSimulator.vb:135, 433` | `new float[256]` allocated on every `ApplySources` call; VB reuses a `Private ReadOnly _levelValue(255)` field. 1 KB per step. Side effect of the field-to-local cleanup. |+| `ColorSchemeStore.cs:46` | `ColorSchemeStore.vb:62` | `FindDefaultFolder` probes for `*.vbproj`. The only `.vbproj` is a sibling of `Wave_Dude_2D/`, so the C# exe never finds the repo's tracked `ColorSchemeList/` and creates an empty `bin\Debug\ColorSchemeList`. The vbproj also had `<Content Include="ColorSchemeList\*.json" CopyToOutputDirectory=PreserveNewest>`; the csproj has no such item. |+| `ProbeGraphPainter.cs:138, 196`; `ProbeSettings.cs:143` | `ProbeGraphPainter.vb:123, 159`; `ProbeSettings.vb:142` | `If Not (yMax > yMin)` became `if (yMax <= yMin)`. NaN limits no longer reset to -1..1. Reachable from UI-entered values. |+| `ProbeSampler.cs:87` | `ProbeSampling.vb:214` | `Measurement > Amplitude` instead of `<> Amplitude`; `ProbeGraphPainter.cs:222` still uses `!=`, and `ProbeMeasurement.cs:5-6` documents the `>` as a contract. |+| `Form1.Colors.cs:708` | `Form1.vb:3131` | `StopRole` centre case is `case 4:`; VB is `If StopCount Mod 2 = 1 AndAlso k = StopCount \ 2`. Same today, diverges if `StopCount` becomes even. |+| `Form1.cs:85` | `Form1.vb:109` | `Debug.Assert(_stopButtons.Length == 9, ...)`; VB compares with `ColorScheme.StopCount`, so the assert no longer guards what its message says. |+| `GpuWaveSimulator.cs:634-644` | `GpuWaveSimulator.vb:791` | `_sinceFinish = 0` only inside `ReadBack`; VB resets it on every `PrepareFrame`. Harmless. |+| `Form1.Simulation.cs:1366` | `Form1.Designer.vb:4130` | `colCreatedOn2` is `protected internal virtual` property in the Simulation part; VB declares it `Protected Friend WithEvents` in the Designer (accidental accessibility in the original). Belongs in `Form1.Designer.cs` as a private field like `colCreatedOn`. |+| `Form1.cs:1170` | `Form1.vb:1835` | `NativeSize` lost `[StructLayout(LayoutKind.Sequential)]` (default is the same, intent lost). |++Deliberate post-decompile fixes, original is the VB (keep, but feed back to the author):++| C# location | VB location | Difference |+|---|---|---|+| `AviMjpegWriter.cs:174` | `AviMjpegWriter.vb:182` | movi LIST size: VB writes `end - 216` (includes the size DWORD, off by 4); C# writes `end - 220`. Proven by `avi_check`. The current C# header is otherwise byte-identical to the VB's 224-byte layout. |+| `GpuWaveSimulator.cs:719-731` | `GpuWaveSimulator.vb:848-873` | `SetProbes(null)` releases the old set (VB returned early and leaked). On failure the C# leaves no probes installed and throws "the intensity is not tracked" bare; VB kept the previous probes working and prefixed "the probes could not be set up on the GPU: ...". |+| `GpuWaveSimulator.cs:734, 489-506` | `GpuWaveSimulator.vb:859, 665-681` | Probe program and failed buffers are released; VB leaked them. |+| `IWaveEngine.cs:12` | `IWaveEngine.vb:31` | Interface no longer extends `IDisposable` (project convention). |+| `Form1.Output.cs:418` | `Form1.vb:1560-1563` | `btnDeleteScene_Click` uses `SelectedFilePaths` (skips null tags) instead of `DirectCast(item.Tag, String)`. |+| `SimulationRunner.cs:534`, `Form1.Probes.cs:809` | `SimulationRunner.vb:161`, `Form1.Probes.vb:699-700` | `_collector` kept for still exports (VB comment explains it); redundant status-label clear dropped. |++Decompiler artefacts with identical behaviour (cosmetic, fix when touching the file):++- `MessageBoxIcon.Information/Warning/Error` → `Asterisk/Exclamation/Hand`; `Keys.Enter` → `Keys.Return` (all Form1 parts).+- `OpenClApi.cs:42, 50`: `[MarshalAs(UnmanagedType.VBByRefStr)] ref string` for `options`/`kernelName` is what the VB compiler emits for by-value `String`; idiomatic C# is plain `string`, which removes the `ref string name` dance at `GpuWaveSimulator.cs:486-488, 530`.+- `OpenClApi.cs:14`: VB `Module` became `internal sealed class` with a public constructor; should be `static class`.+- `SimulationRunner.cs:538-550`: nested `*EventHandler` delegates are the VB compiler's expansion of `Public Event X(args)`; `Action<...>` is the hand-written form.+- `SimulationJob.cs:13-19`, `SimulationResult.cs:15-23`, `ProbeSeries.cs:11-14`, `ProbeSettings.cs:18-39`, `GpuDeviceInfo.cs:13-17`, `ColorPickerControl.cs:43-45`, `Form1.cs:33-69`: constructors that are expanded VB field/property initialisers.+- Expanded `Optional` arguments at call sites: `ColorLut.Build(scheme, false, blackLevel, false, false)` (`Form1.Simulation.cs:738, 749`), `InputBox(..., -1, -1)` (`Form1.Colors.cs:351`), `RefreshOutputProjectList("")` (`Form1.Output.cs:33, 65`), `SetOutputPreviewImage(null, false)` (`:401`).+- `MfVideoWriter.cs` qualifies every static call as `MfVideoWriter.X(...)`.+- `My/*.cs` carry ILSpy `// Token: ...` lines; `Properties/AssemblyInfo.cs:2,4,6` has unused usings.+- `ProbeControlSet` constructed with 22 positional arguments (`Form1.Probes.cs:67-68`); VB used named arguments (`Form1.Probes.vb:169-180`).++## C# docs that are wrong or stale++| C# location | Problem | VB authority |+|---|---|---|+| `SimulationJob.cs:48, 51` | `FieldLut/IntensityLut` "null when neither export nor preview is wanted". Null means grey levels; `FrameRenderer.Colorize` renders grey when the LUT is null. | `SimulationRunner.vb:53` |+| `SimulationJob.cs:72-75` | `GlowOverlay` "null when not exporting or both gains are 0". VB: null when there is no scene image or both gains are 0; frozen at run start. | `SimulationRunner.vb:71-74` |+| `SimulationSettings.cs:110-113` and CLAUDE.md | Per-key fallbacks presented as an anomaly. They are deliberate: old projects keep their exact behaviour; new projects take the Designer values via `StartNewProject`. | `SimulationSettings.vb:47-49, 92-103, 106-119, 122-139` |+| `SceneSettings.cs:16-26` | Constructor silently omits `DampingEdgeEnabled`/`UseObjectSources` with no explanation (same deliberate no-default design). | `SceneSettings.vb:72-75, 85-87` |+| `SourceElement.cs:84-88` | Says both engines "hard-code 30 rather than referencing this constant". Stale: both use `DetachRampSteps` now. `GpuWaveSimulator.cs:388` comment still says "30 steps". | — |+| `WaveSimulator.cs:644` | `_subSteps` "1 unless the 4th-order stencil is on". Also 1 when the scene's c² does not need it. | `WaveSimulator.vb:65-71, 197-199` |+| `WaveSimulator.cs:608` | `NominalDecayLevel` described only as a fallback; it is the calibration constant in the τ formula, and `IntensityRetention` (`:356`) hard-codes `100.0` instead of using it. | `WaveSimulator.vb:79-80` |+| `GpuWaveSimulator.cs:19-20` | "Kernel launches and uploads are asynchronous". Uploads are blocking (`blocking = 1U` at `:513, 522`; `:508` says so). | — |+| `ColorLut.cs:44, 39-40` | `blackLevel` documented as 0..1 and lifting only; VB: "Lifts (positive) or lowers (negative)". | `ColorLut.vb:67` |+| `ColorScheme.cs:29-32` | `SchemeType` "decides which combo box offers the scheme"; VB adds "only a label saved in the file; any scheme can technically be used for either". | `ColorScheme.vb:59-62` |+| `ProbeSettings.cs:92` | `UseStartAfterStep` "sampling/accumulation and the graph are gated". Sampling is not gated; the collector keeps sampling and zeroes the cumulative total. "(0 = from the start)" dropped. | `ProbeSettings.vb:111`, `ProbeSampling.vb:303-307` |+| `ProbeMeasurement.cs:5-6` | Documents the `>` comparison as an engine rule (see semantic table). | `ProbeSampling.vb:214` |+| `FrameRenderer.cs:106-113` | `ToRgbBytes` "any size; clipped or padded". VB: a format normalisation, not a resize; the one caller already passes the right size. | `FrameRenderer.vb:90-93` |+| `Form1.Scene.cs:24`, `Form1.Probes.cs:57-58` | "Called once from the constructor". Both are called from `Form1_Load` (`Form1.cs:123, 125`). | `Form1.vb:161, 163` |+| `Form1.Scene.cs:329` | "0.25 keeps a full-contrast step edge (gradient 4 * 255) just within the byte range". VB: a hard edge reaches ~1442 raw; `GlowScale` brings that into range "without every ordinary edge saturating", and a diagonal full-contrast edge does saturate. | `Form1.vb:2109-2121` |+| `Form1.Simulation.cs:15` | The only Form1 part with no class-level summary. | `Form1.vb:3156-3161` |+| `AboutForm.cs:45` | `DisplayVersion` doc dropped the link to the Form1 title bar it is kept in sync with. (VB comment itself is stale: "V0.25", "Wave Maker".) | `AboutForm.vb:33-34` |+| `Form1.Output.cs:745` vs `Form1.vb:1865` | C# documents `COMException`; VB says "never throws". The C# is right (PreserveSig=false). Do not "fix" back. | — |+| `GpuWaveSimulator.cs:39-40` vs `GpuWaveSimulator.vb:176-177` | VB claims `problems` also explains earlier failures when a later GPU worked; its code does not. C# documents the actual behaviour. | — |++## Folded constants (name exists, literal used)++| C# location(s) | Literal | VB expression |+|---|---|---|+| `ColorLut.cs:157` | `255` | `ColorScheme.EntryCount` |+| `ColorScheme.cs:160, 197, 199-201` | `254`, `8.0`, `7` | `EntryCount - 1`, `StopCount - 1`, `StopCount - 2` |+| `Form1.cs:85`; `Form1.Colors.cs:635, 696, 706, 708` | `9`, `8.0`, `8`, `4` | `ColorScheme.StopCount` and derived |+| `Form1.Colors.cs:653, 654, 659, 676, 696, 734` | `127`, `254` | `EntryCount \ 2`, `EntryCount - 1` |+| `Form1.Simulation.cs:108, 109, 140, 141, 731, 742` | `"field"`, `"intensity"` | `ColorScheme.SchemeTypeField/Intensity` (Form1.Colors.cs still uses the constants) |+| `Form1.cs:93`; `Form1.Colors.cs:729, 732, 734, 737, 740` | `120`, `16`, `119`, `15` | `ThumbWidth`, `ThumbHeight` (declared at `Form1.cs:959-962`, unused) |+| `Form1.Output.cs:562, 697`; `Form1.Simulation.cs:1195, 1214` | `1`, `4` | `FVM_ICON`, `FVM_DETAILS` (declared at `Form1.cs:1084-1087`, unused; VB `:4223-4225` comments "Windows Explorer's own view-mode numbers (the classic Shell FOLDERVIEWMODE enum)") |+| `Form1.Scene.cs:38, 625, 754, 773` | `1000m`, `8192`, `8`, `16384` | `SceneSettings.MaxImageSourceScale`, `MaxDampingEdgeSize`, `MinCanvasSize`, `MaxCanvasSize` |+| `Form1.Probes.cs:87, 227, 228`; `Form1.Sources.cs:34, 37, 48, 51, 673` | `16383`, `16384` | `SceneSettings.MaxCanvasSize - 1`, `MaxCanvasSize` |+| `Form1.Scene.cs:330` | `0.25` | local `Const GlowScale` |+| `Form1.Simulation.cs:1259, 1261, 1264, 1270, 1286` | `BindingFlags.InvokeMethod \| BindingFlags.GetProperty` | local `Const memberFlags` |+| `Form1.Sources.cs:979, 994` | `0.7f`, `3f`/`6f` | local `Const marginFraction = 0.15F` (`1 - 2*margin`), `Const dotRadius = 3.0F` |+| `ProbeGraphPainter.cs:787-790` | `7f` (x8) | local `Const arm = 7.0F` in `DrawCross` |+| `WaveSimulator.cs:515, 516` | `0.35` | local `Const EdgeWidth` in `PulseEnvelope` |+| `WaveSimulator.cs:356` | `100.0` | `NominalDecayLevel` |+| `WaveSimulator.cs:615, 618, 624` | `1.3333334f`, `-0.083333336f`, `10.666667f` | `4.0F / 3.0F`, `-1.0F / 12.0F`, `32.0F / 3.0F` |+| `MfVideoWriter.cs:66, 301, 141, 59-60` | `9437184L`, `131184`, `4294967297UL`, `& -2` | `4096L * 2304L`, `&H20070`, `(1UL << 32) Or 1UL`, `And Not 1` |+| `OpenClApi.cs:292-319` | decimal | `&H1084, &H902, &H1002, &H100C, &H1010, &H101F, &H102B, &H102C, &H1035, &H1183` (cl.h spelling) |+| `Project.cs:42, 45, 48, 51, 54` | `"configuration.json"`, `"assets"`, `"output_frames"`, `"output_video"`, `"scene_images"` | `ProjectConfig.FileName`, `ProjectStore.*FolderName` |+| `ProjectStore.cs:111, 115` | in messages | `ProjectConfig.FileName`, `LegacyFileName` |++Doc-text folds that will go stale: `ColorScheme.cs:8, 135, 151-152, 185, 196`; `ColorSchemeStore.cs:17`; `Form1.Sources.cs:23-24, 660`; `Form1.Probes.cs:220`; `Form1.Scene.cs:617, 742`; `GpuWaveSimulator.cs:388` ("30 steps"); `WaveSimulator.cs:36` ("100/level").++## Local names where the VB is better++| C# | VB | Where |+|---|---|---|+| `source` (probed buffer) | `data` | `WaveSimulator.cs:216, 282` ("source" means wave source in that class) |+| `cycles`, `shifted`, `period`, `i`, `fade`/`sinceDetach`, `i`/`j`, `lowest` | `cycleClock`, `adjustedClock`, `dynPeriod`, `subStep`, `detachFade`/`stepsSinceDetach`, `p`/`k`, `minActiveLevel` | `WaveSimulator.cs:431, 441, 448, 163, 389-392, 212-275, 330` |+| `i`, `random` | `subStep`, `seedRng` | `GpuWaveSimulator.cs:611, 255` |+| `framePixels`, `fieldOverlay`/`intensityOverlay`, `canvas` | `fullPixels`, `fieldOverlayScaled`/`intensityOverlayScaled`, `normalized` | `SimulationRunner.cs:250, 255-256`; `FrameRenderer.cs:117` |+| `lastStepsDone`, `series`, `t`, `i`/`j`+`y`/`x`, `tickCount` | `batchStartStep`, `samples`, `fraction`, `y`/`x`+`fy`/`fx`, `guard` | `ProbeCollector.cs:48, 123`; `ProbeGraphPainter.cs:600, 287`; `ProbeOverlay.cs:75-85` |+| `i`, `overlayBrush`, `dir`, `name` | `y`, `veil`, `probe`, `schemeName` | `ColorPickerControl.cs:365, 299`; `ColorSchemeStore.cs:44, 89` |+| `arraySizeX/Y`, `i`/`j` | `cols`/`rows`, `row`/`col` | `SourceSettings.cs:239-244` |+| `frequency` (it is the 1-255 level) | `level` | `Form1.Sources.cs:616` |+| `width`/`height`, `source`, `spacings`, `bitmap`, `box` | `boxW`/`boxH`, `shown`, `relevantSpacing`, `placeholder`, `rect` | `Form1.Sources.cs:962-963, 885, 677, 784`; `Form1.Probes.cs:697, 934` |+| `location`, `size`+`canvas` (bitmap), `bytesPerPixel`, `center`, `loadingSim`, `path`/`folder`, `fileName`, `target`, `projectName` | `rootButtonSpot`, `canvas`+`fresh`/`placeholder`, `bytesPerDstPixel`, `cMid`, `wasLoading`, `imagePath`/`videoPath`/`projectFolder`, `oldName`, `targetPath`, `projectLabel` | `Form1.cs:130, 789`; `Form1.Scene.cs:542-592, 395, 314`; `Form1.Simulation.cs:136, 250, 268, 1248`; `Form1.Output.cs:327-689, 653` |++Everywhere else the C# names are equal or better than the VB.++## Lost documentation, by file (VB line → C# line)++Quote the VB text at the given C# location. Items marked **why** carry rationale that is nowhere else.++### WaveSimulator.vb → WaveSimulator.cs+- Class summary `:30-71` → `:8-23`: Python lineage ("port of the Python class WaveSimulator2D (CuPy)", sources applied "as in update_scene / StaticImageScene.update_field"); **why** two-stage intensity (single pole 6 dB/octave never removes the ripple at the source frequency; two stages 12 dB/octave but over-delay short pulses; blend ≈ 9 dB/octave); alpha scales inversely with the slowest source frequency × TimeDecayFactor; border "so that the step needs no edge tests"; 4th-order **why** (dispersion: under-resolved wavelengths travel slower; ~2× memory reads; coefficients reach ~7× further at the highest spatial frequency; instability symptom "everywhere saturates except at object edges"); sub-step scaling (c² by 1/n², d by its n-th root, so n sub-steps equal one ordinary step exactly; n is 1 whenever 3×3 is used *or the scene's c² does not need it*).+- Ctor params `:165-169` → `:33-37`: sourceAmplitude "(1 = the value of the Python code)"; trackIntensity "(costs extra time in every step)"; timeDecayFactor/intensityScale "see that property's comment" in SimulationSettings.+- `Stride` `:290` → `:128`: "Pixel (x, y) is at (y + 1) * Stride + x + 1". `FieldData`/`IntensityData` `:297, 304` and `IWaveEngine.vb:42, 45` → `:131-138`, `IWaveEngine.cs:26-34`: "Do not change."+- Constants `:79-97` → `:608-626`: `NominalDecayLevel` "nominal source level (of 255) that TimeDecayFactor's steps count is calibrated against"; `IntensityBlend` "0.5 is the middle ground, about 9 dB/octave"; 4th-order derivation "(-f(-2) + 16f(-1) - 30f(0) + 16f(+1) - f(+2)) / 12 per axis, -60/12 = -5" (and `' 16 / 12`, `' -60 / 12` tags); `FourthOrderLambdaMax` "2 * (-1/12 cos 2k + 4/3 cos k - 5/2)|k=π per axis, summed = -32/3"; `SubStepTargetLimit` **why** "the 3x3 kernel's own c² |λmax| is about 1.8 at the highest c² the app allows, i.e. about 2.2 times under the limit of 4".+- Fields `:106-111, 146-147` → `:647-653, 701-705`: `_dEffective`/`_c2Mult` are "the original _d itself / exactly 1.0F, a bit-for-bit no-op"; `_intensityAlpha` "(replaces the old fixed 0.98F)"; non-randomising elements "never touch this state: pure function of _time, exactly as before".+- `ComputePulsePosition` `:474-493` → `:415-431`: return range "(0 = the very start of the 'off' span, up to but not including its current period)"; **why** "a single/non-randomized source sitting silent for its off-width at the very start of a run was never the intent, only a side effect of the cycle position formula"; randomized elements keep the off-first start "since there the elements are meant to desynchronize from a common starting point"; "every source keeps its own, independently-drifting rhythm"; "cycles of the source's own frequency since t = 0 (not folding in the phase, so the on/off timing does not shift when only the phase is changed)".+- `PulseEnvelope` `:535-575` → `:474-516`: off precedes on "so every source is silent for its own off-width before its first pulse, rather than every source firing simultaneously at t = 0"; Gaussian "tapers smoothly to (about) 0 at both ends"; SmoothedSquare "atan-smoothed square wave, avoiding a hard on/off step that would ring the field"; "FIXED-width (in cycles, not a fraction of the on/off span) smoothed edge"; **why** the first-cycle guard (wrapping in the very first off-span "would fabricate a phantom falling edge: pos = 0 would land exactly on it and start the run at envelope ~0.5 instead of ~0, emitting a spurious one-cycle blip; left un-wrapped (deeply negative), dRise/dFall correctly place it far from both edges"); "0 at the falling edge, grows past it" / "0 at the rising edge" / "signed distance to the *nearest* rising edge".+- `UpdateField` `:586-588, 615-617` → `:533, 561`: intensity on the last sub-step only "so its own exponential averaging still runs once per AdvanceOneStep call, from the field after all sub-steps, matching its calibration regardless of how many sub-steps"; the fallback ring "(y = 0, y = h - 1, x = 0, x = w - 1) falls back to the original 3x3 kernel".+- Inline `:197-199, 235, 252-254, 272-273, 351-352, 445-448, 527-529` → `:64, 97, 119, 116, 221, 389, 465-469`: sub-steps stay 1 unless 4th-order *and* the scene's highest c² needs it; "a randomized composite element can fall outside" the canvas; the slowest-source rule "(a level of 0 means 'no source' and is excluded)"; "the very first cycle uses the off-width rolled at Generate time; later cycles redraw from OffWidthBase"; "before 'start after step' the totals are simply never added to: earlier intensity is purged rather than baked in"; **why** detach fades "then stops driving the field entirely (not even towards 0) so it releases its hold and stops diffracting waves through that point. A hard cutoff would leave a small kink in the forcing, which can ring"; "should not happen (_time only increases)"; "the anchor only advances once a cycle has completed, so it still reading 0 means no cycle has completed yet".+- `IWaveEngine.vb:52-53, 71, 86` → `IWaveEngine.cs:39-42, 61-63`, `WaveEngineFactory.cs:17-34`: PrepareFrame "so only ask for what is going to be drawn"; ReadProbeProfiles "On the GPU this waits for the card, so do not call it every step"; "Object sources run on either engine, the same as the image sources".++### GpuWaveSimulator.vb / OpenClApi.vb → GpuWaveSimulator.cs, GpuDeviceInfo.cs, OpenClApi.cs+Kernel text is token-identical; the only kernel-internal comments (`:633-636`) survived.+- Class summary `:30-55` → `:7-15, 309, 592-593, 157-168`: the scheme as formulas, "(why two stages and the blend, not the single, fixed-0.98 filter)", pointers to `SimulationSettings.TimeDecayFactor`/`IntensityScale`; the `#define` "so there is no extra cost when it is off"; "matching the CPU engine and its own earlier calibration"; "c2Scale exactly 1.0F, an exact no-op multiply".+- `KernelSource` `:486-489` → `:306-310`: **why** c2Scale and intensityAlpha "are runtime kernel arguments rather than a #define, so they need no text formatting/locale handling" (the C# does splice `DetachRampSteps` as an integer, which is safe; floats are deliberately not spliced).+- `TryCreate` `:178` → `:28-42`: "Throws DllNotFoundException when there is no OpenCL driver."+- `OpenClApi.vb:28-31` → `OpenClApi.cs:8-13`: "OpenCL 1.2", "NVIDIA, Intel and AMD all install it", type mapping "size_t is an IntPtr, cl_bitfield a ULong, cl_uint a UInteger and cl_bool a UInteger".+- Inline `:227-228, 318, 327-329, 449-450, 525-526, 545-548, 557-563, 574-577, 594-596, 618-619, 638-644, 775, 818-820, 123-126, 75-76` → `:92-103, 181, 200, 274, 323, 374, 383-394, 388, 422, 443, 461, 595, 679-681, 391-392, 200`: canvas filter "(a randomized composite element can fall outside)"; the level-to-frequency table "shared by the image sources and the object sources"; the slowest-source rule; **why** args 13-16 "appended rather than renumbering 0-12, so every SetMem/SetInt call keeps its existing index"; the kernel's `0.5f` is `WaveSimulator.IntensityBlend`; **why** xorshift ("OpenCL has no built-in RNG ... matches WaveSimulator's RandomInt only in spirit, not bit-for-bit: the two engines are not expected to reproduce each other"); off-first ordering; detach "releases its hold and stops diffracting"; the t=0 clock shift; the anchor-reads-0 meaning; the seven-line phantom-falling-edge explanation (same as the CPU one above); clFinish "so errors show up in time"; purge "rather than baked into the total"; rngState "only the entropy bits matter, not signedness"; "(replaces the old fixed 0.98f in the kernel)".+- `GpuDeviceInfo.Discrete` `OpenClApi.vb:190` → `GpuDeviceInfo.cs:106`: examples "(the NVIDIA GeForce) ... (Intel UHD)".++### SimulationRunner.vb → SimulationRunner.cs, SimulationJob.cs, SimulationResult.cs+- `:118-122` → `:9-14`: "as the loop in main_curr.py".+- `:77-82` → `SimulationJob.cs:78-82`: overlay gains "frozen at the start of the run from numBrightnessFieldOverlay/... and chkDiplayOverlayInField/...; **only affects the exported videos**: the live preview blends its own copy on the UI thread, which can track the checkbox live; a running export cannot".+- `:105, 109-113, 131, 142-145, 183, 479-480` → `SimulationResult.cs:49, 55-59`; `SimulationRunner.cs:51-55, 513, 98-101, 471-474`: Engine examples `"CPU (8 threads)"`, `"GPU: NVIDIA GeForce MX130 (OpenCL)"`; last frames "rendered right before the engine was closed down, so a still export has something to save once the live engine no longer exists"; ProbesUpdated "The receiver owns the arrays"; **why** `PreviewIntervalMs` ("keeps a GPU engine's readback rate steady and independent of how fast the UI thread displays the previous one, rather than riding on _previewPending alone; ~30 fps is already faster than a picture box is usefully watchable at"); PauseRun "The videos stay open"; OpenSink fallback reasons "(no Media Foundation, size not supported)".+- Inline `:161-163, 294-296, 349, 355-368, 373, 404, 418, 432, 436-491` → `:534, 255, 319, 327, 333, 371, 384, 403, 410-501`: `_collector` kept "so RenderCurrentFrame can also burn the probe markers/graphs onto a still export (the video loop already did, stills did not)"; overlay "gain-prescaled once, up front; this was the actual cost of the overlay on a video export"; "the probe values up to this step (the graphs in the videos need them)"; the 14-line `previewDue` **why** (GPU readback cost riding on UI speed; the overlay checkboxes made the run *faster*; a video export forces a readback anyway so it was never visible there); "a GPU engine copies only the data that is going to be drawn"; "about 20 times a second"; "close the videos, also after a stop or an error, so that the files can be played"; the empty-catch reasons ("nothing more can be done", "no still frame this time - not fatal", "an empty leftover file does no harm").++### FrameRenderer.vb, FrameSink.vb, SceneData.vb → FrameRenderer.cs, IFrameSink.cs, AviFrameSink.cs, SceneData.cs+- `FrameRenderer.vb:31-37, 61` → `:9-14, 54-58`: "like WaveVisualizer.render_field and render_intensity"; "(exponent 0.5, as in the Python code)".+- `:90-93, 125-131, 143-151` → `:106-113, 153-158, 173-176`: ToRgbBytes is "just a format normalization, not a real resize"; **why** ScaleOverlayRgb ("so AddOverlay's per-frame, per-pixel work is a plain add instead of a float multiply and CInt per byte per frame; gain is fixed for the whole run"); AddOverlay "never darkens ... parallelized by row since this runs once per exported frame at full resolution and was the actual cost of the glow-edges overlay; the live preview's ComposeGlowOverlay is kept separate since it runs on the UI thread against a Bitmap".+- `FrameSink.vb:41-44` → `AviFrameSink.cs:8-12`: "Windows' own players do not play it; VLC does."+- `SceneData.vb:31-42, 87, 117-118, 158` → `:9-18, 63-66, 97-101, 162-167`: "(the time step is 1)"; "the rules are those of the Python classes StaticImageScene, StaticRefractiveIndex and StaticDampening"; "Format32bppArgb is stored as B, G, R, A"; Empty uses "the same rule as a scene image's red channel: index = red / 100"; ApplyBorder "as in StaticDampening".++### MfVideoWriter.vb, AviMjpegWriter.vb → MfVideoWriter.cs, IMF*Native.cs, AviMjpegWriter.cs+- `MfVideoWriter.vb:25-29` → `IMFSampleNative.cs:6-11`, `IMFAttributesNative.cs:6-11`: **why** "Every interface repeats the methods of IMFAttributes because .NET does not inherit them in COM interfaces."+- `:137-142, 146, 216-217, 231` → `:6-12, 300, 80-83, 94`: "the encoder that is built into Windows, so no codec is needed and every Windows player opens the file"; "(MF_VERSION of the Windows 7 and later SDK)"; bitrate examples "0.01 at quality 1, 0.15 at 70 and 0.5 at 100 (1920 x 1080 at 60 frames/s: 1 to 62 Mbit/s)"; "the pictures are given as 32 bit pixels; the sink writer converts them for the encoder".+- `AviMjpegWriter.vb:27-31, 40, 70, 92` → `:8-13, 194, 45, 66`: "VLC and most video editors play the file; ffmpeg can convert it to MP4"; "(unsigned 32 bit sizes)"; `192` = "'hdrl' + avih chunk (64) + strl list chunk (124)"; `116` = "'strl' + strh chunk (64) + strf chunk (48)".++### ProbeSampling.vb, ProbeGraphPainter.vb, ProbeSettings.vb → Probe*.cs+- `ProbeSampling.vb:25, 38, 132-139, 153-156` → `ProbeSeries.cs:5-8, 19-22`; `ProbeSampler.cs:6-12, 186-190`: "(value i belongs to step i + 1)"; "Do not change."; the four-case table (point / point integrated → collector sums / line → profile on demand / line integrated → engine sums per pixel); **why** UseStartAfterStep purges "so the total shown once recording starts is not inflated by intensity that arrived before it - see ProbeCollector.Collect, WaveSimulator.SampleProbes and the profile_accumulate kernel".+- `ProbeSampling.vb:291-292, 304-305` → `ProbeCollector.cs:48, 67-71`: `batchStartStep` meaning; "keep the running total at zero ... so the total does not jump the moment recording starts".+- `ProbeGraphPainter.vb:96-100, 174, 260-261, 266-267, 276-277, 322, 330, 561` → `ProbeGraphPainter.cs:95-100, 222, 353-354, 359, 369-372, 453, 459`; `ProbeOverlay.cs:30-36`: **why** point probes are trimmed (xMin never below the start step, "more room for the data that follows, especially with the full scale") while line probes stay blank ("a profile of the current instant has nothing meaningful to show before the start step"); "a point probe's own range/autoscale must see the real trace; only a line probe uses shownTrace"; "an intensity starts at zero"; axis labels "value axis" / "step axis (point) or position on the line (line)"; Burn "the frame is the whole scene, so the box is where the probe says (in scene pixels)".+- `ProbeSettings.vb:93-97, 162` → `ProbeSettings.cs:71-72, 176-177`: Active "Off by default for both probes of a new project; a probe loaded from a project saved before 'active' was written still comes back On, so that project keeps its exact previous behavior"; Title "The number is also drawn at the probe in the picture."+- VB enums give explicit numeric values (`ProbeSettings.vb:29-62`); the C# enum files rely on implicit numbering (values identical; they drive the combo-box index).++### SimulationSettings.vb, SourceSettings.vb, SceneSettings.vb, Projects/*.vb → *.cs+- `SimulationSettings.vb:26-42, 47-49, 64-66, 70-75, 81, 86, 92-103, 106-119, 122-139, 142-153` → `:7-11, 244-245 (replace remarks 110-113), 55-59, 61-65, 73, 79, 85, 88-92, 94, 97`: keys "with no control on the screen yet but editable in the file: field_brightness, intensity_brightness, field_black_level, intensity_black_level, source_frequency_scale, video_fps"; "defaults are those of the Python example (main_curr.py)"; **why** Steps/TimeDecayFactor have no software default ("a new project starts at whatever the Designer value is; DefaultSteps is only the fallback for a project saved before 'steps' existed"); scheme name match "exact name (case-insensitive) and matching SchemeType, otherwise nothing selected"; FieldBrightness "render_field(7) in Python; 30 is high enough to see a single source"; SourceFrequencyScale "multiplies the frequency of the sources that come from the green channel"; VideoQuality "1 (small files) to 100 (best picture, large files)"; Use4thOrderLaplacian full description + **why** old projects load Off; WaveSpeedC **why** 0.563 ("found experimentally to be correct at around a source frequency of 100, kept only so such a project's displayed wavelength estimate does not change; not a global setting"); TimeDecayFactor **why** an EMA ("raw Sqr(field) would flicker at twice the source frequency"), the print-through vs trail trade-off, "the number of steps that time constant works out to at a nominal medium source (green level 100)"; IntensityScale "changes the actual numbers in the preview, the videos, the probe data and exported files, unlike the brightness settings; exists because the raw intensity lands around 1e-5".+- `SourceSettings.vb:29, 27, 92-97, 131-134, 137-140, 143, 151, 371-375, 418-420` → `SourceMainType.cs:12, 5-9`; `SourceElement.cs:84-88`; `SourceSettings.cs:72, 75, 78, 88, 426-428, 473`: "Named Simple (not Single) because Single is a reserved VB keyword"; "(or line, in a future version)"; DetachRampSteps **why** ("an abrupt cutoff leaves a small kink in the forcing, which can ring; shared by both engines so the two stay in exact agreement"); a skipped source "neither drives the field nor gets in the way of waves passing through its position"; detach **why** ("a source that keeps driving the field holds it at a fixed value there, which diffracts waves that later pass through"); DetachAfterSteps "(0-based)"; Amplitude "100 matches numAmplitude's Designer default"; the three legacy-key comments (`has_position` defaults True "since its sources were positioned under the old rules"; SourceOn/DetachSource "default to the behavior it always had: on, and never detaching"; `off_width_base` "defaults to this element's own off_width_cycles (already read above), exactly its anchor under the old always-static behavior").+- `SceneSettings.vb:27-38, 46, 58, 72-75, 82, 85-87` → `:8-12, 220-227, 55/245-251, 40-41, 49, 52-53`: "the size of a scene image is not stored: it is read from the image"; "no scene-level 'use probes' switch: each probe has its own On"; image path "relative to the project folder when inside it (forward slashes)"; "defaults are those of the Python example (1920 x 1080 canvas, 64 px damping edge)"; refractive index "1.0 to 2.55 (a red channel value of 100 to 255, as in a scene image)"; DampingEdgeEnabled/UseObjectSources **why** no default and the False fallback; ImageSourceScale "source_amplitude of StaticImageScene".+- `ProjectStore.vb:27-33, 55-58, 218`; `Project.vb:78-79` → `ProjectStore.cs:269, 22-28, 245-247`; `Project.cs:44`: assets "where the user keeps third-party files, such as the original Photoshop file of a scene image; not read or written by the simulator"; ValidateName "The name is never changed silently"; "a folder that cannot be created is reported when it is needed".+- `ProjectConfig.vb:30-40, 49, 58, 108, 144-147` → `:11-21, 406, 424-425, 61, 103`: the worked example of adding a section; **the forward-compatibility contract** "Keys that this version does not know are kept and written back unchanged, so a file written by a newer version is not damaged by an older one (refused when format_version is newer)"; "Increase it when a change makes old files incompatible"; `_values` "insertion ordered in practice, so the file keeps a stable, readable order"; "(Form1's btnDescription/frmDescription)"; SetValue accepted types "String, Boolean, numbers, Nothing, a Dictionary(Of String, Object) or a list or array of these".+- `AppSettings.vb:42-44, 81` → `:38-43, 97-99`: ProjectRoot vs LastRootFolder/LastProjectName distinction; "the settings are a convenience only".++### ColorSchemes/*.vb → ColorLut.cs, ColorScheme.cs, ColorSchemeStore.cs, ColorPickerControl.cs+- `ColorLut.vb:28-35, 61-69, 117-132, 97-98` → `:6-13, 33-46, 104-134, 75-79`: "get_colormap_lut" options; **why** options are not saved in the scheme file ("they belong to how a scheme is used, field or intensity, not to the scheme itself"); order of operations "as in Python; reverse is new, optional"; "converted to 8 bit by truncation, like the Python code"; blackLevel may be negative; reverse "like matplotlib's _r maps"; "like render_field / render_intensity; the Python default exponent is 0.5"; symmetric origin "Python: entries 0..127 = src[0::2] and 127..254 the same list mirrored, i.e. entry i = src(2 * min(i, 254 - i))".+- `ColorScheme.vb:26-36, 42-43, 59-62, 121-124, 155-158, 187-188` → `:7-17, 267, 29-32, 97-100, 150-154, 196`: "the same table size the Python simulator uses"; **why** 255 entries and 9 stops ("with an odd number of stops the middle stop is exactly the centre entry 127, the zero-field color; with 9 stops that is Color 5"; "entry 127 is exactly 4.0, the middle stop"); StopCount "one Color button each; 9 since the Color 8/9 buttons were added to the Designer (previously upgraded from 5 to 7 the same way)"; imported schemes "(matplotlib, seaborn, Python tables) have no stops"; "only a label saved in the file"; FromStops stop order; ToStopScheme "This is lossy".+- `ColorSchemeStore.vb:31-39, 48-53, 72, 179` → `:12-21, 29-37, 63-65, 224`: "the same format as the files exported from Python ... (e.g. in the color_schemes folder)"; FindDefaultFolder "while developing this is the ColorSchemeList folder of the project itself, so edits end up in the project"; "the caller checks whether the folder exists"; "write to a temporary file first so a failed save never leaves a half-written scheme behind".+- `ColorPickerControl.vb:31-35, 224-252` → `:12-19, 267-285`: "built completely in code, so it has no designer file" (explains `[DesignerCategory("Code")]`); OnPaint section labels.++### Form1.vb → Form1.cs, Form1.Projects.cs, Form1.Output.cs, Form1.Scene.cs, Form1.Colors.cs, Form1.Simulation.cs+- `:142-144, 157, 181-183, 199-202, 189-190` → `Form1.cs:113, 121, 138, 158, 141`: tabMainFunctions owner-drawn "only so a disabled tab's label can be shown in a lighter gray (a disabled TabPage still draws its label at full strength)"; lblInfo "a clickable 'hyperlink' style label"; Enter in a NumericUpDown "beeps and leaves the value uncommitted"; SuppressKeyPress **why** ("Enter is not a character its edit box accepts, which is what Windows was beeping about ... a NumericUpDown parses/clamps its text on losing focus regardless of how focus was lost"); "a plain loop over Controls rather than a fixed list, so it also covers any NumericUpDown added later".+- `:268-276, 284-287, 302-303, 315-317, 329-330, 337-338, 343-344` → `Form1.cs:219-223, 230, 245, 254, 265, 275, 280`: UpdateProjectAccess rules ("the Configuration tab and the color scheme tab manage the application's own settings, so they are never restricted"; "Disabling a TabPage is not enough by itself, see tabMainFunctions_Selecting"); btnPickRoot blinks "for a fresh install on another computer"; "grpNavigateTabs stays enabled: btnGotoConfiguration jumps to the always-available tab"; **why** `tabMainFunctions.Invalidate()` ("Changing a TabPage's Enabled does not by itself repaint the tab strip"); "WinForms' TabControl has no built-in notion of a locked tab"; "the selected tab a shade lighter, so which one is open is still visible without the native visual style".+- `:237, 250-256, 392-398, 443-448, 710-715, 758-760, 812-828, 843-859, 868-877, 903-905` → `Form1.cs:207, 964, 328, 394-398, 620-627, 688, 700-715, 728-748, 793-801, 831`: "the runner closes the video files before it ends"; the project-folder model; SaveAs "not a file dialog ... SaveProjectTo itself asks to overwrite"; "txtRootFolder just displays it, AppSettings.ProjectRoot is the real value"; PrepareSceneImageFor "catches an image picked before the new project was ever saved"; "there is no such thing as an 'unsaved new project' to ask about any more"; StartNewProject Enabled contract and the no-default controls; SetCurrentProject "the preview-clearing must only run when the project is actually changing, or every 'Save configuration' would blank the Sources/Probes picture"; "(AutoLoadSceneImageIfEmpty only fills an empty picture, so a stale one would never be replaced)"; BrowseForFolder **why** hand-built ("plain FolderBrowserDialog shows no address bar to type a path into and makes other drives awkward"; rooted at This PC "so every drive is one click away").+- `:1072-1081, 1230-1235, 1272-1273, 1304-1309` → `Form1.Projects.cs:9-17, 202-206, 288, 334-343`: list-sort conventions and the Tag/ProjectListEntry reason; **why** `btnNewProject2_Click` saves before `SetCurrentProject` ("a freshly created project has no 'steps' or 'time_decay_factor' key yet, so FromConfig would fall back to its legacy defaults, silently discarding the Designer values StartNewProject just set"); delete warning names the assets folder "since deleting the project deletes those too, and they have no other copy here"; "a project's name is always just its folder name".+- `:1337-1350, 1457-1460, 1501-1504, 1827-1833` → `Form1.Output.cs:12-19, 264-268, 343-348, 726`: **why** shell thumbnails ("there is no dependency-free way to decode/play a frame with just System.Drawing/System.Windows.Forms"); "the Projects list is not one of these three and keeps its own selection"; **the warning** "genuine COM interop which could not be exercised on an actual Windows machine while writing it. GetShellThumbnail is written so a wrong detail surfaces as 'no thumbnail' rather than a crash; if the preview comes out consistently missing for videos, this is the place to revisit".+- `:1917-1925, 1941, 1984, 2004, 2067-2070, 2109-2121, 2129-2147, 2206-2215, 2223, 2244, 2301-2304, 2378, 2422-2427, 2473-2474` → `Form1.Scene.cs:37-39, 63-65, 113, 137, 227, 269-275, 285-305, 378-385, 396, 421, 495-501, 590, 646-650, 718-722`: **why** no `ShowSceneInControls()` at init ("would overwrite the Designer defaults before StartNewProject reads them"); "the image label tells that the image could not be loaded"; "a scene image has its own refractive index per pixel"; ClearGlowEdgesImage callers and **why** `_sceneImage` is kept; glow edges **why** per channel ("a hard red-to-black edge lights up mostly in red, the way Photoshop's 'Glowing Edges' does") and the GlowScale calibration (~1442 raw max; "ask if this should be stronger/weaker"); "24bppRgb stores each pixel as three bytes, B,G,R"; ComposeGlowOverlay **why** multiplicative ("keeps a still-black background black at any gain; a brightness slider that lifted the black background would defeat its own purpose"; "the frame itself is never modified"); overlay-gain semantics "1 is the Designer default, higher brightens faint edges, 0 is the same as unchecking"; the stale-overlay hazard on scene-mode switch ("would also be baked into any picture shared into the Sources/Probes tabs"); "an image from outside the project folder is copied in, so the project does not depend on a file elsewhere".+- `:2756, 2775, 2781, 2984-2985, 3047, 3071-3114` → `Form1.Colors.cs:230, 259, 267, 503-507, 589, 621-678`: "ends the preview; also refreshes the display"; "clicking a Color button while a list item is only previewed loads that scheme first"; "an imported scheme is a full table without stops: editing it means making a stop-based approximation"; scheme_type persistence; "radio buttons can only be changed for the current scheme"; gradient layout ("top = entry 0 (Color 1), bottom = entry 254, middle = entry 127 (centre Color)"; "tick marks dark and light so they show on any color").+- `:3156-3161, 3183-3185, 3217-3282, 3300, 3339, 3392-3408, 3414-3417, 3430-3450, 3578, 3603-3620, 3649, 3697-3708, 3718-3721, 3764-3893, 3933-4015, 4163-4167, 4185-4250, 4313, 4322-4325` → `Form1.Simulation.cs:15, 24-63, 88, 123, 206-218, 224, 244-263, 455, 484-504, 536, 594-598, 609-612, 659-809, 857-1015, 1161, 1184-1238, 1328, 1341-1354`: the class summary ("'Start simulation' hands a copy of everything to a SimulationRunner ... PostToUi passes events on to this thread"); "(render_field / render_intensity in the Python code)"; **why** the numFieldScaling2 mirror pair matches range/precision; "2 decimals, otherwise the default of -0.05 would be rounded"; lblWarningField/Intensity history; **why** no `ShowSimulationInControls()` at init ("would clamp numSimulationSteps/numTimeDecayFactor from their Designer defaults (3000 and 10) to their Minimum"); "the quality only matters for exported videos"; **why** the scheme folder and project list are re-read from disk on tab entry; numSimulationSteps "replaces the old cmbSimulationSteps combo, so no separate parsing/validation here"; `_loadingSim` as the reentrancy guard for the linked controls; "the button is also a stop button"; CopyPreviewToTabs "overlay baked in when 'Display overlay' is checked"; "btnShareSceneImage is not gated, matching 'Import scene image' which always works"; "back to the Preview tab, so the user follows the simulation"; **why** `UpdateRunButtons` only recolours ("with its custom Azure BackColor, Windows' disabled-button rendering draws the text with a strange two-tone etched effect; btnPauzeResume_Click already ignores clicks while nothing runs"); the ten `Validate()` calls "so a value typed in but not confirmed yet is used"; "the runner works on copies, so the settings can be edited while it runs"; the glow overlay "frozen at the start of the run" note; "a full-resolution snapshot for a still export once nothing is running"; NextNumericSuffix "instead of the previous date/time stamp, which made file names too long; grows past 4 digits rather than wrapping"; **the Explorer view-mode hack** ("Explorer has no command-line switch for view mode ... Shell.Application COM via reflection since Option Strict is on and a COM reference for this alone is more trouble than it is worth ... not fully reliable: if a window for the folder is already open Explorer reuses it, and Explorer remembers per folder whatever view the user leaves it in, so this only matters the first time ... every failure swallowed"); "so the folder can be opened even before any video has been exported"; "a new run is starting, drop the cached snapshots from the previous run"; the Button1 pointer to Form1.Source.vb.++### Form1.Probes.vb, Form1.Source.vb → Form1.Probes.cs, Form1.Sources.cs+- `Form1.Probes.vb:28-45, 72-78, 92-93, 207, 460-463, 496-499, 559, 614-619` → `Form1.Probes.cs:10-24, 27, 44, 93, 439-445, 489, 596, 689`: the contract that a switched-off probe "keeps being sampled, so switching it back on shows its recorded history" while "marker, graph box and burned-in overlay are all skipped"; the picture is "a copy of a simulation picture, shared by both probes"; **why** `ProbeUi` guards early events ("InitializeComponent sets numRunningWindow's 500, and that alone fires the change event before _probeUi exists"); padding "from before Probe 2 existed"; "the graphs and markers are drawn over the pictures (the pictures stay clean)"; "the number of clicks depends on the type; only cancel a pick that belongs to this probe"; "a line probe shows nothing before the start step: nothing to freeze"; canvas size source and placeholder replacement.+- `Form1.Source.vb:27-48, 73-75, 91-93, 123-124, 133-136, 177-181, 213-214, 331-338, 347-348, 371, 406-408, 430-437, 550-551, 556-565, 581, 596-624, 637-638, 650-660, 681-685, 758-772, 800-807, 831-848, 876-888` → `Form1.Sources.cs:10-18, (Form1.cs:1150), 38, 70, 77-80, 147-151, 193, 355-360, 370, 398, 436, 455, 598, 604-608, 628, 650-661, 677, 698, 723, 828-836, 885-891, 925-929, 975-984`: the object-source model (HasPosition "so an unpositioned source is never mistaken for one at (0, 0)"; Save resolves parameters "including a fresh random draw when 'Inherit + randomize' is chosen, into a fixed list of elements; the engine always runs the already-generated list, never re-randomizing, so a run is reproducible"; "there is no separate Edit step"); `_sourceSaveButtonDefaultBackColor` "captured once so ClearSourceDirty restores exactly that"; **why** array-size Min/Max are odd with Increment 2; owner-drawn list "stays fully selectable, only the text color changes"; first-source selection rationale; "a source saved before it was ever generated (should not normally happen)"; CommitSourceEdits' second caller (position pick) and **why**; "always (re)generate the elements, so a changed position is never left stale"; "the editor keeps editing the source just saved, so Save again updates it in place"; **the ValueChanged gotcha** ("a value that happens to equal what a control already shows does not raise that event", twice); position deliberately excluded from dirty tracking; "not guarded by _loadingSource" reasons (three places); UpdateLambdaLabel output format and **caveat** ("only an estimate: the real per-pixel wave speed comes from the scene's refractive index and is not necessarily uniform"); "the current culture's own decimal separator (a comma in nl-NL)"; **why** the randomize limits ("so GenerateElements' inherited ± amount can never clip against a hard limit and end up biased instead of a true symmetric spread"; position "can never overshoot as far as a neighboring grid position"; phase not limited "since ±180° is the same angle either way"); the hand-written min loop "without relying on System.Linq (not imported by this file)"; **why** even array sizes are rejected ("centre between two pixels places the whole array off-grid in an irregular way"; the spinner cannot produce one but typing can; Validating "only fires from an actual focus change, never from a Value assignment in code"); SyncSourceListSelectionToEditor **why**; the explicit `_editing.PosX = ...` after setting the spinners **why**; position pick commits an existing source but not a new one "since adding it here could silently add an incomplete/unnamed source"; live position display "but only once it actually has one, never at the unset default"; the preview box purpose ("a composite source's elements can be too small or too close together to make out at canvas scale"; "blank until generated by Save source"; the Invalidate contract); "a single element has no span to scale to, fall back to a fixed half-extent instead of dividing by zero"; "keeps outer dots from touching the edge"; "true size: one simulation pixel is one screen pixel".++### AboutForm.vb, HelpForm.vb, frmDescription.vb → *.cs+- `AboutForm.vb:25-34, 48` → `AboutForm.cs:8-11, 45, 35-37`: "Designer-editable; this file only fills in the copyright string and loads the icon; opened from AboutToolStripMenuItem_Click"; DisplayVersion "kept in sync by hand with Form1's title bar, since AssemblyVersion is left at 1.0.0.0"; "no icon available (e.g. running outside a normal exe)".+- `HelpForm.vb:26-33, 171-172` → `HelpForm.cs:7-11, 111-114`: "a dedicated section on the propagation speed c, since its correct value depends on both the Laplacian order and the source frequency and is easy to get wrong"; "opened from HelpToolStripMenuItem_Click"; AppendBullet "used for the per-control breakdowns".+- `frmDescription.vb:23-32` → `frmDescription.cs:6-10, 19`: "saved to the project only when the dialog returns OK (btnSaveDescription); btnCancelDescription discards any typing"; "Form1 sets this before showing the dialog and reads it back after OK".++## Project-level differences (vbproj vs csproj)++- `ColorSchemeList\*.json` was `Content` with `CopyToOutputDirectory=PreserveNewest`; the csproj has no Content item (see semantic table, `FindDefaultFolder`).+- ClickOnce publishing (`PublishUrl ...\2D_wave_sim_install_V0.29\`, `ApplicationRevision 18`), manifest signing (`2D_wave_sim_V01_TemporaryKey.pfx`, thumbprint) and bootstrapper packages dropped; the `.pfx` was not copied. The PublishUrl confirms the author's own label for this build was V0.29.+- `Debug|x64` / `Release|x64` configurations (`Prefer32Bit=true`, `MinimumRecommendedRules.ruleset`) dropped; AnyCPU only.+- `AutoGenerateBindingRedirects`, `Deterministic` not set in the csproj. Project-level `OptionStrict Off` (every file opts in individually). Unused VB references `System.Data`, `System.Deployment`, `System.Xml`, `System.Xml.Linq`, `System.Data.DataSetExtensions`, `System.Net.Http`.+- Resources: VB references `Resources\QR-code.png` through `ResXFileRef`; the C# resx embeds a BinaryFormatter-serialised `Bitmap` (pixel-identical, 128×128) that will not load on .NET 10. `Form1.resx` stores a serialised `Icon` object instead of the raw `.ico` bytes. `AppIcon.ico` and `Wave_Dude_2D.ico` are byte-identical.+- `Application.myapp` values (`MySubMain`, `MainForm Form1`, `SingleInstance false`, `ShutdownMode 0`, `EnableVisualStyles`, `SaveMySettingsOnExit`) are hard-coded in `My\MyApplication.cs:35-49` and match. `Settings.settings` lost `UseMySettingsClassName` and the `(Default)` profile.+- Designer: 318/318 controls, all 229 `.Text` strings and all 209 `Handles`/`+=` wirings match. VB fields are `Friend WithEvents`; C# makes them `private`. The 950-odd VB designer separator comments are boilerplate, not author text.+- `ColorSchemeList/` (repo root) and `2D_wave_sim_V01/ColorSchemeList/`: 23 files, byte-identical.++## Verified intact (no action)++- All JSON keys, string enum encodings, defaults and per-key fallbacks in `SimulationSettings`, `SourceSettings`/`SourceElement`, `SceneSettings`, `ProbeSettings`, `AppSettings`, `ProjectConfig`, `ColorSchemeStore`.+- All six OpenCL kernels and `xorshift32`, token for token; every kernel argument index; all 23 P/Invoke signatures.+- All COM interfaces (`IMFAttributes` 30 slots, `IMFSample` 30+14, `IMFMediaBuffer` 5, `IMFSinkWriter` 11), GUIDs, marshalling, MF call sequence.+- Every `CInt`/`CByte`/`CLng` on a floating value became `Math.Round` (banker's), never a truncating cast; every `CInt(Math.Truncate(...))` became a cast; every `\` became integer `/`.+- `Optional` parameter defaults everywhere (`ColorLut.Build`, `IntensityIndex`, `SceneData.Empty`, `GpuWaveSimulator.TryCreate`, `RefreshOutputProjectList`, `SetOutputPreviewImage`).+- The single `Debug.Assert` (`Form1.vb:109`) survives at `Form1.cs:85`.+- `ColorLut.IntensityIndex` is uncalled in the VB too, so the C# "not currently called" note is accurate.diff --git a/_tools/avi_check/Program.cs b/_tools/avi_check/Program.csnew file mode 100644index 0000000..ae42518--- /dev/null+++ b/_tools/avi_check/Program.cs@@ -0,0 +1,94 @@+using System;+using System.IO;+using System.Text;+using _2D_wave_sim_V01;++// Writes a 3-frame MJPEG AVI with dummy payloads, then walks the RIFF tree and checks every+// size/offset against what the AVI spec expects. Exit code 0 = structure is valid.+internal static class Program+{+ private static int _checks;+ private static int _failures;++ private static void Check(bool ok, string what)+ {+ Console.WriteLine((ok ? " ok " : " FAIL ") + what);+ _checks++;+ if (!ok) _failures++;+ }++ private static int Main()+ {+ string path = Path.Combine(Path.GetTempPath(), "avi_check.avi");+ int[] frameSizes = { 1001, 2000, 777 }; // odd sizes exercise the pad byte+ using (var w = new AviMjpegWriter(path, 320, 240, 25))+ {+ foreach (int n in frameSizes)+ {+ var payload = new byte[n];+ for (int i = 0; i < n; i++) payload[i] = (byte)i;+ w.AddFrame(payload, n);+ }+ }+ byte[] f = File.ReadAllBytes(path);+ Func<int, string> fourcc = o => Encoding.ASCII.GetString(f, o, 4);+ Func<int, uint> u32 = o => BitConverter.ToUInt32(f, o);+ Func<int, ushort> u16 = o => BitConverter.ToUInt16(f, o);++ Console.WriteLine("file length " + f.Length);+ Check(fourcc(0) == "RIFF" && fourcc(8) == "AVI ", "RIFF/AVI signature");+ Check(u32(4) == f.Length - 8, "RIFF size = file length - 8");+ Check(fourcc(12) == "LIST" && u32(16) == 192 && fourcc(20) == "hdrl", "LIST hdrl 192");+ Check(fourcc(24) == "avih" && u32(28) == 56, "avih 56");+ Check(u32(32) == 1000000 / 25, "avih.dwMicroSecPerFrame");+ Check(u32(44) == 0x10, "avih.dwFlags = AVIF_HASINDEX");+ Check(u32(48) == 3, "avih.dwTotalFrames = 3");+ Check(u32(56) == 1, "avih.dwStreams = 1");+ Check(u32(60) == 2000, "avih.dwSuggestedBufferSize = largest frame");+ Check(u32(64) == 320 && u32(68) == 240, "avih width/height");+ Check(fourcc(88) == "LIST" && u32(92) == 116 && fourcc(96) == "strl", "LIST strl 116");+ Check(fourcc(100) == "strh" && u32(104) == 56, "strh 56");+ Check(fourcc(108) == "vids" && fourcc(112) == "MJPG", "strh fccType/fccHandler");+ Check(u32(128) == 1 && u32(132) == 25, "strh dwScale=1 dwRate=25");+ Check(u32(140) == 3, "strh.dwLength = 3");+ Check(u32(144) == 2000, "strh.dwSuggestedBufferSize = largest frame");+ // AVISTREAMHEADER: dwQuality follows dwSuggestedBufferSize, i.e. PosStreamBufferSize (144) + 4+ Check(u32(148) == 0xFFFFFFFFU, "strh.dwQuality = 0xFFFFFFFF (-1, default)");+ Check(u16(156) == 0 && u16(158) == 0 && u16(160) == 320 && u16(162) == 240, "strh.rcFrame");+ Check(fourcc(164) == "strf" && u32(168) == 40, "strf 40");+ Check(u32(172) == 40 && u32(176) == 320 && u32(180) == 240, "bih size/width/height");+ Check(u16(184) == 1 && u16(186) == 24 && fourcc(188) == "MJPG", "bih planes/bitcount/compression");+ Check(fourcc(212) == "LIST" && fourcc(220) == "movi", "LIST movi at 212/220");++ // walk the movi chunks+ int pos = 224;+ int moviEnd = 220 + (int)u32(216);+ int frame = 0;+ var offsets = new int[frameSizes.Length];+ while (pos < moviEnd)+ {+ Check(fourcc(pos) == "00dc", "frame " + frame + " chunk id at " + pos);+ uint size = u32(pos + 4);+ Check(size == frameSizes[frame], "frame " + frame + " size " + size);+ Check(f[pos + 8] == 0 && f[pos + 8 + (int)size - 1] == (byte)(size - 1), "frame " + frame + " payload intact");+ offsets[frame] = pos - 220;+ pos += 8 + (int)size + (int)(size & 1);+ frame++;+ }+ Check(frame == frameSizes.Length, "movi LIST size covers exactly " + frameSizes.Length + " frames");+ Check(pos == moviEnd, "movi LIST size ends on chunk boundary");++ Check(fourcc(pos) == "idx1" && u32(pos + 4) == 16 * frameSizes.Length, "idx1 header");+ for (int i = 0; i < frameSizes.Length; i++)+ {+ int e = pos + 8 + 16 * i;+ Check(fourcc(e) == "00dc" && u32(e + 4) == 0x10, "idx1[" + i + "] id/flags");+ Check(u32(e + 8) == offsets[i], "idx1[" + i + "] offset " + u32(e + 8) + " == " + offsets[i]);+ Check(u32(e + 12) == frameSizes[i], "idx1[" + i + "] size");+ }+ Check(pos + 8 + 16 * frameSizes.Length == f.Length, "idx1 ends at EOF");++ Console.WriteLine(_checks + " checks: " + (_failures == 0 ? "AVI structure OK" : _failures + " failed"));+ return _failures == 0 ? 0 : 1;+ }+}diff --git a/_tools/engine_check/Program.cs b/_tools/engine_check/Program.csnew file mode 100644index 0000000..3dedd95--- /dev/null+++ b/_tools/engine_check/Program.cs@@ -0,0 +1,146 @@+using System;+using System.Collections.Generic;+using System.Drawing;+using _2D_wave_sim_V01;++namespace EngineCheck+{+ // Drives the CPU and (if available) GPU engines over the same scene and compares their fields, so a+ // refactor of either engine is checked against the other. Exit code 0 = all checks passed.+ internal static class Program+ {+ private static int _failures;++ private static void Check(bool ok, string what)+ {+ Console.WriteLine((ok ? " ok " : " FAIL ") + what);+ if (!ok) _failures++;+ }++ private static List<SourceElement> Sources()+ {+ return new List<SourceElement>+ {+ new SourceElement { PosX = 20, PosY = 24, Level = 120, Amplitude = 1.0, Mode = SourceMode.Continuous },+ new SourceElement { PosX = 44, PosY = 12, Level = 200, Amplitude = 0.7, PhaseRad = 0.5, Mode = SourceMode.Pulsed, PulseShape = SourcePulseShape.Gaussian, OnWidthCycles = 4, OffWidthCycles = 6 },+ new SourceElement { PosX = 44, PosY = 36, Level = 90, Amplitude = 0.5, Mode = SourceMode.Pulsed, PulseShape = SourcePulseShape.SmoothedSquare, OnWidthCycles = 5, OffWidthCycles = 3, DetachAfterStep = 120 },+ new SourceElement { PosX = 99, PosY = 99, Level = 50, Amplitude = 9.0, Mode = SourceMode.Continuous }, // outside: must be dropped+ };+ }++ private static float MaxAbs(float[] a)+ {+ float m = 0f;+ foreach (float v in a) m = Math.Max(m, Math.Abs(v));+ return m;+ }++ private static float MaxDiff(float[] a, float[] b)+ {+ float m = 0f;+ for (int i = 0; i < a.Length; i++) m = Math.Max(m, Math.Abs(a[i] - b[i]));+ return m;+ }++ private static ProbeSampler Probes(int w, int h)+ {+ var probes = new List<ProbeSettings>+ {+ new ProbeSettings { Kind = ProbeKind.Point, Measurement = ProbeMeasurement.Amplitude, PosAX = 20, PosAY = 24, Active = true },+ new ProbeSettings { Kind = ProbeKind.Line, Measurement = ProbeMeasurement.IntegratedIntensity, PosAX = 5, PosAY = 5, PosBX = 40, PosBY = 30, Active = true, UseStartAfterStep = true, StartAfterStep = 50 },+ new ProbeSettings { Kind = ProbeKind.Point, Measurement = ProbeMeasurement.Intensity, PosAX = 30, PosAY = 20, Active = true },+ };+ return ProbeSampler.Build(probes, w, h);+ }++ private static float MaxDiff(float[][] a, float[][] b)+ {+ float m = 0f;+ for (int i = 0; i < a.Length; i++)+ {+ if (a[i] == null || b[i] == null) { if (a[i] != b[i]) return float.PositiveInfinity; continue; }+ if (a[i].Length != b[i].Length) return float.PositiveInfinity;+ m = Math.Max(m, MaxDiff(a[i], b[i]));+ }+ return m;+ }++ private static void Run(IWaveEngine engine, int steps)+ {+ for (int i = 0; i < steps; i++)+ {+ engine.AdvanceOneStep();+ engine.SampleProbes();+ }+ engine.PrepareFrame(true, true);+ }++ private static int Main()+ {+ const int W = 64, H = 48, Steps = 200;+ // Scene with an image source (green level 160) so both source kernels run.+ Bitmap image = new Bitmap(W, H);+ using (Graphics g = Graphics.FromImage(image)) g.Clear(Color.FromArgb(100, 0, 0)); // refractive index 1.00+ image.SetPixel(10, 10, Color.FromArgb(100, 160, 0));+ SceneData scene = SceneData.FromImage(image, true, 6);+ Check(scene.SourceCount == 1, "scene has 1 image source");++ foreach (bool fourth in new[] { false, true })+ {+ Console.WriteLine("--- 4th order: " + fourth);+ WaveSimulator cpu = new WaveSimulator(scene, 1.0, 1.0, true, fourth, 10.0, 1.0, Sources());+ cpu.SetProbes(Probes(W, H));+ Run(cpu, Steps);+ float[] cpuField = (float[])cpu.FieldData.Clone();+ float[] cpuInten = (float[])cpu.IntensityData.Clone();+ float[][] cpuSamples = cpu.TakeProbeSamples();+ float[][] cpuProfiles = cpu.ReadProbeProfiles();+ Check(cpuSamples[0].Length == Steps && cpuSamples[2].Length == Steps && cpuSamples[1].Length == 0, "CPU point probes have one sample per step");+ Check(cpuProfiles[1] != null && cpuProfiles[1].Length > 30 && MaxAbs(cpuProfiles[1]) > 0f, "CPU integrated line profile populated");+ Check(cpu.TakeProbeSamples()[0].Length == 0, "CPU TakeProbeSamples clears");+ Check(MaxAbs(cpuField) > 0.01f, "CPU field is non-trivial (max |u| = " + MaxAbs(cpuField) + ")");+ Check(MaxAbs(cpuInten) > 0f, "CPU intensity accumulated");+ Check(Math.Abs(cpu.Time - Steps) < 1e-9, "CPU time counts steps");+ // Border stays zero (never written).+ bool borderZero = true;+ for (int x = 0; x < cpu.Stride; x++) borderZero &= cpuField[x] == 0f && cpuField[(H + 1) * cpu.Stride + x] == 0f;+ Check(borderZero, "CPU padding rows untouched");++ string problems = "";+ GpuWaveSimulator gpu = GpuWaveSimulator.TryCreate(scene, 1.0, 1.0, true, fourth, 10.0, 1.0, ref problems, Sources());+ if (gpu == null)+ {+ Console.WriteLine(" skip GPU: " + problems);+ continue;+ }+ using (gpu)+ {+ Console.WriteLine(" " + gpu.Description);+ gpu.SetProbes(Probes(W, H));+ Run(gpu, Steps);+ float diffField = MaxDiff(cpuField, gpu.FieldData);+ float diffInten = MaxDiff(cpuInten, gpu.IntensityData);+ Check(diffField < 1e-3f * Math.Max(1f, MaxAbs(cpuField)), "GPU field matches CPU (max diff " + diffField + ")");+ Check(diffInten < 1e-3f * Math.Max(1f, MaxAbs(cpuInten)), "GPU intensity matches CPU (max diff " + diffInten + ")");+ float[][] gpuSamples = gpu.TakeProbeSamples();+ float[][] gpuProfiles = gpu.ReadProbeProfiles();+ float diffSamples = MaxDiff(cpuSamples, gpuSamples);+ float diffProfiles = MaxDiff(cpuProfiles, gpuProfiles);+ Check(diffSamples < 1e-3f, "GPU point-probe samples match CPU (max diff " + diffSamples + ")");+ Check(diffProfiles < 1e-3f * Math.Max(1f, MaxAbs(cpuProfiles[1])), "GPU line profile matches CPU (max diff " + diffProfiles + ")");+ // Re-installing probes replaces the previous set (no leak, no stale state); clearing empties results.+ gpu.SetProbes(Probes(W, H));+ Run(gpu, 10);+ Check(gpu.TakeProbeSamples()[0].Length == 10, "GPU probes re-installed and sampling again");+ gpu.SetProbes(null);+ Check(gpu.TakeProbeSamples().Length == 0 && gpu.ReadProbeProfiles().Length == 0, "GPU: probes cleared -> empty results");+ gpu.Dispose();+ gpu.Dispose();+ Check(true, "GPU double dispose is harmless");+ }+ }+ Console.WriteLine(_failures == 0 ? "ENGINES OK" : _failures + " check(s) failed");+ return _failures == 0 ? 0 : 1;+ }+ }+}diff --git a/_tools/field_usage.py b/_tools/field_usage.pynew file mode 100644index 0000000..d1a29bc--- /dev/null+++ b/_tools/field_usage.py@@ -0,0 +1,27 @@+"""List every private field/const of the given classes with usage counts, grouped by method."""+import re, sys++STRING = re.compile(r'"(?:[^"\\]|\\.)*"')+FIELD = re.compile(r'^\t\tprivate (?:readonly |static |const )*([A-Za-z0-9_<>\[\],]+) (_[A-Za-z0-9_]+|[A-Z][A-Za-z0-9_]*)(?: =|;)', re.M)+METHOD = re.compile(r'^\t\t(?:public|private|internal|protected)[^\r\n=;]*? ([A-Za-z0-9_]+)\([^)]*\)\s*(?:=>|\r?\n\t\t\{)', re.M)++for f in sys.argv[1:]:+ src = open('Wave_Dude_2D/%s.cs' % f, encoding='utf-8').read()+ code = '\n'.join(l for l in src.split('\n') if not l.strip().startswith('///'))+ code = STRING.sub('""', code)+ fields = FIELD.findall(code)+ meths = [(m.group(1), m.start()) for m in METHOD.finditer(code)]+ print('=== %s: %d private fields/consts' % (f, len(fields)))+ for typ, name in fields:+ uses = []+ for m in re.finditer(r'(?<![A-Za-z0-9_.])' + re.escape(name) + r'\b', code):+ line = code[code.rfind('\n', 0, m.start()) + 1:m.end()]+ if not line.startswith('\t\tprivate'):+ uses.append(m.start())+ where = {}+ for u in uses:+ owner = [n for n, s in meths if s <= u]+ key = owner[-1] if owner else '<decl>'+ where[key] = where.get(key, 0) + 1+ flag = '<-- ' if len(uses) <= 2 or len(where) <= 1 else ' '+ print('%s%-26s %-20s uses=%-3d %s' % (flag, name, typ, len(uses), ', '.join('%s(%d)' % kv for kv in sorted(where.items()))))diff --git a/_tools/modernize.py b/_tools/modernize.pynew file mode 100644index 0000000..09f5c99--- /dev/null+++ b/_tools/modernize.py@@ -0,0 +1,52 @@+"""Mechanical C# modernisation of the hand-maintained files (not *.Designer.cs, not My/):++ 1. block-bodied single-return getters -> expression-bodied (`=> expr;` / `get => expr;`)+ 2. single-statement setters -> `set => stmt;`+ 3. single-return / single-statement methods of trivial shape stay as they are (readability)+ 4. `this.member` qualification removed (the project style; a following build with+ CS1717 (self-assignment) as a tripwire catches any parameter/field shadowing)+"""+import glob, re, sys++SRC = 'Wave_Dude_2D'+NL = r'\r?\n'++# { get { return X; } } with no setter -> => X;+GETTER_ONLY = re.compile(+ r'(?P<head>^(?P<ind>\t+)(?P<decl>(?:public|internal|protected|private)(?: static| override| virtual| new| readonly)* [^\r\n=;{]+?[A-Za-z0-9_]+))' + NL ++ r'(?P=ind)\{' + NL ++ r'(?P=ind)\tget' + NL ++ r'(?P=ind)\t\{' + NL ++ r'(?P=ind)\t\treturn (?P<expr>[^\r\n]+);' + NL ++ r'(?P=ind)\t\}' + NL ++ r'(?P=ind)\}', re.M)++# get { return X; } (inside a property that also has a setter) -> get => X;+GETTER_IN = re.compile(+ r'^(?P<ind>\t+)get' + NL + r'(?P=ind)\{' + NL + r'(?P=ind)\treturn (?P<expr>[^\r\n]+);' + NL + r'(?P=ind)\}', re.M)++# set { one statement; } -> set => one statement;+SETTER_IN = re.compile(+ r'^(?P<ind>\t+)set' + NL + r'(?P=ind)\{' + NL + r'(?P=ind)\t(?P<stmt>[^\r\n{}]+;)' + NL + r'(?P=ind)\}', re.M)++THIS = re.compile(r'\bthis\.(?=[A-Za-z_])')++def modernize(text):+ before = text+ text = GETTER_ONLY.sub(lambda m: '%s%s => %s;' % (m.group('ind'), m.group('decl'), m.group('expr')), text)+ text = GETTER_IN.sub(lambda m: '%sget => %s;' % (m.group('ind'), m.group('expr')), text)+ text = SETTER_IN.sub(lambda m: '%sset => %s' % (m.group('ind'), m.group('stmt')), text)+ text = THIS.sub('', text)+ return text++total = 0+for path in sorted(glob.glob(SRC + '/*.cs')):+ if path.endswith('.Designer.cs'):+ continue+ raw = open(path, 'rb').read().decode('utf-8')+ new = modernize(raw)+ if new != raw:+ open(path, 'wb').write(new.encode('utf-8'))+ total += 1+ print('modernized', path)+print(total, 'files changed')