support Potlatch legacy tile scheme; don't support Google
[potlatch2.git] / net / systemeD / halcyon / TileSet.as
1 package net.systemeD.halcyon {
2
3         import flash.display.*;
4         import flash.events.*;
5         import flash.net.*;
6         import flash.system.LoaderContext;
7         import flash.utils.Timer;
8         import flash.filters.*;
9         import net.systemeD.halcyon.MapEvent;
10
11     public class TileSet extends Sprite {
12
13                 public var tile_l:int;
14                 public var tile_r:int;
15                 public var tile_b:int;
16                 public var tile_t:int;
17
18                 private var offset_lon:Number=0;
19                 private var offset_lat:Number=0;
20
21                 private var requests:Array=[];
22                 private var tiles:Object={};            // key is "z,x,y"; value "true" (needed) or reference to sprite
23                 private var waiting:int=0;                      // number of tiles currently being 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
30                 private var sharpenFilter:BitmapFilter = new ConvolutionFilter(3, 3, 
31                         [0, -1, 0,
32             -1, 5, -1,
33              0, -1, 0], 0);
34                 private var sharpening:Boolean = false;
35                 // http://flylib.com/books/en/2.701.1.170/1/
36
37         public function TileSet(map:Map) {
38                         this.map=map;
39                         alpha=0.5;
40                         createSprites();
41                         map.addEventListener(MapEvent.NUDGE_BACKGROUND, nudgeHandler);
42                 }
43         
44                 public function init(params:Object, update:Boolean=false):void {
45                         baseurl=params.url;
46                         scheme =params.scheme ? params.scheme : '900913';
47                         tiles={};
48                         offset_lon=offset_lat=x=y=0;
49                         while (numChildren) { removeChildAt(0); }
50                         createSprites();
51                         if (update) { this.update(); }
52                 }
53
54                 private function createSprites():void {
55                         for (var i:uint=map.MINSCALE; i<=map.MAXSCALE; i++) {
56                                 this.addChild(new Sprite());
57                         }
58                 }
59
60                 public function setDimming(dim:Boolean):void {
61                         alpha=dim ? 0.5 : 1;
62                 }
63
64                 public function setSharpen(sharpen:Boolean):void {
65                         var f:Array=[]; if (sharpen) { f=[sharpenFilter]; }
66                         for (var i:uint=0; i<numChildren; i++) {
67                                 var s:Sprite=Sprite(getChildAt(i));
68                                 for (var j:uint=0; j<s.numChildren; j++) {
69                                         s.getChildAt(j).filters=f;
70                                 }
71                         }
72                         sharpening=sharpen;
73                 }
74
75                 public function changeScale(scale:uint):void {
76                         for (var i:uint=map.MINSCALE; i<=map.MAXSCALE; i++) {
77                                 this.getChildAt(i-map.MINSCALE).visible=(scale==i);
78                         }
79                         x=map.lon2coord(map.centre_lon+offset_lon)-map.lon2coord(map.centre_lon);
80                         y=map.lat2coord(map.centre_lat+offset_lat)-map.lat2coord(map.centre_lat);
81                 }
82                         
83                 // Update bounds - called on every move
84                 
85                 public function update():void {
86                         if (!baseurl) { return; }
87                         tile_l=lon2tile(map.edge_l-offset_lon);
88                         tile_r=lon2tile(map.edge_r-offset_lon);
89                         tile_t=lat2tile(map.edge_t-offset_lat);
90                         tile_b=lat2tile(map.edge_b-offset_lat);
91                         for (var tx:int=tile_l; tx<=tile_r; tx++) {
92                                 for (var ty:int=tile_t; ty<=tile_b; ty++) {
93                                         if (!tiles[map.scale+','+tx+','+ty]) { addRequest(tx,ty); }
94                                 }
95                         }
96                 }
97
98                 // Mark that a tile needs to be loaded
99                 
100                 public function addRequest(tx:int,ty:int):void {
101                         tiles[map.scale+','+tx+','+ty]=true;
102                         requests.push([map.scale,tx,ty]);
103                 }
104
105                 // Service tile queue - called on every frame to download new tiles
106                 
107                 public function serviceQueue():void {
108                         if (waiting==4 || requests.length==0) { return; }
109                         var r:Array, tx:int, ty:int, tz:int, l:DisplayObject;
110
111                         for (var i:uint=0; i<Math.min(requests.length, 4-waiting); i++) {
112                                 r=requests.shift(); tz=r[0]; tx=r[1]; ty=r[2];
113                                 if (tx>=tile_l && tx<=tile_r && ty>=tile_t && ty<=tile_b) {
114                                         // Tile is on-screen, so load
115                                         waiting++;
116                                         var loader:Loader = new Loader();
117                                         loader.contentLoaderInfo.addEventListener(Event.INIT, doImgInit);
118                         loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, missingTileError);
119                                         loader.load(new URLRequest(tileURL(tx,ty,tz)), 
120                                                     new LoaderContext(true));
121                                         l=this.getChildAt(map.scale-map.MINSCALE);
122                                         Sprite(l).addChild(loader);
123                                         loader.x=map.lon2coord(tile2lon(tx));
124                                         loader.y=map.lat2coord(tile2lat(ty));
125                                         if (sharpening) { loader.filters=[sharpenFilter]; }
126 //                                      loader.alpha=0.5;
127                                 }
128                         }
129                 }
130
131         private function missingTileError(event:Event):void {
132                         waiting--;
133                         return;
134                 }
135
136                 protected function doImgInit(event:Event):void {
137                         event.target.loader.alpha=0;
138                         var t:Timer=new Timer(10,10);
139                         t.addEventListener(TimerEvent.TIMER,function():void { upFade(DisplayObject(event.target.loader)); });
140                         t.start();
141                         waiting--;
142                         return;
143                 }
144                 
145                 protected function upFade(s:DisplayObject):void {
146                         s.alpha+=0.1;
147                 }
148
149                 
150                 // Assemble tile URL
151                 
152                 private function tileURL(tx:int,ty:int,tz:uint):String {
153                         var t:String='';
154                         switch (scheme.toLowerCase()) {
155
156                                 case 'microsoft':
157                                         var u:String='';
158                                         for (var zoom:uint=tz; zoom>0; zoom--) {
159                                                 var byte:uint=0;
160                                                 var mask:uint=1<<(zoom-1);
161                                                 if ((tx & mask)!=0) byte++;
162                                                 if ((ty & mask)!=0) byte+=2;
163                                                 u+=String(byte);
164                                         }
165                                         t=baseurl.replace('$quadkey',u); break;
166
167                                 default:
168                                         if (baseurl.indexOf('$x')>-1) {
169                                                 t=baseurl.replace('$z',map.scale).replace('$x',tx).replace('$y',ty);
170                                         } else {
171                                                 t=baseurl.replace('!',map.scale).replace('!',tx).replace('!',ty);
172                                         }
173                                         break;
174
175                         }
176                         for each (var block:* in blocks) { if (t.match(block)) return ''; }
177                         return t;
178                 }
179                 
180                 public function get url():String {
181                         return baseurl ? baseurl : '';
182                 }
183
184                 // Update offset
185                 
186                 public function nudgeHandler(event:MapEvent):void {
187                         if (!baseurl) { return; }
188                         this.x+=event.params.x; this.y+=event.params.y;
189                         offset_lat=map.centre_lat-map.coord2lat(map.lat2coord(map.centre_lat)-this.y);
190                         offset_lon=map.centre_lon-map.coord2lon(map.lon2coord(map.centre_lon)-this.x);
191                         update();
192                 }
193
194                 
195                 // ------------------------------------------------------------------
196                 // Co-ordinate conversion functions
197
198                 private function lon2tile(lon:Number):int {
199                         return (Math.floor((lon+180)/360*Math.pow(2,map.scale)));
200                 }
201                 private function lat2tile(lat:Number):int { 
202                         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)));
203                 }
204                 private function tile2lon(t:int):Number {
205                         return (t/Math.pow(2,map.scale)*360-180);
206                 }
207                 private function tile2lat(t:int):Number { 
208                         var n:Number=Math.PI-2*Math.PI*t/Math.pow(2,map.scale);
209                         return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n))));
210                 }
211
212         }
213 }