refactor the potlatch 2 code to look more MVC wrt the API parts
[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.Sprite;
6         import flash.display.Shape;
7         import flash.display.Stage;
8         import flash.events.*;
9         import flash.net.*;
10
11     import net.systemeD.halcyon.connection.*;
12     import net.systemeD.halcyon.connection.EntityEvent;
13         import net.systemeD.halcyon.styleparser.*;
14
15     public class Map extends Sprite {
16
17                 public const MASTERSCALE:Number=5825.4222222222;// master map scale - how many Flash pixels in 1 degree longitude
18                                                                                                                 // (for Landsat, 5120)
19                 public const MINSCALE:uint=13;                                  // don't zoom out past this
20                 public const MAXSCALE:uint=19;                                  // don't zoom in past this
21
22                 public var ruleset:RuleSet=new RuleSet();               // rules
23                 
24                 public var ways:Object=new Object();                    // geodata
25                 public var nodes:Object=new Object();                   //  |
26                 public var pois:Object=new Object();                    //  |
27                 public var relations:Object=new Object();               //  |
28
29                 public var scale:uint=14;                                               // map scale
30                 public var scalefactor:Number=MASTERSCALE;              // current scaling factor for lon/latp
31                 public var bigedge_l:Number= 999999;                    // area of largest whichways
32                 public var bigedge_r:Number=-999999;                    //  |
33                 public var bigedge_b:Number= 999999;                    //  |
34                 public var bigedge_t:Number=-999999;                    //  |
35
36                 public var waycount:uint=0;                                             // ways:                number currently loaded
37                 public var waysrequested:uint=0;                                //                              total number requested
38                 public var waysreceived:uint=0;                                 //                              total number received
39                 public var relcount:uint=0;                                             // relations:   number currently loaded
40                 public var relsrequested:uint=0;                                //                              total number requested
41                 public var relsreceived:uint=0;                                 //                              total number received
42                 public var poicount:uint=0;                                             // POIs:                number currently loaded
43                 public var whichrequested:uint=0;                               // whichways:   total number requested
44                 public var whichreceived:uint=0;                                //                              total number received
45
46                 public var edge_l:Number;                                               // current bounding box
47                 public var edge_r:Number;                                               //  |
48                 public var edge_t:Number;                                               //  |
49                 public var edge_b:Number;                                               //  |
50
51                 public var baselon:Number;                                              // urllon-xradius/masterscale;
52                 public var basey:Number;                                                // lat2lat2p(urllat)+yradius/masterscale;
53                 public var mapwidth:uint;                                               // width (Flash pixels)
54                 public var mapheight:uint;                                              // height (Flash pixels)
55
56                 private var dragging:Boolean=false;                             // dragging map?
57                 private var lastxmouse:Number;                                  //  |
58                 private var lastymouse:Number;                                  //  |
59                 
60                 public var backdrop:Object;                                             // reference to backdrop sprite
61                 
62                 public var connection:Connection;                       // server connection
63
64                 // ------------------------------------------------------------------------------------------
65                 // Map constructor function
66
67         public function Map() {
68
69                         for (var l:int=0; l<13; l++) {                          // 11 layers (10 is +5, 0 is -5)
70                                 var s:Sprite=new Sprite();
71                                 s.addChild(new Sprite());                               // [layer][0]=fill, [1]=stroke, [2]=names
72                                 s.addChild(new Sprite());
73                                 s.addChild(new Sprite());
74                                 addChild(s);
75                         }
76                         s=new Sprite(); addChild(s);                            // 11 - POIs
77                         s=new Sprite(); addChild(s);                            // 12 - shields
78
79                         connection= Connection.getConnection();
80             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
81             connection.addEventListener(Connection.NEW_POI, newPOICreated);
82                         connection.getEnvironment(new Responder(gotEnvironment,connectionError));
83
84         }
85
86                 public function gotEnvironment(r:Object):void {
87                         init(51.45889,-0.21476);
88                 }
89
90                 // ------------------------------------------------------------------------------------------
91                 // Initialise map at a given lat/lon
92
93         public function init(startlat:Number,startlon:Number):void {
94
95                         ruleset.load("test.yaml?d="+Math.random());
96 //                      rules.initExample();            // initialise dummy rules
97
98                         updateSize();
99                         baselon  =startlon                      -(mapwidth /2)/MASTERSCALE;
100                         basey    =lat2latp(startlat)+(mapheight/2)/MASTERSCALE;
101                         addDebug("Baselon "+baselon+", basey "+basey);
102                         updateCoords(0,0);
103                         download();
104                         
105         }
106
107                 // ------------------------------------------------------------------------------------------
108                 // Recalculate co-ordinates from new Flash origin
109
110                 public function updateCoords(tx:Number,ty:Number):void {
111                         x=tx; y=ty;
112
113                         // ** calculate tile_l etc.
114                         edge_t=coord2lat(-y          );
115                         edge_b=coord2lat(-y+mapheight);
116                         edge_l=coord2lon(-x          );
117                         edge_r=coord2lon(-x+mapwidth );
118                         addDebug("Lon "+edge_l+"-"+edge_r);
119                         addDebug("Lat "+edge_b+"-"+edge_t);
120                 }
121                 
122                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
123                         var cy:Number=-(lat2coord(lat)-mapheight/2);
124                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
125                         updateCoords(cx,cy);
126                 }
127
128
129                 // Co-ordinate conversion functions
130
131                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
132                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
133                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
134                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
135
136                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
137                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
138
139                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
140                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
141
142 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
143 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
144
145
146                 // ------------------------------------------------------------------------------------------
147                 // Resize map size based on current stage and height
148
149                 public function updateSize():void {
150                         mapwidth =stage.stageWidth; backdrop.width=mapwidth; mask.width=mapwidth;
151                         mapheight=stage.stageHeight; backdrop.height=mapheight; mask.height=mapheight;
152                 }
153
154                 // ------------------------------------------------------------------------------------------
155                 // Download map data
156                 // (typically from whichways, but will want to add more connections)
157
158                 public function download():void {
159                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
160                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
161                         bigedge_l=edge_l; bigedge_r=edge_r;
162                         bigedge_b=edge_b; bigedge_t=edge_t;
163                         addDebug("Calling with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
164                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
165                 }
166
167 /*
168                 public function gotBbox(r:Object):void {
169                         addDebug("got whichways");
170                         var code:uint         =r.shift(); if (code) { connectionError(); return; }
171                         var message:String    =r.shift();
172                         var waylist:Array     =r[0];
173                         var pointlist:Array   =r[1];
174                         var relationlist:Array=r[2];
175                         var i:uint, v:uint;
176
177                         for each (var w:Array in waylist) {
178                                 i=w[0]; v=w[1];
179                                 if (ways[i] && ways[i].version==v) { continue; }
180                                 ways[i]=new Way(i,v,this);
181                                 ways[i].load(connection);
182                         }
183
184                         for each (var p:Array in pointlist) {
185                                 i=p[0]; v=p[4];
186                                 if (pois[i] && pois[i].version==v) { continue; }
187                                 pois[i]=new POI(i,v,p[1],p[2],p[3],this);
188                         }
189
190                         addDebug("waylist is "+waylist);
191                 }
192 */
193
194         private function newWayCreated(event:EntityEvent):void {
195             var way:Way = event.entity as Way;
196             ways[way.id] = new WayUI(way, this);
197         }
198
199         private function newPOICreated(event:EntityEvent):void {
200             var node:Node = event.entity as Node;
201             pois[node.id] = new POI(node, this);
202         }
203
204                 // ------------------------------------------------------------------------------------------
205                 // Redraw all items, zoom in and out
206                 
207                 public function redraw():void {
208 //                      addDebug("redrawing");
209 //                      var s:String='';
210                         for each (var w:WayUI in ways) {
211                 w.redraw();
212 //                s+=w.id+",";
213             }
214 //                      addDebug(s);
215                         // ** do POIs, etc.
216                 }
217
218                 public function zoomIn():void {
219                         if (scale==MAXSCALE) { return; }
220                         changeScale(scale+1);
221                 }
222
223                 public function zoomOut():void {
224                         if (scale==MINSCALE) { return; }
225                         changeScale(scale-1);
226                 }
227
228                 private function changeScale(newscale:uint):void {
229                         addDebug("new scale "+newscale);
230                         scale=newscale;
231                         scalefactor=MASTERSCALE/Math.pow(2,14-scale);
232                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
233                         download();
234                         redraw();
235                 }
236
237                 private function reportPosition():void {
238                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
239                 }
240
241
242                 // ==========================================================================================
243                 // Events
244                 
245                 // ------------------------------------------------------------------------------------------
246                 // Mouse events
247                 
248                 public function mouseDownHandler(event:MouseEvent):void {
249                         dragging=true;
250                         lastxmouse=mouseX; lastymouse=mouseY;
251                 }
252         
253                 public function mouseUpHandler(event:MouseEvent):void {
254                         if (!dragging) { return; }
255                         dragging=false;
256                         updateCoords(x,y);
257                         download();
258                 }
259         
260                 public function mouseMoveHandler(event:MouseEvent):void {
261                         if (!dragging) { return; }
262                         x+=mouseX-lastxmouse;
263                         y+=mouseY-lastymouse;
264                         lastxmouse=mouseX; lastymouse=mouseY;
265                 }
266         
267                 // ------------------------------------------------------------------------------------------
268                 // Miscellaneous events
269                 
270                 public function keyUpHandler(event:KeyboardEvent):void {
271 addDebug("pressed "+event.keyCode);
272                         if (event.keyCode==82) { this.redraw(); }                       // R - redraw
273                         if (event.keyCode==73) { this.zoomIn(); }                       // I - zoom in
274                         if (event.keyCode==79) { this.zoomOut(); }                      // O - zoom out
275                         if (event.keyCode==76) { this.reportPosition(); }       // L - report lat/long
276                 }
277
278                 public function connectionError(err:Object=null): void {
279                         addDebug("got error"); 
280                 }
281
282                 // ------------------------------------------------------------------------------------------
283                 // Debugging
284                 
285                 public function addDebug(text:String):void {
286                         Globals.vars.debug.appendText(text+"\n");
287                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
288                 }
289                 
290         }
291 }