Files

325 lines
12 KiB
Python

#!/usr/bin/env python3
# coding=utf-8
"""
Genere le schema explicatif des parametres de l'extension.
python docs/schema_parametres.py # les deux versions
python docs/schema_parametres.py fr # docs/parametres.svg + .png (README)
python docs/schema_parametres.py en # docs/parameters_en.svg
# + images/parameters_en.png (onglet
# « Help » de la boite de dialogue)
Les formes sont calculees par skull_fill_core (memes fonctions que l'extension),
le schema reste donc fidele au resultat reel. L'export PNG passe par
inkscape.com, qui attend la fin de l'export (contrairement au raccourci
Chocolatey « inkscape »).
"""
import math
import os
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, ROOT)
import skull_fill_core # noqa: E402,F401
W, H = 1400, 1280 # 4 panneaux de 700 x 640
INK = "#343a40" # element principal
GHOST = "#dde1e5" # elements secondaires / voisins
DIM = "#d9480f" # cotes
DIM2 = "#1971c2" # cotes secondaires
EDGE = "#212529" # contour des formes
FONT = "font-family:Arial,Helvetica,sans-serif"
INKSCAPE = [r"C:\Program Files\Inkscape\bin\inkscape.com", "/usr/bin/inkscape",
"/Applications/Inkscape.app/Contents/MacOS/inkscape"]
# Version par langue : textes, fichiers produits, largeur du PNG et agrandissement
# des textes (la version anglaise est affichee reduite dans la boite de dialogue :
# 900 px de large, textes x 1.25 pour rester lisibles).
VERSIONS = {
"fr": {
"svg": os.path.join(HERE, "parametres.svg"),
"png": os.path.join(HERE, "parametres.png"),
"png_width": 1400,
"font_scale": 1.0,
"text": {
"title1": "Hauteur des crânes",
"note1": ["Tailles tirées entre la plus petite et la plus grande :",
"beaucoup de petits crânes, quelques grands par-dessus."],
"title2": "Espacement",
"note2": ["Pas de la grille, en % de la plus petite hauteur.",
"Sous 100 %, les crânes se chevauchent sans laisser de vide."],
"title3": "Inclinaison et miroir",
"tilt": "max",
"mirror": "miroir",
"note3": ["Angle tiré entre -max et +max ; un crâne sur deux,",
"au hasard, est retourné en miroir."],
"title4": "Résultat",
"note4": ["Seule l'encre visible est écrite : rien de caché",
"ni de masqué, prêt pour la gravure laser."],
},
},
"en": {
"svg": os.path.join(HERE, "parameters_en.svg"),
"png": os.path.join(ROOT, "images", "parameters_en.png"),
"png_width": 900,
"font_scale": 1.25,
"text": {
"title1": "Skull height",
"note1": ["Sizes range from the smallest to the largest:",
"many small skulls, a few large ones on top."],
"title2": "Spacing",
"note2": ["Grid step, in % of the smallest height.",
"Below 100 %, skulls overlap and leave no gap."],
"title3": "Tilt and mirror",
"tilt": "max",
"mirror": "mirror",
"note3": ["Random angle between -max and +max;",
"about half the skulls are mirrored."],
"title4": "Result",
"note4": ["Only the visible ink is written: nothing",
"hidden or masked, ready for laser engraving."],
},
},
}
def _unit(angle):
"""Vecteur unitaire, angle en degres, sens anti-horaire a l'ecran (y vers le bas)."""
a = math.radians(angle)
return math.cos(a), -math.sin(a)
out = []
T = {}
FS = 1.0
def fmt(v):
return "{:.2f}".format(v).rstrip("0").rstrip(".")
def pts(polyline):
return " ".join("{},{}".format(fmt(x), fmt(y)) for x, y in polyline)
def polyline(points, color, width, extra=""):
out.append('<polyline points="{}" fill="none" stroke="{}" stroke-width="{}" '
'stroke-linejoin="miter" {}/>'.format(pts(points), color, fmt(width), extra))
def motif(polylines, color, width):
for pl in polylines:
polyline(pl, color, width)
def text(x, y, s, size=17, color=INK, anchor="start", weight="normal", halo=True):
style = "{};font-size:{}px;font-weight:{};fill:{}".format(
FONT, fmt(size * FS), weight, color)
if halo:
style += ";paint-order:stroke;stroke:#ffffff;stroke-width:5px;stroke-linejoin:round"
out.append('<text x="{}" y="{}" text-anchor="{}" style="{}">{}</text>'.format(
fmt(x), fmt(y), anchor, style, s))
def note(x, y, lines):
"""Legende de bas de panneau, derniere ligne sur la ligne de base `y`."""
step = 22 * FS
for k, line in enumerate(lines):
text(x, y - (len(lines) - 1 - k) * step, line, size=16, halo=False)
def arrow_head(tip, direction, color, size=9):
ux, uy = direction
nx, ny = -uy, ux
base = (tip[0] - size * ux, tip[1] - size * uy)
out.append('<polygon points="{}" fill="{}"/>'.format(pts([
tip, (base[0] + 0.45 * size * nx, base[1] + 0.45 * size * ny),
(base[0] - 0.45 * size * nx, base[1] - 0.45 * size * ny)]), color))
def dimension(p, q, offset, label, color=DIM, label_pos=0.5, label_shift=18, size=17):
"""Cote entre p et q, decalee de `offset` perpendiculairement."""
dx, dy = q[0] - p[0], q[1] - p[1]
length = math.hypot(dx, dy)
ux, uy = dx / length, dy / length
nx, ny = -uy, ux
a = (p[0] + offset * nx, p[1] + offset * ny)
b = (q[0] + offset * nx, q[1] + offset * ny)
sign = 1 if offset >= 0 else -1
for base, end in ((p, a), (q, b)):
polyline([(base[0] + sign * 4 * nx, base[1] + sign * 4 * ny),
(end[0] + sign * 6 * nx, end[1] + sign * 6 * ny)], color, 1,
'stroke-dasharray="3,3"')
polyline([a, b], color, 1.6)
arrow_head(a, (-ux, -uy), color)
arrow_head(b, (ux, uy), color)
lx = a[0] + label_pos * (b[0] - a[0]) + sign * label_shift * FS * nx
ly = a[1] + label_pos * (b[1] - a[1]) + sign * label_shift * FS * ny + 6 * FS
text(lx, ly, label, size=size, color=color, anchor="middle", weight="bold")
def arc(center, radius, a0, a1, color, label=None, label_radius=None, size=16):
"""Arc de a0 a a1 degres (sens anti-horaire a l'ecran), fleche au bout."""
steps = 40
points = []
for k in range(steps + 1):
ux, uy = _unit(a0 + (a1 - a0) * k / steps)
points.append((center[0] + radius * ux, center[1] + radius * uy))
polyline(points[:-2], color, 1.6)
last, before = points[-1], points[-3]
d = math.hypot(last[0] - before[0], last[1] - before[1])
arrow_head(last, ((last[0] - before[0]) / d, (last[1] - before[1]) / d), color, 8)
if label:
ux, uy = _unit((a0 + a1) / 2)
r = label_radius or radius + 24
text(center[0] + r * ux, center[1] + r * uy + 6 * FS, label, size=size,
color=color, anchor="middle", weight="bold")
def circle_ring(cx, cy, r, n=180):
return [(cx + r * math.cos(2 * math.pi * k / n), cy + r * math.sin(2 * math.pi * k / n))
for k in range(n)]
def panel_title(x, y, number, title):
text(x, y, "{} {}".format(number, title), size=22, weight="bold", halo=False)
# --------------------------------------------------------------------------
# Panneaux : un par parametre (ou groupe de parametres), numerotes 1 a 4.
# Dessiner avec les vraies fonctions de skull_fill_core, puis coter avec
# dimension() / arc() et legender avec note().
# --------------------------------------------------------------------------
def skull(placement, color=EDGE, fill="#ffffff"):
"""Crane du noyau, comme le dessine l'extension (silhouette, puis encre)."""
body, ink = skull_fill_core.skull_paths(placement)
if fill != "none":
out.append('<path d="{}" fill="{}"/>'.format(body, fill))
out.append('<path d="{}" fill="{}"/>'.format(ink, color))
def dot(x, y, color=DIM):
out.append('<circle cx="{}" cy="{}" r="4" fill="{}"/>'.format(fmt(x), fmt(y), color))
def panel_1():
panel_title(30, 50, 1, T["title1"])
small, big = 130, 330
skull((190, 345, small, 0, False))
skull((450, 330, big, 0, False))
x = 190 - 0.42 * small
dimension((x, 345 - small / 2), (x, 345 + small / 2), 22, "min", label_shift=30)
x = 450 + 0.42 * big
dimension((x, 330 - big / 2), (x, 330 + big / 2), -22, "max", label_shift=30)
note(30, 610, T["note1"])
def panel_2():
panel_title(730, 50, 2, T["title2"])
h, step = 120, 0.7 * 120
rows = []
for j, y in enumerate((330, 330 + 0.866 * step)):
for i in range(4):
rows.append((870 + (i + 0.5 * j) * step, y, h, 0, False))
for placement in reversed(rows):
skull(placement)
for x, y, _h, _a, _m in rows:
dot(x, y)
dimension((rows[0][0], rows[0][1]), (rows[1][0], rows[1][1]), -95,
"70 %", label_shift=16)
note(730, 610, T["note2"])
def panel_3():
panel_title(30, 690, 3, T["title3"])
c, h, angle = (220, 960), 280, 25
skull((c[0], c[1], h, 0, False), color=GHOST, fill="none")
skull((c[0], c[1], h, angle, False))
top = 175
polyline([c, (c[0], c[1] - top)], DIM2, 1.2, 'stroke-dasharray="5,4"')
ux, uy = _unit(90 - angle)
polyline([c, (c[0] + top * ux, c[1] + top * uy)], DIM2, 1.2, 'stroke-dasharray="5,4"')
arc(c, 165, 90, 90 - angle, DIM2, T["tilt"], label_radius=190)
skull((470, 960, 140, 0, False))
skull((620, 960, 140, 0, True))
y = 1060
polyline([(500, y), (590, y)], DIM, 1.6)
arrow_head((500, y), (-1, 0), DIM)
arrow_head((590, y), (1, 0), DIM)
text(545, y + 28, T["mirror"], size=17, color=DIM, anchor="middle", weight="bold")
note(30, 1250, T["note3"])
def panel_4():
panel_title(730, 690, 4, T["title4"])
cx, cy, r = 1050, 950, 225
ring = circle_ring(cx, cy, r)
region = skull_fill_core.Region([ring])
placements = skull_fill_core.skull_placements([ring], 45, 140, seed=2)
# Exactement ce qu'ecrit l'extension : l'encre visible, les interstices,
# rien d'autre (pas de blanc, pas de masque).
gaps = skull_fill_core.visible_gaps(placements, region)
out.append('<path d="{}" fill="{}" fill-rule="evenodd"/>'.format(
skull_fill_core.rings_to_d(gaps), EDGE))
for _placement, rings in skull_fill_core.visible_skulls(placements, region):
out.append('<path d="{}" fill="{}" fill-rule="evenodd"/>'.format(
skull_fill_core.rings_to_d(rings), EDGE))
out.append('<circle cx="{}" cy="{}" r="{}" fill="none" stroke="{}" stroke-width="2" '
'stroke-dasharray="8,5"/>'.format(cx, cy, r + 6, DIM2))
note(730, 1250, T["note4"])
def export_png(svg_path, png_path, width):
exe = next((path for path in INKSCAPE if os.path.exists(path)), None)
if exe is None:
print("Inkscape introuvable : exporter {} a la main".format(svg_path))
return
os.makedirs(os.path.dirname(png_path), exist_ok=True)
subprocess.run([exe, svg_path, "--export-type=png",
"--export-width={}".format(width),
"--export-filename={}".format(png_path)],
check=True, stderr=subprocess.DEVNULL)
print(png_path)
def build(language):
global FS
version = VERSIONS[language]
out.clear()
T.clear()
T.update(version["text"])
FS = version["font_scale"]
out.append('<rect width="{}" height="{}" fill="#ffffff"/>'.format(W, H))
for x1, y1, x2, y2 in ((700, 20, 700, H - 20), (20, 640, W - 20, 640)):
out.append('<line x1="{}" y1="{}" x2="{}" y2="{}" stroke="#dee2e6" '
'stroke-width="1.5"/>'.format(x1, y1, x2, y2))
panel_1()
panel_2()
panel_3()
panel_4()
svg = ('<?xml version="1.0" encoding="UTF-8"?>\n'
'<svg xmlns="http://www.w3.org/2000/svg" width="{0}" height="{1}" '
'viewBox="0 0 {0} {1}">\n{2}\n</svg>\n').format(W, H, "\n".join(out))
with open(version["svg"], "w", encoding="utf-8", newline="\n") as handle:
handle.write(svg)
print(version["svg"])
export_png(version["svg"], version["png"], version["png_width"])
def main(argv):
languages = argv or sorted(VERSIONS)
for language in languages:
build(language)
if __name__ == "__main__":
main(sys.argv[1:])