curtilage 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+
5
+ module Curtilage
6
+ # Optional machine-learned building footprints, for places OSM hasn't
7
+ # mapped. They are derived from imagery by ML, so they're opt-in: the build
8
+ # adds them only with ml_footprints:, and generation uses them only with
9
+ # buildings: :osm_filled or :ml.
10
+ module Footprints
11
+ class Error < StandardError; end
12
+
13
+ SOURCES = %w[microsoft].freeze
14
+
15
+ # Microsoft Global ML Building Footprints (ODbL, like OSM), published as
16
+ # gzipped GeoJSON lines in zoom-9 quadkey tiles.
17
+ MICROSOFT_HOST = "minedbuildings.z5.web.core.windows.net"
18
+ MICROSOFT_INDEX = "/global-buildings/dataset-links.csv"
19
+ MICROSOFT_PREFIX = "/global-buildings/"
20
+ ZOOM = 9
21
+ MAX_INDEX_BYTES = 50_000_000
22
+ MAX_TILE_BYTES = 500_000_000
23
+ MAX_TILES = 2_000
24
+
25
+ module_function
26
+
27
+ # Downloads the tiles covering bbox [min_lng, min_lat, max_lng, max_lat]
28
+ # into dir and returns their paths.
29
+ def microsoft(bbox, dir, log: $stderr)
30
+ keys = quadkeys(bbox, ZOOM)
31
+ rows = microsoft_index.select { |row| keys.include?(row[:quadkey]) }
32
+ raise Error, "#{rows.size} footprint tiles is more than #{MAX_TILES}" if rows.size > MAX_TILES
33
+
34
+ FileUtils.mkdir_p(dir)
35
+ log.puts "downloading #{rows.size} Microsoft footprint tiles"
36
+ rows.map do |row|
37
+ dest = File.join(dir, "#{row[:location]}-#{row[:quadkey]}-#{File.basename(row[:path])}")
38
+ File.file?(dest) ? dest : Download.fetch(MICROSOFT_HOST, row[:path], dest, max_bytes: MAX_TILE_BYTES)
39
+ end
40
+ end
41
+
42
+ # [{location:, quadkey:, path:}] from Microsoft's index. URLs pointing
43
+ # anywhere but Microsoft's footprint host are dropped.
44
+ def microsoft_index
45
+ csv = Download.read(MICROSOFT_HOST, MICROSOFT_INDEX, max_bytes: MAX_INDEX_BYTES)
46
+ parse_index(csv)
47
+ end
48
+
49
+ def parse_index(csv)
50
+ csv.each_line.drop(1).filter_map do |line|
51
+ location, quadkey, url = line.strip.split(",")
52
+ path = Download.path_on(url.to_s, MICROSOFT_HOST, MICROSOFT_PREFIX)
53
+ next unless path && location.to_s.match?(/\A[\w-]+\z/) && quadkey.to_s.match?(/\A[0-3]+\z/)
54
+
55
+ { location: location, quadkey: quadkey, path: path }
56
+ end
57
+ end
58
+
59
+ # Quadkeys of the web-map tiles at zoom covering the bounding box.
60
+ def quadkeys(bbox, zoom)
61
+ min_lng, min_lat, max_lng, max_lat = bbox
62
+ x0, y1 = tile(min_lng, min_lat, zoom)
63
+ x1, y0 = tile(max_lng, max_lat, zoom)
64
+ (x0..x1).flat_map { |x| (y0..y1).map { |y| quadkey(x, y, zoom) } }
65
+ end
66
+
67
+ def tile(lng, lat, zoom)
68
+ n = 2**zoom
69
+ lat = lat.clamp(-85.05, 85.05) * Math::PI / 180
70
+ x = ((lng + 180) / 360 * n).floor.clamp(0, n - 1)
71
+ y = ((1 - (Math.log(Math.tan(lat) + (1 / Math.cos(lat))) / Math::PI)) / 2 * n).floor.clamp(0, n - 1)
72
+ [x, y]
73
+ end
74
+
75
+ def quadkey(x, y, zoom)
76
+ (1..zoom).map do |i|
77
+ mask = 1 << (zoom - i)
78
+ (x.nobits?(mask) ? 0 : 1) + (y.nobits?(mask) ? 0 : 2)
79
+ end.join
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,578 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Curtilage
4
+ # Proposes a premises polygon for a pin from the OSM features around it.
5
+ #
6
+ # Methods are pure functions of (pin, features, options). Each returns a
7
+ # Result with the premises ring ([lng, lat], closed), the store zone (the
8
+ # building's own outline, always inside the premises), a step-by-step
9
+ # explanation, review flags and the validation result. Premises are convex,
10
+ # which keeps clipping simple and matches hand-drawn premises
11
+ # (near-rectangles that line up with the building).
12
+ #
13
+ # The lot steps live in generator_lot.rb and the store zone in
14
+ # generator_store.rb; they reopen this module.
15
+ #
16
+ # Compared against hand-drawn premises, grow_trim was the best method and
17
+ # building the best fallback. box is only a baseline: it crosses public
18
+ # roads on most sites, so propose never offers it.
19
+ module Generator
20
+ # ring: the premises. store_ring: the building's own outline (the store
21
+ # zone), or nil.
22
+ Result = Struct.new(:method_name, :ring, :store_ring, :explanation, :flags, :validation, :building, :attribution,
23
+ keyword_init: true) do
24
+ def ok?
25
+ !ring.nil? && validation.ok?
26
+ end
27
+
28
+ # A GeoJSON Feature (as a Hash) with everything about the result in
29
+ # its properties. Show the attribution wherever the polygon is shown.
30
+ # include_store: a FeatureCollection of the premises and the store
31
+ # zone instead, told apart by properties.role.
32
+ def to_geojson(attribution: self.attribution || ["© OpenStreetMap contributors"], include_store: false)
33
+ premises = {
34
+ type: "Feature",
35
+ geometry: ring && { type: "Polygon", coordinates: [ring] },
36
+ properties: {
37
+ role: "premises", ok: ok?, method: method_name, flags: flags, building: building,
38
+ errors: validation.errors, warnings: validation.warnings, metrics: validation.metrics,
39
+ explanation: explanation, attribution: attribution
40
+ },
41
+ }
42
+ return premises unless include_store
43
+
44
+ store = { type: "Feature", geometry: store_ring && { type: "Polygon", coordinates: [store_ring] },
45
+ properties: { role: "store", building: building, attribution: attribution } }
46
+ { type: "FeatureCollection", features: [premises, store] }
47
+ end
48
+ end
49
+
50
+ # What the parking steps need about the site being generated.
51
+ Site = Struct.new(:features, :target, :opts, :log)
52
+
53
+ # Notes explain each step; flags are reasons a person should look first.
54
+ Log = Struct.new(:notes, :flags) do
55
+ def note(text) = notes << text
56
+
57
+ def flag(name, text)
58
+ flags << name unless flags.include?(name)
59
+ notes << text
60
+ end
61
+ end
62
+
63
+ METHODS = %i[grow_trim building box].freeze
64
+ CHAIN = %i[grow_trim building].freeze
65
+
66
+ PUBLIC_HIGHWAYS = %w[
67
+ motorway trunk primary secondary tertiary unclassified residential
68
+ motorway_link trunk_link primary_link secondary_link tertiary_link
69
+ ].freeze
70
+
71
+ # Roughly half a carriageway (lanes, turn lane, kerb) by road class, so
72
+ # premises stop near the kerb rather than mid-street. The shapefiles carry
73
+ # no width or lane count, so this is a typical figure, not a measurement.
74
+ ROAD_HALF_WIDTH_M = {
75
+ "motorway" => 12, "trunk" => 10, "primary" => 9, "secondary" => 8, "tertiary" => 7,
76
+ "unclassified" => 5, "residential" => 5, "link" => 5,
77
+ # Railways: the track bed plus clearance to the lineside fence.
78
+ "rail" => 5, "light_rail" => 4, "subway" => 4, "narrow_gauge" => 3
79
+ }.freeze
80
+
81
+ # A driveway reaches a public road when it comes this close to one.
82
+ ENTRANCE_MAX_M = 15
83
+ # How far beyond the lot a driveway is followed toward the street.
84
+ ENTRANCE_REACH_M = 25
85
+
86
+ # Building types (OSM building=*) that are homes: the lot never takes
87
+ # their yards (see home? and behind_home?).
88
+ HOUSE_TYPES = %w[house detached residential semidetached_house terrace bungalow static_caravan cabin
89
+ apartments].freeze
90
+ # Structures that are part of a site's lot when next to its building:
91
+ # parking garages, carports and canopies (drive-throughs, fuel pumps).
92
+ LOT_TYPES = %w[parking carport roof].freeze
93
+
94
+ DEFAULTS = {
95
+ building_max_distance_m: 30, # use the nearest building only this close
96
+ large_building_m2: 5_000, # flag: likely shared (strip mall, multi-tenant)
97
+ large_building_note_m2: 1_500, # explanation only, no flag: may be shared
98
+ pin_clearance_m: 5, # keep this much room around the pin
99
+ building_clearance_m: 3, # road trims stop at least this far from the building
100
+ grow_m: 30, # grow_trim: how far to grow before trimming
101
+ road_offset_m: nil, # trim this far short of road centrelines; nil: by road class
102
+ neighbour_min_area_m2: 40, # grow_trim: smaller buildings (sheds) don't bound a lot
103
+ neighbour_gap_m: 3, # grow_trim: strip left to a neighbouring building (nil: halfway)
104
+ neighbour_strip_min_area_m2: 0, # grow_trim: smaller neighbours are split halfway
105
+ house_max_m2: 250, # an untyped building smaller than this, among others, may be a home
106
+ house_street_m: 25, # ... when two more small buildings are this close
107
+ parking_reach_m: 20, # grow_trim: parking this close (an aisle and a walkway) is its lot
108
+ shared_lot_buildings: 3, # grow_trim: a lot touching this many other buildings is shared
109
+ small_building_m2: 50, # flag: a building this small may be a kiosk or shed, not the site
110
+ parking_max_extent_m: 60, # grow_trim: claim parking at most this far from the building
111
+ building_margin_m: 20, # building: margin around its rectangle
112
+ box_side_m: 60, # box: side of the square around the pin
113
+ max_vertices: 10, # the premises are simplified to at most this many corners
114
+ store_zone: true, # also return the building's outline as the store zone
115
+ max_store_vertices: 20, # the store outline is simplified to at most this many corners
116
+ buildings: :osm, # :osm, :osm_filled (ML footprints where OSM has none) or :ml
117
+ scope: :site, # :site, or :centre (the whole shopping centre when on a shared lot)
118
+ }.freeze
119
+
120
+ BUILDING_SOURCES = %i[osm osm_filled ml].freeze
121
+ SCOPES = %i[site centre].freeze
122
+
123
+ module_function
124
+
125
+ # The recommended path: grow_trim, falling back to building when its
126
+ # result fails validation. Returns the first valid result, else the last
127
+ # attempt (not ok?, with every attempt's explanation).
128
+ def propose(pin, features, **)
129
+ features = Features.new(pin, features) unless features.is_a?(Features)
130
+ failures = []
131
+ CHAIN.each do |method|
132
+ result = generate(method, pin, features, **)
133
+ if result.ok?
134
+ unless failures.empty?
135
+ result.flags.unshift(:fallback)
136
+ result.explanation.unshift(*failures)
137
+ end
138
+ return result
139
+ end
140
+ failures << "#{method} failed (#{failure_reason(result)})"
141
+ return result.tap { |r| r.explanation = failures + r.explanation } if method == CHAIN.last
142
+ end
143
+ end
144
+
145
+ # One method, no fallback. features: a Curtilage::Features or the raw list.
146
+ def generate(method, pin, features, **options)
147
+ raise ArgumentError, "unknown method #{method.inspect}" unless METHODS.include?(method)
148
+
149
+ opts = DEFAULTS.merge(options)
150
+ unless SCOPES.include?(opts[:scope])
151
+ raise ArgumentError,
152
+ "unknown scope: #{opts[:scope].inspect} (have: site, centre)"
153
+ end
154
+ unless BUILDING_SOURCES.include?(opts[:buildings])
155
+ raise ArgumentError, "unknown buildings: #{opts[:buildings].inspect} (have: #{BUILDING_SOURCES.join(", ")})"
156
+ end
157
+
158
+ features = Features.new(pin, features) unless features.is_a?(Features)
159
+ features = choose_buildings(features, opts[:buildings])
160
+ log = Log.new([], [])
161
+ log.note("dropped #{features.dropped} unusable OSM features") if features.dropped.positive?
162
+ xy, target = send(method, features, opts, log)
163
+ finish(method, pin, [xy, target], log, opts)
164
+ end
165
+
166
+ # The building flavour: OSM only (default), OSM filled in with ML
167
+ # footprints that don't overlap any OSM building, or ML footprints only.
168
+ def choose_buildings(features, source)
169
+ case source
170
+ when :osm then features
171
+ when :ml then features.with_buildings(features.ml_buildings)
172
+ else
173
+ extra = features.ml_buildings.reject do |m|
174
+ features.buildings.any? { |b| b.near?(m) && Geometry.overlap?(b.hull, m.hull) }
175
+ end
176
+ features.with_buildings(features.buildings + extra)
177
+ end
178
+ end
179
+
180
+ def finish(method, pin, shape, log, opts)
181
+ xy, target = shape
182
+ result = Result.new(method_name: method, explanation: log.notes, flags: log.flags, building: target&.id)
183
+ unless xy
184
+ result.validation = Validation.check(pin, nil)
185
+ return result
186
+ end
187
+
188
+ premises = premises_xy(xy, target, opts, log)
189
+ result.ring = ring_of(premises, pin)
190
+ result.store_ring = ring_of(store_xy(target, premises, opts, log), pin) if target && opts[:store_zone]
191
+ result.validation = Validation.check(pin, result.ring)
192
+ result
193
+ end
194
+
195
+ # The premises always hold the whole building (the store zone has to
196
+ # sit inside them): widened to take it in if needed, and simplified only
197
+ # in ways that keep it.
198
+ def premises_xy(xy, target, opts, log)
199
+ xy = Geometry.clean(Geometry.counter_clockwise(xy))
200
+ if target && !target.hull.all? { |p| inside?(xy, p) }
201
+ log.note("widened the premises to take in the whole building")
202
+ xy = Geometry.counter_clockwise(Geometry.convex_hull(xy + target.hull))
203
+ end
204
+ return xy if xy.size <= opts[:max_vertices]
205
+
206
+ log.note("simplified #{xy.size} vertices to at most #{opts[:max_vertices]}")
207
+ Geometry.simplify_containing(xy, opts[:max_vertices], target ? target.hull : [])
208
+ end
209
+
210
+ def inside?(xy, point)
211
+ Geometry.contains?(xy, point) || Geometry.distance_to_edges(xy, point) < 0.01
212
+ end
213
+
214
+ def ring_of(xy, pin)
215
+ ring = Geometry.unproject(xy, pin).map { |lng, lat| [lng.round(7), lat.round(7)] }
216
+ ring << ring.first
217
+ end
218
+
219
+ def failure_reason(result)
220
+ return result.explanation.last if result.ring.nil?
221
+
222
+ result.validation.errors.join(", ")
223
+ end
224
+
225
+ # Grow from the building toward its lot; trim at public roads and
226
+ # railways (the premises never cross one) and short of neighbouring
227
+ # buildings; then take in the site's parking, garages, canopies and
228
+ # driveways (generator_lot.rb).
229
+ def grow_trim(features, opts, log)
230
+ target = find_building(features, opts, log)
231
+ return [nil, nil] unless target
232
+
233
+ poly = trim_at_roads(grown(target, opts, log), features, target, opts, log)
234
+ lots = own_parking(features, target, opts, log)
235
+ shared = lots.select { |lot| lot.instance_variable_get(:@shared) }
236
+ return [centre(shared, Site.new(features, target, opts, log)), target] if opts[:scope] == :centre && shared.any?
237
+
238
+ claimed = lots.select { |lot| lot.kind == "building" }
239
+ features = features.with_buildings(features.buildings - claimed) unless claimed.empty?
240
+ poly = trim_at_neighbours(poly, features, target, opts, log)
241
+ poly = add_parking(poly, lots, Site.new(features, target, opts, log)) unless lots.empty?
242
+ [poly, target]
243
+ end
244
+
245
+ def neighbours(features, target, opts)
246
+ features.buildings.reject { |b| b.equal?(target) || b.area < opts[:neighbour_min_area_m2] }
247
+ end
248
+
249
+ # The building's minimum rectangle plus a margin, trimmed at public
250
+ # roads (premises never cross one).
251
+ def building(features, opts, log)
252
+ target = find_building(features, opts, log)
253
+ return [nil, nil] unless target
254
+
255
+ rect = Geometry.minimum_rectangle(target.xy)
256
+ log.note("building rectangle grown by #{opts[:building_margin_m]} m")
257
+ box = Geometry.oriented_box(rect[:corners], rect[:angle], opts[:building_margin_m])
258
+ poly = Geometry.counter_clockwise(Geometry.convex_hull(box + pin_square(opts)))
259
+ [trim_at_roads(poly, features, target, opts, log), target]
260
+ end
261
+
262
+ # A square around the pin: the baseline the other methods must beat.
263
+ def box(_features, opts, log)
264
+ half = opts[:box_side_m] / 2.0
265
+ log.note("square of #{opts[:box_side_m]} m around the pin")
266
+ [[[-half, -half], [half, -half], [half, half], [-half, half]], nil]
267
+ end
268
+
269
+ def grown(target, opts, log)
270
+ rect = target.rectangle
271
+ log.note("grew the building rectangle by #{opts[:grow_m]} m")
272
+ box = Geometry.oriented_box(rect[:corners], rect[:angle], opts[:grow_m])
273
+ Geometry.counter_clockwise(Geometry.convex_hull(box + pin_square(opts)))
274
+ end
275
+
276
+ # The smallest building under the pin, else the nearest one close enough.
277
+ # Flags a large one: the site may be one unit of it.
278
+ def find_building(features, opts, log)
279
+ target = building_under_pin(features, log) || nearest_building(features, opts, log)
280
+ if target&.kind == "ml_building"
281
+ log.flag(:ml_footprint, "building #{target.id} is a machine-learned footprint, not mapped in OSM: " \
282
+ "check it exists")
283
+ end
284
+ if target && target.area < opts[:small_building_m2]
285
+ log.flag(:small_building, "building is only #{target.area.round} m2: check it's the site " \
286
+ "(a kiosk or drive-through), not a shed or canopy next to it")
287
+ end
288
+ if target && target.area > opts[:large_building_m2]
289
+ log.flag(:large_building, "building is over #{opts[:large_building_m2]} m2: if it's shared " \
290
+ "(strip mall, several tenants), check which part is the site")
291
+ elsif target && target.area > opts[:large_building_note_m2]
292
+ log.note("building is #{target.area.round} m2: large enough that it may be shared")
293
+ end
294
+ target
295
+ end
296
+
297
+ def building_under_pin(features, log)
298
+ target = features.buildings.select { |b| Geometry.contains?(b.xy, [0.0, 0.0]) }.min_by(&:area)
299
+ log.note("building #{target.id} is under the pin (#{target.area.round} m2)") if target
300
+ target
301
+ end
302
+
303
+ # A tiny structure (a canopy or kiosk roof) right by the pin loses to a
304
+ # real building in reach: the canopy then counts as part of the lot.
305
+ def nearest_building(features, opts, log)
306
+ in_reach = features.buildings.map { |b| [Geometry.distance_to_edges(b.xy, [0.0, 0.0]), b] }
307
+ .select { |d, _| d <= opts[:building_max_distance_m] }
308
+ real = in_reach.reject { |_, b| b.area < opts[:small_building_m2] }
309
+ distance, target = (real.empty? ? in_reach : real).min_by(&:first)
310
+ if target
311
+ log.flag(:building_not_under_pin, "no building under the pin; using building #{target.id}, " \
312
+ "#{distance.round} m away (#{target.area.round} m2)")
313
+ target
314
+ else
315
+ log.note("no building within #{opts[:building_max_distance_m]} m of the pin")
316
+ nil
317
+ end
318
+ end
319
+
320
+ # Cuts along each public road's stretch beside the site, following its
321
+ # overall direction: premises line up with the kerb, which may be at an
322
+ # angle to the building. A stretch within ROAD_SNAP_DEG of a building side
323
+ # is snapped square to it, so short bends at junctions average out.
324
+ #
325
+ # Stretches are applied nearest first: once the nearest road has trimmed
326
+ # the polygon, a road beyond it (say the far side of a junction) no
327
+ # longer reaches it, so its extended line can't slice across the lot.
328
+ def trim_at_roads(poly, features, target, opts, log)
329
+ road_stretches(features, target, opts).each do |road, run, offset|
330
+ next unless run.any? { |p| Geometry.contains?(poly, p) || Geometry.distance_to_edges(poly, p) < offset }
331
+
332
+ trimmed, used = trim_along(poly, fit_direction(run, target), target, offset, opts[:building_clearance_m])
333
+ next log.note("kept the part beyond #{road_label(road)}: it would cut the building") unless trimmed
334
+ next if trimmed.size < 3
335
+
336
+ label = "trimmed at #{road_label(road)}, #{used.round} m short of its centreline"
337
+ log.note(label) unless log.notes.include?(label)
338
+ poly = trimmed
339
+ end
340
+ poly
341
+ end
342
+
343
+ # [road, stretch points, offset] for every public road and railway near
344
+ # the building, nearest stretch first.
345
+ def road_stretches(features, target, opts)
346
+ (features.roads.select { |road| PUBLIC_HIGHWAYS.include?(road.highway) } + features.railways)
347
+ .flat_map { |road| road_runs(road, target).map { |run| [road, run, road_offset(road, opts)] } }
348
+ .sort_by { |_, run, _| run.map { |p| Geometry.distance_to_edges(target.hull, p) }.min }
349
+ end
350
+
351
+ ROAD_REACH_M = 60 # only the road this close to the building bounds the site
352
+ ROAD_BEND_DEG = 30 # a sharper turn starts a new stretch
353
+ ROAD_SNAP_DEG = 5 # a stretch this close to a building side is squared to it
354
+
355
+ # Points every 2 m along the road within reach of the building, split
356
+ # into stretches wherever the road turns by more than ROAD_BEND_DEG.
357
+ def road_runs(road, target)
358
+ runs = []
359
+ run = nil
360
+ road.xy.each_cons(2) do |a, b|
361
+ heading = Math.atan2(b[1] - a[1], b[0] - a[0]) % Math::PI
362
+ samples(a, b).each do |p|
363
+ if Geometry.distance_to_edges(target.hull, p) > ROAD_REACH_M
364
+ run = nil
365
+ next
366
+ end
367
+ if run.nil? || angle_between(run[:heading], heading) > ROAD_BEND_DEG * Math::PI / 180
368
+ run = { heading: heading, points: [] }
369
+ runs << run
370
+ end
371
+ run[:points] << p
372
+ end
373
+ end
374
+ runs.map { |r| r[:points] }.select { |pts| pts.size >= 2 }
375
+ end
376
+
377
+ def samples(a, b)
378
+ n = [(Math.hypot(b[0] - a[0], b[1] - a[1]) / 2).ceil, 1].max
379
+ (0..n).map { |i| Geometry.lerp(a, b, i.fdiv(n)) }
380
+ end
381
+
382
+ # Smallest angle between two undirected headings (radians, mod pi).
383
+ def angle_between(first, second)
384
+ d = (first - second).abs % Math::PI
385
+ [d, Math::PI - d].min
386
+ end
387
+
388
+ # [centroid, unit direction] of the stretch's best-fit line, snapped to a
389
+ # building side when nearly parallel.
390
+ def fit_direction(points, target)
391
+ centre = Geometry.centroid(points)
392
+ heading = principal_heading(points, centre)
393
+ axis = target.rectangle[:angle]
394
+ 2.times do |k|
395
+ side = axis + (k * Math::PI / 2)
396
+ heading = side if angle_between(heading % Math::PI, side % Math::PI) <= ROAD_SNAP_DEG * Math::PI / 180
397
+ end
398
+ [centre, [Math.cos(heading), Math.sin(heading)]]
399
+ end
400
+
401
+ # Direction of greatest spread (the first principal axis), in radians.
402
+ def principal_heading(points, centre)
403
+ cx, cy = centre
404
+ sxx = points.sum { |x, _| (x - cx)**2 }
405
+ syy = points.sum { |_, y| (y - cy)**2 }
406
+ sxy = points.sum { |x, y| (x - cx) * (y - cy) }
407
+ 0.5 * Math.atan2(2 * sxy, sxx - syy)
408
+ end
409
+
410
+ # Clips at the line, moved toward the pin by up to offset metres but
411
+ # never closer than clearance metres to the building (the pavement in
412
+ # front of a building on the street stays in the premises). Returns
413
+ # [polygon, offset used], [poly, 0] when the pin is on the line, or nil
414
+ # when the centreline itself would cut the building.
415
+ def trim_along(poly, line, target, offset, clearance = 0)
416
+ origin, direction = line
417
+ normal = [direction[1], -direction[0]]
418
+ pin_side = side([0.0, 0.0], origin, normal)
419
+ return [poly, 0] if pin_side.abs < 1e-6
420
+
421
+ normal = normal.map(&:-@) if pin_side.positive?
422
+ building_side = target.hull.map { |p| side(p, origin, normal) }.max
423
+ return nil if building_side > 0.5
424
+
425
+ offset = offset.clamp(0, [-building_side - clearance, 0].max)
426
+ origin = [origin[0] - (normal[0] * offset), origin[1] - (normal[1] * offset)]
427
+ [Geometry.clip_half_plane(poly, origin, normal), offset]
428
+ end
429
+
430
+ # Half the road's width when the caller gives no fixed offset.
431
+ def road_offset(road, opts)
432
+ opts[:road_offset_m] || ROAD_HALF_WIDTH_M.fetch(road.highway, ROAD_HALF_WIDTH_M["link"])
433
+ end
434
+
435
+ def trim_at_neighbours(poly, features, target, opts, log)
436
+ hull = target.hull
437
+ area = Geometry.bounds(poly)
438
+ neighbours(features, target, opts).each do |other|
439
+ next unless Geometry.bounds_near?(area, other.bounds)
440
+
441
+ other_hull = other.hull
442
+ next unless Geometry.overlap?(other_hull, poly)
443
+
444
+ if Geometry.overlap?(other_hull, hull)
445
+ log.note("building #{other.id} touches the building, so it can't be split off")
446
+ next
447
+ end
448
+ home = home?(other, features, opts) && (behind_home?(other, target, features) ? :behind : :beside)
449
+ other.instance_variable_set(:@home, home)
450
+ strip = neighbour_strip(other, opts)
451
+ trimmed = split_from_neighbour(poly, hull, other_hull, target.rectangle[:angle], stop: strip_stop(strip))
452
+ next if trimmed.size < 3
453
+
454
+ explain_cut(log, other, strip)
455
+ poly = trimmed
456
+ end
457
+ poly
458
+ end
459
+
460
+ HALFWAY = ->(near, far) { (near + far) / 2 }
461
+
462
+ def explain_cut(log, other, strip)
463
+ case other.instance_variable_get(:@home)
464
+ when :behind
465
+ log.flag(:near_houses, "the lot backs onto a home (building #{other.id}): split halfway, " \
466
+ "check where its yard starts")
467
+ when :beside
468
+ log.flag(:near_houses, "the lot runs beside a home (building #{other.id}), stopping " \
469
+ "#{strip} m short of it: check the property line")
470
+ else
471
+ log.note(strip ? "stopped #{strip} m short of building #{other.id}" : "split halfway to building #{other.id}")
472
+ end
473
+ end
474
+
475
+ # The strip left to a neighbour, or nil to split halfway. Pavement
476
+ # between two buildings usually belongs to one of them, and the site's
477
+ # own lot is the likelier owner, so claim it up to a narrow strip.
478
+ # Small neighbours (houses, below neighbour_strip_min_area_m2) keep the
479
+ # halfway split: their yard isn't the site's.
480
+ def neighbour_strip(other, opts)
481
+ gap = opts[:neighbour_gap_m]
482
+ return nil if other.instance_variable_get(:@home) == :behind
483
+
484
+ gap if gap && other.area >= opts[:neighbour_strip_min_area_m2]
485
+ end
486
+
487
+ # A home: typed as one, or (untyped, as mappers often leave it) a small
488
+ # building with other small buildings close by, like a residential street.
489
+ def home?(other, features, opts)
490
+ return true if HOUSE_TYPES.include?(other.category)
491
+ return false if other.category || other.area >= opts[:house_max_m2]
492
+
493
+ small = features.buildings.count do |b|
494
+ !b.equal?(other) && b.category.nil? && b.area < opts[:house_max_m2] && b.near?(other, opts[:house_street_m])
495
+ end
496
+ small >= 2
497
+ end
498
+
499
+ # Whether the site is behind the home: across its back yard, judged by
500
+ # which way the home faces its nearest street. Beside or in front of a
501
+ # home, the lot runs up to the usual strip; behind it, only halfway.
502
+ def behind_home?(home, target, features)
503
+ centre = Geometry.centroid(home.hull)
504
+ street = nearest_street_point(centre, features)
505
+ return true unless street
506
+
507
+ front = [street[0] - centre[0], street[1] - centre[1]]
508
+ site = Geometry.centroid(target.hull).zip(centre).map { |a, b| a - b }
509
+ cosine = Geometry.dot(front, site) / ((Math.hypot(*front) * Math.hypot(*site)) + 1e-9)
510
+ cosine < -0.5
511
+ end
512
+
513
+ def nearest_street_point(point, features)
514
+ roads = features.roads.select { |r| PUBLIC_HIGHWAYS.include?(r.highway) }
515
+ points = roads.flat_map do |road|
516
+ road.xy.each_cons(2).map { |a, b| Geometry.closest_point_on_segment(point, a, b) }
517
+ end
518
+ points.min_by { |p| Math.hypot(p[0] - point[0], p[1] - point[1]) }
519
+ end
520
+
521
+ # Never less than halfway: a narrow gap is still split down the middle.
522
+ def strip_stop(strip)
523
+ return HALFWAY unless strip
524
+
525
+ ->(near, far) { [(near + far) / 2, far - strip].max }
526
+ end
527
+
528
+ # Cuts between the building and a neighbour (halfway by default), square
529
+ # to one of the building's sides (hand-drawn premises are rectangles): of
530
+ # the sides facing the neighbour with a clear gap, the cut that keeps the
531
+ # most lot. Falls back to a cut across the line between their nearest
532
+ # points.
533
+ def split_from_neighbour(poly, hull, other, angle, stop: HALFWAY)
534
+ cuts = 4.times.filter_map { |k| square_cut(poly, hull, other, angle + (k * Math::PI / 2), stop) }
535
+ return cuts.max_by { |c| c.size >= 3 ? Geometry.area(c) : 0 } unless cuts.empty?
536
+
537
+ diagonal_cut(poly, hull, other, stop)
538
+ end
539
+
540
+ def diagonal_cut(poly, hull, other, stop)
541
+ _, p, q = Geometry.closest_points(hull, other)
542
+ normal = [q[0] - p[0], q[1] - p[1]]
543
+ length = Math.hypot(*normal)
544
+ return poly if length < 1e-6
545
+
546
+ normal = normal.map { |v| v / length }
547
+ at = stop.call(Geometry.dot(p, normal), Geometry.dot(q, normal))
548
+ Geometry.clip_half_plane(poly, [normal[0] * at, normal[1] * at], normal)
549
+ end
550
+
551
+ # The cut facing direction (radians) where stop puts it in the gap, or
552
+ # nil when the buildings overlap along that direction.
553
+ def square_cut(poly, hull, other, direction, stop)
554
+ normal = [Math.cos(direction), Math.sin(direction)]
555
+ near = hull.map { |p| Geometry.dot(p, normal) }.max
556
+ far = other.map { |p| Geometry.dot(p, normal) }.min
557
+ return nil unless far > near
558
+
559
+ at = stop.call(near, far)
560
+ Geometry.clip_half_plane(poly, [normal[0] * at, normal[1] * at], normal)
561
+ end
562
+
563
+ def side(point, origin, normal)
564
+ ((point[0] - origin[0]) * normal[0]) + ((point[1] - origin[1]) * normal[1])
565
+ end
566
+
567
+ def pin_square(opts)
568
+ c = opts[:pin_clearance_m]
569
+ [[-c, -c], [c, -c], [c, c], [-c, c]]
570
+ end
571
+
572
+ def road_label(road)
573
+ kind = PUBLIC_HIGHWAYS.include?(road.highway) ? "road" : "railway"
574
+ name = road.name.to_s.empty? ? "#{kind} #{road.id}" : road.name
575
+ "#{name} (#{road.highway})"
576
+ end
577
+ end
578
+ end