From 1403517184ec2ae6bd777d3f6d603274601e6c65 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Mon, 30 Nov 2026 22:07:20 -0500 Subject: [PATCH] feat(simulator): estimate plate heat buildup during a cut Add PlateHeatSimulation, a grid model driven by the cut simulation's timed moves: cutting and piercing add absorbed power under the torch, heat conducts within each piece and is lost from both faces. Finished cutouts drop their slug and its heat; a finished outside contour cuts the part free of the skeleton so no heat crosses the kerf. The Cut Simulator gains a Heat layer (Now / Peak so far) with the absorbed power as an input, colored against the 99.5th percentile so single-cell pierce spikes don't wash out area buildup. Temperatures are relative estimates for comparing cut orders; see docs/plate-heat-map.md. Co-Authored-By: Claude Opus 5.5 --- .../CNC/Thermal/PlateHeatSimulation.cs | 387 ++++++++++++++++++ OpenNest.Core/CNC/Thermal/ThermalMaterial.cs | 35 ++ .../CNC/Thermal/ThermalParameters.cs | 30 ++ .../CNC/PlateHeatSimulationTests.cs | 194 +++++++++ OpenNest/Controls/CutSimulationOverlay.cs | 134 ++++++ OpenNest/Forms/CutSimulatorForm.cs | 78 ++++ docs/plate-heat-map.md | 34 ++ 7 files changed, 892 insertions(+) create mode 100644 OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs create mode 100644 OpenNest.Core/CNC/Thermal/ThermalMaterial.cs create mode 100644 OpenNest.Core/CNC/Thermal/ThermalParameters.cs create mode 100644 OpenNest.Tests/CNC/PlateHeatSimulationTests.cs create mode 100644 docs/plate-heat-map.md diff --git a/OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs b/OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs new file mode 100644 index 00000000..137884c6 --- /dev/null +++ b/OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs @@ -0,0 +1,387 @@ +using System; +using System.Collections.Generic; +using OpenNest.Geometry; + +namespace OpenNest.CNC.Thermal +{ + /// + /// Estimates how heat builds up and spreads in the sheet while a + /// plays: a grid of cells over the plate, each holding its temperature rise above ambient in + /// kelvin. Cutting and piercing add the absorbed power along the torch's path, heat conducts + /// to neighboring cells of the same piece and is lost to the air from both faces. + /// + /// The pieces change as contours close: a cutout's slug falls away with its heat, and a + /// part's perimeter separates the part from the skeleton so no heat crosses the kerf. That is + /// what traps heat in narrow skeleton webs. Edges are insulated. Values are relative + /// estimates for comparing cut orders, not calibrated temperatures; see + /// docs/plate-heat-map.md. + /// + /// + public sealed class PlateHeatSimulation + { + private const int Removed = -1; + private const double ArcStepRadians = System.Math.PI / 18; + private const int MaxCells = 400_000; + private const int MaxSamplesPerStep = 10_000; + + // Explicit diffusion is stable below a quarter on a square grid; the cap keeps timing + // fine enough that playback shows heat arrive with the torch. + private const double StabilityFactor = 0.2; + private const double MaxStepSeconds = 1.0; + + private readonly List deposits = new(); + private readonly List events = new(); + private readonly int[] region; + private float[] temperature; + private float[] next; + private readonly float[] peak; + private readonly double diffusionRate; + private readonly double lossRate; + private readonly double maxStep; + private int depositCursor; + private int eventCursor; + private int nextRegion; + private double time; + + public PlateHeatSimulation(Plate plate, CutSimulation simulation, ThermalParameters parameters) + { + ArgumentNullException.ThrowIfNull(plate); + ArgumentNullException.ThrowIfNull(simulation); + ArgumentNullException.ThrowIfNull(parameters); + if (!(parameters.Thickness > 0)) + throw new ArgumentOutOfRangeException(nameof(parameters), "The sheet thickness must be positive."); + + Simulation = simulation; + Parameters = parameters; + + var bounds = plate.BoundingBox(includeParts: false); + var cell = parameters.EffectiveCellSize; + while (CellCount(bounds, cell) > MaxCells) + cell *= 1.25; + CellSize = cell; + OriginX = bounds.X; + OriginY = bounds.Y; + Columns = System.Math.Max(1, (int)System.Math.Ceiling(bounds.Length / cell)); + Rows = System.Math.Max(1, (int)System.Math.Ceiling(bounds.Width / cell)); + + var count = Columns * Rows; + region = new int[count]; + temperature = new float[count]; + next = new float[count]; + peak = new float[count]; + + var metersPerUnit = parameters.MetersPerUnit; + var dx = cell * metersPerUnit; + var thickness = parameters.Thickness * metersPerUnit; + var material = parameters.Material; + var volumetricHeat = material.Density * material.SpecificHeat; + diffusionRate = material.Diffusivity / (dx * dx); + lossRate = 2 * parameters.SurfaceCoefficient / (volumetricHeat * thickness); + maxStep = System.Math.Min(MaxStepSeconds, StabilityFactor / diffusionRate); + + BuildDeposits(parameters.AbsorbedPower / (volumetricHeat * thickness * dx * dx)); + BuildPieceEvents(); + Reset(); + } + + public CutSimulation Simulation { get; } + public ThermalParameters Parameters { get; } + + public int Columns { get; } + public int Rows { get; } + + /// Lower-left corner of cell (0, 0) in plate coordinates. + public double OriginX { get; } + public double OriginY { get; } + + /// Cell edge in the plate's units (larger than asked for on very large sheets). + public double CellSize { get; } + + /// How far the model has run. + public TimeSpan Time => TimeSpan.FromSeconds(time); + + /// Temperature rise of each cell now, row by row from the bottom; zero where material fell away. + public ReadOnlySpan Temperatures => temperature; + + /// The highest rise each cell has reached so far. + public ReadOnlySpan Peaks => peak; + + /// True for a cell whose material fell away as a slug. + public bool IsRemoved(int index) => region[index] == Removed; + + /// The cell holding , or -1 off the grid. + public int CellAt(Vector point) + { + var column = (int)System.Math.Floor((point.X - OriginX) / CellSize); + var row = (int)System.Math.Floor((point.Y - OriginY) / CellSize); + if (column < 0 || row < 0 || column >= Columns || row >= Rows) + return -1; + return row * Columns + column; + } + + public Vector CellCenter(int index) => + new(OriginX + (index % Columns + 0.5) * CellSize, OriginY + (index / Columns + 0.5) * CellSize); + + /// Runs the model to , restarting first to go back in time. + public void AdvanceTo(TimeSpan target) + { + var seconds = target.TotalSeconds; + if (seconds < time) + Reset(); + while (time < seconds) + Step(System.Math.Min(maxStep, seconds - time)); + } + + /// Runs the whole cut, then more. + public void RunToEnd(TimeSpan cooling = default) => AdvanceTo(Simulation.TotalTime + cooling); + + public void Reset() + { + Array.Clear(temperature); + Array.Clear(peak); + Array.Clear(region); + depositCursor = 0; + eventCursor = 0; + nextRegion = 0; + time = 0; + } + + /// Index of the largest value, or -1 when every value is zero or less. + public static int IndexOfMax(ReadOnlySpan values) + { + var best = -1; + var max = 0f; + for (var i = 0; i < values.Length; i++) + { + if (values[i] > max) + { + max = values[i]; + best = i; + } + } + return best; + } + + private static long CellCount(Box bounds, double cell) => + (long)System.Math.Max(1, System.Math.Ceiling(bounds.Length / cell)) + * (long)System.Math.Max(1, System.Math.Ceiling(bounds.Width / cell)); + + private void Step(double seconds) + { + var end = time + seconds; + while (depositCursor < deposits.Count && deposits[depositCursor].Time <= end) + { + var deposit = deposits[depositCursor++]; + if (region[deposit.Cell] != Removed) + temperature[deposit.Cell] += deposit.Rise; + } + while (eventCursor < events.Count && events[eventCursor].Time <= end) + Apply(events[eventCursor++]); + + Diffuse(seconds); + time = end; + } + + private void Diffuse(double seconds) + { + var share = (float)(diffusionRate * seconds); + var keep = (float)System.Math.Exp(-lossRate * seconds); + var columns = Columns; + var current = temperature; + for (var row = 0; row < Rows; row++) + { + var rowStart = row * columns; + for (var column = 0; column < columns; column++) + { + var i = rowStart + column; + var piece = region[i]; + if (piece == Removed) + { + next[i] = 0; + continue; + } + + var t = current[i]; + var flow = 0f; + if (column > 0 && region[i - 1] == piece) + flow += current[i - 1] - t; + if (column < columns - 1 && region[i + 1] == piece) + flow += current[i + 1] - t; + if (row > 0 && region[i - columns] == piece) + flow += current[i - columns] - t; + if (row < Rows - 1 && region[i + columns] == piece) + flow += current[i + columns] - t; + + var value = (t + share * flow) * keep; + next[i] = value; + if (value > peak[i]) + peak[i] = value; + } + } + (temperature, next) = (next, temperature); + } + + private void Apply(PieceEvent piece) + { + // Only skeleton cells change: a part cut free earlier (one nested in this cutout) + // stays its own piece. + if (piece.IsCutout) + { + foreach (var cell in piece.Cells) + { + if (region[cell] == 0) + { + region[cell] = Removed; + temperature[cell] = 0; + } + } + return; + } + + var id = ++nextRegion; + foreach (var cell in piece.Cells) + { + if (region[cell] == 0) + region[cell] = id; + } + } + + // Heat goes in where the torch is, in proportion to the time it spends there. + private void BuildDeposits(double risePerSecond) + { + var spacing = CellSize / 2; + foreach (var step in Simulation.Steps) + { + var seconds = step.Duration.TotalSeconds; + if (seconds <= 0) + continue; + var start = step.StartTime.TotalSeconds; + + if (step.Kind == CutSimulationStepKind.Pierce) + { + AddDeposit(start + seconds / 2, step.Start, risePerSecond * seconds); + continue; + } + if (step.Kind != CutSimulationStepKind.Cut) + continue; + + var samples = (int)System.Math.Clamp(System.Math.Ceiling(step.Length / spacing), 1, MaxSamplesPerStep); + var rise = risePerSecond * seconds / samples; + for (var k = 0; k < samples; k++) + { + var fraction = (k + 0.5) / samples; + var position = step.PointAt(step.ProgressAt(TimeSpan.FromSeconds(seconds * fraction))); + AddDeposit(start + seconds * fraction, position, rise); + } + } + deposits.Sort((a, b) => a.Time.CompareTo(b.Time)); + } + + private void AddDeposit(double at, Vector point, double rise) + { + var cell = CellAt(point); + if (cell >= 0) + deposits.Add(new Deposit(at, cell, (float)rise)); + } + + // Each closed contour changes the pieces when it finishes: a cutout drops its slug, an + // outside contour (a part's perimeter) cuts the part free of the skeleton. + private void BuildPieceEvents() + { + var steps = Simulation.Steps; + var i = 0; + while (i < steps.Count) + { + var contour = steps[i].ContourIndex; + if (contour < 0) + { + i++; + continue; + } + + var points = new List(); + var isCutout = false; + var end = TimeSpan.Zero; + for (; i < steps.Count && steps[i].ContourIndex == contour; i++) + { + var step = steps[i]; + end = step.EndTime; + if (step.Kind != CutSimulationStepKind.Cut + || step.Layer is not (LayerType.Cut or LayerType.Display)) + continue; + isCutout |= step.IsHole; + AddPoints(points, step); + } + + if (points.Count < 3 || points[0].DistanceTo(points[^1]) > CellSize / 2) + continue; + var cells = CellsInside(points); + if (cells.Length > 0) + events.Add(new PieceEvent(end.TotalSeconds, cells, isCutout)); + } + events.Sort((a, b) => a.Time.CompareTo(b.Time)); + } + + private static void AddPoints(List points, CutSimulationStep step) + { + if (points.Count == 0) + points.Add(step.Start); + if (!step.IsArc) + { + points.Add(step.End); + return; + } + var segments = System.Math.Max(1, (int)System.Math.Ceiling(System.Math.Abs(step.Sweep) / ArcStepRadians)); + for (var k = 1; k <= segments; k++) + points.Add(step.PointAt((double)k / segments)); + } + + private int[] CellsInside(List polygon) + { + double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; + foreach (var p in polygon) + { + minX = System.Math.Min(minX, p.X); + minY = System.Math.Min(minY, p.Y); + maxX = System.Math.Max(maxX, p.X); + maxY = System.Math.Max(maxY, p.Y); + } + + var firstColumn = System.Math.Max(0, (int)System.Math.Floor((minX - OriginX) / CellSize)); + var lastColumn = System.Math.Min(Columns - 1, (int)System.Math.Floor((maxX - OriginX) / CellSize)); + var firstRow = System.Math.Max(0, (int)System.Math.Floor((minY - OriginY) / CellSize)); + var lastRow = System.Math.Min(Rows - 1, (int)System.Math.Floor((maxY - OriginY) / CellSize)); + + var cells = new List(); + for (var row = firstRow; row <= lastRow; row++) + { + for (var column = firstColumn; column <= lastColumn; column++) + { + var index = row * Columns + column; + if (Contains(polygon, CellCenter(index))) + cells.Add(index); + } + } + return cells.ToArray(); + } + + // Even-odd ray test; the polygon need not repeat its first point. + private static bool Contains(List polygon, Vector point) + { + var inside = false; + for (int i = 0, j = polygon.Count - 1; i < polygon.Count; j = i++) + { + var a = polygon[i]; + var b = polygon[j]; + if ((a.Y > point.Y) != (b.Y > point.Y) + && point.X < (b.X - a.X) * (point.Y - a.Y) / (b.Y - a.Y) + a.X) + inside = !inside; + } + return inside; + } + + private readonly record struct Deposit(double Time, int Cell, float Rise); + + private sealed record PieceEvent(double Time, int[] Cells, bool IsCutout); + } +} diff --git a/OpenNest.Core/CNC/Thermal/ThermalMaterial.cs b/OpenNest.Core/CNC/Thermal/ThermalMaterial.cs new file mode 100644 index 00000000..3a8b8d83 --- /dev/null +++ b/OpenNest.Core/CNC/Thermal/ThermalMaterial.cs @@ -0,0 +1,35 @@ +using System; + +namespace OpenNest.CNC.Thermal +{ + /// Bulk thermal properties in SI units (W/m·K, kg/m³, J/kg·K). + public sealed record ThermalMaterial(string Name, double Conductivity, double Density, double SpecificHeat) + { + public static readonly ThermalMaterial MildSteel = new("Mild steel", 50, 7850, 490); + public static readonly ThermalMaterial StainlessSteel = new("Stainless steel", 16, 8000, 500); + public static readonly ThermalMaterial Aluminum = new("Aluminum", 167, 2700, 900); + + /// Thermal diffusivity in m²/s. + public double Diffusivity => Conductivity / (Density * SpecificHeat); + + /// + /// Picks a preset from a stock material name or grade; anything unrecognized is mild steel. + /// + public static ThermalMaterial ForName(string name) + { + if (string.IsNullOrWhiteSpace(name)) + return MildSteel; + var text = name.Trim(); + if (Has(text, "stainless") || Has(text, "304") || Has(text, "316") || Has(text, "430") + || text.StartsWith("SS", StringComparison.OrdinalIgnoreCase)) + return StainlessSteel; + if (Has(text, "alum") || Has(text, "5052") || Has(text, "6061") || Has(text, "3003") + || text.StartsWith("AL", StringComparison.OrdinalIgnoreCase)) + return Aluminum; + return MildSteel; + } + + private static bool Has(string text, string value) => + text.Contains(value, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/OpenNest.Core/CNC/Thermal/ThermalParameters.cs b/OpenNest.Core/CNC/Thermal/ThermalParameters.cs new file mode 100644 index 00000000..7bb1d855 --- /dev/null +++ b/OpenNest.Core/CNC/Thermal/ThermalParameters.cs @@ -0,0 +1,30 @@ +namespace OpenNest.CNC.Thermal +{ + /// Inputs to . Lengths are in the plate's units. + public sealed class ThermalParameters + { + public ThermalMaterial Material { get; init; } = ThermalMaterial.MildSteel; + + /// Sheet thickness in . + public double Thickness { get; init; } + + public Units Units { get; init; } + + /// + /// Watts that stay in the sheet while the torch is on: the share of the beam's power not + /// carried off in the melt, the gas or through the kerf. An estimate to calibrate. + /// + public double AbsorbedPower { get; init; } = 1000; + + /// Heat loss to the air from both faces, in W/m²·K (still air is about 10-25). + public double SurfaceCoefficient { get; init; } = 20; + + /// Grid cell edge in ; zero picks 0.5 in (12 mm). + public double CellSize { get; init; } + + internal double MetersPerUnit => Units == Units.Millimeters ? 0.001 : 0.0254; + + internal double EffectiveCellSize => + CellSize > 0 ? CellSize : Units == Units.Millimeters ? 12 : 0.5; + } +} diff --git a/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs b/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs new file mode 100644 index 00000000..851ec515 --- /dev/null +++ b/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs @@ -0,0 +1,194 @@ +using OpenNest.CNC; +using OpenNest.CNC.Thermal; +using OpenNest.Geometry; + +namespace OpenNest.Tests.CNC; + +public class PlateHeatSimulationTests +{ + private static readonly CutParameters Cutting = new() + { + Feedrate = 100, // in/min + RapidTravelRate = 600, + PierceTime = TimeSpan.FromSeconds(1), + Units = Units.Inches, + }; + + private static ThermalParameters Thermal(double surfaceCoefficient = 0) => new() + { + Material = ThermalMaterial.MildSteel, + Thickness = 0.25, + Units = Units.Inches, + AbsorbedPower = 1000, + SurfaceCoefficient = surfaceCoefficient, + CellSize = 0.5, + }; + + // Joules per kelvin held by one cell of the grid above. + private static double CellCapacity(ThermalParameters p) + { + var dx = p.CellSize * 0.0254; + return p.Material.Density * p.Material.SpecificHeat * p.Thickness * 0.0254 * dx * dx; + } + + // Counterclockwise: a cutout under the CI Fiber rule. Clockwise: a part's outside. + private static Program Square(double size, bool clockwise) + { + var program = new Program(); + program.Codes.Add(new RapidMove(0, 0)); + if (clockwise) + { + program.Codes.Add(new LinearMove(0, size)); + program.Codes.Add(new LinearMove(size, size)); + program.Codes.Add(new LinearMove(size, 0)); + } + else + { + program.Codes.Add(new LinearMove(size, 0)); + program.Codes.Add(new LinearMove(size, size)); + program.Codes.Add(new LinearMove(0, size)); + } + program.Codes.Add(new LinearMove(0, 0)); + return program; + } + + private static Program Line(double length) + { + var program = new Program(); + program.Codes.Add(new RapidMove(0, 0)); + program.Codes.Add(new LinearMove(length, 0)); + return program; + } + + private static (Plate Plate, CutSimulation Simulation) Cut(Program program, Vector location) + { + var plate = new Plate(48, 96); + plate.Parts.Add(new Part(new Drawing("part", program), location)); + return (plate, CutSimulation.Build(plate, Cutting)); + } + + private static double TorchOnSeconds(CutSimulation simulation) => simulation.Steps + .Where(s => s.Kind is CutSimulationStepKind.Cut or CutSimulationStepKind.Pierce) + .Sum(s => s.Duration.TotalSeconds); + + private static double TotalHeat(PlateHeatSimulation heat, ThermalParameters p) + { + var sum = 0.0; + foreach (var t in heat.Temperatures) + sum += t; + return sum * CellCapacity(p); + } + + [Fact] + public void WithoutSurfaceLossAllAbsorbedEnergyStaysInTheSheet() + { + var (plate, simulation) = Cut(Line(20), new Vector(10, 10)); + var p = Thermal(); + var heat = new PlateHeatSimulation(plate, simulation, p); + + heat.RunToEnd(TimeSpan.FromSeconds(30)); + + var expected = p.AbsorbedPower * TorchOnSeconds(simulation); + Assert.Equal(expected, TotalHeat(heat, p), expected * 1e-4); + } + + [Fact] + public void SurfaceLossDecaysHeatExponentially() + { + var (plate, simulation) = Cut(Line(20), new Vector(10, 10)); + var p = Thermal(surfaceCoefficient: 20); + var heat = new PlateHeatSimulation(plate, simulation, p); + + heat.RunToEnd(); + var atEnd = TotalHeat(heat, p); + heat.RunToEnd(TimeSpan.FromSeconds(120)); + + var thickness = p.Thickness * 0.0254; + var rate = 2 * p.SurfaceCoefficient / (p.Material.Density * p.Material.SpecificHeat * thickness); + Assert.Equal(System.Math.Exp(-rate * 120), TotalHeat(heat, p) / atEnd, 3); + } + + [Fact] + public void HeatSpreadsFromTheCut() + { + var (plate, simulation) = Cut(Line(4), new Vector(20, 20)); + var heat = new PlateHeatSimulation(plate, simulation, Thermal()); + + heat.RunToEnd(); + var near = heat.CellAt(new Vector(22, 20.1)); + var away = heat.CellAt(new Vector(22, 23.1)); + Assert.True(heat.Temperatures[near] > 0); + var awayAtEnd = heat.Temperatures[away]; + + heat.RunToEnd(TimeSpan.FromSeconds(60)); + + Assert.True(heat.Temperatures[away] > awayAtEnd); + Assert.True(heat.Temperatures[near] < heat.Peaks[near]); + Assert.True(heat.Peaks[near] > heat.Peaks[away]); + } + + [Fact] + public void CutoutSlugFallsAwayWithItsHeat() + { + var (plate, simulation) = Cut(Square(6, clockwise: false), new Vector(10, 10)); + var heat = new PlateHeatSimulation(plate, simulation, Thermal()); + + heat.RunToEnd(); + + var inside = heat.CellAt(new Vector(13, 13)); + Assert.True(heat.IsRemoved(inside)); + Assert.Equal(0f, heat.Temperatures[inside]); + Assert.False(heat.IsRemoved(heat.CellAt(new Vector(5, 5)))); + } + + [Fact] + public void CutFreePartKeepsItsHeatAcrossTheKerf() + { + var (plate, simulation) = Cut(Square(6, clockwise: true), new Vector(10, 10)); + var heat = new PlateHeatSimulation(plate, simulation, Thermal()); + heat.RunToEnd(); + + double PartHeat() + { + var sum = 0.0; + for (var i = 0; i < heat.Temperatures.Length; i++) + { + var c = heat.CellCenter(i); + if (c.X > 10 && c.X < 16 && c.Y > 10 && c.Y < 16) + sum += heat.Temperatures[i]; + } + return sum; + } + + var before = PartHeat(); + heat.RunToEnd(TimeSpan.FromSeconds(120)); + + Assert.True(before > 0); + Assert.False(heat.IsRemoved(heat.CellAt(new Vector(13, 13)))); + Assert.Equal(before, PartHeat(), before * 1e-4); + } + + [Fact] + public void GoingBackInTimeReplaysTheSameState() + { + var (plate, simulation) = Cut(Square(6, clockwise: false), new Vector(10, 10)); + var heat = new PlateHeatSimulation(plate, simulation, Thermal(20)); + var middle = TimeSpan.FromTicks(simulation.TotalTime.Ticks / 2); + + heat.AdvanceTo(middle); + var first = heat.Temperatures.ToArray(); + heat.RunToEnd(); + heat.AdvanceTo(middle); + + Assert.Equal(first, heat.Temperatures.ToArray()); + } + + [Theory] + [InlineData("304 Stainless", "Stainless steel")] + [InlineData("SS", "Stainless steel")] + [InlineData("Aluminum 5052", "Aluminum")] + [InlineData("A36", "Mild steel")] + [InlineData("", "Mild steel")] + public void MaterialNamesPickAPreset(string name, string expected) => + Assert.Equal(expected, ThermalMaterial.ForName(name).Name); +} diff --git a/OpenNest/Controls/CutSimulationOverlay.cs b/OpenNest/Controls/CutSimulationOverlay.cs index b28536c6..9d5c0937 100644 --- a/OpenNest/Controls/CutSimulationOverlay.cs +++ b/OpenNest/Controls/CutSimulationOverlay.cs @@ -6,12 +6,25 @@ using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Windows.Forms; using OpenNest.CNC; +using OpenNest.CNC.Thermal; using OpenNest.Desktop.Interaction; using OpenNest.Geometry; using OpenNest.Math; namespace OpenNest.Controls; +/// What the cut simulator's heat layer shows. +internal enum HeatView +{ + Off, + + /// The estimated temperature rise at the playhead. + Now, + + /// The hottest each area has been up to the playhead. + Peak, +} + /// /// Plays a over the plate: the cut trail grows behind the torch, /// travel is traced faintly and parts the torch has not reached yet are drawn muted. @@ -30,6 +43,11 @@ internal sealed class CutSimulationOverlay : IDisposable private readonly Stopwatch sinceZoom = new(); private readonly CutSimulationPlayback playback = new(); + private PlateHeatSimulation heat; + private HeatView heatMode; + private float heatScale = 1; + private Bitmap heatImage; + // The finished trail, rendered once at the scale it was built for, so panning and playback // only blit it and draw the moves since. Null when the whole timeline would be too large an // image (zoomed in), where each paint draws only the moves on screen. @@ -98,10 +116,35 @@ internal sealed class CutSimulationOverlay : IDisposable public void Load(CutSimulation value) { ResetTrail(); + heat = null; playback.Load(value); view.Invalidate(); } + /// The heat model shown under the trail, run along with the playhead; null for none. + public PlateHeatSimulation Heat => heat; + + public HeatView HeatMode + { + get => heatMode; + set + { + heatMode = value; + view.Invalidate(); + } + } + + /// + /// Shows (built on the loaded timeline) colored against + /// kelvin, normally the hottest any cell gets over the whole cut. + /// + public void LoadHeat(PlateHeatSimulation value, float scale) + { + heat = value; + heatScale = System.Math.Max(1f, scale); + view.Invalidate(); + } + public void Play() { playback.Play(); @@ -121,6 +164,7 @@ internal sealed class CutSimulationOverlay : IDisposable { playback.Clear(); ResetTrail(); + heat = null; view.Invalidate(); } @@ -152,6 +196,7 @@ internal sealed class CutSimulationOverlay : IDisposable var finished = System.Math.Clamp(index, 0, Simulation.Steps.Count); using var pens = new TrailPens(dpi); + DrawHeat(graphics, time); DrawTrail(graphics, pens, finished); if (index >= Simulation.Steps.Count) @@ -245,6 +290,94 @@ internal sealed class CutSimulationOverlay : IDisposable private static float Fraction(float value) => value - (float)System.Math.Floor(value); + // One image pixel per model cell, stretched over the plate with smoothing. + private void DrawHeat(Graphics graphics, TimeSpan time) + { + if (heat == null || heatMode == HeatView.Off) + return; + + heat.AdvanceTo(time); + var values = heatMode == HeatView.Peak ? heat.Peaks : heat.Temperatures; + var columns = heat.Columns; + var rows = heat.Rows; + if (heatImage == null || heatImage.Width != columns || heatImage.Height != rows) + { + heatImage?.Dispose(); + heatImage = new Bitmap(columns, rows, PixelFormat.Format32bppArgb); + } + + var pixels = new int[columns * rows]; + for (var row = 0; row < rows; row++) + { + // Image rows run down the screen; model rows run up the plate. + var line = (rows - 1 - row) * columns; + for (var column = 0; column < columns; column++) + { + var cell = row * columns + column; + pixels[line + column] = heat.IsRemoved(cell) ? 0 : HeatColor(values[cell] / heatScale); + } + } + var data = heatImage.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + try + { + System.Runtime.InteropServices.Marshal.Copy(pixels, 0, data.Scan0, pixels.Length); + } + finally + { + heatImage.UnlockBits(data); + } + + var topLeft = view.PointWorldToGraph(new Vector(heat.OriginX, heat.OriginY + rows * heat.CellSize)); + var bottomRight = view.PointWorldToGraph(new Vector(heat.OriginX + columns * heat.CellSize, heat.OriginY)); + var destination = RectangleF.FromLTRB( + System.Math.Min(topLeft.X, bottomRight.X), System.Math.Min(topLeft.Y, bottomRight.Y), + System.Math.Max(topLeft.X, bottomRight.X), System.Math.Max(topLeft.Y, bottomRight.Y)); + + var state = graphics.Save(); + try + { + graphics.InterpolationMode = InterpolationMode.Bilinear; + graphics.PixelOffsetMode = PixelOffsetMode.Half; + using var attributes = new ImageAttributes(); + attributes.SetWrapMode(WrapMode.TileFlipXY); + graphics.DrawImage(heatImage, + new[] { destination.Location, new PointF(destination.Right, destination.Top), new PointF(destination.Left, destination.Bottom) }, + new RectangleF(0, 0, columns, rows), GraphicsUnit.Pixel, attributes); + } + finally + { + graphics.Restore(state); + } + } + + private static readonly (float At, Color Color)[] HeatStops = + { + (0f, Color.FromArgb(40, 60, 200)), + (0.3f, Color.FromArgb(0, 190, 200)), + (0.55f, Color.FromArgb(240, 220, 0)), + (0.8f, Color.FromArgb(255, 110, 0)), + (1f, Color.FromArgb(220, 0, 0)), + }; + + // Cool cells fade out so the plate shows through; hotter ones turn opaque and red. + internal static int HeatColor(float fraction) + { + if (!(fraction > 0.03f)) + return 0; + var t = System.Math.Min(1f, fraction); + var i = 1; + while (i < HeatStops.Length - 1 && t > HeatStops[i].At) + i++; + var (fromAt, from) = HeatStops[i - 1]; + var (toAt, to) = HeatStops[i]; + var k = (t - fromAt) / (toAt - fromAt); + var alpha = (int)(255 * System.Math.Min(0.8f, 0.2f + t)); + return Color.FromArgb(alpha, + (int)(from.R + (to.R - from.R) * k), + (int)(from.G + (to.G - from.G) * k), + (int)(from.B + (to.B - from.B) * k)).ToArgb(); + } + private void RebuildTrail(float scale, PointF phase) { ResetTrail(); @@ -472,6 +605,7 @@ internal sealed class CutSimulationOverlay : IDisposable timer.Dispose(); settleTimer.Dispose(); ResetTrail(); + heatImage?.Dispose(); } private sealed class TrailPens(float dpi) : IDisposable diff --git a/OpenNest/Forms/CutSimulatorForm.cs b/OpenNest/Forms/CutSimulatorForm.cs index 405f818d..75de10cf 100644 --- a/OpenNest/Forms/CutSimulatorForm.cs +++ b/OpenNest/Forms/CutSimulatorForm.cs @@ -3,6 +3,7 @@ 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; @@ -31,6 +32,9 @@ namespace OpenNest.Forms 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; @@ -134,6 +138,15 @@ namespace OpenNest.Forms 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, @@ -148,6 +161,8 @@ namespace OpenNest.Forms 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()); @@ -165,6 +180,12 @@ namespace OpenNest.Forms 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"); @@ -178,6 +199,8 @@ namespace OpenNest.Forms 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]; @@ -246,6 +269,60 @@ namespace OpenNest.Forms 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, + }); + 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(); + 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); + heatScaleText = $"{material.Name}; 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) @@ -356,6 +433,7 @@ namespace OpenNest.Forms 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); diff --git a/docs/plate-heat-map.md b/docs/plate-heat-map.md new file mode 100644 index 00000000..b5856c0d --- /dev/null +++ b/docs/plate-heat-map.md @@ -0,0 +1,34 @@ +# Plate heat map + +`OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs` estimates how heat builds up in the sheet +while a [cut simulation](cut-time-estimates.md) plays. The Cut Simulator shows it under the cut +trail (Heat: Now or Peak so far). It is a display and analysis aid: no sequencer uses it yet, and +it never changes the plate. + +## Model + +- A grid over the plate's bounds, 0.5 in (12 mm) cells by default, made coarser on sheets that + would need more than 400,000 cells. Each cell holds its temperature rise above ambient. +- Heat in: while the torch is on (cuts and pierces), `AbsorbedPower` watts go into the cell under + the torch, in proportion to the time spent there. Scribes add nothing. +- Conduction: explicit finite differences between the four neighbors of the same piece, with the + time step kept below the stability limit and at most 1 s. Sheet edges are insulated. +- Loss: convection from both faces at `SurfaceCoefficient` (W/m²·K). +- Pieces: when a closed contour finishes, a cutout (an interior contour by the CI Fiber rule the + timeline already uses) removes its slug's cells and their heat; a part's outside contour + separates its cells from the skeleton, so no heat crosses the kerf. Only skeleton cells change, + so a part nested in a cutout stays its own piece. Open contours (cut-offs, breaks) change + nothing. +- Material from the nest's material name and grade (`ThermalMaterial.ForName`: stainless, + aluminum, otherwise mild steel); thickness from the nest. + +Not modeled: radiation, heat into the slats, pierce power differing from cutting power, the +heat carried off by the melt beyond `AbsorbedPower`, kerf width and warping. The absorbed power +(1000 W by default) is an uncalibrated guess, so the temperatures are relative; use them to +compare cut orders of one plate, not as real values. + +## Display + +The simulator colors the field against the 99.5th percentile of the whole cut's peaks: a pierce +puts its energy into a single cell, and scaling to that cell would hide the areas where heat +builds up. Cells whose slug fell away are transparent.