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
@@ -0,0 +1,107 @@
1
+ """Compile a workflow-authored plan to a normal editable text-to-CAD source."""
2
+
3
+ import json
4
+ from itertools import product
5
+ from pathlib import Path
6
+ import shutil
7
+ import sys
8
+
9
+ from plan import compile_source
10
+
11
+
12
+ def fused_plan(plan):
13
+ stocks = []
14
+ supplied = plan["stocks"]
15
+ if isinstance(supplied, dict):
16
+ supplied = list(supplied.values())
17
+ for stock in supplied:
18
+ if plan.get("corner_default") and stock["op"] == "rounded_prism":
19
+ radius = round(min(stock["width"], stock["depth"]) / 10, 3)
20
+ print(f"Default vertical corner radius: {radius:g} mm.")
21
+ stocks.append({**stock, "radius": radius})
22
+ elif stock["op"] == "symmetric_prisms_x":
23
+ half = stock["thickness"] / 2
24
+ stocks.extend({"op": "prism_x", "yz_points": stock["yz_points"],
25
+ "x0": center - half, "x1": center + half}
26
+ for center in stock["x_centers"])
27
+ else:
28
+ stocks.append(stock)
29
+ steps = [{"name": f"stock_{index}", **stock} for index, stock in enumerate(stocks)]
30
+ last = steps[0]["name"]
31
+ if len(steps) > 1:
32
+ steps.append({"name": "joined", "op": "fuse", "body": last,
33
+ "items": [step["name"] for step in steps[1:]]})
34
+ last = "joined"
35
+ cuts = plan["cuts"]
36
+ probes = list(plan.get("void", []))
37
+ if plan.get("centered_bore"):
38
+ if len(stocks) != 1 or stocks[0]["op"] not in ("stock", "rounded_prism", "block"):
39
+ raise ValueError("A centered through-hole needs one block or rounded stock.")
40
+ stock = stocks[0]
41
+ x = (stock["x0"] + stock["x1"]) / 2 if stock["op"] == "block" else 0
42
+ y = (stock["y0"] + stock["y1"]) / 2 if stock["op"] == "block" else 0
43
+ cuts = [{**cut, "x_centers": [x], "y_centers": [y]} for cut in cuts]
44
+ if "clearance" in plan:
45
+ diameter = plan["clearance"]
46
+ cuts = [{**cut, "diameter": diameter} for cut in cuts]
47
+ print(f"Centered through-hole diameter: {diameter:g} mm including bolt clearance.")
48
+ stock_roles = plan["stocks"] if isinstance(plan["stocks"], dict) else {}
49
+ base = stock_roles.get("base") or stock_roles.get("foot")
50
+ if not base and len(stocks) == 1 and stocks[0]["op"] in ("stock", "block", "rounded_prism"):
51
+ base = stocks[0]
52
+ upright = stock_roles.get("upright")
53
+ if base:
54
+ if base["op"] == "stock":
55
+ base_middle = base.get("bottom", 0) + base["height"] / 2
56
+ else:
57
+ base_middle = (base["z0"] + base["z1"]) / 2
58
+ else:
59
+ base_middle = None
60
+ if isinstance(cuts, dict):
61
+ axial = cuts.get("axial_bore")
62
+ side = cuts.get("positive_x_port")
63
+ if axial and side and "stop" not in side:
64
+ cuts = {
65
+ **cuts,
66
+ "positive_x_port": {**side, "stop": axial["x"]},
67
+ }
68
+ cuts = list(cuts.values())
69
+ for index, cut in enumerate(cuts):
70
+ name = f"cut_{index}"
71
+ if cut["op"] == "rounded_prism":
72
+ tool = f"tool_{index}"
73
+ steps.append({"name": tool, **cut})
74
+ steps.append({"name": name, "op": "cut", "body": last, "items": [tool]})
75
+ else:
76
+ steps.append({"name": name, "body": last, **cut})
77
+ if cut["op"] in ("drill_pattern_z", "cut_slots_y") and base_middle is not None:
78
+ probes.extend([x, y, base_middle] for x, y in product(cut["x_centers"], cut["y_centers"]))
79
+ if cut["op"] == "drill_pattern_y" and upright:
80
+ middle_y = (upright["y0"] + upright["y1"]) / 2
81
+ probes.extend([x, middle_y, z] for x, z in product(cut["x_centers"], cut["z_centers"]))
82
+ last = name
83
+ return {**plan, "steps": steps, "result": last, "void": [list(point) for point in dict.fromkeys(map(tuple, probes))]}
84
+
85
+
86
+ def main():
87
+ root = Path.cwd()
88
+ path = root / "geometry-plan.json"
89
+ plan = json.loads(path.read_text(encoding="utf-8"))
90
+ if "stocks" in plan:
91
+ plan = fused_plan(plan)
92
+ number_of_solids = plan.get("solids", 1)
93
+ if type(number_of_solids) is not int or number_of_solids < 1:
94
+ raise ValueError("solids must be a positive whole number")
95
+ code = compile_source(plan, number_of_solids)
96
+ target = root / "src/model.py"
97
+ target.parent.mkdir(exist_ok=True)
98
+ shutil.copyfile(Path(__file__).with_name("cad_primitives.py"), target.with_name("cad_primitives.py"))
99
+ target.write_text(code, encoding="utf-8")
100
+ print(f"Saved src/model.py with {len(plan['steps'])} features and {number_of_solids} expected solids.")
101
+
102
+
103
+ if __name__ == "__main__":
104
+ try:
105
+ main()
106
+ except (OSError, ValueError) as error:
107
+ sys.exit(str(error))
@@ -0,0 +1,148 @@
1
+ """Translate a model-authored CAD operation plan into editable build123d source."""
2
+
3
+ import json
4
+ import keyword
5
+ import math
6
+ import re
7
+
8
+
9
+ OPERATIONS = {
10
+ "stock": ("width depth height", "bottom x y"),
11
+ "block": ("x0 x1 y0 y1 z0 z1", ""),
12
+ "cylinder_z": ("diameter z0 z1", "x y"),
13
+ "cylinder_y": ("diameter y0 y1", "x z"),
14
+ "cylinder_x": ("diameter x0 x1", "y z"),
15
+ "round_all": ("body radius", ""),
16
+ "round_vertical": ("body radius", ""),
17
+ "drill_through_z": ("body diameter", "x y"),
18
+ "drill_through_y": ("body diameter", "x z"),
19
+ "drill_through_x": ("body diameter", "y z"),
20
+ "drill_pattern_z": ("body diameter x_centers y_centers", ""),
21
+ "counterbore_z": ("body diameter floor", "x y"),
22
+ "drill_from_positive_x": ("body diameter stop y z", ""),
23
+ "drill_pattern_y": ("body diameter x_centers z_centers", ""),
24
+ "cut_slots_y": ("body overall_length width x_centers y_centers z0 z1", ""),
25
+ "rounded_prism": ("width depth radius z0 z1", ""),
26
+ "slot_y": ("overall_length width x y z0 z1", ""),
27
+ "prism_x": ("yz_points x0 x1", ""),
28
+ "half_z": ("body plane_z upper", ""),
29
+ "cut": ("body items", ""),
30
+ "fuse": ("body items", ""),
31
+ "assembly": ("parts", ""),
32
+ "translate": ("body dx dy dz", ""),
33
+ }
34
+ def identifier(name):
35
+ return isinstance(name, str) and re.fullmatch(r"[a-z][a-z0-9_]*", name) and not keyword.iskeyword(name)
36
+
37
+
38
+ def number(value):
39
+ return type(value) in (float, int) and math.isfinite(value)
40
+
41
+
42
+ def expression(value, known):
43
+ if isinstance(value, str) and value in known:
44
+ return value
45
+ if value is True or value is False or number(value):
46
+ return repr(value)
47
+ if isinstance(value, list):
48
+ return "[" + ", ".join(expression(item, known) for item in value) + "]"
49
+ raise ValueError(f"Unknown reference or invalid argument {value!r}.")
50
+
51
+
52
+ def points(value):
53
+ if not isinstance(value, list) or not all(
54
+ isinstance(point, list) and len(point) == 3 and all(number(coordinate) for coordinate in point)
55
+ for point in value
56
+ ):
57
+ raise ValueError("Check points must be lists of three numbers.")
58
+ return [tuple(point) for point in value]
59
+
60
+
61
+ def references(value, known):
62
+ if isinstance(value, str):
63
+ return {value} if value in known else set()
64
+ if isinstance(value, dict):
65
+ value = list(value.values())
66
+ return set().union(*(references(item, known) for item in value)) if isinstance(value, list) else set()
67
+
68
+
69
+ def read_plan(answer):
70
+ start = answer.find("{")
71
+ if start < 0:
72
+ raise ValueError("Pi did not return a JSON plan.")
73
+ return json.JSONDecoder().raw_decode(answer[start:])[0]
74
+
75
+
76
+ def compile_source(plan, expected_solids):
77
+ if not isinstance(plan, dict) or not isinstance(plan.get("steps"), list):
78
+ raise ValueError("Pi's plan must contain a steps array.")
79
+ known = set()
80
+ dependencies = {}
81
+ lines = ["import build123d as bd", "from cad import model",
82
+ "import cad_primitives as shapes", ""]
83
+ parameter = plan.get("parameter")
84
+ if parameter is not None:
85
+ if not (isinstance(parameter, dict) and identifier(parameter.get("name")) and number(parameter.get("default"))):
86
+ raise ValueError("The parameter needs a Python name and numeric default.")
87
+ name = parameter["name"]
88
+ known.add(name)
89
+ lines += [f"{name} = model.param({name!r}, {parameter['default']!r}, unit='mm')", ""]
90
+ lines += ["", "def geometry():"]
91
+ for step in plan["steps"]:
92
+ if not isinstance(step, dict):
93
+ raise ValueError("Each step needs an object with a name, op and named arguments.")
94
+ name, operation = step.get("name"), step.get("op")
95
+ if not identifier(name) or name in known or name in ("model", "bd", "shapes"):
96
+ raise ValueError(f"Invalid or duplicate step name {name!r}.")
97
+ if not isinstance(operation, str) or operation not in OPERATIONS:
98
+ raise ValueError(f"Unknown operation {operation!r}.")
99
+ mandatory, optional = (set(names.split()) for names in OPERATIONS[operation])
100
+ arguments = {key: value for key, value in step.items() if key not in ("name", "op")}
101
+ missing, extra = mandatory - arguments.keys(), arguments.keys() - (mandatory | optional)
102
+ if missing or extra:
103
+ raise ValueError(f"{operation} is missing {sorted(missing)} and has unknown fields {sorted(extra)}.")
104
+ if operation == "assembly":
105
+ labels = arguments["parts"]
106
+ if not isinstance(labels, dict) or not labels or not all(
107
+ isinstance(label, str) and label.strip() for label in labels
108
+ ):
109
+ raise ValueError("Assembly takes a nonempty object mapping part labels to step names.")
110
+ entries = ", ".join(f"{label!r}: {expression(reference, known)}"
111
+ for label, reference in labels.items())
112
+ code = "shapes.assembly(**{" + entries + "})"
113
+ elif operation in ("cut", "fuse"):
114
+ body = expression(arguments["body"], known)
115
+ items = arguments["items"]
116
+ if not isinstance(items, list) or not items:
117
+ raise ValueError("cut and fuse use a nonempty items array of step names.")
118
+ cutters = ", ".join(expression(item, known) for item in items)
119
+ code = f"{body}.{operation}({cutters})"
120
+ elif operation == "translate":
121
+ body = expression(arguments["body"], known)
122
+ shift = ", ".join(expression(arguments[axis], known) for axis in ("dx", "dy", "dz"))
123
+ code = f"bd.Pos({shift}) * {body}"
124
+ else:
125
+ args = [f"{key}={expression(value, known)}" for key, value in arguments.items()]
126
+ code = f"shapes.{operation}({', '.join(args)})"
127
+ lines.append(f" {name} = {code}")
128
+ dependencies[name] = references(arguments, known)
129
+ known.add(name)
130
+
131
+ result = expression(plan.get("result"), known)
132
+ if result not in dependencies:
133
+ raise ValueError("The result must be the name of a geometry step.")
134
+ used = {result}
135
+ for name in reversed(dependencies):
136
+ if name in used:
137
+ used.update(dependencies[name])
138
+ unused = [name for name in dependencies if name not in used]
139
+ if unused:
140
+ raise ValueError("Connect these unused steps to the final result: " + ", ".join(unused))
141
+ void = points(plan.get("void", []))
142
+ material = points(plan.get("material", []))
143
+ if not (void or material):
144
+ raise ValueError("Pi's plan omitted a geometry probe.")
145
+ lines += [f" return shapes.checked({result}, solids={expected_solids}, material={material!r}, void={void!r})",
146
+ "", "", "@model", "def part():", " return geometry()", "", "",
147
+ 'if __name__ == "__main__":', " part()", ""]
148
+ return "\n".join(lines)
Binary file