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