alt-click (for now) to bring ways in from vector background layers
[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
16     import net.systemeD.halcyon.connection.*;
17     import net.systemeD.halcyon.connection.EntityEvent;
18         import net.systemeD.halcyon.styleparser.*;
19         import net.systemeD.halcyon.vectorlayers.*;
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=19;                                  // 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 waycount:uint=0;                                             // ways:                number currently loaded
44                 public var waysrequested:uint=0;                                //                              total number requested
45                 public var waysreceived:uint=0;                                 //                              total number received
46                 public var relcount:uint=0;                                             // relations:   number currently loaded
47                 public var relsrequested:uint=0;                                //                              total number requested
48                 public var relsreceived:uint=0;                                 //                              total number received
49                 public var poicount:uint=0;                                             // POIs:                number currently loaded
50                 public var whichrequested:uint=0;                               // whichways:   total number requested
51                 public var whichreceived:uint=0;                                //                              total number received
52
53                 public var edge_l:Number;                                               // current bounding box
54                 public var edge_r:Number;                                               //  |
55                 public var edge_t:Number;                                               //  |
56                 public var edge_b:Number;                                               //  |
57                 public var centre_lat:Number;                                   // centre lat/lon
58                 public var centre_lon:Number;                                   //  |
59
60                 public var baselon:Number;                                              // urllon-xradius/masterscale;
61                 public var basey:Number;                                                // lat2lat2p(urllat)+yradius/masterscale;
62                 public var mapwidth:uint;                                               // width (Flash pixels)
63                 public var mapheight:uint;                                              // height (Flash pixels)
64
65                 public var dragstate:uint=NOT_DRAGGING;                 // dragging map
66                 private var lastxmouse:Number;                                  //  |
67                 private var lastymouse:Number;                                  //  |
68                 private var downX:Number;                                               //  |
69                 private var downY:Number;                                               //  |
70                 public const NOT_DRAGGING:uint=0;                               //  |
71                 public const NOT_MOVED:uint=1;                                  //  |
72                 public const DRAGGING:uint=2;                                   //  |
73                 
74                 public var initparams:Object;                                   // object containing HTML page parameters
75
76                 public var backdrop:Object;                                             // reference to backdrop sprite
77                 public var tileset:TileSet;                                             // 900913 tile background
78                 public var showall:Boolean=true;                                // show all objects, even if unstyled?
79                 
80                 public var connection:Connection;                               // server connection
81                 public var vectorlayers:Array=[];                               // VectorLayer objects 
82
83                 public const TILESPRITE:uint=0;
84                 public const VECTORSPRITE:uint=1;
85                 public const WAYSPRITE:uint=2;
86                 public const NAMESPRITE:uint=13;
87                 
88                 // ------------------------------------------------------------------------------------------
89                 // Map constructor function
90
91         public function Map(initparams:Object) {
92
93                         this.initparams=initparams;
94                         connection = Connection.getConnection(initparams);
95             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
96             connection.addEventListener(Connection.NEW_POI, newPOICreated);
97             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumbered);
98             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumbered);
99                         gotEnvironment(null);
100
101                         addEventListener(Event.ENTER_FRAME, everyFrame);
102         }
103
104                 public function gotEnvironment(r:Object):void {
105                         var loader:Loader = new Loader();
106                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotFont);
107                         loader.load(new URLRequest("FontLibrary.swf"));
108                 }
109                 
110                 public function gotFont(r:Event):void {
111                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
112                         Font.registerFont(FontLibrary.DejaVu);
113
114                         if (initparams['lat'] != null) {
115                                 // parameters sent from HTML
116                                 init(initparams['lat'],
117                                          initparams['lon'],
118                                          initparams['zoom'],
119                                          initparams['style'],
120                                          initparams['tileurl']);
121
122                         } else {
123                                 // somewhere innocuous
124                                 init(53.09465,-2.56495,17,"test.css?d="+Math.random(),"");
125                         }
126                 }
127
128                 // ------------------------------------------------------------------------------------------
129                 // Initialise map at a given lat/lon
130
131         public function init(startlat:Number,startlon:Number,startscale:uint=0,style:String=null,tileurl:String=''):void {
132                         while (numChildren) { removeChildAt(0); }
133
134                         tileset=new TileSet(this);                                      // 0 - 900913 background
135                         addChild(tileset);                                                      //   |
136                         tileset.init(tileurl);
137
138                         vectorbg = new Sprite();                                        // 1 - vector background layers
139                         addChild(vectorbg);                                                     //   |
140
141                         paint = new MapPaint(this,-5,5);                        // 2 - core paint object
142                         addChild(paint);                                                        //   |
143                         paint.isBackground=false;                                       //   |
144
145                         if (style) {
146                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
147                                 paint.ruleset.loadFromCSS(style);
148                         }
149                         if (startscale>0) { scale=startscale; }
150
151                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
152                         baselon    =startlon          -(mapwidth /2)/scalefactor;
153                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
154                         addDebug("Baselon "+baselon+", basey "+basey);
155                         updateCoords(0,0);
156                         download();
157                         
158         }
159
160                 // ------------------------------------------------------------------------------------------
161                 // Recalculate co-ordinates from new Flash origin
162
163                 public function updateCoords(tx:Number,ty:Number):void {
164                         x=tx; y=ty;
165
166                         edge_t=coord2lat(-y          );
167                         edge_b=coord2lat(-y+mapheight);
168                         edge_l=coord2lon(-x          );
169                         edge_r=coord2lon(-x+mapwidth );
170                         setCentre();
171
172                         tileset.update();
173                 }
174                 
175                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
176                         var cy:Number=-(lat2coord(lat)-mapheight/2);
177                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
178                         updateCoords(cx,cy);
179                 }
180                 
181                 private function setCentre():void {
182                         centre_lat=coord2lat(-y+mapheight/2);
183                         centre_lon=coord2lon(-x+mapwidth/2);
184                         this.dispatchEvent(new MapEvent(MapEvent.MOVE, {lat:centre_lat, lon:centre_lon, scale:scale}));
185                 }
186
187                 // Co-ordinate conversion functions
188
189                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
190                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
191                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
192                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
193
194                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
195                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
196
197                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
198                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
199
200 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
201 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
202
203
204                 // ------------------------------------------------------------------------------------------
205                 // Resize map size based on current stage and height
206
207                 public function updateSize(w:uint, h:uint):void {
208                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
209                         
210                         mapwidth = w;
211                         mapheight= h;
212             if ( backdrop != null ) {
213                 backdrop.width=mapwidth;
214                 backdrop.height=mapheight;
215             }
216             if ( mask != null ) {
217                 mask.width=mapwidth;
218                 mask.height=mapheight;
219             }
220                 }
221
222                 // ------------------------------------------------------------------------------------------
223                 // Download map data
224                 // (typically from whichways, but will want to add more connections)
225
226                 public function download():void {
227                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
228                         
229                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
230                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
231                         bigedge_l=edge_l; bigedge_r=edge_r;
232                         bigedge_b=edge_b; bigedge_t=edge_t;
233                         addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
234                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
235                 }
236
237
238
239         private function newWayCreated(event:EntityEvent):void {
240             var way:Way = event.entity as Way;
241                         if (!way.loaded) { return; }
242                         paint.createWayUI(way);
243         }
244
245         private function newPOICreated(event:EntityEvent):void {
246             var node:Node = event.entity as Node;
247                         var nodeui:NodeUI=paint.createNodeUI(node);
248                         nodeui.redraw();
249         }
250
251                 private function wayRenumbered(event:EntityRenumberedEvent):void {
252             var way:Way = event.entity as Way;
253                         paint.renumberWayUI(way,event.oldID);
254                 }
255
256                 private function nodeRenumbered(event:EntityRenumberedEvent):void {
257             var node:Node = event.entity as Node;
258                         paint.renumberNodeUI(node,event.oldID);
259                 }
260
261         public function setHighlight(entity:Entity, settings:Object):void {
262                         var stateType:String;
263                         var ui:EntityUI=null;
264                         if      ( entity is Way  ) { ui = paint.wayuis[entity.id]; }
265                         else if ( entity is Node ) { ui = paint.nodeuis[entity.id]; }
266                         if (ui==null) { return; }
267                         for (stateType in settings) {
268                                 ui.setHighlight(stateType, settings[stateType]);
269                         }
270                         ui.redraw();
271         }
272
273         // Handle mouse events on ways/nodes
274         private var mapController:MapController = null;
275
276         public function setController(controller:MapController):void {
277             this.mapController = controller;
278         }
279
280         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
281             if ( mapController != null )
282                 mapController.entityMouseEvent(event, entity);
283                                 
284         }
285
286                 // ------------------------------------------------------------------------------------------
287                 // Redraw all items, zoom in and out
288                 
289                 public function redraw():void {
290                         paint.redraw();
291                         for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
292                 }
293                 public function redrawPOIs():void { 
294                         paint.redrawPOIs();
295                         for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
296                 }
297                 
298                 public function zoomIn():void {
299                         if (scale==MAXSCALE) { return; }
300                         changeScale(scale+1);
301                 }
302
303                 public function zoomOut():void {
304                         if (scale==MINSCALE) { return; }
305                         changeScale(scale-1);
306                 }
307
308                 private function changeScale(newscale:uint):void {
309                         addDebug("new scale "+newscale);
310                         scale=newscale;
311                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
312                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
313                         tileset.changeScale(scale);
314                         download();
315                         redraw();
316                 }
317
318                 private function reportPosition():void {
319                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
320                 }
321                 
322                 public function setStyle(style:String):void {
323                         if (style) {
324                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
325                                 paint.ruleset.loadFromCSS(style);
326                         }
327         }
328
329                 // ------------------------------------------------------------------------------------------
330                 // Export (experimental)
331                 // ** just a bit of fun for now!
332                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
333                 // to that area (will probably require creating a new DisplayObject with a different origin
334                 // and mask)
335 /*              
336                 public function export():void {
337                         addDebug("size is "+this.width+","+this.height);
338                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
339                         jpgSource.draw(this);
340                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
341                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
342                         var fileRef:FileReference = new FileReference();
343 //                      fileRef.save(jpgStream,'map.jpeg');
344                 }
345
346 */
347
348                 // ==========================================================================================
349                 // Events
350                 
351                 // ------------------------------------------------------------------------------------------
352                 // Mouse events
353                 
354                 public function mouseDownHandler(event:MouseEvent):void {
355                         dragstate=NOT_MOVED;
356                         lastxmouse=downX=mouseX;
357                         lastymouse=downY=mouseY;
358                 }
359         
360                 public function mouseUpHandler(event:MouseEvent):void {
361                         if (dragstate==DRAGGING) {
362                                 updateCoords(x,y);
363                                 download();
364                         }
365                         dragstate=NOT_DRAGGING;
366                 }
367         
368                 public function mouseMoveHandler(event:MouseEvent):void {
369                         if (dragstate==NOT_DRAGGING) {
370                                 return;
371                         }
372                         
373                         if (dragstate==NOT_MOVED && Math.abs(downX - mouseX) < 3 && Math.abs(downY - mouseY) < 3) {
374                                 return;
375                         }
376                         
377                         dragstate=DRAGGING;
378                         x+=mouseX-lastxmouse;
379                         y+=mouseY-lastymouse;
380                         lastxmouse=mouseX; lastymouse=mouseY;
381                         setCentre();
382                 }
383         
384                 // ------------------------------------------------------------------------------------------
385                 // Do every frame
386
387                 private function everyFrame(event:Event):void {
388                         if (tileset) { tileset.serviceQueue(); }
389                 }
390
391                 // ------------------------------------------------------------------------------------------
392                 // Miscellaneous events
393                 
394                 public function keyUpHandler(event:KeyboardEvent):void {
395                         if ( !event.ctrlKey ) return;
396                         addDebug("pressed "+event.keyCode);
397                         if (event.keyCode==82) { redraw(); }                    // R - redraw
398                         if (event.keyCode==73) { zoomIn(); }                    // I - zoom in
399                         if (event.keyCode==79) { zoomOut(); }                   // O - zoom out
400                         if (event.keyCode==76) { reportPosition(); }    // L - report lat/long
401                 }
402
403                 public function connectionError(err:Object=null): void {
404                         addDebug("got error"); 
405                 }
406
407                 // ------------------------------------------------------------------------------------------
408                 // Debugging
409                 
410                 public function addDebug(text:String):void {
411                         if (!Globals.vars.hasOwnProperty('debug')) return;
412                         if (!Globals.vars.debug.visible) return;
413                         Globals.vars.debug.appendText(text+"\n");
414                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
415                 }
416
417         }
418 }