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