A GPU-accelerated tri-dexel material-removal simulator built in Unity — a real-time simulation of 4-axis CNC machining on a small benchtop mill. A simple machining simulation, and a work in progress.
Showcase_BallNose, one sinusoidal pass — the round-bottomed groove is the ball-nose profile itself,
no post-processing.
One continuous take, real time (24s). The tool runs a serpentine roughing raster across the block, then a contour finishing lap around the perimeter at double feed — shearing off the scalloped edge that roughing leaves behind, because a round tool reversing at the end of each pass cannot cut a straight one. Raw output of the compute-shader simulation below; no post-processing.
This is a real-time simulation of a CNC mill removing material — precise enough to catch a bad cut by eye before it happens on a real machine. It's a simple machining simulation, and a work in progress: nothing beyond what's described below is built yet.
The core idea: represent the workpiece as a tri-dexel volume — three independent sets of parallel rays (one set per axis: X, Y, Z), each ray broken into the solid/empty intervals it currently passes through. Sweeping a cutting tool through the volume becomes a fast 1D interval-subtraction problem repeated across every ray, instead of a full 3D boolean mesh operation. It's the same representation used by commercial CAM verification engines (ModuleWorks-class tools use a discrete dexel model for GPU-accelerated cut simulation) for exactly this reason: it's cheap, it has no trouble with the undercuts a height-map can't represent, and it parallelizes trivially on a GPU.
- Three dexel grids, one per axis. A single-direction dexel grid samples the surface poorly wherever the surface is nearly parallel to the ray direction (think: a vertical wall, viewed by rays pointing straight down). Tri-dexel fixes this by keeping three grids and letting each axis cover the others' blind spots.
- Shared GPU node pool. Each dexel column is a linked list of solid/empty segments. All three axes'
segments live in one big pool of nodes on the GPU (
NodePool), addressed through per-axis head pointers (HeadBuffer) — one pool, one allocator, no per-axis buffer juggling. - Cut kernel. Every frame the tool is intersected against every ray in the region it overlaps, and the corresponding interval is subtracted from that column's segment list.
- Generalized cutter. Tools are not hard-coded shapes. Every standard cutter is a solid of revolution, so it is described by a 2D profile in the (radius, axial) half-plane and decomposed into primitives with closed-form ray intersections — a cone frustum (covering the cylinder, the flat end cap, and any taper) and a sphere cap (the ball nose). That yields flat, ball-nose, bull-nose and tapered/V-bit tools from one code path, and new tooling needs no shader change. Only a flat end mill leaves a flat floor: a ball nose loses effective radius as it approaches the bottom of a pocket, so adjacent passes stop overlapping down there and leave scallops that no step-over can remove.
- Swept substepping. A single cut only removes what the tool covers at that instant. If the tool moves more than about half its own radius in one frame, stamping once per frame leaves un-milled ridges. So the sim interpolates several intermediate poses between last frame's position and this frame's, and stamps each one — cheap insurance against a fast-moving tool leaving gaps.
- Gather + indirect draw. A compute pass compacts the scattered linked-list segments across all
three axes into one flat buffer, and the whole workpiece is rendered in a single
DrawMeshInstancedIndirectcall — no per-segment C#-side draw calls, no CPU readback in the hot path. - Workpiece-frame math, not indexed rotation. The dexel grid lives in the workpiece's local space. Rotating the workpiece (the CNC's A-axis / rotary table) is just a transform change — the grid never needs to be rebuilt or re-sampled for a new angle. That property is what makes true simultaneous 4-axis motion (X, Y, Z, and A all moving at once — not "index to an angle, then machine") tractable at all: nothing here special-cases the rotary axis.
Everything above is written to be purely geometric/kinematic — no cutting-force model, no spindle RPM, no tool-wear or chip-load estimation. That's deliberate, not a limitation: the target machine doesn't have spindle-speed control to begin with, and the project's whole point is trajectory planning, not process physics.
This project is a work in progress. The simulation here is the foundation anything else would need to sit on top of, and nothing beyond it exists yet. It's still useful on its own, because it makes bad machine output visible on screen instead of found out on the mill.
The runtime is split into three assemblies, so the boundaries are enforced by the
compiler rather than by convention. TriDexelCNC.Core is the simulation and
references nothing — not the renderer, not the scene glue, and (later) not
whatever consumes it. That is what lets an external harness be added without the
simulation ever learning about it.
TriDexelCNC.Core Assets/Scripts/Core the simulation
TriDexelCNC.Rendering Assets/Scripts/Rendering drawing a volume -> Core
TriDexelCNC.Scene Assets/Scripts/Scene MonoBehaviours -> Core, Rendering
| scene | tool | program |
|---|---|---|
Assets/Scenes/SampleScene.unity |
flat end mill | roughing raster + contour finishing lap |
Assets/Scenes/Showcase/Showcase_FlatEndMill.unity |
flat end mill | one sinusoidal pass |
Assets/Scenes/Showcase/Showcase_BallNose.unity |
ball nose | one sinusoidal pass |
Assets/Scenes/Showcase/Showcase_BullNose.unity |
corner-radius | one sinusoidal pass |
Assets/Scenes/Showcase/Showcase_VBit.unity |
15-degree V-bit | one sinusoidal pass |
The four showcase scenes run the same program with a different CutterAsset in each. Because the
pass is a single sweep with no overlap, the groove's cross-section is the tool profile — so the
scenes are directly comparable: a square-walled channel, a round-bottomed one, one with radiused
corners, and a narrow vee. Swapping the tool is one field on the CutterTool component.
TriDexelCNC.Tests.EditMode Assets/Tests/EditMode 30 tests, pure C#, no GPU
TriDexelCNC.Tests.PlayMode Assets/Tests/PlayMode 47 tests, GPU, no scene
Run them from Window > General > Test Runner. Both reference Core only, so
they need no scene and no external harness. 77 tests, about 3.5 seconds.
The edit-mode tier covers DexelGrid's index math and every CutterShape
profile, and validates the closed-form CutterGeometry.IntersectRay against the
brute-force Contains oracle over ~19k containment checks across all four
cutter types — the validation the shader header describes. A ray fired through
the tool axis is also checked to cut a chord of exactly twice the profile radius,
computed independently of BuildProfile.
The play-mode tier constructs a DexelVolume directly and asserts the three
properties that matter for correctness and that no screenshot would reveal: a
plunge removes pir^2h to within the grid resolution, all three dexel fields
agree on how much stock is left, and the same pose sequence produces
bit-identical state on every run.
The question that decides the worst bugs is whether the cut follows exactly the volume the tool swept, for that tool's specific geometry. Comparing volumes answers it badly: volume is a scalar, so an over-cut here and an under-cut there cancel — and the likeliest bug in this code, an off-by-half-cell ray origin, removes material on one side of the true surface and leaves it on the other in almost exactly equal measure. Worse, lateral discretization puts a floor of several percent on any volume comparison.
So the comparison is of sets, along the rays. The dexel field is exact
along its rays — intervals are floats, never quantized, and all the
discretization is lateral. Comparing simulation against truth on the same ray
cancels the lateral error identically, which moves the assertable threshold from
5% of a volume to 1e-4 world units, and yields three two-sided measures:
over-cut volume (gouges), under-cut volume (uncarved material), and surface
deviation.
Ground truth needs no envelope mathematics. Exact swept-volume boundaries are a research problem — the sweep-envelope differential equation needs self-intersection trimming, and the grazing curve of a surface of revolution under five-axis motion is a quartic even for a linear profile. But a test wants a membership oracle, not a boundary, and along a ray that is just a union of closed-form ray/tool intervals. The sampling is made sound rather than hand-waved: over one oracle step the furthest any point of the tool moves is bounded, so the sampled union is contained in the true swept volume and the true volume is contained in that union dilated by the same amount.
Two tiers, because conflating them forces the looser bound:
| tier | oracle gets | measures | asserted at |
|---|---|---|---|
| 1 — exactness | the same poses the sim stamped | interval subtraction, dispatch regions, transforms, pool handling | 1e-4 world units |
| 2 — fidelity | a far finer sampling | the substep planner | sweepTolerance |
Alongside them, MetamorphicTests checks relations between outputs rather
than outputs themselves — order invariance, batch invariance, idempotence,
monotonicity, rigid-motion equivariance, tool-family continuity. These need no
ground truth at all. Order invariance is the strongest: interval subtraction is
commutative, so any order of the same poses must give bit-identical geometry,
which is precisely what a GPU race would break and what no oracle-based test
would necessarily notice.
| File | Role |
|---|---|
Assets/Scripts/Scene/TriDexelManager.cs |
Scene component. Wires the tool and workpiece Transforms to a DexelVolume, steps it once per frame, and hands it to the renderer. Both stepping and drawing can be turned off so an external harness owns the timing. |
Assets/Scripts/Core/MachiningEnvironment.cs |
One machining setup: stock, loaded tool, swept stepping and run stats. Plain C#, no Update, no Transform — construct N of them, drive them at whatever rate you like. TriDexelManager just owns one. |
Assets/Scripts/Core/DexelObservation.cs |
Reduces a volume to a fixed-size observation on the GPU — a height map plus scalars — so callers never read the node pool back directly. 29x cheaper than the readback it replaces, and the observation shape does not depend on the grid resolution. |
Assets/Scripts/Core/DexelVolume.cs |
The simulation: three dexel grids, every GPU buffer behind them, and the cut/gather dispatches. Plain C#, IDisposable — no MonoBehaviour, no Time, no Graphics. Clones its compute shaders so many volumes can coexist. |
Assets/Scripts/Rendering/DexelRenderer.cs |
Draws a volume: the gather pass plus one DrawMeshInstancedIndirect. Optional — a headless simulation never constructs one. |
Assets/Scripts/Core/DexelGrid.cs |
Pure C# index math for one axis of the grid (resolution, spacing, world-to-column lookups). |
Assets/Scripts/Core/CutterSweep.cs |
How finely a moving cutter must be stamped for the union of stamps to be the swept volume, and how much material a coarser step leaves standing. Keyed on the tool's radius where it is about half a step wide — not on its widest point. |
Assets/Scripts/Core/CutterShape.cs |
Tool geometry. Turns APT-style parameters (diameter, corner radius, taper) into a revolved profile the GPU can intersect, and carries the C# reference implementation of that intersection, used as the test oracle for the HLSL port. |
Assets/Scripts/Core/CutterAsset.cs |
One cutter, as a named project asset — the tool library. Presets live in Assets/Tools. |
Assets/Scripts/Scene/CutterTool.cs |
The tool in the scene: which CutterAsset is loaded, its pose (tip and axis), and its generated mesh. Swapping tools is one field here. |
Assets/Scripts/Rendering/CutterMesh.cs |
Revolves a cutter profile into a display mesh at true world size, so the tool you see is the tool the sim cuts with — a taper draws as a cone, a bull nose shows its corner radius. |
Assets/Shaders/TriDexelSimulation.compute |
The Cut kernel: intersects the cutter profile against every dexel ray in the tool's AABB and subtracts the covered interval from that column's segment list. Plus InitColumns / InitCounters, which fill the volume with solid stock on the GPU so a per-run reset uploads nothing. |
Assets/Shaders/TriDexelObserve.compute |
Observe / ResetScalars: walks the vertical dexel columns and reduces them to a height map (mean / min / max / solid fraction per cell) and a remaining-stock scalar. |
Assets/Shaders/TriDexelGather.compute |
ResetCounter / Gather / PrepareArgs: walks all three axes' linked lists, compacts the live segments into one flat buffer, and fills the indirect-draw arguments. |
Assets/Shaders/TriDexelCommon.hlsl |
Shared GPU side: segment-node layout, axis/column bit packing, and the analytic ray–cutter intersection. |
Assets/Shaders/TriDexelVisual.shader |
Custom/TriDexelVisual — expands each gathered segment into a box instance at draw time. |
Assets/Scripts/Scene/ToolAutoMover_Rect.cs |
Demo/diagnostic scaffolding, not part of the sim: drives the tool through a roughing raster plus contour finishing lap, at a constant feed. |
Assets/Scripts/Scene/ToolAutoMover_SinLine.cs |
Demo/diagnostic scaffolding: a single sinusoidal pass. Cut in one pass with no overlap, the groove's cross-section is the tool profile, so it reads a cutter's signature directly. Used by the four CutterExamples rigs in SampleScene — one per CutterType. |
Built and tested in Unity 6000.4.5f1.
Early-stage, and a work in progress. The dexel simulation runs and renders correctly at real-time rates — that's what's built so far.

