Files
AlexandClaude Opus 5.5 2353640d2a Rename Docs/ to docs/ so README image links resolve
The README references docs/apercu.png and docs/parametres.png, but the
folder was tracked as Docs/, which breaks the links on case-sensitive
hosts such as the Gitea server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:56:52 +01:00

390 lines
15 KiB
Python

#!/usr/bin/env python3
# coding=utf-8
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 Alex
"""
Generates the diagram that explains the extension parameters.
python docs/schema_parametres.py # both 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 ("Help"
# tab of the dialog)
Shapes are computed by dog_bandana_core (same functions as the extension),
so the diagram stays faithful to the actual result. PNG export goes through
inkscape.com, which waits for the export to finish (unlike the Chocolatey
"inkscape" shim).
"""
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 dog_bandana_core # noqa: E402
W, H = 1400, 1280 # 4 panels of 700 x 640
INK = "#343a40" # main element
GHOST = "#dde1e5" # secondary / neighbouring elements
DIM = "#d9480f" # dimensions
DIM2 = "#1971c2" # secondary dimensions
EDGE = "#212529" # shape outlines
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 per language: texts, output files, PNG width and text scaling (the
# English version is shown reduced in the dialog: 900 px wide, texts x 1.25 to
# stay readable).
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": "Période et épaisseur du trait",
"period": "Période",
"width": "Épaisseur",
"note1": ["Période : d'axe en axe de deux lignes voisines.",
"Épaisseur : celle du trait, à bouts ronds ; la moitié",
"de la période donne autant de noir que de blanc."],
"title2": "Itérations",
"default": "{} (défaut)",
"iterations": "plus d'itérations",
"note2": ["Peu d'itérations : points et lignes courtes ; beaucoup :",
"longues lignes régulières. La graine aléatoire change",
"le dessin en gardant le même aspect."],
"title3": "Au bord de la forme",
"cut": "Couper les lignes",
"follow": "Longer le bord",
"note3": ["Couper : le motif est découpé comme un tissu.",
"Longer : les lignes s'arrêtent avant le bord et le suivent."],
"title4": "Marge",
"margin": "Marge",
"note4": ["Espace libre entre le bord de la forme et les traits",
"(bouts ronds compris). À 0, les traits touchent le bord."],
},
},
"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": "Period and line width",
"period": "Period",
"width": "Width",
"note1": ["Period: center to center of two neighbouring lines.",
"Width: round-capped stroke; half the period",
"gives as much black as white."],
"title2": "Iterations",
"default": "{} (default)",
"iterations": "more iterations",
"note2": ["Few iterations: dots and short lines; many:",
"long regular lines. The random seed changes",
"the drawing, not its look."],
"title3": "At the shape edge",
"cut": "Cut the lines",
"follow": "Follow the edge",
"note3": ["Cut: the pattern is cut like fabric.",
"Follow: lines stop before the edge, run along it."],
"title4": "Margin",
"margin": "Margin",
"note4": ["Free space between the shape edge and the",
"strokes (round tips included). 0: strokes touch it."],
},
},
}
def _unit(angle):
"""Unit vector, angle in degrees, counterclockwise on screen (y pointing down)."""
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):
"""Panel caption, last line on baseline `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):
"""Dimension between p and q, shifted by `offset` perpendicularly."""
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 from a0 to a1 degrees (counterclockwise on screen), arrow at the end."""
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)
# --------------------------------------------------------------------------
# Panels: one per parameter (or group of parameters), numbered 1 to 4.
# Patterns computed by dog_bandana_core.turing_pattern, as in the extension.
# --------------------------------------------------------------------------
def strokes(polylines, color, width):
"""Round-capped strokes, like those produced by the extension."""
for pl in polylines:
out.append('<polyline points="{}" fill="none" stroke="{}" stroke-width="{}" '
'stroke-linecap="round" stroke-linejoin="round"/>'.format(
pts(pl), color, fmt(width)))
def outline(rings, color=EDGE, width=2, extra=""):
d = " ".join("M " + " L ".join("{},{}".format(fmt(x), fmt(y)) for x, y in ring) + " Z"
for ring in rings)
out.append('<path d="{}" fill="none" stroke="{}" stroke-width="{}" {}/>'.format(
d, color, fmt(width), extra))
def rect_ring(x0, y0, x1, y1):
return [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
def crossings(polylines, x):
"""Crossings of the polylines with the vertical x: (y, slope, index)."""
found = []
for index, pl in enumerate(polylines):
for (ax, ay), (bx, by) in zip(pl, pl[1:]):
if (ax <= x) != (bx <= x):
t = (x - ax) / (bx - ax)
found.append((ay + t * (by - ay), abs((by - ay) / (bx - ax)), index))
return sorted(found)
def panel_1():
"""Period and width: dimensions on two neighbouring, nearly parallel lines."""
period, width = 64, 28
region = rect_ring(60, 90, 640, 530)
def near(cuts, index, y):
return any(i == index and abs(cy - y) < 6 for cy, _s, i in cuts)
# Look for two neighbouring lines, nearly horizontal over a good length
# (verticals x - 70, x, x + 70), about one period apart: the dimensions
# fit in the white space between them.
best = None
for seed in range(1, 9):
lines = dog_bandana_core.turing_pattern([region], period, width, seed=seed,
steps=150)
for x in range(250, 480, 6):
cuts = crossings(lines, x)
left, right = crossings(lines, x - 70), crossings(lines, x + 70)
for (y1, s1, i1), (y2, s2, i2) in zip(cuts, cuts[1:]):
if not (170 < y1 < 400 and i1 != i2):
continue
if not all(near(c, i, y) for c in (left, right)
for i, y in ((i1, y1), (i2, y2))):
continue
score = abs(y2 - y1 - period) + 30 * (s1 + s2) + abs(x - 360) / 20
if best is None or score < best[0]:
best = (score, lines, x, y1, y2, i1, i2)
_score, lines, x, y1, y2, i1, i2 = best
panel_title(30, 50, 1, T["title1"])
strokes([pl for k, pl in enumerate(lines) if k not in (i1, i2)], GHOST, width)
strokes([lines[i1], lines[i2]], INK, width)
outline([region], EDGE, 2)
# Period: center to center; width: edge to edge of a single line.
for y in (y1, y2):
polyline([(x - 25, y), (x + 25, y)], DIM, 1.4, 'stroke-dasharray="4,3"')
dimension((x, y1), (x, y2), 0, "")
text(x + 12, (y1 + y2) / 2 + 6, T["period"], color=DIM, weight="bold")
# Width on the lower line, label below it (clear area).
xw = x - 70
dimension((xw, y2 - width / 2), (xw, y2 + width / 2), 0, "", color=DIM2)
text(xw, y2 + width / 2 + 28, T["width"], color=DIM2, anchor="middle",
weight="bold")
note(30, 610, T["note1"])
def panel_2():
"""Iterations: same seed, three evolution times."""
ox = 700
panel_title(ox + 30, 50, 2, T["title2"])
size, gap = 190, 25
for k, steps in enumerate((20, 60, 300)):
x0 = ox + 30 + k * (size + gap)
region = rect_ring(x0, 130, x0 + size, 130 + size)
lines = dog_bandana_core.turing_pattern([region], 20, 9, seed=5, steps=steps)
strokes(lines, INK, 9)
outline([region], EDGE, 2)
label = T["default"].format(steps) if steps == 60 else str(steps)
text(x0 + size / 2, 130 + size + 40, label, size=20, color=DIM,
anchor="middle", weight="bold")
arrow_y = 420
polyline([(ox + 60, arrow_y), (ox + 630, arrow_y)], DIM2, 1.6)
arrow_head((ox + 640, arrow_y), (1, 0), DIM2)
text(ox + 345, arrow_y + 30, T["iterations"], color=DIM2, anchor="middle",
weight="bold")
note(ox + 30, 610, T["note2"])
def panel_3():
"""Shape edge: pattern cut (like fabric) or running along the edge."""
oy = 640
panel_title(30, oy + 50, 3, T["title3"])
for k, edge in enumerate(("cut", "follow")):
cx, cy, r = 190 + k * 320, oy + 270, 140
ring = circle_ring(cx, cy, r)
lines = dog_bandana_core.turing_pattern([ring], 24, 11, seed=2, edge=edge)
strokes(lines, INK, 11)
outline([ring], EDGE, 2)
text(cx, cy + r + 40, T[edge], size=19, color=DIM, anchor="middle",
weight="bold")
note(30, oy + 610, T["note3"])
def panel_4():
"""Margin: free space between the edge and the strokes."""
ox, oy = 700, 640
panel_title(ox + 30, oy + 50, 4, T["title4"])
margin, period, width = 40, 30, 14
x0, y0, x1, y1 = ox + 70, oy + 90, ox + 630, oy + 470
lines = dog_bandana_core.turing_pattern([rect_ring(x0, y0, x1, y1)], period, width,
margin=margin, seed=6)
strokes(lines, INK, width)
outline([rect_ring(x0, y0, x1, y1)], EDGE, 2.5)
outline([rect_ring(x0 + margin, y0 + margin, x1 - margin, y1 - margin)], DIM2, 1.5,
'stroke-dasharray="6,4"')
dimension((x0, y1 + 22), (x0 + margin, y1 + 22), 0, "", color=DIM)
text(x0 + margin + 12, y1 + 29, T["margin"], color=DIM, weight="bold")
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 not found: export {} by hand".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:])