sidrefresh's picture
Add files using upload-large-folder tool
e33425b verified
Raw History Blame Contribute Delete
8.02 kB
"""Minimal SVG path geometry for the t16 rubric (pure Python, no deps).
svg_polylines(svg_text) -> list of polylines [[(x, y), ...], ...] in the SVG's
user units, with <g>/<path> transform="translate/scale/matrix" applied and
the viewBox mapped to width/height. Supports path commands M m L l H h V v
C c S s Q q T t Z z (cubics/quads sampled at 12 points), plus <polyline>,
<polygon> and <line>. Anything else is ignored — the rubric reports "no path".
Friction's SVG export (ExportSvgDialog) and hand-written SVGs both fit this.
"""
import math
import re
import xml.etree.ElementTree as ET
_NUM = re.compile(r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?")
def _mat_mul(a, b):
a11, a12, a13, a21, a22, a23 = a; b11, b12, b13, b21, b22, b23 = b
return (a11 * b11 + a12 * b21, a11 * b12 + a12 * b22, a11 * b13 + a12 * b23 + a13,
a21 * b11 + a22 * b21, a21 * b12 + a22 * b22, a21 * b13 + a22 * b23 + a23)
def _parse_transform(t):
m = (1, 0, 0, 0, 1, 0)
if not t:
return m
for name, args in re.findall(r"(\w+)\s*\(([^)]*)\)", t):
v = [float(x) for x in _NUM.findall(args)]
if name == "translate":
tx, ty = (v + [0])[:2]; mm = (1, 0, tx, 0, 1, ty)
elif name == "scale":
sx = v[0]; sy = v[1] if len(v) > 1 else sx; mm = (sx, 0, 0, 0, sy, 0)
elif name == "matrix" and len(v) == 6:
a, b, c, d, e, f = v; mm = (a, c, e, b, d, f)
elif name == "rotate":
ang = math.radians(v[0]); ca, sa = math.cos(ang), math.sin(ang)
mm = (ca, -sa, 0, sa, ca, 0)
if len(v) == 3:
cx, cy = v[1], v[2]
mm = _mat_mul(_mat_mul((1, 0, cx, 0, 1, cy), mm), (1, 0, -cx, 0, 1, -cy))
else:
continue
m = _mat_mul(m, mm)
return m
def _apply(m, x, y):
return (m[0] * x + m[1] * y + m[2], m[3] * x + m[4] * y + m[5])
def _bezier(p0, p1, p2, p3=None, n=12):
pts = []
for i in range(1, n + 1):
t = i / n
if p3 is None: # quadratic
x = (1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t ** 2 * p2[0]
y = (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t ** 2 * p2[1]
else:
x = ((1 - t) ** 3 * p0[0] + 3 * (1 - t) ** 2 * t * p1[0] + 3 * (1 - t) * t ** 2 * p2[0] + t ** 3 * p3[0])
y = ((1 - t) ** 3 * p0[1] + 3 * (1 - t) ** 2 * t * p1[1] + 3 * (1 - t) * t ** 2 * p2[1] + t ** 3 * p3[1])
pts.append((x, y))
return pts
def path_polylines(d):
tokens = re.findall(r"[MmLlHhVvCcSsQqTtZzAa]|" + _NUM.pattern, d or "")
polys, cur, start = [], None, None
x = y = 0.0; cmd = None; i = 0; last_ctrl = None
nums = []
def take(k):
nonlocal i
vals = [float(t) for t in tokens[i:i + k]]; i += k
return vals
while i < len(tokens):
t = tokens[i]
if re.match(r"[A-Za-z]", t):
cmd = t; i += 1
if cmd in "Zz":
if cur and start:
cur.append(start)
cur = None; last_ctrl = None
continue
if cmd is None:
i += 1; continue
rel = cmd.islower(); c = cmd.upper()
try:
if c == "M":
px, py = take(2); x, y = (x + px, y + py) if rel else (px, py)
cur = [(x, y)]; polys.append(cur); start = (x, y); cmd = "l" if rel else "L"; last_ctrl = None
elif c == "L":
px, py = take(2); x, y = (x + px, y + py) if rel else (px, py); cur.append((x, y)); last_ctrl = None
elif c == "H":
(px,) = take(1); x = x + px if rel else px; cur.append((x, y)); last_ctrl = None
elif c == "V":
(py,) = take(1); y = y + py if rel else py; cur.append((x, y)); last_ctrl = None
elif c == "C":
v = take(6)
if rel: v = [v[0] + x, v[1] + y, v[2] + x, v[3] + y, v[4] + x, v[5] + y]
cur.extend(_bezier((x, y), (v[0], v[1]), (v[2], v[3]), (v[4], v[5]))); last_ctrl = (v[2], v[3]); x, y = v[4], v[5]
elif c == "S":
v = take(4)
if rel: v = [v[0] + x, v[1] + y, v[2] + x, v[3] + y]
c1 = (2 * x - last_ctrl[0], 2 * y - last_ctrl[1]) if last_ctrl else (x, y)
cur.extend(_bezier((x, y), c1, (v[0], v[1]), (v[2], v[3]))); last_ctrl = (v[0], v[1]); x, y = v[2], v[3]
elif c == "Q":
v = take(4)
if rel: v = [v[0] + x, v[1] + y, v[2] + x, v[3] + y]
cur.extend(_bezier((x, y), (v[0], v[1]), (v[2], v[3]))); last_ctrl = (v[0], v[1]); x, y = v[2], v[3]
elif c == "T":
v = take(2)
if rel: v = [v[0] + x, v[1] + y]
c1 = (2 * x - last_ctrl[0], 2 * y - last_ctrl[1]) if last_ctrl else (x, y)
cur.extend(_bezier((x, y), c1, (v[0], v[1]))); last_ctrl = c1; x, y = v
elif c == "A":
v = take(7); x, y = (x + v[5], y + v[6]) if rel else (v[5], v[6]); cur.append((x, y)); last_ctrl = None
else:
i += 1
except (IndexError, ValueError, TypeError):
break
return [p for p in polys if len(p) >= 2]
def _animate_last(el):
for ch in el:
if ch.tag.split("}")[-1] == "animate" and ch.get("values"):
vals = [v.strip() for v in ch.get("values").split(";") if v.strip()]
if vals:
return max(vals, key=len) # the longest path string = fully grown
return None
def animate_values(text):
"""Per-frame path strings of the first animated <path> (Friction export),
or [] — lets a rubric see how the line grows frame by frame."""
try:
root = ET.fromstring(text)
except ET.ParseError:
return []
for el in root.iter():
if el.tag.split("}")[-1] == "path":
for ch in el:
if ch.tag.split("}")[-1] == "animate" and ch.get("values"):
return [v.strip() for v in ch.get("values").split(";")]
return []
def svg_polylines(text):
try:
root = ET.fromstring(text)
except ET.ParseError:
return []
# viewBox -> width/height mapping
vb = root.get("viewBox"); base = (1, 0, 0, 0, 1, 0)
try:
if vb:
vx, vy, vw, vh = [float(v) for v in _NUM.findall(vb)]
w = float(_NUM.findall(root.get("width", str(vw)))[0]); h = float(_NUM.findall(root.get("height", str(vh)))[0])
base = (w / vw, 0, -vx * w / vw, 0, h / vh, -vy * h / vh)
except (ValueError, IndexError, ZeroDivisionError):
pass
out = []
def walk(el, m):
m = _mat_mul(m, _parse_transform(el.get("transform")))
tag = el.tag.split("}")[-1]
polys = []
if tag == "path":
d = el.get("d")
if not d:
# Friction's SVG export (ExportSvgDialog) writes an animated path:
# no d attribute, the per-frame path strings live in
# <animate attributeName="d" values="M..;M..;..">. The LAST value
# is the fully grown line (Sub-Path at 100 %); the sequence is
# also the frame-by-frame growth, exposed via animate_values().
d = _animate_last(el)
polys = path_polylines(d)
elif tag in ("polyline", "polygon"):
v = [float(t) for t in _NUM.findall(el.get("points", ""))]
pts = list(zip(v[0::2], v[1::2]))
if tag == "polygon" and pts: pts.append(pts[0])
polys = [pts] if len(pts) >= 2 else []
elif tag == "line":
try:
polys = [[(float(el.get("x1")), float(el.get("y1"))), (float(el.get("x2")), float(el.get("y2")))]]
except (TypeError, ValueError):
polys = []
for p in polys:
out.append([_apply(m, x, y) for x, y in p])
for ch in el:
walk(ch, m)
walk(root, base)
return out