]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/gui/map/MapTileCacher.java
Version 7, February 2009
[GpsPrune.git] / tim / prune / gui / map / MapTileCacher.java
1 package tim.prune.gui.map;
2
3 import java.awt.Image;
4 import java.awt.Toolkit;
5 import java.awt.image.ImageObserver;
6 import java.net.MalformedURLException;
7 import java.net.URL;
8
9
10 /**
11  * Class to handle the caching of map tiles from openstreetmap
12  */
13 public class MapTileCacher implements ImageObserver
14 {
15         /** Parent to be informed of updates */
16         private MapCanvas _parent = null;
17         /** Array of images to hold tiles */
18         private Image[] _tiles = new Image[GRID_SIZE * GRID_SIZE];
19         /** Current zoom level */
20         private int _zoom = -1;
21         /** X coordinate of central tile */
22         private int _tileX = -1;
23         /** Y coordinate of central tile */
24         private int _tileY = -1;
25         /** X coord of grid centre */
26         private int _gridCentreX = 0;
27         /** Y coord of grid centre */
28         private int _gridCentreY = 0;
29         /** Tile configuration */
30         private MapTileConfig _tileConfig = null;
31
32         /** Grid size */
33         private static final int GRID_SIZE = 11;
34         /** max zoom level of map tiles */
35         private static final int MAX_TILE_ZOOM = 18;
36
37
38         /**
39          * Constructor
40          * @param inParent parent canvas to be informed of updates
41          */
42         public MapTileCacher(MapCanvas inParent)
43         {
44                 _parent = inParent;
45         }
46
47         /**
48          * Recentre the map and clear the cache
49          * @param inZoom zoom level
50          * @param inTileX x coord of central tile
51          * @param inTileY y coord of central tile
52          */
53         public void centreMap(int inZoom, int inTileX, int inTileY)
54         {
55                 if (inZoom != _zoom)
56                 {
57                         _zoom = inZoom;
58                         clearAll();
59                 }
60                 _gridCentreX = getCacheCoordinate(_gridCentreX + inTileX - _tileX);
61                 _gridCentreY = getCacheCoordinate(_gridCentreY + inTileY - _tileY);
62                 _tileX = inTileX;
63                 _tileY = inTileY;
64                 // Mark boundaries as invalid
65                 for (int i=0; i<GRID_SIZE; i++)
66                 {
67                         _tiles[getArrayIndex(_tileX + GRID_SIZE/2 + 1, _tileY + i - GRID_SIZE/2)] = null;
68                         _tiles[getArrayIndex(_tileX + i - GRID_SIZE/2, _tileY + GRID_SIZE/2 + 1)] = null;
69                 }
70         }
71
72         /**
73          * Clear all the cached images
74          */
75         public void clearAll()
76         {
77                 // Clear all images if zoom changed
78                 for (int i=0; i<_tiles.length; i++) {
79                         _tiles[i] = null;
80                 }
81         }
82
83         /**
84          * @param inX x index of tile
85          * @param inY y index of tile
86          * @return selected tile if already loaded, or null otherwise
87          */
88         public Image getTile(int inX, int inY)
89         {
90                 if (_tileConfig == null) {_tileConfig = new MapTileConfig();}
91                 int arrayIndex = getArrayIndex(inX, inY);
92                 Image image = _tiles[arrayIndex];
93                 if (image != null)
94                 {
95                         // image already finished loading so return it
96                         return image;
97                 }
98
99                 // Protect against zoom > max
100                 if (isOverzoomed()) return null;
101
102                 // Trigger load if not already triggered
103                 // Work out tile coords for URL
104                 int urlX = getUrlCoordinate(inX, _zoom);
105                 int urlY = getUrlCoordinate(inY, _zoom);
106                 try
107                 {
108                         // Use configured tile server
109                         String url = _tileConfig.getUrl() + _zoom + "/" + urlX + "/" + urlY + ".png";
110                         // Load image asynchronously, using observer
111                         image = Toolkit.getDefaultToolkit().createImage(new URL(url));
112                         _tiles[arrayIndex] = image;
113                         if (image.getWidth(this) > 0) {return image;}
114                 }
115                 catch (MalformedURLException urle) {} // ignore
116                 return null;
117         }
118
119         /**
120          * @return true if zoom is too high for tiles
121          */
122         public boolean isOverzoomed()
123         {
124                 return (_zoom > MAX_TILE_ZOOM);
125         }
126
127         /**
128          * Get the array index for the given coordinates
129          * @param inX x coord of tile
130          * @param inY y coord of tile
131          * @return array index
132          */
133         private int getArrayIndex(int inX, int inY)
134         {
135                 //System.out.println("Getting array index for (" + inX + ", " + inY + ") where the centre is at ("  + _tileX + ", " + _tileY
136                 //      + ") and grid coords (" + _gridCentreX + ", " + _gridCentreY + ")");
137                 int x = getCacheCoordinate(inX - _tileX + _gridCentreX);
138                 int y = getCacheCoordinate(inY - _tileY + _gridCentreY);
139                 //System.out.println("Transformed to (" + x + ", " + y + ")");
140                 return (x + y * GRID_SIZE);
141         }
142
143         /**
144          * Transform a coordinate from map tiles to array coordinates
145          * @param inTile coordinate of tile
146          * @return coordinate in array (wrapping around cache grid)
147          */
148         private static int getCacheCoordinate(int inTile)
149         {
150                 int tile = inTile;
151                 while (tile >= GRID_SIZE) {tile -= GRID_SIZE;}
152                 while (tile < 0) {tile += GRID_SIZE;}
153                 return tile;
154         }
155
156         /**
157          * Make sure a url coordinate is within range
158          * @param inTile coordinate of tile in map system
159          * @param inZoom zoom factor
160          * @return coordinate for url (either vertical or horizontal)
161          */
162         private static int getUrlCoordinate(int inTile, int inZoom)
163         {
164                 int mapSize = 1 << inZoom;
165                 int coord = inTile;
166                 while (coord >= mapSize) {coord -= mapSize;}
167                 while (coord < 0) {coord += mapSize;}
168                 // coord is now between 0 and mapsize
169                 return coord;
170         }
171
172         /**
173          * Convert to string for debug
174          * @see java.lang.Object#toString()
175          */
176         public String toString()
177         {
178                 StringBuffer result = new StringBuffer("Grid centre (" + _gridCentreX + "," + _gridCentreY + ") - (" + _tileX + "," + _tileY + ")\n");
179                 for (int i=0; i<GRID_SIZE; i++)
180                 {
181                         for (int j=0; j<GRID_SIZE; j++) {
182                                 if (i == _gridCentreY && j == _gridCentreX) {
183                                         result.append(_tiles[j + i*GRID_SIZE] == null?"c":"C");
184                                 }
185                                 else {
186                                         result.append(_tiles[j + i*GRID_SIZE] == null?".":"*");
187                                 }
188                         }
189                         result.append("\n");
190                 }
191                 return result.toString();
192         }
193
194         /**
195          * Method called by image loader to inform of updates to the tiles
196          * @param img the image
197          * @param infoflags flags describing how much of the image is known
198          * @param x ignored
199          * @param y ignored
200          * @param width ignored
201          * @param height ignored
202          * @return false to carry on loading, true to stop
203          */
204         public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
205         {
206                 boolean loaded = (infoflags & ImageObserver.ALLBITS) > 0;
207                 boolean error = (infoflags & ImageObserver.ERROR) > 0;
208                 if (loaded || error) {
209                         _parent.tilesUpdated(loaded);
210                 }
211                 return !loaded;
212         }
213
214         /**
215          * Set or reset the tile config
216          * @param inConfig object containing tile config
217          */
218         public void setTileConfig(MapTileConfig inConfig)
219         {
220                 _tileConfig = inConfig;
221                 clearAll();
222         }
223 }