Remember dimming/sharpening preferences
[potlatch2.git] / net / systemeD / halcyon / Map.as
old mode 100755 (executable)
new mode 100644 (file)
index 43ce446..59f93e6
@@ -12,10 +12,12 @@ 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.Globals;
 
 //     for experimental export function:
 //     import flash.net.FileReference;
@@ -26,14 +28,10 @@ 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 ruleset:RuleSet;                                             // rules
-               
-               public var ways:Object=new Object();                    // geodata
-               public var nodes:Object=new Object();                   //  |
-               public var pois:Object=new Object();                    //  |
-               public var relations:Object=new Object();               //  |
+               public var paint:MapPaint;                                              // sprite for ways and (POI/tagged) nodes in core layer
+               public var vectorbg:Sprite;                                             // sprite for vector background layers
 
                public var scale:uint=14;                                               // map scale
                public var scalefactor:Number=MASTERSCALE;              // current scaling factor for lon/latp
@@ -42,79 +40,55 @@ 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;                                               //  |
                public var edge_b:Number;                                               //  |
+               public var centre_lat:Number;                                   // centre lat/lon
+               public var centre_lon:Number;                                   //  |
 
                public var baselon:Number;                                              // urllon-xradius/masterscale;
                public var basey:Number;                                                // lat2lat2p(urllat)+yradius/masterscale;
                public var mapwidth:uint;                                               // width (Flash pixels)
                public var mapheight:uint;                                              // height (Flash pixels)
 
-               private var dragging:Boolean=false;                             // dragging map?
+               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 
+               public var initparams:Object;                                   // object containing HTML page parameters
 
                public var backdrop:Object;                                             // reference to backdrop sprite
+               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:Object={};                              // VectorLayer objects 
+               
                // ------------------------------------------------------------------------------------------
                // Map constructor function
 
         public function Map(initparams:Object) {
 
-                       // Set up layering
-                       // [layer][2]                   - names
-                       // [layer][1][sublayer] - stroke
-                       // [layer][0]                   - fill
-
-                       for (var l:int=0; l<13; l++) {                          // 11 layers (10 is +5, 0 is -5)
-                               var s:Sprite = getHitSprite();          //  |
-                               s.addChild(getPaintSprite());                   //      | 0 fill
-                               var t:Sprite = getPaintSprite();                //  | 1 stroke
-                               for (var j:int=0; j<11; j++) {                  //      |  | ten sublayers
-                                       t.addChild(getPaintSprite());           //  |  |  |
-                               }                                                                               //  |  |  |
-                               s.addChild(t);                                                  //  |  |
-                               s.addChild(getPaintSprite());                   //      | 2 names
-                               s.addChild(getHitSprite());                         //  | 3 entity hit tests
-                               addChild(s);                                                    //  |
-                       }
-                       addChild(getPaintSprite());                             // 11 - POIs
-                       addChild(getPaintSprite());                             // 12 - shields and POI names
-
                        this.initparams=initparams;
                        connection = Connection.getConnection(initparams);
             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
             connection.addEventListener(Connection.NEW_POI, newPOICreated);
+            connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumbered);
+            connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumbered);
                        gotEnvironment(null);
-        }
-
-        private function getPaintSprite():Sprite {
-            var s:Sprite = new Sprite();
-            s.mouseEnabled = false;
-            s.mouseChildren = false;
-            return s;
-        }
 
-        private function getHitSprite():Sprite {
-            var s:Sprite = new Sprite();
-            return s;
+                       addEventListener(Event.ENTER_FRAME, everyFrame);
         }
 
                public function gotEnvironment(r:Object):void {
@@ -131,31 +105,59 @@ package net.systemeD.halcyon {
                                // parameters sent from HTML
                                init(initparams['lat'],
                                         initparams['lon'],
-                                        initparams['zoom'],
-                                        initparams['style']);
+                                        initparams['zoom']);
 
                        } else {
                                // somewhere innocuous
-                               init(53.09465,-2.56495,17,"test.yaml?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,style:String):void {
-                       ruleset=new RuleSet(this,redrawPOIs);
-                       ruleset.loadFromCSS("test.css?"+Math.random());         // ** test for MapCSS
-                       //updateSize();
+        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(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);                                                     //   |
 
-                       scale=startscale;
-                       scalefactor=MASTERSCALE/Math.pow(2,14-scale);
+                       paint = new MapPaint(this,-5,5);                        // 2 - core paint object
+                       addChild(paint);                                                        //   |
+                       paint.isBackground=false;                                       //   |
+
+                       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(styleurl);
+                       }
+                       if (startscale>0) {
+                               scale=startscale;
+                               this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
+                       }
+
+                       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);
+              });
+            }
         }
 
                // ------------------------------------------------------------------------------------------
@@ -164,13 +166,13 @@ package net.systemeD.halcyon {
                public function updateCoords(tx:Number,ty:Number):void {
                        x=tx; y=ty;
 
-                       // ** calculate tile_l etc.
                        edge_t=coord2lat(-y          );
                        edge_b=coord2lat(-y+mapheight);
                        edge_l=coord2lon(-x          );
                        edge_r=coord2lon(-x+mapwidth );
-                       addDebug("Lon "+edge_l+"-"+edge_r);
-                       addDebug("Lat "+edge_b+"-"+edge_t);
+                       setCentre();
+
+                       tileset.update();
                }
                
                public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
@@ -178,7 +180,22 @@ package net.systemeD.halcyon {
                        var cx:Number=-(lon2coord(lon)-mapwidth/2);
                        updateCoords(cx,cy);
                }
+               
+               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, 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
 
@@ -201,8 +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;
-                       mapheight= h;
+                       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}));
+                       
             if ( backdrop != null ) {
                 backdrop.width=mapwidth;
                 backdrop.height=mapheight;
@@ -213,41 +233,79 @@ 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,edge_l,edge_r,edge_t,edge_b));
+                       this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
                        
                        if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
                                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;
-                       addDebug("Calling with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
+                       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;
-            ways[way.id] = new WayUI(way, this);
+                       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;
-            pois[node.id] = new POI(node, this);
+                       if (!node.within(edge_l,edge_r,edge_t,edge_b)) { return; }
+                       paint.createNodeUI(node);
         }
 
-        public function setHighlight(entity:Entity, stateType:String, isOn:Boolean):void {
-            if ( entity is Way ) {
-                var wayUI:WayUI = ways[entity.id];
-                if ( wayUI != null )
-                    wayUI.setHighlight(stateType, isOn);
-            }
+               private function wayRenumbered(event:EntityRenumberedEvent):void {
+            var way:Way = event.entity as Way;
+                       paint.renumberWayUI(way,event.oldID);
+               }
+
+               private function nodeRenumbered(event:EntityRenumberedEvent):void {
+            var node:Node = event.entity as Node;
+                       paint.renumberNodeUI(node,event.oldID);
+               }
+
+        public function setHighlight(entity:Entity, settings:Object):void {
+                       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;
 
@@ -261,18 +319,32 @@ 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 {
-                       for each (var w:WayUI in ways) { w.recalculate(); w.redraw(); }
-                       for each (var p:POI in pois) { p.redraw(); }
+                       paint.redraw();
+                       for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
                }
-
-               public function redrawPOIs():void {
-                       for each (var p:POI in pois) { p.redraw(); }
+               public function redrawPOIs():void { 
+                       paint.redrawPOIs();
+                       for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
                }
-
+               
                public function zoomIn():void {
                        if (scale==MAXSCALE) { return; }
                        changeScale(scale+1);
@@ -286,15 +358,46 @@ package net.systemeD.halcyon {
                private function changeScale(newscale:uint):void {
                        addDebug("new scale "+newscale);
                        scale=newscale;
-                       scalefactor=MASTERSCALE/Math.pow(2,14-scale);
+                       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(url:String):void {
+                       styleurl=url;
+                       if (paint) { 
+                               paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
+                               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)
@@ -321,36 +424,64 @@ package net.systemeD.halcyon {
                // ------------------------------------------------------------------------------------------
                // Mouse events
                
+               public function set draggable(draggable:Boolean):void {
+                       _draggable=draggable;
+                       dragstate=NOT_DRAGGING;
+               }
+
                public function mouseDownHandler(event:MouseEvent):void {
-                       dragging=true;
-                       lastxmouse=mouseX; lastymouse=mouseY;
+                       if (!_draggable) { return; }
+                       dragstate=NOT_MOVED;
+                       lastxmouse=mouseX; downX=stage.mouseX;
+                       lastymouse=mouseY; downY=stage.mouseY;
+                       downTime=new Date().getTime();
                }
         
-               public function mouseUpHandler(event:MouseEvent):void {
-                       if (!dragging) { return; }
-                       dragging=false;
-                       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 (!dragging) { return; }
+                       if (!_draggable) { return; }
+                       if (dragstate==NOT_DRAGGING) { 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;
+                       }
+                       
                        x+=mouseX-lastxmouse;
                        y+=mouseY-lastymouse;
                        lastxmouse=mouseX; lastymouse=mouseY;
+                       setCentre();
                }
         
+               // ------------------------------------------------------------------------------------------
+               // Do every frame
+
+               private function everyFrame(event:Event):void {
+                       if (tileset) { tileset.serviceQueue(); }
+               }
+
                // ------------------------------------------------------------------------------------------
                // Miscellaneous events
                
                public function keyUpHandler(event:KeyboardEvent):void {
-// addDebug("pressed "+event.keyCode);
-            if ( !event.ctrlKey ) return;
-                       if (event.keyCode==82) { this.redraw(); }                       // R - redraw
-                       if (event.keyCode==73) { this.zoomIn(); }                       // I - zoom in
-                       if (event.keyCode==79) { this.zoomOut(); }                      // O - zoom out
-                       if (event.keyCode==76) { this.reportPosition(); }       // L - report lat/long
-//                     if (event.keyCode==69) { this.export(); }                       // E - export
+                       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 {
@@ -360,12 +491,18 @@ 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");
                        Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
                }
-               
+
        }
 }