Files
OpenNest/OpenNest/Forms/CutSimulatorForm.cs
T
ajandClaude Opus 5.5 41e8e9496f feat(simulator): lose plate heat into the support slats
The heat model now loses heat through the bottom face into the bed the
sheet rests on when ThermalParameters.SupportBed is given. Each cell gets
the share of its area over a slat's top (SupportSlats.SlatsIn) or a grid
point's square pad (SupportGrid.PointsIn, GridContactSize), placed for the
plate's quadrant and computed by overlap rather than snapped to cells.
That share times ContactCoefficient (200 W/m2K by default, an effective
estimate to calibrate; slats get no temperature of their own) is added to
the air loss as a per-cell exponential decay, which stays stable. Without
a bed the model is unchanged. The Cut Simulator passes the plate's bed and
says in the heat label whether slats or the grid cool the sheet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:47:25 -05:00

485 lines
21 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.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 CutTimeMachineBox machineBox;
private readonly ComboBox heatBox;
private readonly NumericUpDown heatPowerBox;
private readonly Label heatLabel;
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 ▶▶");
var jumps = new FlowLayoutPanel { AutoSize = true, Dock = DockStyle.Fill, WrapContents = false };
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);
var status = new TableLayoutPanel { AutoSize = true, Dock = DockStyle.Fill, ColumnCount = 2 };
status.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
status.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
status.Controls.AddRange(new Control[]
{
StatusCaption("Time"), timeLabel,
StatusCaption("Part"), partLabel,
StatusCaption("Drawing"), drawingLabel,
StatusCaption("Motion"), stateLabel,
});
var units = nestForm.Nest.Units;
var rateSuffix = " " + UnitsHelper.GetShortTimeUnitPair(units);
var saved = SavedCutParameters.Load(units);
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");
var rates = new TableLayoutPanel { AutoSize = true, Dock = DockStyle.Fill, ColumnCount = 4 };
rates.Controls.AddRange(new Control[]
{
RateLabel("Outside feed"), feedBox,
RateLabel("Hole feed"), holeFeedBox,
RateLabel("Rapid"), rapidBox,
RateLabel("Pierce"), pierceBox,
});
machineBox = new CutTimeMachineBox();
skipEtchBox = new CheckBox
{
Text = "Skip etch-only contours",
Checked = saved.SkipScribe,
AutoSize = true,
Margin = new Padding(12, 6, 3, 3),
};
var motion = new FlowLayoutPanel { AutoSize = true, Dock = DockStyle.Fill, WrapContents = true };
motion.Controls.AddRange(new Control[] { RateLabel("Acceleration"), machineBox, skipEtchBox });
heatBox = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = 110, Anchor = AnchorStyles.Left };
heatBox.Items.AddRange(new object[] { "Off", "Now", "Peak so far" });
heatBox.SelectedIndex = 0;
heatPowerBox = NewNumber(1000, 50, 20000, 0, " W");
heatPowerBox.Increment = 100;
var heatRow = new FlowLayoutPanel { AutoSize = true, Dock = DockStyle.Fill, WrapContents = true };
heatRow.Controls.AddRange(new Control[] { RateLabel("Heat"), heatBox, RateLabel("Into plate"), heatPowerBox });
heatLabel = StatusValue(2);
var layout = new TableLayoutPanel
{
Dock = DockStyle.Fill,
AutoSize = true,
ColumnCount = 1,
Padding = new Padding(6),
};
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
layout.Controls.Add(transport);
layout.Controls.Add(jumps);
layout.Controls.Add(trackBar);
layout.Controls.Add(status);
layout.Controls.Add(rates);
layout.Controls.Add(motion);
layout.Controls.Add(heatRow);
layout.Controls.Add(heatLabel);
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();
machineBox.SelectedIndexChanged += (_, _) => 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(machineBox, "Machine whose acceleration limits time the moves (Tools > Machine Configuration)");
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,
};
private static Button JumpButton(string text) =>
new() { Text = text, AutoSize = true, MinimumSize = new Size(80, 0) };
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, machineBox.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();
}
private string heatScaleText = "";
private void UpdateHeatLabel()
{
var heat = overlay.Heat;
if (heat == null || heatBox.SelectedIndex == 0)
return;
heat.AdvanceTo(overlay.Time);
var values = heatBox.SelectedIndex == 2 ? heat.Peaks : heat.Temperatures;
var hottest = PlateHeatSimulation.IndexOfMax(values);
var now = hottest < 0 ? 0 : values[hottest];
heatLabel.Text = $"Hottest {now: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());
machineBox.SaveChoice();
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;
}
}
}
}