Register a setPosition function that can be used from javascript to
[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     import flash.external.ExternalInterface;
16
17     import net.systemeD.halcyon.connection.*;
18     import net.systemeD.halcyon.connection.EntityEvent;
19         import net.systemeD.halcyon.styleparser.*;
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=23;                                  // 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                 private var downTime:Number;                                    //  |
62                 public const NOT_DRAGGING:uint=0;                               //  |
63                 public const NOT_MOVED:uint=1;                                  //  |
64                 public const DRAGGING:uint=2;                                   //  |
65                 public const TOLERANCE:uint=7;                                  //  |
66                 
67                 public var initparams:Object;                                   // object containing HTML page parameters
68
69                 public var backdrop:Object;                                             // reference to backdrop sprite
70                 public var tileset:TileSet;                                             // background tile object
71                 private var tileparams:Object={ url:'' };               // background tile URL, name and scheme
72                 private var styleurl:String='';                                 // internal style URL
73                 public var showall:Boolean=true;                                // show all objects, even if unstyled?
74                 
75                 public var connection:Connection;                               // server connection
76                 public var vectorlayers:Object={};                              // VectorLayer objects 
77                 
78                 // ------------------------------------------------------------------------------------------
79                 // Map constructor function
80
81         public function Map(initparams:Object) {
82
83                         this.initparams=initparams;
84                         connection = Connection.getConnection(initparams);
85             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
86             connection.addEventListener(Connection.NEW_POI, newPOICreated);
87             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumbered);
88             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumbered);
89                         gotEnvironment(null);
90
91                         addEventListener(Event.ENTER_FRAME, everyFrame);
92         }
93
94                 public function gotEnvironment(r:Object):void {
95                         var loader:Loader = new Loader();
96                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotFont);
97                         loader.load(new URLRequest("FontLibrary.swf"));
98                 }
99                 
100                 public function gotFont(r:Event):void {
101                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
102                         Font.registerFont(FontLibrary.DejaVu);
103
104                         if (initparams['lat'] != null) {
105                                 // parameters sent from HTML
106                                 init(initparams['lat'],
107                                          initparams['lon'],
108                                          initparams['zoom']);
109
110                         } else {
111                                 // somewhere innocuous
112                                 init(53.09465,-2.56495,17);
113                         }
114                 }
115
116                 // ------------------------------------------------------------------------------------------
117                 // Initialise map at a given lat/lon
118
119         public function init(startlat:Number,startlon:Number,startscale:uint=0):void {
120                         while (numChildren) { removeChildAt(0); }
121
122                         tileset=new TileSet(this);                                      // 0 - 900913 background
123                         addChild(tileset);                                                      //   |
124                         tileset.init(tileparams);                                       //   |
125
126                         vectorbg = new Sprite();                                        // 1 - vector background layers
127                         addChild(vectorbg);                                                     //   |
128
129                         paint = new MapPaint(this,-5,5);                        // 2 - core paint object
130                         addChild(paint);                                                        //   |
131                         paint.isBackground=false;                                       //   |
132
133                         if (styleurl) {                                                         // if we've only just set up paint, then setStyle won't have created the RuleSet
134                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
135                                 paint.ruleset.loadFromCSS(styleurl);
136                         }
137                         if (startscale>0) {
138                                 scale=startscale;
139                                 this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
140                         }
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             this.dispatchEvent(new Event(MapEvent.INITIALISED));
148                         download();
149
150             ExternalInterface.addCallback("setPosition", function (lat:Number,lon:Number,zoom:uint):void {
151                 updateCoordsFromLatLon(lat, lon);
152                 changeScale(zoom);
153             });
154         }
155
156                 // ------------------------------------------------------------------------------------------
157                 // Recalculate co-ordinates from new Flash origin
158
159                 public function updateCoords(tx:Number,ty:Number):void {
160                         x=tx; y=ty;
161
162                         edge_t=coord2lat(-y          );
163                         edge_b=coord2lat(-y+mapheight);
164                         edge_l=coord2lon(-x          );
165                         edge_r=coord2lon(-x+mapwidth );
166                         setCentre();
167
168                         tileset.update();
169                 }
170                 
171                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
172                         var cy:Number=-(lat2coord(lat)-mapheight/2);
173                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
174                         updateCoords(cx,cy);
175                 }
176                 
177                 private function setCentre():void {
178                         centre_lat=coord2lat(-y+mapheight/2);
179                         centre_lon=coord2lon(-x+mapwidth/2);
180                         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}));
181                 }
182                 
183                 public function nudgeBackground(x:Number,y:Number):void {
184                         this.dispatchEvent(new MapEvent(MapEvent.NUDGE_BACKGROUND, { x: x, y: y }));
185                 }
186
187                 private function moveMap(dx:Number,dy:Number):void {
188                         updateCoords(x+dx,y+dy);
189                         updateEntityUIs(false, false);
190                         download();
191                 }
192
193                 // Co-ordinate conversion functions
194
195                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
196                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
197                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
198                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
199
200                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
201                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
202
203                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
204                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
205
206 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
207 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
208
209
210                 // ------------------------------------------------------------------------------------------
211                 // Resize map size based on current stage and height
212
213                 public function updateSize(w:uint, h:uint):void {
214                         mapwidth = w; centre_lon=coord2lon(-x+w/2);
215                         mapheight= h; centre_lat=coord2lat(-y+h/2);
216
217                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
218                         
219             if ( backdrop != null ) {
220                 backdrop.width=mapwidth;
221                 backdrop.height=mapheight;
222             }
223             if ( mask != null ) {
224                 mask.width=mapwidth;
225                 mask.height=mapheight;
226             }
227                 }
228
229         /** Download map data. Data is downloaded for the connection and the vector layers, where supported.
230         * The bounding box for the download is taken from the current map edges.
231         */
232                 public function download():void {
233                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
234                         
235                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
236                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
237                         bigedge_l=edge_l; bigedge_r=edge_r;
238                         bigedge_b=edge_b; bigedge_t=edge_t;
239                         if (connection.waycount>1000) {
240                                 connection.purgeOutside(edge_l,edge_r,edge_t,edge_b);
241                         }
242                         addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
243                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
244
245             // Do the same for vector layers
246             for each (var layer:VectorLayer in vectorlayers) {
247               layer.loadBbox(edge_l,edge_r,edge_t,edge_b);
248             }
249                 }
250
251         private function newWayCreated(event:EntityEvent):void {
252             var way:Way = event.entity as Way;
253                         if (!way.loaded || !way.within(edge_l,edge_r,edge_t,edge_b)) { return; }
254                         paint.createWayUI(way);
255         }
256
257         private function newPOICreated(event:EntityEvent):void {
258             var node:Node = event.entity as Node;
259                         if (!node.within(edge_l,edge_r,edge_t,edge_b)) { return; }
260                         paint.createNodeUI(node);
261         }
262
263                 private function wayRenumbered(event:EntityRenumberedEvent):void {
264             var way:Way = event.entity as Way;
265                         paint.renumberWayUI(way,event.oldID);
266                 }
267
268                 private function nodeRenumbered(event:EntityRenumberedEvent):void {
269             var node:Node = event.entity as Node;
270                         paint.renumberNodeUI(node,event.oldID);
271                 }
272
273         public function setHighlight(entity:Entity, settings:Object):void {
274                         if      ( entity is Way  && paint.wayuis[entity.id] ) { paint.wayuis[entity.id].setHighlight(settings);  }
275                         else if ( entity is Node && paint.nodeuis[entity.id]) { paint.nodeuis[entity.id].setHighlight(settings); }
276         }
277
278         public function setHighlightOnNodes(way:Way, settings:Object):void {
279                         if (paint.wayuis[way.id]) paint.wayuis[way.id].setHighlightOnNodes(settings);
280         }
281
282                 /* Protect Entities and EntityUIs against purging. This prevents the currently selected items
283                    from being purged even though they're off-screen. */
284
285                 public function setPurgable(entities:Array, purgable:Boolean):void {
286                         for each (var entity:Entity in entities) {
287                                 entity.locked=!purgable;
288                                 if ( entity is Way  ) {
289                                         var way:Way=entity as Way;
290                                         if (paint.wayuis[way.id]) { paint.wayuis[way.id].purgable=purgable; }
291                                         for (var i:uint=0; i<way.length; i++) {
292                                                 var node:Node=way.getNode(i)
293                                                 node.locked=!purgable;
294                                                 if (paint.nodeuis[node.id]) { paint.nodeuis[node.id].purgable=purgable; }
295                                         }
296                                 } else if ( entity is Node && paint.nodeuis[entity.id]) { 
297                                         paint.nodeuis[entity.id].purgable=purgable;
298                                 }
299                         }
300                 }
301
302         // Handle mouse events on ways/nodes
303         private var mapController:MapController = null;
304
305         public function setController(controller:MapController):void {
306             this.mapController = controller;
307         }
308
309         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
310             if ( mapController != null )
311                 mapController.entityMouseEvent(event, entity);
312                                 
313         }
314
315                 // ------------------------------------------------------------------------------------------
316                 // Add vector layer
317                 
318                 public function addVectorLayer(layer:VectorLayer):void {
319                         vectorlayers[layer.name]=layer;
320                         vectorbg.addChild(layer.paint);
321                 }
322
323                 // ------------------------------------------------------------------------------------------
324                 // Redraw all items, zoom in and out
325                 
326                 public function updateEntityUIs(redraw:Boolean,remove:Boolean):void {
327                         paint.updateEntityUIs(connection.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
328                         for each (var v:VectorLayer in vectorlayers) {
329                                 v.paint.updateEntityUIs(v.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
330                         }
331                 }
332                 public function redraw():void {
333                         paint.redraw();
334                         for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
335                 }
336                 public function redrawPOIs():void { 
337                         paint.redrawPOIs();
338                         for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
339                 }
340                 
341                 public function zoomIn():void {
342                         if (scale==MAXSCALE) { return; }
343                         changeScale(scale+1);
344                 }
345
346                 public function zoomOut():void {
347                         if (scale==MINSCALE) { return; }
348                         changeScale(scale-1);
349                 }
350
351                 private function changeScale(newscale:uint):void {
352                         addDebug("new scale "+newscale);
353                         scale=newscale;
354                         this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
355                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
356                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
357                         tileset.changeScale(scale);
358                         updateEntityUIs(true,true);
359                         download();
360                 }
361
362                 private function reportPosition():void {
363                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
364                 }
365                 
366                 public function setStyle(url:String):void {
367                         styleurl=url;
368                         if (paint) { 
369                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
370                                 paint.ruleset.loadFromCSS(url);
371                         }
372         }
373
374                 public function setBackground(bg:Object):void {
375                         tileparams=bg;
376                         if (tileset) { tileset.init(bg, bg.url!=''); }
377                 }
378
379                 public function setDimming(dim:Boolean):void {
380                         if (tileset) { tileset.setDimming(dim); }
381                 }
382
383                 public function setSharpen(sharpen:Boolean):void {
384                         if (tileset) { tileset.setSharpen(sharpen); }
385                 }
386
387                 // ------------------------------------------------------------------------------------------
388                 // Export (experimental)
389                 // ** just a bit of fun for now!
390                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
391                 // to that area (will probably require creating a new DisplayObject with a different origin
392                 // and mask)
393 /*              
394                 public function export():void {
395                         addDebug("size is "+this.width+","+this.height);
396                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
397                         jpgSource.draw(this);
398                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
399                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
400                         var fileRef:FileReference = new FileReference();
401 //                      fileRef.save(jpgStream,'map.jpeg');
402                 }
403
404 */
405
406                 // ==========================================================================================
407                 // Events
408                 
409                 // ------------------------------------------------------------------------------------------
410                 // Mouse events
411                 
412                 public function set draggable(draggable:Boolean):void {
413                         _draggable=draggable;
414                         dragstate=NOT_DRAGGING;
415                 }
416
417                 public function mouseDownHandler(event:MouseEvent):void {
418                         if (!_draggable) { return; }
419                         dragstate=NOT_MOVED;
420                         lastxmouse=mouseX; downX=stage.mouseX;
421                         lastymouse=mouseY; downY=stage.mouseY;
422                         downTime=new Date().getTime();
423                 }
424         
425                 public function mouseUpHandler(event:MouseEvent=null):void {
426                         if (dragstate==DRAGGING) { moveMap(0,0); }
427                         dragstate=NOT_DRAGGING;
428                 }
429         
430                 public function mouseMoveHandler(event:MouseEvent):void {
431                         if (!_draggable) { return; }
432                         if (dragstate==NOT_DRAGGING) { return; }
433                         
434                         if (dragstate==NOT_MOVED) {
435                                 if (new Date().getTime()-downTime<300) {
436                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE   && Math.abs(downY-stage.mouseY)<=TOLERANCE  ) return;
437                                 } else {
438                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE/2 && Math.abs(downY-stage.mouseY)<=TOLERANCE/2) return;
439                                 }
440                                 dragstate=DRAGGING;
441                         }
442                         
443                         x+=mouseX-lastxmouse;
444                         y+=mouseY-lastymouse;
445                         lastxmouse=mouseX; lastymouse=mouseY;
446                         setCentre();
447                 }
448         
449                 // ------------------------------------------------------------------------------------------
450                 // Do every frame
451
452                 private function everyFrame(event:Event):void {
453                         if (tileset) { tileset.serviceQueue(); }
454                 }
455
456                 // ------------------------------------------------------------------------------------------
457                 // Miscellaneous events
458                 
459                 public function keyUpHandler(event:KeyboardEvent):void {
460                         if (event.target is TextField) return;                          // not meant for us
461                         switch (event.keyCode) {
462                                 case 33:        zoomIn(); break;                                        // Page Up - zoom in
463                                 case 34:        zoomOut(); break;                                       // Page Down - zoom out
464                                 case 37:        moveMap(mapwidth/2,0); break;           // left cursor
465                                 case 38:        moveMap(0,mapheight/2); break;          // up cursor
466                                 case 39:        moveMap(-mapwidth/2,0); break;          // right cursor
467                                 case 40:        moveMap(0,-mapheight/2); break;         // down cursor
468 //                              case 76:        reportPosition(); break;                        // L - report lat/long
469                         }
470                 }
471
472                 public function connectionError(err:Object=null): void {
473                         addDebug("got error"); 
474                 }
475
476                 // ------------------------------------------------------------------------------------------
477                 // Debugging
478                 
479                 public function clearDebug():void {
480                         if (!Globals.vars.hasOwnProperty('debug')) return;
481                         Globals.vars.debug.text='';
482                 }
483                         
484                 public function addDebug(text:String):void {
485                         trace(text);
486                         if (!Globals.vars.hasOwnProperty('debug')) return;
487                         if (!Globals.vars.debug.visible) return;
488                         Globals.vars.debug.appendText(text+"\n");
489                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
490                 }
491
492         }
493 }