Move the area and tiger stateClass assignment to use EntityUI.setStateClass, and...
[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                         removeGenericEventListeners();
41             entity.removeEventListener(Connection.WAY_NODE_ADDED, wayNodeAdded);
42             entity.removeEventListener(Connection.WAY_NODE_REMOVED, wayNodeRemoved);
43             entity.removeEventListener(Connection.WAY_REORDERED, wayReordered);
44             entity.removeEventListener(Connection.WAY_DRAGGED, wayDragged);
45             for (var i:uint = 0; i < Way(entity).length; i++ ) {
46                 Way(entity).getNode(i).removeEventListener(Connection.NODE_MOVED, nodeMoved);
47             }
48                 }
49                 
50                 private function attachNodeListeners():void {
51                         var way:Way=entity as Way;
52             for (var i:uint = 0; i < way.length; i++ ) {
53                 way.getNode(i).addEventListener(Connection.NODE_MOVED, nodeMoved);
54             }
55                 }
56                 
57                 private function wayNodeAdded(event:WayNodeEvent):void {
58                     event.node.addEventListener(Connection.NODE_MOVED, nodeMoved);
59             recalculate();
60                     redraw();
61                         redrawMultis();
62                 }
63                     
64                 private function wayNodeRemoved(event:WayNodeEvent):void {
65                     if (!event.node.hasParent(event.way)) {
66                                 event.node.removeEventListener(Connection.NODE_MOVED, nodeMoved);
67                         }
68                         if (paint.nodeuis[event.node.id]) {
69                                 paint.nodeuis[event.node.id].redraw();
70                         }
71             recalculate();
72                     redraw();
73                         redrawMultis();
74                 }
75                     
76         private function nodeMoved(event:NodeMovedEvent):void {
77                         recalculate();
78             redraw();
79                         redrawMultis();
80         }
81         private function wayReordered(event:EntityEvent):void {
82             redraw();
83                         redrawMultis();
84         }
85                 private function wayDragged(event:WayDraggedEvent):void {
86                         offsetSprites(event.xDelta,event.yDelta);
87                 }
88
89                 override protected function relationAdded(event:RelationMemberEvent):void {
90                         super.relationAdded(event);
91                         redrawMultis();
92                 }
93                 override protected function relationRemoved(event:RelationMemberEvent):void {
94                         super.relationRemoved(event);
95                         redrawMultis();
96                 }
97                 override protected function relationTagChanged(event:TagEvent):void {
98                         super.relationTagChanged(event);
99                         redrawMultis();
100                 }
101
102                 override public function suspendRedraw(event:EntityEvent):void {
103                         super.suspendRedraw(event);
104                         recalculateDue=false;
105                 }
106                 
107                 override public function resumeRedraw(event:EntityEvent):void {
108                         suspended=false;
109                         if (recalculateDue) { recalculate(); }
110                         super.resumeRedraw(event);
111                 }
112
113                 public function redrawMultis():void {
114                         var multis:Array=entity.findParentRelationsOfType('multipolygon','inner');
115                         for each (var m:Relation in multis) {
116                                 var outers:Array=m.findMembersByRole('outer');
117                                 for each (var e:Entity in outers) { 
118                                         if (e is Way && paint.wayuis[e.id]) {
119                                                 paint.wayuis[e.id].redraw();
120                                         }
121                                 }
122                         }
123                 }
124
125         public function setHighlightOnNodes(settings:Object):void {
126                         for (var i:uint = 0; i < Way(entity).length; i++) {
127                 var node:Node = Way(entity).getNode(i);
128                                 if (paint.nodeuis[node.id]) {
129                                         paint.nodeuis[node.id].setHighlight(settings);
130                                         paint.nodeuis[node.id].redraw();
131                                 }
132                         }
133         }
134
135                 // ------------------------------------------------------------------------------------------
136                 // Calculate length etc.
137                 // ** this could be made scale-independent - would speed up redraw
138                 
139                 public function recalculate():void {
140                         if (suspended) { recalculateDue=true; return; }
141                         
142                         var lx:Number, ly:Number, sc:Number;
143                         var node:Node, latp:Number, lon:Number;
144                         var cx:Number=0, cy:Number=0;
145                         var way:Way=entity as Way;
146                         
147                         pathlength=0;
148                         patharea=0;
149                         if (way.length==0) { return; }
150                         
151                         lx = way.getNode(way.length-1).lon;
152                         ly = way.getNode(way.length-1).latp;
153                         for ( var i:uint = 0; i < way.length; i++ ) {
154                 node = way.getNode(i);
155                 latp = node.latp;
156                 lon  = node.lon;
157
158                                 // length and area
159                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
160                                 sc = (lx*latp-lon*ly)*paint.map.scalefactor;
161                                 cx += (lx+lon)*sc;
162                                 cy += (ly+latp)*sc;
163                                 patharea += sc;
164                                 
165                                 // heading
166                                 if (i>0) { heading[i-1]=Math.atan2((lon-lx),(latp-ly)); }
167
168                                 lx=lon; ly=latp;
169                         }
170                         heading[way.length-1]=heading[way.length-2];
171
172                         pathlength*=paint.map.scalefactor;
173                         patharea/=2;
174                         if (patharea!=0 && way.isArea()) {
175                                 centroid_x=paint.map.lon2coord(cx/patharea/6);
176                                 centroid_y=paint.map.latp2coord(cy/patharea/6);
177                         } else if (pathlength>0) {
178                                 var c:Array=pointAt(0.5);
179                                 centroid_x=c[0];
180                                 centroid_y=c[1];
181                         }
182                 }
183
184                 // ------------------------------------------------------------------------------------------
185                 // Redraw
186
187                 override public function doRedraw():Boolean {
188                         interactive=false;
189                         removeSprites();
190                         if (Way(entity).length==0) { return false; }
191                         if (!paint.ready) { return false; }
192
193             // Copy tags object, and add states
194             var tags:Object = entity.getTagsCopy();
195             setStateClass('area', Way(entity).isArea());
196             setStateClass('tiger', (entity.isUneditedTiger() && Globals.vars.highlightTiger));
197             tags=applyStateClasses(tags);
198
199                         // Keep track of maximum stroke width for hitzone
200                         var maxwidth:Number=4;
201
202                         // Create styleList if not already drawn
203                         if (!styleList || !styleList.isValidAt(paint.map.scale)) {
204                                 styleList=paint.ruleset.getStyles(entity, tags, paint.map.scale);
205                         }
206
207                         // Which layer?
208                         layer=styleList.layerOverride();
209                         if (isNaN(layer)) {
210                                 layer=0;
211                                 if (tags['layer']) { layer=Math.min(Math.max(tags['layer'],paint.minlayer),paint.maxlayer); }
212                         }
213
214                         // Iterate through each sublayer, drawing any styles on that layer
215                         var drawn:Boolean;
216                         var multis:Array=entity.findParentRelationsOfType('multipolygon','outer');
217                         var inners:Array=[];
218                         for each (var m:Relation in multis) {
219                                 inners=inners.concat(m.findMembersByRole('inner'));
220                         }
221
222                         for each (var sublayer:Number in styleList.sublayers) {
223                                 if (styleList.shapeStyles[sublayer]) {
224                                         var s:ShapeStyle=styleList.shapeStyles[sublayer];
225                                         var stroke:Shape, fill:Shape, casing:Shape, roadname:Sprite;
226                                         var x0:Number=paint.map.lon2coord(Way(entity).getNode(0).lon);
227                                         var y0:Number=paint.map.latp2coord(Way(entity).getNode(0).latp);
228                                         interactive||=s.interactive;
229
230                                         // Stroke
231                                         if (s.width)  {
232                                                 stroke=new Shape(); addToLayer(stroke,STROKESPRITE,sublayer);
233                                                 stroke.graphics.moveTo(x0,y0);
234                                                 s.applyStrokeStyle(stroke.graphics);
235                                                 if (s.dashes && s.dashes.length>0) {
236                                                         var segments:Array=dashedLine(stroke.graphics,s.dashes); 
237                                                         if (s.line_style) { lineDecoration(stroke.graphics,s,segments); }
238                                                 } else { solidLines(stroke.graphics,inners); }
239                                                 drawn=true;
240                                                 if (s.interactive) { maxwidth=Math.max(maxwidth,s.width); }
241                                         }
242
243                                         // Fill
244                                         if ((!isNaN(s.fill_color) || s.fill_image) && entity.findParentRelationsOfType('multipolygon','inner').length==0) {
245                                                 fill=new Shape(); addToLayer(fill,FILLSPRITE);
246                                                 fill.graphics.moveTo(x0,y0);
247                                                 if (s.fill_image) { new WayBitmapFiller(this,fill.graphics,s); }
248                                                                          else { s.applyFill(fill.graphics); }
249                                                 solidLines(fill.graphics,inners);
250                                                 fill.graphics.endFill();
251                                                 drawn=true;
252                                         }
253
254                                         // Casing
255                                         if (s.casing_width) { 
256                                                 casing=new Shape(); addToLayer(casing,CASINGSPRITE);
257                                                 casing.graphics.moveTo(x0,y0);
258                                                 s.applyCasingStyle(casing.graphics);
259                                                 if (s.casing_dashes && s.casing_dashes.length>0) { dashedLine(casing.graphics,s.casing_dashes); }
260                                                                                                                                         else { solidLines(casing.graphics,inners); }
261                                                 drawn=true;
262                                                 if (s.interactive) { maxwidth=Math.max(maxwidth,s.casing_width); }
263                                         }
264                                 }
265                                 
266                                 if (styleList.textStyles[sublayer]) {
267                                         var t:TextStyle=styleList.textStyles[sublayer];
268                                         interactive||=t.interactive;
269                                         roadname=new Sprite(); addToLayer(roadname,NAMESPRITE);
270                                         nameformat = t.getTextFormat();
271                                         var a:String=tags[t.text];
272                                         if (a) {
273                                                 if (t.font_caps) { a=a.toUpperCase(); }
274                                                 if (t.text_center && centroid_x) {
275                                                         t.writeNameLabel(roadname,a,centroid_x,centroid_y);
276                                                 } else {
277                                                         writeNameOnPath(roadname,a,t.text_offset ? t.text_offset : 0);
278                                                 }
279                                                 if (t.text_halo_radius>0) { roadname.filters=t.getHaloFilter(); }
280                                         }
281                                 }
282                                 
283                                 // ** ShieldStyle to do
284                         }
285
286                         // Draw icons
287                         var r:Number;
288                         var nodeSelected:int=stateClasses["nodeSelected"];
289                         for (var i:uint = 0; i < Way(entity).length; i++) {
290                 var node:Node = Way(entity).getNode(i);
291                                 var nodeStateClasses:Object={};
292 //                              if (i==0) { nodetags['_heading']= heading[i]; }
293 //                                   else { nodetags['_heading']=(heading[i]+heading[i-1])/2; }
294                                 // ** FIXME - heading isn't currently applied
295                                 nodeStateClasses['junction']=(node.numParentWays>1);
296                                 paint.createNodeUI(node,r,layer,nodeStateClasses);
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 }