Remember dimming/sharpening preferences
[potlatch2.git] / net / systemeD / halcyon / Map.as
old mode 100755 (executable)
new mode 100644 (file)
index 95d8e24..59f93e6
@@ -12,11 +12,11 @@ package net.systemeD.halcyon {
        import flash.utils.ByteArray;
        import flash.events.*;
        import flash.net.*;
+    import flash.external.ExternalInterface;
 
     import net.systemeD.halcyon.connection.*;
     import net.systemeD.halcyon.connection.EntityEvent;
        import net.systemeD.halcyon.styleparser.*;
-       import net.systemeD.halcyon.vectorlayers.*;
        import net.systemeD.halcyon.Globals;
 
 //     for experimental export function:
@@ -28,7 +28,7 @@ package net.systemeD.halcyon {
                public const MASTERSCALE:Number=5825.4222222222;// master map scale - how many Flash pixels in 1 degree longitude
                                                                                                                // (for Landsat, 5120)
                public const MINSCALE:uint=13;                                  // don't zoom out past this
-               public const MAXSCALE:uint=19;                                  // don't zoom in past this
+               public const MAXSCALE:uint=23;                                  // don't zoom in past this
 
                public var paint:MapPaint;                                              // sprite for ways and (POI/tagged) nodes in core layer
                public var vectorbg:Sprite;                                             // sprite for vector background layers
@@ -40,16 +40,6 @@ package net.systemeD.halcyon {
                public var bigedge_b:Number= 999999;                    //  |
                public var bigedge_t:Number=-999999;                    //  |
 
-               public var waycount:uint=0;                                             // ways:                number currently loaded
-               public var waysrequested:uint=0;                                //                              total number requested
-               public var waysreceived:uint=0;                                 //                              total number received
-               public var relcount:uint=0;                                             // relations:   number currently loaded
-               public var relsrequested:uint=0;                                //                              total number requested
-               public var relsreceived:uint=0;                                 //                              total number received
-               public var poicount:uint=0;                                             // POIs:                number currently loaded
-               public var whichrequested:uint=0;                               // whichways:   total number requested
-               public var whichreceived:uint=0;                                //                              total number received
-
                public var edge_l:Number;                                               // current bounding box
                public var edge_r:Number;                                               //  |
                public var edge_t:Number;                                               //  |
@@ -63,27 +53,27 @@ package net.systemeD.halcyon {
                public var mapheight:uint;                                              // height (Flash pixels)
 
                public var dragstate:uint=NOT_DRAGGING;                 // dragging map
+               private var _draggable:Boolean=true;                    //  |
                private var lastxmouse:Number;                                  //  |
                private var lastymouse:Number;                                  //  |
                private var downX:Number;                                               //  |
                private var downY:Number;                                               //  |
+               private var downTime:Number;                                    //  |
                public const NOT_DRAGGING:uint=0;                               //  |
                public const NOT_MOVED:uint=1;                                  //  |
                public const DRAGGING:uint=2;                                   //  |
+               public const TOLERANCE:uint=7;                                  //  |
                
                public var initparams:Object;                                   // object containing HTML page parameters
 
                public var backdrop:Object;                                             // reference to backdrop sprite
-               public var tileset:TileSet;                                             // 900913 tile background
+               public var tileset:TileSet;                                             // background tile object
+               private var tileparams:Object={ url:'' };               // background tile URL, name and scheme
+               private var styleurl:String='';                                 // internal style URL
                public var showall:Boolean=true;                                // show all objects, even if unstyled?
                
                public var connection:Connection;                               // server connection
-               public var vectorlayers:Array=[];                               // VectorLayer objects 
-
-               public const TILESPRITE:uint=0;
-               public const VECTORSPRITE:uint=1;
-               public const WAYSPRITE:uint=2;
-               public const NAMESPRITE:uint=13;
+               public var vectorlayers:Object={};                              // VectorLayer objects 
                
                // ------------------------------------------------------------------------------------------
                // Map constructor function
@@ -115,25 +105,28 @@ package net.systemeD.halcyon {
                                // parameters sent from HTML
                                init(initparams['lat'],
                                         initparams['lon'],
-                                        initparams['zoom'],
-                                        initparams['style'],
-                                        initparams['tileurl']);
+                                        initparams['zoom']);
 
                        } else {
                                // somewhere innocuous
-                               init(53.09465,-2.56495,17,"test.css?d="+Math.random(),"");
+                               init(53.09465,-2.56495,17);
                        }
                }
 
                // ------------------------------------------------------------------------------------------
                // Initialise map at a given lat/lon
 
-        public function init(startlat:Number,startlon:Number,startscale:uint=0,style:String=null,tileurl:String=''):void {
+        public function init(startlat:Number, startlon:Number, startscale:uint=0):void {
                        while (numChildren) { removeChildAt(0); }
 
                        tileset=new TileSet(this);                                      // 0 - 900913 background
+                       if (initparams['tileblocks']) {                         //   | option to block dodgy tile sources
+                               tileset.blocks=initparams['tileblocks'];//   |
+                       }                                                                                       //   |
                        addChild(tileset);                                                      //   |
-                       tileset.init(tileurl);
+                       tileset.init(tileparams, false, 
+                                    initparams['background_dim']    ==null ? true  : initparams['background_dim'],
+                                    initparams['background_sharpen']==null ? false : initparams['background_sharpen']);
 
                        vectorbg = new Sprite();                                        // 1 - vector background layers
                        addChild(vectorbg);                                                     //   |
@@ -142,19 +135,29 @@ package net.systemeD.halcyon {
                        addChild(paint);                                                        //   |
                        paint.isBackground=false;                                       //   |
 
-                       if (style) {
+                       if (styleurl) {                                                         // if we've only just set up paint, then setStyle won't have created the RuleSet
                                paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
-                               paint.ruleset.loadFromCSS(style);
+                               paint.ruleset.loadFromCSS(styleurl);
+                       }
+                       if (startscale>0) {
+                               scale=startscale;
+                               this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
                        }
-                       if (startscale>0) { scale=startscale; }
 
                        scalefactor=MASTERSCALE/Math.pow(2,13-scale);
                        baselon    =startlon          -(mapwidth /2)/scalefactor;
                        basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
                        addDebug("Baselon "+baselon+", basey "+basey);
                        updateCoords(0,0);
+            this.dispatchEvent(new Event(MapEvent.INITIALISED));
                        download();
-                       
+
+            if (ExternalInterface.available) {
+              ExternalInterface.addCallback("setPosition", function (lat:Number,lon:Number,zoom:uint):void {
+                  updateCoordsFromLatLon(lat, lon);
+                  changeScale(zoom);
+              });
+            }
         }
 
                // ------------------------------------------------------------------------------------------
@@ -181,7 +184,17 @@ package net.systemeD.halcyon {
                private function setCentre():void {
                        centre_lat=coord2lat(-y+mapheight/2);
                        centre_lon=coord2lon(-x+mapwidth/2);
-                       this.dispatchEvent(new MapEvent(MapEvent.MOVE, {lat:centre_lat, lon:centre_lon, scale:scale}));
+                       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}));
+               }
+               
+               public function nudgeBackground(x:Number,y:Number):void {
+                       this.dispatchEvent(new MapEvent(MapEvent.NUDGE_BACKGROUND, { x: x, y: y }));
+               }
+
+               private function moveMap(dx:Number,dy:Number):void {
+                       updateCoords(x+dx,y+dy);
+                       updateEntityUIs(false, false);
+                       download();
                }
 
                // Co-ordinate conversion functions
@@ -205,10 +218,11 @@ package net.systemeD.halcyon {
                // Resize map size based on current stage and height
 
                public function updateSize(w:uint, h:uint):void {
+                       mapwidth = w; centre_lon=coord2lon(-x+w/2);
+                       mapheight= h; centre_lat=coord2lat(-y+h/2);
+
                        this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
                        
-                       mapwidth = w;
-                       mapheight= h;
             if ( backdrop != null ) {
                 backdrop.width=mapwidth;
                 backdrop.height=mapheight;
@@ -219,10 +233,9 @@ package net.systemeD.halcyon {
             }
                }
 
-               // ------------------------------------------------------------------------------------------
-               // Download map data
-               // (typically from whichways, but will want to add more connections)
-
+        /** Download map data. Data is downloaded for the connection and the vector layers, where supported.
+        * The bounding box for the download is taken from the current map edges.
+        */
                public function download():void {
                        this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
                        
@@ -230,22 +243,28 @@ package net.systemeD.halcyon {
                                edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
                        bigedge_l=edge_l; bigedge_r=edge_r;
                        bigedge_b=edge_b; bigedge_t=edge_t;
+                       if (connection.waycount>1000) {
+                               connection.purgeOutside(edge_l,edge_r,edge_t,edge_b);
+                       }
                        addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
                        connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
-               }
-
 
+            // Do the same for vector layers
+            for each (var layer:VectorLayer in vectorlayers) {
+              layer.loadBbox(edge_l,edge_r,edge_t,edge_b);
+            }
+               }
 
         private function newWayCreated(event:EntityEvent):void {
             var way:Way = event.entity as Way;
-                       if (!way.loaded) { return; }
+                       if (!way.loaded || !way.within(edge_l,edge_r,edge_t,edge_b)) { return; }
                        paint.createWayUI(way);
         }
 
         private function newPOICreated(event:EntityEvent):void {
             var node:Node = event.entity as Node;
-                       var nodeui:NodeUI=paint.createNodeUI(node);
-                       nodeui.redraw();
+                       if (!node.within(edge_l,edge_r,edge_t,edge_b)) { return; }
+                       paint.createNodeUI(node);
         }
 
                private function wayRenumbered(event:EntityRenumberedEvent):void {
@@ -259,17 +278,34 @@ package net.systemeD.halcyon {
                }
 
         public function setHighlight(entity:Entity, settings:Object):void {
-                       var stateType:String;
-                       var ui:EntityUI=null;
-                       if      ( entity is Way  ) { ui = paint.wayuis[entity.id]; }
-                       else if ( entity is Node ) { ui = paint.nodeuis[entity.id]; }
-                       if (ui==null) { return; }
-                       for (stateType in settings) {
-                               ui.setHighlight(stateType, settings[stateType]);
-                       }
-                       ui.redraw();
+                       if      ( entity is Way  && paint.wayuis[entity.id] ) { paint.wayuis[entity.id].setHighlight(settings);  }
+                       else if ( entity is Node && paint.nodeuis[entity.id]) { paint.nodeuis[entity.id].setHighlight(settings); }
+        }
+
+        public function setHighlightOnNodes(way:Way, settings:Object):void {
+                       if (paint.wayuis[way.id]) paint.wayuis[way.id].setHighlightOnNodes(settings);
         }
 
+               /* Protect Entities and EntityUIs against purging. This prevents the currently selected items
+                  from being purged even though they're off-screen. */
+
+               public function setPurgable(entities:Array, purgable:Boolean):void {
+                       for each (var entity:Entity in entities) {
+                               entity.locked=!purgable;
+                               if ( entity is Way  ) {
+                                       var way:Way=entity as Way;
+                                       if (paint.wayuis[way.id]) { paint.wayuis[way.id].purgable=purgable; }
+                                       for (var i:uint=0; i<way.length; i++) {
+                                               var node:Node=way.getNode(i)
+                                               node.locked=!purgable;
+                                               if (paint.nodeuis[node.id]) { paint.nodeuis[node.id].purgable=purgable; }
+                                       }
+                               } else if ( entity is Node && paint.nodeuis[entity.id]) { 
+                                       paint.nodeuis[entity.id].purgable=purgable;
+                               }
+                       }
+               }
+
         // Handle mouse events on ways/nodes
         private var mapController:MapController = null;
 
@@ -283,9 +319,23 @@ package net.systemeD.halcyon {
                                
         }
 
+               // ------------------------------------------------------------------------------------------
+               // Add vector layer
+               
+               public function addVectorLayer(layer:VectorLayer):void {
+                       vectorlayers[layer.name]=layer;
+                       vectorbg.addChild(layer.paint);
+               }
+
                // ------------------------------------------------------------------------------------------
                // Redraw all items, zoom in and out
                
+               public function updateEntityUIs(redraw:Boolean,remove:Boolean):void {
+                       paint.updateEntityUIs(connection.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
+                       for each (var v:VectorLayer in vectorlayers) {
+                               v.paint.updateEntityUIs(v.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
+                       }
+               }
                public function redraw():void {
                        paint.redraw();
                        for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
@@ -308,24 +358,47 @@ package net.systemeD.halcyon {
                private function changeScale(newscale:uint):void {
                        addDebug("new scale "+newscale);
                        scale=newscale;
+                       this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
                        scalefactor=MASTERSCALE/Math.pow(2,13-scale);
                        updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
                        tileset.changeScale(scale);
+                       updateEntityUIs(true,true);
                        download();
-                       redraw();
                }
 
                private function reportPosition():void {
                        addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
                }
                
-               public function setStyle(style:String):void {
-                       if (style) {
+               public function setStyle(url:String):void {
+                       styleurl=url;
+                       if (paint) { 
                                paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
-                               paint.ruleset.loadFromCSS(style);
+                               paint.ruleset.loadFromCSS(url);
                        }
         }
 
+               public function setBackground(bg:Object):void {
+                       tileparams=bg;
+                       if (tileset) { tileset.init(bg, bg.url!=''); }
+               }
+
+               public function setDimming(dim:Boolean):void {
+                       if (tileset) { tileset.setDimming(dim); }
+               }
+               public function getDimming():Boolean {
+                       if (tileset) { return tileset.getDimming(); }
+                       return true;
+               }
+
+               public function setSharpen(sharpen:Boolean):void {
+                       if (tileset) { tileset.setSharpen(sharpen); }
+               }
+               public function getSharpen():Boolean {
+                       if (tileset) { return tileset.getSharpen(); }
+                       return false;
+               }
+
                // ------------------------------------------------------------------------------------------
                // Export (experimental)
                // ** just a bit of fun for now!
@@ -351,30 +424,37 @@ package net.systemeD.halcyon {
                // ------------------------------------------------------------------------------------------
                // Mouse events
                
+               public function set draggable(draggable:Boolean):void {
+                       _draggable=draggable;
+                       dragstate=NOT_DRAGGING;
+               }
+
                public function mouseDownHandler(event:MouseEvent):void {
+                       if (!_draggable) { return; }
                        dragstate=NOT_MOVED;
-                       lastxmouse=downX=mouseX;
-                       lastymouse=downY=mouseY;
+                       lastxmouse=mouseX; downX=stage.mouseX;
+                       lastymouse=mouseY; downY=stage.mouseY;
+                       downTime=new Date().getTime();
                }
         
-               public function mouseUpHandler(event:MouseEvent):void {
-                       if (dragstate==DRAGGING) {
-                               updateCoords(x,y);
-                               download();
-                       }
+               public function mouseUpHandler(event:MouseEvent=null):void {
+                       if (dragstate==DRAGGING) { moveMap(0,0); }
                        dragstate=NOT_DRAGGING;
                }
         
                public function mouseMoveHandler(event:MouseEvent):void {
-                       if (dragstate==NOT_DRAGGING) {
-                               return;
-                       }
+                       if (!_draggable) { return; }
+                       if (dragstate==NOT_DRAGGING) { return; }
                        
-                       if (dragstate==NOT_MOVED && Math.abs(downX - mouseX) < 3 && Math.abs(downY - mouseY) < 3) {
-                               return;
+                       if (dragstate==NOT_MOVED) {
+                               if (new Date().getTime()-downTime<300) {
+                                       if (Math.abs(downX-stage.mouseX)<=TOLERANCE   && Math.abs(downY-stage.mouseY)<=TOLERANCE  ) return;
+                               } else {
+                                       if (Math.abs(downX-stage.mouseX)<=TOLERANCE/2 && Math.abs(downY-stage.mouseY)<=TOLERANCE/2) return;
+                               }
+                               dragstate=DRAGGING;
                        }
                        
-                       dragstate=DRAGGING;
                        x+=mouseX-lastxmouse;
                        y+=mouseY-lastymouse;
                        lastxmouse=mouseX; lastymouse=mouseY;
@@ -392,12 +472,16 @@ package net.systemeD.halcyon {
                // Miscellaneous events
                
                public function keyUpHandler(event:KeyboardEvent):void {
-                       if ( !event.ctrlKey ) return;
-                       addDebug("pressed "+event.keyCode);
-                       if (event.keyCode==82) { redraw(); }                    // R - redraw
-                       if (event.keyCode==73) { zoomIn(); }                    // I - zoom in
-                       if (event.keyCode==79) { zoomOut(); }                   // O - zoom out
-                       if (event.keyCode==76) { reportPosition(); }    // L - report lat/long
+                       if (event.target is TextField) return;                          // not meant for us
+                       switch (event.keyCode) {
+                               case 33:        zoomIn(); break;                                        // Page Up - zoom in
+                               case 34:        zoomOut(); break;                                       // Page Down - zoom out
+                               case 37:        moveMap(mapwidth/2,0); break;           // left cursor
+                               case 38:        moveMap(0,mapheight/2); break;          // up cursor
+                               case 39:        moveMap(-mapwidth/2,0); break;          // right cursor
+                               case 40:        moveMap(0,-mapheight/2); break;         // down cursor
+//                             case 76:        reportPosition(); break;                        // L - report lat/long
+                       }
                }
 
                public function connectionError(err:Object=null): void {
@@ -407,7 +491,13 @@ package net.systemeD.halcyon {
                // ------------------------------------------------------------------------------------------
                // Debugging
                
+               public function clearDebug():void {
+                       if (!Globals.vars.hasOwnProperty('debug')) return;
+                       Globals.vars.debug.text='';
+               }
+                       
                public function addDebug(text:String):void {
+                       trace(text);
                        if (!Globals.vars.hasOwnProperty('debug')) return;
                        if (!Globals.vars.debug.visible) return;
                        Globals.vars.debug.appendText(text+"\n");