/[thuban]/branches/WIP-pyshapelib-bramz/Thuban/UI/baserenderer.py
ViewVC logotype

Contents of /branches/WIP-pyshapelib-bramz/Thuban/UI/baserenderer.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1918 - (show annotations)
Mon Nov 3 17:33:19 2003 UTC (21 years, 4 months ago) by bh
Original Path: trunk/thuban/Thuban/UI/baserenderer.py
File MIME type: text/x-python
File size: 17208 byte(s)
(BaseRenderer.draw_shape_layer_incrementally): Use the ReadValue
method. ReadValue is faster than ReadRowAsDict since it only reads
one cell especially now that the dbf file objects actually
implement it.

1 # Copyright (c) 2001, 2002, 2003 by Intevation GmbH
2 # Authors:
3 # Bernhard Herzog <[email protected]>
4 # Jonathan Coles <[email protected]>
5 # Frank Koormann <[email protected]>
6 #
7 # This program is free software under the GPL (>=v2)
8 # Read the file COPYING coming with Thuban for details.
9
10 """Basic rendering logic for Thuban maps
11
12 The code in this module is completely independend of wx so that it can
13 be tested reasonably easily and it could make it easier to write non-wx
14 renderers.
15 """
16
17 from __future__ import generators
18
19 __version__ = "$Revision$"
20 # $Source$
21 # $Id$
22
23 import traceback
24
25 from Thuban.Model.layer import Layer, RasterLayer
26 from Thuban.Model.data import SHAPETYPE_ARC, SHAPETYPE_POINT
27 from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \
28 ALIGN_LEFT, ALIGN_RIGHT
29
30 import Thuban.Model.resource
31
32 if Thuban.Model.resource.has_gdal_support():
33 from gdalwarp import ProjectRasterFile
34
35
36 class BaseRenderer:
37
38 """Basic Renderer Infrastructure for Thuban Maps
39
40 This class can't be used directly to render because it doesn't know
41 anything about real DCs such as how to create pens or brushes. That
42 functionality has to be provided by derived classes. The reason for
43 this is that it makes the BaseRenderer completely independend of wx
44 and thus it's quite easy to write test cases for it.
45 """
46 # If true the render honors the visibility flag of the layers
47 honor_visibility = 1
48
49 # Transparent brushes and pens. Derived classes should define these
50 # as appropriate.
51 TRANSPARENT_PEN = None
52 TRANSPARENT_BRUSH = None
53
54 def __init__(self, dc, map, scale, offset, region = None,
55 resolution = 72.0, honor_visibility = None):
56 """Inititalize the renderer.
57
58 dc -- the device context to render on.
59
60 scale, offset -- the scale factor and translation to convert
61 between projected coordinates and the DC coordinates
62
63 region -- The region to draw as a (x, y, width, height) tuple in
64 the map's coordinate system. Default is None meaning
65 to draw everything.
66
67 resolution -- the assumed resolution of the DC. Used to convert
68 absolute lengths like font sizes to DC coordinates. The
69 default is 72.0. If given, this parameter must be
70 provided as a keyword argument.
71
72 honor_visibility -- boolean. If true, honor the visibility flag
73 of the layers, otherwise draw all layers. If None (the
74 default), use the renderer's default. If given, this
75 parameter must be provided as a keyword argument.
76 """
77 # resolution in pixel/inch
78 self.dc = dc
79 self.map = map
80 self.scale = scale
81 self.offset = offset
82 self.region = region
83 if honor_visibility is not None:
84 self.honor_visibility = honor_visibility
85 # store the resolution in pixel/point because it's more useful
86 # later.
87 self.resolution = resolution / 72.0
88
89 def tools_for_property(self, prop):
90 """Return a suitable pen and brush for the property
91
92 This method must be implemented in derived classes. The return
93 value should be a tuple (pen, brush).
94 """
95 raise NotImplementedError
96
97 def render_map(self):
98 """Render the map onto the DC.
99
100 Both map and DC are the ones the renderer was instantiated with.
101
102 This method is just a front-end for render_map_incrementally
103 which does all rendering in one go. It also calls the dc's
104 BeginDrawing and EndDrawing methods before and after calling
105 render_map_incrementally.
106 """
107
108 self.dc.BeginDrawing()
109 try:
110 for cont in self.render_map_incrementally():
111 pass
112 finally:
113 self.dc.EndDrawing()
114
115 def render_map_incrementally(self):
116 """Render the map incrementally.
117
118 Return an iterator whose next method should be called until it
119 returns False. After returning False it will raise StopIteration
120 so that you could also use it in a for loop (implementation
121 detail: this method is implemented as a generator).
122
123 Iterate through all layers and draw them. Layers containing
124 vector data are drawn with the draw_shape_layer method, raster
125 layers are drawn with draw_raster_layer. The label layer is
126 drawn last with draw_label_layer.
127
128 During execution of this method, the map is bound to self.map so
129 that methods especially in derived classes have access to the
130 map if necessary.
131 """
132 # Whether the raster layer has already been drawn. See below for
133 # the optimization this is used for
134 seenRaster = True
135
136 #
137 # This is only a good optimization if there is only one
138 # raster layer and the image covers the entire window (as
139 # it currently does). We note if there is a raster layer
140 # and only begin drawing layers once we have drawn it.
141 # That way we avoid drawing layers that won't be seen.
142 #
143 if Thuban.Model.resource.has_gdal_support():
144 for layer in self.map.Layers():
145 if isinstance(layer, RasterLayer) and layer.Visible():
146 seenRaster = False
147 break
148
149 for layer in self.map.Layers():
150 # if honor_visibility is true, only draw visible layers,
151 # otherwise draw all layers
152 if not self.honor_visibility or layer.Visible():
153 if isinstance(layer, Layer) and seenRaster:
154 for i in self.draw_shape_layer_incrementally(layer):
155 yield True
156 elif isinstance(layer, RasterLayer) \
157 and Thuban.Model.resource.has_gdal_support():
158 self.draw_raster_layer(layer)
159 seenRaster = True
160 yield True
161
162 self.draw_label_layer(self.map.LabelLayer())
163 yield False
164
165 def draw_shape_layer_incrementally(self, layer):
166 """Draw the shape layer layer onto the map incrementally.
167
168 This method is a generator which yields True after every 500
169 shapes.
170 """
171 scale = self.scale
172 offx, offy = self.offset
173
174 map_proj = self.map.projection
175 layer_proj = layer.projection
176
177 brush = self.TRANSPARENT_BRUSH
178 pen = self.TRANSPARENT_PEN
179
180 old_prop = None
181 old_group = None
182 lc = layer.GetClassification()
183 field = layer.GetClassificationColumn()
184 defaultGroup = lc.GetDefaultGroup()
185 table = layer.ShapeStore().Table()
186
187 if lc.GetNumGroups() == 0:
188 # There's only the default group, so we can pretend that
189 # there is no field to classifiy on which makes things
190 # faster since we don't need the attribute information at
191 # all.
192 field = None
193
194 # Determine which render function to use.
195 useraw, draw_func, draw_func_param = self.low_level_renderer(layer)
196
197 #
198 # Iterate through all shapes that have to be drawn.
199 #
200
201 # Count the shapes drawn so that we can yield every few hundred
202 # shapes
203 count = 0
204
205 # Cache the tools (pens and brushes) for the classification
206 # groups. This is a mapping from the group's ids to the a tuple
207 # (pen, brush)
208 tool_cache = {}
209
210 for shape in self.layer_shapes(layer):
211 count += 1
212 if field is None:
213 group = defaultGroup
214 else:
215 value = table.ReadValue(shape.ShapeID(), field)
216 group = lc.FindGroup(value)
217
218 if not group.IsVisible():
219 continue
220
221 try:
222 pen, brush = tool_cache[id(group)]
223 except KeyError:
224 pen, brush = tool_cache[id(group)] \
225 = self.tools_for_property(group.GetProperties())
226
227 if useraw:
228 data = shape.RawData()
229 else:
230 data = shape.Points()
231 draw_func(draw_func_param, data, pen, brush)
232 if count % 500 == 0:
233 yield True
234
235 def layer_shapes(self, layer):
236 """Return an iterable over the shapes to be drawn from the given layer.
237
238 The default implementation simply returns all ids in the layer.
239 Override in derived classes to be more precise.
240 """
241 return layer.ShapeStore().AllShapes()
242
243 def low_level_renderer(self, layer):
244 """Return the low-level renderer for the layer for draw_shape_layer
245
246 The low level renderer to be returned by this method is a tuple
247 (useraw, func, param) where useraw is a boolean indicating
248 whether the function uses the raw shape data, func is a callable
249 object and param is passed as the first parameter to func. The
250 draw_shape_layer method will call func like this:
251
252 func(param, shapedata, pen, brush)
253
254 where shapedata is the return value of the RawData method of the
255 shape object if useraw is true or the return value of the Points
256 method if it's false. pen and brush are the pen and brush to use
257 to draw the shape on the dc.
258
259 The default implementation returns one of
260 self.draw_polygon_shape, self.draw_arc_shape or
261 self.draw_point_shape as func and layer as param. None of the
262 method use the raw shape data. Derived classes can override this
263 method to return more efficient low level renderers.
264 """
265 shapetype = layer.ShapeType()
266 if shapetype == SHAPETYPE_POINT:
267 func = self.draw_point_shape
268 elif shapetype == SHAPETYPE_ARC:
269 func = self.draw_arc_shape
270 else:
271 func = self.draw_polygon_shape
272 return False, func, layer
273
274 def make_point(self, x, y):
275 """Convert (x, y) to a point object.
276
277 Derived classes must override this method.
278 """
279 raise NotImplementedError
280
281 def projected_points(self, layer, points):
282 """Return the projected coordinates of the points taken from layer.
283
284 Transform all the points in the list of lists of coordinate
285 pairs in points.
286
287 The transformation applies the inverse of the layer's projection
288 if any, then the map's projection if any and finally applies
289 self.scale and self.offset.
290
291 The returned list has the same structure as the one returned the
292 shape's Points method.
293 """
294 proj = self.map.GetProjection()
295 if proj is not None:
296 forward = proj.Forward
297 else:
298 forward = None
299 proj = layer.GetProjection()
300 if proj is not None:
301 inverse = proj.Inverse
302 else:
303 inverse = None
304 result = []
305 scale = self.scale
306 offx, offy = self.offset
307 make_point = self.make_point
308 for part in points:
309 result.append([])
310 for x, y in part:
311 if inverse:
312 x, y = inverse(x, y)
313 if forward:
314 x, y = forward(x, y)
315 result[-1].append(make_point(x * scale + offx,
316 -y * scale + offy))
317 return result
318
319 def draw_polygon_shape(self, layer, points, pen, brush):
320 """Draw a polygon shape from layer with the given brush and pen
321
322 The shape is given by points argument which is a the return
323 value of the shape's Points() method. The coordinates in the
324 DC's coordinate system are determined with
325 self.projected_points.
326 """
327 points = self.projected_points(layer, points)
328
329 if brush is not self.TRANSPARENT_BRUSH:
330 polygon = []
331 for part in points:
332 polygon.extend(part)
333
334 insert_index = len(polygon)
335 for part in points[:-1]:
336 polygon.insert(insert_index, part[0])
337
338 self.dc.SetBrush(brush)
339 self.dc.SetPen(self.TRANSPARENT_PEN)
340 self.dc.DrawPolygon(polygon)
341
342 if pen is not self.TRANSPARENT_PEN:
343 # At last draw the boundarys of the simple polygons
344 self.dc.SetBrush(self.TRANSPARENT_BRUSH)
345 self.dc.SetPen(pen)
346 for part in points:
347 self.dc.DrawLines(part)
348
349 def draw_arc_shape(self, layer, points, pen, brush):
350 """Draw an arc shape from layer with the given brush and pen
351
352 The shape is given by points argument which is a the return
353 value of the shape's Points() method. The coordinates in the
354 DC's coordinate system are determined with
355 self.projected_points.
356 """
357 points = self.projected_points(layer, points)
358 self.dc.SetBrush(brush)
359 self.dc.SetPen(pen)
360 for part in points:
361 self.dc.DrawLines(part)
362
363 def draw_point_shape(self, layer, points, pen, brush):
364 """Draw a point shape from layer with the given brush and pen
365
366 The shape is given by points argument which is a the return
367 value of the shape's Points() method. The coordinates in the
368 DC's coordinate system are determined with
369 self.projected_points.
370
371 The point is drawn as a circle centered on the point.
372 """
373 points = self.projected_points(layer, points)
374 if not points:
375 return
376
377 radius = self.resolution * 5
378 self.dc.SetBrush(brush)
379 self.dc.SetPen(pen)
380 for part in points:
381 for p in part:
382 self.dc.DrawEllipse(p.x - radius, p.y - radius,
383 2 * radius, 2 * radius)
384
385 def draw_raster_layer(self, layer):
386 """Draw the raster layer
387
388 This implementation does the projection and scaling of the data
389 as required by the layer's and map's projections and the scale
390 and offset of the renderer and then hands the transformed data
391 to self.draw_raster_data() which has to be implemented in
392 derived classes.
393 """
394 offx, offy = self.offset
395 width, height = self.dc.GetSizeTuple()
396
397 in_proj = ""
398 proj = layer.GetProjection()
399 if proj is not None:
400 for p in proj.GetAllParameters():
401 in_proj += "+" + p + " "
402
403 out_proj = ""
404 proj = self.map.GetProjection()
405 if proj is not None:
406 for p in proj.GetAllParameters():
407 out_proj += "+" + p + " "
408
409 xmin = (0 - offx) / self.scale
410 ymin = (offy - height) / self.scale
411 xmax = (width - offx) / self.scale
412 ymax = (offy - 0) / self.scale
413
414 try:
415 data = ProjectRasterFile(layer.GetImageFilename(),
416 in_proj, out_proj,
417 (xmin, ymin, xmax, ymax), "",
418 (width, height))
419 except (IOError, AttributeError, ValueError):
420 # Why does this catch AttributeError and ValueError?
421 # FIXME: The exception should be communicated to the user
422 # better.
423 traceback.print_exc()
424 else:
425 self.draw_raster_data(data)
426
427 def draw_raster_data(self, data):
428 """Draw the raster image in data onto the DC
429
430 The raster image data is a string holding the data in BMP
431 format. The data is exactly the size of the dc and covers it
432 completely.
433
434 This method has to be implemented by derived classes.
435 """
436 raise NotImplementedError
437
438 def label_font(self):
439 """Return the font object for the label layer"""
440 raise NotImplementedError
441
442 def draw_label_layer(self, layer):
443 """Draw the label layer
444
445 All labels are draw in the font returned by self.label_font().
446 """
447 scale = self.scale
448 offx, offy = self.offset
449
450 self.dc.SetFont(self.label_font())
451
452 map_proj = self.map.projection
453 if map_proj is not None:
454 forward = map_proj.Forward
455 else:
456 forward = None
457
458 for label in layer.Labels():
459 x = label.x
460 y = label.y
461 text = label.text
462 if forward:
463 x, y = forward(x, y)
464 x = x * scale + offx
465 y = -y * scale + offy
466 width, height = self.dc.GetTextExtent(text)
467 if label.halign == ALIGN_LEFT:
468 # nothing to be done
469 pass
470 elif label.halign == ALIGN_RIGHT:
471 x = x - width
472 elif label.halign == ALIGN_CENTER:
473 x = x - width/2
474 if label.valign == ALIGN_TOP:
475 # nothing to be done
476 pass
477 elif label.valign == ALIGN_BOTTOM:
478 y = y - height
479 elif label.valign == ALIGN_CENTER:
480 y = y - height/2
481 self.dc.DrawText(text, x, y)

Properties

Name Value
svn:eol-style native
svn:keywords Author Date Id Revision

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26