be save on late evaluations
[PyX/mjg.git] / pyx / deco.py
blobfb091278a08e1c35b3f6aa2b9fe98e9e0362b148
1 #!/usr/bin/env python
2 # -*- coding: ISO-8859-1 -*-
5 # Copyright (C) 2002-2004 Jörg Lehmann <joergl@users.sourceforge.net>
6 # Copyright (C) 2003-2004 Michael Schindler <m-schindler@users.sourceforge.net>
7 # Copyright (C) 2002-2004 André Wobst <wobsta@users.sourceforge.net>
9 # This file is part of PyX (http://pyx.sourceforge.net/).
11 # PyX is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
16 # PyX is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with PyX; if not, write to the Free Software
23 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 # TODO:
26 # - should we improve on the arc length -> arg parametrization routine or
27 # should we at least factor it out?
29 import sys, math
30 import attr, base, canvas, color, helper, path, style, trafo, unit
33 # Decorated path
36 class decoratedpath(base.PSCmd):
37 """Decorated path
39 The main purpose of this class is during the drawing
40 (stroking/filling) of a path. It collects attributes for the
41 stroke and/or fill operations.
42 """
44 def __init__(self, path, strokepath=None, fillpath=None,
45 styles=None, strokestyles=None, fillstyles=None,
46 subcanvas=None):
48 self.path = path
50 # path to be stroked or filled (or None)
51 self.strokepath = strokepath
52 self.fillpath = fillpath
54 # global style for stroking and filling and subdps
55 self.styles = helper.ensurelist(styles)
57 # styles which apply only for stroking and filling
58 self.strokestyles = helper.ensurelist(strokestyles)
59 self.fillstyles = helper.ensurelist(fillstyles)
61 # the canvas can contain additional elements of the path, e.g.,
62 # arrowheads,
63 if subcanvas is None:
64 self.subcanvas = canvas.canvas()
65 else:
66 self.subcanvas = subcanvas
69 def bbox(self):
70 scbbox = self.subcanvas.bbox()
71 pbbox = self.path.bbox()
72 if scbbox is not None:
73 return scbbox+pbbox
74 else:
75 return pbbox
77 def prolog(self):
78 result = []
79 for style in list(self.styles) + list(self.fillstyles) + list(self.strokestyles):
80 result.extend(style.prolog())
81 result.extend(self.subcanvas.prolog())
82 return result
84 def outputPS(self, file):
85 # draw (stroke and/or fill) the decoratedpath on the canvas
86 # while trying to produce an efficient output, e.g., by
87 # not writing one path two times
89 # small helper
90 def _writestyles(styles, file=file):
91 for style in styles:
92 style.outputPS(file)
94 # apply global styles
95 if self.styles:
96 file.write("gsave\n")
97 _writestyles(self.styles)
99 if self.fillpath is not None:
100 file.write("newpath\n")
101 self.fillpath.outputPS(file)
103 if self.strokepath==self.fillpath:
104 # do efficient stroking + filling
105 file.write("gsave\n")
107 if self.fillstyles:
108 _writestyles(self.fillstyles)
110 file.write("fill\n")
111 file.write("grestore\n")
113 if self.strokestyles:
114 file.write("gsave\n")
115 _writestyles(self.strokestyles)
117 file.write("stroke\n")
119 if self.strokestyles:
120 file.write("grestore\n")
121 else:
122 # only fill fillpath - for the moment
123 if self.fillstyles:
124 file.write("gsave\n")
125 _writestyles(self.fillstyles)
127 file.write("fill\n")
129 if self.fillstyles:
130 file.write("grestore\n")
132 if self.strokepath is not None and self.strokepath!=self.fillpath:
133 # this is the only relevant case still left
134 # Note that a possible stroking has already been done.
136 if self.strokestyles:
137 file.write("gsave\n")
138 _writestyles(self.strokestyles)
140 file.write("newpath\n")
141 self.strokepath.outputPS(file)
142 file.write("stroke\n")
144 if self.strokestyles:
145 file.write("grestore\n")
147 if self.strokepath is None and self.fillpath is None:
148 raise RuntimeError("Path neither to be stroked nor filled")
150 # now, draw additional elements of decoratedpath
151 self.subcanvas.outputPS(file)
153 # restore global styles
154 if self.styles:
155 file.write("grestore\n")
157 def outputPDF(self, file):
158 # draw (stroke and/or fill) the decoratedpath on the canvas
160 def _writestyles(styles, file=file):
161 for style in styles:
162 style.outputPDF(file)
164 def _writestrokestyles(strokestyles, file=file):
165 for style in strokestyles:
166 if isinstance(style, color.color):
167 style.outputPDF(file, fillattr=0)
168 else:
169 style.outputPDF(file)
171 def _writefillstyles(fillstyles, file=file):
172 for style in fillstyles:
173 if isinstance(style, color.color):
174 style.outputPDF(file, strokeattr=0)
175 else:
176 style.outputPDF(file)
178 # apply global styles
179 if self.styles:
180 file.write("q\n") # gsave
181 _writestyles(self.styles)
183 if self.fillpath is not None:
184 self.fillpath.outputPDF(file)
186 if self.strokepath==self.fillpath:
187 # do efficient stroking + filling
188 file.write("q\n") # gsave
190 if self.fillstyles:
191 _writefillstyles(self.fillstyles)
192 if self.strokestyles:
193 _writestrokestyles(self.strokestyles)
195 file.write("B\n") # both stroke and fill
196 file.write("Q\n") # grestore
197 else:
198 # only fill fillpath - for the moment
199 if self.fillstyles:
200 file.write("q\n") # gsave
201 _writefillstyles(self.fillstyles)
203 file.write("f\n") # fill
205 if self.fillstyles:
206 file.write("Q\n") # grestore
208 if self.strokepath is not None and self.strokepath!=self.fillpath:
209 # this is the only relevant case still left
210 # Note that a possible stroking has already been done.
212 if self.strokestyles:
213 file.write("q\n") # gsave
214 _writestrokestyles(self.strokestyles)
216 self.strokepath.outputPDF(file)
217 file.write("S\n") # stroke
219 if self.strokestyles:
220 file.write("Q\n") # grestore
222 if self.strokepath is None and self.fillpath is None:
223 raise RuntimeError("Path neither to be stroked nor filled")
225 # now, draw additional elements of decoratedpath
226 self.subcanvas.outputPDF(file)
228 # restore global styles
229 if self.styles:
230 file.write("Q\n") # grestore
233 # Path decorators
236 class deco:
238 """decorators
240 In contrast to path styles, path decorators depend on the concrete
241 path to which they are applied. In particular, they don't make
242 sense without any path and can thus not be used in canvas.set!
246 def decorate(self, dp):
247 """apply a style to a given decoratedpath object dp
249 decorate accepts a decoratedpath object dp, applies PathStyle
250 by modifying dp in place and returning the new dp.
253 pass
256 # stroked and filled: basic decos which stroked and fill,
257 # respectively the path
260 class _stroked(deco, attr.exclusiveattr):
262 """stroked is a decorator, which draws the outline of the path"""
264 def __init__(self, styles=[]):
265 attr.exclusiveattr.__init__(self, _stroked)
266 self.styles = attr.mergeattrs(styles)
267 attr.checkattrs(self.styles, [style.strokestyle])
269 def __call__(self, styles=[]):
270 # XXX or should we also merge self.styles
271 return _stroked(styles)
273 def decorate(self, dp):
274 dp.strokepath = dp.path
275 dp.strokestyles = self.styles
276 return dp
278 stroked = _stroked()
279 stroked.clear = attr.clearclass(_stroked)
282 class _filled(deco, attr.exclusiveattr):
284 """filled is a decorator, which fills the interior of the path"""
286 def __init__(self, styles=[]):
287 attr.exclusiveattr.__init__(self, _filled)
288 self.styles = attr.mergeattrs(styles)
289 attr.checkattrs(self.styles, [style.fillstyle])
291 def __call__(self, styles=[]):
292 # XXX or should we also merge self.styles
293 return _filled(styles)
295 def decorate(self, dp):
296 dp.fillpath = dp.path
297 dp.fillstyles = self.styles
298 return dp
300 filled = _filled()
301 filled.clear = attr.clearclass(_filled)
304 # Arrows
307 # two helper functions which construct the arrowhead and return its size, respectively
309 def _arrowheadtemplatelength(anormpath, size):
310 "calculate length of arrowhead template (in parametrisation of anormpath)"
311 # get tip (tx, ty)
312 tx, ty = anormpath.begin()
314 # obtain arrow template by using path up to first intersection
315 # with circle around tip (as suggested by Michael Schindler)
316 ipar = anormpath.intersect(path.circle(tx, ty, size))
317 if ipar[0]:
318 alen = ipar[0][0]
319 else:
320 # if this doesn't work, use first order conversion from pts to
321 # the bezier curve's parametrization
322 tvec = anormpath.tangent(0)
323 tlen = tvec.arclen_pt()
324 try:
325 alen = unit.topt(size)/tlen
326 except ArithmeticError:
327 # take maximum, we can get
328 alen = anormpath.range()
329 if alen > anormpath.range(): alen = anormpath.range()
331 return alen
334 def _arrowhead(anormpath, size, angle, constriction):
336 """helper routine, which returns an arrowhead for a normpath
338 returns arrowhead at begin of anormpath with size,
339 opening angle and relative constriction
342 alen = _arrowheadtemplatelength(anormpath, size)
343 tx, ty = anormpath.begin()
345 # now we construct the template for our arrow but cutting
346 # the path a the corresponding length
347 arrowtemplate = anormpath.split([alen])[0]
349 # from this template, we construct the two outer curves
350 # of the arrow
351 arrowl = arrowtemplate.transformed(trafo.rotate(-angle/2.0, tx, ty))
352 arrowr = arrowtemplate.transformed(trafo.rotate( angle/2.0, tx, ty))
354 # now come the joining backward parts
355 if constriction:
356 # arrow with constriction
358 # constriction point (cx, cy) lies on path
359 cx, cy = anormpath.at(constriction*alen)
361 arrowcr= path.line(*(arrowr.end()+(cx,cy)))
363 arrow = arrowl.reversed() << arrowr << arrowcr
364 arrow.append(path.closepath())
365 else:
366 # arrow without constriction
367 arrow = arrowl.reversed() << arrowr
368 arrow.append(path.closepath())
370 return arrow
373 _base = unit.v_pt(6)
375 class arrow(deco, attr.attr):
377 """arrow is a decorator which adds an arrow to either side of the path"""
379 def __init__(self, attrs=[], position=0, size=_base, angle=45, constriction=0.8):
380 self.attrs = attr.mergeattrs([style.linestyle.solid, filled] + attrs)
381 attr.checkattrs(self.attrs, [deco, style.fillstyle, style.strokestyle])
382 self.position = position
383 self.size = unit.length(size, default_type="v")
384 self.angle = angle
385 self.constriction = constriction
387 def __call__(self, attrs=None, position=None, size=None, angle=None, constriction=None):
388 if attrs is None:
389 attrs = self.attrs
390 if position is None:
391 position = self.position
392 if size is None:
393 size = self.size
394 if angle is None:
395 angle = self.angle
396 if constriction is None:
397 constriction = self.constriction
398 return arrow(attrs=attrs, position=position, size=size, angle=angle, constriction=constriction)
400 def decorate(self, dp):
401 # XXX raise exception error, when strokepath is not defined
403 # convert to normpath if necessary
404 if isinstance(dp.strokepath, path.normpath):
405 anormpath = dp.strokepath
406 else:
407 anormpath = path.normpath(dp.path)
408 if self.position:
409 anormpath = anormpath.reversed()
411 # add arrowhead to decoratedpath
412 dp.subcanvas.draw(_arrowhead(anormpath, self.size, self.angle, self.constriction),
413 self.attrs)
415 # calculate new strokepath
416 alen = _arrowheadtemplatelength(anormpath, self.size)
417 if self.constriction:
418 ilen = alen*self.constriction
419 else:
420 ilen = alen
422 # correct somewhat for rotation of arrow segments
423 ilen = ilen*math.cos(math.pi*self.angle/360.0)
425 # this is the rest of the path, we have to draw
426 anormpath = anormpath.split([ilen])[1]
428 # go back to original orientation, if necessary
429 if self.position:
430 anormpath.reverse()
432 # set the new (shortened) strokepath
433 dp.strokepath = anormpath
435 return dp
437 arrow.clear = attr.clearclass(arrow)
439 # arrows at begin of path
440 barrow = arrow(position=0)
441 barrow.SMALL = barrow(size=_base/math.sqrt(64))
442 barrow.SMALl = barrow(size=_base/math.sqrt(32))
443 barrow.SMAll = barrow(size=_base/math.sqrt(16))
444 barrow.SMall = barrow(size=_base/math.sqrt(8))
445 barrow.Small = barrow(size=_base/math.sqrt(4))
446 barrow.small = barrow(size=_base/math.sqrt(2))
447 barrow.normal = barrow(size=_base)
448 barrow.large = barrow(size=_base*math.sqrt(2))
449 barrow.Large = barrow(size=_base*math.sqrt(4))
450 barrow.LArge = barrow(size=_base*math.sqrt(8))
451 barrow.LARge = barrow(size=_base*math.sqrt(16))
452 barrow.LARGe = barrow(size=_base*math.sqrt(32))
453 barrow.LARGE = barrow(size=_base*math.sqrt(64))
455 # arrows at end of path
456 earrow = arrow(position=1)
457 earrow.SMALL = earrow(size=_base/math.sqrt(64))
458 earrow.SMALl = earrow(size=_base/math.sqrt(32))
459 earrow.SMAll = earrow(size=_base/math.sqrt(16))
460 earrow.SMall = earrow(size=_base/math.sqrt(8))
461 earrow.Small = earrow(size=_base/math.sqrt(4))
462 earrow.small = earrow(size=_base/math.sqrt(2))
463 earrow.normal = earrow(size=_base)
464 earrow.large = earrow(size=_base*math.sqrt(2))
465 earrow.Large = earrow(size=_base*math.sqrt(4))
466 earrow.LArge = earrow(size=_base*math.sqrt(8))
467 earrow.LARge = earrow(size=_base*math.sqrt(16))
468 earrow.LARGe = earrow(size=_base*math.sqrt(32))
469 earrow.LARGE = earrow(size=_base*math.sqrt(64))
472 class wriggle(deco, attr.attr):
474 def __init__(self, skipleft=1, skipright=1, radius=0.5, loops=8, curvesperloop=10):
475 self.skipleft_str = skipleft
476 self.skipright_str = skipright
477 self.radius_str = radius
478 self.loops = loops
479 self.curvesperloop = curvesperloop
481 def decorate(self, dp):
482 # XXX: is this the correct way to select the basepath???!!!
483 if isinstance(dp.strokepath, path.normpath):
484 basepath = dp.strokepath
485 elif dp.strokepath is not None:
486 basepath = path.normpath(dp.strokepath)
487 elif isinstance(dp.path, path.normpath):
488 basepath = dp.path
489 else:
490 basepath = path.normpath(dp.path)
492 skipleft = unit.topt(unit.length(self.skipleft_str, default_type="v"))
493 skipright = unit.topt(unit.length(self.skipright_str, default_type="v"))
494 startpar, endpar = basepath.arclentoparam(map(unit.t_pt, [skipleft, basepath.arclen_pt() - skipright]))
495 radius = unit.topt(unit.length(self.radius_str))
497 # search for the first intersection of a circle around start point x, y bigger than startpar
498 x, y = basepath.at_pt(startpar)
499 startcircpar = None
500 for intersectpar in basepath.intersect(path.circle_pt(x, y, radius))[0]:
501 if startpar < intersectpar and (startcircpar is None or startcircpar > intersectpar):
502 startcircpar = intersectpar
503 if startcircpar is None:
504 raise RuntimeError("couldn't find wriggle start point")
505 # calculate start position and angle
506 xcenter, ycenter = basepath.at_pt(startcircpar)
507 startpos = basepath.split([startcircpar])[0].arclen_pt()
508 startangle = math.atan2(y-ycenter, x-xcenter)
510 # find the last intersection of a circle around x, y smaller than endpar
511 x, y = basepath.at_pt(endpar)
512 endcircpar = None
513 for intersectpar in basepath.intersect(path.circle_pt(x, y, radius))[0]:
514 if endpar > intersectpar and (endcircpar is None or endcircpar < intersectpar):
515 endcircpar = intersectpar
516 if endcircpar is None:
517 raise RuntimeError("couldn't find wriggle end point")
518 # calculate end position and angle
519 x2, y2 = basepath.at_pt(endcircpar)
520 endpos = basepath.split([endcircpar])[0].arclen_pt()
521 endangle = math.atan2(y-y2, x-x2)
523 if endangle < startangle:
524 endangle += 2*math.pi
526 # calculate basepath points
527 sections = self.loops * self.curvesperloop
528 posrange = endpos - startpos
529 poslist = [startpos + i*posrange/sections for i in range(sections+1)]
530 parlist = basepath.arclentoparam(map(unit.t_pt, poslist))
531 atlist = [basepath.at_pt(x) for x in parlist]
533 # from pyx import color
534 # for at in atlist:
535 # dp.subcanvas.stroke(path.circle_pt(at[0], at[1], 1), [color.rgb.blue])
537 # calculate wriggle points and tangents
538 anglerange = 2*math.pi*self.loops + endangle - startangle
539 deltaangle = anglerange / sections
540 tangentlength = radius * 4 * (1 - math.cos(deltaangle/2)) / (3 * math.sin(deltaangle/2))
541 wriggleat = [None]*(sections+1)
542 wriggletangentstart = [None]*(sections+1)
543 wriggletangentend = [None]*(sections+1)
544 for i in range(sections+1):
545 x, y = atlist[i]
546 angle = startangle + i*anglerange/sections
547 dx, dy = math.cos(angle), math.sin(angle)
548 wriggleat[i] = x + radius*dx, y + radius*dy
549 # dp.subcanvas.stroke(path.line_pt(x, y, x + radius*dx, y + radius*dy), [color.rgb.blue])
550 wriggletangentstart[i] = x + radius*dx + tangentlength*dy, y + radius*dy - tangentlength*dx
551 wriggletangentend[i] = x + radius*dx - tangentlength*dy, y + radius*dy + tangentlength*dx
553 # build wriggle path
554 wrigglepath = basepath.split([startpar])[0]
555 wrigglepath.append(path.multicurveto_pt([wriggletangentend[i-1] +
556 wriggletangentstart[i] +
557 wriggleat[i]
558 for i in range(1, sections+1)]))
559 wrigglepath = wrigglepath.glue(basepath.split([endpar])[1]) # glue and glued?!?
561 # store wriggle path
562 dp.path = wrigglepath # otherwise the bbox is wrong!
563 dp.strokepath = wrigglepath
564 return dp
567 class smoothed(deco, attr.attr):
569 """Bends corners in a path.
571 This decorator replaces corners in a path with bezier curves. There are two cases:
572 - If the corner lies between two lines, _two_ bezier curves will be used
573 that are highly optimized to look good (their curvature is to be zero at the ends
574 and has to have zero derivative in the middle).
575 Additionally, it can controlled by the softness-parameter.
576 - If the corner lies between curves then _one_ bezier is used that is (except in some
577 special cases) uniquely determined by the tangents and curvatures at its end-points.
578 In some cases it is necessary to use only the absolute value of the curvature to avoid a
579 cusp-shaped connection of the new bezier to the old path. In this case the use of
580 "strict=0" allows the sign of the curvature to switch.
581 - The radius argument gives the arclength-distance of the corner to the points where the
582 old path is cut and the beziers are inserted.
583 - Path elements that are too short (shorter than the radius) are skipped
586 def __init__(self, radius, softness=1, strict=0):
587 self.radius = unit.length(radius, default_type="v")
588 self.softness = softness
589 self.strict = strict
591 def _twobeziersbetweentolines(self, B, tangent1, tangent2, r1, r2, softness=1):
592 # Takes the corner B
593 # and two tangent vectors heading to and from B
594 # and two radii r1 and r2:
595 # All arguments must be in Points
596 # Returns the seven control points of the two bezier curves:
597 # - start d1
598 # - control points g1 and f1
599 # - midpoint e
600 # - control points f2 and g2
601 # - endpoint d2
603 # make direction vectors d1: from B to A
604 # d2: from B to C
605 d1 = -tangent1[0] / math.hypot(*tangent1), -tangent1[1] / math.hypot(*tangent1)
606 d2 = tangent2[0] / math.hypot(*tangent2), tangent2[1] / math.hypot(*tangent2)
608 # 0.3192 has turned out to be the maximum softness available
609 # for straight lines ;-)
610 f = 0.3192 * softness
611 g = (15.0 * f + math.sqrt(-15.0*f*f + 24.0*f))/12.0
613 # make the control points
614 f1 = B[0] + f * r1 * d1[0], B[1] + f * r1 * d1[1]
615 f2 = B[0] + f * r2 * d2[0], B[1] + f * r2 * d2[1]
616 g1 = B[0] + g * r1 * d1[0], B[1] + g * r1 * d1[1]
617 g2 = B[0] + g * r2 * d2[0], B[1] + g * r2 * d2[1]
618 d1 = B[0] + r1 * d1[0], B[1] + r1 * d1[1]
619 d2 = B[0] + r2 * d2[0], B[1] + r2 * d2[1]
620 e = 0.5 * (f1[0] + f2[0]), 0.5 * (f1[1] + f2[1])
622 return [d1, g1, f1, e, f2, g2, d2]
624 def _onebezierbetweentwopathels(self, A, B, tangentA, tangentB, curvA, curvB, strict=0):
625 # connects points A and B with a bezier curve that has
626 # prescribed tangents dirA, dirB and curvatures curA, curB.
627 # If strict, the sign of the curvature will be forced which may invert
628 # the sign of the tangents. If not strict, the sign of the curvature may
629 # be switched but the tangent may not.
631 def sign(x):
632 try: return abs(a) / a
633 except ZeroDivisionError: return 0
635 # normalise the tangent vectors
636 dirA = (tangentA[0] / math.hypot(*tangentA), tangentA[1] / math.hypot(*tangentA))
637 dirB = (tangentB[0] / math.hypot(*tangentB), tangentB[1] / math.hypot(*tangentB))
638 # some shortcuts
639 T = dirA[0] * dirB[1] - dirA[1] * dirB[0]
640 D = 3 * (dirA[0] * (B[1]-A[1]) - dirA[1] * (B[0]-A[0]))
641 E = 3 * (dirB[0] * (B[1]-A[1]) - dirB[1] * (B[0]-A[0]))
642 # the variables: \dot X(0) = a * dirA
643 # \dot X(1) = b * dirB
644 a, b = None, None
646 # ask for some special cases:
647 # Newton iteration is likely to fail if T==0 or curvA,curvB==0
648 if abs(T) < 1e-10:
649 try:
650 a = 2.0 * D / curvA
651 a = math.sqrt(abs(a)) * sign(a)
652 b = -2.0 * E / curvB
653 b = math.sqrt(abs(b)) * sign(b)
654 except ZeroDivisionError:
655 sys.stderr.write("*** PyX Warning: The connecting bezier is not uniquely determined."
656 "The simple heuristic solution may not be optimal.")
657 a = b = 1.5 * hypot(A[0] - B[0], A[1] - B[1])
658 else:
659 if abs(curvA) < 1.0e-4:
660 b = D / T
661 a = - (E + b*abs(b)*curvB*0.5) / T
662 elif abs(curvB) < 1.0e-4:
663 a = -E / T
664 b = (D - a*abs(a)*curvA*0.5) / T
665 else:
666 a, b = None, None
668 # do the general case: Newton iteration
669 if a is None:
670 # solve the coupled system
671 # 0 = Ga(a,b) = 0.5 a |a| curvA + b * T - D
672 # 0 = Gb(a,b) = 0.5 b |b| curvB + a * T + E
673 # this system is equivalent to the geometric contraints:
674 # the curvature and the normal tangent vectors
675 # at parameters 0 and 1 are to be continuous
676 # the system is solved by 2-dim Newton-Iteration
677 # (a,b)^{i+1} = (a,b)^i - (DG)^{-1} (Ga(a^i,b^i), Gb(a^i,b^i))
678 a = b = 0
679 Ga = Gb = 1
680 while max(abs(Ga),abs(Gb)) > 1.0e-5:
681 detDG = abs(a*b) * curvA*curvB - T*T
682 invDG = [[curvB*abs(b)/detDG, -T/detDG], [-T/detDG, curvA*abs(a)/detDG]]
684 Ga = a*abs(a)*curvA*0.5 + b*T - D
685 Gb = b*abs(b)*curvB*0.5 + a*T + E
687 a, b = a - invDG[0][0]*Ga - invDG[0][1]*Gb, b - invDG[1][0]*Ga - invDG[1][1]*Gb
689 # the curvature may change its sign if we would get a cusp
690 # in the optimal case we have a>0 and b>0
691 if not strict:
692 a, b = abs(a), abs(b)
694 return [A, (A[0] + a * dirA[0] / 3.0, A[1] + a * dirA[1] / 3.0),
695 (B[0] - b * dirB[0] / 3.0, B[1] - b * dirB[1] / 3.0), B]
698 def decorate(self, dp):
699 radius = unit.topt(self.radius)
700 # XXX: is this the correct way to select the basepath???!!!
701 # compare to wriggle()
702 if isinstance(dp.strokepath, path.normpath):
703 basepath = dp.strokepath
704 elif dp.strokepath is not None:
705 basepath = path.normpath(dp.strokepath)
706 elif isinstance(dp.path, path.normpath):
707 basepath = dp.path
708 else:
709 basepath = path.normpath(dp.path)
711 newpath = path.path()
712 for normsubpath in basepath.subpaths:
713 npels = normsubpath.normpathels
714 arclens = [npel.arclen_pt() for npel in npels]
716 # 1. Build up a list of all relevant normpathels
717 # and the lengths where they will be cut (length with respect to the normsubpath)
718 npelnumbers = []
719 cumalen = 0
720 for no in range(len(arclens)):
721 alen = arclens[no]
722 # a first selection criterion for skipping too short normpathels
723 # the rest will queeze the radius
724 if alen > radius:
725 npelnumbers.append(no)
726 else:
727 sys.stderr.write("*** PyX Warning: smoothed is skipping a normpathel that is too short\n")
728 cumalen += alen
729 # XXX: what happens, if 0 or -1 is skipped and path not closed?
731 # 2. Find the parameters, points,
732 # and calculate tangents and curvatures
733 params, tangents, curvatures, points = [], [], [], []
734 for no in npelnumbers:
735 npel = npels[no]
736 alen = arclens[no]
738 # find the parameter(s): either one or two
739 if no is npelnumbers[0] and not normsubpath.closed:
740 pars = npel._arclentoparam_pt([max(0, alen - radius)])[0]
741 elif alen > 2 * radius:
742 pars = npel._arclentoparam_pt([radius, alen - radius])[0]
743 else:
744 pars = npel._arclentoparam_pt([0.5 * alen])[0]
746 # find points, tangents and curvatures
747 ts,cs,ps = [],[],[]
748 for par in pars:
749 # XXX: there is no trafo method for normpathels?
750 thetrafo = normsubpath.trafo(par + no)
751 p = thetrafo._apply(0,0)
752 t = thetrafo._apply(1,0)
753 ps.append(p)
754 ts.append((t[0]-p[0], t[1]-p[1]))
755 c = npel.curvradius_pt(par)
756 if c is None: cs.append(0)
757 else: cs.append(1.0/c)
758 #dp.subcanvas.stroke(path.circle_pt(p[0], p[1], 3), [color.grey.black, style.linewidth.THin])
759 #dp.subcanvas.stroke(path.line_pt(p[0], p[1], p[0] + 10*(t[0]-p[0]), p[1] + 10*(t[1]-p[1])), [color.grey.black, earrow.small, style.linewidth.THin])
761 params.append(pars)
762 points.append(ps)
763 tangents.append(ts)
764 curvatures.append(cs)
766 do_moveto = 1 # we do not know yet where to moveto
767 # 3. First part of extra handling of closed paths
768 if not normsubpath.closed:
769 bpart = npels[npelnumbers[0]].split(params[0])[0]
770 if do_moveto:
771 newpath.append(path.moveto_pt(*bpart.begin_pt()))
772 do_moveto = 0
773 if isinstance(bpart, path.normline):
774 newpath.append(path.lineto_pt(*bpart.end_pt()))
775 elif isinstance(bpart, path.normcurve):
776 newpath.append(path.curveto_pt(bpart.x1, bpart.y1, bpart.x2, bpart.y2, bpart.x3, bpart.y3))
777 do_moveto = 0
779 # 4. Do the splitting for the first to the last element,
780 # a closed path must be closed later
781 for i in range(len(npelnumbers)-1+(normsubpath.closed==1)):
782 this = npelnumbers[i]
783 next = npelnumbers[(i+1) % len(npelnumbers)]
784 thisnpel, nextnpel = npels[this], npels[next]
786 # split thisnpel apart and take the middle peace
787 if len(points[this]) == 2:
788 mpart = thisnpel.split(params[this])[1]
789 if do_moveto:
790 newpath.append(path.moveto_pt(*mpart.begin_pt()))
791 do_moveto = 0
792 if isinstance(mpart, path.normline):
793 newpath.append(path.lineto_pt(*mpart.end_pt()))
794 elif isinstance(mpart, path.normcurve):
795 newpath.append(path.curveto_pt(mpart.x1, mpart.y1, mpart.x2, mpart.y2, mpart.x3, mpart.y3))
797 # add the curve(s) replacing the corner
798 if isinstance(thisnpel, path.normline) and isinstance(nextnpel, path.normline) \
799 and (next-this == 1 or (this==0 and next==len(npels)-1)):
800 d1,g1,f1,e,f2,g2,d2 = self._twobeziersbetweentolines(
801 thisnpel.end_pt(), tangents[this][-1], tangents[next][0],
802 math.hypot(points[this][-1][0] - thisnpel.end_pt()[0], points[this][-1][1] - thisnpel.end_pt()[1]),
803 math.hypot(points[next][0][0] - nextnpel.begin_pt()[0], points[next][0][1] - nextnpel.begin_pt()[1]),
804 softness=self.softness)
805 if do_moveto:
806 newpath.append(path.moveto_pt(*d1))
807 do_moveto = 0
808 newpath.append(path.curveto_pt(*(g1 + f1 + e)))
809 newpath.append(path.curveto_pt(*(f2 + g2 + d2)))
810 else:
811 #dp.subcanvas.fill(path.circle_pt(points[next][0][0], points[next][0][1], 2))
812 if not self.strict:
813 # the curvature may have the wrong sign -- produce a heuristic for the sign:
814 vx, vy = thisnpel.end_pt()[0] - points[this][-1][0], thisnpel.end_pt()[1] - points[this][-1][1]
815 wx, wy = points[next][0][0] - thisnpel.end_pt()[0], points[next][0][1] - thisnpel.end_pt()[1]
816 sign = vx * wy - vy * wx
817 sign = sign / abs(sign)
818 curvatures[this][-1] = sign * abs(curvatures[this][-1])
819 curvatures[next][0] = sign * abs(curvatures[next][0])
820 A,B,C,D = self._onebezierbetweentwopathels(
821 points[this][-1], points[next][0], tangents[this][-1], tangents[next][0],
822 curvatures[this][-1], curvatures[next][0], strict=self.strict)
823 if do_moveto:
824 newpath.append(path.moveto_pt(*A))
825 do_moveto = 0
826 newpath.append(path.curveto_pt(*(B + C + D)))
828 # 5. Second part of extra handling of closed paths
829 if normsubpath.closed:
830 if do_moveto:
831 newpath.append(path.moveto_pt(*dp.strokepath.begin()))
832 sys.stderr.write("*** PyXWarning: The whole path has been smoothed away -- sorry\n")
833 newpath.append(path.closepath())
834 else:
835 epart = npels[npelnumbers[-1]].split([params[-1][0]])[-1]
836 if do_moveto:
837 newpath.append(path.moveto_pt(*epart.begin_pt()))
838 do_moveto = 0
839 if isinstance(epart, path.normline):
840 newpath.append(path.lineto_pt(*epart.end_pt()))
841 elif isinstance(epart, path.normcurve):
842 newpath.append(path.curveto_pt(epart.x1, epart.y1, epart.x2, epart.y2, epart.x3, epart.y3))
844 dp.strokepath = newpath
845 return dp
847 smoothed.clear = attr.clearclass(smoothed)
849 _base = 1
850 smoothed.SHARP = smoothed(radius="%f cm" % (_base/math.sqrt(64)))
851 smoothed.SHARp = smoothed(radius="%f cm" % (_base/math.sqrt(32)))
852 smoothed.SHArp = smoothed(radius="%f cm" % (_base/math.sqrt(16)))
853 smoothed.SHarp = smoothed(radius="%f cm" % (_base/math.sqrt(8)))
854 smoothed.Sharp = smoothed(radius="%f cm" % (_base/math.sqrt(4)))
855 smoothed.sharp = smoothed(radius="%f cm" % (_base/math.sqrt(2)))
856 smoothed.normal = smoothed(radius="%f cm" % (_base))
857 smoothed.round = smoothed(radius="%f cm" % (_base*math.sqrt(2)))
858 smoothed.Round = smoothed(radius="%f cm" % (_base*math.sqrt(4)))
859 smoothed.ROund = smoothed(radius="%f cm" % (_base*math.sqrt(8)))
860 smoothed.ROUnd = smoothed(radius="%f cm" % (_base*math.sqrt(16)))
861 smoothed.ROUNd = smoothed(radius="%f cm" % (_base*math.sqrt(32)))
862 smoothed.ROUND = smoothed(radius="%f cm" % (_base*math.sqrt(64)))