Repository navigation
Expand file tree
/
Copy pathcontext.py
More file actions
4134 lines (3638 loc) · 156 KB
/
Copy pathcontext.py
File metadata and controls
4134 lines (3638 loc) · 156 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#=== CONTEXT =========================================================================================
# 2D NodeBox API in OpenGL.
# Authors: Tom De Smedt, Frederik De Bleser
# License: BSD (see LICENSE.txt for details).
# Copyright (c) 2008-2012 City In A Bottle (cityinabottle.org)
# http://cityinabottle.org/nodebox
# All graphics are drawn directly to the screen.
# No scenegraph is kept for obvious performance reasons (therefore, no canvas._grobs as in NodeBox).
# Debugging must be switched on or of before other modules are imported.
import pyglet
pyglet.options['debug_gl'] = False
from pyglet.gl import *
from pyglet.image import Texture
from math import cos, sin, radians, pi, floor
from time import time
from random import seed, choice, shuffle, random as rnd
from new import instancemethod
from glob import glob
from os import path, remove
from sys import getrefcount
from StringIO import StringIO
from hashlib import md5
from types import FunctionType
from datetime import datetime
from numbers import Number
import geometry
#import bezier
# Do this at the end, when we have defined BezierPath, which is needed in the bezier module.
#import shader
# Do this when we have defined texture() and image(), which are needed in the shader module.
# OpenGL version, e.g. "2.0 NVIDIA-1.5.48".
OPENGL = pyglet.gl.gl_info.get_version()
#=====================================================================================================
#--- CACHING -----------------------------------------------------------------------------------------
# OpenGL Display Lists offer a simple way to precompile batches of OpenGL commands.
# The drawback is that the commands, once compiled, can't be modified.
def precompile(function, *args, **kwargs):
""" Creates an OpenGL Display List from the OpenGL commands in the given function.
A Display List will precompile the commands and (if possible) store them in graphics memory.
Returns an id which can be used with precompiled() to execute the cached commands.
"""
id = glGenLists(1)
glNewList(id, GL_COMPILE)
function(*args, **kwargs)
glEndList()
return id
def precompiled(id):
""" Executes the Display List program with the given id.
"""
glCallList(id)
def flush(id):
""" Removes the Display List program with the given id from memory.
"""
if id is not None:
glDeleteLists(id, 1)
#=====================================================================================================
#--- COLOR -------------------------------------------------------------------------------------------
RGB = "RGB"
HSB = "HSB"
XYZ = "XYZ"
LAB = "LAB"
_background = None # Current state background color.
_fill = None # Current state fill color.
_stroke = None # Current state stroke color.
_strokewidth = 1 # Current state strokewidth.
_strokestyle = "solid" # Current state strokestyle.
_alpha = 1 # Current state alpha transparency.
class Color(list):
def __init__(self, *args, **kwargs):
""" A color with R,G,B,A channels, with channel values ranging between 0.0-1.0.
Either takes four parameters (R,G,B,A), three parameters (R,G,B),
two parameters (grayscale and alpha) or one parameter (grayscale or Color object).
An optional base=1.0 parameter defines the range of the given parameters.
An optional colorspace=RGB defines the color space of the given parameters.
"""
# Values are supplied as a tuple.
if len(args) == 1 and isinstance(args[0], (list, tuple)):
args = args[0]
# R, G, B and A.
if len(args) == 4:
r, g, b, a = args[0], args[1], args[2], args[3]
# R, G and B.
elif len(args) == 3:
r, g, b, a = args[0], args[1], args[2], 1
# Two values, grayscale and alpha.
elif len(args) == 2:
r, g, b, a = args[0], args[0], args[0], args[1]
# One value, another color object.
elif len(args) == 1 and isinstance(args[0], Color):
r, g, b, a = args[0].r, args[0].g, args[0].b, args[0].a
# One value, None.
elif len(args) == 1 and args[0] is None:
r, g, b, a = 0, 0, 0, 0
# One value, grayscale.
elif len(args) == 1:
r, g, b, a = args[0], args[0], args[0], 1
# No value, transparent black.
elif len(args):
r, g, b, a = 0, 0, 0, 0
# Transform to base 1:
base = float(kwargs.get("base", 1.0))
if base != 1:
r, g, b, a = [ch/base for ch in r, g, b, a]
# Transform to color space RGB:
colorspace = kwargs.get("colorspace")
if colorspace and colorspace != RGB:
if colorspace == HSB: r, g, b = hsb_to_rgb(r, g, b)
if colorspace == XYZ: r, g, b = xyz_to_rgb(r, g, b)
if colorspace == LAB: r, g, b = lab_to_rgb(r, g, b)
list.__init__(self, [r, g, b, a])
self._dirty = False
def __setitem__(self, i, v):
list.__setitem__(self, i, v)
self._dirty = True
def _get_r(self): return self[0]
def _get_g(self): return self[1]
def _get_b(self): return self[2]
def _get_a(self): return self[3]
def _set_r(self, v): self[0] = v
def _set_g(self, v): self[1] = v
def _set_b(self, v): self[2] = v
def _set_a(self, v): self[3] = v
r = red = property(_get_r, _set_r)
g = green = property(_get_g, _set_g)
b = blue = property(_get_b, _set_b)
a = alpha = property(_get_a, _set_a)
def _get_rgb(self):
return self[0], self[1], self[2]
def _set_rgb(self, (r,g,b)):
self[0] = r
self[1] = g
self[2] = b
rgb = property(_get_rgb, _set_rgb)
def _get_rgba(self):
return self[0], self[1], self[2], self[3]
def _set_rgba(self, (r,g,b,a)):
self[0] = r
self[1] = g
self[2] = b
self[3] = a
rgba = property(_get_rgba, _set_rgba)
def copy(self):
return Color(self)
def _apply(self):
glColor4f(self[0], self[1], self[2], self[3] * _alpha)
def __repr__(self):
return "Color(%.3f, %.3f, %.3f, %.3f)" % \
(self[0], self[1], self[2], self[3])
def __eq__(self, clr):
if not isinstance(clr, Color): return False
return self[0] == clr[0] \
and self[1] == clr[1] \
and self[2] == clr[2] \
and self[3] == clr[3]
def __ne__(self, clr):
return not self.__eq__(clr)
def map(self, base=1.0, colorspace=RGB):
""" Returns a list of R,G,B,A values mapped to the given base,
e.g. from 0-255 instead of 0.0-1.0 which is useful for setting image pixels.
Other values than RGBA can be obtained by setting the colorspace (RGB/HSB/XYZ/LAB).
"""
r, g, b, a = self
if colorspace != RGB:
if colorspace == HSB: r, g, b = rgb_to_hsb(r, g, b)
if colorspace == XYZ: r, g, b = rgb_to_xyz(r, g, b)
if colorspace == LAB: r, g, b = rgb_to_lab(r, g, b)
if base != 1:
r, g, b, a = [ch*base for ch in r, g, b, a]
if base != 1 and isinstance(base, int):
r, g, b, a = [int(ch) for ch in r, g, b, a]
return r, g, b, a
def blend(self, clr, t=0.5, colorspace=RGB):
""" Returns a new color between the two colors.
Parameter t is the amount to interpolate between the two colors
(0.0 equals the first color, 0.5 is half-way in between, etc.)
Blending in CIE-LAB colorspace avoids "muddy" colors in the middle of the blend.
"""
ch = zip(self.map(1, colorspace)[:3], clr.map(1, colorspace)[:3])
r, g, b = [geometry.lerp(a, b, t) for a, b in ch]
a = geometry.lerp(self.a, len(clr)==4 and clr[3] or 1, t)
return Color(r, g, b, a, colorspace=colorspace)
def rotate(self, angle):
""" Returns a new color with it's hue rotated on the RYB color wheel.
"""
h, s, b = rgb_to_hsb(*self[:3])
h, s, b = rotate_ryb(h, s, b, angle)
return Color(h, s, b, self.a, colorspace=HSB)
color = Color
def background(*args, **kwargs):
""" Sets the current background color.
"""
global _background
if args:
_background = Color(*args, **kwargs)
xywh = (GLint*4)(); glGetIntegerv(GL_VIEWPORT, xywh); x,y,w,h = xywh
rect(x, y, w, h, fill=_background, stroke=None)
return _background
def fill(*args, **kwargs):
""" Sets the current fill color for drawing primitives and paths.
"""
global _fill
if args:
_fill = Color(*args, **kwargs)
return _fill
fill(0) # The default fill is black.
def stroke(*args, **kwargs):
""" Sets the current stroke color.
"""
global _stroke
if args:
_stroke = Color(*args, **kwargs)
return _stroke
def nofill():
""" No current fill color.
"""
global _fill
_fill = None
def nostroke():
""" No current stroke color.
"""
global _stroke
_stroke = None
def strokewidth(width=None):
""" Sets the outline stroke width.
"""
# Note: strokewidth is clamped to integers (e.g. 0.2 => 1),
# but finer lines can be achieved visually with a transparent stroke.
# Thicker strokewidth results in ugly (i.e. no) line caps.
global _strokewidth
if width is not None:
_strokewidth = width
glLineWidth(width)
return _strokewidth
SOLID = "solid"
DOTTED = "dotted"
DASHED = "dashed"
def strokestyle(style=None):
""" Sets the outline stroke style (SOLID / DOTTED / DASHED).
"""
global _strokestyle
if style is not None and style != _strokestyle:
_strokestyle = style
glLineDash(style)
return _strokestyle
def glLineDash(style):
if style == SOLID:
glDisable(GL_LINE_STIPPLE)
elif style == DOTTED:
glEnable(GL_LINE_STIPPLE); glLineStipple(0, 0x0101)
elif style == DASHED:
glEnable(GL_LINE_STIPPLE); glLineStipple(1, 0x000F)
def outputmode(mode=None):
raise NotImplementedError
def colormode(mode=None, range=1.0):
raise NotImplementedError
#--- COLOR SPACE -------------------------------------------------------------------------------------
# Transformations between RGB, HSB, CIE XYZ and CIE LAB color spaces.
# http://www.easyrgb.com/math.php
def rgb_to_hsb(r, g, b):
""" Converts the given R,G,B values to H,S,B (between 0.0-1.0).
"""
h, s, v = 0, 0, max(r, g, b)
d = v - min(r, g, b)
if v != 0:
s = d / float(v)
if s != 0:
if r == v: h = 0 + (g-b) / d
elif g == v: h = 2 + (b-r) / d
else : h = 4 + (r-g) / d
h = h / 6.0 % 1
return h, s, v
def hsb_to_rgb(h, s, v):
""" Converts the given H,S,B color values to R,G,B (between 0.0-1.0).
"""
if s == 0:
return v, v, v
h = h % 1 * 6.0
i = floor(h)
f = h - i
x = v * (1-s)
y = v * (1-s * f)
z = v * (1-s * (1-f))
if i > 4:
return v, x, y
return [(v,z,x), (y,v,x), (x,v,z), (x,y,v), (z,x,v)][int(i)]
def rgb_to_xyz(r, g, b):
""" Converts the given R,G,B values to CIE X,Y,Z (between 0.0-1.0).
"""
r, g, b = [ch > 0.04045 and ((ch+0.055) / 1.055) ** 2.4 or ch / 12.92 for ch in r, g, b]
r, g, b = [ch * 100.0 for ch in r, g, b]
r, g, b = ( # Observer = 2, Illuminant = D65
r * 0.4124 + g * 0.3576 + b * 0.1805,
r * 0.2126 + g * 0.7152 + b * 0.0722,
r * 0.0193 + g * 0.1192 + b * 0.9505)
return r/95.047, g/100.0, b/108.883
def xyz_to_rgb(x, y, z):
""" Converts the given CIE X,Y,Z color values to R,G,B (between 0.0-1.0).
"""
x, y, z = x*95.047, y*100.0, z*108.883
x, y, z = [ch / 100.0 for ch in x, y, z]
r = x * 3.2406 + y * -1.5372 + z * -0.4986
g = x * -0.9689 + y * 1.8758 + z * 0.0415
b = x * -0.0557 + y * -0.2040 + z * 1.0570
r, g, b = [ch > 0.0031308 and 1.055 * ch**(1/2.4) - 0.055 or ch * 12.92 for ch in r, g, b]
return r, g, b
def rgb_to_lab(r, g, b):
""" Converts the given R,G,B values to CIE L,A,B (between 0.0-1.0).
"""
x, y, z = rgb_to_xyz(r, g, b)
x, y, z = [ch > 0.008856 and ch**(1/3.0) or (ch*7.787) + (16/116.0) for ch in x, y, z]
l, a, b = y*116-16, 500*(x-y), 200*(y-z)
l, a, b = l/100.0, (a+86)/(86+98), (b+108)/(108+94)
return l, a, b
def lab_to_rgb(l, a, b):
""" Converts the given CIE L,A,B color values to R,G,B (between 0.0-1.0).
"""
l, a, b = l*100, a*(86+98)-86, b*(108+94)-108
y = (l+16)/116.0
x = y + a/500.0
z = y - b/200.0
x, y, z = [ch**3 > 0.008856 and ch**3 or (ch-16/116.0)/7.787 for ch in x, y, z]
return xyz_to_rgb(x, y, z)
def luminance(r, g, b):
""" Returns an indication (0.0-1.0) of how bright the color appears.
"""
return (r*0.2125 + g*0.7154 + b+0.0721) * 0.5
def darker(clr, step=0.2):
""" Returns a copy of the color with a darker brightness.
"""
h, s, b = rgb_to_hsb(clr.r, clr.g, clr.b)
r, g, b = hsb_to_rgb(h, s, max(0, b-step))
return Color(r, g, b, len(clr)==4 and clr[3] or 1)
def lighter(clr, step=0.2):
""" Returns a copy of the color with a lighter brightness.
"""
h, s, b = rgb_to_hsb(clr.r, clr.g, clr.b)
r, g, b = hsb_to_rgb(h, s, min(1, b+step))
return Color(r, g, b, len(clr)==4 and clr[3] or 1)
darken, lighten = darker, lighter
#--- COLOR ROTATION ----------------------------------------------------------------------------------
# Approximation of the RYB color wheel.
# In HSB, colors hues range from 0 to 360,
# but on the color wheel these values are not evenly distributed.
# The second tuple value contains the actual value on the wheel (angle).
_colorwheel = [
( 0, 0), ( 15, 8), ( 30, 17), ( 45, 26),
( 60, 34), ( 75, 41), ( 90, 48), (105, 54),
(120, 60), (135, 81), (150, 103), (165, 123),
(180, 138), (195, 155), (210, 171), (225, 187),
(240, 204), (255, 219), (270, 234), (285, 251),
(300, 267), (315, 282), (330, 298), (345, 329), (360, 360)
]
def rotate_ryb(h, s, b, angle=180):
""" Rotates the given H,S,B color (0.0-1.0) on the RYB color wheel.
The RYB colorwheel is not mathematically precise,
but focuses on aesthetically pleasing complementary colors.
"""
h = h*360 % 360
# Find the location (angle) of the hue on the RYB color wheel.
for i in range(len(_colorwheel)-1):
(x0, y0), (x1, y1) = _colorwheel[i], _colorwheel[i+1]
if y0 <= h <= y1:
a = geometry.lerp(x0, x1, t=(h-y0)/(y1-y0))
break
# Rotate the angle and retrieve the hue.
a = (a+angle) % 360
for i in range(len(_colorwheel)-1):
(x0, y0), (x1, y1) = _colorwheel[i], _colorwheel[i+1]
if x0 <= a <= x1:
h = geometry.lerp(y0, y1, t=(a-x0)/(x1-x0))
break
return h/360.0, s, b
def complement(clr):
""" Returns the color opposite on the color wheel.
The complementary color contrasts with the given color.
"""
if not isinstance(clr, Color):
clr = Color(clr)
return clr.rotate(180)
def analog(clr, angle=20, d=0.1):
""" Returns a random adjacent color on the color wheel.
Analogous color schemes can often be found in nature.
"""
h, s, b = rgb_to_hsb(*clr[:3])
h, s, b = rotate_ryb(h, s, b, angle=random(-angle,angle))
s *= 1 - random(-d,d)
b *= 1 - random(-d,d)
return Color(h, s, b, len(clr)==4 and clr[3] or 1, colorspace=HSB)
#--- COLOR MIXIN -------------------------------------------------------------------------------------
# Drawing commands like rect() have optional parameters fill and stroke to set the color directly.
def color_mixin(**kwargs):
fill = kwargs.get("fill", _fill)
stroke = kwargs.get("stroke", _stroke)
strokewidth = kwargs.get("strokewidth", _strokewidth)
strokestyle = kwargs.get("strokestyle", _strokestyle)
return (fill, stroke, strokewidth, strokestyle)
#--- COLOR PLANE -------------------------------------------------------------------------------------
# Not part of the standard API but too convenient to leave out.
def colorplane(x, y, width, height, *a):
""" Draws a rectangle that emits a different fill color from each corner.
An optional number of colors can be given:
- four colors define top left, top right, bottom right and bottom left,
- three colors define top left, top right and bottom,
- two colors define top and bottom,
- no colors assumes black top and white bottom gradient.
"""
if len(a) == 2:
# Top and bottom colors.
clr1, clr2, clr3, clr4 = a[0], a[0], a[1], a[1]
elif len(a) == 4:
# Top left, top right, bottom right, bottom left.
clr1, clr2, clr3, clr4 = a[0], a[1], a[2], a[3]
elif len(a) == 3:
# Top left, top right, bottom.
clr1, clr2, clr3, clr4 = a[0], a[1], a[2], a[2]
elif len(a) == 0:
# Black top, white bottom.
clr1 = clr2 = (0,0,0,1)
clr3 = clr4 = (1,1,1,1)
glPushMatrix()
glTranslatef(x, y, 0)
glScalef(width, height, 1)
glBegin(GL_QUADS)
glColor4f(clr1[0], clr1[1], clr1[2], clr1[3] * _alpha); glVertex2f(-0.0, 1.0)
glColor4f(clr2[0], clr2[1], clr2[2], clr2[3] * _alpha); glVertex2f( 1.0, 1.0)
glColor4f(clr3[0], clr3[1], clr3[2], clr3[3] * _alpha); glVertex2f( 1.0, -0.0)
glColor4f(clr4[0], clr4[1], clr4[2], clr4[3] * _alpha); glVertex2f(-0.0, -0.0)
glEnd()
glPopMatrix()
#=====================================================================================================
#--- TRANSFORMATIONS ---------------------------------------------------------------------------------
# Unlike NodeBox, all transformations are CORNER-mode and originate from the bottom-left corner.
# Example: using Transform to get a transformed path.
# t = Transform()
# t.rotate(45)
# p = BezierPath()
# p.rect(10,10,100,70)
# p = t.transform_path(p)
# p.contains(x,y) # now we can check if the mouse is in the transformed shape.
Transform = geometry.AffineTransform
def push():
""" Pushes the transformation state.
Subsequent transformations (translate, rotate, scale) remain in effect until pop() is called.
"""
glPushMatrix()
def pop():
""" Pops the transformation state.
This reverts the transformation to before the last push().
"""
glPopMatrix()
def translate(x, y, z=0):
""" By default, the origin of the layer or canvas is at the bottom left.
This origin point will be moved by (x,y) pixels.
"""
glTranslatef(round(x), round(y), round(z))
def rotate(degrees, axis=(0,0,1)):
""" Rotates the transformation state, i.e. all subsequent drawing primitives are rotated.
Rotations work incrementally:
calling rotate(60) and rotate(30) sets the current rotation to 90.
"""
glRotatef(degrees, *axis)
def scale(x, y=None, z=None):
""" Scales the transformation state.
"""
if y is None:
y = x
if z is None:
z = 1
glScalef(x, y, z)
def reset():
""" Resets the transform state of the layer or canvas.
"""
glLoadIdentity()
CORNER = "corner"
CENTER = "center"
def transform(mode=None):
if mode == CENTER:
raise NotImplementedError, "no center-mode transform"
return CORNER
def skew(x, y):
raise NotImplementedError
#=====================================================================================================
#--- DRAWING PRIMITIVES ------------------------------------------------------------------------------
# Drawing primitives: Point, line, rect, ellipse, arrow. star.
# The fill and stroke are two different shapes put on top of each other.
Point = geometry.Point
def line(x0, y0, x1, y1, **kwargs):
""" Draws a straight line from x0, y0 to x1, y1 with the current stroke color and strokewidth.
"""
fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs)
if stroke is not None and strokewidth > 0:
glColor4f(stroke[0], stroke[1], stroke[2], stroke[3] * _alpha)
glLineWidth(strokewidth)
if strokestyle != _strokestyle:
glLineDash(strokestyle)
glBegin(GL_LINES)
glVertex2f(x0, y0)
glVertex2f(x1, y1)
glEnd()
def rect(x, y, width, height, **kwargs):
""" Draws a rectangle with the bottom left corner at x, y.
The current stroke, strokewidth and fill color are applied.
"""
fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs)
if fill is not None:
glColor4f(fill[0], fill[1], fill[2], fill[3] * _alpha)
glRectf(x, y, x+width, y+height)
if stroke is not None and strokewidth > 0:
glLineWidth(strokewidth)
glLineDash(strokestyle)
glColor4f(stroke[0], stroke[1], stroke[2], stroke[3] * _alpha)
# Note: this performs equally well as when using precompile().
glBegin(GL_LINE_LOOP)
glVertex2f(x, y)
glVertex2f(x+width, y)
glVertex2f(x+width, y+height)
glVertex2f(x, y+height)
glEnd()
def triangle(x1, y1, x2, y2, x3, y3, **kwargs):
""" Draws the triangle created by connecting the three given points.
The current stroke, strokewidth and fill color are applied.
"""
fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs)
for i, clr in enumerate((fill, stroke)):
if clr is not None and (i==0 or strokewidth > 0):
if i == 1:
glLineWidth(strokewidth)
if strokestyle != _strokestyle:
glLineDash(strokestyle)
glColor4f(clr[0], clr[1], clr[2], clr[3] * _alpha)
# Note: this performs equally well as when using precompile().
glBegin((GL_TRIANGLES, GL_LINE_LOOP)[i])
glVertex2f(x1, y1)
glVertex2f(x2, y2)
glVertex2f(x3, y3)
glEnd()
_ellipses = {}
ELLIPSE_SEGMENTS = 50
def ellipse(x, y, width, height, segments=ELLIPSE_SEGMENTS, **kwargs):
""" Draws an ellipse with the center located at x, y.
The current stroke, strokewidth and fill color are applied.
"""
if not segments in _ellipses:
# For the given amount of line segments, calculate the ellipse once.
# Then reuse the cached ellipse by scaling it to the desired size.
commands = []
f = 2 * pi / segments
v = [(cos(t)/2, sin(t)/2) for t in [i*f for i in range(segments)+[0]]]
for mode in (GL_TRIANGLE_FAN, GL_LINE_LOOP):
commands.append(precompile(lambda:(
glBegin(mode),
[glVertex2f(x, y) for (x, y) in v],
glEnd()
)))
_ellipses[segments] = commands
fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs)
for i, clr in enumerate((fill, stroke)):
if clr is not None and (i==0 or strokewidth > 0):
if i == 1:
glLineWidth(strokewidth)
if strokestyle != _strokestyle:
glLineDash(strokestyle)
glColor4f(clr[0], clr[1], clr[2], clr[3] * _alpha)
glPushMatrix()
glTranslatef(x, y, 0)
glScalef(width, height, 1)
glCallList(_ellipses[segments][i])
glPopMatrix()
oval = ellipse # Backwards compatibility.
def arrow(x, y, width, **kwargs):
""" Draws an arrow with its tip located at x, y.
The current stroke, strokewidth and fill color are applied.
"""
head = width * 0.4
tail = width * 0.2
fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs)
for i, clr in enumerate((fill, stroke)):
if clr is not None and (i==0 or strokewidth > 0):
if i == 1:
glLineWidth(strokewidth)
glLineDash(strokestyle)
glColor4f(clr[0], clr[1], clr[2], clr[3] * _alpha)
# Note: this performs equally well as when using precompile().
glBegin((GL_POLYGON, GL_LINE_LOOP)[i])
glVertex2f(x, y)
glVertex2f(x-head, y+head)
glVertex2f(x-head, y+tail)
glVertex2f(x-width, y+tail)
glVertex2f(x-width, y-tail)
glVertex2f(x-head, y-tail)
glVertex2f(x-head, y-head)
glVertex2f(x, y)
glEnd()
def gcd(a, b):
return gcd(b, a % b) if b else a
_stars = {} #TODO: LRU?
def fast_star(x, y, points=20, outer=100, inner=50, **kwargs):
""" Draws a star with the given points, outer radius and inner radius.
The current stroke, strokewidth and fill color are applied.
"""
scale = gcd(inner, outer)
iscale = inner / scale
oscale = outer / scale
cached = _stars.get((points, iscale, oscale), [])
if not cached:
radii = [oscale, iscale] * int(points+1); radii.pop() # which radius?
f = pi / points
v = [(r*sin(i*f), r*cos(i*f)) for i, r in enumerate(radii)]
cached.append(precompile(lambda:(
glBegin(GL_TRIANGLE_FAN),
glVertex2f(0, 0),
[glVertex2f(vx, vy) for (vx, vy) in v],
glEnd()
)))
cached.append(precompile(lambda:(
glBegin(GL_LINE_LOOP),
[glVertex2f(vx, vy) for (vx, vy) in v],
glEnd()
)))
_stars[(points, iscale, oscale)] = cached
fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs)
for i, clr in enumerate((fill, stroke)):
if clr is not None and (i == 0 or strokewidth > 0):
if i == 1:
glLineWidth(strokewidth)
if strokestyle != _strokestyle:
glLineDash(strokestyle)
glColor4f(clr[0], clr[1], clr[2], clr[3] * _alpha)
glPushMatrix()
glTranslatef(x, y, 0)
glScalef(scale, scale, 1)
glCallList(cached[i])
glPopMatrix()
def star(x, y, points=20, outer=100, inner=50, **kwargs):
""" Draws a star with the given points, outer radius and inner radius.
The current stroke, strokewidth and fill color are applied.
This is about 20x slower than fast_star; use it only if you need the path returned.
"""
p = BezierPath(**kwargs)
p.moveto(x, y+outer)
for i in range(0, int(2*points)+1):
r = (outer, inner)[i%2]
a = pi*i/points
p.lineto(x+r*sin(a), y+r*cos(a))
p.closepath()
if kwargs.get("draw", True):
p.draw(**kwargs)
return p
#=====================================================================================================
#--- BEZIER PATH -------------------------------------------------------------------------------------
# A BezierPath class with lineto(), curveto() and moveto() commands.
# It has all the path math functionality from NodeBox and a ray casting algorithm for contains().
# A number of caching mechanisms are used for performance:
# drawn vertices, segment lengths, path bounds, and a hit test area for BezierPath.contains().
# For optimal performance, the path should be created once (not every frame) and left unmodified.
# When points in the path are added, removed or modified, a _dirty flag is set.
# When dirty, the cache will be cleared and the new path recalculated.
# If the path is being drawn with a fill color, this means doing tessellation
# (i.e. additional math for finding out if parts overlap and punch a hole in the shape).
MOVETO = "moveto"
LINETO = "lineto"
CURVETO = "curveto"
CLOSE = "close"
RELATIVE = "relative" # Number of straight lines to represent a curve = 20% of curve length.
RELATIVE_PRECISION = 0.2
class PathError(Exception):
pass
class NoCurrentPointForPath(Exception):
pass
class NoCurrentPath(Exception):
pass
class PathPoint(Point):
def __init__(self, x=0, y=0):
""" A control handle for PathElement.
"""
self._x = x
self._y = y
self._dirty = False
def _get_x(self): return self._x
def _set_x(self, v):
self._x = v
self._dirty = True
def _get_y(self): return self._y
def _set_y(self, v):
self._y = v
self._dirty = True
x = property(_get_x, _set_x)
y = property(_get_y, _set_y)
def copy(self, parent=None):
return PathPoint(self._x, self._y)
class PathElement(object):
def __init__(self, cmd=None, pts=None):
""" A point in the path, optionally with control handles:
- MOVETO : the list of points contains a single (x,y)-tuple.
- LINETO : the list of points contains a single (x,y)-tuple.
- CURVETO : the list of points contains (vx1,vy1), (vx2,vy2), (x,y) tuples.
- CLOSETO : no points.
"""
if cmd == MOVETO \
or cmd == LINETO:
pt, h1, h2 = pts[0], pts[0], pts[0]
elif cmd == CURVETO:
pt, h1, h2 = pts[2], pts[0], pts[1]
else:
pt, h1, h2 = (0,0), (0,0), (0,0)
self._cmd = cmd
self._x = pt[0]
self._y = pt[1]
self._ctrl1 = PathPoint(h1[0], h1[1])
self._ctrl2 = PathPoint(h2[0], h2[1])
self.__dirty = False
def _get_dirty(self):
return self.__dirty \
or self.ctrl1._dirty \
or self.ctrl2._dirty
def _set_dirty(self, b):
self.__dirty = b
self.ctrl1._dirty = b
self.ctrl2._dirty = b
_dirty = property(_get_dirty, _set_dirty)
@property
def cmd(self):
return self._cmd
def _get_x(self): return self._x
def _set_x(self, v):
self._x = v
self.__dirty = True
def _get_y(self): return self._y
def _set_y(self, v):
self._y = v
self.__dirty = True
x = property(_get_x, _set_x)
y = property(_get_y, _set_y)
def _get_xy(self):
return (self.x, self.y)
def _set_xy(self, (x,y)):
self.x = x
self.y = y
xy = property(_get_xy, _set_xy)
# Handle 1 describes now the curve from the previous point started.
def _get_ctrl1(self): return self._ctrl1
def _set_ctrl1(self, v):
self._ctrl1 = PathPoint(v.x, v.y)
self.__dirty = True
# Handle 2 describes how the curve from the previous point arrives in this point.
def _get_ctrl2(self): return self._ctrl2
def _set_ctrl2(self, v):
self._ctrl2 = PathPoint(v.x, v.y)
self.__dirty = True
ctrl1 = property(_get_ctrl1, _set_ctrl1)
ctrl2 = property(_get_ctrl2, _set_ctrl2)
def __eq__(self, pt):
if not isinstance(pt, PathElement): return False
return self.cmd == pt.cmd \
and self.x == pt.x \
and self.y == pt.y \
and self.ctrl1 == pt.ctrl1 \
and self.ctrl2 == pt.ctrl2
def __ne__(self, pt):
return not self.__eq__(pt)
def __repr__(self):
return "%s(cmd='%s', x=%.1f, y=%.1f, ctrl1=(%.1f, %.1f), ctrl2=(%.1f, %.1f))" % (
self.__class__.__name__, self.cmd, self.x, self.y,
self.ctrl1.x, self.ctrl1.y,
self.ctrl2.x, self.ctrl2.y)
def copy(self):
if self.cmd == MOVETO \
or self.cmd == LINETO:
pts = ((self.x, self.y),)
elif self.cmd == CURVETO:
pts = ((self.ctrl1.x, self.ctrl1.y), (self.ctrl2.x, self.ctrl2.y), (self.x, self.y))
else:
pts = None
return PathElement(self.cmd, pts)
class BezierPath(list):
def __init__(self, path=None, **kwargs):
""" A list of PathElements describing the curves and lines that make up the path.
"""
if isinstance(path, (BezierPath, list, tuple)):
self.extend([pt.copy() for pt in path])
self._kwargs = kwargs
self._cache = None # Cached vertices for drawing.
self._segments = None # Cached segment lengths.
self._bounds = None # Cached bounding rectangle.
self._polygon = None # Cached polygon hit test area.
self._dirty = False
self._index = {}
def copy(self):
return BezierPath(self, **self._kwargs)
def append(self, pt):
self._dirty = True; list.append(self, pt)
def extend(self, points):
self._dirty = True; list.extend(self, points)
def insert(self, i, pt):
self._dirty = True; self._index={}; list.insert(self, i, pt)
def remove(self, pt):
self._dirty = True; self._index={}; list.remove(self, pt)
def pop(self, i):
self._dirty = True; self._index={}; list.pop(self, i)
def __setitem__(self, i, pt):
self._dirty = True; self._index={}; list.__setitem__(self, i, pt)
def __delitem__(self, i):
self._dirty = True; self._index={}; list.__delitem__(self, i)
def sort(self):
self._dirty = True; self._index={}; list.sort(self)
def reverse(self):
self._dirty = True; self._index={}; list.reverse(self)
def index(self, pt):
return self._index.setdefault(pt, list.index(self, pt))
def _update(self):
# Called from BezierPath.draw().
# If points were added or removed, clear the cache.
b = self._dirty
for pt in self: b = b or pt._dirty; pt._dirty = False
if b:
if self._cache is not None:
if self._cache[0]: flush(self._cache[0])
if self._cache[1]: flush(self._cache[1])
self._cache = self._segments = self._bounds = self._polygon = None
self._dirty = False
def moveto(self, x, y):
""" Adds a new point to the path at x, y.
"""
self.append(PathElement(MOVETO, ((x, y),)))
def lineto(self, x, y):
""" Adds a line from the previous point to x, y.
"""
self.append(PathElement(LINETO, ((x, y),)))
def curveto(self, x1, y1, x2, y2, x3, y3):
""" Adds a Bezier-curve from the previous point to x3, y3.
The curvature is determined by control handles x1, y1 and x2, y2.
"""
self.append(PathElement(CURVETO, ((x1, y1), (x2, y2), (x3, y3))))
def arcto(self, x, y, radius=1, clockwise=True, short=False):
""" Adds a number of Bezier-curves that draw an arc with the given radius to (x,y).
The short parameter selects either the "long way" around or the "shortcut".
"""
x0, y0 = self[-1].x, self[-1].y
phi = geometry.angle(x0,y0,x,y)
for p in bezier.arcto(x0, y0, radius, radius, phi, short, not clockwise, x, y):
f = len(p) == 2 and self.lineto or self.curveto
f(*p)
def closepath(self):
""" Adds a line from the previous point to the last MOVETO.
"""
self.append(PathElement(CLOSE))
def rect(self, x, y, width, height, roundness=0.0):
""" Adds a (rounded) rectangle to the path.
Corner roundness can be given as a relative float or absolute int.
"""
if roundness <= 0:
self.moveto(x, y)
self.lineto(x+width, y)
self.lineto(x+width, y+height)
self.lineto(x, y+height)
self.lineto(x, y)
else:
if isinstance(roundness, int):
r = min(roundness, width/2, height/2)
else:
r = min(width, height)
r = min(roundness, 1) * r * 0.5
self.moveto(x+r, y)
self.lineto(x+width-r, y)
self.arcto(x+width, y+r, radius=r, clockwise=False)