You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

398 lines
17 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# -*- coding: utf-8 -*-
"""Вспомогательные функции геометрического ядра (FreeCAD / OpenCASCADE) для проекта клапана.
Запускается интерпретатором из комплекта FreeCAD:
tools/freecad/squashfs-root/usr/bin/python <script.py>
Модуль сам добавляет в sys.path библиотеки FreeCAD и локальные pylibs.
Соглашение о координатах модели: ось Z — ось входного патрубка (вертикаль клапана), Z = 0 — торец
(уплотнительная плоскость) входного фланца; ось выходного патрубка направлена по +X.
"""
import math
import os
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FC_ROOT = os.path.join(ROOT, "tools", "freecad", "squashfs-root")
if os.path.join(FC_ROOT, "usr", "lib") not in sys.path:
sys.path[:0] = [os.path.join(FC_ROOT, "usr", "lib")]
_pl = os.path.join(ROOT, "tools", "pylibs311")
if _pl not in sys.path:
sys.path.append(_pl) # в конец: комплектные numpy/scipy FreeCAD имеют приоритет
import FreeCAD # noqa: E402
import Part # noqa: E402
from FreeCAD import Matrix, Vector as V # noqa: E402
BIG = 5000.0
# --------------------------------------------------------------------------------------------
# Профили (контуры в полуплоскости r–z) и тела вращения
# --------------------------------------------------------------------------------------------
def _corner(p_prev, p, p_next, spec):
"""Обработка вершины контура: скругление {'f': R} или фаска {'c': C} ({'c': (C1, C2)}).
Возвращает (точка_входа, [рёбра_вершины], точка_выхода) в координатах (x, y) контура."""
ax, ay = p_prev[0] - p[0], p_prev[1] - p[1]
bx, by = p_next[0] - p[0], p_next[1] - p[1]
la, lb = math.hypot(ax, ay), math.hypot(bx, by)
ux, uy, wx, wy = ax / la, ay / la, bx / lb, by / lb
if "f" in spec:
R = float(spec["f"])
cosang = max(-1.0, min(1.0, ux * wx + uy * wy))
ang = math.acos(cosang)
d = R / math.tan(ang / 2.0)
if d > la + 1e-9 or d > lb + 1e-9:
raise ValueError("скругление R%.3g не помещается в вершине %s" % (R, p))
t1 = (p[0] + ux * d, p[1] + uy * d)
t2 = (p[0] + wx * d, p[1] + wy * d)
hx, hy = ux + wx, uy + wy
hl = math.hypot(hx, hy)
hx, hy = hx / hl, hy / hl
dist = R / math.sin(ang / 2.0)
c = (p[0] + hx * dist, p[1] + hy * dist)
m = (c[0] - hx * R, c[1] - hy * R)
return t1, ("arc", t1, m, t2), t2
if "c" in spec:
cc = spec["c"]
c1, c2 = (cc, cc) if not isinstance(cc, (tuple, list)) else cc
t1 = (p[0] + ux * c1, p[1] + uy * c1)
t2 = (p[0] + wx * c2, p[1] + wy * c2)
return t1, ("line", t1, t2), t2
raise ValueError("неизвестная обработка вершины: %r" % (spec,))
def profile_wire(points, plane="xz"):
"""Замкнутый контур по списку вершин. Вершина: (a, b) или (a, b, {'f': R}) / (a, b, {'c': C}).
plane='xz' — контур в плоскости XZ (a = x = r, b = z), 'xy' — в плоскости XY."""
pts = [(float(p[0]), float(p[1])) for p in points]
specs = [(p[2] if len(p) > 2 else None) for p in points]
n = len(pts)
if pts[0] == pts[-1]:
pts, specs, n = pts[:-1], specs[:-1], n - 1
ins, outs, mids = [None] * n, [None] * n, [None] * n
for i in range(n):
if specs[i]:
t1, mid, t2 = _corner(pts[i - 1], pts[i], pts[(i + 1) % n], specs[i])
ins[i], mids[i], outs[i] = t1, mid, t2
else:
ins[i] = outs[i] = pts[i]
def to3(q):
return V(q[0], 0, q[1]) if plane == "xz" else V(q[0], q[1], 0)
edges = []
for i in range(n):
if mids[i]:
kind = mids[i][0]
if kind == "arc":
edges.append(Part.Arc(to3(mids[i][1]), to3(mids[i][2]), to3(mids[i][3])).toShape())
else:
edges.append(Part.makeLine(to3(mids[i][1]), to3(mids[i][2])))
a, b = outs[i], ins[(i + 1) % n]
if math.hypot(a[0] - b[0], a[1] - b[1]) > 1e-7:
edges.append(Part.makeLine(to3(a), to3(b)))
return Part.Wire(edges)
def revolve(points, angle=360.0):
"""Тело вращения вокруг оси Z по контуру в полуплоскости (r, z)."""
for p in points:
if p[0] < -1e-9:
raise ValueError("точка контура с r < 0: %r" % (p,))
face = Part.Face(profile_wire(points, "xz"))
solid = face.revolve(V(0, 0, 0), V(0, 0, 1), angle)
return _as_solid(solid)
def extrude_xy(points, h, z0=0.0):
"""Призма: контур в плоскости XY (на высоте z0), выдавливание по +Z на h."""
face = Part.Face(profile_wire(points, "xy"))
face.translate(V(0, 0, z0))
return _as_solid(face.extrude(V(0, 0, h)))
def _as_solid(shape):
if shape.ShapeType == "Solid":
return shape
if shape.Solids:
return shape.Solids[0] if len(shape.Solids) == 1 else Part.makeCompound(shape.Solids)
try:
return Part.Solid(Part.Shell(shape.Faces))
except Exception:
return shape
# --------------------------------------------------------------------------------------------
# Примитивы
# --------------------------------------------------------------------------------------------
_AX = {"x": V(1, 0, 0), "y": V(0, 1, 0), "z": V(0, 0, 1), "-x": V(-1, 0, 0), "-y": V(0, -1, 0), "-z": V(0, 0, -1)}
def cyl(d, h, at=(0, 0, 0), axis="z"):
"""Цилиндр диаметром d, высотой h; основание в точке at, ось axis ('x','y','z','-x',… или Vector)."""
ax = _AX[axis] if isinstance(axis, str) else axis
return Part.makeCylinder(d / 2.0, h, V(*at), ax)
def tube(do, di, h, at=(0, 0, 0), axis="z"):
return cyl(do, h, at, axis).cut(cyl(di, h, at, axis))
def cone(d1, d2, h, at=(0, 0, 0), axis="z"):
ax = _AX[axis] if isinstance(axis, str) else axis
return Part.makeCone(d1 / 2.0, d2 / 2.0, h, V(*at), ax)
def box(lx, ly, lz, at=(0, 0, 0)):
"""Параллелепипед с минимальным углом в точке at."""
return Part.makeBox(lx, ly, lz, V(*at))
def sphere(d, at=(0, 0, 0)):
return Part.makeSphere(d / 2.0, V(*at))
def polar(shape, n, start_deg=0.0, axis_pt=(0, 0, 0), axis_dir=(0, 0, 1)):
"""n копий тела по окружности вокруг оси (первая — повёрнута на start_deg)."""
out = []
for i in range(n):
s = shape.copy()
s.rotate(V(*axis_pt), V(*axis_dir), start_deg + i * 360.0 / n)
out.append(s)
return out
def fuse_all(shapes):
s = shapes[0]
if len(shapes) > 1:
s = s.multiFuse(list(shapes[1:]))
return clean(s)
def cut_all(shape, tools):
if not tools:
return shape
return clean(shape.cut(Part.makeCompound(list(tools)) if len(tools) > 1 else tools[0]))
def clean(shape):
"""Удаление лишних разбиений граней после булевых операций."""
try:
r = shape.removeSplitter()
return r if r.isValid() else shape
except Exception:
return shape
def hex_prism(s, h, at=(0, 0, 0), axis="z", chamfer=True, hole_d=0.0):
"""Шестигранная призма «под ключ» s высотой h (гайка/головка). chamfer — фаски 30° с двух торцов."""
R = s / math.sqrt(3.0)
pts = [(R * math.cos(math.radians(60 * i)), R * math.sin(math.radians(60 * i))) for i in range(6)]
pr = extrude_xy(pts, h)
if chamfer:
e = (2 * R - 0.95 * s) / 2.0 * math.tan(math.radians(30)) # высота фаски на вершине
dk = 0.95 * s # диаметр фаски на торце
prof = [(0, 0), (dk / 2, 0), (R + 0.2, (R + 0.2 - dk / 2) * math.tan(math.radians(30))),
(R + 0.2, h - (R + 0.2 - dk / 2) * math.tan(math.radians(30))), (dk / 2, h), (0, h)]
pr = pr.common(revolve(prof))
_ = e
if hole_d > 0:
pr = pr.cut(cyl(hole_d, h + 2, (0, 0, -1)))
return place(pr, at, axis)
def place(shape, at=(0, 0, 0), axis="z"):
"""Перенос тела, построенного вдоль +Z от начала координат: ось → axis, начало → at."""
s = shape.copy()
ax = _AX[axis] if isinstance(axis, str) else axis
z = V(0, 0, 1)
if (ax - z).Length > 1e-9:
if (ax + z).Length < 1e-9:
s.rotate(V(0, 0, 0), V(1, 0, 0), 180)
else:
rot_ax = z.cross(ax)
s.rotate(V(0, 0, 0), rot_ax, math.degrees(z.getAngle(ax)))
s.translate(V(*at))
return s
def helix_spring(d, D, n_work, L0, n_end=1.0, ground=0.75, pts_per_turn=24, right_hand=True):
"""Пружина сжатия: пруток d, средний диаметр D, рабочих витков n_work, опорных по n_end с каждой
стороны (поджаты), длина в свободном состоянии L0; торцы зашлифованы на `ground` окружности.
Ось — Z, нижний торец Z = 0."""
n_tot = n_work + 2.0 * n_end
t_end = d # шаг поджатых витков
# ось прутка начинается на z = d/2 (нешлифованная) — шлифовкой снимается (1-ground_frac) высоты
z_start = d / 2.0 * (1.0 - 0.0)
h_free = L0 - d # высота между осями крайних сечений (до шлифовки условно)
h_ends = 2.0 * n_end * t_end
t_work = (h_free - h_ends) / n_work
pts = []
N = int(round(n_tot * pts_per_turn))
for i in range(N + 1):
tau = i / float(pts_per_turn) # число витков от начала
if tau <= n_end:
z = tau * t_end
elif tau <= n_end + n_work:
z = n_end * t_end + (tau - n_end) * t_work
else:
z = n_end * t_end + n_work * t_work + (tau - n_end - n_work) * t_end
ang = 2.0 * math.pi * tau * (1.0 if right_hand else -1.0)
pts.append(V(D / 2.0 * math.cos(ang), D / 2.0 * math.sin(ang), z_start + z))
path = Part.BSplineCurve()
path.interpolate(pts)
wire = Part.Wire([path.toShape()])
p0, p1 = pts[0], pts[1]
tang = (p1 - p0)
tang.normalize()
circ = Part.Wire([Part.makeCircle(d / 2.0, p0, tang)])
sweep = wire.makePipeShell([circ], True, True)
solid = _as_solid(sweep)
# шлифовка торцов: обрезка по плоскостям Z = 0 и Z = L0
slab = Part.makeCylinder(D + d, L0, V(0, 0, 0), V(0, 0, 1))
_ = ground
return _as_solid(solid.common(slab))
# --------------------------------------------------------------------------------------------
# Виды и проекции
# --------------------------------------------------------------------------------------------
def view_matrix(right, up):
"""Матрица перехода «модель → вид»: x' = right, y' = up, z' = right × up (на наблюдателя)."""
r, u = V(*right), V(*up)
r.normalize()
u.normalize()
w = r.cross(u)
m = Matrix()
m.A11, m.A12, m.A13 = r.x, r.y, r.z
m.A21, m.A22, m.A23 = u.x, u.y, u.z
m.A31, m.A32, m.A33 = w.x, w.y, w.z
return m
VIEWS = {
# имя: (right, up) — наблюдатель смотрит против оси z' = right × up
# ГОСТ 2.305: наблюдатель — на стороне оси z' = right × up
"front": ((1, 0, 0), (0, 0, 1)), # главный вид: наблюдатель на −Y; X вправо, Z вверх
"back": ((-1, 0, 0), (0, 0, 1)), # наблюдатель на +Y
"left": ((0, -1, 0), (0, 0, 1)), # вид слева: наблюдатель на −X (изображение — справа от главного)
"right": ((0, 1, 0), (0, 0, 1)), # вид справа: наблюдатель на +X
"top": ((1, 0, 0), (0, 1, 0)), # вид сверху: наблюдатель на +Z; X вправо, +Y вверх
"bottom": ((1, 0, 0), (0, -1, 0)), # вид снизу: наблюдатель на −Z
}
def to_view(shape, view="front", origin=(0, 0, 0)):
"""Копия тела в системе координат вида (x' вправо, y' вверх, z' к наблюдателю).
origin — точка модели, совмещаемая с началом координат вида."""
m = view_matrix(*VIEWS[view]) if isinstance(view, str) else view_matrix(*view)
s = shape.copy()
if origin != (0, 0, 0):
s.translate(V(-origin[0], -origin[1], -origin[2]))
s.transformShape(m)
return s
def hlr(shape_in_view, smooth=False, hidden=False):
"""Проекция с удалением невидимых линий. Тело уже в координатах вида. Возвращает dict списков рёбер."""
import TechDraw
res = TechDraw.projectEx(shape_in_view, V(0, 0, 1))
out = {"visible": [], "smooth": [], "hidden": []}
for idx in (0, 2, 3): # V (резкие), VN (сшивки), VO (очерковые)
out["visible"] += list(res[idx].Edges) if not res[idx].isNull() else []
if smooth and not res[1].isNull():
out["smooth"] += list(res[1].Edges)
if hidden:
for idx in (5, 7, 8):
out["hidden"] += list(res[idx].Edges) if not res[idx].isNull() else []
return out
def half_behind(shape_in_view, z_cut=0.0):
"""Часть тела за секущей плоскостью z' = z_cut (наблюдатель со стороны +z')."""
bb = shape_in_view.BoundBox
if bb.ZMin >= z_cut - 1e-6:
return None
if bb.ZMax <= z_cut + 1e-6:
return shape_in_view
cutter = Part.makeBox(2 * BIG, 2 * BIG, BIG, V(-BIG, -BIG, z_cut))
r = shape_in_view.cut(cutter)
return r if (not r.isNull() and r.Edges) else None
def section_loops(shape_in_view, z_cut=0.0, defl=0.01):
"""Контуры сечения тела плоскостью z' = z_cut: список замкнутых ломаных [(x, y), …]."""
bb = shape_in_view.BoundBox
if bb.ZMin > z_cut - 1e-6 or bb.ZMax < z_cut + 1e-6:
return []
loops = []
try:
wires = shape_in_view.slice(V(0, 0, 1), z_cut)
except Exception:
wires = []
for w in wires:
pts = wire_points(w, defl)
if len(pts) >= 3:
loops.append(pts)
return loops
def wire_points(wire, defl=0.01):
pts = []
for e in wire.OrderedEdges:
ep = edge_points(e, defl)
if pts and _d2(pts[-1], ep[0]) > _d2(pts[-1], ep[-1]):
ep = ep[::-1]
if pts and _d2(pts[-1], ep[0]) < 1e-12:
ep = ep[1:]
pts += ep
if len(pts) > 1 and _d2(pts[0], pts[-1]) < 1e-12:
pts = pts[:-1]
return pts
def _d2(a, b):
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
def edge_points(edge, defl=0.01):
"""Дискретизация ребра в ломаную [(x, y), …] (z отбрасывается)."""
try:
tid = edge.Curve.TypeId
except Exception:
tid = ""
if tid == "Part::GeomLine":
vs = edge.Vertexes
return [(vs[0].X, vs[0].Y), (vs[-1].X, vs[-1].Y)]
pts = edge.discretize(Deflection=defl)
if len(pts) < 2:
vs = edge.Vertexes
return [(v.X, v.Y) for v in vs]
return [(p.x, p.y) for p in pts]
def edge_prim(edge, defl=0.01):
"""Ребро проекции → примитив чертежа: ('line', p, q) | ('circle', c, r) | ('poly', pts)."""
try:
tid = edge.Curve.TypeId
except Exception:
tid = ""
if tid == "Part::GeomLine":
vs = edge.Vertexes
return ("line", (vs[0].X, vs[0].Y), (vs[-1].X, vs[-1].Y))
if tid == "Part::GeomCircle" and edge.isClosed() and abs(abs(edge.Curve.Axis.z) - 1.0) < 1e-9:
c = edge.Curve.Center
return ("circle", (c.x, c.y), edge.Curve.Radius)
return ("poly", edge_points(edge, defl))
# --------------------------------------------------------------------------------------------
# Масса и инерция
# --------------------------------------------------------------------------------------------
def mass_props(shape, density_kg_m3):
"""Масса (кг), центр масс (мм), объём (мм3)."""
vol = shape.Volume
com = shape.CenterOfMass if hasattr(shape, "CenterOfMass") else shape.Solids[0].CenterOfMass
return {"mass": vol * 1e-9 * density_kg_m3, "volume": vol, "com": (com.x, com.y, com.z)}

Powered by TurnKey Linux.