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