Debian Codegraph @

experimental/svg_test.py

raw symbols SCIP
1 # -*- coding: latin-1 -*-
2 import re
3 import os.path
4 import pyglet
5 from pyglet.gl import (
6 glEnable,
7 glBlendFunc,
8 glHint,
9 GL_LINE_SMOOTH,
10 GL_BLEND,
11 GL_SRC_ALPHA,
12 GL_ONE_MINUS_SRC_ALPHA,
13 GL_LINE_SMOOTH_HINT,
14 GL_LINES,
15 GL_DONT_CARE,
16 )
17 from pyglet.gl.gl_compat import (
18 glPushAttrib,
19 glPopAttrib,
20 glPushMatrix,
21 glPopMatrix,
22 glScalef,
23 glTranslatef,
24 GL_ENABLE_BIT,
25 )
26
27 import xml.dom
28 import xml.dom.minidom
29
30
31 class SmoothLineGroup(pyglet.graphics.Group):
32 @staticmethod
33 def set_state():
34 glPushAttrib(GL_ENABLE_BIT)
35 glEnable(GL_LINE_SMOOTH)
36 glEnable(GL_BLEND)
37 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
38 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE)
39
40 @staticmethod
41 def unset_state():
42 glPopAttrib()
43
44
45 class Curve:
46 PATH_RE = re.compile(r'([MLHVCSQTAZ])([^MLHVCSQTAZ]+)', re.IGNORECASE)
47 INT = r'([+-]?\d+)'
48 FLOAT = r'(?:[\s,]*)([+-]?\d+(?:\.\d+)?)'
49
50 HANDLERS = {}
51
52 def handle(self, rx, types, HANDLERS=HANDLERS):
53 def register(function):
54 HANDLERS[self] = (rx and re.compile(rx), function, types)
55 return function
56
57 return register
58
59 def __init__(self, spec, batch):
60 self.batch = batch
61
62 self.start = None
63 self.current = None
64 self.min_x = self.min_y = self.max_x = self.max_y = None
65
66 for cmd, value in self.PATH_RE.findall(spec):
67 # print (cmd, value)
68 if not cmd:
69 continue
70 rx, handler, types = self.HANDLERS[cmd.upper()]
71 if rx is None:
72 handler(self, cmd)
73 else:
74 v = []
75 for fields in rx.findall(value):
76 v.append([types[i](e) for i, e in enumerate(fields)])
77 handler(self, cmd, v)
78
79 def _determine_rect(self, x, y):
80 y = -y
81 if self.min_x is None:
82 self.min_x = self.max_x = x
83 self.min_y = self.max_y = y
84 else:
85 if self.min_x > x:
86 self.min_x = x
87 elif self.max_x < x:
88 self.max_x = x
89 if self.min_y > y:
90 self.min_y = y
91 elif self.max_y < y:
92 self.max_y = y
93
94 @handle('M', FLOAT * 2, (float, float))
95 def moveto(self, cmd, points):
96 """Start a new sub-path at the given (x,y) coordinate. M (uppercase)
97 indicates that absolute coordinates will follow; m (lowercase)
98 indicates that relative coordinates will follow. If a relative moveto
99 (m) appears as the first element of the path, then it is treated as a
100 pair of absolute coordinates. If a moveto is followed by multiple pairs
101 of coordinates, the subsequent pairs are treated as implicit lineto
102 commands.
103
104 Parameters are (x y)+
105 """
106 points = [list(map(float, point)) for point in points]
107 # XXX handle relative
108 # XXX confirm that we always reset start here
109 self.start = self.current = points[0]
110 if len(points) > 2:
111 self.lineto({'m': 'l', 'M': 'L'}[cmd], points[1:])
112
113 @handle('L', FLOAT * 2, (float, float))
114 def lineto(self, cmd, points):
115 """Draw a line from the current point to the given (x,y) coordinate
116 which becomes the new current point. L (uppercase) indicates that
117 absolute coordinates will follow; l (lowercase) indicates that relative
118 coordinates will follow. A number of coordinates pairs may be specified
119 to draw a polyline. At the end of the command, the new current point is
120 set to the final set of coordinates provided.
121
122 Parameters are (x y)+
123 """
124 l = []
125 self._determine_rect(*self.current)
126 for point in points:
127 cx, cy = self.current
128 x, y = list(map(float, point))
129 l.extend([cx, -cy])
130 l.extend([x, -y])
131 self.current = (x, y)
132 self._determine_rect(x, y)
133 self.batch.add(len(l) // 2, GL_LINES, SmoothLineGroup(), ('v2f', l))
134
135 @handle('H', FLOAT, (float,))
136 def horizontal_lineto(self, cmd, xvals):
137 """Draws a horizontal line from the current point (cpx, cpy) to (x,
138 cpy). H (uppercase) indicates that absolute coordinates will follow; h
139 (lowercase) indicates that relative coordinates will follow. Multiple x
140 values can be provided (although usually this doesn't make sense). At
141 the end of the command, the new current point becomes (x, cpy) for the
142 final value of x.
143
144 Parameters are x+
145 """
146 cx, cy = self.current
147 self._determine_rect(*self.current)
148 x = float(xvals[-1])
149 self.batch.add(2, GL_LINES, None, ('v2f', (cx, -cy, x, -cy)))
150 self.current = (x, cy)
151 self._determine_rect(x, cy)
152
153 @handle('V', FLOAT, (float,))
154 def vertical_lineto(self, cmd, yvals):
155 """Draws a vertical line from the current point (cpx, cpy) to (cpx, y).
156 V (uppercase) indicates that absolute coordinates will follow; v
157 (lowercase) indicates that relative coordinates will follow. Multiple y
158 values can be provided (although usually this doesn't make sense). At
159 the end of the command, the new current point becomes (cpx, y) for the
160 final value of y.
161
162 Parameters are y+
163 """
164 cx, cy = self.current
165 self._determine_rect(*self.current)
166 y = float(yvals[-1])
167 self.batch.add(2, GL_LINES, None, ('v2f', [cx, -cy, cx, -y]))
168 self.current = (cx, y)
169 self._determine_rect(cx, y)
170
171 @handle('Z', None, None)
172 def closepath(self, cmd):
173 """Close the current subpath by drawing a straight line from the
174 current point to current subpath's initial point.
175 """
176 self.batch.add(2, GL_LINES, SmoothLineGroup(), ('v2f', self.current + tuple(self.start)))
177
178 @handle('C', FLOAT * 6, (float,) * 6)
179 def curveto(self, cmd, control_points):
180 """Draws a cubic Bézier curve from the current point to (x,y) using
181 (x1,y1) as the control point at the beginning of the curve and (x2,y2)
182 as the control point at the end of the curve. C (uppercase) indicates
183 that absolute coordinates will follow; c (lowercase) indicates that
184 relative coordinates will follow. Multiple sets of coordinates may be
185 specified to draw a polybézier. At the end of the command, the new
186 current point becomes the final (x,y) coordinate pair used in the
187 polybézier.
188
189 Control points are (x1 y1 x2 y2 x y)+
190 """
191 l = []
192 last = None
193 for entry in control_points:
194 x1, y1, x2, y2, x, y = list(map(float, entry))
195 t = 0
196 cx, cy = self.current
197 self.last_control = (x2, y2)
198 self.current = (x, y)
199 x1 *= 3
200 x2 *= 3
201 y1 *= 3
202 y2 *= 3
203 while t <= 1.01:
204 a = t
205 a2 = a ** 2
206 a3 = a ** 3
207 b = 1 - t
208 b2 = b ** 2
209 b3 = b ** 3
210 px = cx * b3 + x1 * b2 * a + x2 * b * a2 + x * a3
211 py = cy * b3 + y1 * b2 * a + y2 * b * a2 + y * a3
212 if last is not None:
213 l.extend(last)
214 l.extend((px, -py))
215 last = (px, -py)
216 self._determine_rect(px, py)
217 t += 0.01
218 self.batch.add(len(l) // 2, GL_LINES, SmoothLineGroup(), ('v2f', l))
219
220 @handle('S', FLOAT * 4, (float,) * 4)
221 def smooth_curveto(self, cmd, control_points):
222 """Draws a cubic Bézier curve from the current point to (x,y). The
223 first control point is assumed to be the reflection of the second
224 control point on the previous command relative to the current point.
225 (If there is no previous command or if the previous command was not an
226 C, c, S or s, assume the first control point is coincident with the
227 current point.) (x2,y2) is the second control point (i.e., the control
228 point at the end of the curve). S (uppercase) indicates that absolute
229 coordinates will follow; s (lowercase) indicates that relative
230 coordinates will follow. Multiple sets of coordinates may be specified
231 to draw a polybézier. At the end of the command, the new current point
232 becomes the final (x,y) coordinate pair used in the polybézier.
233
234 Control points are (x2 y2 x y)+
235 """
236 assert self.last_control is not None, 'S must follow S or C'
237
238 l = []
239 last = None
240 for entry in control_points:
241 x2, y2, x, y = list(map(float, entry))
242
243 # Reflect last control point
244 cx, cy = self.current
245 lcx, lcy = self.last_control
246 dx, dy = cx - lcx, cy - lcy
247 x1, y1 = cx + dx, cy + dy
248
249 t = 0
250 cx, cy = self.current
251 self.last_control = (x2, y2)
252 self.current = (x, y)
253
254 x1 *= 3
255 x2 *= 3
256 y1 *= 3
257 y2 *= 3
258 while t <= 1.01:
259 a = t
260 a2 = a ** 2
261 a3 = a ** 3
262 b = 1 - t
263 b2 = b ** 2
264 b3 = b ** 3
265 px = cx * b3 + x1 * b2 * a + x2 * b * a2 + x * a3
266 py = cy * b3 + y1 * b2 * a + y2 * b * a2 + y * a3
267 if last is not None:
268 l.extend(last)
269 l.extend((px, -py))
270 last = (px, -py)
271 self._determine_rect(px, py)
272 t += 0.01
273 # degenerate vertices
274 self.batch.add(len(l) // 2, GL_LINES, SmoothLineGroup(), ('v2f', l))
275
276 @handle('Q', FLOAT * 4, (float,) * 4)
277 def quadratic_curveto(self, cmd, control_points):
278 """Draws a quadratic Bézier curve from the current point to (x,y)
279 using (x1,y1) as the control point. Q (uppercase) indicates that
280 absolute coordinates will follow; q (lowercase) indicates that
281 relative coordinates will follow. Multiple sets of coordinates may
282 be specified to draw a polybézier. At the end of the command, the
283 new current point becomes the final (x,y) coordinate pair used in
284 the polybézier.
285
286 Control points are (x1 y1 x y)+
287 """
288 raise NotImplementedError('not implemented')
289
290 @handle('T', FLOAT * 2, (float,) * 2)
291 def smooth_quadratic_curveto(self, cmd, control_points):
292 """Draws a quadratic Bézier curve from the current point to (x,y).
293 The control point is assumed to be the reflection of the control
294 point on the previous command relative to the current point. (If
295 there is no previous command or if the previous command was not a
296 Q, q, T or t, assume the control point is coincident with the
297 current point.) T (uppercase) indicates that absolute coordinates
298 will follow; t (lowercase) indicates that relative coordinates will
299 follow. At the end of the command, the new current point becomes
300 the final (x,y) coordinate pair used in the polybézier.
301
302 Control points are (x y)+
303 """
304 raise NotImplementedError('not implemented')
305
306 @handle('A', FLOAT * 3 + INT * 2 + FLOAT * 2, (float,) * 3 + (int,) * 2 + (float,) * 2)
307 def elliptical_arc(self, cmd, parameters):
308 """Draws an elliptical arc from the current point to (x, y). The
309 size and orientation of the ellipse are defined by two radii (rx,
310 ry) and an x-axis-rotation, which indicates how the ellipse as a
311 whole is rotated relative to the current coordinate system. The
312 center (cx, cy) of the ellipse is calculated automatically to
313 satisfy the constraints imposed by the other parameters.
314 large-arc-flag and sweep-flag contribute to the automatic
315 calculations and help determine how the arc is drawn.
316
317 Parameters are (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+
318 """
319 raise NotImplementedError('not implemented')
320
321
322 class SVG:
323 def __init__(self, filename, rect=None):
324 self._rect = rect
325 self.scale_x = None
326 self.scale_y = None
327 self.translate_x = None
328 self.translate_y = None
329 dom = xml.dom.minidom.parse(filename)
330 tag = dom.documentElement
331 if tag.tagName != 'svg':
332 raise ValueError(f'document is <{tag.tagName}> instead of <svg>')
333
334 # generate all the drawing elements
335 self.batch = pyglet.graphics.Batch()
336 self.objects = []
337 for tag in tag.getElementsByTagName('g'):
338 for tag in tag.getElementsByTagName('path'):
339 self.objects.append(Curve(tag.getAttribute('d'), self.batch))
340
341 # determine drawing bounds
342 self.min_x = min(o.min_x for o in self.objects)
343 self.max_x = max(o.max_x for o in self.objects)
344 self.min_y = min(o.min_y for o in self.objects)
345 self.max_y = max(o.max_y for o in self.objects)
346
347 # determine or apply drawing rect
348 if rect is None:
349 self._rect = (self.min_x, self.min_y,
350 self.max_x - self.min_x,
351 self.max_y - self.min_y)
352
353 @property
354 def rect(self):
355 return self._rect
356
357 @rect.setter
358 def rect(self, new_rect):
359 self._rect = new_rect
360 # figure transform for display rect
361 self.translate_x, self.translate_y, rw, rh = new_rect
362 self.scale_x = abs(rw / float(self.max_x - self.min_x))
363 self.scale_y = abs(rh / float(self.max_y - self.min_y))
364
365 def draw(self):
366 glPushMatrix()
367 if self._rect is not None:
368 glScalef(self.scale_x, self.scale_y, 1)
369 glTranslatef(self.translate_x - self.min_x, self.translate_x - self.min_y, 0)
370 self.batch.draw()
371 glPopMatrix()
372
373
374 window = pyglet.window.Window(width=600, height=300, resizable=True)
375
376 dirname = os.path.dirname(__file__)
377 svg = SVG(os.path.join(dirname, 'hello_world.svg'), rect=(0, 0, 600, 300))
378
379
380 @window.event
381 def on_draw():
382 window.clear()
383 svg.draw()
384
385
386 @window.event
387 def on_resize(w, h):
388 print("Resized")
389 svg.rect = svg.rect[:2] + (w, h)
390
391
392 pyglet.app.run()