Skip to content

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

C#

Preview: scene image and glowing-edges outline, run and picture toggles, tree check boxes

Alexander Graef553cb00c1bc2
diff --git a/WaveDude.WPF/Converters/TreeIdConverter.cs b/WaveDude.WPF/Converters/TreeIdConverter.cs
new file mode 100644
index 0000000..670e751
--- /dev/null
+++ b/WaveDude.WPF/Converters/TreeIdConverter.cs
@@ -0,0 +1,27 @@
+using System.Globalization;
+using System.Windows.Data;
+using WaveDude.Model;
+using WaveDude.Rendering;
+
+namespace WaveDude.WPF.Converters;
+
+/// <summary>
+/// The automation id of a Project tree row from its node: "Tree:" plus the item's name (sources, probes,
+/// colour schemes), a folder's label, or the type name of the fixed nodes ("Tree:Scene"), so a harness
+/// can reach a row with Tab and act on it.
+/// </summary>
+public sealed class TreeIdConverter : IValueConverter
+{
+ public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => "Tree:" + value switch
+ {
+ Source source => source.Name,
+ Probe probe => probe.Name,
+ ColorScheme scheme => scheme.Name,
+ NamedCollection folder => folder.Key,
+ null => "",
+ _ => value.GetType().Name,
+ };
+
+ public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
+ throw new NotSupportedException();
+}
diff --git a/WaveDude.WPF/MainWindow.Live.cs b/WaveDude.WPF/MainWindow.Live.cs
index e0dd843..f310665 100644
--- a/WaveDude.WPF/MainWindow.Live.cs
+++ b/WaveDude.WPF/MainWindow.Live.cs
@@ -1,7 +1,9 @@
+using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using WaveDude.Model;
+using WaveDude.Rendering;
using WaveDude.Runs;
using WaveDude.WPF.Properties;
using WaveDude.WPF.Rendering;
@@ -44,6 +46,7 @@ public partial class MainWindow
private DispatcherTimer? _scratchTimer;
private DispatcherTimer? _rerunTimer;
private (string Path, DateTime Written, ScenePixels Pixels)? _imageCache;
+ private (byte[] Data, ScenePixels Pixels)? _embeddedCache;
/// <summary>Whether the project was edited in a way that changes the simulation since the current run started.</summary>
public bool IsRunStale
@@ -72,6 +75,13 @@ public partial class MainWindow
_watcher?.Dispose();
_watcher = null;
_imageCache = null;
+ _embeddedCache = null;
+ // the new project's own schemes and scene image; the pane does not exist yet when the constructor sets the first project
+ Dispatcher.InvokeAsync(() =>
+ {
+ previewPane?.RefreshColors();
+ UpdateScenePixels();
+ }, DispatcherPriority.Background);
IsRunStale = false;
ScratchFrame = null;
if (project != null)
@@ -85,10 +95,20 @@ public partial class MainWindow
private void OnProjectChanged(object? sender, ProjectChange change)
{
+ if (change.Item is ColorScheme or ObservableCollection<ColorScheme>)
+ {
+ // a project scheme edited, added or removed: recolour the frame shown
+ previewPane.RefreshColors();
+ return;
+ }
if (!change.AffectsSimulation)
{
return;
}
+ if (change.Item is Scene)
+ {
+ UpdateScenePixels();
+ }
if (Run != null)
{
IsRunStale = true;
@@ -227,6 +247,24 @@ public partial class MainWindow
}
}
+ /// <summary>Hands the preview the decoded scene image (null for a canvas, or when it cannot be read: that is logged once the run reports it).</summary>
+ private void UpdateScenePixels()
+ {
+ if (previewPane == null)
+ {
+ return;
+ }
+ try
+ {
+ previewPane.ScenePixels = LoadSceneImage();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or FileFormatException or RunSpecException)
+ {
+ Logger.Debug("Scene image not shown: {Message}", ex.Message);
+ previewPane.ScenePixels = null;
+ }
+ }
+
/// <summary>The decoded scene image for an image scene, decoded once per file version; null for a blank canvas.</summary>
private ScenePixels? LoadSceneImage()
{
@@ -234,6 +272,17 @@ public partial class MainWindow
{
return null;
}
+ if (Project.Scene.ImageData is { } data)
+ {
+ // embedded: decoded once per byte array (a new pick is a new array)
+ if (_embeddedCache is { } embedded && ReferenceEquals(embedded.Data, data))
+ {
+ return embedded.Pixels;
+ }
+ ScenePixels decoded = SceneImageLoader.Load(data);
+ _embeddedCache = (data, decoded);
+ return decoded;
+ }
string path = ResolveScenePath();
DateTime written = File.GetLastWriteTimeUtc(path);
if (_imageCache is { } cached && cached.Path == path && cached.Written == written)
diff --git a/WaveDude.WPF/Panes/PreviewPane.xaml b/WaveDude.WPF/Panes/PreviewPane.xaml
index 957dca0..c1b297a 100644
--- a/WaveDude.WPF/Panes/PreviewPane.xaml
+++ b/WaveDude.WPF/Panes/PreviewPane.xaml
@@ -13,16 +13,24 @@
<converters:FrameToStepConverter x:Key="FrameToStep" />
<converters:NotNullConverter x:Key="NotNull" />
+ <!-- "run": a play triangle inside a ring (the author asked for an explicit start button, 2026-10-13) -->
+ <StreamGeometry x:Key="RunGeometry">M0,7 A7,7 0 1 1 14,7 A7,7 0 1 1 0,7 Z M1.4,7 A5.6,5.6 0 1 0 12.6,7 A5.6,5.6 0 1 0 1.4,7 Z M5.2,3.5 L10.8,7 L5.2,10.5 Z</StreamGeometry>
+ <!-- the two pictures: a wave for the field, a sun for the intensity -->
+ <StreamGeometry x:Key="FieldGeometry">M0,6 C1.5,1 2.5,1 4,6 C5.5,11 6.5,11 8,6 C9,3 10,3 11,6 L11,7.5 C10,5 9,5 8,7.5 C6.5,12.5 5.5,12.5 4,7.5 C2.5,2.5 1.5,2.5 0,7.5 Z</StreamGeometry>
+ <StreamGeometry x:Key="IntensityGeometry">M3,5 A2,2 0 1 1 7,5 A2,2 0 1 1 3,5 Z M4.4,0 L5.6,0 L5.6,2 L4.4,2 Z M4.4,8 L5.6,8 L5.6,10 L4.4,10 Z M0,4.4 L2,4.4 L2,5.6 L0,5.6 Z M8,4.4 L10,4.4 L10,5.6 L8,5.6 Z</StreamGeometry>
<StreamGeometry x:Key="PlayGeometry">M0,0 L9,5 L0,10 Z</StreamGeometry>
<StreamGeometry x:Key="PauseGeometry">M0,0 L3,0 L3,10 L0,10 Z M6,0 L9,0 L9,10 L6,10 Z</StreamGeometry>
<StreamGeometry x:Key="SideBySideGeometry">M0,0 L5,0 L5,10 L0,10 Z M7,0 L12,0 L12,10 L7,10 Z</StreamGeometry>
<StreamGeometry x:Key="StackedGeometry">M0,0 L12,0 L12,4 L0,4 Z M0,6 L12,6 L12,10 L0,10 Z</StreamGeometry>
- <StreamGeometry x:Key="StepBackGeometry">M0,0 L2,0 L2,10 L0,10 Z M9,0 L3,5 L9,10 Z</StreamGeometry>
- <StreamGeometry x:Key="StepForwardGeometry">M7,0 L9,0 L9,10 L7,10 Z M0,0 L6,5 L0,10 Z</StreamGeometry>
+ <!-- frame step: the triangle leaves a bar behind it ("◀|" "|▶", the editors' frame-step look); a bar in front of the
+ triangle is the players' skip to start/end, which the author read it as (point 1, changed 2026-10-13) -->
+ <StreamGeometry x:Key="StepBackGeometry">M7,0 L9,0 L9,10 L7,10 Z M0,5 L6,0 L6,10 Z</StreamGeometry>
+ <StreamGeometry x:Key="StepForwardGeometry">M0,0 L2,0 L2,10 L0,10 Z M3,0 L9,5 L3,10 Z</StreamGeometry>
<StreamGeometry x:Key="SetInGeometry">M0,0 L4,0 L4,2 L2,2 L2,8 L4,8 L4,10 L0,10 Z M6,2 L11,5 L6,8 Z</StreamGeometry>
<StreamGeometry x:Key="SetOutGeometry">M11,0 L7,0 L7,2 L9,2 L9,8 L7,8 L7,10 L11,10 Z M5,2 L0,5 L5,8 Z</StreamGeometry>
<StreamGeometry x:Key="ClearRangeGeometry">M0,1.5 L1.5,0 L5,3.5 L8.5,0 L10,1.5 L6.5,5 L10,8.5 L8.5,10 L5,6.5 L1.5,10 L0,8.5 L3.5,5 Z</StreamGeometry>
- <StreamGeometry x:Key="LoopGeometry">M5,1 A4,4 0 1 1 1,5 L3,5 A2,2 0 1 0 5,3 Z M5,0 L8,2 L5,4 Z</StreamGeometry>
+ <!-- "repeat": two arrows chasing each other (the loop-shaped one read oddly, 2026-10-14) -->
+ <StreamGeometry x:Key="LoopGeometry">M1,2 L8,2 L8,0 L12,3 L8,6 L8,4 L3,4 L3,6 L1,6 Z M11,8 L4,8 L4,10 L0,7 L4,4 L4,6 L9,6 L9,4 L11,4 Z</StreamGeometry>
<!-- "live": a dot inside a ring (even-odd fill makes the ring hollow) -->
<StreamGeometry x:Key="LiveGeometry">M0.5,5 A4.5,4.5 0 1 1 9.5,5 A4.5,4.5 0 1 1 0.5,5 Z M1.5,5 A3.5,3.5 0 1 0 8.5,5 A3.5,3.5 0 1 0 1.5,5 Z M3.5,5 A1.5,1.5 0 1 1 6.5,5 A1.5,1.5 0 1 1 3.5,5 Z</StreamGeometry>
<BooleanToVisibilityConverter x:Key="BoolToVisibility" />
@@ -64,6 +72,7 @@
<!-- glyph toggle (and radio) button; the checked one stays pressed. Used for the loop toggle and
the split radios, whose group is one tab stop with Left/Right inside (see the StackPanel below) -->
+ <!-- the toggles share the buttons' look, including the greyed, half-transparent disabled state (Live without a run, 2026-10-14) -->
<Style x:Key="TransportToggle" TargetType="{x:Type ToggleButton}">
<Setter Property="Width" Value="22" />
<Setter Property="Height" Value="22" />
@@ -88,6 +97,10 @@
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonPressed}" />
<Setter Property="Foreground" Value="White" />
</Trigger>
+ <Trigger Property="IsEnabled" Value="False">
+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />
+ <Setter Property="Opacity" Value="0.5" />
+ </Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
@@ -206,6 +219,11 @@
this one, since both dock to the bottom) and follows in the tab order. -->
<Border DockPanel.Dock="Bottom" BorderBrush="{DynamicResource ToolWindowBorder}" BorderThickness="0,1,0,0" Padding="4,3">
<DockPanel KeyboardNavigation.TabNavigation="Local">
+ <!-- an explicit "run the simulation" next to Play (Play alone starts one only when needed) -->
+ <Button DockPanel.Dock="Left" TabIndex="0" Style="{StaticResource TransportButton}" Content="{StaticResource RunGeometry}"
+ Command="{x:Static commands:SimulationCommands.Run}" ToolTip="{DynamicResource TipPreviewRun}"
+ AutomationProperties.Name="{DynamicResource TipPreviewRun}" AutomationProperties.AutomationId="PreviewRun" />
+ <Rectangle DockPanel.Dock="Left" Width="1" Margin="4,2" Fill="{DynamicResource ToolWindowBorder}" />
<Button x:Name="playButton" DockPanel.Dock="Left" TabIndex="1" Style="{StaticResource TransportButton}" Content="{StaticResource PlayGeometry}"
Command="MediaCommands.Play" ToolTip="{DynamicResource TipPreviewPlay}"
AutomationProperties.Name="{DynamicResource TipPreviewPlay}" AutomationProperties.AutomationId="PreviewPlay" />
@@ -241,7 +259,7 @@
<!-- right-docked items: the first declared is the rightmost -->
<!-- one tab stop, the checked radio (IsTabStop follows IsChecked); the arrow keys move to the
neighbour and check it, in code, since WPF's directional navigation skips non-tab-stops -->
- <StackPanel x:Name="splitGroup" DockPanel.Dock="Right" Orientation="Horizontal" KeyboardNavigation.TabIndex="11"
+ <StackPanel x:Name="splitGroup" DockPanel.Dock="Right" Orientation="Horizontal" KeyboardNavigation.TabIndex="13"
KeyDown="OnSplitGroupKeyDown">
<RadioButton Style="{StaticResource TransportToggle}" Content="{StaticResource SideBySideGeometry}" GroupName="Split"
ToolTip="{DynamicResource TipPreviewSideBySide}"
@@ -254,6 +272,17 @@
IsChecked="{Binding Orientation, ElementName=pane, Converter={StaticResource EnumBoolean}, ConverterParameter={x:Static Orientation.Vertical}}"
IsTabStop="{Binding IsChecked, RelativeSource={RelativeSource Self}, Mode=OneWay}" />
</StackPanel>
+ <!-- show or hide each picture (the layer's Preview setting; the author wanted one picture at a time, point 4) -->
+ <ToggleButton DockPanel.Dock="Right" TabIndex="12" Style="{StaticResource TransportToggle}" Content="{StaticResource IntensityGeometry}"
+ IsChecked="{Binding IntensitySettings.Preview, ElementName=pane, Mode=TwoWay}"
+ IsEnabled="{Binding IntensitySettings, ElementName=pane, Converter={StaticResource NotNull}}"
+ ToolTip="{DynamicResource TipPreviewShowIntensity}"
+ AutomationProperties.Name="{DynamicResource TipPreviewShowIntensity}" AutomationProperties.AutomationId="PreviewShowIntensity" />
+ <ToggleButton DockPanel.Dock="Right" TabIndex="11" Style="{StaticResource TransportToggle}" Content="{StaticResource FieldGeometry}"
+ IsChecked="{Binding FieldSettings.Preview, ElementName=pane, Mode=TwoWay}"
+ IsEnabled="{Binding FieldSettings, ElementName=pane, Converter={StaticResource NotNull}}"
+ ToolTip="{DynamicResource TipPreviewShowField}"
+ AutomationProperties.Name="{DynamicResource TipPreviewShowField}" AutomationProperties.AutomationId="PreviewShowField" />
<Rectangle DockPanel.Dock="Right" Width="1" Margin="4,2" Fill="{DynamicResource ToolWindowBorder}" />
<ComboBox x:Name="speedBox" DockPanel.Dock="Right" TabIndex="10" Width="64" IsEditable="True" ItemsSource="{x:Static local:PreviewPane.SpeedPresets}"
Text="{Binding Speed, ElementName=pane, Mode=TwoWay, Converter={StaticResource DoubleText}}" ToolTip="{DynamicResource TipPreviewSpeed}"
@@ -318,6 +347,9 @@
<!-- the picture with the source/probe handles over it; both fill the same rectangle -->
<Grid>
<Image Source="{TemplateBinding Content}" Stretch="Uniform" AutomationProperties.AutomationId="{TemplateBinding Tag}" />
+ <!-- the scene outline, a translucent layer of the same pixel size, so it lands exactly on the frame -->
+ <Image Source="{Binding Path=(local:PreviewPane.OverlayImage), RelativeSource={RelativeSource TemplatedParent}}"
+ Stretch="Uniform" IsHitTestVisible="False" />
<!-- styled here, not implicitly: WPF applies implicit styles inside a template only to Controls, and the overlay is a Panel -->
<controls:SceneOverlay SourceStyle="{StaticResource SourceMarker}" ProbeStyle="{StaticResource ProbeMarker}"
LineBrush="White" LabelBrush="White" AccentBrush="{DynamicResource Accent}"
@@ -390,14 +422,16 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
- <HeaderedContentControl Style="{StaticResource PictureCell}" Header="{DynamicResource SectionField}"
+ <HeaderedContentControl x:Name="fieldCell" Style="{StaticResource PictureCell}" Header="{DynamicResource SectionField}"
Content="{Binding FieldImage, ElementName=pane}" Tag="PreviewFieldImage"
+ local:PreviewPane.OverlayImage="{Binding FieldOverlay, ElementName=pane}"
Visibility="{Binding FieldSettings.Preview, ElementName=pane, Converter={StaticResource BoolToVisibility}, FallbackValue=Visible}" />
- <GridSplitter Style="{StaticResource PictureSplitter}" ToolTip="{DynamicResource TipPreviewSplitter}"
+ <GridSplitter x:Name="pictureSplitter" Style="{StaticResource PictureSplitter}" ToolTip="{DynamicResource TipPreviewSplitter}"
AutomationProperties.Name="{DynamicResource TipPreviewSplitter}" AutomationProperties.AutomationId="PreviewSplitter"
MouseDoubleClick="OnSplitterMouseDoubleClick" KeyDown="OnSplitterKeyDown" />
- <HeaderedContentControl Style="{StaticResource SecondPictureCell}" Header="{DynamicResource SectionIntensity}"
+ <HeaderedContentControl x:Name="intensityCell" Style="{StaticResource SecondPictureCell}" Header="{DynamicResource SectionIntensity}"
Content="{Binding IntensityImage, ElementName=pane}" Tag="PreviewIntensityImage"
+ local:PreviewPane.OverlayImage="{Binding IntensityOverlay, ElementName=pane}"
Visibility="{Binding IntensitySettings.Preview, ElementName=pane, Converter={StaticResource BoolToVisibility}, FallbackValue=Visible}" />
</Grid>
diff --git a/WaveDude.WPF/Panes/PreviewPane.xaml.cs b/WaveDude.WPF/Panes/PreviewPane.xaml.cs
index cbd0906..8079183 100644
--- a/WaveDude.WPF/Panes/PreviewPane.xaml.cs
+++ b/WaveDude.WPF/Panes/PreviewPane.xaml.cs
@@ -9,6 +9,7 @@ using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using WaveDude.Model;
+using WaveDude.Rendering;
using WaveDude.Runs;
using WaveDude.WPF.Commands;
using WaveDude.WPF.Converters;
@@ -59,6 +60,8 @@ public partial class PreviewPane : UserControl
/// <summary>The picture shown while there is no run: black, in the canvas's size so the overlay and the aspect ratio are right.</summary>
private BitmapSource _blackFrame = BlackFrame(16, 9);
+ private BitmapSource? _sceneBitmap;
+ private byte[]? _edges;
/// <summary>Identifies the <see cref="Project"/> property.</summary>
public static readonly DependencyProperty ProjectProperty = DependencyProperty.Register(
@@ -135,6 +138,26 @@ public partial class PreviewPane : UserControl
public static readonly DependencyProperty FieldImageProperty = DependencyProperty.Register(
nameof(FieldImage), typeof(ImageSource), typeof(PreviewPane));
+ /// <summary>Identifies the <see cref="ScenePixels"/> property.</summary>
+ public static readonly DependencyProperty ScenePixelsProperty = DependencyProperty.Register(
+ nameof(ScenePixels), typeof(ScenePixels), typeof(PreviewPane), new PropertyMetadata(null, (d, _) => ((PreviewPane)d).OnScenePixelsChanged()));
+
+ /// <summary>Identifies the <see cref="FieldOverlay"/> property.</summary>
+ public static readonly DependencyProperty FieldOverlayProperty = DependencyProperty.Register(
+ nameof(FieldOverlay), typeof(ImageSource), typeof(PreviewPane));
+
+ /// <summary>Identifies the <see cref="IntensityOverlay"/> property.</summary>
+ public static readonly DependencyProperty IntensityOverlayProperty = DependencyProperty.Register(
+ nameof(IntensityOverlay), typeof(ImageSource), typeof(PreviewPane));
+
+ /// <summary>Attached to each picture cell: the overlay layer its template draws over the frame.</summary>
+ public static readonly DependencyProperty OverlayImageProperty = DependencyProperty.RegisterAttached(
+ "OverlayImage", typeof(ImageSource), typeof(PreviewPane));
+
+ public static ImageSource? GetOverlayImage(DependencyObject element) => (ImageSource?)element.GetValue(OverlayImageProperty);
+
+ public static void SetOverlayImage(DependencyObject element, ImageSource? value) => element.SetValue(OverlayImageProperty, value);
+
/// <summary>Identifies the <see cref="IntensityImage"/> property.</summary>
public static readonly DependencyProperty IntensityImageProperty = DependencyProperty.Register(
nameof(IntensityImage), typeof(ImageSource), typeof(PreviewPane));
@@ -350,6 +373,31 @@ public partial class PreviewPane : UserControl
set => SetValue(FieldImageProperty, value);
}
+ /// <summary>
+ /// The decoded scene image of an image scene, null for a blank canvas (2026-10-13). It is the picture
+ /// shown where no frame exists, gives the canvas its size before any run, and is the source of the
+ /// glowing-edges overlays (<see cref="FieldOverlay"/>, <see cref="IntensityOverlay"/>).
+ /// </summary>
+ public ScenePixels? ScenePixels
+ {
+ get => (ScenePixels?)GetValue(ScenePixelsProperty);
+ set => SetValue(ScenePixelsProperty, value);
+ }
+
+ /// <summary>The outline layer over the field picture; null when off, at gain 0, or without a scene image.</summary>
+ public ImageSource? FieldOverlay
+ {
+ get => (ImageSource?)GetValue(FieldOverlayProperty);
+ private set => SetValue(FieldOverlayProperty, value);
+ }
+
+ /// <summary>The outline layer over the intensity picture; null when off, at gain 0, or without a scene image.</summary>
+ public ImageSource? IntensityOverlay
+ {
+ get => (ImageSource?)GetValue(IntensityOverlayProperty);
+ private set => SetValue(IntensityOverlayProperty, value);
+ }
+
/// <summary>Picture of the intensity at <see cref="Position"/>; the presenter's bitmap, or a black frame without a run (or without an intensity plane).</summary>
public ImageSource? IntensityImage
{
@@ -506,9 +554,11 @@ public partial class PreviewPane : UserControl
UpdateCanvas(run.Store);
_presenter.Show(Position);
}
- else if (run == null && _presenter.Source != null)
+ else if (run == null && scratch == null && _presenter.Source != null)
{
- // nothing at all any more (project closed or replaced)
+ // nothing at all any more (project closed or replaced: the window reset the scratch frame too). With a
+ // scratch frame for another position pending, the last picture stays: clearing here made every scrub
+ // without a run flash the empty picture before the new frame arrived (2026-10-13)
_presenter.Source = null;
UpdateCanvas(null);
}
@@ -521,16 +571,47 @@ public partial class PreviewPane : UserControl
private void UpdateCanvas(IFrameSource? source)
{
- int width = Math.Max(1, source?.Width ?? Run?.Spec.Width ?? (int)GetValue(SceneWidthProperty));
- int height = Math.Max(1, source?.Height ?? Run?.Spec.Height ?? (int)GetValue(SceneHeightProperty));
+ // the scene image's size wins over the project's numbers, which only apply to a blank canvas
+ int width = Math.Max(1, source?.Width ?? Run?.Spec.Width ?? ScenePixels?.Width ?? (int)GetValue(SceneWidthProperty));
+ int height = Math.Max(1, source?.Height ?? Run?.Spec.Height ?? ScenePixels?.Height ?? (int)GetValue(SceneHeightProperty));
CanvasWidth = width;
CanvasHeight = height;
if (_blackFrame.PixelWidth != width || _blackFrame.PixelHeight != height)
{
_blackFrame = BlackFrame(width, height);
}
- FieldImage = _presenter.FieldBitmap ?? _blackFrame;
- IntensityImage = _presenter.IntensityBitmap ?? _blackFrame;
+ // without a frame, an image scene shows the scene image itself (the author's picking background), a canvas black
+ BitmapSource empty = _sceneBitmap is { } scene && scene.PixelWidth == width && scene.PixelHeight == height ? scene : _blackFrame;
+ FieldImage = _presenter.FieldBitmap ?? empty;
+ IntensityImage = _presenter.IntensityBitmap ?? empty;
+ }
+
+ /// <summary>A new scene image (or none): rebuilds the picture, the edge picture and both overlays, and re-derives the canvas.</summary>
+ private void OnScenePixelsChanged()
+ {
+ ScenePixels? pixels = ScenePixels;
+ _sceneBitmap = pixels == null ? null : SceneBitmaps.Image(pixels);
+ _edges = pixels == null ? null : GlowingEdges.Compute(pixels.Bgra, pixels.Width, pixels.Height, pixels.StrideBytes);
+ UpdateOverlay(FrameLayer.Field);
+ UpdateOverlay(FrameLayer.Intensity);
+ UpdateCanvas();
+ }
+
+ /// <summary>Rebuilds one layer's outline from its settings: null when switched off, at gain 0, or without a scene image.</summary>
+ private void UpdateOverlay(FrameLayer layer)
+ {
+ DisplayLayer? settings = layer == FrameLayer.Field ? FieldSettings : IntensitySettings;
+ ImageSource? overlay = _edges != null && ScenePixels is { } pixels && settings is { Overlay: true }
+ ? SceneBitmaps.Overlay(_edges, pixels.Width, pixels.Height, settings.OverlayGain)
+ : null;
+ if (layer == FrameLayer.Field)
+ {
+ FieldOverlay = overlay;
+ }
+ else
+ {
+ IntensityOverlay = overlay;
+ }
}
/// <summary>The canvas follows the project's size while nothing is shown.</summary>
@@ -603,20 +684,77 @@ public partial class PreviewPane : UserControl
settings.PropertyChanged += handler;
}
ApplyLayer(layer);
+ UpdateOverlay(layer);
+ UpdatePictureLayout();
}
- private void OnFieldSettingsPropertyChanged(object? sender, PropertyChangedEventArgs e) => ApplyLayer(FrameLayer.Field);
+ private void OnFieldSettingsPropertyChanged(object? sender, PropertyChangedEventArgs e) => OnLayerSettingChanged(FrameLayer.Field, e.PropertyName);
+
+ private void OnIntensitySettingsPropertyChanged(object? sender, PropertyChangedEventArgs e) => OnLayerSettingChanged(FrameLayer.Intensity, e.PropertyName);
+
+ /// <summary>An outline setting rebuilds that layer's overlay; anything else re-applies the palette.</summary>
+ private void OnLayerSettingChanged(FrameLayer layer, string? property)
+ {
+ if (property is nameof(DisplayLayer.Overlay) or nameof(DisplayLayer.OverlayGain))
+ {
+ UpdateOverlay(layer);
+ }
+ else if (property != nameof(DisplayLayer.OverlayInExport))
+ {
+ ApplyLayer(layer);
+ }
+ if (property == nameof(DisplayLayer.Preview))
+ {
+ UpdatePictureLayout();
+ }
+ }
- private void OnIntensitySettingsPropertyChanged(object? sender, PropertyChangedEventArgs e) => ApplyLayer(FrameLayer.Intensity);
+ /// <summary>
+ /// A hidden picture gives its room to the other one (2026-10-13): with one picture off, the other
+ /// spans the whole grid and the splitter is collapsed; with both on, the cells go back to the
+ /// style's placement (the local values are cleared so the orientation triggers apply again) and the
+ /// user's split survives, since the column and row sizes are never touched.
+ /// </summary>
+ private void UpdatePictureLayout()
+ {
+ bool field = FieldSettings?.Preview ?? true;
+ bool intensity = IntensitySettings?.Preview ?? true;
+ bool single = field != intensity;
+ pictureSplitter.Visibility = single ? Visibility.Collapsed : Visibility.Visible;
+ foreach (HeaderedContentControl cell in new[] { fieldCell, intensityCell })
+ {
+ if (single)
+ {
+ cell.SetValue(Grid.ColumnProperty, 0);
+ cell.SetValue(Grid.RowProperty, 0);
+ cell.SetValue(Grid.ColumnSpanProperty, 3);
+ cell.SetValue(Grid.RowSpanProperty, 3);
+ }
+ else
+ {
+ cell.ClearValue(Grid.ColumnProperty);
+ cell.ClearValue(Grid.RowProperty);
+ cell.ClearValue(Grid.ColumnSpanProperty);
+ cell.ClearValue(Grid.RowSpanProperty);
+ }
+ }
+ }
/// <summary>Hands a layer's palette, brightness and visibility to the presenter, which redraws the frame shown.</summary>
private void ApplyLayer(FrameLayer layer)
{
DisplayLayer? settings = layer == FrameLayer.Field ? FieldSettings : IntensitySettings;
- int[]? lut = settings == null ? null : ColorSchemeCatalog.Instance.LutFor(settings.ColorScheme, settings.BlackLevel);
+ int[]? lut = settings == null ? null : ColorSchemeCatalog.Instance.LutFor(Project, settings.ColorScheme, settings.BlackLevel);
_presenter.SetLayer(layer, lut, (float)(settings?.Brightness ?? DisplayLayer.DefaultBrightness), settings?.Preview ?? true);
}
+ /// <summary>Rebuilds both palettes and redraws: a project colour scheme changed, or the project was replaced.</summary>
+ public void RefreshColors()
+ {
+ ApplyLayer(FrameLayer.Field);
+ ApplyLayer(FrameLayer.Intensity);
+ }
+
// ---------------------------------------------------------------- playback
private static object CoerceSpeed(DependencyObject d, object value)
diff --git a/WaveDude.WPF/Panes/ProjectTree.xaml b/WaveDude.WPF/Panes/ProjectTree.xaml
index 0db8a86..d5c1829 100644
--- a/WaveDude.WPF/Panes/ProjectTree.xaml
+++ b/WaveDude.WPF/Panes/ProjectTree.xaml
@@ -4,11 +4,14 @@
xmlns:local="clr-namespace:WaveDude.WPF.Panes"
xmlns:commands="clr-namespace:WaveDude.WPF.Commands"
xmlns:converters="clr-namespace:WaveDude.WPF.Converters"
- xmlns:model="clr-namespace:WaveDude.Model;assembly=WaveDude">
+ xmlns:model="clr-namespace:WaveDude.Model;assembly=WaveDude"
+ xmlns:rendering="clr-namespace:WaveDude.Rendering;assembly=WaveDude">
<UserControl.Resources>
<converters:EnumerateConverter x:Key="Enumerate" />
<converters:NamedCollectionConverter x:Key="NamedCollections" />
+ <converters:ColorSchemeBrushConverter x:Key="ColorSchemeBrush" />
+ <converters:TreeIdConverter x:Key="TreeId" />
<StreamGeometry x:Key="PlusGeometry">M4,0 L4,8 M0,4 L8,4</StreamGeometry>
<StreamGeometry x:Key="MinusGeometry">M0,4 L8,4</StreamGeometry>
@@ -80,6 +83,7 @@
<!-- keys act on the selection; only while the tree has focus -->
<TreeView.InputBindings>
<KeyBinding Key="Delete" Command="{x:Static commands:ProjectCommands.Remove}" />
+ <KeyBinding Key="Space" Command="{x:Static commands:ProjectCommands.ToggleEnabled}" />
<KeyBinding Key="D" Modifiers="Ctrl" Command="{x:Static commands:ProjectCommands.Duplicate}" />
<KeyBinding Key="Up" Modifiers="Alt" Command="{x:Static commands:ProjectCommands.MoveUp}" />
<KeyBinding Key="Down" Modifiers="Alt" Command="{x:Static commands:ProjectCommands.MoveDown}" />
@@ -89,6 +93,8 @@
<Style TargetType="{x:Type TreeViewItem}" BasedOn="{StaticResource {x:Type TreeViewItem}}">
<Setter Property="IsExpanded" Value="True" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
+ <!-- "Tree:<name>" so a harness can Tab to a row and act on it -->
+ <Setter Property="AutomationProperties.AutomationId" Value="{Binding Converter={StaticResource TreeId}}" />
<!-- context menu: the node is the data context, the row is the command target -->
<Setter Property="ContextMenu">
<Setter.Value>
@@ -102,6 +108,7 @@
<MenuItem Header="{DynamicResource MenuProjectAddSource}" Command="{x:Static commands:ProjectCommands.AddSource}" />
<MenuItem Header="{DynamicResource MenuProjectAddProbe}" Command="{x:Static commands:ProjectCommands.AddProbe}" />
<Separator />
+ <MenuItem Header="{DynamicResource MenuProjectToggleEnabled}" Command="{x:Static commands:ProjectCommands.ToggleEnabled}" InputGestureText="Space" />
<MenuItem Header="{DynamicResource MenuProjectDuplicate}" Command="{x:Static commands:ProjectCommands.Duplicate}" InputGestureText="Ctrl+D" />
<MenuItem Header="{DynamicResource MenuProjectRemove}" Command="{x:Static commands:ProjectCommands.Remove}" InputGestureText="Del" />
<Separator />
@@ -117,12 +124,13 @@
<!-- one template per model type; children come from the bound properties, lists become folders -->
<HierarchicalDataTemplate DataType="{x:Type model:Project}">
<HierarchicalDataTemplate.ItemsSource>
- <MultiBinding Converter="{StaticResource NamedCollections}" ConverterParameter=",,,Sources,Probes">
+ <MultiBinding Converter="{StaticResource NamedCollections}" ConverterParameter=",,,TreeSources,TreeProbes,TreeColorSchemes">
<Binding Path="Scene" />
<Binding Path="Simulation" />
<Binding Path="Display" />
<Binding Path="Sources" />
<Binding Path="Probes" />
+ <Binding Path="ColorSchemes" />
</MultiBinding>
</HierarchicalDataTemplate.ItemsSource>
<TextBlock Text="{DynamicResource TreeProject}" />
@@ -156,6 +164,34 @@
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 -->
+ <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}'}" />
+ <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>
+ </DockPanel>
+ </DataTemplate>
+ <!-- a project colour scheme: its gradient and name -->
+ <DataTemplate DataType="{x:Type rendering:ColorScheme}">
+ <DockPanel>
+ <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}" />
+ <Rectangle DockPanel.Dock="Left" Width="36" Height="10" Margin="0,0,6,0" VerticalAlignment="Center" StrokeThickness="0.5"
+ Stroke="{DynamicResource TextBoxBorder}" Fill="{Binding Stops, Converter={StaticResource ColorSchemeBrush}}" />
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" />
</DockPanel>
</DataTemplate>
@@ -167,7 +203,21 @@
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}" />
- <TextBlock Text="{Binding Name}" VerticalAlignment="Center" />
+ <!-- the enabled check box (Space on the selected row toggles it too); the name greys out when off -->
+ <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}'}" />
+ <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>
</DockPanel>
</DataTemplate>
</TreeView.Resources>
diff --git a/WaveDude.WPF/Panes/ProjectTree.xaml.cs b/WaveDude.WPF/Panes/ProjectTree.xaml.cs
index 03291eb..99b008d 100644
--- a/WaveDude.WPF/Panes/ProjectTree.xaml.cs
+++ b/WaveDude.WPF/Panes/ProjectTree.xaml.cs
@@ -1,3 +1,4 @@
+using WaveDude.Rendering;
using System.Collections;
using System.Windows;
using System.Windows.Controls;
@@ -113,7 +114,7 @@ public partial class ProjectTree : UserControl
{
return; // row buttons are clicks, not drags
}
- if (FindAncestor<TreeViewItem>(origin) is { DataContext: Source or Probe } row)
+ if (FindAncestor<TreeViewItem>(origin) is { DataContext: Source or Probe or ColorScheme } row)
{
_dragCandidate = row.DataContext;
_dragStart = e.GetPosition(tree);
@@ -233,6 +234,7 @@ public partial class ProjectTree : UserControl
{
Source => Project?.Sources,
Probe => Project?.Probes,
+ ColorScheme => Project?.ColorSchemes,
_ => null,
};
diff --git a/WaveDude.WPF/Rendering/SceneBitmaps.cs b/WaveDude.WPF/Rendering/SceneBitmaps.cs
new file mode 100644
index 0000000..73bac54
--- /dev/null
+++ b/WaveDude.WPF/Rendering/SceneBitmaps.cs
@@ -0,0 +1,60 @@
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using WaveDude.Rendering;
+using WaveDude.Runs;
+
+namespace WaveDude.WPF.Rendering;
+
+/// <summary>
+/// The preview's pictures made from a scene image (2026-10-13): the image itself, shown where there is
+/// no frame yet, and the glowing-edges overlay (<see cref="GlowingEdges"/>) as a translucent layer. WPF
+/// composites source-over, not additively like the author's export, so the overlay's alpha carries the
+/// edge strength times the gain and its colour is the edge colour at full brightness: a black (no edge)
+/// pixel leaves the frame alone, a faint edge tints it a little, a hard edge paints its colour over it.
+/// All bitmaps are frozen. UI thread (or any thread; the results are shareable).
+/// </summary>
+public static class SceneBitmaps
+{
+ /// <summary>The scene image as a bitmap (alpha ignored).</summary>
+ public static BitmapSource Image(ScenePixels pixels)
+ {
+ BitmapSource bitmap = BitmapSource.Create(pixels.Width, pixels.Height, 96, 96, PixelFormats.Bgr32, null, pixels.Bgra, pixels.StrideBytes);
+ bitmap.Freeze();
+ return bitmap;
+ }
+
+ /// <summary>
+ /// The overlay layer for one picture: alpha = min(255, strongest channel × <paramref name="gain"/>),
+ /// colour = the edge colour scaled so its strongest channel is 255. Null when the gain is 0.
+ /// </summary>
+ /// <param name="edgesBgra">The picture from <see cref="GlowingEdges.Compute"/>.</param>
+ /// <param name="width">Width in pixels.</param>
+ /// <param name="height">Height in pixels.</param>
+ /// <param name="gain">The layer's overlay gain (<c>DisplayLayer.OverlayGain</c>).</param>
+ public static BitmapSource? Overlay(byte[] edgesBgra, int width, int height, double gain)
+ {
+ if (gain <= 0.0)
+ {
+ return null;
+ }
+ var layer = new byte[edgesBgra.Length];
+ for (int i = 0; i < layer.Length; i += 4)
+ {
+ int b = edgesBgra[i];
+ int g = edgesBgra[i + 1];
+ int r = edgesBgra[i + 2];
+ int max = Math.Max(b, Math.Max(g, r));
+ if (max == 0)
+ {
+ continue; // transparent black
+ }
+ layer[i] = (byte)(b * 255 / max);
+ layer[i + 1] = (byte)(g * 255 / max);
+ layer[i + 2] = (byte)(r * 255 / max);
+ layer[i + 3] = (byte)Math.Min(255.0, max * gain);
+ }
+ BitmapSource bitmap = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgra32, null, layer, width * 4);
+ bitmap.Freeze();
+ return bitmap;
+ }
+}
diff --git a/WaveDude.WPF/Themes/Controls.xaml b/WaveDude.WPF/Themes/Controls.xaml
index 05543ee..42475fd 100644
--- a/WaveDude.WPF/Themes/Controls.xaml
+++ b/WaveDude.WPF/Themes/Controls.xaml
@@ -17,6 +17,7 @@
<StreamGeometry x:Key="CheckGeometry">M0,4 L3,7 L8,1</StreamGeometry>
<StreamGeometry x:Key="ChevronRightGeometry">M0,0 L5,5 L0,10</StreamGeometry>
<StreamGeometry x:Key="ChevronDownGeometry">M0,0 L5,5 L10,0</StreamGeometry>
+ <StreamGeometry x:Key="ChevronUpGeometry">M0,5 L5,0 L10,5</StreamGeometry>
<StreamGeometry x:Key="CloseGeometry">M0,1 L1,0 L4,3 L7,0 L8,1 L5,4 L8,7 L7,8 L4,5 L1,8 L0,7 L3,4 Z</StreamGeometry>
<StreamGeometry x:Key="DropDownGeometry">M0,0 L8,0 L4,4 Z</StreamGeometry>
diff --git a/WaveDude/Model/Display.cs b/WaveDude/Model/Display.cs
index b210799..8405eca 100644
--- a/WaveDude/Model/Display.cs
+++ b/WaveDude/Model/Display.cs
@@ -102,11 +102,20 @@ public sealed class DisplayLayer : ObservableObject
/// <summary>Default <see cref="Brightness"/>.</summary>
public const double DefaultBrightness = 30.0;
+ /// <summary>Default <see cref="OverlayGain"/>: the edge picture as computed.</summary>
+ public const double DefaultOverlayGain = 1.0;
+
+ /// <summary>Largest <see cref="OverlayGain"/>, the author's control's maximum.</summary>
+ public const double MaxOverlayGain = 5.0;
+
private string _colorScheme = "";
private double _brightness = DefaultBrightness;
private double _blackLevel;
private bool _preview = true;
private bool _export;
+ private bool _overlay = true;
+ private double _overlayGain = DefaultOverlayGain;
+ private bool _overlayInExport;
/// <summary>Name of the colour scheme mapped onto the values.</summary>
[XmlAttribute]
@@ -164,6 +173,46 @@ public sealed class DisplayLayer : ObservableObject
set => SetProperty(ref _export, value);
}
+ /// <summary>
+ /// Whether the preview lays the scene image's "glowing edges" outline over this output (the author's
+ /// "Display overlay"; on by default here, 2026-10-13), so the scene layout shows under the field or
+ /// intensity. Only an image scene has one.
+ /// </summary>
+ [XmlAttribute]
+ [DefaultValue(true)]
+ [Category("Scene outline")]
+ [DisplayName("Outline in the preview")]
+ [Description("Lay the scene image's glowing-edges outline over this output in the preview.")]
+ public bool Overlay
+ {
+ get => _overlay;
+ set => SetProperty(ref _overlay, value);
+ }
+
+ /// <summary>Multiplier of the outline's brightness, 0 to <see cref="MaxOverlayGain"/>; 1 shows the edge picture as computed, 0 hides it.</summary>
+ [XmlAttribute]
+ [DefaultValue(DefaultOverlayGain)]
+ [Category("Scene outline")]
+ [DisplayName("Outline brightness")]
+ [Description("Multiplier of the outline: 1 as computed, higher lifts faint edges, 0 hides it.")]
+ public double OverlayGain
+ {
+ get => _overlayGain;
+ set => SetProperty(ref _overlayGain, value);
+ }
+
+ /// <summary>Whether an export bakes the outline into this output's frames (additively, as the author's program does); off by default.</summary>
+ [XmlAttribute]
+ [DefaultValue(false)]
+ [Category("Scene outline")]
+ [DisplayName("Outline in the export")]
+ [Description("Bake the outline into exported frames and videos of this output.")]
+ public bool OverlayInExport
+ {
+ get => _overlayInExport;
+ set => SetProperty(ref _overlayInExport, value);
+ }
+
/// <summary>Clamps every value into its valid range; an empty scheme name falls back to <paramref name="defaultScheme"/>.</summary>
public void Normalize(string defaultScheme)
{
@@ -173,6 +222,7 @@ public sealed class DisplayLayer : ObservableObject
}
Brightness = Math.Clamp(Brightness, 1e-4, 1e5);
BlackLevel = Math.Clamp(BlackLevel, -10.0, 1.0);
+ OverlayGain = Math.Clamp(OverlayGain, 0.0, MaxOverlayGain);
}
/// <summary>The colour scheme name, for display in a property grid.</summary>
diff --git a/WaveDude/Rendering/GlowingEdges.cs b/WaveDude/Rendering/GlowingEdges.cs
new file mode 100644
index 0000000..fc99c08
--- /dev/null
+++ b/WaveDude/Rendering/GlowingEdges.cs
@@ -0,0 +1,98 @@
+namespace WaveDude.Rendering;
+
+/// <summary>
+/// The author's "glowing edges" picture of a scene image (ported 2026-10-13 from <c>Form1.vb</c>,
+/// <c>ComputeGlowingEdges</c> / <c>ComposeGlowOverlay</c>): a same-size picture that is black except
+/// along edges, where each channel holds how sharply that channel changes there (a Sobel magnitude
+/// times <see cref="Scale"/>, clamped to a byte), so a hard red-to-black edge lights up in red, the way
+/// Photoshop's Glowing Edges filter does. The outermost ring of pixels stays black (no full 3×3
+/// neighbourhood). The preview lays this over the pictures as a semi-transparent layer; an export bakes
+/// it in additively with <see cref="BlendAdditive"/>, as his program does. Pure functions, any thread.
+/// </summary>
+public static class GlowingEdges
+{
+ /// <summary>
+ /// The author's brightness knob: a full black-to-white edge gives a raw Sobel magnitude of about 1442,
+ /// and 0.25 brings that into the byte range without every ordinary edge saturating to white.
+ /// </summary>
+ public const double Scale = 0.25;
+
+ /// <summary>
+ /// The edge picture of a BGRA image as BGRA bytes (alpha 255), <paramref name="width"/> × <paramref name="height"/>,
+ /// tightly packed (stride = width × 4). An image smaller than 3 × 3 gives all black.
+ /// </summary>
+ /// <param name="bgra">The scene image's pixels, BGRA, <paramref name="strideBytes"/> bytes per row.</param>
+ /// <param name="width">Width in pixels.</param>
+ /// <param name="height">Height in pixels.</param>
+ /// <param name="strideBytes">Bytes per source row (at least width × 4).</param>
+ public static byte[] Compute(ReadOnlySpan<byte> bgra, int width, int height, int strideBytes)
+ {
+ var result = new byte[width * height * 4];
+ for (int i = 3; i < result.Length; i += 4)
+ {
+ result[i] = 255;
+ }
+ if (width < 3 || height < 3)
+ {
+ return result;
+ }
+ for (int y = 1; y < height - 1; y++)
+ {
+ int rowUp = (y - 1) * strideBytes;
+ int rowMid = y * strideBytes;
+ int rowDown = (y + 1) * strideBytes;
+ int dstRow = y * width * 4;
+ for (int x = 1; x < width - 1; x++)
+ {
+ int cUp = rowUp + (x - 1) * 4;
+ int cMid = rowMid + (x - 1) * 4;
+ int cDown = rowDown + (x - 1) * 4;
+ int dst = dstRow + x * 4;
+ for (int channel = 0; channel < 3; channel++)
+ {
+ int p00 = bgra[cUp + channel];
+ int p01 = bgra[cUp + 4 + channel];
+ int p02 = bgra[cUp + 8 + channel];
+ int p10 = bgra[cMid + channel];
+ int p12 = bgra[cMid + 8 + channel];
+ int p20 = bgra[cDown + channel];
+ int p21 = bgra[cDown + 4 + channel];
+ int p22 = bgra[cDown + 8 + channel];
+ int gx = (p02 + 2 * p12 + p22) - (p00 + 2 * p10 + p20);
+ int gy = (p20 + 2 * p21 + p22) - (p00 + 2 * p01 + p02);
+ double magnitude = Math.Sqrt((double)gx * gx + (double)gy * gy) * Scale;
+ result[dst + channel] = (byte)Math.Min(255.0, magnitude);
+ }
+ }
+ }
+ return result;
+ }
+
+ /// <summary>
+ /// Bakes the edge picture into a rendered frame the author's way: each channel becomes
+ /// min(255, frame + edge × <paramref name="gain"/>), so black edge pixels leave the frame alone at any
+ /// gain and the picture never gets lighter where there is no edge. For the export (opt-in per layer,
+ /// <c>DisplayLayer.OverlayInExport</c>); the preview composites a translucent layer instead.
+ /// </summary>
+ /// <param name="frameArgb">The frame's pixels, packed <c>0xAARRGGBB</c>, width × height, modified in place.</param>
+ /// <param name="width">Width in pixels of both.</param>
+ /// <param name="height">Height in pixels of both.</param>
+ /// <param name="edgesBgra">The picture from <see cref="Compute"/> (tightly packed BGRA).</param>
+ /// <param name="gain">Multiplier of the edge picture; 0 changes nothing.</param>
+ public static void BlendAdditive(Span<int> frameArgb, int width, int height, ReadOnlySpan<byte> edgesBgra, double gain)
+ {
+ if (gain <= 0.0)
+ {
+ return;
+ }
+ int count = width * height;
+ for (int i = 0; i < count; i++)
+ {
+ int argb = frameArgb[i];
+ int b = Math.Min(255, (argb & 0xFF) + (int)(edgesBgra[i * 4] * gain));
+ int g = Math.Min(255, ((argb >> 8) & 0xFF) + (int)(edgesBgra[i * 4 + 1] * gain));
+ int r = Math.Min(255, ((argb >> 16) & 0xFF) + (int)(edgesBgra[i * 4 + 2] * gain));
+ frameArgb[i] = unchecked((int)0xFF000000) | (r << 16) | (g << 8) | b;
+ }
+ }
+}