mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-05 14:09:28 -05:00
With short steps only around the torch, the processor is faster than the card at the quarter-inch cells full sheets use, and the card only gained at a cell size they do not use. Drop OpenNest.Gpu, the ILGPU dependency and the accelerator interface; the heat map runs the same on every computer. The measured card timings stay in docs/plate-heat-map.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1093 lines
50 KiB
C#
1093 lines
50 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Runtime.InteropServices;
|
|
using System.Threading;
|
|
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>
|
|
/// <para>
|
|
/// While the torch cuts, steps are short enough to follow it, but only the cells around the
|
|
/// torch take them; the rest of the plate takes one step as long as diffusion allows.
|
|
/// Use one thread at a time.
|
|
/// </para>
|
|
/// </summary>
|
|
public sealed class PlateHeatSimulation
|
|
{
|
|
private const int Removed = -1;
|
|
private const double ArcStepRadians = System.Math.PI / 18;
|
|
private const int MaxCells = 700_000;
|
|
private const int MaxSamplesPerStep = 10_000;
|
|
|
|
// Cell updates for a whole run, counting diffusion-limited steps, when the cell size is
|
|
// automatic. The first halving may take a few seconds for the longest cuts, so a full
|
|
// sheet gets quarter-inch cells for cuts of several hours. Finer cells have to be quick:
|
|
// on a full sheet their hot lines are too thin to see and stretch the color scale.
|
|
private const double WorkBudget = 4_000_000_000;
|
|
private const double FinerWorkBudget = 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;
|
|
|
|
// A step adds all its heat at once, so one in which the torch crosses several cells
|
|
// lays it down in lumps that show as stripes along a straight cut. A step while cutting
|
|
// is therefore no longer than the torch takes to cross this many cells, though never
|
|
// shortened below the floor (a very high feed over fine cells). Cells this fine need half
|
|
// that where the diffusion step alone would let a slow torch cross a whole cell.
|
|
private const double MaxTravelCells = 1.0;
|
|
private const double FineTravelCells = 0.5;
|
|
private const double FineCellMeters = 0.004;
|
|
private const double MinStepSeconds = 0.005;
|
|
|
|
// Only the cells around the torch take those short steps: those within this many cells
|
|
// of where it put heat during the steps and the slot before them. The slot before keeps
|
|
// the cells beside a fresh cut on short steps until their own peak has passed. Heat
|
|
// moves a cell in about a slot, so the cells past the margin change too slowly to need
|
|
// more than the one long step the rest of the plate takes.
|
|
private const int WindowMargin = 4;
|
|
|
|
// Decay factors for long steps of odd lengths (a slot cut where a piece changes) are
|
|
// kept up to this much memory.
|
|
private const long IntervalKeepBytes = 32L << 20;
|
|
|
|
// Samples of the torch's path per cell; fewer leave some cells with more than others.
|
|
private const int SamplesPerCell = 4;
|
|
|
|
// 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 = 128L << 20;
|
|
|
|
// A cancellable run looks for a request before its first step and this often after.
|
|
private const int CancelCheckSteps = 64;
|
|
|
|
// 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.
|
|
internal const float Negligible = 1e-30f;
|
|
|
|
// Grids this large split each step's cells across processors.
|
|
private const int ParallelCells = 65_536;
|
|
|
|
private readonly List<(double Time, HeatSample Sample)> 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;
|
|
// The distinct contact fractions (a bed repeats a few), and which one each cell has.
|
|
private readonly float[] contactValues;
|
|
private readonly int[] contactValueOf;
|
|
private readonly double contactRate;
|
|
// Each cell's decay for a scheduled step, by the count its slot is split into.
|
|
private readonly Dictionary<int, float[]> splitKeeps = new();
|
|
private readonly float[] partialStepKeep;
|
|
private double partialStepSeconds = -1;
|
|
// Each cell's decay for a long step over some of a slot's steps, by split and count.
|
|
private readonly Dictionary<(int Split, int Count), float[]> intervalKeeps = new();
|
|
private readonly bool windowed;
|
|
// The window: the cells that take short steps, as runs along rows. Its cells and the
|
|
// ones touching them are copied twice (a short step reads one copy and writes the
|
|
// other), and its peaks kept from before the long step; all laid out as the grid is.
|
|
private readonly List<(int Start, int Length)> windowRuns = new();
|
|
private float[] windowCurrent;
|
|
private float[] windowNext;
|
|
private float[] windowPeak;
|
|
private byte[] windowCells;
|
|
private readonly double maxStep;
|
|
private readonly HeatStepSchedule schedule;
|
|
private bool onBoundary;
|
|
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);
|
|
schedule = new HeatStepSchedule(simulation, maxStep, cell,
|
|
dx < FineCellMeters ? FineTravelCells : MaxTravelCells, MinStepSeconds);
|
|
|
|
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);
|
|
partialStepKeep = new float[count];
|
|
(contactValues, contactValueOf) = Distinct(contactFraction);
|
|
}
|
|
}
|
|
|
|
maxCheckpoints = (int)System.Math.Max(1, CheckpointBytes / (8L * count));
|
|
var runSteps = (double)schedule.StepCount;
|
|
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();
|
|
windowed = !parameters.WholePlateSteps;
|
|
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. A cancelled run stops between two steps.
|
|
/// </summary>
|
|
public void AdvanceTo(TimeSpan target, CancellationToken cancellationToken = default)
|
|
{
|
|
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);
|
|
}
|
|
|
|
var taken = 0;
|
|
while (time < seconds)
|
|
{
|
|
if (taken++ % CancelCheckSteps == 0)
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
var (slot, index, split) = schedule.StepAfter(time);
|
|
var boundary = schedule.End(slot, index, split);
|
|
var reaches = boundary <= seconds;
|
|
var end = reaches ? boundary : seconds;
|
|
// A whole scheduled step has exactly the nominal length, whatever the rounding
|
|
// of its ends, so every run through it computes the same.
|
|
var whole = reaches && onBoundary;
|
|
var count = 1;
|
|
var complete = true;
|
|
if (whole && windowed && split > 1)
|
|
count = IntervalSteps(slot, index, split, seconds, out complete);
|
|
|
|
if (count > 1)
|
|
StepInterval(slot, index, split, count);
|
|
else
|
|
Step(whole ? maxStep / split : end - time, end, whole ? split : 0);
|
|
onBoundary = reaches;
|
|
// A straight run takes every interval whole; one cut short by the target has
|
|
// left its path.
|
|
if (!whole || !complete)
|
|
straight = false;
|
|
if (!straight || !whole)
|
|
continue;
|
|
straightSteps += count;
|
|
Record();
|
|
}
|
|
}
|
|
|
|
/// <summary>Runs the whole cut, then <paramref name="cooling"/> more.</summary>
|
|
public void RunToEnd(TimeSpan cooling = default, CancellationToken cancellationToken = default) =>
|
|
AdvanceTo(Simulation.TotalTime + cooling, cancellationToken);
|
|
|
|
public void Reset()
|
|
{
|
|
Array.Clear(temperature);
|
|
Array.Clear(peak);
|
|
ResetPieces();
|
|
depositCursor = 0;
|
|
time = 0;
|
|
onBoundary = true;
|
|
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 diffusion-limited step) stays within its 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, short (going back resumes from a checkpoint). The torch travel limit is left out
|
|
// so that feed does not change the picture's resolution.
|
|
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;
|
|
var budget = halvings == 0 ? WorkBudget : FinerWorkBudget;
|
|
// Twelve millimeter halves to 3 mm, a little under an eighth inch.
|
|
if (CellCount(bounds, finer) > MaxCells || RunWork(bounds, seconds, finer, parameters) > budget)
|
|
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));
|
|
|
|
// The whole steps, from this one on, that go as one interval: up to the end of the slot
|
|
// or the step before one in which a piece changes (the same for every run), or, not
|
|
// complete, up to the target.
|
|
private int IntervalSteps(long slot, int index, int split, double seconds, out bool complete)
|
|
{
|
|
var pending = eventCursor;
|
|
var first = schedule.End(slot, index, split);
|
|
while (pending < events.Count && events[pending].Time <= first)
|
|
pending++;
|
|
|
|
complete = true;
|
|
var count = 1;
|
|
while (index + count <= split)
|
|
{
|
|
var end = schedule.End(slot, index + count, split);
|
|
if (pending < events.Count && events[pending].Time <= end)
|
|
break;
|
|
if (end > seconds)
|
|
{
|
|
complete = false;
|
|
break;
|
|
}
|
|
count++;
|
|
}
|
|
return count;
|
|
}
|
|
|
|
// Several whole steps of one slot at once. The window around the torch takes them one
|
|
// by one, as Step would, with the cells next to it held where they started; every
|
|
// other cell takes a single step of their combined length. Pieces change only in the
|
|
// first step (IntervalSteps), so the links hold throughout.
|
|
private void StepInterval(long slot, int index, int split, int count)
|
|
{
|
|
var start = time;
|
|
var firstEnd = schedule.End(slot, index, split);
|
|
var lastEnd = schedule.End(slot, index + count - 1, split);
|
|
var from = depositCursor;
|
|
while (depositCursor < deposits.Count && deposits[depositCursor].Time <= firstEnd)
|
|
depositCursor++;
|
|
for (var i = from; i < depositCursor; i++)
|
|
Add(deposits[i].Sample, temperature);
|
|
while (eventCursor < events.Count && events[eventCursor].Time <= firstEnd)
|
|
Apply(events[eventCursor]);
|
|
|
|
var to = depositCursor;
|
|
while (to < deposits.Count && deposits[to].Time <= lastEnd)
|
|
to++;
|
|
|
|
var seconds = count == split ? maxStep : maxStep * count / split;
|
|
var share = (float)(diffusionRate * seconds);
|
|
var keep = (float)System.Math.Exp(-lossRate * seconds);
|
|
var cellKeep = contactFraction == null ? null : IntervalKeep(split, count, seconds);
|
|
if (to == from)
|
|
{
|
|
// No heat from the torch in these steps, so one long step everywhere, the cells
|
|
// beside the last cut included.
|
|
Diffuse(share, keep, cellKeep);
|
|
time = lastEnd;
|
|
return;
|
|
}
|
|
|
|
FindWindow(start, from, to);
|
|
CopyWindow();
|
|
|
|
// The long step would also raise the window's peaks, from values the short steps
|
|
// replace.
|
|
Diffuse(share, keep, cellKeep);
|
|
foreach (var (first, length) in windowRuns)
|
|
Array.Copy(windowPeak, first, peak, first, length);
|
|
|
|
var stepSeconds = maxStep / split;
|
|
var stepShare = (float)(diffusionRate * stepSeconds);
|
|
var stepKeep = (float)System.Math.Exp(-lossRate * stepSeconds);
|
|
var stepCellKeep = contactFraction == null ? null : SplitKeep(split);
|
|
for (var k = 0; k < count; k++)
|
|
{
|
|
if (k > 0)
|
|
{
|
|
var end = schedule.End(slot, index + k, split);
|
|
for (; depositCursor < to && deposits[depositCursor].Time <= end; depositCursor++)
|
|
Add(deposits[depositCursor].Sample, windowCurrent);
|
|
}
|
|
foreach (var (first, length) in windowRuns)
|
|
DiffuseCells(windowCurrent, windowNext, first, first + length, stepShare, stepKeep, stepCellKeep);
|
|
(windowCurrent, windowNext) = (windowNext, windowCurrent);
|
|
}
|
|
foreach (var (first, length) in windowRuns)
|
|
Array.Copy(windowCurrent, first, temperature, first, length);
|
|
depositCursor = to;
|
|
time = lastEnd;
|
|
}
|
|
|
|
// Lists the window's cells in windowRuns: every cell within the margin of a cell that
|
|
// samples from to to, or those of the slot before the interval, put heat in.
|
|
private void FindWindow(double start, int from, int to)
|
|
{
|
|
windowCells ??= new byte[temperature.Length];
|
|
var first = from;
|
|
while (first > 0 && deposits[first - 1].Time > start - maxStep)
|
|
first--;
|
|
|
|
int firstRow = int.MaxValue, lastRow = -1, firstColumn = int.MaxValue, lastColumn = -1;
|
|
var previous = -1;
|
|
for (var i = first; i < to; i++)
|
|
{
|
|
var sample = deposits[i].Sample;
|
|
var corner = sample.Lower * Columns + sample.Left;
|
|
if (corner == previous)
|
|
continue;
|
|
previous = corner;
|
|
|
|
var left = System.Math.Max(0, sample.Left - WindowMargin);
|
|
var right = System.Math.Min(Columns - 1, sample.Left + 1 + WindowMargin);
|
|
var lower = System.Math.Max(0, sample.Lower - WindowMargin);
|
|
var upper = System.Math.Min(Rows - 1, sample.Lower + 1 + WindowMargin);
|
|
for (var row = lower; row <= upper; row++)
|
|
windowCells.AsSpan(row * Columns + left, right - left + 1).Fill(1);
|
|
firstRow = System.Math.Min(firstRow, lower);
|
|
lastRow = System.Math.Max(lastRow, upper);
|
|
firstColumn = System.Math.Min(firstColumn, left);
|
|
lastColumn = System.Math.Max(lastColumn, right);
|
|
}
|
|
|
|
windowRuns.Clear();
|
|
for (var row = firstRow; row <= lastRow; row++)
|
|
{
|
|
var cells = windowCells.AsSpan(row * Columns + firstColumn, lastColumn - firstColumn + 1);
|
|
var at = 0;
|
|
while (at < cells.Length)
|
|
{
|
|
var skip = cells[at..].IndexOf((byte)1);
|
|
if (skip < 0)
|
|
break;
|
|
at += skip;
|
|
var length = cells[at..].IndexOf((byte)0);
|
|
if (length < 0)
|
|
length = cells.Length - at;
|
|
windowRuns.Add((row * Columns + firstColumn + at, length));
|
|
at += length;
|
|
}
|
|
cells.Clear();
|
|
}
|
|
}
|
|
|
|
// Copies the window's cells, and the cells touching them, which keep these values while
|
|
// it steps.
|
|
private void CopyWindow()
|
|
{
|
|
windowCurrent ??= new float[temperature.Length];
|
|
windowNext ??= new float[temperature.Length];
|
|
windowPeak ??= new float[temperature.Length];
|
|
foreach (var (first, length) in windowRuns)
|
|
{
|
|
Array.Copy(peak, first, windowPeak, first, length);
|
|
var column = first % Columns;
|
|
var left = column > 0 ? first - 1 : first;
|
|
var cells = length + (column > 0 ? 1 : 0) + (column + length < Columns ? 1 : 0);
|
|
for (var at = left - Columns; at <= left + Columns; at += Columns)
|
|
{
|
|
if (at < 0 || at >= temperature.Length)
|
|
continue;
|
|
Array.Copy(temperature, at, windowCurrent, at, cells);
|
|
Array.Copy(temperature, at, windowNext, at, cells);
|
|
}
|
|
}
|
|
}
|
|
|
|
// split names the scheduled step length, or is zero for a step cut short.
|
|
private void Step(double seconds, double end, int split)
|
|
{
|
|
var from = depositCursor;
|
|
while (depositCursor < deposits.Count && deposits[depositCursor].Time <= end)
|
|
depositCursor++;
|
|
for (var i = from; i < depositCursor; i++)
|
|
Add(deposits[i].Sample, temperature);
|
|
while (eventCursor < events.Count && events[eventCursor].Time <= end)
|
|
Apply(events[eventCursor]);
|
|
|
|
var share = (float)(diffusionRate * seconds);
|
|
var keep = (float)System.Math.Exp(-lossRate * seconds);
|
|
var cellKeep = contactFraction == null ? null
|
|
: split > 0 ? SplitKeep(split)
|
|
: PartialStepKeep(seconds);
|
|
Diffuse(share, keep, cellKeep);
|
|
time = end;
|
|
}
|
|
|
|
// Shares a sample between the four cells whose centers surround the torch, by how close
|
|
// it is to each, so heat moves smoothly across the grid with the torch. Only cells of
|
|
// the piece under the torch take a share, which keeps heat from crossing a kerf. The
|
|
// heat goes into target: the grid, or a window's copy of it.
|
|
private void Add(HeatSample deposit, float[] target)
|
|
{
|
|
var piece = region[deposit.Cell];
|
|
if (piece == Removed)
|
|
return;
|
|
|
|
var left = deposit.Left;
|
|
var right = System.Math.Min(left + 1, Columns - 1);
|
|
var lower = deposit.Lower * Columns;
|
|
var upper = System.Math.Min(deposit.Lower + 1, Rows - 1) * Columns;
|
|
var lowerLeft = Share(lower + left, piece, (1 - deposit.X) * (1 - deposit.Y));
|
|
var lowerRight = Share(lower + right, piece, deposit.X * (1 - deposit.Y));
|
|
var upperLeft = Share(upper + left, piece, (1 - deposit.X) * deposit.Y);
|
|
var upperRight = Share(upper + right, piece, deposit.X * deposit.Y);
|
|
|
|
// The cell under the torch always has a share, so the total is never zero.
|
|
var rise = deposit.Rise / (lowerLeft + lowerRight + upperLeft + upperRight);
|
|
target[lower + left] += rise * lowerLeft;
|
|
target[lower + right] += rise * lowerRight;
|
|
target[upper + left] += rise * upperLeft;
|
|
target[upper + right] += rise * upperRight;
|
|
}
|
|
|
|
private float Share(int cell, int piece, float weight) => region[cell] == piece ? weight : 0f;
|
|
|
|
// 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(float share, float keep, float[] cellKeep)
|
|
{
|
|
// 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(temperature, next, 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(temperature, next, last, count, share, keep, cellKeep);
|
|
(temperature, next) = (next, temperature);
|
|
}
|
|
|
|
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
|
private void DiffuseCells(float[] current, float[] result, int start, int end, float share, float keep, float[] cellKeep)
|
|
{
|
|
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;
|
|
result[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 scheduled
|
|
// ones; playback ends each frame on a shorter one, kept until its length changes.
|
|
private float[] SplitKeep(int split)
|
|
{
|
|
if (!splitKeeps.TryGetValue(split, out var keep))
|
|
splitKeeps[split] = keep = ContactKeep(maxStep / split, new float[temperature.Length]);
|
|
return keep;
|
|
}
|
|
|
|
private float[] PartialStepKeep(double seconds)
|
|
{
|
|
if (seconds != partialStepSeconds)
|
|
{
|
|
ContactKeep(seconds, partialStepKeep);
|
|
partialStepSeconds = seconds;
|
|
}
|
|
return partialStepKeep;
|
|
}
|
|
|
|
// The decay over a long step of count of a slot's split steps; a whole slot's is the one
|
|
// an unsplit slot uses.
|
|
private float[] IntervalKeep(int split, int count, double seconds)
|
|
{
|
|
if (count == split)
|
|
return SplitKeep(1);
|
|
if (!intervalKeeps.TryGetValue((split, count), out var keep))
|
|
{
|
|
if ((intervalKeeps.Count + 1) * 4L * temperature.Length > IntervalKeepBytes)
|
|
intervalKeeps.Clear();
|
|
intervalKeeps[(split, count)] = keep = ContactKeep(seconds, new float[temperature.Length]);
|
|
}
|
|
return keep;
|
|
}
|
|
|
|
// The exponential is worked out once per distinct contact fraction, not per cell.
|
|
private float[] ContactKeep(double seconds, float[] keep)
|
|
{
|
|
var values = new float[contactValues.Length];
|
|
for (var i = 0; i < values.Length; i++)
|
|
values[i] = (float)System.Math.Exp(-(lossRate + contactRate * contactValues[i]) * seconds);
|
|
for (var i = 0; i < keep.Length; i++)
|
|
keep[i] = values[contactValueOf[i]];
|
|
return keep;
|
|
}
|
|
|
|
private static (float[] Values, int[] IndexOf) Distinct(float[] source)
|
|
{
|
|
var seen = new Dictionary<float, int>();
|
|
var values = new List<float>();
|
|
var indexOf = new int[source.Length];
|
|
for (var i = 0; i < source.Length; i++)
|
|
{
|
|
if (!seen.TryGetValue(source[i], out var index))
|
|
{
|
|
seen[source[i]] = index = values.Count;
|
|
values.Add(source[i]);
|
|
}
|
|
indexOf[i] = index;
|
|
}
|
|
return (values.ToArray(), indexOf);
|
|
}
|
|
|
|
// 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 of a straight run from the start (one never cut short by an
|
|
// earlier target) each time its step count passes another multiple of checkpointInterval,
|
|
// kept as the run passes them. A straight run to any later target takes exactly the same
|
|
// steps up to there, so it passes the same states.
|
|
private void Record()
|
|
{
|
|
var number = straightSteps / checkpointInterval;
|
|
var last = checkpoints.Count == 0 ? 0 : checkpoints[^1].Number;
|
|
if (number <= last || checkpoints.Count >= maxCheckpoints)
|
|
return;
|
|
checkpoints.Add(new Checkpoint(time, straightSteps, number, depositCursor, eventCursor,
|
|
(float[])temperature.Clone(), (float[])peak.Clone()));
|
|
}
|
|
|
|
// The latest checkpoint a straight run to the target passes.
|
|
private Checkpoint CheckpointBefore(double seconds)
|
|
{
|
|
for (var i = checkpoints.Count - 1; i >= 0; i--)
|
|
{
|
|
if (checkpoints[i].Time <= seconds)
|
|
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;
|
|
onBoundary = true;
|
|
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 / SamplesPerCell;
|
|
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)
|
|
return;
|
|
|
|
// Beyond the outermost cell centers the edge cell takes both shares.
|
|
var x = System.Math.Clamp((point.X - OriginX) / CellSize - 0.5, 0, Columns - 1);
|
|
var y = System.Math.Clamp((point.Y - OriginY) / CellSize - 0.5, 0, Rows - 1);
|
|
var left = (int)x;
|
|
var lower = (int)y;
|
|
deposits.Add((at, new HeatSample(cell, left, lower, (float)(x - left), (float)(y - lower), (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 sealed record Checkpoint(double Time, int StraightSteps, int Number,
|
|
int DepositCursor, int EventCursor, float[] Temperature, float[] Peak);
|
|
|
|
private sealed record PieceEvent(double Time, int[] Cells, bool IsCutout);
|
|
}
|
|
}
|