#!/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 relief_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 relief_core # noqa: E402
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": "Longueur d'arête",
"edge": "arête",
"period": "5 arêtes (période)",
"note1": ["Le motif se répète toutes les 5 arêtes :",
"plus l'arête est grande, plus il est grossier."],
"title2": "Rotation",
"angle": "angle",
"ref": "avant",
"note2": ["Le motif tourne dans le sens horaire,",
"autour de l'origine du motif."],
"title3": "Origine du motif",
"row_shape": "Centre de chaque forme",
"row_doc": "Origine du document",
"note3": ["Centre : un nœud de la grille au milieu de chaque forme.",
"Document : un seul motif continu d'une forme à l'autre."],
"title4": "Résultat",
"hole": "le trou reste vide",
"outline": "contour (option)",
"lines": "traits coupés au bord",
"note4": ["Un groupe au-dessus de la forme, avec un chemin",
"par forme ; formes à trous prises en charge."],
},
},
"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": "Edge length",
"edge": "edge",
"period": "5 edges (period)",
"note1": ["The pattern repeats every 5 edges:",
"a longer edge gives a coarser pattern."],
"title2": "Rotation",
"angle": "angle",
"ref": "before",
"note2": ["The pattern turns clockwise,",
"around the pattern origin."],
"title3": "Pattern origin",
"row_shape": "Center of each shape",
"row_doc": "Document origin",
"note3": ["Center: a grid node in the middle of each shape.",
"Document: one continuous pattern across shapes."],
"title4": "Result",
"hole": "the hole stays empty",
"outline": "outline (option)",
"lines": "lines cut at the edge",
"note4": ["A group above the shape, with one path",
"per shape; shapes with holes are supported."],
},
},
}
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(''.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('{}'.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(''.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 rect_ring(x, y, w, h):
return [(x, y), (x + w, y), (x + w, y + h), (x, y + h)]
def panel_title(x, y, number, title):
text(x, y, "{} {}".format(number, title), size=22, weight="bold", halo=False)
def fill(rings, edge, angle, anchor, color, width):
"""Dessine le motif de relief_core dans `rings`."""
segments = relief_core.fill_rings(rings, edge, angle, anchor)
motif(relief_core.segments_to_polylines(segments), color, width)
def outline(rings, color, width, extra=""):
for ring in rings:
polyline(ring + [ring[0]], color, width, extra)
def marker(point, color=DIM):
out.append(''.format(fmt(point[0]), fmt(point[1]), color))
def label_with_leader(anchor_point, label_point, label, color=DIM, align="start"):
polyline([anchor_point, label_point], color, 1.4)
out.append(''.format(
fmt(anchor_point[0]), fmt(anchor_point[1]), color))
dx = 8 if align == "start" else -8
text(label_point[0] + dx, label_point[1] + 5 * FS, label, size=16, color=color,
anchor=align, weight="bold")
# --------------------------------------------------------------------------
# Panneaux : un par parametre (ou groupe de parametres), numerotes 1 a 4.
# --------------------------------------------------------------------------
def panel_1():
panel_title(30, 50, 1, T["title1"])
box = rect_ring(60, 90, 580, 470)
cx, cy = 350.0, 325.0
edge = 44.0
fill([box], edge, 0, (cx, cy), INK, 2.2)
outline([box], EDGE, 2.6)
hx = edge * relief_core.COS30
# une arete verticale presente du motif (noeud (0,2) -> (0,4)) et la periode
p, q = (cx, cy + edge), (cx, cy + 2 * edge)
dimension(p, q, -34, T["edge"], DIM, label_shift=24)
dimension((cx, cy - 3 * edge), (cx, cy + 2 * edge), 36,
T["period"], DIM2, label_shift=18)
note(30, 610, T["note1"])
def panel_2():
ox = 700
panel_title(ox + 30, 50, 2, T["title2"])
cx, cy = ox + 350.0, 325.0
shape = [circle_ring(cx, cy, 225)]
edge = 44.0
fill(shape, edge, 0, (cx, cy), GHOST, 2.0)
fill(shape, edge, 20, (cx, cy), INK, 2.2)
outline(shape, EDGE, 2.6)
# reference verticale avant rotation, et verticale tournee
ux, uy = _unit(90)
polyline([(cx, cy), (cx + 190 * ux, cy + 190 * uy)], DIM2, 1.6, 'stroke-dasharray="6,4"')
ux, uy = _unit(70)
polyline([(cx, cy), (cx + 190 * ux, cy + 190 * uy)], DIM, 1.8)
arc((cx, cy), 120, 90, 70, DIM, T["angle"], label_radius=146)
marker((cx, cy))
text(cx - 10, cy - 196, T["ref"], size=16, color=DIM2, anchor="end", weight="bold")
note(ox + 30, 610, T["note2"])
def panel_3():
oy = 640
panel_title(30, oy + 50, 3, T["title3"])
edge = 26.0
rects = [rect_ring(70, oy + 120, 250, 150), rect_ring(350, oy + 120, 250, 150)]
rects2 = [rect_ring(70, oy + 340, 250, 150), rect_ring(350, oy + 340, 250, 150)]
# rangee A : un noeud au centre de chaque forme
text(70, oy + 100, T["row_shape"], size=17, color=DIM, weight="bold", halo=False)
for ring in rects:
center = (ring[0][0] + 125, ring[0][1] + 75)
fill([ring], edge, 0, center, INK, 1.8)
outline([ring], EDGE, 2.4)
marker(center)
# rangee B : grille ancree au coin de la page, motif continu
text(70, oy + 320, T["row_doc"], size=17, color=DIM2, weight="bold", halo=False)
band = rect_ring(40, oy + 330, 590, 170)
fill([band], edge, 0, (0.0, 0.0), GHOST, 1.6)
for ring in rects2:
fill([ring], edge, 0, (0.0, 0.0), INK, 1.8)
outline([ring], EDGE, 2.4)
note(30, oy + 610, T["note3"])
def panel_4():
ox, oy = 700, 640
panel_title(ox + 30, oy + 50, 4, T["title4"])
cx, cy = ox + 280.0, oy + 330.0
# forme a trou : cercle exterieur, cercle interieur decale
outer = circle_ring(cx, cy, 170)
inner = circle_ring(cx + 45, cy + 20, 55)
rings = [outer, inner]
fill(rings, 26.0, 0, (cx, cy), INK, 2.0)
outline(rings, DIM, 3.2)
label_with_leader((cx + 45 + 55, cy + 20), (cx + 185, cy + 20), T["hole"], DIM, "start")
label_with_leader((cx - 170 * 0.866, cy - 170 * 0.5), (ox + 40, cy - 190),
T["outline"], DIM, "start")
label_with_leader((cx - 60, cy + 95), (ox + 40, cy + 215), T["lines"], DIM2, "start")
note(ox + 30, oy + 610, 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(''.format(W, H))
for x1, y1, x2, y2 in ((700, 20, 700, H - 20), (20, 640, W - 20, 640)):
out.append(''.format(x1, y1, x2, y2))
panel_1()
panel_2()
panel_3()
panel_4()
svg = ('\n'
'\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:])