diff --git a/design-docs/lh20-r04-photo-refinement.md b/design-docs/lh20-r04-photo-refinement.md new file mode 100644 index 00000000..e40779b9 --- /dev/null +++ b/design-docs/lh20-r04-photo-refinement.md @@ -0,0 +1,34 @@ +# LH20 R0.4:按用户实物照片细化完整五指 + +2026-11-17,用户在要求把最新版放回 `8780/hand_launcher/#/chatgpt` 入口后,提供五张实物近照并要求对比优化。用户特意说明小拇指已拆下,模型应该完整。 + +## 决定与理由 + +在保留 R0.3 尺寸基准和 20 轴的基础上,新建 R0.4:指节改为圆弧壳体及独立弧面盖,使用阶梯端盖与三点紧固几何、包覆式黑色指腹、错层叉架和倾斜拇指安装框架。保持五条四轴链,并把完整小指纳入检查。用户照片比官网远景更明确地展示了壳体分缝、叉架和指腹形状,因此这些成为本轮造型依据。 + +照片无标尺,不能据此推导精确尺寸、内部驱动、材料牌号或承载能力。橙色柔性电路只做分段走线占位,未声称连续导通、柔性变形或弯折寿命已验证。旧版传动不自动成为新版已适配结构。 + +拒绝把实物缺指状态复制到设计中、只换材质颜色、复制官方 STEP 冒充本轮设计,以及在未运行检查时沿用旧版报告。使用实际 BREP 视图对比,不用生成图片代替模型。 + +## 检查驱动的修订 + +初版完整五指展开姿态通过检查,但单指 `(0,8,10,6)` 度轻屈检查发现 link0/link1 约 0.256 mm³ 相交。把近端叉耳收窄并嵌套在前一节外叉架内,同时匹配更窄的关节外壳。继续测量发现剩余相交位于中心 x=±3.311 mm、z=7.575–7.857 mm:新指节半厚超过原关节开口半径,留下了顶部薄唇。因此将开口半径从 7.6 mm 改为 8.6 mm,而不是只修侧面。保持 0.01 mm³ 阈值,保存失败报告,不以改变判定掩盖相交。 + +拇指安装框架倾斜后,掌背检修口与基座避让将掌壳边框切断。收小检修口并保留连续边框,重新生成实体。所有修改位于源几何,不修补导出网格。 + +## 交付边界 + +新源码在 `examples/lh20_hand_r04`;验证通过后,用户原 `8780` 菜单和 `8764` 菜单均更新到 R0.4。Claude 模型和旧 Codex 工作区保留。STEP 与外观 URDF 从同一检查过的原生包导出,五指共 21 link / 20 joint;打包时校验摘要和网格相对引用。 + +检查限定于实际运行的姿态。零件有效性、干涉检查、运动学布局不等于制造、公差、强度、驱动集成、触觉或实物抓取验证。 + +最终展开原生包摘要为 `d310b1cf4fda043512f87fa933d428fb73b45e8e38fb3cf510afc237b945c570`,245 个实体通过几何、约束及精确干涉检查;轻屈包另行检查通过。STEP 回读保留 245 个实体,体积相对误差约 4.03×10⁻⁷;URDF 为完整五指 21 link、20 joint、84 个网格。 + +下载目录中的新交付文件夹和 ZIP 已校验 102 个文件;打包时还比较了独立单指和整手中食指的逐件体积。浏览器在用户原 `8780/hand_launcher/#/chatgpt` 地址显示 R0.4、245 个零件,指向独立编辑器 8795;8764 菜单也指向同一版本。 + +标准 SDK STEP 输出的每根手指约束 JSON 超过 22 kB,触发本机 OCCT 字符串扫描缓冲溢出。局部 `exchange_step.py` 采用同一原生写入器已有的 `metadata_properties=False`,把完整记录写入绑定原生包和 STEP 摘要的 JSON 文件。几何、层级、名称、颜色不变,回读门槛不变,没有修改共享 SDK 或补丁处理 STEP 文本。原生包保留完整语义。 + +## 提交划分 + +- `DECISION: Refine the complete five-finger exterior from physical reference photos`:几何、基准解释、检查和交付。 +- `DECISION: Keep both hand menus on the verified photo-refined revision`:把已经验证的结果接入用户正在使用的两个入口。 diff --git a/examples/lh20_hand_r04/.gitignore b/examples/lh20_hand_r04/.gitignore new file mode 100644 index 00000000..5f2b67bd --- /dev/null +++ b/examples/lh20_hand_r04/.gitignore @@ -0,0 +1,4 @@ +out/ +__pycache__/ +__marimo__/ +.sca-editor/ diff --git a/examples/lh20_hand_r04/BRIEF.md b/examples/lh20_hand_r04/BRIEF.md new file mode 100644 index 00000000..ee308857 --- /dev/null +++ b/examples/lh20_hand_r04/BRIEF.md @@ -0,0 +1,27 @@ +Mode: interactive — 沿用用户自主设计授权,按五张实物照片细化完整五指。 + +# LH20 R0.4 — 实物外形对照修订 + +2026-11-17,用户明确说明照片里的小拇指已拆下,目标必须保留完整五指。沿用无腱绳、允许内部电线、精细操作与柔顺抓取的方向。本轮为既有 CAD 外形细化,不把照片当作内部驱动或精确尺寸证据。 + +## 逐区域解释与修改 + +| 实物可见特征 | R0.3 差距 | 本轮修改与验收 | +| --- | --- | --- | +| 图 1、3 圆弧指节壳体、横向分缝 | 平板插片占据主轮廓 | 圆弧截面、真实凹槽、独立弧面盖;正侧视检查 | +| 图 1、3、5 叉形关节和圆形端盖 | 轴端仅为小圆环 | 叉架开口、阶梯端盖、三点紧固几何;单指精确干涉检查 | +| 图 1、4 黑色指腹与银色背甲分件 | 接触片太薄、颜色层次弱 | 包覆式黑色指腹、金属背甲及分缝;五个指尖均保留 | +| 图 2、4、5 拇指根部空间转接 | 根部几乎共面 | 拇指安装框架增加朝掌方向角度;按同一坐标切掌壳避让 | +| 图 1、3、5 橙色柔性电路 | 走线位置缺失 | 浅槽和分段电路外观占位;不声称弯折寿命或连续动态走线已完成 | +| 图 2、4 黑色掌壳、分层腕接口 | 材料对比弱 | 保留收腰和检修分件,调整深色材质与腕圈层次 | +| 照片只有三根长指+拇指 | 小指已拆下 | CAD、URDF 均保留五条四轴链,不复制缺指状态 | + +## 基准与验收边界 + +- 单位 mm / degree,掌面 +Z、手指 +Y。掌宽、指长沿用 R0.3 设计值;没有尺度标尺,不声称等尺寸复刻。 +- 保留 20 轴。拇指基座增加绕局部 Y 轴 24°、X 轴 8°的造型角度,是设计输入而非实测值。 +- 紧固件是候选尺寸几何;未验证螺纹、预紧和强度。旧版传动仍未适配。 +- 单指先建模、检查、看图,再扩展到整手。OCP 检查有效性、正体积、装配约束及精确干涉,阈值仍为 0.01 mm³,不掩盖失败。 +- 展开与一组轻屈姿态分别检查,不等于全行程验证。真实 BREP 产生掌面、背面、斜视和单指图。 +- STEP 回读、URDF 引用检查;完整五指 21 link / 20 joint 是交付约束。原生包摘要绑定检查和预览。 +- 新源码 `examples/lh20_hand_r04`;完成后更新用户原入口 `http://127.0.0.1:8780/hand_launcher/#/chatgpt`。 diff --git a/examples/lh20_hand_r04/README.md b/examples/lh20_hand_r04/README.md new file mode 100644 index 00000000..f328baaf --- /dev/null +++ b/examples/lh20_hand_r04/README.md @@ -0,0 +1,51 @@ +# LH20 R0.4 — 实物照片对照优化 + +依据 2026-11-17 用户提供的五张实物照片细化 R0.3。保留完整五指(包括照片中被拆掉的小拇指)、20 轴和无腱绳设计方向。 + +本版把平板指节改为圆弧壳体与独立弧面盖,重做关节叉架开口、阶梯端盖和三点紧固细节,扩大黑色指腹包覆,增加分段柔性电路走线占位,并让拇指基座有空间朝向。尺寸沿用现有设计值,不能从无标尺照片声称实测还原。 + +**这是外形与关节布局模型。内部电机、减速器、轴承和连续柔性电路未完成适配。橙色件表示走线占用位置,不是已验证的柔性电路设计。** + +## 查看 + +用户原入口:`http://127.0.0.1:8780/hand_launcher/#/chatgpt`。 + +另一个菜单:`http://127.0.0.1:8764/hands/codex`;独立编辑器:`http://127.0.0.1:8795/`。R0.3 保留在原目录及端口 8785。 + +## 重建与检查 + +```sh +.venv/bin/python examples/lh20_hand_r04/build.py finger +.venv/bin/python examples/lh20_hand_r04/verify.py --name finger --collisions +.venv/bin/python examples/lh20_hand_r04/render.py --name finger +.venv/bin/python examples/lh20_hand_r04/build.py hand +.venv/bin/python examples/lh20_hand_r04/verify.py --collisions +.venv/bin/python examples/lh20_hand_r04/render.py +.venv/bin/python examples/lh20_hand_r04/compare.py +.venv/bin/python examples/lh20_hand_r04/build.py hand --pose relaxed +.venv/bin/python examples/lh20_hand_r04/verify.py --name hand_relaxed --collisions +.venv/bin/python examples/lh20_hand_r04/export.py +.venv/bin/python examples/lh20_hand_r04/package.py ~/Downloads/LH20_Codex_R04_实物对照优化_2026-11-17 +``` + +`out/hand.scadpkg` 为完整五指原生包。`*_build.json` 记录包摘要与具体角度;`*_check.json` 检查实体、约束和精确干涉(0.01 mm³ 阈值);检查失败历史会保留。轻屈姿态为四根长指各 `(0,8,10,6)` 度,拇指 `(0,4,8,8)` 度。通过这两组检查也不意味着全行程无干涉。 + +`hand_overview.png` 是真实 CAD 掌面、背面和斜视图,另有 `hand_side.png` 与 `finger_*` 局部视图。预览记录绑定原生包摘要。 + +`LH20_R04_exterior.step` 通过回读数量和体积检查;`LH20_R04_exterior.urdf` 与 `meshes/` 包含完整五指、21 link、20 个关节。URDF 只用于外观及运动学查看,effort/velocity 为零,无惯量、碰撞模型或驱动能力声明。网格和关节坐标为米,STEP 为毫米。 + +该版每根手指的 AP242 描述性 JSON 超过 22 kB,触发本机 OCCT STEP 读取器的字符串扫描缓冲限制。`exchange_step.py` 使用原生写入器已有的 `metadata_properties=False` 选项,保持实体、名称、颜色、放置及装配层级,将完整描述记录写入 `LH20_R04_exterior_metadata.json` 并绑定包和 STEP 摘要。未修改 STEP 文本或简化几何;仍须通过原有回读检查。 + +打包脚本校验来源摘要、相对网格引用和 ZIP 文件摘要;不会覆盖已有交付目录。实际检查摘要见 `out/`,不沿用其他版本的结果。 + +2026-11-17 本轮结果:245 个实体的展开和上述轻屈姿态检查均通过;检查确认五指各四轴。STEP 回读保留 245 个实体,体积相对误差约 4.03×10⁻⁷;URDF 为 21 link、20 joint、84 个网格。单指、整手的同名分件还在打包时比较体积,防止子装配缓存混入旧形状。 + +## 源码与边界 + +- `parts/finger_surfaces.py`:圆弧壳体、可拆盖、叉架、黑色指腹和走线槽。 +- `parts/joint_details.py`:阶梯端盖和候选紧固件。 +- `parts/links.py`:组合独立分件及关节连接点。 +- `parts/palm.py`:掌壳、检修盖和倾斜拇指安装框架。 +- `finger.py`、`hand.py`:关节约束与完整五指装配。 + +制造公差、承力、轴向固定、真实电机与传动空间、连续电气路线、全运动包络、触觉器件和实物抓取性能仍需后续工程验证。详见 `BRIEF.md` 中逐张照片对应的修改与假设。 diff --git a/examples/lh20_hand_r04/assembly_support.py b/examples/lh20_hand_r04/assembly_support.py new file mode 100644 index 00000000..c175b84d --- /dev/null +++ b/examples/lh20_hand_r04/assembly_support.py @@ -0,0 +1,19 @@ +"""Assembly frames and physical joint datums shared by all notebooks.""" + +import numpy as np +import simplecadapi as scad +from parts.common import transform + + +def axis_matrix(axis): + xy = { + "z": ((1, 0, 0), (0, 1, 0)), + "x": ((0, 1, 0), (0, 0, 1)), + "y": ((0, 0, 1), (1, 0, 0)), + } + x, y = map(np.array, xy[axis]) + return transform(rotation=np.column_stack([x, y, np.cross(x, y)])) + + +def ref(component, connector="origin"): + return scad.ConnectorRef(component_id=component, connector_id=connector) diff --git a/examples/lh20_hand_r04/build.py b/examples/lh20_hand_r04/build.py new file mode 100644 index 00000000..4e989776 --- /dev/null +++ b/examples/lh20_hand_r04/build.py @@ -0,0 +1,45 @@ +"""Capture exterior notebooks; the source is the editable parametric definition.""" + +import argparse, time, hashlib, json +import simplecadapi as scad +from simplecadapi.runtime import run_notebook +from parameters import HERE, OUT, FINGERS + + +def main(target, pose=None): + OUT.mkdir(exist_ok=True) + start = time.time() + overrides = None + if pose: + if target == "hand": + overrides = {f.name.upper(): (0.0, 8.0, 10.0, 6.0) for f in FINGERS} + overrides["THUMB"] = (0.0, 4.0, 8.0, 8.0) + else: + overrides = {"FINGER": "index", "ANGLES": (0.0, 8.0, 10.0, 6.0)} + run = run_notebook(HERE / f"{target}.py", cache=False, overrides=overrides) + path = OUT / f"{target}{'_relaxed' if pose else ''}.scadpkg" + scad.capture(run.definition, path, include_scene=False) + poses = ( + (overrides or {f.name.upper(): (0, 0, 0, 0) for f in FINGERS}) + if target == "hand" + else {"INDEX": overrides["ANGLES"] if overrides else (0, 0, 0, 0)} + ) + path.with_name(path.stem + "_build.json").write_text( + json.dumps( + { + "package_sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + "pose_degrees": poses, + "scope": "Photo-informed exterior; dimensions are design inputs, not measurements of the reference hand", + }, + indent=2, + ) + ) + print(path, path.stat().st_size, round(time.time() - start, 2), flush=True) + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("target", choices=("hand", "finger"), default="hand", nargs="?") + ap.add_argument("--pose", choices=("relaxed",)) + args = ap.parse_args() + main(args.target, args.pose) diff --git a/examples/lh20_hand_r04/compare.py b/examples/lh20_hand_r04/compare.py new file mode 100644 index 00000000..f1aa045b --- /dev/null +++ b/examples/lh20_hand_r04/compare.py @@ -0,0 +1,38 @@ +"""Compose a labelled comparison of two actual CAD renders, never concept imagery.""" + +import hashlib +import json +from PIL import Image, ImageDraw, ImageFont +from parameters import HERE, OUT + + +def main(): + previous = HERE.parent / "lh20_hand_r03" / "out" + image = Image.new("RGB", (2000, 1490), "#edf0f2") + draw = ImageDraw.Draw(image) + title = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 36) + label = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 23) + for i, (source, heading) in enumerate( + ((previous, "R0.3 / PREVIOUS"), (OUT, "R0.4 / PHOTO-REFINED")) + ): + record = json.loads((source / "hand_overview.json").read_text()) + assert ( + hashlib.sha256((source / "hand.scadpkg").read_bytes()).hexdigest() + == record["package_sha256"] + ) + shot = Image.open(source / "hand_front.png").convert("RGB") + assert shot.size == (1000, 1300) + image.paste(shot, (i * 1000, 105)) + draw.text((i * 1000 + 55, 38), heading, font=title, fill="#23343c") + draw.text( + (55, 1430), + "Actual CAD | Complete five fingers | Actuator integration pending", + font=label, + fill="#46565e", + ) + image.save(OUT / "r03_r04_comparison.png") + print(OUT / "r03_r04_comparison.png") + + +if __name__ == "__main__": + main() diff --git a/examples/lh20_hand_r04/exchange_step.py b/examples/lh20_hand_r04/exchange_step.py new file mode 100644 index 00000000..adbce269 --- /dev/null +++ b/examples/lh20_hand_r04/exchange_step.py @@ -0,0 +1,46 @@ +"""AP242 adapter: avoid the OCCT scanner limit on long descriptive JSON tokens. + +The native writer already supports metadata_properties=False. Keep all BREP, +assembly instances, names, placements and materials; preserve the complete +descriptive records in a package-bound JSON sidecar instead of a >22 kB token. +No geometry is altered and no written STEP text is patched. +""" + +import hashlib +import json +from simplecadapi import _cpp as native +from simplecadapi.artifacts import materialize_definition +from simplecadapi.exporter.step import _native_definitions +from simplecadapi.translator.package_units import read_product_package_translation_units + + +def export_compatible_step(package_path, output_path): + package, units = read_product_package_translation_units(package_path) + root = materialize_definition(package.root_definition) + definitions = _native_definitions(root, units) + report = native.export_step_assembly( + definitions=definitions, + root_id=root.assembly_id, + path=output_path, + schema="AP242DIS", + metadata_properties=False, + ) + records = [] + for definition in definitions: + records.append(definition["metadata"]) + records.extend(c["metadata"] for c in definition.get("components", [])) + sidecar = output_path.with_name(output_path.stem + "_metadata.json") + sidecar.write_text( + json.dumps( + { + "package_sha256": hashlib.sha256(package_path.read_bytes()).hexdigest(), + "step_sha256": hashlib.sha256(output_path.read_bytes()).hexdigest(), + "reason": "Long AP242 descriptive JSON strings exceed this OCCT reader's scanner buffer; complete records are preserved here and in the native package.", + "records": records, + }, + ensure_ascii=False, + indent=2, + ), + encoding="utf-8", + ) + return report diff --git a/examples/lh20_hand_r04/export.py b/examples/lh20_hand_r04/export.py new file mode 100644 index 00000000..1c100bdf --- /dev/null +++ b/examples/lh20_hand_r04/export.py @@ -0,0 +1,163 @@ +"""STEP and visual URDF for the checked exterior; no invented drive properties.""" + +import hashlib, json, re +import xml.etree.ElementTree as ET +import numpy as np +from scipy.spatial.transform import Rotation +from exchange_step import export_compatible_step +from simplecadapi.exporter._surface_mesh import tessellate_solid +from OCP.STEPControl import STEPControl_Reader +from OCP.IFSelect import IFSelect_RetDone +from OCP.TopExp import TopExp_Explorer +from OCP.TopAbs import TopAbs_SOLID +from parameters import OUT, FINGERS, AXES, MATERIALS +from model_io import read_model, flatten +from verify import volume + + +def seq(values): + return " ".join(f"{v:.10g}" for v in values) + + +def sub(parent, tag, **attrs): + return ET.SubElement(parent, tag, {k: str(v) for k, v in attrs.items()}) + + +def main(): + package = OUT / "hand.scadpkg" + digest = hashlib.sha256(package.read_bytes()).hexdigest() + check = json.loads((OUT / "hand_check.json").read_text()) + assert ( + check["package_sha256"] == digest + and check["geometry_pass"] + and check["constraints_pass"] + and check["clearance_pass"] + ) + leaves = flatten(read_model()) + step = OUT / "LH20_R04_exterior.step" + report = export_compatible_step(package, step) + reader = STEPControl_Reader() + assert reader.ReadFile(str(step)) == IFSelect_RetDone + reader.TransferRoots() + imported = reader.OneShape() + exp = TopExp_Explorer(imported, TopAbs_SOLID) + count = 0 + while exp.More(): + count += 1 + exp.Next() + source_volume = sum(r["volume_mm3"] for r in check["geometry"]) + error = abs(volume(imported) - source_volume) / source_volume + assert count == len(leaves) and error < 1e-5 + frames = {"palm": np.eye(4)} + for f in FINGERS: + for k in range(4): + frames[f"{f.name}_{k}"] = next( + m for path, p, m in leaves if path == f"/{f.name}/link{k}" + ) + groups = {} + meshdir = OUT / "meshes" + meshdir.mkdir(exist_ok=True) + for path, p, m in leaves: + tokens = path.strip("/").split("/") + owner = "palm" + if tokens[0] in {f.name for f in FINGERS} and tokens[1] != "mount": + owner = f"{tokens[0]}_{re.search(r'\d+', tokens[1]).group()}" + material = p.material.material_id + vertices, triangles = tessellate_solid( + p.body, + linear_deflection=0.12, + angular_deflection_degrees=12, + relative=False, + ) + pose = np.linalg.inv(frames[owner]) @ m + vertices = (np.asarray(vertices) @ pose[:3, :3].T + pose[:3, 3]) / 1000 + groups.setdefault((owner, material), []).append( + (vertices, np.asarray(triangles)) + ) + robot = ET.Element("robot", name="LH20_R04_exterior_only") + links = {name: sub(robot, "link", name=name) for name in frames} + for name, (_, color) in MATERIALS.items(): + mat = sub(robot, "material", name=name) + sub(mat, "color", rgba=seq([*color, 1])) + files = [] + for (owner, material), blocks in groups.items(): + filename = f"{owner}_{material}.obj" + lines = [] + offset = 0 + for vertices, triangles in blocks: + lines.extend("v " + seq(v) for v in vertices) + lines.extend( + "f " + " ".join(str(int(i + offset + 1)) for i in row) + for row in triangles + ) + offset += len(vertices) + (meshdir / filename).write_text("\n".join(lines) + "\n") + files.append(filename) + visual = sub(links[owner], "visual") + geometry = sub(visual, "geometry") + sub(geometry, "mesh", filename="meshes/" + filename) + sub(visual, "material", name=material) + for f in FINGERS: + for k in range(4): + parent = "palm" if k == 0 else f"{f.name}_{k - 1}" + child = f"{f.name}_{k}" + pose = np.linalg.inv(frames[parent]) @ frames[child] + joint = sub(robot, "joint", name=child + "_axis", type="revolute") + sub(joint, "parent", link=parent) + sub(joint, "child", link=child) + sub( + joint, + "origin", + xyz=seq(pose[:3, 3] / 1000), + rpy=seq(Rotation.from_matrix(pose[:3, :3]).as_euler("xyz")), + ) + sub(joint, "axis", xyz="0 0 1" if AXES[k] == "z" else "1 0 0") + # Display ranges are proposed, not qualified motion limits. Zero + # effort/velocity intentionally makes no actuator performance claim. + lo, hi = (-20, 20) if k == 0 else (0, 90) + sub( + joint, + "limit", + lower=np.deg2rad(lo), + upper=np.deg2rad(hi), + effort=0, + velocity=0, + ) + robot.insert( + 0, + ET.Comment( + "Exterior visualization only. No inertia, collision, transmission or motor performance qualification." + ), + ) + ET.indent(robot, space=" ") + urdf = OUT / "LH20_R04_exterior.urdf" + ET.ElementTree(robot).write(urdf, encoding="utf-8", xml_declaration=True) + parsed = ET.parse(urdf).getroot() + assert len(parsed.findall("joint")) == 20 + assert {e.attrib["name"] for e in parsed.findall("link")} == {"palm"} | { + f"{f.name}_{k}" for f in FINGERS for k in range(4) + } + assert {e.attrib["name"] for e in parsed.findall("joint")} == { + f"{f.name}_{k}_axis" for f in FINGERS for k in range(4) + } + assert all( + (OUT / e.attrib["filename"]).is_file() for e in parsed.findall(".//mesh") + ) + result = dict( + package_sha256=digest, + step_occurrences=count, + step_relative_volume_error=error, + urdf_links=len(links), + urdf_joints=20, + mesh_files=len(files), + scope="Exterior STEP and visualization URDF only; dynamics and actuator integration pending", + step_descriptive_metadata="LH20_R04_exterior_metadata.json (full records; STEP keeps geometry, hierarchy and materials)", + step_sha256=hashlib.sha256(step.read_bytes()).hexdigest(), + urdf_sha256=hashlib.sha256(urdf.read_bytes()).hexdigest(), + ) + (OUT / "exchange_check.json").write_text(json.dumps(result, indent=2)) + print(json.dumps(result, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/examples/lh20_hand_r04/finger.py b/examples/lh20_hand_r04/finger.py new file mode 100644 index 00000000..69ef32e1 --- /dev/null +++ b/examples/lh20_hand_r04/finger.py @@ -0,0 +1,93 @@ +# /// script +# dependencies = ["simplecadapi"] +# [tool.simplecadapi] +# id = "lh20_r04_finger" +# kind = "assembly" +# revision = "0.4.0" +# /// +"""Four-axis exterior study; internal transmission is deliberately not implied.""" + +import marimo + +app = marimo.App() +with app.setup: + import simplecadapi as scad + from parts.links import link_parts, base_part + from parts import finger_surfaces, joint_details + from parts.common import frame + from assembly_support import ref + + +@app.cell +def _(): + # ---- params: finger-pose ---- + FINGER = "index" + ANGLES = (0.0, 0.0, 0.0, 0.0) + return FINGER, ANGLES + + +@app.cell +def _(FINGER): + # ---- feature: finger-exterior-definitions (build) ---- + # Explicit module dependencies keep nested cache entries tied to fork geometry. + _surface_schema = (finger_surfaces.dims, joint_details.cap_frame) + links = [link_parts(FINGER, k) for k in range(4)] + mount = base_part(FINGER) + return links, mount + + +@app.cell +def _(links, mount, ANGLES): + # ---- feature: articulated-exterior (build) ---- + _a = scad.make_assembly_rassembly( + assembly_id=scad.notebook_id(), name="LH20 R0.4 外形设计 / 四轴手指" + ) + _a = scad.add_component_rassembly( + assembly=_a, item=mount.part, component_id="mount", placement=frame() + ) + _a = scad.ground_component_rassembly(assembly=_a, component_id="mount") + for _k, _parts in enumerate(links): + _cid = f"link{_k}" + _a = scad.add_component_rassembly( + assembly=_a, item=_parts["rail"].part, component_id=_cid, placement=frame() + ) + _parent = "mount" if _k == 0 else f"link{_k - 1}" + _connector = "hinge" if _k == 0 else "next" + _a = scad.add_revolute_constraint_rassembly( + assembly=_a, + constraint_id=f"axis{_k}", + connector_a=ref(_parent, _connector), + connector_b=ref(_cid, "hinge"), + drive_angle_degrees=float(ANGLES[_k]), + ) + for _key, _part in _parts.items(): + if _key == "rail": + continue + _detail = f"detail{_k}_{_key}" + _a = scad.add_component_rassembly( + assembly=_a, item=_part.part, component_id=_detail, placement=frame() + ) + _a = scad.add_fixed_constraint_rassembly( + assembly=_a, + constraint_id=f"fix_{_detail}", + connector_a=ref(_cid, "origin"), + connector_b=ref(_detail, "origin"), + ) + exterior = scad.set_public_connector_rassembly( + assembly=_a, + public_connector_id="mount", + source_component_id="mount", + source_connector_id="origin", + ) + return (exterior,) + + +@app.cell +def _(exterior): + # ---- feature: solve-finger-exterior (modify) ---- + result = scad.solve_assembly_constraints_rassembly(assembly=exterior, strict=True) + return (result,) + + +if __name__ == "__main__": + app.run() diff --git a/examples/lh20_hand_r04/hand.py b/examples/lh20_hand_r04/hand.py new file mode 100644 index 00000000..6887e46f --- /dev/null +++ b/examples/lh20_hand_r04/hand.py @@ -0,0 +1,122 @@ +# /// script +# dependencies = ["simplecadapi"] +# [tool.simplecadapi] +# id = "lh20_r04_exterior" +# kind = "assembly" +# revision = "0.4.0" +# /// +"""LH20 R0.4 exterior redesign. Old actuators have not been fitted to this envelope.""" + +import marimo + +app = marimo.App() +with app.setup: + import simplecadapi as scad + from parts.palm import palm_parts + from parts.common import frame + from assembly_support import ref + + +@app.cell +def _(): + # ---- params: exterior-pose ---- + INDEX = (0.0, 0.0, 0.0, 0.0) + MIDDLE = (0.0, 0.0, 0.0, 0.0) + RING = (0.0, 0.0, 0.0, 0.0) + LITTLE = (0.0, 0.0, 0.0, 0.0) + THUMB = (0.0, 0.0, 0.0, 0.0) + return INDEX, MIDDLE, RING, LITTLE, THUMB + + +@app.cell +def _(): + # ---- feature: palm-definitions (build) ---- + palm = palm_parts() + return (palm,) + + +@app.cell +def _(INDEX): + index = scad.use("finger.py", id="index_exterior", FINGER="index", ANGLES=INDEX) + return (index,) + + +@app.cell +def _(MIDDLE): + middle = scad.use("finger.py", id="middle_exterior", FINGER="middle", ANGLES=MIDDLE) + return (middle,) + + +@app.cell +def _(RING): + ring = scad.use("finger.py", id="ring_exterior", FINGER="ring", ANGLES=RING) + return (ring,) + + +@app.cell +def _(LITTLE): + little = scad.use("finger.py", id="little_exterior", FINGER="little", ANGLES=LITTLE) + return (little,) + + +@app.cell +def _(THUMB): + thumb = scad.use("finger.py", id="thumb_exterior", FINGER="thumb", ANGLES=THUMB) + return (thumb,) + + +@app.cell +def _(palm, index, middle, ring, little, thumb): + # ---- feature: complete-exterior-assembly (build) ---- + _a = scad.make_assembly_rassembly( + assembly_id=scad.notebook_id(), name="LH20 R0.4 / 外形重设计 / 内部待适配" + ) + _a = scad.add_component_rassembly( + assembly=_a, + item=palm["front"].part, + component_id="palm_front", + placement=frame(), + ) + _a = scad.ground_component_rassembly(assembly=_a, component_id="palm_front") + for _key, _part in palm.items(): + if _key == "front": + continue + _cid = "palm_" + _key + _a = scad.add_component_rassembly( + assembly=_a, item=_part.part, component_id=_cid, placement=frame() + ) + _a = scad.add_fixed_constraint_rassembly( + assembly=_a, + constraint_id="fix_" + _cid, + connector_a=ref("palm_front"), + connector_b=ref(_cid), + ) + for _name, _finger in [ + ("index", index), + ("middle", middle), + ("ring", ring), + ("little", little), + ("thumb", thumb), + ]: + _a = scad.add_component_rassembly( + assembly=_a, item=_finger, component_id=_name, placement=frame() + ) + _a = scad.add_fixed_constraint_rassembly( + assembly=_a, + constraint_id="mount_" + _name, + connector_a=ref("palm_front", _name + "_root"), + connector_b=ref(_name, "mount"), + ) + exterior = _a + return (exterior,) + + +@app.cell +def _(exterior): + # ---- feature: solve-exterior (modify) ---- + result = scad.solve_assembly_constraints_rassembly(assembly=exterior, strict=True) + return (result,) + + +if __name__ == "__main__": + app.run() diff --git a/examples/lh20_hand_r04/model_io.py b/examples/lh20_hand_r04/model_io.py new file mode 100644 index 00000000..6324ee2b --- /dev/null +++ b/examples/lh20_hand_r04/model_io.py @@ -0,0 +1,41 @@ +import numpy as np +import simplecadapi as scad +from parameters import OUT + + +def matrix(placement): + m = np.eye(4) + m[:3, 0] = placement.x_axis + m[:3, 1] = placement.y_axis + m[:3, 2] = placement.z_axis + m[:3, 3] = placement.origin + return m + + +def flatten(item, parent=None, path=""): + parent = np.eye(4) if parent is None else parent + if isinstance(item, scad.Part): + return [(path, item, parent)] + result = [] + for cid in item.component_ids(): + c = item.get_component(cid) + result.extend(flatten(c.item, parent @ matrix(c.placement), f"{path}/{cid}")) + return result + + +def read_model(name="hand"): + return scad.materialize_definition( + scad.load_product_package(OUT / f"{name}.scadpkg") + ) + + +def reports(item, path=""): + if isinstance(item, scad.Part): + return [] + r = scad.inspect_assembly_constraints_rconstraintreport(assembly=item) + rows = [ + dict(path=path, solved=bool(r.solved), constraints=len(item.constraint_ids())) + ] + for cid in item.component_ids(): + rows.extend(reports(item.get_component(cid).item, path + "/" + cid)) + return rows diff --git a/examples/lh20_hand_r04/package.py b/examples/lh20_hand_r04/package.py new file mode 100644 index 00000000..72e99f98 --- /dev/null +++ b/examples/lh20_hand_r04/package.py @@ -0,0 +1,174 @@ +"""Package the checked exterior exchange files without replacing an older delivery.""" + +import argparse +import hashlib +import json +from pathlib import Path +import shutil +import xml.etree.ElementTree as ET +import zipfile + +from parameters import OUT + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("destination", type=Path) + args = parser.parse_args() + dest = args.destination.expanduser().resolve() + archive = dest.with_name(dest.name + ".zip") + if dest.exists() or archive.exists(): + raise FileExistsError( + "Use a new destination; existing deliveries are preserved." + ) + check = json.loads((OUT / "hand_check.json").read_text()) + exchange = json.loads((OUT / "exchange_check.json").read_text()) + preview = json.loads((OUT / "hand_overview.json").read_text()) + source_hash = digest(OUT / "hand.scadpkg") + assert source_hash == check["package_sha256"] == exchange["package_sha256"] + assert preview["package_sha256"] == source_hash + assert digest(OUT / "hand_overview.png") == preview["image_sha256"] + assert all( + check[key] for key in ("geometry_pass", "constraints_pass", "clearance_pass") + ) + relaxed = json.loads((OUT / "hand_relaxed_check.json").read_text()) + relaxed_build = json.loads((OUT / "hand_relaxed_build.json").read_text()) + assert ( + digest(OUT / "hand_relaxed.scadpkg") + == relaxed["package_sha256"] + == relaxed_build["package_sha256"] + ) + assert all( + relaxed[key] for key in ("geometry_pass", "constraints_pass", "clearance_pass") + ) + assert set(check["five_finger_structure"]) == { + "index", + "middle", + "ring", + "little", + "thumb", + } + finger_check = json.loads((OUT / "finger_check.json").read_text()) + finger_preview = json.loads((OUT / "finger_overview.json").read_text()) + assert ( + digest(OUT / "finger.scadpkg") + == finger_check["package_sha256"] + == finger_preview["package_sha256"] + ) + assert digest(OUT / "finger_overview.png") == finger_preview["image_sha256"] + assert all( + finger_check[key] + for key in ("geometry_pass", "constraints_pass", "clearance_pass") + ) + hand_index = { + r["path"].removeprefix("/index"): r + for r in check["geometry"] + if r["path"].startswith("/index/") + } + assert set(hand_index) == {r["path"] for r in finger_check["geometry"]} + for row in finger_check["geometry"]: + assert abs(row["volume_mm3"] - hand_index[row["path"]]["volume_mm3"]) < 1e-5, ( + "Nested finger differs from independently checked geometry" + ) + step = "LH20_R04_exterior.step" + urdf = "LH20_R04_exterior.urdf" + assert digest(OUT / step) == exchange["step_sha256"] + assert digest(OUT / urdf) == exchange["urdf_sha256"] + step_metadata = json.loads((OUT / "LH20_R04_exterior_metadata.json").read_text()) + assert step_metadata["package_sha256"] == source_hash + assert step_metadata["step_sha256"] == exchange["step_sha256"] + mesh_refs = { + element.attrib["filename"] + for element in ET.parse(OUT / urdf).findall(".//mesh") + } + for ref in mesh_refs: + assert ref.startswith("meshes/") and ".." not in Path(ref).parts + assert (OUT / ref).is_file() + files = [ + step, + urdf, + "LH20_R04_exterior_metadata.json", + "hand_overview.png", + "hand_front.png", + "hand_back.png", + "hand_profile.png", + "hand_side.png", + "r03_r04_comparison.png", + "finger_overview.png", + "finger_side.png", + "hand_build.json", + "hand_relaxed_build.json", + "hand_relaxed_check.json", + "hand_check.json", + "exchange_check.json", + "hand_overview.json", + *sorted(mesh_refs), + ] + dest.mkdir(parents=True) + for relative in files: + target = dest / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(OUT / relative, target) + assert digest(target) == digest(OUT / relative) + (dest / "先读我.txt").write_text( + "LH20 Codex R0.4 — 外形重设计\n\n" + "本版依据用户实物照片改为圆弧指节、独立外盖、错层叉架、三点紧固端盖和黑色指腹。\n" + "完整五指均保留,包含照片中被拆下的小拇指;照片无标尺,尺寸不是实测还原值。\n" + "hand_overview.png 是实际 CAD 的三视角图。\n" + f"STEP 包含 {exchange['step_occurrences']} 个外形实体;URDF 包含 21 个 link、20 个旋转关节。\n" + "URDF 与 meshes 文件夹须一起移动,网格和关节坐标单位为米。STEP 单位为毫米。\n\n" + "STEP 中保留实体、颜色与装配层级;较长的装配说明保存在 LH20_R04_exterior_metadata.json 中。\n" + "这是外形与关节布局交付。旧版内部驱动尚未适配到新外形;\n" + "橙色分段件只表示柔性电路走线占位,未完成连续电气连接和弯折寿命验证。\n" + "URDF 用于外观和运动学查看,无惯量、碰撞模型或传动定义,\n" + "effort/velocity 为零,不用于动力学或驱动能力验证。\n" + "检查覆盖展开与记录中轻屈姿态的实体、约束和精确干涉,以及 STEP 回读。\n" + "不代表已完成全运动范围、制造、公差或实物抓取验证。\n\n" + "本地查看:http://127.0.0.1:8780/hand_launcher/#/chatgpt\n" + "源码:/Users/jerry/linkhand/SimpleCADAPI/examples/lh20_hand_r04\n", + encoding="utf-8", + ) + hashes = { + p.relative_to(dest).as_posix(): digest(p) + for p in sorted(dest.rglob("*")) + if p.is_file() + } + (dest / "manifest.json").write_text( + json.dumps( + {"source_package_sha256": source_hash, "files": hashes}, + indent=2, + ensure_ascii=False, + ), + encoding="utf-8", + ) + with zipfile.ZipFile(archive, "x", zipfile.ZIP_DEFLATED) as zf: + for path in sorted(dest.rglob("*")): + if path.is_file(): + zf.write(path, dest.name + "/" + path.relative_to(dest).as_posix()) + with zipfile.ZipFile(archive) as zf: + assert zf.testzip() is None + for relative, expected in hashes.items(): + assert ( + hashlib.sha256(zf.read(dest.name + "/" + relative)).hexdigest() + == expected + ) + print( + json.dumps( + { + "folder": str(dest), + "zip": str(archive), + "mesh_files": len(mesh_refs), + "verified_files": len(hashes), + }, + ensure_ascii=False, + indent=2, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/examples/lh20_hand_r04/parameters.py b/examples/lh20_hand_r04/parameters.py new file mode 100644 index 00000000..dfe01e0a --- /dev/null +++ b/examples/lh20_hand_r04/parameters.py @@ -0,0 +1,39 @@ +"""Exterior-led proportions. Actuator fit and load capacity are not qualified.""" + +from dataclasses import dataclass +from pathlib import Path + +HERE = Path(__file__).resolve().parent +OUT = HERE / "out" +REVISION = "0.4.0" + + +@dataclass(frozen=True) +class Finger: + name: str + base: tuple + splay: float + lengths: tuple + width: float + + +FINGERS = ( + Finger("index", (28.5, 74, 0), -3.0, (14, 37, 26, 22), 17.4), + Finger("middle", (8.5, 79, 0), 0.0, (14, 40, 28, 23), 17.6), + Finger("ring", (-11.5, 74, 0), 3.0, (14, 37, 26, 22), 17.0), + Finger("little", (-30.5, 64, 0), 7.0, (13, 32, 23, 20), 15.6), + Finger("thumb", (32, 29, 3), -52.0, (14, 30, 25, 22), 17.8), +) +AXES = ("z", "x", "x", "x") +HINGE_CLEARANCE_RADIUS = 8.6 # ui: number(8.4, 10.0, step=0.1) +MATERIALS = { + "frame": (2700, (0.64, 0.67, 0.69)), + "panel": (1100, (0.82, 0.85, 0.86)), + "pad": (1100, (0.035, 0.041, 0.048)), + "graphite": (1100, (0.065, 0.075, 0.085)), + "service": (1100, (0.085, 0.095, 0.105)), + "joint": (2700, (0.50, 0.54, 0.56)), + "machined": (7800, (0.76, 0.80, 0.82)), + "black": (1100, (0.045, 0.055, 0.06)), + "flex": (1400, (0.62, 0.34, 0.07)), +} diff --git a/examples/lh20_hand_r04/parts/__init__.py b/examples/lh20_hand_r04/parts/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/lh20_hand_r04/parts/common.py b/examples/lh20_hand_r04/parts/common.py new file mode 100644 index 00000000..a312cd39 --- /dev/null +++ b/examples/lh20_hand_r04/parts/common.py @@ -0,0 +1,131 @@ +"""Constrained rounded profiles and small, explicitly named library parts.""" + +import math +import numpy as np +import simplecadapi as s +from scipy.spatial.transform import Rotation +from parameters import HERE, REVISION, MATERIALS + + +def frame(matrix=None, origin=(0, 0, 0)): + if matrix is None: + return s.make_placement_rplacement(origin=origin) + return s.make_placement_rplacement( + origin=tuple(matrix[:3, 3]), + x_axis=tuple(matrix[:3, 0]), + y_axis=tuple(matrix[:3, 1]), + ) + + +def transform(origin=(0, 0, 0), rotation=None): + m = np.eye(4) + m[:3, 3] = origin + if rotation is not None: + m[:3, :3] = rotation + return m + + +def placed(body, matrix): + v = Rotation.from_matrix(matrix[:3, :3]).as_rotvec() + a = np.linalg.norm(v) + if a > 1e-12: + body = s.rotate_shape(shape=body, angle=math.degrees(a), axis=tuple(v / a)) + return s.translate_shape(shape=body, vector=tuple(matrix[:3, 3])) + + +def rounded_sketch(name, width, height, radius, origin=(0, 0, 0), normal=(0, 0, 1)): + assert 0 < radius < min(width, height) / 2 + plane = s.make_workplane_rworkplane(origin=origin, normal=normal, x_dir=(1, 0, 0)) + sk = s.make_sketch_rsketch(name=name, plane=plane) + for key, (x, y) in zip( + ("a", "b", "c", "d"), + ( + (-width / 2, -height / 2), + (width / 2, -height / 2), + (width / 2, height / 2), + (-width / 2, height / 2), + ), + ): + sk = s.add_point_rsketch(sketch=sk, point_id=key, x=x, y=y) + sk = s.constrain_fix_rsketch(sketch=sk, target=key) + for i, (a, b) in enumerate((("a", "b"), ("b", "c"), ("c", "d"), ("d", "a"))): + sk = s.add_line_rsketch(sketch=sk, entity_id=f"edge{i}", start=a, end=b) + for i in range(4): + sk = s.fillet_corner_rsketch( + sketch=sk, a=f"edge{i}", b=f"edge{(i + 1) % 4}", radius=radius + ) + return sk + + +def rounded_loft(name, sections): + profiles = [] + for i, (y, w, d, r, x, z) in enumerate(sections): + sk = rounded_sketch(f"{name}_{i}", w, d, r, origin=(x, y, z), normal=(0, 1, 0)) + profiles.append( + s.make_wire_from_sketch_rwire(sketch=sk, require_fully_constrained=True) + ) + return s.loft_rsolid(profiles=profiles, ruled=False, side_faces_tag=f"{name}.side") + + +def plate(width, length, radius, z, thickness, center=(0, 0)): + sk = rounded_sketch("panel_profile", width, length, radius, origin=(*center, z)) + face = s.make_face_from_sketch_rface(sketch=sk, require_fully_constrained=True) + return s.extrude_rsolid(profile=face, direction=(0, 0, 1), distance=thickness) + + +def cylinder(radius, width, axis="x", center=(0, 0, 0)): + direction = {"x": (1, 0, 0), "y": (0, 1, 0), "z": (0, 0, 1)}[axis] + return s.make_cylinder_rsolid( + radius=radius, + height=width, + axis=direction, + bottom_face_center=tuple( + center[i] - width / 2 * direction[i] for i in range(3) + ), + ) + + +def box(width, length, height, center=(0, 0, 0)): + return s.make_box_rsolid( + width=width, height=length, depth=height, bottom_face_center=center + ) + + +def rim(body, radius, distance): + select = s.ql.edges().where( + s.ql.and_( + s.ql.prop("geom.type", "==", "CIRCLE"), + s.ql.prop("geom.length", ">=", 2 * math.pi * radius - 0.02), + s.ql.prop("geom.length", "<=", 2 * math.pi * radius + 0.02), + ) + ) + edges = select.resolve(body) + print("RIM", radius, len(edges), flush=True) + return s.chamfer_rsolid(solid=body, edges=select.exactly(2), distance=distance) + + +def part(pid, builder, material, connectors=(), label=None): + @s.part(id=pid, revision=REVISION, project_root=HERE) + def build(): + body = builder() + p = s.make_part_rpart(part_id=pid, body=body, name=label or pid) + density, color = MATERIALS[material] + p = s.assign_material_rpart( + part=p, + material=s.make_material_rmaterial( + material_id=material, + density=density, + density_unit="kg/m^3", + color=color, + ), + ) + for name, m in connectors or (("origin", np.eye(4)),): + p = s.add_connector_rpart( + part=p, + connector=s.make_placement_connector_rconnector( + connector_id=name, placement=frame(m), name=name + ), + ) + return p + + return build() diff --git a/examples/lh20_hand_r04/parts/finger_surfaces.py b/examples/lh20_hand_r04/parts/finger_surfaces.py new file mode 100644 index 00000000..4560abbb --- /dev/null +++ b/examples/lh20_hand_r04/parts/finger_surfaces.py @@ -0,0 +1,200 @@ +"""Photo-informed curved shells, fork openings and enveloping contact pads.""" + +import simplecadapi as s +from parameters import AXES, HINGE_CLEARANCE_RADIUS +from parts.common import rounded_loft, plate, cylinder, box + + +def dims(spec, k): + return spec.lengths[k], spec.width - (0, 0.3, 1.0, 1.6)[k], (16, 16.2, 15, 14.2)[k] + + +def outline(spec, k): + length, width, depth = dims(spec, k) + if k == 3: + # ---- feature: fingertip-crown (build, profile=geometry) ---- + body = box(width, length, depth, (0, length / 2, -depth / 2)) + return s.fillet_rsolid( + solid=body, edges=s.ql.edges().exactly(12), radius=depth / 2 - 0.5 + ) + # ---- feature: tubular-continuous-envelope (build, profile=sketch) ---- + return rounded_loft( + "barrel", + [ + (0.45, width, depth, min(width, depth) / 2 - 0.8, 0, 0), + ( + length * 0.5, + width - 0.25, + depth, + min(width - 0.25, depth) / 2 - 0.65, + 0, + 0, + ), + ( + length - 0.45, + width - 0.6, + depth - 0.3, + min(width - 0.6, depth - 0.3) / 2 - 0.8, + 0, + 0, + ), + ], + ) + + +def articulation_tools(spec, k): + length, width, depth = dims(spec, k) + axis = AXES[k] + tools = [ + cylinder( + 6.65 if k == 0 else HINGE_CLEARANCE_RADIUS, width - 8.8 if axis == "x" else depth + 2, axis + ) + ] + if k < 3: + tools.append(cylinder(HINGE_CLEARANCE_RADIUS, width - 4.4, "x", (0, length, 0))) + if axis == "x": + tools.append(cylinder(1.3, width + 6, "x")) + if k < 3: + tools.append(cylinder(1.3, width + 6, "x", (0, length, 0))) + return tools + + +def proximal_neck_tools(spec, k): + # Incoming ears nest axially inside the preceding link's outer fork. + _, width, _ = dims(spec, k) + return [ + cylinder(8, 40, "z", (side * ((width - 5) / 2 + 8), 0.45, 0)) + for side in (-1, 1) + ] + + +def flex_slot(spec, k): + length, _, depth = dims(spec, k) + start = 8.0 if k == 0 else 0.8 + # A shallow recess leaves a continuous structural web below the channel. + return plate( + 3.8, + length - start - 0.8, + 0.75, + -depth / 2 - 1, + 1.9, + (0, (start + length - 0.8) / 2), + ) + + +def flex_shape(spec, k): + length, _, depth = dims(spec, k) + start = 8.3 if k == 0 else 1.1 + return plate( + 3.1, + length - start - 1.1, + 0.6, + -depth / 2 + 0.35, + 0.18, + (0, (start + length - 1.1) / 2), + ) + + +def hollow_shell(spec, k): + length, width, depth = dims(spec, k) + body = outline(spec, k) + if k in (1, 2): + # ---- feature: unqualified-drive-envelope (subtract, profile=sketch) ---- + cavity = rounded_loft( + "inner", + [ + ( + 8.2, + width - 4.6, + depth - 4.6, + min(width - 4.6, depth - 4.6) / 2 - 0.7, + 0, + 0, + ), + ( + length - 8.2, + width - 5.0, + depth - 4.6, + min(width - 5, depth - 4.6) / 2 - 0.7, + 0, + 0, + ), + ], + ) + body = s.cut_rsolid(body, cavity, on_split="error") + # ---- feature: circumferential-machining-reliefs (subtract) ---- + for y in (length * 0.43, length * 0.64): + outer = rounded_loft( + "relief_outer", + [ + (y - 0.12, width + 2, depth + 2, 3, 0, 0), + (y + 0.12, width + 2, depth + 2, 3, 0, 0), + ], + ) + core = rounded_loft( + "relief_core", + [ + ( + y - 0.2, + width - 0.65, + depth - 0.45, + min(width - 0.65, depth - 0.45) / 2 - 0.8, + 0, + 0, + ), + ( + y + 0.2, + width - 0.65, + depth - 0.45, + min(width - 0.65, depth - 0.45) / 2 - 0.8, + 0, + 0, + ), + ], + ) + body = s.cut_rsolid( + body, s.cut_rsolid(outer, core, on_split="error"), on_split="error" + ) + # ---- feature: curved-fork-saddles (subtract) ---- + body = s.cut_rsolid(body, *articulation_tools(spec, k), on_split="error") + if k > 0: + # ---- feature: nested-proximal-fork-neck (subtract) ---- + body = s.cut_rsolid(body, *proximal_neck_tools(spec, k), on_split="error") + if k < 3: + # ---- feature: recessed-flex-routing (subtract) ---- + body = s.cut_rsolid(body, flex_slot(spec, k), on_split="error") + return body + + +def cover_mask(spec, k, inset=0): + length, width, _ = dims(spec, k) + return box(width + 4, length - 17 - inset * 2, 20, (0, length / 2, 0.25 + inset)) + + +def tip_mask(spec, gap=0): + length, width, _ = dims(spec, 3) + start = 7.3 + gap + return box( + width + 5, length + 2 - start, 20, (0, (start + length + 2) / 2, -1.8 + gap) + ) + + +def rail_shape(spec, k): + body = hollow_shell(spec, k) + if k in (1, 2): + # ---- feature: detachable-curved-cover-seat (subtract) ---- + body = s.cut_rsolid(body, cover_mask(spec, k), on_split="error") + if k == 3: + # ---- feature: fingertip-backbone-and-contact-seat (subtract) ---- + body = s.cut_rsolid(body, tip_mask(spec), on_split="error") + return body + + +def cover_shape(spec, k): + # ---- feature: matching-curved-service-cover (intersect) ---- + return s.intersect_rsolid(hollow_shell(spec, k), cover_mask(spec, k, 0.18)) + + +def tip_pad(spec): + # ---- feature: wraparound-black-contact-pad (intersect) ---- + return s.intersect_rsolid(hollow_shell(spec, 3), tip_mask(spec, 0.25)) diff --git a/examples/lh20_hand_r04/parts/finishing.py b/examples/lh20_hand_r04/parts/finishing.py new file mode 100644 index 00000000..08666928 --- /dev/null +++ b/examples/lh20_hand_r04/parts/finishing.py @@ -0,0 +1,96 @@ +"""Named machining details with explicit QL selections, never cosmetic lines.""" + +import math +import simplecadapi as scad + + +def circular_rims(body, radius, *, z=None, tolerance=0.02): + predicates = [ + scad.ql.prop("geom.type", "==", "CIRCLE"), + scad.ql.prop("geom.length", ">=", 2 * math.pi * (radius - tolerance)), + scad.ql.prop("geom.length", "<=", 2 * math.pi * (radius + tolerance)), + ] + if z is not None: + predicates += [ + scad.ql.prop("geom.center.z", ">=", z - tolerance), + scad.ql.prop("geom.center.z", "<=", z + tolerance), + ] + return scad.ql.edges().where(scad.ql.and_(*predicates)) + + +def rim_chamfer(body, radius, distance, *, z=None, expected=2): + selection = circular_rims(body, radius, z=z) + found = selection.resolve(body) + print(f"RIM r={radius:g}: {len(found)} edges; chamfer {distance:g}", flush=True) + return scad.chamfer_rsolid( + solid=body, edges=selection.exactly(expected), distance=distance + ) + + +def round_box(width, length, height, center, radius): + body = scad.make_box_rsolid( + width=width, height=length, depth=height, bottom_face_center=center + ) + edges = scad.ql.edges() + return scad.fillet_rsolid(solid=body, edges=edges.exactly(12), radius=radius) + + +def hex_recess(across_flats, z, depth): + sketch = scad.make_sketch_rsketch( + name="hex_driver", + plane=scad.make_workplane_rworkplane( + origin=(0, 0, z), normal=(0, 0, 1), x_dir=(1, 0, 0) + ), + ) + radius = across_flats / math.sqrt(3) + for i in range(6): + angle = math.radians(i * 60) + sketch = scad.add_point_rsketch( + sketch=sketch, + point_id=f"p{i}", + x=radius * math.cos(angle), + y=radius * math.sin(angle), + ) + sketch = scad.constrain_fix_rsketch(sketch=sketch, target=f"p{i}") + for i in range(6): + sketch = scad.add_line_rsketch( + sketch=sketch, entity_id=f"e{i}", start=f"p{i}", end=f"p{(i + 1) % 6}" + ) + profile = scad.make_face_from_sketch_rface( + sketch=sketch, require_fully_constrained=True + ) + return scad.extrude_rsolid(profile=profile, direction=(0, 0, 1), distance=depth) + + +def cap_screw(): + """Nominal M1.2 mounting candidate; thread is represented at minor diameter. + + Origin is the cap underside. 0.83 mm top sits 0.02 below the 0.85 cap. + The tapered head and the tool socket are real geometry; no thread claim. + """ + shank = scad.make_cylinder_rsolid( + radius=0.48, height=1.98, bottom_face_center=(0, 0, -1.6) + ) + head = scad.make_cone_rsolid( + bottom_radius=0.57, + top_radius=1.05, + height=0.48, + bottom_face_center=(0, 0, 0.35), + ) + body = scad.union_rsolid(shank, head) + return scad.cut_rsolid(body, hex_recess(0.7, 0.50, 0.6), on_split="error") + + +def round_loft_end(body, y, radius): + face = scad.ql.faces().where( + scad.ql.and_( + scad.ql.prop("geom.type", "==", "PLANE"), + scad.ql.prop("geom.center.y", ">=", y - 0.001), + scad.ql.prop("geom.center.y", "<=", y + 0.001), + ) + ) + edges = face.boundary("edge") + found = edges.resolve(body) + print(f"END y={y:g}: {len(found)} edges; radius {radius:g}", flush=True) + # The constrained ellipse is split into two rational arcs at the loft seam. + return scad.fillet_rsolid(solid=body, edges=edges.exactly(2), radius=radius) diff --git a/examples/lh20_hand_r04/parts/joint_details.py b/examples/lh20_hand_r04/parts/joint_details.py new file mode 100644 index 00000000..042b0e09 --- /dev/null +++ b/examples/lh20_hand_r04/parts/joint_details.py @@ -0,0 +1,85 @@ +"""Stepped joint end caps and candidate three-point flush fasteners.""" + +import math +import numpy as np +import simplecadapi as s +from scipy.spatial.transform import Rotation +from parameters import AXES +from parts.common import cylinder, rim, placed, transform +from parts.finishing import hex_recess +from parts.finger_surfaces import dims + + +def cap_frame(spec, k, side): + _, width, depth = dims(spec, k) + span = max(width, dims(spec, k - 1)[1]) + 0.3 if k else depth + 0.3 + if AXES[k] == "x": + rotation = Rotation.from_euler("y", side * 90, degrees=True).as_matrix() + origin = (side * (span / 2 + 0.1), 0, 0) + else: + rotation = ( + np.eye(3) + if side == 1 + else Rotation.from_euler("x", 180, degrees=True).as_matrix() + ) + origin = (0, 0, side * (span / 2 + 0.1)) + return transform(origin, rotation) + + +def bolt_points(): + return [ + (3.65 * math.cos(math.radians(a)), 3.65 * math.sin(math.radians(a))) + for a in (90, 210, 330) + ] + + +def bolt_clearance(x, y): + straight = cylinder(0.48, 2.5, "z", (x, y, 0.4)) + sink = s.make_cone_rsolid( + bottom_radius=0.48, top_radius=0.94, height=0.4, bottom_face_center=(x, y, 0.7) + ) + return s.union_rsolid(straight, sink) + + +def short_fastener(): + # ---- feature: short-cap-fastener-candidate (build, profile=geometry) ---- + shank = cylinder(0.38, 0.8, "z", (0, 0, 0.35)) + head = s.make_cone_rsolid( + bottom_radius=0.43, + top_radius=0.85, + height=0.32, + bottom_face_center=(0, 0, 0.72), + ) + body = s.union_rsolid(shank, head) + # ---- feature: physical-hex-tool-socket (subtract, profile=sketch) ---- + return s.cut_rsolid(body, hex_recess(0.65, 0.85, 0.5), on_split="error") + + +def cap_shape(spec, k, side): + # ---- feature: stepped-machined-end-cap (build, profile=geometry) ---- + body = cylinder(6.3, 0.8, "z", (0, 0, 0.4)) + body = rim(body, 6.3, 0.18) + inset = cylinder(5.55, 0.3, "z", (0, 0, 0.85)) + body = s.union_rsolid(body, inset) + # ---- feature: three-point-cap-fixing (subtract) ---- + body = s.cut_rsolid( + body, *[bolt_clearance(x, y) for x, y in bolt_points()], on_split="error" + ) + return placed(body, cap_frame(spec, k, side)) + + +def bolt_shape(spec, k, side, index): + x, y = bolt_points()[index] + return placed(short_fastener(), cap_frame(spec, k, side) @ transform((x, y, 0))) + + +def hub_shape(spec, k): + _, width, depth = dims(spec, k) + axis = AXES[k] + # ---- feature: compact-hinge-barrel-envelope (build, profile=geometry) ---- + body = rim( + cylinder(6.25, width - 9.4 if axis == "x" else depth - 1, axis), 6.25, 0.3 + ) + span = max(width, dims(spec, k - 1)[1]) + 0.3 if k else depth + 0.3 + axle = cylinder(0.98, span + 0.1, axis) + return s.union_rsolid(body, axle) diff --git a/examples/lh20_hand_r04/parts/links.py b/examples/lh20_hand_r04/parts/links.py new file mode 100644 index 00000000..4c922621 --- /dev/null +++ b/examples/lh20_hand_r04/parts/links.py @@ -0,0 +1,67 @@ +"""Compose the photo-informed finger surface and named joint details.""" + +from functools import lru_cache +import numpy as np +from parameters import FINGERS, AXES +from assembly_support import axis_matrix +from parts.common import part, cylinder +from parts.finger_surfaces import dims, rail_shape, cover_shape, tip_pad, flex_shape +from parts.joint_details import cap_shape, hub_shape, bolt_shape + + +@lru_cache(maxsize=None) +def link_parts(name, k): + spec = next(f for f in FINGERS if f.name == name) + length, _, _ = dims(spec, k) + connectors = [("origin", np.eye(4)), ("hinge", axis_matrix(AXES[k]))] + if k < 3: + next_frame = axis_matrix(AXES[k + 1]) + next_frame[:3, 3] = (0, length, 0) + connectors.append(("next", next_frame)) + prefix = f"{name}_{k}" + result = { + "rail": part( + prefix + "_rail", lambda: rail_shape(spec, k), "frame", connectors + ), + "hub": part( + prefix + "_hub", + lambda: hub_shape(spec, k), + "joint", + label="关节外壳包络:内部驱动待适配", + ), + } + for side, key in ((-1, "left"), (1, "right")): + result["cap_" + key] = part( + prefix + "_cap_" + key, + lambda side=side: cap_shape(spec, k, side), + "machined", + ) + for i in range(3): + bolt = f"bolt_{key}_{i}" + result[bolt] = part( + prefix + "_" + bolt, + lambda side=side, i=i: bolt_shape(spec, k, side, i), + "joint", + ) + if k in (1, 2): + result["cover"] = part(prefix + "_cover", lambda: cover_shape(spec, k), "frame") + if k < 3: + result["flex"] = part( + prefix + "_flex", + lambda: flex_shape(spec, k), + "flex", + label="分段柔性电路外观占位:未验证连续弯折路线", + ) + if k == 3: + result["pad"] = part(prefix + "_pad", lambda: tip_pad(spec), "pad") + return result + + +@lru_cache(maxsize=None) +def base_part(name): + return part( + name + "_root_mount", + lambda: cylinder(2.5, 2.5, "z", (0, 0, -10.8)), + "joint", + (("origin", np.eye(4)), ("hinge", np.eye(4))), + ) diff --git a/examples/lh20_hand_r04/parts/palm.py b/examples/lh20_hand_r04/parts/palm.py new file mode 100644 index 00000000..b86120b1 --- /dev/null +++ b/examples/lh20_hand_r04/parts/palm.py @@ -0,0 +1,163 @@ +"""Waisted palm with a thenar transition and fitted surface panels.""" + +from functools import lru_cache +import numpy as np +import simplecadapi as s +from scipy.spatial.transform import Rotation +from parameters import FINGERS +from parts.common import ( + rounded_loft, + plate, + cylinder, + box, + part, + transform, + placed, + rim, +) +from parts.finishing import cap_screw +from parts.surface_fixings import screw_sink + +SECTIONS = ( + (-4, 45, 23, 9, 0, -0.5), + (8, 48, 27, 10, -1, -0.5), + (28, 64, 29, 11, -2, -1), + (48, 78, 27, 10, -4, -1), + (64, 80, 24, 8, -4, -1), + (76, 75, 21, 7, -3, -1), +) +SCREWS = ((-20, 23, -15.8), (8, 23, -15.8), (-20, 49, -15.0), (8, 49, -15.0)) + + +def base_transform(spec): + rotation = Rotation.from_euler("z", spec.splay, degrees=True).as_matrix() + if spec.name == "thumb": + rotation = ( + rotation + @ Rotation.from_euler("y", 24, degrees=True).as_matrix() + @ Rotation.from_euler("x", 8, degrees=True).as_matrix() + ) + return transform(spec.base, rotation) + + +def envelope(): + # ---- feature: waisted-palm-surface (build, profile=sketch) ---- + body = rounded_loft("palm", SECTIONS) + # ---- feature: flowing-thenar-buttress (add, profile=sketch) ---- + thumb = rounded_loft( + "thenar", + [ + (14, 24, 18, 7, 21, 1), + (25, 30, 24, 9, 23, 1), + (40, 24, 22, 8, 26, 1), + (49, 12, 16, 5, 27, -1), + ], + ) + return s.union_rsolid(body, thumb) + + +def root_tools(): + tools = [] + for f in FINGERS: + m = base_transform(f) + tools.append(placed(cylinder(7.2, 60, "z"), m)) + end = f.lengths[0] + 3 + form = rounded_loft( + "root_space", + [(-0.5, f.width + 3.4, 19, 3, 0, 0), (end, f.width + 3.4, 19, 3, 0, 0)], + ) + tools.append(placed(form, m)) + return tools + + +def shell(side): + # ---- feature: continuous-palm-shell (build, profile=sketch) ---- + body = envelope() + inner = rounded_loft( + "palm_inner", + [(y, w - 4, d - 4, max(2, r - 2), x, z) for y, w, d, r, x, z in SECTIONS], + ) + # ---- feature: palm-internal-space (subtract) ---- + body = s.cut_rsolid(body, inner, on_split="error") + # ---- feature: articulation-root-apertures (subtract) ---- + body = s.cut_rsolid(body, *root_tools(), on_split="error") + # ---- feature: continuous-side-parting-line (intersect) ---- + mask = box(160, 150, 40, (0, 40, 0.15 if side == "front" else -40.15)) + return s.intersect_rsolid(body, mask) + + +def panel_mask(side, gap=0): + if side == "front": + return plate(52 - 2 * gap, 43 - 2 * gap, 12 - gap, 0, 35, (-7, 35)) + # Keep a continuous border between the canted thumb socket and service hatch. + return plate(50 - 2 * gap, 43 - 2 * gap, 9 - gap, -35, 35, (-7, 35)) + + +def cover_shape(side): + body = shell(side) + # ---- feature: inset-panel-opening (subtract) ---- + return s.cut_rsolid(body, panel_mask(side), on_split="error") + + +def screw_pose(x, y, z): + return transform( + (x, y, z + 0.85), Rotation.from_euler("x", 180, degrees=True).as_matrix() + ) + + +def panel_shape(side): + # ---- feature: fitted-surface-panel (intersect) ---- + body = s.intersect_rsolid(shell(side), panel_mask(side, 0.30)) + if side == "back": + # ---- feature: compact-service-fixing-lands (add) ---- + for x, y, z in SCREWS: + boss = cylinder(1.9, 3.5, "z", (x, y, z + 1.75)) + body = s.union_rsolid(body, boss) + # ---- feature: recessed-service-fixings (subtract) ---- + for x, y, z in SCREWS: + body = s.cut_rsolid( + body, + cylinder(0.65, 12, "z", (x, y, z + 3)), + screw_sink(screw_pose(x, y, z)), + on_split="error", + ) + return body + + +def wrist_shape(flange=False): + # ---- feature: integrated-wrist-collar (build, profile=sketch) ---- + sections = ( + [(-16, 44, 28, 7, 0, 0), (-13, 44, 28, 7, 0, 0)] + if flange + else [(-12.65, 40, 24, 8, 0, 0), (-4.35, 44.4, 23, 9, 0, -0.5)] + ) + body = rounded_loft("wrist", sections) + # ---- feature: electrical-and-mounting-ports (subtract) ---- + tools = [cylinder(8, 30, "y", (0, -10, 0))] + for x in (-15, 15): + for z in (-8, 8): + tools.append(cylinder(1.7, 30, "y", (x, -10, z))) + return s.cut_rsolid(body, *tools, on_split="error") + + +@lru_cache(maxsize=1) +def palm_parts(): + connectors = [("origin", np.eye(4))] + [ + (f.name + "_root", base_transform(f)) for f in FINGERS + ] + result = { + "front": part( + "palm_front", lambda: cover_shape("front"), "graphite", connectors + ), + "back": part("palm_back", lambda: cover_shape("back"), "graphite"), + "contact": part("palm_contact", lambda: panel_shape("front"), "service"), + "service": part("palm_service", lambda: panel_shape("back"), "service"), + "wrist": part("wrist_collar", lambda: wrist_shape(False), "graphite"), + "flange": part("wrist_flange", lambda: wrist_shape(True), "machined"), + } + for i, (x, y, z) in enumerate(SCREWS): + pose = screw_pose(x, y, z) + result[f"screw{i}"] = part( + f"palm_screw_{i}", lambda pose=pose: placed(cap_screw(), pose), "machined" + ) + return result diff --git a/examples/lh20_hand_r04/parts/surface_fixings.py b/examples/lh20_hand_r04/parts/surface_fixings.py new file mode 100644 index 00000000..a286c4b5 --- /dev/null +++ b/examples/lh20_hand_r04/parts/surface_fixings.py @@ -0,0 +1,16 @@ +"""Shared countersink used by the unchanged palm service panel.""" + +import simplecadapi as s +from parts.common import placed + + +def screw_sink(pose): + return placed( + s.make_cone_rsolid( + bottom_radius=0.62, + top_radius=1.22, + height=0.6, + bottom_face_center=(0, 0, 0.3), + ), + pose, + ) diff --git a/examples/lh20_hand_r04/render.py b/examples/lh20_hand_r04/render.py new file mode 100644 index 00000000..b74c86e5 --- /dev/null +++ b/examples/lh20_hand_r04/render.py @@ -0,0 +1,89 @@ +"""Orthographic and oblique inspection images, always rendered from CAD BREP.""" + +import argparse, hashlib, json +import numpy as np +from PIL import Image, ImageDraw, ImageFont +from simplecadapi._cpp import _native +from parts.common import placed +from model_io import read_model, flatten +from parameters import OUT + + +def panel(leaves, view, width=1000, height=1300): + scene = _native.RenderScene() + for path, p, m in leaves: + scene.add_shape( + placed(p.body, m), + color=tuple(p.material.color)[:3], + studio_material=p.material.material_id in ("frame", "joint"), + linear_deflection=0.07, + angular_deflection=0.15, + edges=False, + ink=False, + ) + result = _native.render_scene( + scene, + width, + height, + supersample=2, + style="standard", + zoom=1.4 if len(leaves) > 50 else 1.15, + views=[(*view, "")], + view_up=(0, 1, 0), + show_axes=False, + edge_width_scale=0, + background_top=(0.94, 0.95, 0.96), + background_bottom=(0.86, 0.89, 0.91), + ) + return Image.fromarray(np.asarray(result.rgba)[:, :, :3].copy()) + + +def font(size): + return ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", size) + + +def main(name): + leaves = flatten(read_model(name)) + image = Image.new("RGB", (3000, 1550), "#f1f3f5") + draw = ImageDraw.Draw(image) + draw.text((65, 40), "LH20 / EXTERIOR REDESIGN", font=font(52), fill="#23343c") + draw.text( + (65, 110), + "R0.4 | Real parametric CAD | Actuator integration pending", + font=font(26), + fill="#566973", + ) + for i, (v, title) in enumerate( + ( + ((90, 0), "PALMAR"), + ((-90, 180), "DORSAL"), + ((35, 35), "THREE-QUARTER / PROFILE"), + ) + ): + print("Rendering", title, flush=True) + shot = panel(leaves, v) + shot.save(OUT / f"{name}_{('front', 'back', 'profile')[i]}.png") + image.paste(shot, (i * 1000, 200)) + draw.text((i * 1000 + 35, 168), title, font=font(23), fill="#41555e") + path = OUT / f"{name}_overview.png" + image.save(path) + panel(leaves, (0, 0)).save(OUT / f"{name}_side.png") + path.with_suffix(".json").write_text( + json.dumps( + dict( + package_sha256=hashlib.sha256( + (OUT / f"{name}.scadpkg").read_bytes() + ).hexdigest(), + image_sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + scope="Actual exterior CAD; not a complete internal mechanism", + ), + indent=2, + ) + ) + print(path, flush=True) + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--name", default="hand") + main(ap.parse_args().name) diff --git a/examples/lh20_hand_r04/requirements.txt b/examples/lh20_hand_r04/requirements.txt new file mode 100644 index 00000000..4ac397d6 --- /dev/null +++ b/examples/lh20_hand_r04/requirements.txt @@ -0,0 +1,3 @@ +simplecadapi[verify,editor]==2.3.0 +scipy==1.18.1 +numpy==2.5.5 diff --git a/examples/lh20_hand_r04/verify.py b/examples/lh20_hand_r04/verify.py new file mode 100644 index 00000000..cdc1a158 --- /dev/null +++ b/examples/lh20_hand_r04/verify.py @@ -0,0 +1,135 @@ +"""Independent BREP validity, nominal clearances and solved exterior datums.""" + +import argparse, hashlib, json +from itertools import combinations +import numpy as np +from OCP.BRepCheck import BRepCheck_Analyzer +from OCP.BRepGProp import BRepGProp +from OCP.GProp import GProp_GProps +from OCP.BRepBndLib import BRepBndLib +from OCP.Bnd import Bnd_Box +from OCP.BRepAlgoAPI import BRepAlgoAPI_Common +from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform +from OCP.gp import gp_Trsf +from simplecadapi.verify import to_ocp +from model_io import read_model, flatten, reports +from parameters import OUT, FINGERS + + +def volume(shape): + p = GProp_GProps() + BRepGProp.VolumeProperties_s(shape, p) + return p.Mass() + + +def bounds(shape): + b = Bnd_Box() + BRepBndLib.AddOptimal_s(shape, b, False, False) + return np.array(b.Get()) + + +def main(name, collisions): + root = read_model(name) + leaves = flatten(root) + facts = [] + shapes = [] + for path, p, m in leaves: + shape = to_ocp(p.body) + t = gp_Trsf() + t.SetValues(*[float(v) for v in m[:3].reshape(-1)]) + shape = BRepBuilderAPI_Transform(shape, t, False).Shape() + v = volume(shape) + b = bounds(shape) + facts.append( + dict( + path=path, + part=p.part_id, + valid=bool(BRepCheck_Analyzer(shape).IsValid()), + volume_mm3=v, + bounds_mm=b.tolist(), + ) + ) + shapes.append((path, shape, b)) + print("Measured", len(shapes), "solids", flush=True) + intersections = [] + candidates = 0 + if collisions: + for (a, sa, ba), (b, sb, bb) in combinations(shapes, 2): + if np.any(np.minimum(ba[3:], bb[3:]) - np.maximum(ba[:3], bb[:3]) < 0.001): + continue + candidates += 1 + common = BRepAlgoAPI_Common(sa, sb) + if not common.IsDone(): + raise RuntimeError((a, b, "boolean failed")) + v = volume(common.Shape()) + if v > 0.01: + row = dict(a=a, b=b, volume_mm3=v) + intersections.append(row) + print("OVERLAP", row, flush=True) + bb = np.array([r["bounds_mm"] for r in facts]) + dimensions = bb[:, 3:].max(axis=0) - bb[:, :3].min(axis=0) + report = reports(root) + structure = {} + if name.startswith("hand"): + names = [f.name for f in FINGERS] + assert set(names) <= set(root.component_ids()), ( + "Complete five-finger hand required" + ) + for finger in names: + item = root.get_component(finger).item + assert {f"link{k}" for k in range(4)} <= set(item.component_ids()) + assert {f"axis{k}" for k in range(4)} <= set(item.constraint_ids()) + structure[finger] = {"articulated_links": 4, "revolute_constraints": 4} + build_path = OUT / f"{name}_build.json" + build = json.loads(build_path.read_text()) if build_path.exists() else None + digest = hashlib.sha256((OUT / f"{name}.scadpkg").read_bytes()).hexdigest() + if build: + assert build["package_sha256"] == digest + result = dict( + model=name, + package_sha256=digest, + scope="Exterior design only; specified package pose, not actuator fit or full travel qualification", + pose_degrees=build["pose_degrees"] if build else None, + five_finger_structure=structure, + occurrences=len(leaves), + bounds_size_mm=dimensions.tolist(), + geometry=facts, + geometry_pass=all(r["valid"] and r["volume_mm3"] > 0 for r in facts), + assembly_reports=report, + constraints_pass=all(r["solved"] for r in report), + collisions_checked=collisions, + boolean_pairs=candidates, + intersections=intersections, + clearance_pass=collisions and not intersections, + ) + path = OUT / f"{name}_check.json" + if path.exists(): + history = OUT / "history" + history.mkdir(exist_ok=True) + ( + history + / f"{name}_{hashlib.sha256(path.read_bytes()).hexdigest()[:12]}.json" + ).write_bytes(path.read_bytes()) + path.write_text(json.dumps(result, indent=2)) + print( + json.dumps( + { + k: v + for k, v in result.items() + if k not in ("geometry", "assembly_reports", "intersections") + }, + indent=2, + ), + flush=True, + ) + assert result["geometry_pass"] and result["constraints_pass"] + if collisions: + assert result["clearance_pass"] + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--name", default="hand") + ap.add_argument("--collisions", action="store_true") + a = ap.parse_args() + main(a.name, a.collisions)