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.

1057 lines
53 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 -*-
"""2D-чертёжный движок проекта (оформление по ЕСКД).
Что реализовано и по каким стандартам:
* форматы листов — ГОСТ 2.301-68; рамка и основная надпись (формы 1, 2, 2а) — ГОСТ 2.104-2006;
* типы линий — ГОСТ 2.303-68 (сплошная толстая основная s, тонкая s/3…s/2, штрихпунктирная, штриховая,
разомкнутая);
* шрифт — osifont (ISO 3098, начертание типа Б с наклоном; соответствует ГОСТ 2.304-81), размер h — высота
прописных букв в мм;
* штриховка сечений — ГОСТ 2.306-68; размеры — ГОСТ 2.307-2011; позиции — ГОСТ 2.109-73.
Все координаты листа — в миллиметрах, начало — левый нижний угол листа.
Вывод: PDF / PNG / SVG (matplotlib) и DXF (ezdxf).
"""
import math
import os
import numpy as np
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FONT_DIR = os.path.join(ROOT, "tools", "freecad", "squashfs-root", "usr", "share", "Mod", "TechDraw",
"Resources", "fonts")
FONT_FILES = {"italic": "osifont-italic.ttf", "upright": "osifont-lgpl3fe.ttf"}
CAP_RATIO = 1511.0 / 2048.0 # высота прописной буквы / кегль (измерено по шрифту)
MM2PT = 72.0 / 25.4
FORMATS = {"A0": (841.0, 1189.0), "A1": (594.0, 841.0), "A2": (420.0, 594.0), "A3": (297.0, 420.0),
"A4": (210.0, 297.0)}
_fp_cache = {}
_tw_cache = {}
def _fp(font):
from matplotlib.font_manager import FontProperties
if font not in _fp_cache:
_fp_cache[font] = FontProperties(fname=os.path.join(FONT_DIR, FONT_FILES[font]))
return _fp_cache[font]
def text_width(s, h, font="italic"):
"""Ширина строки (мм) при высоте прописных h (мм)."""
for a, b in Sheet.GLYPH_FIX.items():
s = s.replace(a, b)
key = (s, font)
if key not in _tw_cache:
from matplotlib.textpath import TextPath
if not s.strip():
_tw_cache[key] = 0.35 * len(s)
else:
ext = TextPath((0, 0), s, size=1000, prop=_fp(font)).get_extents()
_tw_cache[key] = (ext.x1 - min(ext.x0, 0.0)) / 1000.0
return _tw_cache[key] * h / CAP_RATIO
def fmt_num(v, nd=2):
"""Число для размерной надписи: десятичная запятая, без незначащих нулей."""
s = ("%.*f" % (nd, v)).rstrip("0").rstrip(".")
if s in ("-0", ""):
s = "0"
return s.replace(".", ",")
def hatch_segments(loops, angle=45.0, step=3.0, phase=0.0):
"""Отрезки штриховки области, заданной контурами (правило чёт-нечет). Всё в одних координатах."""
a = math.radians(angle)
ca, sa = math.cos(a), math.sin(a)
rows = []
for loop in loops:
P = np.asarray(loop, dtype=float)
if len(P) < 3:
continue
R = np.column_stack((P[:, 0] * ca + P[:, 1] * sa, -P[:, 0] * sa + P[:, 1] * ca))
rows.append(np.hstack((R, np.roll(R, -1, axis=0))))
if not rows:
return []
E = np.vstack(rows)
y1, y2 = E[:, 1], E[:, 3]
ymin, ymax = min(y1.min(), y2.min()), max(y1.max(), y2.max())
out = []
k0, k1 = int(math.ceil((ymin - phase) / step)), int(math.floor((ymax - phase) / step))
for k in range(k0, k1 + 1):
y = phase + k * step + 1.3e-6
m = ((y1 <= y) & (y2 > y)) | ((y2 <= y) & (y1 > y))
if not m.any():
continue
e = E[m]
xs = np.sort(e[:, 0] + (y - e[:, 1]) * (e[:, 2] - e[:, 0]) / (e[:, 3] - e[:, 1]))
for i in range(0, len(xs) - 1, 2):
if xs[i + 1] - xs[i] > 1e-4:
xa, xb = xs[i], xs[i + 1]
out.append(((xa * ca - y * sa, xa * sa + y * ca), (xb * ca - y * sa, xb * sa + y * ca)))
return out
class Sheet(object):
def __init__(self, fmt="A3", landscape=True, s=0.7, h=3.5, mult=1):
w, hh = FORMATS[fmt]
if mult > 1: # дополнительные форматы (кратность по короткой стороне)
w = w * mult
self.fmt = fmt if mult == 1 else "%sx%d" % (fmt, mult)
self.W, self.H = (max(w, hh), min(w, hh)) if landscape else (min(w, hh), max(w, hh))
self.s = s
self.h = h # основной размер шрифта размерных чисел
self.arrow = 4.0 if h < 5 else 5.0
self.items = []
# стиль: (толщина мм, штрихи мм | None)
self.styles = {
"main": (s, None),
"thin": (round(s / 2.8, 2), None),
"center": (round(s / 2.8, 2), (14.0, 2.0, 1.5, 2.0)),
"center_s": (round(s / 2.8, 2), (6.0, 1.5, 1.0, 1.5)),
"hidden": (round(s / 2.0, 2), (4.0, 1.5)),
"hatch": (round(s / 3.5, 2), None),
"cut": (1.5 * s, None),
"phantom": (round(s / 2.8, 2), (14.0, 2.0, 1.5, 2.0, 1.5, 2.0)),
"frame": (s, None),
}
self.frame_box = (20.0, 5.0, self.W - 5.0, self.H - 5.0)
# ------------------------------------------------------------------ примитивы
def line(self, p, q, style="main"):
self.items.append(("poly", [tuple(p), tuple(q)], style, False))
def poly(self, pts, style="main", closed=False):
if len(pts) >= 2:
self.items.append(("poly", [tuple(p) for p in pts], style, closed))
def circle(self, c, r, style="main"):
self.items.append(("circle", tuple(c), float(r), style))
def arc(self, c, r, a0, a1, style="main"):
"""Дуга от угла a0 до a1 (градусы, против часовой стрелки)."""
if a1 < a0:
a1 += 360.0
n = max(6, int(abs(a1 - a0) / 3.0) + 1)
pts = [(c[0] + r * math.cos(math.radians(a0 + (a1 - a0) * i / n)),
c[1] + r * math.sin(math.radians(a0 + (a1 - a0) * i / n))) for i in range(n + 1)]
self.poly(pts, style)
def fill(self, loops, color="k"):
"""Заливка области (правило чёт-нечет): loops — список контуров."""
loops = [[tuple(p) for p in lp] for lp in loops if len(lp) >= 3]
if loops:
self.items.append(("fill", loops, color))
# символы, которых нет в osifont, — замена допустимым написанием
GLYPH_FIX = {"\u0451": "\u0435", "\u0401": "\u0415", "\u2026": "...", "\u2009": " ", "\u00a0": " ", "\u2032": "'", "\u2033": '"', "\u2217": "*", "\u2212": "-"}
def text(self, p, s, h=None, angle=0.0, ha="left", va="baseline", font="italic", mask=False):
"""mask=True — под надписью прерываются линии штриховки и контура (ГОСТ 2.306 п. 9, ГОСТ 2.307)."""
if s is None or s == "":
return
s = str(s)
for a, b in self.GLYPH_FIX.items():
s = s.replace(a, b)
hh = float(h or self.h)
if mask:
w = text_width(s, hh, font)
x0 = {"left": 0.0, "center": -w / 2.0, "right": -w}[ha] - 0.6
y0 = {"baseline": -0.12 * hh, "center": -0.65 * hh, "top": -1.3 * hh, "bottom": 0.0}.get(va, -0.12 * hh)
x1, y1 = x0 + w + 1.2, y0 + 1.25 * hh + 0.5
a = math.radians(angle)
ca, sa = math.cos(a), math.sin(a)
corners = [(p[0] + x * ca - y * sa, p[1] + x * sa + y * ca) for x, y in ((x0, y0), (x1, y0), (x1, y1), (x0, y1))]
self.items.append(("mask", corners))
self.items.append(("text", tuple(p), s, hh, float(angle), ha, va, font))
def rect(self, x0, y0, x1, y1, style="main"):
self.poly([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], style, closed=True)
def arrowhead(self, tip, direction_deg, length=None, half_deg=10.0):
"""Стрелка: остриё в tip, направление острия — direction_deg."""
L = length or self.arrow
a = math.radians(direction_deg)
bx, by = tip[0] - L * math.cos(a), tip[1] - L * math.sin(a)
w = L * math.tan(math.radians(half_deg))
nx, ny = -math.sin(a), math.cos(a)
self.fill([[tip, (bx + nx * w, by + ny * w), (bx - nx * w, by - ny * w)]])
def dot(self, p, d=1.2):
n = 16
self.fill([[(p[0] + d / 2 * math.cos(2 * math.pi * i / n), p[1] + d / 2 * math.sin(2 * math.pi * i / n))
for i in range(n)]])
def hatch(self, loops, angle=45.0, step=3.0, phase=0.0, style="hatch"):
for a, b in hatch_segments(loops, angle, step, phase):
self.items.append(("poly", [a, b], style, False))
def text_block(self, x, y_top, lines, h=None, step=None, width=None, font="italic", numbered=False):
"""Многострочный текст (технические требования). Возвращает y нижней границы."""
h = h or self.h
step = step or h * 2.0
y = y_top - h
for i, ln in enumerate(lines):
prefix = ("%d " % (i + 1)) if numbered else ""
indent = text_width("00 ", h, font) if numbered else 0.0
words = ln.split(" ")
cur = ""
first = True
rows = []
for wd in words:
trial = (cur + " " + wd).strip()
if width and text_width(trial, h, font) > width - indent and cur:
rows.append(cur)
cur = wd
else:
cur = trial
rows.append(cur)
for r in rows:
if first and numbered:
self.text((x, y), prefix.strip(), h, font=font)
self.text((x + indent, y), r, h, font=font)
first = False
y -= step
return y + step - h * 0.4
# ------------------------------------------------------------------ размеры (координаты листа)
def _dim_text(self, value, text, pre, suf):
if text is None:
text = fmt_num(value)
return "%s%s%s" % (pre, text, suf)
@staticmethod
def _tol_parts(tol):
"""tol: None | str (симметричное, «±0,15», пишется в строку) | (верхнее, нижнее) — пишутся мелким шрифтом
в две строки (ГОСТ 2.307 п. 4: отклонение, равное нулю, не указывают)."""
if tol is None or isinstance(tol, str):
return None
up, lo = tol
return (up if up not in (None, "", "0") else None, lo if lo not in (None, "", "0") else None)
def tol_width(self, tol, h):
tp = self._tol_parts(tol)
if tp is None:
return 0.0
hs = max(2.5, h - 1.0)
return 0.6 + max(text_width(tp[0] or "", hs), text_width(tp[1] or "", hs))
def dim_label(self, p, s, h=None, angle=0.0, ha="center", tol=None):
"""Размерное число с отклонениями. p — точка привязки (база строки), ha — выравнивание всей надписи."""
h = h or self.h
if isinstance(tol, str) and tol:
s = s + tol
tw = text_width(s, h)
tt = self.tol_width(tol, h)
full = tw + tt
a = math.radians(angle)
ux, uy, vx, vy = math.cos(a), math.sin(a), -math.sin(a), math.cos(a)
off = {"left": 0.0, "center": -full / 2.0, "right": -full}[ha]
x0, y0 = p[0] + ux * off, p[1] + uy * off
self.text((x0, y0), s, h, angle=angle, ha="left")
tp = self._tol_parts(tol)
if tp:
hs = max(2.5, h - 1.0)
xt, yt = x0 + ux * (tw + 0.6), y0 + uy * (tw + 0.6)
up, lo = tp
if up and lo:
self.text((xt + vx * (hs + 0.9), yt + vy * (hs + 0.9)), up, hs, angle=angle)
self.text((xt, yt), lo, hs, angle=angle)
elif up:
self.text((xt + vx * (h - hs + 0.2), yt + vy * (h - hs + 0.2)), up, hs, angle=angle)
elif lo:
self.text((xt, yt), lo, hs, angle=angle)
return full
def dim_h(self, p1, p2, y, text=None, pre="", suf="", h=None, tpos="auto", value=None, ext=2.0, gap=0.8,
tol=None):
"""Горизонтальный размер между точками p1, p2 (лист); y — положение размерной линии.
tol — предельные отклонения (см. _tol_parts)."""
if tol is not None:
return self._dim_tol("h", p1, p2, y, text, pre, suf, h, tpos, value, ext, gap, tol)
h = h or self.h
(x1, ya), (x2, yb) = p1, p2
if x2 < x1:
x1, x2, ya, yb = x2, x1, yb, ya
for xx, yy in ((x1, ya), (x2, yb)):
if abs(y - yy) > 1e-6:
sg = 1.0 if y > yy else -1.0
self.line((xx, yy + sg * gap), (xx, y + sg * ext), "thin")
s = self._dim_text(value if value is not None else (x2 - x1), text, pre, suf)
tw = text_width(s, h)
L, A = x2 - x1, self.arrow
inside = L >= 2 * A + 1.5
if inside:
self.line((x1, y), (x2, y), "thin")
self.arrowhead((x1, y), 180.0)
self.arrowhead((x2, y), 0.0)
else:
self.line((x1 - A - 2.5, y), (x2 + A + 2.5, y), "thin")
self.arrowhead((x1, y), 0.0)
self.arrowhead((x2, y), 180.0)
if tpos == "auto":
tpos = "c" if (inside and tw <= L - 2 * A + 3.0) or (not inside and tw <= L - 0.6) else "r"
if tpos == "c":
self.text(((x1 + x2) / 2.0, y + 1.0), s, h, ha="center")
elif tpos == "r":
x0 = x2 + (0.0 if inside else A + 2.5) + 1.2
if inside:
self.line((x2, y), (x0 + tw + 0.8, y), "thin")
else:
self.line((x2 + A + 2.5, y), (x0 + tw + 0.8, y), "thin")
self.text((x0, y + 1.0), s, h, ha="left")
elif tpos == "l":
x0 = x1 - (0.0 if inside else A + 2.5) - 1.2
self.line((x0 - tw - 0.8, y), (x1 - (0.0 if inside else A + 2.5), y), "thin")
self.text((x0, y + 1.0), s, h, ha="right")
else: # число — смещение центра текста от середины
self.text(((x1 + x2) / 2.0 + float(tpos), y + 1.0), s, h, ha="center")
def _dim_tol(self, kind, p1, p2, at, text, pre, suf, h, tpos, value, ext, gap, tol):
"""Размер с предельными отклонениями: линии строит dim_h/dim_v (с пустым текстом), надпись — dim_label."""
h = h or self.h
if kind == "h":
(x1, ya), (x2, yb) = p1, p2
L = abs(x2 - x1)
else:
(xa, x1), (xb, x2) = p1, p2
L = abs(x2 - x1)
v = value if value is not None else L
s = self._dim_text(v, text, pre, suf)
full = text_width(s + (tol if isinstance(tol, str) else ""), h) + self.tol_width(tol, h)
A = self.arrow
inside = L >= 2 * A + 1.5
if tpos == "auto":
tpos = "c" if (inside and full <= L - 2 * A + 3.0) or (not inside and full <= L - 0.6) else "r"
blank = " " * 0
if kind == "h":
self.dim_h(p1, p2, at, text=blank, h=h, tpos="c", value=value, ext=ext, gap=gap)
xl, xr = min(x1, x2), max(x1, x2)
if tpos == "c":
self.dim_label(((xl + xr) / 2.0, at + 1.0), s, h, 0.0, "center", tol)
elif tpos in ("r", "l"):
ofs = 0.0 if inside else A + 2.5
if tpos == "r":
x0 = xr + ofs + 1.2
self.line((xr + ofs, at), (x0 + full + 0.8, at), "thin")
self.dim_label((x0, at + 1.0), s, h, 0.0, "left", tol)
else:
x0 = xl - ofs - 1.2
self.line((x0 - full - 0.8, at), (xl - ofs, at), "thin")
self.dim_label((x0, at + 1.0), s, h, 0.0, "right", tol)
else:
self.dim_label(((xl + xr) / 2.0 + float(tpos), at + 1.0), s, h, 0.0, "center", tol)
else:
self.dim_v(p1, p2, at, text=blank, h=h, tpos="c", value=value, ext=ext, gap=gap)
yl, yr = min(x1, x2), max(x1, x2)
if tpos == "c":
self.dim_label((at - 1.0, (yl + yr) / 2.0), s, h, 90.0, "center", tol)
elif tpos in ("r", "l"):
ofs = 0.0 if inside else A + 2.5
if tpos == "r":
y0 = yr + ofs + 1.2
self.line((at, yr + ofs), (at, y0 + full + 0.8), "thin")
self.dim_label((at - 1.0, y0), s, h, 90.0, "left", tol)
else:
y0 = yl - ofs - 1.2
self.line((at, y0 - full - 0.8), (at, yl - ofs), "thin")
self.dim_label((at - 1.0, y0), s, h, 90.0, "right", tol)
else:
self.dim_label((at - 1.0, (yl + yr) / 2.0 + float(tpos)), s, h, 90.0, "center", tol)
def dim_v(self, p1, p2, x, text=None, pre="", suf="", h=None, tpos="auto", value=None, ext=2.0, gap=0.8,
tol=None):
"""Вертикальный размер между точками p1, p2 (лист); x — положение размерной линии."""
if tol is not None:
return self._dim_tol("v", p1, p2, x, text, pre, suf, h, tpos, value, ext, gap, tol)
h = h or self.h
(xa, y1), (xb, y2) = p1, p2
if y2 < y1:
y1, y2, xa, xb = y2, y1, xb, xa
for xx, yy in ((xa, y1), (xb, y2)):
if abs(x - xx) > 1e-6:
sg = 1.0 if x > xx else -1.0
self.line((xx + sg * gap, yy), (x + sg * ext, yy), "thin")
s = self._dim_text(value if value is not None else (y2 - y1), text, pre, suf)
tw = text_width(s, h)
L, A = y2 - y1, self.arrow
inside = L >= 2 * A + 1.5
if inside:
self.line((x, y1), (x, y2), "thin")
self.arrowhead((x, y1), 270.0)
self.arrowhead((x, y2), 90.0)
else:
self.line((x, y1 - A - 2.5), (x, y2 + A + 2.5), "thin")
self.arrowhead((x, y1), 90.0)
self.arrowhead((x, y2), 270.0)
if tpos == "auto":
tpos = "c" if (inside and tw <= L - 2 * A + 3.0) or (not inside and tw <= L - 0.6) else "r"
if tpos == "c":
self.text((x - 1.0, (y1 + y2) / 2.0), s, h, angle=90.0, ha="center")
elif tpos == "r": # выше размера
y0 = y2 + (0.0 if inside else A + 2.5) + 1.2
self.line((x, y2 + (0.0 if inside else A + 2.5)), (x, y0 + tw + 0.8), "thin")
self.text((x - 1.0, y0), s, h, angle=90.0, ha="left")
elif tpos == "l": # ниже размера
y0 = y1 - (0.0 if inside else A + 2.5) - 1.2
self.line((x, y0 - tw - 0.8), (x, y1 - (0.0 if inside else A + 2.5)), "thin")
self.text((x - 1.0, y0), s, h, angle=90.0, ha="right")
else:
self.text((x - 1.0, (y1 + y2) / 2.0 + float(tpos)), s, h, angle=90.0, ha="center")
def dim_h_half(self, x_axis, p_end, y, text, h=None, over=4.0, ext=2.0, gap=0.8):
"""Диаметр на изображении «половина вида — половина разреза» (ГОСТ 2.307 п. 2.?: размерную линию
проводят с обрывом дальше оси, стрелка — одна). p_end — точка контура (лист), y — размерная линия."""
h = h or self.h
xe, ye = p_end
sg = 1.0 if xe > x_axis else -1.0
if abs(y - ye) > 1e-6:
s2 = 1.0 if y > ye else -1.0
self.line((xe, ye + s2 * gap), (xe, y + s2 * ext), "thin")
x0 = x_axis - sg * over
self.line((x0, y), (xe, y), "thin")
self.arrowhead((xe, y), 0.0 if sg > 0 else 180.0)
self.text(((x0 + xe) / 2.0 + sg * 1.0, y + 1.0), text, h, ha="center")
def leader(self, target, knee, text, h=None, side=None, end="dot", under=None):
"""Линия-выноска: от target (точка или стрелка) к knee, далее полка с текстом над ней.
side: +1 — полка вправо, −1 — влево (по умолчанию — в сторону от target)."""
h = h or self.h
if side is None:
side = 1 if knee[0] >= target[0] else -1
if end == "dot":
self.dot(target)
elif end == "arrow":
self.arrowhead(target, math.degrees(math.atan2(target[1] - knee[1], target[0] - knee[0])))
self.line(target, knee, "thin")
tw = max(text_width(text, h), text_width(under, h) if under else 0.0)
x_end = knee[0] + side * (tw + 2.0)
self.line(knee, (x_end, knee[1]), "thin")
xt = knee[0] + side * 1.0
self.text((xt, knee[1] + 1.0), text, h, ha="left" if side > 0 else "right")
if under:
self.text((xt, knee[1] - h - 1.2), under, h, ha="left" if side > 0 else "right")
return x_end
def pos(self, target, knee, n, h=None, side=None):
"""Номер позиции на полке линии-выноски (шрифт на 1–2 размера больше размерных чисел)."""
return self.leader(target, knee, str(n), h=h or (5.0 if self.h <= 3.5 else 7.0), side=side)
def dim_radius(self, c, r, ang_deg, text=None, h=None, inside=True, L=12.0, pre="R"):
a = math.radians(ang_deg)
tip = (c[0] + r * math.cos(a), c[1] + r * math.sin(a))
s = "%s%s" % (pre, text if text is not None else fmt_num(r))
if inside:
tail = (c[0] + (r - L) * math.cos(a), c[1] + (r - L) * math.sin(a))
self.arrowhead(tip, ang_deg)
else:
tail = (c[0] + (r + L) * math.cos(a), c[1] + (r + L) * math.sin(a))
self.arrowhead(tip, ang_deg + 180.0)
self.line(tip, tail, "thin")
side = 1 if math.cos(a) * (1 if not inside else -1) >= 0 else -1
tw = text_width(s, h or self.h)
self.line(tail, (tail[0] + side * (tw + 2.0), tail[1]), "thin")
self.text((tail[0] + side * 1.0, tail[1] + 1.0), s, h, ha="left" if side > 0 else "right")
def dim_angle(self, c, r, a0, a1, text=None, h=None):
"""Угловой размер: дуга радиуса r между направлениями a0 и a1 (градусы)."""
if a1 < a0:
a0, a1 = a1, a0
self.arc(c, r, a0, a1, "thin")
p0 = (c[0] + r * math.cos(math.radians(a0)), c[1] + r * math.sin(math.radians(a0)))
p1 = (c[0] + r * math.cos(math.radians(a1)), c[1] + r * math.sin(math.radians(a1)))
self.arrowhead(p0, a0 - 90.0)
self.arrowhead(p1, a1 + 90.0)
am = math.radians((a0 + a1) / 2.0)
s = text if text is not None else fmt_num(a1 - a0) + "°"
self.text((c[0] + (r + 1.5) * math.cos(am), c[1] + (r + 1.5) * math.sin(am)), s, h, ha="center")
def cut_mark(self, p1, p2, letter, view_dir_deg, h=None, stroke=10.0):
"""Обозначение секущей плоскости: разомкнутая линия (штрихи у концов p1, p2), стрелки взгляда, буквы."""
h = h or (5.0 if self.h <= 3.5 else 7.0)
dx, dy = p2[0] - p1[0], p2[1] - p1[1]
L = math.hypot(dx, dy)
ux, uy = dx / L, dy / L
a = math.radians(view_dir_deg)
vx, vy = math.cos(a), math.sin(a)
for p, sg in ((p1, 1.0), (p2, -1.0)):
q = (p[0] + sg * ux * stroke, p[1] + sg * uy * stroke)
self.line(p, q, "cut")
base = (p[0] + sg * ux * 2.5, p[1] + sg * uy * 2.5)
tail = (base[0] - vx * 12.0, base[1] - vy * 12.0)
self.line(tail, base, "thin")
self.arrowhead(base, view_dir_deg, length=self.arrow + 1.0, half_deg=12.0)
self.text((tail[0] - sg * ux * (h * 0.9), tail[1] - sg * uy * (h * 0.9) - h / 2.0), letter, h,
ha="center")
def view_label(self, p, text, h=None):
"""Надпись над изображением: «А–А», «Б (2:1)», «Вид В»."""
self.text(p, text, h or (5.0 if self.h <= 3.5 else 7.0), ha="center")
def view_arrow(self, tip, direction_deg, letter, h=None, L=14.0, letter_side=1):
"""Стрелка направления взгляда для дополнительного вида (ГОСТ 2.305 п. 4.2) с буквой."""
h = h or (5.0 if self.h <= 3.5 else 7.0)
a = math.radians(direction_deg)
tail = (tip[0] - L * math.cos(a), tip[1] - L * math.sin(a))
self.line(tail, tip, "thin")
self.arrowhead(tip, direction_deg, length=self.arrow + 2.0, half_deg=12.0)
nx, ny = -math.sin(a) * letter_side, math.cos(a) * letter_side
mid = ((tail[0] + tip[0]) / 2.0 + nx * (h * 0.6 + 1.5), (tail[1] + tip[1]) / 2.0 + ny * (h * 0.6 + 1.5) - h / 2.0)
self.text(mid, letter, h, ha="center")
def element_mark(self, c, r, letter, ang_deg=45.0, h=None, shelf=None):
"""Обозначение выносного элемента (ГОСТ 2.305 п. 7.2): тонкая окружность, выноска с полкой и буквой."""
h = h or (5.0 if self.h <= 3.5 else 7.0)
self.circle(c, r, "thin")
a = math.radians(ang_deg)
p = (c[0] + r * math.cos(a), c[1] + r * math.sin(a))
L = shelf if shelf is not None else 10.0
knee = (p[0] + L * math.cos(a), p[1] + L * math.sin(a))
self.line(p, knee, "thin")
side = 1 if math.cos(a) >= 0 else -1
tw = text_width(letter, h)
self.line(knee, (knee[0] + side * (tw + 2.0), knee[1]), "thin")
self.text((knee[0] + side * 1.0, knee[1] + 1.0), letter, h, ha="left" if side > 0 else "right")
def wavy(self, pts, amp=0.8, wl=6.0, style="thin"):
"""Сплошная волнистая линия (ГОСТ 2.303) вдоль ломаной pts."""
out = []
for (x0, y0), (x1, y1) in zip(pts[:-1], pts[1:]):
L = math.hypot(x1 - x0, y1 - y0)
if L < 1e-9:
continue
ux, uy = (x1 - x0) / L, (y1 - y0) / L
n = max(2, int(L / 0.5))
for i in range(n + 1):
t = L * i / n
w = amp * math.sin(2 * math.pi * t / wl)
out.append((x0 + ux * t - uy * w, y0 + uy * t + ux * w))
self.poly(out, style)
def rough(self, tip, value=None, rot=0.0, kind="remove", h=None, shelf=True):
"""Знак шероховатости по ГОСТ 2.309-73 (ред. 2003): вершина в tip; rot — поворот знака (град);
kind: 'remove' — со снятием слоя, 'none' — без снятия слоя, 'any' — способ не устанавливается.
value — строка параметра («Ra 1,6»), пишется над полкой знака."""
h = h or self.h
a = math.radians(rot)
ca, sa = math.cos(a), math.sin(a)
def T(x, y):
return (tip[0] + x * ca - y * sa, tip[1] + x * sa + y * ca)
t60 = math.tan(math.radians(60.0))
H1, H2 = 1.4 * h, 3.0 * h
pL = (-H1 / t60, H1)
pR = (H2 / t60, H2)
self.poly([T(*pL), T(0, 0), T(*pR)], "thin")
if kind == "remove":
self.line(T(*pL), T(H1 / t60, H1), "thin")
elif kind == "none":
rr = H1 / (1.0 + 1.0 / math.sin(math.radians(30.0))) * 1.0
cy = H1 - rr
c = T(0.0, cy + 0.15 * rr)
self.circle(c, rr * 0.95, "thin")
if value:
tw = text_width(value, h)
if shelf:
self.line(T(*pR), T(pR[0] + tw + 1.5, pR[1]), "thin")
self.text(T(pR[0] + 0.8, pR[1] + 0.8), value, h, angle=rot, ha="left")
else:
self.text(T(pL[0] - 0.5, 0.6 * h), value, h, angle=rot, ha="right")
return pR[0] + (text_width(value, h) + 1.5 if value else 0.0)
def tol_frame(self, p, kind, value, base=None, h=None):
"""Рамка допуска формы/расположения (ГОСТ 2.308): p — левый нижний угол; kind: 'coax' (соосность),
'perp', 'par', 'runout'. Возвращает (x_right, y_mid, x_left)."""
h = h or self.h
H = 2.0 * h
x, y = p
w1 = H
w2 = text_width(value, h) + 3.0
w3 = (text_width(base, h) + 3.0) if base else 0.0
self.rect(x, y, x + w1 + w2 + w3, y + H, "thin")
self.line((x + w1, y), (x + w1, y + H), "thin")
if base:
self.line((x + w1 + w2, y), (x + w1 + w2, y + H), "thin")
c = (x + w1 / 2.0, y + H / 2.0)
if kind == "coax":
self.circle(c, 0.42 * h, "thin")
self.circle(c, 0.85 * h, "thin")
elif kind == "perp":
self.line((c[0] - 0.8 * h, c[1] - 0.7 * h), (c[0] + 0.8 * h, c[1] - 0.7 * h), "thin")
self.line((c[0], c[1] - 0.7 * h), (c[0], c[1] + 0.8 * h), "thin")
elif kind == "runout":
self.line((c[0] - 0.6 * h, c[1] - 0.8 * h), (c[0] + 0.6 * h, c[1] + 0.8 * h), "thin")
self.arrowhead((c[0] + 0.6 * h, c[1] + 0.8 * h), 53.0, length=1.5)
self.text((x + w1 + w2 / 2.0, y + (H - h) / 2.0), value, h, ha="center")
if base:
self.text((x + w1 + w2 + w3 / 2.0, y + (H - h) / 2.0), base, h, ha="center", font="upright")
return x + w1 + w2 + w3, y + H / 2.0, x
def datum(self, p, direction_deg, letter, L=8.0, h=None):
"""Обозначение базы (ГОСТ 2.308): зачернённый треугольник с основанием в точке p (на размерной линии
или контуре), соединительная линия длиной L в направлении direction_deg и рамка с буквой."""
h = h or self.h
a = math.radians(direction_deg)
ux, uy = math.cos(a), math.sin(a)
nx, ny = -uy, ux
b = 1.6 * h / 2.0
hgt = 1.6 * h * math.sqrt(3) / 2.0
tri = [(p[0] + nx * b, p[1] + ny * b), (p[0] - nx * b, p[1] - ny * b), (p[0] + ux * hgt, p[1] + uy * hgt)]
self.fill([tri])
q = (p[0] + ux * (hgt + L), p[1] + uy * (hgt + L))
self.line((p[0] + ux * hgt, p[1] + uy * hgt), q, "thin")
S = 2.0 * h
cx, cy = q[0] + ux * S / 2.0, q[1] + uy * S / 2.0
self.rect(cx - S / 2.0, cy - S / 2.0, cx + S / 2.0, cy + S / 2.0, "thin")
self.text((cx, cy - h / 2.0), letter, h, ha="center", font="upright")
def rough_leader(self, target, knee, value, kind="remove", h=None, side=1):
"""Знак шероховатости на полке линии-выноски со стрелкой (ГОСТ 2.309 черт. 4) — для поверхностей,
на которых знак нельзя поставить читаемо."""
h = h or self.h
self.line(target, knee, "thin")
self.arrowhead(target, math.degrees(math.atan2(target[1] - knee[1], target[0] - knee[0])))
t60 = math.tan(math.radians(60.0))
w = 1.4 * h / t60 + 2.0
tip = (knee[0] + side * w, knee[1])
self.line(knee, (tip[0] + side * 0.0, knee[1]), "thin")
self.rough(tip, value, 0.0, kind, h)
def rough_general(self, value=None, kind="remove", h=None, paren=True):
"""Обозначение шероховатости, одинаковой для части поверхностей, в правом верхнем углу (ГОСТ 2.309 п. 2.5):
«Ra 12,5 (√)». Возвращает левую границу надписи."""
h = h or 5.0
x1, y1 = self.frame_box[2], self.frame_box[3]
xr = x1 - 6.0
yb = y1 - 6.0 - 3.0 * h
w_paren = 0.0
if paren:
# «( √ )» — знак без параметра в скобках
wp = text_width("(", h)
self.text((xr - wp, yb + 0.3 * h), ")", h, font="upright")
t60 = math.tan(math.radians(60.0))
sw = 3.0 * h / t60 + 1.4 * h / t60
tipx = xr - wp - 0.8 - 3.0 * h / t60
self.rough((tipx, yb), None, 0.0, "any", h)
self.text((tipx - 1.4 * h / t60 - 0.8 - wp, yb + 0.3 * h), "(", h, font="upright")
w_paren = wp * 2 + sw + 2.5
t60 = math.tan(math.radians(60.0))
tw = text_width(value or "", h)
tipx = xr - w_paren - tw - 1.5 - 3.0 * h / t60
self.rough((tipx, yb), value, 0.0, kind, h)
return tipx - 1.4 * h / t60
def table(self, x, y_top, widths, rows, h=3.5, row_h=8.0, header_rows=0, aligns=None, frame="main",
wrap=True, pad=1.5, line_step=None):
"""Таблица: widths — ширины столбцов, rows — списки строк (ячейка — str; длинный текст переносится).
Возвращает y нижней границы."""
aligns = aligns or ["left"] * len(widths)
line_step = line_step or h * 1.75
xs = [x]
for w in widths:
xs.append(xs[-1] + w)
y = y_top
ybreaks = [y]
for ri, row in enumerate(rows):
cells = []
nl = 1
for ci, c in enumerate(row):
lines = []
for part in str(c).split("\n"):
if wrap:
cur = ""
for wd in part.split(" "):
tr = (cur + " " + wd).strip()
if cur and text_width(tr, h) > widths[ci] - 2 * pad:
lines.append(cur)
cur = wd
else:
cur = tr
lines.append(cur)
else:
lines.append(part)
cells.append(lines)
nl = max(nl, len(lines))
rh = max(row_h, nl * line_step + (row_h - h) * 0.9)
for ci, lines in enumerate(cells):
n = len(lines)
yy = y - rh / 2.0 + (n - 1) * line_step / 2.0 - h / 2.0
for ln in lines:
al = aligns[ci]
xx = xs[ci] + pad if al == "left" else (xs[ci + 1] - pad if al == "right" else
(xs[ci] + xs[ci + 1]) / 2.0)
self.text((xx, yy), ln, h, ha=al)
yy -= line_step
y -= rh
ybreaks.append(y)
for i, yy in enumerate(ybreaks):
st = frame if (i == 0 or i == len(ybreaks) - 1 or i == header_rows) else "thin"
self.line((x, yy), (xs[-1], yy), st)
for xx in xs:
self.line((xx, y_top), (xx, y), frame)
return y
# ------------------------------------------------------------------ рамка и основная надпись
def frame(self, extra=True):
x0, y0, x1, y1 = self.frame_box
self.rect(0.0, 0.0, self.W, self.H, "thin")
self.rect(x0, y0, x1, y1, "frame")
if extra: # дополнительные графы ГОСТ 2.104 (поле подшивки)
xs = (x0 - 12.0, x0 - 7.0, x0)
labels = ["Инв. № подл.", "Подп. и дата", "Взам. инв. №", "Инв. № дубл.", "Подп. и дата"]
heights = [25.0, 35.0, 25.0, 25.0, 35.0]
yy = y0
self.line((xs[0], y0), (xs[0], y0 + sum(heights)), "main")
self.line((xs[1], y0), (xs[1], y0 + sum(heights)), "main")
self.line((xs[0], y0), (x0, y0), "main")
for lab, hh in zip(labels, heights):
self.line((xs[0], yy + hh), (x0, yy + hh), "main")
self.text((xs[0] + 3.6, yy + hh / 2.0), lab, 2.5, angle=90.0, ha="center")
yy += hh
def title_block(self, f, form=1):
"""Основная надпись ГОСТ 2.104-2006. form: 1 — чертежи, 2 — текстовые документы (первый лист),
'2a' — последующие листы. f — словарь граф."""
x0, y0, x1, y1 = self.frame_box
X, Y = x1 - 185.0, y0
T = self.text
if form == "2a":
Hb = 15.0
self.rect(X, Y, x1, Y + Hb, "main")
for xx in (7, 17, 40, 55, 65, 175):
self.line((X + xx, Y), (X + xx, Y + Hb), "main")
self.line((X, Y + 5), (X + 65, Y + 5), "main")
self.line((X, Y + 10), (X + 65, Y + 10), "thin")
self.line((X + 175, Y + 8), (x1, Y + 8), "main")
for xx, lab in ((3.5, "Изм."), (12, "Лист"), (28.5, "№ докум."), (47.5, "Подп."), (60, "Дата")):
T((X + xx, Y + 1.3), lab, 2.5, ha="center")
T((X + 120, Y + 5.0), f.get("code", ""), 5.0, ha="center")
T((X + 180, Y + 9.6), "Лист", 2.5, ha="center")
T((X + 180, Y + 2.0), str(f.get("sheet", "")), 3.5, ha="center")
return Hb
Hb = 55.0 if form == 1 else 40.0
self.rect(X, Y, x1, Y + Hb, "main")
nrow = int(Hb / 5)
hdr = 6 if form == 1 else 5 # число строк подписей (Разраб. … Утв.)
for xx in (17, 40, 55, 65):
self.line((X + xx, Y), (X + xx, Y + Hb), "main")
self.line((X + 7, Y + hdr * 5), (X + 7, Y + Hb), "main")
for i in range(1, nrow):
st = "main" if i in (hdr, hdr + 1) else "thin"
self.line((X, Y + 5 * i), (X + 65, Y + 5 * i), st)
for xx, lab in ((3.5, "Изм."), (12, "Лист"), (28.5, "№ докум."), (47.5, "Подп."), (60, "Дата")):
T((X + xx, Y + hdr * 5 + 1.3), lab, 2.5, ha="center")
roles = (["Разраб.", "Пров.", "Т.контр.", "", "Н.контр.", "Утв."] if form == 1 else
["Разраб.", "Пров.", "", "Н.контр.", "Утв."])
names = f.get("names", {})
for i, role in enumerate(roles):
yy = Y + (hdr - 1 - i) * 5 + 1.3
T((X + 1.0, yy), role, 2.5)
T((X + 18.0, yy), names.get(role, ""), 2.5)
self.line((X + 65, Y + Hb - 15), (x1, Y + Hb - 15), "main")
T((X + 125, Y + Hb - 10.0), f.get("code", ""), 7.0, ha="center")
self.line((X + 135, Y), (X + 135, Y + Hb - 15), "main")
self.line((X + 65, Y + 15), (x1, Y + 15), "main") if form == 1 else None
# наименование
title = f.get("title", [])
if isinstance(title, str):
title = [title]
ty0 = Y + 15 if form == 1 else Y
th = (Hb - 15) - (15 if form == 1 else 0)
hs = f.get("title_h", 5.0)
stp = hs * 1.7
ycur = ty0 + th / 2.0 + (len(title) - 1) * stp / 2.0 - hs / 2.0
for ln in title:
T((X + 100, ycur), ln, hs, ha="center")
ycur -= stp
if form == 1:
mat = f.get("material", [])
if isinstance(mat, str):
mat = [mat]
ym = Y + 7.5 + (len(mat) - 1) * 3.0 - 1.75
for ln in mat:
T((X + 100, ym), ln, f.get("material_h", 3.5), ha="center")
ym -= 6.0
# Лит., Масса, Масштаб
self.line((X + 135, Y + 35), (x1, Y + 35), "main")
self.line((X + 135, Y + 20), (x1, Y + 20), "main")
self.line((X + 150, Y + 20), (X + 150, Y + 40), "main")
self.line((X + 167, Y + 20), (X + 167, Y + 40), "main")
self.line((X + 140, Y + 20), (X + 140, Y + 35), "thin")
self.line((X + 145, Y + 20), (X + 145, Y + 35), "thin")
self.line((X + 155, Y + 15), (X + 155, Y + 20), "main")
T((X + 142.5, Y + 36.3), "Лит.", 2.5, ha="center")
T((X + 158.5, Y + 36.3), "Масса", 2.5, ha="center")
T((X + 176, Y + 36.3), "Масштаб", 2.5, ha="center")
T((X + 137.5, Y + 25.5), f.get("lit", ""), 3.5, ha="center")
T((X + 158.5, Y + 25.5), f.get("mass", ""), 3.5, ha="center")
T((X + 176, Y + 25.5), f.get("scale", ""), 5.0, ha="center")
T((X + 136.0, Y + 16.3), "Лист %s" % f.get("sheet", ""), 2.5)
T((X + 156.0, Y + 16.3), "Листов %s" % f.get("sheets", ""), 2.5)
org = f.get("org", [])
else:
self.line((X + 135, Y + 20), (x1, Y + 20), "main")
self.line((X + 135, Y + 15), (x1, Y + 15), "main")
self.line((X + 150, Y + 15), (X + 150, Y + 25), "main")
self.line((X + 165, Y + 15), (X + 165, Y + 25), "main")
self.line((X + 140, Y + 15), (X + 140, Y + 20), "thin")
self.line((X + 145, Y + 15), (X + 145, Y + 20), "thin")
T((X + 142.5, Y + 21.3), "Лит.", 2.5, ha="center")
T((X + 157.5, Y + 21.3), "Лист", 2.5, ha="center")
T((X + 175, Y + 21.3), "Листов", 2.5, ha="center")
T((X + 137.5, Y + 16.2), f.get("lit", ""), 2.5, ha="center")
T((X + 157.5, Y + 16.2), str(f.get("sheet", "")), 2.5, ha="center")
T((X + 175, Y + 16.2), str(f.get("sheets", "")), 2.5, ha="center")
org = f.get("org", [])
if isinstance(org, str):
org = [org]
yo = Y + 7.5 + (len(org) - 1) * 2.5 - 1.5
for ln in org:
T((X + 160, yo), ln, 3.5, ha="center")
yo -= 5.5
# графа 26 — обозначение, повёрнутое на 180° (левый верхний угол)
if form == 1 and f.get("code"):
self.rect(x0, y1 - 14.0, x0 + 70.0, y1, "main")
T((x0 + 35.0, y1 - 7.0 + 2.5), f["code"], 5.0, angle=180.0, ha="center")
return Hb
# ------------------------------------------------------------------ вывод
def _render(self, path, dpi=200):
import matplotlib.pyplot as plt
fig = self.figure()
meta = {"Creator": "valve-project", "CreationDate": None, "ModDate": None} if path.endswith(".pdf") else None
if path.endswith(".png"):
fig.savefig(path, dpi=dpi, facecolor="white")
elif path.endswith(".svg"):
fig.savefig(path, metadata={"Date": None})
else:
fig.savefig(path, metadata=meta)
plt.close(fig)
def figure(self):
"""Фигура matplotlib с листом (для save и для сводного многостраничного PDF)."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.patches import PathPatch
from matplotlib.path import Path
matplotlib.rcParams["pdf.fonttype"] = 42
matplotlib.rcParams["svg.fonttype"] = "path"
matplotlib.rcParams["lines.scale_dashes"] = False
matplotlib.rcParams["svg.hashsalt"] = "valve"
fig = plt.figure(figsize=(self.W / 25.4, self.H / 25.4))
ax = fig.add_axes([0, 0, 1, 1])
ax.set_xlim(0, self.W)
ax.set_ylim(0, self.H)
ax.set_aspect("equal")
ax.axis("off")
groups = {}
for it in self.items:
if it[0] == "poly":
pts = list(it[1]) + ([it[1][0]] if it[3] else [])
groups.setdefault(it[2], []).append(np.asarray(pts, dtype=float))
elif it[0] == "circle":
(cx, cy), r = it[1], it[2]
n = int(max(32, min(720, 2 * math.pi * r / 0.25)))
t = np.linspace(0, 2 * math.pi, n + 1)
groups.setdefault(it[3], []).append(np.column_stack((cx + r * np.cos(t), cy + r * np.sin(t))))
for st, segs in groups.items():
lw, dash = self.styles[st]
ls = "solid" if dash is None else (0, tuple(d * MM2PT for d in dash))
ax.add_collection(LineCollection(segs, linewidths=lw * MM2PT, colors="k", linestyles=ls,
capstyle="round", joinstyle="round"))
for it in self.items:
if it[0] == "mask":
lp = it[1]
ax.add_patch(PathPatch(Path(list(lp) + [lp[0]], [Path.MOVETO] + [Path.LINETO] * (len(lp) - 1) +
[Path.CLOSEPOLY]), facecolor="white", edgecolor="none", lw=0, zorder=2.5))
elif it[0] == "fill":
verts, codes = [], []
for lp in it[1]:
verts += list(lp) + [lp[0]]
codes += [Path.MOVETO] + [Path.LINETO] * (len(lp) - 1) + [Path.CLOSEPOLY]
ax.add_patch(PathPatch(Path(verts, codes), facecolor=it[2], edgecolor="none", lw=0))
elif it[0] == "text":
_, p, s, h, ang, ha, va, font = it
if font == "italic" and any(c in s for c in self.BROKEN_ITALIC) and va == "baseline":
self._text_patched(ax, p, s, h, ang, ha)
continue
ax.text(p[0], p[1], s, fontproperties=_fp(font), fontsize=h / CAP_RATIO * MM2PT, rotation=ang,
ha=ha, va=va, rotation_mode="anchor", color="k")
return fig
# в osifont-italic глиф «Э» испорчен (залитый контур): такие символы рисуются контуром прямого начертания
# с наклоном 15° (тип Б с наклоном 75° по ГОСТ 2.304)
BROKEN_ITALIC = "Э"
def _text_patched(self, ax, p, s, h, ang, ha):
from matplotlib.patches import PathPatch
from matplotlib.textpath import TextPath
from matplotlib.transforms import Affine2D
pieces, cur = [], ""
for ch in s:
if ch in self.BROKEN_ITALIC:
if cur:
pieces.append(("t", cur))
cur = ""
pieces.append(("g", ch))
else:
cur += ch
if cur:
pieces.append(("t", cur))
from matplotlib.textpath import TextToPath
t2p = TextToPath()
size = h / CAP_RATIO
def adv(t, f): # ширина по продвижениям глифов (с пробелами)
pr = _fp(f).copy()
pr.set_size(size)
return t2p.get_text_width_height_descent(t, pr, ismath=False)[0]
widths = [adv(t, "italic") if k == "t" else adv(t, "upright") for k, t in pieces]
total = sum(widths)
off = {"left": 0.0, "center": -total / 2.0, "right": -total}[ha]
a = math.radians(ang)
ux, uy = math.cos(a), math.sin(a)
x = off
for (k, t), w in zip(pieces, widths):
px, py = p[0] + ux * x, p[1] + uy * x
if not t.strip():
x += w
continue
if k == "t":
tp = TextPath((0, 0), t, size=size, prop=_fp("italic"))
tr = Affine2D().rotate_deg(ang).translate(px, py)
else:
tp = TextPath((0, 0), t, size=size, prop=_fp("upright"))
tr = Affine2D().skew_deg(15.0, 0.0).rotate_deg(ang).translate(px, py)
ax.add_patch(PathPatch(tr.transform_path(tp), facecolor="k", edgecolor="none", lw=0))
x += w
def save(self, path_noext, formats=("pdf", "png", "dxf"), dpi=150):
os.makedirs(os.path.dirname(path_noext) or ".", exist_ok=True)
for f in formats:
if f == "dxf":
self.save_dxf(path_noext + ".dxf")
else:
self._render(path_noext + "." + f, dpi=dpi)
def save_dxf(self, path):
import ezdxf
from ezdxf.enums import TextEntityAlignment as TA
doc = ezdxf.new("R2010", setup=True)
doc.units = ezdxf.units.MM
doc.header["$INSUNITS"] = 4
for nm in ("ESKD", "ESKD_UPRIGHT"):
if nm not in doc.styles:
doc.styles.add(nm, font=FONT_FILES["italic" if nm == "ESKD" else "upright"])
lw_ok = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, 60, 70, 80, 90, 100, 106, 120, 140]
lt = {"center": "CENTER", "center_s": "CENTER2", "hidden": "DASHED", "phantom": "PHANTOM"}
for st, (lw, dash) in self.styles.items():
w = min(lw_ok, key=lambda v: abs(v - lw * 100))
doc.layers.add(st.upper(), lineweight=w, linetype=lt.get(st, "CONTINUOUS"), color=7)
doc.layers.add("TEXT", color=7)
doc.layers.add("FILL", color=7)
msp = doc.modelspace()
amap = {("left", "baseline"): TA.LEFT, ("center", "baseline"): TA.CENTER, ("right", "baseline"): TA.RIGHT,
("left", "center"): TA.MIDDLE_LEFT, ("center", "center"): TA.MIDDLE_CENTER,
("right", "center"): TA.MIDDLE_RIGHT, ("left", "top"): TA.TOP_LEFT,
("center", "top"): TA.TOP_CENTER, ("right", "top"): TA.TOP_RIGHT,
("left", "bottom"): TA.BOTTOM_LEFT, ("center", "bottom"): TA.BOTTOM_CENTER,
("right", "bottom"): TA.BOTTOM_RIGHT}
for it in self.items:
if it[0] == "poly":
pts, st, closed = it[1], it[2], it[3]
if len(pts) == 2 and not closed:
msp.add_line(pts[0], pts[1], dxfattribs={"layer": st.upper()})
else:
msp.add_lwpolyline(pts, close=closed, dxfattribs={"layer": st.upper()})
elif it[0] == "circle":
msp.add_circle(it[1], it[2], dxfattribs={"layer": it[3].upper()})
elif it[0] == "fill":
hat = msp.add_hatch(color=7, dxfattribs={"layer": "FILL"})
for lp in it[1]:
hat.paths.add_polyline_path(lp, is_closed=True)
elif it[0] == "text":
_, p, s, h, ang, ha, va, font = it
e = msp.add_text(s, height=h, rotation=ang,
dxfattribs={"layer": "TEXT", "style": "ESKD" if font == "italic" else "ESKD_UPRIGHT",
"oblique": 0})
e.set_placement(p, align=amap.get((ha, va), TA.LEFT))
doc.saveas(path)
class View(object):
"""Изображение на листе: перевод координат модели вида (мм) в координаты листа с масштабом."""
def __init__(self, sheet, ox, oy, scale=1.0):
self.sh, self.ox, self.oy, self.k = sheet, float(ox), float(oy), float(scale)
def P(self, x, y=None):
if y is None:
x, y = x
return (self.ox + self.k * x, self.oy + self.k * y)
def prims(self, prims, style="main"):
for pr in prims:
if pr[0] == "line":
self.sh.line(self.P(pr[1]), self.P(pr[2]), style)
elif pr[0] == "circle":
self.sh.circle(self.P(pr[1]), pr[2] * self.k, style)
elif pr[0] == "poly":
self.sh.poly([self.P(p) for p in pr[1]], style)
def line(self, p, q, style="main"):
self.sh.line(self.P(p), self.P(q), style)
def poly(self, pts, style="main", closed=False):
self.sh.poly([self.P(p) for p in pts], style, closed)
def circle(self, c, r, style="main"):
self.sh.circle(self.P(c), r * self.k, style)
def axis(self, p, q, ext=4.0, style="center"):
"""Осевая линия с выступом ext (мм листа) за заданные точки."""
a, b = self.P(p), self.P(q)
L = math.hypot(b[0] - a[0], b[1] - a[1])
ux, uy = (b[0] - a[0]) / L, (b[1] - a[1]) / L
self.sh.line((a[0] - ux * ext, a[1] - uy * ext), (b[0] + ux * ext, b[1] + uy * ext), style)
def cross(self, c, r, ext=3.0, style="center_s"):
"""Центровые линии окружности радиуса r."""
self.axis((c[0] - r, c[1]), (c[0] + r, c[1]), ext, style)
self.axis((c[0], c[1] - r), (c[0], c[1] + r), ext, style)
def hatch(self, loops, angle=45.0, step=3.0, phase=0.0):
self.sh.hatch([[self.P(p) for p in lp] for lp in loops], angle, step, phase)
def fill(self, loops, color="k"):
self.sh.fill([[self.P(p) for p in lp] for lp in loops], color)
def dim_h(self, p1, p2, y, **kw):
"""Горизонтальный размер; p1, p2 и y — в координатах модели вида."""
kw.setdefault("value", abs(p2[0] - p1[0]))
self.sh.dim_h(self.P(p1), self.P(p2), self.oy + self.k * y, **kw)
def dim_v(self, p1, p2, x, **kw):
kw.setdefault("value", abs(p2[1] - p1[1]))
self.sh.dim_v(self.P(p1), self.P(p2), self.ox + self.k * x, **kw)
def dim_d(self, d, y_at, y_line, x0=0.0, **kw):
"""Диаметр d (симметрично оси x0) — линейным размером между образующими на уровне y_at."""
kw.setdefault("pre", "⌀")
self.dim_h((x0 - d / 2.0, y_at), (x0 + d / 2.0, y_at), y_line, **kw)
def dim_dv(self, d, x_at, x_line, y0=0.0, **kw):
"""Диаметр d (симметрично оси y0) — вертикальным размером на уровне x_at."""
kw.setdefault("pre", "⌀")
self.dim_v((x_at, y0 - d / 2.0), (x_at, y0 + d / 2.0), x_line, **kw)
def leader(self, target, knee, text, **kw):
return self.sh.leader(self.P(target), self.P(knee), text, **kw)
def pos(self, target, knee, n, **kw):
return self.sh.pos(self.P(target), self.P(knee), n, **kw)
def text(self, p, s, **kw):
self.sh.text(self.P(p), s, **kw)

Powered by TurnKey Linux.