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