Merge branch 'master' into history
[potlatch2.git] / net / systemeD / halcyon / TileSet.as
1 package net.systemeD.halcyon {
2
3         import flash.display.*;
4         import flash.events.*;
5         import flash.filters.*;
6         import flash.net.*;
7         import flash.system.LoaderContext;
8         import flash.utils.Timer;
9
10     public class TileSet extends Sprite {
11
12                 public var tile_l:int;
13                 public var tile_r:int;
14                 public var tile_b:int;
15                 public var tile_t:int;
16
17                 private var offset_lon:Number=0;
18                 private var offset_lat:Number=0;
19
20                 private var requests:Array=[];
21                 private var tiles:Object={};            // key is "z,x,y"; value "true" if queued, or reference to loader object if requested
22                 private var waiting:int=0;                      // number of tiles currently being downloaded
23                 private var loadcount:int=0;            // number of tiles fully downloaded
24                 private var baseurl:String;                     // e.g. http://npe.openstreetmap.org/$z/$x/$y.png
25                 private var scheme:String;                      // 900913 or microsoft
26                 public var blocks:Array;                        // array of regexes which are verboten
27
28                 private var map:Map;
29                 private const MAXTILEREQUESTS:uint= 4;
30                 private const MAXTILESLOADED:uint=30;
31
32                 private var sharpenFilter:BitmapFilter = new ConvolutionFilter(3, 3, 
33                         [0, -1, 0,
34             -1, 5, -1,
35              0, -1, 0], 0);
36                 private var sharpening:Boolean = false;
37                 // http://flylib.com/books/en/2.701.1.170/1/
38
39         public function TileSet(map:Map) {
40                         this.map=map;
41                         createSprites();
42                         map.addEventListener(MapEvent.NUDGE_BACKGROUND, nudgeHandler);
43                 }
44         
45                 /** @param params Currently includes "url" and "scheme"
46                  * @param update Trigger update now?
47                  * @param dim Start with imagery faded?
48                  * @param sharpen Start with sharpen filter applied?
49                  */
50                 public function init(params:Object, update:Boolean=false):void {
51                         baseurl=params.url;
52                         scheme =params.scheme ? params.scheme : '900913';
53                         tiles={};
54                         offset_lon=offset_lat=x=y=0;
55                         while (numChildren) { removeChildAt(0); }
56                         createSprites();
57                         if (update) { this.update(); }
58                 }
59
60                 private function createSprites():void {
61                         for (var i:uint=map.MINSCALE; i<=map.MAXSCALE; i++) {
62                                 this.addChild(new Sprite());
63                         }
64                 }
65
66                 /** Toggle fading of imagery. */
67                 public function setDimming(dim:Boolean):void {
68                         alpha=dim ? 0.5 : 1;
69                 }
70                 /** Is imagery currently set faded? */
71                 public function getDimming():Boolean {
72                         return (alpha<1);
73                 }
74
75         /** Toggle sharpen filter. */
76                 public function setSharpen(sharpen:Boolean):void {
77                         var f:Array=[]; if (sharpen) { f=[sharpenFilter]; }
78                         for (var i:uint=0; i<numChildren; i++) {
79                                 var s:Sprite=Sprite(getChildAt(i));
80                                 for (var j:uint=0; j<s.numChildren; j++) {
81                                         s.getChildAt(j).filters=f;
82                                 }
83                         }
84                         sharpening=sharpen;
85                 }
86                 
87                 /** Is sharpen filter applied? */
88                 public function getSharpen():Boolean {
89                         return sharpening;
90                 }
91
92                 /** Set zoom scale (no update triggerd). */
93                 public function changeScale(scale:uint):void {
94                         for (var i:uint=map.MINSCALE; i<=map.MAXSCALE; i++) {
95                                 this.getChildAt(i-map.MINSCALE).visible=(scale==i);
96                         }
97                         x=map.lon2coord(map.centre_lon+offset_lon)-map.lon2coord(map.centre_lon);
98                         y=map.lat2coord(map.centre_lat+offset_lat)-map.lat2coord(map.centre_lat);
99                 }
100                         
101                 /** Update bounds of tile area, and request new tiles if needed.  */
102                 
103                 public function update():void {
104                         if (!baseurl) { return; }
105                         tile_l=lon2tile(map.edge_l-offset_lon);
106                         tile_r=lon2tile(map.edge_r-offset_lon);
107                         tile_t=lat2tile(map.edge_t-offset_lat);
108                         tile_b=lat2tile(map.edge_b-offset_lat);
109                         for (var tx:int=tile_l; tx<=tile_r; tx++) {
110                                 for (var ty:int=tile_t; ty<=tile_b; ty++) {
111                                         if (!tiles[map.scale+','+tx+','+ty]) { addRequest(tx,ty); }
112                                 }
113                         }
114                 }
115
116                 /** Mark that a tile needs to be loaded*/
117                 
118                 public function addRequest(tx:int,ty:int):void {
119                         tiles[map.scale+','+tx+','+ty]=true;
120                         requests.push([map.scale,tx,ty]);
121                 }
122
123                 /** Service tile queue - called on every frame to download new tiles */
124                 
125                 public function serviceQueue():void {
126                         if (waiting==MAXTILEREQUESTS || requests.length==0) { return; } //SB
127                         var r:Array, tx:int, ty:int, tz:int, l:DisplayObject;
128
129                         for (var i:uint=0; i<Math.min(requests.length, MAXTILEREQUESTS-waiting); i++) {
130                                 r=requests.shift(); tz=r[0]; tx=r[1]; ty=r[2];
131                                 if (tx>=tile_l && tx<=tile_r && ty>=tile_t && ty<=tile_b) {
132                                         // Tile is on-screen, so load
133                                         waiting++;
134                                         var loader:Loader = new Loader();
135                                         tiles[map.scale+','+tx+','+ty]=loader;
136                                         loader.contentLoaderInfo.addEventListener(Event.INIT, doImgInit);
137                         loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, missingTileError);
138                                         loader.load(new URLRequest(tileURL(tx,ty,tz)), 
139                                                     new LoaderContext(true));
140                                         l=this.getChildAt(map.scale-map.MINSCALE);
141                                         Sprite(l).addChild(loader);
142                                         loader.x=map.lon2coord(tile2lon(tx));
143                                         loader.y=map.lat2coord(tile2lat(ty));
144                                         if (sharpening) { loader.filters=[sharpenFilter]; }
145                     /*
146                     var timer:Timer = new Timer(5000, 1);
147                     timer.addEventListener(TimerEvent.TIMER, function(){checkTileLoaded(map.scale,tx,ty);});
148                     timer.start();
149                                         */
150
151                                 } else {
152                                         tiles[tz+','+tx+','+ty]=false; // Map has moved between the time we wanted this tile and now, so make 
153                                                                        //it available for a future request
154                                 }
155                         }
156                 }
157
158 /* We may need something like this in the future, not sure. Trouble is if a tile doesn't get loaded on first go,
159    it will never get loaded. 
160         private function checkTileLoaded(z,x,y) {
161             if (tiles[z+','+x+','+y]==true){
162                 trace("Didn't even start getting tile: " + z+','+x+','+y);
163                 requests.push([z,x,y]);
164                 return; 
165             }   
166                 var l:Loader = tiles[z+','+x+','+y];
167                 if (l.alpha < 0.1) { 
168                         trace('Broken tile:' + z+','+x+','+y); 
169                 }
170
171         }
172         */
173         private function missingTileError(event:Event):void {
174                         waiting--;
175                         return;
176                 }
177
178                 /** Tile image has been downloaded, so start displaying it. */
179                 protected function doImgInit(event:Event):void {
180                         event.target.loader.alpha=0;
181                         var t:Timer=new Timer(10,10);
182                         t.addEventListener(TimerEvent.TIMER,function():void { upFade(DisplayObject(event.target.loader)); });
183                         t.start();
184                         waiting--;
185                         loadcount++;
186                         if (loadcount>MAXTILESLOADED) purgeTiles();
187                         return;
188                 }
189                 
190                 protected function upFade(s:DisplayObject):void {
191                         s.alpha+=0.1;
192                 }
193                 
194                 protected function purgeTiles():void {
195                         for (var tile:String in tiles) {
196                                 if (tiles[tile] is Sprite) {
197                                         var coords:Array=tile.split(','); var tz:uint=coords[0]; var tx:uint=coords[1]; var ty:uint=coords[1];
198                                         if (tz!=map.scale || tx<tile_l || tx>tile_r || ty<tile_t || ty<tile_b) {
199                                                 if (tiles[tile].parent) tiles[tile].parent.removeChild(tiles[tile]);
200                                                 delete tiles[tile];
201                                                 loadcount--;
202                                         }
203                                 }
204                         }
205                 }
206
207                 
208                 // Assemble tile URL
209                 
210                 private function tileURL(tx:int,ty:int,tz:uint):String {
211                         var t:String='';
212                         switch (scheme.toLowerCase()) {
213
214                                 case 'microsoft':
215                                         var u:String='';
216                                         for (var zoom:uint=tz; zoom>0; zoom--) {
217                                                 var byte:uint=0;
218                                                 var mask:uint=1<<(zoom-1);
219                                                 if ((tx & mask)!=0) byte++;
220                                                 if ((ty & mask)!=0) byte+=2;
221                                                 u+=String(byte);
222                                         }
223                                         t=baseurl.replace('$quadkey',u); break;
224
225                                 case 'tms':
226                                         ty=Math.pow(2,tz)-1-ty;
227                                         t=baseurl.replace('$z',map.scale).replace('$x',tx).replace('$y',ty);
228                                         break;
229
230                                 default:
231                                         if (baseurl.indexOf('$x')>-1) {
232                                                 t=baseurl.replace('$z',map.scale).replace('$x',tx).replace('$y',ty);
233                                         } else {
234                                                 t=baseurl.replace('!',map.scale).replace('!',tx).replace('!',ty);
235                                         }
236                                         break;
237
238                         }
239                         for each (var block:* in blocks) { if (t.match(block)) return ''; }
240                         return t;
241                 }
242                 
243                 public function get url():String {
244                         return baseurl ? baseurl : '';
245                 }
246
247                 /** Respond to nudge event by updating offset between imagery and map. */
248                 public function nudgeHandler(event:MapEvent):void {
249                         if (!baseurl) { return; }
250                         this.x+=event.params.x; this.y+=event.params.y;
251                         offset_lat=map.centre_lat-map.coord2lat(map.lat2coord(map.centre_lat)-this.y);
252                         offset_lon=map.centre_lon-map.coord2lon(map.lon2coord(map.centre_lon)-this.x);
253                         update();
254                 }
255
256                 
257                 // ------------------------------------------------------------------
258                 // Co-ordinate conversion functions
259
260                 private function lon2tile(lon:Number):int {
261                         return (Math.floor((lon+180)/360*Math.pow(2,map.scale)));
262                 }
263                 private function lat2tile(lat:Number):int { 
264                         return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,map.scale)));
265                 }
266                 private function tile2lon(t:int):Number {
267                         return (t/Math.pow(2,map.scale)*360-180);
268                 }
269                 private function tile2lat(t:int):Number { 
270                         var n:Number=Math.PI-2*Math.PI*t/Math.pow(2,map.scale);
271                         return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n))));
272                 }
273
274         }
275 }