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