6dc1b4c51799d1c971a068cde759a020a701cde5
[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             if (entity.isUneditedTiger() && Globals.vars.highlightTiger) { tags[':tiger']='yes'; }
192
193                         // Which layer?
194                         layer=0;
195                         if (tags['layer']) { layer=Math.min(Math.max(tags['layer'],paint.minlayer),paint.maxlayer); }
196
197                         // Keep track of maximum stroke width for hitzone
198                         var maxwidth:Number=4;
199
200                         // Create styleList if not already drawn
201                         if (!styleList || !styleList.isValidAt(paint.map.scale)) {
202                                 styleList=paint.ruleset.getStyles(entity, tags, paint.map.scale);
203                         }
204
205                         // Iterate through each sublayer, drawing any styles on that layer
206                         var drawn:Boolean;
207                         var multis:Array=entity.findParentRelationsOfType('multipolygon','outer');
208                         var inners:Array=[];
209                         for each (var m:Relation in multis) {
210                                 inners=inners.concat(m.findMembersByRole('inner'));
211                         }
212
213                         for each (var sublayer:Number in styleList.sublayers) {
214                                 if (styleList.shapeStyles[sublayer]) {
215                                         var s:ShapeStyle=styleList.shapeStyles[sublayer];
216                                         var stroke:Shape, fill:Shape, casing:Shape, roadname:Sprite;
217                                         var x0:Number=paint.map.lon2coord(Way(entity).getNode(0).lon);
218                                         var y0:Number=paint.map.latp2coord(Way(entity).getNode(0).latp);
219                                         interactive||=s.interactive;
220
221                                         // Stroke
222                                         if (s.width)  {
223                                                 stroke=new Shape(); addToLayer(stroke,STROKESPRITE,sublayer);
224                                                 stroke.graphics.moveTo(x0,y0);
225                                                 s.applyStrokeStyle(stroke.graphics);
226                                                 if (s.dashes && s.dashes.length>0) {
227                                                         var segments:Array=dashedLine(stroke.graphics,s.dashes); 
228                                                         if (s.line_style) { lineDecoration(stroke.graphics,s,segments); }
229                                                 } else { solidLines(stroke.graphics,inners); }
230                                                 drawn=true;
231                                                 if (s.interactive) { maxwidth=Math.max(maxwidth,s.width); }
232                                         }
233
234                                         // Fill
235                                         if ((!isNaN(s.fill_color) || s.fill_image) && entity.findParentRelationsOfType('multipolygon','inner').length==0) {
236                                                 fill=new Shape(); addToLayer(fill,FILLSPRITE);
237                                                 fill.graphics.moveTo(x0,y0);
238                                                 if (s.fill_image) { new WayBitmapFiller(this,fill.graphics,s); }
239                                                                          else { s.applyFill(fill.graphics); }
240                                                 solidLines(fill.graphics,inners);
241                                                 fill.graphics.endFill();
242                                                 drawn=true;
243                                         }
244
245                                         // Casing
246                                         if (s.casing_width) { 
247                                                 casing=new Shape(); addToLayer(casing,CASINGSPRITE);
248                                                 casing.graphics.moveTo(x0,y0);
249                                                 s.applyCasingStyle(casing.graphics);
250                                                 if (s.casing_dashes && s.casing_dashes.length>0) { dashedLine(casing.graphics,s.casing_dashes); }
251                                                                                                                                         else { solidLines(casing.graphics,inners); }
252                                                 drawn=true;
253                                                 if (s.interactive) { maxwidth=Math.max(maxwidth,s.casing_width); }
254                                         }
255                                 }
256                                 
257                                 if (styleList.textStyles[sublayer]) {
258                                         var t:TextStyle=styleList.textStyles[sublayer];
259                                         interactive||=t.interactive;
260                                         roadname=new Sprite(); addToLayer(roadname,NAMESPRITE);
261                                         nameformat = t.getTextFormat();
262                                         var a:String=tags[t.text];
263                                         if (a) {
264                                                 if (t.font_caps) { a=a.toUpperCase(); }
265                                                 if (t.text_center && centroid_x) {
266                                                         t.writeNameLabel(roadname,a,centroid_x,centroid_y);
267                                                 } else {
268                                                         writeNameOnPath(roadname,a,t.text_offset ? t.text_offset : 0);
269                                                 }
270                                                 if (t.text_halo_radius>0) { roadname.filters=t.getHaloFilter(); }
271                                         }
272                                 }
273                                 
274                                 // ** ShieldStyle to do
275                         }
276
277                         // Draw icons
278                         var r:Number;
279                         var nodeSelected:int=stateClasses["nodeSelected"];
280                         for (var i:uint = 0; i < Way(entity).length; i++) {
281                 var node:Node = Way(entity).getNode(i);
282                                 var nodeStateClasses:Object={};
283 //                              if (i==0) { nodetags['_heading']= heading[i]; }
284 //                                   else { nodetags['_heading']=(heading[i]+heading[i-1])/2; }
285                                 // ** FIXME - heading isn't currently applied
286                                 nodeStateClasses['junction']=(node.numParentWays>1);
287
288                                 if (paint.nodeuis[node.id]) {
289                                         var nodeui:NodeUI=paint.nodeuis[node.id];
290                                         for (var state:String in nodeStateClasses) {
291                                                 nodeui.setStateClass(state,nodeStateClasses[state]);
292                                         }
293                                         nodeui.redraw();
294                                 } else {
295                                         paint.nodeuis[node.id]=new NodeUI(node,paint,r,layer,nodeStateClasses);
296                                 }
297                         }
298                         if (!drawn) { return false; }
299                         
300             // create a generic "way" hitzone sprite
301                         if (interactive && drawn) {
302                     hitzone = new Sprite();
303                     hitzone.graphics.lineStyle(maxwidth, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
304                     solidLines(hitzone.graphics,[]);
305                     hitzone.visible = false;
306                                 setListenSprite();
307                         }
308
309                         return true;
310                 }
311                 
312                 // ------------------------------------------------------------------------------------------
313                 // Drawing support functions
314
315                 // Draw solid polyline
316                 
317                 public function solidLines(g:Graphics,inners:Array):void {
318                         solidLine(g,entity as Way);
319                         for each (var w:Way in inners) { solidLine(g,w); }
320                 }
321
322                 private function solidLine(g:Graphics,w:Way):void {
323                         if (w.length==0) { return; }
324             var node:Node = w.getNode(0);
325                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
326                         for (var i:uint = 1; i < w.length; i++) {
327                 node = w.getNode(i);
328                                 g.lineTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
329                         }
330                 }
331
332                 // Draw dashed polyline
333                 
334                 private function dashedLine(g:Graphics,dashes:Array):Array {
335                         var way:Way=entity as Way;
336                         var segments:Array=[];
337                         var draw:Boolean=false, dashleft:Number=0, dc:Array=new Array();
338                         var a:Number, xc:Number, yc:Number;
339                         var curx:Number, cury:Number;
340                         var dx:Number, dy:Number, segleft:Number=0;
341                         var i:int=0;
342
343             var node:Node = way.getNode(0);
344             var nextNode:Node = way.getNode(0);
345                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
346                         while (i < way.length-1 || segleft>0) {
347                                 if (dashleft<=0) {      // should be ==0
348                                         if (dc.length==0) { dc=dashes.slice(0); }
349                                         dashleft=dc.shift();
350                                         if (draw) { segments.push([curx,cury,dx,dy]); }
351                                         draw=!draw;
352                                 }
353                                 if (segleft<=0) {       // should be ==0
354                     node = way.getNode(i);
355                     nextNode = way.getNode(i+1);
356                                         curx=paint.map.lon2coord(node.lon);
357                     dx=paint.map.lon2coord(nextNode.lon)-curx;
358                                         cury=paint.map.latp2coord(node.latp);
359                     dy=paint.map.latp2coord(nextNode.latp)-cury;
360                                         a=Math.atan2(dy,dx); xc=Math.cos(a); yc=Math.sin(a);
361                                         segleft=Math.sqrt(dx*dx+dy*dy);
362                                         i++;
363                                 }
364
365                                 if (segleft<=dashleft) {
366                                         // the path segment is shorter than the dash
367                                         curx+=dx; cury+=dy;
368                                         moveLine(g,curx,cury,draw);
369                                         dashleft-=segleft; segleft=0;
370                                 } else {
371                                         // the path segment is longer than the dash
372                                         curx+=dashleft*xc; dx-=dashleft*xc;
373                                         cury+=dashleft*yc; dy-=dashleft*yc;
374                                         moveLine(g,curx,cury,draw);
375                                         segleft-=dashleft; dashleft=0;
376                                 }
377                         }
378                         return segments;
379                 }
380
381                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
382                         if (draw) { g.lineTo(x,y); }
383                                  else { g.moveTo(x,y); }
384                 }
385
386                 // Draw decoration (arrows etc.)
387                 
388                 private function lineDecoration(g:Graphics,s:ShapeStyle,segments:Array):void {
389                         var c:int=s.color ? s.color : 0;
390                         switch (s.line_style.toLowerCase()) {
391
392                                 case 'arrows':
393                                         var w:Number=s.width*1.5;       // width of arrow
394                                         var l:Number=s.width*2;         // length of arrow
395                                         var angle0:Number, angle1:Number, angle2:Number;
396                                         g.lineStyle(1,c);
397                                         for each (var seg:Array in segments) {
398                                                 g.beginFill(c);
399                                                 angle0= Math.atan2(seg[3],seg[2]);
400                                                 angle1=-Math.atan2(seg[3],seg[2]);
401                                                 angle2=-Math.atan2(seg[3],seg[2])-Math.PI;
402                                                 g.moveTo(seg[0]+l*Math.cos(angle0),
403                                                          seg[1]+l*Math.sin(angle0));
404                                                 g.lineTo(seg[0]+w*Math.sin(angle1),
405                                                          seg[1]+w*Math.cos(angle1));
406                                                 g.lineTo(seg[0]+w*Math.sin(angle2),
407                                                          seg[1]+w*Math.cos(angle2));
408                                                 g.endFill();
409                                         }
410                                         break;
411                                 }
412                 }
413
414                 
415                 // Find point partway (0-1) along a path
416                 // returns (x,y,angle)
417                 // inspired by senocular's Path.as
418                 
419                 private function pointAt(t:Number):Array {
420                         var way:Way=entity as Way;
421                         var totallen:Number = t*pathlength;
422                         var curlen:Number = 0;
423                         var dx:Number, dy:Number, seglen:Number;
424                         for (var i:int = 1; i < way.length; i++){
425                                 dx=paint.map.lon2coord(way.getNode(i).lon)-paint.map.lon2coord(way.getNode(i-1).lon);
426                                 dy=paint.map.latp2coord(way.getNode(i).latp)-paint.map.latp2coord(way.getNode(i-1).latp);
427                                 seglen=Math.sqrt(dx*dx+dy*dy);
428                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
429                                 return new Array(paint.map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
430                                                                  paint.map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
431                                                                  Math.atan2(dy,dx));
432                         }
433                         return new Array(0, 0, 0);
434                 }
435
436                 // Draw name along path
437                 // based on code by Tom Carden
438                 
439                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
440
441                         // make a dummy textfield so we can measure its width
442                         var tf:TextField = new TextField();
443                         tf.defaultTextFormat = nameformat;
444                         tf.text = a;
445                         tf.width = tf.textWidth+4;
446                         tf.height = tf.textHeight+4;
447                         if (pathlength<tf.width) { return; }    // no room for text?
448
449                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
450                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
451
452                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
453                         var offsetSign:Number;  // -1 if we're starting at t2
454                         var tStart:Number;      // t1 or t2
455
456                         // make sure text doesn't run right->left or upside down
457                         if (p1[0] < p2[0] && 
458                                 p1[2] < Math.PI/2 &&
459                                 p1[2] > -Math.PI/2) {
460                                 angleOffset = 0; offsetSign = 1; tStart = t1;
461                         } else {
462                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
463                         } 
464
465                         // make a textfield for each char, centered on the line,
466                         // using getCharBoundaries to rotate it around its center point
467                         var chars:Array = a.split('');
468                         for (var i:int = 0; i < chars.length; i++) {
469                                 var rect:Rectangle = tf.getCharBoundaries(i);
470                                 if (rect) {
471                                         s.addChild(rotatedLetter(chars[i],
472                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
473                                                                                          rect.width, tf.height, angleOffset, textOffset));
474                                 }
475                         }
476                 }
477
478                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
479                         var tf:TextField = new TextField();
480             tf.mouseEnabled = false;
481             tf.mouseWheelEnabled = false;
482                         tf.defaultTextFormat = nameformat;
483                         tf.embedFonts = true;
484                         tf.text = char;
485                         tf.width = tf.textWidth+4;
486                         tf.height = tf.textHeight+4;
487
488                         var p:Array=pointAt(t);
489                         var matrix:Matrix = new Matrix();
490                         matrix.translate(-w/2, -h/2-o);
491                         // ** add (say) -4 to the height to move it up by 4px
492                         matrix.rotate(p[2]+a);
493                         matrix.translate(p[0], p[1]);
494                         tf.transform.matrix = matrix;
495                         return tf;
496                 }
497                 
498                 public function getNodeAt(x:Number, y:Number):Node {
499                         var way:Way=entity as Way;
500                         for (var i:uint = 0; i < way.length; i++) {
501                 var node:Node = way.getNode(i);
502                 var nodeX:Number = paint.map.lon2coord(node.lon);
503                 var nodeY:Number = paint.map.latp2coord(node.latp);
504                 if ( nodeX >= x-NODESIZE && nodeX <= x+NODESIZE &&
505                      nodeY >= y-NODESIZE && nodeY <= y+NODESIZE )
506                     return node;
507             }
508             return null;
509                 }
510
511                 // ------------------------------------------------------------------------------------------
512                 // Interaction
513
514                 public function hitTest(x:Number, y:Number):Way {
515                         if (hitzone.hitTestPoint(x,y,true)) { return entity as Way; }
516                         return null;
517                 }
518         }
519 }