3dSynth

Tutorials / Custom G-code

Open in the interactive tutorials reader

---
title: Tutorial 37 G-code as Geometry Language
description: Using G-code to define shapes, not just moves.
---

Tutorial 37 G-code as Geometry Language

1. Lesson Header

2. Concept Introduction

The Inverse Problem.
Usually: Geometry -> Slicer -> G-code.
Now: G-code -> Geometry.
G-code contains the exact definition of the printed object's volume (Toolpath Volume).
If we sweep the nozzle shape along the path, we reconstruct the solid.
This allows us to use G-code as a Storage Format for procedural geometry.

3. Machine State Explanation

Swept Volume.
A single G1 move creates a cylinder (or capsule) of plastic.
The union of all these capsules is the final object.
Volume = Union(Capsule(P1, P2, R) for all moves).

4. Command Breakdown

5. Minimal Working Example

The Reconstruction.
G-code:
G1 X0 Y0 E1
G1 X10 Y0 E1
Geometry:
A capsule from (0,0) to (10,0) with radius Width/2.

6. Visual Representation

Interactive preview is available in the interactive reader.

7. Build Exercise

Task: Write a Python script to "Voxelize" a G-code file.
1. Define a 3D grid (numpy array).
2. For each G1 move:
- Rasterize the line into the grid.
- Mark voxels as "Filled".
3. Export as .obj or view as a point cloud.

Why?
To verify that a generated G-code file (from Lesson 27) actually forms a watertight solid.

8. Deep Insight Section

G-code vs STL.
STL is a surface mesh (Triangles).
G-code is a volumetric instruction set.
G-code is actually a more accurate representation of the physical object than the STL, because it includes the artifacts, layer lines, and flow variations.

9. Common Failure Modes

  1. Resolution: A high-res voxel grid (0.1mm) requires gigabytes of RAM. Use sparse arrays (Octrees).
  2. Over-extrusion: G-code assumes perfect flow. Real plastic squishes. The reconstruction won't show the "elephant foot" unless you simulate physics (Lesson 42).

10. Real-World Application

Digital Twins.
High-end manufacturing uses G-code simulation to create a "Digital Twin" of the part as manufactured.
They compare this twin to the original CAD to check for tolerances.
"Did the toolpath deviation cause this hole to be too small?"

11. Final Clean Version

The Voxelizer (Conceptual Python):

import numpy as np

grid_size = 100
voxels = np.zeros((grid_size, grid_size, grid_size), dtype=bool)

def draw_line(p1, p2):
    # Bresenham's Line Algorithm in 3D
    # Mark voxels[x,y,z] = True
    pass

# Parse G-code
# For each move:
#   p1 = current_pos
#   p2 = next_pos
#   draw_line(p1, p2)

# Count filled voxels
print(f"Volume: {np.sum(voxels)} units")

12. Stretch Challenge

Challenge: Write a script that converts G-code to STL.
Use the "Marching Cubes" algorithm on your voxel grid to generate a triangle mesh.
Now you can print the G-code... again? Or use it in a render.
This closes the loop: STL -> G-code -> STL.
Measure the error between the original STL and the reconstructed one.