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