]> git.openstreetmap.org Git - chef.git/blob - cookbooks/tile/files/default/ruby/expire.rb
Merge remote-tracking branch 'github/pull/422'
[chef.git] / cookbooks / tile / files / default / ruby / expire.rb
1 #!/usr/bin/ruby
2
3 require "rubygems"
4 require "proj4"
5 require "xml/libxml"
6 require "set"
7 require "time"
8
9 module Expire
10   # projection object to go from latlon -> spherical mercator
11   PROJ = Proj4::Projection.new(["+proj=merc", "+a=6378137", "+b=6378137",
12                                 "+lat_ts=0.0", "+lon_0=0.0", "+x_0=0.0",
13                                 "+y_0=0", "+k=1.0", "+units=m",
14                                 "+nadgrids=@null", "+no_defs +over"])
15
16   # width/height of the spherical mercator projection
17   SIZE = 40075016.6855784
18   # the size of the meta tile blocks
19   METATILE = 8
20   # the directory root for meta tiles
21   HASH_ROOT = "/tiles/default/".freeze
22   # node cache file
23   NODE_CACHE_FILE = "/store/database/nodes".freeze
24
25   # turns a spherical mercator coord into a tile coord
26   def self.tile_from_merc(point, zoom)
27     # renormalise into unit space [0,1]
28     point.x = 0.5 + point.x / SIZE
29     point.y = 0.5 - point.y / SIZE
30     # transform into tile space
31     point.x = point.x * 2**zoom
32     point.y = point.y * 2**zoom
33     # chop of the fractional parts
34     [point.x.to_int, point.y.to_int, zoom]
35   end
36
37   # turns a latlon -> tile x,y given a zoom level
38   def self.tile_from_latlon(latlon, zoom)
39     # first convert to spherical mercator
40     point = PROJ.forward(latlon)
41     tile_from_merc(point, zoom)
42   end
43
44   # this must match the definition of xyz_to_meta in mod_tile
45   def self.xyz_to_meta(x, y, z)
46     # mask off the final few bits
47     x &= ~(METATILE - 1)
48     y &= ~(METATILE - 1)
49     # generate the path
50     hash_path = (0..4).collect do |i|
51       (((x >> 4 * i) & 0xf) << 4) | ((y >> 4 * i) & 0xf)
52     end.reverse.join("/")
53     z.to_s + "/" + hash_path + ".meta"
54   end
55
56   # time to reset to, some very stupidly early time, before OSM started
57   EXPIRY_TIME = Time.parse("2000-01-01 00:00:00")
58
59   # expire the meta tile by setting the modified time back
60   def self.expire_meta(meta)
61     puts "Expiring #{meta}"
62     File.utime(EXPIRY_TIME, EXPIRY_TIME, meta)
63   end
64
65   def self.expire(change_file, min_zoom, max_zoom, tile_dirs)
66     do_expire(change_file, min_zoom, max_zoom) do |set|
67       new_set = Set.new
68       meta_set = Set.new
69
70       # turn all the tiles into expires, putting them in the set
71       # so that we don't expire things multiple times
72       set.each do |xy|
73         # this has to match the routine in mod_tile
74         meta = xyz_to_meta(xy[0], xy[1], xy[2])
75
76         # check each style working out what needs expiring
77         tile_dirs.each do |tile_dir|
78           meta_set.add(tile_dir + "/" + meta) if File.exist?(tile_dir + "/" + meta)
79         end
80
81         # add the parent into the set for the next round
82         new_set.add([xy[0] / 2, xy[1] / 2, xy[2] - 1])
83       end
84
85       # expire all meta tiles
86       meta_set.each do |meta|
87         expire_meta(meta)
88       end
89
90       # return the new set, consisting of all the parents
91       new_set
92     end
93   end
94
95   def self.do_expire(change_file, min_zoom, max_zoom, &_)
96     # read in the osm change file
97     doc = XML::Document.file(change_file)
98
99     # hash map to contain all the nodes
100     nodes = {}
101
102     # we put all the nodes into the hash, as it doesn't matter whether the node was
103     # added, deleted or modified - the tile will need updating anyway.
104     doc.find("//node").each do |node|
105       lat = node["lat"].to_f
106       lat = -85 if lat < -85
107       lat = 85 if lat > 85
108       point = Proj4::Point.new(Math::PI * node["lon"].to_f / 180,
109                                Math::PI * lat / 180)
110       nodes[node["id"].to_i] = tile_from_latlon(point, max_zoom)
111     end
112
113     # now we look for all the ways that have changed and put all of their nodes into
114     # the hash too. this will add too many nodes, as it is possible a long way will be
115     # changed at only a portion of its length. however, due to the non-local way that
116     # mapnik does text placement, it may stil not be enough.
117     #
118     # also, we miss cases where nodes are deleted from ways where that node is not
119     # itself deleted and the coverage of the point set isn't enough to encompass the
120     # change.
121     node_cache = NodeCache.new(NODE_CACHE_FILE)
122     doc.find("//way/nd").each do |node|
123       node_id = node["ref"].to_i
124
125       next if nodes.include? node_id
126
127       # this is a node referenced but not added, modified or deleted, so it should
128       # still be in the node cache.
129       if (entry = node_cache[node_id])
130         point = Proj4::Point.new(entry.lon, entry.lat)
131         nodes[node_id] = tile_from_merc(point, max_zoom)
132       end
133     end
134     node_cache.close
135
136     # create a set of all the tiles at the maximum zoom level which are touched by
137     # any of the nodes we've collected. we'll create the tiles at other zoom levels
138     # by a simple recursion.
139     set = Set.new nodes.values
140
141     # expire tiles and shrink to the set of parents
142     max_zoom.downto(min_zoom) do |_|
143       # allow the block to work on the set, returning the set at the next
144       # zoom level
145       set = yield set
146     end
147   end
148
149   # wrapper to access the osm2pgsql node cache
150   class NodeCache
151     # node cache entry
152     class Node
153       attr_reader :lon, :lat
154
155       def initialize(lon, lat)
156         @lat = lat.to_f / 100.0
157         @lon = lon.to_f / 100.0
158       end
159     end
160
161     # open the cache
162     def initialize(filename)
163       @cache = File.new(filename, "r")
164
165       throw "Unexpected format" unless @cache.sysread(4).unpack("l").first == 1
166       throw "Unexpected ID size" unless @cache.sysread(4).unpack("l").first == 8
167
168       @max_id = @cache.sysread(8).unpack("q").first
169     end
170
171     # close the cache
172     def close
173       @cache.close
174     end
175
176     # lookup a node
177     def [](id)
178       if id <= @max_id
179         offset = 16 + id * 8
180
181         @cache.sysseek(offset)
182
183         lon, lat = @cache.sysread(8).unpack("ll")
184
185         node = Node.new(lon, lat) if lon != -2147483648 && lat != -2147483648
186       end
187
188       node
189     end
190   end
191 end