refactor EntityUI, better stylesheet selection, etc.
[potlatch2.git] / net / systemeD / halcyon / Map.as
1 package net.systemeD.halcyon {
2
3         import flash.text.TextField;
4         import flash.display.DisplayObjectContainer;
5         import flash.display.Loader;
6         import flash.display.Sprite;
7         import flash.display.Shape;
8         import flash.display.Stage;
9         import flash.display.BitmapData;
10         import flash.display.LoaderInfo;
11         import flash.text.Font;
12         import flash.utils.ByteArray;
13         import flash.events.*;
14         import flash.net.*;
15
16     import net.systemeD.halcyon.connection.*;
17     import net.systemeD.halcyon.connection.EntityEvent;
18         import net.systemeD.halcyon.styleparser.*;
19         import net.systemeD.halcyon.vectorlayers.*;
20         import net.systemeD.halcyon.Globals;
21
22 //      for experimental export function:
23 //      import flash.net.FileReference;
24 //      import com.adobe.images.JPGEncoder;
25
26     public class Map extends Sprite {
27
28                 public const MASTERSCALE:Number=5825.4222222222;// master map scale - how many Flash pixels in 1 degree longitude
29                                                                                                                 // (for Landsat, 5120)
30                 public const MINSCALE:uint=13;                                  // don't zoom out past this
31                 public const MAXSCALE:uint=19;                                  // don't zoom in past this
32
33                 public var paint:MapPaint;                                              // sprite for ways and (POI/tagged) nodes in core layer
34                 public var vectorbg:Sprite;                                             // sprite for vector background layers
35
36                 public var scale:uint=14;                                               // map scale
37                 public var scalefactor:Number=MASTERSCALE;              // current scaling factor for lon/latp
38                 public var bigedge_l:Number= 999999;                    // area of largest whichways
39                 public var bigedge_r:Number=-999999;                    //  |
40                 public var bigedge_b:Number= 999999;                    //  |
41                 public var bigedge_t:Number=-999999;                    //  |
42
43                 public var edge_l:Number;                                               // current bounding box
44                 public var edge_r:Number;                                               //  |
45                 public var edge_t:Number;                                               //  |
46                 public var edge_b:Number;                                               //  |
47                 public var centre_lat:Number;                                   // centre lat/lon
48                 public var centre_lon:Number;                                   //  |
49
50                 public var baselon:Number;                                              // urllon-xradius/masterscale;
51                 public var basey:Number;                                                // lat2lat2p(urllat)+yradius/masterscale;
52                 public var mapwidth:uint;                                               // width (Flash pixels)
53                 public var mapheight:uint;                                              // height (Flash pixels)
54
55                 public var dragstate:uint=NOT_DRAGGING;                 // dragging map
56                 private var _draggable:Boolean=true;                    //  |
57                 private var lastxmouse:Number;                                  //  |
58                 private var lastymouse:Number;                                  //  |
59                 private var downX:Number;                                               //  |
60                 private var downY:Number;                                               //  |
61                 public const NOT_DRAGGING:uint=0;                               //  |
62                 public const NOT_MOVED:uint=1;                                  //  |
63                 public const DRAGGING:uint=2;                                   //  |
64                 
65                 public var initparams:Object;                                   // object containing HTML page parameters
66
67                 public var backdrop:Object;                                             // reference to backdrop sprite
68                 public var tileset:TileSet;                                             // 900913 tile background
69                 private var tileurl:String='';                                  // internal tile URL
70                 private var styleurl:String='';                                 // internal style URL
71                 public var showall:Boolean=true;                                // show all objects, even if unstyled?
72                 
73                 public var connection:Connection;                               // server connection
74                 public var vectorlayers:Array=[];                               // VectorLayer objects 
75
76                 public const TILESPRITE:uint=0;
77                 public const VECTORSPRITE:uint=1;
78                 public const WAYSPRITE:uint=2;
79                 public const NAMESPRITE:uint=13;
80                 
81                 // ------------------------------------------------------------------------------------------
82                 // Map constructor function
83
84         public function Map(initparams:Object) {
85
86                         this.initparams=initparams;
87                         connection = Connection.getConnection(initparams);
88             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
89             connection.addEventListener(Connection.NEW_POI, newPOICreated);
90             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumbered);
91             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumbered);
92                         gotEnvironment(null);
93
94                         addEventListener(Event.ENTER_FRAME, everyFrame);
95         }
96
97                 public function gotEnvironment(r:Object):void {
98                         var loader:Loader = new Loader();
99                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotFont);
100                         loader.load(new URLRequest("FontLibrary.swf"));
101                 }
102                 
103                 public function gotFont(r:Event):void {
104                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
105                         Font.registerFont(FontLibrary.DejaVu);
106
107                         if (initparams['lat'] != null) {
108                                 // parameters sent from HTML
109                                 init(initparams['lat'],
110                                          initparams['lon'],
111                                          initparams['zoom']);
112
113                         } else {
114                                 // somewhere innocuous
115                                 init(53.09465,-2.56495,17);
116                         }
117                 }
118
119                 // ------------------------------------------------------------------------------------------
120                 // Initialise map at a given lat/lon
121
122         public function init(startlat:Number,startlon:Number,startscale:uint=0):void {
123                         while (numChildren) { removeChildAt(0); }
124
125                         tileset=new TileSet(this);                                      // 0 - 900913 background
126                         addChild(tileset);                                                      //   |
127                         tileset.init(tileurl);                                          //   |
128
129                         vectorbg = new Sprite();                                        // 1 - vector background layers
130                         addChild(vectorbg);                                                     //   |
131
132                         paint = new MapPaint(this,-5,5);                        // 2 - core paint object
133                         addChild(paint);                                                        //   |
134                         paint.isBackground=false;                                       //   |
135
136                         if (styleurl) {                                                         // if we've only just set up paint, then setStyle won't have created the RuleSet
137                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
138                                 paint.ruleset.loadFromCSS(styleurl);
139                         }
140                         if (startscale>0) { scale=startscale; }
141
142                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
143                         baselon    =startlon          -(mapwidth /2)/scalefactor;
144                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
145                         addDebug("Baselon "+baselon+", basey "+basey);
146                         updateCoords(0,0);
147                         download();
148                         
149         }
150
151                 // ------------------------------------------------------------------------------------------
152                 // Recalculate co-ordinates from new Flash origin
153
154                 public function updateCoords(tx:Number,ty:Number):void {
155                         x=tx; y=ty;
156
157                         edge_t=coord2lat(-y          );
158                         edge_b=coord2lat(-y+mapheight);
159                         edge_l=coord2lon(-x          );
160                         edge_r=coord2lon(-x+mapwidth );
161                         setCentre();
162
163                         tileset.update();
164                 }
165                 
166                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
167                         var cy:Number=-(lat2coord(lat)-mapheight/2);
168                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
169                         updateCoords(cx,cy);
170                 }
171                 
172                 private function setCentre():void {
173                         centre_lat=coord2lat(-y+mapheight/2);
174                         centre_lon=coord2lon(-x+mapwidth/2);
175                         this.dispatchEvent(new MapEvent(MapEvent.MOVE, {lat:centre_lat, lon:centre_lon, scale:scale}));
176                 }
177                 
178                 public function nudgeBackground(x:Number,y:Number):void {
179                         this.dispatchEvent(new MapEvent(MapEvent.NUDGE_BACKGROUND, { x: x, y: y }));
180                 }
181
182                 // Co-ordinate conversion functions
183
184                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
185                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
186                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
187                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
188
189                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
190                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
191
192                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
193                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
194
195 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
196 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
197
198
199                 // ------------------------------------------------------------------------------------------
200                 // Resize map size based on current stage and height
201
202                 public function updateSize(w:uint, h:uint):void {
203                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
204                         
205                         mapwidth = w;
206                         mapheight= h;
207             if ( backdrop != null ) {
208                 backdrop.width=mapwidth;
209                 backdrop.height=mapheight;
210             }
211             if ( mask != null ) {
212                 mask.width=mapwidth;
213                 mask.height=mapheight;
214             }
215                 }
216
217                 // ------------------------------------------------------------------------------------------
218                 // Download map data
219                 // (typically from whichways, but will want to add more connections)
220
221                 public function download():void {
222                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
223                         
224                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
225                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
226                         bigedge_l=edge_l; bigedge_r=edge_r;
227                         bigedge_b=edge_b; bigedge_t=edge_t;
228                         if (connection.waycount>1000) {
229                                 connection.purgeOutside(edge_l,edge_r,edge_t,edge_b);
230                         }
231                         addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
232                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
233                 }
234
235         private function newWayCreated(event:EntityEvent):void {
236             var way:Way = event.entity as Way;
237                         if (!way.loaded || !way.within(edge_l,edge_r,edge_t,edge_b)) { return; }
238                         paint.createWayUI(way);
239         }
240
241         private function newPOICreated(event:EntityEvent):void {
242             var node:Node = event.entity as Node;
243                         if (!node.within(edge_l,edge_r,edge_t,edge_b)) { return; }
244                         paint.createNodeUI(node);
245         }
246
247                 private function wayRenumbered(event:EntityRenumberedEvent):void {
248             var way:Way = event.entity as Way;
249                         paint.renumberWayUI(way,event.oldID);
250                 }
251
252                 private function nodeRenumbered(event:EntityRenumberedEvent):void {
253             var node:Node = event.entity as Node;
254                         paint.renumberNodeUI(node,event.oldID);
255                 }
256
257         public function setHighlight(entity:Entity, settings:Object):void {
258                         var stateType:String;
259                         var ui:EntityUI=null;
260                         if      ( entity is Way  ) { ui = paint.wayuis[entity.id]; }
261                         else if ( entity is Node ) { ui = paint.nodeuis[entity.id]; }
262                         if (ui==null) { return; }
263                         for (stateType in settings) {
264                                 ui.setHighlight(stateType, settings[stateType]);
265                         }
266                         ui.redraw();
267         }
268
269         // Handle mouse events on ways/nodes
270         private var mapController:MapController = null;
271
272         public function setController(controller:MapController):void {
273             this.mapController = controller;
274         }
275
276         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
277             if ( mapController != null )
278                 mapController.entityMouseEvent(event, entity);
279                                 
280         }
281
282                 // ------------------------------------------------------------------------------------------
283                 // Redraw all items, zoom in and out
284                 
285                 public function updateEntityUIs(redraw:Boolean,remove:Boolean):void {
286                         paint.updateEntityUIs(connection.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
287                         for each (var v:VectorLayer in vectorlayers) {
288                                 v.paint.updateEntityUIs(v.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
289                         }
290                 }
291                 public function redraw():void {
292                         paint.redraw();
293                         for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
294                 }
295                 public function redrawPOIs():void { 
296                         paint.redrawPOIs();
297                         for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
298                 }
299                 
300                 public function zoomIn():void {
301                         if (scale==MAXSCALE) { return; }
302                         changeScale(scale+1);
303                 }
304
305                 public function zoomOut():void {
306                         if (scale==MINSCALE) { return; }
307                         changeScale(scale-1);
308                 }
309
310                 private function changeScale(newscale:uint):void {
311                         addDebug("new scale "+newscale);
312                         scale=newscale;
313                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
314                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
315                         tileset.changeScale(scale);
316                         updateEntityUIs(true,true);
317                         download();
318                 }
319
320                 private function reportPosition():void {
321                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
322                 }
323                 
324                 public function setStyle(url:String):void {
325                         styleurl=url;
326                         if (paint) { 
327                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
328                                 paint.ruleset.loadFromCSS(url);
329                         }
330         }
331
332                 public function setBackground(url:String):void {
333                         tileurl=url;
334                         if (tileset) { tileset.init(url, url!=''); }
335                 }
336
337                 public function setDimming(dim:Boolean):void {
338                         if (tileset) { tileset.setDimming(dim); }
339                 }
340
341                 // ------------------------------------------------------------------------------------------
342                 // Export (experimental)
343                 // ** just a bit of fun for now!
344                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
345                 // to that area (will probably require creating a new DisplayObject with a different origin
346                 // and mask)
347 /*              
348                 public function export():void {
349                         addDebug("size is "+this.width+","+this.height);
350                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
351                         jpgSource.draw(this);
352                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
353                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
354                         var fileRef:FileReference = new FileReference();
355 //                      fileRef.save(jpgStream,'map.jpeg');
356                 }
357
358 */
359
360                 // ==========================================================================================
361                 // Events
362                 
363                 // ------------------------------------------------------------------------------------------
364                 // Mouse events
365                 
366                 public function set draggable(draggable:Boolean):void {
367                         _draggable=draggable;
368                         dragstate=NOT_DRAGGING;
369                 }
370
371                 public function mouseDownHandler(event:MouseEvent):void {
372                         if (!_draggable) { return; }
373                         dragstate=NOT_MOVED;
374                         lastxmouse=downX=mouseX;
375                         lastymouse=downY=mouseY;
376                 }
377         
378                 public function mouseUpHandler(event:MouseEvent):void {
379                         if (dragstate==DRAGGING) {
380                                 updateCoords(x,y);
381                                 updateEntityUIs(false, false);
382                                 download();
383                         }
384                         dragstate=NOT_DRAGGING;
385                 }
386         
387                 public function mouseMoveHandler(event:MouseEvent):void {
388                         if (!_draggable) { return; }
389                         if (dragstate==NOT_DRAGGING) { return; }
390                         
391                         if (dragstate==NOT_MOVED && Math.abs(downX - mouseX) < 3 && Math.abs(downY - mouseY) < 3) {
392                                 return;
393                         }
394                         
395                         dragstate=DRAGGING;
396                         x+=mouseX-lastxmouse;
397                         y+=mouseY-lastymouse;
398                         lastxmouse=mouseX; lastymouse=mouseY;
399                         setCentre();
400                 }
401         
402                 // ------------------------------------------------------------------------------------------
403                 // Do every frame
404
405                 private function everyFrame(event:Event):void {
406                         if (tileset) { tileset.serviceQueue(); }
407                 }
408
409                 // ------------------------------------------------------------------------------------------
410                 // Miscellaneous events
411                 
412                 public function keyUpHandler(event:KeyboardEvent):void {
413                         if ( !event.ctrlKey ) return;
414                         addDebug("pressed "+event.keyCode);
415                         if (event.keyCode==73) { zoomIn(); }                    // I - zoom in
416                         if (event.keyCode==79) { zoomOut(); }                   // O - zoom out
417                         if (event.keyCode==76) { reportPosition(); }    // L - report lat/long
418                 }
419
420                 public function connectionError(err:Object=null): void {
421                         addDebug("got error"); 
422                 }
423
424                 // ------------------------------------------------------------------------------------------
425                 // Debugging
426                 
427                 public function clearDebug():void {
428                         if (!Globals.vars.hasOwnProperty('debug')) return;
429                         Globals.vars.debug.text='';
430                 }
431                         
432                 public function addDebug(text:String):void {
433                         if (!Globals.vars.hasOwnProperty('debug')) return;
434                         if (!Globals.vars.debug.visible) return;
435                         Globals.vars.debug.appendText(text+"\n");
436                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
437                 }
438
439         }
440 }