diff --git a/AGENTS.md b/AGENTS.md index 034713fb..bacdb0ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,6 +45,7 @@ Releases: follow [the release procedure](docs/releasing.md) and `scripts/Publish - `OpenNest.IO`: ACadSharp and SVG import/export and ZIP-based `.nest` persistence; depends on Core only (an IO.Tests guard enforces it). Best fits persist only when callers pass `BestFitCacheStore.Shared` as `NestReader`/`NestWriter.BestFitStore`. All DXF-to-Drawing conversion goes through `CadImporter`: `Import` + `BuildDrawing` for editable/reporting flows, `ImportDrawing` for headless callers. Preserve source offsets, entity IDs, suppressed entities and bends. Bend repair is opt-in, requires explicit source units and may not alter cut geometry or unrelated marks. - `OpenNest`: WinForms UI (`Forms/`, `Controls/PlateView`, `Actions/`). `OpenNest.Data` holds cross-platform persistence; new-nest defaults live in `%APPDATA%\OpenNest\defaults.json` (in Database mode, the server's shared copy once it holds one). WinForms `Properties.Settings` persist to `%APPDATA%\OpenNest\user-settings.json` through `AppDataSettingsProvider`, never inside the Velopack install folder; `OpenNest.WinForms.Tests` redirects them to a temp file, so a test run never writes the user's settings. Posts live in `Posts/OpenNest.Posts./` and deploy to each desktop app's output `Posts/` directory (WinForms and Avalonia). Desktop nest edits go through `BeginChange`/`RecordChange`; see [undo and redo](docs/undo-redo.md). - `OpenNest.Desktop` (net8.0): toolkit-neutral desktop logic shared by the WinForms app and `OpenNest.Avalonia`, the cross-platform desktop in progress. It must not reference WinForms/WindowsDesktop, `System.Drawing.Common` or Avalonia (`OpenNest.Desktop.Tests` guards this, including transitive packages); put toolkit-specific rendering, dialogs and settings behind adapters in the front ends. +- `OpenNest.Gpu`: optional ILGPU accelerator for the [heat map](docs/plate-heat-map.md), referencing Core only; Core and Desktop stay free of it and everything must work without a card. Its kernels mirror the CPU heat code. - `OpenNest.Server`: nest storage HTTP service, kept off Engine and IO. `OpenNest.Server.Worker`: the server nesting worker, shipped in the same image. - `OpenNest.Console`, `OpenNest.Mcp`, `OpenNest.Api`: front ends; `OpenNest.Benchmark`: whole-job engine comparisons; `OpenNest.Training`: ML data collection and the Python sketch-search prototype (`sketch-search/README.md`). Benchmark timing comparisons require `--parallel 1`; validate layouts and fulfillment, not just elapsed time. diff --git a/OpenNest.Core/CNC/Thermal/HeatAccelerator.cs b/OpenNest.Core/CNC/Thermal/HeatAccelerator.cs new file mode 100644 index 00000000..cbb1fff1 --- /dev/null +++ b/OpenNest.Core/CNC/Thermal/HeatAccelerator.cs @@ -0,0 +1,75 @@ +using System; + +namespace OpenNest.CNC.Thermal +{ + /// + /// Runs the grid work of a on other hardware, such as a + /// graphics card. The simulation keeps the pieces, the timeline and the checkpoints; the + /// accelerator keeps the temperatures. Its results match the built-in CPU's closely but not + /// bit for bit. + /// + public interface IHeatAccelerator + { + /// The hardware, as shown to the user. + string Name { get; } + + /// + /// A grid of by cells heated by + /// , which are given in time order. Throws when the hardware + /// cannot hold it. + /// + IHeatKernel Create(int columns, int rows, ReadOnlySpan samples); + } + + /// One grid on an . + public interface IHeatKernel : IDisposable + { + /// Sets every temperature and peak to zero. + void Clear(); + + /// + /// Replaces every cell's piece and links. is -1 where material + /// fell away; has bit 0 for a link left, 1 right, 2 below and + /// 3 above. + /// + void SetCells(ReadOnlySpan region, ReadOnlySpan links); + + /// + /// Changes the cells listed in (each once), and drops the heat of + /// those whose region is -1. + /// + void ChangeCells(ReadOnlySpan cells, ReadOnlySpan region, ReadOnlySpan links); + + /// + /// Adds samples up to , each shared between + /// the cells around it that are in its cell's piece, as the CPU does. + /// + void AddSamples(int from, int to); + + /// + /// One explicit step: each cell takes times its difference to + /// every linked neighbor, then keeps the given fraction of its rise. Peaks follow. + /// + /// Diffusion number of the step. + /// The fraction every cell keeps when is null. + /// The fraction each cell keeps. + /// + /// Names so it need be copied only once; negative for an array + /// to copy every time. + /// + void Step(float share, float keep, float[] cellKeep, int keepKey); + + /// Copies the temperatures and peaks out, after all steps so far. + void Read(float[] temperature, float[] peak); + + /// Replaces the temperatures and peaks. + void Write(float[] temperature, float[] peak); + } + + /// + /// Heat from a moment of cutting: the cell under the torch, and the torch's position between + /// cell centers ( and , 0 to 1, from column + /// and row ). + /// + public readonly record struct HeatSample(int Cell, int Left, int Lower, float X, float Y, float Rise); +} diff --git a/OpenNest.Core/CNC/Thermal/HeatStepSchedule.cs b/OpenNest.Core/CNC/Thermal/HeatStepSchedule.cs new file mode 100644 index 00000000..a6cd22b5 --- /dev/null +++ b/OpenNest.Core/CNC/Thermal/HeatStepSchedule.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; + +namespace OpenNest.CNC.Thermal +{ + /// + /// The time steps of a run. Time is divided into slots as + /// long as the diffusion limit allows, and a slot in which the torch cuts is split into equal + /// steps short enough for that move's speed, so only the time that needs short steps pays for + /// them. The boundaries depend on the timeline alone, so a replay takes the same steps. + /// + internal sealed class HeatStepSchedule + { + // Slots are split only into these counts, so a run has few distinct step lengths and + // each one's decay factors can be kept. + private static readonly int[] Splits = { 1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96, 128, 160, 200 }; + + // Two times closer than this share of a slot are the same boundary. + private const double Tolerance = 1e-9; + + private readonly int[] splits; + + /// The timeline. + /// The longest step the diffusion allows. + /// Cell edge in the plate's units. + /// The most cells the torch may cross in one step. + /// No step is split shorter than this for the torch's sake. + public HeatStepSchedule(CutSimulation simulation, double slotSeconds, double cellSize, + double travelCells, double minSeconds) + { + SlotSeconds = slotSeconds; + var total = simulation.TotalTime.TotalSeconds; + splits = new int[(int)System.Math.Max(0, System.Math.Ceiling(total / slotSeconds))]; + Array.Fill(splits, 1); + + foreach (var step in simulation.Steps) + { + var seconds = step.Duration.TotalSeconds; + if (step.Kind != CutSimulationStepKind.Cut || seconds <= 0 || step.Length <= 0) + continue; + + var limit = System.Math.Max(minSeconds, travelCells * cellSize * seconds / step.Length); + var split = SplitFor(slotSeconds / limit); + if (split == 1) + continue; + + var start = step.StartTime.TotalSeconds; + var first = (int)System.Math.Floor(start / slotSeconds + Tolerance); + var last = (int)System.Math.Ceiling((start + seconds) / slotSeconds - Tolerance) - 1; + for (var slot = System.Math.Max(0, first); slot <= System.Math.Min(splits.Length - 1, last); slot++) + splits[slot] = System.Math.Max(splits[slot], split); + } + + foreach (var split in splits) + StepCount += split; + } + + public double SlotSeconds { get; } + + /// Steps from the start to the end of the cut. + public long StepCount { get; } + + /// + /// The first step boundary after , with the count its slot is + /// split into. Past the cut, slots are whole. + /// + public (double Time, int Split) Next(double time) + { + var slot = (long)System.Math.Floor(time / SlotSeconds + Tolerance); + while (true) + { + var split = slot < splits.Length ? splits[slot] : 1; + var start = slot * SlotSeconds; + var index = System.Math.Max(1, (long)System.Math.Floor((time - start) / SlotSeconds * split + Tolerance) + 1); + if (index <= split) + { + var boundary = index == split ? (slot + 1) * SlotSeconds : start + SlotSeconds * index / split; + return (boundary, split); + } + slot++; + } + } + + private static int SplitFor(double needed) + { + foreach (var split in Splits) + { + if (split >= needed - 1e-6) + return split; + } + return Splits[^1]; + } + } +} diff --git a/OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs b/OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs index 26790487..f0998efd 100644 --- a/OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs +++ b/OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs @@ -2,6 +2,7 @@ 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; @@ -23,17 +24,27 @@ namespace OpenNest.CNC.Thermal /// estimates for comparing cut orders, not calibrated temperatures; see /// docs/plate-heat-map.md. /// + /// + /// With large grids run on it, close to the CPU's + /// results but not bit for bit. Use one thread at a time, and dispose to release it. + /// /// - public sealed class PlateHeatSimulation + public sealed class PlateHeatSimulation : IDisposable { private const int Removed = -1; private const double ArcStepRadians = System.Math.PI / 18; - private const int MaxCells = 400_000; + 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 torch travel limit below can multiply the actual steps a few times. - private const double WorkBudget = 60_000_000; + // automatic: on the processor about a second, so a full sheet gets quarter-inch cells; on + // an accelerator a couple of seconds, for eighth-inch cells. The torch travel limit can + // multiply the actual steps a few times. + private const double WorkBudget = 800_000_000; + private const double AcceleratedWorkBudget = 20_000_000_000; + + // Below this an accelerator spends longer starting each step than the step takes. + private const int AcceleratedCells = 100_000; private const int MaxHalvings = 3; // Explicit diffusion is stable below a quarter on a square grid; the cap keeps timing @@ -42,10 +53,13 @@ namespace OpenNest.CNC.Thermal 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 is therefore - // no longer than the torch takes to cross this many cells at its fastest, though never - // shortened below the floor (a very high feed over fine 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; // Samples of the torch's path per cell; fewer leave some cells with more than others. @@ -55,7 +69,10 @@ namespace OpenNest.CNC.Thermal // 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; + private const long CheckpointBytes = 128L << 20; + + // A cancellable run looks for a request this often. + private const int CancelCheckSteps = 64; // Going forward, a checkpoint this many steps past the current time beats stepping there. private const int SkipAheadSteps = 8; @@ -63,12 +80,12 @@ namespace OpenNest.CNC.Thermal // 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; + 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 deposits = new(); + private readonly List<(double Time, HeatSample Sample)> deposits = new(); private readonly List events = new(); private readonly int[] region; private float[] temperature; @@ -78,10 +95,16 @@ namespace OpenNest.CNC.Thermal private readonly double lossRate; private readonly float[] contactFraction; private readonly double contactRate; - private readonly float[] fullStepKeep; + // Each cell's decay for a scheduled step, by the count its slot is split into. + private readonly Dictionary splitKeeps = new(); private readonly float[] partialStepKeep; private double partialStepSeconds = -1; private readonly double maxStep; + private readonly HeatStepSchedule schedule; + private readonly IHeatKernel kernel; + // True while the accelerator is ahead of the arrays here. + private bool stale; + private bool onBoundary; private readonly float[] leftLink; private readonly float[] rightLink; private readonly float[] belowLink; @@ -137,9 +160,8 @@ namespace OpenNest.CNC.Thermal diffusionRate = material.Diffusivity / (dx * dx); lossRate = 2 * parameters.SurfaceCoefficient / (volumetricHeat * thickness); maxStep = System.Math.Min(MaxStepSeconds, StabilityFactor / diffusionRate); - var fastest = FastestCut(simulation); - if (fastest > 0) - maxStep = System.Math.Min(maxStep, System.Math.Max(MinStepSeconds, MaxTravelCells * cell / fastest)); + schedule = new HeatStepSchedule(simulation, maxStep, cell, + dx < FineCellMeters ? FineTravelCells : MaxTravelCells, MinStepSeconds); if (parameters.SupportBed != null && parameters.ContactCoefficient > 0) { @@ -149,19 +171,25 @@ namespace OpenNest.CNC.Thermal { // 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); + 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(); + if (parameters.Accelerator != null && count >= AcceleratedCells) + { + var samples = new HeatSample[deposits.Count]; + for (var i = 0; i < samples.Length; i++) + samples[i] = deposits[i].Sample; + kernel = parameters.Accelerator.Create(Columns, Rows, samples); + } Reset(); } @@ -185,10 +213,27 @@ namespace OpenNest.CNC.Thermal 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; + public ReadOnlySpan Temperatures + { + get + { + Synchronize(); + return temperature; + } + } /// The highest rise each cell has reached so far. - public ReadOnlySpan Peaks => peak; + public ReadOnlySpan Peaks + { + get + { + Synchronize(); + return peak; + } + } + + /// True when the grid runs on . + public bool IsAccelerated => kernel != null; /// True when heat is also lost into the support bed (). public bool UsesSupportBed => contactFraction != null; @@ -218,9 +263,9 @@ namespace OpenNest.CNC.Thermal /// /// Runs the model to . 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. + /// state is exactly that run's. A cancelled run stops between two steps. /// - public void AdvanceTo(TimeSpan target) + public void AdvanceTo(TimeSpan target, CancellationToken cancellationToken = default) { var seconds = target.TotalSeconds; var checkpoint = CheckpointBefore(seconds); @@ -236,35 +281,58 @@ namespace OpenNest.CNC.Thermal Restore(checkpoint); } + var taken = 0; while (time < seconds) { - var step = System.Math.Min(maxStep, seconds - time); - var previous = time; - Step(step); - if (step != maxStep) + if (++taken % CancelCheckSteps == 0) + cancellationToken.ThrowIfCancellationRequested(); + + var (boundary, split) = schedule.Next(time); + 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; + Step(whole ? maxStep / split : end - time, end, whole ? split : 0); + onBoundary = reaches; + if (!whole) { straight = false; continue; } if (straight && ++straightSteps % checkpointInterval == 0) - Record(previous); + Record(); } } /// Runs the whole cut, then more. - public void RunToEnd(TimeSpan cooling = default) => AdvanceTo(Simulation.TotalTime + cooling); + public void RunToEnd(TimeSpan cooling = default, CancellationToken cancellationToken = default) => + AdvanceTo(Simulation.TotalTime + cooling, cancellationToken); public void Reset() { Array.Clear(temperature); Array.Clear(peak); ResetPieces(); + kernel?.Clear(); + stale = false; depositCursor = 0; time = 0; + onBoundary = true; straight = true; straightSteps = 0; } + public void Dispose() => kernel?.Dispose(); + + private void Synchronize() + { + if (!stale) + return; + kernel.Read(temperature, peak); + stale = false; + } + /// Index of the largest value, or -1 when every value is zero or less. public static int IndexOfMax(ReadOnlySpan values) { @@ -282,19 +350,21 @@ namespace OpenNest.CNC.Thermal } // The finest cell, from the coarsest default halved down to the finest, whose whole run - // (every cell, every diffusion-limited 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, - // short (going back resumes from a checkpoint); large sheets stay at the coarsest. The - // torch travel limit is left out so that feed does not change the picture's resolution. + // (every cell, every diffusion-limited 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, 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 budget = parameters.Accelerator == null ? WorkBudget : AcceleratedWorkBudget; var cell = coarsest; for (var halvings = 0; halvings < MaxHalvings; halvings++) { var finer = cell / 2; - if (RunWork(bounds, seconds, finer, parameters) > WorkBudget) + // 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; } @@ -312,24 +382,45 @@ namespace OpenNest.CNC.Thermal (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) + // split names the scheduled step length, or is zero for a step cut short. + private void Step(double seconds, double end, int split) { - var end = time + seconds; + var from = depositCursor; while (depositCursor < deposits.Count && deposits[depositCursor].Time <= end) + depositCursor++; + if (kernel == null) { - Add(deposits[depositCursor++]); + for (var i = from; i < depositCursor; i++) + Add(deposits[i].Sample); + } + else if (depositCursor > from) + { + kernel.AddSamples(from, depositCursor); } while (eventCursor < events.Count && events[eventCursor].Time <= end) Apply(events[eventCursor]); - Diffuse(seconds); + var share = (float)(diffusionRate * seconds); + var keep = (float)System.Math.Exp(-lossRate * seconds); + var cellKeep = contactFraction == null ? null + : split > 0 ? SplitKeep(split) + : PartialStepKeep(seconds); + if (kernel == null) + { + Diffuse(share, keep, cellKeep); + } + else + { + kernel.Step(share, keep, cellKeep, split > 0 ? split : -1); + stale = true; + } 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. - private void Add(Deposit deposit) + private void Add(HeatSample deposit) { var piece = region[deposit.Cell]; if (piece == Removed) @@ -359,14 +450,8 @@ namespace OpenNest.CNC.Thermal // (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) + private void Diffuse(float share, float keep, float[] cellKeep) { - 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; @@ -460,8 +545,15 @@ namespace OpenNest.CNC.Thermal } // 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. + // 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) @@ -546,8 +638,51 @@ namespace OpenNest.CNC.Thermal ApplyToPieces(piece); foreach (var cell in piece.Cells) LinkAround(cell); + if (kernel != null) + SendChanged(piece.Cells); } + private void SendChanged(int[] changed) + { + var around = new HashSet(); + foreach (var cell in changed) + { + around.Add(cell); + if (cell % Columns > 0) + around.Add(cell - 1); + if (cell % Columns < Columns - 1) + around.Add(cell + 1); + if (cell >= Columns) + around.Add(cell - Columns); + if (cell + Columns < region.Length) + around.Add(cell + Columns); + } + + var cells = new int[around.Count]; + around.CopyTo(cells); + var regions = new int[cells.Length]; + var links = new int[cells.Length]; + for (var i = 0; i < cells.Length; i++) + { + regions[i] = region[cells[i]]; + links[i] = LinkBits(cells[i]); + } + kernel.ChangeCells(cells, regions, links); + } + + private void SendAll() + { + if (kernel == null) + return; + var links = new int[region.Length]; + for (var i = 0; i < links.Length; i++) + links[i] = LinkBits(i); + kernel.SetCells(region, links); + } + + private int LinkBits(int i) => (leftLink[i] != 0 ? 1 : 0) | (rightLink[i] != 0 ? 2 : 0) + | (belowLink[i] != 0 ? 4 : 0) | (aboveLink[i] != 0 ? 8 : 0); + private void ApplyToPieces(PieceEvent piece) { eventCursor++; @@ -582,6 +717,7 @@ namespace OpenNest.CNC.Thermal eventCursor = 0; nextRegion = 0; LinkAll(); + SendAll(); } private void LinkAll() @@ -616,25 +752,25 @@ namespace OpenNest.CNC.Thermal 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 + // Checkpoints: the state after every checkpointInterval 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) + private void Record() { var index = straightSteps / checkpointInterval - 1; if (index != checkpoints.Count || index >= maxCheckpoints) return; - checkpoints.Add(new Checkpoint(time, previousTime, straightSteps, depositCursor, eventCursor, + Synchronize(); + checkpoints.Add(new Checkpoint(time, 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. + // 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 (seconds - checkpoints[i].PreviousTime >= maxStep) + if (checkpoints[i].Time <= seconds) return checkpoints[i]; } return null; @@ -653,12 +789,16 @@ namespace OpenNest.CNC.Thermal while (eventCursor < checkpoint.EventCursor) ApplyToPieces(events[eventCursor]); LinkAll(); + SendAll(); } checkpoint.Temperature.CopyTo(temperature, 0); checkpoint.Peak.CopyTo(peak, 0); + kernel?.Write(temperature, peak); + stale = false; depositCursor = checkpoint.DepositCursor; time = checkpoint.Time; + onBoundary = true; straight = true; straightSteps = checkpoint.StraightSteps; } @@ -705,20 +845,7 @@ namespace OpenNest.CNC.Thermal var y = System.Math.Clamp((point.Y - OriginY) / CellSize - 0.5, 0, Rows - 1); var left = (int)x; var lower = (int)y; - deposits.Add(new Deposit(at, cell, left, lower, (float)(x - left), (float)(y - lower), (float)rise)); - } - - // The highest average speed of any cutting move, in plate units per second. - private static double FastestCut(CutSimulation simulation) - { - var fastest = 0.0; - foreach (var step in simulation.Steps) - { - var seconds = step.Duration.TotalSeconds; - if (step.Kind == CutSimulationStepKind.Cut && seconds > 0) - fastest = System.Math.Max(fastest, step.Length / seconds); - } - return fastest; + 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 @@ -817,12 +944,7 @@ namespace OpenNest.CNC.Thermal return inside; } - // A sample of the torch's heat: the cell it is over, and its position between cell - // centers (X and Y, 0 to 1, from column Left and row Lower). - private readonly record struct Deposit(double Time, int Cell, int Left, int Lower, - float X, float Y, float Rise); - - private sealed record Checkpoint(double Time, double PreviousTime, int StraightSteps, + private sealed record Checkpoint(double Time, int StraightSteps, int DepositCursor, int EventCursor, float[] Temperature, float[] Peak); private sealed record PieceEvent(double Time, int[] Cells, bool IsCutout); diff --git a/OpenNest.Core/CNC/Thermal/ThermalParameters.cs b/OpenNest.Core/CNC/Thermal/ThermalParameters.cs index c670c88a..1f8d0a99 100644 --- a/OpenNest.Core/CNC/Thermal/ThermalParameters.cs +++ b/OpenNest.Core/CNC/Thermal/ThermalParameters.cs @@ -36,7 +36,7 @@ namespace OpenNest.CNC.Thermal /// /// Grid cell edge in . Zero picks one for the plate: 0.5 in (12 mm), /// halved down to 1/16 in (1.5 mm) while the whole run stays quick to replay, so small - /// plates and short cuts get finer cells. + /// plates, short cuts and an get finer cells. /// public double CellSize { get; init; } @@ -63,6 +63,12 @@ namespace OpenNest.CNC.Thermal /// public double GridContactSize { get; init; } + /// + /// Hardware to run large grids on, which also allows finer automatic cells; null runs on + /// the processor. + /// + public IHeatAccelerator Accelerator { get; init; } + internal double MetersPerUnit => Units == Units.Millimeters ? 0.001 : 0.0254; internal double EffectiveGridContactSize => diff --git a/OpenNest.Core/OpenNest.Core.csproj b/OpenNest.Core/OpenNest.Core.csproj index 74047974..e51c2394 100644 --- a/OpenNest.Core/OpenNest.Core.csproj +++ b/OpenNest.Core/OpenNest.Core.csproj @@ -7,6 +7,7 @@ + diff --git a/OpenNest.Desktop.Tests/Interaction/HeatEstimateTests.cs b/OpenNest.Desktop.Tests/Interaction/HeatEstimateTests.cs new file mode 100644 index 00000000..5a0feb24 --- /dev/null +++ b/OpenNest.Desktop.Tests/Interaction/HeatEstimateTests.cs @@ -0,0 +1,79 @@ +using OpenNest.CNC; +using OpenNest.CNC.Thermal; +using OpenNest.Desktop.Interaction; +using OpenNest.Geometry; + +namespace OpenNest.Desktop.Tests.Interaction; + +public class HeatEstimateTests +{ + private sealed class BrokenAccelerator : IHeatAccelerator + { + public int Asked { get; private set; } + public string Name => "broken"; + + public IHeatKernel Create(int columns, int rows, ReadOnlySpan samples) + { + Asked++; + throw new InvalidOperationException("out of memory"); + } + } + + private static (Plate Plate, CutSimulation Simulation) Job(double x = 5) + { + var program = new OpenNest.CNC.Program(); + program.Codes.Add(new RapidMove(0, 0)); + program.Codes.Add(new LinearMove(20, 0)); + var plate = new Plate(80, 80); + plate.Parts.Add(new Part(new Drawing("part", program), new Vector(x, 5))); + return (plate, CutSimulation.Build(plate, + new CutParameters { Feedrate = 100, RapidTravelRate = 600, Units = Units.Inches })); + } + + // 0.25 in cells on 80 in square: large enough to be accelerated. + private static ThermalParameters Parameters(IHeatAccelerator? accelerator) => new() + { + Thickness = 0.25, + Units = Units.Inches, + CellSize = 0.25, + Accelerator = accelerator, + }; + + [Fact] + public void AFailingAcceleratorFallsBackToTheProcessor() + { + var (plate, simulation) = Job(); + var broken = new BrokenAccelerator(); + + using var estimate = HeatEstimate.Run(plate, simulation, Parameters!, broken); + + Assert.Equal(1, broken.Asked); + Assert.Null(estimate.Device); + Assert.False(estimate.Heat.IsAccelerated); + Assert.True(estimate.Scale > 1); + Assert.Equal(TimeSpan.Zero, estimate.Heat.Time); + } + + [Fact] + public void ACancelledEstimateThrows() + { + var (plate, simulation) = Job(); + using var cancel = new CancellationTokenSource(); + cancel.Cancel(); + + Assert.Throws( + () => HeatEstimate.Run(plate, simulation, Parameters!, null!, cancel.Token)); + } + + [Fact] + public void ARebuiltTimelineWithTheSameMovesMatches() + { + var (_, first) = Job(); + var (_, again) = Job(); + var (_, moved) = Job(x: 6); + + Assert.True(HeatEstimate.SameMoves(first, again)); + Assert.False(HeatEstimate.SameMoves(first, moved)); + Assert.False(HeatEstimate.SameMoves(first, null!)); + } +} diff --git a/OpenNest.Desktop/Interaction/HeatEstimate.cs b/OpenNest.Desktop/Interaction/HeatEstimate.cs new file mode 100644 index 00000000..572db21f --- /dev/null +++ b/OpenNest.Desktop/Interaction/HeatEstimate.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using OpenNest.CNC; +using OpenNest.CNC.Thermal; + +namespace OpenNest.Desktop.Interaction; + +/// +/// A heat model run over its whole cut, ready to play: what the cut simulator does off the UI +/// thread before it shows the heat layer. +/// +public sealed class HeatEstimate : IDisposable +{ + private HeatEstimate(PlateHeatSimulation heat, float scale, string device) + { + Heat = heat; + Scale = scale; + Device = device; + } + + /// The model, back at the start. + public PlateHeatSimulation Heat { get; } + + /// + /// The rise to color as hottest. Pierces leave single very hot cells, and scaling to them + /// would wash out the areas where heat builds up, so this is the hottest half percent. + /// + public float Scale { get; } + + /// The graphics card the model runs on; null on the processor. + public string Device { get; } + + /// + /// Builds and runs the model, on when there is one and on the + /// processor (with the coarser cells that suit it) when that fails. + /// + /// The model's inputs for the given accelerator, or none. + public static HeatEstimate Run(Plate plate, CutSimulation simulation, + Func parameters, IHeatAccelerator accelerator, + CancellationToken cancellationToken = default) + { + if (accelerator != null) + { + try + { + return Run(plate, simulation, parameters(accelerator), accelerator.Name, cancellationToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Out of card memory or a driver fault: the processor still can. + } + } + return Run(plate, simulation, parameters(null), null, cancellationToken); + } + + /// True when both timelines cut and travel the same, at the same times. + public static bool SameMoves(CutSimulation a, CutSimulation b) => + a != null && b != null && a.Steps.Count == b.Steps.Count + && a.Steps.Zip(b.Steps).All(pair => Move(pair.First).Equals(Move(pair.Second))); + + public void Dispose() => Heat.Dispose(); + + private static object Move(CutSimulationStep s) => + (s.Kind, s.Start, s.End, s.IsArc, s.Center, s.Sweep, s.StartTime, s.Duration, (s.Layer, s.IsHole, s.ContourIndex)); + + private static HeatEstimate Run(Plate plate, CutSimulation simulation, ThermalParameters parameters, + string device, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + var heat = new PlateHeatSimulation(plate, simulation, parameters); + try + { + heat.RunToEnd(cancellationToken: cancellationToken); + var scale = ColorScale(heat); + heat.Reset(); + return new HeatEstimate(heat, scale, heat.IsAccelerated ? device : null); + } + catch + { + heat.Dispose(); + throw; + } + } + + private static float ColorScale(PlateHeatSimulation heat) + { + var all = heat.Peaks; + var peaks = new List(); + for (var i = 0; i < all.Length; i++) + { + if (!heat.IsRemoved(i) && all[i] > 0) + peaks.Add(all[i]); + } + peaks.Sort(); + return peaks.Count == 0 ? 1f : peaks[(int)(0.995 * (peaks.Count - 1))]; + } +} diff --git a/OpenNest.Gpu/GpuHeatAccelerator.cs b/OpenNest.Gpu/GpuHeatAccelerator.cs new file mode 100644 index 00000000..d13a79c5 --- /dev/null +++ b/OpenNest.Gpu/GpuHeatAccelerator.cs @@ -0,0 +1,84 @@ +using System; +using ILGPU; +using ILGPU.Runtime; +using ILGPU.Runtime.CPU; +using ILGPU.Runtime.Cuda; +using ILGPU.Runtime.OpenCL; +using OpenNest.CNC.Thermal; + +namespace OpenNest.Gpu; + +/// +/// Runs grids on a graphics card through ILGPU: CUDA on +/// NVIDIA cards, otherwise OpenCL where the driver offers what ILGPU needs. One instance serves +/// every simulation of the process. +/// +public sealed class GpuHeatAccelerator : IHeatAccelerator, IDisposable +{ + private static readonly Lazy Shared = new(Create); + + private readonly Context context; + + private GpuHeatAccelerator(Context context, Accelerator accelerator) + { + this.context = context; + Accelerator = accelerator; + Kernels = new HeatKernels(accelerator); + } + + /// + /// This computer's graphics card, or null when there is none ILGPU can use. The first call + /// takes a few tenths of a second, so make it off the UI thread. + /// + public static GpuHeatAccelerator Default => Shared.Value; + + public string Name => Accelerator.Name; + + internal Accelerator Accelerator { get; } + internal HeatKernels Kernels { get; } + + // The device and its stream take one caller at a time. + internal object Gate { get; } = new(); + + public IHeatKernel Create(int columns, int rows, ReadOnlySpan samples) + { + lock (Gate) + { + Accelerator.Bind(); + return new GpuHeatKernel(this, columns, rows, samples); + } + } + + /// ILGPU's emulation on the processor, so tests run the kernels without a card. + internal static GpuHeatAccelerator Emulated() + { + var context = Context.Create(builder => builder.CPU()); + return new GpuHeatAccelerator(context, context.CreateCPUAccelerator(0)); + } + + public void Dispose() + { + Accelerator.Dispose(); + context.Dispose(); + } + + private static GpuHeatAccelerator Create() + { + Context context = null; + try + { + context = Context.Create(builder => builder.Cuda().OpenCL()); + Accelerator accelerator = context.GetCudaDevices().Count > 0 ? context.CreateCudaAccelerator(0) + : context.GetCLDevices().Count > 0 ? context.CreateCLAccelerator(0) + : null; + if (accelerator != null) + return new GpuHeatAccelerator(context, accelerator); + } + catch (Exception) + { + // A missing or broken driver only means there is no card to use. + } + context?.Dispose(); + return null; + } +} diff --git a/OpenNest.Gpu/GpuHeatKernel.cs b/OpenNest.Gpu/GpuHeatKernel.cs new file mode 100644 index 00000000..6d004c8a --- /dev/null +++ b/OpenNest.Gpu/GpuHeatKernel.cs @@ -0,0 +1,183 @@ +using System; +using System.Collections.Generic; +using ILGPU; +using ILGPU.Runtime; +using OpenNest.CNC.Thermal; + +namespace OpenNest.Gpu; + +/// One simulation's grid in the card's memory. +internal sealed class GpuHeatKernel : IHeatKernel +{ + // The driver queues steps; wait now and then so the queue stays short. + private const int StepsPerWait = 256; + + private readonly GpuHeatAccelerator owner; + private readonly int columns; + private readonly int rows; + private readonly List buffers = new(); + private readonly Dictionary> keeps = new(); + private readonly MemoryBuffer1D peak; + private readonly MemoryBuffer1D noKeep; + private readonly MemoryBuffer1D region; + private readonly MemoryBuffer1D links; + private readonly MemoryBuffer1D samples; + private MemoryBuffer1D current; + private MemoryBuffer1D next; + private MemoryBuffer1D partialKeep; + // Cell numbers, regions and links of a change, one after another. + private MemoryBuffer1D changes; + private int steps; + + public GpuHeatKernel(GpuHeatAccelerator owner, int columns, int rows, ReadOnlySpan source) + { + this.owner = owner; + this.columns = columns; + this.rows = rows; + var count = columns * rows; + try + { + current = Allocate(count); + next = Allocate(count); + peak = Allocate(count); + noKeep = Allocate(1); + region = Allocate(count); + links = Allocate(count); + samples = Allocate(System.Math.Max(1, source.Length)); + if (source.Length > 0) + samples.View.SubView(0, source.Length).CopyFromCPU(Stream, source.ToArray()); + } + catch + { + Release(); + throw; + } + } + + private AcceleratorStream Stream => owner.Accelerator.DefaultStream; + + public void Clear() => Locked(() => + { + current.MemSetToZero(Stream); + next.MemSetToZero(Stream); + peak.MemSetToZero(Stream); + }); + + public void SetCells(ReadOnlySpan newRegion, ReadOnlySpan newLinks) + { + var regions = newRegion.ToArray(); + var linked = newLinks.ToArray(); + Locked(() => + { + region.View.CopyFromCPU(Stream, regions); + links.View.CopyFromCPU(Stream, linked); + Stream.Synchronize(); + }); + } + + public void ChangeCells(ReadOnlySpan cells, ReadOnlySpan newRegion, ReadOnlySpan newLinks) + { + var count = cells.Length; + if (count == 0) + return; + var packed = new int[count * 3]; + cells.CopyTo(packed); + newRegion.CopyTo(packed.AsSpan(count)); + newLinks.CopyTo(packed.AsSpan(count * 2)); + Locked(() => + { + if (changes == null || changes.Length < packed.Length) + { + Free(changes); + changes = Allocate(System.Math.Max(packed.Length, 4096)); + } + changes.View.SubView(0, packed.Length).CopyFromCPU(Stream, packed); + owner.Kernels.Change(Stream, count, current.View, region.View, links.View, + changes.View.SubView(0, count), changes.View.SubView(count, count), + changes.View.SubView(count * 2, count)); + Stream.Synchronize(); + }); + } + + public void AddSamples(int from, int to) => Locked(() => + owner.Kernels.Add(Stream, 1, current.View, region.View, samples.View, + new SampleRange(from, to, columns, rows))); + + public void Step(float share, float keep, float[] cellKeep, int keepKey) => Locked(() => + { + var perCell = cellKeep == null ? null : Keep(cellKeep, keepKey); + var views = new StepViews(current.View, next.View, peak.View, (perCell ?? noKeep).View, links.View); + owner.Kernels.Diffuse(Stream, columns * rows, views, columns, share, keep, perCell == null ? 0 : 1); + (current, next) = (next, current); + if (++steps % StepsPerWait == 0) + Stream.Synchronize(); + }); + + public void Read(float[] temperature, float[] peaks) => Locked(() => + { + current.View.CopyToCPU(Stream, temperature); + peak.View.CopyToCPU(Stream, peaks); + Stream.Synchronize(); + }); + + public void Write(float[] temperature, float[] peaks) => Locked(() => + { + current.View.CopyFromCPU(Stream, temperature); + peak.View.CopyFromCPU(Stream, peaks); + Stream.Synchronize(); + }); + + public void Dispose() => Locked(Release); + + private MemoryBuffer1D Keep(float[] values, int key) + { + if (key < 0) + { + partialKeep ??= Allocate(values.Length); + partialKeep.View.CopyFromCPU(Stream, values); + Stream.Synchronize(); + return partialKeep; + } + + if (!keeps.TryGetValue(key, out var buffer)) + { + buffer = Allocate(values.Length); + buffer.View.CopyFromCPU(Stream, values); + Stream.Synchronize(); + keeps[key] = buffer; + } + return buffer; + } + + private MemoryBuffer1D Allocate(long length) + where T : unmanaged + { + var buffer = owner.Accelerator.Allocate1D(length); + buffers.Add(buffer); + return buffer; + } + + private void Free(MemoryBuffer buffer) + { + if (buffer == null) + return; + buffers.Remove(buffer); + buffer.Dispose(); + } + + private void Release() + { + foreach (var buffer in buffers) + buffer.Dispose(); + buffers.Clear(); + } + + private void Locked(Action action) + { + lock (owner.Gate) + { + owner.Accelerator.Bind(); + action(); + } + } +} diff --git a/OpenNest.Gpu/HeatKernels.cs b/OpenNest.Gpu/HeatKernels.cs new file mode 100644 index 00000000..f663dd2c --- /dev/null +++ b/OpenNest.Gpu/HeatKernels.cs @@ -0,0 +1,104 @@ +using System; +using ILGPU; +using ILGPU.Runtime; +using OpenNest.CNC.Thermal; +using Floats = ILGPU.Runtime.ArrayView1D; +using Ints = ILGPU.Runtime.ArrayView1D; +using Samples = ILGPU.Runtime.ArrayView1D; + +namespace OpenNest.Gpu; + +/// The views one diffusion step reads and writes. +internal readonly struct StepViews(Floats current, Floats next, Floats peak, Floats cellKeep, Ints links) +{ + public readonly Floats Current = current; + public readonly Floats Next = next; + public readonly Floats Peak = peak; + public readonly Floats CellKeep = cellKeep; + public readonly Ints Links = links; +} + +/// The device programs, compiled once. Each mirrors the CPU code it is named after. +internal sealed class HeatKernels +{ + public HeatKernels(Accelerator accelerator) + { + Diffuse = accelerator.LoadAutoGroupedKernel(DiffuseCell); + Add = accelerator.LoadAutoGroupedKernel(AddSamples); + Change = accelerator.LoadAutoGroupedKernel(ChangeCell); + } + + public Action Diffuse { get; } + public Action Add { get; } + public Action Change { get; } + + // PlateHeatSimulation.DiffuseCells. A missing link reads the cell itself, so its term is zero + // and the index stays in the grid. + private static void DiffuseCell(Index1D index, StepViews views, int columns, float share, float keep, int perCell) + { + int i = index; + var links = views.Links[i]; + var t = views.Current[i]; + var left = views.Current[(links & 1) != 0 ? i - 1 : i]; + var right = views.Current[(links & 2) != 0 ? i + 1 : i]; + var below = views.Current[(links & 4) != 0 ? i - columns : i]; + var above = views.Current[(links & 8) != 0 ? i + columns : i]; + var flow = (left - t) + (right - t) + (below - t) + (above - t); + var value = (t + share * flow) * (perCell != 0 ? views.CellKeep[i] : keep); + if (value < PlateHeatSimulation.Negligible) + value = 0; + views.Next[i] = value; + if (value > views.Peak[i]) + views.Peak[i] = value; + } + + // PlateHeatSimulation.Add, for the samples of one step. One thread takes them in order, since + // neighboring samples share cells; a step has only a few. + private static void AddSamples(Index1D one, Floats temperature, Ints region, Samples samples, SampleRange range) + { + for (var i = range.From; i < range.To; i++) + { + var sample = samples[i]; + var piece = region[sample.Cell]; + if (piece == -1) + continue; + + var columns = range.Columns; + var left = sample.Left; + var right = left + 1 < columns ? left + 1 : columns - 1; + var lower = sample.Lower * columns; + var upper = (sample.Lower + 1 < range.Rows ? sample.Lower + 1 : range.Rows - 1) * columns; + var x = sample.X; + var y = sample.Y; + var lowerLeft = region[lower + left] == piece ? (1 - x) * (1 - y) : 0f; + var lowerRight = region[lower + right] == piece ? x * (1 - y) : 0f; + var upperLeft = region[upper + left] == piece ? (1 - x) * y : 0f; + var upperRight = region[upper + right] == piece ? x * y : 0f; + + var rise = sample.Rise / (lowerLeft + lowerRight + upperLeft + upperRight); + temperature[lower + left] += rise * lowerLeft; + temperature[lower + right] += rise * lowerRight; + temperature[upper + left] += rise * upperLeft; + temperature[upper + right] += rise * upperRight; + } + } + + // New piece and links for a listed cell, and no heat where material fell away. + private static void ChangeCell(Index1D k, Floats temperature, Ints region, Ints links, + Ints cells, Ints newRegion, Ints newLinks) + { + var cell = cells[k]; + region[cell] = newRegion[k]; + links[cell] = newLinks[k]; + if (newRegion[k] == -1) + temperature[cell] = 0; + } +} + +internal readonly struct SampleRange(int from, int to, int columns, int rows) +{ + public readonly int From = from; + public readonly int To = to; + public readonly int Columns = columns; + public readonly int Rows = rows; +} diff --git a/OpenNest.Gpu/OpenNest.Gpu.csproj b/OpenNest.Gpu/OpenNest.Gpu.csproj new file mode 100644 index 00000000..b7089c13 --- /dev/null +++ b/OpenNest.Gpu/OpenNest.Gpu.csproj @@ -0,0 +1,18 @@ + + + net8.0 + OpenNest.Gpu + OpenNest.Gpu + + + + + + + + + + + + + diff --git a/OpenNest.Tests/CNC/GpuHeatAcceleratorTests.cs b/OpenNest.Tests/CNC/GpuHeatAcceleratorTests.cs new file mode 100644 index 00000000..2578b35c --- /dev/null +++ b/OpenNest.Tests/CNC/GpuHeatAcceleratorTests.cs @@ -0,0 +1,144 @@ +using OpenNest.CNC; +using OpenNest.CNC.Thermal; +using OpenNest.Geometry; +using OpenNest.Gpu; +using OpenNest.Support; + +namespace OpenNest.Tests.CNC; + +public class GpuHeatAcceleratorTests +{ + // A framed part on slats: shared samples, a dropped slug, a part cut free and contact decay. + private static (Plate Plate, CutSimulation Simulation, Func Thermal) Job( + SupportBed? bed) + { + var program = new Program(); + foreach (var (x, y, size) in new[] { (3.0, 3.0, 4.0), (0.0, 0.0, 10.0) }) + { + program.Codes.Add(new RapidMove(x, y)); + program.Codes.Add(new LinearMove(x + size, y)); + program.Codes.Add(new LinearMove(x + size, y + size)); + program.Codes.Add(new LinearMove(x, y + size)); + program.Codes.Add(new LinearMove(x, y)); + } + var plate = new Plate(80, 80); + plate.Parts.Add(new Part(new Drawing("part", program), new Vector(8, 8))); + var simulation = CutSimulation.Build(plate, new CutParameters + { + Feedrate = 100, + RapidTravelRate = 600, + PierceTime = TimeSpan.FromSeconds(1), + Units = Units.Inches, + }); + // 0.25 in cells on 80 in square are 102,400 cells, just enough to be accelerated. + return (plate, simulation, accelerator => new ThermalParameters + { + Material = ThermalMaterial.MildSteel, + Thickness = 0.25, + Units = Units.Inches, + CellSize = 0.25, + SupportBed = bed, + Accelerator = accelerator, + }); + } + + private static void AssertClose(ReadOnlySpan expected, ReadOnlySpan actual) + { + Assert.Equal(expected.Length, actual.Length); + for (var i = 0; i < expected.Length; i++) + { + // Devices may fuse a multiply and an add, which rounds once instead of twice. + var allowed = 0.001f + 1e-5f * System.Math.Abs(expected[i]); + if (System.Math.Abs(expected[i] - actual[i]) > allowed) + Assert.Fail($"cell {i}: {actual[i]} instead of {expected[i]}"); + } + } + + private static void AssertMatchesTheProcessor(IHeatAccelerator accelerator, SupportBed? bed) + { + var (plate, simulation, thermal) = Job(bed); + var processor = new PlateHeatSimulation(plate, simulation, thermal(null)); + using var heat = new PlateHeatSimulation(plate, simulation, thermal(accelerator)); + Assert.True(heat.IsAccelerated); + + // To the end, back past checkpoints, forward in frames that cut steps short, and cooling. + TimeSpan At(double fraction) => TimeSpan.FromTicks((long)(simulation.TotalTime.Ticks * fraction)); + foreach (var target in new[] { At(1), At(0.4), At(0.4) + TimeSpan.FromSeconds(0.04), At(0.7), At(1.2) }) + { + processor.AdvanceTo(target); + heat.AdvanceTo(target); + AssertClose(processor.Temperatures, heat.Temperatures); + AssertClose(processor.Peaks, heat.Peaks); + } + Assert.True(heat.IsRemoved(heat.CellAt(new Vector(13, 13)))); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void KernelsMatchTheProcessor(bool slats) + { + using var accelerator = GpuHeatAccelerator.Emulated(); + + AssertMatchesTheProcessor(accelerator, + slats ? new SupportSlats(SlatAxis.X, pitch: 4, thickness: 1, offset: 2) : null); + } + + // Runs on a computer with a usable graphics card only; build agents have none. + [SkippableFact] + public void TheGraphicsCardMatchesTheProcessor() + { + var accelerator = GpuHeatAccelerator.Default; + Skip.If(accelerator == null, "No graphics card ILGPU can use."); + + AssertMatchesTheProcessor(accelerator!, new SupportSlats(SlatAxis.X, pitch: 4, thickness: 1, offset: 2)); + } + + [Fact] + public void AcceleratorAllowsEighthInchCellsOnAFullSheet() + { + using var accelerator = GpuHeatAccelerator.Emulated(); + var p = new ThermalParameters + { + Material = ThermalMaterial.MildSteel, + Thickness = 0.25, + Units = Units.Inches, + Accelerator = accelerator, + }; + + Assert.Equal(0.125, PlateHeatSimulation.AutomaticCellSize(new Box(0, 0, 120, 60), 3600, p)); + } + + [Fact] + public void SmallGridsStayOnTheProcessor() + { + using var accelerator = GpuHeatAccelerator.Emulated(); + var (plate, simulation, _) = Job(null); + using var heat = new PlateHeatSimulation(plate, simulation, new ThermalParameters + { + Thickness = 0.25, + Units = Units.Inches, + CellSize = 0.5, + Accelerator = accelerator, + }); + + Assert.False(heat.IsAccelerated); + } + + [Fact] + public void ACancelledRunStopsAndFinishesExactlyLater() + { + var (plate, simulation, thermal) = Job(null); + var heat = new PlateHeatSimulation(plate, simulation, thermal(null)); + using var cancel = new CancellationTokenSource(); + cancel.Cancel(); + + Assert.Throws(() => heat.RunToEnd(cancellationToken: cancel.Token)); + Assert.True(heat.Time < simulation.TotalTime); + heat.RunToEnd(); + + var straight = new PlateHeatSimulation(plate, simulation, thermal(null)); + straight.RunToEnd(); + Assert.Equal(straight.Temperatures.ToArray(), heat.Temperatures.ToArray()); + } +} diff --git a/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs b/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs index 4a39b666..b505eca4 100644 --- a/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs +++ b/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs @@ -140,16 +140,50 @@ public class PlateHeatSimulationTests Assert.Equal(0.5 / 8, Automatic(plate).CellSize); } - [Fact] - public void LargePlateWithALongCutKeepsHalfInchCells() + // A 5x10 sheet of eight 25 in squares: about half an hour of cutting. + private static Plate FullSheet() { var plate = new Plate(60, 120); var drawing = new Drawing("part", Square(25)); for (var x = 0; x < 2; x++) for (var y = 0; y < 4; y++) plate.Parts.Add(new Part(drawing, new Vector(2 + x * 28, 2 + y * 28))); + return plate; + } - Assert.Equal(0.5, Automatic(plate).CellSize); + [Fact] + public void FullSheetGetsQuarterInchCells() => Assert.Equal(0.25, Automatic(FullSheet()).CellSize); + + [Fact] + public void FullSheetWithAVeryLongCutKeepsHalfInchCells() + { + var p = new ThermalParameters { Material = ThermalMaterial.Aluminum, Thickness = 0.25, Units = Units.Inches }; + + Assert.Equal(0.5, PlateHeatSimulation.AutomaticCellSize(new Box(0, 0, 120, 60), 40_000, p)); + } + + // Half an inch past the budget, a run is cut into longer steps than the torch needs. + [Fact] + public void OnlyCuttingTimeTakesShortSteps() + { + var (_, simulation) = Cut(Line(20), new Vector(10, 80)); + var cut = simulation.Steps.Where(s => s.Kind == CutSimulationStepKind.Cut).ToArray(); + var from = cut[0].StartTime.TotalSeconds; + var to = cut[^1].EndTime.TotalSeconds; + // 100 in/min crosses 0.25 in cells in 0.15 s. + var schedule = new HeatStepSchedule(simulation, 0.6, 0.25, 1, 0.005); + + var time = 0.0; + while (time < simulation.TotalTime.TotalSeconds) + { + var (next, split) = schedule.Next(time); + Assert.True(next > time); + if (time >= from && next <= to) + Assert.True(next - time <= 0.15 + 1e-9, $"{next - time} s step while cutting"); + if (next <= from - 0.6 || time >= to + 0.6) + Assert.Equal(1, split); + time = next; + } } [Fact] @@ -173,10 +207,13 @@ public class PlateHeatSimulationTests // Feeds that cross a whole and a fractional number of cells per diffusion-limited step. [Theory] - [InlineData(47)] - [InlineData(97)] - [InlineData(283)] - public void AStraightCutPeaksEvenlyAlongItsLength(double feedrate) + [InlineData(47, 0.25)] + [InlineData(97, 0.25)] + [InlineData(283, 0.25)] + [InlineData(47, 0.125)] + [InlineData(97, 0.125)] + [InlineData(283, 0.125)] + public void AStraightCutPeaksEvenlyAlongItsLength(double feedrate, double cell) { var plate = new Plate(48, 96); plate.Parts.Add(new Part(new Drawing("part", Line(23.7)), new Vector(10.03, 10.31))); @@ -191,14 +228,14 @@ public class PlateHeatSimulationTests Material = ThermalMaterial.MildSteel, Thickness = 0.135, Units = Units.Inches, - CellSize = 0.25, + CellSize = cell, }); heat.RunToEnd(TimeSpan.FromSeconds(10)); // The middle of the cut, clear of the warm-up and the end. var peaks = new List(); - for (var x = 18.125; x < 28; x += 0.25) + for (var x = 18 + cell / 2; x < 28; x += cell) peaks.Add(heat.Peaks[heat.CellAt(new Vector(x, 10.31))]); var ripple = (peaks.Max() - peaks.Min()) / peaks.Average(); Assert.True(ripple < 0.1, $"peaks vary {ripple:P0} along the cut"); diff --git a/OpenNest.Tests/OpenNest.Tests.csproj b/OpenNest.Tests/OpenNest.Tests.csproj index 125eaa69..e7320c06 100644 --- a/OpenNest.Tests/OpenNest.Tests.csproj +++ b/OpenNest.Tests/OpenNest.Tests.csproj @@ -28,6 +28,7 @@ + diff --git a/OpenNest.WinForms.Tests/Forms/CutSimulatorFormTests.cs b/OpenNest.WinForms.Tests/Forms/CutSimulatorFormTests.cs index 4a9673c3..5c2c77df 100644 --- a/OpenNest.WinForms.Tests/Forms/CutSimulatorFormTests.cs +++ b/OpenNest.WinForms.Tests/Forms/CutSimulatorFormTests.cs @@ -102,6 +102,44 @@ public class CutSimulatorFormTests } }); + [Fact] + public void TheHeatLayerAppearsOnceItsBackgroundRunFinishes() => RunSta(() => + { + using var editor = Editor(); + editor.Nest.Thickness = 0.135; + editor.Show(); + editor.PlateManager.LoadAt(0); + editor.SimulateCutting(); + var simulator = (CutSimulatorForm)typeof(EditNestForm) + .GetField("cutSimulatorForm", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(editor)!; + try + { + Field(simulator, "heatBox").SelectedIndex = 1; + var overlay = editor.PlateView.CutSimulation; + var label = Field