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