The branch now loads maps again. Lots of messy code; most of the VectorLayer stuff...
[potlatch2.git] / net / systemeD / halcyon / Map.as
1 package net.systemeD.halcyon {
2
3         import flash.display.Loader;
4         import flash.display.Sprite;
5         import flash.events.*;
6         import flash.external.ExternalInterface;
7         import flash.geom.Rectangle;
8         import flash.net.*;
9         import flash.text.Font;
10         import flash.text.TextField;
11         import flash.ui.Keyboard;
12         
13         import net.systemeD.halcyon.connection.*;
14         import net.systemeD.halcyon.styleparser.*;
15
16 //      for experimental export function:
17 //      import flash.net.FileReference;
18 //      import com.adobe.images.JPGEncoder;
19
20     /** The representation of part of the map on the screen, including information about coordinates, background imagery, paint properties etc. */
21     public class Map extends Sprite {
22
23                 /** master map scale - how many Flash pixels in 1 degree longitude (for Landsat, 5120) */
24                 public const MASTERSCALE:Number=5825.4222222222; 
25                                                                                                 
26                 /** don't zoom out past this */
27                 public const MINSCALE:uint=13; 
28                 /** don't zoom in past this */
29                 public const MAXSCALE:uint=23; 
30
31                 // Container for MapPaint objects
32                 public var paintContainer:Sprite;
33
34                 /** map scale */
35                 public var scale:uint=14;                                                
36                 /** current scaling factor for lon/latp */
37                 public var scalefactor:Number=MASTERSCALE;
38
39                 public var edge_l:Number;                                               // current bounding box
40                 public var edge_r:Number;                                               //  |
41                 public var edge_t:Number;                                               //  |
42                 public var edge_b:Number;                                               //  |
43                 public var centre_lat:Number;                                   // centre lat/lon
44                 public var centre_lon:Number;                                   //  |
45
46                 /** urllon-xradius/masterscale; */ 
47                 public var baselon:Number;
48                 /** lat2lat2p(urllat)+yradius/masterscale; */
49                 public var basey:Number; 
50                 /** width (Flash pixels) */
51                 public var mapwidth:uint; 
52                 /** height (Flash pixels) */
53                 public var mapheight:uint; 
54
55                 /** Is the map being panned */
56                 public var dragstate:uint=NOT_DRAGGING;                 // dragging map (panning)
57                 /** Can the map be panned */
58                 private var _draggable:Boolean=true;                    //  |
59                 private var lastxmouse:Number;                                  //  |
60                 private var lastymouse:Number;                                  //  |
61                 private var downX:Number;                                               //  |
62                 private var downY:Number;                                               //  |
63                 private var downTime:Number;                                    //  |
64                 public const NOT_DRAGGING:uint=0;                               //  |
65                 public const NOT_MOVED:uint=1;                                  //  |
66                 public const DRAGGING:uint=2;                                   //  |
67                 /** How far the map can be dragged without actually triggering a pan. */
68                 public const TOLERANCE:uint=7;                                  //  |
69                 
70                 /** object containing HTML page parameters: lat, lon, zoom, background_dim, background_sharpen, tileblocks */
71                 public var initparams:Object; 
72
73                 /** reference to backdrop sprite */
74                 public var backdrop:Object; 
75                 /** background tile object */
76                 public var tileset:TileSet; 
77                 /** background tile URL, name and scheme */
78                 public var tileparams:Object={ url:'' }; 
79                 /** show all objects, even if unstyled? */
80                 public var showall:Boolean=true; 
81                 
82                 // ------------------------------------------------------------------------------------------
83                 /** Map constructor function */
84         public function Map() {
85                         // Remove any existing sprites
86                         while (numChildren) { removeChildAt(0); }
87
88                         // 900913 background
89                         tileset=new TileSet(this);
90                         addChild(tileset);
91
92                         // Container for all MapPaint objects
93                         paintContainer = new Sprite();
94                         addChild(paintContainer);
95
96                         addEventListener(Event.ENTER_FRAME, everyFrame);
97                         scrollRect=new Rectangle(0,0,800,600);
98
99                         if (ExternalInterface.available) {
100                                 ExternalInterface.addCallback("setPosition", function (lat:Number,lon:Number,zoom:uint):void {
101                                         updateCoordsFromLatLon(lat, lon);
102                                         changeScale(zoom);
103                                 });
104                         }
105                 }
106
107                 // ------------------------------------------------------------------------------------------
108                 /** Initialise map at a given lat/lon */
109         public function init(startlat:Number, startlon:Number, startscale:uint=0):void {
110                         if (startscale>0) {
111                                 scale=startscale;
112                                 this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
113                         }
114                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
115                         baselon    =startlon          -(mapwidth /2)/scalefactor;
116                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
117                         updateCoords(0,0);
118             this.dispatchEvent(new Event(MapEvent.INITIALISED));
119                         download();
120         }
121
122                 // ------------------------------------------------------------------------------------------
123                 /** Recalculate co-ordinates from new Flash origin */
124
125                 public function updateCoords(tx:Number,ty:Number):void {
126                         setScrollRectXY(tx,ty);
127
128                         edge_t=coord2lat(-ty          );
129                         edge_b=coord2lat(-ty+mapheight);
130                         edge_l=coord2lon(-tx          );
131                         edge_r=coord2lon(-tx+mapwidth );
132                         setCentre();
133
134                         tileset.update();
135                 }
136                 
137                 /** Move the map to centre on a given latitude/longitude. */
138                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
139                         var cy:Number=-(lat2coord(lat)-mapheight/2);
140                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
141                         updateCoords(cx,cy);
142                 }
143                 
144                 private function setScrollRectXY(tx:Number,ty:Number):void {
145                         var w:Number=scrollRect.width;
146                         var h:Number=scrollRect.height;
147                         scrollRect=new Rectangle(-tx,-ty,w,h);
148                 }
149                 private function setScrollRectSize(width:Number,height:Number):void {
150                         var sx:Number=scrollRect.x ? scrollRect.x : 0;
151                         var sy:Number=scrollRect.y ? scrollRect.y : 0;
152                         scrollRect=new Rectangle(sx,sy,width,height);
153                 }
154                 
155                 private function getX():Number { return -scrollRect.x; }
156                 private function getY():Number { return -scrollRect.y; }
157                 
158                 private function setCentre():void {
159                         centre_lat=coord2lat(-getY()+mapheight/2);
160                         centre_lon=coord2lon(-getX()+mapwidth/2);
161                         this.dispatchEvent(new MapEvent(MapEvent.MOVE, {lat:centre_lat, lon:centre_lon, scale:scale, minlon:edge_l, maxlon:edge_r, minlat:edge_b, maxlat:edge_t}));
162                 }
163                 
164                 /** Sets the offset between the background imagery and the map. */
165                 public function nudgeBackground(x:Number,y:Number):void {
166                         this.dispatchEvent(new MapEvent(MapEvent.NUDGE_BACKGROUND, { x: x, y: y }));
167                 }
168
169                 private function moveMap(dx:Number,dy:Number):void {
170                         updateCoords(getX()+dx,getY()+dy);
171                         updateAllEntityUIs(false, false);
172                         download();
173                 }
174                 
175                 /** Recentre map at given lat/lon, updating the UI and downloading entities. */
176                 public function moveMapFromLatLon(lat:Number,lon:Number):void {
177                         updateCoordsFromLatLon(lat,lon);
178                         updateAllEntityUIs(false,false);
179                         download();
180                 }
181                 
182                 /** Recentre map at given lat/lon, if that point is currently outside the visible area. */
183                 public function scrollIfNeeded(lat:Number,lon:Number): void{
184             if (lat> edge_t || lat < edge_b || lon < edge_l || lon > edge_r) {
185                 moveMapFromLatLon(lat, lon);
186             }
187                 }
188
189                 // Co-ordinate conversion functions
190
191                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
192                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
193                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
194                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
195
196                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
197                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
198
199                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
200                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
201
202
203                 // ------------------------------------------------------------------------------------------
204                 /** Resize map size based on current stage and height */
205
206                 public function updateSize(w:uint, h:uint):void {
207                         mapwidth = w; centre_lon=coord2lon(-getX()+w/2);
208                         mapheight= h; centre_lat=coord2lat(-getY()+h/2);
209                         setScrollRectSize(w,h);
210
211                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
212                         
213             if ( backdrop != null ) {
214                 backdrop.width=mapwidth;
215                 backdrop.height=mapheight;
216             }
217             if ( mask != null ) {
218                 mask.width=mapwidth;
219                 mask.height=mapheight;
220             }
221                 }
222
223         /** Download map data. Data is downloaded for the connection and the vector layers, where supported.
224         * The bounding box for the download is taken from the current map edges.
225         */
226                 public function download():void {
227 trace("download "+edge_l+","+edge_r+","+edge_t+","+edge_b)
228                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
229                         for (var i:uint=0; i<paintContainer.numChildren; i++)
230                                 getLayerAt(i).connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
231                 }
232
233         // Handle mouse events on ways/nodes
234         private var mapController:MapController = null;
235
236         /** Assign map controller. */
237         public function setController(controller:MapController):void {
238             this.mapController = controller;
239         }
240
241         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
242             if ( mapController != null )
243                 mapController.entityMouseEvent(event, entity);
244         }
245
246                 // ------------------------------------------------------------------------------------------
247                 // Add layers
248                 
249                 public function addLayer(connection:Connection, styleurl:String, backgroundlayer:Boolean=true):void {
250                         var paint:MapPaint=new MapPaint(this, connection, styleurl, -5, 5);
251                         paintContainer.addChild(paint);
252                         paint.isBackground=backgroundlayer;
253                 }
254
255                 public function removeLayerByName(name:String):void {
256                         for (var i:uint=0; i<paintContainer.numChildren; i++) {
257                                 if (getLayerAt(i).connection.name==name)
258                                         paintContainer.removeChildAt(i);
259                                         // >>>> REFACTOR: needs to do the equivalent of VectorLayer.blank()
260                         }
261                 }
262                 
263                 public function findLayer(name:String):MapPaint {
264                         for (var i:uint=0; i<paintContainer.numChildren; i++)
265                                 if (getLayerAt(i).connection.name==name) return getLayerAt(i);
266                         return null;
267                 }
268
269                 private function getLayerAt(i:uint):MapPaint {
270                         return MapPaint(paintContainer.getChildAt(i));
271                 }
272                 
273                 /* Find which layer is editable */
274                 public function get editableLayer():MapPaint {
275                         var editableLayer:MapPaint;
276                         for (var i:uint=0; i<paintContainer.numChildren; i++) {
277                                 if (!getLayerAt(i).isBackground) {
278                                         if (editableLayer) trace("Multiple editable layers found");
279                                         editableLayer=getLayerAt(i);
280                                 }
281                         }
282                         return editableLayer;
283                 }
284
285                 // ------------------------------------------------------------------------------------------
286                 // Redraw all items, zoom in and out
287                 
288                 private function updateAllEntityUIs(redraw:Boolean,remove:Boolean):void {
289                         for (var i:uint=0; i<paintContainer.numChildren; i++)
290                                 getLayerAt(i).updateEntityUIs(redraw, remove);
291                 }
292                 public function redraw():void {
293                         for (var i:uint=0; i<paintContainer.numChildren; i++)
294                                 getLayerAt(i).redraw();
295                 }
296                 public function redrawPOIs():void { 
297                         for (var i:uint=0; i<paintContainer.numChildren; i++)
298                                 getLayerAt(i).redrawPOIs();
299                 }
300                 
301                 public function zoomIn():void {
302                         if (scale!=MAXSCALE) changeScale(scale+1);
303                 }
304
305                 public function zoomOut():void {
306                         if (scale!=MINSCALE) changeScale(scale-1);
307                 }
308
309                 private function changeScale(newscale:uint):void {
310                         scale=newscale;
311                         this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
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                         updateAllEntityUIs(true,true);
316                         download();
317                 }
318
319                 /** Select a new background imagery. */
320                 public function setBackground(bg:Object):void {
321                         tileparams=bg;
322                         if (tileset) { tileset.init(bg, bg.url!=''); }
323                 }
324
325                 /** Set background dimming on/off. */
326                 public function setDimming(dim:Boolean):void {
327                         if (tileset) { tileset.setDimming(dim); }
328                 }
329                 
330                 /** Return background dimming. */
331                 public function getDimming():Boolean {
332                         if (tileset) { return tileset.getDimming(); }
333                         return true;
334                 }
335
336                 /** Set background sharpening on/off. */
337                 public function setSharpen(sharpen:Boolean):void {
338                         if (tileset) { tileset.setSharpen(sharpen); }
339                 }
340                 /** Return background sharpening. */
341                 public function getSharpen():Boolean {
342                         if (tileset) { return tileset.getSharpen(); }
343                         return false;
344                 }
345
346                 // ------------------------------------------------------------------------------------------
347                 // Export (experimental)
348                 // ** just a bit of fun for now!
349                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
350                 // to that area (will probably require creating a new DisplayObject with a different origin
351                 // and mask)
352 /*              
353                 public function export():void {
354                         trace("size is "+this.width+","+this.height);
355                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
356                         jpgSource.draw(this);
357                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
358                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
359                         var fileRef:FileReference = new FileReference();
360 //                      fileRef.save(jpgStream,'map.jpeg');
361                 }
362
363 */
364
365                 // ==========================================================================================
366                 // Events
367                 
368                 // ------------------------------------------------------------------------------------------
369                 // Mouse events
370                 
371                 /** Should map be allowed to pan? */
372                 public function set draggable(draggable:Boolean):void {
373                         _draggable=draggable;
374                         dragstate=NOT_DRAGGING;
375                 }
376
377                 /** Prepare for being dragged by recording start time and location of mouse. */
378                 public function mouseDownHandler(event:MouseEvent):void {
379                         if (!_draggable) { return; }
380                         dragstate=NOT_MOVED;
381                         lastxmouse=stage.mouseX; downX=stage.mouseX;
382                         lastymouse=stage.mouseY; downY=stage.mouseY;
383                         downTime=new Date().getTime();
384                 }
385         
386                 /** Respond to mouse up by possibly moving map. */
387                 public function mouseUpHandler(event:MouseEvent=null):void {
388                         if (dragstate==DRAGGING) { moveMap(x,y); }
389                         dragstate=NOT_DRAGGING;
390                 }
391         
392                 /** Respond to mouse movement, dragging the map if tolerance threshold met. */
393                 public function mouseMoveHandler(event:MouseEvent):void {
394                         if (!_draggable) { return; }
395                         if (dragstate==NOT_DRAGGING) { 
396                            this.dispatchEvent(new MapEvent(MapEvent.MOUSE_MOVE, { x: coord2lon(mouseX), y: coord2lat(mouseY) }));
397                return; 
398             }
399                         
400                         if (dragstate==NOT_MOVED) {
401                                 if (new Date().getTime()-downTime<300) {
402                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE   && Math.abs(downY-stage.mouseY)<=TOLERANCE  ) return;
403                                 } else {
404                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE/2 && Math.abs(downY-stage.mouseY)<=TOLERANCE/2) return;
405                                 }
406                                 dragstate=DRAGGING;
407                         }
408                         
409                         setScrollRectXY(getX()+stage.mouseX-lastxmouse,getY()+stage.mouseY-lastymouse);
410                         lastxmouse=stage.mouseX; lastymouse=stage.mouseY;
411                         setCentre();
412                 }
413         
414                 // ------------------------------------------------------------------------------------------
415                 // Do every frame
416
417                 private function everyFrame(event:Event):void {
418                         if (tileset) { tileset.serviceQueue(); }
419                 }
420
421                 // ------------------------------------------------------------------------------------------
422                 // Miscellaneous events
423                 
424                 /** Respond to cursor movements and zoom in/out.*/
425                 public function keyUpHandler(event:KeyboardEvent):void {
426                         if (event.target is TextField) return;                          // not meant for us
427                         switch (event.keyCode) {
428                                 case Keyboard.PAGE_UP:  zoomIn(); break;                 // Page Up - zoom in
429                                 case Keyboard.PAGE_DOWN:        zoomOut(); break;            // Page Down - zoom out
430                                 case Keyboard.LEFT:     moveMap(mapwidth/2,0); break;        // left cursor
431                                 case Keyboard.UP:       moveMap(0,mapheight/2); break;           // up cursor
432                                 case Keyboard.RIGHT:    moveMap(-mapwidth/2,0); break;   // right cursor
433                                 case Keyboard.DOWN:     moveMap(0,-mapheight/2); break;      // down cursor
434                         }
435                 }
436
437                 // ------------------------------------------------------------------------------------------
438                 // Debugging
439                 
440                 public function clearDebug():void {
441                         if (!Globals.vars.hasOwnProperty('debug')) return;
442                         Globals.vars.debug.text='';
443                 }
444                         
445                 public function addDebug(text:String):void {
446                         trace(text);
447                         if (!Globals.vars.hasOwnProperty('debug')) return;
448                         if (!Globals.vars.debug.visible) return;
449                         Globals.vars.debug.appendText(text+"\n");
450                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
451                 }
452
453         }
454 }