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