Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/elements/drawing.py
blob: 85f5247ac81925328456058a1e1d28a6901a601b (plain)
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
"""
This file is part of the 'Elements' Project
Elements is a 2D Physics API for Python (supporting Box2D2)

Copyright (C) 2008, The Elements Team, <elements@linuxuser.at>

Home:  http://elements.linuxuser.at
IRC:   #elements on irc.freenode.org

Code:  http://www.assembla.com/wiki/show/elements
       svn co http://svn2.assembla.com/svn/elements                     

License:  GPLv3 | See LICENSE for the full text
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.              
"""
from math import pi
from math import cos
from math import sin
from math import sqrt

import tools

# Functions of a rendering class 
# mandatory:
#    __init__
#    start_drawing
#    after_drawing
#    draw_circle
#    draw_polygon
#    draw_lines
#    set_lineWidth
#
# renderer-specific mandatory functions:
# for pygame:
#    set_surface
# for cairo:
#    draw_text
# for opengl:
#    

# IMPORTANT
# The drawing functions get the coordinates in their screen coordinate system
# no need for translations anymore :)

class draw_pygame(object):
    """ This class handles the drawing with pygame, which is really
        simple since we only need draw_ellipse and draw_polygon.
    """
    lineWidth = 0
    
    def __init__(self):
        """ Load pygame.draw and pygame.Rect, and reference it for
            the drawing methods
            
            Parameters:
              surface .... pygame surface (default: None)
              lineWidth .. 

            Return: Class draw_pygame()
        """
        print "* Pygame selected as renderer"        
        from pygame import draw
        from pygame import Rect
        
        self.draw = draw
        self.Rect = Rect

    def set_lineWidth(self, lw):
        """
        """
        self.lineWidth = lw

    def set_surface(self, surface):
        """
        """
        self.surface = surface

    def get_surface(self):
        """
        """
        return self.surface

    def start_drawing(self):
        pass
        
    def after_drawing(self):
        pass

    def draw_circle(self, clr, pt, radius, angle):
        """ Draw a circle
        
            Parameters:
              pt ........ (x, y)
              clr ....... color in rgb ((r), (g), (b))
              radius .... circle radius 
              angle ..... rotation in radians
              
            Return: -
        """
        x, y = pt
        
        x1 = x - radius
        y1 = y - radius
        
        rect = self.Rect( [x1, y1, 2*radius, 2*radius] )
        self.draw.ellipse(self.surface, clr, rect, self.lineWidth)
                        
        # draw the orientation vector
        if radius > 10:
            rx = cos(angle) * radius
            ry = -sin(angle) * radius
            
            self.draw.line(self.surface, (255,255,255), pt, (x+rx, y+ry))

    def draw_polygon(self, clr, points):
        """ Draw a polygon
        
            Parameters:
              clr ....... color in rgb ((r), (g), (b))
              points .... polygon points in normal (x,y) positions
              
            Return: -
        """
        self.draw.polygon(self.surface, clr, points, self.lineWidth)
        #self.draw.aalines(self.surface, clr, True, points)

    def draw_lines(self, clr, closed, points, width=None):
        """ Draw a polygon
        
            Parameters:
              clr ....... color in rgb ((r), (g), (b))
              points .... polygon points in normal (x,y) positions
              
            Return: -
        """
        if width == None:
            lw = self.lineWidth
        else: 
            lw = width
            
        self.draw.lines(self.surface, clr, closed, points, lw)

class draw_cairo(object):
    """ This class handles the drawing with cairo, which is really
        simple since we only need draw_ellipse and draw_polygon.
    """
    window = None
    da     = None
    circle_surface = None
    box_surface    = None

    def __init__(self, drawMethod="filled"):
        """ Load cairo.draw and cairo.Rect, and reference it for
            the drawing methods
            
            Return: Class draw_cairo()
        """
        print "* Cairo selected as renderer"
        import cairo
        self.cairo = cairo
        self.set_drawing_method(drawMethod)
        #self.draw_box = self.draw_box_image

    def set_lineWidth(self, lw): # unused
        self.lineWidth = lw 

    def set_drawing_area(self, da):
        """ Set the area for Cairo to draw to
        
            da ...... drawing area (gtk.DrawingArea)

            Return: -
        """
        self.da = da
        self.window = da.window
        print "* Cairo renderer drawing area set"

    def set_drawing_method(self, type):
        """ type = filled, image """
        self.draw_circle = getattr(self, "draw_circle_%s" % type)
        #self.draw_box    = getattr(self, "draw_box_%s" % type)

    def start_drawing(self):
        self.width, self.height = self.window.get_size()
        self.imagesurface = self.cairo.ImageSurface(self.cairo.FORMAT_ARGB32, self.width, self.height);
        self.ctx = ctx = self.cairo.Context(self.imagesurface)

        ctx.set_source_rgb(1, 1, 1) # background color
        ctx.paint()

        ctx.move_to(0, 0)
        ctx.set_source_rgb(0, 0, 0) # defaults for the rest of the drawing
        ctx.set_line_width(1)
        ctx.set_tolerance(0.1)

        ctx.set_line_join(self.cairo.LINE_CAP_BUTT)
        # LINE_CAP_BUTT, LINE_CAP_ROUND, LINE_CAP_SQUARE, LINE_JOIN_BEVEL, LINE_JOIN_MITER, LINE_JOIN_ROUND
        
        #ctx.set_dash([20/4.0, 20/4.0], 0)

    def after_drawing(self):
        dest_ctx = self.window.cairo_create()
        dest_ctx.set_source_surface(self.imagesurface)
        dest_ctx.paint()

    def set_circle_image(self, filename):
        self.circle_surface = self.cairo.ImageSurface.create_from_png(filename)
        self.draw_circle = self.draw_circle_image

#    def set_box_image(self, filename):
#        self.box_surface = self.cairo.ImageSurface.create_from_png(filename)
#        self.draw_box = self.draw_box_image

    def draw_circle_filled(self, clr, pt, radius, angle=0):
        x, y = pt

        clr = tools.rgb2floats(clr)
        self.ctx.set_source_rgb(*clr)
        self.ctx.move_to(x, y)
        self.ctx.arc(x, y, radius, 0, 2*3.1415)
        self.ctx.fill()

    def draw_circle():
        pass

    def draw_circle_image(self, clr, pt, radius, angle=0, sf=None):
        if sf == None:
            sf = self.circle_surface
        x, y = pt
        self.ctx.save()
        self.ctx.translate(x, y)
        self.ctx.rotate(-angle)
        image_r = sf.get_width() / 2
        scale = float(radius) / image_r
        self.ctx.scale(scale, scale)
        self.ctx.translate(-0.5*sf.get_width(), -0.5*sf.get_height())
        self.ctx.set_source_surface(sf)
        self.ctx.paint()
        self.ctx.restore()

    def draw_image(self, source, pt, scale=1.0, rot=0, sourcepos=(0,0)):
        self.ctx.save()
        self.ctx.rotate(rot)
        self.ctx.scale(scale, scale)
        destx, desty = self.ctx.device_to_user_distance(pt[0], pt[1])
        self.ctx.set_source_surface(source, destx-sourcepos[0], desty-sourcepos[1])
        self.ctx.rectangle(destx, desty, source.get_width(), source.get_height())
        self.ctx.fill()
        self.ctx.restore()
                 
    def draw_polygon(self, clr, points):
        """ Draw a polygon
        
            Parameters:
              clr ....... color in rgb ((r), (g), (b))
              points .... polygon points in normal (x,y) positions
              
            Return: -
        """        
        clr = tools.rgb2floats(clr)
        self.ctx.set_source_rgb(clr[0], clr[1], clr[2])

        pt = points[0]
        self.ctx.move_to(pt[0], pt[1])
        for pt in points[1:]:
            self.ctx.line_to(pt[0], pt[1])
            
        self.ctx.fill()
   
    def draw_text(self, text, center, clr=(0,0,0), size=12, fontname="Georgia"):
        clr = tools.rgb2floats(clr)
        self.ctx.set_source_rgb(clr[0], clr[1], clr[2])

        self.ctx.select_font_face(fontname, self.cairo.FONT_SLANT_NORMAL, self.cairo.FONT_WEIGHT_NORMAL)
        self.ctx.set_font_size(size)
        x_bearing, y_bearing, width, height = self.ctx.text_extents(text)[:4]
        self.ctx.move_to(center[0] + 0.5 - width / 2 - x_bearing, center[1] + 0.5 - height / 2 - y_bearing)
        self.ctx.show_text(text)

    def draw_lines(self, clr, closed, points):
        """ Draw a polygon
        
            Parameters:
              clr ....... color in rgb ((r), (g), (b))
              closed .... whether or not to close the lines (as a polygon)
              points .... polygon points in normal (x,y) positions
            Return: -
        """        
        clr = tools.rgb2floats(clr)
        self.ctx.set_source_rgb(clr[0], clr[1], clr[2])

        pt = points[0]
        self.ctx.move_to(pt[0], pt[1])
        for pt in points[1:]:
            self.ctx.line_to(pt[0], pt[1])

        if closed:
            pt = points[0]
            self.ctx.line_to(pt[0], pt[1])

        self.ctx.stroke()

class draw_opengl_pyglet(object):
    """ This class handles the drawing with pyglet
    """
    lineWidth = 0
    def __init__(self):
        """ Load pyglet.gl, and reference it for the drawing methods
            
            Parameters:
              surface .... not used with pyglet
              lineWidth .. 
        """
        print "* OpenGL_Pyglet selected as renderer"

        from pyglet import gl
        self.gl = gl

    def set_lineWidth(self, lw):
        self.lineWidth = lw
    
    def draw_circle(self, clr, pt, radius, a=0):
        clr = tools.rgb2floats(clr)
    	self.gl.glColor3f(clr[0], clr[1], clr[2])

        x, y = pt
    	segs = 15
    	coef = 2.0*pi/segs;
    	
    	self.gl.glBegin(self.gl.GL_LINE_LOOP)
    	for n in range(segs):
    		rads = n*coef
    		self.gl.glVertex2f(radius*cos(rads + a) + x, radius*sin(rads + a) + y)
    	self.gl.glVertex2f(x,y)
    	self.gl.glEnd()

    def draw_polygon(self, clr, points):
        clr = tools.rgb2floats(clr)
    	self.gl.glColor3f(clr[0], clr[1], clr[2])
    	
        self.gl.glBegin(self.gl.GL_LINES)

        p1 = points[0]
        for p in points[1:]:
            x1, y1 = p1
            x2, y2 = p1 = p
            
            self.gl.glVertex2f(x1, y1)
            self.gl.glVertex2f(x2, y2)

        x1, y1 = points[0]
        
        self.gl.glVertex2f(x2, y2)
        self.gl.glVertex2f(x1, y1)

        self.gl.glEnd()
                
    def draw_lines(self, clr, closed, points):
        pass

    def start_drawing(self):
        pass
        
    def after_drawing(self):
        pass