Files
OpenNest/OpenNest/Forms/CutSimulatorForm.cs
T

583 lines
25 KiB
C#

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using OpenNest.CNC;
using OpenNest.CNC.Thermal;
using OpenNest.Controls;
using OpenNest.Data;
using OpenNest.Desktop;
using OpenNest.Desktop.Interaction;
using OpenNest.Support;
using NumericUpDown = OpenNest.Controls.NumericUpDown;
namespace OpenNest.Forms
{
/// <summary>
/// Playback controls for a <see cref="CutSimulationOverlay"/> on a nest's plate view. Follows
/// the current plate and rebuilds the timeline when parts are added, removed or resequenced.
/// While it is open the nest is view-only, as in Plan Cutting: the canvas pans and zooms and
/// plates can be stepped through, but nothing that edits is enabled.
/// </summary>
public sealed class CutSimulatorForm : Form
{
private const int TrackResolution = 1000;
private static readonly IReadOnlyList<double> Speeds = CutSimulationPlayback.Speeds;
private readonly EditNestForm nestForm;
private readonly CutSimulationOverlay overlay;
private readonly Button restartButton, playButton, endButton;
private readonly Button previousPartButton, previousContourButton, nextContourButton, nextPartButton;
private readonly ComboBox speedBox;
private readonly TrackBar trackBar;
private readonly Label timeLabel, partLabel, drawingLabel, stateLabel;
private readonly NumericUpDown feedBox, holeFeedBox, rapidBox, pierceBox;
private readonly CheckBox skipEtchBox;
private readonly MachineConfig machine;
private readonly Label machineLabel;
private readonly ComboBox heatBox;
private readonly NumericUpDown heatPowerBox;
private readonly Label heatLabel;
private readonly TabControl tabs;
private readonly TableLayoutPanel jumps;
private readonly ValidationInspectionScope scope;
private Plate plate;
private bool updatingTrack;
private bool rebuildQueued;
public CutSimulatorForm(EditNestForm nestForm)
{
this.nestForm = nestForm;
overlay = nestForm.PlateView.CutSimulation;
Text = "Cut Simulator";
// Fixed size: the window fits its controls once and never follows the status text.
FormBorderStyle = FormBorderStyle.FixedToolWindow;
MaximizeBox = MinimizeBox = false;
StartPosition = FormStartPosition.Manual;
ShowInTaskbar = false;
KeyPreview = true;
MinimumSize = new Size(420, 0);
AutoScaleMode = AutoScaleMode.Dpi;
AutoSize = true;
AutoSizeMode = AutoSizeMode.GrowAndShrink;
restartButton = TransportButton("⏮", 44, 12f);
playButton = TransportButton("▶", 80, 18f);
endButton = TransportButton("⏭", 44, 12f);
speedBox = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = 70, Anchor = AnchorStyles.Left };
foreach (var speed in Speeds)
speedBox.Items.Add(CutSimulationStatus.SpeedText(speed));
speedBox.SelectedIndex = CutSimulationPlayback.DefaultSpeedIndex;
previousPartButton = JumpButton("◀◀ Part");
previousContourButton = JumpButton("◀ Cutout");
nextContourButton = JumpButton("Cutout ▶");
nextPartButton = JumpButton("Part ▶▶");
// Four equal columns, inset in OnLoad so the row spans exactly the slider's track.
jumps = new TableLayoutPanel { AutoSize = true, Dock = DockStyle.Fill, ColumnCount = 4 };
for (var i = 0; i < 4; i++)
jumps.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25));
jumps.Controls.AddRange(new Control[] { previousPartButton, previousContourButton, nextContourButton, nextPartButton });
var transport = new FlowLayoutPanel { AutoSize = true, Dock = DockStyle.Fill, WrapContents = false };
transport.Controls.AddRange(new Control[]
{
restartButton,
playButton,
endButton,
new Label { Text = "Speed", AutoSize = true, Anchor = AnchorStyles.Left, Margin = new Padding(12, 0, 0, 0) },
speedBox,
});
trackBar = new TrackBar
{
Dock = DockStyle.Fill,
AutoSize = false,
Height = 30,
Maximum = TrackResolution,
TickStyle = TickStyle.None,
LargeChange = TrackResolution / 20,
SmallChange = 1,
};
// One labeled row per value, each spanning the window, so the status never widens
// it. Drawing names get two lines; longer ones trim and show in full on hover.
timeLabel = StatusValue(1);
timeLabel.Font = new Font(Font, FontStyle.Bold);
partLabel = StatusValue(1);
drawingLabel = StatusValue(2);
stateLabel = StatusValue(1);
heatBox = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = 110, Anchor = AnchorStyles.Left };
heatBox.Items.AddRange(new object[] { "Off", "Now", "Peak so far" });
heatBox.SelectedIndex = 0;
heatLabel = StatusValue(2);
var status = StatusTable();
status.Controls.AddRange(new Control[]
{
StatusCaption("Part"), partLabel,
StatusCaption("Drawing"), drawingLabel,
StatusCaption("Motion"), stateLabel,
StatusCaption("Heat"), heatBox,
});
status.Controls.Add(heatLabel);
status.SetColumnSpan(heatLabel, 2);
// The time stays in view on both tabs, so a new feed's effect shows as it is typed.
var timeRow = StatusTable();
timeRow.Controls.AddRange(new Control[] { StatusCaption("Time"), timeLabel });
// The inputs live on their own tab; the machine is the nest's (Nest > Machine).
var units = nestForm.Nest.Units;
var rateSuffix = " " + UnitsHelper.GetShortTimeUnitPair(units);
var saved = SavedCutParameters.Load(units);
machine = MachineSettings.FindMachine(nestForm.Nest.Machine);
machineLabel = new Label
{
Text = machine?.Name ?? "None (full speed)",
AutoSize = true,
Margin = new Padding(3, 7, 3, 3),
Anchor = AnchorStyles.Left,
};
feedBox = NewNumber((decimal)saved.Feedrate, 1, 9999, 0, rateSuffix);
holeFeedBox = NewNumber((decimal)(saved.HoleFeedrate ?? saved.Feedrate), 1, 9999, 0, rateSuffix);
rapidBox = NewNumber((decimal)saved.RapidTravelRate, 1, 9999, 0, rateSuffix);
pierceBox = NewNumber((decimal)saved.PierceTime.TotalSeconds, 0, 999, 1, " s");
heatPowerBox = NewNumber(1000, 50, 20000, 0, " W");
heatPowerBox.Increment = 100;
skipEtchBox = new CheckBox
{
Text = "Skip etch-only contours",
Checked = saved.SkipScribe,
AutoSize = true,
Margin = new Padding(3, 6, 3, 3),
};
var settings = new TableLayoutPanel { AutoSize = true, ColumnCount = 4, Padding = new Padding(3, 6, 3, 3) };
settings.Controls.Add(RateLabel("Machine"));
settings.Controls.Add(machineLabel);
settings.SetColumnSpan(machineLabel, 3);
settings.Controls.AddRange(new Control[]
{
RateLabel("Outside feed"), feedBox,
RateLabel("Hole feed"), holeFeedBox,
RateLabel("Rapid"), rapidBox,
RateLabel("Pierce"), pierceBox,
RateLabel("Heat input"), heatPowerBox,
});
settings.Controls.Add(skipEtchBox);
settings.SetColumnSpan(skipEtchBox, 2);
status.Padding = new Padding(3, 6, 3, 3);
tabs = new TabControl { Dock = DockStyle.Fill, Margin = new Padding(3, 6, 3, 3) };
tabs.TabPages.AddRange(new[] { NewTabPage("Status", status), NewTabPage("Settings", settings) });
var layout = new TableLayoutPanel
{
Dock = DockStyle.Fill,
AutoSize = true,
ColumnCount = 1,
Padding = new Padding(6),
};
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
// The timeline leads, as in a media player; the buttons that drive it sit below.
layout.Controls.Add(trackBar);
layout.Controls.Add(timeRow);
layout.Controls.Add(transport);
layout.Controls.Add(jumps);
layout.Controls.Add(tabs);
Controls.Add(layout);
restartButton.Click += (_, _) => overlay.Step(p => p.Restart());
endButton.Click += (_, _) => overlay.Step(p => p.End());
playButton.Click += (_, _) => TogglePlay();
previousPartButton.Click += (_, _) => overlay.Step(p => p.PreviousPart());
previousContourButton.Click += (_, _) => overlay.Step(p => p.PreviousContour());
nextContourButton.Click += (_, _) => overlay.Step(p => p.NextContour());
nextPartButton.Click += (_, _) => overlay.Step(p => p.NextPart());
speedBox.SelectedIndexChanged += (_, _) => overlay.Speed = Speeds[speedBox.SelectedIndex];
trackBar.Scroll += (_, _) => Seek();
feedBox.ValueChanged += (_, _) => Rebuild();
holeFeedBox.ValueChanged += (_, _) => Rebuild();
skipEtchBox.CheckedChanged += (_, _) => Rebuild();
rapidBox.ValueChanged += (_, _) => Rebuild();
pierceBox.ValueChanged += (_, _) => Rebuild();
heatBox.SelectedIndexChanged += (_, _) =>
{
overlay.HeatMode = (HeatView)heatBox.SelectedIndex;
Rebuild();
};
heatPowerBox.ValueChanged += (_, _) => Rebuild();
var tips = new ToolTip();
tips.SetToolTip(restartButton, "Restart");
tips.SetToolTip(playButton, "Play / pause (Space)");
tips.SetToolTip(endButton, "Jump to end");
tips.SetToolTip(previousPartButton, "Back to the start of this part, or the part before (Page Up)");
tips.SetToolTip(previousContourButton, "Back to the start of this cutout or perimeter, or the one before (Ctrl+Left)");
tips.SetToolTip(nextContourButton, "Next cutout or perimeter (Ctrl+Right)");
tips.SetToolTip(nextPartButton, "Next part (Page Down)");
tips.SetToolTip(feedBox, "Feed for outside contours and cut-offs (the CI Fiber post's exterior, L4)");
tips.SetToolTip(holeFeedBox, "Feed for holes and other interior contours (the CI Fiber post's interior, L2)");
tips.SetToolTip(skipEtchBox, "Leave out contours that only etch, as the CI Fiber post does by default");
tips.SetToolTip(machineLabel, "The nest's machine, whose acceleration limits time the moves (Nest > Machine)");
tips.SetToolTip(heatBox, "Estimated heat in the sheet: now, or the hottest each area has been so far");
tips.SetToolTip(heatPowerBox, "Torch power that stays in the sheet as heat (an estimate; most of the beam leaves with the melt)");
tips.SetToolTip(trackBar, "Drag to scrub through the cut (Left/Right step one move)");
overlay.Speed = Speeds[speedBox.SelectedIndex];
overlay.Changed += Overlay_Changed;
nestForm.PlateChanged += NestForm_PlateChanged;
nestForm.FormClosed += NestForm_FormClosed;
AttachPlate(nestForm.PlateView.Plate);
Rebuild();
scope = new ValidationInspectionScope(nestForm, Close, nestForm.PlateNavigation);
nestForm.PlateView.InspectionCloseRequested = Close;
}
private static NumericUpDown NewNumber(decimal value, decimal min, decimal max, int decimals, string suffix) =>
new()
{
Minimum = min,
Maximum = max,
DecimalPlaces = decimals,
Increment = decimals == 0 ? 10 : 0.1m,
Value = System.Math.Clamp(value, min, max),
Suffix = suffix,
Width = 110,
};
private static Button TransportButton(string glyph, int width, float fontSize) =>
new()
{
Text = glyph,
AutoSize = false,
Size = new Size(width, 40),
Font = new Font("Segoe UI Symbol", fontSize),
Anchor = AnchorStyles.Left,
};
// Stretched across an equal column; a fixed height so the row never grows to fill.
private static Button JumpButton(string text)
{
var button = new Button { Text = text, AutoSize = false, Anchor = AnchorStyles.Left | AnchorStyles.Right };
button.Size = new Size(80, button.GetPreferredSize(Size.Empty).Height);
return button;
}
private static TableLayoutPanel StatusTable()
{
var table = new TableLayoutPanel { AutoSize = true, Dock = DockStyle.Fill, ColumnCount = 2 };
table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
return table;
}
private static TabPage NewTabPage(string text, Control content)
{
var page = new TabPage(text) { UseVisualStyleBackColor = true };
content.Dock = DockStyle.Top;
page.Controls.Add(content);
return page;
}
// A tab control never sizes to its pages, so once the handle exists (and DPI scaling is
// done) it is given room for the larger page. Fixed after that: switching tabs or new
// status text never resizes the window.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
var inner = tabs.DisplayRectangle.Size;
var chrome = tabs.Size - inner;
var width = 0;
var height = 0;
foreach (TabPage page in tabs.TabPages)
{
var size = page.Controls[0].GetPreferredSize(new Size(inner.Width, 0));
width = System.Math.Max(width, size.Width);
height = System.Math.Max(height, size.Height);
}
tabs.MinimumSize = new Size(width + chrome.Width, height + chrome.Height);
tabs.Height = tabs.MinimumSize.Height;
AlignJumpsToTrack();
trackBar.SizeChanged += (_, _) => AlignJumpsToTrack();
}
// Insets the jump row so its outer button edges meet the ends of the slider's track line.
private void AlignJumpsToTrack()
{
if (!trackBar.IsHandleCreated)
return;
var channel = new NativeRect();
SendMessage(trackBar.Handle, TbmGetChannelRect, IntPtr.Zero, ref channel);
var start = trackBar.PointToScreen(new Point(channel.Left, 0)).X;
var end = trackBar.PointToScreen(new Point(channel.Right, 0)).X;
var row = jumps.RectangleToScreen(jumps.ClientRectangle);
var margin = previousPartButton.Margin.Left;
var left = System.Math.Max(0, start - row.Left - margin);
var right = System.Math.Max(0, row.Right - end - margin);
if (jumps.Padding.Left != left || jumps.Padding.Right != right)
jumps.Padding = new Padding(left, 0, right, 0);
}
private const int TbmGetChannelRect = 0x0400 + 26;
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
private struct NativeRect
{
public int Left, Top, Right, Bottom;
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref NativeRect lParam);
private static Label StatusCaption(string text) =>
new() { Text = text, AutoSize = true, ForeColor = SystemColors.GrayText, Margin = new Padding(3, 2, 8, 2) };
// Fixed height so changing text never resizes the window.
private Label StatusValue(int lines) =>
new BufferedLabel
{
AutoSize = false,
AutoEllipsis = true,
Dock = DockStyle.Fill,
Width = 40,
Height = Font.Height * lines + 2,
Margin = new Padding(3, 2, 3, 2),
};
private static Label RateLabel(string text) =>
new() { Text = text, AutoSize = true, Margin = new Padding(3, 7, 0, 0), Anchor = AnchorStyles.Left };
private CutParameters GetCutParameters() =>
CutTimeEntry.Parameters(feedBox.Value, holeFeedBox.Value, rapidBox.Value, pierceBox.Value,
skipEtchBox.Checked, nestForm.Nest.Units, machine);
private void Rebuild()
{
if (plate == null)
{
overlay.Clear();
return;
}
overlay.Load(CutSimulation.Build(plate, GetCutParameters()));
LoadHeat();
}
// The colors are scaled to the hottest any cell gets over the whole cut.
private void LoadHeat()
{
heatLabel.Text = "";
if (heatBox.SelectedIndex == 0 || overlay.Simulation == null)
return;
var nest = nestForm.Nest;
if (!(nest.Thickness > 0))
{
heatLabel.Text = "Set the nest's thickness to estimate heat.";
return;
}
var material = ThermalMaterial.ForName($"{nest.Material?.Name} {nest.Material?.Grade}");
var heat = new PlateHeatSimulation(plate, overlay.Simulation, new ThermalParameters
{
Material = material,
Thickness = nest.Thickness,
Units = nest.Units,
AbsorbedPower = (double)heatPowerBox.Value,
SupportBed = plate.SupportBed,
});
heat.RunToEnd();
// Pierces leave single very hot cells; scaling to them would wash out the areas
// where heat builds up, so red is the hottest half percent of the sheet instead.
var peaks = new List<float>();
for (var i = 0; i < heat.Peaks.Length; i++)
{
if (!heat.IsRemoved(i) && heat.Peaks[i] > 0)
peaks.Add(heat.Peaks[i]);
}
peaks.Sort();
var scale = peaks.Count == 0 ? 1f : peaks[(int)(0.995 * (peaks.Count - 1))];
heat.Reset();
overlay.LoadHeat(heat, scale);
var cooling = !heat.UsesSupportBed ? "cooled by air only (no support bed)"
: plate.SupportBed is SupportSlats ? "cooled by air and slats" : "cooled by air and the support grid";
heatScaleText = $"{material.Name}, {cooling}; red is {scale:0} °C above ambient";
UpdateHeatLabel(force: true);
}
private string heatScaleText = "";
// While playing, the hottest temperature would change every frame, too fast to read.
private const long HeatLabelIntervalMs = 1000;
private long heatLabelUpdatedAt;
private void UpdateHeatLabel(bool force = false)
{
var heat = overlay.Heat;
if (heat == null || heatBox.SelectedIndex == 0)
return;
var now = Environment.TickCount64;
if (!force && overlay.IsPlaying && now - heatLabelUpdatedAt < HeatLabelIntervalMs)
return;
heatLabelUpdatedAt = now;
heat.AdvanceTo(overlay.Time);
var values = heatBox.SelectedIndex == 2 ? heat.Peaks : heat.Temperatures;
var hottest = PlateHeatSimulation.IndexOfMax(values);
var hottestNow = hottest < 0 ? 0 : values[hottest];
heatLabel.Text = $"Hottest {hottestNow:0} °C (estimated)\n{heatScaleText}";
}
private void AttachPlate(Plate value)
{
if (plate != null)
{
plate.PartAdded -= Plate_PartsChanged;
plate.PartRemoved -= Plate_PartsChanged;
plate.PartsReordered -= Plate_PartsChanged;
}
plate = value;
if (plate != null)
{
plate.PartAdded += Plate_PartsChanged;
plate.PartRemoved += Plate_PartsChanged;
plate.PartsReordered += Plate_PartsChanged;
}
}
// A fill adds parts one at a time; rebuild once after the batch.
private void Plate_PartsChanged(object sender, EventArgs e)
{
if (rebuildQueued || !IsHandleCreated)
return;
rebuildQueued = true;
BeginInvoke(() =>
{
rebuildQueued = false;
if (!IsDisposed)
Rebuild();
});
}
private void NestForm_PlateChanged(object sender, EventArgs e)
{
if (nestForm.PlateView.Plate == plate)
return;
AttachPlate(nestForm.PlateView.Plate);
overlay.Pause();
overlay.Clear();
Rebuild();
}
private void NestForm_FormClosed(object sender, FormClosedEventArgs e) => Close();
// Parts may have moved since the timeline was built; moves raise no plate event.
private void TogglePlay() => overlay.Step(p => p.TogglePlay(Rebuild));
private void Seek()
{
if (updatingTrack || overlay.Simulation == null)
return;
overlay.Step(p => p.Seek((double)trackBar.Value / TrackResolution));
}
private void StepMove(int direction) => overlay.Step(p => p.StepMove(direction));
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (ActiveControl is not System.Windows.Forms.NumericUpDown and not ComboBox)
{
switch (keyData)
{
case Keys.Escape:
Close();
return true;
case Keys.Space:
TogglePlay();
return true;
case Keys.Control | Keys.Right:
overlay.Step(p => p.NextContour());
return true;
case Keys.Control | Keys.Left:
overlay.Step(p => p.PreviousContour());
return true;
case Keys.PageDown:
overlay.Step(p => p.NextPart());
return true;
case Keys.PageUp:
overlay.Step(p => p.PreviousPart());
return true;
case Keys.Right:
StepMove(1);
return true;
case Keys.Left:
StepMove(-1);
return true;
case Keys.Home:
overlay.Step(p => p.Restart());
return true;
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void Overlay_Changed(object sender, EventArgs e)
{
if (IsDisposed)
return;
var sim = overlay.Simulation;
playButton.Text = overlay.IsPlaying ? "⏸" : "▶";
var status = CutSimulationStatus.For(overlay.Playback, plate, nestForm.Nest.Units);
timeLabel.Text = status.Time;
partLabel.Text = status.Part;
drawingLabel.Text = status.Drawing;
stateLabel.Text = status.Motion;
UpdateHeatLabel();
SetTrack(sim is { Steps.Count: > 0 } && sim.TotalTime > TimeSpan.Zero
? (int)System.Math.Round(TrackResolution * (overlay.Time / sim.TotalTime))
: 0);
}
private void SetTrack(int value)
{
updatingTrack = true;
trackBar.Value = System.Math.Clamp(value, trackBar.Minimum, trackBar.Maximum);
updatingTrack = false;
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
SavedCutParameters.Save(GetCutParameters());
overlay.Changed -= Overlay_Changed;
nestForm.PlateChanged -= NestForm_PlateChanged;
nestForm.FormClosed -= NestForm_FormClosed;
AttachPlate(null);
if (!nestForm.PlateView.IsDisposed)
{
overlay.Clear();
nestForm.PlateView.InspectionCloseRequested = null;
}
base.OnFormClosed(e);
// Unlock after the editor has forgotten this form, then finish a close it held up.
scope.Dispose();
scope.ResumeHostClose();
}
// Playback rewrites the status every frame; a plain label erases before it redraws, so it flashes.
private sealed class BufferedLabel : Label
{
public BufferedLabel()
{
DoubleBuffered = true;
}
}
}
}