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