#!/usr/bin/env python3 """Découpe les bâtiments OpenStreetMap (réponse Overpass JSON, `out geom tags`) en dalles de 1 km pour l'app AR Boucle du Hainaut (www/data/bat/). Usage : python3 tools/build_building_tiles.py corridor.json www/data/bat Projection : identique à l'app (équirectangulaire, R = 6371008.8 m, LAT0 = 50.6°). Chaque bâtiment est rangé dans la dalle qui contient le centre de son emprise. Hauteur : tag `height` si présent, sinon `building:levels` × 3 m + 2 m de toiture, sinon une valeur par défaut selon le type de bâtiment. Données © contributeurs OpenStreetMap, licence ODbL. """ import json, math, os, sys, re, datetime R = 6371008.8 K = math.cos(math.radians(50.6)) TILE = 1000 DEFAULT_H = { 'house': 8, 'detached': 8, 'semidetached_house': 8, 'terrace': 8, 'residential': 9, 'bungalow': 5, 'apartments': 13, 'farm': 8, 'farm_auxiliary': 7, 'barn': 9, 'stable': 6, 'cowshed': 6, 'garage': 3, 'garages': 3, 'carport': 3, 'shed': 3, 'hut': 3, 'greenhouse': 3, 'roof': 4, 'kiosk': 3, 'industrial': 11, 'warehouse': 11, 'commercial': 10, 'retail': 8, 'office': 12, 'school': 10, 'church': 20, 'chapel': 8, 'cathedral': 30, 'public': 10, 'hospital': 15, 'yes': 7, } def proj(lon, lat): return R * K * math.radians(lon), R * math.radians(lat) def num(v): m = re.match(r'\s*([0-9]+(?:[.,][0-9]+)?)', v or '') return float(m.group(1).replace(',', '.')) if m else None def height(tags): h = num(tags.get('height')) if h and 2 <= h <= 200: return h lv = num(tags.get('building:levels')) if lv and 0 < lv < 60: return lv * 3 + 2 return DEFAULT_H.get(tags.get('building'), 7) def rings(el): if el['type'] == 'way' and 'geometry' in el: yield el['geometry'] elif el['type'] == 'relation': for m in el.get('members', []): if m.get('role') == 'outer' and 'geometry' in m: yield m['geometry'] def main(src, out): data = json.load(open(src)) tiles = {} n = 0 for el in data['elements']: tags = el.get('tags', {}) if tags.get('building') in (None, 'no') or tags.get('location') == 'underground': continue h = round(height(tags), 1) for g in rings(el): pts = [proj(p['lon'], p['lat']) for p in g] if len(pts) > 1 and pts[0] == pts[-1]: pts = pts[:-1] if len(pts) < 3: continue cx = sum(p[0] for p in pts) / len(pts); cy = sum(p[1] for p in pts) / len(pts) kx, ky = math.floor(cx / TILE), math.floor(cy / TILE) ox, oy = kx * TILE, ky * TILE flat = [] for x, y in pts: flat += [round((x - ox) * 10), round((y - oy) * 10)] # décimètres depuis le coin SO t = tiles.setdefault(f'{kx}_{ky}', {'h': [], 'p': []}) t['h'].append(h); t['p'].append(flat) n += 1 os.makedirs(out, exist_ok=True) for f in os.listdir(out): if f.endswith('.json'): os.remove(os.path.join(out, f)) total = 0 for key, t in tiles.items(): with open(os.path.join(out, key + '.json'), 'w') as fh: json.dump(t, fh, separators=(',', ':')) total += os.path.getsize(os.path.join(out, key + '.json')) meta = { 'tiles': sorted(tiles), 'tileSize': TILE, 'buildings': n, 'bytes': total, 'build': datetime.datetime.now().strftime('%Y%m%d%H%M'), # version des données (URL des dalles) 'source': '© contributeurs OpenStreetMap (ODbL), extrait Geofabrik', 'date': data.get('osm3s', {}).get('timestamp_osm_base') or datetime.date.today().isoformat(), 'units': 'décimètres depuis le coin sud-ouest de la dalle, projection équirectangulaire LAT0=50.6', } with open(os.path.join(out, 'index.json'), 'w') as fh: json.dump(meta, fh, separators=(',', ':'), ensure_ascii=False) print(f'{n} bâtiments, {len(tiles)} dalles') if __name__ == '__main__': main(sys.argv[1], sys.argv[2])