CNC Simple GCode Reader for Blender

Hi all,

of course there are already professional tools to read CNC (GCode) files and display a path or path animation here’s a little Python script I have done for use in Blender (open source 3D software).

import bpy

def parse_gcode(filepath):
    with open(filepath, 'r') as file:
        lines = file.readlines()

    vertices = []
    edges = []

    current_pos = [0.0, 0.0, 0.0]
    for line in lines:
        if line.startswith('G1'):
            parts = line.split()
            for part in parts:
                if part.startswith('X'):
                    current_pos[0] = float(part[1:])
                elif part.startswith('Y'):
                    current_pos[1] = float(part[1:])
                elif part.startswith('Z'):
                    current_pos[2] = float(part[1:])
            vertices.append(current_pos.copy())

    for i in range(len(vertices) - 1):
        edges.append((i, i + 1))

    return vertices, edges

def create_mesh_from_gcode(vertices, edges):
    mesh = bpy.data.meshes.new("GCodeMesh")
    obj = bpy.data.objects.new("GCodeMeshObj", mesh)
    bpy.context.collection.objects.link(obj)

    mesh.from_pydata(vertices, edges, [])
    mesh.update()

    return obj

# Pfad zur GCode-Datei
gcode_file = "C:/Path/Filename.cnc"

vertices, edges = parse_gcode(gcode_file)
gcode_mesh_obj = create_mesh_from_gcode(vertices, edges)

print("Ready")

To use it, start Blender, go to the “Scripting” tab at the top bar on the right side, then you see the development layout. Move the mouse into the editor area and use “ALT-N” to create a new text file inside the Blender file.

Copy and paste the above code and then adjust the line “gcode_file” with the right path and filename to your cnc file. Keep in mind that Blender/Python wants to have “/” as separator, not “\” as usual in Windows. If you want to use backslashes you need to write “\\” instead.

Then click the little Play button at the top of the editor and you see the loaded path in the 3D area. You can then switch to “Modelling” at the top bar for a better view.

This can be used for a quick path overview, it’s no replacement as GCode interpreter. It can only handle simple G1 commands.

I guess this will also work for laser and 3D print gcode files, but didn’t test that.

Maybe useful for some of you.

5 Likes