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