Библиотека TextToCAD

Python code reference

The complete guide to preparing Python code for FreeCAD.

Quick Start — 5 Minutes

Minimal path from a furniture description to working Python code for FreeCAD

1

Parameters

All dimensions as UPPER_CASE variables

2

Coordinates

Z-marks + expected_objects

3

Parts

Part.makeBox → translate → addObject

4

Validation

doc.recompute() + check every object

Minimal Python: bedside cabinet
Пример кода
# ═══ STAGE 1: PARAMETERS ═══
import FreeCAD
import Part

doc = FreeCAD.ActiveDocument
if doc is None:
    doc = FreeCAD.newDocument("TextToCAD")

W = 450          # Cabinet width, mm
D = 400          # Depth
H = 550          # Height
T = 16           # Chipboard thickness
COKOL_H = 60    # Plinth height

# ═══ STAGE 2: COORDINATES ═══
INNER_W = W - 2 * T         # 418
Z_DNO_BOT = COKOL_H              # 60
Z_DNO_TOP = COKOL_H + T          # 76
Z_KRYSHA_BOT = H - T             # 534

# Check: 60 + 16 + 458 + 16 = 550 ✓

expected_objects = [
    "Bok_LDSP16mm_1", "Bok_LDSP16mm_2",
    "Dno_LDSP16mm_1", "Krysha_LDSP16mm_1",
]

# ═══ STAGE 3: PARTS ═══
side_l = Part.makeBox(T, D, H)
side_l.translate(FreeCAD.Vector(0, 0, 0))
obj = doc.addObject("Part::Feature", "Bok_LDSP16mm_1")
obj.Shape = side_l

side_r = Part.makeBox(T, D, H)
side_r.translate(FreeCAD.Vector(W - T, 0, 0))
obj = doc.addObject("Part::Feature", "Bok_LDSP16mm_2")
obj.Shape = side_r

bottom = Part.makeBox(INNER_W, D, T)
bottom.translate(FreeCAD.Vector(T, 0, Z_DNO_BOT))
obj = doc.addObject("Part::Feature", "Dno_LDSP16mm_1")
obj.Shape = bottom

top_p = Part.makeBox(W, D, T)
top_p.translate(FreeCAD.Vector(0, 0, Z_KRYSHA_BOT))
obj = doc.addObject("Part::Feature", "Krysha_LDSP16mm_1")
obj.Shape = top_p

# ═══ STAGE 4: VALIDATION ═══
doc.recompute()
for name in expected_objects:
    obj = doc.getObject(name)
    if obj is None:
        print("FAIL: " + name)
        continue
    s = obj.Shape
    if s.isNull() or not s.isValid() or s.Volume <= 0:
        print("FAIL: " + name + " - invalid shape")
    else:
        bb = s.BoundBox
        print("OK: " + name + " | " + str(round(bb.XLength)) + "x" + str(round(bb.YLength)) + "x" + str(round(bb.ZLength)))
I

Pipeline & Architecture

TextToCAD/FreeCAD Pipeline

Request → LLM → Python Code → TextToCAD → exec() → 3D Model in FreeCAD

The prompt directs the LLM not to "describe a shape" but to generate concrete Python code using the FreeCAD Part API. The code is executed in an isolated sandbox via exec().

4 Architectural Principles

1.
Syntactic purity of examples. Every code fragment in the prompt is executable Python. The LLM learns from examples — examples must be flawless.
2.
Stage-by-stage generation. 4 stages: parameters → coordinates → parts → validation. A human verifies each stage.
3.
Transparent traceability. Standard doc.addObject() + expected_objects + final verification via doc.getObject().
4.
Enhanced documentation. All examples are commented. Reference tables in tabular format. Templates filled with examples.

3 Product Types

Type A
Metal Structures

Frames, canopies, racks. create_tube, create_tube_z. Fastening: welding.

Type B
Cabinet Furniture

Wardrobes, dressers, kitchens. Part.makeBox, drill_hole, drill_cup. Fasteners: confirmat screws, dowels, cam locks.

Type C
Mixed

Table with metal frame + wooden top. Combination of A and B.

II

Input Request Types

Type A
Full Package

Photos + drawings + instructions + parts list. All dimensions known → blocks A–H of the master prompt.

Type B
Photos + Dimensions

Photographs + W×D×H. Parts derived from proportions per §III. LLM requests confirmation.

Type C
Text Description

"4-drawer dresser, oak, one meter tall". Dimensions from standards in §XVIII. Note: # standard, verify.

Type D
Name Only

"IKEA MALM dresser". LLM performs web search → if assembly instructions found → Type A, otherwise → Type B.

Classification Algorithm
Пример кода
1. Assembly instructions / drawings available?
   YES → Type A → proceed to blocks A–H
   NO → step 2

2. Photos + overall dimensions (W×D×H) available?
   YES → Type B → photo analysis (§III)
   NO → step 3

3. Product name/SKU specified?
   YES → Type D → web search (§III)
   NO → Type C → dimensions from standards (§XVIII)
III

Data Collection & Research

Web Search Algorithm (Type D) — 5 Steps

1.
By name: "[name] dimensions specifications" → overall dims, material, sections
2.
Instructions: "[name] assembly instructions PDF" → priority source
3.
Photos: "[name] photo" → 4 angles for analysis
4.
Analogues: "[furniture type] [sections] dimensions" → if exact match not found
5.
Verification: Discrepancy >20 mm → request clarification from user

Photo Analysis — 4 Angles

Front: sections, proportions, facades, gaps, handles
Side: depth, overhangs, plinth, thicknesses
Open: drawers, slides, shelves
Rear: back panels, stiffeners

Instruction Analysis — 3 Sections

Parts list → each line = Part.makeBox()
Hardware → determines number of drill_hole() calls
Assembly diagrams → populates joint table

IV

9 Critical Generation Rules

1.
Solid bodies. len(shape.Solids) >= 1, shape.Volume > 0, shape.isValid() == True, not shape.isNull()
2.
4-stage structure. PARAMETERS → COORDINATES → PARTS → VALIDATION. Order must not be violated.
3.
Mandatory imports. import FreeCAD, import Part, import math — each on its own line.
4.
Sandbox prohibitions. hasattr(), getattr(), setattr(), delattr() — PROHIBITED. Replacement: if 'Shape' in obj.PropertiesList:
5.
One instruction = one line. Line concatenation is the most common copy-paste error. Never import FreeCAD import Part.
6.
Naming convention. <Type>_<MaterialProfile>_<Number>. ASCII only, ≤32 characters. Cyrillic prohibited.
7.
Parameterization. ALL dimensions as variables in Stage 1. Code body uses only names, not numeric literals.
8.
Transformation order. Create at origin → rotate → translate. NOT create → translate → rotate (rotation around origin!).
9.
No f-strings. The FreeCAD sandbox may not support f-strings. Use concatenation only: "text" + str(value).
V

FreeCAD Sandbox

Prohibited

hasattr(obj, 'Shape') getattr(obj, 'Shape') setattr(obj, 'val', x) delattr(obj, 'val')

Replacement

if 'Shape' in obj.PropertiesList: obj.Shape # direct access obj.val = x # direct assignment # delattr not needed
VI

Part::Feature Naming Convention

<ElementType>_<MaterialProfile>_<Number>
Format: ASCII A-Z, a-z, 0-9, _, x. Maximum 32 characters.
Prohibited: Cyrillic, spaces, hyphens, periods, brackets.
Numbering: From 1, separate counter per ElementType.
Fractional: 1.5 mm → 15, 0.5 mm → 05 (no decimal point).
KeywordDescriptionExample
Truba<W>x<H>x<T>Square/rectangular tubeStolb_Truba60x40x3_1
TrubaKruglD<D>x<T>Round tubeNozhka_TrubaKruglD48x3_2
LDSP<T>mmLaminated chipboardBok_LDSP16mm_1
MDF<T>mmMDFFasad_MDF19mm_1
DVP<T>mmHardboard / HDFZadstena_DVP3mm_1
Steklo<T>mmGlassPolka_Steklo6mm_1
Fanera<T>mmPlywoodDno_Fanera18mm_1
List<T>mmSheet steelPanel_List2mm_1
FurnituraHardware / fittingsPetlya_Furnitura_1
C21_<T>mmCorrugated sheet C21Proflist_C21_05mm_3
VII

4 Code Generation Stages

STAGE 1
Parameters
→ STAGE 2
Coordinates
→ STAGE 3
Parts
→ STAGE 4
Validation

STAGE 1Parameter Block

All dimensions as UPPER_CASE variables. Single source of truth. Grouping: overall dims, materials, fasteners, gaps.

Stage 1 — Example
Пример кода
# ═══ STAGE 1: PARAMETERS ═══
W = 800         # Width, mm
D = 450         # Depth
H = 930         # Height
T = 16          # Chipboard body
T_BACK = 3      # Hardboard back panel
COKOL_H = 80    # Plinth height
GAP_FASAD = 3   # Gap between facades
GUIDE_W = 13    # Ball-bearing slide width
OFFSET_EDGE = 50 # Fastener edge offset

STAGE 2Coordinates & Z-Marks Block

Formulas derived from Stage 1 parameters. Arithmetic verification of Z-levels. expected_objects list.

Stage 2 — Example
Пример кода
# ═══ STAGE 2: COORDINATES ═══
Z_DNO_BOT = COKOL_H                # 80
Z_DNO_TOP = COKOL_H + T            # 96
Z_KRYSHA_BOT = H - T               # 914
INNER_W = W - 2 * T               # 768

# Arithmetic check:
# Plinth: 80 + Bottom: 16 + Section: 818 + Top: 16 = 930 ✓

expected_objects = [
    "Bok_LDSP16mm_1",
    "Bok_LDSP16mm_2",
    "Dno_LDSP16mm_1",
    "Krysha_LDSP16mm_1",
]

STAGE 3Part Generation

Part by part. Each as a separate block. Holes in the same block via drill_hole. Finalize with: doc.addObject("Part::Feature", name).

Stage 3 — Single Part
Пример кода
# --- Left side panel ---
bok_left = Part.makeBox(T, D, H)
bok_left.translate(FreeCAD.Vector(0, 0, 0))

# Confirmat screw for bottom (through-hole, Z axis)
bok_left = drill_hole(
    bok_left,
    x=T / 2.0,
    y=OFFSET_EDGE,
    z=Z_DNO_BOT,
    diameter=7.0,
    depth=T + 1,
    axis="Z"
)

obj = doc.addObject("Part::Feature", "Bok_LDSP16mm_1")
obj.Shape = bok_left

STAGE 4Final Validation

doc.recompute() → check every object from expected_objects → informative messages → raise RuntimeError on failures.

Stage 4 — Validation
Пример кода
doc.recompute()
error_count = 0
for name in expected_objects:
    obj = doc.getObject(name)
    if obj is None:
        print("FAIL: " + name + " - not found")
        error_count += 1
        continue
    if 'Shape' not in obj.PropertiesList:
        print("FAIL: " + name + " - no Shape")
        error_count += 1
        continue
    s = obj.Shape
    if s.isNull() or not s.isValid() or len(s.Solids) < 1 or s.Volume <= 0:
        print("FAIL: " + name + " - invalid")
        error_count += 1
    else:
        bb = s.BoundBox
        print("OK: " + name + " | " +
              str(round(bb.XLength, 1)) + "x" +
              str(round(bb.YLength, 1)) + "x" +
              str(round(bb.ZLength, 1)))
if error_count > 0:
    raise RuntimeError(str(error_count) + " object(s) failed")
VIII

Elevation Marks & Z-Verification

For each horizontal part, specify bottom and top faces. Layer checksum = H.

Elevation Marks — 2100 mm Wardrobe
Пример кода
# ELEVATION MARKS (Z, mm)
# Z = 0       floor
# Z = 0..80   plinth
# Z = 80      bottom face of base (16 mm chipboard)
# Z = 96      top face of base
# Z = 96..436 lower compartment (340 mm)
# Z = 436     bottom face of shelf 1
# Z = 452     top face of shelf 1
# Z = 2084    bottom face of top panel
# Z = 2100    top face of top panel
# Check: 80+16+340+16+1216+16+400+16 = 2100 ✓

Arithmetic Verification

delta = 0 → Perfect
0 < delta ≤ 15 mm → Acceptable (absorbed by facade gaps)
delta > 15 mm → ERROR — recalculate Z top-down
delta < 0 → ERROR — missing section or plinth
IX

Function Reference (11 total)

9.1 FreeCAD Part API

FunctionDescriptionReturns
Part.makeBox(W, D, H)Box from originPart.Shape
Part.makeCylinder(r, h)Cylinder along Z-axis from originPart.Shape
shape.translate(Vector)Translation (mutates shape)None
shape.rotate(center, axis, angle)Rotation (mutates)None
shape.cut(other)Boolean subtractionPart.Shape
shape.fuse(other)Boolean unionPart.Shape
shape.common(other)Boolean intersectionPart.Shape

9.2 create_tube — Hollow Tube

create_tube(start, end, outer_w, outer_h, t)
Пример кода
def create_tube(start, end, outer_w, outer_h, t):
    """Hollow rectangular tube from start to end.
    outer_w, outer_h — outer cross-section, t — wall thickness.
    For square: outer_w == outer_h.
    Returns Part.Shape or None."""
    direction = end.sub(start)
    length = direction.Length
    if length < 0.01:
        return None
    direction.normalize()
    inner_w = outer_w - 2 * t
    inner_h = outer_h - 2 * t
    if inner_w <= 0 or inner_h <= 0:
        return None
    outer = Part.makeBox(outer_w, outer_h, length)
    inner = Part.makeBox(inner_w, inner_h, length + 1)
    inner.translate(FreeCAD.Vector(t, t, -0.5))
    tube = outer.cut(inner)
    tube.translate(FreeCAD.Vector(-outer_w / 2.0, -outer_h / 2.0, 0))
    z_axis = FreeCAD.Vector(0, 0, 1)
    rotation_axis = z_axis.cross(direction)
    if rotation_axis.Length > 1e-6:
        dot = z_axis.dot(direction)
        dot = max(-1.0, min(1.0, dot))
        angle = math.degrees(math.acos(dot))
        tube.rotate(FreeCAD.Vector(0,0,0), rotation_axis, angle)
    elif direction.z < 0:
        tube.rotate(FreeCAD.Vector(0,0,0), FreeCAD.Vector(1,0,0), 180)
    tube.translate(start)
    return tube

9.3 drill_hole — Fastener Hole

6 drilling directions. BoundBox check ±1 mm. Returns Part.Shape with hole cut out.

axisDirectionDescription
"Z"+Z (bottom to top)Standard for horizontal joints
"Z_DOWN"−Z (top to bottom)Top panel from above
"X"+X (left to right)Into end-grain of horizontal panel from left
"X_NEG"−X (right to left)Into end-grain from right
"Y"+Y (front to back)Hinge cups
"Y_NEG"−Y (back to front)Reverse drilling

9.4 drill_cup — Hinge Cup

Typical parameters: cup_d=35, cup_depth=12 for overlay hinge. Axes: "Y" (front) or "Y_NEG".

X

Fastener Reference

TypeD, mmDepth, mmPer jointEdge offset
Confirmat pilot (7×50)5.050250 mm
Confirmat through-hole7.0T+1250 mm
Confirmat countersink10.03.0——
Dowel D8×308.015 (each side)2100 mm
Cam lock socket15.012.5250 mm
Cam lock bolt7.034——
Hinge cup D3535.0122–4 per door100 mm from edge
Shelf pin5.0124 per shelf50 mm
Ball-bearing slide13×45—pair per drawer—
XI

Decomposition into Sub-Prompts

>25 Part::Feature or >200 lines → mandatory decomposition. Order: A → B → C → D → E in a single FreeCAD document.

A
Carcass + fasteners
B
Back panels
C
Doors
D
Hardware
E
Drawers
ComplexityPart::FeatureLines of codeRecommendation
Low1–320–60Single sub-prompt
Medium4–1060–120Single with loops
High10–25120–2002–3 sub-prompts
Very high25+200+Mandatory decomposition
XII

Drawer Pattern on Slides

Drawer Calculation Formulas
Пример кода
INNER_W = W - 2 * T                   # between carcass sides
DRAWER_W = INNER_W - 2 * GUIDE_W      # minus 2 slides (13 mm each)
DRAWER_BOTTOM_W = DRAWER_W - 2 * T   # minus 2 drawer sides

# X position of drawer left side
X_DRAWER_LEFT = T + GUIDE_W            # 16 + 13 = 29

# Facade = carcass width - gaps
FASAD_W = W - 2 * GAP_FASAD
FASAD_H = (Z_SECTION_TOP - Z_SECTION_BOT) - 2 * GAP_FASAD

Each drawer: 2× YashikBok + YashikPered + YashikZad + YashikDno + Fasad + 2× Napravl

XIII

Niches & Decorative Inserts

Critical Rule

A niche ends exactly at Z = side_height (top of side panels). The top panel rests ON the side panels AND on the niche upper edges simultaneously.

Z_NISHA_TOP = Z_KRYSHA_BOT + T
✗ Niche above side panels!
Z_NISHA_TOP = Z_KRYSHA_BOT
✓ Flush with side panels
XIV

LLM Preambles (6 total)

4.1 Universal

9 rules + functions + fastener reference + response format. For any task.

4.2 Shortened

For single simple parts. 9 rules in brief.

4.3 Full Package (A)

Mapping parts from instructions → names. Cross-verification.

4.4 No Documentation (C/D)

Standard size reference. Web search. User confirmation.

4.5 From Screenshot

5 discrepancy categories. Comment # FIXED on every change.

Combined

4.1 + selected specialization (4.3/4.4/4.5).

Universal Preamble Core (condensed)
Пример кода
You are an expert in generating Python code for FreeCAD within TextToCAD.

CRITICAL RULES:
1. Solids>=1, Volume>0, isValid(), not isNull()
2. 4 stages: PARAMETERS → COORDINATES → PARTS → VALIDATION
3. import FreeCAD / import Part / import math — each on its own line
4. PROHIBITED: hasattr(), getattr(), setattr(), delattr()
5. One instruction = one line. Indentation: 4 spaces.
6. Names: <Type>_<MaterialProfile>_<N>, ASCII, ≤32 characters
7. All dimensions as variables in STAGE 1
8. Order: create → rotate → translate (NOT the reverse!)
9. No f-strings. String concatenation only.

FORMAT: Python code only. 4 stages. No explanations. No markdown.
XV

Troubleshooting Common Issues

Line concatenation

Newlines \n lost during copy-paste. Always use the "Copy code" button. Validation blocks >80 chars without \n.

"name 'hasattr' is not defined"

Replacement: if 'Shape' in obj.PropertiesList:

Volume == 0

.cut() removed all volume. Or inner_size >= outer_size in create_tube.

Material not recognized

Leg_1 → won't work. Use Nozhka_Truba40x40x2_1 with keyword.

drill_hole: outside body

Hole coordinates outside BoundBox ±1 mm. Check part's translate values.

Incorrect support scheme

Standard: side panels from Z=0 to Z=H. Base at Z=COKOL_H. Plinth is a decorative strip.

Parts intersecting

Top panel passes through side panels → overlapping Z-ranges. Recalculate Z-marks.

create_tube → None

start == end (length=0) or outer_w <= 2*t (negative cross-section).

XVI

Checklist (31 Points)

Preparation
Code Structure
Syntax
Execution

Full Generation Examples

Example A — Table Frame (Type C)

Dimensions: 1200×800×775
Parts: 9 pcs.
Tube: 40×40×2
Sub-prompts: 2

4 legs (Nozhka_Truba40x40x2_1..4) + 4 frame beams (Frame_Truba40x40x2_1..4) + tabletop (Stoleshnica_LDSP25mm_1). Sub-prompt A: frame via create_tube. Sub-prompt B: tabletop via Part.makeBox.

Example B — Wardrobe 1500×500×2100 (Type B)

Dimensions: 1500×500×2100
Parts: 7+ carcass
Support: Sides from floor
delta: 0 ✓

Side panels Z=0→2100, base at Z=80, top at Z=2084, shelves at Z=436 and Z=1668. Confirmat screws + dowels via drill_hole. Decomposition: A=carcass, B=back panels, C=doors, D=hardware.

XVIII

Standard Sizes Reference

Materials

MaterialThicknessCode
Chipboard (body)16 mmLDSP16mm
Chipboard (countertops)25 mmLDSP25mm
Hardboard (back panels)3 mmDVP3mm
MDF (facades)16–19 mmMDF16mm

Gaps

GapSize
Between facades2–3 mm
For slide rails12.5–13 mm
Top panel overhang10–30 mm
Plinth80 mm (kitchen: 100)

Standard Overall Dimensions

TypeH, mmW, mmD, mm
Dresser800–1000600–1200400–500
Bedside cabinet400–550400–600350–450
Two-door wardrobe2000–2400800–1200550–600
Writing desk7501200–1600600–800
Shelving unit1800–2200600–1000250–350
Kitchen base cabinet850600 (modular)560–600
Tall cabinet (pantry)1800–2200400–600350–500
A

Appendix A — Transliteration

RussianLatinUsage
Боковина (Side panel)BokWardrobes, cabinets
Крыша (Top panel)KryshaUpper panel
Дно (Bottom)DnoBottom panel
Полка (Shelf)PolkaRemovable shelf
Горизонталь (Horizontal)GorizontFixed horizontal panel
Вертикаль (Vertical)VertikalPartition
Цоколь (Plinth)CokolFront strip
Дверь (Door)DverHinged door
Фасад (Facade)FasadDrawer front
Задняя стенка (Back panel)ZadstenaHardboard back
Столешница (Countertop)StoleshnicaWork surface
Ящик боковина (Drawer side)YashikBokDrawer side panel
Ящик перед (Drawer front)YashikPeredDrawer front panel
Ящик зад (Drawer back)YashikZadDrawer back panel
Ящик дно (Drawer bottom)YashikDnoDrawer bottom
Ниша (Niche)NishaDecorative insert
Ножка (Leg)NozhkaSupport leg
Столб (Post)StolbFrame post
Балка (Beam)BalkaHorizontal frame member
Штанга (Rod/Bar)ShtangaClothing rod
Направляющая (Slide rail)NapravlBall-bearing / roller slide
Профлист (Corrugated sheet)ProflistCladding
B

Appendix B — GOST Tubes

TypeDimensions (mm)
Square20×20×1.5, 25×25×2, 40×40×2, 50×50×2, 50×50×3, 60×60×3, 80×80×4
Rectangular40×20×2, 60×40×2, 60×40×3, 80×40×3, 100×50×3
RoundD25×2, D32×2.5, D48×3, D57×3.5, D76×3
C

Appendix C — Changelog

v4.0-FTCAD → v5.0-FTCAD CURRENT

1.Unified structure with TCSL documentation v6.0
2.Single HTML format with table of contents, anchors, code blocks
3.LLM context in hidden block (machine-readable)
4.All 11 functions in a unified reference with tables
5.Visual patterns: drawers, niches, elevation marks
6.31-point interactive checklist
7.Quick start with minimal working example
8.Rule 9 added: f-strings prohibited in sandbox

Reference Sources

texttocad.ru — TextToCAD Platform
tcsl-lang.org/spec — TCSL Specification v1.5
wiki.freecad.org/Part_scripting — FreeCAD Part API
Python/FreeCAD · TextToCAD · Document v5.0
Based on: v4.0-FTCAD + TCSL v6.0 · Date: 2026-04-06
texttocad.ru · texttocad@gmail.com
CC BY-SA 4.0 · TextToCAD