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