some more footling around with POI nodes in ways
[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 flash.events.*;
12         import net.systemeD.halcyon.styleparser.*;
13     import net.systemeD.halcyon.connection.*;
14
15         public class WayUI {
16         private var way:Way;
17
18                 public var pathlength:Number;                           // length of path
19                 public var patharea:Number;                                     // area of path
20                 public var centroid_x:Number;                           // centroid
21                 public var centroid_y:Number;                           //  |
22                 public var layer:int=0;                                         // map layer
23                 public var map:Map;                                                     // reference to parent map
24                 public var sprites:Array=new Array();           // instances in display list
25                 private var stateClasses:Object = new Object();
26         private var hitzone:Sprite;
27         private var listenSprite:Sprite;
28
29                 public static const DEFAULT_TEXTFIELD_PARAMS:Object = {
30                         embedFonts: true,
31                         antiAliasType: AntiAliasType.ADVANCED,
32                         gridFitType: GridFitType.NONE
33                 };
34                 public var nameformat:TextFormat;
35                 
36                 private const FILLSPRITE:uint=0;
37                 private const CASINGSPRITE:uint=1;
38                 private const STROKESPRITE:uint=2;
39                 private const NAMESPRITE:uint=3;
40                 private const NODESPRITE:uint=4;
41                 private const CLICKSPRITE:uint=5;
42
43
44                 public function WayUI(way:Way, map:Map) {
45                         this.way = way;
46                         this.map = map;
47             init();
48             way.addEventListener(Connection.TAG_CHANGE, wayTagChanged);
49             way.addEventListener(Connection.WAY_NODE_ADDED, wayNodeAdded);
50             way.addEventListener(Connection.WAY_NODE_REMOVED, wayNodeRemoved);
51             attachNodeListeners();
52                 }
53                 
54                 private function attachNodeListeners():void {
55             for (var i:uint = 0; i < way.length; i++ ) {
56                 way.getNode(i).addEventListener(Connection.NODE_MOVED, nodeMoved);
57             }
58                 }
59                 
60                 private function wayNodeAdded(event:WayNodeEvent):void {
61                     event.node.addEventListener(Connection.NODE_MOVED, nodeMoved);
62                     redraw();
63                 }
64                     
65                 private function wayNodeRemoved(event:WayNodeEvent):void {
66                     event.node.removeEventListener(Connection.NODE_MOVED, nodeMoved);
67                     redraw();
68                 }
69                     
70         private function wayTagChanged(event:TagEvent):void {
71             redraw();
72         }
73         private function nodeMoved(event:NodeMovedEvent):void {
74             redraw();
75         }
76
77                 private function init():void {
78                         recalculate();
79                         redraw();
80                         // updateBbox(lon, lat);
81                         // ** various other stuff
82                 }
83
84                 // ------------------------------------------------------------------------------------------
85                 // Calculate length etc.
86                 // ** this could be made scale-independent - would speed up redraw
87                 
88                 public function recalculate():void {
89                         var lx:Number, ly:Number, sc:Number;
90                         var cx:Number=0, cy:Number=0;
91                         pathlength=0;
92                         patharea=0;
93                         
94                         lx = way.getNode(way.length-1).lon;
95                         ly = way.getNode(way.length-1).latp;
96                         for ( var i:uint = 0; i < way.length; i++ ) {
97                 var node:Node = way.getNode(i);
98                 var latp:Number = node.latp;
99                 var lon:Number  = node.lon;
100                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
101                                 sc = (lx*latp-lon*ly)*map.scalefactor;
102                                 cx += (lx+lon)*sc;
103                                 cy += (ly+latp)*sc;
104                                 patharea += sc;
105                                 lx=lon; ly=latp;
106                         }
107
108                         pathlength*=map.scalefactor;
109                         patharea/=2;
110                         if (patharea!=0 && way.isArea()) {
111                                 centroid_x=map.lon2coord(cx/patharea/6);
112                                 centroid_y=map.latp2coord(cy/patharea/6);
113                         } else if (pathlength>0) {
114                                 var c:Array=pointAt(0.5);
115                                 centroid_x=c[0];
116                                 centroid_y=c[1];
117                         }
118                 }
119
120                 // ------------------------------------------------------------------------------------------
121                 // Redraw
122
123                 public function redraw():void {
124             // Copy tags object, and add states
125             var tags:Object = way.getTagsCopy();
126             for (var stateKey:String in stateClasses) {
127                 tags[":"+stateKey] = stateKey;
128             }
129                         if (way.isArea()) { tags[':area']='yes'; }
130
131                         // Remove all currently existing sprites
132                         while (sprites.length>0) {
133                                 var d:DisplayObject=sprites.pop(); d.parent.removeChild(d);
134                         }
135
136                         // Which layer?
137                         layer=5;
138                         if ( tags['layer'] )
139                 layer=Math.min(Math.max(tags['layer']+5,-5),5)+5;
140
141                         // Iterate through each sublayer, drawing any styles on that layer
142                         var sl:StyleList=map.ruleset.getStyles(this.way, tags);
143                         var drawn:Boolean;
144                         for (var sublayer:uint=0; sublayer<11; sublayer++) {
145                                 if (sl.shapeStyles[sublayer]) {
146                                         var s:ShapeStyle=sl.shapeStyles[sublayer];
147                                         var stroke:Shape, fill:Shape, casing:Shape, roadname:Sprite;
148                                         var x0:Number=map.lon2coord(way.getNode(0).lon);
149                                         var y0:Number=map.latp2coord(way.getNode(0).latp);
150
151                                         // Stroke
152                                         if (s.width)  {
153                                                 stroke=new Shape(); addToLayer(stroke,STROKESPRITE,sublayer);
154                                                 stroke.graphics.moveTo(x0,y0);
155                                                 s.applyStrokeStyle(stroke.graphics);
156                                                 if (s.dashes && s.dashes.length>0) { dashedLine(stroke.graphics,s.dashes); }
157                                                                                                           else { solidLine(stroke.graphics); }
158                                                 drawn=true;
159                                         }
160
161                                         // Fill
162                                         if (s.fill_color || s.fill_image) {
163                                                 fill=new Shape(); addToLayer(fill,FILLSPRITE);
164                                                 fill.graphics.moveTo(x0,y0);
165                                                 if (s.fill_image) { new WayBitmapFiller(this,fill.graphics,s); }
166                                                                          else { s.applyFill(fill.graphics); }
167                                                 solidLine(fill.graphics);
168                                                 fill.graphics.endFill();
169                                                 drawn=true;
170                                         }
171
172                                         // Casing
173                                         if (s.casing_width) { 
174                                                 casing=new Shape(); addToLayer(casing,CASINGSPRITE);
175                                                 casing.graphics.moveTo(x0,y0);
176                                                 s.applyCasingStyle(casing.graphics);
177                                                 if (s.casing_dashes && s.casing_dashes.length>0) { dashedLine(casing.graphics,s.casing_dashes); }
178                                                                                                                                         else { solidLine(casing.graphics); }
179                                                 drawn=true;
180                                         }
181                                 }
182                                 
183                                 if (sl.textStyles[sublayer]) {
184                                         var t:TextStyle=sl.textStyles[sublayer];
185                                         roadname=new Sprite(); addToLayer(roadname,NAMESPRITE);
186                                         nameformat = t.getTextFormat();
187                                         var a:String=tags[t.text];
188                                         if (a) {
189                                                 if (t.font_caps) { a=a.toUpperCase(); }
190                                                 if (t.text_center && centroid_x) {
191                                                         t.writeNameLabel(roadname,tags[t.text],centroid_x,centroid_y);
192                                                 } else {
193                                                         writeNameOnPath(roadname,a,t.text_offset ? t.text_offset : 0);
194                                                 }
195                                                 if (t.text_halo_radius>0) { roadname.filters=t.getHaloFilter(); }
196                                         }
197                                 }
198                                 
199                                 // ** ShieldStyle to do
200                         }
201
202                         // ** draw icons
203                         for (var i:uint = 0; i < way.length; i++) {
204                 var node:Node = way.getNode(i);
205                     if (map.pois[node.id]) {
206                                         if (map.pois[node.id].loaded) {
207                                                 map.pois[node.id].redraw();
208                                         }
209                                 } else if (node.hasTags()) {
210                                         sl=map.ruleset.getStyles(node,node.getTagsHash());
211                                         if (sl.hasStyles()) {
212                                                 map.pois[node.id]=new POI(node,map,sl);
213                                                 // ** this should be done via the registerPOI/event listener mechanism,
214                                                 //    but that needs a bit of reworking so we can pass in a styleList
215                                                 //    (otherwise we end up computing the styles twice which is expensive)
216                                         }
217                                 }
218                         }
219                         
220                         
221
222                         // No styles, so add a thin trace
223             if (!drawn && map.showall) {
224                 var def:Sprite = new Sprite();
225                 def.graphics.lineStyle(0.5, 0x808080, 1, false, "normal");
226                 solidLine(def.graphics);
227                 addToLayer(def, STROKESPRITE);          // ** this probably needs a sublayer
228                                 drawn=true;
229             }
230             
231             if ( stateClasses["showNodes"] != null ) {
232                 var nodes:Sprite = new Sprite();
233                 drawNodes(nodes.graphics);
234                 addToLayer(nodes, NODESPRITE);
235             }
236
237                         if (!drawn) { return; }
238                         
239             // create a generic "way" hitzone sprite
240             hitzone = new Sprite();
241             hitzone.graphics.lineStyle(4, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
242             solidLine(hitzone.graphics);
243             addToLayer(hitzone, CLICKSPRITE);
244             hitzone.visible = false;
245
246             if ( listenSprite == null ) {
247                 listenSprite = new Sprite();
248                 listenSprite.addEventListener(MouseEvent.CLICK, mouseEvent);
249                 listenSprite.addEventListener(MouseEvent.DOUBLE_CLICK, mouseEvent);
250                 listenSprite.addEventListener(MouseEvent.MOUSE_OVER, mouseEvent);
251                 listenSprite.addEventListener(MouseEvent.MOUSE_OUT, mouseEvent);
252                 listenSprite.addEventListener(MouseEvent.MOUSE_DOWN, mouseEvent);
253                 listenSprite.addEventListener(MouseEvent.MOUSE_UP, mouseEvent);
254                 listenSprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseEvent);
255             }
256             listenSprite.hitArea = hitzone;
257             addToLayer(listenSprite, CLICKSPRITE);
258             listenSprite.buttonMode = true;
259             listenSprite.mouseEnabled = true;
260
261                 }
262                 
263                 // ------------------------------------------------------------------------------------------
264                 // Drawing support functions
265
266                 private function drawNodes(g:Graphics):void {
267             g.lineStyle(1, 0xff0000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
268                         for (var i:uint = 0; i < way.length; i++) {
269                 var node:Node = way.getNode(i);
270                 var x:Number = map.lon2coord(node.lon);
271                 var y:Number = map.latp2coord(node.latp);
272                 g.moveTo(x-2, y-2);
273                 g.lineTo(x+2, y-2);
274                 g.lineTo(x+2, y+2);
275                 g.lineTo(x-2, y+2);
276                 g.lineTo(x-2, y-2);
277                         }
278                 }
279
280                 // Draw solid polyline
281                 
282                 public function solidLine(g:Graphics):void {
283             var node:Node = way.getNode(0);
284                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
285                         for (var i:uint = 1; i < way.length; i++) {
286                 node = way.getNode(i);
287                                 g.lineTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
288                         }
289                 }
290
291                 // Draw dashed polyline
292                 
293                 private function dashedLine(g:Graphics,dashes:Array):void {
294                         var draw:Boolean=false, dashleft:Number=0, dc:Array=new Array();
295                         var a:Number, xc:Number, yc:Number;
296                         var curx:Number, cury:Number;
297                         var dx:Number, dy:Number, segleft:Number=0;
298                         var i:int=0;
299
300             var node:Node = way.getNode(0);
301             var nextNode:Node = way.getNode(0);
302                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
303                         while (i < way.length-1 || segleft>0) {
304                                 if (dashleft<=0) {      // should be ==0
305                                         if (dc.length==0) { dc=dashes.slice(0); }
306                                         dashleft=dc.shift();
307                                         draw=!draw;
308                                 }
309                                 if (segleft<=0) {       // should be ==0
310                     node = way.getNode(i);
311                     nextNode = way.getNode(i+1);
312                                         curx=map.lon2coord(node.lon);
313                     dx=map.lon2coord(nextNode.lon)-curx;
314                                         cury=map.latp2coord(node.latp);
315                     dy=map.latp2coord(nextNode.latp)-cury;
316                                         a=Math.atan2(dy,dx); xc=Math.cos(a); yc=Math.sin(a);
317                                         segleft=Math.sqrt(dx*dx+dy*dy);
318                                         i++;
319                                 }
320
321                                 if (segleft<=dashleft) {
322                                         // the path segment is shorter than the dash
323                                         curx+=dx; cury+=dy;
324                                         moveLine(g,curx,cury,draw);
325                                         dashleft-=segleft; segleft=0;
326                                 } else {
327                                         // the path segment is longer than the dash
328                                         curx+=dashleft*xc; dx-=dashleft*xc;
329                                         cury+=dashleft*yc; dy-=dashleft*yc;
330                                         moveLine(g,curx,cury,draw);
331                                         segleft-=dashleft; dashleft=0;
332                                 }
333                         }
334                 }
335
336                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
337                         if (draw) { g.lineTo(x,y); }
338                                  else { g.moveTo(x,y); }
339                 }
340
341                 
342                 // Find point partway (0-1) along a path
343                 // returns (x,y,angle)
344                 // inspired by senocular's Path.as
345                 
346                 private function pointAt(t:Number):Array {
347                         var totallen:Number = t*pathlength;
348                         var curlen:Number = 0;
349                         var dx:Number, dy:Number, seglen:Number;
350                         for (var i:int = 1; i < way.length; i++){
351                                 dx=map.lon2coord(way.getNode(i).lon)-map.lon2coord(way.getNode(i-1).lon);
352                                 dy=map.latp2coord(way.getNode(i).latp)-map.latp2coord(way.getNode(i-1).latp);
353                                 seglen=Math.sqrt(dx*dx+dy*dy);
354                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
355                                 return new Array(map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
356                                                                  map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
357                                                                  Math.atan2(dy,dx));
358                         }
359                         return new Array(0, 0, 0);
360                 }
361
362                 // Draw name along path
363                 // based on code by Tom Carden
364                 
365                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
366
367                         // make a dummy textfield so we can measure its width
368                         var tf:TextField = new TextField();
369                         tf.defaultTextFormat = nameformat;
370                         tf.text = a;
371                         tf.width = tf.textWidth+4;
372                         tf.height = tf.textHeight+4;
373                         if (pathlength<tf.width) { return; }    // no room for text?
374
375                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
376                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
377
378                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
379                         var offsetSign:Number;  // -1 if we're starting at t2
380                         var tStart:Number;      // t1 or t2
381
382                         // make sure text doesn't run right->left or upside down
383                         if (p1[0] < p2[0] && 
384                                 p1[2] < Math.PI/2 &&
385                                 p1[2] > -Math.PI/2) {
386                                 angleOffset = 0; offsetSign = 1; tStart = t1;
387                         } else {
388                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
389                         } 
390
391                         // make a textfield for each char, centered on the line,
392                         // using getCharBoundaries to rotate it around its center point
393                         var chars:Array = a.split('');
394                         for (var i:int = 0; i < chars.length; i++) {
395                                 var rect:Rectangle = tf.getCharBoundaries(i);
396                                 if (rect) {
397                                         s.addChild(rotatedLetter(chars[i],
398                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
399                                                                                          rect.width, tf.height, angleOffset, textOffset));
400                                 }
401                         }
402                 }
403
404                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
405                         var tf:TextField = new TextField();
406             tf.mouseEnabled = false;
407             tf.mouseWheelEnabled = false;
408                         tf.defaultTextFormat = nameformat;
409                         tf.embedFonts = true;
410                         tf.text = char;
411                         tf.width = tf.textWidth+4;
412                         tf.height = tf.textHeight+4;
413
414                         var p:Array=pointAt(t);
415                         var matrix:Matrix = new Matrix();
416                         matrix.translate(-w/2, -h/2-o);
417                         // ** add (say) -4 to the height to move it up by 4px
418                         matrix.rotate(p[2]+a);
419                         matrix.translate(p[0], p[1]);
420                         tf.transform.matrix = matrix;
421                         return tf;
422                 }
423                 
424                 // Add object (stroke/fill/roadname) to layer sprite
425                 
426                 private function addToLayer(s:DisplayObject,t:uint,sublayer:int=-1):void {
427                         var l:DisplayObject=Map(map).getChildAt(map.WAYSPRITE+layer);
428                         var o:DisplayObject=Sprite(l).getChildAt(t);
429                         if (sublayer!=-1) { o=Sprite(o).getChildAt(sublayer); }
430                         Sprite(o).addChild(s);
431                         sprites.push(s);
432             if ( s is Sprite ) {
433                 Sprite(s).mouseEnabled = false;
434                 Sprite(s).mouseChildren = false;
435             }
436                 }
437
438                 public function getNodeAt(x:Number, y:Number):Node {
439                         for (var i:uint = 0; i < way.length; i++) {
440                 var node:Node = way.getNode(i);
441                 var nodeX:Number = map.lon2coord(node.lon);
442                 var nodeY:Number = map.latp2coord(node.latp);
443                 if ( nodeX >= x-3 && nodeX <= x+3 &&
444                      nodeY >= y-3 && nodeY <= y+3 )
445                     return node;
446             }
447             return null;
448                 }
449
450         private function mouseEvent(event:MouseEvent):void {
451             var node:Node = getNodeAt(event.localX, event.localY);
452             if ( node == null )
453                 map.entityMouseEvent(event, way);
454             else
455                 map.entityMouseEvent(event, node);
456         }
457
458         public function setHighlight(stateType:String, isOn:Boolean):void {
459             if ( isOn && stateClasses[stateType] == null ) {
460                 stateClasses[stateType] = true;
461                 redraw();
462             } else if ( !isOn && stateClasses[stateType] != null ) {
463                 delete stateClasses[stateType];
464                 redraw();
465             }
466         }
467         }
468 }