initial work on tag editor
[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(redrawPOIs);     // 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                         // Set up layering
70                         // [layer][2]                   - names
71                         // [layer][1][sublayer] - stroke
72                         // [layer][0]                   - fill
73
74                         for (var l:int=0; l<13; l++) {                          // 11 layers (10 is +5, 0 is -5)
75                                 var s:Sprite = getPaintSprite();                //  |
76                                 s.addChild(getPaintSprite());                   //      | 0 fill
77                                 var t:Sprite = getPaintSprite();                //  | 1 stroke
78                                 for (var j:int=0; j<11; j++) {                  //      |  | ten sublayers
79                                         t.addChild(getPaintSprite());           //  |  |  |
80                                 }                                                                               //  |  |  |
81                                 s.addChild(t);                                                  //  |  |
82                                 s.addChild(getPaintSprite());                   //      | 2 names
83                                 addChild(s);                                                    //  |
84                         }
85                         s=getPaintSprite(); addChild(s);                        // 11 - POIs
86                         s=getPaintSprite(); addChild(s);                        // 12 - shields and POI names
87
88                         connection= Connection.getConnection();
89             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
90             connection.addEventListener(Connection.NEW_POI, newPOICreated);
91                         connection.getEnvironment(new Responder(gotEnvironment,connectionError));
92
93         }
94
95         private function getPaintSprite():Sprite {
96             var s:Sprite = new Sprite();
97             s.mouseEnabled = false;
98             return s;
99         }
100
101                 public function gotEnvironment(r:Object):void {
102                         init(53.09465,-2.56495,17);
103                 }
104
105                 // ------------------------------------------------------------------------------------------
106                 // Initialise map at a given lat/lon
107
108         public function init(startlat:Number,startlon:Number,startscale:uint):void {
109
110                         ruleset.load("test.yaml?d="+Math.random());
111 //                      rules.initExample();            // initialise dummy rules
112
113                         updateSize();
114
115                         scale=startscale;
116                         scalefactor=MASTERSCALE/Math.pow(2,14-scale);
117                         baselon    =startlon          -(mapwidth /2)/scalefactor;
118                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
119                         addDebug("Baselon "+baselon+", basey "+basey);
120                         updateCoords(0,0);
121                         download();
122                         
123         }
124
125                 // ------------------------------------------------------------------------------------------
126                 // Recalculate co-ordinates from new Flash origin
127
128                 public function updateCoords(tx:Number,ty:Number):void {
129                         x=tx; y=ty;
130
131                         // ** calculate tile_l etc.
132                         edge_t=coord2lat(-y          );
133                         edge_b=coord2lat(-y+mapheight);
134                         edge_l=coord2lon(-x          );
135                         edge_r=coord2lon(-x+mapwidth );
136                         addDebug("Lon "+edge_l+"-"+edge_r);
137                         addDebug("Lat "+edge_b+"-"+edge_t);
138                 }
139                 
140                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
141                         var cy:Number=-(lat2coord(lat)-mapheight/2);
142                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
143                         updateCoords(cx,cy);
144                 }
145
146
147                 // Co-ordinate conversion functions
148
149                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
150                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
151                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
152                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
153
154                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
155                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
156
157                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
158                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
159
160 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
161 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
162
163
164                 // ------------------------------------------------------------------------------------------
165                 // Resize map size based on current stage and height
166
167                 public function updateSize():void {
168                         mapwidth =stage.stageWidth; backdrop.width=mapwidth; mask.width=mapwidth;
169                         mapheight=stage.stageHeight; backdrop.height=mapheight; mask.height=mapheight;
170                 }
171
172                 // ------------------------------------------------------------------------------------------
173                 // Download map data
174                 // (typically from whichways, but will want to add more connections)
175
176                 public function download():void {
177                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD,edge_l,edge_r,edge_t,edge_b));
178                         
179                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
180                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
181                         bigedge_l=edge_l; bigedge_r=edge_r;
182                         bigedge_b=edge_b; bigedge_t=edge_t;
183                         addDebug("Calling with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
184                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
185                 }
186
187
188
189         private function newWayCreated(event:EntityEvent):void {
190             var way:Way = event.entity as Way;
191             ways[way.id] = new WayUI(way, this);
192         }
193
194         private function newPOICreated(event:EntityEvent):void {
195             var node:Node = event.entity as Node;
196             pois[node.id] = new POI(node, this);
197         }
198
199         public function setHighlight(entity:Entity, highlight:Boolean):void {
200             if ( entity is Way ) {
201                 var wayUI:WayUI = ways[entity.id];
202                 if ( wayUI != null )
203                     wayUI.setHighlight(highlight);
204             }
205         }
206
207         // Handle mouse events on ways/nodes
208         private var mapController:MapController = null;
209
210         public function setController(controller:MapController):void {
211             this.mapController = controller;
212         }
213
214         public function wayMouseEvent(event:MouseEvent, way:Way):void {
215             if ( mapController != null )
216                 mapController.entityMouseEvent(event, way);
217         }
218
219                 // ------------------------------------------------------------------------------------------
220                 // Redraw all items, zoom in and out
221                 
222                 public function redraw():void {
223                         for each (var w:WayUI in ways) { w.recalculate(); w.redraw(); }
224                         for each (var p:POI in pois) { p.redraw(); }
225                 }
226
227                 public function redrawPOIs():void {
228                         for each (var p:POI in pois) { p.redraw(); }
229                 }
230
231                 public function zoomIn():void {
232                         if (scale==MAXSCALE) { return; }
233                         changeScale(scale+1);
234                 }
235
236                 public function zoomOut():void {
237                         if (scale==MINSCALE) { return; }
238                         changeScale(scale-1);
239                 }
240
241                 private function changeScale(newscale:uint):void {
242                         addDebug("new scale "+newscale);
243                         scale=newscale;
244                         scalefactor=MASTERSCALE/Math.pow(2,14-scale);
245                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
246                         download();
247                         redraw();
248                 }
249
250                 private function reportPosition():void {
251                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
252                 }
253
254
255                 // ==========================================================================================
256                 // Events
257                 
258                 // ------------------------------------------------------------------------------------------
259                 // Mouse events
260                 
261                 public function mouseDownHandler(event:MouseEvent):void {
262                         dragging=true;
263                         lastxmouse=mouseX; lastymouse=mouseY;
264                 }
265         
266                 public function mouseUpHandler(event:MouseEvent):void {
267                         if (!dragging) { return; }
268                         dragging=false;
269                         updateCoords(x,y);
270                         download();
271                 }
272         
273                 public function mouseMoveHandler(event:MouseEvent):void {
274                         if (!dragging) { return; }
275                         x+=mouseX-lastxmouse;
276                         y+=mouseY-lastymouse;
277                         lastxmouse=mouseX; lastymouse=mouseY;
278                 }
279         
280                 // ------------------------------------------------------------------------------------------
281                 // Miscellaneous events
282                 
283                 public function keyUpHandler(event:KeyboardEvent):void {
284 // addDebug("pressed "+event.keyCode);
285                         if (event.keyCode==82) { this.redraw(); }                       // R - redraw
286                         if (event.keyCode==73) { this.zoomIn(); }                       // I - zoom in
287                         if (event.keyCode==79) { this.zoomOut(); }                      // O - zoom out
288                         if (event.keyCode==76) { this.reportPosition(); }       // L - report lat/long
289                 }
290
291                 public function connectionError(err:Object=null): void {
292                         addDebug("got error"); 
293                 }
294
295                 // ------------------------------------------------------------------------------------------
296                 // Debugging
297                 
298                 public function addDebug(text:String):void {
299                         Globals.vars.debug.appendText(text+"\n");
300                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
301                 }
302                 
303         }
304 }