#!/usr/bin/env python3 """ Builds the app's world piste file from OpenSkiData (https://openskidata.org). Rerun each autumn: curl -O https://tiles.openskimap.org/geojson/ski_areas.geojson.gz (also runs, lifts; at most once a day, by their terms) python3 make_pistes.py ../app/src/main/assets/pistes.bin Data from OpenSkiData / OpenSkiMap.org, (c) OpenStreetMap contributors (ODbL), Skimap.org, Who's On First, (c) Mapterhorn. The result is a derivative database under the ODbL; this script is the method of making it, and both are published. Layout, big-endian. Header: "OMP1", cell count, areas' offset and length, then per half-degree cell x, y (shorts), offset and length. Everything else is deflated: Areas: countries (count, 2 letters each); areas (count; name as length + UTF-8; latitude and longitude * 1e5 as ints; feature count). A cell: names (count, then length + UTF-8); features: code (0 unknown, 1 green, 2 blue, 3 red, 4 black, 5 orange, 8 lift), name + 1, area + 1, country + 1, line count, and per line point count, then per point lon, lat (1e-5 degrees) and height (metres) as zigzag deltas from the point before. All counts and indexes are varints. """ import collections import gzip import json import math import os import re import struct import sys import zlib SIMPLIFY_M = 5.0 CELL_DEGREES = 0.5 def features(folder, name): with gzip.open(os.path.join(folder, name + ".geojson.gz"), "rt", encoding="utf8") as f: for line in f: line = line.strip().rstrip(",") if line.startswith('{"type":"Feature"') or line.startswith('{"properties"'): yield json.loads(line) def varint(out, value): while value >= 0x80: out.append((value & 0x7F) | 0x80) value >>= 7 out.append(value) def zigzag(out, value): varint(out, (value << 1) ^ (value >> 63) if value < 0 else value << 1) def text(out, value): raw = value.encode("utf8") varint(out, len(raw)) out += raw def simplify(points): if len(points) < 3: return points kx = 111320 * math.cos(math.radians(points[0][1])) ky = 110540 xy = [(p[0] * kx, p[1] * ky) for p in points] keep = [False] * len(points) keep[0] = keep[-1] = True stack = [(0, len(points) - 1)] while stack: a, b = stack.pop() ax, ay = xy[a] dx, dy = xy[b][0] - ax, xy[b][1] - ay length = math.hypot(dx, dy) or 1e-9 best, at = 0, None for i in range(a + 1, b): d = abs((xy[i][0] - ax) * dy - (xy[i][1] - ay) * dx) / length if d > best: best, at = d, i if at is not None and best > SIMPLIFY_M: keep[at] = True stack += [(a, at), (at, b)] return [p for p, k in zip(points, keep) if k] def lines_of(geometry): kind = geometry["type"] if kind == "LineString": return [geometry["coordinates"]] if kind == "MultiLineString": return geometry["coordinates"] if kind == "Polygon": return [geometry["coordinates"][0]] if kind == "MultiPolygon": return [p[0] for p in geometry["coordinates"]] return [] def colour(difficulty, convention): """What the sign on the mountain shows: the same word is a different colour in Europe and in America.""" if difficulty is None: return 0 if difficulty in ("advanced", "expert"): return 4 if difficulty in ("freeride", "extreme"): return 5 if difficulty == "novice": return 1 if convention == "north_america": return {"easy": 1, "intermediate": 2}.get(difficulty, 0) if convention == "japan": return {"easy": 1, "intermediate": 3}.get(difficulty, 0) return {"easy": 2, "intermediate": 3}.get(difficulty, 0) def short_name(name): """Data gives every language: "Val Gardena, Gröden, Gherdëina". The first in Latin letters, or simply the first.""" if not name: return "" parts = [p.strip() for p in name.split(",") if p.strip()] for p in parts: if re.search(r"[A-Za-zÀ-ÿ]", p): return p return parts[0] if parts else "" def main(folder, out_path): areas = {} for f in features(folder, "ski_areas"): p = f["properties"] if p.get("status") != "operating": continue g = f["geometry"] first = g["coordinates"] if g["type"] == "Point" else lines_of(g)[0][0] places = p.get("places") or [{}] areas[p["id"]] = dict(name=short_name(p.get("name")), cc=places[0].get("iso3166_1Alpha2") or "", lon=first[0], lat=first[1], count=0) items = [] for f in features(folder, "runs"): p = f["properties"] if "downhill" not in (p.get("uses") or []) or p.get("status") != "operating": continue items.append((colour(p.get("difficulty"), p.get("difficultyConvention")), p.get("name") or p.get("ref") or "", p, lines_of(f["geometry"]))) for f in features(folder, "lifts"): p = f["properties"] if p.get("status") != "operating": continue items.append((8, p.get("name") or p.get("ref") or "", p, lines_of(f["geometry"]))) for _, _, p, _ in items: for s in p.get("skiAreas") or []: a = areas.get(s["properties"]["id"]) if a: a["count"] += 1 used = [i for i, a in areas.items() if a["count"] > 0] used.sort() area_index = {i: n for n, i in enumerate(used)} countries = sorted({a["cc"] for a in (areas[i] for i in used) if len(a["cc"]) == 2} | {(((p.get("places") or [{}])[0]).get("iso3166_1Alpha2") or "") for _, _, p, _ in items} - {""}) country_index = {c: n for n, c in enumerate(countries)} cells = collections.defaultdict(list) for item in items: lines = [l for l in item[3] if len(l) >= 2] if lines: first = lines[0][0] cells[(math.floor(first[0] / CELL_DEGREES), math.floor(first[1] / CELL_DEGREES))].append((item, lines)) blocks = [] for key in sorted(cells): names = {} body = bytearray() varint(body, len(cells[key])) for (code, name, p, _), lines in cells[key]: own = [s["properties"]["id"] for s in p.get("skiAreas") or [] if s["properties"]["id"] in area_index] # The name people use: the smallest area this belongs to, so Cortina and not Dolomiti Superski. smallest = min(own, key=lambda i: areas[i]["count"]) if own else None cc = ((p.get("places") or [{}])[0]).get("iso3166_1Alpha2") or "" body.append(code) varint(body, names.setdefault(name, len(names)) + 1 if name else 0) varint(body, area_index[smallest] + 1 if smallest else 0) varint(body, country_index[cc] + 1 if cc in country_index else 0) varint(body, len(lines)) for line in lines: pts = simplify(line) varint(body, len(pts)) px = py = pz = 0 for q in pts: x, y = round(q[0] * 1e5), round(q[1] * 1e5) z = round(q[2]) if len(q) > 2 and q[2] is not None else pz zigzag(body, x - px) zigzag(body, y - py) zigzag(body, z - pz) px, py, pz = x, y, z head = bytearray() varint(head, len(names)) for n in names: text(head, n) blocks.append((key, zlib.compress(bytes(head + body), 9))) area_block = bytearray() varint(area_block, len(countries)) for c in countries: area_block += c.encode("ascii") varint(area_block, len(used)) for i in used: a = areas[i] text(area_block, a["name"]) area_block += struct.pack(">ii", round(a["lat"] * 1e5), round(a["lon"] * 1e5)) varint(area_block, a["count"]) area_raw = zlib.compress(bytes(area_block), 9) header_size = 4 + 4 + 4 + 4 + len(blocks) * 12 with open(out_path, "wb") as out: out.write(b"OMP1") out.write(struct.pack(">iii", len(blocks), header_size, len(area_raw))) offset = header_size + len(area_raw) for key, raw in blocks: out.write(struct.pack(">hhii", key[0], key[1], offset, len(raw))) offset += len(raw) out.write(area_raw) for _, raw in blocks: out.write(raw) print(f"{len(items)} features, {len(used)} areas, {len(countries)} countries, {len(blocks)} cells, {os.path.getsize(out_path)} bytes, areas {len(area_raw)}, biggest cell {max(len(r) for _, r in blocks)}") if __name__ == "__main__": main(sys.argv[1], sys.argv[2])