Skip to content

Interactive 2D wave optics simulator. Turn any image into a refractive scene, add sources, watch waves refract, diffract and interfere. Probes, intensity maps, video export.

C#

The first start chooses the preview quality for the machine: three tiers from memory, cache drive, GPU and threads

Alexander Graefb4fde238eb8b
diff --git a/CLAUDE.md b/CLAUDE.md
index 5d4729b..4bd3e68 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -160,6 +160,17 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA
an 8-bit run, a reduced resolution or skipped frames make the export run the simulation again at full quality first.
Only an OpenEXR export of I makes a run that stores I itself (squaring √I back would lose a bit); as coded, that run is
then the one the preview shows until the next edit or run (undecided whether it should be a side run).
+- **First start** (2026-10-31, the user's design): with no settings file, the three quality settings and the dithering are
+ chosen once from the machine (`PreviewDefaults.TierOf` on `MachineFacts.Read`; `library_check` proves the table): 32 GB
+ or more → 16-bit samples dithered to 16 bits; else any of under 16 GB, a cache drive with a seek penalty (`StorageDevice`:
+ `IOCTL_STORAGE_QUERY_PROPERTY` on the volume, then on its disks, no elevation; unknown counts as none; on the workstation
+ the HDD D: answers yes, the SSD E: no, and C: on the PERC H310's RAID virtual disk nothing, as Windows itself calls its media
+ type unspecified), no OpenCL GPU or ≤ 4 threads →
+ half resolution, every second frame, 8-bit; else the fixed defaults. Tested at 30 and 15 GiB, since Windows reports
+ under the nominal size. The settings file is written at once, so deleting it redoes the choice; the fixed defaults stay
+ the initialisers (the figure harness strips the attributes, the designer); one Info line after "ready" names the facts
+ and the choice. The levers buy memory and readback, never step time: the divisors shrink the captured frames, not the
+ grid (at the defaults 11 of the 24 examples exceed 6 GB, Example 7 needs 19 GB; at Low the largest is 2.4 GB).
## The app's rules
@@ -359,7 +370,7 @@ numbers: no GPU JPEG, no OpenCL colouring at presentation, no `Vector256`, no Di
## Harnesses
-`library_check` (100+ checks: engines, store, renderer, half tables, screen path, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, work groups on a prime grid, ranges, XOR gate, zone plate, gate port follower, history, clipboard).
+`library_check` (100+ checks: engines, store, renderer, half tables, screen path, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, work groups on a prime grid, ranges, XOR gate, zone plate, gate port follower, history, clipboard, the first start's tiers).
UI, all on `Common.ps1`, with their check counts: `PreviewCheck` 43, `RunCheck` 71, `LanguageCheck` 11,
`ProbeGraphCheck` 39, `ImportCheck` 10, `ExportCheck` 44, `PreviewQualityCheck` 35, `SceneImageCheck` 8,
`ColorPickerCheck` 13, `KeyboardCheck` 13, `AboutCheck` 18, `SelectionCheck` 10. Test projects `tiny*.wdproj` sit beside them. A harness
diff --git a/MANUAL.md b/MANUAL.md
index 8d8c8bc..79cf68d 100644
--- a/MANUAL.md
+++ b/MANUAL.md
@@ -212,7 +212,9 @@ The View menu. Its settings belong to the program, not to the project, and are k
4. **Preview resolution**: Full, Half or Quarter: the preview's run computes the canvas at a reduced size, faster and with less memory, for a weaker machine. An export always uses the full size.
5. **Preview frames**: Full, every second or every fourth frame kept by the preview's run; the timeline does not change.
6. **Preview samples**: 16-bit float keeps the full values, so the brightness can be changed after a run and every level of a gradient shows; 8-bit palette index stores each pixel as its colour at the brightness of the run's start, half the memory, and a brightness change then needs a new run, which starts by itself.
-7. **Preview dithering**: With 16-bit samples, the pictures can be dithered as if the screen had 10, 12, 14 or 16 bits per channel, which hides the banding of dark gradients; on screen only, never in an export. Off by default.
+7. **Preview dithering**: With 16-bit samples, the pictures can be dithered as if the screen had 10, 12, 14 or 16 bits per channel, which hides the banding of dark gradients; on screen only, never in an export. Off by default, except on a machine with plenty of memory (see below).
+
+On its first start the program chooses the preview resolution, the preview frames, the preview samples and the dithering for the machine it runs on, once, and the View menu shows the choice. A machine with 32 GB of memory or more starts with 16-bit samples, dithered to 16 bits. A machine with less than 16 GB, with a hard disk under the cache file, without an OpenCL graphics card or with four processor threads or fewer starts at half resolution with every second frame and 8-bit samples. Every other machine starts at full resolution with every frame and 8-bit samples. Each setting can be changed here at any time.
### The Simulation menu
diff --git a/WaveDudeNext.WPF/App.xaml.cs b/WaveDudeNext.WPF/App.xaml.cs
index b25deb7..cd9a80b 100644
--- a/WaveDudeNext.WPF/App.xaml.cs
+++ b/WaveDudeNext.WPF/App.xaml.cs
@@ -205,6 +205,9 @@ public partial class App : Application
}
FrameCache.Sweep();
+ // the one start without a settings file chooses the preview quality for the machine (2026-10-31, the user's
+ // design); the facts and the choice are told after the "ready" line below, so the status bar shows them
+ (MachineFacts Facts, PreviewTier Tier)? firstStart = Settings.IsFirstStart ? ChoosePreviewDefaults() : null;
ColorSchemeCatalog.Instance.Load();
ThemeController.Instance.Current = Settings.Default.Theme;
ThemeController.Instance.PropertyChanged += (_, args) =>
@@ -230,8 +233,15 @@ public partial class App : Application
var window = new MainWindow();
MainWindow = window;
window.Show();
- // the last start-up line, and so the status bar's first text unless a file is opened below
+ // the last start-up line, and so the status bar's first text unless this is a first start or a file is opened below
Logger.Info("{Title} {Version} ready", FindResource("Title"), Assembly.GetExecutingAssembly().GetName().Version?.ToString(3));
+ if (firstStart is { } first)
+ {
+ Logger.Info("First start on this machine: {Memory:0.0} GB of memory, {Threads} threads, {Gpu}, cache drive {Drive} {DriveKind}: the preview is set to {Quality} (View menu)",
+ first.Facts.PhysicalBytes / (double)(1L << 30), first.Facts.Threads, first.Facts.Gpu.Length == 0 ? "no OpenCL GPU" : first.Facts.Gpu, first.Facts.CacheDrive,
+ first.Facts.CacheDriveSeekPenalty switch { true => "with a seek penalty (a hard disk)", false => "without a seek penalty", null => "of unknown kind" },
+ PreviewDefaults.Describe(first.Tier));
+ }
if (e.Args.Length > 0)
{
// launched with a project file (double-click, "open with", command line); after
@@ -241,6 +251,29 @@ public partial class App : Application
}
}
+ /// <summary>
+ /// Reads the machine's facts, sets the preview quality of its tier (<see cref="PreviewDefaults"/>) and writes the
+ /// settings file at once, so the choice is made once and deleting the file redoes it; the fixed defaults stay the
+ /// initialisers, which the figure harness and the designer rely on. Returns the facts and the tier for the log.
+ /// </summary>
+ private static (MachineFacts Facts, PreviewTier Tier) ChoosePreviewDefaults()
+ {
+ long started = Stopwatch.GetTimestamp();
+ MachineFacts facts = MachineFacts.Read();
+ PreviewTier tier = PreviewDefaults.TierOf(facts);
+ Settings.Default.SetPreviewQuality(PreviewDefaults.QualityOf(tier), PreviewDefaults.DitherBitsOf(tier));
+ Logger.Debug("First start: the machine's facts read in {Ms:0} ms, tier {Tier}", Stopwatch.GetElapsedTime(started).TotalMilliseconds, tier);
+ try
+ {
+ Settings.Default.Save();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Logger.Warn(ex, "The settings file could not be written at the first start; the preview quality will be chosen again at the next start");
+ }
+ return (facts, tier);
+ }
+
/// <inheritdoc/>
protected override void OnExit(ExitEventArgs e)
{
diff --git a/WaveDudeNext.WPF/Settings.cs b/WaveDudeNext.WPF/Settings.cs
index cbec018..959ed3b 100644
--- a/WaveDudeNext.WPF/Settings.cs
+++ b/WaveDudeNext.WPF/Settings.cs
@@ -24,6 +24,8 @@ using System.Windows.Controls;
using System.Xml;
using System.Xml.Serialization;
using NLog;
+using WaveDudeNext.Engine;
+using WaveDudeNext.Runs;
using WaveDudeNext.WPF.Docking;
using WaveDudeNext.WPF.Theming;
@@ -46,6 +48,12 @@ public sealed class Settings : INotifyPropertyChanged
/// <summary>The settings file.</summary>
public static string FilePath { get; } = Path.Combine(App.LocalAppDataDirectory, "Settings.xml");
+ /// <summary>
+ /// Whether this start found no settings file: the one start that chooses the preview quality for the machine
+ /// (<see cref="App.OnStartup"/>, <see cref="PreviewDefaults"/>); an unreadable file is not a first start. Set by <see cref="Load"/>.
+ /// </summary>
+ public static bool IsFirstStart { get; private set; }
+
/// <summary>This user's settings, read from <see cref="FilePath"/> at first use; the defaults when the file is missing or unreadable.</summary>
public static Settings Default { get; } = Load();
@@ -266,6 +274,15 @@ public sealed class Settings : INotifyPropertyChanged
set => Set(ref _exportHints, value);
}
+ /// <summary>Sets the three preview quality settings and the dithering as one: a first start's choice for the machine (<see cref="PreviewDefaults"/>).</summary>
+ public void SetPreviewQuality(PreviewQuality quality, int ditherBits)
+ {
+ PreviewResolution = quality.ResolutionDivisor;
+ PreviewFrames = quality.FrameDivisor;
+ PreviewSampleBytes = quality.Format == FrameFormat.Half ? 2 : 1;
+ PreviewDitherBits = ditherBits;
+ }
+
/// <summary>Writes the settings to <see cref="FilePath"/>, creating the folder; file errors are the caller's.</summary>
public void Save()
{
@@ -283,7 +300,8 @@ public sealed class Settings : INotifyPropertyChanged
{
if (!File.Exists(FilePath))
{
- Logger.Debug("No settings file at '{Path}', using the defaults", FilePath);
+ Logger.Debug("No settings file at '{Path}': a first start, the defaults and the machine's preview quality", FilePath);
+ IsFirstStart = true;
return new Settings();
}
try
diff --git a/WaveDudeNext/Runs/MachineFacts.cs b/WaveDudeNext/Runs/MachineFacts.cs
new file mode 100644
index 0000000..b760951
--- /dev/null
+++ b/WaveDudeNext/Runs/MachineFacts.cs
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Alexander Graef <[email protected]>
+//
+// This file is part of WaveDude Next, a 2D wave simulator.
+//
+// Based on the work of
+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026
+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>
+// 0x23 (Diffraction Limited), author of WaveSimulator2D
+// <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>
+//
+// WaveDude Next is free software: you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
+// <https://www.gnu.org/licenses/>.
+
+using WaveDudeNext.Engine;
+
+namespace WaveDudeNext.Runs;
+
+/// <summary>
+/// What a first start learns about the machine before choosing the preview quality (2026-10-31, the user's design;
+/// <see cref="PreviewDefaults"/> makes the choice): the physical memory, the processor's threads, the OpenCL GPU the
+/// engine would take and whether the frame cache's drive incurs a seek penalty. <see cref="Read"/> gathers them in a
+/// few milliseconds, most of it the OpenCL enumeration; the record itself is immutable and compared by value, so the
+/// harness builds the facts of machines it does not run on. Thread-free.
+/// </summary>
+/// <param name="PhysicalBytes">Bytes of physical memory as Windows reports them, a little under the nominal size (about 15.9 GB on a 16 GB machine).</param>
+/// <param name="Threads">Logical processors.</param>
+/// <param name="Gpu">The OpenCL GPU the engine would take, by name, "(shared memory)" added for one integrated with the processor; empty when there is none or OpenCL is missing.</param>
+/// <param name="CacheDrive">The frame cache's drive for a log line ("C:"), or the cache folder's root when it has no drive letter.</param>
+/// <param name="CacheDriveSeekPenalty">Whether the cache drive incurs a seek penalty, a hard disk; null when Windows cannot say (<see cref="StorageDevice.IncursSeekPenalty"/>).</param>
+public sealed record MachineFacts(long PhysicalBytes, int Threads, string Gpu, string CacheDrive, bool? CacheDriveSeekPenalty)
+{
+ /// <summary>Reads the facts of this machine; a missing OpenCL runtime counts as no GPU.</summary>
+ public static MachineFacts Read()
+ {
+ string gpu = "";
+ try
+ {
+ if (GpuDeviceInfo.FindAll() is [var device, ..])
+ {
+ gpu = device.Discrete ? device.Name : device.Name + " (shared memory)";
+ }
+ }
+ catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException or BadImageFormatException)
+ {
+ // no OpenCL runtime: the CPU engine serves
+ }
+ string root = Path.GetPathRoot(FrameCache.Directory) ?? FrameCache.Directory;
+ return new MachineFacts(FrameMemory.PhysicalBytes(), Environment.ProcessorCount, gpu, root.TrimEnd('\\'), StorageDevice.IncursSeekPenalty(FrameCache.Directory));
+ }
+}
diff --git a/WaveDudeNext/Runs/PreviewDefaults.cs b/WaveDudeNext/Runs/PreviewDefaults.cs
new file mode 100644
index 0000000..b8d8409
--- /dev/null
+++ b/WaveDudeNext/Runs/PreviewDefaults.cs
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Alexander Graef <[email protected]>
+//
+// This file is part of WaveDude Next, a 2D wave simulator.
+//
+// Based on the work of
+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026
+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>
+// 0x23 (Diffraction Limited), author of WaveSimulator2D
+// <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>
+//
+// WaveDude Next is free software: you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
+// <https://www.gnu.org/licenses/>.
+
+using WaveDudeNext.Engine;
+
+namespace WaveDudeNext.Runs;
+
+/// <summary>The classes a first start sorts the machine into; <see cref="PreviewDefaults"/> decides and says what each gets.</summary>
+public enum PreviewTier
+{
+ /// <summary>Little memory, a hard disk under the frame cache, no OpenCL GPU or few threads: half resolution, every second frame, 8-bit samples.</summary>
+ Low,
+
+ /// <summary>Everything else: full resolution, every frame, 8-bit samples, the fixed defaults.</summary>
+ Middle,
+
+ /// <summary>Plenty of memory: full resolution, every frame, 16-bit samples, dithered to 16 bits.</summary>
+ High,
+}
+
+/// <summary>
+/// The preview quality a first start chooses for the machine (2026-10-31, the user's design: one decision, made only
+/// when no settings file exists, visible and changeable in the View menu). The levers buy memory and readback, never
+/// step time: 8-bit samples halve a frame against 16-bit, half resolution divides it by four, every second frame
+/// halves the store again; a Full HD run of 1250 frames with both layers takes 9.7 GB at 16-bit, 4.8 GB at 8-bit and
+/// 0.6 GB at half resolution with every second frame. The weakest link decides, memory first: 32 GB or more is
+/// <see cref="PreviewTier.High"/> whatever else the machine has, since little spills at that size; below it any one
+/// of under 16 GB, a cache drive with a seek penalty, no OpenCL GPU or four threads or fewer makes
+/// <see cref="PreviewTier.Low"/>; the rest is <see cref="PreviewTier.Middle"/>, the fixed defaults. The thresholds are
+/// tested at 30 and 15 GiB because Windows reports the physical memory a little under the nominal size (15.9 GB on a
+/// 16 GB machine). An unknown drive kind counts as no seek penalty. Pure functions; the harness proves the table.
+/// </summary>
+public static class PreviewDefaults
+{
+ /// <summary>Physical memory from which a machine is <see cref="PreviewTier.High"/>: a nominal 32 GB as Windows reports it.</summary>
+ public const long HighBytes = 30L << 30;
+
+ /// <summary>Physical memory below which a machine is <see cref="PreviewTier.Low"/>: a nominal 16 GB as Windows reports it.</summary>
+ public const long LowBytes = 15L << 30;
+
+ /// <summary>Logical processors at or below which a machine is <see cref="PreviewTier.Low"/>.</summary>
+ public const int LowThreads = 4;
+
+ /// <summary>The bits per channel the <see cref="PreviewTier.High"/> preview dithers to.</summary>
+ public const int HighDitherBits = 16;
+
+ /// <summary>The tier of a machine with these facts.</summary>
+ public static PreviewTier TierOf(MachineFacts facts)
+ {
+ if (facts.PhysicalBytes >= HighBytes)
+ {
+ return PreviewTier.High;
+ }
+ bool weak = facts.PhysicalBytes < LowBytes || facts.CacheDriveSeekPenalty == true || facts.Gpu.Length == 0 || facts.Threads <= LowThreads;
+ return weak ? PreviewTier.Low : PreviewTier.Middle;
+ }
+
+ /// <summary>The preview quality of a tier, the intensity as its root as every preview keeps it.</summary>
+ public static PreviewQuality QualityOf(PreviewTier tier) => tier switch
+ {
+ PreviewTier.High => new PreviewQuality(1, 1, FrameFormat.Half),
+ PreviewTier.Low => new PreviewQuality(2, 2, FrameFormat.Index),
+ _ => new PreviewQuality(1, 1, FrameFormat.Index),
+ };
+
+ /// <summary>The preview dithering of a tier: <see cref="HighDitherBits"/> for <see cref="PreviewTier.High"/>, off (0) otherwise.</summary>
+ public static int DitherBitsOf(PreviewTier tier) => tier == PreviewTier.High ? HighDitherBits : 0;
+
+ /// <summary>The tier's settings in words for the log ("half resolution, every second frame, 8-bit samples"); not localised.</summary>
+ public static string Describe(PreviewTier tier) => tier switch
+ {
+ PreviewTier.High => "full resolution, every frame, 16-bit samples dithered to 16 bits",
+ PreviewTier.Low => "half resolution, every second frame, 8-bit samples",
+ _ => "full resolution, every frame, 8-bit samples",
+ };
+}
diff --git a/WaveDudeNext/Runs/StorageDevice.cs b/WaveDudeNext/Runs/StorageDevice.cs
new file mode 100644
index 0000000..20ab81c
--- /dev/null
+++ b/WaveDudeNext/Runs/StorageDevice.cs
@@ -0,0 +1,167 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Alexander Graef <[email protected]>
+//
+// This file is part of WaveDude Next, a 2D wave simulator.
+//
+// Based on the work of
+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026
+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>
+// 0x23 (Diffraction Limited), author of WaveSimulator2D
+// <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>
+//
+// WaveDude Next is free software: you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
+// <https://www.gnu.org/licenses/>.
+
+using System.Globalization;
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+namespace WaveDudeNext.Runs;
+
+/// <summary>
+/// What kind of storage holds a path (2026-10-31, for the first start's choice of the preview quality): whether the
+/// volume incurs a seek penalty, Windows' own distinction between a hard disk and a solid-state drive, the one its
+/// drive optimiser goes by. Asked with <c>IOCTL_STORAGE_QUERY_PROPERTY</c> on handles opened without access rights, so
+/// no elevation is needed: of the volume first, which answers for the disk beneath a simple volume, then of each disk
+/// the volume lies on. A RAID controller's virtual disk answers neither way (the workstation's C: on a PERC H310, whose
+/// media type Windows itself calls unspecified, while its member SSDs answer), so the kind can stay unknown. Thread-free.
+/// </summary>
+public static class StorageDevice
+{
+ private const uint FileShareRead = 0x1U;
+ private const uint FileShareWrite = 0x2U;
+ private const uint OpenExisting = 3U;
+
+ /// <summary>CTL_CODE(IOCTL_STORAGE_BASE, 0x500, METHOD_BUFFERED, FILE_ANY_ACCESS).</summary>
+ private const uint IoctlStorageQueryProperty = 0x002D1400U;
+
+ /// <summary>CTL_CODE(IOCTL_VOLUME_BASE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS): the disks a volume lies on.</summary>
+ private const uint IoctlVolumeGetVolumeDiskExtents = 0x00560000U;
+
+ /// <summary>STORAGE_PROPERTY_ID.StorageDeviceSeekPenaltyProperty.</summary>
+ private const uint StorageDeviceSeekPenaltyProperty = 7U;
+
+ /// <summary>STORAGE_QUERY_TYPE.PropertyStandardQuery.</summary>
+ private const uint PropertyStandardQuery = 0U;
+
+ /// <summary>Disks a volume may span before the question is given up; <c>VOLUME_DISK_EXTENTS</c> is a count, padding and 24 bytes per extent.</summary>
+ private const int MaxExtents = 16;
+
+ /// <summary>
+ /// Whether the volume holding <paramref name="path"/> incurs a seek penalty: true for a hard disk, or a volume with
+ /// one among its disks; false for solid-state drives; null when the question cannot be answered (not Windows, a
+ /// relative or UNC path, a volume and disks that do not report the property). The path need not exist; only its
+ /// drive letter is used.
+ /// </summary>
+ public static bool? IncursSeekPenalty(string path)
+ {
+ if (!OperatingSystem.IsWindows())
+ {
+ return null;
+ }
+ string? root = Path.GetPathRoot(path);
+ // "C:\" and nothing else: a share or a device path has no volume to ask
+ if (root is not { Length: 3 } || root[1] != ':' || root[2] != '\\')
+ {
+ return null;
+ }
+ using SafeFileHandle volume = Open(@"\\.\" + root[..2]);
+ if (volume.IsInvalid)
+ {
+ return null;
+ }
+ if (QuerySeekPenalty(volume) is bool answer)
+ {
+ return answer;
+ }
+ // the volume's stack does not forward the question: ask the disks beneath it; a hard disk among them is a seek
+ // penalty, every disk answering no is none, a disk without an answer leaves the kind unknown
+ uint[] disks = DiskNumbers(volume);
+ if (disks.Length == 0)
+ {
+ return null;
+ }
+ bool? result = false;
+ foreach (uint disk in disks)
+ {
+ using SafeFileHandle device = Open(@"\\.\PhysicalDrive" + disk.ToString(CultureInfo.InvariantCulture));
+ bool? penalty = device.IsInvalid ? null : QuerySeekPenalty(device);
+ if (penalty == true)
+ {
+ return true;
+ }
+ if (penalty == null)
+ {
+ result = null;
+ }
+ }
+ return result;
+ }
+
+ /// <summary>Opens a volume or disk device for queries alone (no access right); the handle is invalid when it cannot be opened.</summary>
+ private static SafeFileHandle Open(string device) => CreateFileW(device, 0U, FileShareRead | FileShareWrite, IntPtr.Zero, OpenExisting, 0U, IntPtr.Zero);
+
+ /// <summary>The seek-penalty property of a volume or disk; null when its driver does not answer.</summary>
+ private static bool? QuerySeekPenalty(SafeFileHandle device)
+ {
+ var query = new StoragePropertyQuery { PropertyId = StorageDeviceSeekPenaltyProperty, QueryType = PropertyStandardQuery };
+ if (!DeviceIoControl(device, IoctlStorageQueryProperty, ref query, (uint)Marshal.SizeOf<StoragePropertyQuery>(),
+ out DeviceSeekPenaltyDescriptor descriptor, (uint)Marshal.SizeOf<DeviceSeekPenaltyDescriptor>(), out uint returned, IntPtr.Zero)
+ || returned < 9U)
+ {
+ return null;
+ }
+ return descriptor.IncursSeekPenalty != 0;
+ }
+
+ /// <summary>The numbers of the disks a volume lies on, each once; empty when the volume does not say or spans more than <see cref="MaxExtents"/>.</summary>
+ private static uint[] DiskNumbers(SafeFileHandle volume)
+ {
+ byte[] buffer = new byte[8 + 24 * MaxExtents];
+ if (!DeviceIoControl(volume, IoctlVolumeGetVolumeDiskExtents, IntPtr.Zero, 0U, buffer, (uint)buffer.Length, out uint returned, IntPtr.Zero) || returned < 8U)
+ {
+ return [];
+ }
+ int count = Math.Min((int)BitConverter.ToUInt32(buffer, 0), MaxExtents);
+ var disks = new HashSet<uint>();
+ for (int i = 0; i < count; i++)
+ {
+ disks.Add(BitConverter.ToUInt32(buffer, 8 + 24 * i));
+ }
+ return [.. disks];
+ }
+
+ /// <summary>The <c>STORAGE_PROPERTY_QUERY</c> structure: the property, the query type and one byte of parameters.</summary>
+ [StructLayout(LayoutKind.Sequential)]
+ private struct StoragePropertyQuery
+ {
+ public uint PropertyId;
+ public uint QueryType;
+ public byte AdditionalParameters;
+ }
+
+ /// <summary>The <c>DEVICE_SEEK_PENALTY_DESCRIPTOR</c> structure: the header's version and size, then the BOOLEAN.</summary>
+ [StructLayout(LayoutKind.Sequential)]
+ private struct DeviceSeekPenaltyDescriptor
+ {
+ public uint Version;
+ public uint Size;
+ public byte IncursSeekPenalty;
+ }
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
+ private static extern SafeFileHandle CreateFileW(string fileName, uint desiredAccess, uint shareMode, IntPtr securityAttributes, uint creationDisposition, uint flagsAndAttributes, IntPtr templateFile);
+
+ [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool DeviceIoControl(SafeFileHandle device, uint ioControlCode, ref StoragePropertyQuery inBuffer, uint inBufferSize,
+ out DeviceSeekPenaltyDescriptor outBuffer, uint outBufferSize, out uint bytesReturned, IntPtr overlapped);
+
+ [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool DeviceIoControl(SafeFileHandle device, uint ioControlCode, IntPtr inBuffer, uint inBufferSize,
+ byte[] outBuffer, uint outBufferSize, out uint bytesReturned, IntPtr overlapped);
+}
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index f28964d..906046d 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -272,6 +272,7 @@ internal static class Program
CheckOpenEdges(W, H);
CheckWorkGroups();
CheckFrameStore(scene);
+ CheckFirstStart();
CheckPreviewQuality(scene, W, H);
CheckRenderer();
CheckColorSchemes();
@@ -290,6 +291,36 @@ internal static class Program
return _failures == 0 ? 0 : 1;
}
+ /// <summary>
+ /// The first start's choice of the preview quality (2026-10-31): the facts of this machine can be read, the cache
+ /// drive's kind among them, and the tier table holds at its edges on the facts of machines this one is not.
+ /// </summary>
+ private static void CheckFirstStart()
+ {
+ MachineFacts facts = MachineFacts.Read();
+ // the drive's kind may be unknown (the workstation's C: is a RAID controller's virtual disk, which answers neither
+ // on the volume nor on the disk): the query must answer the same twice and refuse paths without a volume
+ Check(facts.PhysicalBytes > 1L << 30 && facts.Threads >= 1 && facts.CacheDrive.Length > 0
+ && StorageDevice.IncursSeekPenalty(FrameCache.Directory) == facts.CacheDriveSeekPenalty
+ && StorageDevice.IncursSeekPenalty("relative" + Path.DirectorySeparatorChar + "path") == null && StorageDevice.IncursSeekPenalty(@"\\server\share\cache") == null,
+ "first start: this machine's facts: " + FrameMemory.Gigabytes(facts.PhysicalBytes) + ", " + facts.Threads + " threads, GPU '" + facts.Gpu + "', cache drive " + facts.CacheDrive
+ + " seek penalty " + (facts.CacheDriveSeekPenalty?.ToString() ?? "unknown"));
+ static MachineFacts Machine(double gigabytes, int threads, bool gpu, bool? seekPenalty) => new((long)(gigabytes * (1L << 30)), threads, gpu ? "GPU" : "", "C:", seekPenalty);
+ Check(PreviewDefaults.TierOf(Machine(15.9, 8, true, false)) == PreviewTier.Middle
+ && PreviewDefaults.TierOf(Machine(15.9, 4, true, false)) == PreviewTier.Low
+ && PreviewDefaults.TierOf(Machine(15.9, 8, true, true)) == PreviewTier.Low
+ && PreviewDefaults.TierOf(Machine(15.9, 8, false, false)) == PreviewTier.Low
+ && PreviewDefaults.TierOf(Machine(11.9, 16, true, false)) == PreviewTier.Low
+ && PreviewDefaults.TierOf(Machine(23.9, 8, true, null)) == PreviewTier.Middle
+ && PreviewDefaults.TierOf(Machine(31.9, 2, false, true)) == PreviewTier.High
+ && PreviewDefaults.TierOf(Machine(63.9, 20, true, false)) == PreviewTier.High,
+ "first start: 32 GB is High whatever else; below it under 16 GB, a seek penalty, no GPU or 4 threads is Low, an unknown drive is not");
+ Check(PreviewDefaults.QualityOf(PreviewTier.Low) == new PreviewQuality(2, 2, FrameFormat.Index) && PreviewDefaults.DitherBitsOf(PreviewTier.Low) == 0
+ && PreviewDefaults.QualityOf(PreviewTier.Middle) == new PreviewQuality(1, 1, FrameFormat.Index) && PreviewDefaults.DitherBitsOf(PreviewTier.Middle) == 0
+ && PreviewDefaults.QualityOf(PreviewTier.High) == new PreviewQuality(1, 1, FrameFormat.Half) && PreviewDefaults.DitherBitsOf(PreviewTier.High) == 16,
+ "first start: Low is half resolution, every second frame, 8-bit; Middle the fixed defaults; High 16-bit dithered to 16 bits");
+ }
+
/// <summary>
/// Every <see cref="RangeAttribute"/> on the model agrees with its owner's Normalize(): a value below or above the
/// range lands inside it, and a value at an inclusive bound stays as it is. Each leg runs on a fresh instance, so