900913 tile support, not complete or working yet
[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
20 //      for experimental export function:
21 //      import flash.net.FileReference;
22 //      import com.adobe.images.JPGEncoder;
23
24     public class Map extends Sprite {
25
26                 public const MASTERSCALE:Number=5825.4222222222;// master map scale - how many Flash pixels in 1 degree longitude
27                                                                                                                 // (for Landsat, 5120)
28                 public const MINSCALE:uint=13;                                  // don't zoom out past this
29                 public const MAXSCALE:uint=19;                                  // don't zoom in past this
30
31                 public var ruleset:RuleSet;                                             // rules
32                 
33                 public var ways:Object=new Object();                    // geodata
34                 public var nodes:Object=new Object();                   //  |
35                 public var pois:Object=new Object();                    //  |
36                 public var relations:Object=new Object();               //  |
37
38                 public var scale:uint=14;                                               // map scale
39                 public var scalefactor:Number=MASTERSCALE;              // current scaling factor for lon/latp
40                 public var bigedge_l:Number= 999999;                    // area of largest whichways
41                 public var bigedge_r:Number=-999999;                    //  |
42                 public var bigedge_b:Number= 999999;                    //  |
43                 public var bigedge_t:Number=-999999;                    //  |
44
45                 public var waycount:uint=0;                                             // ways:                number currently loaded
46                 public var waysrequested:uint=0;                                //                              total number requested
47                 public var waysreceived:uint=0;                                 //                              total number received
48                 public var relcount:uint=0;                                             // relations:   number currently loaded
49                 public var relsrequested:uint=0;                                //                              total number requested
50                 public var relsreceived:uint=0;                                 //                              total number received
51                 public var poicount:uint=0;                                             // POIs:                number currently loaded
52                 public var whichrequested:uint=0;                               // whichways:   total number requested
53                 public var whichreceived:uint=0;                                //                              total number received
54
55                 public var edge_l:Number;                                               // current bounding box
56                 public var edge_r:Number;                                               //  |
57                 public var edge_t:Number;                                               //  |
58                 public var edge_b: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                 private var dragging:Boolean=false;                             // dragging map?
66                 private var lastxmouse:Number;                                  //  |
67                 private var lastymouse:Number;                                  //  |
68                 
69                 public var initparams:Object;                                   // object containing 
70
71                 public var backdrop:Object;                                             // reference to backdrop sprite
72                 public var tileset:TileSet;                                             // 900913 tile background
73                 public var showall:Boolean=true;                                // show all objects, even if unstyled?
74                 
75                 public var connection:Connection;                               // server connection
76
77                 // ------------------------------------------------------------------------------------------
78                 // Map constructor function
79
80         public function Map(initparams:Object) {
81
82                         // Add 900913 tile background
83                         tileset=new TileSet(this);
84                         addChild(tileset);
85
86                         // Set up layering
87                         // [layer][3]                   - names
88                         // [layer][2][sublayer] - stroke
89                         // [layer][1]                   - casing
90                         // [layer][0]                   - fill
91
92                         for (var l:int=0; l<13; l++) {                          // 11 layers (10 is +5, 0 is -5)
93                                 var s:Sprite = getHitSprite();          //  |
94                                 s.addChild(getPaintSprite());                   //      | 0 fill
95                                 s.addChild(getPaintSprite());                   //      | 1 casing
96                                 var t:Sprite = getPaintSprite();                //  | 2 stroke
97                                 for (var j:int=0; j<11; j++) {                  //      |  | ten sublayers
98                                         t.addChild(getPaintSprite());           //  |  |  |
99                                 }                                                                               //  |  |  |
100                                 s.addChild(t);                                                  //  |  |
101                                 s.addChild(getPaintSprite());                   //      | 3 names
102                                 s.addChild(getHitSprite());                         //  | 4 entity hit tests
103                                 addChild(s);                                                    //  |
104                         }
105                         addChild(getPaintSprite());                             // 11 - POIs
106                         addChild(getPaintSprite());                             // 12 - shields and POI names
107
108                         this.initparams=initparams;
109                         connection = Connection.getConnection(initparams);
110             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
111             connection.addEventListener(Connection.NEW_POI, newPOICreated);
112                         gotEnvironment(null);
113         }
114
115         private function getPaintSprite():Sprite {
116             var s:Sprite = new Sprite();
117             s.mouseEnabled = false;
118             s.mouseChildren = false;
119             return s;
120         }
121
122         private function getHitSprite():Sprite {
123             var s:Sprite = new Sprite();
124             return s;
125         }
126
127                 public function gotEnvironment(r:Object):void {
128                         var loader:Loader = new Loader();
129                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotFont);
130                         loader.load(new URLRequest("FontLibrary.swf"));
131                 }
132                 
133                 public function gotFont(r:Event):void {
134                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
135                         Font.registerFont(FontLibrary.DejaVu);
136
137                         if (initparams['lat'] != null) {
138                                 // parameters sent from HTML
139                                 init(initparams['lat'],
140                                          initparams['lon'],
141                                          initparams['zoom'],
142                                          initparams['style']);
143
144                         } else {
145                                 // somewhere innocuous
146                                 init(53.09465,-2.56495,17,"test.css?d="+Math.random());
147                         }
148                 }
149
150                 // ------------------------------------------------------------------------------------------
151                 // Initialise map at a given lat/lon
152
153         public function init(startlat:Number,startlon:Number,startscale:uint,style:String):void {
154                         ruleset=new RuleSet(this,redrawPOIs);
155                         ruleset.loadFromCSS(style);
156                         //updateSize();
157
158                         scale=startscale;
159                         scalefactor=MASTERSCALE/Math.pow(2,14-scale);
160                         baselon    =startlon          -(mapwidth /2)/scalefactor;
161                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
162                         addDebug("Baselon "+baselon+", basey "+basey);
163                         updateCoords(0,0);
164                         download();
165                         
166         }
167
168                 // ------------------------------------------------------------------------------------------
169                 // Recalculate co-ordinates from new Flash origin
170
171                 public function updateCoords(tx:Number,ty:Number):void {
172                         x=tx; y=ty;
173
174                         // ** calculate tile_l etc.
175                         edge_t=coord2lat(-y          );
176                         edge_b=coord2lat(-y+mapheight);
177                         edge_l=coord2lon(-x          );
178                         edge_r=coord2lon(-x+mapwidth );
179                         addDebug("Lon "+edge_l+"-"+edge_r);
180                         addDebug("Lat "+edge_b+"-"+edge_t);
181                 }
182                 
183                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
184                         var cy:Number=-(lat2coord(lat)-mapheight/2);
185                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
186                         updateCoords(cx,cy);
187                 }
188
189
190                 // Co-ordinate conversion functions
191
192                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
193                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
194                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
195                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
196
197                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
198                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
199
200                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
201                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
202
203 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
204 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
205
206
207                 // ------------------------------------------------------------------------------------------
208                 // Resize map size based on current stage and height
209
210                 public function updateSize(w:uint, h:uint):void {
211                         mapwidth = w;
212                         mapheight= h;
213             if ( backdrop != null ) {
214                 backdrop.width=mapwidth;
215                 backdrop.height=mapheight;
216             }
217             if ( mask != null ) {
218                 mask.width=mapwidth;
219                 mask.height=mapheight;
220             }
221                 }
222
223                 // ------------------------------------------------------------------------------------------
224                 // Download map data
225                 // (typically from whichways, but will want to add more connections)
226
227                 public function download():void {
228                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD,edge_l,edge_r,edge_t,edge_b));
229                         
230                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
231                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
232                         bigedge_l=edge_l; bigedge_r=edge_r;
233                         bigedge_b=edge_b; bigedge_t=edge_t;
234                         addDebug("Calling with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
235                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
236                 }
237
238
239
240         private function newWayCreated(event:EntityEvent):void {
241             var way:Way = event.entity as Way;
242                         if (!way.loaded) { return; }
243             ways[way.id] = new WayUI(way, this);
244         }
245
246         private function newPOICreated(event:EntityEvent):void {
247             var node:Node = event.entity as Node;
248             pois[node.id] = new POI(node, this);
249         }
250
251         public function setHighlight(entity:Entity, stateType:String, isOn:Boolean):void {
252             if ( entity is Way ) {
253                 var wayUI:WayUI = ways[entity.id];
254                 if ( wayUI != null )
255                     wayUI.setHighlight(stateType, isOn);
256             }
257         }
258
259         // Handle mouse events on ways/nodes
260         private var mapController:MapController = null;
261
262         public function setController(controller:MapController):void {
263             this.mapController = controller;
264         }
265
266         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
267             if ( mapController != null )
268                 mapController.entityMouseEvent(event, entity);
269                                 
270         }
271
272                 // ------------------------------------------------------------------------------------------
273                 // Redraw all items, zoom in and out
274                 
275                 public function redraw():void {
276                         for each (var w:WayUI in ways) { w.recalculate(); w.redraw(); }
277                         for each (var p:POI in pois) { p.redraw(); }
278                 }
279
280                 public function redrawPOIs():void {
281                         for each (var p:POI in pois) { p.redraw(); }
282                 }
283
284                 public function zoomIn():void {
285                         if (scale==MAXSCALE) { return; }
286                         changeScale(scale+1);
287                 }
288
289                 public function zoomOut():void {
290                         if (scale==MINSCALE) { return; }
291                         changeScale(scale-1);
292                 }
293
294                 private function changeScale(newscale:uint):void {
295                         addDebug("new scale "+newscale);
296                         scale=newscale;
297                         scalefactor=MASTERSCALE/Math.pow(2,14-scale);
298                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
299                         download();
300                         redraw();
301                 }
302
303                 private function reportPosition():void {
304                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
305                 }
306
307                 // ------------------------------------------------------------------------------------------
308                 // Export (experimental)
309                 // ** just a bit of fun for now!
310                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
311                 // to that area (will probably require creating a new DisplayObject with a different origin
312                 // and mask)
313 /*              
314                 public function export():void {
315                         addDebug("size is "+this.width+","+this.height);
316                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
317                         jpgSource.draw(this);
318                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
319                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
320                         var fileRef:FileReference = new FileReference();
321 //                      fileRef.save(jpgStream,'map.jpeg');
322                 }
323
324 */
325
326                 // ==========================================================================================
327                 // Events
328                 
329                 // ------------------------------------------------------------------------------------------
330                 // Mouse events
331                 
332                 public function mouseDownHandler(event:MouseEvent):void {
333                         dragging=true;
334                         lastxmouse=mouseX; lastymouse=mouseY;
335                 }
336         
337                 public function mouseUpHandler(event:MouseEvent):void {
338                         if (!dragging) { return; }
339                         dragging=false;
340                         updateCoords(x,y);
341                         download();
342                 }
343         
344                 public function mouseMoveHandler(event:MouseEvent):void {
345                         if (!dragging) { return; }
346                         x+=mouseX-lastxmouse;
347                         y+=mouseY-lastymouse;
348                         lastxmouse=mouseX; lastymouse=mouseY;
349                 }
350         
351                 // ------------------------------------------------------------------------------------------
352                 // Miscellaneous events
353                 
354                 public function keyUpHandler(event:KeyboardEvent):void {
355 // addDebug("pressed "+event.keyCode);
356             if ( !event.ctrlKey ) return;
357                         if (event.keyCode==82) { this.redraw(); }                       // R - redraw
358                         if (event.keyCode==73) { this.zoomIn(); }                       // I - zoom in
359                         if (event.keyCode==79) { this.zoomOut(); }                      // O - zoom out
360                         if (event.keyCode==76) { this.reportPosition(); }       // L - report lat/long
361 //                      if (event.keyCode==69) { this.export(); }                       // E - export
362                 }
363
364                 public function connectionError(err:Object=null): void {
365                         addDebug("got error"); 
366                 }
367
368                 // ------------------------------------------------------------------------------------------
369                 // Debugging
370                 
371                 public function addDebug(text:String):void {
372                         if (!Globals.vars.hasOwnProperty('debug')) return;
373                         if (!Globals.vars.debug.visible) return;
374                         Globals.vars.debug.appendText(text+"\n");
375                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
376                 }
377                 
378         }
379 }