2 # -*- coding: ISO-8859-1 -*-
5 # Copyright (C) 2002-2005 Jörg Lehmann <joergl@users.sourceforge.net>
6 # Copyright (C) 2003-2004 Michael Schindler <m-schindler@users.sourceforge.net>
7 # Copyright (C) 2002-2005 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
25 from __future__
import nested_scopes
29 from math
import radians
, degrees
31 # fallback implementation for Python 2.1
32 def radians(x
): return x
*math
.pi
/180
33 def degrees(x
): return x
*180/math
.pi
35 import bbox
, canvas
, path
, trafo
, unit
40 # fallback implementation for Python 2.2 and below
42 return reduce(lambda x
, y
: x
+y
, list, 0)
47 # fallback implementation for Python 2.2 and below
49 return zip(xrange(len(list)), list)
51 # use new style classes when possible
56 ################################################################################
58 # global epsilon (default precision of normsubpaths)
61 def set(epsilon
=None):
63 if epsilon
is not None:
67 ################################################################################
69 ################################################################################
71 class normsubpathitem
:
73 """element of a normalized sub path
75 Various operations on normsubpathitems might be subject of
76 approximitions. Those methods get the finite precision epsilon,
77 which is the accuracy needed expressed as a length in pts.
79 normsubpathitems should never be modified inplace, since references
80 might be shared betweeen several normsubpaths.
83 def arclen_pt(self
, epsilon
):
84 """return arc length in pts"""
87 def _arclentoparam_pt(self
, lengths_pt
, epsilon
):
88 """return a tuple of params and the total length arc length in pts"""
91 def arclentoparam_pt(self
, lengths_pt
, epsilon
):
92 """return a tuple of params"""
95 def at_pt(self
, params
):
96 """return coordinates at params in pts"""
100 """return coordinates of first point in pts"""
104 """return coordinates of last point in pts"""
108 """return bounding box of normsubpathitem"""
112 """return control box of normsubpathitem
114 The control box also fully encloses the normsubpathitem but in the case of a Bezier
115 curve it is not the minimal box doing so. On the other hand, it is much faster
120 def curveradius_pt(self
, params
):
121 """return the curvature radius at params in pts
123 The curvature radius is the inverse of the curvature. When the
124 curvature is 0, None is returned. Note that this radius can be negative
125 or positive, depending on the sign of the curvature."""
128 def intersect(self
, other
, epsilon
):
129 """intersect self with other normsubpathitem"""
132 def modifiedbegin_pt(self
, x_pt
, y_pt
):
133 """return a normsubpathitem with a modified beginning point"""
136 def modifiedend_pt(self
, x_pt
, y_pt
):
137 """return a normsubpathitem with a modified end point"""
140 def _paramtoarclen_pt(self
, param
, epsilon
):
141 """return a tuple of arc lengths and the total arc length in pts"""
145 """return pathitem corresponding to normsubpathitem"""
148 """return reversed normsubpathitem"""
151 def rotation(self
, params
):
152 """return rotation trafos (i.e. trafos without translations) at params"""
155 def segments(self
, params
):
156 """return segments of the normsubpathitem
158 The returned list of normsubpathitems for the segments between
159 the params. params needs to contain at least two values.
163 def trafo(self
, params
):
164 """return transformations at params"""
166 def transformed(self
, trafo
):
167 """return transformed normsubpathitem according to trafo"""
170 def outputPS(self
, file, writer
, context
):
171 """write PS code corresponding to normsubpathitem to file"""
174 def outputPDF(self
, file, writer
, context
):
175 """write PDF code corresponding to normsubpathitem to file"""
179 class normline_pt(normsubpathitem
):
181 """Straight line from (x0_pt, y0_pt) to (x1_pt, y1_pt) (coordinates in pts)"""
183 __slots__
= "x0_pt", "y0_pt", "x1_pt", "y1_pt"
185 def __init__(self
, x0_pt
, y0_pt
, x1_pt
, y1_pt
):
192 return "normline_pt(%g, %g, %g, %g)" % (self
.x0_pt
, self
.y0_pt
, self
.x1_pt
, self
.y1_pt
)
194 def _arclentoparam_pt(self
, lengths_pt
, epsilon
):
195 # do self.arclen_pt inplace for performance reasons
196 l_pt
= math
.hypot(self
.x0_pt
-self
.x1_pt
, self
.y0_pt
-self
.y1_pt
)
197 return [length_pt
/l_pt
for length_pt
in lengths_pt
], l_pt
199 def arclentoparam_pt(self
, lengths_pt
, epsilon
):
200 """return a tuple of params"""
201 return self
._arclentoparam
_pt
(lengths_pt
, epsilon
)[0]
203 def arclen_pt(self
, epsilon
):
204 return math
.hypot(self
.x0_pt
-self
.x1_pt
, self
.y0_pt
-self
.y1_pt
)
206 def at_pt(self
, params
):
207 return [(self
.x0_pt
+(self
.x1_pt
-self
.x0_pt
)*t
, self
.y0_pt
+(self
.y1_pt
-self
.y0_pt
)*t
)
210 def atbegin_pt(self
):
211 return self
.x0_pt
, self
.y0_pt
214 return self
.x1_pt
, self
.y1_pt
217 return bbox
.bbox_pt(min(self
.x0_pt
, self
.x1_pt
), min(self
.y0_pt
, self
.y1_pt
),
218 max(self
.x0_pt
, self
.x1_pt
), max(self
.y0_pt
, self
.y1_pt
))
222 def curveradius_pt(self
, params
):
223 return [None] * len(params
)
225 def intersect(self
, other
, epsilon
):
226 if isinstance(other
, normline_pt
):
227 a_deltax_pt
= self
.x1_pt
- self
.x0_pt
228 a_deltay_pt
= self
.y1_pt
- self
.y0_pt
230 b_deltax_pt
= other
.x1_pt
- other
.x0_pt
231 b_deltay_pt
= other
.y1_pt
- other
.y0_pt
233 det
= 1.0 / (b_deltax_pt
* a_deltay_pt
- b_deltay_pt
* a_deltax_pt
)
234 except ArithmeticError:
237 ba_deltax0_pt
= other
.x0_pt
- self
.x0_pt
238 ba_deltay0_pt
= other
.y0_pt
- self
.y0_pt
240 a_t
= (b_deltax_pt
* ba_deltay0_pt
- b_deltay_pt
* ba_deltax0_pt
) * det
241 b_t
= (a_deltax_pt
* ba_deltay0_pt
- a_deltay_pt
* ba_deltax0_pt
) * det
243 # check for intersections out of bound
244 # TODO: we might allow for a small out of bound errors.
245 if not (0<=a_t
<=1 and 0<=b_t
<=1):
248 # return parameters of intersection
251 return [(s_t
, o_t
) for o_t
, s_t
in other
.intersect(self
, epsilon
)]
253 def modifiedbegin_pt(self
, x_pt
, y_pt
):
254 return normline_pt(x_pt
, y_pt
, self
.x1_pt
, self
.y1_pt
)
256 def modifiedend_pt(self
, x_pt
, y_pt
):
257 return normline_pt(self
.x0_pt
, self
.y0_pt
, x_pt
, y_pt
)
259 def _paramtoarclen_pt(self
, params
, epsilon
):
260 totalarclen_pt
= self
.arclen_pt(epsilon
)
261 arclens_pt
= [totalarclen_pt
* param
for param
in params
+ [1]]
262 return arclens_pt
[:-1], arclens_pt
[-1]
265 return path
.lineto_pt(self
.x1_pt
, self
.y1_pt
)
268 return normline_pt(self
.x1_pt
, self
.y1_pt
, self
.x0_pt
, self
.y0_pt
)
270 def rotation(self
, params
):
271 return [trafo
.rotate(degrees(math
.atan2(self
.y1_pt
-self
.y0_pt
, self
.x1_pt
-self
.x0_pt
)))]*len(params
)
273 def segments(self
, params
):
275 raise ValueError("at least two parameters needed in segments")
279 xr_pt
= self
.x0_pt
+ (self
.x1_pt
-self
.x0_pt
)*t
280 yr_pt
= self
.y0_pt
+ (self
.y1_pt
-self
.y0_pt
)*t
281 if xl_pt
is not None:
282 result
.append(normline_pt(xl_pt
, yl_pt
, xr_pt
, yr_pt
))
287 def trafo(self
, params
):
288 rotate
= trafo
.rotate(degrees(math
.atan2(self
.y1_pt
-self
.y0_pt
, self
.x1_pt
-self
.x0_pt
)))
289 return [trafo
.translate_pt(*at_pt
) * rotate
290 for param
, at_pt
in zip(params
, self
.at_pt(params
))]
292 def transformed(self
, trafo
):
293 return normline_pt(*(trafo
.apply_pt(self
.x0_pt
, self
.y0_pt
) + trafo
.apply_pt(self
.x1_pt
, self
.y1_pt
)))
295 def outputPS(self
, file, writer
, context
):
296 file.write("%g %g lineto\n" % (self
.x1_pt
, self
.y1_pt
))
298 def outputPDF(self
, file, writer
, context
):
299 file.write("%f %f l\n" % (self
.x1_pt
, self
.y1_pt
))
302 class normcurve_pt(normsubpathitem
):
304 """Bezier curve with control points x0_pt, y0_pt, x1_pt, y1_pt, x2_pt, y2_pt, x3_pt, y3_pt (coordinates in pts)"""
306 __slots__
= "x0_pt", "y0_pt", "x1_pt", "y1_pt", "x2_pt", "y2_pt", "x3_pt", "y3_pt"
308 def __init__(self
, x0_pt
, y0_pt
, x1_pt
, y1_pt
, x2_pt
, y2_pt
, x3_pt
, y3_pt
):
319 return "normcurve_pt(%g, %g, %g, %g, %g, %g, %g, %g)" % (self
.x0_pt
, self
.y0_pt
, self
.x1_pt
, self
.y1_pt
,
320 self
.x2_pt
, self
.y2_pt
, self
.x3_pt
, self
.y3_pt
)
322 def _midpointsplit(self
, epsilon
):
323 """split curve into two parts
325 Helper method to reduce the complexity of a problem by turning
326 a normcurve_pt into several normline_pt segments. This method
327 returns normcurve_pt instances only, when they are not yet straight
328 enough to be replaceable by normcurve_pt instances. Thus a recursive
329 midpointsplitting will turn a curve into line segments with the
330 given precision epsilon.
333 # first, we have to calculate the midpoints between adjacent
335 x01_pt
= 0.5*(self
.x0_pt
+ self
.x1_pt
)
336 y01_pt
= 0.5*(self
.y0_pt
+ self
.y1_pt
)
337 x12_pt
= 0.5*(self
.x1_pt
+ self
.x2_pt
)
338 y12_pt
= 0.5*(self
.y1_pt
+ self
.y2_pt
)
339 x23_pt
= 0.5*(self
.x2_pt
+ self
.x3_pt
)
340 y23_pt
= 0.5*(self
.y2_pt
+ self
.y3_pt
)
342 # In the next iterative step, we need the midpoints between 01 and 12
343 # and between 12 and 23
344 x01_12_pt
= 0.5*(x01_pt
+ x12_pt
)
345 y01_12_pt
= 0.5*(y01_pt
+ y12_pt
)
346 x12_23_pt
= 0.5*(x12_pt
+ x23_pt
)
347 y12_23_pt
= 0.5*(y12_pt
+ y23_pt
)
349 # Finally the midpoint is given by
350 xmidpoint_pt
= 0.5*(x01_12_pt
+ x12_23_pt
)
351 ymidpoint_pt
= 0.5*(y01_12_pt
+ y12_23_pt
)
353 # Before returning the normcurves we check whether we can
354 # replace them by normlines within an error of epsilon pts.
355 # The maximal error value is given by the modulus of the
356 # difference between the length of the control polygon
357 # (i.e. |P1-P0|+|P2-P1|+|P3-P2|), which consitutes an upper
358 # bound for the length, and the length of the straight line
359 # between start and end point of the normcurve (i.e. |P3-P1|),
360 # which represents a lower bound.
361 upperlen1
= (math
.hypot(x01_pt
- self
.x0_pt
, y01_pt
- self
.y0_pt
) +
362 math
.hypot(x01_12_pt
- x01_pt
, y01_12_pt
- y01_pt
) +
363 math
.hypot(xmidpoint_pt
- x01_12_pt
, ymidpoint_pt
- y01_12_pt
))
364 lowerlen1
= math
.hypot(xmidpoint_pt
- self
.x0_pt
, ymidpoint_pt
- self
.y0_pt
)
365 if upperlen1
-lowerlen1
< epsilon
:
366 c1
= normline_pt(self
.x0_pt
, self
.y0_pt
, xmidpoint_pt
, ymidpoint_pt
)
368 c1
= normcurve_pt(self
.x0_pt
, self
.y0_pt
,
370 x01_12_pt
, y01_12_pt
,
371 xmidpoint_pt
, ymidpoint_pt
)
373 upperlen2
= (math
.hypot(x12_23_pt
- xmidpoint_pt
, y12_23_pt
- ymidpoint_pt
) +
374 math
.hypot(x23_pt
- x12_23_pt
, y23_pt
- y12_23_pt
) +
375 math
.hypot(self
.x3_pt
- x23_pt
, self
.y3_pt
- y23_pt
))
376 lowerlen2
= math
.hypot(self
.x3_pt
- xmidpoint_pt
, self
.y3_pt
- ymidpoint_pt
)
377 if upperlen2
-lowerlen2
< epsilon
:
378 c2
= normline_pt(xmidpoint_pt
, ymidpoint_pt
, self
.x3_pt
, self
.y3_pt
)
380 c2
= normcurve_pt(xmidpoint_pt
, ymidpoint_pt
,
381 x12_23_pt
, y12_23_pt
,
383 self
.x3_pt
, self
.y3_pt
)
387 def _arclentoparam_pt(self
, lengths_pt
, epsilon
):
388 a
, b
= self
._midpointsplit
(epsilon
)
389 params_a
, arclen_a_pt
= a
._arclentoparam
_pt
(lengths_pt
, epsilon
)
390 params_b
, arclen_b_pt
= b
._arclentoparam
_pt
([length_pt
- arclen_a_pt
for length_pt
in lengths_pt
], epsilon
)
392 for param_a
, param_b
, length_pt
in zip(params_a
, params_b
, lengths_pt
):
393 if length_pt
> arclen_a_pt
:
394 params
.append(0.5+0.5*param_b
)
396 params
.append(0.5*param_a
)
397 return params
, arclen_a_pt
+ arclen_b_pt
399 def arclentoparam_pt(self
, lengths_pt
, epsilon
):
400 """return a tuple of params"""
401 return self
._arclentoparam
_pt
(lengths_pt
, epsilon
)[0]
403 def arclen_pt(self
, epsilon
):
404 a
, b
= self
._midpointsplit
(epsilon
)
405 return a
.arclen_pt(epsilon
) + b
.arclen_pt(epsilon
)
407 def at_pt(self
, params
):
408 return [( (-self
.x0_pt
+3*self
.x1_pt
-3*self
.x2_pt
+self
.x3_pt
)*t
*t
*t
+
409 (3*self
.x0_pt
-6*self
.x1_pt
+3*self
.x2_pt
)*t
*t
+
410 (-3*self
.x0_pt
+3*self
.x1_pt
)*t
+
412 (-self
.y0_pt
+3*self
.y1_pt
-3*self
.y2_pt
+self
.y3_pt
)*t
*t
*t
+
413 (3*self
.y0_pt
-6*self
.y1_pt
+3*self
.y2_pt
)*t
*t
+
414 (-3*self
.y0_pt
+3*self
.y1_pt
)*t
+
418 def atbegin_pt(self
):
419 return self
.x0_pt
, self
.y0_pt
422 return self
.x3_pt
, self
.y3_pt
425 xmin_pt
, xmax_pt
= path
._bezierpolyrange
(self
.x0_pt
, self
.x1_pt
, self
.x2_pt
, self
.x3_pt
)
426 ymin_pt
, ymax_pt
= path
._bezierpolyrange
(self
.y0_pt
, self
.y1_pt
, self
.y2_pt
, self
.y3_pt
)
427 return bbox
.bbox_pt(xmin_pt
, ymin_pt
, xmax_pt
, ymax_pt
)
430 return bbox
.bbox_pt(min(self
.x0_pt
, self
.x1_pt
, self
.x2_pt
, self
.x3_pt
),
431 min(self
.y0_pt
, self
.y1_pt
, self
.y2_pt
, self
.y3_pt
),
432 max(self
.x0_pt
, self
.x1_pt
, self
.x2_pt
, self
.x3_pt
),
433 max(self
.y0_pt
, self
.y1_pt
, self
.y2_pt
, self
.y3_pt
))
435 def curveradius_pt(self
, params
):
438 xdot
= ( 3 * (1-param
)*(1-param
) * (-self
.x0_pt
+ self
.x1_pt
) +
439 6 * (1-param
)*param
* (-self
.x1_pt
+ self
.x2_pt
) +
440 3 * param
*param
* (-self
.x2_pt
+ self
.x3_pt
) )
441 ydot
= ( 3 * (1-param
)*(1-param
) * (-self
.y0_pt
+ self
.y1_pt
) +
442 6 * (1-param
)*param
* (-self
.y1_pt
+ self
.y2_pt
) +
443 3 * param
*param
* (-self
.y2_pt
+ self
.y3_pt
) )
444 xddot
= ( 6 * (1-param
) * (self
.x0_pt
- 2*self
.x1_pt
+ self
.x2_pt
) +
445 6 * param
* (self
.x1_pt
- 2*self
.x2_pt
+ self
.x3_pt
) )
446 yddot
= ( 6 * (1-param
) * (self
.y0_pt
- 2*self
.y1_pt
+ self
.y2_pt
) +
447 6 * param
* (self
.y1_pt
- 2*self
.y2_pt
+ self
.y3_pt
) )
450 radius
= (xdot
**2 + ydot
**2)**1.5 / (xdot
*yddot
- ydot
*xddot
)
454 result
.append(radius
)
458 def intersect(self
, other
, epsilon
):
459 # There can be no intersection point, when the control boxes are not
460 # overlapping. Note that we use the control box instead of the bounding
461 # box here, because the former can be calculated more efficiently for
463 if not self
.cbox().intersects(other
.cbox()):
465 a
, b
= self
._midpointsplit
(epsilon
)
466 # To improve the performance in the general case we alternate the
467 # splitting process between the two normsubpathitems
468 return ( [( 0.5*a_t
, o_t
) for o_t
, a_t
in other
.intersect(a
, epsilon
)] +
469 [(0.5+0.5*b_t
, o_t
) for o_t
, b_t
in other
.intersect(b
, epsilon
)] )
471 def modifiedbegin_pt(self
, x_pt
, y_pt
):
472 return normcurve_pt(x_pt
, y_pt
,
473 self
.x1_pt
, self
.y1_pt
,
474 self
.x2_pt
, self
.y2_pt
,
475 self
.x3_pt
, self
.y3_pt
)
477 def modifiedend_pt(self
, x_pt
, y_pt
):
478 return normcurve_pt(self
.x0_pt
, self
.y0_pt
,
479 self
.x1_pt
, self
.y1_pt
,
480 self
.x2_pt
, self
.y2_pt
,
483 def _paramtoarclen_pt(self
, params
, epsilon
):
484 arclens_pt
= [segment
.arclen_pt(epsilon
) for segment
in self
.segments([0] + list(params
) + [1])]
485 for i
in range(1, len(arclens_pt
)):
486 arclens_pt
[i
] += arclens_pt
[i
-1]
487 return arclens_pt
[:-1], arclens_pt
[-1]
490 return path
.curveto_pt(self
.x1_pt
, self
.y1_pt
, self
.x2_pt
, self
.y2_pt
, self
.x3_pt
, self
.y3_pt
)
493 return normcurve_pt(self
.x3_pt
, self
.y3_pt
, self
.x2_pt
, self
.y2_pt
, self
.x1_pt
, self
.y1_pt
, self
.x0_pt
, self
.y0_pt
)
495 def rotation(self
, params
):
498 tdx_pt
= (3*( -self
.x0_pt
+3*self
.x1_pt
-3*self
.x2_pt
+self
.x3_pt
)*param
*param
+
499 2*( 3*self
.x0_pt
-6*self
.x1_pt
+3*self
.x2_pt
)*param
+
500 (-3*self
.x0_pt
+3*self
.x1_pt
))
501 tdy_pt
= (3*( -self
.y0_pt
+3*self
.y1_pt
-3*self
.y2_pt
+self
.y3_pt
)*param
*param
+
502 2*( 3*self
.y0_pt
-6*self
.y1_pt
+3*self
.y2_pt
)*param
+
503 (-3*self
.y0_pt
+3*self
.y1_pt
))
504 if math
.hypot(tdx_pt
, tdy_pt
) > 1e-5 or 1:
505 result
.append(trafo
.rotate(degrees(math
.atan2(tdy_pt
, tdx_pt
))))
507 # use rule of l'Hopital instead
508 t2dx_pt
= (6*( -self
.x0_pt
+3*self
.x1_pt
-3*self
.x2_pt
+self
.x3_pt
)*param
+
509 2*( 3*self
.x0_pt
-6*self
.x1_pt
+3*self
.x2_pt
))
510 t2dy_pt
= (6*( -self
.y0_pt
+3*self
.y1_pt
-3*self
.y2_pt
+self
.y3_pt
)*param
+
511 2*( 3*self
.y0_pt
-6*self
.y1_pt
+3*self
.y2_pt
))
512 result
.append(trafo
.rotate(degrees(math
.atan2(t2dy_pt
, t2dx_pt
))))
515 def segments(self
, params
):
517 raise ValueError("at least two parameters needed in segments")
519 # first, we calculate the coefficients corresponding to our
520 # original bezier curve. These represent a useful starting
521 # point for the following change of the polynomial parameter
524 a1x_pt
= 3*(-self
.x0_pt
+self
.x1_pt
)
525 a1y_pt
= 3*(-self
.y0_pt
+self
.y1_pt
)
526 a2x_pt
= 3*(self
.x0_pt
-2*self
.x1_pt
+self
.x2_pt
)
527 a2y_pt
= 3*(self
.y0_pt
-2*self
.y1_pt
+self
.y2_pt
)
528 a3x_pt
= -self
.x0_pt
+3*(self
.x1_pt
-self
.x2_pt
)+self
.x3_pt
529 a3y_pt
= -self
.y0_pt
+3*(self
.y1_pt
-self
.y2_pt
)+self
.y3_pt
533 for i
in range(len(params
)-1):
539 # the new coefficients of the [t1,t1+dt] part of the bezier curve
540 # are then given by expanding
541 # a0 + a1*(t1+dt*u) + a2*(t1+dt*u)**2 +
542 # a3*(t1+dt*u)**3 in u, yielding
544 # a0 + a1*t1 + a2*t1**2 + a3*t1**3 +
545 # ( a1 + 2*a2 + 3*a3*t1**2 )*dt * u +
546 # ( a2 + 3*a3*t1 )*dt**2 * u**2 +
549 # from this values we obtain the new control points by inversion
551 # TODO: we could do this more efficiently by reusing for
552 # (x0_pt, y0_pt) the control point (x3_pt, y3_pt) from the previous
555 x0_pt
= a0x_pt
+ a1x_pt
*t1
+ a2x_pt
*t1
*t1
+ a3x_pt
*t1
*t1
*t1
556 y0_pt
= a0y_pt
+ a1y_pt
*t1
+ a2y_pt
*t1
*t1
+ a3y_pt
*t1
*t1
*t1
557 x1_pt
= (a1x_pt
+2*a2x_pt
*t1
+3*a3x_pt
*t1
*t1
)*dt
/3.0 + x0_pt
558 y1_pt
= (a1y_pt
+2*a2y_pt
*t1
+3*a3y_pt
*t1
*t1
)*dt
/3.0 + y0_pt
559 x2_pt
= (a2x_pt
+3*a3x_pt
*t1
)*dt
*dt
/3.0 - x0_pt
+ 2*x1_pt
560 y2_pt
= (a2y_pt
+3*a3y_pt
*t1
)*dt
*dt
/3.0 - y0_pt
+ 2*y1_pt
561 x3_pt
= a3x_pt
*dt
*dt
*dt
+ x0_pt
- 3*x1_pt
+ 3*x2_pt
562 y3_pt
= a3y_pt
*dt
*dt
*dt
+ y0_pt
- 3*y1_pt
+ 3*y2_pt
564 result
.append(normcurve_pt(x0_pt
, y0_pt
, x1_pt
, y1_pt
, x2_pt
, y2_pt
, x3_pt
, y3_pt
))
568 def trafo(self
, params
):
570 for param
, at_pt
in zip(params
, self
.at_pt(params
)):
571 tdx_pt
= (3*( -self
.x0_pt
+3*self
.x1_pt
-3*self
.x2_pt
+self
.x3_pt
)*param
*param
+
572 2*( 3*self
.x0_pt
-6*self
.x1_pt
+3*self
.x2_pt
)*param
+
573 (-3*self
.x0_pt
+3*self
.x1_pt
))
574 tdy_pt
= (3*( -self
.y0_pt
+3*self
.y1_pt
-3*self
.y2_pt
+self
.y3_pt
)*param
*param
+
575 2*( 3*self
.y0_pt
-6*self
.y1_pt
+3*self
.y2_pt
)*param
+
576 (-3*self
.y0_pt
+3*self
.y1_pt
))
577 result
.append(trafo
.translate_pt(*at_pt
) * trafo
.rotate(degrees(math
.atan2(tdy_pt
, tdx_pt
))))
580 def transformed(self
, trafo
):
581 x0_pt
, y0_pt
= trafo
.apply_pt(self
.x0_pt
, self
.y0_pt
)
582 x1_pt
, y1_pt
= trafo
.apply_pt(self
.x1_pt
, self
.y1_pt
)
583 x2_pt
, y2_pt
= trafo
.apply_pt(self
.x2_pt
, self
.y2_pt
)
584 x3_pt
, y3_pt
= trafo
.apply_pt(self
.x3_pt
, self
.y3_pt
)
585 return normcurve_pt(x0_pt
, y0_pt
, x1_pt
, y1_pt
, x2_pt
, y2_pt
, x3_pt
, y3_pt
)
587 def outputPS(self
, file, writer
, context
):
588 file.write("%g %g %g %g %g %g curveto\n" % (self
.x1_pt
, self
.y1_pt
, self
.x2_pt
, self
.y2_pt
, self
.x3_pt
, self
.y3_pt
))
590 def outputPDF(self
, file, writer
, context
):
591 file.write("%f %f %f %f %f %f c\n" % (self
.x1_pt
, self
.y1_pt
, self
.x2_pt
, self
.y2_pt
, self
.x3_pt
, self
.y3_pt
))
594 ################################################################################
596 ################################################################################
600 """sub path of a normalized path
602 A subpath consists of a list of normsubpathitems, i.e., normlines_pt and
603 normcurves_pt and can either be closed or not.
605 Some invariants, which have to be obeyed:
606 - All normsubpathitems have to be longer than epsilon pts.
607 - At the end there may be a normline (stored in self.skippedline) whose
608 length is shorter than epsilon -- it has to be taken into account
609 when adding further normsubpathitems
610 - The last point of a normsubpathitem and the first point of the next
611 element have to be equal.
612 - When the path is closed, the last point of last normsubpathitem has
613 to be equal to the first point of the first normsubpathitem.
614 - epsilon might be none, disallowing any numerics, but allowing for
615 arbitrary short paths. This is used in pdf output, where all paths need
616 to be transformed to normpaths.
619 __slots__
= "normsubpathitems", "closed", "epsilon", "skippedline"
621 def __init__(self
, normsubpathitems
=[], closed
=0, epsilon
=_marker
):
622 """construct a normsubpath"""
623 if epsilon
is _marker
:
625 self
.epsilon
= epsilon
626 # If one or more items appended to the normsubpath have been
627 # skipped (because their total length was shorter than epsilon),
628 # we remember this fact by a line because we have to take it
629 # properly into account when appending further normsubpathitems
630 self
.skippedline
= None
632 self
.normsubpathitems
= []
635 # a test (might be temporary)
636 for anormsubpathitem
in normsubpathitems
:
637 assert isinstance(anormsubpathitem
, normsubpathitem
), "only list of normsubpathitem instances allowed"
639 self
.extend(normsubpathitems
)
644 def __getitem__(self
, i
):
645 """return normsubpathitem i"""
646 return self
.normsubpathitems
[i
]
649 """return number of normsubpathitems"""
650 return len(self
.normsubpathitems
)
653 l
= ", ".join(map(str, self
.normsubpathitems
))
655 return "normsubpath([%s], closed=1)" % l
657 return "normsubpath([%s])" % l
659 def _distributeparams(self
, params
):
660 """return a dictionary mapping normsubpathitemindices to a tuple
661 of a paramindices and normsubpathitemparams.
663 normsubpathitemindex specifies a normsubpathitem containing
664 one or several positions. paramindex specify the index of the
665 param in the original list and normsubpathitemparam is the
666 parameter value in the normsubpathitem.
670 for i
, param
in enumerate(params
):
673 if index
> len(self
.normsubpathitems
) - 1:
674 index
= len(self
.normsubpathitems
) - 1
677 result
.setdefault(index
, ([], []))
678 result
[index
][0].append(i
)
679 result
[index
][1].append(param
- index
)
682 def append(self
, anormsubpathitem
):
683 """append normsubpathitem
685 Fails on closed normsubpath.
687 if self
.epsilon
is None:
688 self
.normsubpathitems
.append(anormsubpathitem
)
690 # consitency tests (might be temporary)
691 assert isinstance(anormsubpathitem
, normsubpathitem
), "only normsubpathitem instances allowed"
693 assert math
.hypot(*[x
-y
for x
, y
in zip(self
.skippedline
.atend_pt(), anormsubpathitem
.atbegin_pt())]) < self
.epsilon
, "normsubpathitems do not match"
694 elif self
.normsubpathitems
:
695 assert math
.hypot(*[x
-y
for x
, y
in zip(self
.normsubpathitems
[-1].atend_pt(), anormsubpathitem
.atbegin_pt())]) < self
.epsilon
, "normsubpathitems do not match"
698 raise path
.PathException("Cannot append to closed normsubpath")
701 xs_pt
, ys_pt
= self
.skippedline
.atbegin_pt()
703 xs_pt
, ys_pt
= anormsubpathitem
.atbegin_pt()
704 xe_pt
, ye_pt
= anormsubpathitem
.atend_pt()
706 if (math
.hypot(xe_pt
-xs_pt
, ye_pt
-ys_pt
) >= self
.epsilon
or
707 anormsubpathitem
.arclen_pt(self
.epsilon
) >= self
.epsilon
):
709 anormsubpathitem
= anormsubpathitem
.modifiedbegin_pt(xs_pt
, ys_pt
)
710 self
.normsubpathitems
.append(anormsubpathitem
)
711 self
.skippedline
= None
713 self
.skippedline
= normline_pt(xs_pt
, ys_pt
, xe_pt
, ye_pt
)
716 """return arc length in pts"""
717 return sum([npitem
.arclen_pt(self
.epsilon
) for npitem
in self
.normsubpathitems
])
719 def _arclentoparam_pt(self
, lengths_pt
):
720 """return a tuple of params and the total length arc length in pts"""
721 # work on a copy which is counted down to negative values
722 lengths_pt
= lengths_pt
[:]
723 results
= [None] * len(lengths_pt
)
726 for normsubpathindex
, normsubpathitem
in enumerate(self
.normsubpathitems
):
727 params
, arclen
= normsubpathitem
._arclentoparam
_pt
(lengths_pt
, self
.epsilon
)
728 for i
in range(len(results
)):
729 if results
[i
] is None:
730 lengths_pt
[i
] -= arclen
731 if lengths_pt
[i
] < 0 or normsubpathindex
== len(self
.normsubpathitems
) - 1:
732 # overwrite the results until the length has become negative
733 results
[i
] = normsubpathindex
+ params
[i
]
734 totalarclen
+= arclen
736 return results
, totalarclen
738 def arclentoparam_pt(self
, lengths_pt
):
739 """return a tuple of params"""
740 return self
._arclentoparam
_pt
(lengths_pt
)[0]
742 def at_pt(self
, params
):
743 """return coordinates at params in pts"""
744 result
= [None] * len(params
)
745 for normsubpathitemindex
, (indices
, params
) in self
._distributeparams
(params
).items():
746 for index
, point_pt
in zip(indices
, self
.normsubpathitems
[normsubpathitemindex
].at_pt(params
)):
747 result
[index
] = point_pt
750 def atbegin_pt(self
):
751 """return coordinates of first point in pts"""
752 if not self
.normsubpathitems
and self
.skippedline
:
753 return self
.skippedline
.atbegin_pt()
754 return self
.normsubpathitems
[0].atbegin_pt()
757 """return coordinates of last point in pts"""
759 return self
.skippedline
.atend_pt()
760 return self
.normsubpathitems
[-1].atend_pt()
763 """return bounding box of normsubpath"""
764 if self
.normsubpathitems
:
765 abbox
= self
.normsubpathitems
[0].bbox()
766 for anormpathitem
in self
.normsubpathitems
[1:]:
767 abbox
+= anormpathitem
.bbox()
775 Fails on closed normsubpath.
778 raise path
.PathException("Cannot close already closed normsubpath")
779 if not self
.normsubpathitems
:
780 if self
.skippedline
is None:
781 raise path
.PathException("Cannot close empty normsubpath")
783 raise path
.PathException("Normsubpath too short, cannot be closed")
785 xs_pt
, ys_pt
= self
.normsubpathitems
[-1].atend_pt()
786 xe_pt
, ye_pt
= self
.normsubpathitems
[0].atbegin_pt()
787 self
.append(normline_pt(xs_pt
, ys_pt
, xe_pt
, ye_pt
))
788 self
.flushskippedline()
792 """return copy of normsubpath"""
793 # Since normsubpathitems are never modified inplace, we just
794 # need to copy the normsubpathitems list. We do not pass the
795 # normsubpathitems to the constructor to not repeat the checks
796 # for minimal length of each normsubpathitem.
797 result
= normsubpath(epsilon
=self
.epsilon
)
798 result
.normsubpathitems
= self
.normsubpathitems
[:]
799 result
.closed
= self
.closed
801 # We can share the reference to skippedline, since it is a
802 # normsubpathitem as well and thus not modified in place either.
803 result
.skippedline
= self
.skippedline
807 def curveradius_pt(self
, params
):
808 """return the curvature radius at params in pts
810 The curvature radius is the inverse of the curvature. When the
811 curvature is 0, None is returned. Note that this radius can be negative
812 or positive, depending on the sign of the curvature."""
813 result
= [None] * len(params
)
814 for normsubpathitemindex
, (indices
, params
) in self
._distributeparams
(params
).items():
815 for index
, radius_pt
in zip(indices
, self
.normsubpathitems
[normsubpathitemindex
].curveradius_pt(params
)):
816 result
[index
] = radius_pt
819 def extend(self
, normsubpathitems
):
820 """extend path by normsubpathitems
822 Fails on closed normsubpath.
824 for normsubpathitem
in normsubpathitems
:
825 self
.append(normsubpathitem
)
827 def flushskippedline(self
):
828 """flush the skippedline, i.e. apply it to the normsubpath
830 remove the skippedline by modifying the end point of the existing normsubpath
832 while self
.skippedline
:
834 lastnormsubpathitem
= self
.normsubpathitems
.pop()
836 raise ValueError("normsubpath too short to flush the skippedline")
837 lastnormsubpathitem
= lastnormsubpathitem
.modifiedend_pt(*self
.skippedline
.atend_pt())
838 self
.skippedline
= None
839 self
.append(lastnormsubpathitem
)
841 def intersect(self
, other
):
842 """intersect self with other normsubpath
844 Returns a tuple of lists consisting of the parameter values
845 of the intersection points of the corresponding normsubpath.
849 epsilon
= min(self
.epsilon
, other
.epsilon
)
850 # Intersect all subpaths of self with the subpaths of other, possibly including
851 # one intersection point several times
852 for t_a
, pitem_a
in enumerate(self
.normsubpathitems
):
853 for t_b
, pitem_b
in enumerate(other
.normsubpathitems
):
854 for intersection_a
, intersection_b
in pitem_a
.intersect(pitem_b
, epsilon
):
855 intersections_a
.append(intersection_a
+ t_a
)
856 intersections_b
.append(intersection_b
+ t_b
)
858 # although intersectipns_a are sorted for the different normsubpathitems,
859 # within a normsubpathitem, the ordering has to be ensured separately:
860 intersections
= zip(intersections_a
, intersections_b
)
862 intersections_a
= [a
for a
, b
in intersections
]
863 intersections_b
= [b
for a
, b
in intersections
]
865 # for symmetry reasons we enumerate intersections_a as well, although
866 # they are already sorted (note we do not need to sort intersections_a)
867 intersections_a
= zip(intersections_a
, range(len(intersections_a
)))
868 intersections_b
= zip(intersections_b
, range(len(intersections_b
)))
869 intersections_b
.sort()
871 # now we search for intersections points which are closer together than epsilon
872 # This task is handled by the following function
873 def closepoints(normsubpath
, intersections
):
874 split
= normsubpath
.segments([0] + [intersection
for intersection
, index
in intersections
] + [len(normsubpath
)])
876 if normsubpath
.closed
:
877 # note that the number of segments of a closed path is off by one
878 # compared to an open path
880 while i
< len(split
):
881 splitnormsubpath
= split
[i
]
883 while not splitnormsubpath
.normsubpathitems
: # i.e. while "is short"
884 ip1
, ip2
= intersections
[i
-1][1], intersections
[j
][1]
886 result
.append((ip1
, ip2
))
888 result
.append((ip2
, ip1
))
893 splitnormsubpath
= splitnormsubpath
.joined(split
[j
])
899 while i
< len(split
)-1:
900 splitnormsubpath
= split
[i
]
902 while not splitnormsubpath
.normsubpathitems
: # i.e. while "is short"
903 ip1
, ip2
= intersections
[i
-1][1], intersections
[j
][1]
905 result
.append((ip1
, ip2
))
907 result
.append((ip2
, ip1
))
910 splitnormsubpath
= splitnormsubpath
.joined(split
[j
])
916 closepoints_a
= closepoints(self
, intersections_a
)
917 closepoints_b
= closepoints(other
, intersections_b
)
919 # map intersection point to lowest point which is equivalent to the
921 equivalentpoints
= list(range(len(intersections_a
)))
923 for closepoint_a
in closepoints_a
:
924 for closepoint_b
in closepoints_b
:
925 if closepoint_a
== closepoint_b
:
926 for i
in range(closepoint_a
[1], len(equivalentpoints
)):
927 if equivalentpoints
[i
] == closepoint_a
[1]:
928 equivalentpoints
[i
] = closepoint_a
[0]
930 # determine the remaining intersection points
931 intersectionpoints
= {}
932 for point
in equivalentpoints
:
933 intersectionpoints
[point
] = 1
937 intersectionpointskeys
= intersectionpoints
.keys()
938 intersectionpointskeys
.sort()
939 for point
in intersectionpointskeys
:
940 for intersection_a
, index_a
in intersections_a
:
942 result_a
= intersection_a
943 for intersection_b
, index_b
in intersections_b
:
945 result_b
= intersection_b
946 result
.append((result_a
, result_b
))
947 # note that the result is sorted in a, since we sorted
948 # intersections_a in the very beginning
950 return [x
for x
, y
in result
], [y
for x
, y
in result
]
952 def join(self
, other
):
953 """join other normsubpath inplace
955 Fails on closed normsubpath. Fails to join closed normsubpath.
958 raise path
.PathException("Cannot join closed normsubpath")
960 # insert connection line
961 x0_pt
, y0_pt
= self
.atend_pt()
962 x1_pt
, y1_pt
= other
.atbegin_pt()
963 self
.append(normline_pt(x0_pt
, y0_pt
, x1_pt
, y1_pt
))
965 # append other normsubpathitems
966 self
.extend(other
.normsubpathitems
)
967 if other
.skippedline
:
968 self
.append(other
.skippedline
)
970 def joined(self
, other
):
971 """return joined self and other
973 Fails on closed normsubpath. Fails to join closed normsubpath.
979 def _paramtoarclen_pt(self
, params
):
980 """return a tuple of arc lengths and the total arc length in pts"""
981 result
= [None] * len(params
)
983 distributeparams
= self
._distributeparams
(params
)
984 for normsubpathitemindex
in range(len(self
.normsubpathitems
)):
985 if distributeparams
.has_key(normsubpathitemindex
):
986 indices
, params
= distributeparams
[normsubpathitemindex
]
987 arclens_pt
, normsubpathitemarclen_pt
= self
.normsubpathitems
[normsubpathitemindex
]._paramtoarclen
_pt
(params
, self
.epsilon
)
988 for index
, arclen_pt
in zip(indices
, arclens_pt
):
989 result
[index
] = totalarclen_pt
+ arclen_pt
990 totalarclen_pt
+= normsubpathitemarclen_pt
992 totalarclen_pt
+= self
.normsubpathitems
[normsubpathitemindex
].arclen_pt(self
.epsilon
)
993 return result
, totalarclen_pt
996 """return list of pathitems"""
997 if not self
.normsubpathitems
:
1000 # remove trailing normline_pt of closed subpaths
1001 if self
.closed
and isinstance(self
.normsubpathitems
[-1], normline_pt
):
1002 normsubpathitems
= self
.normsubpathitems
[:-1]
1004 normsubpathitems
= self
.normsubpathitems
1006 result
= [path
.moveto_pt(*self
.atbegin_pt())]
1007 for normsubpathitem
in normsubpathitems
:
1008 result
.append(normsubpathitem
.pathitem())
1010 result
.append(path
.closepath())
1014 """return reversed normsubpath"""
1016 for i
in range(len(self
.normsubpathitems
)):
1017 nnormpathitems
.append(self
.normsubpathitems
[-(i
+1)].reversed())
1018 return normsubpath(nnormpathitems
, self
.closed
)
1020 def rotation(self
, params
):
1021 """return rotations at params"""
1022 result
= [None] * len(params
)
1023 for normsubpathitemindex
, (indices
, params
) in self
._distributeparams
(params
).items():
1024 for index
, rotation
in zip(indices
, self
.normsubpathitems
[normsubpathitemindex
].rotation(params
)):
1025 result
[index
] = rotation
1028 def segments(self
, params
):
1029 """return segments of the normsubpath
1031 The returned list of normsubpaths for the segments between
1032 the params. params need to contain at least two values.
1034 For a closed normsubpath the last segment result is joined to
1035 the first one when params starts with 0 and ends with len(self).
1036 or params starts with len(self) and ends with 0. Thus a segments
1037 operation on a closed normsubpath might properly join those the
1038 first and the last part to take into account the closed nature of
1039 the normsubpath. However, for intermediate parameters, closepath
1040 is not taken into account, i.e. when walking backwards you do not
1041 loop over the closepath forwardly. The special values 0 and
1042 len(self) for the first and the last parameter should be given as
1043 integers, i.e. no finite precision is used when checking for
1047 raise ValueError("at least two parameters needed in segments")
1049 result
= [normsubpath(epsilon
=self
.epsilon
)]
1051 # instead of distribute the parameters, we need to keep their
1052 # order and collect parameters for the needed segments of
1053 # normsubpathitem with index collectindex
1056 for param
in params
:
1057 # calculate index and parameter for corresponding normsubpathitem
1060 if index
> len(self
.normsubpathitems
) - 1:
1061 index
= len(self
.normsubpathitems
) - 1
1065 if index
!= collectindex
:
1066 if collectindex
is not None:
1067 # append end point depening on the forthcoming index
1068 if index
> collectindex
:
1069 collectparams
.append(1)
1071 collectparams
.append(0)
1072 # get segments of the normsubpathitem and add them to the result
1073 segments
= self
.normsubpathitems
[collectindex
].segments(collectparams
)
1074 result
[-1].append(segments
[0])
1075 result
.extend([normsubpath([segment
], epsilon
=self
.epsilon
) for segment
in segments
[1:]])
1076 # add normsubpathitems and first segment parameter to close the
1077 # gap to the forthcoming index
1078 if index
> collectindex
:
1079 for i
in range(collectindex
+1, index
):
1080 result
[-1].append(self
.normsubpathitems
[i
])
1083 for i
in range(collectindex
-1, index
, -1):
1084 result
[-1].append(self
.normsubpathitems
[i
].reversed())
1086 collectindex
= index
1087 collectparams
.append(param
)
1088 # add remaining collectparams to the result
1089 segments
= self
.normsubpathitems
[collectindex
].segments(collectparams
)
1090 result
[-1].append(segments
[0])
1091 result
.extend([normsubpath([segment
], epsilon
=self
.epsilon
) for segment
in segments
[1:]])
1094 # join last and first segment together if the normsubpath was
1095 # originally closed and first and the last parameters are the
1096 # beginning and end points of the normsubpath
1097 if ( ( params
[0] == 0 and params
[-1] == len(self
.normsubpathitems
) ) or
1098 ( params
[-1] == 0 and params
[0] == len(self
.normsubpathitems
) ) ):
1099 result
[-1].normsubpathitems
.extend(result
[0].normsubpathitems
)
1100 result
= result
[-1:] + result
[1:-1]
1104 def trafo(self
, params
):
1105 """return transformations at params"""
1106 result
= [None] * len(params
)
1107 for normsubpathitemindex
, (indices
, params
) in self
._distributeparams
(params
).items():
1108 for index
, trafo
in zip(indices
, self
.normsubpathitems
[normsubpathitemindex
].trafo(params
)):
1109 result
[index
] = trafo
1112 def transformed(self
, trafo
):
1113 """return transformed path"""
1114 nnormsubpath
= normsubpath(epsilon
=self
.epsilon
)
1115 for pitem
in self
.normsubpathitems
:
1116 nnormsubpath
.append(pitem
.transformed(trafo
))
1118 nnormsubpath
.close()
1119 elif self
.skippedline
is not None:
1120 nnormsubpath
.append(self
.skippedline
.transformed(trafo
))
1123 def outputPS(self
, file, writer
, context
):
1124 # if the normsubpath is closed, we must not output a normline at
1126 if not self
.normsubpathitems
:
1128 if self
.closed
and isinstance(self
.normsubpathitems
[-1], normline_pt
):
1129 assert len(self
.normsubpathitems
) > 1, "a closed normsubpath should contain more than a single normline_pt"
1130 normsubpathitems
= self
.normsubpathitems
[:-1]
1132 normsubpathitems
= self
.normsubpathitems
1133 file.write("%g %g moveto\n" % self
.atbegin_pt())
1134 for anormsubpathitem
in normsubpathitems
:
1135 anormsubpathitem
.outputPS(file, writer
, context
)
1137 file.write("closepath\n")
1139 def outputPDF(self
, file, writer
, context
):
1140 # if the normsubpath is closed, we must not output a normline at
1142 if not self
.normsubpathitems
:
1144 if self
.closed
and isinstance(self
.normsubpathitems
[-1], normline_pt
):
1145 assert len(self
.normsubpathitems
) > 1, "a closed normsubpath should contain more than a single normline_pt"
1146 normsubpathitems
= self
.normsubpathitems
[:-1]
1148 normsubpathitems
= self
.normsubpathitems
1149 file.write("%f %f m\n" % self
.atbegin_pt())
1150 for anormsubpathitem
in normsubpathitems
:
1151 anormsubpathitem
.outputPDF(file, writer
, context
)
1156 ################################################################################
1158 ################################################################################
1160 class normpathparam
:
1162 """parameter of a certain point along a normpath"""
1164 __slots__
= "normpath", "normsubpathindex", "normsubpathparam"
1166 def __init__(self
, normpath
, normsubpathindex
, normsubpathparam
):
1167 self
.normpath
= normpath
1168 self
.normsubpathindex
= normsubpathindex
1169 self
.normsubpathparam
= normsubpathparam
1170 float(normsubpathparam
)
1173 return "normpathparam(%s, %s, %s)" % (self
.normpath
, self
.normsubpathindex
, self
.normsubpathparam
)
1175 def __add__(self
, other
):
1176 if isinstance(other
, normpathparam
):
1177 assert self
.normpath
is other
.normpath
, "normpathparams have to belong to the same normpath"
1178 return self
.normpath
.arclentoparam_pt(self
.normpath
.paramtoarclen_pt(self
) +
1179 other
.normpath
.paramtoarclen_pt(other
))
1181 return self
.normpath
.arclentoparam_pt(self
.normpath
.paramtoarclen_pt(self
) + unit
.topt(other
))
1185 def __sub__(self
, other
):
1186 if isinstance(other
, normpathparam
):
1187 assert self
.normpath
is other
.normpath
, "normpathparams have to belong to the same normpath"
1188 return self
.normpath
.arclentoparam_pt(self
.normpath
.paramtoarclen_pt(self
) -
1189 other
.normpath
.paramtoarclen_pt(other
))
1191 return self
.normpath
.arclentoparam_pt(self
.normpath
.paramtoarclen_pt(self
) - unit
.topt(other
))
1193 def __rsub__(self
, other
):
1194 # other has to be a length in this case
1195 return self
.normpath
.arclentoparam_pt(-self
.normpath
.paramtoarclen_pt(self
) + unit
.topt(other
))
1197 def __mul__(self
, factor
):
1198 return self
.normpath
.arclentoparam_pt(self
.normpath
.paramtoarclen_pt(self
) * factor
)
1202 def __div__(self
, divisor
):
1203 return self
.normpath
.arclentoparam_pt(self
.normpath
.paramtoarclen_pt(self
) / divisor
)
1206 return self
.normpath
.arclentoparam_pt(-self
.normpath
.paramtoarclen_pt(self
))
1208 def __cmp__(self
, other
):
1209 if isinstance(other
, normpathparam
):
1210 assert self
.normpath
is other
.normpath
, "normpathparams have to belong to the same normpath"
1211 return cmp((self
.normsubpathindex
, self
.normsubpathparam
), (other
.normsubpathindex
, other
.normsubpathparam
))
1213 return cmp(self
.normpath
.paramtoarclen_pt(self
), unit
.topt(other
))
1215 def arclen_pt(self
):
1216 """return arc length in pts corresponding to the normpathparam """
1217 return self
.normpath
.paramtoarclen_pt(self
)
1220 """return arc length corresponding to the normpathparam """
1221 return self
.normpath
.paramtoarclen(self
)
1224 def _valueorlistmethod(method
):
1225 """Creates a method which takes a single argument or a list and
1226 returns a single value or a list out of method, which always
1229 def wrappedmethod(self
, valueorlist
, *args
, **kwargs
):
1231 for item
in valueorlist
:
1234 return method(self
, [valueorlist
], *args
, **kwargs
)[0]
1235 return method(self
, valueorlist
, *args
, **kwargs
)
1236 return wrappedmethod
1239 class normpath(canvas
.canvasitem
):
1243 A normalized path consists of a list of normsubpaths.
1246 def __init__(self
, normsubpaths
=None):
1247 """construct a normpath from a list of normsubpaths"""
1249 if normsubpaths
is None:
1250 self
.normsubpaths
= [] # make a fresh list
1252 self
.normsubpaths
= normsubpaths
1253 for subpath
in normsubpaths
:
1254 assert isinstance(subpath
, normsubpath
), "only list of normsubpath instances allowed"
1256 def __add__(self
, other
):
1257 """create new normpath out of self and other"""
1258 result
= self
.copy()
1262 def __iadd__(self
, other
):
1263 """add other inplace"""
1264 for normsubpath
in other
.normpath().normsubpaths
:
1265 self
.normsubpaths
.append(normsubpath
.copy())
1268 def __getitem__(self
, i
):
1269 """return normsubpath i"""
1270 return self
.normsubpaths
[i
]
1273 """return the number of normsubpaths"""
1274 return len(self
.normsubpaths
)
1277 return "normpath([%s])" % ", ".join(map(str, self
.normsubpaths
))
1279 def _convertparams(self
, params
, convertmethod
):
1280 """return params with all non-normpathparam arguments converted by convertmethod
1283 - self._convertparams(params, self.arclentoparam_pt)
1284 - self._convertparams(params, self.arclentoparam)
1287 converttoparams
= []
1288 convertparamindices
= []
1289 for i
, param
in enumerate(params
):
1290 if not isinstance(param
, normpathparam
):
1291 converttoparams
.append(param
)
1292 convertparamindices
.append(i
)
1295 for i
, param
in zip(convertparamindices
, convertmethod(converttoparams
)):
1299 def _distributeparams(self
, params
):
1300 """return a dictionary mapping subpathindices to a tuple of a paramindices and subpathparams
1302 subpathindex specifies a subpath containing one or several positions.
1303 paramindex specify the index of the normpathparam in the original list and
1304 subpathparam is the parameter value in the subpath.
1308 for i
, param
in enumerate(params
):
1309 assert param
.normpath
is self
, "normpathparam has to belong to this path"
1310 result
.setdefault(param
.normsubpathindex
, ([], []))
1311 result
[param
.normsubpathindex
][0].append(i
)
1312 result
[param
.normsubpathindex
][1].append(param
.normsubpathparam
)
1315 def append(self
, item
):
1316 """append a normsubpath by a normsubpath or a pathitem"""
1317 if isinstance(item
, normsubpath
):
1318 # the normsubpaths list can be appended by a normsubpath only
1319 self
.normsubpaths
.append(item
)
1320 elif isinstance(item
, path
.pathitem
):
1321 # ... but we are kind and allow for regular path items as well
1322 # in order to make a normpath to behave more like a regular path
1323 context
= path
.context(*(self
.normsubpaths
[-1].atend_pt() +
1324 self
.normsubpaths
[-1].atbegin_pt()))
1325 item
.updatenormpath(self
, context
)
1327 def arclen_pt(self
):
1328 """return arc length in pts"""
1329 return sum([normsubpath
.arclen_pt() for normsubpath
in self
.normsubpaths
])
1332 """return arc length"""
1333 return self
.arclen_pt() * unit
.t_pt
1335 def _arclentoparam_pt(self
, lengths_pt
):
1336 """return the params matching the given lengths_pt"""
1337 # work on a copy which is counted down to negative values
1338 lengths_pt
= lengths_pt
[:]
1339 results
= [None] * len(lengths_pt
)
1341 for normsubpathindex
, normsubpath
in enumerate(self
.normsubpaths
):
1342 params
, arclen
= normsubpath
._arclentoparam
_pt
(lengths_pt
)
1344 for i
, result
in enumerate(results
):
1345 if results
[i
] is None:
1346 lengths_pt
[i
] -= arclen
1347 if lengths_pt
[i
] < 0 or normsubpathindex
== len(self
.normsubpaths
) - 1:
1348 # overwrite the results until the length has become negative
1349 results
[i
] = normpathparam(self
, normsubpathindex
, params
[i
])
1356 def arclentoparam_pt(self
, lengths_pt
):
1357 """return the param(s) matching the given length(s)_pt in pts"""
1359 arclentoparam_pt
= _valueorlistmethod(_arclentoparam_pt
)
1361 def arclentoparam(self
, lengths
):
1362 """return the param(s) matching the given length(s)"""
1363 return self
._arclentoparam
_pt
([unit
.topt(l
) for l
in lengths
])
1364 arclentoparam
= _valueorlistmethod(arclentoparam
)
1366 def _at_pt(self
, params
):
1367 """return coordinates of normpath in pts at params"""
1368 result
= [None] * len(params
)
1369 for normsubpathindex
, (indices
, params
) in self
._distributeparams
(params
).items():
1370 for index
, point_pt
in zip(indices
, self
.normsubpaths
[normsubpathindex
].at_pt(params
)):
1371 result
[index
] = point_pt
1374 def at_pt(self
, params
):
1375 """return coordinates of normpath in pts at param(s) or lengths in pts"""
1376 return self
._at
_pt
(self
._convertparams
(params
, self
.arclentoparam_pt
))
1377 at_pt
= _valueorlistmethod(at_pt
)
1379 def at(self
, params
):
1380 """return coordinates of normpath at param(s) or arc lengths"""
1381 return [(x_pt
* unit
.t_pt
, y_pt
* unit
.t_pt
)
1382 for x_pt
, y_pt
in self
._at
_pt
(self
._convertparams
(params
, self
.arclentoparam
))]
1383 at
= _valueorlistmethod(at
)
1385 def atbegin_pt(self
):
1386 """return coordinates of the beginning of first subpath in normpath in pts"""
1387 if self
.normsubpaths
:
1388 return self
.normsubpaths
[0].atbegin_pt()
1390 raise path
.PathException("cannot return first point of empty path")
1393 """return coordinates of the beginning of first subpath in normpath"""
1394 x
, y
= self
.atbegin_pt()
1395 return x
* unit
.t_pt
, y
* unit
.t_pt
1398 """return coordinates of the end of last subpath in normpath in pts"""
1399 if self
.normsubpaths
:
1400 return self
.normsubpaths
[-1].atend_pt()
1402 raise path
.PathException("cannot return last point of empty path")
1405 """return coordinates of the end of last subpath in normpath"""
1406 x
, y
= self
.atend_pt()
1407 return x
* unit
.t_pt
, y
* unit
.t_pt
1410 """return bbox of normpath"""
1412 for normsubpath
in self
.normsubpaths
:
1413 nbbox
= normsubpath
.bbox()
1421 """return param corresponding of the beginning of the normpath"""
1422 if self
.normsubpaths
:
1423 return normpathparam(self
, 0, 0)
1425 raise path
.PathException("empty path")
1428 """return copy of normpath"""
1430 for normsubpath
in self
.normsubpaths
:
1431 result
.append(normsubpath
.copy())
1434 def _curveradius_pt(self
, params
):
1435 """return the curvature radius at params in pts
1437 The curvature radius is the inverse of the curvature. When the
1438 curvature is 0, None is returned. Note that this radius can be negative
1439 or positive, depending on the sign of the curvature."""
1441 result
= [None] * len(params
)
1442 for normsubpathindex
, (indices
, params
) in self
._distributeparams
(params
).items():
1443 for index
, radius_pt
in zip(indices
, self
.normsubpaths
[normsubpathindex
].curveradius_pt(params
)):
1444 result
[index
] = radius_pt
1447 def curveradius_pt(self
, params
):
1448 """return the curvature radius in pts at param(s) or arc length(s) in pts
1450 The curvature radius is the inverse of the curvature. When the
1451 curvature is 0, None is returned. Note that this radius can be negative
1452 or positive, depending on the sign of the curvature."""
1454 return self
._curveradius
_pt
(self
._convertparams
(params
, self
.arclentoparam_pt
))
1455 curveradius_pt
= _valueorlistmethod(curveradius_pt
)
1457 def curveradius(self
, params
):
1458 """return the curvature radius at param(s) or arc length(s)
1460 The curvature radius is the inverse of the curvature. When the
1461 curvature is 0, None is returned. Note that this radius can be negative
1462 or positive, depending on the sign of the curvature."""
1465 for radius_pt
in self
._curveradius
_pt
(self
._convertparams
(params
, self
.arclentoparam
)):
1466 if radius_pt
is not None:
1467 result
.append(radius_pt
* unit
.t_pt
)
1471 curveradius
= _valueorlistmethod(curveradius
)
1474 """return param corresponding of the end of the path"""
1475 if self
.normsubpaths
:
1476 return normpathparam(self
, len(self
)-1, len(self
.normsubpaths
[-1]))
1478 raise path
.PathException("empty path")
1480 def extend(self
, normsubpaths
):
1481 """extend path by normsubpaths or pathitems"""
1482 for anormsubpath
in normsubpaths
:
1483 # use append to properly handle regular path items as well as normsubpaths
1484 self
.append(anormsubpath
)
1486 def intersect(self
, other
):
1487 """intersect self with other path
1489 Returns a tuple of lists consisting of the parameter values
1490 of the intersection points of the corresponding normpath.
1492 other
= other
.normpath()
1494 # here we build up the result
1495 intersections
= ([], [])
1497 # Intersect all normsubpaths of self with the normsubpaths of
1499 for ia
, normsubpath_a
in enumerate(self
.normsubpaths
):
1500 for ib
, normsubpath_b
in enumerate(other
.normsubpaths
):
1501 for intersection
in zip(*normsubpath_a
.intersect(normsubpath_b
)):
1502 intersections
[0].append(normpathparam(self
, ia
, intersection
[0]))
1503 intersections
[1].append(normpathparam(other
, ib
, intersection
[1]))
1504 return intersections
1506 def join(self
, other
):
1507 """join other normsubpath inplace
1509 Both normpaths must contain at least one normsubpath.
1510 The last normsubpath of self will be joined to the first
1511 normsubpath of other.
1513 if not self
.normsubpaths
:
1514 raise path
.PathException("cannot join to empty path")
1515 if not other
.normsubpaths
:
1516 raise PathException("cannot join empty path")
1517 self
.normsubpaths
[-1].join(other
.normsubpaths
[0])
1518 self
.normsubpaths
.extend(other
.normsubpaths
[1:])
1520 def joined(self
, other
):
1521 """return joined self and other
1523 Both normpaths must contain at least one normsubpath.
1524 The last normsubpath of self will be joined to the first
1525 normsubpath of other.
1527 result
= self
.copy()
1528 result
.join(other
.normpath())
1531 # << operator also designates joining
1535 """return a normpath, i.e. self"""
1538 def _paramtoarclen_pt(self
, params
):
1539 """return arc lengths in pts matching the given params"""
1540 result
= [None] * len(params
)
1542 distributeparams
= self
._distributeparams
(params
)
1543 for normsubpathindex
in range(max(distributeparams
.keys()) + 1):
1544 if distributeparams
.has_key(normsubpathindex
):
1545 indices
, params
= distributeparams
[normsubpathindex
]
1546 arclens_pt
, normsubpatharclen_pt
= self
.normsubpaths
[normsubpathindex
]._paramtoarclen
_pt
(params
)
1547 for index
, arclen_pt
in zip(indices
, arclens_pt
):
1548 result
[index
] = totalarclen_pt
+ arclen_pt
1549 totalarclen_pt
+= normsubpatharclen_pt
1551 totalarclen_pt
+= self
.normsubpaths
[normsubpathindex
].arclen_pt()
1554 def paramtoarclen_pt(self
, params
):
1555 """return arc length(s) in pts matching the given param(s)"""
1556 paramtoarclen_pt
= _valueorlistmethod(_paramtoarclen_pt
)
1558 def paramtoarclen(self
, params
):
1559 """return arc length(s) matching the given param(s)"""
1560 return [arclen_pt
* unit
.t_pt
for arclen_pt
in self
._paramtoarclen
_pt
(params
)]
1561 paramtoarclen
= _valueorlistmethod(paramtoarclen
)
1564 """return path corresponding to normpath"""
1566 for normsubpath
in self
.normsubpaths
:
1567 pathitems
.extend(normsubpath
.pathitems())
1568 return path
.path(*pathitems
)
1571 """return reversed path"""
1572 nnormpath
= normpath()
1573 for i
in range(len(self
.normsubpaths
)):
1574 nnormpath
.normsubpaths
.append(self
.normsubpaths
[-(i
+1)].reversed())
1577 def _rotation(self
, params
):
1578 """return rotation at params"""
1579 result
= [None] * len(params
)
1580 for normsubpathindex
, (indices
, params
) in self
._distributeparams
(params
).items():
1581 for index
, rotation
in zip(indices
, self
.normsubpaths
[normsubpathindex
].rotation(params
)):
1582 result
[index
] = rotation
1585 def rotation_pt(self
, params
):
1586 """return rotation at param(s) or arc length(s) in pts"""
1587 return self
._rotation
(self
._convertparams
(params
, self
.arclentoparam_pt
))
1588 rotation_pt
= _valueorlistmethod(rotation_pt
)
1590 def rotation(self
, params
):
1591 """return rotation at param(s) or arc length(s)"""
1592 return self
._rotation
(self
._convertparams
(params
, self
.arclentoparam
))
1593 rotation
= _valueorlistmethod(rotation
)
1595 def _split_pt(self
, params
):
1596 """split path at params and return list of normpaths"""
1598 # instead of distributing the parameters, we need to keep their
1599 # order and collect parameters for splitting of normsubpathitem
1600 # with index collectindex
1602 for param
in params
:
1603 if param
.normsubpathindex
!= collectindex
:
1604 if collectindex
is not None:
1605 # append end point depening on the forthcoming index
1606 if param
.normsubpathindex
> collectindex
:
1607 collectparams
.append(len(self
.normsubpaths
[collectindex
]))
1609 collectparams
.append(0)
1610 # get segments of the normsubpath and add them to the result
1611 segments
= self
.normsubpaths
[collectindex
].segments(collectparams
)
1612 result
[-1].append(segments
[0])
1613 result
.extend([normpath([segment
]) for segment
in segments
[1:]])
1614 # add normsubpathitems and first segment parameter to close the
1615 # gap to the forthcoming index
1616 if param
.normsubpathindex
> collectindex
:
1617 for i
in range(collectindex
+1, param
.normsubpathindex
):
1618 result
[-1].append(self
.normsubpaths
[i
])
1621 for i
in range(collectindex
-1, param
.normsubpathindex
, -1):
1622 result
[-1].append(self
.normsubpaths
[i
].reversed())
1623 collectparams
= [len(self
.normsubpaths
[param
.normsubpathindex
])]
1625 result
= [normpath(self
.normsubpaths
[:param
.normsubpathindex
])]
1627 collectindex
= param
.normsubpathindex
1628 collectparams
.append(param
.normsubpathparam
)
1629 # add remaining collectparams to the result
1630 collectparams
.append(len(self
.normsubpaths
[collectindex
]))
1631 segments
= self
.normsubpaths
[collectindex
].segments(collectparams
)
1632 result
[-1].append(segments
[0])
1633 result
.extend([normpath([segment
]) for segment
in segments
[1:]])
1634 result
[-1].extend(self
.normsubpaths
[collectindex
+1:])
1637 def split_pt(self
, params
):
1638 """split path at param(s) or arc length(s) in pts and return list of normpaths"""
1640 for param
in params
:
1644 return self
._split
_pt
(self
._convertparams
(params
, self
.arclentoparam_pt
))
1646 def split(self
, params
):
1647 """split path at param(s) or arc length(s) and return list of normpaths"""
1649 for param
in params
:
1653 return self
._split
_pt
(self
._convertparams
(params
, self
.arclentoparam
))
1655 def _tangent(self
, params
, length
=None):
1656 """return tangent vector of path at params
1658 If length is not None, the tangent vector will be scaled to
1662 result
= [None] * len(params
)
1663 tangenttemplate
= path
.line_pt(0, 0, 1, 0).normpath()
1664 for normsubpathindex
, (indices
, params
) in self
._distributeparams
(params
).items():
1665 for index
, atrafo
in zip(indices
, self
.normsubpaths
[normsubpathindex
].trafo(params
)):
1666 tangentpath
= tangenttemplate
.transformed(atrafo
)
1667 if length
is not None:
1668 sfactor
= unit
.topt(length
)/tangentpath
.arclen_pt()
1669 tangentpath
= tangentpath
.transformed(trafo
.scale_pt(sfactor
, sfactor
, *tangentpath
.atbegin_pt()))
1670 result
[index
] = tangentpath
1673 def tangent_pt(self
, params
, length
=None):
1674 """return tangent vector of path at param(s) or arc length(s) in pts
1676 If length in pts is not None, the tangent vector will be scaled to
1679 return self
._tangent
(self
._convertparams
(params
, self
.arclentoparam_pt
), length
)
1680 tangent_pt
= _valueorlistmethod(tangent_pt
)
1682 def tangent(self
, params
, length
=None):
1683 """return tangent vector of path at param(s) or arc length(s)
1685 If length is not None, the tangent vector will be scaled to
1688 return self
._tangent
(self
._convertparams
(params
, self
.arclentoparam
), length
)
1689 tangent
= _valueorlistmethod(tangent
)
1691 def _trafo(self
, params
):
1692 """return transformation at params"""
1693 result
= [None] * len(params
)
1694 for normsubpathindex
, (indices
, params
) in self
._distributeparams
(params
).items():
1695 for index
, trafo
in zip(indices
, self
.normsubpaths
[normsubpathindex
].trafo(params
)):
1696 result
[index
] = trafo
1699 def trafo_pt(self
, params
):
1700 """return transformation at param(s) or arc length(s) in pts"""
1701 return self
._trafo
(self
._convertparams
(params
, self
.arclentoparam_pt
))
1702 trafo_pt
= _valueorlistmethod(trafo_pt
)
1704 def trafo(self
, params
):
1705 """return transformation at param(s) or arc length(s)"""
1706 return self
._trafo
(self
._convertparams
(params
, self
.arclentoparam
))
1707 trafo
= _valueorlistmethod(trafo
)
1709 def transformed(self
, trafo
):
1710 """return transformed normpath"""
1711 return normpath([normsubpath
.transformed(trafo
) for normsubpath
in self
.normsubpaths
])
1713 def outputPS(self
, file, writer
, context
):
1714 for normsubpath
in self
.normsubpaths
:
1715 normsubpath
.outputPS(file, writer
, context
)
1717 def outputPDF(self
, file, writer
, context
):
1718 for normsubpath
in self
.normsubpaths
:
1719 normsubpath
.outputPDF(file, writer
, context
)