Kerfio Laser + CNC Workspace Specification
Document purpose: Define the recommended features, architecture, implementation notes, and technical advice for adding a professional Laser workspace and improving the current CNC workspace in Kerfio.
Target application: Kerfio CNC / Kerfio Digital Fabrication Platform
Frontend: React + TypeScript
Backend service: Python + FastAPI
Main goal: Build a unified CNC + Laser workflow where the user can draw/import geometry on a CAD canvas, assign different colors/layers/routes, give every path different manufacturing properties, generate safe G-code, preview the job, and control the machine.
Product Direction
Kerfio should evolve from a CNC-control app into a unified digital fabrication platform. The Laser and CNC sections should share the same core engine:
- CAD canvas
- Layer/path manager
- Machine profile manager
- Toolpath generator
- G-code sender
- G-code preview
- Safety manager
- Job manager
- Macro system
- Camera/vision module
- Material/tool library
The Laser workspace should be treated as a first-class section, not as a small add-on to CNC. Laser work needs different UI, safety checks, material presets, image engraving logic, layer-based settings, and machine-specific controls.
The CNC workspace should support route assignment directly on a CAD canvas, similar to professional CAM workflow: the user selects geometry, assigns an operation type, assigns color/layer, chooses tool/material/cut settings, then Kerfio generates G-code for each operation in a controlled order.
Main User Workflows
Laser Workflow
- Create or select a laser machine profile.
- Import or draw design geometry.
- Organize objects by color/layer.
- Assign each layer an operation:
- Cut
- Line engrave
- Fill engrave
- Image engrave
- Score
- Mark
- Dot/pulse
- Set power, speed, passes, air assist, focus, kerf compensation, and cut order.
- Preview toolpath.
- Run safety checklist.
- Frame the job at low power.
- Start, pause, resume, stop, or emergency stop the job.
- Save project and material settings.
CNC Workflow
- Create or select CNC machine profile.
- Import or draw 2D geometry on the CAD canvas.
- Select paths and assign route colors/layers.
- Assign each route a CNC operation:
- Profile outside cut
- Profile inside cut
- Engrave/V-carve later
- Drill
- Facing
- Slot
- Tabbed cut
- Trace/on-line cut
- Assign tool, feed, speed, depth, step-down, stepover, compensation, tabs, and ramp settings.
- Simulate toolpath.
- Check for collisions, unsafe depths, missing tool, out-of-area moves, and wrong zero.
- Generate G-code.
- Send job to controller.
Laser Workspace Feature List
Machine Profile
Each laser machine must have a profile.
Recommended fields:
laser_machine_profile:
id: string
name: string
controller_family: grbl | fluidnc | marlin | ruida_later | galvo_later
machine_type: diode | co2 | fiber_later | cnc_laser_combo
work_area_x_mm: float
work_area_y_mm: float
work_area_z_mm: float | null
origin: front_left | rear_left | center | custom
homing_enabled: boolean
max_power_value: 255 | 1000 | 10000 | custom
pwm_frequency_hz: float | null
laser_mode_supported: boolean
dynamic_power_supported: boolean
air_assist_supported: boolean
z_focus_supported: boolean
rotary_supported: boolean
camera_supported: boolean
firmware_notes: stringImportant notes:
- GRBL laser mode usually uses
M3for constant power andM4for dynamic power. - In GRBL-style workflows,
$32=1enables laser mode. - For diode lasers, dynamic power mode is usually preferred for vector engraving because it reduces burning during acceleration/deceleration.
- For slow cutting, constant power may be more predictable.
- Kerfio must not assume all controllers interpret
Spower values the same way. Storemax_power_valueper profile.
Laser Device Setup Wizard
Add a step-by-step wizard:
- Choose controller type.
- Choose work area.
- Choose origin position.
- Test connection.
- Read firmware information.
- Test movement.
- Test low-power laser fire.
- Test air assist output.
- Test homing.
- Save profile.
Safety rule: laser fire test must default to extremely low power and short duration.
Suggested low-power fire command strategy:
M3 S1
G4 P0.1
M5The actual S value must be calculated based on the machine profile.
Laser CAD Canvas
Required Canvas Tools
Minimum v1 tools:
- Select
- Pan
- Zoom
- Rectangle
- Circle / ellipse
- Line
- Polyline
- Bezier path
- Text
- Import image
- Import SVG
- Import DXF
- Move
- Scale
- Rotate
- Mirror
- Align
- Distribute
- Group / ungroup
- Lock / unlock
- Hide / show
- Snap to grid
- Snap to object
- Measure tool
- Bounding box display
- Object properties panel
Recommended advanced tools:
- Node edit
- Join paths
- Break path
- Offset path
- Boolean union / subtract / intersect
- Duplicate along line
- Circular array
- Nesting later
- QR code / barcode generator later
Color/Layer-Based Operation Model
This is a critical feature.
Every object/path on the canvas should have:
interface DesignObject {
id: string;
type: 'path' | 'rect' | 'circle' | 'text' | 'image' | 'group';
geometry: GeometryData;
strokeColor: string;
fillColor?: string;
layerId: string;
operationId?: string;
locked: boolean;
visible: boolean;
transform: Transform2D;
metadata?: Record<string, unknown>;
}Each layer/color should map to a manufacturing operation:
interface LaserLayerOperation {
id: string;
name: string;
color: string;
enabled: boolean;
order: number;
mode: 'cut' | 'line_engrave' | 'fill_engrave' | 'image_engrave' | 'score' | 'mark' | 'dot';
powerPercent: number;
speedMmMin: number;
passes: number;
airAssist: boolean;
zOffsetMm?: number;
kerfMm?: number;
lineIntervalMm?: number;
bidirectional?: boolean;
dithering?: 'threshold' | 'atkinson' | 'floyd_steinberg' | 'jarvis' | 'ordered';
overscanMm?: number;
rampPower?: boolean;
startDelayMs?: number;
endDelayMs?: number;
}User-facing example:
| Color | Laser Operation | Example Setting |
|---|---|---|
| Red | Cut | 90% power, 300 mm/min, 2 passes |
| Blue | Line engrave | 25% power, 1500 mm/min, 1 pass |
| Black | Fill engrave | 35% power, 2500 mm/min, 0.1 mm interval |
| Green | Score | 15% power, 2000 mm/min |
This design allows a user to visually assign manufacturing behavior from the canvas.
Object-to-Layer Assignment UX
Recommended UI:
- Left toolbar: drawing/editing tools.
- Center: CAD canvas.
- Right panel: object/layer properties.
- Bottom panel: G-code console and machine status.
- Top ribbon: import, generate, preview, frame, start.
Layer panel features:
- Add layer
- Delete layer
- Rename layer
- Change color
- Enable/disable layer
- Reorder layer
- Assign operation type
- Copy settings from another layer
- Save layer as material preset
- Apply material preset to layer
- Show estimated time per layer
Laser Operation Details
Cut Operation
Required settings:
- Power
- Speed
- Passes
- Kerf compensation
- Air assist
- Lead-in / lead-out later
- Tabs / bridges later
- Cut order
- Inside holes before outside contours
- Z step per pass if Z is available
G-code strategy:
G21 ; mm
G90 ; absolute
M4 S{power} ; or M3 depending on mode
G1 X... Y... F{speed}
M5Line Engrave / Vector Marking
Required settings:
- Power
- Speed
- M3/M4 mode
- Passes
- Air assist optional
- Optimization: reduce travel moves
Fill Engrave
Required settings:
- Power
- Speed
- Line interval
- Scan angle
- Bidirectional scanning
- Overscan
- Fill all shapes together or individually
- Cross-hatch later
Implementation advice:
- Convert filled vector geometry into scanlines.
- Clip scanlines against polygon interiors.
- Generate alternating lines for bidirectional mode.
- Add overscan distance before laser-on and after laser-off to avoid dark edges.
Image Engraving
Required settings:
- DPI or line interval
- Power range
- Speed
- Brightness
- Contrast
- Gamma
- Invert
- Dithering algorithm
- Grayscale power modulation
- Threshold mode
- Crop
- Resize
- Rotate
Recommended algorithms:
- Floyd-Steinberg dithering
- Atkinson dithering
- Ordered dithering
- Threshold
- Grayscale PWM modulation
Python tools:
- Pillow for image manipulation
- OpenCV for image preprocessing
- NumPy for fast raster processing
Dot / Pulse Mode
Useful for perforation, marking dots, or material tests.
Settings:
- Pulse power
- Pulse duration
- Dot spacing
- Row spacing
- Dwell time
G-code pattern:
G0 X... Y...
M3 S{power}
G4 P{duration}
M5Laser Material Library
Kerfio should include a professional material library.
Material preset fields:
laser_material_preset:
id: string
name: string
material_type: plywood | mdf | acrylic | leather | paper | aluminum_marking | steel_marking | cardboard | custom
thickness_mm: float
machine_profile_id: string
lens_or_focus_notes: string
operation_mode: cut | line_engrave | fill_engrave | image_engrave
power_percent: float
speed_mm_min: float
passes: int
air_assist: boolean
line_interval_mm: float | null
kerf_mm: float | null
notes: string
test_result_rating: 1_to_5
created_at: datetime
updated_at: datetimeRequired features:
- Add/edit/delete preset
- Duplicate preset
- Import/export preset JSON
- Apply preset to selected layer
- Save selected layer as preset
- Filter by material, thickness, machine
- Attach test photos later
- Track successful/failed settings
Recommended default categories:
- Plywood
- MDF
- Cardboard
- Paper
- Leather
- Fabric
- Acrylic black
- Acrylic transparent
- Anodized aluminum marking
- Stainless marking spray
- Painted metal marking
Important safety notes:
- Do not recommend cutting PVC/vinyl/chlorinated plastics.
- Warn users that unknown plastics can release toxic fumes.
- Require ventilation/air extraction reminder before job start.
Laser Material Test Generator
Must-have feature.
Test types:
- Power/speed grid
- Pass-count test
- Kerf test
- Focus ramp test
- Line interval test
- Dithering test
- Acrylic cut test
- Wood engraving contrast test
Power/speed grid parameters:
interface LaserMaterialTestRequest {
materialName: string;
testType: 'power_speed_grid' | 'focus_ramp' | 'kerf' | 'line_interval' | 'dithering';
minPower: number;
maxPower: number;
powerSteps: number;
minSpeedMmMin: number;
maxSpeedMmMin: number;
speedSteps: number;
cellWidthMm: number;
cellHeightMm: number;
labelCells: boolean;
operationMode: 'cut' | 'engrave';
}Output:
- G-code file
- Preview image
- Test metadata saved to material library
CNC Workspace Improvements
CNC Canvas Route/Layer System
Kerfio CNC should use the same layer/path idea as Laser, but operation parameters are CNC-specific.
interface CncRouteOperation {
id: string;
name: string;
color: string;
enabled: boolean;
order: number;
operationType:
| 'profile_outside'
| 'profile_inside'
| 'profile_on_line'
| 'pocket'
| 'drill'
| 'facing'
| 'slot'
| 'engrave'
| 'v_carve_later';
toolId: string;
spindleRpm: number;
feedRateMmMin: number;
plungeRateMmMin: number;
safeZMm: number;
startDepthMm: number;
targetDepthMm: number;
stepDownMm: number;
stepOverPercent?: number;
compensation: 'none' | 'inside' | 'outside';
tabs?: TabSettings;
ramp?: RampSettings;
coolant?: 'off' | 'mist' | 'flood';
}Example route mapping:
| Color | CNC Operation | Example Setting |
|---|---|---|
| Red | Outside profile cut | 3.175 mm end mill, 600 mm/min, -6 mm depth |
| Blue | 6 mm end mill, 40% stepover, -3 mm depth | |
| Green | Drill | 3 mm drill, peck cycle |
| Black | Engrave | V-bit, shallow depth |
CNC Operation Types
Profile Cut
Settings:
- Inside/outside/on-line
- Tool diameter
- Depth
- Step-down
- Feed/plunge
- Spindle speed
- Tabs
- Lead-in/lead-out
- Climb/conventional cut
Settings:
- Tool diameter
- Pocket depth
- Step-down
- Stepover
- Clearing strategy
- Finish pass
Recommended strategies:
- Offset pocket
- Zig-zag pocket
- Adaptive clearing later
Drill
Settings:
- Drill diameter
- Peck depth
- Retract height
- Dwell
- Feed rate
Facing
Settings:
- Area boundary
- Stepover
- Direction
- Depth
Engraving
Settings:
- Tool type
- Depth
- Feed
- Text/path support
- V-carve later
CNC Tool Library
Required fields:
cnc_tool:
id: string
name: string
type: end_mill | ball_nose | v_bit | drill | surfacing | engraving
diameter_mm: float
flute_count: int
cutting_length_mm: float
shank_diameter_mm: float
material: carbide | hss | diamond | custom
default_spindle_rpm: int
default_feed_mm_min: float
default_plunge_mm_min: float
default_stepdown_mm: float
default_stepover_percent: float
notes: stringCNC Material Library
Required fields:
- Material name
- Category: wood, MDF, acrylic, aluminum, brass, foam, PCB, plastic
- Recommended tools
- Feed/speed presets
- Max step-down
- Coolant recommendation
- Notes
Toolpath Safety Checks
Before G-code generation and before sending:
- Job is inside work area.
- Safe Z is above clamps.
- Target depth is not positive by mistake.
- Tool diameter is defined.
- Step-down is reasonable.
- Feed/plunge values are not zero.
- Spindle command exists for CNC cutting.
- Laser command does not exist in CNC mode.
- CNC spindle command does not exist in laser mode.
- Homing state is known.
- Work zero is set.
- Emergency stop status is clear.
G-code Engine
Shared G-code Architecture
Recommended Python modules:
kerfio_backend/
app/
machines/
profiles.py
connections.py
controllers/
grbl.py
fluidnc.py
marlin.py
geometry/
svg_import.py
dxf_import.py
transforms.py
offsets.py
boolean_ops.py
raster.py
cam/
laser_generator.py
cnc_generator.py
optimizer.py
safety_checks.py
simulator.py
gcode/
parser.py
sender.py
stream_queue.py
macros.py
dialects.py
materials/
laser_materials.py
cnc_materials.py
vision/
camera.py
calibration.py
alignment.py
api/
routes_laser.py
routes_cnc.py
routes_machine.py
websocket.pyG-code Sender Requirements
The sender must:
- Stream line by line.
- Wait for controller
ok/errorresponses. - Track sent, acknowledged, and pending lines.
- Support pause/resume.
- Support feed hold.
- Support emergency stop/reset.
- Support status polling.
- Support command priority for real-time commands.
- Log all commands and responses.
- Recover from disconnect when possible.
GRBL/FluidNC Real-Time Control
Support real-time commands:
?status report!feed hold~cycle start / resume- Ctrl-X soft reset
For safety, emergency stop should use hardware E-stop first. Software reset is not enough for a dangerous machine.
G-code Preview
Preview must show:
- Rapid moves
- Cut/engrave moves
- Laser-on moves
- Laser-off moves
- Z moves
- Work bounds
- Warnings
- Estimated time
- Per-layer statistics
Recommended frontend rendering:
- Use Three.js for 3D CNC preview.
- Use Canvas/SVG overlay for 2D Laser preview.
- For large G-code files, use Web Workers to parse/render without freezing UI.
React UI Architecture
Recommended Libraries
Core UI:
- React + TypeScript
- Vite
- Zustand for local state
- TanStack Query for backend state and caching
- React Hook Form + Zod for forms and validation
- Tailwind CSS or CSS Modules
- Radix UI or shadcn/ui for accessible components
Canvas/CAD:
- react-konva / Konva for interactive 2D canvas
- Paper.js for vector path editing and boolean operations if needed
- svg-pathdata or similar parser for SVG path manipulation
- d3-scale/d3-zoom only if you need custom zoom/grid behavior
3D/preview:
- Three.js or React Three Fiber
Machine console:
- xterm.js for terminal-like G-code console
File handling:
- browser File API
- JSZip for project export/import bundles
Recommended frontend structure:
src/
app/
routes/
LaserWorkspace.tsx
CncWorkspace.tsx
features/
canvas/
laser/
cnc/
machine/
gcode/
materials/
vision/
settings/
shared/
components/
hooks/
api/
types/
utils/React Laser Workspace Components
LaserWorkspace
LaserTopToolbar
LaserCanvas
LaserLayerPanel
LaserObjectPropertiesPanel
LaserOperationEditor
LaserMaterialLibraryPanel
LaserMachineControlPanel
LaserPreviewPanel
LaserConsolePanel
LaserSafetyChecklistModalReact CNC Workspace Components
CncWorkspace
CncTopToolbar
CncCanvas
CncRouteLayerPanel
CncOperationEditor
CncToolLibraryPanel
CncMaterialPanel
CncMachineControlPanel
CncPreview3DPanel
CncConsolePanel
CncSafetyChecklistModalState Management Advice
Use local Zustand stores for high-frequency UI state:
- selected objects
- zoom/pan
- active tool
- layer visibility
- temporary drag state
- canvas snapping state
Use backend database for durable state:
- projects
- machine profiles
- material presets
- tool library
- job history
- calibration data
Do not send every mouse movement to the backend. Keep editing local, then save project snapshots.
Python Backend Architecture
Recommended Tools
API:
- FastAPI
- Pydantic
- Uvicorn
- WebSocket endpoints for live status
Serial/control:
- pySerial
- pyserial-asyncio if you use async serial streaming
Geometry/CAM:
- Shapely for planar geometry, offsets, boolean operations
- ezdxf for DXF import/export
- svgpathtools for SVG paths
- NumPy
- Pillow
- OpenCV
Database:
- SQLite for local desktop app
- SQLModel or SQLAlchemy
- Alembic migrations
Background jobs:
- asyncio tasks for local single-user mode
- RQ/Celery only if the system becomes multi-user/server-based
Logging:
- structlog or Python logging
- rotating file logs
Packaging:
- PyInstaller for desktop distribution
- Docker for development/testing
API Endpoints
Suggested endpoints:
GET /api/machines
POST /api/machines
GET /api/machines/{id}
PUT /api/machines/{id}
DELETE /api/machines/{id}
POST /api/machine/connect
POST /api/machine/disconnect
POST /api/machine/jog
POST /api/machine/home
POST /api/machine/command
POST /api/machine/start-job
POST /api/machine/pause
POST /api/machine/resume
POST /api/machine/stop
POST /api/machine/emergency-stop
POST /api/laser/generate-gcode
POST /api/laser/material-test
GET /api/laser/materials
POST /api/laser/materials
PUT /api/laser/materials/{id}
POST /api/cnc/generate-gcode
GET /api/cnc/tools
POST /api/cnc/tools
GET /api/cnc/materials
POST /api/cnc/materials
WS /ws/machine-status
WS /ws/job-progress
WS /ws/consoleWebSocket Messages
Example:
{
"type": "machine_status",
"state": "Run",
"x": 10.2,
"y": 30.0,
"z": -1.5,
"feed": 600,
"spindle_or_laser": 350,
"buffer": 12,
"line": 184
}{
"type": "job_progress",
"job_id": "job_123",
"percent": 42.5,
"current_layer": "Red Cut",
"elapsed_sec": 180,
"estimated_remaining_sec": 245
}Camera and Vision Integration
This is especially important for your CNC vision direction.
Laser camera features:
- Live bed camera
- Camera calibration
- Lens distortion correction
- Bed coordinate mapping
- Place design on camera image
- Align job to workpiece
- Edge detection
- Fiducial/marker alignment
- Print-and-cut style alignment
CNC camera features:
- Find workpiece corner
- Find center of circle/hole
- Set work zero visually
- Detect clamps/obstacles later
- Verify material position
- Tool camera alignment offset
Python tools:
- OpenCV
- NumPy
- AprilTag/ArUco detection later
- WebRTC or MJPEG stream depending on performance target
Important calibration data:
camera_calibration:
camera_id: string
machine_profile_id: string
matrix: number[][]
distortion_coefficients: number[]
homography_canvas_to_machine: number[][]
pixels_per_mm: float
camera_mount_offset_x_mm: float
camera_mount_offset_y_mm: floatSafety Requirements
Laser Safety
Mandatory checks:
- User confirms eye protection.
- Ventilation/extractor active.
- Air assist active for cutting.
- Door/interlock status if available.
- Flame sensor status if available.
- Water flow status for CO₂ if available.
- Job is inside work area.
- Material is not PVC/vinyl/unknown toxic plastic.
- Low-power frame completed.
- Emergency stop tested/available.
CNC Safety
Mandatory checks:
- Correct tool installed.
- Workpiece clamped.
- Zero set correctly.
- Safe Z configured.
- Dust collection optional but recommended.
- Spindle speed command exists.
- Toolpath does not exceed machine area.
- Tabs exist for full-depth cutouts if needed.
- Emergency stop available.
Software Safety Design
- Never auto-start a job immediately after G-code generation.
- Always require explicit user start.
- Stop button must be always visible.
- Emergency stop button must be global and prominent.
- Software stop is not a replacement for hardware E-stop.
- Dangerous settings should require confirmation.
Project File Format
Use JSON inside a ZIP bundle.
Suggested extensions:
.kerfio-laser.kerfio-cnc.kerfio-project
Example structure:
project.kerfio-laser
project.json
assets/
image_001.png
import_001.svg
gcode/
last_generated.nc
previews/
preview.pngproject.json should include:
- App version
- Machine profile reference
- Canvas objects
- Layer operations
- Material presets used
- G-code generation options
- Notes
Recommended Implementation Phases
Phase 1: Core Layer-Based Laser + CNC Canvas
- React canvas
- Object import/draw/edit
- Layer/color manager
- Assign operation to layer
- Save/load project
- Basic G-code generation
- Basic preview
Phase 2: Laser Machine Control
- Serial connection
- GRBL/FluidNC support
- Jog/home/unlock/frame/start/pause/resume/stop
- Console
- Job progress
Phase 3: Laser Advanced Tools
- Material library
- Material test generator
- Image engraving
- Fill engraving
- Kerf compensation
- Rotary mode
Phase 4: CNC CAM Improvements
- Profile inside/outside/on-line
- Pocketing
- Drilling
- Tabs
- Tool library
- Material presets
Phase 5: Vision
- Camera stream
- Calibration
- Bed overlay
- Visual zero setting
- Workpiece alignment
Functionality Checklist
Laser Must-Have
- Machine profile
- GRBL/FluidNC connection
- CAD canvas
- SVG import
- DXF import
- Image import
- Color/layer operation assignment
- Cut operation
- Line engrave operation
- Fill engrave operation
- Image engrave operation
- Material library
- Material test generator
- G-code preview
- Frame job
- Low-power fire test
- Start/pause/resume/stop
- Console
- Safety checklist
CNC Must-Have
- CNC machine profile
- Canvas path/layer route assignment
- Tool library
- Material library
- Profile cut inside/outside/on-line
- Pocket operation
- Drill operation
- Tabs
- Safe Z
- G-code preview
- Work zero workflow
- Machine control panel
- Safety checklist
Recommended External References
These are useful references for feature comparison and implementation design:
- LightBurn Documentation: https://docs.lightburnsoftware.com/2.1/
- LightBurn Cuts/Layers: https://docs.lightburnsoftware.com/UI/CutsAndLayers.html
- LightBurn Material Test: https://docs.lightburnsoftware.com/Tools/MaterialTest.html
- LightBurn Camera Calibration: https://docs.lightburnsoftware.com/Camera/Calibration.html
- GRBL Laser Mode: https://github.com/gnea/grbl/blob/master/doc/markdown/laser_mode.md
- GRBL project: https://github.com/grbl/grbl
- FluidNC Documentation: https://fluidnc.com/
- react-konva: https://konvajs.org/docs/react/index.html
- Paper.js Path API: https://paperjs.org/reference/path/
- Shapely Documentation: https://shapely.readthedocs.io/en/stable/manual.html
- Shapely offset_curve: https://shapely.readthedocs.io/en/2.1.2/reference/shapely.offset_curve.html
- OpenCV Camera Calibration: https://opencv24-python-tutorials.readthedocs.io/en/latest/py_tutorials/py_calib3d/py_calibration/py_calibration.html
- FastAPI WebSockets: https://fastapi.tiangolo.com/advanced/websockets/
- pySerial API: https://pyserial.readthedocs.io/en/latest/pyserial_api.html
Final Technical Recommendation
For Kerfio, implement the Laser and CNC route assignment system around one shared concept:
A canvas object belongs to a visual layer/color, and that layer/color maps to one manufacturing operation with specific machine parameters.
This is the correct architecture because it supports both laser and CNC naturally:
- Laser: color/layer = cut, engrave, fill, image, score.
- CNC: color/layer = profile, pocket, drill, engrave, facing.
Build the layer/operation engine first. Then build laser and CNC G-code generation as separate backends that consume the same canvas/project model.
