Very basic map event support, plus calculate area centroids correctly.
[potlatch2.git] / net / systemeD / halcyon / WayUI.as
1 package net.systemeD.halcyon {
2
3         import flash.display.*;
4         import flash.geom.Matrix;
5         import flash.geom.Point;
6         import flash.geom.Rectangle;
7         import flash.text.AntiAliasType;
8         import flash.text.GridFitType;
9         import flash.text.TextField;
10         import flash.text.TextFormat;
11         import net.systemeD.halcyon.styleparser.*;
12     import net.systemeD.halcyon.connection.*;
13
14         public class WayUI {
15         private var way:Way;
16
17                 public var pathlength:Number;                           // length of path
18                 public var patharea:Number;                                     // area of path
19                 public var centroid_x:Number;                           // centroid
20                 public var centroid_y:Number;                           //  |
21                 public var layer:int=0;                                         // map layer
22                 public var map:Map;                                                     // reference to parent map
23                 public var sprites:Array=new Array();           // instances in display list
24
25                 public static const DEFAULT_TEXTFIELD_PARAMS:Object = {
26                         embedFonts: true,
27                         antiAliasType: AntiAliasType.ADVANCED,
28                         gridFitType: GridFitType.NONE
29                 };
30                 [Embed(source="fonts/DejaVuSans.ttf", fontFamily="DejaVu", fontWeight="normal", mimeType="application/x-font-truetype")]
31                 public static var DejaVu:Class;
32                 public var nameformat:TextFormat;
33
34
35                 public function WayUI(way:Way, map:Map) {
36                         this.way = way;
37                         this.map = map;
38             init();
39                 }
40                 
41                 private function init():void {
42                         recalculate();
43                         redraw();
44                         // updateBbox(lon, lat);
45                         // ** various other stuff
46                 }
47
48                 // ------------------------------------------------------------------------------------------
49                 // Calculate length etc.
50                 // ** this could be made scale-independent - would speed up redraw
51                 
52                 public function recalculate():void {
53                         var lx:Number, ly:Number, sc:Number;
54                         var cx:Number=0, cy:Number=0;
55                         pathlength=0;
56                         patharea=0;
57                         
58                         lx = way.getNode(way.length-1).lon;
59                         ly = way.getNode(way.length-1).latp;
60                         for ( var i:uint = 0; i < way.length; i++ ) {
61                 var node:Node = way.getNode(i);
62                 var latp:Number = node.latp;
63                 var lon:Number  = node.lon;
64                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
65                                 sc = (lx*latp-lon*ly)*map.scalefactor;
66                                 cx += (lx+lon)*sc;
67                                 cy += (ly+latp)*sc;
68                                 patharea += sc;
69                                 lx=lon; ly=latp;
70                         }
71
72                         pathlength*=map.scalefactor;
73                         patharea/=2;
74                         if (patharea!=0 && way.isArea()) {
75                                 centroid_x=map.lon2coord(cx/patharea/6);
76                                 centroid_y=map.latp2coord(cy/patharea/6);
77                         } else if (pathlength>0) {
78                                 var c:Array=pointAt(0.5);
79                                 centroid_x=c[0];
80                                 centroid_y=c[1];
81                         }
82                 }
83
84                 // ------------------------------------------------------------------------------------------
85                 // Redraw
86
87                 public function redraw():void {
88             var tags:Object = way.getTagsCopy();
89
90                         // remove all currently existing sprites
91                         while (sprites.length>0) {
92                                 var d:Sprite=sprites.pop(); d.parent.removeChild(d);
93                         }
94
95                         // which layer?
96                         layer=5;
97                         if ( tags['layer'] )
98                 layer=Math.min(Math.max(tags['layer']+5,-5),5)+5;
99
100                         // set style
101                         var styles:Array=map.ruleset.getStyles(false, tags, map.scale);
102                         for each (var s:* in styles) {
103
104                                 if (s is ShapeStyle) {
105                                         var stroke:Sprite, fill:Sprite, roadname:Sprite, f:Graphics, g:Graphics;
106                                         var doStroke:Boolean=false, doDashed:Boolean=false;
107                                         var doFill:Boolean=false, fill_colour:uint, fill_opacity:Number;
108                                         var doCasing:Boolean=false, doDashedCasing:Boolean=false;
109
110                                         // Set stroke style
111                                         if (s.isStroked)  {
112                                                 stroke=new Sprite(); addToLayer(stroke,1,s.sublayer); g=stroke.graphics;
113                                 g.moveTo(map.lon2coord(way.getNode(0).lon), map.latp2coord(way.getNode(0).latp));
114                                                 g.lineStyle(s.stroke_width, s.stroke_colour, s.stroke_opacity/100,
115                                                                         false, "normal", s.stroke_linecap, s.stroke_linejoin);
116                                         }
117
118                                         // Set fill and casing style
119                                         if (s.isFilled || s.isCased) {
120                                                 fill=new Sprite(); addToLayer(fill,0); f=fill.graphics;
121                                 f.moveTo(map.lon2coord(way.getNode(0).lon), map.latp2coord(way.getNode(0).latp));
122                                                 if (s.isCased)  { f.lineStyle(s.casing_width, s.casing_colour, s.casing_opacity/100,
123                                                                                   false, "normal", s.stroke_linecap, s.stroke_linejoin); }
124                                                 if (s.isFilled) { f.beginFill(s.fill_colour,s.fill_opacity/100); }
125                                         }
126
127                                         // Draw stroke
128                                         if (s.stroke_dashArray.length>0) { dashedLine(g,s.stroke_dashArray); }
129                                                            else if (s.isStroked) { solidLine(g); }
130                         
131                                         // Draw fill and casing
132                                         if (s.casing_dashArray.length>0) { dashedLine(f,s.casing_dashArray); f.lineStyle(); }
133                                         if (s.isFilled)                                  { f.beginFill(s.fill_colour,s.fill_opacity/100); 
134                                                                                                            solidLine(f); f.endFill(); }
135                                         else if (s.isCased && s.casing_dashArray.length==0) { solidLine(f); }
136
137
138                                 } else if (s is TextStyle && s.tag && tags[s.tag]) {
139                                         roadname=new Sprite(); addToLayer(roadname,2);
140                                         nameformat = s.getTextFormat();
141                                         var a:String=tags[s.tag]; if (s.font_caps) { a=a.toUpperCase(); }
142                                         if (s.isLine) {
143                                                 writeNameOnPath(roadname,a,s.text_offset ? s.text_offset : 0);
144                                                 if (s.pullout_radius>0) { roadname.filters=s.getPulloutFilter(); }
145                                         } else if (centroid_x) {
146                                                 s.writeNameLabel(roadname,tags[s.tag],centroid_x,centroid_y);
147                                         }
148
149
150                                 } else if (s is ShieldStyle) {
151                                         // ** to do
152                                 }
153                         }
154                 }
155                 
156                 // ------------------------------------------------------------------------------------------
157                 // Drawing support functions
158
159                 // Draw solid polyline
160                 
161                 private function solidLine(g:Graphics):void {
162             var node:Node = way.getNode(0);
163                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
164                         for (var i:uint = 1; i < way.length; i++) {
165                 node = way.getNode(i);
166                                 g.lineTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
167                         }
168                 }
169
170                 // Draw dashed polyline
171                 
172                 private function dashedLine(g:Graphics,dashes:Array):void {
173                         var draw:Boolean=false, dashleft:Number=0, dc:Array=new Array();
174                         var a:Number, xc:Number, yc:Number;
175                         var curx:Number, cury:Number;
176                         var dx:Number, dy:Number, segleft:Number=0;
177                         var i:int=0;
178
179             var node:Node = way.getNode(0);
180             var nextNode:Node = way.getNode(0);
181                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
182                         while (i < way.length-1 || segleft>0) {
183                                 if (dashleft<=0) {      // should be ==0
184                                         if (dc.length==0) { dc=dashes.slice(0); }
185                                         dashleft=dc.shift();
186                                         draw=!draw;
187                                 }
188                                 if (segleft<=0) {       // should be ==0
189                     node = way.getNode(i);
190                     nextNode = way.getNode(i+1);
191                                         curx=map.lon2coord(node.lon);
192                     dx=map.lon2coord(nextNode.lon)-curx;
193                                         cury=map.latp2coord(node.latp);
194                     dy=map.latp2coord(nextNode.latp)-cury;
195                                         a=Math.atan2(dy,dx); xc=Math.cos(a); yc=Math.sin(a);
196                                         segleft=Math.sqrt(dx*dx+dy*dy);
197                                         i++;
198                                 }
199
200                                 if (segleft<=dashleft) {
201                                         // the path segment is shorter than the dash
202                                         curx+=dx; cury+=dy;
203                                         moveLine(g,curx,cury,draw);
204                                         dashleft-=segleft; segleft=0;
205                                 } else {
206                                         // the path segment is longer than the dash
207                                         curx+=dashleft*xc; dx-=dashleft*xc;
208                                         cury+=dashleft*yc; dy-=dashleft*yc;
209                                         moveLine(g,curx,cury,draw);
210                                         segleft-=dashleft; dashleft=0;
211                                 }
212                         }
213                 }
214
215                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
216                         if (draw) { g.lineTo(x,y); }
217                                  else { g.moveTo(x,y); }
218                 }
219
220                 
221                 // Find point partway (0-1) along a path
222                 // returns (x,y,angle)
223                 // inspired by senocular's Path.as
224                 
225                 private function pointAt(t:Number):Array {
226                         var totallen:Number = t*pathlength;
227                         var curlen:Number = 0;
228                         var dx:Number, dy:Number, seglen:Number;
229                         for (var i:int = 1; i < way.length; i++){
230                                 dx=map.lon2coord(way.getNode(i).lon)-map.lon2coord(way.getNode(i-1).lon);
231                                 dy=map.latp2coord(way.getNode(i).latp)-map.latp2coord(way.getNode(i-1).latp);
232                                 seglen=Math.sqrt(dx*dx+dy*dy);
233                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
234                                 return new Array(map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
235                                                                  map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
236                                                                  Math.atan2(dy,dx));
237                         }
238                         return new Array(0, 0, 0);
239                 }
240
241                 // Draw name along path
242                 // based on code by Tom Carden
243                 // ** needs styling
244                 
245                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
246
247                         // make a dummy textfield so we can measure its width
248                         var tf:TextField = new TextField();
249                         tf.defaultTextFormat = nameformat;
250                         tf.text = a;
251                         tf.width = tf.textWidth+4;
252                         tf.height = tf.textHeight+4;
253                         if (pathlength<tf.width) { return; }    // no room for text?
254
255                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
256                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
257
258                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
259                         var offsetSign:Number;  // -1 if we're starting at t2
260                         var tStart:Number;      // t1 or t2
261
262                         // make sure text doesn't run right->left or upside down
263                         if (p1[0] < p2[0] && 
264                                 p1[2] < Math.PI/2 &&
265                                 p1[2] > -Math.PI/2) {
266                                 angleOffset = 0; offsetSign = 1; tStart = t1;
267                         } else {
268                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
269                         } 
270
271                         // make a textfield for each char, centered on the line,
272                         // using getCharBoundaries to rotate it around its center point
273                         var chars:Array = a.split('');
274                         for (var i:int = 0; i < chars.length; i++) {
275                                 var rect:Rectangle = tf.getCharBoundaries(i);
276                                 if (rect) {
277                                         s.addChild(rotatedLetter(chars[i],
278                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
279                                                                                          rect.width, tf.height, angleOffset, textOffset));
280                                 }
281                         }
282                 }
283
284                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
285                         var tf:TextField = new TextField();
286                         tf.embedFonts = true;
287                         tf.defaultTextFormat = nameformat;
288                         tf.text = char;
289                         tf.width = tf.textWidth+4;
290                         tf.height = tf.textHeight+4;
291
292                         var p:Array=pointAt(t);
293                         var matrix:Matrix = new Matrix();
294                         matrix.translate(-w/2, -h/2-o);
295                         // ** add (say) -4 to the height to move it up by 4px
296                         matrix.rotate(p[2]+a);
297                         matrix.translate(p[0], p[1]);
298                         tf.transform.matrix = matrix;
299                         return tf;
300                 }
301                 
302                 // Add object (stroke/fill/roadname) to layer sprite
303                 
304                 private function addToLayer(s:Sprite,t:uint,sublayer:int=-1):void {
305                         var l:DisplayObject=Map(map).getChildAt(layer);
306                         var o:DisplayObject=Sprite(l).getChildAt(t);
307                         if (sublayer!=-1) { o=Sprite(o).getChildAt(sublayer); }
308                         Sprite(o).addChild(s);
309                         sprites.push(s);
310                 }
311         }
312 }