# -*- coding: utf-8 -*- """Изображения из 3D-модели: разрезы, виды, выносные элементы (ГОСТ 2.305), штриховка (ГОСТ 2.306), условности сборочного чертежа (ГОСТ 2.109, 2.305 п. 9: нерассекаемые детали; отверстия на фланце, не попадающие в секущую плоскость, показаны в разрезе), резьбовые соединения (ГОСТ 2.311: резьба стержня закрывает резьбу отверстия).""" import math from shapely.geometry import Polygon, LineString, Point from shapely.ops import unary_union from drawings.dw_env import fu, V, Part, P, bm from drawings.sheet import hatch_segments # Направления взгляда (x' — вправо, y' — вверх, наблюдатель на +z' = x' × y'); первый угол (ГОСТ 2.305). VIEWS = { "front": ((1, 0, 0), (0, 0, 1)), # главный: наблюдатель на −Y "top": ((1, 0, 0), (0, 1, 0)), # вид сверху (наблюдатель на +Z), под главным "bottom": ((1, 0, 0), (0, -1, 0)), # вид снизу (наблюдатель на −Z), над главным "left": ((0, -1, 0), (0, 0, 1)), # вид слева (наблюдатель на −X), справа от главного "right": ((0, 1, 0), (0, 0, 1)), # вид справа (наблюдатель на +X), слева от главного } def tv(shape, view): return fu.to_view(shape, VIEWS[view] if isinstance(view, str) else view) # ================================================================================================ # Сцена: видимые рёбра + контуры сечений по деталям # ================================================================================================ class Scene(object): def __init__(self): self.edges = [] # примитивы ('line'|'circle'|'poly', …) в координатах вида self.hidden = [] self.sec = {} # ключ → список замкнутых контуров self.sec_only = set() # ключи, у которых контур сечения рисуется отдельно (нет в HLR) self.polys = {} # ключ → shapely-область сечения def region(self, key): if key not in self.polys: self.polys[key] = loops_to_region(self.sec.get(key, [])) return self.polys[key] def loops_to_region(loops): """Чёт-нечет → shapely MultiPolygon (для точек позиций и проверок).""" geo = None for lp in loops: if len(lp) < 3: continue pg = Polygon(lp).buffer(0) geo = pg if geo is None else geo.symmetric_difference(pg) return geo def build_scene(items, view, section=True, z_cut=0.0, hidden=False): """items: [(key, shape | [shapes], mode)], mode: 'cut' — рассекается (виден за плоскостью, сечение штрихуется); 'whole' — не рассекается (ГОСТ 2.305 п. 9.?: винты, шпильки, шток, вал…); 'sec' — только сечение (пружина по ГОСТ 2.401: допускается изображать только сечения витков).""" sc = Scene() visible_solids = [] for key, shapes, mode in items: if shapes is None: continue if not isinstance(shapes, (list, tuple)): shapes = [shapes] for s in shapes: v = tv(s, view) if not section: visible_solids.append(v) continue if mode == "whole": visible_solids.append(v) elif mode in ("cut", "sec"): loops = fu.section_loops(v, z_cut) if loops: sc.sec.setdefault(key, []).extend(loops) if mode == "sec": sc.sec_only.add(key) else: h = fu.half_behind(v, z_cut) if h is not None: visible_solids.append(h) if visible_solids: r = fu.hlr(Part.makeCompound(visible_solids), hidden=hidden) sc.edges = [fu.edge_prim(e, 0.02) for e in r["visible"]] sc.hidden = [fu.edge_prim(e, 0.02) for e in r["hidden"]] return sc # ================================================================================================ # Условности сборочного чертежа (копии деталей только для изображения; модель не меняется) # ================================================================================================ def stud_angles(): n = P.BODY["studs_n"] return [180.0 / n + 360.0 / n * i for i in range(n)] # как в cad/build_model.py (не на главных осях) def _nearest_rot(angles, target): best = None for a in angles: d = (target - a + 180.0) % 360.0 - 180.0 if best is None or abs(d) < abs(best[1]): best = (a, d) return best def plane_targets(plane): return (0.0, 180.0) if plane == "xz" else (90.0, 270.0) def conv_fasteners(studs, nuts, plane): """Две шпильки (с гайками), повёрнутые в секущую плоскость (ГОСТ 2.305: отверстия на круглом фланце, не попадающие в секущую плоскость, допускается показывать в разрезе).""" angs = stud_angles() out_s, out_n = [], [] for T in plane_targets(plane): a, d = _nearest_rot(angs, T) i = angs.index(a) for src, dst in ((studs, out_s), (nuts, out_n)): c = src[i].copy() c.rotate(V(0, 0, 0), V(0, 0, 1), d) dst.append(c) return out_s, out_n def conv_bonnet(bonnet, plane): """Крышка — тело вращения с 12 отверстиями: поворот на угол, при котором отверстия попадают в плоскость.""" a, d = _nearest_rot(stud_angles(), plane_targets(plane)[0]) c = bonnet.copy() c.rotate(V(0, 0, 0), V(0, 0, 1), d) return c def conv_body(body, plane, studs_conv): """Корпус: отверстия входного/выходного фланцев и резьбовые отверстия шпилек в секущей плоскости. Инструменты повторяют cad/build_model.body() (размеры — из valve/params.py).""" FI, FO, B = P.FL_IN, P.FL_OUT, P.BODY L, L1 = P.TZ["L"], P.TZ["L1"] zfl = FI["raise_h"] + FI["tf"] zt = B["z_top"] cuts = [] for T in plane_targets(plane): x, y = FI["BC"] / 2 * math.cos(math.radians(T)), FI["BC"] / 2 * math.sin(math.radians(T)) cuts.append(fu.cyl(FI["hole"], zfl + 2, (x, y, -1))) r_st = bm.d1_metric(B["studs_d"], B["studs_pitch"]) / 2 xs, ys = B["studs_pcd"] / 2 * math.cos(math.radians(T)), B["studs_pcd"] / 2 * math.sin(math.radians(T)) cuts.append(fu.cyl(2 * r_st, B["stud_hole_depth"] + 1, (xs, ys, zt - B["stud_hole_depth"]))) cuts.append(fu.cone(2 * r_st, 0.0, r_st * 0.58, (xs, ys, zt - B["stud_hole_depth"]), "-z")) if plane == "xz": xb = L1 - FO["h"] - FO["b"] for sg in (1, -1): cuts.append(fu.cyl(FO["d"], FO["b"] + 4, (xb - 2, 0, L + sg * FO["D1"] / 2), "x")) b = fu.cut_all(body, cuts) return b def thread_cut(housing, rods): """ГОСТ 2.311: в соединении резьба стержня закрывает резьбу отверстия — из корпуса вычитается стержень (в модели наружная резьба — по d, внутренняя — по d1).""" s = housing for r in rods if isinstance(rods, (list, tuple)) else [rods]: if s.BoundBox.intersect(r.BoundBox): s = s.cut(r) return s # ================================================================================================ # Отсечение окружностью (выносные элементы) # ================================================================================================ def clip_seg_circle(p, q, c, r): dx, dy = q[0] - p[0], q[1] - p[1] fx, fy = p[0] - c[0], p[1] - c[1] a = dx * dx + dy * dy if a < 1e-18: return None b = 2 * (fx * dx + fy * dy) cc = fx * fx + fy * fy - r * r disc = b * b - 4 * a * cc if disc <= 0: return None sq = math.sqrt(disc) t0, t1 = (-b - sq) / (2 * a), (-b + sq) / (2 * a) t0, t1 = max(t0, 0.0), min(t1, 1.0) if t1 - t0 < 1e-9: return None return ((p[0] + dx * t0, p[1] + dy * t0), (p[0] + dx * t1, p[1] + dy * t1)) def prim_polyline(pr): if pr[0] == "line": return [pr[1], pr[2]] if pr[0] == "circle": (cx, cy), r = pr[1], pr[2] n = 120 return [(cx + r * math.cos(2 * math.pi * i / n), cy + r * math.sin(2 * math.pi * i / n)) for i in range(n + 1)] return list(pr[1]) def clip_polyline_circle(pts, c, r): out = [] cur = [] for p, q in zip(pts[:-1], pts[1:]): s = clip_seg_circle(p, q, c, r) if s is None: if cur: out.append(cur) cur = [] continue if cur and math.hypot(cur[-1][0] - s[0][0], cur[-1][1] - s[0][1]) < 1e-7: cur.append(s[1]) else: if cur: out.append(cur) cur = [s[0], s[1]] if cur: out.append(cur) return out def clip_polyline_rect(pts, box): """Отсечение ломаной прямоугольником box = (x0, y0, x1, y1) — через shapely.""" x0, y0, x1, y1 = box ls = LineString(pts) rect = Polygon([(x0, y0), (x1, y0), (x1, y1), (x0, y1)]) g = ls.intersection(rect) res = [] if g.is_empty: return res geoms = getattr(g, "geoms", [g]) for gg in geoms: if gg.geom_type == "LineString" and len(gg.coords) >= 2: res.append(list(gg.coords)) return res # ================================================================================================ # Вывод сцены на лист # ================================================================================================ def draw_scene(Vw, sc, styles, clip=None, edge_style="main", skip_keys=(), draw_hidden=False): """Vw — drawings.sheet.View; styles: ключ → dict(angle, step, phase, fill, cross); clip — ('circle', c, r) или ('rect', box) в координатах вида.""" sh = Vw.sh def emit(pts, st): if clip is None: Vw.poly(pts, st) return segs = clip_polyline_circle(pts, clip[1], clip[2]) if clip[0] == "circle" else clip_polyline_rect(pts, clip[1]) for s in segs: Vw.poly(s, st) for pr in sc.edges: if pr[0] == "circle" and clip is None: Vw.circle(pr[1], pr[2], edge_style) else: emit(prim_polyline(pr), edge_style) if draw_hidden: for pr in sc.hidden: emit(prim_polyline(pr), "hidden") for key, loops in sc.sec.items(): if key in skip_keys: continue st = styles.get(key, dict(angle=45.0, step=3.0)) if key in sc.sec_only: for lp in loops: emit(list(lp) + [lp[0]], edge_style) paper_loops = [[Vw.P(p) for p in lp] for lp in loops] if st.get("fill"): if clip is None: sh.fill(paper_loops) else: reg = loops_to_region(loops) cg = (Point(clip[1]).buffer(clip[2], 128) if clip[0] == "circle" else Polygon([(clip[1][0], clip[1][1]), (clip[1][2], clip[1][1]), (clip[1][2], clip[1][3]), (clip[1][0], clip[1][3])])) g = reg.intersection(cg) if reg is not None else None if g is not None and not g.is_empty: for pg in getattr(g, "geoms", [g]): if pg.geom_type == "Polygon": sh.fill([[Vw.P(p) for p in pg.exterior.coords]] + [[Vw.P(p) for p in it.coords] for it in pg.interiors]) continue angs = [st.get("angle", 45.0)] + ([st["angle"] + 90.0] if st.get("cross") else []) for ang in angs: for a, b in hatch_segments(paper_loops, ang, st.get("step", 3.0), st.get("phase", 0.0)): if clip is None: sh.line(a, b, "hatch") else: ia = ((a[0] - Vw.ox) / Vw.k, (a[1] - Vw.oy) / Vw.k) ib = ((b[0] - Vw.ox) / Vw.k, (b[1] - Vw.oy) / Vw.k) for s in (clip_polyline_circle([ia, ib], clip[1], clip[2]) if clip[0] == "circle" else clip_polyline_rect([ia, ib], clip[1])): Vw.poly(s, "hatch") def interior_point(region, prefer=None, side=None): """Точка внутри области сечения (для выноски позиции). prefer — желаемая точка (берётся ближайшая внутренняя), side — +1/−1: правая/левая половина.""" if region is None or region.is_empty: return None g = region if side is not None: bb = region.bounds half = Polygon([(0 if side > 0 else bb[0] - 1, bb[1] - 1), (bb[2] + 1 if side > 0 else 0, bb[1] - 1), (bb[2] + 1 if side > 0 else 0, bb[3] + 1), (0 if side > 0 else bb[0] - 1, bb[3] + 1)]) gg = region.intersection(half) if not gg.is_empty: g = gg parts = sorted(getattr(g, "geoms", [g]), key=lambda x: -x.area) big = parts[0] if prefer is not None: pt = Point(prefer) best = None for pg in parts: inner = pg.buffer(-0.35 * min(2.0, math.sqrt(pg.area) / 4.0)) tgt = inner if not inner.is_empty else pg from shapely.ops import nearest_points q = nearest_points(tgt, pt)[0] d = q.distance(pt) if best is None or d < best[0]: best = (d, (q.x, q.y)) return best[1] p = big.representative_point() return (p.x, p.y) # ================================================================================================ # Номера позиций (ГОСТ 2.109 п. 3.? : полки — параллельно основной надписи, в колонку/строку) # ================================================================================================ def place_positions(sh, items, x_shelf, side, y_min, y_max, step=8.0, h=None): """items: [(номер, точка_на_листе)]; полки — в колонку на x_shelf (side = −1: полка влево от колена). Порядок полок совпадает с порядком точек по высоте — выноски не пересекаются.""" h = h or (5.0 if sh.h <= 3.5 else 7.0) its = sorted(items, key=lambda t: -t[1][1]) n = len(its) ys = [min(y_max, max(y_min, it[1][1])) for it in its] # раздвижка сверху вниз, затем снизу вверх for i in range(1, n): ys[i] = min(ys[i], ys[i - 1] - step) if ys and ys[-1] < y_min: ys[-1] = y_min for i in range(n - 2, -1, -1): ys[i] = max(ys[i], ys[i + 1] + step) for (num, tgt), y in zip(its, ys): sh.pos(tgt, (x_shelf, y), num, side=side) return ys