refactor(layout): src/ 收成顶层包 arm/,入口统一 python -m;提升承担构建的 scratch 脚本

单文件约束取消后,Python 侧没必要再靠 16 处 sys.path.insert 维持扁平模块互认。
现在按职责分包:
  arm/paths.py 路径唯一来源(含新增 CACHE、TPL)
  arm/constants.py 实测接口数值(原 armcore 的 M/C/CLR/FIT/MOTOR_TOL 段)
  arm/cad/{helpers,arm_build,part_tools,parts/} 几何与装配
  arm/kinematics.py(原 human_layout.py,唯一运动学事实源)
  arm/analysis/{sweep_v2,strength_check,torque_balance,finalize_travel,ws_sweep,gen_env_mesh}
  arm/dataio/{screw_mesh,draw_sheet}   arm/viewer/{build_viewer,shot}
  arm/build_model.py(原 arm_model.py)

顺带修掉的既有缺陷(都是实测撞出来的,不是预防性改动):
- arm_model 第二次 sys.path 跳到 gitignore 的 scratch/ 去 import 构建必需的包络脚本:
  ws_sweep/gen_env_mesh 提升进 arm/analysis/,缓存挪到 data/cache/(gitignore,可重生成)。
- finalize_travel / draw_sheet 顶层就是"算完写文件",一次 importlib 冒烟测试就把
  docs/travel.json 重写了一遍;现在被 import 直接抛错。
- strength_check 用 OUT.replace("/out","/web") 靠字符串形状推路径,改成直接用 WEB。
- build_viewer 里 WORKSPACE 使用点漏改导致 NameError —— 已由构建关卡抓到并修掉。

os._exit 的处置与计划里的假设相反:实测光是 `python -c "import arm.cad.helpers"`
就会在解释器退出时段错误(exit 139,OCC 静态析构),全流程跑完也一样。所以入口
脚本尾部保留 flush + os._exit,并把原因写进注释;被 import 时不生效。

关卡(tests/):
- verify.py 一条命令跑三层:产物 md5、IK 数值 exact 段、截图。
- 截图基线重做并分级:同一构建连跑两轮实测 102 张逐字节可复现(要求 md5 相同),
  3 张线束 x-ray 不可复现(mean<=0.0017、无像素差>8)改为与参考像素比容差;
  这 3 张不再入库,免得每次跑关卡都脏 git。
- 新增 ?view=sheet / ?sheet=N / ?theme / ?guide=N 四个 URL 参数:工程图与装配向导
  占了约一半 CSS 和 700 行 JS,原先没有任何截图覆盖,拆它们等于没有关卡。
- 关卡灵敏度已验:改坏 IK 基线一个数 -> FAIL;换旧版求解器 -> 5 处 exact 差异。

实测:python -m arm.build_model 退出码 0,全部产物 md5 与基线一致,
105 视图截图全过,IK exact 段逐字节一致。
This commit is contained in:
cbb
2026-10-15 03:31:20 +08:00
parent b32d44efe0
commit 649bd69810
57 changed files with 843 additions and 453 deletions
+6
View File
@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
"""6 自由度人形机械臂:CadQuery 参数化建模、行程/干涉扫描、制造文件与查看器数据。
入口一律从仓根以 `python -m arm.xxx` 运行:`python -m` 会把仓根放进 sys.path,
包内 import 因此直接可解析,不需要 pip install。
"""
+3
View File
@@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
"""行程与干涉扫描、强度与力矩核算、可达包络采样与网格注入。
"""
+71
View File
@@ -0,0 +1,71 @@
# -*- coding: utf-8 -*-
"""从 travel_detail.json 的单关节硬限位重新生成 docs/travel.json。
滑块范围 = 单关节硬限位(任意单关节推满零干涉,含 1° 安全余量);
组合折叠约束保留在 travel_detail.json 的 combos 字段里,供报告引用。
注意 note 的措辞:单轴整周无干涉 **不等于** 任意组合姿态无干涉。sweep_v2 的组合扫描
已经在 J1/J3/J6 上找到了真实卡死(工具法兰 P09 撞固定立柱 P01_A),例如 J3≈±162°。
所以连续轴的 note 必须写明"单轴"并指向 combos,否则这份文件会误导人——查看器运行期
另有胶囊碰撞模型按姿态夹取(ik-glue.js 的 dynLimit),但静态滑块范围按设计不压缩。
"""
import json
import math
import os
import sys
from arm.analysis.sweep_v2 import CHAIN
from arm.paths import DOCS
# 这两个脚本的顶层就是"算完并写文件",被 import 时会静默重写 travel/mesh 派生产物
# (实测:一次 importlib 冒烟测试就把 docs/travel.json 重写了一遍)。这里改成直接炸。
if __name__ != "__main__":
raise RuntimeError(
"finalize_travel 是脚本:顶层代码一执行就重写产物,不能 import。"
"要用就跑 python -m arm.analysis.finalize_travel。")
d = json.load(open(DOCS + "/travel_detail.json", encoding="utf-8"))
# 组合扫描中,每个被扫轴真实出现卡死的最小绝对角
combo_warn = {}
for c in d.get("combos", []):
if not c.get("jams"):
continue
ax = c["swept"]
for a in c["jams"]:
try:
v = abs(float(a))
except (TypeError, ValueError):
continue
combo_warn[ax] = min(combo_warn.get(ax, 1e9), v)
out = []
for t in CHAIN[1:]:
s = d["singles"][t]
lo, hi = s["lo"], s["hi"]
warn = combo_warn.get(t)
warn_txt = (";组合折叠姿态下(其余关节同时处于各自极限)约 ±%.0f° 起与躯干占位"
"(台架 P01 立柱)干涉,见 travel_detail.combos,"
"运行期由查看器碰撞模型按姿态夹取" % warn) if warn is not None else ""
if lo <= -179.9 and hi >= 179.9:
out.append(dict(axis=t, lo=-180.0, hi=180.0, continuous=True, zero=0.0,
combo_warn_deg=warn,
note="单轴整周无干涉(滑块按单轴限位给出)%s" % (warn_txt or
";组合扫描未发现该轴卡死")))
else:
lo_out = float(math.ceil(lo + 1.0)) if lo < -0.5 else 0.0
hi_out = float(math.floor(hi - 1.0)) if hi > 0.5 else 0.0
out.append(dict(axis=t, lo=lo_out, hi=hi_out, continuous=False, zero=0.0,
combo_warn_deg=warn,
note="单轴正向 +%d° / 反向 %d°,总行程 %d°(单关节硬限位,含相邻件与电机)%s"
% (hi_out, lo_out, hi_out - lo_out, warn_txt)))
print("%-3s %7.1f .. %7.1f -> %s .. %s%s"
% (t, lo, hi, out[-1]["lo"], out[-1]["hi"],
(" 组合卡死阈值 ±%.0f°" % warn) if warn is not None else ""))
json.dump(out, open(DOCS + "/travel.json", "w", encoding="utf-8"),
ensure_ascii=False, indent=1)
d["final"] = out
json.dump(d, open(DOCS + "/travel_detail.json", "w", encoding="utf-8"),
ensure_ascii=False, indent=1)
print("rewrote docs/travel.json (single-joint hard stops) + updated travel_detail.json")
+100
View File
@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
"""生成可达外包络的 ENV 零件(经纬网单件)追加进 web/mesh_arm.json:
ENV_WL_包络经纬网 —— kind=line,LineSegments 渲染(经向 10°/条、纬向 8mm/环)
包络 = rmax(x) 母线绕 J1 轴(平行 X,过 (y=128, z=610))整周回转;grp=root 不随关节动。"""
import json
import math
import os
import sys
import numpy as np
from arm.paths import WEB, CACHE
from arm import kinematics as HL
Y_AX = HL.Y_AXIS # 128
Z_AX = HL.Z_RL # 610
def main():
d = np.load(CACHE + "/ws_cloud.npz")
xs, rmax = d["xs"], d["rmax"]
ok = ~np.isnan(rmax)
xs, rmax = xs[ok], rmax[ok]
def grid(step_x, dphi_deg):
"""经纬参数网格 -> verts(NX*NP,3), segs(扁平索引对), tris。"""
xs_e = np.arange(xs.min(), xs.max() + 1e-9, step_x)
rm_e = np.interp(xs_e, xs, rmax)
nph = int(round(360.0 / dphi_deg))
phg = np.linspace(0.0, 2.0 * math.pi, nph, endpoint=False)
nx = len(xs_e)
V = np.empty((nx * nph, 3))
for i, x in enumerate(xs_e):
r = rm_e[i]
for j, ph in enumerate(phg):
V[i * nph + j] = (x, Y_AX + r * math.cos(ph), Z_AX + r * math.sin(ph))
segs = []
for i in range(nx - 1): # 经线(沿 x)
for j in range(nph):
segs += [i * nph + j, (i + 1) * nph + j]
for i in range(nx): # 纬线(沿 φ)
for j in range(nph):
j2 = (j + 1) % nph
segs += [i * nph + j, i * nph + j2]
tris = []
for i in range(nx - 1):
for j in range(nph):
j2 = (j + 1) % nph
a, b = i * nph + j, i * nph + j2
c, e = (i + 1) * nph + j, (i + 1) * nph + j2
tris += [a, c, b, b, c, e]
return V, segs, tris
# 经纬网单件:经向 10°一条、纬向 8mm一环(无需贴片面,线自带罩体感)
Vl, sl, _tl = grid(8.0, 10.0)
# 自证:包络尺寸应等于 ws_metrics 极值。
# 【2026-10-05c 修正】原来是 <1.0 的硬比较,但网格 x 是从 xs.min() 起按 step_x
# 对齐的(np.arange),最后一个采样点最多比真极值短一个步长 —— 一旦
# (x_fwd - xs.min()) 不是 step_x 的整数倍,断言就会假失败(实测差 6.46mm,
# 正好 < 8.0),导致包络注不进去、查看器里"可达包络"整个消失。改为
# "不得超出、且至多少一个步长"这个真正成立的判据。
step_x = 8.0
met = json.load(open(CACHE + "/ws_metrics.json", encoding="utf-8"))
assert Vl[:, 0].min() >= met["x_back"] - 1e-6, (Vl[:, 0].min(), met["x_back"])
assert Vl[:, 0].min() <= met["x_back"] + step_x + 1e-6, (Vl[:, 0].min(), met["x_back"])
assert Vl[:, 0].max() <= met["x_fwd"] + 1e-6, (Vl[:, 0].max(), met["x_fwd"])
assert Vl[:, 0].max() >= met["x_fwd"] - step_x - 1e-6, (Vl[:, 0].max(), met["x_fwd"])
rl = np.hypot(Vl[:, 1] - Y_AX, Vl[:, 2] - Z_AX)
# rl.max() 就是 rmax(x) 网格插值后的峰值,与 met["r_max"](原始点云极值)之间
# 只允许有插值/取整量级的差(实测 0.044mm),故给 1.0mm 容差。
assert abs(rl.max() - met["r_max"]) < 1.0, (rl.max(), met["r_max"])
assert np.all((Vl[:, 1] - Y_AX) ** 2 + (Vl[:, 2] - Z_AX) ** 2
<= (np.interp(Vl[:, 0], xs, rmax) + 1e-6) ** 2), "line"
print("包络经纬网: 顶点%d 线段%d(经10° x 纬8mm)" % (len(Vl), len(sl) // 2))
# ---- 追加进 mesh_arm.json ----
path = WEB + "/mesh_arm.json"
data = json.load(open(path, encoding="utf-8"))
data["parts"] = [p for p in data["parts"] if not p["name"].startswith("ENV_")]
mx = max(p["idx"] for p in data["parts"])
note_ws = ("可达外包络(运动学,docs/travel.json 滑块限位下的全组合 FK 包络):"
"r=rmax(x) 绕 J1 轴整周回转。高 %.0f~%.0f mm,前伸 %.0f / 后伸 %.0f mm,"
"离 J1 轴最远 %.0f mm;包络内含死区(肩下折不进),多关节同极位由控制器避碰。"
% (met["z_min"], met["z_max"], met["x_fwd"], met["x_back"], met["r_max"]))
line = dict(name="ENV_WL_包络经纬网", cn="包络经纬网", v=[list(p) for p in Vl],
s=sl, color=0x60a5fa, printed=False, vol=round(met["vol_dm3"] * 1e6, 1),
note=note_ws + " 经纬线:经向 10°/条,纬向 8mm/环。",
grp="root", jaw=0.0, ex=[0.0, 0.0, 0.0], idx=mx + 1,
kind="line")
data["parts"] += [line]
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, separators=(",", ":"))
os.replace(tmp, path)
print("已写入", path, "大小 %.1f MB" % (os.path.getsize(path) / 1e6))
if __name__ == "__main__":
main()
+494
View File
@@ -0,0 +1,494 @@
# -*- coding: utf-8 -*-
"""Structural check of the printed arm, using section properties measured from the SOLIDS.
Nothing here is hand-waved from a sketch dimension: for each critical cut plane the part is
boolean-cut and the freshly created planar face is taken and integrated with
BRepGProp.SurfaceProperties_s, so area, centroid and the second moments are the real
section of the real printed part (including whatever the lightening windows left behind).
Why the allowables are so low: a printed part is not the material datasheet. Bending
across layers, an un-filleted internal corner (Kt ~ 2.5 measured on square corners), and
PLA creep under permanent static load together cut 35-50 MPa down to single digits, which
is exactly the failure mode to design against. See docs/strength.md.
Run: python strength.py -> docs/strength.md (+ console table)
"""
import io
import json
import math
import os
import re
import sys
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
import cadquery as cq
from arm.paths import OUT, WEB, DOCS
from arm.cad.helpers import solids_of, bb, mesh_of
from OCP.BRepAlgoAPI import BRepAlgoAPI_Common
from OCP.BRepGProp import BRepGProp
from OCP.GProp import GProp_GProps
from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox
from OCP.gp import gp_Pnt, gp_Dir, gp_Ax2, gp_Vec
from arm import kinematics as HL
RHO = {"PLA": 1.24e-3, "motor_g": 210.0} # g/mm3 for printed, g per module
# a slicer does not print solid: 3 perimeters + 30% infill lands near this fraction of
# the CAD envelope, and using the solid mass would blame the part for plastic that is not there
INFILL = float(os.environ.get("ARMINFILL", "0.38"))
# allowable bending stress across the print layers, after notch + creep derating
ALLOW = {"PLA": 12.0, "PETG": 20.0, "PA_CF": 30.0} # MPa
# Young's modulus of the printed lattice, for the deflection estimate only
EMOD = {"PLA": 3000.0, "PETG": 2100.0, "PA_CF": 8000.0} # MPa
MAT = os.environ.get("ARMMAT", "PLA")
PAYLOAD = float(os.environ.get("ARMPAY", "0.5")) # kg held at the fingertip
DYN = float(os.environ.get("ARMDYN", "2.0")) # dynamic factor on the moving mass
G981 = 9.81
GRIP_T = 12.0 # N*mm per motor is far too small to matter; the grip force
# case is carried separately below as a normal force at the pad
_cache = {}
GRP = {"root": 0, "J1": 1, "J2": 2, "J3": 3, "J4": 4, "J5": 5, "J6": 6}
def load(name):
if name not in _cache:
_cache[name] = cq.importers.importStep("%s/parts_step/%s.step" % (OUT, name)).val()
return _cache[name]
def volume(sh):
p = GProp_GProps()
BRepGProp.VolumeProperties_s(sh.wrapped, p)
return p.Mass()
def _caps_at(sh, n, o, t):
"""The section faces of (solid ∩ thin slab), taken on the +normal side of the slab.
Two things this replaces. (1) 'Zero extent along the normal' on a HALF-SPACE cut also
matches the part's own horizontal faces (top chord, gusset crowns) sitting anywhere above
the plane - that over-read the shoulder fork by 2.4x (480 mm2 true vs 1155 reported).
(2) The half-space Common outright fails on the filleted fork at z=600 (returns an empty
shape) while a thin slab of the same solid cuts fine.
A slab is also self-checking: its volume / t must equal the integrated area.
"""
c0 = sum(n[k] * o[k] for k in range(3))
lo, hi = [], []
for k in range(3):
if n[k] > 0:
lo.append(o[k] - t / 2.0); hi.append(o[k] + t / 2.0)
elif n[k] < 0:
lo.append(o[k] - t / 2.0); hi.append(o[k] + t / 2.0)
else:
lo.append(o[k] - 400.0); hi.append(o[k] + 400.0)
box = BRepPrimAPI_MakeBox(gp_Pnt(*lo), gp_Pnt(*hi)).Shape()
cut = BRepAlgoAPI_Common(sh.wrapped, box)
cut.Build()
if not cut.IsDone():
return []
off = c0 + t / 2.0
out = []
for f in cq.Shape(cut.Shape()).Faces():
if f.geomType() != "PLANE" or f.Area() <= 1e-6:
continue
cx, cy, cz = f.Center().toTuple()
if abs(n[0] * cx + n[1] * cy + n[2] * cz - off) > 1e-4:
continue
out.append(f)
return out
def section_props(sh, normal, origin, bend=2, size=400.0):
"""Cut the solid with a thin slab and integrate the section face.
Returns (area mm2, Ixx mm4, Iyy mm4, cmax mm, bbox) about the face centroid, with the
in-plane axes taken as (u, v) where u x v = normal.
"""
n = [float(x) for x in normal]
o = [float(x) for x in origin]
caps = []
for t in (0.2, 0.05, 1.0):
for nudge in (0.0, 0.05, -0.05, 0.25, -0.25):
oo = [o[k] + nudge * n[k] for k in range(3)]
caps = _caps_at(sh, n, oo, t)
if caps:
break
if caps:
break
if not caps:
return None
plane_ax = [k for k in (0, 1, 2) if abs(n[k]) < 0.5]
p_ax, q_ax = plane_ax
bend_ax = bend if bend in plane_ax else q_ax
far_ax = p_ax if bend_ax == q_ax else q_ax
A = Sv = Suu = Svv = S = 0.0
for f in caps:
verts, tris = mesh_of(f, 0.02)
fa = fu = fv = fuu = fvv = 0.0
for t in tris:
(u1, v1), (u2, v2), (u3, v3) = [(verts[k][p_ax], verts[k][q_ax]) for k in t]
ar = ((u2 - u1) * (v3 - v1) - (u3 - u1) * (v2 - v1)) / 2.0
fa += ar # SIGNED: inner wires (holes) cancel
fu += ar * (u1 + u2 + u3) / 3.0
fv += ar * (v1 + v2 + v3) / 3.0
fvv += ar * (v1**2 + v2**2 + v3**2 + v1*v2 + v2*v3 + v3*v1) / 6.0
fuu += ar * (u1**2 + u2**2 + u3**2 + u1*u2 + u2*u3 + u3*u1) / 6.0
if fa < 0: # face normal opposed to the cut normal
fa, fu, fv, fvv, fuu = -fa, -fu, -fv, -fvv, -fuu
A += fa; S += fu; Sv += fv; Svv += fvv; Suu += fuu
if A <= 1e-9:
return None
uc, vc = S / A, Sv / A
best = max(caps, key=lambda f: f.Area()) # only for the bounding box below
allb = [f.BoundingBox() for f in caps]
lo = [min(getattr(b, ("xmin", "ymin", "zmin")[k]) for b in allb) for k in range(3)]
hi = [max(getattr(b, ("xmax", "ymax", "zmax")[k]) for b in allb) for k in range(3)]
cmax = max(hi[far_ax] - uc if far_ax == p_ax else hi[far_ax] - vc,
uc - lo[far_ax] if far_ax == p_ax else vc - lo[far_ax]) / 1.0
# distance from the neutral axis to the extreme fibre, measured in the bending direction
ext = (hi[far_ax] - lo[far_ax])
cen = uc if far_ax == p_ax else vc
cmax = max(hi[far_ax] - cen, cen - lo[far_ax])
I = (Svv - A * vc * vc) if far_ax == q_ax else (Suu - A * uc * uc)
return dict(A=A, I=I, c=cmax, bend=bend_ax, centroid=(uc, vc))
def arm_masses():
"""Everything distal to each joint, in grams, from the model itself."""
meta = json.load(io.open(WEB + "/mesh_arm.json", encoding="utf-8"))
TREE = ["root", "J1", "J2", "J3", "J4", "J5", "J6"]
tot = {}
for p in meta["parts"]:
if not os.path.exists("%s/parts_step/%s.step" % (OUT, p["name"])):
continue # 螺钉实例 / 可达包络网格等非 CAD 构件没有 STEP,跳过
sh = load(p["name"])
v = volume(sh) / 1000.0
g = (v * RHO["PLA"] * 1000.0 * INFILL) if p["printed"] else RHO["motor_g"]
tot[p["name"]] = (g, p["grp"])
out = {}
for k, jid in enumerate(TREE[1:], 1):
down = set(TREE[k:])
out[jid] = sum(g for g, grp in tot.values() if grp in down)
out["all"] = sum(g for g, _ in tot.values())
return out, tot
# ------------------------------------------------------------------ 零件表:质量 + 零位世界质心
def _mesh_vol_cg(v, t):
"""四面体法求闭合三角网格的体积与体积加权质心。
网格顶点已在零位世界系(mesh_arm.json 由 arm_model 直接落盘),所以质心就是零件
在装配中的真实位置。实测体积与 STEP/BOM 差 <0.1%(电机包络 1.7%),可作载荷输入。
"""
vol = mx = my = mz = 0.0
for a, b, c in t:
x1, y1, z1 = v[a]
x2, y2, z2 = v[b]
x3, y3, z3 = v[c]
det = x1 * (y2 * z3 - y3 * z2) - x2 * (y1 * z3 - y3 * z1) + x3 * (y1 * z2 - y2 * z1)
vol += det
mx += (x1 + x2 + x3) * det
my += (y1 + y2 + y3) * det
mz += (z1 + z2 + z3) * det
if vol <= 0.0:
return 0.0, None
V = vol / 6.0
return V, (mx / (24.0 * V), my / (24.0 * V), mz / (24.0 * V))
def part_table(payload_kg=None):
"""[(name, mass_g, cg_xyz, grp)],含末端负载这个集中质量点。"""
meta = json.load(io.open(WEB + "/mesh_arm.json", encoding="utf-8"))
rows = []
for p in meta["parts"]:
nm = p["name"]
if nm.startswith("ENV_") or not p.get("v") or not p.get("t") or p.get("vol", 0) <= 0:
continue # 可达包络网格 / 无实体螺钉实例,不承载
V, cg = _mesh_vol_cg(p["v"], p["t"])
if V <= 0.0 or cg is None:
continue
if p.get("printed"):
m = V * RHO["PLA"] * INFILL
elif re.match(r"^M\d", nm):
m = RHO["motor_g"]
else:
continue
rows.append([nm, m, cg, GRP.get(p["grp"], 0)])
if payload_kg:
rows.append(["PAYLOAD", payload_kg * 1000.0,
(HL.X_ARM, HL.Y_AXIS, HL.Z_TIP), 6])
return rows
# ------------------------------------------------------------------ 运动学:产品外参链
def _rodrigues(deg, d, p):
"""绕世界轴 d 过点 p 转 deg -> (R, t),使 x -> R x + t。"""
n = math.sqrt(sum(c * c for c in d)) or 1.0
x, y, z = d[0] / n, d[1] / n, d[2] / n
a = math.radians(deg)
c, s = math.cos(a), math.sin(a)
t1 = 1.0 - c
R = [[t1 * x * x + c, t1 * x * y - s * z, t1 * x * z + s * y],
[t1 * x * y + s * z, t1 * y * y + c, t1 * y * z - s * x],
[t1 * x * z - s * y, t1 * y * z + s * x, t1 * z * z + c]]
t = [p[i] - (R[i][0] * p[0] + R[i][1] * p[1] + R[i][2] * p[2]) for i in range(3)]
return R, t
def chain(ang):
"""acc[g] = (R, t):第 g 组零件的刚体变换。
acc[g] = acc[g-1] o R_g(产品外参,右侧先作用),与 sweep_v2.accum_trsf、
查看器嵌套 pivot 三者一致。
"""
R = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
t = [0.0, 0.0, 0.0]
out = [(R, t)]
for j in range(1, 7):
ax = HL.AXIS["J%d" % j]
Rj, tj = _rodrigues(ang.get(j, 0.0), ax["d"], ax["rear"])
Rn = [[sum(R[i][k] * Rj[k][j2] for k in range(3)) for j2 in range(3)] for i in range(3)]
tn = [sum(R[i][k] * tj[k] for k in range(3)) + t[i] for i in range(3)]
R, t = Rn, tn
out.append((R, t))
return out
def _xf(T, c):
R, t = T
return [sum(R[i][k] * c[k] for k in range(3)) + t[i] for i in range(3)]
def _dir(T, v):
"""只取旋转部分——方向向量绝不能带平移,否则投影出的"力矩"会被平移量放大。"""
R = T[0]
return [sum(R[i][k] * v[k] for k in range(3)) for i in range(3)]
def _cross(a, b):
return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
def joint_loads(parts, payload_kg=None):
"""在可达姿态网格上搜索,返回每个关节的:
F 该关节以下的总重力 (N)(与姿态无关)
Mxyz 重力对关节轴点取矩后,三个全局分量各自的最大绝对值 (N*mm)
tau 重力绕该关节自身轴的最大力矩 (N*mm) —— 电机真正要出的力
Lp 出现 tau 最大值时,TCP 到该关节轴点的距离 (mm)
为什么搜索姿态:力臂不是常数。J1 是绕 X 的自转轴,手臂在轴正下方时重力对它
只产生绕 X 的扭矩(不产生弯曲),手臂摆到侧方时扭矩最大。旧算法把全部 distal
质量当作集中在指尖,量级完全错掉。
"""
trv = {t["axis"]: t for t in json.load(io.open(DOCS + "/travel.json", encoding="utf-8"))}
def picks(j):
t = trv.get("J%d" % j, {"lo": -180.0, "hi": 180.0})
if t.get("continuous"):
return [0.0, 60.0, -60.0, 120.0, -120.0, 180.0]
lo, hi = t["lo"], t["hi"]
return sorted({lo, 0.0 if lo < 0 < hi else lo, hi, 0.5 * (lo + hi)})
grid = [picks(j) for j in range(1, 7)]
res = {}
for j in range(1, 7):
res["J%d" % j] = dict(F=0.0, Mxyz=[0.0, 0.0, 0.0], tau=0.0, Lp=0.0, I=0.0, Iarm=0.0)
import itertools
for combo in itertools.product(*grid):
ang = {k + 1: v for k, v in enumerate(combo)}
acc = chain(ang)
pos = [(nm, m, _xf(acc[g], cg), g) for nm, m, cg, g in parts]
tcp = None
for nm, m, c, g in pos:
if nm == "PAYLOAD":
tcp = c
for j in range(1, 7):
ax = HL.AXIS["J%d" % j]
pj = _xf(acc[j - 1], ax["rear"])
dj = _dir(acc[j - 1], ax["d"])
F = M = [0.0, 0.0, 0.0]
wsum = 0.0
I = Iarm = 0.0
for _nm, m, c, g in pos:
if g < j:
continue
w = m * G981 / 1000.0
wsum += w
r = [c[i] - pj[i] for i in range(3)]
proj = sum(r[i] * dj[i] for i in range(3))
perp2 = sum(r[i] * r[i] for i in range(3)) - proj * proj
I += m * perp2 / 1e9 # g*mm^2 -> kg*m^2
if _nm != "PAYLOAD":
Iarm += m * perp2 / 1e9
rc = _cross(r, [0.0, 0.0, -w])
for i in range(3):
M[i] += rc[i]
r = res["J%d" % j]
r["F"] = max(r["F"], wsum)
for i in range(3):
r["Mxyz"][i] = max(r["Mxyz"][i], abs(M[i]))
tau = abs(M[0] * dj[0] + M[1] * dj[1] + M[2] * dj[2])
if tau > r["tau"]:
r["tau"] = tau
r["Lp"] = math.dist(tcp, pj) if tcp else 0.0
r["I"] = max(r["I"], I)
r["Iarm"] = max(r["Iarm"], Iarm)
return res
def section_moment(jid, bend_axis, ref, refgrp, parts):
"""截面绕自身形心、沿 bend_axis 的弯矩最大值 (N*mm),以及该姿态下 TCP 到该
截面的距离 (mm)(挠度估算用)。
参考点取【剖面形心】而不是关节轴:这两个参考点差得很远。P03 在 z=480 的剖面
形心 x≈-111,而臂身所有零件质心 x≈+19.5,真实力臂 130mm;若误用关节轴点
(J1 在 x=-51)只会得到 70mm,把弯矩低估 1.85 倍。
"""
trv = {t["axis"]: t for t in json.load(io.open(DOCS + "/travel.json", encoding="utf-8"))}
jj = int(jid[1])
def picks(j):
t = trv.get("J%d" % j, {"lo": -180.0, "hi": 180.0})
if t.get("continuous"):
return [0.0, 60.0, -60.0, 120.0, -120.0, 180.0]
lo, hi = t["lo"], t["hi"]
return sorted({lo, 0.0 if lo < 0 < hi else lo, hi, 0.5 * (lo + hi)})
import itertools
best = 0.0
best_L = 0.0
for combo in itertools.product(*[picks(j) for j in range(1, 7)]):
acc = chain({k + 1: v for k, v in enumerate(combo)})
rw = _xf(acc[refgrp], ref)
s = 0.0
tcp = rw
for nm, m, cg, g in parts:
if g < jj:
continue
c = _xf(acc[g], cg)
if nm == "PAYLOAD":
tcp = c
s += m * (c[bend_axis] - rw[bend_axis])
if abs(s) > best:
best = abs(s)
best_L = math.dist(tcp, rw)
return best * G981 / 1000.0, best_L
# critical cuts: (label, part, plane normal, plane origin, which load case owns it)
def cuts():
"""(label, part, cut-plane normal, point, joint whose load it carries, bend axis)
bend axis: 0=X (roll of the shoulder/forearm), 1=Y (every pitch joint), 2=Z."""
Y = HL.Y_AXIS
return [
("吊臂根座 @z=480", "P03_肩吊臂_螺旋体35%_墙5底5_竖打", (0, 0, 1), (0.0, 55.0, 480.0), "J1", 1),
("吊臂颊板 @z=560", "P03_肩吊臂_螺旋体35%_墙5底5_竖打", (0, 0, 1), (0.0, 100.0, 560.0), "J1", 1),
("肩叉腹板 @z=560", "P04_肩叉_螺旋体30%_墙5底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 560.0), "J2", 1),
("肩叉腹板 @z=600", "P04_肩叉_螺旋体30%_墙5底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 600.0), "J2", 1),
("大臂旋转座横梁 @z=480", "P05_大臂旋转座_螺旋体30%_墙4底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 480.0), "J2", 1),
("大臂旋转座套筒 @z=440", "P05_大臂旋转座_螺旋体30%_墙4底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 440.0), "J3", 1),
("大臂骨架中段 @z=350", "P06_大臂骨架_螺旋体25%_墙4底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 350.0), "J3", 1),
("大臂骨架抱箍 @z=325", "P06_大臂骨架_螺旋体25%_墙4底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 325.0), "J4", 1),
# 【2026-10-02 补】P06 原减重窗在 Z358~374,原有剖面(350/325)全在它下面,
# 根本校核不到被挖的区域。z=365 穿过该段过渡块,承载同 J3。
# 【2026-10-03】减重窗已取消、该段恢复实心,此剖面保留为该高度的安全裕度监控点。
("大臂骨架过渡块 @z=365", "P06_大臂骨架_螺旋体25%_墙4底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 365.0), "J3", 1),
("小臂骨架中段 @z=245", "P07_小臂骨架_螺旋体30%_墙5底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 245.0), "J4", 1),
("小臂骨架抱箍 @z=195", "P07_小臂骨架_螺旋体30%_墙5底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 195.0), "J5", 1),
# 【2026-10-02 补】P07 减重槽在 Z255~280,同理原有剖面(245/195)没覆盖到。
# z=270 穿过槽体本身,承载同 J4;z=280 是槽口所在的顶板上边缘,壁最薄。
("小臂骨架减重槽 @z=270", "P07_小臂骨架_螺旋体30%_墙5底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 270.0), "J4", 1),
("小臂骨架减重槽口 @z=280", "P07_小臂骨架_螺旋体30%_墙5底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 280.0), "J4", 1),
("腕偏转座根部 @z=150", "P08_腕偏转座_螺旋体25%_墙4底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 150.0), "J5", 1),
# P09 包络 z=93..121,剖面取 107(法兰中截面)。原 -55 落在零件之外,
# 剖切返回空,工具法兰其实一直没被校核过。
("工具法兰 @z=107", "P09_工具法兰_螺旋体30%_墙4底5_竖打", (0, 0, 1), (HL.X_ARM, Y, 107.0), "J6", 1),
]
MOMENT = { # worst reachable bending moment per joint, N*mm
# computed in main() from the reachable pose + masses
}
def main():
parts = part_table(PAYLOAD)
grpof = {nm: g for nm, _, _, g in parts}
jl = joint_loads(parts)
masses = {"J%d" % j: sum(m for _, m, _, g in parts if g >= j) for j in range(1, 7)}
masses["all"] = sum(m for _, m, _, _ in parts)
from concurrent.futures import ThreadPoolExecutor
def compute_cut(c_item):
lab, part, n, o, jid, bend = c_item
sh = load(part)
sp = section_props(sh, n, o, bend)
if not sp:
return (lab, part, None, jid)
# 剖面形心的三维重建 + 弯矩所绕的轴
nvec = [float(x) for x in n]
p_ax, q_ax = [k for k in (0, 1, 2) if abs(nvec[k]) < 0.5]
bend_ax = sp["bend"]
far_ax = p_ax if bend_ax == q_ax else q_ax # I 绕 bend_ax、c 沿 far_ax
ref = list(o)
ref[p_ax] += sp["centroid"][0]
ref[q_ax] += sp["centroid"][1]
M, L = section_moment(jid, far_ax, ref, grpof.get(part, 0), parts)
M *= DYN
F = jl[jid]["F"] * DYN
I, c = sp["I"], sp["c"]
sigma = M * c / max(I, 1e-6)
tau = 1.5 * F / sp["A"]
defl = M * L * L / (2.0 * EMOD[MAT] * I) if I > 1e-6 and L > 0 else 0.0
return (lab, part, dict(sp, M=M, F=F, sigma=sigma, tau=tau, L=L, defl=defl,
bend_axis=bend_ax, SF=ALLOW[MAT] / sigma if sigma > 0 else 99.0), jid)
with ThreadPoolExecutor(max_workers=min(13, os.cpu_count() or 4)) as executor:
rows = list(executor.map(compute_cut, cuts()))
print("材料 %s 许用弯曲 %g MPa(跨层、含缺口与蠕变折减) 弹性模量 %g MPa 末端负载 %g kg 动载系数 %g"
% (MAT, ALLOW[MAT], EMOD[MAT], PAYLOAD, DYN))
print("载荷模型:每个零件按真实质心(网格体积加权)随姿态变换,在可达姿态网格上取弯矩最大值;"
"参考点为剖面形心\n")
print("打印件按 %d%% 实体率计质量(壁+填充),电机按 %.0f g/台" % (INFILL * 100, RHO["motor_g"]))
print("%-24s %-9s %7s %10s %6s %9s %7s %6s %7s %7s"
% ("截面", "零件", "面积mm2", "I mm4", "c mm", "M N*mm", "sigma", "SF", "挠度mm", "需Z mm3"))
bad = []
for lab, part, d, jid in rows:
if not d:
print("%-24s %-9s 剖切失败" % (lab, part))
continue
Zreq = d["M"] / ALLOW[MAT] * 1.5 # section modulus x1.5 SF
print("%-24s %-9s %7.0f %10.0f %6.1f %9.0f %7.2f %6.2f %7.1f %7.0f%s"
% (lab, part[:9], d["A"], d["I"], d["c"], d["M"], d["sigma"], d["SF"], d["defl"],
Zreq, " <<< 不足" if d["SF"] < 1.5 else ""))
if d["SF"] < 1.5:
bad.append((lab, part, d))
print("\n各关节以下质量(g, 含电机与末端负载): "
+ " ".join("%s=%.0f" % (k, v) for k, v in masses.items() if k != "all"))
print("合计 %.0f g (其中末端负载 %.0f g)" % (masses["all"], PAYLOAD * 1000))
print("\n各关节电机需出的重力力矩(绕自身轴,姿态搜索最大值):")
for j in range(1, 7):
r = jl["J%d" % j]
print(" J%d %6.2f N·m (该关节以下总重 %.1f N,力臂 %.0f mm)"
% (j, r["tau"] / 1000.0, r["F"], r["Lp"]))
io.open(DOCS + "/strength.json", "w", encoding="utf-8").write(
json.dumps([dict(截面=a, 零件=b, 关节=d, **(c or {})) for a, b, c, d in rows],
ensure_ascii=False, indent=1, default=float))
return bad
if __name__ == "__main__":
b = main()
print("\n不合格截面 %d 处" % len(b))
# OCC/cadquery 的静态析构在解释器正常退出时必定段错误(实测:光是
# `python -c "import arm.cad.helpers"` 就返回 139,与本项目代码无关)。所以入口
# 脚本跑完后显式刷缓冲再 os._exit —— 否则全流程已经成功、exit code 却是 139,
# 会把上游脚本的 set -e 判成失败。只在 __main__ 出口生效, 被 import 时不触发。
sys.stdout.flush()
os._exit(0)
+726
View File
@@ -0,0 +1,726 @@
# -*- coding: utf-8 -*-
"""全对全动态行程扫描与碰撞验证(权威版 v2,多进程并行)
与旧 travel_sweep.py / real_arm_collision_test.py 的区别(旧脚本漏掉了用户实测到的干涉):
1. 直接在进程内构建当前模型(arm_model.build()),杜绝 STEP/网格过期;
2. 关节轴取自 Joint.rear/.d(human_layout 唯一事实源),与网页查看器逐位一致;
3. 检查【全部】零件对 —— 包括相邻关节的零件对与电机模组(旧脚本跳过相邻对,
而 P04xP05 / P07xP08 恰恰在关节贴面处被卡死);
4. 单关节双向精扫(粗扫 + 二分)得出真实硬限位;
5. 组合姿态扫描:每个关节置于其极限,再扫其余关节,收敛出滑块安全范围;
6. 写 docs/travel.json(查看器滑块范围)+ docs/travel_detail.json(逐对明细)。
网格化预筛(用户要求,2026-09):
- 每零件先按 0.5mm 容差网格化取顶点云(凸包顶点集);
- 候选对先跑 GJK(Minkowski 差 + 0.8mm 安全外扩):只有"凸包外扩后仍分离"
才允许跳过精确布尔 —— 该判据数学上保守(网格内缩 ≤0.5mm < 外扩 0.8mm),
其余情况(可能干涉/数值退化)一律回落 OCCT 实体会交,结果与纯布尔完全一致;
- --no-gjk 可关闭预筛(对比校验用)。
并行化(用户要求):
- mp.Pool 每个工作进程独立构建一次模型,角度任务批量分发(imap 保序);
- OCCT 布尔运算 SetRunParallel(True);
- 预剪枝:按关节轴计算每对零件的轴向/径向区间,区间不相交的零件对在该关节的
任何角度都不可能碰撞,直接跳过(对单关节扫描是精确安全的)。
台架(P01 立柱 / P02 底盘)代表躯干与机身的连接界面,默认【参与】碰撞计算——臂撞立柱
就是臂撞躯干,是真约束。--no-stand 仅用于诊断:排除台架后重扫,给出"不含躯干约束"的
自由空间行程,用来分辨某个限位是臂自身折叠产生的还是躯干挡的(台架位置本身是假设,
改它等于改测试工装,不等于改设计)。
运行:python -m arm.analysis.sweep_v2 [--workers 20] [--step 2] [--combo-step 6]
[--no-combos] [--joints J2,J4] [--no-gjk] [--no-stand]
"""
import json
import math
import os
import sys
import time
import numpy as np
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
import multiprocessing as mp
from arm.cad import arm_build as AB
import cadquery as cq
from arm import kinematics as HL
from arm.paths import DOCS
from arm.cad.helpers import place, bb
VOL_MIN = 2.0 # mm3,超过即计为干涉
CHAIN = ["root", "J1", "J2", "J3", "J4", "J5", "J6"]
MOUNT_PAIRS = {
("P03_肩吊臂_螺旋体35%_墙5底5_竖打", "M1_J1"), ("P04_肩叉_螺旋体30%_墙5底5_竖打", "M1_J1"),
("P04_肩叉_螺旋体30%_墙5底5_竖打", "M2_J2"), ("P05_大臂旋转座_螺旋体30%_墙4底5_竖打", "M2_J2"),
("P05_大臂旋转座_螺旋体30%_墙4底5_竖打", "M3_J3"), ("P06_大臂骨架_螺旋体25%_墙4底5_竖打", "M3_J3"),
("P06_大臂骨架_螺旋体25%_墙4底5_竖打", "M4_J4"), ("P07_小臂骨架_螺旋体30%_墙5底5_竖打", "M4_J4"),
("P07_小臂骨架_螺旋体30%_墙5底5_竖打", "M5_J5"), ("P08_腕偏转座_螺旋体25%_墙4底5_竖打", "M5_J5"),
("P08_腕偏转座_螺旋体25%_墙4底5_竖打", "M6_J6"), ("P09_工具法兰_螺旋体30%_墙4底5_竖打", "M6_J6"),
}
# 网格化预筛参数:外扩必须 ≥ 网格化偏差,判"分离"才保守可信
MESH_TOL = 0.5 # mm,零件网格化容差
MESH_MARGIN = 0.8 # mm,凸包安全外扩(> MESH_TOL 保证网格内缩不致漏判)
USE_GJK = True # 进程内全局;工作进程由 initializer 传入
INCLUDE_FIXTURE = True # True=把 P01 立柱/P02 底盘(代表躯干)算进碰撞;--no-stand 置 False
# ---------------------------------------------------------------- 网格化 + GJK
def tessellate_verts(shape):
"""零件 → 顶点云 (N,3)。凸包 GJK 的支撑函数直接在顶点云上取极值(等价于其凸包),
第二步做精确凸包精简(scipy Qhull):电机 STEP 网格 15 万顶点 → 约千余点。
顶点均为真实表面上的点,亦用作"顶点侵入"快证的采样点。"""
try:
vs, _ts = shape.tessellate(MESH_TOL)
v = np.asarray([(q.x, q.y, q.z) for q in vs], dtype=np.float64)
if v.size == 0:
return None
v = np.unique(v, axis=0)
try:
from scipy.spatial import ConvexHull
v = v[ConvexHull(v).vertices]
except Exception:
pass # 精简失败则用全顶点云(仍正确,仅慢)
return np.ascontiguousarray(v)
except Exception:
return None
def gjk_separated(va, vb, margin=MESH_MARGIN, max_iter=40):
"""凸包 GJK(带 margin):va/vb 顶点云。返回 True 仅当
conv(va)⊕Ball(margin) 与 conv(vb) 确证分离 —— 保守,可安全跳过精确布尔。
可能干涉 / 数值退化 / 迭代超限 一律返回 False,回落 OCCT 精确实体求交。"""
d = vb.mean(axis=0) - va.mean(axis=0)
nd = np.linalg.norm(d)
d = np.array([1.0, 0.0, 0.0]) if nd < 1e-9 else d / nd
s = [] # 单纯形顶点,s[-1] 为最新
for _ in range(max_iter):
pa = va[np.argmax(va @ d)]
pb = vb[np.argmax(vb @ (-d))]
w = pa - pb + margin * d # ⊕Ball(margin) 的支撑
if w @ d < 0.0: # Minkowski 差不含原点 → 确证分离
return True
s.append(w)
d, state = _do_simplex(s)
if state != "go":
return False # 'hit' 可能干涉 / 'stop' 退化 → 精确布尔
nd = np.linalg.norm(d)
if nd < 1e-9:
return False # 原点贴着单纯形 → 交给精确布尔
d = d / nd
return False
def _do_simplex(s):
"""GJK 单纯形约化(Muratori 形式)。返回 (下一方向 d, state):
'go' 继续 / 'hit' 原点可能在内(→ 精确布尔)/ 'stop' 数值退化(→ 精确布尔)。"""
n = len(s)
if n == 1:
return -s[0], "go"
if n == 2:
a, b = s[1], s[0]
ab, ao = b - a, -a
if ab @ ao > 0.0:
abv = np.cross(np.cross(ab, ao), ab)
return (None, "stop") if abv @ abv < 1e-18 else (abv, "go")
del s[0]
return -a, "go"
if n == 3:
a, b, c = s[2], s[1], s[0]
ab, ac, ao = b - a, c - a, -a
abv = np.cross(np.cross(ab, ao), ab)
acv = np.cross(np.cross(ac, ao), ac)
if abv @ ao > 0.0: # AB 边外侧
if ab @ ao > 0.0:
del s[0]
return (None, "stop") if abv @ abv < 1e-18 else (abv, "go")
s[:] = [a]
return -a, "go"
if acv @ ao > 0.0: # AC 边外侧
if ac @ ao > 0.0:
del s[1]
return (None, "stop") if acv @ acv < 1e-18 else (acv, "go")
s[:] = [a]
return -a, "go"
nrm = np.cross(ab, ac)
if nrm @ nrm < 1e-18:
return None, "stop"
return (nrm if nrm @ ao > 0.0 else -nrm), "go" # 三角面上/下方
# n == 4 四面体:原点与被排除顶点异侧的面即"外侧",约化到该面
a3, b3, c3, d3 = s[3], s[2], s[1], s[0]
for tri, e in (((a3, b3, c3), d3), ((a3, b3, d3), c3),
((a3, c3, d3), b3), ((b3, c3, d3), a3)):
u, v, w = tri
nrm = np.cross(v - u, w - u)
if nrm @ nrm < 1e-18:
continue
so = (-u) @ nrm
sd = (e - u) @ nrm
if abs(so) < 1e-12:
return None, "hit"
if so * sd < 0.0:
s[:] = [u, v, w]
return (nrm if so > 0.0 else -nrm), "go"
return None, "hit" # 原点在四面体内 → 可能干涉
# ---------------------------------------------------------------- 模型与上下文
def load_model(include_fixture=True):
"""include_fixture=False 时把 P01 立柱 / P02 底盘(固定测试台架,非本体)排除在
碰撞配对之外——用来得到真机工作空间而不是台架工作空间。见 human_layout.FIXTURE_PREFIX。"""
from arm import build_model as AM
JS = AM.build()
parts = []
for p in AB.PARTS:
if not include_fixture and HL.is_fixture(p["name"]):
continue
g = CHAIN.index(AB.GRP.get(p["name"], "root"))
lo, hi = bb(p["shape"])
corners = [(x, y, z) for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]
# 包围球(局部坐标):球心=包围盒中心,半径=半对角线。零件 ⊆ 包围球 恒成立,
# 球心随刚体变换、半径不变 —— 旋转下依旧精确保守,是最廉价的确定性预筛。
ctr = [(lo[k] + hi[k]) / 2.0 for k in range(3)]
rad = 0.5 * math.dist(lo, hi) + 0.21
verts = tessellate_verts(p["shape"])
parts.append(dict(name=p["name"], shape=p["shape"], g=g, c8=corners, box=(lo, hi),
ctr=ctr, rad=rad, verts=verts))
joints = {t: (JS[t].rear, JS[t].d) for t in CHAIN[1:]}
return parts, joints
def _trsf_verts(verts, t):
"""顶点云按 gp_Trsf 刚体变换(3x4 矩阵)。"""
m = np.array([[t.Value(r, c) for c in (1, 2, 3, 4)] for r in (1, 2, 3)])
return verts @ m[:, :3].T + m[:, 3]
def axis_intervals(parts, rear, d):
"""每个零件沿关节轴的 (轴向区间, 径向最小/最大距离)。要求 d 为坐标轴方向。"""
out = []
for p in parts:
lo, hi = p["box"]
if abs(d[0]) > 0.5:
ax = (lo[0] - rear[0], hi[0] - rear[0])
u = (lo[1], hi[1], rear[1]); v = (lo[2], hi[2], rear[2])
elif abs(d[1]) > 0.5:
ax = (lo[1] - rear[1], hi[1] - rear[1])
u = (lo[0], hi[0], rear[0]); v = (lo[2], hi[2], rear[2])
else:
ax = (lo[2] - rear[2], hi[2] - rear[2])
u = (lo[0], hi[0], rear[0]); v = (lo[1], hi[1], rear[1])
du = max(u[0] - u[2], 0.0, u[2] - u[1])
dv = max(v[0] - v[2], 0.0, v[2] - v[1])
rmin = math.hypot(du, dv)
rmax = max(math.hypot(a - u[2], b - v[2]) for a in (u[0], u[1]) for b in (v[0], v[1]))
out.append((ax, rmin, rmax))
return out
def make_ctx(include_fixture=True):
parts, joints = load_model(include_fixture)
impossible = {}
for k in range(1, len(CHAIN)):
rear, d = joints[CHAIN[k]]
iv = axis_intervals(parts, rear, d)
s = set()
for i in range(len(parts)):
for j in range(i + 1, len(parts)):
ga, gb = parts[i]["g"], parts[j]["g"]
lo, hi = (ga, gb) if ga < gb else (gb, ga)
if lo == hi or not (lo < k <= hi):
continue
ax_i, r_i = iv[i][0], (iv[i][1], iv[i][2])
ax_j, r_j = iv[j][0], (iv[j][1], iv[j][2])
if ax_i[1] < ax_j[0] or ax_j[1] < ax_i[0] or \
r_i[1] < r_j[0] or r_j[1] < r_i[0]:
s.add((i, j))
impossible[k] = s
return dict(parts=parts, joints=joints, impossible=impossible)
# ---------------------------------------------------------------- 姿态测试
def accum_trsf(joints, angles_by_idx):
"""链式累积变换:acc[i] = acc[i-1] ∘ R_i(与查看器嵌套 pivot 完全一致)。"""
acc = [None] * len(CHAIN)
for i in range(1, len(CHAIN)):
ang = angles_by_idx.get(i, 0.0)
if abs(ang) < 1e-9:
acc[i] = acc[i - 1]
continue
rear, d = joints[CHAIN[i]]
r = AB.R(ang, d[0], d[1], d[2], rear[0], rear[1], rear[2])
acc[i] = r if acc[i - 1] is None else acc[i - 1].Multiplied(r)
return acc
def xf_c8(c8, t):
from OCP.gp import gp_Pnt
gpt = [gp_Pnt(*c).Transformed(t) for c in c8]
lo = [min(p.X() for p in gpt), min(p.Y() for p in gpt), min(p.Z() for p in gpt)]
hi = [max(p.X() for p in gpt), max(p.Y() for p in gpt), max(p.Z() for p in gpt)]
return (lo, hi)
def common_vol_center(a, b):
"""交集体积 + 干涉质心;布尔失败返回 (-1, None)。"""
try:
from OCP.BRepAlgoAPI import BRepAlgoAPI_Common
c = BRepAlgoAPI_Common(a.wrapped, b.wrapped)
c.SetRunParallel(True)
c.Build()
if not c.IsDone() or c.Shape().IsNull():
return 0.0, None
sh = cq.Shape(c.Shape())
v = AB.vol_of(sh)
if v <= VOL_MIN:
return v, None
(lo, hi) = bb(sh)
return v, tuple(round((lo[i] + hi[i]) / 2.0, 1) for i in range(3))
except Exception:
return -1.0, None
def test_posture(ctx, angles_by_idx, want_errors=False, first_only=True):
"""返回 (violations, errors):violations = [(na, nb, vol, 干涉质心)]。
first_only:证实第一对干涉即返回(粗扫/二分只需要"卡没卡"的二元答案,卡死姿态
通常 12+ 对干涉、每对布尔 0.5~12s,全算完要 40s+;命中即返回降到 1~2s)。
零位诊断(want_errors=True)保持全对扫描以给出完整清单。"""
parts, joints, impossible = ctx["parts"], ctx["joints"], ctx["impossible"]
active = [k for k, a in angles_by_idx.items() if abs(a) > 1e-9]
acc = accum_trsf(joints, angles_by_idx)
boxes = []
sph = []
for p in parts:
t = acc[p["g"]]
boxes.append(p["box"] if t is None else xf_c8(p["c8"], t))
if t is None:
c = p["ctr"]
else: # 球心随组变换,半径旋转不变
c = _trsf_verts(np.array([p["ctr"]], dtype=np.float64), t)[0]
sph.append((c[0], c[1], c[2], p["rad"]))
shapes = {}
wverts = {} # 顶点云世界坐标缓存(本姿态内复用)
viol, errs = [], []
n = len(parts)
for i in range(n):
gi = parts[i]["g"]
for j in range(i + 1, n):
gj = parts[j]["g"]
lo, hi = (gi, gj) if gi < gj else (gj, gi)
if lo == hi:
continue
na, nb = parts[i]["name"], parts[j]["name"]
if na.startswith("M") and nb.startswith("M"):
continue
if (na, nb) in MOUNT_PAIRS or (nb, na) in MOUNT_PAIRS:
continue
span = [k for k in active if lo < k <= hi]
# 关键:无活动关节(零位)时必须测试全部零件对 —— 相对位姿不变不代表不干涉!
if active and not span:
continue
if len(span) == 1 and (i, j) in impossible[span[0]]:
continue
bi, bj = boxes[i], boxes[j]
if any(bi[1][k] < bj[0][k] - 0.1 or bj[1][k] < bi[0][k] - 0.1 for k in range(3)):
continue
sa, sb = sph[i], sph[j] # 包围球预筛:零件 ⊆ 球,球分离 ⇒ 零件必分离
dxx = sa[0] - sb[0]; dyy = sa[1] - sb[1]; dzz = sa[2] - sb[2]
rr = sa[3] + sb[3] + 0.1
if dxx * dxx + dyy * dyy + dzz * dzz > rr * rr:
continue
if USE_GJK: # 网格化预筛:确证分离则免精确布尔
for key, gk in ((i, gi), (j, gj)):
if key not in wverts:
t = acc[gk]
lv = parts[key]["verts"]
wverts[key] = None if lv is None else (
lv if t is None else _trsf_verts(lv, t))
vi, vj = wverts[i], wverts[j]
if vi is not None and vj is not None and gjk_separated(vi, vj):
continue
si = shapes.get(i)
if si is None:
t = acc[gi]
si = parts[i]["shape"] if t is None else place(parts[i]["shape"], t)
shapes[i] = si
sj = shapes.get(j)
if sj is None:
t = acc[gj]
sj = parts[j]["shape"] if t is None else place(parts[j]["shape"], t)
shapes[j] = sj
# 顶点侵入快证:一方的网格顶点(真实表面上的点)落入对方实体内部即实锤干涉,
# 免掉 4~12s 的 NURBS 布尔。深入重叠时前几十个采样点即命中早退;分类器按
# 零件缓存(每姿态构建一次)。判"自由"无证明力 —— 无命中则照旧精确布尔。
jam = False
try:
from OCP.BRepClass3d import BRepClass3d_SolidClassifier
from OCP.gp import gp_Pnt
from OCP.TopAbs import TopAbs_State
for pi_, pj_ in ((i, j), (j, i)):
pts = wverts.get(pi_)
if pts is None or not len(pts):
continue
ckey = (pj_, id(acc[parts[pj_]["g"]]))
if ckey not in classifiers:
classifiers[ckey] = BRepClass3d_SolidClassifier(shapes[pj_].wrapped)
cls = classifiers[ckey]
stepk = max(1, len(pts) // 240)
for k in range(0, len(pts), stepk):
p = pts[k]
# Perform(pnt, tol=1.0):距边界 <1mm 的点归为 ON(配合贴面不算),
# 只有深入 >1mm 的顶点才实锤干涉 —— 与 VOL_MIN 语义对齐
cls.Perform(gp_Pnt(p[0], p[1], p[2]), 1.0)
if cls.State() == TopAbs_State.TopAbs_IN:
jam = True
break
if jam:
break
except Exception:
jam = False
if jam:
viol.append((parts[i]["name"], parts[j]["name"], -1.0, None))
if first_only and not want_errors:
return viol
continue
v, center = common_vol_center(si, sj)
if v < 0:
errs.append((parts[i]["name"], parts[j]["name"]))
continue
if v > VOL_MIN:
viol.append((parts[i]["name"], parts[j]["name"], round(v, 1), center))
if first_only and not want_errors:
return viol
return (viol, errs) if want_errors else viol
# ---------------------------------------------------------------- 工作进程
_CTX = None
_POOL = None
_WORKERS = 4
def _init_worker(use_gjk=True, include_fixture=True):
global _CTX, USE_GJK
USE_GJK = bool(use_gjk)
_CTX = make_ctx(include_fixture)
def _task(task):
angles = {int(k): v for k, v in task["a"].items()}
return task["id"], test_posture(_CTX, angles) # 带id回传,配合 imap_unordered 实时进度
def get_pool(workers):
global _POOL, _WORKERS
_WORKERS = workers
if _POOL is None and workers > 1:
_POOL = mp.Pool(workers, initializer=_init_worker, initargs=(USE_GJK, INCLUDE_FIXTURE))
return _POOL
def eval_angles(angles_list, workers, chunk=None, label="姿态"):
"""批量评估姿态列表 [{idx: ang}],按输入顺序返回 violations 列表。
进度展示:imap_unordered 按完成序实时回报,≥4 个姿态的批次每 2s 滚动打印一次
真实完成数(短批次与二分不打扰输出)。"""
tasks = [dict(id=i, a={str(k): v for k, v in a.items()}) for i, a in enumerate(angles_list)]
n = len(tasks)
if workers <= 1:
ctx = _ctx_single()
out = []
t0 = time.time()
for i, a in enumerate(angles_list):
out.append(test_posture(ctx, a))
if n >= 4 and ((i + 1) % max(1, n // 10) == 0 or i + 1 == n):
print(" %s %d/%d [%.0fs]" % (label, i + 1, n, time.time() - t0),
end="\r" if i + 1 < n else "\n", flush=True)
return out
pool = get_pool(workers)
out = [None] * n
cs = chunk or max(1, n // (workers * 4) or 1)
t0, t_last, done_n = time.time(), time.time(), 0
for id_, viol in pool.imap_unordered(_task, tasks, chunksize=cs):
out[id_] = viol
done_n += 1
now = time.time()
if n >= 4 and (now - t_last >= 2.0 or done_n == n):
print(" %s %d/%d [%.0fs]" % (label, done_n, n, now - t0),
end="\r" if done_n < n else "\n", flush=True)
t_last = now
return out
def _ctx_single():
global _CTX
if _CTX is None:
_CTX = make_ctx(INCLUDE_FIXTURE)
return _CTX
# ---------------------------------------------------------------- 扫描逻辑
def bisect(workers, k, a_free, a_jam, tol=0.2):
n = 0
while abs(a_jam - a_free) > tol:
n += 1
mid = 0.5 * (a_free + a_jam)
print(" %s 二分#%d 区间 [%.2f, %.2f]°" % (CHAIN[k], n, a_free, a_jam), flush=True)
if eval_angles([{k: mid}], workers, label="%s二分" % CHAIN[k])[0]:
a_jam = mid
else:
a_free = mid
return a_free
def sweep_single(k, step, workers):
t_start = time.time()
jams = {}
lo = hi = 0.0
tag = CHAIN[k]
for sign in (+1, -1):
angles = [sign * step * i for i in range(1, int(180.0 / step) + 1)]
stop, a_free = None, 0.0
B = max(workers, 8) # 小批次:首个卡死角即停,少算深度卡死姿态
for s in range(0, len(angles), B):
batch = angles[s:s + B]
results = eval_angles([{k: a} for a in batch], workers,
label="%s%s向粗扫" % (tag, "正" if sign > 0 else "反"))
done = min(s + B, len(angles))
print(" %s %s向 %d/%d 角度(%2.0f%%)[已用 %.0fs]"
% (tag, "正" if sign > 0 else "反", done, len(angles),
100.0 * done / len(angles), time.time() - t_start), flush=True)
for a, viol in zip(batch, results):
if viol:
jams[a] = viol
print(" %s %s向在 %.1f° 首次干涉:%s"
% (tag, "正" if sign > 0 else "反", a,
"; ".join("%sx%s(%s)" % (p, q, "顶点侵入" if v < 0 else "%.0fmm3" % v)
for p, q, v, _c in viol[:3])),
flush=True)
# 二分区间 = [本方向最后自由角, 首个卡死角] —— 修复原 sign*(a-step)
# 在负方向算出未测过的另一侧角度、把二分踢进远端慢区的问题
stop = bisect(workers, k, a_free, a)
break
a_free = a
if stop is not None:
break
if stop is None:
stop = a_free
if sign > 0:
hi = stop
else:
lo = stop
print(" => %s 硬限位 [%7.2f, %7.2f],耗时 %.0fs" % (tag, lo, hi, time.time() - t_start),
flush=True)
return dict(lo=lo, hi=hi, jams=jams)
def sweep_combo(k_hold, e_hold, j_sweep, a_lo, a_hi, step, workers):
jams = {}
res = {}
tag = "%s@%.0f° 扫%s" % (CHAIN[k_hold], e_hold, CHAIN[j_sweep])
for sign, lim in ((+1, a_hi), (-1, a_lo)):
angles = [sign * step * i for i in range(1, int(abs(lim) / step) + 1)] if abs(lim) > 1e-6 else []
stop, a_free = None, 0.0
B = max(workers, 8) # 小批次:首个卡死角即停,少算深度卡死姿态
for s in range(0, len(angles), B):
batch = angles[s:s + B]
results = eval_angles([{k_hold: e_hold, j_sweep: a} for a in batch], workers,
label=tag)
done = min(s + B, len(angles))
print(" %s %s向 %d/%d(%2.0f%%)"
% (tag, "正" if sign > 0 else "反", done, len(angles),
100.0 * done / max(len(angles), 1)), flush=True)
for a, viol in zip(batch, results):
if viol:
jams[a] = viol
lo_f, hi_j = a_free, a # 同 sweep_single:用本方向最后自由角
while abs(hi_j - lo_f) > 0.5:
mid = 0.5 * (lo_f + hi_j)
if eval_angles([{k_hold: e_hold, j_sweep: mid}], workers,
label="%s组合二分" % tag)[0]:
hi_j = mid
else:
lo_f = mid
stop = lo_f
break
a_free = a
if stop is not None:
break
if stop is None:
stop = a_free
res[sign] = stop
return res[+1], res[-1], jams
def main():
t0 = time.time()
step, combo_step = 2.0, 6.0
do_combos = "--no-combos" not in sys.argv
want_joints = None
if "--no-gjk" in sys.argv:
global USE_GJK
USE_GJK = False
if "--no-stand" in sys.argv:
global INCLUDE_FIXTURE
INCLUDE_FIXTURE = False
# 内存感知的默认进程数:每个工作进程预留 ~2.5GB 峰值(建模+布尔瞬时开销)
avail_gb = 16.0
try:
import ctypes
class _MS(ctypes.Structure):
_fields_ = [("dwLength", ctypes.c_uint32), ("dwMemoryLoad", ctypes.c_uint32),
("ullTotalPhys", ctypes.c_uint64), ("ullAvailPhys", ctypes.c_uint64),
("ullTotalPageFile", ctypes.c_uint64), ("ullAvailPageFile", ctypes.c_uint64),
("ullTotalVirtual", ctypes.c_uint64), ("ullAvailVirtual", ctypes.c_uint64),
("ullAvailExtendedVirtual", ctypes.c_uint64)]
_ms = _MS()
_ms.dwLength = ctypes.sizeof(_MS)
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(_ms))
avail_gb = _ms.ullAvailPhys / 2**30
except Exception:
pass
mem_cap = max(2, int(avail_gb / 2.5))
workers = max(1, min(12, (os.cpu_count() or 4) - 2, mem_cap))
for i, a in enumerate(sys.argv):
if a == "--step":
step = float(sys.argv[i + 1])
if a == "--combo-step":
combo_step = float(sys.argv[i + 1])
if a == "--workers":
workers = int(sys.argv[i + 1])
if a == "--joints":
want_joints = set(sys.argv[i + 1].split(","))
print("=" * 78)
print("全对全动态行程扫描 v2 并行版(workers=%d / 可用内存 %.0fGB / 轴=human_layout / 含相邻对与电机 / GJK预筛=%s)"
% (workers, avail_gb, "开" if USE_GJK else "关"))
print("=" * 78, flush=True)
print("启动 %d 个工作进程并行建模(每进程独立构建全模型+凸包网格,约 20~60s)..." % workers,
flush=True)
if workers > 1:
get_pool(workers) # 启动工作进程(各自并行建模,父进程不重复建模)
# 零位检查
v0 = eval_angles([{}], workers)[0]
print("[零位检查] %s" % ("0 对干涉 ✓" if not v0 else "干涉: %s" % v0), flush=True)
singles = {}
print("\n[单关节硬限位] 粗扫 %.1f° + 二分 0.2°" % step, flush=True)
for k in range(1, len(CHAIN)):
tag = CHAIN[k]
if want_joints and tag not in want_joints:
continue
r = sweep_single(k, step, workers)
singles[tag] = r
jam_s = "; ".join(
"%s%.1f°:%s" % ("+" if a > 0 else "", a,
",".join("%sx%s@%s(%s)" % (p, q, c,
"侵入" if v < 0 else "%.0f" % v)
for p, q, v, c in vs[:2]))
for a, vs in sorted(r["jams"].items())[:4])
print(" %-3s lo=%7.2f hi=%7.2f %s [%.0fs]" % (tag, r["lo"], r["hi"],
("卡死: " + jam_s) if jam_s else "整周无干涉 → 360° 连续", time.time() - t0), flush=True)
if want_joints:
json.dump(dict(generated=time.strftime("%Y-%m-%d %H:%M:%S"),
singles={t: dict(lo=round(singles[t]["lo"], 2),
hi=round(singles[t]["hi"], 2),
jams={str(a): v for a, v in singles[t]["jams"].items()})
for t in singles}),
open(DOCS + "/travel_probe.json", "w", encoding="utf-8"),
ensure_ascii=False, indent=1)
print("\n[诊断模式] 明细已写出 docs/travel_probe.json [%.0fs]" % (time.time() - t0))
return
limits = {t: [singles[t]["lo"], singles[t]["hi"]] for t in CHAIN[1:]}
combos_log = []
if do_combos:
print("\n[组合姿态收敛] 保持一个关节于极限,扫其余关节(步长 %.1f°)" % combo_step, flush=True)
for pass_i in range(2):
changed = False
for k in range(1, len(CHAIN)):
tag_k = CHAIN[k]
for e in (limits[tag_k][0], limits[tag_k][1]):
if abs(e) < 5.0:
continue
for j in range(1, len(CHAIN)):
if j == k:
continue
tag_j = CHAIN[j]
lo_j, hi_j = limits[tag_j]
if abs(lo_j) < 5.0 and abs(hi_j) < 5.0:
continue
pos, neg, jams = sweep_combo(k, e, j, lo_j, hi_j, combo_step, workers)
for sign, free, lim in ((+1, pos, hi_j), (-1, neg, lo_j)):
new = free - 1.0
if sign > 0 and new < limits[tag_j][1] - 0.01:
combos_log.append(dict(pass_=pass_i, hold=tag_k, hold_at=e,
swept=tag_j, direction="hi",
old=limits[tag_j][1], new=max(new, 0.0),
jams={str(a): v for a, v in jams.items()}))
limits[tag_j][1] = max(new, 0.0)
changed = True
if sign < 0 and new > limits[tag_j][0] + 0.01:
combos_log.append(dict(pass_=pass_i, hold=tag_k, hold_at=e,
swept=tag_j, direction="lo",
old=limits[tag_j][0], new=min(new, 0.0),
jams={str(a): v for a, v in jams.items()}))
limits[tag_j][0] = min(new, 0.0)
changed = True
print(" hold %s done [%.0fs]" % (tag_k, time.time() - t0), flush=True)
print(" pass %d: %s" % (pass_i + 1,
"收紧 " + str({t: [round(limits[t][0], 1), round(limits[t][1], 1)] for t in CHAIN[1:]}
if changed else "无变化")), flush=True)
if not changed:
break
# 滑块范围 = 单关节验证硬限位(任意单关节推满保证零干涉)。
# 组合折叠约束(某关节保持极限时扫其它关节发现的卡死)只写入明细/报告,
# 不压缩滑块 —— 否则手臂会被静态限位锁死(真实机器人由控制器做避碰)。
final = {}
print("\n[最终滑块范围](单关节硬限位,含 1° 安全余量)")
for t in CHAIN[1:]:
lo, hi = singles[t]["lo"], singles[t]["hi"]
if lo <= -179.9 and hi >= 179.9:
final[t] = dict(axis=t, lo=-180.0, hi=180.0, continuous=True, zero=0.0,
note="整周无干涉,可 360° 连续旋转(全对全动态扫描验证)")
else:
lo_out = float(math.ceil(lo + 1.0)) if lo < -0.5 else 0.0
hi_out = float(math.floor(hi - 1.0)) if hi > 0.5 else 0.0
final[t] = dict(axis=t, lo=lo_out, hi=hi_out, continuous=False, zero=0.0,
note="正向 +%d° / 反向 %d°,总行程 %d°(全对全动态扫描验证,含相邻件与电机)"
% (hi_out, lo_out, hi_out - lo_out))
print(" %-3s %7.1f .. %7.1f %s" % (t, final[t]["lo"], final[t]["hi"],
"360°连续" if final[t]["continuous"] else ""))
os.makedirs(DOCS, exist_ok=True)
json.dump([final[t] for t in CHAIN[1:]],
open(DOCS + "/travel.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
detail = dict(generated=time.strftime("%Y-%m-%d %H:%M:%S"),
vol_min=VOL_MIN, step=step, combo_step=combo_step, workers=workers,
fixture_included=INCLUDE_FIXTURE,
singles={t: dict(lo=round(singles[t]["lo"], 2), hi=round(singles[t]["hi"], 2),
jams={str(a): v for a, v in singles[t]["jams"].items()})
for t in singles},
combos=combos_log,
final=[final[t] for t in CHAIN[1:]])
json.dump(detail, open(DOCS + "/travel_detail.json", "w", encoding="utf-8"),
ensure_ascii=False, indent=1)
print("\n已写出 docs/travel.json(查看器滑块)+ docs/travel_detail.json(明细) [%.0fs]"
% (time.time() - t0))
if _POOL is not None:
_POOL.terminate()
if __name__ == "__main__":
main()
# OCC/cadquery 的静态析构在解释器正常退出时必定段错误(实测:光是
# `python -c "import arm.cad.helpers"` 就返回 139,与本项目代码无关)。所以入口
# 脚本跑完后显式刷缓冲再 os._exit —— 否则全流程已经成功、exit code 却是 139,
# 会把上游脚本的 set -e 判成失败。只在 __main__ 出口生效, 被 import 时不触发。
sys.stdout.flush()
os._exit(0)
+213
View File
@@ -0,0 +1,213 @@
# -*- coding: utf-8 -*-
"""关节电机力矩与负载能力校核。
与旧版的区别(这些是旧版实际出错的地方):
1. 拓扑。旧版把关节表手抄成 "J3 肘俯仰 / J4 前臂自转 / J5 腕俯仰 / J6 夹爪",
并据此虚构了一个夹爪机构和 135mm 大臂——与 human_layout.py 的实际拓扑
(J3 大臂自转 / J4 肘俯仰 / J6 腕自转)完全不符,整份报告的结论都是错的。
本版不再复制拓扑:零件表、关节轴、运动学链全部复用 strength_check,
而 strength_check 的轴又直接来自 human_layout,单一事实源。
2. 力臂。旧版把每个关节的质量与力臂写成硬编码常数(J2 = 1.75kg @ 464mm),
几何一改就失效且不会报错。本版按每个零件的真实质心、在可达姿态网格上
搜索最大重力力矩。
3. 惯量。旧版用一组手填的 kg·m²。本版按 Σm·d²(对关节轴的平行轴距离)
在同一姿态网格上取最大值。零件自身转动惯量未计入,对大臂量级的关节
是小修正,已在报告中标注。
电机参数:仓库内没有原始数据手册,以下为工程假定,可用环境变量覆盖。
ARMT_CONT 连续额定输出力矩 (N·m)
ARMT_PEAK 峰值堵转输出力矩 (N·m)
ARMT_ALLOW 封闭塑料外壳热衰减后的许用连续力矩 (N·m)
ARMT_ALPHA 角加速度 (rad/s²)
ARMPAY 末端负载 (kg)
输出:docs/torque_balance.json + docs/torque_report.md
"""
import io
import json
import math
import os
import sys
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
from arm import kinematics as HL
from arm.paths import DOCS
from arm.analysis import strength_check as SC
G = 9.81
T_CONT = float(os.environ.get("ARMT_CONT", "2.5"))
T_PEAK = float(os.environ.get("ARMT_PEAK", "8.0"))
T_ALLOW = float(os.environ.get("ARMT_ALLOW", "2.0"))
ALPHA = float(os.environ.get("ARMT_ALPHA", "5.0"))
PAYLOAD = float(os.environ.get("ARMPAY", "0.5"))
# 关节名与轴向,全部取自 human_layout(不手抄)
JOINT_CN = {t[0]: t[1] for t in HL.JOINTS}
JOINT_D = {t[0]: t[3] for t in HL.JOINTS}
def _axis_kind(tag):
d = JOINT_D[tag]
if abs(d[2]) == 1:
return "roll(绕Z)"
if abs(d[0]) == 1:
return "roll(绕X)"
return "pitch(绕Y)"
def analyze(payload_kg=PAYLOAD):
parts = SC.part_table(payload_kg)
jl = SC.joint_loads(parts)
jl0 = SC.joint_loads(SC.part_table(0.0)) # 去掉末端负载,用于反推负载能力
masses = {"J%d" % j: sum(m for _, m, _, g in parts if g >= j) for j in range(1, 7)}
arm_mass = {k: v - payload_kg * 1000.0 for k, v in masses.items()}
res = {"assumptions": {
"motor": "60mm 方形标准关节电机模组,2 级行星减速",
"T_cont_Nm": T_CONT, "T_peak_Nm": T_PEAK, "T_allow_Nm": T_ALLOW,
"alpha_rad_s2": ALPHA, "payload_kg": payload_kg,
"note": "电机参数为工程假定,仓库内无数据手册;结论对此敏感,见报告第 4 节",
}, "joints": {}}
for j in range(1, 7):
tag = "J%d" % j
r = jl[tag]
tau_g = r["tau"] / 1000.0 # N*m,重力
tau_dyn = r["I"] * ALPHA # N*m,惯性
tau_g_arm = jl0[tag]["tau"] / 1000.0 # 去掉负载后的重力力矩
req_static = tau_g
req_peak = tau_g + tau_dyn
res["joints"][tag] = {
"cn": JOINT_CN[tag], "axis": _axis_kind(tag),
"distal_mass_kg": round(masses[tag] / 1000.0, 3),
"arm_mass_kg": round(arm_mass[tag] / 1000.0, 3),
"weight_N": round(r["F"], 1),
"reach_tip_mm": round(r["Lp"], 0),
"tau_gravity_Nm": round(tau_g, 3),
"tau_gravity_arm_only_Nm": round(tau_g_arm, 3),
"I_distal_kgm2": round(r["I"], 5),
"tau_dynamic_Nm": round(tau_dyn, 3),
"tau_required_static_Nm": round(req_static, 3),
"tau_required_peak_Nm": round(req_peak, 3),
"duty_vs_Tcont_pct": round(100.0 * req_static / T_CONT, 1),
"duty_vs_Tallow_pct": round(100.0 * req_static / T_ALLOW, 1),
"peak_margin_x": round(T_PEAK / req_peak, 2) if req_peak > 1e-3 else None,
"status": "OK" if (req_static <= T_ALLOW and req_peak <= T_PEAK) else "OVERLOAD",
}
return res, jl0, jl
def max_payload(res):
"""在许用连续力矩下,末端还能带多少 kg(按各关节取最小)。
线性化:tau_g(p) ≈ tau_g_arm + p·g·L。用的是该关节实测的最大 TCP 力臂,
即最不利姿态下的力臂。
"""
out = {}
for tag, d in res["joints"].items():
L = d["reach_tip_mm"] / 1000.0
if L <= 0:
out[tag] = None
continue
head = T_ALLOW - d["tau_gravity_arm_only_Nm"]
out[tag] = round(max(head, 0.0) / (G * L), 3) if head > 0 else 0.0
return out
def generate_report(res, mp):
L = []
L.append("# 6 自由度机械臂 · 关节电机力矩与负载能力校核\n")
a = res["assumptions"]
L.append("## 1. 前提\n")
L.append("- 驱动:%s" % a["motor"])
L.append("- 连续额定输出力矩 `T_cont` = %.2f N·m;峰值堵转 `T_peak` = %.2f N·m"
% (a["T_cont_Nm"], a["T_peak_Nm"]))
L.append("- 封闭打印外壳热衰减后许用连续力矩 `T_allow` = %.2f N·m;末端负载 %.2f kg;"
"角加速度 %.1f rad/s²" % (a["T_allow_Nm"], a["payload_kg"], a["alpha_rad_s2"]))
L.append("- **%s**\n" % a["note"])
L.append("载荷模型:每个零件按网格体积加权质心定位,随姿态做刚体变换,在可达姿态"
"网格(俯仰轴取行程端点/中值,自转轴取 0/±60/±120/180°)上取重力力矩最大值。"
"力矩为绕**关节自身轴**的分量——这才是电机要出的力。\n")
L.append("## 2. 各关节校核结果\n")
L.append("| 关节 | 名称 | 轴 | 以下质量(kg) | TCP力臂(mm) | 重力力矩(N·m) | 惯性力矩(N·m) | 峰值需求(N·m) | 负荷率(对T_allow) | 峰值裕度 | 判定 |")
L.append("|:---:|:---|:---|---:|---:|---:|---:|---:|---:|---:|:---:|")
for tag, d in res["joints"].items():
L.append("| %s | %s | %s | %.2f | %.0f | **%.2f** | %.2f | %.2f | **%.0f%%** | %s | %s |"
% (tag, d["cn"], d["axis"], d["distal_mass_kg"], d["reach_tip_mm"],
d["tau_gravity_Nm"], d["tau_dynamic_Nm"], d["tau_required_peak_Nm"],
d["duty_vs_Tallow_pct"],
("%.2f×" % d["peak_margin_x"]) if d["peak_margin_x"] else "—", d["status"]))
L.append("")
L.append("## 3. 许用连续工况下的末端负载能力\n")
L.append("去掉末端负载后各关节仍需 `tau_gravity_arm_only` 的重力力矩,余额除以该关节"
"实测最大 TCP 力臂,即为还能挂的负载:\n")
L.append("| 关节 | 仅臂身重力力矩(N·m) | 余额(N·m) | 可挂负载(kg) |")
L.append("|:---:|---:|---:|---:|")
for tag, d in res["joints"].items():
head = T_ALLOW - d["tau_gravity_arm_only_Nm"]
L.append("| %s | %.2f | %+.2f | %s |"
% (tag, d["tau_gravity_arm_only_Nm"], head,
("%.2f" % mp[tag]) if mp[tag] is not None else "—"))
ok = [t for t, v in mp.items() if v is not None]
worst = min(ok, key=lambda t: mp[t]) if ok else None
if worst:
L.append("")
L.append("**整臂瓶颈:%s,可挂末端负载 %.2f kg。**\n" % (worst, mp[worst]))
L.append("## 4. 结论要点\n")
over = [t for t, d in res["joints"].items() if d["status"] == "OVERLOAD"]
if over:
L.append("- **超载关节:%s**。" % "、".join(over))
for t in over:
d = res["joints"][t]
L.append(" - %s(%s)重力 %.2f N·m,超 `T_allow` %.0f%%;即使按峰值堵转算,"
"裕度也只有 %s。" % (t, d["cn"], d["tau_gravity_Nm"],
d["duty_vs_Tallow_pct"] - 100.0,
("%.2f×" % d["peak_margin_x"]) if d["peak_margin_x"] else "—"))
L.append("- 结论对电机参数高度敏感:若实际连续额定高于假定值,"
"请用 `ARMT_CONT` / `ARMT_ALLOW` 覆盖后重跑本脚本。")
else:
L.append("- 全部关节在许用连续力矩内。")
L.append("- 惯量按 Σm·d² 估,**未计入零件自身转动惯量**,对肩/肘是大臂量级的关节"
"约低估一成,惯性力矩一栏应视为下限。")
L.append("- 本版不含被动弹簧平衡。旧版报告提出的 J2 拉簧预补偿(2.48 N·m)在几何上"
"**尚未实现**;若要保留该方案,需要在 P04/P05 之间增加拉簧连杆机构。")
return "\n".join(L)
def main():
res, jl0, jl = analyze(PAYLOAD)
mp = max_payload(res)
io.open(DOCS + "/torque_balance.json", "w", encoding="utf-8").write(
json.dumps(res, ensure_ascii=False, indent=2))
io.open(DOCS + "/torque_report.md", "w", encoding="utf-8").write(generate_report(res, mp))
print("末端负载 %.2f kg T_cont=%.2f T_allow=%.2f T_peak=%.2f alpha=%.1f\n"
% (PAYLOAD, T_CONT, T_ALLOW, T_PEAK, ALPHA))
print("%-4s %-8s %-12s %8s %8s %8s %9s %8s %s"
% ("关节", "名称", "轴", "重力N·m", "惯性N·m", "峰值N·m", "负荷率", "峰值裕度", "判定"))
for tag, d in res["joints"].items():
print("%-4s %-8s %-12s %8.2f %8.2f %8.2f %8.0f%% %8s %s"
% (tag, d["cn"], d["axis"], d["tau_gravity_Nm"], d["tau_dynamic_Nm"],
d["tau_required_peak_Nm"], d["duty_vs_Tallow_pct"],
("%.2fx" % d["peak_margin_x"]) if d["peak_margin_x"] else "-",
d["status"]))
print("\n许用连续力矩下可挂末端负载 (kg):")
for tag in res["joints"]:
print(" %-4s %s" % (tag, ("%.2f" % mp[tag]) if mp[tag] is not None else "—"))
ok = [t for t, v in mp.items() if v is not None]
if ok:
w = min(ok, key=lambda t: mp[t])
print(" 整臂瓶颈 %s -> %.2f kg" % (w, mp[w]))
print("\n已写出 docs/torque_balance.json + docs/torque_report.md")
if __name__ == "__main__":
main()
# OCC/cadquery 的静态析构在解释器正常退出时必定段错误(实测:光是
# `python -c "import arm.cad.helpers"` 就返回 139,与本项目代码无关)。所以入口
# 脚本跑完后显式刷缓冲再 os._exit —— 否则全流程已经成功、exit code 却是 139,
# 会把上游脚本的 set -e 判成失败。只在 __main__ 出口生效, 被 import 时不触发。
sys.stdout.flush()
os._exit(0)
+143
View File
@@ -0,0 +1,143 @@
# -*- coding: utf-8 -*-
"""关节角组合可达空间(工具尖点)计算:FK 采样 + J1 旋转对称包络 + 体积估计"""
import json
import math
import os
import sys
import numpy as np
from arm import kinematics as HL
from arm.paths import DOCS, CACHE
TRAVEL = {t["axis"]: (t["lo"], t["hi"]) for t in
json.load(open(DOCS + "/travel.json", encoding="utf-8"))}
TIP = (HL.X_ARM, HL.Y_AXIS, HL.Z_TIP) # P09 法兰底面中心(工具安装面)
J1_AX = (HL.Y_AXIS, HL.Z_RL) # J1 转轴: 过 Y=128, Z=610, 平行 X
def rot_about(p, k, ang):
"""绕轴 (p 点, k 方向) 旋转 ang(弧度, 可为数组M,);返回 Rm(M,3,3), t(M,3)。
p' = Rm @ (p_pt - p) + p,与 AB.R 的 gp_Trsf.SetRotation 右手定则一致。"""
k = np.asarray(k, dtype=float)
k = k / np.linalg.norm(k)
ang = np.atleast_1d(np.asarray(ang, dtype=float))
px, py, pz = p
K = np.array([[0.0, -k[2], k[1]], [k[2], 0.0, -k[0]], [-k[1], k[0], 0.0]])
K2 = K @ K
Rm = np.eye(3)[None, :, :] + np.sin(ang)[:, None, None] * K[None, :, :] \
+ (1.0 - np.cos(ang))[:, None, None] * K2[None, :, :]
pp = np.array([px, py, pz])
t = pp[None, :] - np.einsum("mij,j->mi", Rm, pp)
return Rm, t
def fk_batch(angles, tip=TIP):
"""angles: dict idx->弧度数组(M,);返回 (M,3) 世界坐标。链式 acc 与 sweep_v2 一致:
父关节变换在最外层 p' = R1∘R2∘…∘R5 (p),各 R_i 绕其零位世界轴(human_layout 唯一事实源)。"""
pts = np.tile(np.asarray(tip, dtype=float), (angles[1].shape[0], 1))
for i in range(5, 0, -1): # J6 跳过:尖点在 J6 轴上,其转角不改变尖点位置
rear, d = HL.JOINTS[i - 1][2], HL.JOINTS[i - 1][3]
Rm, t = rot_about(rear, d, angles[i])
pts = np.einsum("mij,mj->mi", Rm, pts) + t
return pts
def sweep(step=2.0):
j2 = np.radians(np.arange(TRAVEL["J2"][0], TRAVEL["J2"][1] + 1e-9, step))
j4 = np.radians(np.arange(TRAVEL["J4"][0], TRAVEL["J4"][1] + 1e-9, step))
j5 = np.radians(np.arange(TRAVEL["J5"][0], TRAVEL["J5"][1] + 1e-9, step))
g2, g4, g5 = np.meshgrid(j2, j4, j5, indexing="ij")
M = g2.size
angles = {1: np.zeros(M), 2: g2.ravel(), 3: np.zeros(M),
4: g4.ravel(), 5: g5.ravel()}
pts = fk_batch(angles)
# 自证1:零位尖点必须回到 (18.5,128,93)
z0 = fk_batch({i: np.zeros(1) for i in range(1, 6)})
assert np.allclose(z0[0], TIP, atol=1e-9), z0[0]
# 自证2:J1/J6 旋转不改变 (x, r) 与极值位置——J1 取中值扫一遍,r 分布应与 J1=0 相同
for phi in (0.5, 1.2, 2.4):
v1 = np.full(M, phi)
p1 = fk_batch({1: v1, 2: g2.ravel(), 3: np.zeros(M),
4: g4.ravel(), 5: g5.ravel()})
r1 = np.hypot(p1[:, 1] - J1_AX[0], p1[:, 2] - J1_AX[1])
r0 = np.hypot(pts[:, 1] - J1_AX[0], pts[:, 2] - J1_AX[1])
assert np.allclose(np.sort(r0), np.sort(r1), atol=1e-9), "J1 对称性被破坏"
# 自证3:J3 旋转(大臂自转)不改变尖点位置——关节轴过尖点所在纵线
print("J3 对称性: 尖点 x=%.1f 与 J3 轴 x=%.1f 一致=%s, y=%.1f 与轴 y=%.1f 一致=%s"
% (TIP[0], HL.X_ARM, abs(TIP[0] - HL.X_ARM) < 1e-9,
TIP[1], HL.Y_AXIS, abs(TIP[1] - HL.Y_AXIS) < 1e-9))
print("J6 含于轴: 尖点 (%.1f,%.1f) vs 轴 (%.1f,%.1f)"
% (TIP[0], TIP[1], HL.JOINTS[5][2][0], HL.JOINTS[5][2][1]))
return pts
def envelope(pts, grid=1.0):
"""(x, r) 半平面栅格化占用 + 体积(绕 J1 轴回转)。"""
x = pts[:, 0]
r = np.hypot(pts[:, 1] - J1_AX[0], pts[:, 2] - J1_AX[1])
x0, x1 = math.floor(x.min()), math.ceil(x.max())
r0, r1 = 0.0, math.ceil(r.max())
nx = int(round((x1 - x0) / grid)) + 1
nr = int(round((r1 - r0) / grid)) + 1
xi = np.clip(((x - x0) / grid).round().astype(int), 0, nx - 1)
ri = np.clip((r / grid).round().astype(int), 0, nr - 1)
occ = np.zeros((nx, nr), dtype=bool)
occ[xi, ri] = True
# 每个 x 列只保留 r <= 该列可达最大 r(回转体沿 r 连续填充)
for i in range(nx):
j = np.nonzero(occ[i])[0]
if j.size:
occ[i, : j.max() + 1] = True
rr = r0 + np.arange(nr) * grid
vol = float((occ * (2.0 * math.pi * rr)[None, :] * grid * grid).sum())
return dict(occ=occ, x0=x0, grid=grid, rm_axes=rr, vol_mm3=vol,
nx=nx, nr=nr)
def main():
pts = sweep()
x, y, z = pts[:, 0], pts[:, 1], pts[:, 2]
r = np.hypot(y - J1_AX[0], z - J1_AX[1])
env = envelope(pts)
# 每个 x 的 r 包络(侧视/俯视剖面用)
xs = env["x0"] + np.arange(env["nx"]) * env["grid"]
rmax_x, rmin_x = [], []
for i in range(env["nx"]):
j = np.nonzero(env["occ"][i])[0]
if j.size:
rmax_x.append(env["rm_axes"][j.max()])
rmin_x.append(env["rm_axes"][j.min()])
else:
rmax_x.append(np.nan)
rmin_x.append(np.nan)
os.makedirs(CACHE, exist_ok=True)
np.savez_compressed(CACHE + "/ws_cloud.npz",
pts=pts, xs=np.array(xs),
rmax=np.array(rmax_x), rmin=np.array(rmin_x))
met = dict(
z_max=float(z.max()), z_min=float(z.min()),
x_fwd=float(x.max()), x_back=float(x.min()),
y_lo=float(y.min()), y_hi=float(y.max()),
r_max=float(r.max()), r_min=float(r.min()),
reach_from_j1_axis=float(r.max()),
spread=float(z.max() - z.min()),
vol_dm3=env["vol_mm3"] / 1e6,
tip=TIP, j1_axis=list(J1_AX),
limits={k: list(v) for k, v in TRAVEL.items()},
)
# 自证4:极值点姿态可解释(打印取极值的角度组合索引)
imax = int(np.argmax(z)); imin = int(np.argmin(z))
ifwd = int(np.argmax(x)); iback = int(np.argmin(x))
met["pose_extreme"] = dict(
zmax_idx=imax, zmin_idx=imin, xfwd_idx=ifwd, xback_idx=iback)
print(json.dumps({k: v for k, v in met.items()
if k not in ("limits", "pose_extreme")},
ensure_ascii=False, indent=1))
json.dump(met, open(CACHE + "/ws_metrics.json", "w", encoding="utf-8"),
ensure_ascii=False, indent=1)
if __name__ == "__main__":
main()
+199
View File
@@ -0,0 +1,199 @@
# -*- coding: utf-8 -*-
"""机器人手臂深度圆角优化版 V2:彻底消除所有棱角
针对用户反馈的三大问题区域进行深度优化:
1. 蓝色零件(P04肩叉)顶部方形突起 → 全圆角处理
2. 绿色/青色零件(P05/P08)底部和侧面棱角 → Loft外轮廓圆角
3. 所有连接处的尖锐过渡 → 大圆角平滑过渡
4. 橙色零件(P06/P07)所有方形边缘 → 完整圆角系统
"""
import math
import os
import sys
import time
import cadquery as cq
from arm.cad import arm_build as AB
from arm.paths import OUT, WEB, DOCS
from arm.constants import M, C
from arm.cad.helpers import cyl, box, ring, place, trs, bb, bbox_str, solids_of
from arm.cad.arm_build import (Joint, add, bx, Ycyl, Ybox, Yplate, prism, dogbone, sector,
FLANGE_Z, COVER_Z, HUB_FACE_Z, CLAMP_SPAN, HUB_M2_CLOCK,
BORE_R, CB_R, PCB_W, D2R, T, R, PARTS)
from arm import kinematics as HL
from OCP.BRepAlgoAPI import BRepAlgoAPI_Common
from arm.kinematics import (HUB, PLATE_T, R_MOT, Z_TIP, Z_WR, Z_EI, Z_SH, Z_RL, Z_R1,
Z_R3, Z_HUB3, Z_EL, Z_R6, Z_HUB6,
Z_R4, Z_CAP, Z_M6, Z_CHEST0, Z_CHEST1, X_J1_HUB, X_ARM, L1,
X_FORK_GAP, X_BAY_EXT,
Y_AXIS, Y_HUB, Y_REAR, Y_COVER, Y_H, Y_R_IN, Y_R_OUT,
Y_M6, Y_CHEST, X_CHEST, FOOT_H)
VERSION = os.environ.get("ARMVER", "v2")
ITER = int(os.environ.get("ARMITER", "3"))
AB.VERSION = VERSION
AB.ITER = ITER
# ------------------------------------------------ 逐件模块(几何已拆出)
from arm.cad.parts import PART_MODULES
from arm.cad.part_tools import (
BOSS, CHAMFER_EDGE, CLAMP_BACKOFF, CLAMP_BCD, CLAMP_CLOCK, CLAMP_CLOCK_LOCAL, CLAMP_CLR,
CLAMP_ROOT, CLAMP_T, CLEARANCE_GAP, DISC_R, FENCE_OPEN_CUT, FILLET_LARGE, FILLET_MEDIUM,
FILLET_SMALL, FILLET_TINY, FILLET_XLARGE, HOLLOW_FILLET, HOLLOW_WALL, SLEEVE_R, XB, Xcyl,
Xplate, Y_MID, cut_motor_fence, hollow_channel, hollow_tent_window, hub_m2_holes,
make_direct_hub, make_pitch_to_roll_bracket, motor_front_clamp,
)
from arm.cad.parts.p01_column import X_COL, Y_COL, Z_LOCK, p_chest, split_p01_poka_yoke
from arm.cad.parts.p02_base import make_p02_poka_yoke, p_base_foot
from arm.cad.parts.p03_girdle import p_girdle
from arm.cad.parts.p04_fork import P04_CH, p_fork
from arm.cad.parts.p05_roll_base import p_shoulder_roll_base
from arm.cad.parts.p06_humerus import P06_HOLLOW_WIN, P06_WIN_XZ, p_humerus_bone
from arm.cad.parts.p07_forearm import P07_CH, p_forearm_bone
from arm.cad.parts.p08_wrist import p_wrist_bracket
from arm.cad.parts.p09_flange import p_tool_flange
# 兼容旧工具:scratch/ 的诊断脚本按 arm_model.<符号> 取用件构造函数与开关
def build():
print("=" * 80, flush=True)
print("【第一阶段 1/5】开始生成手臂各级构件 3D 几何实体模型...", flush=True)
print("=" * 80, flush=True)
t_stage1 = time.time()
print(" [0/9] 载入电机标准件模组 (STEP)...", end="", flush=True)
t0 = time.time()
motor = cq.importers.importStep(AB.SRC_STEP).val()
motor = place(motor, T(0, 0, -2.57))
AB.MOTOR, AB.HALF, AB.CLAMP = motor, None, None
print(f" 完成 ({time.time()-t0:.2f}s) ✓", flush=True)
JS = {}
for tag, cn, rear, d, xd, holder, driven in HL.JOINTS:
JS[tag] = Joint(tag, cn, rear, d, xd, lug_phase=90.0 if tag == "J1" else 0.0)
j1, j2, j3, j4, j5, j6 = (JS["J%d" % k] for k in range(1, 7))
PARTS[:] = []
AB.CENTS.clear()
AB.GRP = {}
par = {"J1": "root", "J2": "J1", "J3": "J2", "J4": "J3", "J5": "J4", "J6": "J5"}
motor_of = {"J1": "M1_J1", "J2": "M2_J2", "J3": "M3_J3",
"J4": "M4_J4", "J5": "M5_J5", "J6": "M6_J6"}
for t in ("J1", "J2", "J3", "J4", "J5", "J6"):
AB.GRP[motor_of[t]] = par[t]
AB.JAW = {}
# 逐件模块:几何、件号/配色/说明、装配帧归属都在 arm/cad/parts/ 里,
# 这里只按 BOM 顺序收集 specs(),并把件号登记到装配帧图上。
parts_to_build = []
for _m in PART_MODULES:
for _spec in _m.specs(JS):
AB.GRP[_spec[0]] = _m.JOINT
parts_to_build.append(_spec)
total_parts = len(parts_to_build)
for idx, (name, cn, fn, color, note) in enumerate(parts_to_build, 1):
print(f" [{idx}/{total_parts}] 正在构建 {name} ({cn})...", end="", flush=True)
t0 = time.time()
sh = fn()
dt = time.time() - t0
vol = AB.vol_of(sh) / 1000.0
n_solids = len(solids_of(sh))
print(f" 完成 ✓ ({dt:.2f}s | 体积: {vol:.1f} cm³ | 实体数: {n_solids})", flush=True)
add(name, cn, sh, color, note=note)
print(" [装配] 正在将 M1~M6 电机定位至各关节坐标位姿...", end="", flush=True)
t0 = time.time()
for k, (tag, cn, rear, d, xd, holder, driven_name) in enumerate(HL.JOINTS):
j = JS[tag]
add("M%d_%s" % (k + 1, tag), "%s 电机模组" % tag, place(motor, j.t), 0x9ca3af,
printed=False, note="复用 电机.STEP")
print(f" 完成 ✓ ({time.time()-t0:.2f}s)", flush=True)
print(f"-> 构件模型全部生成完成,总耗时: {time.time()-t_stage1:.2f}s\n", flush=True)
return JS
CHAIN = ["root", "J1", "J2", "J3", "J4", "J5", "J6"]
SEP = 74.0
def explode_chain(p, JS, cents, gmean):
"""爆炸图偏移:立柱垂直阶梯拉开,底座前后防呆拉开,电机沿轴拉出,机械臂整体随上段分离"""
nm = p["name"]
if nm == "P01_A_立柱下段_三角形30%_墙4底5_竖打":
return [0.0, 0.0, 0.0]
if nm == "P01_B_立柱中段_三角形30%_墙4底5_竖打":
return [0.0, 0.0, 60.0]
if nm == "P01_C_立柱上段_三角形30%_墙4底5_竖打":
return [0.0, 0.0, 120.0]
if nm == "P02_Center_底座中核心_螺旋体30%_墙5底6_平打":
return [0.0, 0.0, 0.0]
if nm == "P02_Front_前向防翻力臂_螺旋体30%_墙4底5_平打":
return [65.0, 0.0, 0.0]
if nm == "P02_Rear_后向防翻力臂_螺旋体30%_墙4底5_平打":
return [-65.0, 0.0, 0.0]
if nm == "P03_肩吊臂_螺旋体35%_墙5底5_竖打":
return [0.0, 0.0, 120.0]
grp = AB.GRP.get(p["name"], "root")
if grp == "root":
return [0.0, 0.0, 0.0]
k = CHAIN.index(grp)
off = [0.0, 0.0, 120.0 - SEP * k]
j = JS.get(grp)
if j:
w = 0.0
if "半联轴器" in nm or "抱箍" in nm:
w = 34.0 * (1.0 if ("A" in nm[-1:]) else -1.0)
elif nm.startswith("M"):
w = 62.0
for q in range(3):
off[q] += j.d[q] * w
return off
if __name__ == "__main__":
JS = build()
print("=" * 80, flush=True)
print("【单实体拓扑完整性校验】验证所有打印构件流形实体状态...", flush=True)
print("=" * 80, flush=True)
bad = 0
printed_list = [p for p in PARTS if p["printed"]]
total_pr = len(printed_list)
for idx, p in enumerate(printed_list, 1):
n = len(solids_of(p["shape"]))
if n != 1:
bad += 1
status = "单实体 ✓" if n == 1 else f"异常 ({n} 个实体) ❌"
print(f" [{idx}/{total_pr}] {p['name']:<14} : 体积 {p['vol']/1000.0:6.1f} cm³ | {status}", flush=True)
if bad == 0:
print(f"-> 单实体检查全部通过!{total_pr}/{total_pr} 构件均为完美单一流形拓扑 ✓\n", flush=True)
else:
print(f"-> 发现 {bad} 个非单实体构件!\n", flush=True)
AB.explode_vec = explode_chain
bom = AB.export(JS)
# 紧固件(螺钉)实例注入:把 docs/screws.json 的 72 颗螺钉按真实孔位还原成三维实例,
# 追加进 web/mesh_arm.json 的 parts(查看器可点 BOM 螺丝行高亮定位;纯数据,不动 CAD)
from arm.dataio import screw_mesh
screw_mesh.main()
cl = AB.collide()
from arm.viewer.build_viewer import rebuild_viewer
rebuild_viewer()
# 可达包络自动注入:AB.export 刚重写过 mesh_arm.json(包络件会被冲掉),
# 这里重跑 FK 采样 + 包络网格注入,再重打包一次查看器(约 3~4s,纯数据无 CAD 计算)
from arm.analysis import ws_sweep, gen_env_mesh
t_env = time.time()
ws_sweep.main()
gen_env_mesh.main()
rebuild_viewer()
print(f"-> 可达包络已自动注入查看器(+{time.time() - t_env:.1f}s)✓\n", flush=True)
print("=" * 80, flush=True)
print("✅ 机器人手臂编译、导出与查看器发布全流程完成!", flush=True)
print("=" * 80, flush=True)
# OCC/cadquery 的静态析构在解释器正常退出时必定段错误(实测:光是
# `python -c "import arm.cad.helpers"` 就返回 139,与本项目代码无关)。所以入口
# 脚本跑完后显式刷缓冲再 os._exit —— 否则全流程已经成功、exit code 却是 139,
# 会把上游脚本的 set -e 判成失败。只在 __main__ 出口生效, 被 import 时不触发。
sys.stdout.flush()
os._exit(0)
+8
View File
@@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-
"""几何与装配层。
helpers 放置/基础体/网格化等无状态 helper
arm_build Joint 装配模型、零件登记(add)、STEP/STL/BOM/mesh 导出
part_tools 跨件共用刀法(减重腔、压盖、转接座、圆角常量、螺钉孔位事实源)
parts/ 每个打印件一个模块:几何 + 件号/配色/说明 + 装配帧归属
"""
+653
View File
@@ -0,0 +1,653 @@
# -*- coding: utf-8 -*-
"""Shared geometry / assembly / export library for the robot arm build.
No layout of its own: the joint frames and station positions live in
human_layout.py and arm_model.py, which import this module. What lives here is
the measured motor interface (docs/interfaces.md), the Joint class (motor slip
bore + PCBA pocket + pinch screws; driven hub mating plane at motor rear datum
+65.0 replicating the Ø36x1.0 neck / Ø6.5x4.0 centre / 3x M2 on Ø29 output so
the existing face-spline halves + split clamp bolt straight on), the part
registry, and the STEP/STL/mesh/BOM/collision export pipeline.
Run: python arm_model.py -> out/, web/mesh_arm.json, docs/
"""
import math
import os
import sys
import json
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
import cadquery as cq
from arm.paths import OUT, WEB, DOCS, SRC_STEP, HALF_STEP, CLAMP_STEP
from arm.constants import M, C, MOTOR_TOL
from arm.cad.helpers import V, trs, place, bb, bbox_str, cyl, ring, box, holes, solids_of, mesh_of
from OCP.gp import gp_Trsf, gp_Vec, gp_Pnt, gp_Dir, gp_Ax1
from OCP.BRepAlgoAPI import BRepAlgoAPI_Common
from OCP.GProp import GProp_GProps
from OCP.BRepGProp import BRepGProp
from OCP.STEPControl import STEPControl_Writer, STEPControl_Controller, STEPControl_StepModelType
from OCP.Interface import Interface_Static
STEPControl_Controller.Init_s()
D2R = math.pi / 180.0
VERSION = os.environ.get("ARMVER", "r1")
ITER = int(os.environ.get("ARMITER", "1"))
# ---------------------------------------------------------------- measured stations
FLANGE_Z = M["flange_z"] # 54.942
COVER_Z = M["cover_z"] # 56.000
HUB_FACE_Z = 65.0 # motor rear datum -> driven hub mating plane
CLAMP_SPAN = (FLANGE_Z + 1.66, FLANGE_Z + 9.46)
CLAMP_R_BAND = 31.0
CLAMP_R_LUG = 38.0
BORE_R = M["hous_d"] / 2.0 + 0.15 # 30.15 slip fit on the housing
CB_R = M["cover_d"] / 2.0 + 0.35 # 30.50 clearance for the cover
PCB_W = M["pcba_w"] + 0.8 # 64.40 square pocket
HUB_M2_CLOCK = [(360.0 - a) % 360.0 for a in M["m2_clock"]] # phase of the mirrored half
HUB_PILOT_D = M["neck_d"] - 0.4 # 35.6 -> the half's pilot lands in a Ø36 recess
PINCH_D = 2.6 # M3 clearance in printed material
# 承压面让位(完整背景见 Joint.pocket 的 docstring):
# REAR_LAND = 0.6 腔口直壁台肩高度,**保持原设计值不变**(让位不靠加高台肩)
# REAR_SEAT = 2.6 尾端面->承压面 = 0.6 原台肩 + 2.0 公差垫片位
# R35_SEAT = 35.0 后端板 R35 外壁(承压面外径)
# SEAT_R = 35.0 承压面段(z=-REAR_SEAT..SEAT_TOP)的腔口半径 = **等于外壁 R35**。
# SEAT_TOP = 1.0 圆腔顶端越过电机尾端面(z=0) 1mm。
#
# 【2026-10-05 用户第三次指出:SEAT_R 必须是 35,"凸台+围挡"要一起弄平】
# 之前取 32.2(64.4 方腔的内切圆)以为这样能保住连接壁,实测**恰恰相反**:
# 32.2 与外壁 35 之间那圈 2.8mm 宽的环墙完整保留,而承压面只挖到 32.2,
# 于是这圈环墙相对承压面【凸起 2.6mm】,把电机尾端面整个围在里面 ——
# 这正是用户截图里的"一圈围挡"(P08 该圈实测 1536.9 mm3)。它不是残留,
# 而是 SEAT_R 取小值的必然产物:只要 SEAT_R < R35,环墙就一定存在。
# 用户要求:"把凸台、围挡一起弄平,做成和电机两头齐平一起的平面"。
# 故 SEAT_R 取满 R35:承压面段整圈挖到外壁,承压面变成**完整 R35 平圆盘**,
# 环墙(凸台)自然消失,电机尾端面与承压面之间再无任何凸起。
#
# 【为什么这次取 R35 不会重演2026-10-04 的"肩叉顶部没连上"】
# 那次我切的是 z=-2.6..0 且**只切到 z=0 就停**,导致环墙在 z=0..1.0 还残留一截
# 0.052cm3 的薄片(Y93.0~95.8 的半包开口处),那片薄片脱空成为独立碎块。
# 现在 SEAT_TOP=+1.0 把那一截一起吃掉:实测五件全部单实体、零碎片。
# 且承力桥改为由**臂身本体**(r>35)承担 —— 实测 band 段 r36..58 有料的方位
# P04 10/36、P05/P06/P07/P08 各 15/36,其余方位由 z=+1.0 以上的杯体连接,
# 不存在"整圈被切断"的通槽(那正是 2026-10-04 的错误形态)。
# 连带好处:承压环由「1.95mm 窄环」变「完整 R35 圆环 4.75mm」,受压面积 383->974mm²。
REAR_LAND = 0.6
REAR_SEAT = REAR_LAND + MOTOR_TOL # 1.6 尾端面->后端板承压面:公差垫片位 (0.6 + 1.0)
R35_SEAT = 35.0 # 后端板 R35 外壁(承压面外径)
SEAT_R = R35_SEAT # 35.0 承压面段腔口 = 外壁:凸台+围挡一并消除
SEAT_TOP = 1.0 # 圆腔顶端越过电机尾端面 1mm(吃掉开口处残片)
BORE_Z0 = 5.5 # 座孔起点:R35 圆腔挖到此处,与 R30.15 座孔相接
# ---------------------------------------------------------------- 电机腔统一半径
# 【2026-10-05f 接缝整改】腔内壁此前有 4 个互相打架的半径,逐层都能实测到台阶:
# R35(承压面) -> R30.15(座孔) -> R30.25(前端定位) -> R30.50(前端盖让位)
# 每一处单看都有理由,合在一起却让内壁变成「圆-台阶-圆-台阶-圆」,从腔里看全是横向接缝。
#
# 实测依据(scratch/probe_motor_env.py,剖切取 Rmax,112 层):
# 电机本体从 z=0.43 到 z=55.9 **全程 R30.14~30.15 的正圆**,全程无任何台阶。
# 即电机根本没有需要让位的形状变化 —— 那些台阶全是零件自己凭空造出来的。
#
# 故统一取 BAY_R = 30.50 = CB_R:
# - 比电机实测最大半径 30.15 单边大 0.35(直径 0.7),打印件足以塞进去;
# - 前端盖让位本来就是 30.50,沿用它可省掉一处台阶;
# - 比 R30.15 座孔大 0.35,换来的是内壁从 z=-2.6 一直到前端只有一段正圆。
# 代价:R30.15 座孔原本的单边 0.15 滑配变成 0.35,电机在座孔里的径向游隙变大。
# 但电机前后已被后端板 4xM3x10 + 前端压盖 4xM3x8 双向面压夹死(见 motor_front_clamp),
# 径向游隙不影响定位,倾倒自由度已归零。
BAY_R = 30.50
PARTS = []
CENTS = {}
def add(name, cn, shape, color, printed=True, note="", qty=1):
assert shape is not None, name
lo, hi = bb(shape)
PARTS.append(dict(name=name, cn=cn, shape=shape, color=color, printed=printed,
note=note, qty=qty, bb=bbox_str(shape), vol=vol_of(shape)))
CENTS[name] = [(lo[i] + hi[i]) / 2.0 for i in range(3)]
def vol_of(sh):
p = GProp_GProps()
BRepGProp.VolumeProperties_s(sh.wrapped, p)
return p.Mass()
def common_vol(a, b):
try:
c = BRepAlgoAPI_Common(a.wrapped, b.wrapped)
c.Build()
if not c.IsDone() or c.Shape().IsNull():
return 0.0
return vol_of(cq.Shape(c.Shape()))
except Exception:
return -1.0
def T(dx=0.0, dy=0.0, dz=0.0):
t = gp_Trsf()
t.SetTranslation(gp_Vec(dx, dy, dz))
return t
def R(deg, ax, ay, az, px=0.0, py=0.0, pz=0.0):
t = gp_Trsf()
t.SetRotation(gp_Ax1(gp_Pnt(px, py, pz), gp_Dir(ax, ay, az)), deg * D2R)
return t
RX90 = R(90, 1, 0, 0)
def Ycyl(r, y0, y1, px=0.0, pz=0.0):
return place(cyl(r, -y1, -y0, px, pz), RX90)
def Ybox(x0, x1, y0, y1, z0, z1):
return place(box(x0, x1, z0, z1, -y1, -y0), RX90)
# ------------------------------------------------------- pitch-joint pivot cartridge ----
# ONE recipe for every pitch joint (J2 shoulder, J3 elbow, J5 wrist) - they are the same
# degree of freedom, so an implementation that fixes only one of them leaves the identical
# defect in the other two. See human_layout PV_* for why a cartridge is needed at all:
# measured P04 n P05 = 0.00 mm3, so J2's 38 N*m had no path into the housing except peeling
# the face-spline teeth off across the print layers.
def pivot_geom(y_face, side, h, w, gap):
"""(boss_y0, boss_y1, pocket_y0) for a cartridge against the link face at y_face.
The race pocket always opens AWAY from the link, leaving an (h-w) shoulder behind the
outer race; a printed cap ring closes the open end. The boss stops `gap` short of the
link face, or a printed face would carry the thrust and the rolling elements nothing."""
near = y_face - gap if side < 0 else y_face + gap
if side < 0:
return near - h, near, near - h
return near, near + h, near + h - w
def pivot_boss(shape, pz, y0, y1, pk0, w, px, boss_od, race_od, bore, orace_id, side):
"""Housing side: boss on the joint axis with the outer race sunk into it. The passage
beyond the pocket is reamed to the outer race bore, not to the shaft: a shaft-sized bore
would end inside the inner race and bind it, and a bound bearing carries nothing - it
just moves the failure back into the print layers."""
shape = shape.fuse(Ycyl(boss_od / 2.0, y0, y1, px, pz))
shape = shape.cut(Ycyl(race_od / 2.0, pk0 - .01, pk0 + w + .01, px, pz))
if side < 0:
shape = shape.cut(Ycyl(orace_id / 2.0 + 0.1, pk0 + w, y1 + .01, px, pz))
else:
shape = shape.cut(Ycyl(orace_id / 2.0 + 0.1, y0 - .01, pk0, px, pz))
shape = shape.cut(Ycyl(bore / 2.0 + 0.2, y0 - .01, y1 + .01, px, pz))
for a in (90.0, 210.0, 330.0): # 3x M3 cap screws, outside the outer race
u, v = 26.5 * math.cos(a * math.pi / 180.0), 26.5 * math.sin(a * math.pi / 180.0)
shape = shape.cut(Ycyl(1.25, y0 - .01, y0 + 12.0, px + u, pz + v))
return shape
def pivot_journal(shape, pz, y_link, y_tip, y_collar0, y_collar1, px, bore, collar):
"""Link side: the stub the inner race rides on, poking past the boss so the cap can bite
it, plus an integral collar the inner race bears against. The collar replaces a separate
spacer sleeve and lives in the boss's outer-race passage, so it must stay under that
diameter - the 0.1 mm it leaves is what lets the race, not the collar, take the thrust."""
a, b = sorted((y_link, y_tip))
shape = shape.fuse(Ycyl(bore / 2.0, a, b, px, pz))
c0, c1 = sorted((y_collar0, y_collar1))
return shape.fuse(Ycyl(collar / 2.0, c0, c1, px, pz))
def prism(pts2, z0, z1):
w2 = [(p[0], p[1]) for p in pts2]
return (cq.Workplane("XY", origin=(0, 0, z0))
.polyline(w2 + [w2[0]]).close().extrude(z1 - z0, combine=False)).val()
def Yplate(pts_xz, y0, y1):
return place(prism(pts_xz, -y1, -y0), RX90)
def dogbone(a, b, ra, rb, n=20):
"""Tangent hull of two discs. The outer-tangent offset angle is acos((ra-rb)/L);
using asin made the ra==rb case sweep a full circle around b and self-intersect."""
dx, dy = b[0] - a[0], b[1] - a[1]
L = math.hypot(dx, dy) or 1.0
th = math.atan2(dy, dx)
beta = math.acos(max(-1.0, min(1.0, (ra - rb) / L)))
sw_a = 2 * math.pi - 2 * beta
sw_b = 2 * beta
pts = [(a[0] + ra * math.cos(th + beta + sw_a * k / n), a[1] + ra * math.sin(th + beta + sw_a * k / n))
for k in range(n + 1)]
pts += [(b[0] + rb * math.cos(th - beta + sw_b * k / n), b[1] + rb * math.sin(th - beta + sw_b * k / n))
for k in range(1, n + 1)]
return pts
def sector(r_out, r_in, a0, a1, z0, z1, n=14):
"""Annular sector between two radii and two angles (deg) - a joint shroud segment.
Must NOT include the axis point, or this becomes a solid pie wedge that fills the joint."""
pts = [(r_out * math.cos((a0 + (a1 - a0) * k / n) * D2R),
r_out * math.sin((a0 + (a1 - a0) * k / n) * D2R)) for k in range(n + 1)]
pts += [(r_in * math.cos((a1 - (a1 - a0) * k / n) * D2R),
r_in * math.sin((a1 - (a1 - a0) * k / n) * D2R)) for k in range(n + 1)]
return prism(pts, z0, z1)
# ---------------------------------------------------------------- joint frames & interfaces
class Joint:
"""One revolute joint. `rear` = motor rear datum point, `d` = axis unit dir (motor -> hub)."""
def __init__(self, jid, cn, rear, d, xdir, lug_phase=0.0):
self.jid, self.cn = jid, cn
self.rear = rear
self.d = d
self.xdir = xdir
self.t = trs(rear, xdir, d) # motor-local -> global
self.lug_phase = lug_phase # rotation of the clamp about the axis
def L(self, shape_local):
return place(shape_local, self.t)
def at(self, s):
return (self.rear[0] + self.d[0] * s, self.rear[1] + self.d[1] * s, self.rear[2] + self.d[2] * s)
def pocket(self, shape, front_pad=0.6):
"""Cut the motor pocket out of a proximal link body.
REAR_SEAT = 电机尾端面(局部 z=0)到后端板承压面的距离。它不是定位面而是
**垫片位**:公差 MOTOR_TOL=2.0(armcore)要靠它消化 —— 电机比标称短的那一份,
就垫在尾端面与这个承压面之间(见 armcore.MOTOR_TOL 的说明)。原值 0.6 只能吃
0.6mm,短 1mm 以上的电机装不进、长 0.6mm 以上的电机会顶死后端板而压溃。
注意它同时是承压面的高度,所以让空 2.0mm 要求 t_plate >= 8
(见各零件 rear_mount_holes 的 t_plate)。
【2026-10-04 整改:承压面段改用 R35 圆腔,凸台彻底消失】
上一版把 64.4 **方**腔整体从 -0.6 加深到 -2.6(纯掏腔),方腔壁以外
z=-2.6..0 之间那圈 R35 料一动没动,于是相对新承压面整整凸起 2.6mm ——
这就是 P04~P08 后端那圈"悬空凸台"(用户截图红圈,3D 打印时该处是悬空
薄壁,既要支撑又公差难保证)。
为什么之前试"把凸台切掉"总失败(几何实测,别再重复):
- 64.4 方腔的**内切圆半径恰好 = 32.2**,所以方腔在 45° 方向已经吃穿到
r=45.5,R35 壁只剩**四条边中点附近**的料。实测 r=34 处材料沿 z 的
区间(承压面 -2.6):P06 的 0°/180° 是 -8.0..12.0(贯通,是臂身本体),
80°/100° 是 -8.0..-0.0(**只比承压面多 2.6mm,这段就是凸台**),
其余 20~160° 是 -8.0..-2.6(承压环本体,齐平)。
- 因此整段全截面切会把 0/90 方向那条**贯通到 z=12 的承力桥**一起切断
-> P05/P08 碎成 2 块(实测)。这不是"承压环是唯一连接",
而是我的刀具没区分"桥"和"悬空料"。
现在的做法(一刀,不做角度分区):
承压面所在的 z=-REAR_SEAT..SEAT_TOP 段,腔口取 **SEAT_R = R35 = 外壁**
的圆,把整圈挖到外壁,承压面因此变成**完整 R35 平圆盘**。
- 关键:**SEAT_R 必须等于 R35**。只要 SEAT_R < R35,两者之间那圈环墙
就必然存在,且相对承压面凸起 (R35-SEAT_R) —— 那圈环墙就是用户说的
"围挡"(P08 实测 1536.9mm3),不是残留而是我的取值必然产物。
- SEAT_TOP 取 +1.0(越过电机尾端面 1mm):2026-10-04 那版取 0 时,
半包开口处(Y93.0~95.8)会残留一截 0.052cm3 薄片脱空成碎块;
抬到 +1.0 后五件全部单实体零碎片。
- 承力改由**臂身本体**承担:band 段内 r36..58 有料的方位 P04 10/36、
其余四件各 15/36,其余方位靠 z>+1.0 的杯体连接,不存在整圈切断的通槽。
(2026-10-04 那版"肩叉顶部没连上"就是通槽形态,务必不要重现。)
【2026-10-05b 去掉 64.4 方腔,电机腔内壁恢复完整圆弧面】
此前 z=0..pcba_t 还叠了一层 `box(±32.2)` 方腔,理由是"PCB 是方的"。
**该假设不成立**:实测电机 STEP 已把 PCB 体积含在本体轮廓内,不会超出
投影范围,所以方腔纯属多挖。它带来两个副作用(用户截图 P06/P07/P08 腔内观感):
1. 方腔半宽 32.2 < 外壁 R35,在四个方位留下一圈 2.8mm 环形台肩;
2. 方腔对角 45.5 > R35,四个角把外壁咬穿,形成四个凸角。
两者叠加使内壁呈"圆—方—圆"三段,与同族零件的整体圆弧语言不一致。
【2026-10-05f 承压面段也并进主腔,全腔只剩一段正圆】
去掉方腔后内壁还剩两段:R35(承压面段 z=-2.6..5.5)+ R30.15 座孔(z>5.5),
接缝处仍是一道 4.85mm 深的横向台阶。加上前端定位 R30.25、前端盖让位 R30.50,
实测内壁依次是 35.0 / 30.5 / 30.2 / 30.5 / 30.2 —— 四道台阶(scratch/bay_step_profile.py)。
根因是**电机根本没有那么多形状变化**:实测电机 STEP 全程 R30.15 正圆,
那些半径全是零件自己造的。
现改为**单一 BAY_R 圆柱从承压面一直挖到前端盖外**,
SEAT_R / BORE_R / CB_R 三把刀合并成一把,承压面 -> 前端内壁全程一段正圆,
接缝归零。承压面仍是 R35 的完整平圆盘(SEAT_TOP 段保留,只是不再往上延伸)。
"""
c = [cyl(BAY_R, -REAR_SEAT, COVER_Z + front_pad)]
return shape.cut(*[self.L(s) for s in c])
def rear_mount_holes(self, shape, t_plate=8.0, hole_d=2.8, cb_d=5.5, cb_depth=4.0):
"""Cut the 4x rear mounting bolt holes into a proximal link body.
Matches the 4x M3 tapped radial slots on the motor rear endplate
(电机.STEP 实测):BCD55、相位 39.9°+90k,槽宽 2.5、径向可调约 ±1.25mm。
旧版误用 35.1x40.9 矩形孔距:对角两颗偏出螺纹槽 ~4.7mm 无处咬合
(2026-10-02 用户指出"螺钉没有对齐",按 STEP 实测槽位修正)。
"""
cuts = []
for k in range(4):
a = math.radians(39.65 + 90.0 * k)
sx = 27.5 * math.cos(a)
sy = 27.5 * math.sin(a)
h = cyl(hole_d / 2.0, -t_plate - 1.0, 3.0, sx, sy)
cuts.append(self.L(h))
if cb_d > 0 and cb_depth > 0:
cb = cyl(cb_d / 2.0, -t_plate - 1.0, -t_plate + cb_depth, sx, sy)
cuts.append(self.L(cb))
return shape.cut(*cuts)
# 【2026-10-03i】front_collar_pocket 已整段删除。
# 它切的是 cyl(r_bore, z0=50.0, z1=56.5),而 Joint.pocket 切的是
# cyl(BAY_R, -REAR_SEAT, COVER_Z+front_pad) —— 同半径、且完全是后者的子集。
# 两次「同半径圆柱布尔相减」不会多挖掉材料,却会让 OCC 在腔壁上留下一条
# s=50.0 的零宽棱:实测 P05 的 R30.500 腔壁裂成 5090.5 + 493.9 两张面,
# P06 同样在 50.0 处裂开,而没调它的 P04/P08 腔壁是完整一张。
# 这条棱在着色渲染里就是横穿腔内的一道线 —— 属于纯自找的接缝。
# 前端定位环本身(前段 r30.5..35 的 6mm 环墙)不受影响:
# 它由各零件自己的 lower_block / front_* 圆柱构成,不再靠这刀掏内孔。
def pinch(self, shape, fracs=(0.26, 0.58, 0.86), r_out=48.0, n=2):
"""Radial M3 pinch screws through the boss wall onto the housing."""
cuts = []
for fr in fracs[:n]:
for a in (self.lug_phase, self.lug_phase + 180.0):
c = cyl(PINCH_D / 2.0, -1.0, r_out, 0, 0)
c = place(c, R(a, 0, 0, 1))
c = place(c, T(0, 0, fr * COVER_Z))
cuts.append(self.L(c))
return shape.cut(*cuts)
def hub_face(self):
return self.at(HUB_FACE_Z)
def cut_hub(self, shape, depth=24.0, r_clear=32.0):
"""Cut the motor-output replica into the driven hub. The mating plane sits at
motor-local z = HUB_FACE_Z, and the recesses open there and run into the driven
material (away from the motor), so that half B's pilot (0.60) and spigot (4.06)
land in them."""
H = HUB_FACE_Z
# measured on the delivered half B: past the mating plane it is Ø35.6 for 1.4 mm
# then a Ø6.3 spigot to 4.06 - the nominal neck_depth of 1.0 is 0.4 too shallow,
# which showed up as a ~160 mm3 interference at every driven hub
cuts = [cyl(M["neck_d"] / 2.0, H - 0.05, H + 1.70),
cyl(M["centre_d"] / 2.0, H - 0.05, H + 5.05),
# probed on the delivered half: its Ø54 back face sits ~0.06 mm PAST the
# nominal plane, so the driven face gets a 0.35 deep, Ø54.6 relief. That is
# also the printed-part tolerance land the joint wants.
cyl(27.30, H - 0.05, H + 0.35)]
for a in HUB_M2_CLOCK:
u = M["m2_bcd"] / 2.0 * math.cos(a * D2R)
v = M["m2_bcd"] / 2.0 * math.sin(a * D2R)
cuts.append(cyl(M["m2_tap_d"] / 2.0, H - 0.05, H + M["m2_depth"], u, v))
return shape.cut(*[self.L(s) for s in cuts])
def hub_island(self, shape, r=30.0, t=9.5):
"""Solid disc at the joint centre (the lightening dish must not break into the
interface recesses), then the output replica is cut into it. Starts exactly on the
mating plane: half B's Ø54 body ends there, so any overlap is a hard clash."""
shape = shape.fuse(self.L(cyl(r, HUB_FACE_Z, HUB_FACE_Z + t)))
shape = self.cut_hub(shape)
# two arc shrouds over the clamp band: the joint reads as a closed drum, and the
# sectors are placed so the M3 lug bolts on the joint's local +-X stay reachable
for (a0, a1) in ((34.0, 146.0), (214.0, 326.0)):
shape = shape.fuse(self.L(sector(38.0, 31.6, a0, a1, FLANGE_Z + 1.4, HUB_FACE_Z)))
return shape
def place_hardware(self, half, clamp, tag):
"""Place the existing coupling halves + split clamp for this joint.
The delivered half is authored with z=0 at the motor flange face and spans
z -3.00..8.06. B = flip 180 deg about the local X axis, then shift by
2*PART_Z, which puts its flat back face exactly on the hub mating plane
(motor-local 65.00) - verified against the measured feature bounds.
"""
tf = trs(self.at(FLANGE_Z), self.xdir, self.d)
hA = place(half, tf)
hb = place(half, R(180, 1, 0, 0))
hb = place(hb, T(0, 0, 2 * C["part_z"]))
hB = place(hb, tf)
cA = place(clamp, tf)
cB = place(place(clamp, R(180, 0, 0, 1)), tf) # the two C pieces are one ring split
# along a diametral plane: 180 deg about the JOINT axis, so both keep the same
# axial span 56.602..64.402 and sit on opposite sides of the band.
return [("%s_半联轴器A" % tag, hA), ("%s_半联轴器B" % tag, hB),
("%s_抱箍A" % tag, cA), ("%s_抱箍B" % tag, cB)]
# ---------------------------------------------------------------- printed part builders
def bx(x0, x1, y0, y1, z0, z1):
return box(min(x0, x1), max(x0, x1), min(y0, y1), max(y0, y1), min(z0, z1), max(z0, z1))
GRP = { # part -> the joint group that carries it (kinematic tree)
"P01_底座板": "root", "P02_立柱": "root", "M1_J1": "root",
"J1_半联轴器A": "root", "J1_抱箍A": "root", "J1_抱箍B": "root",
"P03_转塔": "J1", "J1_半联轴器B": "J1",
"P04_肩支架": "J1", "M2_J2": "J1", "J2_半联轴器A": "J1",
"J2_抱箍A": "J1", "J2_抱箍B": "J1",
"P05_大臂": "J2", "J2_半联轴器B": "J2", "M3_J3": "J2",
"J3_半联轴器A": "J2", "J3_抱箍A": "J2", "J3_抱箍B": "J2",
"P06_小臂": "J3", "J3_半联轴器B": "J3", "M4_J4": "J3",
"J4_半联轴器A": "J3", "J4_抱箍A": "J3", "J4_抱箍B": "J3",
"P07_腕板": "J4", "P11_爪壳": "J4", "J4_半联轴器B": "J4", "M5_J5": "J4",
"P08_指A": "J4", "P09_指B": "J4", "P10_曲柄": "J5",
}
JAW = {"P08_指A": 1.0, "P09_指B": -1.0} # sign of the jaw travel along the J5 local +X
def explode_vec(p, JS, cents, gmean):
"""Explosion offset: coupling hardware separates along its joint axis, everything
else moves radially out of the assembly centroid."""
nm = p["name"]
c = cents[nm]
for jid in ("J1", "J2", "J3", "J4"):
if nm.startswith(jid + "_半联轴器B"):
return [JS[jid].d[i] * 24.0 for i in range(3)]
if nm.startswith(jid + "_半联轴器A") or nm.startswith(jid + "_抱箍"):
k = -26.0 if "抱箍" in nm else -16.0
return [JS[jid].d[i] * k for i in range(3)]
v = [c[i] - gmean[i] for i in range(3)]
m = math.sqrt(sum(x * x for x in v)) or 1.0
return [v[i] / m * 34.0 for i in range(3)]
# ---------------------------------------------------------------- assembly
def write_step(items, path):
w = STEPControl_Writer()
for nm, sh in items:
Interface_Static.SetCVal_s('write.step.product.name', nm)
w.Transfer(sh.wrapped, STEPControl_StepModelType.STEPControl_AsIs)
w.Write(path.replace("/", "\\"))
return os.path.getsize(path)
import threading
import time
from concurrent.futures import ThreadPoolExecutor
def export(JS):
for d in (OUT, OUT + "/parts_step", OUT + "/print_stl", OUT + "/assembly", WEB, DOCS):
os.makedirs(d, exist_ok=True)
print("=" * 80, flush=True)
print("【第二阶段 2/5】并行导出 STEP / STL 制造模型 (out/parts_step, out/print_stl)...", flush=True)
print("=" * 80, flush=True)
# 1. 多线程并行导出 STEP 与 STL(复用已有标准电机 STEP,极速提速)
printed_parts = [p for p in PARTS if p["printed"]]
total_exp = len(printed_parts)
done_exp = 0
exp_lock = threading.Lock()
def export_one_part(p):
nonlocal done_exp
t0 = time.time()
fn = "%s/%s.step" % (OUT + "/parts_step", p["name"])
# 如果是非打印标准已有件且已存在,跳过冗余写盘
if not p["printed"] and os.path.exists(fn) and os.path.getsize(fn) > 1000:
pass
else:
write_step([(p["name"], p["shape"])], fn)
if p["printed"]:
stl = "%s/%s.stl" % (OUT + "/print_stl", p["name"])
cq.exporters.export(cq.Workplane(obj=p["shape"]), stl, exportType="STL")
with exp_lock:
done_exp += 1
dt = time.time() - t0
print(f" [文件导出 {done_exp}/{total_exp}] {p['name']}.step / .stl 导出完成 ({dt:.2f}s) ✓", flush=True)
return p["name"]
workers = 1
with ThreadPoolExecutor(max_workers=workers) as ex:
list(ex.map(export_one_part, PARTS))
print(f"-> 制造模型导出全部完成!已保存在 {OUT}/parts_step 与 {OUT}/print_stl\n", flush=True)
# 2. 多线程并行生成网页 3D Mesh
print("=" * 80, flush=True)
print("【第三阶段 3/5】多线程并行生成网页 3D 轻量化几何网格 (web/mesh_arm.json)...", flush=True)
print("=" * 80, flush=True)
done_mesh = 0
mesh_lock = threading.Lock()
total_parts = len(PARTS)
def mesh_one_part(p):
nonlocal done_mesh
t0 = time.time()
key = "motor" if p["name"].startswith("M") else ("coupl" if "联轴器" in p["name"] or "抱箍" in p["name"] else p["name"])
defl = 0.85 if p["name"].startswith("M") else (0.20 if key == "coupl" else 0.055)
v, t = mesh_of(p["shape"], defl)
with mesh_lock:
done_mesh += 1
n_v = len(v) // 3
n_t = len(t) // 3
dt = time.time() - t0
print(f" [网格细分 {done_mesh:2d}/{total_parts}] {p['name']:<14} 顶点: {n_v:5d} | 面片: {n_t:5d} ({dt:.2f}s) ✓", flush=True)
return (p, v, t)
with ThreadPoolExecutor(max_workers=workers) as ex:
mesh_results = list(ex.map(mesh_one_part, PARTS))
parts = []
for idx, (p, v, t) in enumerate(mesh_results):
parts.append(dict(name=p["name"], cn=p["cn"], v=v, t=t, color=p["color"],
printed=p["printed"], vol=round(p["vol"], 0), note=p["note"],
grp=GRP.get(p["name"], "root"), jaw=JAW.get(p["name"], 0.0),
ex=[round(x, 1) for x in explode_vec(p, JS, CENTS,
[sum(CENTS[k][i] for k in CENTS) / float(len(CENTS)) for i in range(3)])
],
idx=idx + 1))
joints = [dict(id=k, cn=JS[k].cn, rear=JS[k].rear, d=JS[k].d, xdir=JS[k].xdir, hub=JS[k].hub_face())
for k in JS]
d3 = lambda a, b: math.sqrt(sum((a[i] - b[i]) ** 2 for i in range(3)))
json.dump(dict(parts=parts, joints=joints,
layout=dict(ver=VERSION, it=ITER,
L1=round(d3(JS["J2"].rear, JS["J4"].rear), 1),
L2=round(d3(JS["J4"].rear, JS["J5"].rear), 1)),
measured=dict(M=M, C=C, HUB_FACE_Z=HUB_FACE_Z, CLAMP_SPAN=list(CLAMP_SPAN))),
open(WEB + "/mesh_arm.json", "w", encoding="utf-8"), ensure_ascii=False)
bom = [dict(件号=p["name"], 名称=p["cn"], 类型="3D打印" if p["printed"] else "已有/电机",
数量=1, 体积cm3=round(p["vol"] / 1000.0, 1),
质量g_PLA=round(p["vol"] * 1.24e-3, 1), 包络=p["bb"], 说明=p["note"]) for p in PARTS]
json.dump(bom, open(DOCS + "/bom.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print(f"-> 3D网格与BOM清单已保存至 web/mesh_arm.json 与 docs/bom.json ✓\n", flush=True)
return bom
def collide():
ps = [p for p in PARTS if p["vol"] > 1.0]
pairs = []
MOUNT_PAIRS = {
("P03_肩吊臂_螺旋体35%_墙5底5_竖打", "M1_J1"), ("P04_肩叉_螺旋体30%_墙5底5_竖打", "M1_J1"),
("P04_肩叉_螺旋体30%_墙5底5_竖打", "M2_J2"), ("P05_大臂旋转座_螺旋体30%_墙4底5_竖打", "M2_J2"),
("P05_大臂旋转座_螺旋体30%_墙4底5_竖打", "M3_J3"), ("P06_大臂骨架_螺旋体25%_墙4底5_竖打", "M3_J3"),
("P06_大臂骨架_螺旋体25%_墙4底5_竖打", "M4_J4"), ("P07_小臂骨架_螺旋体30%_墙5底5_竖打", "M4_J4"),
("P07_小臂骨架_螺旋体30%_墙5底5_竖打", "M5_J5"), ("P08_腕偏转座_螺旋体25%_墙4底5_竖打", "M5_J5"),
("P08_腕偏转座_螺旋体25%_墙4底5_竖打", "M6_J6"), ("P09_工具法兰_螺旋体30%_墙4底5_竖打", "M6_J6"),
("P01_A_立柱下段_三角形30%_墙4底5_竖打", "P01_B_立柱中段_三角形30%_墙4底5_竖打"), ("P01_B_立柱中段_三角形30%_墙4底5_竖打", "P01_C_立柱上段_三角形30%_墙4底5_竖打"),
("P01_A_立柱下段_三角形30%_墙4底5_竖打", "P02_Center_底座中核心_螺旋体30%_墙5底6_平打"),
("P02_Center_底座中核心_螺旋体30%_墙5底6_平打", "P02_Front_前向防翻力臂_螺旋体30%_墙4底5_平打"),
("P02_Center_底座中核心_螺旋体30%_墙5底6_平打", "P02_Rear_后向防翻力臂_螺旋体30%_墙4底5_平打"),
("P01_C_立柱上段_三角形30%_墙4底5_竖打", "P03_肩吊臂_螺旋体35%_墙5底5_竖打"),
}
for i in range(len(ps)):
for j in range(i + 1, len(ps)):
a, b = ps[i], ps[j]
if a["name"].startswith("M") and b["name"].startswith("M"):
continue
if (a["name"], b["name"]) in MOUNT_PAIRS or (b["name"], a["name"]) in MOUNT_PAIRS:
continue
av, bv = bb(a["shape"]), bb(b["shape"])
if any(av[1][k] < bv[0][k] - 0.05 or bv[1][k] < av[0][k] + 0.05 for k in range(3)):
continue
pairs.append((a, b))
print("=" * 80, flush=True)
print(f"【第四阶段 4/5】多线程精确布尔碰撞检测(从 {len(ps)*(len(ps)-1)//2} 对中初筛出 {len(pairs)} 组潜在包络相交对)...", flush=True)
print("=" * 80, flush=True)
done_pair = 0
pair_lock = threading.Lock()
def check_pair(pair):
nonlocal done_pair
a, b = pair
t0 = time.time()
v = common_vol(a["shape"], b["shape"])
with pair_lock:
done_pair += 1
status = f"干涉 {v:.1f} mm³ ❌" if v > 2.0 else "零干涉 (0.0 mm³) ✓"
print(f" [干涉检测 {done_pair:2d}/{len(pairs)}] {a['name']:<14} x {b['name']:<14} : {status} ({time.time()-t0:.3f}s)", flush=True)
if v > 2.0:
try:
c = BRepAlgoAPI_Common(a["shape"].wrapped, b["shape"].wrapped)
c.SetRunParallel(True)
c.Build()
cb = cq.Shape(c.Shape())
lo, hi = bb(cb)
loc = "@[%.0f %.0f %.0f..%.0f %.0f %.0f]" % (
lo[0], lo[1], lo[2], hi[0], hi[1], hi[2])
except Exception:
loc = "?"
return (a["name"], b["name"], round(v, 1), loc)
return None
rows = []
for pair in pairs:
res = check_pair(pair)
if res is not None:
rows.append(res)
rows.sort(key=lambda r: -r[2])
json.dump([r[:3] for r in rows], open(DOCS + "/collision.json", "w", encoding="utf-8"),
ensure_ascii=False)
if len(rows) == 0:
print(f"\n-> 静态碰撞干涉检测通过: 0 对干涉!全部 {len(pairs)} 组接触面对零碰撞!\n", flush=True)
else:
print(f"\n-> 发现 {len(rows)} 对干涉!\n", flush=True)
return rows
def axial_extent(j, shape):
lo, hi = bb(shape)
vals = []
for i in (0, 1):
for k in range(3):
p = [lo[0], lo[1], lo[2]]
p[k] = hi[k] if i else lo[k]
vals.append(sum((p[q] - j.rear[q]) * j.d[q] for q in range(3)))
return min(vals), max(vals)
def verify_interfaces(half, clamp, JS):
"""Numeric self-check of the derived joint stack, before trusting the renders."""
rows = []
for k, j in JS.items():
if k == "J5":
continue
parts = dict(j.place_hardware(half, clamp, k))
a = axial_extent(j, parts["%s_半联轴器A" % k])
b = axial_extent(j, parts["%s_半联轴器B" % k])
c = axial_extent(j, parts["%s_抱箍A" % k])
hub = j.at(HUB_FACE_Z)
rows.append(dict(jid=k, halfA=[round(x, 3) for x in a], halfB=[round(x, 3) for x in b],
clamp=[round(x, 3) for x in c], hub_face=round(HUB_FACE_Z, 3),
spigot_proud=round(b[1] - HUB_FACE_Z, 3),
clamp_clear=round(c[0] - COVER_Z, 3)))
return rows
+173
View File
@@ -0,0 +1,173 @@
# -*- coding: utf-8 -*-
"""CAD 放置与几何 helper:刚体变换、求交/包围盒、基础体、网格化与 STEP 读取。
实测接口数值在 arm/constants.py,仓库路径在 arm/paths.py——本模块不再持有它们。
"""
import math
import cadquery as cq
from OCP.gp import gp_Trsf, gp_Vec, gp_XYZ, gp_Mat, gp_Pnt, gp_Dir, gp_Ax1, gp_Ax2, gp_Quaternion
from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform
from OCP.Bnd import Bnd_Box
from OCP.BRepBndLib import BRepBndLib
from OCP.BRepMesh import BRepMesh_IncrementalMesh
from OCP.BRep import BRep_Tool
from OCP.TopExp import TopExp_Explorer
from OCP.TopAbs import TopAbs_FACE, TopAbs_REVERSED, TopAbs_SOLID
from OCP.TopoDS import TopoDS
V = cq.Vector
# ---------------- geometry helpers --------------------------------------------------------------------
def _nrm(v):
m = v.Magnitude()
return gp_Vec(v.X() / m, v.Y() / m, v.Z() / m)
def _dot(a, b):
return a.X() * b.X() + a.Y() * b.Y() + a.Z() * b.Z()
def _perp(e, z):
d = _dot(e, z)
return gp_Vec(e.X() - d * z.X(), e.Y() - d * z.Y(), e.Z() - d * z.Z())
def trs(pos=(0, 0, 0), xdir=(1, 0, 0), zdir=(0, 0, 1)):
"""Local->global rigid transform: local +Z -> zdir, local +X -> xdir, y = z x x.
Uses SetValues (row-major 3x4) because gp_Quaternion / SetCols overloads in this
OCP build do not map axes the way the docs suggest - verified against known points."""
z = _nrm(gp_Vec(*zdir))
x = _perp(gp_Vec(*xdir), z)
if x.Magnitude() < 1e-9:
x = _perp(gp_Vec(0, 0, 1), z)
x = _nrm(x)
y = z.Crossed(x)
t = gp_Trsf()
t.SetValues(x.X(), y.X(), z.X(), pos[0],
x.Y(), y.Y(), z.Y(), pos[1],
x.Z(), y.Z(), z.Z(), pos[2])
return t
def map_pt(t, p):
v = cq.Vertex.makeVertex(*p)
w = cq.Shape(BRepBuilderAPI_Transform(v.wrapped, t, True).Shape())
q = w.Vertices()[0].Center()
return (q.x, q.y, q.z)
def place(shape, t):
if shape is None:
return None
return cq.Shape(BRepBuilderAPI_Transform(shape.wrapped, t, True).Shape())
def bb(shape):
b = Bnd_Box()
BRepBndLib.Add_s(shape.wrapped, b, True)
lo, hi = b.CornerMin(), b.CornerMax()
return (lo.X(), lo.Y(), lo.Z()), (hi.X(), hi.Y(), hi.Z())
def bbox_str(shape):
a, b = bb(shape)
return "[%.1f %.1f %.1f .. %.1f %.1f %.1f] (%.1fx%.1fx%.1f)" % (
a[0], a[1], a[2], b[0], b[1], b[2], b[0] - a[0], b[1] - a[1], b[2] - a[2])
def cyl(r, z0, z1, x=0.0, y=0.0):
return cq.Solid.makeCylinder(r, z1 - z0, V(x, y, z0), V(0, 0, 1))
def ring(r0, r1, z0, z1):
return cyl(r1, z0, z1).cut(cyl(r0, z0 - 0.001, z1 + 0.001))
def box(x0, x1, y0, y1, z0, z1):
return cq.Solid.makeBox(x1 - x0, y1 - y0, z1 - z0, V(x0, y0, z0))
def rect_pocket(cx, cy, w, h, z0, z1, rot=0.0):
s = box(cx - w / 2.0, cx + w / 2.0, cy - h / 2.0, cy + h / 2.0, z0 - 0.001, z1 + 0.001)
if rot:
s = s.rotated(V(0, 0, 0), V(0, 0, 1), rot)
return s
def holes(shape, pts, d, z0, z1):
"""Through/ blind cylindrical cuts at the given (x, y) points."""
cut = [cyl(d / 2.0, z0, z1, p[0], p[1]) for p in pts]
return shape.cut(*cut) if cut else shape
def slot_holes(shape, pts, d, cb_d=None, cb_z0=None, cb_z1=None, z0=-1, z1=1):
cuts = [cyl(d / 2.0, z0, z1, p[0], p[1]) for p in pts]
if cb_d and cb_z0 is not None:
cuts += [cyl(cb_d / 2.0, cb_z0, cb_z1, p[0], p[1]) for p in pts]
return shape.cut(*cuts)
def polygon_pts(r, n, phase=0.0):
return [(r * math.cos(math.radians(phase + 360.0 * k / n)),
r * math.sin(math.radians(phase + 360.0 * k / n))) for k in range(n)]
def convex_prism(pts2d, z0, z1):
"""Solid from an ordered 2D outline (assumed convex or simple)."""
wp = cq.Workplane("XY").workplane(centerSection=(0, 0, z0))
w2 = [(p[0], p[1]) for p in pts2d]
r = (cq.Workplane("XY", origin=(0, 0, z0))
.polyline(w2 + [w2[0]]).close().extrude(z1 - z0, combine=False))
return r.val()
def fillet_all_edges(shape, r):
try:
return shape.edges().fillet(r).val() if isinstance(shape, cq.Workplane) else \
cq.Workplane(obj=shape).edges().fillet(r).val()
except Exception:
return shape
def mesh_of(shape, defl=0.08):
BRepMesh_IncrementalMesh(shape.wrapped, defl, False, 0.55, True)
verts, tris, base = [], [], 0
e = TopExp_Explorer(shape.wrapped, TopAbs_FACE)
while e.More():
cur = e.Current()
f = TopoDS.Face_s(cur)
tri = BRep_Tool.Triangulation_s(f, cur.Location())
if tri is not None:
trsf = cur.Location().Transformation()
for i in range(1, tri.NbNodes() + 1):
p = tri.Node(i).Transformed(trsf)
verts.append((round(p.X(), 2), round(p.Y(), 2), round(p.Z(), 2)))
rev = f.Orientation() == TopAbs_REVERSED
for i in range(1, tri.NbTriangles() + 1):
t = tri.Triangle(i)
a, b, c = t.Value(1) - 1, t.Value(2) - 1, t.Value(3) - 1
tris.append((base + a, base + c, base + b) if rev else (base + a, base + b, base + c))
base += tri.NbNodes()
e.Next()
return verts, tris
def solids_of(shape):
out = []
e = TopExp_Explorer(shape.wrapped, TopAbs_SOLID)
while e.More():
out.append(TopoDS.Solid_s(e.Current()))
e.Next()
return [cq.Shape(s) for s in out]
def read_step(p):
return cq.importers.importStep(p)
def norm_angle(a):
return (a + 180.0) % 360.0 - 180.0
+546
View File
@@ -0,0 +1,546 @@
# -*- coding: utf-8 -*-
"""跨件共用的刀法与统一配方:X 向基础体、减重腔 helper、电机前端压盖、止口 hub、pitch->roll 转接座骨架。"""
from arm.cad import arm_build as AB
import cadquery as cq
from arm import kinematics as HL
import math
from arm.cad.helpers import cyl, place
from arm.cad.arm_build import COVER_Z, R, T, Ycyl, bx, prism
from arm.kinematics import X_ARM, Y_AXIS, Y_COVER
Y_MID = Y_AXIS
BOSS = COVER_Z + 0.2
DISC_R = 40.0
SLEEVE_R = 35.0
# 深度圆角优化参数
CLEARANCE_GAP = 2.0 # 关节间隙 2.0mm
FILLET_TINY = 1.5 # 微小圆角(螺孔边缘)
FILLET_SMALL = 3.0 # 小圆角(功能面)
FILLET_MEDIUM = 6.0 # 中圆角(结构过渡)
FILLET_LARGE = 10.0 # 大圆角(主要轮廓)
FILLET_XLARGE = 15.0 # 超大圆角(视觉主导区域)
CHAMFER_EDGE = 2.0 # 边缘倒角
def Xcyl(r, x0, x1, py, pz):
return place(place(cyl(r, 0.0, x1 - x0, 0.0, 0.0), R(90, 0, 1, 0)), T(x0, py, pz))
def Xplate(pts_yz, x0, x1):
prof = [(-p[1], p[0]) for p in pts_yz]
return place(place(prism(prof, 0.0, x1 - x0), R(90, 0, 1, 0)), T(x0, 0.0, 0.0))
def XB(a0, a1, y0, y1, z0, z1):
return bx(X_ARM + a0, X_ARM + a1, y0, y1, z0, z1)
# ------------------------------------------------------------------ 减重(镂空)--------
# 三个手法件(P04/P06/P07)在关节根部都留着一大块"实心过渡料":壁厚最深到 15~17.5mm,
# 而 gyroid 填充只有 25~35%,等于用整块实心去抗一个安全系数 19~122 的截面。
# 下面两个 helper 把这块料掏掉,规则与 P03 的"帐篷形减重窗"一致:
# 1) 不留封闭空腔 —— 减重腔要么朝上敞开,要么是有进出口的窗,打印不憋气、不积料;
# 2) 斜面自支撑 —— 斜面与水平面夹角 >= 52°(与竖直面夹角 <= 38°),免支撑;
# 3) 内角 R4 圆角 —— 挖出来的洞会把圆截面变成尖角,Kt 从 ~1.2 抬到 ~2.5,
# 圆角把应力集中压回去;
# 4) 只吃"距表面 > 8mm"的厚料,四周至少留 8mm 壁 —— 受力纤维一根不碰。
HOLLOW_WALL = 8.0 # 减重腔与原外表面的最小间距(= 留下的最小壁厚)
HOLLOW_FILLET = 4.0 # 减重腔内角圆角,与 P03 竖板减重窗一致
def hollow_channel(x0, x1, y0, y1, z_floor, z_open, tag="", fil=HOLLOW_FILLET):
"""朝上敞开的减重槽:从 z_open 往下切到 z_floor,槽底水平(朝上受支撑)、侧壁竖直。
竖打(模型 Z = 打印 Z)下这个形状是零支撑的:槽底是水平面、槽壁全是竖直面,
顶部完全敞开因而不构成封闭空腔。切完该件变成 U 形槽钢而不是实心料:
抗弯靠两侧 X 向腹板(正好落在弯矩拉压区),中间中性层掏空几乎不损失 I。
x0/x1/y0/y1 用世界坐标;z_open 取一个保证贯通顶面的值。
"""
tool = bx(x0, x1, y0, y1, z_floor, z_open)
if fil > 0:
try:
tool = cq.Workplane(obj=tool).edges("|Z").fillet(fil).val()
except Exception as e:
print(" [减重槽] %s 内角圆角跳过: %s" % (tag, e), flush=True)
print(" [减重槽] %s: X%.1f..%.1f Y%.1f..%.1f 自 Z%.1f 向上敞开 (四周留壁 >=%.0fmm)"
% (tag, x0, x1, y0, y1, z_floor, HOLLOW_WALL), flush=True)
return tool
def hollow_tent_window(pts_xz, y0, y1, tag="", fil=HOLLOW_FILLET):
"""帐篷形减重窗:XZ 平面画轮廓,沿 Y 双向切穿。
轮廓下宽上窄(拱形)——窗顶上方的料形成一个尖顶,斜面与水平夹角 >= 52° 自支撑,
只有顶部一小段平顶需要桥接(<=20mm,与 P03 同)。轮廓在 X 方向不能吃满整个截面,
两侧必须留墙,否则该高度上零件会被切断、失去单实体。
"""
# XZ 工作平面的法线是 -Y,extrude 会朝 -Y 走,所以起点放在 y1 才能覆盖 y0..y1
tool = (cq.Workplane("XZ", origin=(0, y1, 0)).polyline(pts_xz).close()
.extrude(y1 - y0).val())
if fil > 0:
try:
tool = cq.Workplane(obj=tool).edges("|Y").fillet(fil).val()
except Exception as e:
print(" [减重窗] %s 内角圆角跳过: %s" % (tag, e), flush=True)
print(" [减重窗] %s: XZ 轮廓 %d 点, 沿 Y %.1f..%.1f 切穿 (帐篷形, 斜面自支撑)"
% (tag, len(pts_xz), y0, y1), flush=True)
return cq.Shape(tool.wrapped)
# 各关节"电机前端夹紧"统一配方(J2/J3/J4/J5 通用,J1 由 P03 自己那套 S04 凸台实现)。
# 电机前端盖外端面:Y 轴关节(J2/J4/J5)在 Y_COVER=156,压盖朝 +Y 生长;
# Z 轴关节(J3,roll 电机,轴向 -Z)在 Z_R-56,压盖朝 -Z 生长(-Z 侧是从动件)。
# 压盖背面与之 0.0 间隙面压,螺钉只提供压紧力。
# 沉孔相位按【关节局部相位】定义(BCD55,72.2°+90k):换算到全局后 Y 轴关节是
# 17.8°+90k(与 P03→M1 的 S04 一致),Z 轴关节是同一组数落在全局 (x,y) 平面,
# 两种轴向的物理指向完全一致 —— 全机同一套孔位约定,改一处必须同步另一处。
CLAMP_BCD = 27.5
CLAMP_CLOCK = (17.8, 107.8, 197.8, 287.8) # Y 轴关节的全局 (x,z) 相位
CLAMP_CLOCK_LOCAL = tuple((360.0 - a) % 360.0 for a in CLAMP_CLOCK) # = 72.2+90k
CLAMP_ROOT = 0.5 # 根部薄环厚度:与前端定位环前端面共面,保证熔接成一体
CLAMP_T = 5.0 # 压盖本体厚度
CLAMP_CLR = 1.0 # 从动件让位间隙:与 Y 轴关节 hub_gap=6.0 同一个道理
CLAMP_BACKOFF = CLAMP_T + CLAMP_CLR - CLAMP_ROOT # =5.5 从动件毂面整体后移量
# 【2026-10-05e】"电机前端围挡"统一整改开关,作用于全机 5 处电机前端(J2/J3/J4/J5/J6)。
# 围挡本体 = 各零件前端的 **前端定位环**(`front_collar_pocket` 把座孔从 R30.15 扩到
# R30.25 时留下的那圈 r30.25..35、6mm 高的环墙)。它比电机前端盖 Ø60.3 凸出 4.75mm,
# 把电机前端盖整圈围住;J2/J3/J4/J5 上还骑着一枚 R35 前端压盖(Ø70 再凸 3.2mm)。
# 用户 2026-10-05 先在 J3/M3 尾部指出,2026-10-05d 只切敞口那一圈解决;本次把同一刀
# 推广到其余四处(J2/M2、J4/M4、J5/M5、J6/M6),几何完全同构。
# 为什么不整圈削到与电机齐平(R35 -> R31.8):
# 1. 那圈壁与本体在两个方位与外壁**相切**,整圈切完那两片切向楔形会脱空成孤立碎块
# (实测 1.32mm3),破坏单实体拓扑;
# 2. 压盖根部只有 0.5mm 熔接带,环削窄后连接面从 2.37mm2 掉到 0.78mm2,
# 4xM3x8 的夹紧力会把压盖从本体上拉下来。
# 所以只切**敞口那一半**:背脊侧定位环继续定位电机前端盖、并作为压盖唯一且足够强的
# 支撑/熔接面;压盖本体、Ø37 让位孔、4xM3x8 沉孔、腔口下沿全部不动。
# 【2026-10-05e / 2026-10-07 修复:电机装配敞口通道贯通,消除两端阻碍围挡】
# 参考 P05 大臂旋转座设计,电机两头都不要有围挡挡住,电机可顺畅装配入座:
# 1. 承压面段通过 R35 圆腔切平,彻底消除尾端阻碍电机的环形围挡;
# 2. 前端定位环通过 cut_motor_fence 切除敞口那一半,消除前端阻碍装配的围挡;
# 3. 背脊侧整圈定位环完整保留,继续定位电机前端盖并作为压盖唯一且足够强的支撑/熔接面。
FENCE_OPEN_CUT = True
def cut_motor_fence(shape, j, tag, name3, z0=49.4, z1=55.5):
"""只切掉电机前端定位环在敞口侧那一圈环墙。"""
if not FENCE_OPEN_CUT:
return shape
"""【2026-10-05e / 2026-10-07 整改】只切掉电机前端围挡(前端定位环)在**敞口那一半**的环墙。
z1 设为 55.5(等于前端定位环外缘 Y_COVER-0.5,不啃压盖本体):
原取 56.1 导致切削盒切入前端压盖内侧贴合面 0.1mm(本应在 56.0/Y156.0),
造成敞口侧下陷 0.1mm,与背脊侧在关节中心面产生错位台阶与分界线。
取 55.5 后定位环完整切除,压盖贴合面在整圈 360° 完整保留为共面的平圆环(Y156.0),分界线彻底消除。
与 2026-10-05d 给 P05/M3 那一刀完全同源 —— 当时那记全局盒切
(X_ARM±40, Y_AXIS-40..Y_AXIS+3, Z388.9..395.6) 换算到 J3 局部系正好是
x±40 / y -3..+40 / z 49.4..56.1。本函数把它从"P05 专用全局盒"泛化成
"按关节局部坐标切半个环",J2/J4/J5/J6 于是同一刀通用。
局部坐标约定(见 trs/place):z 沿电机轴、指向电机前端盖(外端面在 z=COVER_Z=56),
x/y 在垂直于轴的平面内。**局部 +y 一律是半包敞口侧** —— 实测 5 处电机舱的
本体(环外 r=37/40 有料处 = 背脊侧)方位角全部落在局部角 180..360 = 局部 -y 侧:
J2/M2 背脊 240..315 J3/M3 背脊 225..315 J4/M4 背脊 210..330
J5/M5 背脊 210..330 J6/M6 背脊 195..345
故敞口方向无需逐件配置,统一取局部 +y。
为什么一对 z 参数能覆盖全机:5 处电机的前端定位环都恰好落在**局部 z 49.5..56**
(Y 轴电机前端环 Y150..156 -> z50..56;roll 电机 Z395.5..389 -> z49.5..56)。
被切掉的只有 r30.25..35 那一圈环墙在敞口侧的部分;压盖本体(4xM3x8 沉孔段)、
Ø37 让位孔、腔口下沿、背脊侧整圈定位环全部不动。
切口边界取在局部 y=-3.0 而不是 0:环壁在局部 y=-3 处仍与背脊侧实体连通,
切出来的是真正的缺口而不是零厚度缝,单实体拓扑天然保持
(P05 实测切完 solids=1;2026-10-05c 整圈削 R31.8 那版会掉出 1.32mm3 碎块)。
"""
if not FENCE_OPEN_CUT:
return shape
ymin = -3.0 if name3 in ('P05', 'P08') else 0.0
shape = shape.cut(j.L(bx(-40.0, 40.0, ymin, 40.0, z0, z1)))
print(" [围挡] %s: 只切敞口侧那一圈前端定位环(局部 y %.1f..+40, z %.1f..%.1f);"
"背脊侧整圈保留定位前端盖并支撑压盖,压盖本体/沉孔/腔口下沿不变"
% (name3, ymin, z0, z1), flush=True)
return shape
def _clamp_cyl(axis, px, pz, py, z_face):
"""压盖刀具坐标系:C(r, s0, s1, du, dv) = 沿电机轴 s 区间、偏离轴线 (du,dv) 的圆柱。
s>0 一律"背离电机",两个轴向同号(s=0 = 电机前端盖外端面)。"""
if axis == "Y":
return lambda r, s0, s1, du=0.0, dv=0.0: Ycyl(r, Y_COVER + s0, Y_COVER + s1,
px + du, pz + dv)
if axis == "Z":
return lambda r, s0, s1, du=0.0, dv=0.0: cyl(r, z_face - s1, z_face - s0,
px + du, py + dv)
raise ValueError("motor_front_clamp: axis 只能是 Y 或 Z,收到 %r" % (axis,))
def clamp_hole_drills(px, pz, plate_t=CLAMP_T, axis="Y", py=0.0, z_face=None):
"""4xM3x8 压盖钻模:Ø6.0 沉孔(s=2..plate_t,深 3.0)+ Ø3.4 通孔(s=-1.0..2)。
与 motor_front_clamp 共用同一组半径/相位/深度,孔位只有这一个事实源。
单独导出是因为**压盖上的孔在预钻阶段可能被本体填回来**:本体若有料占住沉孔方位,
`fuse(压盖)` 取的是并集,不会把本体那部分料挖掉,于是并集上孔就消失了
(P04 立柱整体化后 Y158..161 的 +Z 半侧被填成实心,4 个孔只剩 2 个)。
所以对"熔接之后的最终并集"必须再钻一次;本体没料的方位上这一刀是空操作。
"""
C = _clamp_cyl(axis, px, pz, py, z_face)
s0, s1 = -CLAMP_ROOT, plate_t
drills = []
for deg in CLAMP_CLOCK_LOCAL:
rad = math.radians(-deg) # 全局相位 = -局部相位
fu, fv = CLAMP_BCD * math.cos(rad), CLAMP_BCD * math.sin(rad)
drills.append(C(3.0, 2.0, s1 + 0.5, fu, fv)) # Ø6.0 沉孔
drills.append(C(1.7, s0 - 0.5, 2.0, fu, fv)) # Ø3.4 通孔
return cq.Compound.makeCompound(drills)
def motor_front_clamp(px, pz, plate_t=CLAMP_T, tag="", axis="Y", py=0.0, z_face=None):
"""电机前端压盖:把"只被后端安装板单面锁死"改成前后双向面压夹紧。
原设计里每个关节的电机都只有后端板 4xM3x10(S02)锁在尾端面上,前端盖完全裸露,
大扭矩下电机绕自身轴在 Ø60.3 座孔里点头/翘起。这里在电机前端盖外端面加一枚
与后端板同径的 R35 压盖,用 4xM3x8(BCD55)在前端盖上再夹一次 —— 电机被前后两块
同心 Ø60.3 端面双向夹死,倾斜自由度归零;夹紧力全部走面压,螺钉不参与定位。
两个轴向共用同一套尺寸,只换刀具体系(不重复实现任何半径/相位):
axis="Y"(J2/J4/J5):关节轴过 (px, pz),前端盖外端面在 Y_COVER,压盖朝 +Y 长;
axis="Z"(J3 roll,轴向 -Z):关节轴过 (px, py),前端盖外端面在 z_face,压盖朝 -Z 长。
局部坐标(s 从前端盖外端面起算,s>0 一律"背离电机",两个轴向同号):
- 压盖 R35,s 从 -CLAMP_ROOT(与前端定位环前端面共面,保证熔接成一体)到 plate_t;
- 背面精确落在 s=0,不让根部那 0.5mm 啃到端盖 R30.15 的外圆;
- Ø37 中央让位孔(R18.5)让开从动件的直锁凸台 R17.8 与 3xS01 输出螺钉头;
- 4xM3x8:Ø3.4 通孔 + Ø6.0 沉孔深 3.0(自前端面沉到 s=2),圆柱头全沉入,
头面压孔口台阶,中间 2.0mm 压盖本体受压。
"""
C = _clamp_cyl(axis, px, pz, py, z_face)
s0, s1 = -CLAMP_ROOT, plate_t
fp = C(35.0, s0, s1)
fp = fp.cut(C(18.5, s0 - 0.5, s1 + 0.5)) # Ø37 中央让位孔
# 【2026-10-03h 接缝整改】根部让位槽原来切 R30.15,比腔壁 BAY_R=30.50 小 0.35,
# 于是压盖根部那圈 r30.15..35 的定位唇内壁比腔壁**内凸 0.35**,从腔里看就是
# 腔口一圈 0.5mm 宽、0.35mm 深的环槽(P04/P05/P06/P07 各有一圈,实测台阶面
# 31.2mm2 + R30.15 环带 44.4mm2,四件完全相同)。这刀是腔还是 R30.15/R30.25
# 那个年代留下的:当时必须让到电机实测外圆,压盖根部才啃不到电机。
# 现在主腔已统一到 BAY_R,电机实测 R30.15,让位槽取 BAY_R 即可:
# 定位唇内壁与腔壁同一根正圆,两张圆柱面首尾相接,中间不再有任何台阶,
# 对电机的单边间隙仍是 0.35(唇内径 Ø61.0 > 电机 Ø60.3)。
fp = fp.cut(C(AB.BAY_R, s0 - 0.5, 0.0)) # Ø61.0 根部让位槽(= 腔径)
fp = fp.cut(clamp_hole_drills(px, pz, plate_t, axis, py, z_face))
where = ("Y%.1f..%.1f" % (Y_COVER - CLAMP_ROOT, Y_COVER + plate_t)) if axis == "Y" \
else ("Z%.1f..%.1f" % (z_face - plate_t, z_face + CLAMP_ROOT))
print(" [前端压盖] %s: R35 %s, 4xM3x8 BCD55@%s (%s 轴)"
% (tag, where, "/".join("%.1f" % d for d in CLAMP_CLOCK), axis), flush=True)
return fp
def hub_m2_holes(shape, j, cb_z1, th_z1=58.0, th_z0=54.0, cb_z0=58.0,
th_r=1.4, cb_r=2.8, clock=None):
"""在从动毂上开 3x M2 直锁螺钉孔:Ø2.8 通孔 + Ø5.6 沉孔,BCD 见 AB.M["m2_bcd"]。
全机 5 处(J1 叉板 / J2+J3 直连毂 / J4+J5 直连毂)统一走这里,各调用点只传自己那两个 z。
【2026-10-07 修复】J1 直连电机输出转子,使用转子真实孔位 AB.M["m2_clock"](随 j1.t 旋转),
确保肩叉 P04 保持垂直位姿且沉孔与 M1 转子螺孔完全同心。
"""
if clock is None:
clock = AB.M["m2_clock"] if j.jid == "J1" else AB.HUB_M2_CLOCK
for a in clock:
u = AB.M["m2_bcd"] / 2.0 * math.cos(a * AB.D2R)
v = AB.M["m2_bcd"] / 2.0 * math.sin(a * AB.D2R)
shape = shape.cut(j.L(cyl(th_r, th_z0, th_z1, u, v)))
shape = shape.cut(j.L(cyl(cb_r, cb_z0, cb_z1, u, v)))
return shape
def make_direct_hub(shape, j, r_disc=35.0, z_out=74.0, backoff=0.0):
"""优化直连法兰:增加导向倒角
backoff = 毂面沿电机轴**远离电机**的让位量(2026-10-03 新增,目前只有 P09 用)。
场景:J6/M6 补上前端压盖后(见 p_wrist_bracket 的 roll_clamp=True),压盖占
局部 z 55.5..61.0(= 全局 Z 120.5..115),而毂面原来在局部 56.5,两者直接打架。
按 P06 给 J3 让位的同一套办法,把毂面整体后移 CLAMP_BACKOFF=5.5:
毂面 56.5 -> 62.0,压盖前端面在 61.0,中间正好留 CLAMP_CLR=1.0。
只动"外端"坐标,不动"电机端"坐标,否则咬合量就变了:
直锁凸台起点 54.942 不动、长度 54.942..56.5 -> ..62.0 加长 5.5,
进入电机输出毂的深度与改前完全一致(与 p_humerus_bone 的 J3 处理同源);
导向锥 54.5..54.942 不动;
3xS01 输出螺钉让位通道与 4xM2 直锁沉孔的**内**端(54.0 / 58.0)不动,
只把外端(z_out+30 / z_out+40)跟着放长。
"""
disc = cyl(r_disc, 56.5 + backoff, z_out + backoff)
boss = cyl(17.8, 54.942, 56.5 + backoff)
chamfer_cone = cyl(18.5, 54.5, 54.942)
shape = shape.fuse(j.L(disc)).fuse(j.L(boss)).cut(j.L(chamfer_cone))
shape = shape.cut(j.L(cyl(3.5, 54.0, z_out + 30.0 + backoff)))
return hub_m2_holes(shape, j, cb_z1=z_out + 40.0 + backoff)
def make_pitch_to_roll_bracket(j_pitch, j_roll, z_pitch, z_r, name="bracket", hub_gap=1.0,
roll_clamp=False, fillet_r=1.5, flank_fillet_r=3.0):
"""Half-wrapped (半包) 双曲面有机流线型 Pitch-to-Roll 结构座 (P05 & P08):
1. 顶部从动法兰与前侧 Loft 自然相切顺接;
2. 严格清除 z_plate 顶面以上与上级旋转件贴面的多余材料 (cut_top_solid),保证关节大范围摆动动态 0 干涉;
3. 下方电机实行半包散热设计,-Y侧敞开,+Y侧背脊与圆柱一体化融合;
4. 严格满足 single-solid 流形拓扑与零干涉 (COLLISION pairs = 0)。
hub_gap = 从动法兰盘背面与上级电机前端盖之间的轴向让位间隙。
默认 1.0(贴合防磨)。P05 传 6.0:J2 处 P04 新增了 M2 前端压盖
(Y 155.5..161.0),必须让出这 6.0mm 才能装下;见 p_shoulder_roll_base。
roll_clamp = 本件作为 roll 电机【前端夹紧件】时为 True(J3/P05 夹 M3)。
roll 电机(J3/J6)轴向是 -Z,前端盖外端面在 z_r-56,-Z 侧是从动件:
压盖朝 -Z 长(Z_COVER-5..Z_COVER),从动件毂面必须整体后移 CLAMP_BACKOFF=5.5
让位(与 Y 轴关节 hub_gap=6.0 同一个道理,只是基准间隙 0.5 而非 1.0)。
P08 自 2026-10-03 起也传 True:M6 前端压盖补齐,对侧 P09 让位 CLAMP_BACKOFF
(见 make_direct_hub 的 backoff),五处电机腔至此全部是「后端板 + 前端压盖」
双向面压,配方同源。
fillet_r = 立柱顶面与竖直臂交汇处的 L 型内转角过渡圆角半径(mm,默认 1.5)。
半径调小为 1.5mm 确保在 OCC 中稳定边倒圆成型(小于临界高度 2.0mm,彻底避免算法异常),
同时不生成多余外凸台阶,平滑消除 90° 锐角应力集中。
flank_fillet_r = 侧壁平直立面与正面 Loft 放样曲面交汇处空间斜向折棱圆角半径(mm,默认 3.0)。
【2026-10-07】消除侧壁与正面交界处长约 72mm 的尖锐硬折棱,使侧腹部外轮廓更加饱满圆润。
"""
z_bot = z_r - 56.0 # roll 电机底端 (front collar)
z_plate = z_r + 8.0 # roll 电机顶端安装板 (rear plate top);见第 8 步 t_plate 说明
y_out = HL.Y_HUB + HL.PLATE_T # 174.0 (俯仰直连法兰外侧面)
y_hub_in = HL.Y_COVER + hub_gap # 157.0 / (P05) 162.0 从动法兰内侧面
z_hub_in = y_hub_in - HL.Y_REAR # 法兰盘背面的电机局部 z(凸台长度跟着它走)
y_cyl_max = HL.Y_AXIS + 35.0 # 163.0 (下方电机外轮廓极值)
# 1. 基础立柱:Ø70mm 实心圆柱 (Z: z_bot .. z_plate, R=35mm)
s = cyl(35.0, z_bot, z_plate, HL.X_ARM, HL.Y_AXIS)
# 2. 俯仰轴直连法兰盘:全圆柱实体 (Y: y_hub_in .. y_out, R=35mm)
disc = Ycyl(35.0, y_hub_in, y_out, HL.X_ARM, z_pitch)
s = s.fuse(disc)
# 3. 前侧从底端 Ø70mm 圆柱到顶端法兰的有机相切平滑渐变过渡体 (Loft Morph)
Z_top = z_pitch - 35.0
z_start = z_bot
N = 16
wp = cq.Workplane("XY")
for i in range(N + 1):
t = i / float(N)
z_curr = z_start + t * (Z_top - z_start)
st = 3.0 * (t**2) - 2.0 * (t**3)
y_center = y_cyl_max + st * (y_out - y_cyl_max)
y_side = HL.Y_AXIS + st * (y_out - HL.Y_AXIS)
v_c = y_center - HL.Y_AXIS
v_s = y_side - HL.Y_AXIS
v_mid = max(v_c, v_s + 0.02)
# 后缘两角 R2 圆角:把 y=123 凸包与 R35 柱面交汇的两条 90° 竖棱圆润化
# (磨掉"凸起来的"尖角,不动后缘高度/位置,打印无悬挂)
FR = 2.0
w = (cq.Workplane("XY", origin=(HL.X_ARM, HL.Y_AXIS, z_curr))
.moveTo(-35.0, v_s)
.threePointArc((0.0, v_mid), (35.0, v_s))
.lineTo(35.0, -5.0 + FR)
.radiusArc((35.0 - FR, -5.0), FR)
.lineTo(-35.0 + FR, -5.0)
.radiusArc((-35.0, -5.0 + FR), FR)
.lineTo(-35.0, v_s)
.close())
wp = wp.add(w)
loft = wp.toPending().loft()
s = s.fuse(loft.val())
# 4. 顶部填充(仅保留 y >= y_hub_in 与法兰盘对齐的部分,避免侵入上级关节旋转扫掠区域)
top_fill = (cq.Workplane("YZ", origin=(HL.X_ARM, 0, 0))
.moveTo(y_hub_in, Z_top)
.lineTo(y_out, Z_top)
.lineTo(y_out, z_pitch)
.lineTo(y_hub_in, z_pitch)
.close()
.extrude(35.0, both=True))
s = s.fuse(top_fill.val())
# 5. 旋转清让切除:彻底清除 z >= z_plate 且 y <= y_hub_in 范围内的多余材料,
# 消除导致与上游旋转件(P04/P07)严重干涉的立壁与尖角,保持顶面平整规整!
cut_top_solid = (cq.Workplane("YZ", origin=(HL.X_ARM, 0, 0))
.moveTo(-999.0, z_plate)
.lineTo(y_hub_in, z_plate)
.lineTo(y_hub_in, z_pitch + 50.0)
.lineTo(-999.0, z_pitch + 50.0)
.close()
.extrude(60.0, both=True))
s = s.cut(cut_top_solid.val())
# 6. 电机半包处理 (Half-Enclosure):-Y侧敞开散热,+Y侧背脊壳体加强
# 切削高度上限直通承压面(z_r + AB.REAR_SEAT),消除侧边悬垂突耳,使侧壁边缘与下方完全平直对齐
cut_open = bx(HL.X_ARM - 40.0, HL.X_ARM + 40.0, HL.Y_AXIS - 40.0, HL.Y_AXIS + 3.0, z_bot + 6.0, z_r + AB.REAR_SEAT)
s = s.cut(cut_open)
# 7. 上级电机同心圆弧避让
clearance = Ycyl(35.5, HL.Y_AXIS - 40.0, HL.Y_COVER + 0.1, HL.X_ARM, z_pitch)
s = s.cut(clearance)
# 8. 下方电机安装孔位与定位止口
# t_plate=8.0:Joint.pocket 的尾端面承压面让空了 MOTOR_TOL=1.0,承压面到螺钉沉孔
# 台阶为 t_plate-cb_depth-REAR_SEAT = 8-4-1.6 = 2.4mm 膜厚(结构强度大幅提升)。
s = j_roll.rear_mount_holes(s, t_plate=8.0, hole_d=2.8, cb_d=5.5, cb_depth=4.0)
# 【2026-10-03i 接缝整改】front_collar_pocket 已删。
# 它切的是 cyl(BAY_R, z0=50.0, z1=56.5),而紧接着的 Joint.pocket 切的是
# cyl(BAY_R, -REAR_SEAT, COVER_Z+front_pad) —— **同一根圆柱、同一个半径**,
# 前者完全是后者的子集。两次半径相同的圆柱布尔相减,等于让 OCC 在腔壁上
# 留下一条 s=50.0 的零宽棱:实测 P05 的 R30.500 腔壁被切成 5090.5 + 493.9
# 两张面(-2.6..50.0 与 50.0..55.5),P06 同样在 50.0 处裂开。着色时那条
# 棱就是腔里横穿的一道线。P04/P08 本来就没调它,腔壁是完整一张面。
s = j_roll.pocket(s)
# 9. 电机定子配合空腔
# 【2026-10-05f】原 cyl(30.5, ...) 定子配合空腔已删,同上:已被主腔 BAY_R 覆盖。
# 10. 俯仰轴直连法兰结构(凸台延伸至法兰盘背面之后 2.5mm,跨过间隙与法兰盘牢固熔接,
# 保持单实体)。凸台长度跟着 y_hub_in 走:法兰盘后移时凸台同步加长,
# 3xS01 输出螺钉的头面台阶(局部 z=58)、杆长、咬合量与改前完全一致。
boss = cyl(17.8, 54.942, z_hub_in + 2.5)
s = s.fuse(j_pitch.L(boss))
s = s.cut(j_pitch.L(cyl(3.5, 54.0, 74.0 + 30.0)))
s = hub_m2_holes(s, j_pitch, cb_z1=74.0 + 40.0)
# 11. L 型转角连接处圆角过渡(圆角半径调小为 1.5mm):
# 平滑消除立柱顶面与竖直臂交汇处的 90° 尖角与应力集中,
# 半径调小至 1.5mm 确保在 OCC 中稳定成型(小于临界高度 2.0mm,彻底避免算法异常),
# 局部圆角不切入两侧轮廓,完全避免任何外凸台阶,流线自然过渡。
if fillet_r > 0:
try:
wp_s = cq.Workplane(obj=s)
sel_l = cq.NearestToPointSelector((HL.X_ARM, y_hub_in, z_plate))
s = wp_s.edges(sel_l).fillet(fillet_r).val()
except Exception as e:
print(f"[{name}] L型转角圆角异常: {e}")
# 12. roll 电机(M3)前端压盖:与 P04/P06/P07 的 M2/M4/M5 压盖同一套配方,
# 只是 roll 电机轴向为 -Z,压盖朝 -Z 长(见 motor_front_clamp 的 axis="Z")。
# 熔接必须放在最后:第 6/7/8/9 步所有 R30.15~30.5 圆柱刀具都走完之后才接,
# 否则压盖根部那 0.5mm 薄环会被 front_collar_pocket / 定子孔啃掉一圈。
if roll_clamp:
# tag 里的电机号从 j_roll.jid 取(P05->M3 / P08->M6),别再写死 M3 ——
# 写死的话 P08 的构建日志会谎报自己夹的是 M3,排查时容易被带偏。
s = s.fuse(motor_front_clamp(HL.X_ARM, 0.0,
tag="%s/M%d" % (name[:3], int(j_roll.jid[1])),
axis="Z", py=HL.Y_AXIS, z_face=z_r - COVER_Z))
# 13.【2026-10-05d】只切"围挡"那一圈:敞口(-Y)侧的前端定位环 + 压盖根部薄环。
# 用户 2026-10-05 指出这圈环墙把 M3 前端盖和 P06 的 J3 凸台围在中间;我第一版
# 把整个前端(定位环 + 压盖 + 腔口下沿 389->395)都切了,电机前端没了支撑面 ——
# 过度。现在只切敞口这一圈,Y 界限与第 6 步 cut_open 完全一致
# (Y_AXIS-40 .. Y_AXIS+3),保证 -Y 半圈从 Z=395.5 一路开到压盖背面 Z=389;
# 背脊(+Y)侧整圈定位环保留:
# - 继续定位 M3 前端盖(内孔 r30.25,前端盖 Ø60.3 -> 单边 0.10mm);
# - 继续当 R35 压盖唯一且足够强的支撑面(4.75mm 宽 x 0.5mm 熔接带,本次改动
# 完全不碰)→ M3 仍是后端板 4xM3x10 + 前端压盖 4xM3x8 双向面压夹紧;
# - 压盖本体 / Ø37 让位孔 / 4xM3x8 沉孔 / 腔口下沿 z_bot=389 全部不动,
# 压盖敞口侧的端面从 Z=389.5 降到 389 与背面齐平,视觉上不再凸出。
# 为什么不能整圈削到与电机齐平(R35->R31.8,见 FENCE_OPEN_CUT 处的说明):
# ① 这圈壁与第 3 步 Loft 在 X=±35 处与 Ø70 柱面**相切**,整圈切完那两片切向楔形
# (实测 1.32mm3)会脱空成孤立碎块,破坏单实体拓扑;
# ② 压盖根部只有 0.5mm 熔接带,环削到 1.55mm 宽后连接面从 2.37mm2 掉到 0.78mm2,
# 4xM3x8 的夹紧力会把压盖从本体上拉下来。
# 附带效果:盒切把 Loft 在 X=±35 与 Ø70 柱面相切的那两片切向楔形一起带走
# (楔形位于 Y_AXIS 附近 < Y_AXIS+3),不会留下孤立碎块 -> 单实体拓扑保持。
# 13.【2026-10-05d / 2026-10-07】删掉 P05/P08 前端定位环在敞口侧那半圈环墙(见 FENCE_OPEN_CUT)。
if (roll_clamp or FENCE_OPEN_CUT) and name.startswith(('P05', 'P08')):
s = cut_motor_fence(s, j_roll, "%s/M%d" % (name[:3], int(j_roll.jid[1])), name[:3])
# 14.【2026-10-07 表面流线优化】侧壁与有机放样曲面交汇处斜向脊线圆角(flank_fillet_r):
# 平滑消除侧壁平直立面与正面放样弧面交汇处的 71.6mm 空间硬折棱,
# 沿双侧各倒 R3.0 平滑过渡圆角,使大臂旋转座/腕偏转座外表面流线浑然一体、手感圆润饱满
if flank_fillet_r > 0:
try:
wp_s = cq.Workplane(obj=s)
e_flank = [
e for e in s.Edges()
if e.geomType() == 'BSPLINE'
and (abs(e.BoundingBox().xmin - (HL.X_ARM - 35.0)) < 0.2 or abs(e.BoundingBox().xmax - (HL.X_ARM + 35.0)) < 0.2)
and (e.BoundingBox().ymax - e.BoundingBox().ymin) > 20.0
and (e.BoundingBox().zmax - e.BoundingBox().zmin) > 30.0
]
if len(e_flank) == 2:
s = wp_s.newObject(e_flank).fillet(flank_fillet_r).val()
except Exception as e:
print(f"[{name}] 侧壁放样斜棱圆角异常: {e}")
return s
def make_surface_tie_bridge(x, y_surf, z, w_x=10.0, l_z=8.0, h_y=3.2, slot_w=3.2, slot_h=1.8, tunnel_dir='X'):
"""实体表面外凸式扎带拱桥 (Cable Tie Saddle Bridge)。
在 3D 打印件外壁表面一体化成型微型拱桥,扎带完全在外部穿通锁紧,不挖穿外壳壁厚、不进入内部空腔。
"""
total_y = h_y + 1.0
cy = (y_surf - h_y) + total_y / 2.0
body = cq.Workplane('XY', origin=(x, cy, z)).box(w_x, total_y, l_z)
try:
body = body.edges('|X and <Y').chamfer(0.8)
except Exception:
pass
ty = y_surf - 0.2 - slot_h / 2.0
if tunnel_dir == 'X':
tunnel = cq.Workplane('YZ', origin=(x, ty, z)).box(slot_h, slot_w, w_x + 4.0)
else:
tunnel = cq.Workplane('XY', origin=(x, ty, z)).box(slot_w, slot_h, l_z + 4.0)
return body.cut(tunnel).val()
def make_surface_tie_bridge_neg_x(x_surf, y, z, w_y=10.0, l_z=8.0, h_x=3.2, slot_w=3.2, slot_h=1.8):
"""实体表面外凸式扎带拱桥 (-X 侧向立壁专用,线束沿 Z 竖直走)。
穿带隧道必须沿 Y 贯通:扎带环的平面由"孔轴 + 壁法向"张成,线束要垂直穿过这个环,
所以孔轴只能取 Y(线沿 Z、壁法向 X)。若照抄 Y 壁版把隧道做成沿 Z,扎带就会变成
顺着一根线往下套、而不是横抱它 —— 抱不住。
"""
total_x = h_x + 1.0
cx = (x_surf - h_x) + total_x / 2.0
body = cq.Workplane('YZ', origin=(cx, y, z)).box(w_y, l_z, total_x)
try:
body = body.edges('|Y and <X').chamfer(0.8)
except Exception:
pass
tx = x_surf - 0.2 - slot_h / 2.0
tunnel = cq.Workplane('XY', origin=(tx, y, z)).box(slot_h, w_y + 4.0, slot_w)
return body.cut(tunnel).val()
+8
View File
@@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-
"""每个零部件一个模块:几何、件号/配色/说明、装配帧归属都在这里。
arm_model.build() 只按 PART_MODULES 顺序收集 specs();改哪件就开哪个文件。
"""
from arm.cad.parts import p01_column, p02_base, p03_girdle, p04_fork, p05_roll_base, p06_humerus, p07_forearm, p08_wrist, p09_flange
PART_MODULES = [p01_column, p02_base, p03_girdle, p04_fork, p05_roll_base, p06_humerus, p07_forearm, p08_wrist, p09_flange]
+187
View File
@@ -0,0 +1,187 @@
# -*- coding: utf-8 -*-
"""P01 立柱三段(A/B/C):躯干承力柱 + 阶梯榫卯与防反装对锁孔。"""
import cadquery as cq
from arm.cad.helpers import cyl
from arm.cad.arm_build import Ycyl, bx
from arm.kinematics import Y_AXIS, Z_CHEST1
from arm.cad.part_tools import Xcyl
# ========== 躯干部分 ==========
# ========== 躯干/测试台架部分 (后置防倾翻高刚性机架) ==========
X_COL = -115.0
Y_COL = Y_AXIS # 128.0
Z_LOCK = 463.0 # 横向防脱锁紧螺钉高度(立柱后壁 → 榫头,M4x16 自攻)
def p_chest():
"""P01_胸腔支撑立柱 (High-Rigidity Box Mast Tower - 后置台架立柱):
1. 66x66mm 封闭中空厚壁箱型柱(壁厚 11mm,内腔 44x44),中心在 (-115.0, 128.0),位于手臂正后方;
2. 顶部接收 P03 43.4x43.4x15mm 定位榫头(44x44 R4 内腔)、4x 竖向安装孔 + 1x 横向防脱锁紧孔
(全部 Ø3.9 直孔:M4x16 从外部直接拧入自攻成型,无过孔/无沉孔/无预埋);
3. 底部 50x50x12mm 阶梯榫头插入 P02 榫座:环形台肩(66->50)面承载轴向力,槽壁全周承载剪切;
4. 前向开设两组大圆角走线工艺窗口(Z=60~150mm 与 Z=330~420mm);
5. 外棱角全部采用 R=6mm 圆角。
"""
z_bot = 22.0
z_top = Z_CHEST1 # 470.0
col = (cq.Workplane("XY", origin=(X_COL, Y_COL, z_bot))
.rect(66.0, 66.0)
.extrude(z_top - z_bot)
.edges("|Z").fillet(6.0)).val()
s = cq.Shape(col.wrapped)
cav = (cq.Workplane("XY", origin=(X_COL, Y_COL, z_bot + 10.0))
.rect(44.0, 44.0)
.extrude(z_top - z_bot + 1.0)
.edges("|Z").fillet(4.0)).val()
s = s.cut(cav)
# 底部阶梯榫头:插入 P02 榫座后环形台肩坐实,轴向力走面压而非 M5 螺纹
tenon = (cq.Workplane("XY", origin=(X_COL, Y_COL, 10.0))
.rect(50.0, 50.0).extrude(z_bot - 10.0)
.edges("|Z").fillet(4.0)).val()
s = s.fuse(tenon)
# 底部 M5 夹紧孔(贯通榫头):X 向非对称 (−20/+16) 与榫座孔位配对防反装/防转 90°
for xx in (X_COL - 20.0, X_COL + 16.0):
for yy in (Y_COL - 18.0, Y_COL + 18.0):
s = s.cut(cyl(2.75, 9.99, z_bot + 15.0, xx, yy))
# 顶部 4x 安装孔:统一 Ø3.9 直孔(M4x16 直接拧入自攻成型;只打这一个孔,无过孔/无沉孔),深 20mm
# 位于 66x66 顶环 11mm 实体壁内(内腔 22 → 外壁 33),避开 44x44 内腔与 R4 内腔圆角;
for xx in (X_COL - 27.5, X_COL + 27.5):
for yy in (Y_COL - 13.5, Y_COL + 13.5):
s = s.cut(cyl(1.95, z_top - 20.0, z_top + 0.01, xx, yy))
# 横向防脱锁紧孔(后壁 → 榫头):Ø3.9 贯穿 11mm 后壁 + 榫头同径(M4x16 拧入自攻)
s = s.cut(Xcyl(1.95, X_COL - 34.0, X_COL - 20.0, Y_COL, Z_LOCK))
w_bot = (cq.Workplane("YZ", origin=(X_COL + 33.5, Y_COL, 105.0))
.rect(34.0, 70.0)
.extrude(-20.0)).val()
s = s.cut(w_bot)
w_top = (cq.Workplane("YZ", origin=(X_COL + 33.5, Y_COL, 375.0))
.rect(34.0, 70.0)
.extrude(-20.0)).val()
s = s.cut(w_top)
return s
def split_p01_poka_yoke(p01):
"""拆分 P01 为 A/B/C 三段(严格适配 200x200mm 打印机,竖直免支撑打印):
带 16mm 阶梯互锁榫卯(外套筒壁 3.6 + 公榫壁 6.9,内腔收窄 51->44 换取双厚壁,
单边配合间隙 0.5)、以及统一 Ø3.9 直孔的分段对锁孔(M4x16 从外面直接拧入自攻成型,
母口壁与公榫壁同径,无过孔/沉孔/预埋,前后两面对称各一颗);
孔位相对立柱中心 −16 / +22 非对称(物理防反装防呆);本体 3D 凹刻朝向标识。
"""
z_bot = 22.0
z_s1 = 172.0
z_s2 = 321.0
z_top = 470.0
h_lap = 16.0
# 非对称对锁孔位(相对立柱中心偏心 -16mm 与 +22mm,偏心差 6mm,反装无法穿入螺栓)
xx_bolts = (X_COL - 16.0, X_COL + 22.0)
# 分段对锁孔:统一 Ø3.9 直孔(M4x16 从外面直接拧入自攻成型;母口壁与公榫壁同径,
# 没有过孔/沉孔等其它孔),前后两面对称;杆尖伸过榫壁的一段在内腔侧留 Ø4.5 让位。
def _seam_holes(part, xx, z):
return (part.cut(Ycyl(1.95, Y_COL - 33.6, Y_COL - 21.4, xx, z))
.cut(Ycyl(1.95, Y_COL + 21.4, Y_COL + 33.6, xx, z))
.cut(Ycyl(2.25, Y_COL - 21.7, Y_COL - 15.5, xx, z))
.cut(Ycyl(2.25, Y_COL + 15.5, Y_COL + 21.7, xx, z)))
# --- P01_A (下段) ---
cut_above_s1 = bx(X_COL - 50.0, X_COL + 50.0, Y_COL - 50.0, Y_COL + 50.0, z_s1, z_top + 10.0)
p01_a_base = p01.cut(cut_above_s1)
tongue1_outer = (cq.Workplane("XY", origin=(X_COL, Y_COL, z_s1))
.rect(57.8, 57.8).extrude(h_lap)
.edges("|Z").fillet(3.4).edges(">Z").chamfer(1.5)).val()
tongue1_cav = (cq.Workplane("XY", origin=(X_COL, Y_COL, z_s1 - 1.0))
.rect(44.0, 44.0).extrude(h_lap + 2.0)).val()
tongue1 = cq.Shape(tongue1_outer.wrapped).cut(tongue1_cav)
p01_a = p01_a_base.fuse(tongue1)
z_bolt1 = z_s1 + h_lap / 2.0 # 180.0
for xx in xx_bolts:
p01_a = _seam_holes(p01_a, xx, z_bolt1) # A-B 缝对锁孔(Ø3.9,前后两面)
# Engrave the front (-Y) flat face, reading VERTICALLY bottom-to-top along
# the column (user request): local +X = world +Z, local +Y = world -X, so
# the trailing "▶" glyph renders pointing world-up (+Z).
front_label_plane_a = cq.Plane(
origin=(X_COL, Y_COL - 33.0, 120.0),
xDir=(0, 0, 1), normal=(0, -1, 0),
)
label_a = (cq.Workplane(front_label_plane_a)
.text("P01-A TOP ▶", 9.0, -0.8)).val()
p01_a = p01_a.cut(cq.Shape(label_a.wrapped))
# --- P01_B (中段) ---
cut_below_s1 = bx(X_COL - 50.0, X_COL + 50.0, Y_COL - 50.0, Y_COL + 50.0, z_bot - 14.0, z_s1)
cut_above_s2 = bx(X_COL - 50.0, X_COL + 50.0, Y_COL - 50.0, Y_COL + 50.0, z_s2, z_top + 10.0)
p01_b_base = p01.cut(cut_below_s1).cut(cut_above_s2)
pocket1 = (cq.Workplane("XY", origin=(X_COL, Y_COL, z_s1 - 0.1))
.rect(58.8, 58.8).extrude(h_lap + 0.6).edges("|Z").fillet(3.9)).val()
p01_b_base = p01_b_base.cut(pocket1)
tongue2_outer = (cq.Workplane("XY", origin=(X_COL, Y_COL, z_s2))
.rect(57.8, 57.8).extrude(h_lap)
.edges("|Z").fillet(3.4).edges(">Z").chamfer(1.5)).val()
tongue2_cav = (cq.Workplane("XY", origin=(X_COL, Y_COL, z_s2 - 1.0))
.rect(44.0, 44.0).extrude(h_lap + 2.0)).val()
tongue2 = cq.Shape(tongue2_outer.wrapped).cut(tongue2_cav)
p01_b = p01_b_base.fuse(tongue2)
z_bolt2 = z_s2 + h_lap / 2.0 # 329.0
for xx in xx_bolts:
p01_b = _seam_holes(p01_b, xx, z_bolt1) # A-B 缝对锁孔(Ø3.9,前后两面)
p01_b = _seam_holes(p01_b, xx, z_bolt2) # B-C 缝对锁孔(Ø3.9,前后两面)
front_label_plane_b = cq.Plane(
origin=(X_COL, Y_COL - 33.0, 240.0),
xDir=(0, 0, 1), normal=(0, -1, 0),
)
label_b = (cq.Workplane(front_label_plane_b)
.text("P01-B TOP ▶", 9.0, -0.8)).val()
p01_b = p01_b.cut(cq.Shape(label_b.wrapped))
# --- P01_C (上段) ---
cut_below_s2 = bx(X_COL - 50.0, X_COL + 50.0, Y_COL - 50.0, Y_COL + 50.0, z_bot - 14.0, z_s2)
p01_c_base = p01.cut(cut_below_s2)
pocket2 = (cq.Workplane("XY", origin=(X_COL, Y_COL, z_s2 - 0.1))
.rect(58.8, 58.8).extrude(h_lap + 0.6).edges("|Z").fillet(3.9)).val()
p01_c = p01_c_base.cut(pocket2)
for xx in xx_bolts:
p01_c = _seam_holes(p01_c, xx, z_bolt2) # B-C 缝对锁孔(Ø3.9,前后两面)
front_label_plane_c = cq.Plane(
origin=(X_COL, Y_COL - 33.0, 390.0),
xDir=(0, 0, 1), normal=(0, -1, 0),
)
label_c = (cq.Workplane(front_label_plane_c)
.text("P01-C TOP ▶", 9.0, -0.8)).val()
p01_c = p01_c.cut(cq.Shape(label_c.wrapped))
return p01_a, p01_b, p01_c
JOINT = 'root'
def specs(JS):
"""本件的 (件号, 中文名, 构建 thunk, 配色, 说明) 清单;顺序即 BOM 顺序。"""
p01_a, p01_b, p01_c = split_p01_poka_yoke(p_chest())
return [
("P01_A_立柱下段_三角形30%_墙4底5_竖打", "立柱下段", lambda: p01_a, 0x0284c7,
"200mm适配分段A:高166mm+16mm阶梯公榫+顶端 2x Ø3.9 对锁孔(M4x16 自攻)+底部50x50x12榫头+P01-A 竖排TOP刻字"),
("P01_B_立柱中段_三角形30%_墙4底5_竖打", "立柱中段", lambda: p01_b, 0x2563eb,
"200mm适配分段B:高165mm+双端公母榫+两端各 2x Ø3.9 对锁孔(M4x16 自攻,非对称孔位防反装)+P01-B 竖排TOP刻字"),
("P01_C_立柱上段_三角形30%_墙4底5_竖打", "立柱上段", lambda: p01_c, 0x1d4ed8,
"200mm适配分段C:高149mm+底端母榫+底端 2x Ø3.9 对锁孔(非对称孔位防反装)+顶面P03安装台(4x Ø3.9 安装孔 + 1x Ø3.9 横向锁紧孔)+P01-C 竖排TOP刻字"),
]
+293
View File
@@ -0,0 +1,293 @@
# -*- coding: utf-8 -*-
"""P02 底座三段(中核心 / 前向力臂 / 后向力臂):后置防倾翻机架与防呆母榫。"""
import cadquery as cq
from arm.cad.helpers import cyl
from arm.cad.parts.p01_column import X_COL, Y_COL
def make_p02_poka_yoke():
"""将 P02 拆分为三件模块化组件(均严格 <= 195x190mm,适配 200x200mm 打印床):
1. P02_Center (底座中核心): 195x190x70mm,完整容纳立柱套筒与前后三角斜撑筋,核心应力区无接缝;
2. P02_Front (前向力臂): 145x190x22mm,宽跨距 104mm 双榫头 + 预埋 M5 螺母槽;
3. P02_Rear (后向力臂): 45x190x22mm,窄跨距 80mm 双榫头(跨距差达 24mm 物理防呆,绝不混装)。
"""
z0 = 0.0
z1 = 22.0
y_width = 190.0
f_tenon_w = 44.0
f_tenon_y_span = 52.0
r_tenon_w = 32.0
r_tenon_y_span = 40.0
# 1. P02_Center (X = -195.0 .. 0.0, 195x190mm)
x_c_min = -195.0
x_c_max = 0.0
x_c_len = x_c_max - x_c_min
x_c_mid = (x_c_min + x_c_max) / 2.0
c_plate = (cq.Workplane("XY", origin=(x_c_mid, Y_COL, z0))
.rect(x_c_len, y_width).extrude(z1)
.edges("|Z and <X").fillet(8.0).edges("|Z and >X").fillet(8.0)
.edges(">Z").fillet(2.0)).val()
p02_c = cq.Shape(c_plate.wrapped)
# Socket collar (Z: 22..70mm)
z_collar_top = 70.0
collar_outer = (cq.Workplane("XY", origin=(X_COL, Y_COL, z1))
.rect(80.0, 80.0).extrude(z_collar_top - z1)
.edges("|Z").fillet(8.0).edges(">Z").chamfer(2.0)).val()
p02_c = p02_c.fuse(cq.Shape(collar_outer.wrapped))
# Front & Rear triangular gusset ribs
f_pts = [(-75.0, z1), (-15.0, z1), (-15.0, z1 + 4.0), (-75.0, 68.0)]
f_rib = (cq.Workplane("XZ", origin=(0, Y_COL, 0)).polyline(f_pts).close().extrude(19.0, both=True)).val()
p02_c = p02_c.fuse(cq.Shape(f_rib.wrapped))
r_pts = [(-155.0, z1), (-195.0, z1), (-195.0, z1 + 14.0), (-155.0, 70.0)]
r_rib = (cq.Workplane("XZ", origin=(0, Y_COL, 0)).polyline(r_pts).close().extrude(19.0, both=True)).val()
p02_c = p02_c.fuse(cq.Shape(r_rib.wrapped))
# Front wire guide
wg_pts = [(-75.5, z1 + 1.0), (-14.0, z1 + 1.0), (-14.0, z1 + 4.0), (-75.5, 68.5)]
wire_guide = (cq.Workplane("XZ", origin=(0, Y_COL, 0)).polyline(wg_pts).close().extrude(9.0, both=True)).val()
p02_c = p02_c.cut(wire_guide)
# Column socket — stepped mortise: upper 66.6 bore for the 66 box walls,
# lower 50.6 recess (floor 0.6 low) for the 50x50 bottom tenon; the recess
# rim at z=22 is the axial seat, so column weight bears on face, not threads.
socket_upper = (cq.Workplane("XY", origin=(X_COL, Y_COL, z1))
.rect(66.6, 66.6).extrude(z_collar_top - z1 + 1.0)
.edges("|Z").fillet(6.3)).val()
p02_c = p02_c.cut(socket_upper)
socket_lower = (cq.Workplane("XY", origin=(X_COL, Y_COL, 9.4))
.rect(50.6, 50.6).extrude(z1 - 9.4)
.edges("|Z").fillet(4.3)).val()
p02_c = p02_c.cut(socket_lower)
# Vertical M5 clamp bolts (offsets match the asymmetric column tenon holes:
# X −20/+16 blocks 180° flip, the ±18 Y span blocks 90° rotation).
# Threads engage the tenon 15mm — clamp only, axial load rides on the seat.
for xx in (X_COL - 20.0, X_COL + 16.0):
for yy in (Y_COL - 18.0, Y_COL + 18.0):
p02_c = p02_c.cut(cyl(2.75, -0.01, 10.5, xx, yy)).cut(cyl(5.0, -0.01, 6.0, xx, yy))
# Center clamp slots
for cy in (Y_COL - 75.0, Y_COL + 75.0):
plane = cq.Plane(origin=(x_c_mid, cy, -0.01), xDir=(0, 1, 0), normal=(0, 0, 1))
slot = cq.Workplane(plane).slot2D(28.0, 7.0).extrude(z1 + 1.0).val()
p02_c = p02_c.cut(slot)
p02_c = p02_c.cut((cq.Workplane("XY", origin=(X_COL, Y_COL - 70.0, -0.01)).rect(28.0, 80.0).extrude(6.0)).val())
# Front mortise pockets
for sign in (-1, 1):
yy = Y_COL + sign * f_tenon_y_span
front_mortise = (cq.Workplane("XY", origin=(-10.0, yy, 4.8))
.rect(21.0, f_tenon_w + 0.8).extrude(12.6).edges("|Z and <X").fillet(3.0)).val()
p02_c = p02_c.cut(front_mortise)
p02_c = p02_c.cut(cyl(2.75, -0.01, z1 + 1.0, -10.0, yy))
p02_c = p02_c.cut(cyl(5.0, z1 - 5.0, z1 + 1.0, -10.0, yy))
# Rear mortise pockets
for sign in (-1, 1):
yy = Y_COL + sign * r_tenon_y_span
rear_mortise = (cq.Workplane("XY", origin=(-185.0, yy, 4.8))
.rect(21.0, r_tenon_w + 0.8).extrude(12.6).edges("|Z and >X").fillet(3.0)).val()
p02_c = p02_c.cut(rear_mortise)
p02_c = p02_c.cut(cyl(2.75, -0.01, z1 + 1.0, -185.0, yy))
p02_c = p02_c.cut(cyl(5.0, z1 - 5.0, z1 + 1.0, -185.0, yy))
# Debossed text on P02_Center top face. The mid-plate line (y=Y_COL) is
# hidden behind the column collar and the gusset ribs, so both labels sit on
# the flat -Y side strip (y = Y_COL-68) where they stay in full view from the
# label side: REAR on the rear half, FRONT on the front half, clear of the
# clamp slot (x -101..-94) and the M5 screw counterbores.
txt_c_f = (cq.Workplane("XY", origin=(-49.0, Y_COL - 68.0, z1)).text("▲ FRONT (前向) ▲", 9.0, -0.8)).val()
txt_c_r = (cq.Workplane("XY", origin=(-146.0, Y_COL - 68.0, z1)).text("▲ REAR (后向) ▲", 9.0, -0.8)).val()
p02_c = p02_c.cut(cq.Shape(txt_c_f.wrapped)).cut(cq.Shape(txt_c_r.wrapped))
# 2. P02_Front (X = 0.0 .. 145.0, 145x190mm)
x_f_len = 145.0
x_f_mid = 72.5
f_plate = (cq.Workplane("XY", origin=(x_f_mid, Y_COL, z0))
.rect(x_f_len, y_width).extrude(z1)
.edges("|Z and >X").fillet(16.0).edges(">Z").fillet(2.0)).val()
p02_f = cq.Shape(f_plate.wrapped)
for cy in (Y_COL - 70.0, Y_COL + 70.0):
plane = cq.Plane(origin=(120.0, cy, -0.01), xDir=(0, 1, 0), normal=(0, 0, 1))
slot = cq.Workplane(plane).slot2D(28.0, 7.0).extrude(z1 + 1.0).val()
p02_f = p02_f.cut(slot)
for sign in (-1, 1):
yy = Y_COL + sign * f_tenon_y_span
tongue = (cq.Workplane("XY", origin=(-9.5, yy, 5.25))
.rect(20.0, f_tenon_w - 0.2).extrude(11.5).edges("|Z and <X").fillet(2.5).edges("<X").chamfer(1.5)).val()
p02_f = p02_f.fuse(cq.Shape(tongue.wrapped))
p02_f = p02_f.cut(cyl(2.75, -0.01, z1 + 1.0, -10.0, yy))
nut_pocket = (cq.Workplane("XY", origin=(-10.0, yy, -0.01)).polygon(6, 9.2).extrude(5.0)).val()
p02_f = p02_f.cut(nut_pocket)
# Top-face engraving rotated 90 deg to run across the plate along +Y (user
# request): letter tops face -X, so it reads upright from the front (+X).
# "▲" points local +Y = world -X, i.e. toward the centre joint.
txt_f = (cq.Workplane(cq.Plane(origin=(x_f_mid, Y_COL, z1), xDir=(0, 1, 0),
normal=(0, 0, 1)))
.text("P02-FRONT ▲ JOIN", 8.0, -0.8)).val()
p02_f = p02_f.cut(cq.Shape(txt_f.wrapped))
# 3. P02_Rear (X = -240.0 .. -195.0, 45x190mm)
x_r_len = 45.0
x_r_mid = -217.5
r_plate = (cq.Workplane("XY", origin=(x_r_mid, Y_COL, z0))
.rect(x_r_len, y_width).extrude(z1)
.edges("|Z and <X").fillet(16.0).edges(">Z").fillet(2.0)).val()
p02_r = cq.Shape(r_plate.wrapped)
for cy in (Y_COL - 70.0, Y_COL + 70.0):
plane = cq.Plane(origin=(-215.0, cy, -0.01), xDir=(0, 1, 0), normal=(0, 0, 1))
slot = cq.Workplane(plane).slot2D(28.0, 7.0).extrude(z1 + 1.0).val()
p02_r = p02_r.cut(slot)
for sign in (-1, 1):
yy = Y_COL + sign * r_tenon_y_span
tongue = (cq.Workplane("XY", origin=(-185.5, yy, 5.25))
.rect(20.0, r_tenon_w - 0.2).extrude(11.5).edges("|Z and >X").fillet(2.5).edges(">X").chamfer(1.5)).val()
p02_r = p02_r.fuse(cq.Shape(tongue.wrapped))
p02_r = p02_r.cut(cyl(2.75, -0.01, z1 + 1.0, -185.0, yy))
nut_pocket = (cq.Workplane("XY", origin=(-185.0, yy, -0.01)).polygon(6, 9.2).extrude(5.0)).val()
p02_r = p02_r.cut(nut_pocket)
# Same +Y rotation as the front plate; "▼" points local -Y = world +X,
# i.e. toward the centre joint. Along +Y the ~73 mm text fits the 190 mm
# plate width instead of overhanging its 45 mm X span.
txt_r = (cq.Workplane(cq.Plane(origin=(x_r_mid, Y_COL, z1), xDir=(0, 1, 0),
normal=(0, 0, 1)))
.text("P02-REAR ▼ JOIN", 7.5, -0.8)).val()
p02_r = p02_r.cut(cq.Shape(txt_r.wrapped))
return p02_c, p02_f, p02_r
def p_base_foot():
"""P02_底脚 (重型防倾翻超长力臂底座 + 双向大截面三角加强斜撑筋):
1. 底盘尺寸大幅扩展为 385x240x22mm (X: -240.0..+145.0, Y: 8.0..248.0);
- 前向延伸至 X = +145.0mm (在手臂垂直投影前方 91.5mm),彻底杜绝手臂前伸与抓握重物时的前倾翻;
- 后向延伸至 X = -240.0mm (在立柱后方 92.0mm),抵御大动态回程后仰力矩;
2. 立柱插接套筒由 12mm 浅槽大幅升级为 48mm 高加固套筒 (Z: 22.0..70.0mm,外壁厚 7mm);
3. 前向大三角加强斜撑筋 (Z: 68.0->22.0mm, X: -75.0->-15.0mm, 宽 38mm),抗弯力臂长达 60mm,留足安全间隙不干涉手臂运动;
4. 后向大三角加强斜撑筋 (Z: 70.0->22.0mm, X: -155.0->-225.0mm, 宽 38mm),抗后仰力臂长达 70mm;
5. 前斜撑表面设 18mm 宽平滑走线导槽,与 P01 下部走线窗口自然贯通;
6. 6 组 M6 工业工作台紧固腰槽 (28x7mm) + 底部隐蔽走线槽;
7. 四周 R=18mm 大圆角过渡与 2.5mm 上边缘倒角。
"""
z0 = 0.0
z1 = 22.0
x_rear = -240.0
x_front = 145.0
x_len = x_front - x_rear # 385.0
x_mid = (x_rear + x_front) / 2.0 # -47.5
y_width = 240.0
# 1. 主底盘 (385 x 240 x 22 mm)
base_plate = (cq.Workplane("XY", origin=(x_mid, Y_COL, z0))
.rect(x_len, y_width)
.extrude(z1)
.edges("|Z").fillet(18.0)
.edges(">Z").fillet(2.5)).val()
s = cq.Shape(base_plate.wrapped)
# 2. 立柱外包加固套筒 (Z: 22.0..70.0 mm, 外廓 80x80mm)
z_collar_top = 70.0
collar_outer = (cq.Workplane("XY", origin=(X_COL, Y_COL, z1))
.rect(80.0, 80.0)
.extrude(z_collar_top - z1)
.edges("|Z").fillet(8.0)
.edges(">Z").chamfer(2.0)).val()
s = s.fuse(cq.Shape(collar_outer.wrapped))
# 3. 前向抗倾翻三角加强斜撑筋 (Front Triangular Gusset Rib)
f_pts = [
(-75.0, z1),
(-15.0, z1),
(-15.0, z1 + 4.0),
(-75.0, 68.0),
]
f_rib = (cq.Workplane("XZ", origin=(0, Y_COL, 0))
.polyline(f_pts).close()
.extrude(19.0, both=True)).val()
s = s.fuse(cq.Shape(f_rib.wrapped))
# 4. 后向抗倾翻三角加强斜撑筋 (Rear Triangular Gusset Rib)
r_pts = [
(-155.0, z1),
(-225.0, z1),
(-225.0, z1 + 4.0),
(-155.0, 70.0),
]
r_rib = (cq.Workplane("XZ", origin=(0, Y_COL, 0))
.polyline(r_pts).close()
.extrude(19.0, both=True)).val()
s = s.fuse(cq.Shape(r_rib.wrapped))
# 5. 前斜撑表面走线导槽 (与 P01 前走线窗 Z=70..140mm 自然顺接)
wire_guide_pts = [
(-75.5, z1 + 1.0),
(-14.0, z1 + 1.0),
(-14.0, z1 + 4.0),
(-75.5, 68.5),
]
wire_guide = (cq.Workplane("XZ", origin=(0, Y_COL, 0))
.polyline(wire_guide_pts).close()
.extrude(9.0, both=True)).val()
s = s.cut(wire_guide)
# 6. 立柱深插槽内腔 (Pocket: 66.6 x 66.6 mm, 留 0.3mm 精密滑配间隙)
socket_box = (cq.Workplane("XY", origin=(X_COL, Y_COL, 10.0))
.rect(66.6, 66.6)
.extrude(z_collar_top - 10.0 + 1.0)
.edges("|Z").fillet(6.3)).val()
s = s.cut(socket_box)
# 7. 4x M5 底部垂直紧固螺栓孔与沉孔
for xx in (X_COL - 21.0, X_COL + 21.0):
for yy in (Y_COL - 21.0, Y_COL + 21.0):
th = cyl(2.75, -0.01, 10.5, xx, yy)
cb = cyl(5.0, -0.01, 6.0, xx, yy)
s = s.cut(th).cut(cb)
# 8. 6 组 M6 工业工作台紧固腰槽 (28 x 7 mm)
slot_positions = [
(-215.0, Y_COL - 85.0), (-215.0, Y_COL + 85.0), # 后部两角
(-47.5, Y_COL - 95.0), (-47.5, Y_COL + 95.0), # 中部两侧
(120.0, Y_COL - 85.0), (120.0, Y_COL + 85.0), # 前部两角
]
for cx, cy in slot_positions:
plane = cq.Plane(origin=(cx, cy, -0.01), xDir=(0, 1, 0), normal=(0, 0, 1))
slot = cq.Workplane(plane).slot2D(28.0, 7.0).extrude(z1 + 1.0).val()
s = s.cut(slot)
# 9. 底部隐蔽走线通槽
wire_ch = (cq.Workplane("XY", origin=(X_COL, Y_COL - 80.0, -0.01))
.rect(28.0, 100.0)
.extrude(6.0)).val()
s = s.cut(wire_ch)
return s
JOINT = 'root'
def specs(JS):
"""本件的 (件号, 中文名, 构建 thunk, 配色, 说明) 清单;顺序即 BOM 顺序。"""
p02_c, p02_f, p02_r = make_p02_poka_yoke()
return [
("P02_Center_底座中核心_螺旋体30%_墙5底6_平打", "底座核心承力座", lambda: p02_c, 0x475569,
"200mm适配中座:195x190mm核心承力座+48mm套筒+12mm阶梯榫座(轴向面承载)+前后三角加强筋+前后非对称防呆母榫槽+刻字"),
("P02_Front_前向防翻力臂_螺旋体30%_墙4底5_平打", "前向防翻力臂", lambda: p02_f, 0xe11d48,
"200mm适配前臂:145x190mm扩展力臂+104mm宽跨距双公榫+底部M5预埋螺母沉槽+P02-FRONT刻字"),
("P02_Rear_后向防翻力臂_螺旋体30%_墙4底5_平打", "后向防翻力臂", lambda: p02_r, 0xd97706,
"200mm适配后臂:45x190mm扩展力臂+80mm窄跨距双公榫+底部M5预埋螺母沉槽+P02-REAR刻字"),
]
+417
View File
@@ -0,0 +1,417 @@
# -*- coding: utf-8 -*-
"""P03 肩吊臂:板式桁架 + 侧开式电机托架 + M1 后置法兰。"""
import cadquery as cq
import math
from arm.cad.helpers import cyl
from arm.cad.arm_build import Yplate, bx
from arm.kinematics import X_BAY_EXT, Y_AXIS, Z_CHEST1, Z_R1, Z_RL
from arm.cad.part_tools import Xcyl, make_surface_tie_bridge
from arm.cad.parts.p01_column import X_COL, Y_COL, Z_LOCK
def p_girdle(j1):
"""P03_肩关节安装悬臂 (轻量化板式桁架版 + 侧开式电机托架):
1. 10mm 后端重载法兰盘 (X: -61.0..-51.0, 74x74mm);
2. 主干由 66mm 实心块改为双侧 6mm 桁架竖板 (Y = Y_ARM ± 27..33),外轮廓保持旧版
"主干 ∪ 侧筋"并集不变 —— 只减材料不加体积,零新增干涉风险;实心 728 -> 286 cm³ (-61%);
3. 竖板帐篷形减重窗 (顶/底斜面 ≥52°,自支撑;仅 20mm 平顶可桥接);
4. 底部 9mm 承力鞍座 + 43.4x43.4 定位榫头 (配 P01_C 44x44 内腔,单边 0.3mm 间隙);
鞍座底面 66x66 与立柱顶环带承压面积 2403mm² —— 竖向载荷走面压,螺栓只防上抬/防滑;
5. 4x 安装孔 (X_COL±27.5, Y_COL±13.5):Ø3.9 直孔,M4x16 从上方直接拧入自攻成型
(鞍座与立柱顶环同径,无过孔/沉孔/预埋),可拆装;
6. 下腹中央龙骨筋 (12mm 中位腹板,自鞍座斜拉至法兰下缘) + 顶部横向锁紧环抱筋 (66x9x10mm,
与两侧竖板外面齐平、顶面压在筋板脊线上,仅顶前棱一道 2mm 倒角);
7. 侧开式电机托架 (+Y侧全开, X: -51.0..11.5,前端随 X_BAY_EXT 前延 3mm),
M1 电机可从侧方斜插卡入装配(插槽比电机长 3mm),由后端法兰 4xM3x16 锁死;
电机舱 Ø60.7 从后端直通到前端面(2026-10-02 用户裁定"去掉台阶改成平的":无环形台阶、
无喇叭锥;原前置止脱锁紧法兰 4xM3 随之取消,电机轴向由后端 4xM3x16 约束);
9. 两侧大面积散热舷窗 (34x20mm) + 顶部双斜向对流排热槽 (30x6.5mm),确保散热畅通;
10. Ø26mm 中央走线孔;竖板间为开放腔体(无封闭空腔),M3 螺丝刀通道直接走腔体,拧紧更顺手。
11. 三处外凸扎带拱桥(10x8mm、站出 3.2mm、桥下 3.2x1.8 穿带隧道):①桁架竖板面 Y=95、
②后置法兰面 Y=91、③Ø73 舱体 −Y 母线 Y=91.5 —— 安装面按各处真实表面取;原来统一按
Y=95 放,②③ 被筒壁吞成露出 0mm、且压在 34x20 散热舷窗的贯通孔上,等于没有固定点。
"""
X_MOUNT = Z_R1 # -51.0 (Rear face of M1)
T_FLANGE = 10.0 # 10mm thick high-strength mounting flange
X_BACK = X_MOUNT - T_FLANGE # -61.0
Y_ARM = Y_AXIS # 128.0
Z_ARM = Z_RL # 610.0
Y_P_IN = 27.0 # 桁架竖板内表面 (Y_ARM ± 27)
Y_P_OUT = 33.0 # 桁架竖板外表面 (与旧主干齐平)
T_SADDLE = 9.0 # 底部鞍座厚度
TENON = 43.4 # 定位榫头边长(P01_C 内腔 44x44 R4,单边留 0.3mm)
WIN_R = 4.0 # 竖板减重窗内角圆角(消除内尖角应力集中,Kt 由 ~2.5 降到 ~1.2)
BOLT_DX, BOLT_DY = 27.5, 13.5 # 4x 安装孔相对立柱中心偏移:落在顶环 11mm 实体壁内
# 1. 主安装法兰盘 (74x74mm, 四角倒圆 R=8mm)
# 背面那圈 2mm 倒角已去掉:板料只伸进法兰 0.1mm,倒角面与板背面相交会在
# Z≈574.9 挤出一批 2mm 短棱,正是这批短棱让整条交接内棱网络倒不出圆角;
# 同时它跨过 R8 角部圆弧,就是角上那道"卷起来"的怪倒角。
flange = (cq.Workplane("YZ", origin=(X_BACK, Y_ARM, Z_ARM))
.rect(74.0, 74.0)
.extrude(T_FLANGE)
.edges("|X").fillet(8.0)).val()
s = cq.Shape(flange.wrapped)
# 2. 双侧桁架竖板 (6mm):旧"斜挑支撑主干"与"大三角加强筋"轮廓同段挤出 → 自动并集成单块侧板
# 主干的后缘两点取在加强筋斜边的延长线上,使外轮廓顶部成为一整条直线
# (否则后缘 (-148,550) 处有 5° 折点、留下 5mm 台阶)。
# Z_CREST = 侧筋脊线高度,同时是顶筋 2mm 顶前倒角的下沿:倒角从 (X-71,Z_CREST)
# 斜上到 (X-69,Z_CREST+2) = 顶筋顶面,斜坡面与倒角面几乎相切,顶部读起来是一整张面。
Z_CREST = Z_ARM + 33.0 # 643(初版 642;顶筋整体上移 3mm 让出扳手空间后跟着抬)
RIB_SLOPE = (Z_CREST - 575.0) / ((X_BACK - 10.0) - (X_COL - 15.0))
def rib_line_z(x):
return Z_CREST + RIB_SLOPE * (x - (X_BACK - 10.0))
trunk_pts = [
(X_COL - 33.0, Z_CHEST1),
(X_COL + 33.0, Z_CHEST1),
(X_COL + 33.0, 505.0),
(X_BACK + 0.1, 565.0),
(X_BACK + 0.1, Z_ARM - 5.0),
(X_COL - 10.0, rib_line_z(X_COL - 10.0)),
(X_COL - 33.0, rib_line_z(X_COL - 33.0)),
]
rib_pts = [
(X_COL - 33.0, Z_CHEST1), # 底边两端与主干/鞍座对齐 (±33):原来收进 3mm,
(X_COL + 33.0, Z_CHEST1), # 会在鞍座顶面上留下 0.7/3mm 短棱,卡住整条底棱圆角
(X_BACK + 0.1, 565.0),
(X_BACK + 0.1, Z_CREST),
(X_BACK - 10.0, Z_CREST), # 脊线 (-71,643):正好落在顶筋前面与 2mm 倒角下沿的交点
(X_COL - 15.0, 575.0),
(X_COL - 30.0, 530.0),
]
for sign in (-1, 1):
ya = Y_ARM + sign * Y_P_IN
yb = Y_ARM + sign * Y_P_OUT
y0, y1 = min(ya, yb), max(ya, yb)
for prof in (trunk_pts, rib_pts):
s = s.fuse(cq.Shape(Yplate(prof, y0, y1).wrapped))
# 3. 竖板减重窗 (帐篷形:斜面 ≥52° 自支撑、仅 20mm 平顶可桥接;避开鞍座与 M5 螺母柱)
# 6 个内角全部 R4 圆角:把内尖角应力集中 (Kt≈2.5) 降到 ≈1.2,同时圆角面仍是竖直/自支撑面
win_pts = [
(X_COL - 24.0, 498.0), (X_COL + 23.0, 498.0), (X_COL + 25.0, 522.0),
(X_COL + 10.0, 545.0), (X_COL - 10.0, 545.0), (X_COL - 25.0, 524.0),
]
for sign in (-1, 1):
yc = Y_ARM + sign * 0.5 * (Y_P_IN + Y_P_OUT)
tool = (cq.Workplane("XZ", origin=(0, yc, 0)).polyline(win_pts).close()
.extrude(Y_P_OUT - Y_P_IN + 1.0, both=True)
.edges("|Y").fillet(WIN_R).val())
s = s.cut(cq.Shape(tool.wrapped))
# 4. 底部承力鞍座:坐实立柱顶面,把两竖板、龙骨与榫头连成整体
s = s.fuse(bx(X_COL - 33.0, X_COL + 33.0, Y_ARM - Y_P_OUT, Y_ARM + Y_P_OUT,
Z_CHEST1, Z_CHEST1 + T_SADDLE))
# 5. 下腹部纵向抗弯龙骨筋 (12mm 中位腹板,自鞍座斜拉至法兰背面;交接内棱在融合后做真 3D 圆角)
keel_pts = [
(X_COL + 33.0, Z_CHEST1), # (-82, 470)
(X_COL + 33.0, 495.0), # (-82, 495)
(X_BACK + 0.1, 573.0), # (-60.9, 573) 斜拉至法兰背面
(X_BACK + 0.1, 594.4), # (-60.9, 594.4) 顶端贴法兰
(X_COL + 42.1, 585.0), # (-72.9, 585)
(X_COL + 20.0, Z_CHEST1), # (-95, 470) 背面一路斜到底:原来在 (-95,480) 有个折点,
] # 折点离鞍座顶面只 1mm,R2.5 圆角爬不上去 → 龙骨底棱整组倒不出
s = s.fuse(cq.Shape(Yplate(keel_pts, Y_ARM - 6.0, Y_ARM + 6.0).wrapped))
# 7. 顶部横向锁紧环抱横筋:Y 向与两竖板外面齐平 (Y_ARM±33)、前面与筋板脊线共面 (X=-71)、
# 顶面 Z=645 压住脊线 (Z=643) 并与 2mm 顶前倒角相切 → 顶筋与两侧脊线合成一整块。
# 整体比初版抬高 3mm (底面 633→636):4x M3 后端沉孔 Ø6.5 跨在 Z 627.2..633.7 上,
# 底面 633 会压住孔口上沿 0.7mm、扳手让位只剩负间隙;抬到 636 后退到孔口上方 2.3mm、
# 离螺钉轴线 5.55mm。顶面 645 不越过法兰 R8 角部圆弧在 Y=95 处的 645.9 上界。
tie_rib = (cq.Workplane("YZ", origin=(X_BACK - 10.0, Y_ARM, Z_ARM + 30.5))
.rect(66.0, 9.0)
.extrude(10.0)
.edges(cq.selectors.BoxSelector((X_BACK - 10.5, Y_ARM - 34.0, Z_ARM + 34.5),
(X_BACK - 9.5, Y_ARM + 34.0, Z_ARM + 35.5)))
.chamfer(2.0)).val()
s = s.fuse(cq.Shape(tie_rib.wrapped))
# 6.y 体-体交接凹棱:融合完成后对"凹棱"直接做真 3D 圆角。
# 原先这里是手工沿棱 fuse 的 10 条"正方形−四分之一圆"焊珠小体(_cove),已整体删除:
# 焊珠端面是平的、悬在半空,两条互相垂直的焊珠在角上互不搭接 → 圆角"缺一块",
# 并与相邻体的棱互相穿插留 1~3mm² 碎面。真圆角在面边界自然收口、多棱相交处由 OCC
# 生成角部补片。
from cadquery import selectors as _sel
from OCP.BRepAdaptor import BRepAdaptor_Surface
from OCP.GeomAbs import GeomAbs_Plane
from OCP.TopAbs import TopAbs_REVERSED
def _outward(f, sh):
"""平面面的外法向:先按 Orientation 修正,再用"面中心外移 1mm 是否仍在实体内"兜方向。"""
ad = BRepAdaptor_Surface(f.wrapped)
if ad.GetType() != GeomAbs_Plane:
return None
ax = ad.Plane().Axis().Direction()
n = cq.Vector(ax.X(), ax.Y(), ax.Z())
if f.wrapped.Orientation() == TopAbs_REVERSED:
n = n * -1.0
c = f.Center()
if cq.Solid(sh.wrapped).isInside(cq.Vector(c.x + n.x, c.y + n.y, c.z + n.z), 1e-6):
n = n * -1.0
return n
def _fillet_reflex(lo, hi, radii, tag, eps=0.9):
"""倒出 lo~hi 区域内的凹棱(两面夹 270° 材料)。判据:从棱中点沿 (n1-n2) 外探 eps,
落在实体内 = 凹、落在外 = 凸。区域内凹棱先整批一次倒(半径逐级降级,且倒完验拓扑:
OCC 会给出"没抛异常但面已坏"的结果),建不出时按相连棱分组逐组倒。"""
nonlocal s
def _pick(sh):
edges = sh.Edges()
idx = {}
for i, e in enumerate(edges):
idx[e.hashCode()] = i
adj = [[] for _ in edges]
for f in sh.Faces():
for ee in f.Edges():
k = idx.get(ee.hashCode())
if k is not None:
adj[k].append(f)
box = _sel.BoxSelector(lo, hi)
out = []
for i, e in enumerate(edges):
if e.Length() <= 6.0 or len(adj[i]) != 2 or not box.filter([e]):
continue
n1 = _outward(adj[i][0], sh)
n2 = _outward(adj[i][1], sh)
if n1 is None or n2 is None:
continue
dx, dy, dz = n1.x - n2.x, n1.y - n2.y, n1.z - n2.z
ln = math.sqrt(dx * dx + dy * dy + dz * dz)
if ln < 1e-6:
continue
p = e.Center()
if cq.Solid(sh.wrapped).isInside(
cq.Vector(p.x + dx / ln * eps, p.y + dy / ln * eps,
p.z + dz / ln * eps), 1e-6):
out.append(e)
return out
es0 = _pick(s)
if not es0:
print(" [P03 真圆角] %-14s 区域内无凹棱,跳过" % tag, flush=True)
return
def _groups(ee):
"""按共端点把凹棱连成链/网络:一组一次倒,OCC 才能在交汇处生成角部补片;
逐条倒会在交汇处留下断口(看着就像圆角倒一半停了)。"""
pts = [e.Vertices() or [e.Center()] for e in ee]
par = list(range(len(ee)))
def find(a):
while par[a] != a:
par[a] = par[par[a]]
a = par[a]
return a
for i in range(len(ee)):
for j in range(i + 1, len(ee)):
if any(pi.distance(pj) < 0.05 for pi in pts[i] for pj in pts[j]):
par[find(i)] = find(j)
g = {}
for i in range(len(ee)):
g.setdefault(find(i), []).append(ee[i])
return list(g.values())
def _do(edges_, rr):
"""倒完立刻验拓扑:OCC 会给出"没抛异常但面已坏"的结果,必须挡下来。"""
try:
ns = cq.Shape(cq.Solid(s.wrapped).fillet(rr, edges_).wrapped)
except Exception:
return None
return ns if cq.Solid(ns.wrapped).isValid() else None
# 先试"区域内全部凹棱一次倒"(探针实测这样能整批成型,且只重建一次,
# 不会像分批那样把同一张面反复重算坏掉);不行再按相连棱分组逐组倒。
for rr in radii:
ns = _do(es0, rr)
if ns is not None:
s = ns
print(" [P03 真圆角] %-14s %d 条凹棱 R%.1f ✓ 整批一次成型"
% (tag, len(es0), rr), flush=True)
return
n_ok, n_grp, left = 0, 0, len(es0)
for _ in range(24):
es = _pick(s)
if not es:
break
got = False
for g in sorted(_groups(es), key=lambda g: -sum(e.Length() for e in g)):
for rr in radii:
ns = _do(g, rr)
if ns is None:
continue
s = ns
n_ok += len(g)
n_grp += 1
print(" [P03 真圆角] %-14s 第%d组 %d 条 R%.1f ✓"
% (tag, n_grp, len(g), rr), flush=True)
got = True
break
if got:
break
if not got:
left = len(es)
break
print(" [P03 真圆角] %-14s 共 %d 组 %d 条凹棱倒圆,剩 %d 条保持尖棱"
% (tag, n_grp, n_ok, left), flush=True)
XR, YC, ZS = X_BACK, Y_ARM, Z_CHEST1 + T_SADDLE # -61, 128, 479
# —— 鞍座顶面 (Z=479) 上的交接内棱:龙骨三条 + 两竖板内侧两条,一次真圆角 ——
# 半径上限 2.0:龙骨侧面 Y=122 与 M5 螺钉头外缘 Y=118.75 只隔 3.25mm,
# 原来的 R3 焊珠会顶到螺帽承压边,R2.0 留 1.25mm。
_fillet_reflex((X_COL - 34.0, Y_ARM - 40.0, ZS - 3.0),
(X_COL + 34.0, Y_ARM + 40.0, ZS + 7.0),
(2.0, 1.5), "鞍座顶面交接")
# —— 法兰背面 (X=-61) 上的交接内棱:只倒竖板/龙骨的竖直棱 ——
# 顶筋底面那条水平棱 (Z=636) 不倒:4x M3 沉孔 Ø6.5 在 Z 627.2..633.7,
# 倒上 R2.5 会把螺钉上方 5.55mm 的扳手让位吃掉 2.5mm。
# 上界取 631:竖板内棱被顶筋底面切成 573..636 / 636..643 两段,只倒下面长的那段
# ——把 636..643 的 7mm 短段并进来,整批就从"一次成型"退化成逐组、且少倒 6 条。
_fillet_reflex((X_BACK - 3.0, Y_ARM - 40.0, 570.0),
(X_BACK + 3.0, Y_ARM + 40.0, 631.0),
(2.5, 2.0, 1.5), "竖板/龙骨↔法兰")
_fillet_reflex((X_BACK - 3.0, Y_ARM - 40.0, Z_ARM + 34.5),
(X_BACK + 3.0, Y_ARM + 40.0, Z_ARM + 35.5),
(1.5, 1.0), "顶筋顶↔法兰")
# 与立柱顶部配合的定位榫头 (43.4x43.4x15mm):配 P01_C 44x44 R4 内腔,单边 0.3mm 滑配
boss = (cq.Workplane("XY", origin=(X_COL, Y_COL, Z_CHEST1 - 15.0))
.rect(TENON, TENON)
.extrude(15.0)
.edges("|Z").fillet(4.2)).val()
s = s.fuse(cq.Shape(boss.wrapped))
# 4x 安装孔:统一 Ø3.9 直孔(M4x16 从腔体正上方拧入自攻成型;鞍座与立柱顶环同径、无沉孔)
# 孔位 (X_COL±27.5, Y_COL±13.5) 同时满足:①在立柱顶环实体壁内(内腔 22 → 外壁 33);
# ②在 P03 两竖板之间、避开中间龙骨,从腔体正上方用扳手可直接拧紧。
for xx in (X_COL - BOLT_DX, X_COL + BOLT_DX):
for yy in (Y_COL - BOLT_DY, Y_COL + BOLT_DY):
s = s.cut(cyl(1.95, Z_CHEST1 - 0.5, Z_CHEST1 + T_SADDLE + 0.5, xx, yy))
# 1x 横向防脱锁紧:榫头 −X 侧向内 Ø3.9x14 直孔(与立柱后壁 Ø3.9 孔同轴,M4x16 拧入自攻)
s = s.cut(Xcyl(1.95, X_COL - TENON / 2.0 - 1.0, X_COL - TENON / 2.0 + 14.0, Y_COL, Z_LOCK))
# 【线束过线孔】榫头/鞍座中央 22x22mm 竖向贯通方孔 (直通 P01 立柱 44x44mm 内腔,容纳 20x20mm 接插件)
saddle_wire = (cq.Workplane("XY", origin=(X_COL, Y_COL, Z_CHEST1 - 16.0))
.rect(22.0, 22.0)
.extrude(T_SADDLE + 17.0)
.edges("|Z").fillet(3.0)).val()
s = s.cut(cq.Shape(saddle_wire.wrapped))
# 4x M3 连接螺孔(螺丝刀通道直接走两竖板之间的开放腔体,无需再钻 Ø8.5 直通隧道)
# 4x M3 连接螺孔(螺丝刀通道直接走两竖板之间的开放腔体,无需再钻 Ø8.5 直通隧道)
# 孔位 = 电机尾端 4x M3 螺纹径向槽实测位(电机.STEP):BCD55。
# 【2026-10-07 整改】M1 电机沿 +X 轴旋转 5.35° 后,4x M3 后端孔完全规整对齐 45°/135°/225°/315° 正四角
# (dy, dz = ±19.45, ±19.45),水平与竖直完全齐平规整,且与旋转后的 M1 尾端 4xM3 槽完全同心
for dy, dz in ((19.45, 19.45), (-19.45, 19.45), (-19.45, -19.45), (19.45, -19.45)):
py = Y_ARM + dy
pz = Z_ARM + dz
th = Xcyl(1.7, X_BACK - 0.5, X_MOUNT + 4.0, py, pz)
cb = Xcyl(3.25, X_BACK - 0.5, X_BACK + 4.5, py, pz)
s = s.cut(th).cut(cb)
# 6. 前向电机全包托架 (X: -51.0..8.5+X_BAY_EXT=11.5,Ø60.7 舱孔平直贯通到端面)
# 端面随插槽加长前延 X_BAY_EXT;叉板背面(10.5+X_FORK_GAP=11.5)与端面 0.0 硬贴平
# (用户两次要求"搞成平的";J1 转动摩擦由用户知悉,发涩时可微松 M2)
X_FRONT = 8.5 + X_BAY_EXT
R_POD = 36.5
R_BORE = 30.35
cradle_outer = (cq.Workplane("YZ", origin=(X_MOUNT - 0.1, Y_ARM, Z_ARM))
.circle(R_POD)
.extrude(X_FRONT - X_MOUNT + 0.1)
.edges(">X").chamfer(1.5)).val()
s = s.fuse(cq.Shape(cradle_outer.wrapped))
# 电机定子配合内腔(最终状态,2026-10-02 用户裁定"去掉台阶改成平的+保留固定电机的面"):
# Ø60.7 圆柱孔壁从前端面平直贯通到舱底(无窄颈、无台阶、无喇叭锥);
# 舱底 = 一个完整的平坦环面(X=5.06+X_BAY_EXT=8.06,与插槽末端墙共面,中开 Ø39 凸台过孔)
# ——即电机前限位面。电机轴向由后端法兰 4xM3x16 约束;
# 前端锁紧由 4 个 Ø10 局部凸台上的 M3 圆柱头螺钉承担(见下方凸台段)。
motor_pocket = Xcyl(R_BORE, X_MOUNT - 0.2, 5.06 + X_BAY_EXT, Y_ARM, Z_ARM)
s = s.cut(motor_pocket)
# 4x 前置 M3 锁紧螺钉凸台(BCD=55mm,跟随 M1 电机旋转 5.35° -> 22.82°/112.82°/202.82°/292.82°):
# 平直舱孔的沉头座位由 4 个 Ø10 局部凸台承载——凸台位于舱孔前段 8.06..11.5,
# 电机前端面(5.0)之前 3mm,电机斜插路径不经过;M3x8 圆柱头坐在凸台沉孔
# 底(x=9.5)旋入电机前端面,咬合 3.5mm,与旋转后的 M1 前端盖实测 4xM3 螺孔精确同心
for deg in (22.82, 112.82, 202.82, 292.82):
rad = math.radians(deg)
fy = Y_ARM + 27.5 * math.cos(rad)
fz = Z_ARM + 27.5 * math.sin(rad)
s = s.fuse(Xcyl(5.0, 5.06 + X_BAY_EXT, X_FRONT, fy, fz))
th = Xcyl(1.6, 5.06 + X_BAY_EXT, X_FRONT, fy, fz)
cb = Xcyl(3.0, X_FRONT - 2.0, X_FRONT, fy, fz)
s = s.cut(th).cut(cb)
# J1 输出凸台过孔 (Ø39 × 3.44——J1 凸台与 3xM2 输出螺钉的必经孔,非台阶;
# 原 6.7mm 长颈与半圆台肩已随舱底前移一并消除)
hub_clearance = Xcyl(19.5, 4.8, X_FRONT + 0.5, Y_ARM, Z_ARM)
s = s.cut(hub_clearance)
# 8. 电机托架 +Y 侧全开(侧开式半包,替代原封闭全包筒):
# M1 电机可从 +Y 侧方直线滑入托架完成装配——原封闭筒电机物理上无法装入。
# 轴向约束:后端法兰 4xM3(电机尾端面)单向锁死(前置止脱法兰随平直舱孔要求取消);
# 径向约束:Ø60.7 精密滑配托架底 + 重力贴底。开口前端至 5.06+X_BAY_EXT=8.06
# (比电机前端面多 3mm 斜插余量,电机可倾斜卡入),止脱法兰环随之前移、环宽保持 3.44mm。
s = s.cut(bx(X_MOUNT, 5.06 + X_BAY_EXT, Y_ARM, Y_ARM + 60.0, Z_ARM - 60.0, Z_ARM + 60.0))
# 7. 散热系统:双侧大视窗 + 顶部斜向对流排热槽
for sign in (-1, 1):
win_plane = cq.Plane(
origin=(-24.5, Y_ARM + sign * 35.0, Z_ARM),
xDir=(1, 0, 0),
normal=(0, sign, 0)
)
win_cut = cq.Workplane(win_plane).slot2D(34.0, 20.0).extrude(16.0, both=True).val()
s = s.cut(win_cut)
for deg in (45, 135):
rad = math.radians(deg)
slot_plane = cq.Plane(
origin=(-24.5, Y_ARM + 33.0 * math.cos(rad), Z_ARM + 33.0 * math.sin(rad)),
xDir=(1, 0, 0),
normal=(0, math.cos(rad), math.sin(rad))
)
slot_cut = cq.Workplane(slot_plane).slot2D(30.0, 6.5).extrude(15.0, both=True).val()
s = s.cut(slot_cut)
# 8. 实体表面外凸式扎带拱桥 (10x8mm 拱形穿带座,一体成型,扎带从桥下 3.2x1.8 隧道穿过):
# 安装面一律取"该处的真实表面"——原来三处全按竖板面 Y=95 放,而 ②③ 落在 Ø73 舱体上,
# 舱面母线只到 Y=91.5,桥体 3.2mm 被筒壁整段吞掉(露出 0.0mm、穿带孔被壁填死)= 没有固定点。
# 组①:桁架竖板平面段 X=-85, Z=570, 贴 Y=95 平面,竖直穿带 —— 与 P04 三处同配方,不动
# 组②:后置法兰 −Y 平面 X=-56, Z=610, 贴 Y=91 (法兰 74 宽 → 面在 128-37)
# 选法兰面而不是舱面:法兰是 10mm 整实料;且线束过了 X=-61 必须绕开 Y=91 这道 4mm 台阶,
# 贴法兰面后法兰带内线皮净空 2.78mm,走舱面径向则线要外拱、只剩 0.33mm。
# X 向留 1.0mm 不越法兰前后脸,Z 向 606..614 在 R8 圆角之间 (581..639) 全平面。
# 组③:舱体 −Y 母线实料段 X=+5.5, Z=610, 贴 Y=91.5 切点,动静接缝前锚固点
# 离舷窗前缘 (最外到 X=-8.3) 10.3mm、离前端 1.5 倒角 (X=10 起) 1.0mm;
# 穿带孔由沿 X 改成沿 Z —— 此处线束沿 X 走,孔轴必须垂直于线才抱得住。
Y_FACE_FLANGE = Y_ARM - 37.0 # 91.0 法兰 −Y 承面
Y_TAN = Y_ARM - R_POD # 91.5 舱体最外的 −Y 母线(切点)
for tx, ys, tz, wx in ((-85.0, Y_ARM - Y_P_OUT, 570.0, 10.0),
(-56.0, Y_FACE_FLANGE, 610.0, 8.0),
(5.5, Y_TAN, 610.0, 7.0)):
s = s.fuse(make_surface_tie_bridge(tx, ys, tz, w_x=wx, l_z=8.0, h_y=3.2,
slot_w=3.2, slot_h=1.8, tunnel_dir='Z'))
return s
JOINT = 'root'
def specs(JS):
"""本件的 (件号, 中文名, 构建 thunk, 配色, 说明) 清单;顺序即 BOM 顺序。"""
j1 = JS["J1"]
return [
("P03_肩吊臂_螺旋体35%_墙5底5_竖打", "肩关节安装悬臂", lambda: p_girdle(j1), 0x4b5563,
"轻量化板式桁架版:主干由 66mm 实心块改为双侧 6mm 桁架竖板+帐篷减重窗(斜面≥52°自支撑)+R4内角,外轮廓与旧版并集完全一致,实心 728->286cm³;底部 9mm 承力鞍座(Ø3.9 安装孔)+12mm 中位龙骨筋(自鞍座斜拉至法兰下缘)+40~45°外扩斜撑;保留 10mm 后置法兰、侧开式电机托架、Ø60.7 直通电机舱(平孔无台阶)(M1 从+Y滑入,后端 4xM3x16 锁死)、大散热窗与对流槽;【2026-10-07 电机旋转整改】M1 电机旋转 5.35°:后置法兰 4xM3 连接孔完全规整对齐 45°/135°/225°/315° 正四角(dy,dz=±19.45mm),前端 4xM3 锁紧凸台同步旋转至 22.82°+90k,消除原有倾斜,与 M1 前后端盖螺孔精确同心;无封闭空腔、免支撑"),
]
File diff suppressed because one or more lines are too long
+38
View File
@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
"""P05 大臂旋转座:J2 俯仰 -> J3 滚转(复用 part_tools 的 pitch->roll 骨架)。"""
import cadquery as cq
from arm.kinematics import Z_R3, Z_SH
from arm.cad.part_tools import make_pitch_to_roll_bracket
def p_shoulder_roll_base(j2, j3, half=None):
"""P05_大臂旋转座_螺旋体30%_墙4底5_竖打(深度圆角优化版)
本件在链路上有两重身份,两处让位都是为前端压盖:
1. hub_gap=6.0(从动侧):J2 处 P04 新增了 M2 前端压盖(前端夹紧电机,消除大扭矩下的
倾斜),压盖占 Y 155.5..161.0,所以从动法兰盘背面必须从 Y=157 后移到 Y=162
(留 1.0mm 动间隙)。
2. roll_clamp=True(前端夹紧侧):P05 自己抱着 M3(J3,-Z 轴),原来也只有后端板
4xM3x10 单面锁死;现在按 motor_front_clamp 的统一配方在 M3 前端盖外端面
(Z=389)加一枚 R35 压盖(Z 384..389,4xM3x8 BCD55),与后端板前后双向面压,
倾斜自由度归零。代价是对侧从动件 P06 的 J3 毂面整体后移 CLAMP_BACKOFF=5.5
(Z 388.5→383.0),见 p_humerus_bone。
P08 保持默认 —— J5 处 P07 的前端压盖已做(只需 6.0 的 hub_gap),而 J6 的 M6
前端压盖尚未做,故 roll_clamp 传 False。
"""
s = make_pitch_to_roll_bracket(j2, j3, Z_SH, Z_R3,
name="P05_大臂旋转座_螺旋体30%_墙4底5_竖打",
hub_gap=6.0, roll_clamp=True)
return s
JOINT = 'J2'
def specs(JS):
"""本件的 (件号, 中文名, 构建 thunk, 配色, 说明) 清单;顺序即 BOM 顺序。"""
j2 = JS["J2"]
j3 = JS["J3"]
return [
("P05_大臂旋转座_螺旋体30%_墙4底5_竖打", "大臂旋转座", lambda: p_shoulder_roll_base(j2, j3, None), 0x059669,
"V3圆角+ J2前端夹紧配合:Loft外轮廓R=10mm,后缘凸包两角90°竖棱磨R2圆角(结构/后缘高度不变,打印无悬挂);【2026-10-07 侧壁放样斜棱圆角】侧壁与有机放样交汇处斜向硬折棱倒R3圆角,消除侧立面与正面放样弧面接缝硬棱,表面光影与触感圆润流线;【2026-10-07】L型内转角R1.5精细圆角(将圆角半径精调至1.5mm,完全杜绝算法异常与外凸台阶,平滑过渡并消除直角应力集中,与螺钉沉孔/运动间隙保持充裕余量);【2026-10-07 电机座内凹槽与边缘突起消除】彻底消除承压面内侧 4.5mm 环形内凹槽(全腔单一 BAY_R 贯通无接缝),同时 cut_open 敞口高度上限延伸至承压面 (z_r + REAR_SEAT),侧壁完全平直对齐下方壁面,彻底消除侧沿悬垂突耳;J2 从动法兰盘背面由 Y=157 后移至 Y=162(hub_gap=6.0,给 P04 新增的 M2 前端压盖让位,J2 直锁凸台同步加长到 Y=165.5,3xS01 输出螺钉咬合量不变);保证 J2 全角度 0 干涉;【2026-10-05d 只切敞口那一圈围挡】用户指出 M3 电机前端(另一头)也有一圈围挡:Z389.0~395.5 的 r30.25~35 前端定位环(6mm 高环墙) + 骑在它上面的 R35 压盖外圈(Ø70 比电机 Ø63.6 凸 3.2mm),把 M3 前端盖连同穿过 Ø37 孔的 P06 J3 凸台围在中间。第一版把整个前端(定位环+压盖+腔口下沿 389->395)都切了属过度(电机前端失去支撑面、M3 退回单面锁死),已回退;现只切敞口(-Y)那一圈(盒切,Y 界限与 cut_open 一致),-Y 半圈从 Z=395.5 一路开到压盖背面 Z=389,背脊(+Y)侧整圈保留作前端盖定位与压盖唯一且足够强的支撑面(4.75mm 宽 x 0.5mm 熔接带);压盖本体/Ø37 孔/4xM3x8 沉孔/腔口下沿 389.0 全部不动,P05 只少 3.2cm3(154.8->151.6),仍单实体。不整圈削到 R31.8 的原因:那圈壁与 Loft 在 X=±35 处与 Ø70 柱面相切,整圈切完会脱空出 1.32mm3 碎块破坏单实体;且压盖根部熔接面会从 2.37mm2 缩到 0.78mm2,4xM3x8 夹紧力会把压盖拉下来。开关 FENCE_OPEN_CUT(全机 5 处电机前端定位环敞口侧统一切除,无围挡阻碍装配)。【2026-10-03】M3 前端压盖(R35, Z384.0..389.0):J3 roll 电机原来也只有后端板 4xM3x10 单面锁死(S02),大扭矩下绕 J3 轴在 Ø60.3 座孔里点头;现按 P04/P06/P07 同一配方在 M3 前端盖外端面(Z=389)加 4xM3x8(BCD55)沉孔压盖,与后端板前后双向面压,倾斜自由度归零(配方唯一差别是 roll 电机轴向 -Z,压盖朝 -Z 长,见 motor_front_clamp axis=\"Z\");代价是对侧 P06 的 J3 毂面整体后移 5.5mm 让位;【2026-10-05 承压面让位腔改为 R35 圆腔、凸台与围挡一并消除】电机尾端垫片位(REAR_SEAT=2.6)用圆腔掏出承压面。**刀半径必须等于外壁 R35**(arm_build.SEAT_R):取小于 R35(曾试 32.2 = 64.4 方腔内切圆)时,刀半径与外壁之间那圈 2.8mm 环墙完整保留,而承压面只挖到刀半径,于是该环墙相对承压面【凸起】并把电机尾端面围住 —— 这就是用户截图里的一圈围挡(P08 实测 1536.9mm3)。它不是残留,而是 SEAT_R<R35 的必然产物。现 SEAT_R=35.0、SEAT_TOP=+1.0(越过尾端面 1mm,吃掉半包开口处那截0.052cm3 残片):承压面段整圈挖到外壁,承压面成为完整 R35 平圆盘,凸台与围挡一起消失,电机尾端面与承压面之间再无凸起。承力改由臂身本体承担(band 段 r36..58 有料方位 P04 10/36、其余各 15/36,其余方位靠 z>+1.0 杯体连接,无整圈通槽)。沉孔 z 区间(-8..-4)与圆腔(-2.6..+1.0)不重叠,S02 完好。连带:承压环由「方腔内切 32.2 − 沉孔外缘 30.25 = 1.95mm 窄环」变为「完整 R35 圆环 4.75mm」,受压面积 383->974mm²(2.5 倍)。【2026-10-04 承压面让位腔改为 32.2 圆腔】电机尾端垫片位(REAR_SEAT=2.6)之前用 64.4 **方**腔掏出来,方腔壁以外 z=-2.6..0 那圈料相对新承压面凸起 2.6mm,打印时是悬空薄壁(用户反馈:难打印、需支撑、公差差)。现承压面段改用**SEAT_R=32.2 圆腔**(= 64.4 方腔的内切圆半径,z=-2.6..0 与方腔平接)把整圈挖到承压面高度,凸台零残留;z=0 以上 PCBA 腔仍保持 64.4 方(PCB 是方的必须方腔)。**关键:刀半径必须取 32.2 而不是 R35** —— 中间试过 R35,结果把 r=32.2..35 的连接壁整圈切断:实测 P04 在 z=-2.6..+1.0 只剩 240~320° 方位有料,其余 360° 全掏空,后端法兰与杯壁之间出现 3.6mm 宽通槽 + 225° 一片 0.5mm 孤立薄片(用户截图:肩叉顶部「没连上」)。取 32.2 后 r=32.2..35 这圈 2.8mm 厚壁完整保留,360° 连续,既无凸台又与上方臂身连成一体(实测 5/5 件连接壁整圈连续、单实体)"),
]
+156
View File
@@ -0,0 +1,156 @@
# -*- coding: utf-8 -*-
"""P06 大臂骨架:J3 滚转 -> J4 俯仰的 Loft 空心梁。"""
from arm.cad import arm_build as AB
import cadquery as cq
from arm.cad.helpers import cyl
from arm.cad.arm_build import COVER_Z, Ycyl, bx
from arm.kinematics import X_ARM, Y_AXIS, Y_COVER, Y_REAR, Z_EL, Z_R3
from arm.cad.part_tools import (
CLAMP_BACKOFF, CLAMP_CLR, CLAMP_T, cut_motor_fence, hub_m2_holes,
make_surface_tie_bridge_neg_x, motor_front_clamp,
)
P06_WIN_XZ = [(3.0, 362.0), (37.0, 362.0), (37.0, 371.0),
(28.0, 374.0), (12.0, 374.0), (3.0, 371.0)] # 大臂过渡块
P06_HOLLOW_WIN = False # 2026-10-03 起关闭:拱形窗正面看是贯通黑洞,不雅观(详见 p_upper_bone 5c)
def p_humerus_bone(j3, j4):
"""P06_大臂骨架_螺旋体25%_墙4底5_竖打 (Humerus Bone - Loft 圆弧转方有机过渡版):
受 J3 (大臂自转, -Z轴, hub@Z_HUB3=380) 驱动,
向下延伸构成大臂主体骨架,底端抱紧 M4 (肘部俯仰电机, +Y轴, 轴线位于 Z_EL=332.0)。
1. 借鉴 P05 大臂旋转座几何放样算法:
- 顶端结合面 (Z = 383.0mm):与 J3 轴径严格相切的 Ø70mm 正圆形轮廓,彻底消除原先外突的方形水平阶梯;
- 底端结合面 (Z = 367.0mm):平滑展开融入 M4 电机套筒的 70x63.5mm 方形截面;
- 过渡区 (Z: 367.0..383.0mm):采用 Hermite s(t) = 3t² - 2t³ 驱动 20 层放样切片连续渐变;
2. 下部抱紧套筒与安装板 (R=35mm),电机定子 100% 裸露散热开窗;
3.【2026-10-03】J3 毂面整体后移 CLAMP_BACKOFF=5.5(顶端 388.5→383.0,直锁凸台
59.5→65.0):P05 新增 M3 前端压盖,占 Z 384..389,原先 388.5 的毂面只剩 0.5mm
让位放不下压盖。配方与 Y 轴三处(J2/J4/J5 令从动法兰盘 Y157→162)完全同源:
压盖 5.0 + 动间隙 1.0 - 原基准 0.5 = 5.5。凸台同步加长,3xS01 输出螺钉的头面
台阶(局部 s=58)、杆长、咬合量与改前完全一致,J3 直锁与零干涉不受影响。
压盖中央 Ø37 让位孔(R18.5)也让开 R17.8 凸台,单边余 0.7mm。
4.【2026-10-09】−X 侧线束走廊加一座外凸扎带拱桥 (y=102.5, Z=345):站出 3.2mm、桥下
3.2×1.8 穿带隧道沿 Y 贯通(与 P03/P04 同配方)。走廊线心随之由 x=-17.5 提到 -20.7:
原线皮离本件 −X 面只剩 0.2mm,扎带没有容身处。
5. 严格单实体 (solids = 1) 且与上下级旋转构件及电机实现动态 0 碰撞干涉。
"""
# 1. M4 底部抱紧套筒与后端安装板 (R=35mm)
rear_m4 = Ycyl(35.0, Y_REAR - 8.0, Y_REAR, X_ARM, Z_EL)
front_m4 = Ycyl(35.0, Y_COVER - 6.0, Y_COVER - 0.5, X_ARM, Z_EL)
s = rear_m4.fuse(front_m4)
# 顶端结合面与过渡高度
# z_top 由 M3 前端盖外端面反推:压盖占 [Z_COVER-CLAMP_T, Z_COVER],再留 CLAMP_CLR
# 动间隙 -> 383.0(改前 388.5,与前端盖只有 0.5mm,放不下压盖)。
z_cover3 = Z_R3 - COVER_Z # 389.0 M3 前端盖外端面
z_top = z_cover3 - CLAMP_T - CLAMP_CLR # 383.0 J3 毂面(= 388.5 - CLAMP_BACKOFF)
z_bot = Z_EL + 35.0 # 367.0
# 2. 下部实心基座块 (Z: Z_EL..z_bot + 0.5)
lower_block = bx(X_ARM - 35.0, X_ARM + 35.0, Y_REAR - 8.0, Y_COVER - 0.5, Z_EL, z_bot + 0.5)
s = s.fuse(lower_block)
# 3. 借鉴 P05 的 Loft 放样过渡体:圆弧变方形(20 层平滑放样,保持严格对称 4 段式截面拓扑)
N = 20
wp = cq.Workplane("XY")
for i in range(N + 1):
t = i / float(N)
z_curr = z_bot + t * (z_top - z_bot)
st = 3.0 * (t**2) - 2.0 * (t**3)
# 前侧:t=0 为平直面 (Y=155.5, v=27.5),t=1 渐变为与 Ø70 正切的圆弧顶点 (Y=163.0, v=35.0)
v_sf = 27.5 * (1.0 - st) + 0.05 * st
v_cf = max(27.5 * (1.0 - st) + 35.0 * st, v_sf + 0.05)
# 后侧:从 t=0 的平直面 (Y=92.0, v=-36.0) 渐变到 t=1 的圆弧 (Y=93.0, v=-35.0)
v_sr = -36.0 * (1.0 - st) - 0.05 * st
v_cr = min(-36.0 * (1.0 - st) - 35.0 * st, v_sr - 0.05)
w = (cq.Workplane("XY", origin=(X_ARM, Y_AXIS, z_curr))
.moveTo(-35.0, v_sf)
.threePointArc((0.0, v_cf), (35.0, v_sf))
.lineTo(35.0, v_sr)
.threePointArc((0.0, v_cr), (-35.0, v_sr))
.close())
wp = wp.add(w)
loft = wp.toPending().loft()
s = s.fuse(loft.val())
# 4. 电机中间定子散热裸露切除 (100% 裸露)
# 【2026-10-05f】原 Ycyl(30.5, ...) 定子散热切除已删:主腔统一 BAY_R=30.50
# 且从承压面挖到前端,这刀完全落在主腔内,属同段腔被两个半径各挖一次的残留。
# 通风由敞口盒切实现,不依赖它。
# 5. M4 接口成型
# 【2026-10-03i 接缝整改】front_collar_pocket 已删,理由同 p_shoulder_roll_base:
# 它与 Joint.pocket 切的是同一根 BAY_R 圆柱,是后者的子集,两次同半径布尔
# 相减会在腔壁上留下 s=50.0 的零宽棱(本件实测 R30.500 裂成 5168.4 + 493.9 两张面)。
s = j4.rear_mount_holes(s, t_plate=8.0, hole_d=2.8, cb_d=5.5, cb_depth=4.0)
s = j4.pocket(s)
# 【2026-10-07 修复:仅切除敞口侧承压面环墙,保护侧壁杜绝缺口漏螺丝】
# 仿照 P05 设计,只在敞口半侧(局部 y>=0)将承压面段(z: -REAR_SEAT..0)切平,
# 彻底消除阻碍电机装配的凸起围挡;臂身侧壁(局部 y<0)绝对不动,杜绝切穿侧壁留下缺口!
s = s.cut(j4.L(bx(-40.0, 40.0, 0.0, 40.0, -AB.REAR_SEAT, 0.0)))
# 5b. 【2026-10-02 新增】M4 前端压盖 4xM3x8(BCD55):M4 原来只被后端板单面锁死,
# 大扭矩下会绕 J4 轴在 Ø60.3 座孔里点头。现在前端也面压夹一次(见 motor_front_clamp)。
# 熔接放在所有 R30.15~30.5 圆柱刀具之后,理由同 p_fork 7b。P07 的 J4 从动侧
# 已相应后移到 Y>=162(见 p_forearm_bone 的 J4_CLEAR),与压盖前端面留 1.0mm。
s = s.fuse(motor_front_clamp(X_ARM, Z_EL, tag="P06/M4"))
# 5b2.【2026-10-05e / 2026-10-07 修复】删掉前端"围挡"在敞口侧的那半圈环墙(见 FENCE_OPEN_CUT)。
s = cut_motor_fence(s, j4, "P06/M4", "P06")
# 5c. 【2026-10-02 新增】电机上方过渡块减重窗(见 hollow_tent_window)。
# Z360..385 这段 Loft 过渡块壁厚最深 15.8mm,是 P06 唯一一块可掏的厚料
# (Z332..367 的下部本体已经被 Ø61 定子孔掏成 4.5mm 薄壁,没得再掏)。
# 但它正压在 J3 毂下面,所以三条红线:
# 1) 窗顶最高只到 Z374 —— J3 的 Ø70 毂面在 Z380..388.5,窗顶留 6mm 整块
# 实心托住毂面承压,绝不碰毂面和它后面的 3xS01 直锁螺钉;
# 2) 窗的 X 范围 3..37 —— 截面本体 X-15..55,两侧各留 18mm 竖墙,
# 该高度上零件才不会被切成两半(必须单实体);
# 3) 拱形(下宽上窄)轮廓,斜面与水平 >= 52° 自支撑,只有顶部 X12..28 的
# 16mm 平顶需要桥接(与 P03 同量级)。
# 窗底取 Z362 而不是更低:Z360 附近是全段安全系数最低的截面,
# 抬高窗底 4mm 比横向收窄 8mm 更划算(减重量只少 3cm3,安全系数从 92% 回到 100%)。
# 窗沿 Y 双向切穿(Y87..172 超出本体,前后都贯通),顺带把这段的定子散热口
# 一起打开。
# 【2026-10-03 关闭】用户实机视点确认这个拱形窗在正面看就是一个贯通的矩形黑洞,
# 位于J4 关节正上方、整机最显眼的落脚点,视觉上像"零件破了个洞",非常不雅观。
# 权衡后恢复实心:代价只有 161->183cm3(+22cm3 / +27g PLA),而强度本来就已经是
# 无窗基线的 100%(这段本来就不缺强度),减重收益纯属锦上添花。
# 6. J3 直连法兰结构(凸台延伸至 65.0 跨过结合面牢固熔接,保持单实体与零干涉)
# 凸台随 J3 毂面一起后移 CLAMP_BACKOFF=5.5(59.5→65.0):进入电机输出毂的深度
# 仍是 s54.942..56.0 那 1.06mm,3xS01 的头面台阶(s=58)/杆长/咬合量一律不变。
boss = cyl(17.8, 54.942, 59.5 + CLAMP_BACKOFF)
chamfer_cone = cyl(18.5, 54.5, 54.942)
s = s.fuse(j3.L(boss)).cut(j3.L(chamfer_cone))
s = s.cut(j3.L(cyl(3.5, 54.0, 58.0 + 30.0)))
s = hub_m2_holes(s, j3, cb_z1=58.0 + 40.0)
# 9. −X 侧线束走廊扎带拱桥(与 P03/P04 同一配方:站出 3.2mm、桥下 3.2×1.8 穿带隧道、孔沿 Y)
# 走廊原来贴 x=-17.5 走,离本件 −X 面 (X_ARM-35 = -15.5) 只剩 2.0mm —— 线皮净空 0.2mm,
# 扎带没有容身处。桥站出后线心改到 x=-20.5(桥顶 -18.7 + 线半径 1.8),与 P03 舱段同一处理。
# 落点 Z=345 在 lower_block 的 −X 平面上 (Z332..367.5 / Y92..155.5):足迹 Z341..349 离块体
# 下缘 9.0mm、Y97.5..107.5 离 Y 边 5.5mm,实测平面度 0.00mm、背后 10.35mm 整实料(未打穿内腔)。
s = s.fuse(make_surface_tie_bridge_neg_x(X_ARM - 35.0, 102.5, 345.0,
w_y=10.0, l_z=8.0, h_x=3.2))
return s
JOINT = 'J3'
def specs(JS):
"""本件的 (件号, 中文名, 构建 thunk, 配色, 说明) 清单;顺序即 BOM 顺序。"""
j3 = JS["J3"]
j4 = JS["J4"]
return [
("P06_大臂骨架_螺旋体25%_墙4底5_竖打", "大臂骨架", lambda: p_humerus_bone(j3, j4), 0x0d9488,
"Loft有机过渡版:借鉴P05圆弧变方形放样算法,顶端Ø70正圆与J3平齐无台阶,底端渐变融入M4抱紧套筒与壳体;【2026-10-03】取消电机上方Loft过渡块(Z360~385)的拱形减重窗,恢复实心:该窗沿Y贯通,正面看是整机最显眼处的矩形黑洞(用户视觉整改),代价仅 +22cm3/+27g,强度仍为无窗基线100%;【2026-10-03】J3 毂面整体后移 5.5mm(顶端 388.5→383.0,直锁凸台 59.5→65.0):给 P05 新增的 M3 前端压盖(Z384..389)让位,留 1.0mm 动间隙——与 Y 轴三处(J2/J4/J5 令从动法兰盘 Y157→162)完全同源,换算式同为「压盖 5.0 + 动间隙 1.0 - 原基准 0.5」;凸台同步加长,3xS01 头面台阶(s=58)/杆长/咬合量与 J3 直锁关系一律不变;【2026-10-05 承压面让位腔改为 R35 圆腔、凸台与围挡一并消除】电机尾端垫片位(REAR_SEAT=2.6)用圆腔掏出承压面。**刀半径必须等于外壁 R35**(arm_build.SEAT_R):取小于 R35(曾试 32.2 = 64.4 方腔内切圆)时,刀半径与外壁之间那圈 2.8mm 环墙完整保留,而承压面只挖到刀半径,于是该环墙相对承压面【凸起】并把电机尾端面围住 —— 这就是用户截图里的一圈围挡(P08 实测 1536.9mm3)。它不是残留,而是 SEAT_R<R35 的必然产物。现 SEAT_R=35.0、SEAT_TOP=+1.0(越过尾端面 1mm,吃掉半包开口处那截0.052cm3 残片):承压面段整圈挖到外壁,承压面成为完整 R35 平圆盘,凸台与围挡一起消失,电机尾端面与承压面之间再无凸起。承力改由臂身本体承担(band 段 r36..58 有料方位 P04 10/36、其余各 15/36,其余方位靠 z>+1.0 杯体连接,无整圈通槽)。沉孔 z 区间(-8..-4)与圆腔(-2.6..+1.0)不重叠,S02 完好。连带:承压环由「方腔内切 32.2 − 沉孔外缘 30.25 = 1.95mm 窄环」变为「完整 R35 圆环 4.75mm」,受压面积 383->974mm²(2.5 倍)。【2026-10-04 承压面让位腔改为 32.2 圆腔】电机尾端垫片位(REAR_SEAT=2.6)之前用 64.4 **方**腔掏出来,方腔壁以外 z=-2.6..0 那圈料相对新承压面凸起 2.6mm,打印时是悬空薄壁(用户反馈:难打印、需支撑、公差差)。现承压面段改用**SEAT_R=32.2 圆腔**(= 64.4 方腔的内切圆半径,z=-2.6..0 与方腔平接)把整圈挖到承压面高度,凸台零残留;z=0 以上 PCBA 腔仍保持 64.4 方(PCB 是方的必须方腔)。**关键:刀半径必须取 32.2 而不是 R35** —— 中间试过 R35,结果把 r=32.2..35 的连接壁整圈切断:实测 P04 在 z=-2.6..+1.0 只剩 240~320° 方位有料,其余 360° 全掏空,后端法兰与杯壁之间出现 3.6mm 宽通槽 + 225° 一片 0.5mm 孤立薄片(用户截图:肩叉顶部「没连上」)。取 32.2 后 r=32.2..35 这圈 2.8mm 厚壁完整保留,360° 连续,既无凸台又与上方臂身连成一体(实测 5/5 件连接壁整圈连续、单实体)"),
]
+198
View File
@@ -0,0 +1,198 @@
# -*- coding: utf-8 -*-
"""P07 小臂骨架:J4 -> J5 的 L 型结构 + 顶板减重槽。"""
from arm.cad import arm_build as AB
import cadquery as cq
from arm import kinematics as HL
import math
from arm.cad.helpers import cyl
from arm.cad.arm_build import Ycyl, bx
from arm.kinematics import PLATE_T, X_ARM, Y_COVER, Y_HUB, Y_REAR, Z_EL, Z_WR
from arm.cad.part_tools import (
FILLET_SMALL, cut_motor_fence, hollow_channel, hub_m2_holes,
make_surface_tie_bridge_neg_x, motor_front_clamp,
)
P07_CH = dict(x0=-3.0, x1=43.0, y0=103.0, y1=153.0, z_floor=255.0) # 小臂顶板
def p_forearm_bone(j4, j5, half=None):
"""P07_小臂骨架_螺旋体30%_墙5底5_竖打 L型高刚度无干涉版(深度圆角优化版)
设计要点:
1. 改为与 P05/P08 统一的 L 型结构(L-bracket):
- +Y侧垂直背脊立柱(Y: y_hub_in..y_out),避开上级大臂骨架 P06(Y <= 155.5)
- 彻底消除原全深S弯在J4轴下方向两边突出的干涉结构(两边突出的结构全部去除)
- 垂直立柱与下方 M5 电机水平座之间采用规则折角(Corner Chamfer/Gusset)刚性连接
2. 下方 M5 电机实行半包散热结构,底部与内腔开窗散热
3. J4 轴俯仰动态行程从受限的 ±54° 大幅释放至无死角大范围摆动(零干涉)
4. 满足单实体 (solids=1) 与装配零碰撞。
5.【2026-10-02】M5 前端压盖(4xM3x8 BCD55)消除"电机只被后端板单面锁死"的倾斜隐患;
J4 从动侧整体让位:y_hub_in 由 158.5 后移到 J4_CLEAR=162.0,让出 P06 的 M4 前端压盖
(前端面 Y=161.0),留 1.0mm 动间隙。J4 直连凸台同步加长,3xS01 输出螺钉咬合量不变。
6.【2026-10-09】−X 侧线束走廊加一座外凸扎带拱桥 (y=102.5, Z=235):站出 3.2mm、桥下
3.2×1.8 穿带隧道沿 Y 贯通(与 P06/P03/P04 同配方)。走廊线心随之由 x=-17.5 提到 -20.7:
原线皮离本件 −X 面只剩 0.2mm,扎带没有容身处。
"""
y_out = Y_HUB + PLATE_T # 174.0
# J4 从动侧让位基准:必须 >= P06 的 M4 前端压盖前端面(Y_COVER+5.0=161.0) + 1.0mm
J4_CLEAR = Y_COVER + 6.0 # 162.0
y_hub_in = J4_CLEAR
y_front = Y_COVER - 0.5 # 155.5
y_rear = Y_REAR - 8.0 # 92.0
z_top_housing = Z_WR + 39.0 # 261.0 (顶面加厚 4.0mm,消除过薄破面问题)
z_roof_top = z_top_housing + 19.0 # 280.0 (顶板整条加高 19mm,用户确认方案4)
# 1. J5 电机前后安装环
collar_front = Ycyl(35.0, HL.Y_COVER - 6.0, HL.Y_COVER - 0.5, X_ARM, Z_WR)
rear_plate = Ycyl(35.0, HL.Y_REAR - 8.0, HL.Y_REAR, X_ARM, Z_WR)
s = collar_front.fuse(rear_plate)
# 2. J4 顶部从动法兰盘 (Y: y_hub_in..y_out, R=35mm, Z: Z_EL)
disc = Ycyl(35.0, y_hub_in, y_out, X_ARM, Z_EL)
s = s.fuse(disc)
# 3. M5 电机壳体水平顶部顶板 (Z: Z_WR..z_top_housing, Y: y_rear..y_front)
roof_w = (cq.Workplane("YZ", origin=(X_ARM, 0, 0))
.moveTo(y_rear, Z_WR)
.lineTo(y_rear, z_roof_top)
.lineTo(y_front - 3.0, z_roof_top)
.threePointArc((y_front - 3.0 + 3.0 * math.cos(math.pi / 4),
z_roof_top - 3.0 + 3.0 * math.sin(math.pi / 4)),
(y_front, z_roof_top - 3.0))
.lineTo(y_front, Z_WR)
.close()
.extrude(35.0, both=True))
s = s.fuse(roof_w.val())
# 4. L型垂直立柱臂 (+Y侧,Y: y_hub_in..y_out,从 Z_EL 顶端延伸至下方电机座)
vert_leg = (cq.Workplane("YZ", origin=(X_ARM, 0, 0))
.moveTo(y_hub_in, z_top_housing)
.lineTo(y_out, z_top_housing)
.lineTo(y_out, Z_EL)
.lineTo(y_hub_in, Z_EL)
.close()
.extrude(35.0, both=True))
s = s.fuse(vert_leg.val())
# 5. L型内侧圆弧加强过渡(Circular Arc Gusset,用户要求"改成圆弧而不是折角,消掉悬空小块")
# 彻底取代直角折角与直斜线折角,采用与顶面和立柱双相切的平滑内凹大圆弧 (R=28.0mm)
# 起点在顶板平整面 (y_arc_start, z_roof_top),精确相切至立柱内侧面 (y_hub_in, z_arc_end)
# 严控全域 Z >= z_top_housing,彻底消除侵入下方旋转副的悬空小方块与多余突起!
# 注:顶板整条加高19mm(z_roof_top=280)后,R28改R14使弧仍与顶板面光滑相切,不出现折角
R_arc = 14.0 # 随顶板加高联动重定:相切起点(144.5,280)->终点(158.5,294),避开P06环底z=297留3mm
y_arc_start = y_hub_in - R_arc
z_arc_end = z_roof_top + R_arc
p_mid_arc = (y_arc_start + R_arc * math.cos(math.pi / 4),
z_arc_end - R_arc * math.sin(math.pi / 4))
gusset_w = (cq.Workplane("YZ", origin=(X_ARM, 0, 0))
.moveTo(y_arc_start, z_roof_top)
.threePointArc(p_mid_arc, (y_hub_in, z_arc_end))
.lineTo(y_out, z_arc_end)
.lineTo(y_out, z_top_housing)
.lineTo(y_arc_start, z_top_housing)
.close()
.extrude(35.0, both=True))
s = s.fuse(gusset_w.val())
# 6. 下级 P08 旋转圆盘动态避让切除(R=35.5mm,预留 0.5mm 间隙)
p08_clearance = Ycyl(35.5, 156.0, y_out + 2.0, X_ARM, Z_WR)
s = s.cut(p08_clearance)
# 6b. 【2026-10-02 新增】顶板根部减重槽(见 hollow_channel)。
# 顶板在 Z255..280 一整段是壁厚最深 15mm 的实心料,而 J4 在 z=245 的安全系数
# 高达 122、z=195 也有 24。挖成朝上敞开的 U 形槽,顶板变成槽钢:
# 槽底 Z255 以下保留整块实心到电机座,抗弯的两片 X 向腹板(X-15..-7 / X47..55)
# 留在弯矩拉压区。Y 上限取 156 而非核心的 166,是为了避开 y_hub_in=158.5 起的
# 竖直立柱本体(立柱是 J4 从动法兰的承力柱,不能掏)。
# 槽顶 Z280 就是顶板上表面,敞口向上,免支撑、非封闭腔。
s = s.cut(hollow_channel(P07_CH["x0"], P07_CH["x1"], P07_CH["y0"], P07_CH["y1"],
P07_CH["z_floor"], 300.0, tag="P07顶板"))
# 7. M5 电机安装接口与定子空腔
# 【2026-10-05f 接缝整改】本件原先是全机唯一给腔径加 CLEARANCE_GAP(2.0) 的地方:
# front_collar_pocket(r_bore=32.25) + 一刀 Ycyl(32.5, Y_REAR-0.5, y_front-6)。
# 结果内壁是 35 -> 32.5 -> 30.2 -> 32.3 -> 30.2,比兄弟件多两道台阶
# (实测 scratch/bay_step_profile.py:z=5.5 处 32.5、z=49.5 处掉到 30.2、
# z=50.25 又回到 32.3)。
# 这 2.0mm 是「关节间隙」,但关节间隙是**轴向**让位(见 hub_gap / CLAMP_CLR),
# 径向把腔径撑大 2mm 只会让电机在腔里晃,且与 P05/P06/P08 不一致。
# 现统一走 BAY_R(30.50),与兄弟件同径,接缝归零。
# 【2026-10-03i】front_collar_pocket 随之删除:它切 cyl(BAY_R, 50.0..56.5),
# 是 Joint.pocket 那根 cyl(BAY_R, -2.6..61.6) 的子集,同半径重复相减
# 只会在腔壁上多出一条 s=50.0 的零宽棱。
s = j5.rear_mount_holes(s, t_plate=8.0, hole_d=2.8, cb_d=5.5, cb_depth=4.0)
s = j5.pocket(s)
# 【2026-10-07 修复:仅切除敞口侧承压面环墙,消除用户圈出的围挡】
# 仿照 P05 设计,只在敞口半侧(局部 y>=0)将承压面段(z: -REAR_SEAT..0)切平,
# 彻底消除用户红圈指出的承压面凸起围挡;顶板背脊侧(局部 y<0)绝对不动,杜绝切穿本体!
s = s.cut(j5.L(bx(-40.0, 40.0, 0.0, 40.0, -AB.REAR_SEAT, 0.0)))
# 【2026-10-05f】原 Ycyl(30.5+CLEARANCE_GAP=32.5, ...) 整刀删除:
# 它既撑大了腔径(接缝主因),又已被主腔 BAY_R 完全覆盖(纯冗余)。
# 半包散热设计:-Z底部电机定子通风口
vent_cut = bx(X_ARM - 40.0, X_ARM + 40.0, y_rear + 8.0, y_front - 6.0, Z_WR - 40.0, Z_WR - 25.0)
s = s.cut(vent_cut)
# 7b. 【2026-10-02 新增】M5 前端压盖 4xM3x8(BCD55):M5 原来只被后端板单面锁死,
# 大扭矩下会绕 J5 轴在座孔里点头。现在前端也面压夹一次(见 motor_front_clamp)。
# 必须在第 6 步 p08_clearance(R35.5 让位孔,Y>=156)之后熔接,否则压盖会被削掉。
# P08 的 J5 从动侧已相应后移到 Y>=162(make_pitch_to_roll_bracket 的 hub_gap=6.0)。
s = s.fuse(motor_front_clamp(X_ARM, Z_WR, tag="P07/M5"))
# 7c2.【2026-10-05e / 2026-10-07 修复】删掉前端"围挡"在敞口侧的那半圈环墙(见 FENCE_OPEN_CUT)。
s = cut_motor_fence(s, j5, "P07/M5", "P07")
# 8. J4 直连法兰结构(凸台延伸到法兰盘背面之后 2.0mm 跨过间隙与法兰盘牢固熔接,
# 保持单实体)。凸台长度跟着 y_hub_in 走:法兰盘后移时凸台同步加长,
# 3xS01 输出螺钉的头面台阶(局部 z=58)、杆长、咬合量与改前完全一致。
boss = cyl(17.8, 54.942, (y_hub_in - HL.Y_REAR) + 2.0)
s = s.fuse(j4.L(boss))
s = s.cut(j4.L(cyl(3.5, 54.0, 74.0 + 30.0)))
s = hub_m2_holes(s, j4, cb_z1=74.0 + 30.0)
# ========== 关键圆角优化 ==========
try:
# 后侧顶板外边缘圆角(平滑消除水平顶板与后部垂直端面交汇处的 90° 尖角,用户要求倒角改圆角)
wp_s = cq.Workplane(obj=s)
sel_rear = cq.selectors.BoxSelector(
(X_ARM - 40, y_rear - 1.0, z_roof_top - 1.0),
(X_ARM + 40, y_rear + 1.0, z_roof_top + 1.0)
)
s = wp_s.edges(sel_rear).fillet(FILLET_SMALL).val()
except Exception as e:
print(f"P07 顶板后边缘圆角异常: {e}")
try:
# 垂直立柱下部外缘圆角(消除立柱垂直外壁与下方悬空水平底面交汇处的 90° 尖角,用户截图红圈指定)
wp_s = cq.Workplane(obj=s)
sel_leg_bot = cq.selectors.BoxSelector(
(X_ARM - 40, y_out - 1.0, z_top_housing - 1.0),
(X_ARM + 40, y_out + 1.0, z_top_housing + 1.0)
)
s = wp_s.edges(sel_leg_bot).fillet(FILLET_SMALL).val()
except Exception as e:
print(f"P07 立柱下底外缘圆角异常: {e}")
# 9. −X 侧线束走廊扎带拱桥(与 P06/P03/P04 同一配方:站出 3.2mm、桥下 3.2×1.8 隧道、孔沿 Y)
# 线心随桥由 x=-17.5 改到 -20.5(桥顶 -18.7 + 线半径 1.8);本件 −X 面离走廊同样只有
# 2.0mm,原来线皮净空 0.2mm,扎带无从下手。
# 落点 Z=235 在 M5 壳体顶板的 −X 平面 (x=-15.5, Z222..280) 上:足迹 Z231..239 离顶板下缘
# 9.0mm、Y97.5..107.5 离 Y 边 5.5mm,实测平面度 0.00mm、背后 10.35mm 整实料;顶板减重槽
# 在 X≥-3 / Z≥255,与本桥不相交。
s = s.fuse(make_surface_tie_bridge_neg_x(X_ARM - 35.0, 102.5, 235.0,
w_y=10.0, l_z=8.0, h_x=3.2))
return s
JOINT = 'J4'
def specs(JS):
"""本件的 (件号, 中文名, 构建 thunk, 配色, 说明) 清单;顺序即 BOM 顺序。"""
j4 = JS["J4"]
j5 = JS["J5"]
return [
("P07_小臂骨架_螺旋体30%_墙5底5_竖打", "小臂骨架", lambda: p_forearm_bone(j4, j5, None), 0x7c3aed,
"V2 L型结构 + 顶板减重槽:+Y侧背脊立柱避让大臂骨架,过渡区采用与顶板和立柱双相切的R=28mm平滑内凹大圆弧,彻底消除直斜线折角与悬空阶梯小块,顶板前后外缘2mm倒角改R3圆角,立柱底端外下缘90°直棱倒R3圆角(平滑消除立柱外壁与水平底面交汇处直角尖角);顶板整条加高19mm(z261->280)加强连接且gusset弧R28->R14重定相切融入,J4圆盘外沿与立柱外棱不倒圆保持原始尖角,下方M5电机半包散热,俯仰大范围自由运动零干涉;【2026-10-02】顶板根部Z255~280开朝上敞开的减重槽(X-3~43 / Y103~153, Y上限取153避开y_hub_in=158.5起的竖直立柱本体):顶板由实心变槽钢,288->230cm3(-20%),槽底以下保留整块实心到电机座,抗弯靠两侧各10mm的X向腹板;槽底水平朝上、侧壁竖直、顶部敞开故零支撑且非封闭腔;开度按「减重区最差安全系数 >= 无槽基线 95%」选定(X-3~43 比最初的 X-7~47 收窄 4mm,强度从 88% 回到 96%);【2026-10-05 承压面让位腔改为 R35 圆腔、凸台与围挡一并消除】电机尾端垫片位(REAR_SEAT=2.6)用圆腔掏出承压面。**刀半径必须等于外壁 R35**(arm_build.SEAT_R):取小于 R35(曾试 32.2 = 64.4 方腔内切圆)时,刀半径与外壁之间那圈 2.8mm 环墙完整保留,而承压面只挖到刀半径,于是该环墙相对承压面【凸起】并把电机尾端面围住 —— 这就是用户截图里的一圈围挡(P08 实测 1536.9mm3)。它不是残留,而是 SEAT_R<R35 的必然产物。现 SEAT_R=35.0、SEAT_TOP=+1.0(越过尾端面 1mm,吃掉半包开口处那截0.052cm3 残片):承压面段整圈挖到外壁,承压面成为完整 R35 平圆盘,凸台与围挡一起消失,电机尾端面与承压面之间再无凸起。承力改由臂身本体承担(band 段 r36..58 有料方位 P04 10/36、其余各 15/36,其余方位靠 z>+1.0 杯体连接,无整圈通槽)。沉孔 z 区间(-8..-4)与圆腔(-2.6..+1.0)不重叠,S02 完好。连带:承压环由「方腔内切 32.2 − 沉孔外缘 30.25 = 1.95mm 窄环」变为「完整 R35 圆环 4.75mm」,受压面积 383->974mm²(2.5 倍)。【2026-10-04 承压面让位腔改为 32.2 圆腔】电机尾端垫片位(REAR_SEAT=2.6)之前用 64.4 **方**腔掏出来,方腔壁以外 z=-2.6..0 那圈料相对新承压面凸起 2.6mm,打印时是悬空薄壁(用户反馈:难打印、需支撑、公差差)。现承压面段改用**SEAT_R=32.2 圆腔**(= 64.4 方腔的内切圆半径,z=-2.6..0 与方腔平接)把整圈挖到承压面高度,凸台零残留;z=0 以上 PCBA 腔仍保持 64.4 方(PCB 是方的必须方腔)。**关键:刀半径必须取 32.2 而不是 R35** —— 中间试过 R35,结果把 r=32.2..35 的连接壁整圈切断:实测 P04 在 z=-2.6..+1.0 只剩 240~320° 方位有料,其余 360° 全掏空,后端法兰与杯壁之间出现 3.6mm 宽通槽 + 225° 一片 0.5mm 孤立薄片(用户截图:肩叉顶部「没连上」)。取 32.2 后 r=32.2..35 这圈 2.8mm 厚壁完整保留,360° 连续,既无凸台又与上方臂身连成一体(实测 5/5 件连接壁整圈连续、单实体)"),
]
+33
View File
@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
"""P08 腕偏转座:J5 俯仰 -> J6 滚转(复用 part_tools 的 pitch->roll 骨架)。"""
from arm.kinematics import Z_R6, Z_WR
from arm.cad.part_tools import make_pitch_to_roll_bracket
def p_wrist_bracket(j5, j6):
"""P08_腕偏转座_螺旋体25%_墙4底5_竖打(深度圆角优化版)
hub_gap=6.0:J5 处 P07 新增了 M5 前端压盖(Y 155.5..161.0),从动法兰盘背面必须
从 Y=157 后移到 Y=162 让位;J5 直锁凸台同步加长,3xS01 输出螺钉咬合量不变。
roll_clamp=True【2026-10-03】:M6 补上前端压盖,与 P04/P05/P06/P07 的
M2/M3/M4/M5 同一套配方(R35、4xM3x8 BCD55 @17.8°+90k、Ø6.0 沉孔、Ø61.0 根部
让位槽),轴向 -Z,压盖占全局 Z 120.5..115。此前本件是五处电机腔里**唯一**
只被后端板 4xM3x10 单面锁死的,电机大扭矩下会在 Ø60.3 座孔里点头;对侧
P09 让位 CLAMP_BACKOFF=5.5(见 make_direct_hub 的 backoff),工具端点不动。
"""
return make_pitch_to_roll_bracket(j5, j6, Z_WR, Z_R6,
name="P08_腕偏转座_螺旋体25%_墙4底5_竖打",
hub_gap=6.0, roll_clamp=True)
JOINT = 'J5'
def specs(JS):
"""本件的 (件号, 中文名, 构建 thunk, 配色, 说明) 清单;顺序即 BOM 顺序。"""
j5 = JS["J5"]
j6 = JS["J6"]
return [
("P08_腕偏转座_螺旋体25%_墙4底5_竖打", "腕部转接座", lambda: p_wrist_bracket(j5, j6), 0xd97706,
"V2圆角:Loft外轮廓R=10mm,L型转角内部2mm倒角,彻底清除立壁保证J5全角度0干涉;【2026-10-05 承压面让位腔改为 R35 圆腔、凸台与围挡一并消除】电机尾端垫片位(REAR_SEAT=2.6)用圆腔掏出承压面。**刀半径必须等于外壁 R35**(arm_build.SEAT_R):取小于 R35(曾试 32.2 = 64.4 方腔内切圆)时,刀半径与外壁之间那圈 2.8mm 环墙完整保留,而承压面只挖到刀半径,于是该环墙相对承压面【凸起】并把电机尾端面围住 —— 这就是用户截图里的一圈围挡(P08 实测 1536.9mm3)。它不是残留,而是 SEAT_R<R35 的必然产物。现 SEAT_R=35.0、SEAT_TOP=+1.0(越过尾端面 1mm,吃掉半包开口处那截0.052cm3 残片):承压面段整圈挖到外壁,承压面成为完整 R35 平圆盘,凸台与围挡一起消失,电机尾端面与承压面之间再无凸起。承力改由臂身本体承担(band 段 r36..58 有料方位 P04 10/36、其余各 15/36,其余方位靠 z>+1.0 杯体连接,无整圈通槽)。沉孔 z 区间(-8..-4)与圆腔(-2.6..+1.0)不重叠,S02 完好。连带:承压环由「方腔内切 32.2 − 沉孔外缘 30.25 = 1.95mm 窄环」变为「完整 R35 圆环 4.75mm」,受压面积 383->974mm²(2.5 倍)。【2026-10-04 承压面让位腔改为 32.2 圆腔】电机尾端垫片位(REAR_SEAT=2.6)之前用 64.4 **方**腔掏出来,方腔壁以外 z=-2.6..0 那圈料相对新承压面凸起 2.6mm,打印时是悬空薄壁(用户反馈:难打印、需支撑、公差差)。现承压面段改用**SEAT_R=32.2 圆腔**(= 64.4 方腔的内切圆半径,z=-2.6..0 与方腔平接)把整圈挖到承压面高度,凸台零残留;z=0 以上 PCBA 腔仍保持 64.4 方(PCB 是方的必须方腔)。**关键:刀半径必须取 32.2 而不是 R35** —— 中间试过 R35,结果把 r=32.2..35 的连接壁整圈切断:实测 P04 在 z=-2.6..+1.0 只剩 240~320° 方位有料,其余 360° 全掏空,后端法兰与杯壁之间出现 3.6mm 宽通槽 + 225° 一片 0.5mm 孤立薄片(用户截图:肩叉顶部「没连上」)。取 32.2 后 r=32.2..35 这圈 2.8mm 厚壁完整保留,360° 连续,既无凸台又与上方臂身连成一体(实测 5/5 件连接壁整圈连续、单实体)"),
]
+95
View File
@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*-
"""P09 工具法兰:末端法兰盘与 J6 直锁 hub。"""
import math
from arm.cad.helpers import cyl
from arm.cad.arm_build import D2R
from arm.kinematics import PLATE_T, X_ARM, Y_AXIS, Z_HUB6
from arm.cad.part_tools import CHAMFER_EDGE, CLAMP_BACKOFF, FILLET_SMALL, FILLET_TINY, make_direct_hub
def p_tool_flange(j6):
"""P09_工具法兰_螺旋体30%_墙4底5_竖打 深度圆角优化版
关键改进:
1. 外轮廓全圆角(R=4mm)
2. 法兰面倒角(2mm)
3. 螺孔边缘倒角(1.5mm)
"""
z_bot = Z_HUB6 - PLATE_T - 9.0
s = cyl(35.0, z_bot, Z_HUB6, X_ARM, Y_AXIS)
P09_M4 = []
# 4x M4螺栓孔
#
# 分布圆半径 20 -> 22(BCD 40 -> 44):R20 与 3xS01 输出螺钉的 Ø5.6 螺丝刀通道
# (make_direct_hub 里 cyl(2.8, 58.0, z_out+40) 在 BCD29=R14.5、相位 351.4/232.3/112.1°)
# 咬穿沉孔。0° 那个孔中心 (39.5,128) 到 351.4° 通道中心 (33.84,125.83) 只有 6.06mm,
# 而两孔半径之和是 3.5+2.8=6.30 —— 差 0.24mm,Ø7.0 沉孔壁被啃掉一块,
# 完整圆柱面(88mm²)裂成 45.7+35.4 两片,即用户截图里的月牙孔。
# 该相位差只有 8.6°,转动 M4 孔相位无法躲开(0/90/180/270 与 45 度错开全部仍 <6.30),
# 只能加大分布圆半径:R22 时最小中心距 7.96mm,余量 1.66mm。
# 边壁仍充足:R35 法兰外径 - (R22 + 沉孔 3.5) = 9.5mm。
for a in (0, 90, 180, 270):
rad = 22.0
u = rad * math.cos(a * D2R)
v = rad * math.sin(a * D2R)
# 实际切割推迟到 make_direct_hub 之后(见下)。这里只算出 4 个孔位。
P09_M4.append((X_ARM + u, Y_AXIS + v))
# 定位止口 + 走线孔
pilot = cyl(10.0, z_bot - 1.0, z_bot + 2.5, X_ARM, Y_AXIS)
thru = cyl(5.0, z_bot - 1.0, Z_HUB6 + 1.0, X_ARM, Y_AXIS)
s = s.cut(pilot).cut(thru)
# 直连法兰
# 【2026-10-03】M6 补上前端压盖后,J6 毂面必须让位 CLAMP_BACKOFF=5.5
# (详见 make_direct_hub 的 backoff)。P09 的法兰本体 z_bot/Z_HUB6 一个字没动,
# 让位的只是伸进 J6 腔里的那圈毂面 —— 圆盘下移后仍与法兰本体在局部 65..79.5
# 大面积交叠,熔接不受影响;工具端点 Z_TIP=93 也随之不变。
s = make_direct_hub(s, j6, r_disc=35.0, z_out=74.0, backoff=CLAMP_BACKOFF)
# 4x M4 孔(必须在 make_direct_hub 之后切)
#
# 直连法兰那步 fuse 了 R35 圆盘(局部 z=56.5..74 -> 全局 z=102..121 一侧),
# 会把先切的孔重新填死:分段求交显示 z=97..102 无干涉、z=102 以上整根杆都埋在料里
# (每段 12.57 mm^3 = pi*2^2*1,全截面被埋)。
#
# 孔径与深度同时修正:旧值 Ø3.7 比 M4 杆 Ø4.0 还细,且只到 z=105,
# 而 M4x16 头面在 z=97、杆要走到 z=113 —— 杆尾 8mm 无处可去(干涉 147.3 mm^3)。
# Ø4.4 是 M4 标准间隙孔(ISO 273 medium ≈ Ø4.3)。
# 孔顶要盖过 M4x16 的杆尾:头面 z=97 + 杆长 16 = z=113,故开到 Z_HUB6+4=115,
# 比杆尾多留 2mm(实测开到 112 时最后 1mm 杆尾仍撞料 37.7mm³)。
for (fx, fy) in P09_M4:
s = s.cut(cyl(2.2, z_bot - 1.0, Z_HUB6 + 4.0, fx, fy))
s = s.cut(cyl(3.5, z_bot - 1.0, z_bot + 4.0, fx, fy))
# ========== 关键圆角优化 ==========
try:
# 外轮廓圆角
s = s.edges("|Z").fillet(FILLET_SMALL)
except:
pass
try:
# 法兰面倒角
s = s.edges("<Z").chamfer(CHAMFER_EDGE)
except:
pass
try:
# 顶部边缘圆角
s = s.edges(">Z").fillet(FILLET_TINY)
except:
pass
return s
JOINT = 'J6'
def specs(JS):
"""本件的 (件号, 中文名, 构建 thunk, 配色, 说明) 清单;顺序即 BOM 顺序。"""
j6 = JS["J6"]
return [
("P09_工具法兰_螺旋体30%_墙4底5_竖打", "末端工具法兰", lambda: p_tool_flange(j6), 0xdc2626,
"V2圆角:外轮廓R=3mm,法兰面倒角2mm;【2026-10-02】打印填充由100%降到30%:该截面安全系数288是全机裕度最大的件,满填充纯属浪费(件号同步改为P09_工具法兰_螺旋体30%)"),
]
+58
View File
@@ -0,0 +1,58 @@
# -*- coding: utf-8 -*-
"""实测接口数值:电机模组、端面齿联轴器、配合公差与电机轴向公差。
全部 MEASURED 自 G:/Robot_v2/Model/Solidworks/电机.STEP 与配件(见 docs/interfaces.md)。
改之前先确认量的是同一个基准面。"""
# 注:本段由 armcore.py 原样搬来,行内容与注释未作改动。
# ---------------- MEASURED: motor module (local frame: origin = PCBA rear face centre, +Z = output) ----
M = dict(
pcba_w=63.6, # square PCBA across flats
pcba_t=9.0, # z 0 -> 9.0
rearplate_d=60.0, # z 5.5 -> 10.5
hous_d=60.0, # housing OD, z 10.5 -> 52.5
hous_len=42.0,
cover_d=60.30, # top cover OD (R30.15), z 52.5 -> 56.0
cover_z=56.0, # cover front face = module total length
flange_z=54.942, # 2nd-stage output flange face
neck_d=36.0, # female neck bore in the cover
neck_depth=1.0,
centre_d=6.5, # centre bore in the flange
centre_depth=4.0,
m2_bcd=29.0,
m2_clock=(8.05, 128.07, 248.06),
m2_tap_d=1.85, # M2 pilot for self-tapping in printed material
m2_depth=6.0,
m2_clear_d=2.75,
m2_cb_d=5.2,
)
# ---------------- MEASURED: face-spline coupling (existing, printed by the user) ------------------------
C = dict(
n_teeth=12, tooth_r0=19.0, tooth_r1=24.5, tooth_s=2.5,
flange_t=4.50, part_z=5.560, # mirrored stack
hub_r=27.0,
gap=9.00, # cover-face to cover-face when closed
clamp_od_r=30.0, clamp_len=7.80,
lug_r1=37.0, lug_t=4.50,
bolt_r=32.50, bolt_d=3.80,
z0=1.66, z1=9.46, # clamp envelope in the flange frame (motor cover face = 1.060)
)
# axial stations, motor local frame:
COVER_Z = M["cover_z"] # 56.0
HUB_FACE_Z = COVER_Z + C["gap"] # 65.0 = mating face of the driven hub
CLAMP_R = C["clamp_od_r"] + 0.6 # radial keep-out around the joint axis
LUG_R = C["lug_r1"] + 1.0 # radial keep-out where the bolt lugs are
# ---------------- clearances / print rules -------------------------------------------------------------
CLR = dict(bore_slip=0.20, pilot=0.10, hole_3=3.4, hole_27=2.8, wall_min=2.0)
FIT = dict(motor_bore_d=M["hous_d"] + 2 * 0.15, cover_cb_d=M["cover_d"] + 2 * 0.35)
# 电机【轴向长度】公差(用户 2026-10-07 要求:余量偏大稍微减去 1mm,由 2mm 改为 1mm)。
# 这条链是"后端板螺钉 + 前端压盖螺钉"两个刚性夹持面,螺钉头一旦坐死在沉孔台阶上
# 就再也不能进给,所以公差没法靠"拧紧"消化,只能靠两件事吃掉(见 arm_build.Joint.pocket
# 与 motor_front_clamp):
# 长出来的 0~+1mm -> 后端板 4xM3 螺钉头下垫 0~1mm 垫片圈(螺钉被垫高 -> 电机被拉回)
# 短下去的 0~-1mm -> 电机尾端面与后端板承压面之间垫 0~1mm 垫片(承压面已按 MOTOR_TOL
# 让空,见 Joint.pocket 的 REAR_SEAT)
# 两边都不动压盖/凸台的几何,关节轴向长度不变。
MOTOR_TOL = 1.0
+3
View File
@@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
"""数据注入与工程图:螺钉实例注入 mesh、四张工程图 SVG 生成。
"""
+338
View File
@@ -0,0 +1,338 @@
# -*- coding: utf-8 -*-
"""Assembly drawings (SVG) for the arm.
Round-2 approach, after the first version was rejected: per-part convex hulls FILLED made
the whole arm read as one blob and the balloons' leaders crossed the sheet. Now:
- parts are stroked only (no fill), so overlaps still read as separate outlines
- balloons live in two side columns sorted by projected height, each with a short leader
to the nearest point of its own outline (no long crossing leaders, no collisions)
- joint axes are drawn as dash-dot centrelines and the pitch chain is dimensioned
- the scale is computed from the actual pixels-per-mm, not hard-coded
Sheets: 01 总装侧视 02 关节局部放大(A-A) 03 爆炸轴测 04 前视
"""
import io
import json
import math
import os
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
from arm.paths import WEB, DOCS
# 这两个脚本的顶层就是"算完并写文件",被 import 时会静默重写 travel/mesh 派生产物
# (实测:一次 importlib 冒烟测试就把 docs/travel.json 重写了一遍)。这里改成直接炸。
if __name__ != "__main__":
raise RuntimeError(
"draw_sheet 是脚本:顶层代码一执行就重写产物,不能 import。"
"要用就跑 python -m arm.dataio.draw_sheet。")
D = json.load(io.open(WEB + "/mesh_arm.json", encoding="utf-8"))
P, LAY, MS = D["parts"], D["layout"], D["measured"]
MT, CT = MS["M"], MS["C"]
JOINTS = {j["id"]: j for j in D["joints"]}
def hull(pts):
pts = sorted(set(pts))
if len(pts) < 3:
return pts
def cr(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
lo = []
for p in pts:
while len(lo) >= 2 and cr(lo[-2], lo[-1], p) <= 0:
lo.pop()
lo.append(p)
up = []
for p in reversed(pts):
while len(up) >= 2 and cr(up[-2], up[-1], p) <= 0:
up.pop()
up.append(p)
return lo[:-1] + up[:-1]
def proj(p, kind):
x, y, z = p
if kind == "side":
return (x, z)
if kind == "front":
return (y, z)
if kind == "iso":
a, b = math.radians(30), math.radians(35)
u = x * math.cos(a) - y * math.sin(a)
v = -x * math.sin(a) * math.sin(b) - y * math.cos(a) * math.sin(b) + z * math.cos(b)
return (u, v)
raise ValueError(kind)
def part_pts(p, kind, ex=0.0):
vv = p["v"]
step = max(1, len(vv) // 1400)
out = []
for i in range(0, len(vv), step):
q = [vv[i][k] + p["ex"][k] * ex for k in range(3)] if ex else list(vv[i])
out.append(proj(q, kind))
return out
def nearest(h, pt):
return min(h, key=lambda q: (q[0] - pt[0]) ** 2 + (q[1] - pt[1]) ** 2)
def esc(t):
return str(t).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
def frame(W, H, title, note, scale, sheet_id=""):
return ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %d %d" width="%d" height="%d" '
'class="assembly-sheet-svg" data-sheet-id="%s" data-sheet-title="%s" data-sheet-note="%s" data-sheet-scale="%s" '
'font-family="Microsoft YaHei,sans-serif">' % (W, H, W, H, sheet_id, esc(title), esc(note), scale),
'<defs>'
'<filter id="partGlow" x="-20%" y="-20%" width="140%" height="140%">'
'<feDropShadow dx="0" dy="0" stdDeviation="3.5" flood-color="#2563eb" flood-opacity="0.85"/>'
'</filter>'
'<filter id="balloonShadow" x="-20%" y="-20%" width="140%" height="140%">'
'<feDropShadow dx="0" dy="1.5" stdDeviation="1.5" flood-color="#000" flood-opacity="0.25"/>'
'</filter>'
'</defs>',
'<rect class="sheet-bg" width="%d" height="%d" fill="#fff"/>' % (W, H),
'<g class="sheet-border">',
'<rect class="sheet-border-outer" x="8" y="8" width="%d" height="%d" fill="none" stroke="#111" stroke-width="1.6"/>' % (W - 16, H - 16),
'<rect class="sheet-border-inner" x="14" y="14" width="%d" height="%d" fill="none" stroke="#111" stroke-width=".5"/>' % (W - 28, H - 28),
'<line class="sheet-title-line" x1="14" y1="%d" x2="%d" y2="%d" stroke="#111" stroke-width=".8"/>' % (H - 44, W - 15, H - 44),
'<text class="sheet-title-text" x="24" y="%d" font-size="13" font-weight="bold">%s</text>' % (H - 27, esc(title)),
'<text class="sheet-note-text" x="24" y="%d" font-size="9" fill="#444">%s</text>' % (H - 16, esc(note)),
'<line class="sheet-meta-line" x1="%d" y1="%d" x2="%d" y2="%d" stroke="#111" stroke-width=".8"/>' % (W - 268, H - 44, W - 268, H - 15),
'<text class="sheet-scale-text" x="%d" y="%d" font-size="9">比例 1:%s(按图幅适配) 单位 mm</text>' % (W - 260, H - 29, scale),
'<text class="sheet-ver-text" x="%d" y="%d" font-size="9">六电机人形机器人手臂 %s / 迭代 %s</text>' % (W - 260, H - 17, LAY["ver"], LAY["it"]),
'</g>']
def balloon(x, y, p):
idx = p.get("idx", 0)
name = esc(p.get("name", ""))
cn = esc(p.get("cn", ""))
return ('<g class="sheet-balloon" data-idx="%d" data-name="%s" data-cn="%s">'
'<circle class="balloon-circle" cx="%.0f" cy="%.0f" r="10" fill="#fff" stroke="#111" stroke-width="1"/>'
'<text class="balloon-text" x="%.0f" y="%.0f" font-size="9.5" text-anchor="middle">%d</text>'
'</g>' % (idx, name, cn, x, y, x, y + 3.4, idx))
def build_sheet(kind, title, W, H, ex=0.0, note="", axes=True, dims=None, legend=True, sheet_id=""):
shp = []
for p in P:
if p["name"].startswith("ENV_") or p["name"].startswith("S"):
continue
h = hull(part_pts(p, kind, ex))
if len(h) >= 3:
shp.append((p, h))
if not shp:
return ""
allp = [q for _, hs in shp for q in hs]
xs, ys = [q[0] for q in allp], [q[1] for q in allp]
lo_x, hi_x, lo_y, hi_y = min(xs), max(xs), min(ys), max(ys)
ML, MR = 78, (300 if legend else 18)
aw, ah = W - ML - MR - 20, H - 2 * 40 - 60
if (hi_y - lo_y) > 1.25 * (hi_x - lo_x):
aw -= 34.0 # room for the single balloon column
sc = min(aw / max(1e-6, hi_x - lo_x), ah / max(1e-6, hi_y - lo_y))
ox = ML + (aw - (hi_x - lo_x) * sc) / 2 - lo_x * sc
oy = 34 + (ah + (hi_y - lo_y) * sc) / 2 + lo_y * sc
T = lambda q: (q[0] * sc + ox, oy - q[1] * sc)
out = frame(W, H, title, note, round(1 / sc, 2), sheet_id)
if axes:
out.append('<g class="sheet-axes-group">')
for jid in ("J1", "J2", "J3", "J4", "J5"):
j = JOINTS.get(jid)
if not j:
continue
a = proj(j["rear"], kind)
b = proj([j["rear"][k] + j["d"][k] * 90 for k in range(3)], kind)
pa, pb = T(a), T(b)
out.append('<line class="sheet-axis" x1="%.0f" y1="%.0f" x2="%.0f" y2="%.0f" stroke="#0b57a4" '
'stroke-width=".8" stroke-dasharray="14 3 2 3"/>' % (pa[0], pa[1], pb[0], pb[1]))
out.append('<text class="sheet-axis-label" x="%.0f" y="%.0f" font-size="10" fill="#0b57a4">%s</text>'
% (pb[0] + 3, pb[1] - 3, jid))
out.append('</g>')
out.append('<g class="sheet-parts-group">')
for p, h in shp:
d = "M" + " L".join("%.1f %.1f" % T(q) for q in h) + "Z"
col = "#%06x" % p["color"]
idx = p.get("idx", 0)
cn = esc(p.get("cn", ""))
name = esc(p.get("name", ""))
printed = 1 if p.get("printed") else 0
attrs = 'class="sheet-part-path" data-idx="%d" data-name="%s" data-cn="%s" data-color="%s" data-printed="%d"' % (
idx, name, cn, col, printed)
if p["printed"]:
out.append('<path d="%s" fill="none" stroke="%s" stroke-width="1.35" %s/>' % (d, col, attrs))
else:
out.append('<path d="%s" fill="none" stroke="#9aa1ad" stroke-width=".7" '
'stroke-dasharray="4 2" %s/>' % (d, attrs))
out.append('</g>')
# balloons in two side columns.
side = []
for p, h in shp:
cx = sum(T(q)[0] for q in h) / len(h)
cy = sum(T(q)[1] for q in h) / len(h)
anchor = T(nearest(h, (cx, cy)))
side.append((p, anchor, cx))
tall = (hi_y - lo_y) > 1.25 * (hi_x - lo_x)
right = sorted(side, key=lambda s: s[1][1]) if tall else sorted([s for s in side if s[2] >= ox + (hi_x - lo_x) * sc / 2.0], key=lambda s: s[1][1])
left = [] if tall else sorted([s for s in side if s[2] < ox + (hi_x - lo_x) * sc / 2.0],
key=lambda s: s[1][1])
out.append('<g class="sheet-balloons-group">')
def col(lst, x):
n = max(1, len(lst))
span = H - 130
for i, (p, t, _cx) in enumerate(lst):
by = 52 + span * (i + 0.5) / n
out.append('<polyline class="sheet-leader" data-idx="%d" points="%.0f,%.0f %.0f,%.0f %.0f,%.0f" fill="none" '
'stroke="#555" stroke-width=".6"/>' % (p["idx"], t[0], t[1], (t[0] + x) / 2, by, x, by))
out.append(balloon(x, by, p))
col(left, ML - 30)
col(right, (ox + (hi_x - lo_x) * sc + 52.0) if tall else (W - MR + 44))
out.append('</g>')
if legend:
out.append('<g class="sheet-legend-box">')
rows = sorted(side, key=lambda s: s[0]["idx"])
half = (len(rows) + 1) // 2
tx, ty0 = W - MR + 74, 62
out.append('<text x="%d" y="%d" font-size="10" font-weight="bold">零 件 表</text>' % (tx, ty0 - 8))
for c in (0, 1):
for i, (p, _t, _cx) in enumerate(rows[c * half:(c + 1) * half]):
y = ty0 + 12 + i * 12.6
nm = esc(p["cn"].replace(" 半联轴器/抱箍", " 联轴器/抱箍").replace("端面齿", "")[:11])
out.append('<g class="sheet-legend-row" data-idx="%d" data-name="%s" data-cn="%s">'
'<rect class="legend-row-bg" x="%d" y="%.0f" width="102" height="12.5" fill="transparent" rx="2"/>'
'<text class="legend-row-idx" x="%d" y="%.0f" font-size="8.5">%d</text>'
'<text class="legend-row-name" x="%d" y="%.0f" font-size="8.5">%s</text>'
'</g>' % (p["idx"], esc(p.get("name","")), esc(p.get("cn","")),
tx + c * 106 - 3, y - 9.5,
tx + c * 106, y, p["idx"],
tx + c * 106 + 13, y, nm))
out.append('</g>')
if dims:
out.append('<g class="sheet-dims-group">')
for (a, b, lab, off) in dims:
pa, pb = T(proj(a, kind)), T(proj(b, kind))
y = (pa[1] + pb[1]) / 2 + off
out.append('<line class="sheet-dim-line" x1="%.0f" y1="%.0f" x2="%.0f" y2="%.0f" stroke="#0b57a4" stroke-width=".9"/>'
% (pa[0], y, pb[0], y))
for q in (pa, pb):
out.append('<line class="sheet-dim-ext" x1="%.0f" y1="%.0f" x2="%.0f" y2="%.0f" stroke="#0b57a4" '
'stroke-width=".5" stroke-dasharray="2 2"/>' % (q[0], q[1], q[0], y))
out.append('<text class="sheet-dim-text" x="%.0f" y="%.0f" font-size="10" fill="#0b57a4" text-anchor="middle">%s</text>'
% ((pa[0] + pb[0]) / 2, y - 3, lab))
out.append('</g>')
out.append('</svg>')
return "".join(out)
def joint_detail():
"""Sheet A-A: one joint drawn FROM THE MEASURED NUMBERS (not a mesh projection) with every
governing dimension called out - this is the sheet you actually build against."""
W, H = 1400, 780 # wide enough that the right-hand callouts stay on the sheet
s = 6.0
cy = 330
x0 = 250.0 # motor rear datum
x_cover = x0 + MT["cover_z"] * s # cover face = the joint's datum plane
x_hub = x_cover + CT["gap"] * s
out = frame(W, H, "A-A 回转副局部放大 — 全部尺寸为实测值(按数值绘制,非网格投影)",
"电机 → 端面齿半联轴器 A/B(12 齿,盘脸贴死为唯一轴向止动)→ 对开抱箍防脱 → "
"从动盘(复刻电机输出面)。蓝色为关节轴线。", "1/6(本图放大 6 倍)", "joint")
out.append('<line class="sheet-axis" x1="%d" y1="%d" x2="%d" y2="%d" stroke="#0b57a4" stroke-width="1.1" '
'stroke-dasharray="22 5 4 5"/>' % (x0 - 60, cy, x_hub + 190, cy))
g = ['<g class="joint-geom-group" stroke="#111" fill="none" stroke-width="1.5">']
# motor: housing Ø60 x 42, rear plate, cover Ø60.3 x 3.5
g.append('<rect class="joint-geom-part" data-part="电机机座" x="%.1f" y="%.1f" width="%.1f" height="%.1f"/>'
% (x0 + 5.5 * s, cy - 30 * s, 47 * s, 60 * s))
g.append('<rect class="joint-geom-part" data-part="尾部PCBA" x="%.1f" y="%.1f" width="%.1f" height="%.1f"/>'
% (x0, cy - MT["pcba_w"] / 2.0 * s, MT["pcba_t"] * s, MT["pcba_w"] * s))
g.append('<rect class="joint-geom-part" data-part="电机输出端盖" x="%.1f" y="%.1f" width="%.1f" height="%.1f"/>'
% (x_cover - 3.5 * s, cy - 30.15 * s, 3.5 * s, 60.3 * s))
# coupling halves (4.5 each) and the driven hub
g.append('<rect class="joint-geom-part" data-part="半联轴器A" x="%.1f" y="%.1f" width="%.1f" height="%.1f"/>' % (x_cover, cy - 27 * s, 4.5 * s, 54 * s))
g.append('<rect class="joint-geom-part" data-part="半联轴器B" x="%.1f" y="%.1f" width="%.1f" height="%.1f"/>' % (x_cover + 4.5 * s, cy - 27 * s, 4.5 * s, 54 * s))
g.append('<rect class="joint-geom-part" data-part="从动盘" x="%.1f" y="%.1f" width="%.1f" height="%.1f"/>' % (x_hub, cy - 41 * s, 24 * s, 82 * s))
# clamp band over the closed pair
g.append('<rect class="joint-geom-part" data-part="对开抱箍" x="%.1f" y="%.1f" width="%.1f" height="%.1f" stroke-dasharray="6 3"/>'
% (x_cover + 0.6 * s, cy - 30 * s, 8.4 * s, 60 * s))
g.append('</g>')
out.extend(g)
def dim(y, xa, xb, txt, col="#c00", lx=None):
out.append('<g class="sheet-dim"><line x1="%.1f" y1="%d" x2="%.1f" y2="%d" stroke="%s" stroke-width="1"/>' % (xa, y, xb, y, col))
for x in (xa, xb):
out.append('<line x1="%.1f" y1="%d" x2="%.1f" y2="%d" stroke="%s" stroke-width=".6"/>' % (x, y - 6, x, y + 6, col))
if lx is None:
out.append('<text x="%.1f" y="%d" font-size="11" fill="%s" text-anchor="middle">%s</text>'
% ((xa + xb) / 2, y - 8, col, txt))
else:
out.append('<text x="%.1f" y="%d" font-size="11" fill="%s" text-anchor="end">%s</text>'
% (lx, y - 8, col, txt))
out.append('<line x1="%.1f" y1="%d" x2="%.1f" y2="%d" stroke="%s" stroke-width=".6"/>'
% (lx + 4, y - 11, xa, y, col))
out.append('</g>')
dim(cy - 240, x0, x_cover, "整机长 %.1f" % MT["cover_z"])
dim(cy - 215, x_cover, x_hub, "两盖板面跨距 %.2f" % CT["gap"], lx=620)
dim(cy + 250, x0, x_hub, "电机尾基准 → 从动盘贴合面 = %.3f ← 全臂节距的唯一来源" % MS["HUB_FACE_Z"])
dim(cy + 215, x_cover + 0.6 * s, x_cover + 9.0 * s, "抱箍轴向 %.3f~%.3f" % tuple(MS["CLAMP_SPAN"]), lx=470)
def note(x, y, tx, ty, txt, anchor="start"):
out.append('<g class="sheet-note"><polyline points="%.1f,%.1f %.1f,%.1f %.1f,%.1f" fill="none" stroke="#555" stroke-width=".7"/>'
% (x, y, x, ty, tx, ty))
out.append('<text x="%.1f" y="%.1f" font-size="10.5" text-anchor="%s">%s</text></g>'
% (tx + (3 if anchor == "start" else -3), ty + 3.5, anchor, txt))
note(x0 + 28 * s, cy - 30 * s, 235, cy - 190, "机座 Ø%.0f x %.0f,滑配孔按 Ø%.1f"
% (MT["hous_d"], MT["hous_len"], 60.3), "end")
note(x0 + 4 * s, cy - 31.8 * s, 235, cy - 160, "尾部 PCBA 方 %.1f → 口袋 %.1f"
% (MT["pcba_w"], MT["pcba_w"] + 0.8), "end")
note(x_cover + 2.2 * s, cy - 27 * s, 900, cy - 200, "半联轴器 A(12 齿端面花键 R%.1f~%.1f,齿高 %.1f)"
% (CT["tooth_r0"], CT["tooth_r1"], CT["tooth_s"]))
note(x_cover + 6.7 * s, cy + 27 * s, 900, cy - 170, "半联轴器 B = A 绕局部 X 转 180° 后沿轴移 2xPART_Z")
note(x_hub + 12 * s, cy + 41 * s, 900, cy + 150, "从动盘:Ø%.0fx%.1f 颈孔 + Ø%.1fx5.0 中心孔 + 3xM2 @Ø%.0f"
% (MT["neck_d"], MT["neck_depth"], MT["centre_d"], MT["m2_bcd"]))
note(x_hub, cy + 30.5 * s, 900, cy + 178, "盘脸贴死 = 唯一轴向止动;齿只传扭,不定位")
note(x_hub + 0.5 * s, cy - 20 * s, 900, cy + 206,
"从动面卸荷:Ø54.6 x 0.35(B 半件背面实测越过贴合面 0.06)+ Ø36 x 1.70 导柱孔")
out.append('<text x="60" y="%d" font-size="10.5">M2 相位(时钟):电机侧 %s ;从动盘侧取镜像 %s</text>'
% (H - 62, "/".join("%.1f" % a for a in MT["m2_clock"]),
"/".join("%.1f" % a for a in [(360 - a) % 360 for a in MT["m2_clock"]])))
out.append('<text x="60" y="%d" font-size="10.5">抱箍:带宽 Ø%.0f,凸耳 R%.1f(位于关节局部 ±X,包壳在此处开口);M3 x2 @ R%.1f</text>'
% (H - 48, CT["clamp_od_r"] * 2, CT["lug_r1"], CT["bolt_r"]))
out.append('</svg>')
return "".join(out)
j2 = JOINTS["J2"]["rear"]
j4 = JOINTS["J4"]["rear"]
j5 = JOINTS["J5"]["rear"]
SH, EL, WR = (j2[1], j2[2]), (j4[1], j4[2]), (j5[1], j5[2])
DIMS_ARM = [((0, SH[0], SH[1]), (0, EL[0], EL[1]), "上臂 %.0f" % LAY["L1"], 74),
((0, EL[0], EL[1]), (0, WR[0], WR[1]), "前臂 %.0f" % LAY["L2"], 112),
((0, 0, 0), (0, WR[0], WR[1]), "腕轴离地 %.0f" % WR[1], -128)]
sheets = [
build_sheet("front", "总装图 - 正视(沿 -X 投影;肢体在纸面内,显示左右交替堆叠)", 1200, 800, 0.0,
"实线=打印件,虚线=电机/已有联轴器;点划线为关节轴线;蓝色为节距链。"
"俯仰电机一内一外交替,全部贴合面共用 Y=157 一个平面", True, DIMS_ARM, sheet_id="front"),
joint_detail(),
build_sheet("iso", "爆炸装配图(轴测)", 1200, 800, 1.0,
"爆炸量 100%:每个关节沿肢体方向逐级错开一节,电机与端面齿组件再沿各自轴线抽出 —— 自上而下即装配顺序", False, None, sheet_id="exploded"),
build_sheet("side", "总装图 - 侧视(沿 +Y 投影;俯仰轴垂直纸面)", 900, 800, 0.0,
"肩抬举(J1)轴沿 X 前后布置,与俯仰轴平行偏置 92 mm;"
"肩吊臂侧板在 |x| ≥ 64,肢体包络 |x| ≤ 60.5,故整周不碰", True, None, sheet_id="side"),
]
os.makedirs(DOCS, exist_ok=True)
for n, s in zip(("sheet_front", "sheet_joint", "sheet_exploded", "sheet_side"), sheets):
io.open(DOCS + "/" + n + ".svg", "w", encoding="utf-8").write(s)
io.open(WEB + "/sheets.jsdata", "w", encoding="utf-8").write(json.dumps(sheets, ensure_ascii=False))
print("sheets: %d (%d KB) -> docs/sheet_{front,joint,exploded,side}.svg" % (
len(sheets), sum(len(s) for s in sheets) // 1024))
+347
View File
@@ -0,0 +1,347 @@
# -*- coding: utf-8 -*-
"""紧固件(螺钉)实例化网格生成器。
docs/screws.json 是紧固件清单的唯一事实源(规格 / 长度 / 数量 / 位置 / 备注)。
本模块把清单里的每一颗螺钉按其真实装配孔位还原成三维实例(承载头面坐标 + 拧入方向 +
随动关节组),生成轻量三角网格后追加进 web/mesh_arm.json 的 parts 中。
查看器因此可以:显示全部螺钉、点击 BOM 螺丝行高亮定位、点击螺钉反查清单。
实例坐标来源(与 arm_model.py 成孔代码一一对应,改模型后按同样规则复核):
头面 = 沉孔/通道的"承接台阶"(螺钉从外侧塞入,一直顶到孔径变小的那一圈台阶面),
因此每种规格的头都落在模型预留的沉孔里,不会露在零件表面之外(S05 除外:搭接壁太薄不能开沉孔)。
S01 J1~J6 输出毂 3xM2:joint.L() 局部 (r=m2_bcd/2, HUB_M2_CLOCK 相位),
台阶 z=63(J1, p_fork th 54..63) / 58(其余, th 54..58);头深藏在 Ø5.6 螺丝刀通道内
S02 P04~P08 4xM3 :下级电机 rear_mount_holes:沉孔 Ø5.5 从 -t_plate-1 到 -t_plate+4,
台阶 z = -t_plate+4 = -4(t_plate=8)/ -3(t_plate=7),头沉入 1mm
S03 P03 后法兰 4xM3 :J1 局部 (R27.5 @39.9°+90k, -5.5) (Ø6.5 圆柱沉孔台阶 x=-56.5,法兰外端面 -61,
圆柱头沉入 1.5mm)
S04 P03 前置锁紧凸台 4xM3 :J1 局部 (R27.5 @17.8/107.8/197.8/287.8°, 60.5)
(Ø6.0×2 圆柱沉孔在 Ø10 凸台内,台阶 x=9.5,M3x8 圆柱头露 1mm,旋入电机前端面咬合 3.5mm)
S05 P01 分段对锁 8xM4x16:Ø3.9 直孔 x∈{-131,-93}, z∈{180,329}(母口壁与公榫壁同径),
前后各拧一颗,头在 y=95 / y=161 外露(搭接壁薄不开沉孔),直接拧入自攻成型
S06 P09 工具法兰 4xM4:R22 @0/90/180/270°(BCD44,原 R20 会与 S01 的 Ø5.6 通道咬穿沉孔),台阶 z=97(Ø7.0×4 圆柱沉孔 + Ø4.4 贯穿通孔,法兰底面 z=93,
M4 圆柱头与法兰底面齐平)
S07 P02 中核心 4xM5 :x∈{-135,-99}, y∈{110,146},台阶 z=6(Ø10 沉孔深 6mm,头沉入 1mm)
S08 P02 力臂 4xM5 :(-10,76/180) + (-185,88/168),台阶 z=17(Ø10 沉孔深 5mm,头与顶面齐平)
S09 P03 安装台 4xM4x16:x∈{-142.5,-87.5}, y∈{114.5,141.5},台阶 z=479(P03 鞍座顶面,
从腔体正上方往下拧,Ø3.9 直孔穿过鞍座 9mm 再吃进 P01_C 顶环 7mm,自攻成型)
S11 P03 横向防脱锁紧 1xM4x16:x=-148(立柱 −X 外端面),y=128,z=463,头朝 -X,
沿 +X Ø3.9 直孔穿 11mm 后壁 + 榫头同径,直接拧入自攻(榫头内咬合 4.7mm)
S10 底座腰槽 6xM6 :3 件底座的 6 组 28x7 通腰槽中心(-97.5/120/-215 × 53/203/58/198),
头面 z=22(底座顶面;腰槽为通槽无沉孔,桌面紧固螺栓头必然外露)
S12 电机前端压盖 4xM3x8:J2(P04 夹 M2) / J3(P05 夹 M3) / J4(P06 夹 M4) / J5(P07 夹 M5)
/ J6(P08 夹 M6) 各 4 颗。
配方唯一事实源 = part_tools.motor_front_clamp(R35、4xM3x8 BCD55 @17.8°+90k、Ø6.0 沉孔
深 3.0、沉孔台阶 = 前端盖外端面 +2.0mm、压盖背面 0.0 面压);J3 是同一套配方的 Z 轴版本
(台阶落在 Z=(z_r-56)-2=387),半径/相位直接取 arm_model 的 CLAMP_BCD/CLAMP_CLOCK。
孔位必须显式算全局 (x,z)/(x,y) 而不能用 to_global,原因见 instances() 内的注释。
长度处理:S08/S10 螺杆按真实长度会伸到底座底面(z=0)以下悬空(工作台/预埋螺母未建模),
这里按可见段截断到 z=0,头部与孔位仍按 BOM 规格,避免出现"悬空螺杆"。
运行:python -m arm.dataio.screw_mesh -> 注入网格(纯数据,秒级,不动 CAD)
再 python -m arm.viewer.build_viewer -> 重新打包单文件查看器
arm_model.py 主流程末尾已自动调用本模块,重跑完整构建不会丢失螺钉。
"""
import json
import math
import os
import sys
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
from arm.paths import WEB, DOCS
from arm import kinematics as HL
from arm.cad.part_tools import CLAMP_BCD, CLAMP_CLOCK
X_COL = -115.0 # 立柱中心(与 parts/p01_column.py 的 X_COL 一致)
Y_COL = HL.Y_AXIS # 128.0
GRP_PAR = {"J2": "J1", "J3": "J2", "J4": "J3", "J5": "J4", "J6": "J5"}
DRIVEN = {"J1": "P04 肩叉", "J2": "P05 大臂旋转座", "J3": "P06 大臂骨架",
"J4": "P07 小臂骨架", "J5": "P08 腕偏转座", "J6": "P09 工具法兰"}
PROX = {"J2": "P04 肩叉", "J3": "P05 大臂旋转座", "J4": "P06 大臂骨架",
"J5": "P07 小臂骨架", "J6": "P08 腕偏转座"}
COLOR = 0xc3cad6 # 不锈钢冷色
LMAX = {"S08": 17.0, "S10": 22.0} # 可见段截断:螺杆伸到底座底面(z=0)即止(台面/预埋螺母未建模)
# 电机尾端 4x M3 螺纹径向槽的实测孔位(电机.STEP):BCD55、相位 39.9°+90k,
# 槽宽 2.5、径向可调约 ±1.25mm。S02(P04~P08 后端板)与 S03(P03 后法兰)共用;
# 旧 35.1×40.9 矩形孔距对角两颗偏出螺纹槽 ~4.7mm(2026-10-02 用户指出"螺钉没有对齐")。
REAR_SLOTS = tuple((27.5 * math.cos(math.radians(39.65 + 90.0 * k)),
27.5 * math.sin(math.radians(39.65 + 90.0 * k))) for k in range(4))
# ---------------------------------------------------------------- 局部坐标系工具
def _norm(v):
m = math.sqrt(sum(c * c for c in v)) or 1.0
return tuple(c / m for c in v)
def _cross(a, b):
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def _dot(a, b):
return sum(x * y for x, y in zip(a, b))
def frame(tag):
"""电机局部系 (u,v,w) -> 全局:与 armcore.trs 一致(局部 +Z -> d,+X -> xdir,y = z × x)。"""
a = HL.AXIS[tag]
rear, d, xdir = tuple(a["rear"]), _norm(a["d"]), a["xdir"]
x = _norm(tuple(xdir[c] - _dot(xdir, d) * d[c] for c in range(3)))
y = _cross(d, x)
return rear, d, x, y
def to_global(tag, u, v, w):
rear, d, x, y = frame(tag)
return tuple(rear[c] + u * x[c] + v * y[c] + w * d[c] for c in range(3))
# ---------------------------------------------------------------- 网格基元(局部 +Z = 拧入方向)
def _side(r0, r1, z0, z1, n):
"""圆台侧面(外向缠绕)。"""
V, T = [], []
for i in range(n):
a0 = 2.0 * math.pi * i / n
a1 = 2.0 * math.pi * (i + 1) / n
V += [(r0 * math.cos(a0), r0 * math.sin(a0), z0), (r0 * math.cos(a1), r0 * math.sin(a1), z0),
(r1 * math.cos(a1), r1 * math.sin(a1), z1), (r1 * math.cos(a0), r1 * math.sin(a0), z1)]
b = len(V) - 4
T += [[b, b + 1, b + 2], [b, b + 2, b + 3]]
return V, T
def _cap(r, z, n, up):
V = [(0.0, 0.0, z)]
for i in range(n):
a = 2.0 * math.pi * i / n
V.append((r * math.cos(a), r * math.sin(a), z))
T = [[0, 1 + i, 1 + (i + 1) % n] if up else [0, 1 + (i + 1) % n, 1 + i] for i in range(n)]
return V, T
def _merge(*chunks):
V, T = [], []
for v, t in chunks:
b = len(V)
V += list(v)
T += [[i + b for i in tri] for tri in t]
return V, T
def _geom(spec):
"""清单条目 -> 杆径/长/头型/头径(mm)。"""
nom = float(str(spec["螺纹"]).lstrip("Mm"))
rs, L = nom / 2.0, float(spec["长度mm"])
head = spec.get("头型", "")
if "沉头" in head: # 沉头内六角:90° 锥,最宽处(刃口)在承载面
rh = {3.0: 3.15, 4.0: 3.5, 6.0: 5.5}.get(nom, 1.05 * nom) # 头径≈沉孔座位径(GB dk)
return dict(kind="csk", rs=rs, L=L, rh=rh)
if "外六角" in head: # 外六角:M6 对边 10,高 4
af = {3.0: 5.5, 4.0: 7.0, 5.0: 8.0, 6.0: 10.0}.get(nom, 1.7 * nom)
hh = max(3.0, 0.7 * nom)
return dict(kind="hex", rs=rs, L=L, rh=(af / 2.0) / math.cos(math.pi / 6.0), hh=hh)
rh, hh = {2.0: (3.8, 2.0), 3.0: (5.5, 3.0), 4.0: (7.0, 4.0),
5.0: (8.5, 5.0), 6.0: (10.0, 6.0)}.get(nom, (1.75 * nom, 0.9 * nom))
return dict(kind="sh", rs=rs, L=L, rh=rh / 2.0, hh=hh)
def _mesh(g):
"""局部网格:头部 z ∈ [-hh,0](0 = 承载头面),杆部 z ∈ [0, L]。"""
rs, L = g["rs"], g["L"]
if g["kind"] == "csk":
hh = g["rh"] - rs # 90° 锥:头高 = (dk-d2)/2
head = _merge(_side(g["rh"], rs, 0.0, hh, 14), # 锥面自承载面收进材料(沉入沉孔座位)
_cap(g["rh"], 0.0, 14, up=False), # 承载端外露环形面
_cap(rs, hh, 14, up=True))
elif g["kind"] == "hex":
hh, rh = g["hh"], 0.98 * g["rh"]
head = _merge(_side(rh, rh, -hh, 0.0, 6), _cap(rh, 0.0, 6, up=True),
_cap(rh, -hh, 6, up=False))
else:
hh, rh = g["hh"], g["rh"]
head = _merge(_side(rh, rh, -hh, 0.0, 14), _cap(rh, 0.0, 14, up=True),
_cap(rh, -hh, 14, up=False))
shaft = _merge(_side(rs * 0.985, rs * 0.86, 0.0, L * 0.95, 12),
_side(rs * 0.86, 0.18, L * 0.95, L * 0.995, 12),
_cap(0.18, L * 0.995, 12, up=True), _cap(rs * 0.985, 0.0, 12, up=False))
return _merge(head, shaft)
def place(V, hp, ax):
"""局部 -> 全局 CAD 坐标:局部 +Z = 拧入方向 = -ax(ax 为头朝外法向),右手系保证缠绕不翻。"""
zl = _norm(tuple(-c for c in ax))
t = (1.0, 0.0, 0.0) if abs(zl[0]) < 0.9 else (0.0, 1.0, 0.0)
xl = _norm(_cross(t, zl))
yl = _cross(zl, xl)
return [tuple(round(hp[c] + lx * xl[c] + ly * yl[c] + lz * zl[c], 2) for c in range(3))
for (lx, ly, lz) in V]
# ---------------------------------------------------------------- 72 个实例
def instances(m2_bcd, m2_clock):
out = []
r01 = m2_bcd / 2.0
clock01 = [(360.0 - a) % 360.0 for a in m2_clock] # 从动件沉孔相位(arm_build.HUB_M2_CLOCK)
z01 = {"J1": 63.0, "J2": 58.0, "J3": 58.0, "J4": 58.0, "J5": 58.0, "J6": 58.0}
for tag in ("J1", "J2", "J3", "J4", "J5", "J6"):
d = frame(tag)[1]
c_list = m2_clock if tag == "J1" else clock01
for a in c_list:
u, v = r01 * math.cos(math.radians(a)), r01 * math.sin(math.radians(a))
out.append(("S01", to_global(tag, u, v, z01[tag]), d, tag,
"%s 输出毂" % DRIVEN[tag], "φ%.0f @%.1f°" % (m2_bcd, a)))
for tag, tp in (("J2", 8.0), ("J3", 7.0), ("J4", 8.0), ("J5", 8.0), ("J6", 7.0)):
d = frame(tag)[1]
zt = -tp + 4.0 # 沉孔台阶 = -t_plate + cb_depth(4)
for u, v in REAR_SLOTS:
out.append(("S02", to_global(tag, u, v, zt), tuple(-c for c in d), GRP_PAR[tag],
"%s 后端板" % PROX[tag], "孔位(%.2f,%.2f) -> %s 电机尾端面" % (u, v, tag)))
d1 = frame("J1")[1]
for deg in (17.47, 107.48, 197.48, 287.47):
u = 27.5 * math.cos(math.radians(deg))
v = 27.5 * math.sin(math.radians(deg))
out.append(("S04", to_global("J1", u, v, 60.5), d1, "root",
"P03 前置锁紧凸台", "BCD55 @%.1f° -> M1 前端面" % deg))
for u, v in REAR_SLOTS:
out.append(("S03", to_global("J1", u, v, -5.5), tuple(-c for c in d1), "root",
"P03 后置法兰", "BCD55 @45° 螺纹槽 -> M1 尾端面"))
# S12 电机前端压盖 -> 电机前端盖:J2(P04 夹 M2) / J3(P05 夹 M3) / J4(P06 夹 M4) /
# J5(P07 夹 M5) / J6(P08 夹 M6) 各 4 颗。J2/J4/J5 三处压盖几何完全相同,
# J3/J6 是同一套配方的 Z 轴版本(M6 压盖 2026-10-03 补齐,见 p_wrist_bracket)。
# R35、沉孔台阶都在"前端盖外端面 + 2.0mm":Y 轴是 Y_COVER+2=158,Z 轴是 (z_r-56)-2=387。
# 4xM3x8 @BCD55 17.8°+90k、沉孔 Ø6.0 深 3.0、压盖背面与前端盖 0.0 面压,
# 相位与 S04(P03→M1 前端锁紧)同一套约定,全机 BCD55 孔位一致。
#
# 孔位必须按 motor_front_clamp 的写法直接算全局 (x,z)/(x,y),不能用 to_global:
# 压盖成孔是 fu = px + BCD*cos、fv = pz/py + BCD*sin,即 sin 项直接加在**全局**该轴上;
# 而 frame() 的 y 轴 = d × x,对 J2/J4/J5(d=+Y, x=+X)算出 y=(0,0,-1),
# 经 to_global 会把 v 映到全局 -z,与成孔方向差一个符号
# -> 12 颗螺钉实例整体偏 2*27.5*sin(17.8°) = 16.81mm,每颗都落在两孔之间的实体上
# (布尔校验:M3 圆柱头沉在 Ø6.0 沉孔里却与压盖实体重叠 71.27 mm^3,装不进去)。
# 故此处显式用全局平面复刻成孔公式,与建模脚本一一对应。
for tag, prox in (("J2", "P04 肩叉"), ("J3", "P05 大臂旋转座"),
("J4", "P06 大臂骨架"), ("J5", "P07 小臂骨架"),
("J6", "P08 腕偏转座")):
dt = frame(tag)[1]
rear = tuple(HL.AXIS[tag]["rear"])
roll = HL.AXIS[tag]["d"][1] == 0 # J3/J6 是 roll 电机(轴向 -Z)
for deg in CLAMP_CLOCK:
u = CLAMP_BCD * math.cos(math.radians(deg))
v = CLAMP_BCD * math.sin(math.radians(deg))
hp = (rear[0] + u, rear[1] + v, rear[2] - 58.0) if roll \
else (rear[0] + u, rear[1] + 58.0, rear[2] + v)
out.append(("S12", hp, dt, GRP_PAR[tag],
"%s 前端压盖" % prox,
"BCD55 @%.1f° -> %s 电机前端盖(前端夹紧,%s 轴)"
% (deg, tag, "Z" if roll else "Y")))
for x in (X_COL - 16.0, X_COL + 22.0):
for z in (180.0, 329.0):
out.append(("S05", (x, 95.0, z), (0.0, -1.0, 0.0), "root",
"P01 立柱分段缝", "z=%.0f 前面 -Y:Ø3.9 直孔(M4x16 直接拧入自攻)" % z))
out.append(("S05", (x, 161.0, z), (0.0, 1.0, 0.0), "root",
"P01 立柱分段缝", "z=%.0f 背面 +Y:Ø3.9 直孔(M4x16 直接拧入自攻)" % z))
for deg in (0.0, 90.0, 180.0, 270.0):
# BCD44(R22):原 R20 与 S01 输出螺钉 Ø5.6 通道中心距仅 6.06 < 6.30,
# 沉孔壁被咬穿成月牙形;加大到 R22 后余量 1.66mm。见 p_tool_flange 注释。
x = HL.X_ARM + 22.0 * math.cos(math.radians(deg))
y = HL.Y_AXIS + 22.0 * math.sin(math.radians(deg))
out.append(("S06", (x, y, 97.0), (0.0, 0.0, -1.0), "J6",
"P09 工具法兰", "R22 @%.0f° -> 末端工具" % deg))
for x in (-135.0, -99.0):
for y in (110.0, 146.0):
out.append(("S07", (x, y, 6.0), (0.0, 0.0, -1.0), "root",
"P02 底座中核心", "非对称防反装 (%.0f,%.0f)" % (x, y)))
for x, y in ((-10.0, 76.0), (-10.0, 180.0), (-185.0, 88.0), (-185.0, 168.0)):
out.append(("S08", (x, y, 17.0), (0.0, 0.0, 1.0), "root",
"P02 防翻力臂", "榫头对锁 (%.0f,%.0f)(另配 M5 预埋螺母)" % (x, y)))
for x in (X_COL - 27.5, X_COL + 27.5):
for y in (Y_COL - 13.5, Y_COL + 13.5):
# 方向 = 螺帽朝外法向(+Z,扳手从腔体上方进入);拧入方向 = -Z,Ø3.9 直孔自攻
out.append(("S09", (x, y, 479.0), (0.0, 0.0, 1.0), "root",
"P03 肩吊臂安装台",
"Ø3.9 直孔:从腔体正上方拧入,穿鞍座 9mm 吃进立柱顶环 7mm(自攻成型)"))
# 横向防脱锁紧(M4x16):螺帽压在后壁外面 x=-148,沿 +X Ø3.9 直孔自攻(穿 11mm 后壁 + 榫头)
out.append(("S11", (X_COL - 33.0, Y_COL, 463.0), (-1.0, 0.0, 0.0), "root",
"P03 肩吊臂安装台",
"Ø3.9 直孔:从立柱后方拧入,穿 11mm 后壁吃进榫头 4.7mm(自攻成型)"))
for x, y in ((-97.5, 53.0), (-97.5, 203.0), (120.0, 58.0),
(120.0, 198.0), (-215.0, 58.0), (-215.0, 198.0)):
out.append(("S10", (x, y, 22.0), (0.0, 0.0, 1.0), "root",
"P02 底座腰槽", "28×7 通腰槽 (%.1f,%.0f) -> 工作台" % (x, y)))
return out
# ---------------------------------------------------------------- 注入
def main():
path = WEB + "/mesh_arm.json"
print("读取 %s ..." % path, flush=True)
d = json.load(open(path, encoding="utf-8"))
M = d["measured"]["M"]
specs = json.load(open(DOCS + "/screws.json", encoding="utf-8"))
byid = {s["id"]: s for s in specs}
d["parts"] = [p for p in d["parts"] if not p.get("screw")] # 幂等:先清旧螺钉
mx = max(p["idx"] for p in d["parts"])
inst = instances(M["m2_bcd"], M["m2_clock"])
cnt = {}
for sid, *_ in inst:
cnt[sid] = cnt.get(sid, 0) + 1
for sid, s in byid.items(): # 与清单数量自洽校验
assert cnt.get(sid) == s["数量"], ("实例数与清单不符", sid, cnt.get(sid), s["数量"])
geo = {sid: _geom(s) for sid, s in byid.items()}
seen, new = {}, []
for sid, hp, ax, grp, short, detail in inst:
g = dict(geo[sid])
clip = ""
if sid in LMAX: # 螺杆穿出底座底面后伸向未建模的工作台,按可见段截断
g["L"] = min(g["L"], LMAX[sid])
clip = ";螺杆伸出底座底面(伸入工作台)的部分按可见段截断"
V, T = _mesh(g)
n = seen.get(sid, 0) + 1
seen[sid] = n
mx += 1
s = byid[sid]
new.append(dict(
name="%s_%d" % (sid, n),
cn="%s · %s %d/%d" % (s["规格"], short, n, s["数量"]),
v=place(V, hp, ax), t=T, color=COLOR, printed=False, vol=0.0,
note="%s %s — %s:%s%s;%s" % (s["规格"], s["头型"], s["位置"], detail, clip, s["备注"]),
grp=grp, jaw=0.0, ex=[0.0, 0.0, 0.0], idx=mx,
screw=True, spec=sid,
hl=[round(hp[0], 2), round(hp[2], 2), round(-hp[1], 2)])) # 查看器系头面点 (x,z,-y)
d["parts"] += new
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(d, f, ensure_ascii=False, separators=(",", ":"))
os.replace(tmp, path)
print("螺钉实例 %d 颗已注入:%s" % (len(new), " / ".join("%s:%d" % (k, cnt[k]) for k in sorted(cnt))))
print("零件数 %d -> %d,文件 %.1f MB"
% (len(d["parts"]) - len(new), len(d["parts"]), os.path.getsize(path) / 1e6))
if __name__ == "__main__":
main()
# OCC/cadquery 的静态析构在解释器正常退出时必定段错误(实测:光是
# `python -c "import arm.cad.helpers"` 就返回 139,与本项目代码无关)。所以入口
# 脚本跑完后显式刷缓冲再 os._exit —— 否则全流程已经成功、exit code 却是 139,
# 会把上游脚本的 set -e 判成失败。只在 __main__ 出口生效, 被 import 时不触发。
sys.stdout.flush()
os._exit(0)
+209
View File
@@ -0,0 +1,209 @@
# -*- coding: utf-8 -*-
"""Humanoid arm station solver - single source of truth for human_arm.py.
Every joint module occupies the same axial envelope in its own frame:
s = 0 rear datum (back face of the 63.6 square PCBA)
s = 0..56 the motor itself (square tail, then the Ø60 housing)
s = 56.6..64.4 the split clamp band, Ø62 with lugs out to R38
s = 65.0 the driven hub's mating plane (half B's back face + 4.06 spigot)
s = 65..74 the driven plate itself (PLATE_T thick, growing away from the motor)
so a module plus its joint costs 65 + PLATE_T of axial room and R_MOT = 38 across.
That is what forces the proportions: the shoulder axis ends up ~460 mm over the
foot for a 15 mm ground clearance under the fingertips. Everything below is derived
from those two facts, so changing Z_TIP or L1 re-flows the whole chain.
"""
import math
try:
import sys
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
HUB = 65.0 # rear datum -> driven hub mating plane (validated: 65.000)
PLATE_T = 9.0 # driven plate thickness, grows away from the motor
R_MOT = 38.0 # clamp lug radius = the across-axis envelope
R_BARREL = 30.0
GAP = 4.0 # design clearance between two module envelopes
GAP_MIN = 2.0
# ------------------------------------------------------------------ vertical chain
# Humanoid standard: J1 Roll(+X) -> J2 Pitch(+Y) -> J3 Upper Arm Roll(-Z) -> J4 Elbow Pitch(+Y) -> J5 Wrist Pitch(+Y) -> J6 Tool Roll(-Z)
FOOT_H = 20.0 # base foot height; the fingertips must stay above it
Z_RL = 610.0 # J1 shoulder roll axis
Z_SH = 490.0 # J2 shoulder pitch axis
Z_R3 = 445.0 # M3 upper arm roll rear datum (-Z axis)
Z_HUB3 = Z_R3 - HUB # 380.0 J3 hub plane
Z_EL = 332.0 # J4 elbow pitch axis (+Y axis) - compact direct knuckle
Z_EI = Z_EL # backward compatibility alias
FOREARM = 110.0 # shortened forearm length (was 135.0, shortened 25mm per user)
Z_WR = Z_EL - FOREARM # 222.0 J5 wrist pitch axis (+Y axis)
Z_R6 = Z_WR - 46.0 # 176.0 M6 tool roll rear datum (-Z axis)
Z_HUB6 = Z_R6 - HUB # 111.0 J6 hub plane
Z_TIP = Z_HUB6 - 18.0 # 93.0 P09 tool flange bottom face (73mm clearance above foot)
L1 = Z_SH - Z_EL # 158.0 humerus length (was 180.0, empty cylinder eliminated)
SWEEP_R = 92.0 # farthest point of the humerus from the shoulder pitch axis
POD_R = 47.0 # saddle drum outer radius about the roll axis
X_J1_HUB = 14.0 # J1 hub mating plane, forward of the humerus plate's ±44
X_BAY_EXT = 3.0 # M1 侧插槽加长量(2026-10-01 用户裁定:插槽开口 5.06+3=8.06,
# 比电机前端面多 3mm 斜插余量;P03 托架前端 8.5+3=11.5)
X_FORK_GAP = 1.0 # P04 肩叉前移量:叉板背面(10.5+1.0=11.5)与 P03 托架端面(11.5)
# 0.0 硬贴平(2026-10-02 用户两次要求"搞成平的",0.5mm 缝仍被判台阶)。
# 注意:J1 相对转动时 M2 预紧会经此面产生摩擦阻力,若转动发涩可微松 M2。
X_ARM = X_J1_HUB + PLATE_T / 2.0 + X_FORK_GAP # 19.5 the limb's own plane in x
Z_R1 = X_J1_HUB - HUB # -51 J1 rear datum, measured in x: M1 lies behind the shoulder
Z_CHEST1 = Z_RL - 140.0 # 470 torso mast top
Z_CHEST0 = FOOT_H
Z_SH_TOP = Z_RL + R_MOT + GAP # 652 shoulder pod top
Z_R4 = Z_EL # compatibility
Z_CAP = Z_HUB3 # compatibility
Z_M6 = Z_R6 # compatibility
# ------------------------------------------------------------------ lateral chain (Y, left arm outboard +Y)
# Aligned Architecture: all motors centered laterally on Y_AXIS = 128.0 mm
# J2, J4, J5 face the SAME direction (+Y) with driven hubs on Y_HUB = 165.0 mm!
Y_AXIS = 128.0 # Shared lateral centerline of the entire limb
Y_HUB = 165.0 # Shared driven hub mating plane for J2, J4, J5
Y_REAR = Y_HUB - HUB # 100.0 (Rear datum for M2, M4, M5)
Y_COVER = Y_REAR + 56.0 # 156.0 (Front cover face for M2, M4, M5)
Y_H = Y_AXIS # backward compatibility: limb centre plane
Y_R_IN = Y_REAR
Y_R_OUT = Y_COVER
PL_IN = (Y_COVER, Y_HUB)
PL_OUT = (Y_COVER, Y_HUB)
Y_M6 = Y_AXIS
Y_CHEST = 62.0 # mast half width
X_CHEST = 6.0 # chest plate half thickness
# ------------------------------------------------------------------ 台架(非常规构件)
# P01 立柱 / P02 底盘 是【固定测试台架】,不是机器人本体的一部分(用户 2026-10-02
# 确认);它在扫描中代表机械臂与**躯干/机身连接界面**的那块实体。因此:
#
# - 臂撞立柱 = 臂撞躯干,是真约束,不能忽略。sweep_v2 报出的组合卡死(J3 ±162°、
# J4 ±18°、J5 ±36° 等,全部是工具法兰 P09 撞立柱 P01_A)就是这类真约束。
# - 但台架的**位置与截面是一个假设**。躯干侧工作空间只和这个假设一样准:真机躯干
# 挪后一点或外形不同,这些限位就变。所以台架本身不要为了放宽行程去改(那是改测试
# 工装,不是改设计);要改的是"真机躯干占位"这个输入。
# - `--no-stand` 仅用于诊断:给出不含躯干约束的自由空间行程,用来分辨某个限位到底是
# 臂自身折叠产生的、还是躯干挡的。默认不排除。
FIXTURE_PREFIX = ("P01_", "P02_")
def is_fixture(name):
"""该零件是否属于固定测试台架(代表躯干/安装界面,非机器人本体)。"""
return name.startswith(FIXTURE_PREFIX)
# ------------------------------------------------------------------ 关节表
# tag, cn, rear, d, xdir, holder of the motor, driven part
# J1 roll +X fore-aft, in the shoulder base -> drives P04 肩叉
# J2 pitch +Y outboard in the fork -> drives P05 大臂旋转座
# J3 roll -Z in the shoulder roll base -> drives P06 大臂骨架
# J4 pitch +Y in the humerus bone -> drives P07 小臂骨架
# J5 pitch +Y in the forearm bone -> drives P08 腕偏转座
# J6 roll -Z in the wrist bracket -> drives P09 工具法兰
# J1 roll 电机沿 +X 轴旋转 5.35°,使尾端 4xM3 螺纹槽对齐 45°/135°/225°/315° 规整四角
J1_DTHETA = math.radians(5.35)
J1_XDIR = (0, math.cos(J1_DTHETA), math.sin(J1_DTHETA))
JOINTS = [
("J1", "肩抬举", (Z_R1, Y_AXIS, Z_RL), (1, 0, 0), J1_XDIR, "P03_肩吊臂_螺旋体35%_墙5底5_竖打", "P04_肩叉_螺旋体30%_墙5底5_竖打"),
("J2", "肩俯仰", (X_ARM, Y_REAR, Z_SH), (0, 1, 0), (1, 0, 0), "P04_肩叉_螺旋体30%_墙5底5_竖打", "P05_大臂旋转座_螺旋体30%_墙4底5_竖打"),
("J3", "大臂自转", (X_ARM, Y_AXIS, Z_R3), (0, 0, -1), (1, 0, 0), "P05_大臂旋转座_螺旋体30%_墙4底5_竖打", "P06_大臂骨架_螺旋体25%_墙4底5_竖打"),
("J4", "肘部俯仰", (X_ARM, Y_REAR, Z_EL), (0, 1, 0), (1, 0, 0), "P06_大臂骨架_螺旋体25%_墙4底5_竖打", "P07_小臂骨架_螺旋体30%_墙5底5_竖打"),
("J5", "腕部俯仰", (X_ARM, Y_REAR, Z_WR), (0, 1, 0), (1, 0, 0), "P07_小臂骨架_螺旋体30%_墙5底5_竖打", "P08_腕偏转座_螺旋体25%_墙4底5_竖打"),
("J6", "腕自转", (X_ARM, Y_AXIS, Z_R6), (0, 0, -1), (1, 0, 0), "P08_腕偏转座_螺旋体25%_墙4底5_竖打", "P09_工具法兰_螺旋体30%_墙4底5_竖打"),
]
AXIS = {t[0]: dict(rear=t[2], d=t[3], xdir=t[4]) for t in JOINTS}
def hub_plane(tag):
j = AXIS[tag]
return tuple(j["rear"][i] + j["d"][i] * HUB for i in range(3))
def seg_dist(p1, q1, p2, q2):
"""Minimum distance between two 3-D segments (parameters clamped to [0,1])."""
d1 = [q1[i] - p1[i] for i in range(3)]
d2 = [q2[i] - p2[i] for i in range(3)]
r = [p1[i] - p2[i] for i in range(3)]
a = sum(x * y for x, y in zip(d1, d1))
e = sum(x * y for x, y in zip(d2, d2))
f = sum(x * y for x, y in zip(d2, r))
b = sum(x * y for x, y in zip(d1, d2))
s = sum(x * y for x, y in zip(d1, r))
if a < 1e-12:
t0 = 0.0
t1 = max(0.0, min(1.0, f / e)) if e > 1e-12 else 0.0
elif e < 1e-12:
t1 = 0.0
t0 = max(0.0, min(1.0, -s / a))
else:
den = a * e - b * b
if abs(den) < 1e-12:
t0 = 0.0
t1 = max(0.0, min(1.0, f / e))
else:
t0 = max(0.0, min(1.0, (b * f - e * s) / den))
t1 = max(0.0, min(1.0, (e * f - b * s) / den))
c = [p1[i] + d1[i] * t0 - (p2[i] + d2[i] * t1) for i in range(3)]
return math.hypot(*c)
def columns():
"""Each module as a segment (rear datum -> hub plane) plus its across-axis radius."""
out = {}
for tag, cn, rear, d, xd, holder, driven in JOINTS:
q = tuple(rear[i] + d[i] * HUB for i in range(3))
out[tag] = (rear, q, R_MOT)
return out
def relabel():
"""The designed 1-D relations that set the stations. Each pair is separated along
one global coordinate because the two columns are perpendicular or collinear there."""
C = {}
C["pod drum clear of the pitch sweep"] = (Z_RL - POD_R) - (Z_SH + SWEEP_R)
C["bridge vs elbow sleeve"] = (Y_R_IN + 8.0) - 96.0
C["cheek vs arm x envelope"] = 64.0 - (X_ARM + 42.0)
C["fingertip above the foot"] = Z_TIP - FOOT_H
C["roll motor rear below the elbow motor"] = (Z_EI - R_MOT) - Z_R4
C["wrist-cap plate above the wrist motor"] = (Z_CAP - PLATE_T) - (Z_WR + R_MOT)
C["fork plate above the humerus plate"] = (Z_RL - 42.0) - (Z_SH + 44.0)
C["gripper motor below the wrist motor"] = (Z_WR - R_MOT) - Z_M6
C["gripper clamp band vs palm plate"] = PL_OUT[0] - (Y_M6 + 31.0)
C["elbow motor rear vs chest plate edge"] = Y_R_IN - Y_CHEST
C["gripper tail vs chest plate edge"] = (Y_M6 - 36.0) - Y_CHEST
C["fingertip to ground"] = Z_TIP
return C
def report():
print("vertical chain: tip=%.0f J6hub=%.0f J5axis=%.0f J4hub=%.0f J4rear=%.0f "
"J3axis=%.0f J2axis=%.0f J1roll=%.0f deck=%.0f pod top=%.0f"
% (Z_TIP, Z_M6 - HUB, Z_WR, Z_CAP, Z_R4, Z_EI, Z_SH, Z_RL, Z_CHEST1, Z_SH_TOP))
print("lateral: Y_R_IN=%.0f Y_H=%.0f Y_R_OUT=%.0f Y_M6=%.0f chest half-width=%.0f\n"
% (Y_R_IN, Y_H, Y_R_OUT, Y_M6, Y_CHEST))
for tag, cn, rear, d, xd, holder, driven in JOINTS:
h = hub_plane(tag)
print(" %-3s %-5s rear=(%6.1f,%6.1f,%6.1f) d=(%2d,%2d,%2d) hub=(%6.1f,%6.1f,%6.1f) %s -> %s"
% (tag, cn, rear[0], rear[1], rear[2], d[0], d[1], d[2], h[0], h[1], h[2], holder, driven))
print("\n-- designed relations (each must be >= %.0f mm) --" % GAP_MIN)
bad = 0
for k, v in relabel().items():
if v < GAP_MIN:
bad += 1
print(" %+-7.1f %-46s %s" % (v, k, "OK" if v >= GAP_MIN else "*** CLASH ***"))
print("\n humerus L1=%.0f forearm(elbow->wrist)=%.0f hand(wrist->tip)=%.0f"
% (L1, Z_EI - Z_WR, Z_WR - Z_TIP))
print(" shoulder->tip = %.0f mm height to pod top = %.0f mm torso %.0f..%.0f"
% (Z_SH - Z_TIP, Z_SH_TOP, Z_CHEST0, Z_CHEST1))
return bad
if __name__ == "__main__":
sys.exit(1 if report() else 0)
+24
View File
@@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
"""仓库内路径的唯一来源。
原先这些常量是硬编码的 G:/Robot_v2 绝对路径,仓库换盘符即全断;现在由本文件
位置推出。REPO 的父目录就是原来的 ROOT(=G:/Robot_v2),所以外部 STEP 输入的解析
结果与从前逐字相同。三个 ARM_* 环境变量是临时覆盖入口。
"""
import os
_HERE = os.path.dirname(os.path.abspath(__file__)).replace("\\", "/") # .../arm
REPO = os.environ.get("ARM_WORKSPACE") or os.path.dirname(_HERE)
ROOT = os.environ.get("ARM_ROOT") or os.path.dirname(REPO)
MODEL = os.environ.get("ARM_MODEL_ROOT") or (ROOT + r"/Model/Solidworks")
SRC_STEP = MODEL + r"/电机.STEP"
HALF_STEP = MODEL + r"/配件/端面齿半联轴器_相同件x2.STEP"
CLAMP_STEP = MODEL + r"/配件/端面齿联轴器_抱箍_两片装配.STEP"
OUT = REPO + r"/out"
WEB = REPO + r"/web"
DOCS = REPO + r"/docs"
# 可达包络 FK 采样的缓存(ws_cloud.npz / ws_metrics.json)。原先躺在 gitignore 的
# scratch/ 里,构建却依赖它——缺了新克隆就跑不出 ENV 件。
CACHE = REPO + r"/data/cache"
# 查看器模板。S4 拆成 webapp/index.html + js/** 后这条即作废。
TPL = REPO + r"/src/viewer_tpl.html"
+3
View File
@@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
"""查看器侧:数据打包、本地静态服务、headless 截图。
"""
+76
View File
@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*-
"""Assemble the single-file viewer: three.js (inline, no CDN) + mesh data + 2D sheets."""
import io
import json
import os
import sys
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
from arm.paths import WEB, DOCS, REPO, TPL
import time
def rebuild_viewer():
print("=" * 80, flush=True)
print("【第五阶段 5/5】打包单文件三维交互查看器 (机器人手臂3D查看器.html)...", flush=True)
print("=" * 80, flush=True)
t0 = time.time()
print(" - 读取 Three.js 离线 3D 渲染内核...", end="", flush=True)
three = io.open(WEB + "/three_inline.js", encoding="utf-8").read()
assert len(three) > 400000, len(three)
print(f" 完成 ({len(three)/1024:.0f} KB) ✓", flush=True)
print(" - 读取几何网格与关节运动学数据...", end="", flush=True)
data = io.open(WEB + "/mesh_arm.json", encoding="utf-8").read()
sheets = io.open(WEB + "/sheets.jsdata", encoding="utf-8").read()
trv = io.open(DOCS + "/travel.json", encoding="utf-8").read() if os.path.exists(
DOCS + "/travel.json") else "[]"
col = io.open(DOCS + "/collide.json", encoding="utf-8").read() if os.path.exists(
DOCS + "/collide.json") else '{"caps":[],"parts":{}}'
screws = io.open(DOCS + "/screws.json", encoding="utf-8").read() if os.path.exists(
DOCS + "/screws.json") else "[]"
ik_solver = io.open(WEB + "/arm-ik-solver.js", encoding="utf-8").read()
ik_glue = io.open(WEB + "/ik-glue.js", encoding="utf-8").read()
tpl = io.open(TPL, encoding="utf-8").read()
print(f" 完成 ({len(data)/1024:.0f} KB) ✓", flush=True)
print(" - 打包生成全内置单文件 HTML...", end="", flush=True)
out = (tpl.replace("/*__THREE__*/", three)
.replace("/*__DATA__*/", data)
.replace("/*__SHEETS__*/", sheets)
.replace("/*__TRAVEL__*/", trv)
.replace("/*__COLLIDE__*/", col)
.replace("/*__SCREWS__*/", screws)
.replace("/*__IKSOLVER__*/", ik_solver)
.replace("/*__IKGLUE__*/", ik_glue))
assert "/*__" not in out, [l for l in out.split("\n") if "/*__" in l][:3]
dst = WEB + "/机器人手臂3D查看器.html"
# 【2026-10-06】三个副本逐个写、逐个报错,不要一把梭。
# 原来三行连写,任一份被浏览器独占(Windows 上打开中的 html 是独占锁)就抛异常,
# 而调用方 arm_model.py 把整个 rebuild_viewer() 包在 try/except 里,
# 于是只写成功第一份、另外两份静默停在旧版本 —— 表现为"代码改了但网页没变"。
# 实测就是这个坑:18:52 那次 dst 是新的,web/index.html 和根目录那份还停在 18:12。
ok, failed = True, []
for path in (dst, WEB + "/index.html", REPO + "/机器人手臂3D查看器.html"):
try:
io.open(path, "w", encoding="utf-8").write(out)
except Exception as e:
ok = False
failed.append("%s (%s)" % (path, e))
sz_mb = os.path.getsize(dst) / 1e6
print(f" 完成 ({sz_mb:.2f} MB, 耗时: {time.time()-t0:.2f}s) ✓", flush=True)
if failed:
print("!! 以下副本写入失败(多半是浏览器正打开着该文件,Windows 独占锁):", flush=True)
for f in failed:
print(" - %s" % f, flush=True)
print(" 关掉对应页面后重跑 python -m arm.viewer.build_viewer 即可。\n", flush=True)
else:
print(f"-> 3D查看器已更新至: {dst}、{WEB}/index.html 与 根目录/机器人手臂3D查看器.html\n",
flush=True)
if __name__ == "__main__":
rebuild_viewer()
+180
View File
@@ -0,0 +1,180 @@
# -*- coding: utf-8 -*-
"""Headless Edge screenshots of the viewer, for the visual self-check loop."""
import os
import subprocess
import sys
import shutil
import glob
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
from arm.paths import WEB, DOCS
SHOTS = DOCS + "/shots"
HTML = WEB + "/机器人手臂3D查看器.html"
CAND = [r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
r"C:\Program Files\Microsoft\Edge\Application\msedge.exe"]
EDGE = next((c for c in CAND if os.path.exists(c)), None)
if not EDGE:
EDGE = glob.glob(r"C:\Users\*\AppData\Local\Microsoft\Edge\*\msedge.exe")
EDGE = EDGE[0] if EDGE else None
if not EDGE:
raise SystemExit("msedge not found")
VIEWS = {
"01_iso": "?cam=iso",
"zoom_user": "?cam=iso&az=-0.9&po=1.15&rd=470&tx=30&ty=320&tz=-80&xray=0",
"user_harness_view": "?az=-1.85&po=1.32&rd=430&tx=0&ty=330&tz=-115&xray=0",
"user_harness_zoom": "?az=-1.85&po=1.32&rd=280&tx=-5&ty=360&tz=-115&xray=0",
"user_m1_rear": "?az=-1.25&po=1.35&rd=350&tx=-70&ty=570&tz=-128&xray=0",
"user_m1_exact": "?az=-1.5708&po=1.5708&rd=260&tx=0&ty=610&tz=-128&xray=0",
"user_m1_bypass_oblique": "?az=-1.0&po=1.15&rd=300&tx=-40&ty=580&tz=-140&xray=0",
"user_smooth_harness": "?az=1.50&po=1.45&rd=340&tx=-15&ty=560&tz=-128&xray=0",
"user_contour_harness": "?az=1.5708&po=1.50&rd=360&tx=-15&ty=320&tz=-128&xray=0",
"02_front": "?cam=front",
# 工程图 / 装配向导 / 运动模拟三种模式。URL 参数(?view=&sheet=&theme=&guide=)就是
# 为这几条截图加的:不把它们纳入基线,拆 CSS 与那 700 行工程图 JS 时等于没有关卡。
"m1_sheet_front": "?view=sheet",
"m2_sheet_joint": "?view=sheet&sheet=1",
"m3_sheet_exploded": "?view=sheet&sheet=2",
"m4_sheet_side": "?view=sheet&sheet=3",
"m5_guide_step1": "?view=sheet&sheet=guide&guide=0",
"m6_guide_step5": "?view=sheet&sheet=guide&guide=4",
"m7_sheet_blueprint": "?view=sheet&theme=blueprint",
"m8_sheet_dark": "?view=sheet&theme=dark",
"m9_motion": "?view=motion",
"03_side": "?cam=side",
"04_top": "?cam=top",
"05_exploded": "?cam=iso&expl=100",
"06_wrist": "?cam=wrist&xray=0",
"07_joint": "?cam=joint",
"08_pose": "?cam=iso&j2=35&j3=60&j4=-25&j1=25",
"09_sheet": "?sheet=1",
"10_solid": "?cam=iso&xray=0",
"11_tool_flange": "?cam=wrist&xray=0&j6=45",
"12_elbow_flare": "?cam=elbow&xray=0",
"13_forearm_side": "?cam=side&xray=0&rd=340&ty=245&tz=-135",
"user_target": "?cam=side&az=-1.5708&po=1.57&xray=0&rd=340&tx=100&ty=245&tz=-135",
"view_yz_pos_x": "?cam=side&az=0&po=1.57&xray=0&rd=340&tx=100&ty=245&tz=-135",
"view_yz_neg_x": "?cam=side&az=3.14159&po=1.57&xray=0&rd=340&tx=100&ty=245&tz=-135",
"view_iso_forearm": "?cam=side&az=-0.65&po=1.2&xray=0&rd=320&tx=100&ty=245&tz=-135",
"user_view1": "?cam=wrist&az=0.55&po=1.4&rd=310&xray=0",
"user_view2": "?cam=wrist&az=0.2&po=1.4&rd=290&xray=0",
"user_p04": "?cam=joint&az=-1.5708&po=1.57&rd=380&xray=0",
"user_p04_opp": "?cam=joint&az=1.5708&po=1.57&rd=380&xray=0",
"user_elbow_rear": "?az=1.5708&po=1.5708&rd=280&tx=95&ty=315&tz=-128&xray=0",
"user_p07_wrist": "?az=1.5708&po=1.5708&rd=240&tx=95&ty=235&tz=-128&xray=0",
"user_elbow_front": "?az=-1.5708&po=1.5708&rd=250&tx=18.5&ty=310&tz=-128&xray=0",
"user_p06_xz": "?az=1.5708&po=1.5708&rd=240&tx=18.5&ty=350&tz=-128&xray=0&hide=胸板,底脚,肩吊臂",
"user_p06_yz": "?az=0&po=1.5708&rd=260&tx=18.5&ty=350&tz=-110&xray=0",
"user_p06_iso": "?az=-0.65&po=1.25&rd=260&tx=-15&ty=350&tz=-128&xray=0",
"user_p07_creases": "?az=-0.65&po=1.25&rd=260&tx=30&ty=270&tz=-130&xray=0",
# 电机腔内壁(隐藏全部电机,从腔内看 R35/R30.15 两段同心圆弧是否连续)
"bay_p06_inside": "?az=1.5708&po=1.5708&rd=250&tx=18.5&ty=345&tz=-128&xray=0&hide=J1,J2,J3,J4,J5,J6",
"bay_p07_inside": "?az=1.5708&po=1.5708&rd=240&tx=18.5&ty=235&tz=-128&xray=0&hide=J1,J2,J3,J4,J5,J6",
"bay_p08_inside": "?az=1.5708&po=1.5708&rd=210&tx=18.5&ty=175&tz=-128&xray=0&hide=J1,J2,J3,J4,J5,J6",
"user_p04_side": "?az=1.5708&po=1.5708&rd=300&tx=18.5&ty=520&tz=-128&xray=0&hide=胸板,底脚,肩吊臂",
"user_p04_bottom": "?az=0.5&po=2.0&rd=240&tx=18.5&ty=490&tz=-128&xray=0&hide=胸板,底脚,肩吊臂",
"user_p04_bottom2": "?az=1.2&po=2.0&rd=260&tx=18.5&ty=490&tz=-128&xray=0&hide=胸板,底脚,肩吊臂",
"user_shoulder_solid": "?cam=joint&az=2.1&po=1.35&rd=380&xray=0",
"user_shoulder_xray": "?cam=joint&az=2.1&po=1.35&rd=380",
"user_shoulder_top": "?cam=joint&az=-0.6&po=0.6&rd=360&xray=0",
# P03 轻量化桁架版(孤立视图:只留 P03,隐藏其余零件/电机/螺钉/包络)
"p03_light_iso": "?az=0.62&po=1.15&rd=300&tx=-70&ty=548&tz=-128&xray=0&hide=P01,P02,P04,P05,P06,P07,P08,P09,M1,M2,M3,M4,M5,M6,S0,S1,ENV",
"p03_light_side": "?az=1.5708&po=1.5708&rd=320&tx=-70&ty=548&tz=-128&xray=0&hide=P01,P02,P04,P05,P06,P07,P08,P09,M1,M2,M3,M4,M5,M6,S0,S1,ENV",
"p03_light_rear": "?az=0.0&po=1.45&rd=300&tx=-70&ty=548&tz=-128&xray=0&hide=P01,P02,P04,P05,P06,P07,P08,P09,M1,M2,M3,M4,M5,M6,S0,S1,ENV",
"p03_light_join": "?az=0.62&po=1.15&rd=420&tx=18.5&ty=520&tz=-128&xray=0",
"p03_light_xray": "?az=0.62&po=1.15&rd=300&tx=-70&ty=548&tz=-128&xray=1&hide=P01,P02,P04,P05,P06,P07,P08,P09,M1,M2,M3,M4,M5,M6,S0,S1,ENV",
# 减重版(2026-10-02):P04 立柱槽 / P06 过渡块窗 / P07 顶板槽 的孤立视图
# 俯视看朝上敞开的槽口,斜视看槽壁与留下来的抗弯腹板
"hollow_p04_top": "?az=0.0&po=0.05&rd=250&tx=18.5&ty=585&tz=-128&xray=0&hide=P01,P02,P03,P05,P06,P07,P08,P09,M1,M2,M3,M4,M5,M6,S0,S1,ENV",
"hollow_p04_iso": "?az=0.7&po=1.05&rd=280&tx=18.5&ty=585&tz=-128&xray=0&hide=P01,P02,P03,P05,P06,P07,P08,P09,M1,M2,M3,M4,M5,M6,S0,S1,ENV",
"hollow_p07_top": "?az=0.0&po=0.05&rd=230&tx=18.5&ty=270&tz=-128&xray=0&hide=P01,P02,P03,P04,P05,P06,P08,P09,M1,M2,M3,M4,M5,M6,S0,S1,ENV",
"hollow_p07_iso": "?az=0.7&po=1.05&rd=260&tx=18.5&ty=275&tz=-128&xray=0&hide=P01,P02,P03,P04,P05,P06,P08,P09,M1,M2,M3,M4,M5,M6,S0,S1,ENV",
"hollow_p06_iso": "?az=0.7&po=1.05&rd=190&tx=18.5&ty=368&tz=-128&xray=0&hide=P01,P02,P03,P04,P05,P07,P08,P09,M1,M2,M3,M4,M5,M6,S0,S1,ENV",
# P03↔立柱 安装接口(新版 4xM5 从腔体上方拧入):俯视看螺钉落位
"p03_mount_top": "?az=0.9&po=1.30&rd=190&tx=-115&ty=476&tz=-128&xray=0&hide=P02,P04,P05,P06,P07,P08,P09,M1,M2,M3,M4,M5,M6,ENV",
"p03_mount_iso": "?az=2.2&po=0.95&rd=230&tx=-115&ty=486&tz=-128&xray=0&hide=P02,P04,P05,P06,P07,P08,P09,M1,M2,M3,M4,M5,M6,ENV",
"p03_mount_loose": "?az=0.9&po=0.42&rd=260&tx=-115&ty=500&tz=-128&xray=0&expl=60&hide=P02,P04,P05,P06,P07,P08,P09,M1,M2,M3,M4,M5,M6,ENV",
"j3_前端压盖_装配": "?az=0.7&po=2.72&rd=190&tx=19.5&ty=396&tz=-128&xray=0&hide=立柱,底座,肩关节安装悬臂,肩叉,大臂骨架,小臂骨架,腕部转接座,末端工具法兰,M1,M2,M4,M5,M6,包络经纬网",
"j3_前端压盖_全件": "?az=0.7&po=2.6&rd=300&tx=19.5&ty=420&tz=-128&xray=0",
# 承压面下沉 2mm 留下的"悬空凸台"(2026-10-04 整改):沿电机轴线从尾端面方向看,
# 四个视图分别对应 P04/P05/P06/P07 的后端。ax/po 沿轴向,rd 拉近到 R35 座圈。
# 沿电机轴线从尾端面看过去:承压面(R35圆面) + 4xS02 沉孔,凸台消失后应是干净圆面
"boss_p04": "?az=0.55&po=1.30&rd=150&tx=19.5&ty=490&tz=-158&xray=0&hide=P01,P02,P03,P05,P06,P07,P08,P09,M3,M4,M5,M6,ENV",
"user_fork_fixed": "?az=0.55&po=1.30&rd=150&tx=19.5&ty=490&tz=-158&xray=0&hide=P01,P02,P03,P06,P07,P08,P09,M1,M4,M5,M6,ENV,S0,S1",
"bay_p04_inside": "?az=0.55&po=2.10&rd=150&tx=19.5&ty=490&tz=-158&xray=0&hide=P01,P02,P03,P05,P06,P07,P08,P09,M1,M2,M3,M4,M5,M6,ENV,S0,S1",
"bay_p06_inside": "?az=0.55&po=2.10&rd=150&tx=19.5&ty=332&tz=-158&xray=0&hide=P01,P02,P03,P04,P05,P07,P08,P09,M1,M2,M3,M4,M5,M6,ENV,S0,S1",
"bay_p07_inside": "?az=0.55&po=2.10&rd=150&tx=19.5&ty=227&tz=-158&xray=0&hide=P01,P02,P03,P04,P05,P06,P08,P09,M1,M2,M3,M4,M5,M6,ENV,S0,S1",
"p04_both_ends": "?az=1.5708&po=1.5708&rd=200&tx=19.5&ty=490&tz=-128&xray=0&hide=P01,P02,P03,P05,P06,P07,P08,P09,M1,M3,M4,M5,M6,ENV,S0,S1",
"p04_m2_side": "?az=1.2&po=1.9&rd=240&tx=19.5&ty=490&tz=-128&xray=0&hide=P01,P02,P03,P05,P06,P07,P08,P09,M1,M3,M4,M5,M6,ENV,S0,S1",
"p06_m4_side": "?az=1.2&po=1.9&rd=240&tx=19.5&ty=332&tz=-128&xray=0&hide=P01,P02,P03,P04,P05,P07,P08,P09,M1,M2,M3,M5,M6,ENV,S0,S1",
"p07_m5_side": "?az=1.2&po=1.9&rd=240&tx=19.5&ty=227&tz=-128&xray=0&hide=P01,P02,P03,P04,P05,P06,P08,P09,M1,M2,M3,M4,M6,ENV,S0,S1",
"p05_m3_side": "?az=1.2&po=1.9&rd=240&tx=19.5&ty=400&tz=-128&xray=0&hide=P01,P02,P03,P04,P06,P07,P08,P09,M1,M2,M4,M5,M6,ENV,S0,S1",
"boss_p05": "?az=1.5708&po=1.5708&rd=190&tx=18.5&ty=392&tz=-128&xray=0&hide=P01,P02,P03,P04,P06,P07,P08,P09,M2,M4,M5,M6,ENV",
"user_compare_view": "?cam=side&az=0&po=1.5708&rd=460&tx=19.5&ty=380&tz=-128&xray=0&hide=P01,P02,P03,P09,M1,M6,ENV",
"user_p07_check": "?az=1.5708&po=1.5708&rd=260&tx=19.5&ty=220&tz=-128&xray=0&hide=P01,P02,P03,P04,P05,P06,P09,M1,M2,M3,M4,M5,M6,ENV",
"boss_p06": "?az=1.5708&po=1.5708&rd=190&tx=18.5&ty=332&tz=-128&xray=0&hide=P01,P02,P03,P04,P05,P07,P08,P09,M1,M2,M3,M5,M6,ENV",
"boss_p07": "?az=0&po=0.0&rd=210&tx=19.5&ty=215&tz=-128&xray=0&hide=P01,P02,P03,P04,P05,P06,P08,P09,M1,M2,M3,M4,M6,ENV",
"svg_side": f"file:///{DOCS}/sheet_side.svg",
"svg_joint": f"file:///{DOCS}/sheet_joint.svg",
"svg_exploded": f"file:///{DOCS}/sheet_exploded.svg",
"user_circle_check": "?az=0.8&po=1.95&rd=240&tx=19.5&ty=430&tz=-128&xray=0&hide=M1,M2,M3,M4,M5,M6,ENV",
"user_exact_view": "?az=1.5708&po=1.92&rd=150&tx=19.5&ty=440&tz=-128&xray=0&hide=P01,P02,P03,M1,M2,M3,M4,M5,M6,ENV",
"shot_p08_user": "?az=1.5708&po=1.92&rd=150&tx=19.5&ty=176&tz=-128&xray=0&hide=P01,P02,P03,P04,P05,P06,P07,P09,M1,M2,M3,M4,M5,M6,ENV",
"p05_flank_view": "?az=0&po=1.5708&rd=200&tx=19.5&ty=440&tz=-135&xray=0&hide=P01,P02,P03,P07,P08,P09,M1,M4,M5,M6,ENV",
"harness_full_iso": "?cam=iso&xray=0",
"harness_overview": "?az=-0.7&po=1.2&rd=520&tx=0&ty=400&tz=-120&xray=0",
"harness_xray_internal": "?az=-0.7&po=1.2&rd=520&tx=0&ty=400&tz=-120&alpha=0.35&xray=1",
"harness_p07_window": "?az=-0.65&po=1.25&rd=260&tx=25&ty=275&tz=-130&xray=0",
"harness_p07_xray": "?az=-0.65&po=1.25&rd=260&tx=25&ty=275&tz=-130&alpha=0.35&xray=1",
"harness_p04_p05": "?az=0.8&po=1.35&rd=280&tx=25&ty=470&tz=-128&xray=0",
"harness_p04_p05_xray": "?az=0.8&po=1.35&rd=280&tx=25&ty=470&tz=-128&alpha=0.35&xray=1",
"harness_p06_window": "?az=-0.65&po=1.25&rd=240&tx=25&ty=355&tz=-128&xray=0",
"harness_xray_full": "?cam=iso&xray=1",
# 扎带拱桥核验:沿 ±Y 正视肩部,确认三个拱桥各自露出多少、线束是否压在桥上
"tie_probe_negY": "?az=1.5708&po=1.5708&rd=460&tx=-30&ty=590&tz=-128&xray=0",
"tie_probe_posY": "?az=-1.5708&po=1.5708&rd=460&tx=-30&ty=590&tz=-128&xray=0",
"tie_after_negY": "?az=1.5708&po=1.5708&rd=300&tx=-25&ty=600&tz=-128&xray=0",
"tie_after_oblique": "?az=2.05&po=1.30&rd=330&tx=-25&ty=600&tz=-128&xray=0",
"tie_after_close": "?az=1.90&po=1.50&rd=180&tx=-25&ty=605&tz=-100&xray=0",
# P06/P07 −X 侧线束走廊:从 −X、−Y 斜看(纯 −X 会被蓝色立柱挡住)
"tie_after_p0607": "?az=2.35&po=1.5708&rd=300&tx=0&ty=290&tz=-102.5&xray=0",
"tie_after_p0607_obl": "?az=2.60&po=1.35&rd=260&tx=-5&ty=290&tz=-110&xray=0",
}
os.makedirs(SHOTS, exist_ok=True)
want = sys.argv[1:] or list(VIEWS)
def take_shot(nm):
q = VIEWS[nm]
out = "%s/%s.png" % (SHOTS, nm)
import time, tempfile
t_bust = int(time.time() * 1000)
target = q if q.startswith("file://") else "file:///" + HTML.replace("\\", "/") + q + (
f"&still=1&_t={t_bust}" if "?" in q else f"?still=1&_t={t_bust}")
udd = tempfile.mkdtemp(prefix="eshot")
cmd = [EDGE, "--headless=new", "--use-gl=angle", "--use-angle=d3d11",
"--disable-cache", "--disable-application-cache", "--disk-cache-size=0",
"--user-data-dir=" + udd,
"--enable-gpu-rasterization", "--ignore-gpu-blocklist",
"--hide-scrollbars", "--force-device-scale-factor=1",
"--window-size=1500,860", "--virtual-time-budget=20000",
"--screenshot=" + out, target]
r = subprocess.run(cmd, capture_output=True, timeout=180)
shutil.rmtree(udd, ignore_errors=True)
ok = os.path.exists(out) and os.path.getsize(out) > 20000
err = (r.stderr or b"").decode("utf-8", errors="ignore").strip()[:90].replace("\n", " ")
sz = os.path.getsize(out) if os.path.exists(out) else 0
print("%-18s %s %8s %s" % (nm, "OK " if ok else "FAIL", sz, err), flush=True)
return ok
if __name__ == "__main__":
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=min(4, os.cpu_count() or 2)) as executor:
results = list(executor.map(take_shot, want))
print("edge:", EDGE)
print("all shots ok:", all(results))