Support inline status, where the status field is part of e.g. map calls
[potlatch2.git] / net / systemeD / halcyon / WayUI.as
1 package net.systemeD.halcyon {
2
3         import flash.display.*;
4         import flash.events.*;
5         import flash.geom.Matrix;
6         import flash.geom.Rectangle;
7         import flash.text.TextField;
8         import flash.text.TextFormat;
9         
10         import net.systemeD.halcyon.connection.*;
11         import net.systemeD.halcyon.styleparser.*;
12
13         /** The graphical representation of a Way. */ 
14         public class WayUI extends EntityUI {
15
16                 /** Total length of way */
17                 public var pathlength:Number;
18                 /** Area of the way */
19                 public var patharea:Number;
20                 /** X coord of the centre of the area */
21                 public var centroid_x:Number;
22                 /** Y coord of the centre of the area */
23                 public var centroid_y:Number;                           //  |
24                 /** Angle at each node */
25                 public var heading:Array=new Array();
26                 /** vertex to draw exclusively, or not at all (used by DragWayNode) */ 
27                 public var drawExcept:Number;
28                 /** " */
29                 public var drawOnly:Number;
30                 private var indexStart:uint;
31                 private var indexEnd:uint;
32                 public var nameformat:TextFormat;
33                 private var recalculateDue:Boolean=false;
34                 // Store the temporary highlight settings applied to all nodes.
35                 private var nodehighlightsettings: Object={};
36
37                 private const NODESIZE:uint=6;
38
39                 public function WayUI(way:Way, paint:MapPaint) {
40                         super(way,paint);
41             entity.addEventListener(Connection.WAY_NODE_ADDED, wayNodeAdded, false, 0, true);
42             entity.addEventListener(Connection.WAY_NODE_REMOVED, wayNodeRemoved, false, 0, true);
43             entity.addEventListener(Connection.WAY_REORDERED, wayReordered, false, 0, true);
44             entity.addEventListener(Connection.ENTITY_DRAGGED, wayDragged, false, 0, true);
45             attachNodeListeners();
46             attachRelationListeners();
47             recalculate();
48                         redraw();
49                         redrawMultis();
50                 }
51                 
52                 public function removeEventListeners():void {
53                         removeGenericEventListeners();
54             entity.removeEventListener(Connection.WAY_NODE_ADDED, wayNodeAdded);
55             entity.removeEventListener(Connection.WAY_NODE_REMOVED, wayNodeRemoved);
56             entity.removeEventListener(Connection.WAY_REORDERED, wayReordered);
57             entity.removeEventListener(Connection.ENTITY_DRAGGED, wayDragged);
58                         removeNodeListeners();
59                         removeRelationListeners();
60                 }
61                 
62                 private function attachNodeListeners():void {
63                         var way:Way=entity as Way;
64             for (var i:uint = 0; i < way.length; i++ ) {
65                 way.getNode(i).addEventListener(Connection.NODE_MOVED, nodeMoved, false, 0, true);
66             }
67                 }
68                 
69                 private function removeNodeListeners():void {
70                         var way:Way=entity as Way;
71             for (var i:uint = 0; i < way.length; i++ ) {
72                 way.getNode(i).removeEventListener(Connection.NODE_MOVED, nodeMoved);
73             }
74                 }
75                 
76                 private function wayNodeAdded(event:WayNodeEvent):void {
77                     event.node.addEventListener(Connection.NODE_MOVED, nodeMoved, false, 0, true);
78             recalculate();
79                     redraw();
80                         redrawMultis();
81                 }
82                     
83                 private function wayNodeRemoved(event:WayNodeEvent):void {
84                     if (!event.node.hasParent(event.way)) {
85                                 event.node.removeEventListener(Connection.NODE_MOVED, nodeMoved);
86                         }
87                         paint.redrawEntity(event.node);
88             recalculate();
89                     redraw();
90                         redrawMultis();
91                 }
92                     
93         private function nodeMoved(event:NodeMovedEvent):void {
94                         recalculate();
95             redraw();
96                         redrawMultis();
97         }
98         private function wayReordered(event:EntityEvent):void {
99             redraw();
100                         redrawMultis();
101         }
102                 private function wayDragged(event:EntityDraggedEvent):void {
103                         offsetSprites(event.xDelta,event.yDelta);
104                 }
105
106                 override protected function relationAdded(event:RelationMemberEvent):void {
107                         super.relationAdded(event);
108                         redrawMultis();
109                 }
110                 override protected function relationRemoved(event:RelationMemberEvent):void {
111                         super.relationRemoved(event);
112                         redrawMultis();
113                 }
114                 override protected function relationTagChanged(event:TagEvent):void {
115                         super.relationTagChanged(event);
116                         redrawMultis();
117                 }
118
119                 /** Don't redraw until further notice. */
120                 override public function suspendRedraw(event:EntityEvent):void {
121                         super.suspendRedraw(event);
122                         recalculateDue=false;
123                 }
124                 
125                 /** Continue redrawing as normal. */
126                 override public function resumeRedraw(event:EntityEvent):void {
127                         suspended=false;
128                         if (recalculateDue) { recalculate(); }
129                         super.resumeRedraw(event);
130                 }
131
132                 /** Redraw other ways that are the "outer" part of a multipolygon of which we are the "inner" */
133                 public function redrawMultis():void {
134                         var multis:Array=entity.findParentRelationsOfType('multipolygon','inner');
135                         for each (var m:Relation in multis) {
136                                 var outers:Array=m.findMembersByRole('outer');
137                                 for each (var e:Entity in outers) { 
138                                         paint.redrawEntity(e);
139                                 }
140                         }
141                 }
142         
143         /** Mark every node in this way as highlighted, and redraw it. 
144         * 
145         * @param settings Style state that it applies to. @see EntityUI#setStateClass()
146         *  */
147         public function setHighlightOnNodes(settings:Object):void {
148                         for (var i:uint = 0; i < Way(entity).length; i++) {
149                 var node:Node = Way(entity).getNode(i);
150                                 // Speed things up a bit by only setting the highlight if it's either:
151                                 // a) an "un-highlight" (so we don't leave mess behind when scrolling)
152                                 // b) currently onscreen
153                                 // Currently this means if you highlight an object then scroll, nodes will scroll
154                                 // into view that should be highlighted but aren't.
155                                 if (settings.hoverway==false || 
156                                     settings.selectedway==false || 
157                                     node.within(paint.map.edge_l, paint.map.edge_r, paint.map.edge_t, paint.map.edge_b)) {
158                                     paint.setHighlight(node,settings); // Triggers redraw if required
159                                 }
160                                 if (settings.selectedway || settings.hoverway)
161                                         nodehighlightsettings=settings;
162                                 else
163                                         nodehighlightsettings={}; 
164                         }
165         }
166         
167         // An ugly hack to allow nodes that have recently scrolled into view to get highlighted.
168         public function updateHighlights():void {
169                 if (nodehighlightsettings)
170                    setHighlightOnNodes(nodehighlightsettings);
171         }
172
173                 // ------------------------------------------------------------------------------------------
174                 /** Calculate pathlength, patharea, centroid_x, centroid_y, heading[]. 
175                 * ** this could be made scale-independent - would speed up redraw
176                 */
177                 public function recalculate():void {
178                         if (suspended) { recalculateDue=true; return; }
179                         
180                         var lx:Number, ly:Number, sc:Number;
181                         var node:Node, latp:Number, lon:Number;
182                         var cx:Number=0, cy:Number=0;
183                         var way:Way=entity as Way;
184                         
185                         pathlength=0;
186                         patharea=0;
187                         if (way.length==0) { return; }
188                         
189                         lx = way.getNode(way.length-1).lon;
190                         ly = way.getNode(way.length-1).latp;
191                         for ( var i:uint = 0; i < way.length; i++ ) {
192                 node = way.getNode(i);
193                 latp = node.latp;
194                 lon  = node.lon;
195
196                                 // length and area
197                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
198                                 sc = (lx*latp-lon*ly)*paint.map.scalefactor;
199                                 cx += (lx+lon)*sc;
200                                 cy += (ly+latp)*sc;
201                                 patharea += sc;
202                                 
203                                 // heading
204                                 if (i>0) { heading[i-1]=Math.atan2((lon-lx),(latp-ly)); }
205
206                                 lx=lon; ly=latp;
207                         }
208                         heading[way.length-1]=heading[way.length-2];
209
210                         pathlength*=paint.map.scalefactor;
211                         patharea/=2;
212                         if (patharea!=0 && way.isArea()) {
213                                 centroid_x=paint.map.lon2coord(cx/patharea/6);
214                                 centroid_y=paint.map.latp2coord(cy/patharea/6);
215                         } else if (pathlength>0) {
216                                 var c:Array=pointAt(0.5);
217                                 centroid_x=c[0];
218                                 centroid_y=c[1];
219                         }
220                 }
221
222                 // ------------------------------------------------------------------------------------------
223         
224                 /** Go through the complex process of drawing this way, including applying styles, casings, fills, fonts... */
225                 override public function doRedraw():Boolean {
226                         interactive=false;
227                         removeSprites();
228                         if (Way(entity).length==0) { return false; }
229                         if (!paint.ready) { return false; }
230
231             // Copy tags object, and add states
232             var tags:Object = entity.getTagsCopy();
233             setStateClass('area', Way(entity).isArea());
234             setStateClass('tiger', (entity.isUneditedTiger() && Globals.vars.highlightTiger));
235             tags=applyStateClasses(tags);
236                         if (entity.status) { tags['_status']=entity.status; }
237
238                         // Keep track of maximum stroke width for hitzone
239                         var maxwidth:Number=4;
240
241                         // Create styleList if not already drawn
242                         if (!styleList || !styleList.isValidAt(paint.map.scale)) {
243                                 styleList=paint.ruleset.getStyles(entity, tags, paint.map.scale);
244                         }
245
246                         // Which layer?
247                         layer=styleList.layerOverride();
248                         if (isNaN(layer)) {
249                                 layer=0;
250                                 if (tags['layer']) { layer=Math.min(Math.max(tags['layer'],paint.minlayer),paint.maxlayer); }
251                         }
252
253                         // Do we have to draw all nodes in the way?
254                         var hasFills:Boolean=styleList.hasFills();
255                         if (isNaN(drawOnly) || hasFills) {
256                                 indexStart=0; indexEnd=Way(entity).length; 
257                         } else {
258                                 indexStart=Math.max(0,drawOnly-1);
259                                 indexEnd  =Math.min(drawOnly+2,Way(entity).length);
260                         }
261
262                         // Iterate through each subpart, drawing any styles on that layer
263                         var drawn:Boolean;
264                         var multis:Array=entity.findParentRelationsOfType('multipolygon','outer');
265                         var inners:Array=[];
266                         for each (var m:Relation in multis) {
267                                 inners=inners.concat(m.findMembersByRole('inner',Way));
268                         }
269
270                         for each (var subpart:String in styleList.subparts) {
271                                 if (styleList.shapeStyles[subpart]) {
272                                         var s:ShapeStyle=styleList.shapeStyles[subpart];
273                                         var stroke:Shape, fill:Shape, casing:Shape, roadname:Sprite;
274                                         var x0:Number=paint.map.lon2coord(Way(entity).getNode(0).lon);
275                                         var y0:Number=paint.map.latp2coord(Way(entity).getNode(0).latp);
276                                         interactive||=s.interactive;
277
278                                         // Stroke
279                                         if (s.width)  {
280                                                 stroke=new Shape(); addToLayer(stroke,STROKESPRITE,s.sublayer);
281                                                 stroke.graphics.moveTo(x0,y0);
282                                                 s.applyStrokeStyle(stroke.graphics);
283                                                 if (s.dashes && s.dashes.length>0) {
284                                                         var segments:Array=dashedLine(stroke.graphics,s.dashes); 
285                                                         if (s.line_style) { lineDecoration(stroke.graphics,s,segments); }
286                                                 } else { solidLines(stroke.graphics,inners); }
287                                                 drawn=true;
288                                                 if (s.interactive) { maxwidth=Math.max(maxwidth,s.width); }
289                                         }
290
291                                         // Fill
292                                         if ((!isNaN(s.fill_color) || s.fill_image) && entity.findParentRelationsOfType('multipolygon','inner').length==0 && isNaN(drawExcept)) {
293                                                 fill=new Shape(); addToLayer(fill,FILLSPRITE,s.sublayer);
294                                                 fill.graphics.moveTo(x0,y0);
295                                                 if (s.fill_image) { new WayBitmapFiller(this,fill.graphics,s); }
296                                                                          else { s.applyFill(fill.graphics); }
297                                                 solidLines(fill.graphics,inners);
298                                                 fill.graphics.endFill();
299                                                 drawn=true;
300                                         }
301
302                                         // Casing
303                                         if (s.casing_width) { 
304                                                 casing=new Shape(); addToLayer(casing,CASINGSPRITE);
305                                                 casing.graphics.moveTo(x0,y0);
306                                                 s.applyCasingStyle(casing.graphics);
307                                                 if (s.casing_dashes && s.casing_dashes.length>0) { dashedLine(casing.graphics,s.casing_dashes); }
308                                                                                                                                         else { solidLines(casing.graphics,inners); }
309                                                 drawn=true;
310                                                 if (s.interactive) { maxwidth=Math.max(maxwidth,s.casing_width); }
311                                         }
312                                 }
313                                 
314                                 if (styleList.textStyles[subpart] && isNaN(drawExcept)) {
315                                         var t:TextStyle=styleList.textStyles[subpart];
316                                         interactive||=t.interactive;
317                                         roadname=new Sprite(); addToLayer(roadname,NAMESPRITE);
318                                         nameformat = t.getTextFormat();
319                                         var a:String=tags[t.text];
320                                         if (a) {
321                                                 if (t.font_caps) { a=a.toUpperCase(); }
322                                                 if (t.text_center && centroid_x) {
323                                                         t.writeNameLabel(roadname,a,centroid_x,centroid_y);
324                                                 } else {
325                                                         writeNameOnPath(roadname,a,t.text_offset ? t.text_offset : 0);
326                                                 }
327                                                 if (t.text_halo_radius>0) { roadname.filters=t.getHaloFilter(); }
328                                         }
329                                 }
330                                 
331                                 // ** ShieldStyle to do
332                         }
333
334                         // Draw icons
335                         var r:Number;
336                         var nodeSelected:int=stateClasses["nodeSelected"];
337                         for (var i:uint = indexStart; i < indexEnd; i++) {
338                 var node:Node = Way(entity).getNode(i);
339                                 var nodeStateClasses:Object={};
340 //                              if (i==0) { nodetags['_heading']= heading[i]; }
341 //                                   else { nodetags['_heading']=(heading[i]+heading[i-1])/2; }
342                                 // ** FIXME - heading isn't currently applied
343                                 nodeStateClasses['junction']=(node.numParentWays>1);
344                                 paint.createNodeUI(node,r,layer,nodeStateClasses);
345                         }
346                         if (!drawn) { return false; } // If not visible, no hitzone.
347                         
348             // create a generic "way" hitzone sprite
349                         if (interactive && drawn) {
350                     hitzone = new Sprite();
351                     hitzone.graphics.lineStyle(maxwidth, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
352                     solidLines(hitzone.graphics,[]);
353                     hitzone.visible = false;
354                                 setListenSprite();
355                         }
356
357                         return true;
358                 }
359                 
360                 // ------------------------------------------------------------------------------------------
361                 // Drawing support functions
362
363                 /** Draw solid polyline */
364                 
365                 public function solidLines(g:Graphics,inners:Array):void {
366                         solidLine(g);
367                         for each (var w:Way in inners) { solidLineOtherWay(g,w); }
368                 }
369
370                 private function solidLine(g:Graphics):void {
371                         if (indexEnd==0) { return; }
372                         var way:Way=entity as Way;
373                         
374             var node:Node = way.getNode(indexStart);
375                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
376                         for (var i:uint = indexStart+1; i < indexEnd; i++) {
377                 node = way.getNode(i);
378                                 if (!isNaN(drawExcept) && (i-1==drawExcept || i==drawExcept)) {
379                                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
380                                 } else {
381                                         g.lineTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
382                                 }
383                         }
384                 }
385
386                 private function solidLineOtherWay(g:Graphics,way:Way):void {
387                         if (way.length==0) { return; }
388                         
389                         var node:Node = way.getNode(0);
390                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
391                         for (var i:uint = 1; i < way.length; i++) {
392                                 node = way.getNode(i);
393                                 g.lineTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
394                         }
395                 }
396
397                 /** Draw dashed polyline */
398                 
399                 private function dashedLine(g:Graphics,dashes:Array):Array {
400                         var way:Way=entity as Way;
401                         var segments:Array=[]; // array of dash locations being constructed for later arrow drawing
402                         var draw:Boolean=false; // are we drawing or marking empty space till next dash
403                         var dashleft:Number=0; // how much of current dash is left
404                         var dc:Array=new Array(); // copy of dashes, gets consumed then replaced
405                         var xc:Number, yc:Number; // normalised vector coordinates of direction to next node 
406                         var curx:Number, cury:Number; // current drawing location
407                         var dx:Number, dy:Number, segleft:Number=0; // distance remaining until next node
408                         var i:int=indexStart; // node index
409                         var dashstartx:int, dashstarty:int; // needed to draw reverse arrows
410                         var dashstartxc: Number, dashstartyc: Number;
411
412             var node:Node = way.getNode(i);
413             var nextNode:Node = way.getNode(i);
414                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
415                         while (i < indexEnd-1 || segleft>0) {
416                                 if (dashleft<=0) {      // should be ==0
417                                     // finished drawing current dash, pop another one off the pattern, looping if necessary
418                                         if (dc.length==0) { dc=dashes.slice(0); }
419                                         dashleft=dc.shift();
420                                         if (draw) { segments.push([curx,cury,xc,yc, dashstartx, dashstarty, dashstartxc, dashstartyc]); }
421                                         draw=!draw;
422                                         // record start of each dash, if we need to draw a reverse arrow head later
423                                         dashstartx = curx; dashstarty = cury;
424                                         dashstartxc = xc; dashstartyc = yc;
425                                 }
426                                 if (i==drawExcept || i==drawExcept+1) { draw=false; }
427                                 if (segleft<=0) {       // should be ==0
428                     // arrived at target node. calculate direction to next node.
429                     node = way.getNode(i);
430                     nextNode = way.getNode(i+1);
431                                         curx=paint.map.lon2coord(node.lon);
432                     dx=paint.map.lon2coord(nextNode.lon)-curx;
433                                         cury=paint.map.latp2coord(node.latp);
434                     dy=paint.map.latp2coord(nextNode.latp)-cury;
435                                         segleft=Math.sqrt(dx*dx+dy*dy);
436                                         xc = dx/segleft;
437                                         yc = dy/segleft;
438                                         if (i==0) {
439                         // record start location of very first dash
440                         dashstartx = curx; dashstarty = cury;
441                         dashstartxc = xc; dashstartyc = yc;
442                                         }
443                                         i++;
444                                 }
445
446                                 if (segleft<=dashleft) {
447                                         // the path segment is shorter than the dash: draw to end of segment
448                                         curx+=dx; cury+=dy;
449                                         moveLine(g,curx,cury,draw);
450                                         dashleft-=segleft; segleft=0;
451                                 } else {
452                                         // draw whole dash, then loop
453                                         curx+=dashleft*xc; dx-=dashleft*xc;
454                                         cury+=dashleft*yc; dy-=dashleft*yc;
455                                         moveLine(g,curx,cury,draw);
456                                         segleft-=dashleft; dashleft=0;
457                                 }
458                         }
459                         return segments;
460                 }
461
462                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
463                         if (draw) { g.lineTo(x,y); }
464                                  else { g.moveTo(x,y); }
465                 }
466
467                 /** Draw decoration (arrows etc.) */
468                 
469                 private function lineDecoration(g:Graphics,s:ShapeStyle,segments:Array):void {
470                         var c:int=s.color ? s.color : 0;
471                         switch (s.line_style.toLowerCase()) {
472
473                                 case 'arrows':; case 'arrows-reversed':
474                                         var w:Number=s.width*1.5;  // width of arrow
475                                         var l:Number=s.width*2;    // length of arrow
476                                         g.lineStyle(1,c);
477                                         for each (var seg:Array in segments) {
478                                                 g.beginFill(c);
479                                                 // seg: {dashendx, dashendy, dx, dy, dashstartx, dashstarty, dashstartdx, dashstartdy} 
480                                                 // where dx is normalised x component of direction vector
481                                                 // note that a dash can go around a corner, so the info is not redundant
482                                                 
483                                                 if (s.line_style.toLowerCase() == "arrows-reversed") {
484                                 g.moveTo(seg[4]-l*seg[6], seg[5]-l*seg[7]); // note reversed arrow head
485                                 g.lineTo(seg[4]-w*seg[7], seg[5]+w*seg[6]);
486                                 g.lineTo(seg[4]+w*seg[7], seg[5]-w*seg[6]);
487                                                 } else {
488                                                         g.moveTo(seg[0]+l*seg[2], seg[1]+l*seg[3]);
489                                 g.lineTo(seg[0]-w*seg[3], seg[1]+w*seg[2]);
490                                 g.lineTo(seg[0]+w*seg[3], seg[1]-w*seg[2]);
491                             }
492                                                 g.endFill();
493                                         }
494                                         break;
495                 case 'triangle':
496                     w=s.width*10;   //triangle egde
497                     g.lineStyle(1,c);
498                     for each (seg in segments) {
499                         g.beginFill(c);
500                         var angle0:Number = -Math.atan2(seg[3], seg[2]) + Math.PI / 2; //0
501                         var angle1:Number = -Math.atan2(seg[3], seg[2]) - Math.PI/6;       //60
502                         g.moveTo(seg[0], seg[1]);//start 0,0
503                         g.lineTo(seg[0] - w * Math.sin(angle0), seg[1] - w * Math.cos(angle0));
504                         g.lineTo(seg[0] + w * Math.sin(angle1), seg[1] + w * Math.cos(angle1));
505                         g.endFill();
506                     }
507                     break;
508                                 }
509                 }
510                 
511                 /** Find point partway (0-1) along a path
512                   * @return (x,y,angle)
513                   * inspired by senocular's Path.as */
514                 
515                 private function pointAt(t:Number):Array {
516                         var way:Way=entity as Way;
517                         var totallen:Number = t*pathlength;
518                         var curlen:Number = 0;
519                         var dx:Number, dy:Number, seglen:Number;
520                         for (var i:int = 1; i < way.length; i++){
521                                 dx=paint.map.lon2coord(way.getNode(i).lon)-paint.map.lon2coord(way.getNode(i-1).lon);
522                                 dy=paint.map.latp2coord(way.getNode(i).latp)-paint.map.latp2coord(way.getNode(i-1).latp);
523                                 seglen=Math.sqrt(dx*dx+dy*dy);
524                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
525                                 return new Array(paint.map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
526                                                                  paint.map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
527                                                                  Math.atan2(dy,dx));
528                         }
529                         return new Array(0, 0, 0);
530                 }
531
532                 /** Draw name along path
533                  * based on code by Tom Carden
534                  * */
535                 
536                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
537
538                         // make a dummy textfield so we can measure its width
539                         var tf:TextField = new TextField();
540                         tf.defaultTextFormat = nameformat;
541                         tf.text = a;
542                         tf.width = tf.textWidth+4;
543                         tf.height = tf.textHeight+4;
544                         if (pathlength<tf.width) { return; }    // no room for text?
545
546                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
547                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
548
549                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
550                         var offsetSign:Number;  // -1 if we're starting at t2
551                         var tStart:Number;      // t1 or t2
552
553                         // make sure text doesn't run right->left or upside down
554                         if (p1[0] < p2[0] && 
555                                 p1[2] < Math.PI/2 &&
556                                 p1[2] > -Math.PI/2) {
557                                 angleOffset = 0; offsetSign = 1; tStart = t1;
558                         } else {
559                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
560                         } 
561
562                         // make a textfield for each char, centered on the line,
563                         // using getCharBoundaries to rotate it around its center point
564                         var chars:Array = a.split('');
565                         for (var i:int = 0; i < chars.length; i++) {
566                                 var rect:Rectangle = tf.getCharBoundaries(i);
567                                 if (rect) {
568                                         s.addChild(rotatedLetter(chars[i],
569                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
570                                                                                          rect.width, tf.height, angleOffset, textOffset));
571                                 }
572                         }
573                 }
574
575                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
576                         var tf:TextField = new TextField();
577             tf.mouseEnabled = false;
578             tf.mouseWheelEnabled = false;
579                         tf.defaultTextFormat = nameformat;
580                         tf.embedFonts = true;
581                         tf.text = char;
582                         tf.width = tf.textWidth+4;
583                         tf.height = tf.textHeight+4;
584
585                         var p:Array=pointAt(t);
586                         var matrix:Matrix = new Matrix();
587                         matrix.translate(-w/2, -h/2-o);
588                         // ** add (say) -4 to the height to move it up by 4px
589                         matrix.rotate(p[2]+a);
590                         matrix.translate(p[0], p[1]);
591                         tf.transform.matrix = matrix;
592                         return tf;
593                 }
594                 
595                 public function getNodeAt(x:Number, y:Number):Node {
596                         var way:Way=entity as Way;
597                         for (var i:uint = 0; i < way.length; i++) {
598                 var node:Node = way.getNode(i);
599                 var nodeX:Number = paint.map.lon2coord(node.lon);
600                 var nodeY:Number = paint.map.latp2coord(node.latp);
601                 if ( nodeX >= x-NODESIZE && nodeX <= x+NODESIZE &&
602                      nodeY >= y-NODESIZE && nodeY <= y+NODESIZE )
603                     return node;
604             }
605             return null;
606                 }
607
608                 // ------------------------------------------------------------------------------------------
609                 /* Interaction */
610         // TODO: can this be sped up? Hit testing for long ways (that go off the screen) seems to be very slow. */
611                 public function hitTest(x:Number, y:Number):Way {
612                         if (hitzone.hitTestPoint(x,y,true)) { return entity as Way; }
613                         return null;
614                 }
615         }
616 }