Initiale version
This commit is contained in:
commit
00e9ba3434
19 files changed
+2586
No files matched your search
+217
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
# coding=utf-8
|
||||
"""
|
||||
Extension Inkscape : remplit les formes selectionnees d'un labyrinthe de
|
||||
Turing (motif « Dog Bandana »), trace en lignes centrales a bouts ronds.
|
||||
|
||||
Le motif est calcule par l'equation de Swift-Hohenberg sur une grille qui
|
||||
couvre la forme, puis reduit a la ligne centrale de chaque bande : un trait
|
||||
par « vermicelle », pret pour la gravure laser en mode ligne.
|
||||
|
||||
La logique vit dans `dog_bandana_core`, sans dependance a inkex.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import inkex
|
||||
from inkex.bezier import cspsubdiv
|
||||
from inkex.localization import localize
|
||||
from inkex.units import convert_unit
|
||||
|
||||
# L'extension vit dans son propre sous-dossier des extensions Inkscape, qui
|
||||
# n'est pas forcement dans sys.path : on l'y ajoute pour trouver dog_bandana_core.
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from dog_bandana_core import (MAX_PIXELS, grid_pixels, laser_order, # noqa: E402
|
||||
parse_color, polylines_to_d, turing_pattern)
|
||||
|
||||
|
||||
def use_system_language():
|
||||
"""Renseigne LANGUAGE avec la langue du systeme si rien ne la fixe.
|
||||
|
||||
Sous Windows, Inkscape regle sur « langue du systeme » ne transmet aucune
|
||||
variable de langue au script : gettext retomberait sur l'anglais alors que
|
||||
la boite de dialogue, traduite par Inkscape lui-meme, est dans la langue
|
||||
de l'utilisateur.
|
||||
"""
|
||||
if any(os.environ.get(name) for name in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG")):
|
||||
return
|
||||
try:
|
||||
import ctypes
|
||||
import locale
|
||||
language = locale.windows_locale.get(
|
||||
ctypes.windll.kernel32.GetUserDefaultUILanguage())
|
||||
except Exception: # pylint: disable=broad-except
|
||||
return # hors Windows : LANG est toujours defini
|
||||
if language:
|
||||
os.environ["LANGUAGE"] = language
|
||||
|
||||
|
||||
# Installe _() dans les builtins : catalogue « dogbandana » de la langue
|
||||
# de l'interface (Inkscape transmet domaine et dossier par l'environnement),
|
||||
# textes anglais d'origine sinon.
|
||||
use_system_language()
|
||||
localize()
|
||||
|
||||
# Elements qui delimitent une surface a remplir.
|
||||
SHAPES = (inkex.PathElement, inkex.Rectangle, inkex.Circle, inkex.Ellipse,
|
||||
inkex.Polygon)
|
||||
|
||||
|
||||
def uu_per_mm(svg):
|
||||
"""Unites utilisateur par millimetre, comme Inkscape les affiche.
|
||||
|
||||
svg.unittouu() devine l'unite du document par arrondi a l'unite connue la
|
||||
plus proche : il se trompe des que l'echelle n'est pas standard (page
|
||||
redimensionnee). On prend le rapport reel page / viewBox ; Inkscape
|
||||
applique une echelle uniforme (preserveAspectRatio « meet »), soit la
|
||||
plus petite des deux.
|
||||
"""
|
||||
try:
|
||||
vb_w, vb_h = svg.viewbox_width, svg.viewbox_height
|
||||
page_w = svg.to_dimensional(svg.viewport_width, "mm")
|
||||
page_h = svg.to_dimensional(svg.viewport_height, "mm")
|
||||
except AttributeError: # inkex anterieur a 1.2
|
||||
return svg.unittouu("1mm")
|
||||
if not (vb_w and vb_h and page_w and page_h):
|
||||
return svg.unittouu("1mm")
|
||||
return 1 / min(page_w / vb_w, page_h / vb_h)
|
||||
|
||||
|
||||
def length_to_uu(svg, value, unit="mm"):
|
||||
"""Longueur reelle (valeur + unite) -> unites utilisateur du document."""
|
||||
return convert_unit("{}{}".format(value, unit), "mm") * uu_per_mm(svg)
|
||||
|
||||
|
||||
def element_rings(elem, flatness):
|
||||
"""Contour de l'element en coordonnees absolues : liste d'anneaux.
|
||||
|
||||
Les courbes sont aplaties en polylignes (ecart maximal `flatness`).
|
||||
"""
|
||||
path = elem.path.transform(elem.composed_transform())
|
||||
csp = path.to_superpath()
|
||||
cspsubdiv(csp, flatness)
|
||||
rings = []
|
||||
for sub in csp:
|
||||
ring = [(node[1][0], node[1][1]) for node in sub]
|
||||
if len(ring) > 1 and ring[0] == ring[-1]:
|
||||
ring.pop()
|
||||
if len(ring) >= 3:
|
||||
rings.append(ring)
|
||||
return rings
|
||||
|
||||
|
||||
class DogBandana(inkex.EffectExtension):
|
||||
"""Remplit chaque forme selectionnee d'un labyrinthe de Turing."""
|
||||
|
||||
def add_arguments(self, pars):
|
||||
# Un argument par <param> du .inx, memes noms et memes valeurs par defaut.
|
||||
pars.add_argument("--tab", default="pattern")
|
||||
pars.add_argument("--period", type=float, default=4.0)
|
||||
pars.add_argument("--line_width", type=float, default=2.0)
|
||||
pars.add_argument("--margin", type=float, default=0.0)
|
||||
pars.add_argument("--unit", default="mm")
|
||||
pars.add_argument("--iterations", type=int, default=60)
|
||||
pars.add_argument("--seed", type=int, default=1)
|
||||
pars.add_argument("--edge", default="cut")
|
||||
pars.add_argument("--stroke_color", default="255")
|
||||
pars.add_argument("--keep_original", type=inkex.Boolean, default=True)
|
||||
|
||||
def effect(self):
|
||||
opt = self.options
|
||||
|
||||
shapes = []
|
||||
for elem in self.svg.selection.values():
|
||||
if isinstance(elem, SHAPES):
|
||||
shapes.append(elem)
|
||||
elif isinstance(elem, inkex.Group):
|
||||
shapes.extend(e for e in elem.descendants() if isinstance(e, SHAPES))
|
||||
if not shapes:
|
||||
inkex.errormsg(_("Select at least one closed shape (path, rectangle, "
|
||||
"circle, ellipse, polygon) or a group containing some."))
|
||||
return
|
||||
|
||||
period = length_to_uu(self.svg, opt.period, opt.unit)
|
||||
width = length_to_uu(self.svg, opt.line_width, opt.unit)
|
||||
margin = length_to_uu(self.svg, opt.margin, opt.unit)
|
||||
if period <= 0 or width <= 0:
|
||||
inkex.errormsg(_("The period and the line width must be strictly positive."))
|
||||
return
|
||||
if width >= period:
|
||||
inkex.errormsg(_("The line width must be smaller than the period, "
|
||||
"otherwise neighbouring lines merge. Reduce the line "
|
||||
"width or increase the period."))
|
||||
return
|
||||
|
||||
color, opacity = parse_color(opt.stroke_color, ("#000000", 1.0))
|
||||
style = inkex.Style({
|
||||
"fill": "none",
|
||||
"stroke": color,
|
||||
"stroke-opacity": str(opacity),
|
||||
"stroke-width": str(width),
|
||||
"stroke-linecap": "round",
|
||||
"stroke-linejoin": "round",
|
||||
})
|
||||
|
||||
# Position de la tete du laser : chaque trace demarre la ou le
|
||||
# precedent s'est arrete (voir path_element).
|
||||
self.head = (0.0, 0.0)
|
||||
empty = 0
|
||||
for elem in shapes:
|
||||
rings = element_rings(elem, period / 50)
|
||||
if grid_pixels(rings, period) > MAX_PIXELS:
|
||||
inkex.errormsg(_("The shape is too large for this period: the "
|
||||
"computation would take too long. Increase the "
|
||||
"period or split the shape."))
|
||||
return
|
||||
if not self.process(elem, rings, period, width, margin, style):
|
||||
empty += 1
|
||||
if empty:
|
||||
inkex.errormsg(_("{} shape(s) too narrow for the pattern: reduce the "
|
||||
"line width, the period or the margin.").format(empty))
|
||||
|
||||
def path_element(self, polylines, style):
|
||||
"""Chemin SVG des traits, dans l'ordre de gravure optimise.
|
||||
|
||||
Les traits qui se touchent sont enchaines, puis ordonnes au plus pres
|
||||
de la position de la tete : moins de deplacements a vide du laser.
|
||||
Tout trait genere passe par ici.
|
||||
"""
|
||||
polylines = laser_order(polylines, self.head)
|
||||
if polylines:
|
||||
self.head = polylines[-1][-1]
|
||||
node = inkex.PathElement()
|
||||
node.path = polylines_to_d(polylines, precision=3)
|
||||
node.style = style
|
||||
return node
|
||||
|
||||
def process(self, elem, rings, period, width, margin, style):
|
||||
"""Remplit un element ; renvoie False si la forme est trop etroite."""
|
||||
opt = self.options
|
||||
polylines = turing_pattern(rings, period, width, margin, seed=opt.seed,
|
||||
edge=opt.edge, steps=opt.iterations)
|
||||
if not polylines:
|
||||
return False
|
||||
|
||||
parent = elem.getparent()
|
||||
group = inkex.Group()
|
||||
group.label = _("Dog Bandana pattern")
|
||||
if parent is not None:
|
||||
# Resultat calcule en coordonnees absolues du document : on
|
||||
# neutralise la transformation heritee du parent d'accueil.
|
||||
parent_transform = parent.composed_transform()
|
||||
if parent_transform != inkex.Transform():
|
||||
group.transform = -parent_transform
|
||||
parent.insert(parent.index(elem) + 1, group)
|
||||
else:
|
||||
self.svg.add(group)
|
||||
group.add(self.path_element(polylines, style))
|
||||
|
||||
if not opt.keep_original:
|
||||
elem.delete()
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
DogBandana().run()
|
||||
Reference in new issue
Block a user