fix horrid merge bug (yay!). Implement suspend/resume events for redrawing, to speed...
[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.TextField;
8         import flash.text.TextFormat;
9         import flash.events.*;
10         import net.systemeD.halcyon.styleparser.*;
11     import net.systemeD.halcyon.connection.*;
12         import net.systemeD.halcyon.Globals;
13
14         public class WayUI extends EntityUI {
15
16         private var way:Way;
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 heading:Array=new Array();           // angle at each node
22         private var hitzone:Sprite;
23                 public var nameformat:TextFormat;
24
25                 private const NODESIZE:uint=6;
26
27                 public function WayUI(way:Way, map:Map) {
28                         super();
29                         this.way = way;
30                         this.map = map;
31             init();
32             way.addEventListener(Connection.TAG_CHANGED, wayTagChanged);
33             way.addEventListener(Connection.WAY_NODE_ADDED, wayNodeAdded);
34             way.addEventListener(Connection.WAY_NODE_REMOVED, wayNodeRemoved);
35                         way.addEventListener(Connection.WAY_DELETED, wayDeleted);
36                         way.addEventListener(Connection.ADDED_TO_RELATION, wayRelationAdded);
37                         way.addEventListener(Connection.REMOVED_FROM_RELATION, wayRelationRemoved);
38                         way.addEventListener(Connection.SUSPEND_REDRAW, suspendRedraw);
39                         way.addEventListener(Connection.RESUME_REDRAW, resumeRedraw);
40             attachNodeListeners();
41             attachRelationListeners();
42                 }
43                 
44                 private function attachNodeListeners():void {
45             for (var i:uint = 0; i < way.length; i++ ) {
46                 way.getNode(i).addEventListener(Connection.NODE_MOVED, nodeMoved);
47             }
48                 }
49
50                 private function attachRelationListeners():void {
51                     var relations:Array = way.parentRelations;
52             for each(var relation:Relation in relations ) {
53                 relation.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
54             }
55                 }
56                 
57                 private function wayRelationAdded(event:RelationMemberEvent):void {
58                     event.relation.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
59                     redraw();
60                 }
61                 
62                 private function wayRelationRemoved(event:RelationMemberEvent):void {
63                     event.relation.removeEventListener(Connection.TAG_CHANGED, relationTagChanged);
64                     redraw();
65                 }
66                 
67                 private function wayNodeAdded(event:WayNodeEvent):void {
68                     event.node.addEventListener(Connection.NODE_MOVED, nodeMoved);
69                     redraw();
70                 }
71                     
72                 private function wayNodeRemoved(event:WayNodeEvent):void {
73                     event.node.removeEventListener(Connection.NODE_MOVED, nodeMoved);
74                     redraw();
75                 }
76                     
77         private function wayTagChanged(event:TagEvent):void {
78             redraw();
79         }
80         private function relationTagChanged(event:TagEvent):void {
81             redraw();
82         }
83         private function nodeMoved(event:NodeMovedEvent):void {
84             redraw();
85         }
86                 private function wayDeleted(event:EntityEvent):void {
87                         redraw();
88                 }
89
90                 private function init():void {
91                         recalculate();
92                         redraw();
93                         // updateBbox(lon, lat);
94                         // ** various other stuff
95                 }
96
97                 // ------------------------------------------------------------------------------------------
98                 // Calculate length etc.
99                 // ** this could be made scale-independent - would speed up redraw
100                 
101                 public function recalculate():void {
102                         var lx:Number, ly:Number, sc:Number;
103                         var node:Node, latp:Number, lon:Number;
104                         var cx:Number=0, cy:Number=0;
105                         pathlength=0;
106                         patharea=0;
107                         if (way.length==0) { return; }
108                         
109                         lx = way.getNode(way.length-1).lon;
110                         ly = way.getNode(way.length-1).latp;
111                         for ( var i:uint = 0; i < way.length; i++ ) {
112                 node = way.getNode(i);
113                 latp = node.latp;
114                 lon  = node.lon;
115
116                                 // length and area
117                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
118                                 sc = (lx*latp-lon*ly)*map.scalefactor;
119                                 cx += (lx+lon)*sc;
120                                 cy += (ly+latp)*sc;
121                                 patharea += sc;
122                                 
123                                 // heading
124                                 if (i>0) { heading[i-1]=Math.atan2((lon-lx),(latp-ly)); }
125
126                                 lx=lon; ly=latp;
127                         }
128                         heading[way.length-1]=heading[way.length-2];
129
130                         pathlength*=map.scalefactor;
131                         patharea/=2;
132                         if (patharea!=0 && way.isArea()) {
133                                 centroid_x=map.lon2coord(cx/patharea/6);
134                                 centroid_y=map.latp2coord(cy/patharea/6);
135                         } else if (pathlength>0) {
136                                 var c:Array=pointAt(0.5);
137                                 centroid_x=c[0];
138                                 centroid_y=c[1];
139                         }
140                 }
141
142                 // ------------------------------------------------------------------------------------------
143                 // Redraw
144
145                 override public function doRedraw(sl:StyleList):Boolean {
146                         removeSprites();
147                         if (way.length==0) { return false; }
148
149             // Copy tags object, and add states
150             var tags:Object = way.getTagsCopy();
151                         tags=applyStateClasses(tags);
152                         if (way.isArea()) { tags[':area']='yes'; }
153
154                         // Which layer?
155                         layer=5;
156                         if ( tags['layer'] )
157                 layer=Math.min(Math.max(tags['layer']+5,-5),5)+5;
158
159                         // Iterate through each sublayer, drawing any styles on that layer
160                         if (!sl) { sl=map.ruleset.getStyles(this.way, tags); }
161                         var drawn:Boolean;
162                         for (var sublayer:int=10; sublayer>=0; sublayer--) {
163                                 if (sl.shapeStyles[sublayer]) {
164                                         var s:ShapeStyle=sl.shapeStyles[sublayer];
165                                         var stroke:Shape, fill:Shape, casing:Shape, roadname:Sprite;
166                                         var x0:Number=map.lon2coord(way.getNode(0).lon);
167                                         var y0:Number=map.latp2coord(way.getNode(0).latp);
168
169                                         // Stroke
170                                         if (s.width)  {
171                                                 stroke=new Shape(); addToLayer(stroke,STROKESPRITE,sublayer);
172                                                 stroke.graphics.moveTo(x0,y0);
173                                                 s.applyStrokeStyle(stroke.graphics);
174                                                 if (s.dashes && s.dashes.length>0) { dashedLine(stroke.graphics,s.dashes); }
175                                                                                                           else { solidLine(stroke.graphics); }
176                                                 drawn=true;
177                                         }
178
179                                         // Fill
180                                         if (s.fill_color || s.fill_image) {
181                                                 fill=new Shape(); addToLayer(fill,FILLSPRITE);
182                                                 fill.graphics.moveTo(x0,y0);
183                                                 if (s.fill_image) { new WayBitmapFiller(this,fill.graphics,s); }
184                                                                          else { s.applyFill(fill.graphics); }
185                                                 solidLine(fill.graphics);
186                                                 fill.graphics.endFill();
187                                                 drawn=true;
188                                         }
189
190                                         // Casing
191                                         if (s.casing_width) { 
192                                                 casing=new Shape(); addToLayer(casing,CASINGSPRITE);
193                                                 casing.graphics.moveTo(x0,y0);
194                                                 s.applyCasingStyle(casing.graphics);
195                                                 if (s.casing_dashes && s.casing_dashes.length>0) { dashedLine(casing.graphics,s.casing_dashes); }
196                                                                                                                                         else { solidLine(casing.graphics); }
197                                                 drawn=true;
198                                         }
199                                 }
200                                 
201                                 if (sl.textStyles[sublayer]) {
202                                         var t:TextStyle=sl.textStyles[sublayer];
203                                         roadname=new Sprite(); addToLayer(roadname,NAMESPRITE);
204                                         nameformat = t.getTextFormat();
205                                         var a:String=tags[t.text];
206                                         if (a) {
207                                                 if (t.font_caps) { a=a.toUpperCase(); }
208                                                 if (t.text_center && centroid_x) {
209                                                         t.writeNameLabel(roadname,a,centroid_x,centroid_y);
210                                                 } else {
211                                                         writeNameOnPath(roadname,a,t.text_offset ? t.text_offset : 0);
212                                                 }
213                                                 if (t.text_halo_radius>0) { roadname.filters=t.getHaloFilter(); }
214                                         }
215                                 }
216                                 
217                                 // ** ShieldStyle to do
218                         }
219
220                         // Draw icons
221                         // ** there should be huge potential to optimise this - at present we're
222                         //    running getStyles for every node in the way on every redraw
223                         // ** fix r/heading behaviour - that doesn't look right
224                         var r:Number;
225                         var nodetags:Object;
226                         var nodeSelected:int=stateClasses["nodeSelected"];
227                         for (var i:uint = 0; i < way.length; i++) {
228                 var node:Node = way.getNode(i);
229                                 nodetags=node.getTagsCopy();
230                                 if (i==0) { nodetags['_heading']= heading[i]; }
231                                      else { nodetags['_heading']=(heading[i]+heading[i-1])/2; }
232                                 if (stateClasses["showNodes"]) { nodetags[':selectedway']='yes'; }
233                                 if (stateClasses["showNodesHover"]) { nodetags[':hoverway']='yes'; }
234                                 if (node.id==nodeSelected) { nodetags[':selected']='yes'; }
235                                 if (node.numParentWays>1) { nodetags[':junction']='yes'; }
236                                 sl=map.ruleset.getStyles(node,nodetags);
237                                 if (sl.hasStyles()) {
238                                         if (!map.pois[node.id]) {
239                                                 map.pois[node.id]=new NodeUI(node,map,r);
240                                         }
241                                         map.pois[node.id].redraw(sl);
242                                 } else if (map.pois[node.id]) {
243                                         map.pois[node.id].removeSprites();
244                                         delete map.pois[node.id];
245                                 }
246                         }
247                         if (!drawn) { return false; }
248                         
249             // create a generic "way" hitzone sprite
250             hitzone = new Sprite();
251             hitzone.graphics.lineStyle(4, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
252             solidLine(hitzone.graphics);
253             addToLayer(hitzone, CLICKSPRITE);
254             hitzone.visible = false;
255                         createListenSprite(hitzone);
256
257                         return true;
258                 }
259                 
260                 // ------------------------------------------------------------------------------------------
261                 // Drawing support functions
262
263                 // Draw solid polyline
264                 
265                 public function solidLine(g:Graphics):void {
266             var node:Node = way.getNode(0);
267                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
268                         for (var i:uint = 1; i < way.length; i++) {
269                 node = way.getNode(i);
270                                 g.lineTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
271                         }
272                 }
273
274                 // Draw dashed polyline
275                 
276                 private function dashedLine(g:Graphics,dashes:Array):void {
277                         var draw:Boolean=false, dashleft:Number=0, dc:Array=new Array();
278                         var a:Number, xc:Number, yc:Number;
279                         var curx:Number, cury:Number;
280                         var dx:Number, dy:Number, segleft:Number=0;
281                         var i:int=0;
282
283             var node:Node = way.getNode(0);
284             var nextNode:Node = way.getNode(0);
285                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
286                         while (i < way.length-1 || segleft>0) {
287                                 if (dashleft<=0) {      // should be ==0
288                                         if (dc.length==0) { dc=dashes.slice(0); }
289                                         dashleft=dc.shift();
290                                         draw=!draw;
291                                 }
292                                 if (segleft<=0) {       // should be ==0
293                     node = way.getNode(i);
294                     nextNode = way.getNode(i+1);
295                                         curx=map.lon2coord(node.lon);
296                     dx=map.lon2coord(nextNode.lon)-curx;
297                                         cury=map.latp2coord(node.latp);
298                     dy=map.latp2coord(nextNode.latp)-cury;
299                                         a=Math.atan2(dy,dx); xc=Math.cos(a); yc=Math.sin(a);
300                                         segleft=Math.sqrt(dx*dx+dy*dy);
301                                         i++;
302                                 }
303
304                                 if (segleft<=dashleft) {
305                                         // the path segment is shorter than the dash
306                                         curx+=dx; cury+=dy;
307                                         moveLine(g,curx,cury,draw);
308                                         dashleft-=segleft; segleft=0;
309                                 } else {
310                                         // the path segment is longer than the dash
311                                         curx+=dashleft*xc; dx-=dashleft*xc;
312                                         cury+=dashleft*yc; dy-=dashleft*yc;
313                                         moveLine(g,curx,cury,draw);
314                                         segleft-=dashleft; dashleft=0;
315                                 }
316                         }
317                 }
318
319                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
320                         if (draw) { g.lineTo(x,y); }
321                                  else { g.moveTo(x,y); }
322                 }
323
324                 
325                 // Find point partway (0-1) along a path
326                 // returns (x,y,angle)
327                 // inspired by senocular's Path.as
328                 
329                 private function pointAt(t:Number):Array {
330                         var totallen:Number = t*pathlength;
331                         var curlen:Number = 0;
332                         var dx:Number, dy:Number, seglen:Number;
333                         for (var i:int = 1; i < way.length; i++){
334                                 dx=map.lon2coord(way.getNode(i).lon)-map.lon2coord(way.getNode(i-1).lon);
335                                 dy=map.latp2coord(way.getNode(i).latp)-map.latp2coord(way.getNode(i-1).latp);
336                                 seglen=Math.sqrt(dx*dx+dy*dy);
337                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
338                                 return new Array(map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
339                                                                  map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
340                                                                  Math.atan2(dy,dx));
341                         }
342                         return new Array(0, 0, 0);
343                 }
344
345                 // Draw name along path
346                 // based on code by Tom Carden
347                 
348                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
349
350                         // make a dummy textfield so we can measure its width
351                         var tf:TextField = new TextField();
352                         tf.defaultTextFormat = nameformat;
353                         tf.text = a;
354                         tf.width = tf.textWidth+4;
355                         tf.height = tf.textHeight+4;
356                         if (pathlength<tf.width) { return; }    // no room for text?
357
358                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
359                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
360
361                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
362                         var offsetSign:Number;  // -1 if we're starting at t2
363                         var tStart:Number;      // t1 or t2
364
365                         // make sure text doesn't run right->left or upside down
366                         if (p1[0] < p2[0] && 
367                                 p1[2] < Math.PI/2 &&
368                                 p1[2] > -Math.PI/2) {
369                                 angleOffset = 0; offsetSign = 1; tStart = t1;
370                         } else {
371                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
372                         } 
373
374                         // make a textfield for each char, centered on the line,
375                         // using getCharBoundaries to rotate it around its center point
376                         var chars:Array = a.split('');
377                         for (var i:int = 0; i < chars.length; i++) {
378                                 var rect:Rectangle = tf.getCharBoundaries(i);
379                                 if (rect) {
380                                         s.addChild(rotatedLetter(chars[i],
381                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
382                                                                                          rect.width, tf.height, angleOffset, textOffset));
383                                 }
384                         }
385                 }
386
387                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
388                         var tf:TextField = new TextField();
389             tf.mouseEnabled = false;
390             tf.mouseWheelEnabled = false;
391                         tf.defaultTextFormat = nameformat;
392                         tf.embedFonts = true;
393                         tf.text = char;
394                         tf.width = tf.textWidth+4;
395                         tf.height = tf.textHeight+4;
396
397                         var p:Array=pointAt(t);
398                         var matrix:Matrix = new Matrix();
399                         matrix.translate(-w/2, -h/2-o);
400                         // ** add (say) -4 to the height to move it up by 4px
401                         matrix.rotate(p[2]+a);
402                         matrix.translate(p[0], p[1]);
403                         tf.transform.matrix = matrix;
404                         return tf;
405                 }
406                 
407                 public function getNodeAt(x:Number, y:Number):Node {
408                         for (var i:uint = 0; i < way.length; i++) {
409                 var node:Node = way.getNode(i);
410                 var nodeX:Number = map.lon2coord(node.lon);
411                 var nodeY:Number = map.latp2coord(node.latp);
412                 if ( nodeX >= x-NODESIZE && nodeX <= x+NODESIZE &&
413                      nodeY >= y-NODESIZE && nodeY <= y+NODESIZE )
414                     return node;
415             }
416             return null;
417                 }
418
419         override protected function mouseEvent(event:MouseEvent):void {
420                         map.entityMouseEvent(event, way);
421         }
422
423         }
424 }