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