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#
Review of the commits since 6a18c6b: the drag carries text alone, consolidations, nine harness checks
Alexander Graef973073508fac
diff --git a/CLAUDE.md b/CLAUDE.mdindex 1b084ea..dedcd66 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,6 +1,6 @@# WaveDude Next — project notes for Claude-Last updated 2026-10-16. The long history is in git (`git show a6f85dc:CLAUDE.md`). Keep this file short.+Last updated 2026-10-23. The long history is in git (`git show a6f85dc:CLAUDE.md`). Keep this file short.## What this is@@ -132,19 +132,19 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA- **Reduced preview** (View menu): resolution 1/2/4, frames 1/2/4 (the timeline never changes), samples 16-bit or**8-bit palette index, the default**: the stored samples at the palette's 255 colours and the captured brightness,half the store; 16-bit keeps the brightness turnable after a run and shows every level of the gradient. In 8-bit a- brightness edit is a simulation edit. The index is computed from the value a 16-bit frame stores, rounded to a half- (the field, the intensity's root), on the CPU and in the kernel (a bit-level rounding there), and the GPU program is- built with a correctly rounded square root where the card has one, so CPU and GPU store the same index bytes (2026-10-19).+ brightness edit is a simulation edit. **A 16-bit intensity plane holds √I** (2026-10-23, the user's choice: the+ renderer colours √I, and as I the dark end lay among half's subnormals, below 6.1e-5, up to a palette level between+ neighbours; as √I the floor is at I = 3.7e-9, the brightest parts a bit coarser): `FrameShape.IntensityRoot`, from the+ run's `PreviewQuality`, produced by `FrameConversion` and `capture_half`, reported by every `IFrameSource` through its+ `Shape`; the renderer, the screen path (which blends it as energy) and the fit go by its `SampleKind`. **The 8-bit+ index is the palette index of the half a 16-bit frame would store** (the field, √I), computed on the CPU and in the+ kernel (a bit-level rounding there, the GPU program built with a correctly rounded square root where the card has one),+ so CPU and GPU store the same bytes (2026-10-19) and both previews start from one value (2026-10-23, the user's choice:+ rounding I to a half first had merged the darkest indices at a high brightness, 2e-8 at 30 coming out 0 instead of 1).Every export needs the 16-bit samples (2026-10-23, the user's choice, so a picture has every level of the gradient):an 8-bit run, a reduced resolution or skipped frames make the export run the simulation again at full quality first.- **A 16-bit intensity plane holds √I** (2026-10-23, the user's choice: the renderer colours √I, and as I the dark end- lay among half's subnormals, below 6.1e-5, up to a palette level between neighbours; as √I the floor is at I =- 3.7e-9, the brightest parts a bit coarser): `FrameShape.IntensityRoot`, from the run's `PreviewQuality`, produced by- `FrameConversion` and `capture_half`, reported by every `IFrameSource`; the renderer, the screen path (which blends- it as energy) and the fit go by its `SampleKind`. Only an OpenEXR export of I makes a run that stores I itself- (squaring √I back would lose a bit). The 8-bit index is the palette index of that same stored half, √I for the- intensity (2026-10-23, the user's choice: one rule for both previews; rounding I to a half first had merged the- darkest indices at a high brightness, 2e-8 at 30 coming out 0 instead of 1).+ 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).## The app's rules@@ -178,6 +178,32 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAand point handles belong to the current item alone. Probe graph boxes follow their probe while attached, resize by a grip, keep their textsize; an amplitude axis is symmetric about zero; an intensity graph's value axis can be logarithmic (2026-10-20,Jeroen's point 8: `Decades` below the fitted top, zeros on the bottom line, powers-of-ten ticks; the field stays linear).+- **Undo and redo** (2026-10-22, the user's request, unlimited): `ProjectHistory` keeps one snapshot per step, the+ project file's XML without the scene image plus the image's bytes by reference (equal bytes shared). A step ends after+ 0.5 s of quiet with no mouse button held (`MainWindow.History`); Undo and Redo (Ctrl+Z, Ctrl+Y, Ctrl+Shift+Z; a text+ box keeps its own) write the step back into the same project object, the lists refilled and the settings objects+ replaced, so the watcher reports it as an edit (stale run, scratch frame, re-run) and nothing is recorded; the+ selection follows by name, then by index; the title's asterisk clears at the saved step. The Edit menu (between File+ and View) holds Undo, Redo, Cut, Copy, Paste and Delete; the UI harnesses step over it.+- **Copy, cut, paste, drag and drop** (2026-10-23, the user's choices): `ProjectClipboard` writes sources, parts,+ probes and schemes (the `INamed` items) and the Scene, Simulation and Display objects as a fragment of their own file+ elements, in the app's format and as plain text (read back from text too, so a text editor takes and gives the XML).+ Paste goes behind the current item, before it for a drop on a row's upper half, renames only on a clash, emitters+ from the target's seed; a settings object replaces only on its own row or the project root. A tree drag carries the+ same text and nothing else; the target decides (2026-10-23, the user's choice, replacing a live item in the drag data+ and a refusal of the own drag by the pictures): the own tree reorders the item it keeps in a field, another window's+ tree pastes, and a picture of this window or another pastes and moves the objects as a group onto the drop pixel+ (`PlaceAt`, held inside the canvas), so a drag from the tree to the picture duplicates. `ObjectsData` reads a drag or+ the clipboard and parses each text once; the window reads the clipboard once per change of Windows' clipboard+ sequence number.+- **Icons** (2026-10-22/23): a menu entry gets one through the attached `MenuIcon.Glyph` (a code point of Segoe Fluent+ Icons that Segoe MDL2 Assets has too, for Windows 10; the `IconGlyphText` style, greyscale) or `MenuIcon.Drawing`, the+ name of an `Icon<Name>` (and `Icon<Name>Fill`) `StreamGeometry` in `Themes/Controls.xaml`; both make an `IconView`,+ which the tree's rows and toolbar use directly (`PlusBadge` on the add buttons) and which draws in the inherited text+ colour, so a disabled row's icon greys with its name through one trigger on the row. Drawings are 16 px, 1 px strokes+ on half pixels, ink in rows and columns 0 to 14 (odd, so it centres like text); every tree row, toolbar button and+ menu entry is 23 px, the menu bar's headers through their padding. The pictures' 20 px handle glyphs stay in+ `PreviewPane.xaml`.- **Colour schemes are gradients** (2026-10-23, the user's design): the model holds the stops and no table; how manycolours are taken is the renderer's (`ColorLut`): 255 at i/254 for 8-bit frames (the author's table, truncated as inhis Python), and for 16-bit frames a table of the 65,536 half values per layer and brightness, the gradient at each@@ -191,7 +217,7 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAthe canvas came back from WPF in single precision, the reuse test failed on every frame, and the pane flickered).**Preview dithering** (View menu, user setting, off by default until the user has seen it; only with 16-bit samples):the colours at 16 bits per channel (`DeepHalfTable`) to 8 through a Bayer matrix of 2, 4, 8 or 16 cells a side for- 10, 12, 14 or 16 bits, fixed to the screen's pixels; preview only, never in an export (a video crushes it; an export+ 10, 12, 14 or 16 bits, fixed to the picture's pixels (on the screen's, by the window's layout rounding); preview only, never in an export (a video crushes it; an exportabove 8 bits per channel is a possible future goal). A better algorithm than Bayer may come later.- **Colour schemes** are stop lists in `.wdscheme` XML, shipped ones embedded, user ones in`%LOCALAPPDATA%\WaveDudeNext\ColorSchemes`, project ones in the `.wdproj`; an in-house picker edits stops;@@ -245,7 +271,7 @@ numbers: no GPU JPEG, no OpenCL colouring at presentation, no `Vector256`, no Di## Harnesses-`library_check` (100+ checks: engines, store, renderer, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, ranges, XOR gate).+`library_check` (100+ checks: engines, store, renderer, half tables, screen path, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, ranges, XOR gate, zone plate, gate port follower, history, clipboard).UI, all on `Common.ps1`, with their check counts: `PreviewCheck` 43, `RunCheck` 71, `LanguageCheck` 11,`ProbeGraphCheck` 39, `ImportCheck` 10, `ExportCheck` 38, `PreviewQualityCheck` 35, `SceneImageCheck` 8,`ColorPickerCheck` 13, `KeyboardCheck` 13, `AboutCheck` 18, `SelectionCheck` 10. Test projects `tiny*.wdproj` sit beside them. A harnessdiff --git a/OpticalParts.md b/OpticalParts.mdindex f46e337..d90cc40 100644--- a/OpticalParts.md+++ b/OpticalParts.md@@ -16,15 +16,21 @@ The class is the kind (2026-10-22: the `PartKind` enum was removed).(the English stem of new names, "Zone plate"), `PrepareNew()` if a new part needs something a loaded one must notget (a fibre's default path: `XmlSerializer` appends a file's items to the list it finds), and its properties under`CLAUDE.md`'s model conventions (`[Range]` beside every clamp in `Normalize()`).-2. Its shape in `Parts/PartShape.cs` (`PartShape.For`) and, if it has one, its size grip in `SceneOverlay.GripOf`.+2. Its shape in `Parts/PartShape.cs` (`PartShape.For`) and, if it has one, its size grip in `SceneOverlay.GripOf` and+ `SetGrip`.3. An `[XmlElement("Name", typeof(…))]` line on `Project.Parts`: one element name per kind.4. Its entry in `PartMenuEntries` (`Panes/ProjectTree.xaml`), where the app decides which kinds it offers and in whichorder; both menus take their entries from there.-5. A form in `Views/` with its `DataTemplate` in `PropertiesPane.xaml`, and its strings (`MenuAdd…`, `Label.`, `Hint.`,- `Enum.` for its enums) in all four tables.+5. A form in `Views/` with its `DataTemplate` in `PropertiesPane.xaml` (a template for a base class serves its+ subclasses: one for `LogicGatePart`), and its strings (`MenuAdd…`, `Label.`, `Hint.`, `Enum.` for its enums) in all+ four tables.+6. A 16 px drawing in `Themes/Controls.xaml` (2026-10-23): `Icon<Name>` stroked and, for solid parts, `Icon<Name>Fill`,+ `<Name>` the class name without "Part", 1 px lines on half pixels, the ink in rows and columns 0 to 14; the menu+ entry names it (`controls:MenuIcon.Drawing`) and the tree row finds it by the class name (`PartIconConverter`).`library_check` finds every part class by reflection: it fails one without its file element, one that `AddPart`-cannot add as "<stem> 1", and a clamped number without its `[Range]`. The menu entry and the form are not checked.+cannot add as "<stem> 1", and a clamped number without its `[Range]`. The menu entry, the form and the drawing are not+checked.## How parts reach the simulation@@ -66,7 +72,7 @@ cladding rim (`LogicGateDesign.Absorption`).## The kinds-Every part has `Name`, `Enabled` (a disabled part is not painted), `X`, `Y` (its centre, ≥ 0) and `Angle` (−180..180).+Every part has `Name`, `Enabled` (a disabled part is not painted), `X`, `Y` (its centre, ≥ 0) and `Angle` (−180, 180].Defaults and ranges are in the attributes beside each property; the figures below are the defaults.**Lens** (`LensPart`, `<Lens>`): `Diameter` 200 across the axis, `Thickness` 40 on the axis, signed radii `R1` 300 (the@@ -120,7 +126,7 @@ three, so they share dimensions and ports and tile together (measured at 120 ×- **Design**: entered as a source frequency (`DesignFrequency` 50); the wavelength follows from`Simulation.SourceFrequencyScale`, which `GatePortFollower` hands each gate (`FrequencyScale`), and the form shows it.`LogicGateDesign` lays the gate out with `WaveguideModes`, a mode solver on the engine's own discrete equations- (4th-order stencil; its β matches a simulated guide to 1e-5): smooth S-bends whose radius follows the mode's+ (4th-order stencil; its β matched a simulated guide to 1e-5 when measured, `library_check` holds it within 2e-3): smooth S-bends whose radius follows the mode'sconfinement, a measured coupling excess of 0.07 rad taken off. Defaults `CoreIndex` 2.55 in `CladdingIndex` 1.45,the phase section then lowered on arm A: port spacing 60, 120 × 544 px; both inputs leave about 1 % at the XOR output,the sum 1.9× (the user found 1600 px unacceptable).diff --git a/WaveDudeNext.WPF/Controls/IconView.cs b/WaveDudeNext.WPF/Controls/IconView.csindex fa933b0..1b3ee5b 100644--- a/WaveDudeNext.WPF/Controls/IconView.cs+++ b/WaveDudeNext.WPF/Controls/IconView.cs@@ -25,8 +25,8 @@ namespace WaveDudeNext.WPF.Controls;/// <summary>/// A 16 px icon (2026-10-23): a <see cref="Glyph"/> of Windows' icon font, or one of the app's own <see cref="Drawing"/>s,-/// in its inherited text colour, so it greys out with the text beside it. Used in the project tree's rows and, through-/// <see cref="Create"/>, by <see cref="MenuIcon"/>. Not focusable. UI thread.+/// in its inherited text colour, so it greys out with the text beside it. The project tree's rows and toolbar hold one each,+/// and <see cref="MenuIcon"/> gives one to a menu entry. Not focusable. UI thread./// </summary>public sealed class IconView : ContentControl{@@ -42,6 +42,7 @@ public sealed class IconView : ContentControlpublic static readonly DependencyProperty PlusBadgeProperty = DependencyProperty.Register(nameof(PlusBadge), typeof(bool), typeof(IconView), new PropertyMetadata(false, OnIconChanged));+ /// <summary>An empty 16 px icon, out of the Tab cycle.</summary>public IconView(){Focusable = false;@@ -78,42 +79,40 @@ public sealed class IconView : ContentControlset => SetValue(PlusBadgeProperty, value);}+ /// <summary>The glyph when there is one, else the drawing with its badge; nothing for neither.</summary>private static void OnIconChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){var view = (IconView)d;- UIElement? icon = Create(view.Glyph, view.Drawing);- if (view.PlusBadge && icon is Grid drawn)- {- var badge = new Path();- badge.SetResourceReference(FrameworkElement.StyleProperty, "IconPlusBadgeStyle");- drawn.Children.Add(badge);- }- view.Content = icon;- }-- /// <summary>The element showing <paramref name="glyph"/>, else <paramref name="drawing"/>; null for neither.</summary>- public static UIElement? Create(string? glyph, string? drawing)- {- if (glyph is { Length: > 0 })+ if (view.Glyph is { Length: > 0 } glyph){var text = new TextBlock { Text = glyph };// resolved once the element is in place, so a menu built in code finds the theme's style too- text.SetResourceReference(FrameworkElement.StyleProperty, "MenuIconText");- return text;+ text.SetResourceReference(StyleProperty, "IconGlyphText");+ view.Content = text;+ }+ else if (view.Drawing is { Length: > 0 } drawing)+ {+ // the inherited text colour each path holds itself (an ancestor lookup ran before the icon was in place and never+ // found one, 2026-10-23)+ var colour = new Binding { Path = new PropertyPath(TextElement.ForegroundProperty), RelativeSource = RelativeSource.Self };+ var stroke = new Path { StrokeThickness = 1.0 };+ stroke.SetResourceReference(Path.DataProperty, "Icon" + drawing);+ stroke.SetBinding(Shape.StrokeProperty, colour);+ var fill = new Path();+ fill.SetResourceReference(Path.DataProperty, "Icon" + drawing + "Fill");+ fill.SetBinding(Shape.FillProperty, colour);+ var drawn = new Grid { Width = 16, Height = 16, Children = { stroke, fill } };+ if (view.PlusBadge)+ {+ var badge = new Path();+ badge.SetResourceReference(StyleProperty, "IconPlusBadgeStyle");+ drawn.Children.Add(badge);+ }+ view.Content = drawn;}- if (drawing is not { Length: > 0 })+ else{- return null;+ view.Content = null;}- // the inherited text colour each path holds itself (an ancestor lookup ran before the icon was in place and never- // found one, 2026-10-23)- var colour = new Binding { Path = new PropertyPath(TextElement.ForegroundProperty), RelativeSource = RelativeSource.Self };- var stroke = new Path { StrokeThickness = 1.0 };- stroke.SetResourceReference(Path.DataProperty, "Icon" + drawing);- stroke.SetBinding(Shape.StrokeProperty, colour);- var fill = new Path();- fill.SetResourceReference(Path.DataProperty, "Icon" + drawing + "Fill");- fill.SetBinding(Shape.FillProperty, colour);- return new Grid { Width = 16, Height = 16, Children = { stroke, fill } };}}diff --git a/WaveDudeNext.WPF/Controls/MenuIcon.cs b/WaveDudeNext.WPF/Controls/MenuIcon.csindex d0064a5..06b981c 100644--- a/WaveDudeNext.WPF/Controls/MenuIcon.cs+++ b/WaveDudeNext.WPF/Controls/MenuIcon.cs@@ -21,11 +21,10 @@ using System.Windows.Controls;namespace WaveDudeNext.WPF.Controls;/// <summary>-/// A menu entry's icon: a glyph of Windows' icon font (2026-10-22, the user's request for the standard icons), or one of-/// the app's own drawings (<see cref="DrawingProperty"/>). The glyph is attached as-/// <c>controls:MenuIcon.Glyph="&#xE74E;"</c>, it gives the <see cref="MenuItem"/> a <see cref="TextBlock"/> of that-/// character in the theme's <c>MenuIconText</c> style (Segoe Fluent Icons on Windows 11, Segoe MDL2 Assets on Windows 10,-/// in the entry's text colour); both are made by <see cref="IconView.Create"/>, as the tree's icons are. UI thread.+/// A menu entry's icon, an <see cref="IconView"/> made from an attached property: <c>controls:MenuIcon.Glyph="&#xE74E;"</c>+/// for a glyph of Windows' icon font (2026-10-22, the user's request for the standard icons; Segoe Fluent Icons on Windows 11,+/// Segoe MDL2 Assets on Windows 10, in the theme's <c>IconGlyphText</c> style), <c>controls:MenuIcon.Drawing="Lens"</c> for one+/// of the app's own drawings (2026-10-23, for the entries the font has no glyph for). UI thread./// </summary>public static class MenuIcon{@@ -39,11 +38,7 @@ public static class MenuIcon/// <summary>Sets the glyph of <paramref name="item"/>, which becomes its icon.</summary>public static void SetGlyph(MenuItem item, string? glyph) => item.SetValue(GlyphProperty, glyph);- /// <summary>- /// Identifies the attached Drawing property: the name of one of the app's own 16 px icon drawings (2026-10-23), for- /// entries the icon font has no glyph for. The theme holds it as a stroked geometry <c>Icon{name}</c> and, where part of- /// it is solid, a filled one <c>Icon{name}Fill</c>; both are drawn in the entry's text colour, as vectors.- /// </summary>+ /// <summary>Identifies the attached Drawing property: the name of one of the app's 16 px drawings (<see cref="IconView.Drawing"/>), or null for none.</summary>public static readonly DependencyProperty DrawingProperty = DependencyProperty.RegisterAttached("Drawing", typeof(string), typeof(MenuIcon), new PropertyMetadata(null, OnDrawingChanged));@@ -53,19 +48,19 @@ public static class MenuIcon/// <summary>Sets the drawing of <paramref name="item"/>, which becomes its icon.</summary>public static void SetDrawing(MenuItem item, string? name) => item.SetValue(DrawingProperty, name);- private static void OnDrawingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)+ private static void OnGlyphChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){if (d is MenuItem item){- item.Icon = IconView.Create(null, e.NewValue as string);+ item.Icon = e.NewValue is string glyph ? new IconView { Glyph = glyph } : null;}}- private static void OnGlyphChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)+ private static void OnDrawingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){if (d is MenuItem item){- item.Icon = IconView.Create(e.NewValue as string, null);+ item.Icon = e.NewValue is string name ? new IconView { Drawing = name } : null;}}}diff --git a/WaveDudeNext.WPF/Controls/SceneOverlay.cs b/WaveDudeNext.WPF/Controls/SceneOverlay.csindex b0da3b3..a4bb934 100644--- a/WaveDudeNext.WPF/Controls/SceneOverlay.cs+++ b/WaveDudeNext.WPF/Controls/SceneOverlay.cs@@ -27,7 +27,6 @@ using System.Windows.Input;using System.Windows.Media;using NLog;using WaveDudeNext.Model;-using WaveDudeNext.WPF.Panes;namespace WaveDudeNext.WPF.Controls;@@ -973,28 +972,17 @@ public sealed class SceneOverlay : Panel}}- // ---------------------------------------------------------------- dropping objects from another window+ // ---------------------------------------------------------------- dropping objects onto the picture- /// <summary>The dragged text last parsed during a drag over this picture, and what it held.</summary>- private (string Text, ProjectClipboard.Clip? Clip)? _dropCache;+ /// <summary>The objects a drag carries, parsed once per drag.</summary>+ private readonly ObjectsData _dragged = new();/// <summary>- /// The objects a drag from another window carries, when it carries sources, parts, probes or schemes (as Copy writes- /// them, through <see cref="ProjectTree.ObjectsText"/>); null for anything else, and for a drag from this window, which- /// the tree reorders.+ /// The objects a drag carries, when it carries sources, parts, probes or schemes (as Copy writes them, from this+ /// window's tree or another's); null for anything else./// </summary>- private ProjectClipboard.Clip? DroppableClip(IDataObject data)- {- if (Project is not { } project || ProjectTree.IsFromThisWindow(data, project) || ProjectTree.ObjectsText(data) is not { } text)- {- return null;- }- if (_dropCache is not { } cache || cache.Text != text)- {- _dropCache = cache = (text, ProjectClipboard.Read(text));- }- return cache.Clip is { HasItems: true } clip ? clip : null;- }+ private ProjectClipboard.Clip? DroppableClip(IDataObject data) =>+ Project != null && _dragged.Clip(data) is { HasItems: true } clip ? clip : null;/// <inheritdoc/>protected override void OnDragOver(DragEventArgs e)@@ -1005,27 +993,27 @@ public sealed class SceneOverlay : Panel}/// <summary>- /// A drop of objects from another window (the user's choice, 2026-10-23): pasted as Paste does, at the end of their- /// lists, then moved as a group so the first one sits on the canvas pixel under the mouse, held inside the canvas as a- /// group drag is; the dropped objects become the selection. One undo step.+ /// A drop of objects (the user's choices, 2026-10-23: from another window, and since the drag carries text alone, from+ /// this window's tree too, a drag to duplicate): pasted as Paste does, at the end of their lists, then moved as a group+ /// so the first one sits on the canvas pixel under the mouse, held inside the canvas as a group drag is; the dropped+ /// objects become the selection. One undo step./// </summary>protected override void OnDrop(DragEventArgs e){base.OnDrop(e);e.Handled = true;- // read afresh: the paste takes the clip's objects into the project, so the parsed one of the drag-over is dropped- if (Project is not { } project || DroppableClip(e.Data) == null || ProjectTree.ObjectsText(e.Data) is not { } text- || ProjectClipboard.Read(text) is not { } clip)+ // taken, not kept: the paste makes the clip's objects the project's+ if (Project is not { } project || DroppableClip(e.Data) is not { } clip){return;}- _dropCache = null;+ _dragged.Clear();(double x, double y) = ToCanvasExact(e.GetPosition(this));int canvasX = (int)Math.Floor(x);int canvasY = (int)Math.Floor(y);IReadOnlyList<object> pasted = ProjectClipboard.Paste(project, clip, null);ProjectClipboard.PlaceAt(pasted, canvasX, canvasY, CanvasWidth, CanvasHeight);- Logger.Debug("Dropped {Count} object(s) from another window onto the picture at ({X}, {Y})", pasted.Count, canvasX, canvasY);+ Logger.Debug("Dropped {Count} object(s) onto the picture at ({X}, {Y})", pasted.Count, canvasX, canvasY);if (SelectedItems is { } selection){selection.Clear();diff --git a/WaveDudeNext.WPF/Converters/PartIconConverter.cs b/WaveDudeNext.WPF/Converters/PartIconConverter.csindex 894aa2b..9069f4e 100644--- a/WaveDudeNext.WPF/Converters/PartIconConverter.cs+++ b/WaveDudeNext.WPF/Converters/PartIconConverter.cs@@ -22,14 +22,14 @@ using WaveDudeNext.Model;namespace WaveDudeNext.WPF.Converters;/// <summary>-/// The icon drawing of an optical part (2026-10-23): its class name without "Part" (a <see cref="LensPart"/> is "Lens", an+/// The icon drawing of an optical part (2026-10-23): its class name without the Part suffix (a <see cref="LensPart"/> is "Lens", an/// <see cref="XorGatePart"/> "XorGate"), the name of the theme's <c>Icon{name}</c> geometry the Add part menu shows too./// </summary>public sealed class PartIconConverter : IValueConverter{/// <inheritdoc/>public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>- value is OpticalPart part ? part.GetType().Name.Replace("Part", "", StringComparison.Ordinal) : null;+ value is OpticalPart part ? part.GetType().Name[..^"Part".Length] : null;/// <inheritdoc/>public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>diff --git a/WaveDudeNext.WPF/MainWindow.Clipboard.cs b/WaveDudeNext.WPF/MainWindow.Clipboard.csindex 725f97d..afe4b6d 100644--- a/WaveDudeNext.WPF/MainWindow.Clipboard.cs+++ b/WaveDudeNext.WPF/MainWindow.Clipboard.cs@@ -19,7 +19,6 @@ using System.Runtime.InteropServices;using System.Windows;using System.Windows.Input;using WaveDudeNext.Model;-using WaveDudeNext.Rendering;using WaveDudeNext.WPF.Commands;namespace WaveDudeNext.WPF;@@ -36,14 +35,14 @@ namespace WaveDudeNext.WPF;/// </summary>public partial class MainWindow{- /// <summary>The clipboard text last looked at and what it held, so the menus' frequent "can paste" checks parse it once.</summary>- private (string Text, ProjectClipboard.Clip? Clip)? _clipCache;+ /// <summary>The clipboard's objects as last parsed and the clipboard's change count then, so the menus' frequent "can paste" checks read the clipboard once per change.</summary>+ private (uint Sequence, ProjectClipboard.Clip? Clip)? _clipCache;/// <summary>The copyable objects the command acts on: the row given, or the selection it belongs to.</summary>private object[] CopyGroup(object? parameter) => [.. Group(parameter).Where(item => ProjectClipboard.CanCopy(Project, item))];/// <summary>The list items among them (sources, parts, probes, schemes): what Cut takes away.</summary>- private object[] CutGroup(object? parameter) => [.. Group(parameter).Where(item => item is Source or OpticalPart or Probe or ColorScheme)];+ private object[] CutGroup(object? parameter) => [.. Group(parameter).Where(item => item is INamed)];private void CanCopyObjects(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = CopyGroup(e.Parameter).Length > 0;@@ -56,17 +55,19 @@ public partial class MainWindowprivate void OnCutObjects(object sender, ExecutedRoutedEventArgs e){- object[] group = CutGroup(e.Parameter);- if (group.Length > 0 && CopyToClipboard(group))+ if (CopyToClipboard(CutGroup(e.Parameter))){- ProjectCommands.Remove.Execute(group.Length == 1 ? group[0] : e.Parameter, this);+ // the same group: Remove takes the row given, or the selection it belongs to, as Cut did+ ProjectCommands.Remove.Execute(e.Parameter, this);}}private void OnPasteObjects(object sender, ExecutedRoutedEventArgs e){- // read afresh: a paste takes the clip's objects into the project, so each paste needs its own- if (ReadClipboard() is not { } text || ProjectClipboard.Read(text) is not { } clip)+ // taken, not kept: a paste makes the clip's objects the project's, so the next paste parses the text afresh+ ProjectClipboard.Clip? clip = ClipboardClip();+ _clipCache = null;+ if (clip == null){return;}@@ -77,7 +78,7 @@ public partial class MainWindow}Logger.Debug("Pasted {Count} object(s): {Names}", pasted.Count, string.Join(", ", pasted.Select(NameOrKind)));SelectedItems.Clear();- foreach (object item in pasted.Where(item => item is Source or OpticalPart or Probe or ColorScheme))+ foreach (object item in pasted.Where(item => item is INamed)){SelectedItems.Add(item);}@@ -99,51 +100,41 @@ public partial class MainWindow{Clipboard.SetDataObject(data, copy: true);}- catch (COMException ex)+ catch (ExternalException ex){// another program holds the clipboard openLogger.Warn(ex, "The clipboard is busy: nothing was copied");return false;}Logger.Debug("Copied {Count} object(s): {Names}", items.Length, string.Join(", ", items.Select(NameOrKind)));- _clipCache = null;return true;}- /// <summary>The objects on the clipboard as last parsed, for the "can paste" checks; null without any.</summary>+ /// <summary>The objects on the clipboard, read and parsed once per change of the clipboard (Windows counts its changes); null without any.</summary>private ProjectClipboard.Clip? ClipboardClip(){- if (ReadClipboard() is not { } text)- {- return null;- }- if (_clipCache is not { } cache || cache.Text != text)+ uint sequence = GetClipboardSequenceNumber();+ if (sequence != 0 && _clipCache is { } cache && cache.Sequence == sequence){- _clipCache = cache = (text, ProjectClipboard.Read(text));+ return cache.Clip;}- return cache.Clip;- }-- /// <summary>The objects on the clipboard as text (the app's format, or plain text that may hold them), or null.</summary>- private static string? ReadClipboard()- {+ ProjectClipboard.Clip? clip;try{- return Clipboard.GetDataObject() is { } data ? Panes.ProjectTree.ObjectsText(data) : null;+ clip = Clipboard.GetDataObject() is { } data && ObjectsData.Text(data) is { } text ? ProjectClipboard.Read(text) : null;}- catch (COMException)+ catch (ExternalException){// another program holds the clipboard open; the next check tries againreturn null;}+ _clipCache = (sequence, clip);+ return clip;}- private static string NameOrKind(object item) => item switch- {- Source source => source.Name,- OpticalPart part => part.Name,- Probe probe => probe.Name,- ColorScheme scheme => scheme.Name,- _ => item.GetType().Name,- };+ /// <summary>Windows' count of the clipboard's changes; 0 when it cannot be told (then the clipboard is read every time).</summary>+ [DllImport("user32.dll")]+ private static extern uint GetClipboardSequenceNumber();++ private static string NameOrKind(object item) => (item as INamed)?.Name ?? item.GetType().Name;}diff --git a/WaveDudeNext.WPF/MainWindow.Display.cs b/WaveDudeNext.WPF/MainWindow.Display.csindex 80d1238..6fef539 100644--- a/WaveDudeNext.WPF/MainWindow.Display.cs+++ b/WaveDudeNext.WPF/MainWindow.Display.cs@@ -103,7 +103,7 @@ public partial class MainWindow}}FrameLayer plane = PlaneOf(_fitRequest.Layer);- var source = new SnapshotFrameSource(result.Snapshot);+ IFrameSource source = new SnapshotFrameSource(result.Snapshot);var halves = new Half[source.Width * source.Height];double? fit = source.Has(plane) && source.CopyLayer(0, plane, halves) ? BrightnessFit.For(halves, source.KindOf(plane)) : null;// the runner's engine is released once its result is read (the snapshot belongs to the runner)diff --git a/WaveDudeNext.WPF/MainWindow.History.cs b/WaveDudeNext.WPF/MainWindow.History.csindex e2ac5c0..02e9dd2 100644--- a/WaveDudeNext.WPF/MainWindow.History.cs+++ b/WaveDudeNext.WPF/MainWindow.History.cs@@ -19,7 +19,6 @@ using System.Collections;using System.Windows.Input;using System.Windows.Threading;using WaveDudeNext.Model;-using WaveDudeNext.Rendering;namespace WaveDudeNext.WPF;@@ -113,9 +112,8 @@ public partial class MainWindow{return;}- object? current = SelectedItem;- List<(IList? List, string? Name, int Index)> selection = [.. SelectedItems.Select(Locate)];- (IList? List, string? Name, int Index)? currentPlace = current != null ? Locate(current) : null;+ List<Place> selection = [.. SelectedItems.Select(Locate)];+ Place? currentPlace = SelectedItem is { } current ? Locate(current) : null;bool moved;_restoring = true;try@@ -159,37 +157,23 @@ public partial class MainWindowproject => project.Display.Video,];- /// <summary>Where a selected item sits: its list, name and index there; or, with no list, the index of its settings object (-1 for anything else).</summary>- private (IList? List, string? Name, int Index) Locate(object item)- {- foreach (IList list in (IList[])[Project.Sources, Project.Parts, Project.Probes, Project.ColorSchemes])- {- int index = list.IndexOf(item);- if (index >= 0)- {- return (list, NameOf(item), index);- }- }- return (null, null, Array.FindIndex(SettingsObjects, get => ReferenceEquals(get(Project), item)));- }+ /// <summary>A selected item's place: its list, name and index there; or, with no list, the index of its settings object in <see cref="SettingsObjects"/> (-1 for anything else).</summary>+ private readonly record struct Place(IList? List, string? Name, int Index);- /// <summary>The restored object at a place <see cref="Locate"/> gave: the item of that name in the same list, else at the same index, or the settings object at the same place; null when it is gone.</summary>- private object? Find((IList? List, string? Name, int Index) place)+ /// <summary>Where a selected item sits now.</summary>+ private Place Locate(object item) =>+ ListOf(item) is { } list && list.IndexOf(item) is >= 0 and var index+ ? new Place(list, (item as INamed)?.Name, index)+ : new Place(null, null, Array.FindIndex(SettingsObjects, get => ReferenceEquals(get(Project), item)));++ /// <summary>The restored object at a place: the item of that name in the same list, else at the same index, or the settings object at the same place; null when it is gone.</summary>+ private object? Find(Place place){if (place.List is { } list){- object? named = place.Name != null ? list.Cast<object>().FirstOrDefault(item => NameOf(item) == place.Name) : null;+ object? named = place.Name != null ? list.OfType<INamed>().FirstOrDefault(item => item.Name == place.Name) : null;return named ?? (place.Index < list.Count ? list[place.Index] : null);}return place.Index >= 0 ? SettingsObjects[place.Index](Project) : null;}-- private static string? NameOf(object item) => item switch- {- Source source => source.Name,- OpticalPart part => part.Name,- Probe probe => probe.Name,- ColorScheme scheme => scheme.Name,- _ => null,- };}diff --git a/WaveDudeNext.WPF/MainWindow.Project.cs b/WaveDudeNext.WPF/MainWindow.Project.csindex c7ffa08..22ba6f4 100644--- a/WaveDudeNext.WPF/MainWindow.Project.cs+++ b/WaveDudeNext.WPF/MainWindow.Project.cs@@ -166,7 +166,7 @@ public partial class MainWindow}private void CanEditItem(object sender, CanExecuteRoutedEventArgs e) =>- e.CanExecute = Target(e.Parameter) is Source or OpticalPart or Probe or ColorScheme;+ e.CanExecute = Target(e.Parameter) is INamed;private void CanToggleEnabled(object sender, CanExecuteRoutedEventArgs e) =>e.CanExecute = Target(e.Parameter) is Source or OpticalPart or Probe;@@ -226,7 +226,7 @@ public partial class MainWindowprivate void CanDelete(object sender, CanExecuteRoutedEventArgs e) =>e.CanExecute = e.OriginalSource is System.Windows.Controls.TextBox box? box is { IsReadOnly: false, SelectionLength: > 0 }- : Target(null) is Source or OpticalPart or Probe or ColorScheme;+ : Target(null) is INamed;private void OnDelete(object sender, ExecutedRoutedEventArgs e){@@ -282,13 +282,13 @@ public partial class MainWindowprivate void CanMoveUp(object sender, CanExecuteRoutedEventArgs e){object? item = Target(e.Parameter);- e.CanExecute = ListOf(item) is { } list && item is Source or OpticalPart or Probe or ColorScheme && list.IndexOf(item) > 0;+ e.CanExecute = ListOf(item) is { } list && item is INamed && list.IndexOf(item) > 0;}private void CanMoveDown(object sender, CanExecuteRoutedEventArgs e){object? item = Target(e.Parameter);- e.CanExecute = ListOf(item) is { } list && item is Source or OpticalPart or Probe or ColorScheme && list.IndexOf(item) < list.Count - 1;+ e.CanExecute = ListOf(item) is { } list && item is INamed && list.IndexOf(item) < list.Count - 1;}private void OnMoveUp(object sender, ExecutedRoutedEventArgs e) => MoveBy(Target(e.Parameter), -1);diff --git a/WaveDudeNext.WPF/MainWindow.xaml.cs b/WaveDudeNext.WPF/MainWindow.xaml.csindex 843768c..5760fb6 100644--- a/WaveDudeNext.WPF/MainWindow.xaml.cs+++ b/WaveDudeNext.WPF/MainWindow.xaml.cs@@ -111,13 +111,9 @@ public partial class MainWindow : WindowLogger.Info("Preview quality: {Quality} (View menu)", PreviewQualitySetting);OnPreviewQualityChanged();}- else if (args.PropertyName == nameof(Settings.PreviewDitherBits) && Settings.Default.PreviewDitherBits == 0)- {- Logger.Info("Preview dithering off (View menu)");- }else if (args.PropertyName == nameof(Settings.PreviewDitherBits)){- Logger.Info("Preview dithering from {Bits} bits per channel (View menu)", Settings.Default.PreviewDitherBits);+ Logger.Info("Preview dithering {State} (View menu)", Settings.Default.PreviewDitherBits == 0 ? "off" : "from " + Settings.Default.PreviewDitherBits + " bits per channel");}};Closing += (_, e) =>diff --git a/WaveDudeNext.WPF/ObjectsData.cs b/WaveDudeNext.WPF/ObjectsData.csnew file mode 100644index 0000000..bd27e85--- /dev/null+++ b/WaveDudeNext.WPF/ObjectsData.cs@@ -0,0 +1,78 @@+// 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.Runtime.InteropServices;+using System.Windows;+using WaveDudeNext.Model;++namespace WaveDudeNext.WPF;++/// <summary>+/// Project objects carried by a drag or the clipboard (2026-10-23): the text <see cref="ProjectClipboard.Write"/> makes,+/// in the app's format or as plain text that may hold it (copied back from a text editor, which keeps text only;+/// <see cref="ProjectClipboard.Read"/> decides, and text not starting with an element is not even parsed). An instance+/// parses each text once, for the many drag-over events of one drag. The text is all a drag carries, from this window+/// or another: the target decides what a drop does (the tree reorders its own drag, anything else pastes a copy). UI thread.+/// </summary>+internal sealed class ObjectsData+{+ private (string Text, ProjectClipboard.Clip? Clip)? _cache;++ /// <summary>The objects <paramref name="data"/> carries, parsed once per text; null without any.</summary>+ public ProjectClipboard.Clip? Clip(IDataObject data)+ {+ if (Text(data) is not { } text)+ {+ return null;+ }+ if (_cache is not { } cache || cache.Text != text)+ {+ _cache = cache = (text, ProjectClipboard.Read(text));+ }+ return cache.Clip;+ }++ /// <summary>The objects as <see cref="Clip"/> gives them, then forgotten: a paste makes them the project's, so the same text is parsed afresh next time.</summary>+ public ProjectClipboard.Clip? Take(IDataObject data)+ {+ ProjectClipboard.Clip? clip = Clip(data);+ _cache = null;+ return clip;+ }++ /// <summary>Forgets the parsed text.</summary>+ public void Clear() => _cache = null;++ /// <summary>The objects' text in <paramref name="data"/>: the app's format, else plain text that starts with an element; null for neither (and when the data cannot be read).</summary>+ public static string? Text(IDataObject data)+ {+ try+ {+ if (data.GetDataPresent(ProjectClipboard.Format))+ {+ return data.GetData(ProjectClipboard.Format) as string;+ }+ return data.GetDataPresent(DataFormats.UnicodeText) && data.GetData(DataFormats.UnicodeText) is string text && text.TrimStart().StartsWith('<')+ ? text+ : null;+ }+ catch (Exception ex) when (ex is ExternalException or InvalidOperationException)+ {+ return null;+ }+ }+}diff --git a/WaveDudeNext.WPF/Panes/PreviewPane.xaml b/WaveDudeNext.WPF/Panes/PreviewPane.xamlindex c8a8edb..c78afc9 100644--- a/WaveDudeNext.WPF/Panes/PreviewPane.xaml+++ b/WaveDudeNext.WPF/Panes/PreviewPane.xaml@@ -163,9 +163,14 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</Setter></Style>- <!-- the handle glyphs (SourceGlyph, ProbeGlyph, PartGlyph) are in Themes/Controls.xaml, shared with the project tree's icons;- every stroke is drawn twice here, a dark halo first, so the glyph reads on any picture. The selected item's handle and- the focused handle show the accent -->+ <!-- the handles of the sources, parts and probes on the pictures: a ring for a source, a ring with an inner ring for a+ part (a lens-shaped glyph read as squashed, 2026-10-18), a square for a probe point, each with four crosshair ticks+ outside it and a gap around the exact pixel; every stroke is drawn twice, a dark halo first, so the glyph reads on+ any picture. The selected item's handle and the focused handle show the accent. Glyphs are 20 x 20 with the point+ at (10, 10); the tree's 16 px icons (Themes/Controls.xaml) are drawn after them -->+ <StreamGeometry x:Key="SourceGlyph">M4,10 A6,6 0 1 1 16,10 A6,6 0 1 1 4,10 M10,0 L10,2.5 M10,17.5 L10,20 M0,10 L2.5,10 M17.5,10 L20,10</StreamGeometry>+ <StreamGeometry x:Key="ProbeGlyph">M4.5,4.5 L15.5,4.5 L15.5,15.5 L4.5,15.5 Z M10,0 L10,2.5 M10,17.5 L10,20 M0,10 L2.5,10 M17.5,10 L20,10</StreamGeometry>+ <StreamGeometry x:Key="PartGlyph">M4,10 A6,6 0 1 1 16,10 A6,6 0 1 1 4,10 M7.5,10 A2.5,2.5 0 1 1 12.5,10 A2.5,2.5 0 1 1 7.5,10 M10,0 L10,2.5 M10,17.5 L10,20 M0,10 L2.5,10 M17.5,10 L20,10</StreamGeometry><Style x:Key="MarkerBase" TargetType="{x:Type controls:MarkerThumb}"><Setter Property="Width" Value="20" /><Setter Property="Height" Value="20" />diff --git a/WaveDudeNext.WPF/Panes/ProjectTree.xaml b/WaveDudeNext.WPF/Panes/ProjectTree.xamlindex d6c4fed..6998820 100644--- a/WaveDudeNext.WPF/Panes/ProjectTree.xaml+++ b/WaveDudeNext.WPF/Panes/ProjectTree.xaml@@ -88,9 +88,24 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<Setter Property="Background" Value="Transparent" /><Setter Property="BorderBrush" Value="Transparent" /><Setter Property="Padding" Value="6,1,6,0" />- <Setter Property="MinHeight" Value="23" /><Setter Property="Margin" Value="1,0" /></Style>+ <!-- a row whose item is switched off greys its icon and name: both take the text colour the row's panel passes down+ (TextElement.Foreground), so one trigger on the panel does for both; the glyph buttons hold their own colour -->+ <Style x:Key="DisabledRow" TargetType="{x:Type DockPanel}">+ <Style.Triggers>+ <DataTrigger Binding="{Binding Enabled}" Value="False">+ <Setter Property="TextElement.Foreground" Value="{DynamicResource GrayText}" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ <Style x:Key="InactiveRow" TargetType="{x:Type DockPanel}">+ <Style.Triggers>+ <DataTrigger Binding="{Binding Active}" Value="False">+ <Setter Property="TextElement.Foreground" Value="{DynamicResource GrayText}" />+ </DataTrigger>+ </Style.Triggers>+ </Style><!-- the part entries, the optics first and the plain shapes after a separator, in one place for both menus that offerthem (the menu of kinds and the tree rows' Add part): each entry adds its kind, the class as the parameter. Notshared, so every menu that lists them gets its own entries (added to its items by ProjectTree.MenuEntries) -->@@ -318,44 +333,24 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<!-- item rows: name, move up/down and remove --><DataTemplate DataType="{x:Type model:Source}">- <DockPanel>+ <DockPanel Style="{StaticResource DisabledRow}"><Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource MinusGeometry}"ToolTip="{DynamicResource TipRemove}" AutomationProperties.Name="{DynamicResource TipRemove}" Command="{x:Static commands:ProjectCommands.Remove}" CommandParameter="{Binding}" /><Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource ChevronDownGeometry}"ToolTip="{DynamicResource TipMoveDown}" AutomationProperties.Name="{DynamicResource TipMoveDown}" Command="{x:Static commands:ProjectCommands.MoveDown}" CommandParameter="{Binding}" /><Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource ChevronUpGeometry}"ToolTip="{DynamicResource TipMoveUp}" AutomationProperties.Name="{DynamicResource TipMoveUp}" Command="{x:Static commands:ProjectCommands.MoveUp}" CommandParameter="{Binding}" />- <!-- the enabled check box (Space on the selected row toggles it too); the name greys out when off -->+ <!-- the enabled check box (Space on the selected row toggles it too); the icon and the name grey out when off (the row style) --><CheckBox DockPanel.Dock="Left" Focusable="False" IsTabStop="False" MinHeight="0" Margin="0,0,4,0" VerticalAlignment="Center"IsChecked="{Binding Enabled}" ToolTip="{DynamicResource TipSourceEnabled}"AutomationProperties.Name="{DynamicResource TipSourceEnabled}" AutomationProperties.AutomationId="{Binding Name, StringFormat='Enabled:{0}'}" />- <controls:IconView DockPanel.Dock="Left" Drawing="Source" Margin="0,0,4,0" VerticalAlignment="Center">- <controls:IconView.Style>- <Style TargetType="{x:Type controls:IconView}">- <Style.Triggers>- <DataTrigger Binding="{Binding Enabled}" Value="False">- <Setter Property="Foreground" Value="{DynamicResource GrayText}" />- </DataTrigger>- </Style.Triggers>- </Style>- </controls:IconView.Style>- </controls:IconView>- <TextBlock Text="{Binding Name}" VerticalAlignment="Center">- <TextBlock.Style>- <Style TargetType="{x:Type TextBlock}">- <Style.Triggers>- <DataTrigger Binding="{Binding Enabled}" Value="False">- <Setter Property="Foreground" Value="{DynamicResource GrayText}" />- </DataTrigger>- </Style.Triggers>- </Style>- </TextBlock.Style>- </TextBlock>+ <controls:IconView DockPanel.Dock="Left" Drawing="Source" Margin="0,0,4,0" VerticalAlignment="Center" />+ <TextBlock Text="{Binding Name}" VerticalAlignment="Center" /></DockPanel></DataTemplate><!-- an optical part: like a source, the enabled check box, the name, move and remove --><DataTemplate DataType="{x:Type model:OpticalPart}">- <DockPanel>+ <DockPanel Style="{StaticResource DisabledRow}"><Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource MinusGeometry}"ToolTip="{DynamicResource TipRemove}" AutomationProperties.Name="{DynamicResource TipRemove}" Command="{x:Static commands:ProjectCommands.Remove}" CommandParameter="{Binding}" /><Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource ChevronDownGeometry}"@@ -365,28 +360,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<CheckBox DockPanel.Dock="Left" Focusable="False" IsTabStop="False" MinHeight="0" Margin="0,0,4,0" VerticalAlignment="Center"IsChecked="{Binding Enabled}" ToolTip="{DynamicResource TipPartEnabled}"AutomationProperties.Name="{DynamicResource TipPartEnabled}" AutomationProperties.AutomationId="{Binding Name, StringFormat='Enabled:{0}'}" />- <controls:IconView DockPanel.Dock="Left" Drawing="{Binding Converter={StaticResource PartIcon}}" Margin="0,0,4,0" VerticalAlignment="Center">- <controls:IconView.Style>- <Style TargetType="{x:Type controls:IconView}">- <Style.Triggers>- <DataTrigger Binding="{Binding Enabled}" Value="False">- <Setter Property="Foreground" Value="{DynamicResource GrayText}" />- </DataTrigger>- </Style.Triggers>- </Style>- </controls:IconView.Style>- </controls:IconView>- <TextBlock Text="{Binding Name}" VerticalAlignment="Center">- <TextBlock.Style>- <Style TargetType="{x:Type TextBlock}">- <Style.Triggers>- <DataTrigger Binding="{Binding Enabled}" Value="False">- <Setter Property="Foreground" Value="{DynamicResource GrayText}" />- </DataTrigger>- </Style.Triggers>- </Style>- </TextBlock.Style>- </TextBlock>+ <controls:IconView DockPanel.Dock="Left" Drawing="{Binding Converter={StaticResource PartIcon}}" Margin="0,0,4,0" VerticalAlignment="Center" />+ <TextBlock Text="{Binding Name}" VerticalAlignment="Center" /></DockPanel></DataTemplate><!-- a project colour scheme: its gradient and name -->@@ -404,39 +379,19 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</DockPanel></DataTemplate><DataTemplate DataType="{x:Type model:Probe}">- <DockPanel>+ <DockPanel Style="{StaticResource InactiveRow}"><Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource MinusGeometry}"ToolTip="{DynamicResource TipRemove}" AutomationProperties.Name="{DynamicResource TipRemove}" Command="{x:Static commands:ProjectCommands.Remove}" CommandParameter="{Binding}" /><Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource ChevronDownGeometry}"ToolTip="{DynamicResource TipMoveDown}" AutomationProperties.Name="{DynamicResource TipMoveDown}" Command="{x:Static commands:ProjectCommands.MoveDown}" CommandParameter="{Binding}" /><Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource ChevronUpGeometry}"ToolTip="{DynamicResource TipMoveUp}" AutomationProperties.Name="{DynamicResource TipMoveUp}" Command="{x:Static commands:ProjectCommands.MoveUp}" CommandParameter="{Binding}" />- <!-- the enabled check box (Space on the selected row toggles it too); the name greys out when off -->+ <!-- the enabled check box (Space on the selected row toggles it too); the icon and the name grey out when off (the row style) --><CheckBox DockPanel.Dock="Left" Focusable="False" IsTabStop="False" MinHeight="0" Margin="0,0,4,0" VerticalAlignment="Center"IsChecked="{Binding Active}" ToolTip="{DynamicResource TipProbeActive}"AutomationProperties.Name="{DynamicResource TipProbeActive}" AutomationProperties.AutomationId="{Binding Name, StringFormat='Enabled:{0}'}" />- <controls:IconView DockPanel.Dock="Left" Drawing="Probe" Margin="0,0,4,0" VerticalAlignment="Center">- <controls:IconView.Style>- <Style TargetType="{x:Type controls:IconView}">- <Style.Triggers>- <DataTrigger Binding="{Binding Active}" Value="False">- <Setter Property="Foreground" Value="{DynamicResource GrayText}" />- </DataTrigger>- </Style.Triggers>- </Style>- </controls:IconView.Style>- </controls:IconView>- <TextBlock Text="{Binding Name}" VerticalAlignment="Center">- <TextBlock.Style>- <Style TargetType="{x:Type TextBlock}">- <Style.Triggers>- <DataTrigger Binding="{Binding Active}" Value="False">- <Setter Property="Foreground" Value="{DynamicResource GrayText}" />- </DataTrigger>- </Style.Triggers>- </Style>- </TextBlock.Style>- </TextBlock>+ <controls:IconView DockPanel.Dock="Left" Drawing="Probe" Margin="0,0,4,0" VerticalAlignment="Center" />+ <TextBlock Text="{Binding Name}" VerticalAlignment="Center" /></DockPanel></DataTemplate></TreeView.Resources>diff --git a/WaveDudeNext.WPF/Panes/ProjectTree.xaml.cs b/WaveDudeNext.WPF/Panes/ProjectTree.xaml.csindex 86da3b5..93fbb59 100644--- a/WaveDudeNext.WPF/Panes/ProjectTree.xaml.cs+++ b/WaveDudeNext.WPF/Panes/ProjectTree.xaml.cs@@ -43,8 +43,6 @@ namespace WaveDudeNext.WPF.Panes;/// </summary>public partial class ProjectTree : UserControl{- private const string DragFormat = "WaveDudeNext.ProjectTree.Item";-private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();/// <summary>Identifies the <see cref="Project"/> property.</summary>@@ -93,8 +91,10 @@ public partial class ProjectTree : UserControlprivate object? _dragCandidate;/// <summary>Whether a drag started in this tree is under way: its drops reorder, and never paste a copy of themselves.</summary>private bool _dragging;- /// <summary>The dragged text last parsed during a drag over this tree, and what it held.</summary>- private (string Text, ProjectClipboard.Clip? Clip)? _dropCache;+ /// <summary>The list item a drag from this tree carries, which a drop on this tree reorders; null while a settings row is dragged.</summary>+ private object? _dragItem;+ /// <summary>The objects a drag from elsewhere carries, parsed once per drag.</summary>+ private readonly ObjectsData _dragged = new();private Point _dragStart;private InsertionAdorner? _adorner;private object? _anchor;@@ -318,11 +318,12 @@ public partial class ProjectTree : UserControlreturn false;}- // ----- drag and drop: reordering within the tree, copying between windows ------ // A drag carries the item itself, for reordering within its list here, and the item as Copy writes it (the app's- // clipboard format and plain text, 2026-10-23), so another WaveDude Next window takes a copy as Paste would and a- // text editor takes the XML. A drop from another window is placed by the paste logic: before or after a row of a list- // (by the half of the row), at the end of a folder's list, or onto Scene, Simulation, Display or the project root.+ // ----- drag and drop: reordering within the tree, copying anywhere else -----+ // A drag carries the item as Copy writes it (the app's clipboard format and plain text, 2026-10-23) and nothing else;+ // the item itself stays in a field here, so a drop on this tree reorders it within its list, while any other target+ // takes a copy: another WaveDude Next window's tree as Paste would, a picture of this window or another at the drop+ // pixel, a text editor as XML. A drop of objects on this tree is placed by the paste logic: before or after a row of a+ // list (by the half of the row), at the end of a folder's list, or onto Scene, Simulation, Display or the project root.private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e){@@ -334,7 +335,7 @@ public partial class ProjectTree : UserControl}if (FindAncestor<TreeViewItem>(origin) is { } row && Project is { } project && ProjectClipboard.CanCopy(project, row.DataContext)){- if (row.DataContext is Source or OpticalPart or Probe or ColorScheme && TryModifiedClick(row.DataContext))+ if (row.DataContext is INamed && TryModifiedClick(row.DataContext)){e.Handled = true; // the TreeView would make the row its plain selectionreturn;@@ -359,10 +360,7 @@ public partial class ProjectTree : UserControlobject item = _dragCandidate;_dragCandidate = null;var data = new DataObject();- if (ListOf(item) != null)- {- data.SetData(DragFormat, item);- }+ _dragItem = ListOf(item) != null ? item : null;string text = ProjectClipboard.Write(project, [item]);data.SetData(ProjectClipboard.Format, text);data.SetText(text);@@ -374,7 +372,8 @@ public partial class ProjectTree : UserControlfinally{_dragging = false;- _dropCache = null;+ _dragItem = null;+ _dragged.Clear();ClearAdorner();}}@@ -384,7 +383,7 @@ public partial class ProjectTree : UserControle.Effects = DragDropEffects.None;e.Handled = true;ClearAdorner();- if (OwnItem(e.Data) is { } item)+ if (_dragItem is { } item){if (FindDropTarget(item, e.GetPosition(tree)) is { } target){@@ -393,7 +392,7 @@ public partial class ProjectTree : UserControl}return;}- if (!_dragging && DraggedClip(e.Data) is { } clip && FindPasteTarget(clip, e.GetPosition(tree)) is { } paste)+ if (!_dragging && _dragged.Clip(e.Data) is { } clip && FindPasteTarget(clip, e.GetPosition(tree)) is { } paste){e.Effects = DragDropEffects.Copy;ShowAdorner(paste.Row, paste.Header, paste.Placement);@@ -410,7 +409,7 @@ public partial class ProjectTree : UserControl{return;}- if (OwnItem(e.Data) is { } item)+ if (_dragItem is { } item){if (FindDropTarget(item, e.GetPosition(tree)) is not { } target){@@ -429,23 +428,21 @@ public partial class ProjectTree : UserControl}return;}- // read afresh: the paste takes the clip's objects into the project- if (_dragging || ObjectsText(e.Data) is not { } text || ProjectClipboard.Read(text) is not { } clip- || FindPasteTarget(clip, e.GetPosition(tree)) is not { } paste)+ // taken, not kept: the paste makes the clip's objects the project's+ if (_dragging || _dragged.Take(e.Data) is not { } clip || FindPasteTarget(clip, e.GetPosition(tree)) is not { } paste){return;}IReadOnlyList<object> pasted = ProjectClipboard.Paste(project, clip, paste.Current, paste.Before);- _dropCache = null;if (pasted.Count == 0){return;}- Logger.Debug("Dropped {Count} object(s) from another window", pasted.Count);+ Logger.Debug("Dropped {Count} object(s) into the tree", pasted.Count);if (SelectedItems is { } selection){selection.Clear();- foreach (object added in pasted.Where(added => added is Source or OpticalPart or Probe or ColorScheme))+ foreach (object added in pasted.Where(added => added is INamed)){selection.Add(added);}@@ -453,80 +450,11 @@ public partial class ProjectTree : UserControlSelect(pasted[^1]);}- /// <summary>- /// Whether a drag started in this window: it carries a live item of <paramref name="project"/>'s lists (a drag from- /// another window carries none that can be read here). The pictures refuse such drops: they take objects from other- /// windows only.- /// </summary>- internal static bool IsFromThisWindow(IDataObject data, Project project)- {- try- {- return data.GetDataPresent(DragFormat) && data.GetData(DragFormat) is { } item- && ((IList[])[project.Sources, project.Parts, project.Probes, project.ColorSchemes]).Any(list => list.Contains(item));- }- catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or InvalidOperationException)- {- return false;- }- }-- /// <summary>The dragged item when the drag started in this tree and the item is in this project's lists; null otherwise (a drag from another window carries no live object).</summary>- private object? OwnItem(IDataObject data)- {- try- {- return data.GetDataPresent(DragFormat) && data.GetData(DragFormat) is { } item && ListOf(item)?.Contains(item) == true ? item : null;- }- catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or InvalidOperationException)- {- return null;- }- }-- /// <summary>- /// The objects a drag or the clipboard carries, as Copy writes them: the app's format, else plain text that may hold- /// them (2026-10-23: copied back from a text editor, which keeps text only; <see cref="ProjectClipboard.Read"/> decides,- /// and text not starting with an element is not even parsed). Null for neither. Shared by the tree, the pictures and- /// Paste.- /// </summary>- internal static string? ObjectsText(IDataObject data)- {- try- {- if (data.GetDataPresent(ProjectClipboard.Format))- {- return data.GetData(ProjectClipboard.Format) as string;- }- return data.GetDataPresent(DataFormats.UnicodeText) && data.GetData(DataFormats.UnicodeText) is string text && text.TrimStart().StartsWith('<')- ? text- : null;- }- catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or InvalidOperationException)- {- return null;- }- }-- /// <summary>The dragged objects as last parsed, for the many drag-over events of one drag; null without any.</summary>- private ProjectClipboard.Clip? DraggedClip(IDataObject data)- {- if (ObjectsText(data) is not { } text)- {- return null;- }- if (_dropCache is not { } cache || cache.Text != text)- {- _dropCache = cache = (text, ProjectClipboard.Read(text));- }- return cache.Clip;- }-- /// <summary>Where a drop from another window would go, as the paste logic takes it: the current item it is placed by, and before it or not.</summary>+ /// <summary>Where a drop of objects would go, as the paste logic takes it: the current item it is placed by, and before it or not.</summary>private sealed record PasteTarget(TreeViewItem Row, FrameworkElement Header, InsertionPlacement Placement, object? Current, bool Before);/// <summary>- /// Resolves a drop of <paramref name="clip"/> from another window: on a list item before or after it (by the half of the+ /// Resolves a drop of <paramref name="clip"/> from elsewhere: on a list item before or after it (by the half of the/// row), on a folder at the end of its list, on Scene, Simulation, Display or the project root as a paste onto them. Null/// where the clip has nothing to give (settings onto a list row without list items, for instance)./// </summary>diff --git a/WaveDudeNext.WPF/Panes/PropertiesPane.xaml b/WaveDudeNext.WPF/Panes/PropertiesPane.xamlindex 2418e78..4ad68c9 100644--- a/WaveDudeNext.WPF/Panes/PropertiesPane.xaml+++ b/WaveDudeNext.WPF/Panes/PropertiesPane.xaml@@ -73,13 +73,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<DataTemplate DataType="{x:Type model:ZonePlatePart}"><views:ZonePlatePartView /></DataTemplate>- <DataTemplate DataType="{x:Type model:XorGatePart}">- <views:LogicGatePartView />- </DataTemplate>- <DataTemplate DataType="{x:Type model:AndGatePart}">- <views:LogicGatePartView />- </DataTemplate>- <DataTemplate DataType="{x:Type model:OrGatePart}">+ <!-- an implicit template is found along the base classes, so the three gate kinds share one -->+ <DataTemplate DataType="{x:Type model:LogicGatePart}"><views:LogicGatePartView /></DataTemplate><DataTemplate DataType="{x:Type model:Probe}">diff --git a/WaveDudeNext.WPF/Themes/Controls.xaml b/WaveDudeNext.WPF/Themes/Controls.xamlindex 5ecdfff..cf54489 100644--- a/WaveDudeNext.WPF/Themes/Controls.xaml+++ b/WaveDudeNext.WPF/Themes/Controls.xaml@@ -80,13 +80,6 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</Setter></Style>- <ControlTemplate x:Key="MenuPopupContent" TargetType="{x:Type MenuItem}">- <Border Background="{DynamicResource MenuPopupBackground}"- BorderBrush="{DynamicResource MenuPopupBorder}" BorderThickness="1" Padding="2">- <ItemsPresenter KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="True" />- </Border>- </ControlTemplate>-<ControlTemplate x:Key="MenuTopLevelHeaderTemplate" TargetType="{x:Type MenuItem}"><Border x:Name="Bd" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True"><Grid>@@ -212,10 +205,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</ControlTemplate.Triggers></ControlTemplate>- <!-- a menu icon from Windows' icon font (controls:MenuIcon.Glyph): Segoe Fluent Icons on Windows 11, Segoe MDL2 Assets on Windows 10 (the same code+ <!-- an icon from Windows' icon font (IconView Glyph, controls:MenuIcon.Glyph): Segoe Fluent Icons on Windows 11, Segoe MDL2 Assets on Windows 10 (the same codepoints), drawn on their 16 px grid; the line is held to 16 px, as the font's own line height overflowed the 16 px slotand cut the glyphs, and the glyph then moved down 3 px to the text's middle (measured on a capture: it sat 3.5 px high) -->- <Style x:Key="MenuIconText" TargetType="{x:Type TextBlock}">+ <Style x:Key="IconGlyphText" TargetType="{x:Type TextBlock}"><Setter Property="FontFamily" Value="Segoe Fluent Icons, Segoe MDL2 Assets" /><Setter Property="FontSize" Value="16" /><Setter Property="LineHeight" Value="16" />@@ -231,16 +224,9 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<Setter Property="VerticalAlignment" Value="Center" /></Style>- <!-- the handles of the sources, parts and probes on the pictures (moved here 2026-10-23, shared with the project tree):- a ring for a source, a ring with an inner ring for a part (a lens-shaped glyph read as squashed, 2026-10-18), a square- for a probe point, each with four crosshair ticks outside it and a gap around the exact pixel. Glyphs are 20 x 20 with- the point at (10, 10) -->- <StreamGeometry x:Key="SourceGlyph">M4,10 A6,6 0 1 1 16,10 A6,6 0 1 1 4,10 M10,0 L10,2.5 M10,17.5 L10,20 M0,10 L2.5,10 M17.5,10 L20,10</StreamGeometry>- <StreamGeometry x:Key="ProbeGlyph">M4.5,4.5 L15.5,4.5 L15.5,15.5 L4.5,15.5 Z M10,0 L10,2.5 M10,17.5 L10,20 M0,10 L2.5,10 M17.5,10 L20,10</StreamGeometry>- <StreamGeometry x:Key="PartGlyph">M4,10 A6,6 0 1 1 16,10 A6,6 0 1 1 4,10 M7.5,10 A2.5,2.5 0 1 1 12.5,10 A2.5,2.5 0 1 1 7.5,10 M10,0 L10,2.5 M10,17.5 L10,20 M0,10 L2.5,10 M17.5,10 L20,10</StreamGeometry>- <!-- the same glyphs as 16 px icons for the tree's rows and folders and the tree's toolbar (IconView Drawing="Source",- "Probe", "Part"), drawn for the pixel grid (2026-10-23; the handle glyphs scaled to 0.8 had put ticks and edges between- pixels, grey and heavier than the text): 1 px lines on half pixels around the pixel (7, 7), the ink in rows and columns+ <!-- the pictures' handle glyphs (PreviewPane.xaml) as 16 px icons for the tree's rows and folders and the tree's toolbar+ (IconView Drawing="Source", "Probe", "Part"), drawn for the pixel grid (2026-10-23; the handle glyphs scaled to 0.8 had+ put ticks and edges between pixels, grey and heavier than the text): 1 px lines on half pixels around the pixel (7, 7), the ink in rows and columns0 to 14, an odd 15 so it centres in the 23 px toolbar buttons and tree rows as the text does; the probe's square is7 px, which weighs as much as the 9 px ring and leaves the corner free for the plus of an add button (IconPlusBadge) --><StreamGeometry x:Key="IconSource">M3.5,7.5 A4,4 0 1 1 11.5,7.5 A4,4 0 1 1 3.5,7.5 M7.5,0 V2 M7.5,13 V15 M0,7.5 H2 M13,7.5 H15</StreamGeometry>diff --git a/WaveDudeNext.WPF/Themes/Editors.xaml b/WaveDudeNext.WPF/Themes/Editors.xamlindex 9387721..32f082b 100644--- a/WaveDudeNext.WPF/Themes/Editors.xaml+++ b/WaveDudeNext.WPF/Themes/Editors.xaml@@ -584,6 +584,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<Setter Property="VerticalAlignment" Value="Center" /><Setter Property="TextTrimming" Value="CharacterEllipsis" /></Style>+ <!-- a read-only value beside its label (a lens's edge thickness, a gate's layout): bound to every input it depends on, so the text follows them -->+ <Style x:Key="FormReadout" TargetType="{x:Type TextBlock}">+ <Setter Property="VerticalAlignment" Value="Center" />+ </Style><!-- the chain between two number boxes that keeps them equal (a rectangle's or ellipse's width and length,2026-10-20, the user's request after the image editors): a toggle showing two linked rings, parted when off -->diff --git a/WaveDudeNext.WPF/Views/LensPartView.xaml b/WaveDudeNext.WPF/Views/LensPartView.xamlindex 5ebadfd..cf67287 100644--- a/WaveDudeNext.WPF/Views/LensPartView.xaml+++ b/WaveDudeNext.WPF/Views/LensPartView.xaml@@ -84,7 +84,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<!-- read-only: what the radii leave at the rim; 0 when the surfaces meet there --><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelEdgeThickness}" />- <TextBlock VerticalAlignment="Center" ToolTip="{DynamicResource TipEdgeThickness}" AutomationProperties.AutomationId="PartEdgeThickness">+ <TextBlock Style="{StaticResource FormReadout}" ToolTip="{DynamicResource TipEdgeThickness}" AutomationProperties.AutomationId="PartEdgeThickness"><TextBlock.Text><MultiBinding Converter="{StaticResource EdgeThickness}"><Binding Path="Diameter" />diff --git a/WaveDudeNext.WPF/Views/LogicGatePartView.xaml b/WaveDudeNext.WPF/Views/LogicGatePartView.xamlindex f0f409f..70c0f43 100644--- a/WaveDudeNext.WPF/Views/LogicGatePartView.xaml+++ b/WaveDudeNext.WPF/Views/LogicGatePartView.xaml@@ -30,10 +30,6 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<UserControl.Resources><converters:LogicGateLayoutConverter x:Key="Layout" /><converters:EnumNameConverter x:Key="EnumName" />- <!-- a read-only value beside its label; the layout values bind the gate plus every input they depend on, so the text follows them -->- <Style x:Key="LayoutText" TargetType="{x:Type TextBlock}">- <Setter Property="VerticalAlignment" Value="Center" />- </Style></UserControl.Resources><ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">@@ -47,7 +43,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<!-- read-only: the wavelength the frequency gives with the project's frequency scale --><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelWavelength}" />- <TextBlock Style="{StaticResource LayoutText}" ToolTip="{DynamicResource TipGateWavelength}" AutomationProperties.AutomationId="PartWavelength">+ <TextBlock Style="{StaticResource FormReadout}" ToolTip="{DynamicResource TipGateWavelength}" AutomationProperties.AutomationId="PartWavelength"><TextBlock.Text><MultiBinding Converter="{StaticResource Layout}" ConverterParameter="Wavelength"><Binding /><Binding Path="Wavelength" />@@ -75,7 +71,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<!-- read-only: the quarter-wave thickness for the core, the least reflecting band --><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelQuarterWave}" />- <TextBlock Style="{StaticResource LayoutText}" ToolTip="{DynamicResource TipQuarterWave}" AutomationProperties.AutomationId="PartQuarterWave">+ <TextBlock Style="{StaticResource FormReadout}" ToolTip="{DynamicResource TipQuarterWave}" AutomationProperties.AutomationId="PartQuarterWave"><TextBlock.Text><MultiBinding Converter="{StaticResource Layout}" ConverterParameter="QuarterWave"><Binding /><Binding Path="Wavelength" /><Binding Path="CoreIndex" /><Binding Path="CladdingIndex" /><Binding Path="PortSpacing" />@@ -117,7 +113,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<Label Style="{StaticResource FormSection}" Content="{DynamicResource SectionLayout}" /><controls:FormPanel ToolTip="{DynamicResource TipGateLayout}"><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelCoreWidth}" />- <TextBlock Style="{StaticResource LayoutText}" AutomationProperties.AutomationId="PartCoreWidth">+ <TextBlock Style="{StaticResource FormReadout}" AutomationProperties.AutomationId="PartCoreWidth"><TextBlock.Text><MultiBinding Converter="{StaticResource Layout}" ConverterParameter="CoreWidth"><Binding /><Binding Path="Wavelength" /><Binding Path="CoreIndex" /><Binding Path="CladdingIndex" /><Binding Path="PortSpacing" />@@ -126,7 +122,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</TextBlock><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelCouplerGap}" />- <TextBlock Style="{StaticResource LayoutText}" AutomationProperties.AutomationId="PartCouplerGap">+ <TextBlock Style="{StaticResource FormReadout}" AutomationProperties.AutomationId="PartCouplerGap"><TextBlock.Text><MultiBinding Converter="{StaticResource Layout}" ConverterParameter="Gap"><Binding /><Binding Path="Wavelength" /><Binding Path="CoreIndex" /><Binding Path="CladdingIndex" /><Binding Path="PortSpacing" />@@ -135,7 +131,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</TextBlock><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelCouplerLength}" />- <TextBlock Style="{StaticResource LayoutText}" AutomationProperties.AutomationId="PartCouplerLength">+ <TextBlock Style="{StaticResource FormReadout}" AutomationProperties.AutomationId="PartCouplerLength"><TextBlock.Text><MultiBinding Converter="{StaticResource Layout}" ConverterParameter="CouplerLength"><Binding /><Binding Path="Wavelength" /><Binding Path="CoreIndex" /><Binding Path="CladdingIndex" /><Binding Path="PortSpacing" />@@ -144,7 +140,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</TextBlock><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelGateLength}" />- <TextBlock Style="{StaticResource LayoutText}" AutomationProperties.AutomationId="PartGateLength">+ <TextBlock Style="{StaticResource FormReadout}" AutomationProperties.AutomationId="PartGateLength"><TextBlock.Text><MultiBinding Converter="{StaticResource Layout}" ConverterParameter="Length"><Binding /><Binding Path="Wavelength" /><Binding Path="CoreIndex" /><Binding Path="CladdingIndex" /><Binding Path="PortSpacing" />@@ -156,7 +152,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<Label Style="{StaticResource FormSection}" Content="{DynamicResource SectionPorts}" /><controls:FormPanel ToolTip="{DynamicResource TipGatePorts}"><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelInputA}" />- <TextBlock Style="{StaticResource LayoutText}" AutomationProperties.AutomationId="PartInputA">+ <TextBlock Style="{StaticResource FormReadout}" AutomationProperties.AutomationId="PartInputA"><TextBlock.Text><MultiBinding Converter="{StaticResource Layout}" ConverterParameter="InputA"><Binding /><Binding Path="X" /><Binding Path="Y" /><Binding Path="Angle" /><Binding Path="Wavelength" /><Binding Path="CoreIndex" /><Binding Path="CladdingIndex" /><Binding Path="PortSpacing" />@@ -165,7 +161,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</TextBlock><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelInputB}" />- <TextBlock Style="{StaticResource LayoutText}" AutomationProperties.AutomationId="PartInputB">+ <TextBlock Style="{StaticResource FormReadout}" AutomationProperties.AutomationId="PartInputB"><TextBlock.Text><MultiBinding Converter="{StaticResource Layout}" ConverterParameter="InputB"><Binding /><Binding Path="X" /><Binding Path="Y" /><Binding Path="Angle" /><Binding Path="Wavelength" /><Binding Path="CoreIndex" /><Binding Path="CladdingIndex" /><Binding Path="PortSpacing" />@@ -174,7 +170,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</TextBlock><TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:LogicGatePart.UpperOutputActive}" />- <TextBlock Style="{StaticResource LayoutText}" AutomationProperties.AutomationId="PartOutputUpper">+ <TextBlock Style="{StaticResource FormReadout}" AutomationProperties.AutomationId="PartOutputUpper"><TextBlock.Text><MultiBinding Converter="{StaticResource Layout}" ConverterParameter="OutputUpper"><Binding /><Binding Path="X" /><Binding Path="Y" /><Binding Path="Angle" /><Binding Path="Wavelength" /><Binding Path="CoreIndex" /><Binding Path="CladdingIndex" /><Binding Path="PortSpacing" />@@ -183,7 +179,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</TextBlock><TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:LogicGatePart.LowerOutputActive}" />- <TextBlock Style="{StaticResource LayoutText}" AutomationProperties.AutomationId="PartOutputLower">+ <TextBlock Style="{StaticResource FormReadout}" AutomationProperties.AutomationId="PartOutputLower"><TextBlock.Text><MultiBinding Converter="{StaticResource Layout}" ConverterParameter="OutputLower"><Binding /><Binding Path="X" /><Binding Path="Y" /><Binding Path="Angle" /><Binding Path="Wavelength" /><Binding Path="CoreIndex" /><Binding Path="CladdingIndex" /><Binding Path="PortSpacing" />diff --git a/WaveDudeNext.WPF/Views/PartCommonView.xaml b/WaveDudeNext.WPF/Views/PartCommonView.xamlindex 0d9c03a..2e46ff9 100644--- a/WaveDudeNext.WPF/Views/PartCommonView.xaml+++ b/WaveDudeNext.WPF/Views/PartCommonView.xaml@@ -32,7 +32,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" ToolTip="{meta:Hint model:OpticalPart.Name}" AutomationProperties.AutomationId="PartName" /><CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:OpticalPart.Enabled}"- IsChecked="{Binding Enabled}" ToolTip="{meta:Hint model:OpticalPart.Enabled}" />+ IsChecked="{Binding Enabled}" ToolTip="{meta:Hint model:OpticalPart.Enabled}" AutomationProperties.AutomationId="PartEnabled" /></controls:FormPanel><Label Style="{StaticResource FormSection}" Content="{DynamicResource SectionPosition}" />diff --git a/WaveDudeNext.WPF/Views/SourceView.xaml b/WaveDudeNext.WPF/Views/SourceView.xamlindex 0d74b8b..fc2d6da 100644--- a/WaveDudeNext.WPF/Views/SourceView.xaml+++ b/WaveDudeNext.WPF/Views/SourceView.xaml@@ -54,7 +54,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" ToolTip="{meta:Hint model:Source.Name}" /><CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:Source.Enabled}"- IsChecked="{Binding Enabled}" ToolTip="{meta:Hint model:Source.Enabled}" />+ IsChecked="{Binding Enabled}" ToolTip="{meta:Hint model:Source.Enabled}" AutomationProperties.AutomationId="SourceEnabled" /></controls:FormPanel><Label Style="{StaticResource FormSection}" Content="{DynamicResource SectionPosition}" />diff --git a/WaveDudeNext.WPF/Views/TrianglePartView.xaml b/WaveDudeNext.WPF/Views/TrianglePartView.xamlindex 816d7b5..8b8ea22 100644--- a/WaveDudeNext.WPF/Views/TrianglePartView.xaml+++ b/WaveDudeNext.WPF/Views/TrianglePartView.xaml@@ -72,7 +72,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<!-- read-only: what the two base angles leave for the apex --><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelApexAngle}" />- <TextBlock VerticalAlignment="Center" ToolTip="{DynamicResource TipApexAngle}" AutomationProperties.AutomationId="PartApexAngle">+ <TextBlock Style="{StaticResource FormReadout}" ToolTip="{DynamicResource TipApexAngle}" AutomationProperties.AutomationId="PartApexAngle"><TextBlock.Text><MultiBinding Converter="{StaticResource ApexAngle}"><Binding Path="Type" />diff --git a/WaveDudeNext.WPF/Views/ZonePlatePartView.xaml b/WaveDudeNext.WPF/Views/ZonePlatePartView.xamlindex cedc662..98e8367 100644--- a/WaveDudeNext.WPF/Views/ZonePlatePartView.xaml+++ b/WaveDudeNext.WPF/Views/ZonePlatePartView.xaml@@ -28,10 +28,6 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<UserControl.Resources><converters:ZonePlateConverter x:Key="Plate" />- <!-- a read-only value beside its label; it binds the plate plus every input it depends on, so the text follows them -->- <Style x:Key="ReadoutText" TargetType="{x:Type TextBlock}">- <Setter Property="VerticalAlignment" Value="Center" />- </Style></UserControl.Resources><ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">@@ -45,7 +41,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<!-- read-only: the wavelength the frequency gives with the project's frequency scale --><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelWavelength}" />- <TextBlock Style="{StaticResource ReadoutText}" ToolTip="{DynamicResource TipGateWavelength}" AutomationProperties.AutomationId="PartWavelength">+ <TextBlock Style="{StaticResource FormReadout}" ToolTip="{DynamicResource TipGateWavelength}" AutomationProperties.AutomationId="PartWavelength"><TextBlock.Text><MultiBinding Converter="{StaticResource Plate}" ConverterParameter="Wavelength"><Binding /><Binding Path="Wavelength" />@@ -82,7 +78,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<Label Style="{StaticResource FormSection}" Content="{DynamicResource SectionZones}" /><controls:FormPanel ToolTip="{DynamicResource TipZones}"><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelZoneCount}" />- <TextBlock Style="{StaticResource ReadoutText}" AutomationProperties.AutomationId="PartZoneCount">+ <TextBlock Style="{StaticResource FormReadout}" AutomationProperties.AutomationId="PartZoneCount"><TextBlock.Text><MultiBinding Converter="{StaticResource Plate}" ConverterParameter="Zones"><Binding /><Binding Path="ZoneCount" /><Binding Path="Diameter" /><Binding Path="FocalLength" />@@ -91,7 +87,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</TextBlock><TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelOuterZone}" />- <TextBlock Style="{StaticResource ReadoutText}" AutomationProperties.AutomationId="PartOuterZone">+ <TextBlock Style="{StaticResource FormReadout}" AutomationProperties.AutomationId="PartOuterZone"><TextBlock.Text><MultiBinding Converter="{StaticResource Plate}" ConverterParameter="OuterZone"><Binding /><Binding Path="ZoneCount" /><Binding Path="Diameter" /><Binding Path="FocalLength" />diff --git a/WaveDudeNext/Model/IMovable.cs b/WaveDudeNext/Model/IMovable.csindex ed43212..796bd09 100644--- a/WaveDudeNext/Model/IMovable.cs+++ b/WaveDudeNext/Model/IMovable.cs@@ -66,7 +66,7 @@ public static class Movable}/// <summary>- /// Moves every item by the same delta; nothing happens for a zero delta. The optical parts move last: a source on an+ /// Moves every item by the same delta; nothing happens for a zero delta. The optical parts move last: a source on a/// logic gate's input follows the gate by itself (<see cref="Parts.GatePortFollower"/>), so a source moved with the group/// must have left the old port before the gate moves, or it would be moved twice./// </summary>diff --git a/WaveDudeNext/Model/INamed.cs b/WaveDudeNext/Model/INamed.csnew file mode 100644index 0000000..b4f7cde--- /dev/null+++ b/WaveDudeNext/Model/INamed.cs@@ -0,0 +1,29 @@+// 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/>.++namespace WaveDudeNext.Model;++/// <summary>+/// A project object with a name of its own: the items of the project's lists (a source, a part, a probe, a colour scheme),+/// which the tree shows by name, Paste renames on a clash and an undo step finds again by name. A name is unique within+/// its list, compared without case.+/// </summary>+public interface INamed+{+ /// <summary>The name, unique within the object's list.</summary>+ string Name { get; set; }+}diff --git a/WaveDudeNext/Model/OpticalPart.cs b/WaveDudeNext/Model/OpticalPart.csindex 19a9d1f..3eea211 100644--- a/WaveDudeNext/Model/OpticalPart.cs+++ b/WaveDudeNext/Model/OpticalPart.cs@@ -34,7 +34,7 @@ namespace WaveDudeNext.Model;/// convention). Refractive indices run from 1.00 to 2.55 in steps of 0.01 (red = index × 100). The class is the kind,/// chosen when the part is added (<see cref="Project.AddPart(Type)"/>) and never changed./// </summary>-public abstract class OpticalPart : ObservableObject, IMovable+public abstract class OpticalPart : ObservableObject, IMovable, INamed{/// <summary>Smallest refractive index a part can have.</summary>public const double MinIndex = 1.0;@@ -2184,13 +2184,6 @@ public abstract class LogicGatePart : OpticalPart, IFrequencyDesignedset => SetProperty(ref _lowerOutputActive, value);}- /// <summary>Tells the form that the values derived from the design follow an edit of a design input.</summary>- private void OnDesignChanged()- {- OnPropertyChanged(nameof(Wavelength));- OnPropertyChanged(nameof(PortSpacingUsed));- }-/// <summary>Refractive index of the waveguide cores, 1.00 to 2.55; above the cladding's for guiding.</summary>[XmlAttribute][DefaultValue(DefaultCoreIndex)]@@ -2261,6 +2254,13 @@ public abstract class LogicGatePart : OpticalPart, IFrequencyDesignedset => PortSpacing = value;}+ /// <summary>Tells the form that the values derived from the design follow an edit of a design input.</summary>+ private void OnDesignChanged()+ {+ OnPropertyChanged(nameof(Wavelength));+ OnPropertyChanged(nameof(PortSpacingUsed));+ }+/// <summary>The layout for the current values (guarded as the painter guards them), or null when the cores guide nothing. Any thread; cached.</summary>[XmlIgnore][Browsable(false)]@@ -2418,6 +2418,9 @@ public sealed class ZonePlatePart : OpticalPart, IFrequencyDesigned/// </summary>public const int BlockAbsorption = 96;+ /// <summary>Default <see cref="MountWidth"/> in pixels.</summary>+ public const int DefaultMountWidth = 200;+private int _diameter = DefaultDiameter;private int _thickness = DefaultThickness;private int _coating = DefaultCoating;@@ -2428,9 +2431,6 @@ public sealed class ZonePlatePart : OpticalPart, IFrequencyDesignedprivate bool _mount;private int _mountWidth = DefaultMountWidth;- /// <summary>Default <see cref="MountWidth"/> in pixels.</summary>- public const int DefaultMountWidth = 200;-/// <inheritdoc/>public override string NameStem => "Zone plate";diff --git a/WaveDudeNext/Model/Probe.cs b/WaveDudeNext/Model/Probe.csindex 9aa089f..7d892e3 100644--- a/WaveDudeNext/Model/Probe.cs+++ b/WaveDudeNext/Model/Probe.cs@@ -90,7 +90,7 @@ public enum ProbeValueScale/// A measurement point or line on the canvas and the graph that shows its values. Positions are/// canvas pixels with the origin at the top left./// </summary>-public sealed class Probe : ObservableObject, IMovable+public sealed class Probe : ObservableObject, IMovable, INamed{/// <summary>Default <see cref="Window"/> in steps.</summary>public const int DefaultWindow = 500;diff --git a/WaveDudeNext/Model/Project.cs b/WaveDudeNext/Model/Project.csindex dbf2759..0100565 100644--- a/WaveDudeNext/Model/Project.cs+++ b/WaveDudeNext/Model/Project.cs@@ -58,7 +58,8 @@ public sealed class Project : ObservableObjectprivate static readonly ILogger Logger = LogManager.GetCurrentClassLogger();private static readonly XmlSerializer Serializer = new(typeof(Project));- private static readonly XmlSerializerNamespaces NoNamespaces = new([XmlQualifiedName.Empty]);+ /// <summary>No namespace declarations on the root: the file as it is written, and the history's snapshots of it.</summary>+ internal static readonly XmlSerializerNamespaces NoNamespaces = new([XmlQualifiedName.Empty]);private static readonly XmlWriterSettings WriterSettings = new(){Indent = true,diff --git a/WaveDudeNext/Model/ProjectClipboard.cs b/WaveDudeNext/Model/ProjectClipboard.csindex 0ed0b92..8e0e9e1 100644--- a/WaveDudeNext/Model/ProjectClipboard.cs+++ b/WaveDudeNext/Model/ProjectClipboard.cs@@ -56,7 +56,7 @@ public static class ProjectClipboard/// <summary>Whether <paramref name="item"/> of <paramref name="project"/> can be copied: a list item or a settings object.</summary>public static bool CanCopy(Project project, object item) =>- item is Source or OpticalPart or Probe or ColorScheme || SettingsObjects.Any(entry => ReferenceEquals(entry.Get(project), item));+ item is INamed || SettingsObjects.Any(entry => ReferenceEquals(entry.Get(project), item));/// <summary>The clipboard text for <paramref name="items"/> of <paramref name="project"/>: their elements in tree order; items that cannot be copied are left out.</summary>public static string Write(Project project, IEnumerable<object> items)@@ -123,10 +123,10 @@ public static class ProjectClipboardpasted.Add(value);}}- Insert(project.Sources, clip.Objects.OfType<Source>(), current, before, source => source.Name, (source, name) => source.Name = name, pasted);- Insert(project.Parts, clip.Objects.OfType<OpticalPart>(), current, before, part => part.Name, (part, name) => part.Name = name, pasted);- Insert(project.Probes, clip.Objects.OfType<Probe>(), current, before, probe => probe.Name, (probe, name) => probe.Name = name, pasted);- Insert(project.ColorSchemes, clip.Objects.OfType<ColorScheme>(), current, before, scheme => scheme.Name, (scheme, name) => scheme.Name = name, pasted);+ Insert(project.Sources, clip.Objects.OfType<Source>(), current, before, pasted);+ Insert(project.Parts, clip.Objects.OfType<OpticalPart>(), current, before, pasted);+ Insert(project.Probes, clip.Objects.OfType<Probe>(), current, before, pasted);+ Insert(project.ColorSchemes, clip.Objects.OfType<ColorScheme>(), current, before, pasted);foreach (Source source in pasted.OfType<Source>()){// the emitters follow the seed of the project they are in now@@ -153,16 +153,16 @@ public static class ProjectClipboardMovable.MoveAll(movables, dx, dy);}- private static void Insert<T>(IList<T> list, IEnumerable<T> items, object? current, bool before, Func<T, string> nameOf, Action<T, string> rename, List<object> pasted)- where T : class+ /// <summary>Puts <paramref name="items"/> into <paramref name="list"/> behind (or before) <paramref name="current"/> when that is one of its items, else at its end, renamed where the name is taken.</summary>+ private static void Insert<T>(IList<T> list, IEnumerable<T> items, object? current, bool before, List<object> pasted)+ where T : class, INamed{int at = current is T anchor && list.IndexOf(anchor) is >= 0 and var index ? (before ? index : index + 1) : list.Count;foreach (T item in items){- string name = nameOf(item);- if (list.Any(other => string.Equals(nameOf(other), name, StringComparison.OrdinalIgnoreCase)))+ if (list.Any(other => string.Equals(other.Name, item.Name, StringComparison.OrdinalIgnoreCase))){- rename(item, Project.CopyName(name, list.Select(nameOf)));+ item.Name = Project.CopyName(item.Name, list.Select(other => other.Name));}list.Insert(at++, item);pasted.Add(item);@@ -220,7 +220,7 @@ public static class ProjectClipboardpublic sealed record Clip(IReadOnlyList<object> Objects){/// <summary>Whether the clip holds list items (sources, parts, probes, schemes).</summary>- public bool HasItems => Objects.Any(item => item is Source or OpticalPart or Probe or ColorScheme);+ public bool HasItems => Objects.Any(item => item is INamed);/// <summary>Whether the clip can be pasted with <paramref name="current"/> the project's current item: it has list items, or a settings object of the current row's kind, or of any kind onto the project root.</summary>public bool CanPaste(Project project, object? current) =>diff --git a/WaveDudeNext/Model/ProjectHistory.cs b/WaveDudeNext/Model/ProjectHistory.csindex feec85f..30fe4e1 100644--- a/WaveDudeNext/Model/ProjectHistory.cs+++ b/WaveDudeNext/Model/ProjectHistory.cs@@ -120,7 +120,7 @@ public sealed class ProjectHistoryvar text = new StringWriter();using (var writer = XmlWriter.Create(text, new XmlWriterSettings { Indent = false })){- Serializer.Serialize(writer, _project);+ Serializer.Serialize(writer, _project, Project.NoNamespaces);}byte[]? image = _project.Scene.ImageData;if (image != null && previous != null && !ReferenceEquals(image, previous) && image.AsSpan().SequenceEqual(previous))@@ -150,6 +150,7 @@ public sealed class ProjectHistoryif (value is IList items && property.GetValue(_project) is IList target){object[] moved = [.. items.Cast<object>()];+ // the throw-away project lets go of them first (it follows its schemes' renames, as the real one will)items.Clear();target.Clear();foreach (object item in moved)@@ -171,13 +172,10 @@ public sealed class ProjectHistoryreturn new XmlSerializer(typeof(Project), overrides);}- /// <summary>One step: the project's XML without the scene image, and the image's bytes (shared between steps while unchanged).</summary>- private sealed record Snapshot(string Xml, byte[]? Image)- {- /// <summary>Equal when the XML is and the image is the same array (equal bytes were made the same array by <see cref="Capture"/>).</summary>- public bool Equals(Snapshot? other) => other != null && ReferenceEquals(Image, other.Image) && Xml == other.Xml;-- /// <inheritdoc/>- public override int GetHashCode() => Xml.GetHashCode();- }+ /// <summary>+ /// One step: the project's XML without the scene image, and the image's bytes (shared between steps while unchanged).+ /// Two steps are equal when the XML is and the image is the same array (the record's own equality; equal bytes were+ /// made the same array by <see cref="Capture"/>).+ /// </summary>+ private sealed record Snapshot(string Xml, byte[]? Image);}diff --git a/WaveDudeNext/Model/Source.cs b/WaveDudeNext/Model/Source.csindex b4aef41..6fa256c 100644--- a/WaveDudeNext/Model/Source.cs+++ b/WaveDudeNext/Model/Source.cs@@ -46,7 +46,7 @@ public enum PulseShape/// remnant of the 8-bit image channel; above 255 the grid cannot sample the wave), amplitude in percent, phase in/// degrees with decimals, widths in cycles of the source frequency, detach time in simulation steps./// </summary>-public sealed class Source : ObservableObject, IMovable+public sealed class Source : ObservableObject, IMovable, INamed{/// <summary>Smallest frequency level: just above 0, a wave of any length.</summary>public const double MinLevel = 0.01;diff --git a/WaveDudeNext/Parts/GatePortFollower.cs b/WaveDudeNext/Parts/GatePortFollower.csindex 8a57c99..5300a08 100644--- a/WaveDudeNext/Parts/GatePortFollower.cs+++ b/WaveDudeNext/Parts/GatePortFollower.cs@@ -89,29 +89,27 @@ public sealed class GatePortFollower : IDisposable_parts.CollectionChanged += OnPartsChanged;_simulation = _project.Simulation;_simulation.PropertyChanged += OnSimulationChanged;+ double scale = _simulation.SourceFrequencyScale;foreach (LogicGatePart gate in _project.Parts.OfType<LogicGatePart>()){- if (!_inputs.ContainsKey(gate))+ gate.PropertyChanged += OnGateChanged;+ if (known.TryGetValue(gate, out (int X, int Y)[]? ports)){- // a gate seen before keeps its remembered ports, so its sources follow the scale handed over now; a new one starts at it- if (known.TryGetValue(gate, out (int X, int Y)[]? ports))- {- _inputs[gate] = ports;- gate.PropertyChanged += OnGateChanged;- gate.FrequencyScale = _project.Simulation.SourceFrequencyScale;- }- else- {- gate.FrequencyScale = _project.Simulation.SourceFrequencyScale;- _inputs[gate] = Inputs(gate);- gate.PropertyChanged += OnGateChanged;- }+ // a gate seen before keeps its remembered ports, so its sources follow the scale handed over now+ _inputs[gate] = ports;+ gate.FrequencyScale = scale;+ }+ else+ {+ // a new one starts at the ports it has at that scale (the change handler does nothing without remembered ports)+ gate.FrequencyScale = scale;+ _inputs[gate] = Inputs(gate);}}// the other parts laid out for a frequency (a zone plate) have no ports to follow, only the scaleforeach (IFrequencyDesigned part in _project.Parts.OfType<IFrequencyDesigned>().Where(part => part is not LogicGatePart)){- part.FrequencyScale = _project.Simulation.SourceFrequencyScale;+ part.FrequencyScale = scale;}}diff --git a/WaveDudeNext/Rendering/BrightnessFit.cs b/WaveDudeNext/Rendering/BrightnessFit.csindex 6aade09..99c2054 100644--- a/WaveDudeNext/Rendering/BrightnessFit.cs+++ b/WaveDudeNext/Rendering/BrightnessFit.cs@@ -20,7 +20,7 @@ namespace WaveDudeNext.Rendering;/// <summary>/// The display brightness that fits a frame (the preview's Auto, 2026-10-20, Jeroen's point 9): the gain that brings/// the <see cref="Percentile"/> of the coloured magnitude to the top of the palette, |value| for the field and the-/// square root for the intensity (stored as such in the preview; the renderer's own mappings, see <see cref="ColorLut"/>), so the brightest half percent+/// square root for the intensity (which the preview stores and the renderer colours, see <see cref="ColorLut"/>), so the brightest half percent/// saturates and a source cell, far above the field around it, does not darken the picture. Pure arithmetic; any/// thread./// </summary>diff --git a/WaveDudeNext/Rendering/ColorLut.cs b/WaveDudeNext/Rendering/ColorLut.csindex 85c9f78..77f73d5 100644--- a/WaveDudeNext/Rendering/ColorLut.cs+++ b/WaveDudeNext/Rendering/ColorLut.cs@@ -18,13 +18,13 @@namespace WaveDudeNext.Rendering;/// <summary>-/// The colours a renderer takes from a <see cref="ColorScheme"/>'s gradient, with the display options of the Python-/// function <c>get_colormap_lut</c> (invert, black level, make symmetric) applied, for the two kinds of stored frame-/// (2026-10-23, the user's design: the scheme is the gradient, how many colours are taken from it is the renderer's-/// business):+/// The colours a renderer takes from a <see cref="ColorScheme"/>'s gradient through the black level of the Python+/// function <c>get_colormap_lut</c> (its invert, make symmetric and reverse options were carried unused until+/// 2026-10-23), for the two kinds of stored frame (2026-10-23, the user's design: the scheme is the gradient, how many+/// colours are taken from it is the renderer's business):/// <list type="bullet">/// <item>a frame of 8-bit palette indices: <see cref="Argb"/>, <see cref="Size"/> colours at i / 254 like the author's-/// table, looked up by the byte the capture computed (<see cref="FieldIndex"/>, <see cref="IntensityIndex(float, float)"/>,+/// table, looked up by the byte the capture computed (<see cref="FieldIndex"/>, <see cref="IntensityRootIndex"/>,/// the GPU's <c>capture_index</c>), channels truncated like the Python code;</item>/// <item>a frame of 16-bit samples: <see cref="HalfTable"/>, a colour for each of the 65,536 values a half can hold, the/// gradient evaluated at that value's own position and rounded to the nearest level, so a picture has every level the@@ -41,26 +41,23 @@ public sealed class ColorLut/// <summary>Number of values a 16-bit sample can hold: the length of a <see cref="HalfTable"/>.</summary>public const int HalfValues = 1 << 16;+ /// <summary>The sample kinds a table is kept for.</summary>+ private static readonly int Kinds = Enum.GetValues<SampleKind>().Length;+private readonly List<ColorStop> _stops;- private readonly bool _invert;private readonly double _blackLevel;- private readonly bool _makeSymmetric;- private readonly bool _reverse;/// <summary>The half tables built, one per <see cref="SampleKind"/>.</summary>- private readonly TableEntry<int>?[] _tables = new TableEntry<int>?[3];+ private readonly TableEntry<int>?[] _tables = new TableEntry<int>?[Kinds];/// <summary>The 16-bit half tables built, one per <see cref="SampleKind"/>.</summary>- private readonly TableEntry<ulong>?[] _deepTables = new TableEntry<ulong>?[3];+ private readonly TableEntry<ulong>?[] _deepTables = new TableEntry<ulong>?[Kinds];/// <summary>A built half table and the brightness it was built for.</summary>private sealed record TableEntry<T>(float Brightness, T[] Table);- private ColorLut(List<ColorStop> stops, bool invert, double blackLevel, bool makeSymmetric, bool reverse)+ private ColorLut(List<ColorStop> stops, double blackLevel){_stops = stops;- _invert = invert;_blackLevel = blackLevel;- _makeSymmetric = makeSymmetric;- _reverse = reverse;Argb = BuildPalette();}@@ -70,67 +67,30 @@ public sealed class ColorLut/// </summary>public int[] Argb { get; }- /// <summary>Returns palette entry <paramref name="index"/> (0..<see cref="Size"/>-1) as a colour.</summary>- public Rgb ColorAt(int index) => Rgb.FromArgb(Argb[index]);-/// <summary>/// The grey levels the Python code shows without a colour table: palette entry i is the level i, 0..254, and a/// 16-bit sample the same ramp at its own position. Used when a layer's scheme cannot be found./// </summary>- public static ColorLut Grey { get; } = new([new ColorStop(0.0, new Rgb(0, 0, 0)), new ColorStop(1.0, new Rgb(254, 254, 254))], false, 0.0, false, false);+ public static ColorLut Grey { get; } = new([new ColorStop(0.0, new Rgb(0, 0, 0)), new ColorStop(1.0, new Rgb(254, 254, 254))], 0.0);/// <summary>- /// The colours of <paramref name="scheme"/>'s gradient with the display options, applied in the Python order:- /// <paramref name="reverse"/> (new, optional; the gradient read from the far end), <paramref name="invert"/>- /// (each channel becomes <c>1 - channel</c>), <paramref name="makeSymmetric"/> (the gradient squeezed into each half- /// and mirrored, palette entry i read from entry <c>2 * min(i, Size-1-i)</c>), then <paramref name="blackLevel"/>,- /// which maps every channel linearly as <c>c * (1 - b) + b</c>, so 0 becomes <paramref name="blackLevel"/> and 1- /// stays 1. The palette's channels are converted to 8 bit by truncation, like the Python code; alpha is always 255.- /// UI thread (the scheme's stops are copied).+ /// The colours of <paramref name="scheme"/>'s gradient through <paramref name="blackLevel"/>, which maps every channel+ /// linearly as <c>c * (1 - b) + b</c>, so 0 becomes <paramref name="blackLevel"/> and 1 stays 1. The palette's+ /// channels are converted to 8 bit by truncation, like the Python code; alpha is always 255. UI thread (the scheme's+ /// stops are copied)./// </summary>/// <param name="scheme">The gradient.</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>- public static ColorLut Build(ColorScheme scheme, bool invert = false, double blackLevel = 0.0, bool makeSymmetric = false, bool reverse = false) =>- new(scheme.SortedStops(), invert, blackLevel, makeSymmetric, reverse);+ public static ColorLut Build(ColorScheme scheme, double blackLevel = 0.0) => new(scheme.SortedStops(), blackLevel);- /// <summary>The 8-bit palette: the author's table of the gradient (<see cref="ColorScheme.Interpolate"/>, 255 entries at i / 254) through the display options.</summary>+ /// <summary>The 8-bit palette: the author's table of the gradient (<see cref="ColorScheme.Interpolate"/>, 255 entries at i / 254) through the black level, each channel truncated.</summary>private int[] BuildPalette(){Rgb[] table = ColorScheme.Interpolate(_stops, Size);- double[,] rgb = new double[Size, 3];- for (int i = 0; i < Size; i++)- {- Rgb entry = table[_reverse ? (Size - 1 - i) : i];- rgb[i, 0] = entry.R / 255.0;- rgb[i, 1] = entry.G / 255.0;- rgb[i, 2] = entry.B / 255.0;- }- if (_invert)- {- for (int i = 0; i < Size; i++)- {- for (int channel = 0; channel < 3; channel++)- {- rgb[i, channel] = 1.0 - rgb[i, channel];- }- }- }- int[] argb = new int[Size];+ var 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 = _makeSymmetric ? 2 * Math.Min(i, Size - 1 - i) : i;- int[] components = new int[3];- for (int channel = 0; channel < 3; channel++)- {- double level = Math.Clamp(rgb[sourceIndex, channel] * (1.0 - _blackLevel) + _blackLevel, 0.0, 1.0);- components[channel] = Math.Min(255, (int)(level * 255.0));- }- argb[i] = new Rgb((byte)components[0], (byte)components[1], (byte)components[2]).ToArgb();+ argb[i] = new Rgb((byte)(Level(table[i].R) * 255.0), (byte)(Level(table[i].G) * 255.0), (byte)(Level(table[i].B) * 255.0)).ToArgb();}return argb;}@@ -140,13 +100,13 @@ public sealed class ColorLut/// the value's position on the gradient by the sample kind's mapping at <paramref name="brightness"/>, the continuous/// forms of the palette indices (the field <c>(clamp(value · brightness, −1, 1) + 1) / 2</c>, a zero field and NaN in/// the middle; the intensity <c>min(√value · brightness, 1)</c>, its stored square root <c>min(value · brightness, 1)</c>,- /// both 0 for NaN and for values not above zero), the gradient evaluated there through the display options, each+ /// both 0 for NaN and for values not above zero), the gradient evaluated there through the black level, each/// channel rounded to the nearest level. Kept per kind until a call with another brightness; built on the calling/// thread (65,536 evaluations, spread over the pool). Any thread: two threads asking at once may both build it, to the/// same colours. The array must not be modified./// </summary>/// <param name="kind">What the samples are: the signed field, the intensity, or its square root.</param>- /// <param name="brightness">The layer's gain, applied as in <see cref="FieldIndex"/> and <see cref="IntensityIndex(float, float)"/>.</param>+ /// <param name="brightness">The layer's gain, applied as in <see cref="FieldIndex"/> and <see cref="IntensityRootIndex"/>.</param>public int[] HalfTable(SampleKind kind, float brightness) =>Cached(ref _tables[(int)kind], kind, brightness,(r, g, b) => unchecked((int)0xFF000000) | (Round(r * 255.0) << 16) | (Round(g * 255.0) << 8) | Round(b * 255.0));@@ -203,31 +163,15 @@ public sealed class ColorLutprivate static double IntensityPosition(double root, float brightness) =>root > 0.0 ? Math.Clamp(root * brightness, 0.0, 1.0) : 0.0;- /// <summary>The gradient at a position through the display options (the order of <see cref="Build"/>): each channel 0..1, unrounded.</summary>+ /// <summary>The gradient at a position through the black level: each channel 0..1, unrounded.</summary>private (double R, double G, double B) LevelsAt(double position){- if (_makeSymmetric)- {- position = 2.0 * Math.Min(position, 1.0 - position);- }- if (_reverse)- {- position = 1.0 - position;- }(double r, double g, double b) = ColorScheme.Evaluate(_stops, position);return (Level(r), Level(g), Level(b));}- /// <summary>One channel (0..255, unrounded) through invert and black level, as a fraction 0..1.</summary>- private double Level(double channel)- {- double level = channel / 255.0;- if (_invert)- {- level = 1.0 - level;- }- return Math.Clamp(level * (1.0 - _blackLevel) + _blackLevel, 0.0, 1.0);- }+ /// <summary>One channel (0..255, unrounded) through the black level, as a fraction 0..1.</summary>+ private double Level(double channel) => Math.Clamp(channel / 255.0 * (1.0 - _blackLevel) + _blackLevel, 0.0, 1.0);/// <summary>/// Maps a signed field sample to a palette index, like <c>render_field</c>:@@ -259,8 +203,9 @@ public sealed class ColorLutroot > 0f ? (int)(MathF.Min(root * brightness, 1f) * 254f) : 0;/// <summary>- /// The square-root case of <see cref="IntensityIndex(float, float, float)"/>: <c>min(sqrt(intensity) · brightness, 1) · 254</c>,- /// 0 for NaN or a non-positive intensity; the index of a frame whose 16-bit intensity is I itself (<see cref="Engine.FrameShape.IntensityRoot"/>).+ /// The palette index of an intensity, like <c>render_intensity</c>: <c>min(sqrt(intensity) · brightness, 1) · 254</c>,+ /// 0 for NaN or a non-positive intensity. The index of a frame whose 16-bit intensity plane holds the intensity itself;+ /// the preview's plane holds its square root and takes <see cref="IntensityRootIndex"/> (<see cref="Engine.FrameShape.IntensityRoot"/>)./// </summary>/// <param name="intensity">Accumulated intensity from the engine.</param>/// <param name="brightness">Gain applied after the square root.</param>@@ -274,26 +219,4 @@ public sealed class ColorLut// double arithmetic before differed in the last bit at mostreturn (int)(MathF.Min(MathF.Sqrt(intensity) * brightness, 1f) * 254f);}-- /// <summary>- /// 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. The captures use the square-root case, <see cref="IntensityIndex(float, float)"/>.- /// </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) is the Python default.</param>- public static int IntensityIndex(float intensity, float brightness, float exponent = 0.5f)- {- if (float.IsNaN(intensity) || intensity <= 0f)- {- return 0;- }- double scaled = Math.Pow(intensity, exponent) * brightness;- if (double.IsNaN(scaled) || scaled < 0.0)- {- return 0;- }- return (int)(Math.Min(scaled, 1.0) * 254.0);- }}diff --git a/WaveDudeNext/Rendering/ColorScheme.cs b/WaveDudeNext/Rendering/ColorScheme.csindex 07a6a52..47212a8 100644--- a/WaveDudeNext/Rendering/ColorScheme.cs+++ b/WaveDudeNext/Rendering/ColorScheme.cs@@ -105,7 +105,7 @@ public sealed class ColorStop : ObservableObject/// a stop's edit raises <c>Stops</c> on the scheme. UI thread; a renderer works on a copy (<see cref="SortedStops"/>)./// </summary>[XmlRoot("ColorScheme")]-public sealed class ColorScheme : ObservableObject+public sealed class ColorScheme : ObservableObject, INamed{/// <summary>Number of stops of the author's editable gradient: nine, evenly spaced.</summary>public const int StopCount = 9;@@ -386,20 +386,6 @@ public sealed class ColorScheme : ObservableObjectreturn copy;}- /// <summary>A scheme of exactly <see cref="StopCount"/> evenly spaced stops (the author's editor form).</summary>- /// <exception cref="ArgumentException">Not <see cref="StopCount"/> colours.</exception>- public static ColorScheme FromStops(string schemeName, IReadOnlyList<Rgb> stops)- {- if (stops.Count != StopCount)- {- throw new ArgumentException("Exactly " + StopCount.ToString(CultureInfo.InvariantCulture) + " stops are required.");- }- return new ColorScheme(schemeName, stops)- {- Description = StopCount.ToString(CultureInfo.InvariantCulture) + "-stop gradient made in the color scheme editor",- };- }-/// <summary>Nine colours from black to white, the default of a new scheme and the gradient of one without stops.</summary>public static Rgb[] Grey(){diff --git a/WaveDudeNext/Rendering/ColorSchemeStore.cs b/WaveDudeNext/Rendering/ColorSchemeStore.csindex 94bac0a..d492597 100644--- a/WaveDudeNext/Rendering/ColorSchemeStore.cs+++ b/WaveDudeNext/Rendering/ColorSchemeStore.cs@@ -51,8 +51,8 @@ public static class ColorSchemeStore/// <summary>Prefix of the embedded scheme resources (see the csproj's <c>LogicalName</c>).</summary>private const string ResourcePrefix = "ColorSchemes/";- /// <summary>Entries of the author's JSON table ("entry_count"): his palette of 255 colours, the part his program reads.</summary>- private const int AuthorEntryCount = 255;+ /// <summary>Entries of the author's JSON table ("entry_count"): his palette of 255 colours (<see cref="ColorLut.Size"/>), the part his program reads.</summary>+ private const int AuthorEntryCount = ColorLut.Size;private static readonly XmlSerializer Serializer = new(typeof(ColorScheme));private static readonly XmlSerializerNamespaces NoNamespaces = new([XmlQualifiedName.Empty]);diff --git a/WaveDudeNext/Rendering/FrameRenderer.cs b/WaveDudeNext/Rendering/FrameRenderer.csindex 328653b..abb8063 100644--- a/WaveDudeNext/Rendering/FrameRenderer.cs+++ b/WaveDudeNext/Rendering/FrameRenderer.cs@@ -77,13 +77,15 @@ public static class FrameRendererpublic static void RenderIndexed(ReadOnlyMemory<byte> indices, int width, int height, ColorLut lut, Memory<int> pixels){int[] palette = lut.Argb;- Parallel.For(0, height, y =>+ Parallel.ForEach(Blocks(height), block =>{- ReadOnlySpan<byte> row = indices.Span.Slice(y * width, width);- Span<int> target = pixels.Span.Slice(y * width, width);- for (int x = 0; x < width; x++)+ int start = block.Item1 * width;+ int count = (block.Item2 - block.Item1) * width;+ ReadOnlySpan<byte> source = indices.Span.Slice(start, count);+ Span<int> target = pixels.Span.Slice(start, count);+ for (int i = 0; i < source.Length; i++){- target[x] = palette[Math.Min((int)row[x], ColorLut.Size - 1)];+ target[i] = palette[Math.Min((int)source[i], ColorLut.Size - 1)];}});}diff --git a/WaveDudeNext/Rendering/ScreenRenderer.cs b/WaveDudeNext/Rendering/ScreenRenderer.csindex 9e4e03f..5ab4bbe 100644--- a/WaveDudeNext/Rendering/ScreenRenderer.cs+++ b/WaveDudeNext/Rendering/ScreenRenderer.cs@@ -113,7 +113,8 @@ public sealed class ResampleAxis/// the samples are resampled in value space first (<see cref="ResampleAxis"/>, rows then columns; the intensity's square/// root as energy), so every screen pixel shows a value the field or intensity has there, in a colour of the/// gradient; the value is looked up in the layer's-/// half table and, with dithering, rounded to 8 bits per channel through a Bayer matrix fixed to the screen pixels. Only+/// half table and, with dithering, rounded to 8 bits per channel through a Bayer matrix fixed to the picture's pixels (on+/// the screen's, since the window's layout rounding puts the picture on whole pixels). Only/// for the screen: a dithered picture cannot be scaled again, and an export never is one. One instance per picture and/// size, holding the axes and the rows between the passes; one render at a time, on any thread, the rows of each pass/// in parallel blocks.diff --git a/WaveDudeNext/Runs/IFrameSource.cs b/WaveDudeNext/Runs/IFrameSource.csindex 3dadf4b..fc320a2 100644--- a/WaveDudeNext/Runs/IFrameSource.cs+++ b/WaveDudeNext/Runs/IFrameSource.cs@@ -30,23 +30,26 @@ namespace WaveDudeNext.Runs;/// </summary>public interface IFrameSource{+ /// <summary>The frames' geometry and format; the properties below read it.</summary>+ FrameShape Shape { get; }+/// <summary>Frame width in samples.</summary>- int Width { get; }+ int Width => Shape.Width;/// <summary>Frame height in samples.</summary>- int Height { get; }+ int Height => Shape.Height;/// <summary>Width of the simulated canvas the frames were shrunk from, in cells; equals <see cref="Width"/> at full resolution.</summary>- int CanvasWidth { get; }+ int CanvasWidth => Shape.CanvasWidth;/// <summary>Height of the simulated canvas, in cells.</summary>- int CanvasHeight { get; }+ int CanvasHeight => Shape.CanvasHeight;/// <summary>The sample format of every plane.</summary>- FrameFormat Format { get; }+ FrameFormat Format => Shape.Format;/// <summary>Whether a <see cref="FrameFormat.Half"/> intensity plane holds the intensity's square root, the preview's, rather than the intensity (<see cref="FrameShape.IntensityRoot"/>).</summary>- bool IntensityRoot { get; }+ bool IntensityRoot => Shape.IntensityRoot;/// <summary>Frames available: indices 0..Count-1 may be read.</summary>int Count { get; }@@ -77,22 +80,7 @@ public sealed class SnapshotFrameSource(FrameSnapshot snapshot) : IFrameSourcepublic FrameSnapshot Snapshot { get; } = snapshot;/// <inheritdoc/>- public int Width => Snapshot.Width;-- /// <inheritdoc/>- public int Height => Snapshot.Height;-- /// <inheritdoc/>- public int CanvasWidth => Snapshot.Shape.CanvasWidth;-- /// <inheritdoc/>- public int CanvasHeight => Snapshot.Shape.CanvasHeight;-- /// <inheritdoc/>- public FrameFormat Format => Snapshot.Shape.Format;-- /// <inheritdoc/>- public bool IntensityRoot => Snapshot.Shape.IntensityRoot;+ public FrameShape Shape => Snapshot.Shape;/// <inheritdoc/>public int Count => 1;@@ -115,7 +103,7 @@ public sealed class SnapshotFrameSource(FrameSnapshot snapshot) : IFrameSource/// <inheritdoc/>public bool CopyLayer(int frame, FrameLayer layer, Span<Half> destination){- if (Format != FrameFormat.Half)+ if (Shape.Format != FrameFormat.Half){throw new InvalidOperationException("The snapshot's samples are palette indices, not halves.");}diff --git a/WaveDudeNext/Runs/StridedFrameSource.cs b/WaveDudeNext/Runs/StridedFrameSource.csindex b3f66a6..2ee1e61 100644--- a/WaveDudeNext/Runs/StridedFrameSource.cs+++ b/WaveDudeNext/Runs/StridedFrameSource.cs@@ -37,22 +37,7 @@ public sealed class StridedFrameSource(FrameStore store, int stride, int frameCopublic int Stride { get; } = Math.Max(1, stride);/// <inheritdoc/>- public int Width => Store.Width;-- /// <inheritdoc/>- public int Height => Store.Height;-- /// <inheritdoc/>- public int CanvasWidth => Store.CanvasWidth;-- /// <inheritdoc/>- public int CanvasHeight => Store.CanvasHeight;-- /// <inheritdoc/>- public FrameFormat Format => Store.Format;-- /// <inheritdoc/>- public bool IntensityRoot => Store.IntensityRoot;+ public FrameShape Shape => Store.Shape;/// <summary>Timeline frames that can be shown: every stored frame covers <see cref="Stride"/> of them, never beyond the run's frame count.</summary>public int Count => (int)Math.Min((long)Store.Count * Stride, frameCount);diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.csindex f61e47a..8757e4d 100644--- a/_tools/library_check/Program.cs+++ b/_tools/library_check/Program.cs@@ -279,6 +279,7 @@ internal static class ProgramCheckParts();CheckAbsorbingParts();CheckXorGate();+ CheckGatePortFollower();CheckZonePlate();CheckBrightnessFit();CheckRun();@@ -497,6 +498,23 @@ internal static class Programundone++;}Check(undone == 101 && history.Count == 102 && FileOf(project) == first, $"{undone} undos walk back through {history.Count} steps to the first");++ // what the design rests on: a step written back reaches the watcher as an edit, and the restored objects are watched like any+ project.AddSource().X = 12;+ history.Record();+ List<object> changed = [];+ using (var watcher = new ProjectWatcher(project))+ {+ watcher.Changed += (_, change) => changed.Add(change.Item);+ history.Undo();+ int seen = changed.Count;+ history.Redo();+ int afterRedo = changed.Count;+ project.Sources[0].X = 13;+ project.Scene.Width += 1;+ Check(seen > 0 && changed.Skip(afterRedo).Contains(project.Sources[0]) && changed.Skip(afterRedo).Contains(project.Scene),+ $"a step written back reaches the watcher ({seen} changes), and the restored source and scene are watched");+ }}/// <summary>@@ -564,6 +582,11 @@ internal static class ProgramProjectClipboard.PlaceAt(dropped, 1910, 5, 1920, 1080);Check(onto.Sources[0] is { X: 1869, Y: 5 } && onto.Probes[0] is { AX: 1919, AY: 25 }, "near the edge the group stops as a whole inside the canvas, as a group drag does");Check(ProjectClipboard.Read("<Project />") == null && ProjectClipboard.Read("just text") == null, "other text is no clip");+ Check(ProjectClipboard.Read("<Source Name=\"A\" /><Bogus />") == null, "a fragment with an element the file does not know is refused as a whole");+ var twins = new Project();+ string twin = ProjectClipboard.Write(from, [from.Sources[0]]);+ ProjectClipboard.Paste(twins, ProjectClipboard.Read(twin + twin)!, null);+ Check(twins.Sources.Select(s => s.Name).SequenceEqual(["Source 1", "Source 1 copy"]), "the same object twice in one text pastes as the name and the name with copy");}/// <summary>"bench-render [w h]": what colouring a stored frame costs, per layer, at that size (the presenter's cost per picture).</summary>@@ -1847,7 +1870,7 @@ internal static class Program// showed as patches two levels apart; the half table has every level betweenColorScheme infernoScheme = ColorSchemeStore.LoadBuiltIn(null).First(s => s.Name == "Inferno");ColorLut inferno = ColorLut.Build(infernoScheme);- int paletteBlues = Enumerable.Range(0, 16).Select(i => inferno.ColorAt(i).B).Distinct().Count();+ int paletteBlues = Enumerable.Range(0, 16).Select(i => Rgb.FromArgb(inferno.Argb[i]).B).Distinct().Count();int[] dark = inferno.HalfTable(SampleKind.IntensityRoot, 1f);int halfBlues = Enumerable.Range(0, ColorLut.HalfValues).Where(bits => (double)BitConverter.UInt16BitsToHalf((ushort)bits) is var v && v > 0.0 && v <= 15 / 254.0)@@ -1861,14 +1884,14 @@ internal static class Program{stops[i] = new Rgb((byte)(i * 30), 0, (byte)(255 - i * 30));}- ColorScheme scheme = ColorScheme.FromStops("test", stops);+ ColorScheme scheme = new("test", stops);ColorLut built = ColorLut.Build(scheme);- Check(built.ColorAt(0) == stops[0] && built.ColorAt(254) == stops[^1] && built.ColorAt(127) == stops[4], "the palette of a stop scheme hits the stops at 0, 127 and 254");+ Check(Rgb.FromArgb(built.Argb[0]) == stops[0] && Rgb.FromArgb(built.Argb[254]) == stops[^1] && Rgb.FromArgb(built.Argb[127]) == stops[4], "the palette of a stop scheme hits the stops at 0, 127 and 254");var indexed = new int[4];FrameRenderer.RenderIndexed(new byte[] { 0, 127, 254, 255 }, 2, 2, built, indexed);Check(indexed.SequenceEqual([built.Argb[0], built.Argb[127], built.Argb[254], built.Argb[254]]), "RenderIndexed looks each byte up in the palette, 255 as 254");ColorLut lifted = ColorLut.Build(scheme, blackLevel: 0.5);- Check(lifted.ColorAt(0).G == 127 && ((lifted.HalfTable(SampleKind.IntensityRoot, 1f)[0] >> 8) & 0xFF) == 128,+ Check(Rgb.FromArgb(lifted.Argb[0]).G == 127 && ((lifted.HalfTable(SampleKind.IntensityRoot, 1f)[0] >> 8) & 0xFF) == 128,"black level 0.5 lifts a 0 channel to 127 in the palette (truncated, as in Python) and to 128 in the half table (rounded)");CheckScreenRenderer(inferno);}@@ -1945,6 +1968,14 @@ internal static class Programvar flat = new int[2];new ScreenRenderer(4, 2, 2, 1).Render(wave, lut, SampleKind.Field, 1f, 0, flat);Check(flat.All(p => p == lut.HalfTable(SampleKind.Field, 1f)[BitConverter.HalfToUInt16Bits((Half)0f)]), "screen renderer: a crest beside a trough shrinks to the colour of zero");+ // enlarging through the whole path: a 2 x 2 field to 4 x 4, each pixel the bilinear blend of the two samples nearest+ // its centre on each axis (weights 3/4 and 1/4), the outer pixels holding the outer samples; exact in float and half+ Half[] small = [(Half)0.5f, (Half)(-0.5f), (Half)1.0f, (Half)0.0f];+ var large = new int[16];+ new ScreenRenderer(2, 2, 4, 4).Render(small, lut, SampleKind.Field, 1f, 0, large);+ float[] blended = [0.5f, 0.25f, -0.25f, -0.5f, 0.625f, 0.375f, -0.125f, -0.375f, 0.875f, 0.625f, 0.125f, -0.125f, 1.0f, 0.75f, 0.25f, 0.0f];+ int[] fieldTable = lut.HalfTable(SampleKind.Field, 1f);+ Check(large.SequenceEqual(blended.Select(v => fieldTable[BitConverter.HalfToUInt16Bits((Half)v)])), "enlarged 2 x 2 to 4 x 4, every pixel is the bilinear blend of the nearest samples, the ends held");// the dither: a flat plane comes out at the colour's two neighbouring 8-bit levels, their mix over one matrix the// 16-bit colour to the depth's bits; without dithering the level roundedulong[] deep = lut.DeepHalfTable(SampleKind.IntensityRoot, 1f);@@ -2892,8 +2923,10 @@ internal static class Program&& upper.Outline().Max(p => upper.ToCanvas(p.X, p.Y).Y) == lower.Outline().Min(p => lower.ToCanvas(p.X, p.Y).Y),"gates set a port spacing above and below the next column: the XOR output meets the upper gate's input B, the sum output the lower gate's input A, and the two touch");}- Check(new XorGatePart { PortSpacing = 20 }.Design!.PortSpacing == new XorGatePart().Design!.PortSpacing && new XorGatePart { PortSpacing = 120 }.Design!.PortSpacing == 120,- $"a port spacing below the design's minimum ({new XorGatePart().Design!.PortSpacing} px) is raised to it, a larger one is used as typed");+ var odd = new XorGatePart { PortSpacing = 121 };+ Check(new XorGatePart { PortSpacing = 20 }.Design!.PortSpacing == new XorGatePart().Design!.PortSpacing && new XorGatePart { PortSpacing = 120 }.Design!.PortSpacing == 120+ && odd.Design!.PortSpacing == 122 && odd.PortSpacing == 121,+ $"a port spacing below the design's minimum ({new XorGatePart().Design!.PortSpacing} px) is raised to it, a larger one is used as typed, an odd one rounded up to even with the typed value kept");Check(LogicGateDesign.BendShare(0) == 0 && Math.Abs(LogicGateDesign.BendShare(1) - 1) < 1e-12 && Math.Abs(LogicGateDesign.BendShare(0.5) - 0.5) < 1e-12,"the S-bend runs from the ports' offset to the coupler's, symmetric about its middle");@@ -2976,7 +3009,6 @@ internal static class Program(double xorAB, double sumAB, _) = Outputs([Make(ports[0].X, ports[0].Y, 0, 1.0) with { Level = level }, Make(ports[1].X, ports[1].Y, 0, 1.0) with { Level = level }]);double single = xorA + sumA;Check(Math.Abs(xorA / single - 0.5) < 0.1, $"one input splits about evenly: {xorA / single:0.000} to the XOR output");- CheckGatePortFollower();Check(xorAB / single < 0.03 && sumAB / single > 1.8, $"both inputs: the XOR output keeps {xorAB / single:0.000} of one input's power, the sum output {sumAB / single:0.00}× ({sw.ElapsedMilliseconds} ms)");gate.UpperOutputActive = false;gate.LowerOutputActive = false;@@ -3141,6 +3173,18 @@ internal static class Programproject.Sources.Add(c);second.PortSpacing = 80;Check((c.X, c.Y) == second.Ports()![0], "a gate added later is followed too");+ // a gate taken out of the list is let go; one whose cores guide nothing has no ports, so nothing follows until it guides again+ project.Parts.Remove(second);+ (int X, int Y) cBefore = (c.X, c.Y);+ second.PortSpacing = 120;+ Check((c.X, c.Y) == cBefore, "a gate removed from the project moves nothing");+ (int X, int Y) aBefore = (a.X, a.Y);+ gate.CoreIndex = 1.0;+ gate.X += 10;+ Check(gate.Ports() == null && (a.X, a.Y) == aBefore, "a gate whose cores guide nothing has no ports: its sources stay");+ gate.CoreIndex = 2.55;+ gate.X += 10;+ Check(gate.Ports() != null && (a.X, a.Y) == aBefore, "guiding again, it starts from the ports it has then; the sources it left behind are not on them");}gate.PortSpacing = 140;Check(!OnInputs(), "after Dispose nothing follows");