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