8ca965cd4766b652dcc8054f1c4aeddc6c4640fe
[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                                 // ** draw icons
200                                 for (var i:uint = 0; i < way.length; i++) {
201                         var node:Node = way.getNode(i);
202                                         if (node.hasTags()) {
203                                                 map.connection.registerPOI(node);
204                                         }
205                                 }
206                                 
207                                 
208                                 // ** ShieldStyle to do
209                         }
210
211                         // No styles, so add a thin trace
212             if (!drawn && map.showall) {
213                 var def:Sprite = new Sprite();
214                 def.graphics.lineStyle(0.5, 0x808080, 1, false, "normal");
215                 solidLine(def.graphics);
216                 addToLayer(def, STROKESPRITE);          // ** this probably needs a sublayer
217                                 drawn=true;
218             }
219             
220             if ( stateClasses["showNodes"] != null ) {
221                 var nodes:Sprite = new Sprite();
222                 drawNodes(nodes.graphics);
223                 addToLayer(nodes, NODESPRITE);
224             }
225
226                         if (!drawn) { return; }
227                         
228             // create a generic "way" hitzone sprite
229             hitzone = new Sprite();
230             hitzone.graphics.lineStyle(4, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
231             solidLine(hitzone.graphics);
232             addToLayer(hitzone, CLICKSPRITE);
233             hitzone.visible = false;
234
235             if ( listenSprite == null ) {
236                 listenSprite = new Sprite();
237                 listenSprite.addEventListener(MouseEvent.CLICK, mouseEvent);
238                 listenSprite.addEventListener(MouseEvent.DOUBLE_CLICK, mouseEvent);
239                 listenSprite.addEventListener(MouseEvent.MOUSE_OVER, mouseEvent);
240                 listenSprite.addEventListener(MouseEvent.MOUSE_OUT, mouseEvent);
241                 listenSprite.addEventListener(MouseEvent.MOUSE_DOWN, mouseEvent);
242                 listenSprite.addEventListener(MouseEvent.MOUSE_UP, mouseEvent);
243                 listenSprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseEvent);
244             }
245             listenSprite.hitArea = hitzone;
246             addToLayer(listenSprite, CLICKSPRITE);
247             listenSprite.buttonMode = true;
248             listenSprite.mouseEnabled = true;
249
250                 }
251                 
252                 // ------------------------------------------------------------------------------------------
253                 // Drawing support functions
254
255                 private function drawNodes(g:Graphics):void {
256             g.lineStyle(1, 0xff0000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
257                         for (var i:uint = 0; i < way.length; i++) {
258                 var node:Node = way.getNode(i);
259                 var x:Number = map.lon2coord(node.lon);
260                 var y:Number = map.latp2coord(node.latp);
261                 g.moveTo(x-2, y-2);
262                 g.lineTo(x+2, y-2);
263                 g.lineTo(x+2, y+2);
264                 g.lineTo(x-2, y+2);
265                 g.lineTo(x-2, y-2);
266                         }
267                 }
268
269                 // Draw solid polyline
270                 
271                 public function solidLine(g:Graphics):void {
272             var node:Node = way.getNode(0);
273                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
274                         for (var i:uint = 1; i < way.length; i++) {
275                 node = way.getNode(i);
276                                 g.lineTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
277                         }
278                 }
279
280                 // Draw dashed polyline
281                 
282                 private function dashedLine(g:Graphics,dashes:Array):void {
283                         var draw:Boolean=false, dashleft:Number=0, dc:Array=new Array();
284                         var a:Number, xc:Number, yc:Number;
285                         var curx:Number, cury:Number;
286                         var dx:Number, dy:Number, segleft:Number=0;
287                         var i:int=0;
288
289             var node:Node = way.getNode(0);
290             var nextNode:Node = way.getNode(0);
291                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
292                         while (i < way.length-1 || segleft>0) {
293                                 if (dashleft<=0) {      // should be ==0
294                                         if (dc.length==0) { dc=dashes.slice(0); }
295                                         dashleft=dc.shift();
296                                         draw=!draw;
297                                 }
298                                 if (segleft<=0) {       // should be ==0
299                     node = way.getNode(i);
300                     nextNode = way.getNode(i+1);
301                                         curx=map.lon2coord(node.lon);
302                     dx=map.lon2coord(nextNode.lon)-curx;
303                                         cury=map.latp2coord(node.latp);
304                     dy=map.latp2coord(nextNode.latp)-cury;
305                                         a=Math.atan2(dy,dx); xc=Math.cos(a); yc=Math.sin(a);
306                                         segleft=Math.sqrt(dx*dx+dy*dy);
307                                         i++;
308                                 }
309
310                                 if (segleft<=dashleft) {
311                                         // the path segment is shorter than the dash
312                                         curx+=dx; cury+=dy;
313                                         moveLine(g,curx,cury,draw);
314                                         dashleft-=segleft; segleft=0;
315                                 } else {
316                                         // the path segment is longer than the dash
317                                         curx+=dashleft*xc; dx-=dashleft*xc;
318                                         cury+=dashleft*yc; dy-=dashleft*yc;
319                                         moveLine(g,curx,cury,draw);
320                                         segleft-=dashleft; dashleft=0;
321                                 }
322                         }
323                 }
324
325                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
326                         if (draw) { g.lineTo(x,y); }
327                                  else { g.moveTo(x,y); }
328                 }
329
330                 
331                 // Find point partway (0-1) along a path
332                 // returns (x,y,angle)
333                 // inspired by senocular's Path.as
334                 
335                 private function pointAt(t:Number):Array {
336                         var totallen:Number = t*pathlength;
337                         var curlen:Number = 0;
338                         var dx:Number, dy:Number, seglen:Number;
339                         for (var i:int = 1; i < way.length; i++){
340                                 dx=map.lon2coord(way.getNode(i).lon)-map.lon2coord(way.getNode(i-1).lon);
341                                 dy=map.latp2coord(way.getNode(i).latp)-map.latp2coord(way.getNode(i-1).latp);
342                                 seglen=Math.sqrt(dx*dx+dy*dy);
343                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
344                                 return new Array(map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
345                                                                  map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
346                                                                  Math.atan2(dy,dx));
347                         }
348                         return new Array(0, 0, 0);
349                 }
350
351                 // Draw name along path
352                 // based on code by Tom Carden
353                 
354                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
355
356                         // make a dummy textfield so we can measure its width
357                         var tf:TextField = new TextField();
358                         tf.defaultTextFormat = nameformat;
359                         tf.text = a;
360                         tf.width = tf.textWidth+4;
361                         tf.height = tf.textHeight+4;
362                         if (pathlength<tf.width) { return; }    // no room for text?
363
364                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
365                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
366
367                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
368                         var offsetSign:Number;  // -1 if we're starting at t2
369                         var tStart:Number;      // t1 or t2
370
371                         // make sure text doesn't run right->left or upside down
372                         if (p1[0] < p2[0] && 
373                                 p1[2] < Math.PI/2 &&
374                                 p1[2] > -Math.PI/2) {
375                                 angleOffset = 0; offsetSign = 1; tStart = t1;
376                         } else {
377                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
378                         } 
379
380                         // make a textfield for each char, centered on the line,
381                         // using getCharBoundaries to rotate it around its center point
382                         var chars:Array = a.split('');
383                         for (var i:int = 0; i < chars.length; i++) {
384                                 var rect:Rectangle = tf.getCharBoundaries(i);
385                                 if (rect) {
386                                         s.addChild(rotatedLetter(chars[i],
387                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
388                                                                                          rect.width, tf.height, angleOffset, textOffset));
389                                 }
390                         }
391                 }
392
393                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
394                         var tf:TextField = new TextField();
395             tf.mouseEnabled = false;
396             tf.mouseWheelEnabled = false;
397                         tf.defaultTextFormat = nameformat;
398                         tf.embedFonts = true;
399                         tf.text = char;
400                         tf.width = tf.textWidth+4;
401                         tf.height = tf.textHeight+4;
402
403                         var p:Array=pointAt(t);
404                         var matrix:Matrix = new Matrix();
405                         matrix.translate(-w/2, -h/2-o);
406                         // ** add (say) -4 to the height to move it up by 4px
407                         matrix.rotate(p[2]+a);
408                         matrix.translate(p[0], p[1]);
409                         tf.transform.matrix = matrix;
410                         return tf;
411                 }
412                 
413                 // Add object (stroke/fill/roadname) to layer sprite
414                 
415                 private function addToLayer(s:DisplayObject,t:uint,sublayer:int=-1):void {
416                         var l:DisplayObject=Map(map).getChildAt(map.WAYSPRITE+layer);
417                         var o:DisplayObject=Sprite(l).getChildAt(t);
418                         if (sublayer!=-1) { o=Sprite(o).getChildAt(sublayer); }
419                         Sprite(o).addChild(s);
420                         sprites.push(s);
421             if ( s is Sprite ) {
422                 Sprite(s).mouseEnabled = false;
423                 Sprite(s).mouseChildren = false;
424             }
425                 }
426
427                 public function getNodeAt(x:Number, y:Number):Node {
428                         for (var i:uint = 0; i < way.length; i++) {
429                 var node:Node = way.getNode(i);
430                 var nodeX:Number = map.lon2coord(node.lon);
431                 var nodeY:Number = map.latp2coord(node.latp);
432                 if ( nodeX >= x-3 && nodeX <= x+3 &&
433                      nodeY >= y-3 && nodeY <= y+3 )
434                     return node;
435             }
436             return null;
437                 }
438
439         private function mouseEvent(event:MouseEvent):void {
440             var node:Node = getNodeAt(event.localX, event.localY);
441             if ( node == null )
442                 map.entityMouseEvent(event, way);
443             else
444                 map.entityMouseEvent(event, node);
445         }
446
447         public function setHighlight(stateType:String, isOn:Boolean):void {
448             if ( isOn && stateClasses[stateType] == null ) {
449                 stateClasses[stateType] = true;
450                 redraw();
451             } else if ( !isOn && stateClasses[stateType] != null ) {
452                 delete stateClasses[stateType];
453                 redraw();
454             }
455         }
456         }
457 }