Extract direction helpers to Helper class (EdgeDistance, DirectionalGap,
DirectionToOffset, IsHorizontalDirection) and use them to skip parts not
ahead in the push direction or further than the current best distance.
Defer line computation until parts survive bounding box checks.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The BestFitFilter's aspect ratio cap of 5.0 was rejecting valid pair
candidates needed for narrow plates (e.g. 60x6.5, aspect 9.2) and
remainder strips on normal plates. Three fixes:
- BestFitFinder: derive MaxAspectRatio from the plate's own aspect
ratio so narrow plates don't reject all elongated pairs
- SelectPairCandidates: search the full unfiltered candidate list
(not just Keep=true) in strip mode, so pairs rejected by aspect
ratio for the main plate can still be used for narrow remainder
strips
- BestFitCache.Populate: skip caching empty result lists so stale
pre-computed data from nest files doesn't prevent recomputation
Also fixes console --size parsing to use LxW format matching
Size.Parse convention, and includes prior engine refactoring
(sequential fill loops, parallel FillPattern, pre-sorted edge
arrays in RotationSlideStrategy).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Vector implements IEquatable<Vector> with proper GetHashCode for HashSet usage.
Polygon.FindCrossing uses bounding-box pruning to skip non-overlapping edge pairs.
Helper.DirectionalDistance deduplicates vertices via HashSet, sorts edges for
early-exit pruning, and adds a new array-based overload that avoids allocations.
PartBoundary sorts directional edges and exposes GetEdges for zero-alloc access.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replace shape-list iteration with ShapeProfile.Perimeter in both
Part.Intersects and PartBoundary, simplifying the logic and ensuring
only the outermost contour is used for collision detection.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add G-code serialization via ToString() for debugging/ML workflows.
Fix Rotate(angle, origin) to propagate origin to sub-programs instead
of calling the single-argument overload.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Offset-only copies don't modify program codes, so sharing the instance
avoids expensive cloning during large pattern tiling.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add primitive-parameter RayEdgeDistance overload with AggressiveInlining,
merge Left/Right and Up/Down cases. Add DirectionalDistance overload that
accepts (dx, dy) translation without creating Line objects, and FlattenLines
for packing segments into flat arrays for GPU transfer.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Break deeply nested loop structure into focused helper methods,
reducing max nesting from 5 levels to 2. Uses GetRange/AddRange
for cleaner loop building.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Brings in the full NFP implementation: ConvexDecomposition, NoFitPolygon,
InnerFitPolygon, NfpCache, BottomLeftFill, SimulatedAnnealing optimizer,
and INestOptimizer interface. Resolves conflicts by keeping master's
progress reporting infrastructure alongside the new AutoNest methods,
and adapting RunAutoNest_Click to use NFP AutoNest with async/cancellation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Shape.OffsetEntity computed joins between consecutive offset segments
but never joined the last segment back to the first, leaving the
closing corner with a straight line instead of a proper miter/arc.
Track the first entity and apply the same join logic after the loop.
Also wrap nest template loading in try-catch so a corrupt template
file doesn't crash the app on startup — falls back to default nest.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The exit point should be the corner farthest from the origin so the
perimeter (cut last) ends near the machine home. The mapping was
backwards — Q1 (origin bottom-left) was returning (0,0) instead of
(w,l).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Exit point from plate quadrant, nearest-neighbor cutout
sequencing via ShapeProfile + ClosestPointTo, contour type
detection, and normal angle computation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
"Length" is more natural than "height" for flat plate materials.
Renames the field on OpenNest.Geometry.Size, Box.Height property,
and all references across 38 files.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
DXF files can have endpoint gaps at entity junctions that fall right at
the floating-point boundary of Tolerance.Epsilon (0.00001). This caused
shapes to not close, resulting in 0 area and 0% utilization in Best-Fit.
Added ChainTolerance (0.0001) for endpoint chaining in GetConnected and
Shape.IsClosed, keeping the tighter Epsilon for geometric precision.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Implement geometry-aware nesting using No-Fit Polygons and simulated
annealing optimization. Parts interlock based on true shape rather than
bounding boxes, producing tighter layouts for mixed-part scenarios.
New types in Core/Geometry:
- ConvexDecomposition: ear-clipping triangulation for concave polygons
- NoFitPolygon: Minkowski sum via convex decomposition + Clipper2 union
- InnerFitPolygon: feasible region computation for plate placement
New types in Engine:
- NfpCache: caches NFPs keyed by (drawingId, rotation) pairs
- BottomLeftFill: places parts using feasible regions from IFP - NFP union
- INestOptimizer: abstraction for future GA/parallel upgrades
- SimulatedAnnealing: optimizes part ordering and rotation
Integration:
- NestEngine.AutoNest(): new public entry point for mixed-part nesting
- MainForm.RunAutoNest_Click: uses AutoNest instead of Pack
- NestingTools.autonest_plate: new MCP tool for Claude Code integration
- Drawing.Id: auto-incrementing identifier for NFP cache keys
- Clipper2 NuGet added to OpenNest.Core for polygon boolean operations
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The push algorithm's copy distance formula (bboxDim - slideDistance)
produced distances smaller than the part width when inflated boundary
arc vertices interacted spuriously, causing ~0.05 unit overlaps between
all adjacent grid parts.
Two fixes applied:
- Clamp ComputeCopyDistance to bboxDim + PartSpacing minimum
- Use circumscribed polygons (R/cos(halfStep)) for PartBoundary arc
discretization so chord segments never cut inside the true arc,
eliminating the ChordTolerance offset workaround
Also parallelized three sequential fill loops using Parallel.ForEach:
- FindBestFill angle sweep (up to 38 angles x 2 directions)
- FillPattern angle sweep for group/pair fills
- FillRemainingStrip rotation loop
Added diagnostic logging to HasOverlaps, FindCopyDistance, and
FillRecursive for debugging fill issues.
Test result: 45 parts @ 79.6% -> 47 parts @ 83.1%, zero overlaps.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Part.Clone() re-clones from the drawing's unrotated program, re-rotates,
and walks all CNC codes twice for bounding box — 4 O(c) passes per clone.
CloneAtOffset clones from the already-rotated program and computes the
bounding box arithmetically, reducing to 1 O(c) pass per clone.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Opposite hull edges (180° apart) produce identical bounding rectangles
(width/height swapped), so only half the edges need to be checked to
find the minimum area. Applied to the unconstrained overload only.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add bounding box rejection in HasOverlaps to skip expensive
Part.Intersects (CNC→geometry conversion) for non-adjacent parts.
Eliminates ~35% CPU in IsBetterValidFill for grid layouts.
- Optimize RayEdgeDistance: access Line fields directly instead of
property getters (avoids Vector struct copies), inline IsEqualTo
with direct range comparison (avoids Math.Abs), and precompute
deltas for reuse in interpolation.
- Cache line endpoints in DirectionalDistance outer loop to avoid
repeated struct copies in the inner loop.
- Add fill timer to ActionClone.Fill, displayed in PlateView status
bar as "Fill: N parts in M ms".
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace hardcoded PushChordTolerance constant with a configurable
OffsetTolerance property on PlateView (default 0.001), giving smoother
arc profiles in offset drawing and push-to-part collision detection.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add LineTypeName to Layer and propagate resolved color/line-type
through all DXF entity conversions (Arc, Circle, Line, Spline,
Polyline, LwPolyline, Ellipse). Entities that inherit ByLayer
properties now correctly resolve to their layer's values.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add per-entity IsVisible flag and wire up the Colors and Line Types
checkedlistboxes to filter entities by exclusion — checking an item
hides matching entities from the preview and from drawing export.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Fill(NestItem) and Fill(List<Part>) now delegate to their Box overloads
- Add Part.CreateAtOrigin() to replace repeated 4-line build-at-origin pattern
used in NestEngine, RotationSlideStrategy, and PairEvaluator
- Remove dead code: FillArea overloads, Fill(NestItem, int), FillWithPairs(NestItem),
ConvertTileResultToParts, PackBottomLeft.FindPointHorizontal, Pattern.GetLines/GetOffsetLines,
unused count variable in FillNoRotation
- Simplify IsBetterValidFill to delegate to IsBetterFill after overlap check
NestEngine reduced from 717 to 484 lines.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Part.Intersects included rapid move geometry (G00 traversals) when
checking for overlaps, causing false positives. The overlap validation
added in 5bebfcb rejected all FillLinear configs, producing 0 parts.
Every other GetShapes caller already filters SpecialLayers.Rapid.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Polygon offset at concave corners creates geometry that folds back
through itself. Added RemoveSelfIntersections() to Polygon that
detects non-adjacent edge crossings and removes the smaller loop
at each crossing. Applied to both collision detection and rendering.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
RayEdgeDistance returned double.MaxValue for touching vertices (dist ≈ 0),
causing rays from other vertices to hit the far side of stationary parts
and allow movement through obstacles. Now returns 0 when touching so the
distance > 0 check in PushSelected correctly prevents further movement.
Added directional edge filtering using outward normals to discard
back-facing edges before ray checks, reducing line count by ~2/3.
DirectionalDistance now checks both StartPoint and EndPoint per line
to preserve vertices at filtered edge boundaries.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
SetRotation always forced CW regardless of the requested rotation,
so cutouts (which should be CCW for kerf-left) were also set to CW.
Now uses the rotation parameter to set the correct winding direction.
Also reverts the Shape.OffsetEntity cutout side inversion since the
correct fix is proper winding from the converter.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Cutouts wind opposite to the perimeter, so using the same OffsetSide
expands holes instead of shrinking them. Invert the side for cutouts
so the offset buffer correctly contracts holes inward.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Polygon chords are always inside the actual arc, making the offset
boundary smaller than intended. Add PushChordTolerance to the offset
distance so the polygon conservatively overestimates, ensuring the
real offset geometry never overlaps stationary parts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>