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