anycad 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +36 -2
  3. package/install.ps1 +41 -0
  4. package/package.json +16 -4
  5. package/runtime/assembly_plan.py +166 -0
  6. package/runtime/build_model.py +78 -0
  7. package/runtime/cad_help.py +147 -0
  8. package/runtime/cad_primitives.py +110 -0
  9. package/runtime/native_plan.py +107 -0
  10. package/runtime/plan.py +148 -0
  11. package/showcase/anycad-preview.png +0 -0
  12. package/showcase/dovetail-0mm.step +3514 -0
  13. package/showcase/dovetail-plus10mm.step +3514 -0
  14. package/showcase/dovetail-preview.png +0 -0
  15. package/showcase/dovetail-prompt.md +3 -0
  16. package/showcase/rounded-bolt-block.step +987 -0
  17. package/src/cad-construct.ts +231 -0
  18. package/src/cad-tools.ts +84 -0
  19. package/src/extension.ts +228 -0
  20. package/src/runtime.ts +5 -0
  21. package/vendor/text-to-cad/package.json +7 -0
  22. package/vendor/text-to-cad/skills/cad/LICENSE +21 -0
  23. package/vendor/text-to-cad/skills/cad/SKILL.md +241 -0
  24. package/vendor/text-to-cad/skills/cad/agents/openai.yaml +4 -0
  25. package/vendor/text-to-cad/skills/cad/references/2d-profiles-and-dxf.md +197 -0
  26. package/vendor/text-to-cad/skills/cad/references/animation.md +115 -0
  27. package/vendor/text-to-cad/skills/cad/references/build123d-modeling.md +206 -0
  28. package/vendor/text-to-cad/skills/cad/references/environments.md +44 -0
  29. package/vendor/text-to-cad/skills/cad/references/exports.md +249 -0
  30. package/vendor/text-to-cad/skills/cad/references/inspection-and-validation.md +383 -0
  31. package/vendor/text-to-cad/skills/cad/references/kinematics.md +478 -0
  32. package/vendor/text-to-cad/skills/cad/references/manufacturing-cnc.md +127 -0
  33. package/vendor/text-to-cad/skills/cad/references/manufacturing-injection-molding.md +133 -0
  34. package/vendor/text-to-cad/skills/cad/references/manufacturing-printing.md +129 -0
  35. package/vendor/text-to-cad/skills/cad/references/manufacturing-review.md +144 -0
  36. package/vendor/text-to-cad/skills/cad/references/manufacturing-sheet-metal.md +167 -0
  37. package/vendor/text-to-cad/skills/cad/references/model-contract.md +281 -0
  38. package/vendor/text-to-cad/skills/cad/references/positioning.md +94 -0
  39. package/vendor/text-to-cad/skills/cad/references/project-layout.md +79 -0
  40. package/vendor/text-to-cad/skills/cad/references/snapshot-review.md +203 -0
  41. package/workflow.md +13 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AnyCAD contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,37 @@
1
- # Temporary Holding Version
1
+ # AnyCAD
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ AnyCAD is a local parametric CAD workflow for Pi. It generates editable build123d source, runs the official text-to-CAD build and inspection, and exports STEP. It can look up syntax in the included local references and asks for missing mounting dimensions when a design needs to fit existing hardware.
4
+
5
+ ## Showcase
6
+
7
+ ![Exploded dovetail guide and slider with the prompt excerpt and measured run statistics](https://raw.githubusercontent.com/CubM/AnyCAD/v1.0.2/showcase/dovetail-preview.png)
8
+
9
+ > Make a two-solid guide and slider assembly, with sharp edges.
10
+
11
+ The full prompt specifies a 100 × 52 mm base, a through dovetail, a fitted tongue, counterbored mounting holes, and an editable travel parameter. [Read the exact prompt](https://github.com/CubM/AnyCAD/blob/v1.0.2/showcase/dovetail-prompt.md)
12
+
13
+ AnyCAD produced both named solids. The independent grader matched the STEP against a fresh build of the submitted source and measured zero interference at both travel positions. [Starting STEP](https://github.com/CubM/AnyCAD/raw/refs/tags/v1.0.2/showcase/dovetail-0mm.step) · [+10 mm STEP](https://github.com/CubM/AnyCAD/raw/refs/tags/v1.0.2/showcase/dovetail-plus10mm.step)
14
+
15
+ | Model and provider | Agent time | Output tokens | Tool calls | Tool errors | Independent grade |
16
+ | --- | ---: | ---: | ---: | ---: | ---: |
17
+ | `qwen3.8-9b-distill` via LM Studio | 14.5 s | 405 | 1 | 0 | 100/100 |
18
+
19
+ Time includes Pi startup, model inference, and CAD calls. The independent grade runs afterward. A separate [conversational bolt-block example](https://github.com/CubM/AnyCAD/blob/v1.0.2/showcase/anycad-preview.png) passed in 17.7 seconds with 509 output tokens, one call, and zero errors.
20
+
21
+ ## Install
22
+
23
+ Download the Windows x64 bundle from [GitHub Releases](https://github.com/CubM/AnyCAD/releases), extract it to a stable location, and run `./install.ps1` from PowerShell. Pi, Node.js, Python 3.12 x64 and uv are host prerequisites. The release includes the CAD skill and Python wheels for text-to-CAD 0.11.21, build123d 0.13.0 and their dependencies. The installer uses your existing CAD CLI and skill when registered. A source checkout can run the same installer, which uses PyPI if CAD is missing and the wheels are absent.
24
+
25
+ For Pi with the CAD CLI and skill already set up, the compact package installs with `pi install npm:anycad` once available on npm. A GitHub install uses `pi install git:github.com/CubM/AnyCAD`.
26
+
27
+ ## Use
28
+
29
+ Open a new Pi session or run `/reload`. AnyCAD activates on recognizable CAD requests when `lmstudio/qwen3.8-9b-distill` is selected. Start a request with `CAD` to activate it explicitly. CAD turns select low reasoning effort and use the local CAD and file tools. Pi restores the previous tool and reasoning selections after the turn.
30
+
31
+ The LM Studio application, model, and provider extension are host components. AnyCAD uses the provider already configured in Pi. The default output paths are `src/model.py` and `exports/model.step` in the current project.
32
+
33
+ Run `pi list` to see the registered source and `pi remove <source>` to uninstall it. If the installer added the bundled CAD skill, remove that source separately.
34
+
35
+ ## Dependencies and credits
36
+
37
+ The included [text-to-CAD skill](https://github.com/earthtojake/text-to-cad) comes from commit `09eed4073a6660e8ae814a26215209f646b6091a`. Its license accompanies the skill. The release wheels retain their upstream metadata and licenses.
package/install.ps1 ADDED
@@ -0,0 +1,41 @@
1
+ $ErrorActionPreference = 'Stop'
2
+ $package = $PSScriptRoot
3
+ $pi = (Get-Command pi -ErrorAction Stop).Source
4
+ $python = (Get-Command python -ErrorAction Stop).Source
5
+ $wheelhouse = Join-Path $package 'vendor/wheels'
6
+ $requiredCad = '0.11.21'
7
+ $cad = Get-Command cad -ErrorAction SilentlyContinue
8
+
9
+ if ($cad) {
10
+ $currentCad = & $cad.Source --version
11
+ if ($LASTEXITCODE -ne 0) { throw 'The installed CAD CLI could not report its version.' }
12
+ Write-Host "Using installed $currentCad."
13
+ } else {
14
+ $uv = (Get-Command uv -ErrorAction Stop).Source
15
+ & $python -c 'import struct,sys; sys.exit(int(sys.version_info[:2] != (3,12) or struct.calcsize("P") != 8))'
16
+ if ($LASTEXITCODE -ne 0) { throw 'The bundled CAD wheels require Windows x64 Python 3.12.' }
17
+ $sources = if (Test-Path -LiteralPath $wheelhouse) { @('--offline', '--no-index', '--find-links', $wheelhouse) } else { @('--index-url', 'https://pypi.org/simple') }
18
+ & $uv tool install @sources --python $python --with 'build123d==0.13.0' "cad[build123d]==$requiredCad"
19
+ if ($LASTEXITCODE -ne 0) { throw 'Could not install the official CAD CLI and its dependencies.' }
20
+ $toolBin = & $uv tool dir --bin
21
+ if ($LASTEXITCODE -ne 0) { throw 'Could not determine the uv tool directory.' }
22
+ $env:PATH = "$toolBin;$env:PATH"
23
+ & $uv tool update-shell
24
+ if ($LASTEXITCODE -ne 0) { throw 'Could not add the CAD CLI to the user PATH.' }
25
+ }
26
+
27
+ $agent = if ($env:PI_CODING_AGENT_DIR) { $env:PI_CODING_AGENT_DIR } else { Join-Path $HOME '.pi/agent' }
28
+ $settingsFile = Join-Path $agent 'settings.json'
29
+ $sources = @()
30
+ if (Test-Path -LiteralPath $settingsFile) {
31
+ $settings = Get-Content -LiteralPath $settingsFile -Raw | ConvertFrom-Json
32
+ $sources = @($settings.packages | ForEach-Object { if ($_ -is [string]) { $_ } else { $_.source } })
33
+ }
34
+ $officialSkill = $sources | Where-Object { $_ -match '^git:github\.com/earthtojake/text-to-cad(?:@|$)' }
35
+ if (-not $officialSkill) {
36
+ & $pi install (Join-Path $package 'vendor/text-to-cad') --no-approve
37
+ if ($LASTEXITCODE -ne 0) { throw 'Could not register the bundled CAD skill with Pi.' }
38
+ }
39
+ & $pi install $package --no-approve
40
+ if ($LASTEXITCODE -ne 0) { throw 'Could not register the CAD package with Pi.' }
41
+ Write-Host 'AnyCAD is installed.'
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "anycad",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.2",
4
+ "description": "Local parametric CAD for Pi. A two-solid dovetail took 14.5 s, 405 output tokens, 1 call, and 0 errors on qwen3.8-9b-distill.",
5
+ "license": "MIT",
6
+ "repository": { "type": "git", "url": "git+https://github.com/CubM/AnyCAD.git" },
7
+ "homepage": "https://github.com/CubM/AnyCAD#readme",
8
+ "keywords": ["pi-package"],
9
+ "pi": {
10
+ "extensions": ["./src/extension.ts"],
11
+ "image": "https://raw.githubusercontent.com/CubM/AnyCAD/v1.0.2/showcase/dovetail-preview.png"
12
+ },
13
+ "peerDependencies": {
14
+ "@earendil-works/pi-coding-agent": "*",
15
+ "typebox": "*"
16
+ },
17
+ "files": ["src", "runtime/*.py", "vendor/text-to-cad", "showcase", "workflow.md", "install.ps1", "README.md"]
18
+ }
@@ -0,0 +1,166 @@
1
+ """Compile dimensioned assembly features to the normal native CAD source format."""
2
+
3
+ import json
4
+ from itertools import product
5
+ from math import isclose
6
+ from pathlib import Path
7
+ import shutil
8
+ import sys
9
+
10
+ from plan import compile_source
11
+
12
+
13
+ class AssemblyPlan:
14
+ def __init__(self, request):
15
+ self.request = request
16
+ self.steps = []
17
+
18
+ def add(self, name, op, **values):
19
+ self.steps.append({"name": name, "op": op, **values})
20
+ return name
21
+
22
+ def stock(self, name, section):
23
+ return self.add(name, "stock", width=section["width"], depth=section["depth"],
24
+ height=section["z1"] - section["z0"], bottom=section["z0"])
25
+
26
+ def cut(self, name, body, *items):
27
+ return self.add(name, "cut", body=body, items=list(items))
28
+
29
+ def fuse(self, name, body, *items):
30
+ return self.add(name, "fuse", body=body, items=list(items))
31
+
32
+ def z_pattern(self, prefix, pattern, z0, z1):
33
+ centers = dict.fromkeys(product(pattern["x_centers"], pattern["y_centers"]))
34
+ return [self.add(f"{prefix}_{index}", "cylinder_z", diameter=pattern["diameter"],
35
+ z0=z0, z1=z1, x=x, y=y)
36
+ for index, (x, y) in enumerate(centers)]
37
+
38
+ def width_profile(self, name, x0, x1, sections):
39
+ right = [[width / 2, z] for z, width in sections]
40
+ left = [[-y, z] for y, z in reversed(right)]
41
+ return self.add(name, "prism_x", x0=x0, x1=x1, yz_points=right + left)
42
+
43
+ def assemble(self, parts, void):
44
+ result = self.add("complete_assembly", "assembly", parts=parts)
45
+ return {
46
+ "steps": self.steps, "result": result,
47
+ "parameter": self.request["parameter"], "void": void,
48
+ }
49
+
50
+
51
+ def split_support(request):
52
+ p = AssemblyPlan(request)
53
+ base_spec = request["base"]
54
+ bridge_spec = request["bridge"]
55
+ barrel_spec = request["barrel"]
56
+ base = p.stock("base", base_spec)
57
+ pedestal = p.stock("pedestal", request["pedestal"])
58
+ bridge = p.stock("bridge", bridge_spec)
59
+ barrel = p.add("barrel", "cylinder_y", **barrel_spec)
60
+ body = p.fuse("joined", base, pedestal, bridge, barrel)
61
+ body = p.add("slotted", "cut_slots_y", body=body, **request["base_slots"],
62
+ z0=base_spec["z0"] - 1, z1=base_spec["z1"] + 1)
63
+ body = p.add("shaft_bore", "drill_through_y", body=body, x=barrel_spec["x"],
64
+ z=barrel_spec["z"], diameter=request["parameter"]["name"])
65
+ seat = request["shaft_seat"]
66
+ if not request["parameter"]["default"] < seat["diameter"] < barrel_spec["diameter"]:
67
+ raise ValueError("The shaft-seat diameter must be between the shaft bore and the barrel diameters.")
68
+ if not 0 < seat["depth"] < barrel_spec["y1"] - barrel_spec["y0"]:
69
+ raise ValueError("Use the counterbore depth from its opening, within the barrel length.")
70
+ if isclose(seat["entry_y"], barrel_spec["y0"]):
71
+ y0, y1 = barrel_spec["y0"] - 1, barrel_spec["y0"] + seat["depth"]
72
+ elif isclose(seat["entry_y"], barrel_spec["y1"]):
73
+ y0, y1 = barrel_spec["y1"] - seat["depth"], barrel_spec["y1"] + 1
74
+ else:
75
+ raise ValueError("The shaft-seat entry Y must be one of the barrel's two end coordinates.")
76
+ seat_tool = p.add("shaft_seat_tool", "cylinder_y", x=barrel_spec["x"], z=barrel_spec["z"],
77
+ diameter=seat["diameter"], y0=y0, y1=y1)
78
+ body = p.cut("seated", body, seat_tool)
79
+ bolts = request["clamp_bolts"]
80
+ bores = p.z_pattern("bolt", bolts, bridge_spec["z0"] - 1, bridge_spec["z1"] + 1)
81
+ seats = p.z_pattern("bolt_seat", {**bolts, "diameter": bolts["counter_diameter"]},
82
+ bridge_spec["z1"] - bolts["counter_depth"], bridge_spec["z1"] + 1)
83
+ body = p.cut("bolted", body, *bores, *seats)
84
+ split = request["split"]
85
+ lower = p.add("lower_half", "half_z", body=body, plane_z=split["z"], upper=False)
86
+ upper = p.add("upper_half", "half_z", body=body, plane_z=split["z"], upper=True)
87
+ slots = request["base_slots"]
88
+ base_middle = (base_spec["z0"] + base_spec["z1"]) / 2
89
+ bridge_middle = (bridge_spec["z0"] + bridge_spec["z1"]) / 2
90
+ barrel_middle = (barrel_spec["y0"] + barrel_spec["y1"]) / 2
91
+ void = [[x, y, base_middle] for x, y in product(slots["x_centers"], slots["y_centers"])]
92
+ void.extend([x, y, bridge_middle] for x, y in product(bolts["x_centers"], bolts["y_centers"]))
93
+ void.append([barrel_spec["x"], barrel_middle, barrel_spec["z"]])
94
+ return p.assemble({split["lower_name"]: lower, split["upper_name"]: upper}, void)
95
+
96
+
97
+ def dovetail_carriage(request):
98
+ p = AssemblyPlan(request)
99
+ base_spec = request["guide_base"]
100
+ rail_spec = request["rail"]
101
+ slider_spec = request["slider_plate"]
102
+ groove_spec = request["groove"]
103
+ tongue_spec = request["tongue"]
104
+ floor_z, opening_z = groove_spec["floor_z"], groove_spec["opening_z"]
105
+ floor_width, opening_width = groove_spec["floor_width"], groove_spec["opening_width"]
106
+ bottom_z, shoulder_z, top_z = tongue_spec["bottom_z"], tongue_spec["shoulder_z"], tongue_spec["top_z"]
107
+ bottom_width, neck_width = tongue_spec["bottom_width"], tongue_spec["neck_width"]
108
+ if not 0 < opening_width < floor_width < rail_spec["depth"]:
109
+ raise ValueError(f"Groove floor and opening use full Y widths. Got floor {floor_width:g}, "
110
+ f"opening {opening_width:g}, and the rail is only {rail_spec['depth']:g} wide along Y.")
111
+ if not rail_spec["z0"] <= floor_z < opening_z or not isclose(opening_z, rail_spec["z1"]):
112
+ raise ValueError("Set the floor inside the rail and the opening at the rail's top Z.")
113
+ if not 0 < neck_width < bottom_width < floor_width or neck_width >= opening_width:
114
+ raise ValueError("Use full Y widths for the tongue and keep it narrower than the groove.")
115
+ if not floor_z <= bottom_z < shoulder_z <= top_z < slider_spec["z1"] or top_z < slider_spec["z0"]:
116
+ raise ValueError("Use the tongue's absolute bottom, shoulder and top heights. The top must reach the top plate.")
117
+ groove_sections = [(floor_z, floor_width), (opening_z, opening_width)]
118
+ tongue_sections = [(bottom_z, bottom_width), (shoulder_z, neck_width)]
119
+ if top_z > shoulder_z:
120
+ tongue_sections.append((top_z, neck_width))
121
+ guide = p.fuse("guide_stock", p.stock("base", base_spec), p.stock("rail", rail_spec))
122
+ groove = p.width_profile("groove", -rail_spec["width"] / 2 - 1, rail_spec["width"] / 2 + 1,
123
+ groove_sections)
124
+ guide = p.cut("grooved_guide", guide, groove)
125
+ mounts = request["guide_mounts"]
126
+ guide = p.cut(
127
+ "guide_with_mounts", guide,
128
+ *p.z_pattern("mount", mounts, base_spec["z0"] - 1, base_spec["z1"] + 1),
129
+ *p.z_pattern("mount_seat", {**mounts, "diameter": mounts["counter_diameter"]},
130
+ base_spec["z1"] - mounts["counter_depth"], base_spec["z1"] + 1),
131
+ )
132
+ tongue = p.width_profile("tongue", -slider_spec["width"] / 2, slider_spec["width"] / 2,
133
+ tongue_sections)
134
+ slider = p.fuse("slider_stock", tongue, p.stock("slider_plate", slider_spec))
135
+ holes = request["slider_holes"]
136
+ pin = request["transverse_hole"]
137
+ cross = p.add("cross_tool", "cylinder_y", diameter=pin["diameter"], x=pin["x"], z=pin["z"],
138
+ y0=-slider_spec["depth"] / 2 - 1, y1=slider_spec["depth"] / 2 + 1)
139
+ slider = p.cut(
140
+ "drilled_slider", slider, cross,
141
+ *p.z_pattern("slider_hole", holes, bottom_z - 1, slider_spec["z1"] + 1),
142
+ *p.z_pattern("slider_seat", {**holes, "diameter": holes["counter_diameter"]},
143
+ slider_spec["z1"] - holes["counter_depth"], slider_spec["z1"] + 1),
144
+ )
145
+ slider = p.add("placed_slider", "translate", body=slider, dx=request["parameter"]["name"], dy=0, dz=0)
146
+ void = [[mounts["x_centers"][0], mounts["y_centers"][0], (base_spec["z0"] + base_spec["z1"]) / 2]]
147
+ return p.assemble({request["guide_name"]: guide, request["slider_name"]: slider}, void)
148
+
149
+
150
+ def main():
151
+ root = Path.cwd()
152
+ request = json.loads((root / "geometry-plan.json").read_text(encoding="utf-8"))
153
+ kind = {"split_support": split_support, "dovetail": dovetail_carriage}[request["kind"]]
154
+ source = compile_source(kind(request), 2)
155
+ output = root / "src/model.py"
156
+ output.parent.mkdir(exist_ok=True)
157
+ shutil.copyfile(Path(__file__).with_name("cad_primitives.py"), output.with_name("cad_primitives.py"))
158
+ output.write_text(source, encoding="utf-8")
159
+ print("Saved native src/model.py with two geometry-checked parts.")
160
+
161
+
162
+ if __name__ == "__main__":
163
+ try:
164
+ main()
165
+ except (OSError, ValueError, KeyError) as error:
166
+ sys.exit(str(error))
@@ -0,0 +1,78 @@
1
+ """Build, inspect, and optionally export one text-to-CAD model through its official CLI."""
2
+
3
+ import argparse
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ import tempfile
10
+
11
+
12
+ MODEL_ID = re.compile(r"(?mi)^\s*id:\s*([0-9a-f-]{36})\s*$")
13
+
14
+
15
+ def run_cad(directory, *args):
16
+ executable = shutil.which("cad")
17
+ if not executable:
18
+ raise RuntimeError("cad is unavailable on PATH")
19
+ environment = {
20
+ **os.environ,
21
+ "PYTHONIOENCODING": "utf-8",
22
+ "OPENBLAS_NUM_THREADS": "1",
23
+ "OMP_NUM_THREADS": "1",
24
+ "MKL_NUM_THREADS": "1",
25
+ }
26
+ wheelhouse = Path(__file__).resolve().parents[1] / "vendor/wheels"
27
+ if wheelhouse.is_dir():
28
+ existing_links = environment.get("UV_FIND_LINKS", "")
29
+ environment["UV_FIND_LINKS"] = f"{wheelhouse.as_uri()} {existing_links}".strip()
30
+ with tempfile.TemporaryFile() as log:
31
+ process = subprocess.run(
32
+ [executable, *args], cwd=directory, env=environment, timeout=110,
33
+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, check=False,
34
+ )
35
+ log.seek(0)
36
+ output = log.read().decode("utf-8", errors="replace")
37
+ if process.returncode:
38
+ raise RuntimeError(output.strip()[-1800:] or f"cad exited with {process.returncode}")
39
+ return output
40
+
41
+
42
+ def build(directory, source):
43
+ output = run_cad(directory, "run", str(source))
44
+ identifiers = MODEL_ID.findall(output)
45
+ if len(identifiers) != 1:
46
+ raise RuntimeError(
47
+ "Expected one model ID from cad run. Ensure one decorated model is called "
48
+ 'under if __name__ == "__main__". ' + output.strip()[-550:]
49
+ )
50
+ return identifiers[0], output
51
+
52
+
53
+ def main():
54
+ parser = argparse.ArgumentParser(description=__doc__)
55
+ parser.add_argument("source", type=Path)
56
+ parser.add_argument("--step", type=Path, help="Export the verified build to this path.")
57
+ parser.add_argument("--assembly", action="store_true", help="Check interference before export.")
58
+ args = parser.parse_args()
59
+ cwd = Path.cwd()
60
+ try:
61
+ identifier, output = build(cwd, args.source)
62
+ print(output.rstrip())
63
+ summary = run_cad(cwd, "model", "inspect", identifier).replace("\r\n", "\n")
64
+ print("cad model inspect", identifier)
65
+ print(summary.split("\nclosure\n", 1)[0].strip())
66
+ count = re.search(r"(?mi)^\s*parts\s+(\d+)\b", summary)
67
+ if args.assembly or (count and int(count.group(1)) > 1):
68
+ print("cad model interference", identifier)
69
+ print(run_cad(cwd, "model", "interference", identifier).strip())
70
+ if args.step:
71
+ args.step.parent.mkdir(parents=True, exist_ok=True)
72
+ print(run_cad(cwd, "model", "export", identifier, str(args.step)).strip())
73
+ except (RuntimeError, subprocess.TimeoutExpired) as error:
74
+ parser.exit(1, f"CAD build stopped. {error}\n")
75
+
76
+
77
+ if __name__ == "__main__":
78
+ main()
@@ -0,0 +1,147 @@
1
+ """Look up build123d usage from the installed CAD runtime and local text-to-CAD docs."""
2
+
3
+ import argparse
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+
10
+ from build_model import run_cad
11
+
12
+
13
+ RECIPES = {
14
+ "extrude": (
15
+ ("extrude", "RectangleRounded", "Wire.make_polygon"),
16
+ "rounded = bd.extrude(bd.RectangleRounded(width, depth, corner_radius), amount=height)\n"
17
+ "pocket = bd.Pos(0, 0, floor_z) * rounded\n"
18
+ "wire = bd.Wire.make_polygon([(x0, y, z) for y, z in yz_points], close=True)\n"
19
+ "prism = bd.extrude(bd.Face(wire), amount=length, dir=(1, 0, 0))",
20
+ ),
21
+ "fillet": (
22
+ ("fillet", "ShapeList.filter_by"),
23
+ "result = bd.fillet(body.edges().filter_by(bd.Axis.Z), radius)",
24
+ ),
25
+ "box": (
26
+ ("Box", "Pos"),
27
+ "body = bd.Pos(cx, cy, (z0 + z1) / 2) * bd.Box(width, depth, z1 - z0)",
28
+ ),
29
+ "cylinder": (
30
+ ("Cylinder", "Rot"),
31
+ "z_cutter = bd.Pos(cx, cy, (z0 + z1) / 2) * bd.Cylinder(radius, z1 - z0)\n"
32
+ "y_cutter = bd.Pos(cx, (y0 + y1) / 2, cz) * bd.Rot(90, 0, 0) * bd.Cylinder(radius, y1 - y0)\n"
33
+ "x_cutter = bd.Pos((x0 + x1) / 2, cy, cz) * bd.Rot(0, 90, 0) * bd.Cylinder(radius, x1 - x0)",
34
+ ),
35
+ "slot": (
36
+ ("SlotOverall", "extrude"),
37
+ "profile = bd.SlotOverall(overall_length, slot_width, rotation=90)\n"
38
+ "y_slot = bd.Pos(cx, cy, z0) * bd.extrude(profile, amount=z1 - z0)",
39
+ ),
40
+ "split": (
41
+ ("Solid.split", "Compound"),
42
+ "lower = body.split(bd.Plane.XY.offset(seam_z), keep=bd.Keep.BOTTOM)\n"
43
+ "upper = body.split(bd.Plane.XY.offset(seam_z), keep=bd.Keep.TOP)",
44
+ ),
45
+ "assembly": (
46
+ ("Compound",),
47
+ "first.label = 'first'\nsecond.label = 'second'\nassembly = bd.Compound(children=[first, second])",
48
+ ),
49
+ "parameter": (
50
+ ("model.param",),
51
+ 'width = model.param("width", 18.0, min=12.0, max=26.0, unit="mm")',
52
+ ),
53
+ "probe": (
54
+ ("Solid.is_inside", "Shape.bounding_box"),
55
+ "solid = body.solids()[0]\nassert solid.is_valid\nassert solid.is_inside(material_point)\n"
56
+ "assert not solid.is_inside(void_point)\nbox = solid.bounding_box()",
57
+ ),
58
+ "boolean": (
59
+ ("Solid.cut", "Solid.fuse"),
60
+ "one_solid = base.fuse(boss)\npart = one_solid.cut(cutter_1, cutter_2)",
61
+ ),
62
+ }
63
+ ALIASES = {
64
+ "pocket": "extrude", "rounded pocket": "extrude", "rectanglerounded": "extrude",
65
+ "polygon": "extrude", "wire": "extrude", "gusset": "extrude", "dovetail": "extrude",
66
+ "round": "fillet", "hole": "cylinder", "counterbore": "cylinder", "rotation": "cylinder",
67
+ "slotoverall": "slot", "compound": "assembly", "interference": "assembly",
68
+ "param": "parameter", "model.param": "parameter", "bounds": "probe", "is_inside": "probe",
69
+ "cut": "boolean", "fuse": "boolean",
70
+ }
71
+
72
+
73
+ def api_probe(symbols):
74
+ snippet = f"""\
75
+ import inspect
76
+ import build123d as bd
77
+ from cad import model
78
+ for symbol in {symbols!r}:
79
+ target = model if symbol.startswith("model.") else bd
80
+ try:
81
+ for field in symbol.removeprefix("model.").split("."):
82
+ target = getattr(target, field)
83
+ if inspect.isclass(target):
84
+ target = target.__init__
85
+ signature = str(inspect.signature(target))
86
+ print(symbol + signature.replace("(self, ", "(", 1))
87
+ except (AttributeError, TypeError, ValueError):
88
+ print(symbol + ": no callable signature found in this CAD runtime")
89
+ """
90
+ return run_cad(Path.cwd(), "run", "-c", snippet).strip()
91
+
92
+
93
+ def local_matches(docs, keywords):
94
+ rg = shutil.which("rg")
95
+ if not docs.is_dir():
96
+ return []
97
+ pattern = r"(?i)\b(?:" + "|".join(re.escape(word) for word in keywords) + r")\b"
98
+ if rg:
99
+ common_refs = ("build123d-modeling.md", "model-contract.md", "positioning.md", "inspection-and-validation.md")
100
+ globs = [item for name in common_refs for item in ("-g", name)]
101
+ process = subprocess.run(
102
+ [rg, "--no-heading", "-n", "-m", "4", *globs, "-e", pattern, str(docs)],
103
+ text=True, encoding="utf-8", errors="replace", capture_output=True, check=False,
104
+ )
105
+ lines = sorted(process.stdout.splitlines(), key=lambda line: (
106
+ 0 if "`bd." in line or "model.param(" in line else 1, line.casefold()
107
+ ))
108
+ return [line.replace(str(docs) + os.sep, "")[:260] for line in lines[:4]]
109
+ expression = re.compile(pattern)
110
+ return [
111
+ f"{path.relative_to(docs)}:{number}:{line[:200]}"
112
+ for path in sorted(docs.rglob("*.md"))
113
+ for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1)
114
+ if expression.search(line)
115
+ ][:4]
116
+
117
+
118
+ def main():
119
+ parser = argparse.ArgumentParser(description=__doc__)
120
+ parser.add_argument("keywords", nargs="+", help="Operations such as extrude, fillet, or SlotOverall.")
121
+ default_docs = Path(__file__).resolve().parents[1] / "vendor/text-to-cad/skills/cad"
122
+ parser.add_argument("--docs", type=Path, default=default_docs)
123
+ args = parser.parse_args()
124
+ operations = dict.fromkeys(ALIASES.get(word.casefold(), word.casefold()) for word in args.keywords)
125
+ symbols = dict.fromkeys(
126
+ symbol for operation, (names, _) in RECIPES.items() if operation in operations for symbol in names
127
+ )
128
+ for word in args.keywords:
129
+ if ALIASES.get(word.casefold(), word.casefold()) in RECIPES:
130
+ continue
131
+ if re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)*", word):
132
+ symbols[word.removeprefix("bd.")] = None
133
+ if symbols:
134
+ try:
135
+ print(api_probe(list(symbols)))
136
+ except (RuntimeError, subprocess.TimeoutExpired) as error:
137
+ print("CAD API lookup failed:", str(error)[-450:])
138
+ for operation in operations:
139
+ if operation in RECIPES:
140
+ print(f"\n{operation} example\n{RECIPES[operation][1]}")
141
+ matches = local_matches(args.docs, list(operations) + args.keywords)
142
+ if matches:
143
+ print("\nInstalled text-to-CAD references\n" + "\n".join(matches))
144
+
145
+
146
+ if __name__ == "__main__":
147
+ main()
@@ -0,0 +1,110 @@
1
+ """Reusable dimensions-first helpers over the installed build123d solids."""
2
+
3
+ import build123d as bd
4
+
5
+
6
+ def stock(width, depth, height, bottom=0, x=0, y=0):
7
+ return bd.Pos(x, y, bottom + height / 2) * bd.Box(width, depth, height)
8
+
9
+
10
+ def block(x0, x1, y0, y1, z0, z1):
11
+ return stock(x1 - x0, y1 - y0, z1 - z0, z0, (x0 + x1) / 2, (y0 + y1) / 2)
12
+
13
+
14
+ def cylinder_z(diameter, z0, z1, x=0, y=0):
15
+ return bd.Pos(x, y, (z0 + z1) / 2) * bd.Cylinder(diameter / 2, z1 - z0)
16
+
17
+
18
+ def cylinder_y(diameter, y0, y1, x=0, z=0):
19
+ return bd.Pos(x, (y0 + y1) / 2, z) * bd.Rot(90, 0, 0) * bd.Cylinder(diameter / 2, y1 - y0)
20
+
21
+
22
+ def cylinder_x(diameter, x0, x1, y=0, z=0):
23
+ return bd.Pos((x0 + x1) / 2, y, z) * bd.Rot(0, 90, 0) * bd.Cylinder(diameter / 2, x1 - x0)
24
+
25
+
26
+ def drill_through_z(body, diameter, x=0, y=0):
27
+ bounds = body.bounding_box()
28
+ return body.cut(cylinder_z(diameter, bounds.min.Z - 1, bounds.max.Z + 1, x, y))
29
+
30
+
31
+ def drill_through_y(body, diameter, x=0, z=0):
32
+ bounds = body.bounding_box()
33
+ return body.cut(cylinder_y(diameter, bounds.min.Y - 1, bounds.max.Y + 1, x, z))
34
+
35
+
36
+ def drill_through_x(body, diameter, y=0, z=0):
37
+ bounds = body.bounding_box()
38
+ return body.cut(cylinder_x(diameter, bounds.min.X - 1, bounds.max.X + 1, y, z))
39
+
40
+
41
+ def round_all(body, radius):
42
+ return bd.fillet(body.edges(), radius)
43
+
44
+
45
+ def round_vertical(body, radius):
46
+ return bd.fillet(body.edges().filter_by(bd.Axis.Z), radius)
47
+
48
+
49
+ def rounded_prism(width, depth, radius, z0, z1):
50
+ return bd.Pos(0, 0, z0) * bd.extrude(bd.RectangleRounded(width, depth, radius), amount=z1 - z0)
51
+
52
+
53
+ def slot_y(overall_length, width, x, y, z0, z1):
54
+ outline = bd.SlotOverall(overall_length, width, rotation=90)
55
+ return bd.Pos(x, y, z0) * bd.extrude(outline, amount=z1 - z0)
56
+
57
+
58
+ def drill_pattern_z(body, diameter, x_centers, y_centers):
59
+ bounds = body.bounding_box()
60
+ cutters = [cylinder_z(diameter, bounds.min.Z - 1, bounds.max.Z + 1, x, y)
61
+ for x in x_centers for y in y_centers]
62
+ return body.cut(*cutters)
63
+
64
+
65
+ def counterbore_z(body, diameter, floor, x=0, y=0):
66
+ return body.cut(cylinder_z(diameter, floor, body.bounding_box().max.Z + 1, x, y))
67
+
68
+
69
+ def drill_from_positive_x(body, diameter, stop, y, z):
70
+ end = body.bounding_box().max.X + 1
71
+ return body.cut(cylinder_x(diameter, stop, end, y, z))
72
+
73
+
74
+ def drill_pattern_y(body, diameter, x_centers, z_centers):
75
+ bounds = body.bounding_box()
76
+ cutters = [cylinder_y(diameter, bounds.min.Y - 1, bounds.max.Y + 1, x, z)
77
+ for x in x_centers for z in z_centers]
78
+ return body.cut(*cutters)
79
+
80
+
81
+ def cut_slots_y(body, overall_length, width, x_centers, y_centers, z0, z1):
82
+ cutters = [slot_y(overall_length, width, x, y, z0, z1)
83
+ for x in x_centers for y in y_centers]
84
+ return body.cut(*cutters)
85
+
86
+
87
+ def prism_x(yz_points, x0, x1):
88
+ wire = bd.Wire.make_polygon([(x0, y, z) for y, z in yz_points], close=True)
89
+ return bd.extrude(bd.Face(wire), amount=x1 - x0, dir=(1, 0, 0))
90
+
91
+
92
+ def half_z(body, plane_z, upper):
93
+ keep = bd.Keep.TOP if upper else bd.Keep.BOTTOM
94
+ return body.split(bd.Plane.XY.offset(plane_z), keep=keep)
95
+
96
+
97
+ def assembly(**parts):
98
+ for label, part in parts.items():
99
+ part.label = label
100
+ return bd.Compound(children=list(parts.values()))
101
+
102
+
103
+ def checked(body, *, solids=1, material=(), void=()):
104
+ occurrences = list(body.solids())
105
+ assert body.is_valid and len(occurrences) == solids, "Invalid geometry or unexpected solid count"
106
+ for point in material:
107
+ assert any(part.is_inside(point) for part in occurrences), f"Expected material at {point}"
108
+ for point in void:
109
+ assert not any(part.is_inside(point) for part in occurrences), f"Expected void at {point}"
110
+ return body