make parallelise even moar awesome
[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                 public var showall:Boolean=true;                                // show all objects, even if unstyled?
70                 
71                 public var connection:Connection;                               // server connection
72                 public var vectorlayers:Array=[];                               // VectorLayer objects 
73
74                 public const TILESPRITE:uint=0;
75                 public const VECTORSPRITE:uint=1;
76                 public const WAYSPRITE:uint=2;
77                 public const NAMESPRITE:uint=13;
78                 
79                 // ------------------------------------------------------------------------------------------
80                 // Map constructor function
81
82         public function Map(initparams:Object) {
83
84                         this.initparams=initparams;
85                         connection = Connection.getConnection(initparams);
86             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
87             connection.addEventListener(Connection.NEW_POI, newPOICreated);
88             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumbered);
89             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumbered);
90                         gotEnvironment(null);
91
92                         addEventListener(Event.ENTER_FRAME, everyFrame);
93         }
94
95                 public function gotEnvironment(r:Object):void {
96                         var loader:Loader = new Loader();
97                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotFont);
98                         loader.load(new URLRequest("FontLibrary.swf"));
99                 }
100                 
101                 public function gotFont(r:Event):void {
102                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
103                         Font.registerFont(FontLibrary.DejaVu);
104
105                         if (initparams['lat'] != null) {
106                                 // parameters sent from HTML
107                                 init(initparams['lat'],
108                                          initparams['lon'],
109                                          initparams['zoom'],
110                                          initparams['style'],
111                                          initparams['tileurl']);
112
113                         } else {
114                                 // somewhere innocuous
115                                 init(53.09465,-2.56495,17,"test.css?d="+Math.random(),"");
116                         }
117                 }
118
119                 // ------------------------------------------------------------------------------------------
120                 // Initialise map at a given lat/lon
121
122         public function init(startlat:Number,startlon:Number,startscale:uint=0,style:String=null,tileurl:String=''):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 (style) {
137                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
138                                 paint.ruleset.loadFromCSS(style);
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                         var nodeui:NodeUI=paint.createNodeUI(node);
245                         nodeui.redraw();
246         }
247
248                 private function wayRenumbered(event:EntityRenumberedEvent):void {
249             var way:Way = event.entity as Way;
250                         paint.renumberWayUI(way,event.oldID);
251                 }
252
253                 private function nodeRenumbered(event:EntityRenumberedEvent):void {
254             var node:Node = event.entity as Node;
255                         paint.renumberNodeUI(node,event.oldID);
256                 }
257
258         public function setHighlight(entity:Entity, settings:Object):void {
259                         var stateType:String;
260                         var ui:EntityUI=null;
261                         if      ( entity is Way  ) { ui = paint.wayuis[entity.id]; }
262                         else if ( entity is Node ) { ui = paint.nodeuis[entity.id]; }
263                         if (ui==null) { return; }
264                         for (stateType in settings) {
265                                 ui.setHighlight(stateType, settings[stateType]);
266                         }
267                         ui.redraw();
268         }
269
270         // Handle mouse events on ways/nodes
271         private var mapController:MapController = null;
272
273         public function setController(controller:MapController):void {
274             this.mapController = controller;
275         }
276
277         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
278             if ( mapController != null )
279                 mapController.entityMouseEvent(event, entity);
280                                 
281         }
282
283                 // ------------------------------------------------------------------------------------------
284                 // Redraw all items, zoom in and out
285                 
286                 public function updateEntityUIs(redraw:Boolean,remove:Boolean):void {
287                         paint.updateEntityUIs(connection.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
288                         for each (var v:VectorLayer in vectorlayers) {
289                                 v.paint.updateEntityUIs(v.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
290                         }
291                 }
292                 public function redraw():void {
293                         paint.redraw();
294                         for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
295                 }
296                 public function redrawPOIs():void { 
297                         paint.redrawPOIs();
298                         for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
299                 }
300                 
301                 public function zoomIn():void {
302                         if (scale==MAXSCALE) { return; }
303                         changeScale(scale+1);
304                 }
305
306                 public function zoomOut():void {
307                         if (scale==MINSCALE) { return; }
308                         changeScale(scale-1);
309                 }
310
311                 private function changeScale(newscale:uint):void {
312                         addDebug("new scale "+newscale);
313                         scale=newscale;
314                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
315                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
316                         tileset.changeScale(scale);
317                         updateEntityUIs(true,true);
318                         download();
319                 }
320
321                 private function reportPosition():void {
322                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
323                 }
324                 
325                 public function setStyle(style:String):void {
326                         if (style) {
327                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
328                                 paint.ruleset.loadFromCSS(style);
329                         }
330         }
331
332                 // ------------------------------------------------------------------------------------------
333                 // Export (experimental)
334                 // ** just a bit of fun for now!
335                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
336                 // to that area (will probably require creating a new DisplayObject with a different origin
337                 // and mask)
338 /*              
339                 public function export():void {
340                         addDebug("size is "+this.width+","+this.height);
341                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
342                         jpgSource.draw(this);
343                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
344                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
345                         var fileRef:FileReference = new FileReference();
346 //                      fileRef.save(jpgStream,'map.jpeg');
347                 }
348
349 */
350
351                 // ==========================================================================================
352                 // Events
353                 
354                 // ------------------------------------------------------------------------------------------
355                 // Mouse events
356                 
357                 public function set draggable(draggable:Boolean):void {
358                         _draggable=draggable;
359                         dragstate=NOT_DRAGGING;
360                 }
361
362                 public function mouseDownHandler(event:MouseEvent):void {
363                         if (!_draggable) { return; }
364                         dragstate=NOT_MOVED;
365                         lastxmouse=downX=mouseX;
366                         lastymouse=downY=mouseY;
367                 }
368         
369                 public function mouseUpHandler(event:MouseEvent):void {
370                         if (dragstate==DRAGGING) {
371                                 updateCoords(x,y);
372                                 updateEntityUIs(false, false);
373                                 download();
374                         }
375                         dragstate=NOT_DRAGGING;
376                 }
377         
378                 public function mouseMoveHandler(event:MouseEvent):void {
379                         if (!_draggable) { return; }
380                         if (dragstate==NOT_DRAGGING) { return; }
381                         
382                         if (dragstate==NOT_MOVED && Math.abs(downX - mouseX) < 3 && Math.abs(downY - mouseY) < 3) {
383                                 return;
384                         }
385                         
386                         dragstate=DRAGGING;
387                         x+=mouseX-lastxmouse;
388                         y+=mouseY-lastymouse;
389                         lastxmouse=mouseX; lastymouse=mouseY;
390                         setCentre();
391                 }
392         
393                 // ------------------------------------------------------------------------------------------
394                 // Do every frame
395
396                 private function everyFrame(event:Event):void {
397                         if (tileset) { tileset.serviceQueue(); }
398                 }
399
400                 // ------------------------------------------------------------------------------------------
401                 // Miscellaneous events
402                 
403                 public function keyUpHandler(event:KeyboardEvent):void {
404                         if ( !event.ctrlKey ) return;
405                         addDebug("pressed "+event.keyCode);
406                         if (event.keyCode==73) { zoomIn(); }                    // I - zoom in
407                         if (event.keyCode==79) { zoomOut(); }                   // O - zoom out
408                         if (event.keyCode==76) { reportPosition(); }    // L - report lat/long
409                 }
410
411                 public function connectionError(err:Object=null): void {
412                         addDebug("got error"); 
413                 }
414
415                 // ------------------------------------------------------------------------------------------
416                 // Debugging
417                 
418                 public function clearDebug():void {
419                         if (!Globals.vars.hasOwnProperty('debug')) return;
420                         Globals.vars.debug.text='';
421                 }
422                         
423                 public function addDebug(text:String):void {
424                         if (!Globals.vars.hasOwnProperty('debug')) return;
425                         if (!Globals.vars.debug.visible) return;
426                         Globals.vars.debug.appendText(text+"\n");
427                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
428                 }
429
430         }
431 }