mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-05 16:29:27 -05:00
Scrubbing the Cut Simulator backward reset the heat model and replayed from zero, so every frame cost a full run (~75 ms on N26-2EF, over a second at 1/32 in cells). - A straight run from the start now keeps checkpoints (temperature, peak, cursors) about every 500k cell updates, within 32 MB; the pieces are rebuilt from the event cursor. Going back, or jumping more than eight steps ahead, resumes from the latest checkpoint a straight run to the target passes, so the state is exactly that run's. Seeks on N26-2EF drop from 12-150 ms to about 1 ms. - The diffusion step runs branch-free on Vector<float> with neighbor links precomputed as 0/1 weights when pieces change, and splits across processors on grids of 65,536 cells or more. A missing link adds a zero, so results stay bit-identical. - Rises below 1e-30 K are flushed to zero: the heat front passed through subnormal floats, which made long runs 2-4x slower. Only cells below ~3e-18 K change, by at most 2e-25 K; N26-2EF's end state is bit-identical. A full run on N26-2EF falls from ~150-180 ms to ~15-40 ms, so the automatic cell size's work budget rises from 20M to 60M cell updates (still about a tenth of a second); full sheets keep 0.5 in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
768 lines
33 KiB
C#
768 lines
33 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Runtime.InteropServices;
|
|
using System.Threading.Tasks;
|
|
using OpenNest.Geometry;
|
|
using OpenNest.Support;
|
|
using FloatVector = System.Numerics.Vector<float>;
|
|
using Simd = System.Numerics.Vector;
|
|
|
|
namespace OpenNest.CNC.Thermal
|
|
{
|
|
/// <summary>
|
|
/// Estimates how heat builds up and spreads in the sheet while a <see cref="CutSimulation"/>
|
|
/// 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 and, given a
|
|
/// <see cref="ThermalParameters.SupportBed"/>, into the slats or grid points under each cell.
|
|
/// <para>
|
|
/// 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.
|
|
/// </para>
|
|
/// </summary>
|
|
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;
|
|
|
|
// Cell updates for a whole run when the cell size is automatic: about a tenth of a second.
|
|
private const double WorkBudget = 60_000_000;
|
|
private const int MaxHalvings = 3;
|
|
|
|
// 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;
|
|
|
|
// Checkpoints come every this many cell updates of a run (about a millisecond), so going
|
|
// back costs at most that much stepping, and share at most this much memory (temperature
|
|
// and peak per cell); a long run on a large grid spaces them further apart.
|
|
private const double CheckpointWork = 500_000;
|
|
private const long CheckpointBytes = 32L << 20;
|
|
|
|
// Going forward, a checkpoint this many steps past the current time beats stepping there.
|
|
private const int SkipAheadSteps = 8;
|
|
|
|
// A rise below this is set to zero. The front of the spreading heat passes through
|
|
// subnormal floats, which cost the processor about a hundred times a normal operation;
|
|
// dropping them changes no cell above about 1e-18 K.
|
|
private const float Negligible = 1e-30f;
|
|
|
|
// Grids this large split each step's cells across processors.
|
|
private const int ParallelCells = 65_536;
|
|
|
|
private readonly List<Deposit> deposits = new();
|
|
private readonly List<PieceEvent> 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 float[] contactFraction;
|
|
private readonly double contactRate;
|
|
private readonly float[] fullStepKeep;
|
|
private readonly float[] partialStepKeep;
|
|
private double partialStepSeconds = -1;
|
|
private readonly double maxStep;
|
|
private readonly float[] leftLink;
|
|
private readonly float[] rightLink;
|
|
private readonly float[] belowLink;
|
|
private readonly float[] aboveLink;
|
|
private readonly List<Checkpoint> checkpoints = new();
|
|
private readonly int checkpointInterval;
|
|
private readonly int maxCheckpoints;
|
|
private bool straight;
|
|
private int straightSteps;
|
|
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.CellSize > 0
|
|
? parameters.CellSize
|
|
: AutomaticCellSize(bounds, simulation.TotalTime.TotalSeconds, parameters);
|
|
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];
|
|
leftLink = new float[count];
|
|
rightLink = new float[count];
|
|
belowLink = new float[count];
|
|
aboveLink = 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);
|
|
|
|
if (parameters.SupportBed != null && parameters.ContactCoefficient > 0)
|
|
{
|
|
contactFraction = ContactFractions(parameters.SupportBed, plate.Quadrant,
|
|
parameters.EffectiveGridContactSize);
|
|
if (contactFraction != null)
|
|
{
|
|
// Through the bottom face only.
|
|
contactRate = parameters.ContactCoefficient / (volumetricHeat * thickness);
|
|
fullStepKeep = ContactKeep(maxStep, new float[count]);
|
|
partialStepKeep = new float[count];
|
|
}
|
|
}
|
|
|
|
maxCheckpoints = (int)System.Math.Max(1, CheckpointBytes / (8L * count));
|
|
var runSteps = System.Math.Ceiling(simulation.TotalTime.TotalSeconds / maxStep);
|
|
checkpointInterval = (int)System.Math.Clamp(System.Math.Max(
|
|
System.Math.Ceiling(CheckpointWork / count), System.Math.Ceiling(runSteps / maxCheckpoints)),
|
|
1, int.MaxValue);
|
|
|
|
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; }
|
|
|
|
/// <summary>Lower-left corner of cell (0, 0) in plate coordinates.</summary>
|
|
public double OriginX { get; }
|
|
public double OriginY { get; }
|
|
|
|
/// <summary>
|
|
/// Cell edge in the plate's units: the one asked for (larger on very large sheets), or one
|
|
/// picked for the plate (<see cref="ThermalParameters.CellSize"/>).
|
|
/// </summary>
|
|
public double CellSize { get; }
|
|
|
|
/// <summary>How far the model has run.</summary>
|
|
public TimeSpan Time => TimeSpan.FromSeconds(time);
|
|
|
|
/// <summary>Temperature rise of each cell now, row by row from the bottom; zero where material fell away.</summary>
|
|
public ReadOnlySpan<float> Temperatures => temperature;
|
|
|
|
/// <summary>The highest rise each cell has reached so far.</summary>
|
|
public ReadOnlySpan<float> Peaks => peak;
|
|
|
|
/// <summary>True when heat is also lost into the support bed (<see cref="ThermalParameters.SupportBed"/>).</summary>
|
|
public bool UsesSupportBed => contactFraction != null;
|
|
|
|
/// <summary>
|
|
/// The share of each cell's area that rests on a slat or grid point, 0 to 1, row by row
|
|
/// from the bottom; empty when <see cref="UsesSupportBed"/> is false.
|
|
/// </summary>
|
|
public ReadOnlySpan<float> SupportFractions => contactFraction;
|
|
|
|
/// <summary>True for a cell whose material fell away as a slug.</summary>
|
|
public bool IsRemoved(int index) => region[index] == Removed;
|
|
|
|
/// <summary>The cell holding <paramref name="point"/>, or -1 off the grid.</summary>
|
|
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);
|
|
|
|
/// <summary>
|
|
/// Runs the model to <paramref name="target"/>. Going back in time, or far ahead, resumes
|
|
/// from the latest checkpoint a straight run from the start would have passed, so the
|
|
/// state is exactly that run's.
|
|
/// </summary>
|
|
public void AdvanceTo(TimeSpan target)
|
|
{
|
|
var seconds = target.TotalSeconds;
|
|
var checkpoint = CheckpointBefore(seconds);
|
|
if (seconds < time)
|
|
{
|
|
if (checkpoint == null)
|
|
Reset();
|
|
else
|
|
Restore(checkpoint);
|
|
}
|
|
else if (checkpoint != null && checkpoint.Time - time > SkipAheadSteps * maxStep)
|
|
{
|
|
Restore(checkpoint);
|
|
}
|
|
|
|
while (time < seconds)
|
|
{
|
|
var step = System.Math.Min(maxStep, seconds - time);
|
|
var previous = time;
|
|
Step(step);
|
|
if (step != maxStep)
|
|
{
|
|
straight = false;
|
|
continue;
|
|
}
|
|
if (straight && ++straightSteps % checkpointInterval == 0)
|
|
Record(previous);
|
|
}
|
|
}
|
|
|
|
/// <summary>Runs the whole cut, then <paramref name="cooling"/> more.</summary>
|
|
public void RunToEnd(TimeSpan cooling = default) => AdvanceTo(Simulation.TotalTime + cooling);
|
|
|
|
public void Reset()
|
|
{
|
|
Array.Clear(temperature);
|
|
Array.Clear(peak);
|
|
ResetPieces();
|
|
depositCursor = 0;
|
|
time = 0;
|
|
straight = true;
|
|
straightSteps = 0;
|
|
}
|
|
|
|
/// <summary>Index of the largest value, or -1 when every value is zero or less.</summary>
|
|
public static int IndexOfMax(ReadOnlySpan<float> 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;
|
|
}
|
|
|
|
// The finest cell, from the coarsest default halved down to the finest, whose whole run
|
|
// (every cell, every time step) stays within the work budget. Halving the cell costs up
|
|
// to sixteen times the work: four times the cells and, once diffusion limits the step,
|
|
// four times the steps. The budget keeps the first run, which also sets the color scale, to
|
|
// about a tenth of a second (going back resumes from a checkpoint); large sheets stay at
|
|
// the coarsest.
|
|
internal static double AutomaticCellSize(Box bounds, double seconds, ThermalParameters parameters)
|
|
{
|
|
var coarsest = parameters.Units == Units.Millimeters ? 12 : 0.5;
|
|
var cell = coarsest;
|
|
for (var halvings = 0; halvings < MaxHalvings; halvings++)
|
|
{
|
|
var finer = cell / 2;
|
|
if (RunWork(bounds, seconds, finer, parameters) > WorkBudget)
|
|
break;
|
|
cell = finer;
|
|
}
|
|
return cell;
|
|
}
|
|
|
|
private static double RunWork(Box bounds, double seconds, double cell, ThermalParameters parameters)
|
|
{
|
|
var dx = cell * parameters.MetersPerUnit;
|
|
var step = System.Math.Min(MaxStepSeconds, StabilityFactor * dx * dx / parameters.Material.Diffusivity);
|
|
return CellCount(bounds, cell) * System.Math.Ceiling(System.Math.Max(seconds, step) / step);
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
// One explicit step: each cell takes share times the difference to each neighbor of its
|
|
// own piece, then decays. A link weight is 1 between cells of one piece and 0 otherwise
|
|
// (and for every link of a removed cell, which holds no heat), so the sum runs without
|
|
// branches. A missing link adds a zero, leaving the sum exactly as if it were skipped,
|
|
// which keeps the results bit for bit those of the cell-by-cell form.
|
|
private void Diffuse(double seconds)
|
|
{
|
|
var share = (float)(diffusionRate * seconds);
|
|
var keep = (float)System.Math.Exp(-lossRate * seconds);
|
|
var cellKeep = contactFraction == null ? null
|
|
: seconds == maxStep ? fullStepKeep
|
|
: PartialStepKeep(seconds);
|
|
|
|
// Vectors cover the rows with a neighbor above and below; the first and last rows,
|
|
// and any remainder, go cell by cell.
|
|
var count = temperature.Length;
|
|
var width = FloatVector.Count;
|
|
var first = Rows > 2 ? Columns : count;
|
|
var vectors = Rows > 2 ? (count - 2 * Columns) / width : 0;
|
|
var last = first + vectors * width;
|
|
|
|
DiffuseCells(0, System.Math.Min(first, count), share, keep, cellKeep);
|
|
if (vectors > 0)
|
|
{
|
|
var chunks = count >= ParallelCells ? System.Math.Min(Environment.ProcessorCount, vectors) : 1;
|
|
if (chunks <= 1)
|
|
{
|
|
DiffuseVectors(first, last, share, keep, cellKeep);
|
|
}
|
|
else
|
|
{
|
|
var perChunk = (vectors + chunks - 1) / chunks;
|
|
Parallel.For(0, chunks, chunk =>
|
|
{
|
|
var start = first + chunk * perChunk * width;
|
|
var end = System.Math.Min(last, start + perChunk * width);
|
|
if (start < end)
|
|
DiffuseVectors(start, end, share, keep, cellKeep);
|
|
});
|
|
}
|
|
}
|
|
DiffuseCells(last, count, share, keep, cellKeep);
|
|
(temperature, next) = (next, temperature);
|
|
}
|
|
|
|
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
|
private void DiffuseCells(int start, int end, float share, float keep, float[] cellKeep)
|
|
{
|
|
var current = temperature;
|
|
var columns = Columns;
|
|
var count = current.Length;
|
|
for (var i = start; i < end; i++)
|
|
{
|
|
var t = current[i];
|
|
var left = i > 0 ? current[i - 1] : 0f;
|
|
var right = i + 1 < count ? current[i + 1] : 0f;
|
|
var below = i >= columns ? current[i - columns] : 0f;
|
|
var above = i + columns < count ? current[i + columns] : 0f;
|
|
var flow = leftLink[i] * (left - t) + rightLink[i] * (right - t)
|
|
+ belowLink[i] * (below - t) + aboveLink[i] * (above - t);
|
|
var value = (t + share * flow) * (cellKeep == null ? keep : cellKeep[i]);
|
|
if (value < Negligible)
|
|
value = 0;
|
|
next[i] = value;
|
|
if (value > peak[i])
|
|
peak[i] = value;
|
|
}
|
|
}
|
|
|
|
// The same sum as DiffuseCells, a vector of cells at a time; every neighbor index is
|
|
// inside the grid because the range skips the first and last rows.
|
|
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
|
private void DiffuseVectors(int start, int end, float share, float keep, float[] cellKeep)
|
|
{
|
|
var width = FloatVector.Count;
|
|
var columns = (nuint)Columns;
|
|
ref var current = ref MemoryMarshal.GetArrayDataReference(temperature);
|
|
ref var result = ref MemoryMarshal.GetArrayDataReference(next);
|
|
ref var high = ref MemoryMarshal.GetArrayDataReference(peak);
|
|
ref var leftWeight = ref MemoryMarshal.GetArrayDataReference(leftLink);
|
|
ref var rightWeight = ref MemoryMarshal.GetArrayDataReference(rightLink);
|
|
ref var belowWeight = ref MemoryMarshal.GetArrayDataReference(belowLink);
|
|
ref var aboveWeight = ref MemoryMarshal.GetArrayDataReference(aboveLink);
|
|
ref var decay = ref cellKeep == null ? ref Unsafe.NullRef<float>() : ref MemoryMarshal.GetArrayDataReference(cellKeep);
|
|
var shares = new FloatVector(share);
|
|
var keeps = new FloatVector(keep);
|
|
var negligible = new FloatVector(Negligible);
|
|
|
|
for (var index = start; index < end; index += width)
|
|
{
|
|
var i = (nuint)index;
|
|
var t = Simd.LoadUnsafe(ref current, i);
|
|
var flow = Simd.LoadUnsafe(ref leftWeight, i) * (Simd.LoadUnsafe(ref current, i - 1) - t)
|
|
+ Simd.LoadUnsafe(ref rightWeight, i) * (Simd.LoadUnsafe(ref current, i + 1) - t)
|
|
+ Simd.LoadUnsafe(ref belowWeight, i) * (Simd.LoadUnsafe(ref current, i - columns) - t)
|
|
+ Simd.LoadUnsafe(ref aboveWeight, i) * (Simd.LoadUnsafe(ref current, i + columns) - t);
|
|
var value = (t + shares * flow)
|
|
* (cellKeep == null ? keeps : Simd.LoadUnsafe(ref decay, i));
|
|
value = Simd.ConditionalSelect(Simd.LessThan(value, negligible), default, value);
|
|
Simd.StoreUnsafe(value, ref result, i);
|
|
var old = Simd.LoadUnsafe(ref high, i);
|
|
Simd.StoreUnsafe(Simd.ConditionalSelect(Simd.GreaterThan(value, old), value, old), ref high, i);
|
|
}
|
|
}
|
|
|
|
// Each cell's decay over one step: the air from both faces plus the bed under it. An
|
|
// exponential factor stays stable however strong the contact. Most steps are full
|
|
// length; playback ends each frame on a shorter one, kept until its length changes.
|
|
private float[] PartialStepKeep(double seconds)
|
|
{
|
|
if (seconds != partialStepSeconds)
|
|
{
|
|
ContactKeep(seconds, partialStepKeep);
|
|
partialStepSeconds = seconds;
|
|
}
|
|
return partialStepKeep;
|
|
}
|
|
|
|
private float[] ContactKeep(double seconds, float[] keep)
|
|
{
|
|
for (var i = 0; i < keep.Length; i++)
|
|
keep[i] = (float)System.Math.Exp(-(lossRate + contactRate * contactFraction[i]) * seconds);
|
|
return keep;
|
|
}
|
|
|
|
// The share of every cell over the bed: the overlap of each slat's top, or each grid
|
|
// point's square pad, with the cell, so slats narrower or wider than a cell both count.
|
|
// Null for a bed this model does not know.
|
|
private float[] ContactFractions(SupportBed bed, int quadrant, double padSize)
|
|
{
|
|
var area = new double[Columns * Rows];
|
|
var extent = new Box(OriginX, OriginY, Columns * CellSize, Rows * CellSize);
|
|
switch (bed)
|
|
{
|
|
case SupportSlats slats:
|
|
foreach (var slat in slats.SlatsIn(extent, quadrant, int.MaxValue))
|
|
AddOverlap(area, slat.Left, slat.Bottom, slat.Right, slat.Top, 0, Rows - 1);
|
|
break;
|
|
case SupportGrid grid:
|
|
// One row of cells at a time, so a fine grid on a large sheet never lists
|
|
// every point at once.
|
|
var half = padSize / 2;
|
|
for (var row = 0; row < Rows; row++)
|
|
{
|
|
var strip = new Box(extent.Left - half, OriginY + row * CellSize - half,
|
|
extent.Length + padSize, CellSize + padSize);
|
|
foreach (var point in grid.PointsIn(strip, quadrant, int.MaxValue))
|
|
AddOverlap(area, point.X - half, point.Y - half, point.X + half, point.Y + half, row, row);
|
|
}
|
|
break;
|
|
default:
|
|
return null;
|
|
}
|
|
|
|
var cellArea = CellSize * CellSize;
|
|
var fractions = new float[area.Length];
|
|
for (var i = 0; i < area.Length; i++)
|
|
fractions[i] = (float)System.Math.Min(1, area[i] / cellArea);
|
|
return fractions;
|
|
}
|
|
|
|
// Adds the area of the rectangle over each cell in rows firstRow to lastRow.
|
|
private void AddOverlap(double[] area, double left, double bottom, double right, double top,
|
|
int firstRow, int lastRow)
|
|
{
|
|
if (!(right > left) || !(top > bottom))
|
|
return;
|
|
var columnStart = System.Math.Max(0, (int)System.Math.Floor((left - OriginX) / CellSize));
|
|
var columnEnd = System.Math.Min(Columns - 1, (int)System.Math.Floor((right - OriginX) / CellSize));
|
|
var rowStart = System.Math.Max(firstRow, (int)System.Math.Floor((bottom - OriginY) / CellSize));
|
|
var rowEnd = System.Math.Min(lastRow, (int)System.Math.Floor((top - OriginY) / CellSize));
|
|
for (var row = rowStart; row <= rowEnd; row++)
|
|
{
|
|
var cellBottom = OriginY + row * CellSize;
|
|
var height = System.Math.Min(top, cellBottom + CellSize) - System.Math.Max(bottom, cellBottom);
|
|
if (height <= 0)
|
|
continue;
|
|
for (var column = columnStart; column <= columnEnd; column++)
|
|
{
|
|
var cellLeft = OriginX + column * CellSize;
|
|
var width = System.Math.Min(right, cellLeft + CellSize) - System.Math.Max(left, cellLeft);
|
|
if (width > 0)
|
|
area[row * Columns + column] += width * height;
|
|
}
|
|
}
|
|
}
|
|
|
|
private void Apply(PieceEvent piece)
|
|
{
|
|
ApplyToPieces(piece);
|
|
foreach (var cell in piece.Cells)
|
|
LinkAround(cell);
|
|
}
|
|
|
|
private void ApplyToPieces(PieceEvent piece)
|
|
{
|
|
eventCursor++;
|
|
// 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;
|
|
}
|
|
}
|
|
|
|
// The pieces depend only on how many events have run, so they are rebuilt rather than
|
|
// kept with each checkpoint.
|
|
private void ResetPieces()
|
|
{
|
|
Array.Clear(region);
|
|
eventCursor = 0;
|
|
nextRegion = 0;
|
|
LinkAll();
|
|
}
|
|
|
|
private void LinkAll()
|
|
{
|
|
for (var i = 0; i < region.Length; i++)
|
|
Link(i);
|
|
}
|
|
|
|
// A changed cell changes its own links and its neighbors' links to it.
|
|
private void LinkAround(int cell)
|
|
{
|
|
Link(cell);
|
|
var column = cell % Columns;
|
|
if (column > 0)
|
|
Link(cell - 1);
|
|
if (column < Columns - 1)
|
|
Link(cell + 1);
|
|
if (cell >= Columns)
|
|
Link(cell - Columns);
|
|
if (cell + Columns < region.Length)
|
|
Link(cell + Columns);
|
|
}
|
|
|
|
private void Link(int i)
|
|
{
|
|
var piece = region[i];
|
|
var column = i % Columns;
|
|
var alive = piece != Removed;
|
|
leftLink[i] = alive && column > 0 && region[i - 1] == piece ? 1f : 0f;
|
|
rightLink[i] = alive && column < Columns - 1 && region[i + 1] == piece ? 1f : 0f;
|
|
belowLink[i] = alive && i >= Columns && region[i - Columns] == piece ? 1f : 0f;
|
|
aboveLink[i] = alive && i + Columns < region.Length && region[i + Columns] == piece ? 1f : 0f;
|
|
}
|
|
|
|
// Checkpoints: the state after every checkpointInterval full steps of a straight run from
|
|
// the start (one never cut short by an earlier target), kept as the run passes them. A
|
|
// straight run to any later target takes exactly the same steps up to there.
|
|
private void Record(double previousTime)
|
|
{
|
|
var index = straightSteps / checkpointInterval - 1;
|
|
if (index != checkpoints.Count || index >= maxCheckpoints)
|
|
return;
|
|
checkpoints.Add(new Checkpoint(time, previousTime, straightSteps, depositCursor, eventCursor,
|
|
(float[])temperature.Clone(), (float[])peak.Clone()));
|
|
}
|
|
|
|
// The latest checkpoint a straight run to the target passes: its last step was a full
|
|
// one, so the run had at least a full step left before it.
|
|
private Checkpoint CheckpointBefore(double seconds)
|
|
{
|
|
for (var i = checkpoints.Count - 1; i >= 0; i--)
|
|
{
|
|
if (seconds - checkpoints[i].PreviousTime >= maxStep)
|
|
return checkpoints[i];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private void Restore(Checkpoint checkpoint)
|
|
{
|
|
if (checkpoint.EventCursor != eventCursor)
|
|
{
|
|
if (checkpoint.EventCursor < eventCursor)
|
|
{
|
|
Array.Clear(region);
|
|
eventCursor = 0;
|
|
nextRegion = 0;
|
|
}
|
|
while (eventCursor < checkpoint.EventCursor)
|
|
ApplyToPieces(events[eventCursor]);
|
|
LinkAll();
|
|
}
|
|
|
|
checkpoint.Temperature.CopyTo(temperature, 0);
|
|
checkpoint.Peak.CopyTo(peak, 0);
|
|
depositCursor = checkpoint.DepositCursor;
|
|
time = checkpoint.Time;
|
|
straight = true;
|
|
straightSteps = checkpoint.StraightSteps;
|
|
}
|
|
|
|
// 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<Vector>();
|
|
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<Vector> 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<Vector> 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<int>();
|
|
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<Vector> 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 Checkpoint(double Time, double PreviousTime, int StraightSteps,
|
|
int DepositCursor, int EventCursor, float[] Temperature, float[] Peak);
|
|
|
|
private sealed record PieceEvent(double Time, int[] Cells, bool IsCutout);
|
|
}
|
|
}
|