fe0527aedd96befe2b276d074cf7ba5609c53f2a
[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.AntiAliasType;
8         import flash.text.GridFitType;
9         import flash.text.TextField;
10         import flash.text.TextFormat;
11         import flash.events.*;
12         import net.systemeD.halcyon.styleparser.*;
13     import net.systemeD.halcyon.connection.*;
14
15         public class WayUI {
16         private var way:Way;
17
18                 public var pathlength:Number;                           // length of path
19                 public var patharea:Number;                                     // area of path
20                 public var centroid_x:Number;                           // centroid
21                 public var centroid_y:Number;                           //  |
22                 public var layer:int=0;                                         // map layer
23                 public var map:Map;                                                     // reference to parent map
24                 public var sprites:Array=new Array();           // instances in display list
25         private var hitzone:Sprite;
26
27                 public static const DEFAULT_TEXTFIELD_PARAMS:Object = {
28                         embedFonts: true,
29                         antiAliasType: AntiAliasType.ADVANCED,
30                         gridFitType: GridFitType.NONE
31                 };
32                 public var nameformat:TextFormat;
33
34
35                 public function WayUI(way:Way, map:Map) {
36                         this.way = way;
37                         this.map = map;
38             init();
39             way.addEventListener(Connection.TAG_CHANGE, wayTagChanged);
40                 }
41                 
42         private function wayTagChanged(event:TagEvent):void {
43             redraw();
44         }
45
46                 private function init():void {
47                         recalculate();
48                         redraw();
49                         // updateBbox(lon, lat);
50                         // ** various other stuff
51                 }
52
53                 // ------------------------------------------------------------------------------------------
54                 // Calculate length etc.
55                 // ** this could be made scale-independent - would speed up redraw
56                 
57                 public function recalculate():void {
58                         var lx:Number, ly:Number, sc:Number;
59                         var cx:Number=0, cy:Number=0;
60                         pathlength=0;
61                         patharea=0;
62                         
63                         lx = way.getNode(way.length-1).lon;
64                         ly = way.getNode(way.length-1).latp;
65                         for ( var i:uint = 0; i < way.length; i++ ) {
66                 var node:Node = way.getNode(i);
67                 var latp:Number = node.latp;
68                 var lon:Number  = node.lon;
69                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
70                                 sc = (lx*latp-lon*ly)*map.scalefactor;
71                                 cx += (lx+lon)*sc;
72                                 cy += (ly+latp)*sc;
73                                 patharea += sc;
74                                 lx=lon; ly=latp;
75                         }
76
77                         pathlength*=map.scalefactor;
78                         patharea/=2;
79                         if (patharea!=0 && way.isArea()) {
80                                 centroid_x=map.lon2coord(cx/patharea/6);
81                                 centroid_y=map.latp2coord(cy/patharea/6);
82                         } else if (pathlength>0) {
83                                 var c:Array=pointAt(0.5);
84                                 centroid_x=c[0];
85                                 centroid_y=c[1];
86                         }
87                 }
88
89                 // ------------------------------------------------------------------------------------------
90                 // Redraw
91
92                 public function redraw():void {
93             var tags:Object = way.getTagsCopy();
94
95                         // remove all currently existing sprites
96                         while (sprites.length>0) {
97                                 var d:DisplayObject=sprites.pop(); d.parent.removeChild(d);
98                         }
99
100                         // which layer?
101                         layer=5;
102                         if ( tags['layer'] )
103                 layer=Math.min(Math.max(tags['layer']+5,-5),5)+5;
104
105                         // set style
106                         var styles:Array=map.ruleset.getStyles(false, tags, map.scale);
107                         for each (var s:* in styles) {
108
109                                 if (s is ShapeStyle) {
110                                         var stroke:Shape, fill:Shape, roadname:Sprite, f:Graphics, g:Graphics;
111                                         var doStroke:Boolean=false, doDashed:Boolean=false;
112                                         var doFill:Boolean=false, fill_colour:uint, fill_opacity:Number;
113                                         var doCasing:Boolean=false, doDashedCasing:Boolean=false;
114
115                                         // Set stroke style
116                                         if (s.isStroked)  {
117                                                 stroke=new Shape(); addToLayer(stroke,1,s.sublayer); g=stroke.graphics;
118                                 g.moveTo(map.lon2coord(way.getNode(0).lon), map.latp2coord(way.getNode(0).latp));
119                                                 g.lineStyle(s.stroke_width, s.stroke_colour, s.stroke_opacity/100,
120                                                                         false, "normal", s.stroke_linecap, s.stroke_linejoin);
121                                         }
122
123                                         // Set fill and casing style
124                                         if (s.isFilled || s.isCased) {
125                                                 fill=new Shape(); addToLayer(fill,0); f=fill.graphics;
126                                 f.moveTo(map.lon2coord(way.getNode(0).lon), map.latp2coord(way.getNode(0).latp));
127                                                 if (s.isCased)  { f.lineStyle(s.casing_width, s.casing_colour, s.casing_opacity/100,
128                                                                                   false, "normal", s.stroke_linecap, s.stroke_linejoin); }
129                                                 if (s.isFilled) { f.beginFill(s.fill_colour,s.fill_opacity/100); }
130                                         }
131
132                                         // Draw stroke
133                                         if (s.stroke_dashArray.length>0) { dashedLine(g,s.stroke_dashArray); }
134                                                            else if (s.isStroked) { solidLine(g); }
135                         
136                                         // Draw fill and casing
137                                         if (s.casing_dashArray.length>0) { dashedLine(f,s.casing_dashArray); f.lineStyle(); }
138                                         if (s.isFilled)                                  { f.beginFill(s.fill_colour,s.fill_opacity/100); 
139                                                                                                            solidLine(f); f.endFill(); }
140                                         else if (s.isCased && s.casing_dashArray.length==0) { solidLine(f); }
141
142
143                                 } else if (s is TextStyle && s.tag && tags[s.tag]) {
144                                         roadname=new Sprite(); addToLayer(roadname,2);
145                                         nameformat = s.getTextFormat();
146                                         var a:String=tags[s.tag]; if (s.font_caps) { a=a.toUpperCase(); }
147                                         if (s.isLine) {
148                                                 writeNameOnPath(roadname,a,s.text_offset ? s.text_offset : 0);
149                                                 if (s.pullout_radius>0) { roadname.filters=s.getPulloutFilter(); }
150                                         } else if (centroid_x) {
151                                                 s.writeNameLabel(roadname,tags[s.tag],centroid_x,centroid_y);
152                                         }
153
154
155                                 } else if (s is ShieldStyle) {
156                                         // ** to do
157                                 }
158                         }
159
160             if ( styles.length == 0 ) {
161                 // there's no styles... so add a thin trace
162                 var def:Sprite = new Sprite();
163                 def.graphics.lineStyle(0.5, 0x808080, 1, false, "normal");
164                 solidLine(def.graphics);
165                 addToLayer(def, 1);
166             }
167
168             // create a generic "way" hitzone sprite
169             hitzone = new Sprite();
170             hitzone.graphics.lineStyle(4, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
171             solidLine(hitzone.graphics);
172             addToLayer(hitzone, 2);
173             hitzone.visible = false;
174
175             var listenSprite:Sprite = new Sprite();
176             listenSprite.hitArea = hitzone;
177             addToLayer(listenSprite, 2);
178             listenSprite.buttonMode = true;
179             listenSprite.mouseEnabled = true;
180             listenSprite.addEventListener(MouseEvent.CLICK, mouseEvent);
181             listenSprite.addEventListener(MouseEvent.DOUBLE_CLICK, mouseEvent);
182             listenSprite.addEventListener(MouseEvent.MOUSE_OVER, mouseEvent);
183             listenSprite.addEventListener(MouseEvent.MOUSE_OUT, mouseEvent);
184
185                 }
186                 
187                 // ------------------------------------------------------------------------------------------
188                 // Drawing support functions
189
190                 // Draw solid polyline
191                 
192                 private function solidLine(g:Graphics):void {
193             var node:Node = way.getNode(0);
194                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
195                         for (var i:uint = 1; i < way.length; i++) {
196                 node = way.getNode(i);
197                                 g.lineTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
198                         }
199                 }
200
201                 // Draw dashed polyline
202                 
203                 private function dashedLine(g:Graphics,dashes:Array):void {
204                         var draw:Boolean=false, dashleft:Number=0, dc:Array=new Array();
205                         var a:Number, xc:Number, yc:Number;
206                         var curx:Number, cury:Number;
207                         var dx:Number, dy:Number, segleft:Number=0;
208                         var i:int=0;
209
210             var node:Node = way.getNode(0);
211             var nextNode:Node = way.getNode(0);
212                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
213                         while (i < way.length-1 || segleft>0) {
214                                 if (dashleft<=0) {      // should be ==0
215                                         if (dc.length==0) { dc=dashes.slice(0); }
216                                         dashleft=dc.shift();
217                                         draw=!draw;
218                                 }
219                                 if (segleft<=0) {       // should be ==0
220                     node = way.getNode(i);
221                     nextNode = way.getNode(i+1);
222                                         curx=map.lon2coord(node.lon);
223                     dx=map.lon2coord(nextNode.lon)-curx;
224                                         cury=map.latp2coord(node.latp);
225                     dy=map.latp2coord(nextNode.latp)-cury;
226                                         a=Math.atan2(dy,dx); xc=Math.cos(a); yc=Math.sin(a);
227                                         segleft=Math.sqrt(dx*dx+dy*dy);
228                                         i++;
229                                 }
230
231                                 if (segleft<=dashleft) {
232                                         // the path segment is shorter than the dash
233                                         curx+=dx; cury+=dy;
234                                         moveLine(g,curx,cury,draw);
235                                         dashleft-=segleft; segleft=0;
236                                 } else {
237                                         // the path segment is longer than the dash
238                                         curx+=dashleft*xc; dx-=dashleft*xc;
239                                         cury+=dashleft*yc; dy-=dashleft*yc;
240                                         moveLine(g,curx,cury,draw);
241                                         segleft-=dashleft; dashleft=0;
242                                 }
243                         }
244                 }
245
246                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
247                         if (draw) { g.lineTo(x,y); }
248                                  else { g.moveTo(x,y); }
249                 }
250
251                 
252                 // Find point partway (0-1) along a path
253                 // returns (x,y,angle)
254                 // inspired by senocular's Path.as
255                 
256                 private function pointAt(t:Number):Array {
257                         var totallen:Number = t*pathlength;
258                         var curlen:Number = 0;
259                         var dx:Number, dy:Number, seglen:Number;
260                         for (var i:int = 1; i < way.length; i++){
261                                 dx=map.lon2coord(way.getNode(i).lon)-map.lon2coord(way.getNode(i-1).lon);
262                                 dy=map.latp2coord(way.getNode(i).latp)-map.latp2coord(way.getNode(i-1).latp);
263                                 seglen=Math.sqrt(dx*dx+dy*dy);
264                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
265                                 return new Array(map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
266                                                                  map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
267                                                                  Math.atan2(dy,dx));
268                         }
269                         return new Array(0, 0, 0);
270                 }
271
272                 // Draw name along path
273                 // based on code by Tom Carden
274                 // ** needs styling
275                 
276                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
277
278                         // make a dummy textfield so we can measure its width
279                         var tf:TextField = new TextField();
280                         tf.defaultTextFormat = nameformat;
281                         tf.text = a;
282                         tf.width = tf.textWidth+4;
283                         tf.height = tf.textHeight+4;
284                         if (pathlength<tf.width) { return; }    // no room for text?
285
286                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
287                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
288
289                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
290                         var offsetSign:Number;  // -1 if we're starting at t2
291                         var tStart:Number;      // t1 or t2
292
293                         // make sure text doesn't run right->left or upside down
294                         if (p1[0] < p2[0] && 
295                                 p1[2] < Math.PI/2 &&
296                                 p1[2] > -Math.PI/2) {
297                                 angleOffset = 0; offsetSign = 1; tStart = t1;
298                         } else {
299                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
300                         } 
301
302                         // make a textfield for each char, centered on the line,
303                         // using getCharBoundaries to rotate it around its center point
304                         var chars:Array = a.split('');
305                         for (var i:int = 0; i < chars.length; i++) {
306                                 var rect:Rectangle = tf.getCharBoundaries(i);
307                                 if (rect) {
308                                         s.addChild(rotatedLetter(chars[i],
309                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
310                                                                                          rect.width, tf.height, angleOffset, textOffset));
311                                 }
312                         }
313                 }
314
315                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
316                         var tf:TextField = new TextField();
317             tf.mouseEnabled = false;
318             tf.mouseWheelEnabled = false;
319                         tf.defaultTextFormat = nameformat;
320                         tf.embedFonts = true;
321                         tf.text = char;
322                         tf.width = tf.textWidth+4;
323                         tf.height = tf.textHeight+4;
324
325                         var p:Array=pointAt(t);
326                         var matrix:Matrix = new Matrix();
327                         matrix.translate(-w/2, -h/2-o);
328                         // ** add (say) -4 to the height to move it up by 4px
329                         matrix.rotate(p[2]+a);
330                         matrix.translate(p[0], p[1]);
331                         tf.transform.matrix = matrix;
332                         return tf;
333                 }
334                 
335                 // Add object (stroke/fill/roadname) to layer sprite
336                 
337                 private function addToLayer(s:DisplayObject,t:uint,sublayer:int=-1):void {
338                         var l:DisplayObject=Map(map).getChildAt(layer);
339                         var o:DisplayObject=Sprite(l).getChildAt(t);
340                         if (sublayer!=-1) { o=Sprite(o).getChildAt(sublayer); }
341                         Sprite(o).addChild(s);
342                         sprites.push(s);
343             if ( s is Sprite ) Sprite(s).mouseEnabled = false;
344                 }
345
346         private function mouseEvent(event:MouseEvent):void {
347             map.wayMouseEvent(event, way);
348         }
349
350         public function setHighlight(highlight:Boolean):void {
351             hitzone.visible = highlight;
352         }
353         }
354 }