diff --git a/ios-for-arcgis b/ios-for-arcgis index b8fae48..dabd8f6 160000 --- a/ios-for-arcgis +++ b/ios-for-arcgis @@ -1 +1 @@ -Subproject commit b8fae48fab5f6c5ceb0a957f1fc83677e716e754 +Subproject commit dabd8f605499dd80f54bea3ddccdacdc82d8f3a5 diff --git a/ios-for-googlemaps b/ios-for-googlemaps index 2aa9a2e..9596b11 160000 --- a/ios-for-googlemaps +++ b/ios-for-googlemaps @@ -1 +1 @@ -Subproject commit 2aa9a2e7f678b7b4f4d84fbe79d7733bb57d2e2f +Subproject commit 9596b1103ec3a5af000ce246a30feffcc9463f8e diff --git a/ios-for-here b/ios-for-here index fbe8671..5be98a5 160000 --- a/ios-for-here +++ b/ios-for-here @@ -1 +1 @@ -Subproject commit fbe86715fa6bac0dec3a16bf1c37572cc99292df +Subproject commit 5be98a5470c0bcd416a36d9c98fc737b21aa730f diff --git a/ios-for-longdo b/ios-for-longdo index ca5a462..114ce18 160000 --- a/ios-for-longdo +++ b/ios-for-longdo @@ -1 +1 @@ -Subproject commit ca5a462f83a0bd0364ff6fa29e32eb403146cb67 +Subproject commit 114ce1874d1fd0def590a7efdc25378d113cb2c9 diff --git a/ios-for-mapbox b/ios-for-mapbox index 5cdaf20..3340c56 160000 --- a/ios-for-mapbox +++ b/ios-for-mapbox @@ -1 +1 @@ -Subproject commit 5cdaf20b599cbf82d3b57c870ba56dd3fd9ef537 +Subproject commit 3340c568538e6b428e6340015203163f8b92e52f diff --git a/ios-for-mapkit b/ios-for-mapkit index 3e67412..c40c51f 160000 --- a/ios-for-mapkit +++ b/ios-for-mapkit @@ -1 +1 @@ -Subproject commit 3e67412b2284cdbf55749c72fd76a93619165f97 +Subproject commit c40c51f405f8f3f80b77891a050417a179cc1464 diff --git a/ios-for-maplibre b/ios-for-maplibre index c13baa1..6163e13 160000 --- a/ios-for-maplibre +++ b/ios-for-maplibre @@ -1 +1 @@ -Subproject commit c13baa1aadb9c7894ea1e82965e45e7b3e6fdf87 +Subproject commit 6163e13639d3b59ff93844cdfc1d232680fd8555 diff --git a/ios-for-mappls b/ios-for-mappls index 264e4cd..3b75194 160000 --- a/ios-for-mappls +++ b/ios-for-mappls @@ -1 +1 @@ -Subproject commit 264e4cd26efa3cb392f7043d22484fa33b9345a2 +Subproject commit 3b751946f16196dbfaea836a8abb0b986f5f1f37 diff --git a/ios-for-maptiler b/ios-for-maptiler index b1ece0d..92ca6d0 160000 --- a/ios-for-maptiler +++ b/ios-for-maptiler @@ -1 +1 @@ -Subproject commit b1ece0d800843d414d542287aa98f37c41b5d404 +Subproject commit 92ca6d0c3d671e96682e92fa4345aac1761b0d2c diff --git a/ios-for-openmobilemaps b/ios-for-openmobilemaps index 0afd10f..526516f 160000 --- a/ios-for-openmobilemaps +++ b/ios-for-openmobilemaps @@ -1 +1 @@ -Subproject commit 0afd10f6e929e7ad48ce8562364f95018b418f88 +Subproject commit 526516f58a33804db1d9bb2774e1bdbe531fac32 diff --git a/ios-for-tomtom b/ios-for-tomtom index 223320a..20ff0b8 160000 --- a/ios-for-tomtom +++ b/ios-for-tomtom @@ -1 +1 @@ -Subproject commit 223320ae1d891c77f2c3400edbdd77e4dfd77ae7 +Subproject commit 20ff0b8e78a91057d0e00030e3a76e23e667c2d7 diff --git a/ios-sdk-core b/ios-sdk-core index 7a1b04b..334832b 160000 --- a/ios-sdk-core +++ b/ios-sdk-core @@ -1 +1 @@ -Subproject commit 7a1b04b40f7affecb00a3624d1e6a6575e161c86 +Subproject commit 334832b3a867e49b40c36e310cd359bd3345ec9c diff --git a/samples/MapConductorSampleApp/Benchmarks/BostonDataTests.swift b/samples/MapConductorSampleApp/Benchmarks/BostonDataTests.swift new file mode 100644 index 0000000..ff9630b --- /dev/null +++ b/samples/MapConductorSampleApp/Benchmarks/BostonDataTests.swift @@ -0,0 +1,117 @@ +import Foundation +import XCTest + +@testable import MapConductorSampleApp + +/// The Boston page's MCPG v2 decoding (BostonData.swift). The same fixture is +/// decoded by the React (bostonData.test.ts) and Android (BostonDataTest.kt) tests. +final class BostonDataTests: XCTestCase { + /// Two polygons with every field (fields = 15), written by the generator (the React + /// sample's tools/boston/fixture.py): the same polygons at 1e-6 and at 1e-5 degree. + private let fixture = hexData( + "4d43504702000000020000000f067c020109436166c3a920e298950204f4abb228a7b0e24300d00fd00f0000cf0f03db0bd804" + + "d8040000a006000802000103ffea068ff40414142700" + ) + private let fixture5 = hexData( + "4d43504702000000020000000f057c020109436166c3a920e298950204b284850483b8e30600c801c8010000c7010395013c3c" + + "000050000802000103bf57e73e02020300" + ) + + private static func hexData(_ hex: String) -> Data { + var bytes: [UInt8] = [] + var index = hex.startIndex + while index < hex.endIndex { + let next = hex.index(index, offsetBy: 2) + bytes.append(UInt8(hex[index..= 8 } }) + } + + func testAreaIsTheOutlineLessItsHoles() throws { + let polygon = try BostonDataLoader.decode(fixture, idPrefix: "t")[0] + let outline = BostonBuilding(id: "o", level: 0, height: nil, name: nil, use: nil, rings: [polygon.rings[0]]) + let hole = BostonBuilding(id: "h", level: 0, height: nil, name: nil, use: nil, rings: [polygon.rings[1]]) + XCTAssertEqual(polygon.areaSquareMetres, outline.areaSquareMetres - hole.areaSquareMetres, accuracy: 1e-6) + // About 82 m x 111 m. + XCTAssertEqual(outline.areaSquareMetres, 9100, accuracy: 100) + } +} diff --git a/samples/MapConductorSampleApp/Benchmarks/BostonRoadsDataTests.swift b/samples/MapConductorSampleApp/Benchmarks/BostonRoadsDataTests.swift new file mode 100644 index 0000000..b41a694 --- /dev/null +++ b/samples/MapConductorSampleApp/Benchmarks/BostonRoadsDataTests.swift @@ -0,0 +1,85 @@ +import Foundation +import XCTest + +@testable import MapConductorSampleApp + +/// The Boston roads page's decoding (MCPG v2 with the road class and lines bits, +/// BostonRoadsData.swift). The same fixture is decoded by the React and Android tests +/// (written by the React sample's tools/boston/fixture.py). +final class BostonRoadsDataTests: XCTestCase { + /// Two roads, fields = name | road class | lines, 1e-5 degree: a multi-byte name, + /// an open three-point path, and a nameless two-point path stepping back south-west. + private let fixture = hexData( + "4d4350470200000002000000380510436166c3a92053747265657420e29895010103b284850483b8e30614140a2800060102ef56973e1313" + ) + + private static func hexData(_ hex: String) -> Data { + var bytes: [UInt8] = [] + var index = hex.startIndex + while index < hex.endIndex { + let next = hex.index(index, offsetBy: 2) + bytes.append(UInt8(hex[index.. String { guard let building = tap.building else { return "No building here" } - if let use = building.use { return "\(building.name ?? building.id) · \(use.label)" } + let area = formatArea(building.areaSquareMetres) + if let use = building.use { return "Parcel · \(use.label) · \(area)" } let height = building.height.map { "\($0.formatted()) m" } ?? "height unknown" - return "\(building.name ?? "Building") · \(height) · \(building.id.prefix(8))" + return "\(building.name ?? "Building") · \(height) · \(area)" } } @@ -295,15 +296,21 @@ private struct BostonPolygonInfo: View { private var rows: [(String, String)] { var rows: [(String, String)] = [] if let use = building.use { - rows.append(("Parcel", building.name?.replacingOccurrences(of: "Parcel ", with: "") ?? "—")) rows.append(("Land use", use.label)) } else { if let name = building.name { rows.append(("Name", name)) } rows.append(("Height", building.height.map { "\($0.formatted()) m" } ?? "unknown")) - rows.append(("Overture ID", building.id.count > 13 ? "\(building.id.prefix(13))…" : building.id)) } + rows.append(("Area", formatArea(building.areaSquareMetres))) let holes = building.rings.count - 1 rows.append(("Vertices", "\(building.vertexCount)" + (holes > 0 ? " (holes \(holes))" : ""))) return rows } } + +/// "1,234 m²", or hectares from 10,000 m² up. +func formatArea(_ squareMetres: Double) -> String { + squareMetres >= 10_000 + ? String(format: "%.2f ha", squareMetres / 10_000) + : "\(Int(squareMetres.rounded()).formatted(.number.locale(Locale(identifier: "en_US")))) m²" +} diff --git a/samples/MapConductorSampleApp/Sources/pages/polygon/boston/BostonBuildingsViewModel.swift b/samples/MapConductorSampleApp/Sources/pages/polygon/boston/BostonBuildingsViewModel.swift index 65cd01f..7959986 100644 --- a/samples/MapConductorSampleApp/Sources/pages/polygon/boston/BostonBuildingsViewModel.swift +++ b/samples/MapConductorSampleApp/Sources/pages/polygon/boston/BostonBuildingsViewModel.swift @@ -72,6 +72,21 @@ final class BostonBuildingsViewModel: ObservableObject { private var highlighted: (state: PolygonState, fill: UIColor)? private var loadTask: Task? + // Which ids of the dataset have reached the map, from their states' + // `onAdded`. The loading overlay stays up until every id of the list now + // handed to the map has. A set and a counter: a hundred thousand calls + // cost next to nothing. + // + // An id stays recorded when its building leaves the list (the area + // shrank). The SDK only calls `onAdded` again for a polygon it saw leave, + // and a list replaced before the SDK got to it is never seen: forgetting + // the id there left the overlay up for good when the area was switched + // mid-load. So the count is redone against each new list. + private var generation = 0 + private var addedIds: Set = [] + private var listIds: Set = [] + private var onMapCount = 0 + init() { let env = ProcessInfo.processInfo.environment let parts = env["MAPCONDUCTOR_SAMPLE_INIT_CAMERA"]?.split(separator: ",").compactMap { Double($0) } ?? [] @@ -112,6 +127,12 @@ final class BostonBuildingsViewModel: ObservableObject { tap = nil highlighted = nil doc = nil + // Calls for the previous dataset's states are ignored from here on. + generation += 1 + let generation = self.generation + addedIds = [] + listIds = [] + onMapCount = 0 phase = .read(loaded: 0, total: 0) let started = CACurrentMediaTime() loadTask = Task { [weak self] in @@ -136,8 +157,13 @@ final class BostonBuildingsViewModel: ObservableObject { self?.onTap(state: event.state, building: building, point: GeoPoint.from(position: event.clicked)) } } + let onAdded: OnPolygonAddedHandler = { [weak self] state in + MainActor.assumeIsolated { self?.polygonAdded(state.id, generation: generation) } + } self.states = await Task.detached(priority: .userInitiated) { - doc.buildings.map { Self.makeState($0, dataset: dataset, onTap: onTap) } + doc.buildings.map { building in + Self.makeState(building, dataset: dataset, onTap: onTap, onAdded: onAdded) + } }.value guard !Task.isCancelled, self.dataset == dataset else { return } self.buildMs = (CACurrentMediaTime() - built) * 1000 @@ -155,10 +181,15 @@ final class BostonBuildingsViewModel: ObservableObject { guard let doc else { return } var shown: [PolygonState] = [] var vertices = 0 + var listIds: Set = [] for (i, building) in doc.buildings.enumerated() where building.level <= area { shown.append(states[i]) vertices += building.vertexCount + listIds.insert(building.id) } + // Counted against the new list from here on. + self.listIds = listIds + onMapCount = listIds.reduce(0) { $0 + (addedIds.contains($1) ? 1 : 0) } stats = BostonStats(polygons: shown.count, vertices: vertices, loadMs: loadMs, buildMs: buildMs) print(String( format: "BOSTON shown dataset=%@ polygons=%d vertices=%d load=%.0fms build=%.0fms t=%.3f", @@ -166,14 +197,34 @@ final class BostonBuildingsViewModel: ObservableObject { )) phase = .draw polygonList = BostonPolygonList(shown) - // The overlay stays up until the frame after the list reached the map. - DispatchQueue.main.async { [weak self] in + // The list has been handed to the map; the SDK still has work to do + // (hole unions, tiling) before the polygons are on it. + DispatchQueue.main.async { DispatchQueue.main.async { - guard let self, self.phase == .draw else { return } - self.phase = nil print(String(format: "BOSTON handed t=%.3f", CACurrentMediaTime())) } } + finishDrawingIfAllAdded() + } + + /// `onAdded` of the polygon `id`: it is on the map (natively, or in the tile + /// layer the map has been given; the tile images may still be loading). + private func polygonAdded(_ id: String, generation: Int) { + guard generation == self.generation, addedIds.insert(id).inserted else { return } + // A building of a list since replaced: on the map, but not one the + // overlay waits for now. + guard listIds.contains(id) else { return } + onMapCount += 1 + if onMapCount == 1 { + print(String(format: "BOSTON firstAdded t=%.3f", CACurrentMediaTime())) + } + finishDrawingIfAllAdded() + } + + private func finishDrawingIfAllAdded() { + guard phase == .draw, onMapCount >= listIds.count else { return } + phase = nil + print(String(format: "BOSTON added count=%d t=%.3f", onMapCount, CACurrentMediaTime())) } /// Moves the highlight to `state` (or clears it) and records the tap. @@ -189,7 +240,8 @@ final class BostonBuildingsViewModel: ObservableObject { nonisolated private static func makeState( _ building: BostonBuilding, dataset: BostonDataset, - onTap: @escaping (PolygonEvent, BostonBuilding) -> Void + onTap: @escaping (PolygonEvent, BostonBuilding) -> Void, + onAdded: @escaping OnPolygonAddedHandler ) -> PolygonState { let rings = building.rings.map { ring -> [GeoPointProtocol] in stride(from: 0, to: ring.count, by: 2).map { GeoPoint(latitude: ring[$0 + 1], longitude: ring[$0]) } @@ -204,7 +256,8 @@ final class BostonBuildingsViewModel: ObservableObject { strokeWidth: 1, fillColor: Self.fill(dataset: dataset, building: building), extra: building.id, - onClick: { event in onTap(event, building) } + onClick: { event in onTap(event, building) }, + onAdded: onAdded ) } diff --git a/samples/MapConductorSampleApp/Sources/pages/polygon/boston/BostonData.swift b/samples/MapConductorSampleApp/Sources/pages/polygon/boston/BostonData.swift index f2d4c89..833835c 100644 --- a/samples/MapConductorSampleApp/Sources/pages/polygon/boston/BostonData.swift +++ b/samples/MapConductorSampleApp/Sources/pages/polygon/boston/BostonData.swift @@ -1,27 +1,42 @@ import Foundation +import MapConductorCore import UIKit /// The polygons the Boston page draws. Same data and file format as the React /// sample (`examples/basic/src/pages/polygon/boston/bostonData.ts`) and the /// Android one (`BostonData.kt`). /// -/// - ``BostonDataset/downtown``: the bundled Overture extract (JSON), three nested areas. +/// - ``BostonDataset/downtown``: Overture building footprints of downtown in three +/// nested areas (`boston-downtown.bin`). /// - ``BostonDataset/buildings`` / ``BostonDataset/parcels``: the whole city, about -/// 100,000 polygons each. Those files are too large for the app bundle; copy them -/// into the app's Documents folder on the device: +/// 100,000 polygons each (`boston-city-buildings.bin`, `boston-city-parcels.bin`): +/// Overture buildings, and Analyze Boston Parcels 2025 joined with the FY2026 +/// Property Assessment land use. /// -/// xcrun devicectl device copy to --device \ -/// --domain-type appDataContainer --domain-identifier com.mapconductor.sample \ -/// --source boston-parcels.bin --destination Documents/boston/boston-parcels.bin +/// All three are bundled (Resources). The React sample's `examples/basic/tools/boston/` +/// builds them from the official sources (see its README). /// -/// A parcel's label is "|". +/// The files carry no ids: this is a polygon demo, and a polygon's id on the map +/// is its index in the file. /// -/// Binary layout (little-endian): -/// 'MCPG' u32 version=1 u32 count -/// per polygon: u8 labelLen, label (UTF-8), u16 height (0.1 m, 0xFFFF unknown), -/// u16 ringCount, per ring: u32 n, n x (i32 dLat, i32 dLng) -/// Coordinates are 1e-6 degree integers, each the difference from the -/// previous vertex across the whole file. +/// Binary layout, MCPG v2: +/// 'MCPG' u32 version=2 u32 count u8 fields u8 digits (little-endian) +/// fields: 1 = height, 2 = land use, 4 = area, 8 = name, 16 = road class (what the file carries), +/// 32 = lines: the shapes are polylines, not polygons (the roads; see BostonRoadsData.swift) +/// digits: coordinates are integers of 10^-digits degree (buildings 6, parcels 5) +/// per polygon, only the fields present, in this order: +/// height varint, 0 = unknown, else the height in 0.1 m plus 1 +/// land use u8, the index in ``LandUse`` (family … unknown) +/// area u8, the smallest downtown area (0, 1 or 2) the building fits in +/// name varint byte length (0 = none), UTF-8 +/// road class u8, the index in ``RoadClass`` (highway … path) +/// varint ringCount, per ring: varint n, n x (svarint dLat, svarint dLng) +/// varint is LEB128 (7 bits at a time, low first); svarint is a zigzag varint. +/// Coordinates are integers of 10^-digits degree, each the difference from the +/// previous vertex across the whole file. A ring's closing vertex (the same as its first) +/// is not stored: n counts the others, and the reader closes the ring again. +/// With the lines bit (32) a "ring" is an open polyline: every vertex is stored +/// (n >= 2) and the reader does not close it. enum BostonDataset: String, CaseIterable, Identifiable { case downtown case buildings @@ -37,18 +52,18 @@ enum BostonDataset: String, CaseIterable, Identifiable { } } - fileprivate var file: String? { + /// The file's name in the app bundle, without the `.bin` extension. + fileprivate var resource: String { switch self { - case .downtown: return nil - case .buildings: return "boston/boston-buildings-city.bin" - case .parcels: return "boston/boston-parcels.bin" + case .downtown: return "boston-downtown" + case .buildings: return "boston-city-buildings" + case .parcels: return "boston-city-parcels" } } fileprivate var attribution: String { switch self { - case .downtown: return "" - case .buildings: + case .downtown, .buildings: return "© OpenStreetMap contributors, Esri Community Maps contributors, USGS, Microsoft — via Overture Maps Foundation (ODbL 1.0)" case .parcels: return "City of Boston, Parcels 2025 and FY2026 Property Assessment (Analyze Boston) (ODC PDDL)" @@ -57,6 +72,7 @@ enum BostonDataset: String, CaseIterable, Identifiable { } /// A parcel's land use, from the City of Boston's Property Assessment. +/// The order is the file's: a land use is stored as its index here. enum LandUse: String, CaseIterable { case family, apartment, condo, mixed, commercial, industrial, exempt, vacant, unknown @@ -98,9 +114,22 @@ struct BostonBuilding { let name: String? let use: LandUse? /// Rings as flat [lng, lat, lng, lat, ...]; the first is the outline, the rest holes. + /// For a road (a file with the lines bit) the one "ring" is the open polyline. let rings: [[Double]] + /// A road's class, from a file with the road class field. + var road: RoadClass? = nil var vertexCount: Int { rings.reduce(0) { $0 + $1.count / 2 } } + + /// The area in square metres: the outline less its holes. + var areaSquareMetres: Double { + let areas = rings.map { ring in + Spherical.computeArea(stride(from: 0, to: ring.count, by: 2).map { + GeoPoint(latitude: ring[$0 + 1], longitude: ring[$0]) as GeoPointProtocol + }) + } + return (areas.first ?? 0) - areas.dropFirst().reduce(0, +) + } } struct BostonDoc { @@ -119,9 +148,7 @@ enum BostonLoadPhase: Equatable { enum BostonDataLoader { struct Missing: LocalizedError { let path: String - var errorDescription: String? { - "Missing \(path). Copy it to the app's Documents folder with devicectl (see BostonData.swift)." - } + var errorDescription: String? { "Missing \(path) in the app bundle." } } /// Reads and decodes `dataset` off the main thread, reporting progress there. @@ -130,26 +157,16 @@ enum BostonDataLoader { onProgress: @escaping @MainActor (BostonLoadPhase) -> Void ) async throws -> BostonDoc { try await Task.detached(priority: .userInitiated) { - let bytes: Data - let url: URL - if let file = dataset.file { - let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] - url = documents.appendingPathComponent(file) - guard FileManager.default.fileExists(atPath: url.path) else { throw Missing(path: "Documents/\(file)") } - } else { - guard let bundled = Bundle.main.url(forResource: "boston-buildings", withExtension: "json") else { - throw Missing(path: "boston-buildings.json (app bundle)") - } - url = bundled + guard let url = Bundle.main.url(forResource: dataset.resource, withExtension: "bin") else { + throw Missing(path: "\(dataset.resource).bin") } - bytes = try readWithProgress(url, onProgress: onProgress) + let bytes = try readWithProgress(url, onProgress: onProgress) await onProgress(.decode) - if dataset == .downtown { return try decodeDowntown(bytes) } - return BostonDoc(attribution: dataset.attribution, buildings: try decode(bytes, dataset: dataset)) + return BostonDoc(attribution: dataset.attribution, buildings: try decode(bytes, idPrefix: dataset.rawValue)) }.value } - private static func readWithProgress( + static func readWithProgress( _ url: URL, onProgress: @escaping @MainActor (BostonLoadPhase) -> Void ) throws -> Data { @@ -166,85 +183,86 @@ enum BostonDataLoader { return data } - private static func decodeDowntown(_ bytes: Data) throws -> BostonDoc { - struct Doc: Decodable { - struct Item: Decodable { - let id: String - let l: Int - let h: Double? - let n: String? - let rings: [[Double]] - } - let attribution: String - let license: String - let buildings: [Item] - } - let doc = try JSONDecoder().decode(Doc.self, from: bytes) - return BostonDoc( - attribution: "\(doc.attribution) (\(doc.license))", - buildings: doc.buildings.map { - BostonBuilding(id: $0.id, level: $0.l, height: $0.h, name: $0.n, use: nil, rings: $0.rings) - } - ) - } - - private static func decode(_ bytes: Data, dataset: BostonDataset) throws -> [BostonBuilding] { + /// Decodes an MCPG v2 file (see the top of this file); polygon `i` gets the id "-". + static func decode(_ bytes: Data, idPrefix: String) throws -> [BostonBuilding] { try bytes.withUnsafeBytes { (raw: UnsafeRawBufferPointer) -> [BostonBuilding] in - func u8(_ at: Int) -> Int { Int(raw[at]) } - func u16(_ at: Int) -> Int { Int(raw.loadUnaligned(fromByteOffset: at, as: UInt16.self).littleEndian) } func u32(_ at: Int) -> Int { Int(raw.loadUnaligned(fromByteOffset: at, as: UInt32.self).littleEndian) } - func i32(_ at: Int) -> Int { Int(Int32(littleEndian: raw.loadUnaligned(fromByteOffset: at, as: Int32.self))) } - guard raw.count >= 12, String(decoding: raw[0..<4], as: UTF8.self) == "MCPG", u32(4) == 1 else { + guard raw.count >= 14, String(decoding: raw[0..<4], as: UTF8.self) == "MCPG", u32(4) == 2 else { throw CocoaError(.fileReadCorruptFile) } let count = u32(8) + let fields = Int(raw[12]) + let scale = pow(10, Double(raw[13])) + var offset = 14 + func varint() throws -> Int { + var value = 0 + var shift = 0 + while true { + guard offset < raw.count else { throw CocoaError(.fileReadCorruptFile) } + let b = Int(raw[offset]) + offset += 1 + value |= (b & 0x7F) << shift + if b < 0x80 { return value } + shift += 7 + } + } + func svarint() throws -> Int { + let v = try varint() + return (v >> 1) ^ -(v & 1) + } var buildings: [BostonBuilding] = [] buildings.reserveCapacity(count) - var seen = Set() - seen.reserveCapacity(count) - var offset = 12 var lat = 0, lng = 0 for i in 0.. 0 { name = String(decoding: raw[offset..<(offset + length)], as: UTF8.self) } + offset += length + } + if fields & 16 != 0 { + road = RoadClass.allCases[Int(raw[offset])] + offset += 1 + } + let lines = fields & 32 != 0 + let ringCount = try varint() var rings: [[Double]] = [] rings.reserveCapacity(ringCount) for _ in 0..|". - // Parts of a multipolygon share the label, so a repeat gets the index appended. - var key = label - var use: LandUse? - if dataset == .parcels { - let parts = label.split(separator: "|", maxSplits: 1, omittingEmptySubsequences: false) - key = parts.first.map(String.init) ?? "" - use = parts.count > 1 ? (LandUse(rawValue: String(parts[1])) ?? .unknown) : .unknown - } - var id = key.isEmpty ? "\(dataset.rawValue)-\(i)" : key - if seen.contains(id) { id = "\(id)#\(i)" } - seen.insert(id) buildings.append(BostonBuilding( - id: id, - level: 0, - height: height == 0xFFFF ? nil : Double(height) / 10, - name: dataset == .parcels && !key.isEmpty ? "Parcel \(key)" : nil, - use: use, - rings: rings + id: "\(idPrefix)-\(i)", level: level, height: height, name: name, use: use, rings: rings, road: road )) } return buildings diff --git a/samples/MapConductorSampleApp/Sources/pages/polyline/boston/BostonRoadsData.swift b/samples/MapConductorSampleApp/Sources/pages/polyline/boston/BostonRoadsData.swift new file mode 100644 index 0000000..5bde2b3 --- /dev/null +++ b/samples/MapConductorSampleApp/Sources/pages/polyline/boston/BostonRoadsData.swift @@ -0,0 +1,111 @@ +import Foundation +import MapConductorCore +import UIKit + +/// The roads the Boston roads page draws. Same data and file format as the React +/// sample (`examples/basic/src/pages/polyline/boston/`) and the Android one. +/// +/// `boston-city-roads.bin` (bundled, Resources): Overture Maps `transportation/segment` +/// (release 2026-10-21.0), road subtype only, cut at the City of Boston boundary +/// (Analyze Boston): 54,645 polylines, 234,765 vertices. Built by the React sample's +/// `examples/basic/tools/boston/pack.py roads` (see its README). +/// +/// MCPG v2 (see BostonData.swift) with fields = name (8) | road class (16) | lines (32), +/// coordinates at 1e-5 degree, vertices almost on a straight line (0.5 m) left out, +/// both ends kept. One record is one polyline; there are no ids: a road's id on the +/// map is its index in the file. +enum RoadClass: Int, CaseIterable, Identifiable { + case highway, primary, secondary, tertiary, local, service, path + + var id: Int { rawValue } + + /// The same colours, widths and zIndex as the React and Android samples: + /// the bigger the road, the wider, the warmer and the higher. + var color: UIColor { + switch self { + case .highway: return UIColor(red: 0xE8 / 255, green: 0x59 / 255, blue: 0x0C / 255, alpha: 1) + case .primary: return UIColor(red: 0xF0 / 255, green: 0x8C / 255, blue: 0x00 / 255, alpha: 1) + case .secondary: return UIColor(red: 0xFA / 255, green: 0xB0 / 255, blue: 0x05 / 255, alpha: 1) + case .tertiary: return UIColor(red: 0xFF / 255, green: 0xD4 / 255, blue: 0x3B / 255, alpha: 1) + case .local: return UIColor(red: 0x86 / 255, green: 0x8E / 255, blue: 0x96 / 255, alpha: 1) + case .service: return UIColor(red: 0xAD / 255, green: 0xB5 / 255, blue: 0xBD / 255, alpha: 1) + case .path: return UIColor(red: 0x74 / 255, green: 0xB8 / 255, blue: 0x16 / 255, alpha: 1) + } + } + + /// On screen, in points. + var width: Double { + switch self { + case .highway: return 5 + case .primary: return 4 + case .secondary: return 3.5 + case .tertiary: return 3 + case .local: return 2 + case .service: return 1.5 + case .path: return 1 + } + } + + var zIndex: Int { 6 - rawValue } + + var label: String { + switch self { + case .highway: return "Highway" + case .primary: return "Primary" + case .secondary: return "Secondary" + case .tertiary: return "Tertiary" + case .local: return "Local" + case .service: return "Service" + case .path: return "Path" + } + } +} + +struct BostonRoad { + let id: String + let road: RoadClass + let name: String? + /// The open polyline as flat [lng, lat, lng, lat, ...]. + let points: [Double] + + var vertexCount: Int { points.count / 2 } + + /// The length in metres: the geodesic distances between its points, summed. + var lengthMetres: Double { + var total = 0.0 + var i = 2 + while i < points.count { + total += Spherical.computeDistanceBetween( + from: GeoPoint(latitude: points[i - 1], longitude: points[i - 2]), + to: GeoPoint(latitude: points[i + 1], longitude: points[i]) + ) + i += 2 + } + return total + } +} + +enum BostonRoadsLoader { + static let attribution = "© OpenStreetMap contributors, TomTom — via Overture Maps Foundation (ODbL 1.0); boundary: City of Boston (Analyze Boston)" + + /// Reads and decodes the bundled roads off the main thread, reporting progress there. + static func load(onProgress: @escaping @MainActor (BostonLoadPhase) -> Void) async throws -> [BostonRoad] { + try await Task.detached(priority: .userInitiated) { + guard let url = Bundle.main.url(forResource: "boston-city-roads", withExtension: "bin") else { + throw BostonDataLoader.Missing(path: "boston-city-roads.bin") + } + let bytes = try BostonDataLoader.readWithProgress(url, onProgress: onProgress) + await onProgress(.decode) + return try decode(bytes) + }.value + } + + /// Decodes an MCPG v2 file of polylines; road `i` gets the id "roads-". + static func decode(_ bytes: Data) throws -> [BostonRoad] { + guard bytes.count >= 14, bytes[bytes.startIndex + 12] & 32 != 0 else { throw CocoaError(.fileReadCorruptFile) } + return try BostonDataLoader.decode(bytes, idPrefix: "roads").map { record in + guard record.rings.count == 1, record.rings[0].count >= 4 else { throw CocoaError(.fileReadCorruptFile) } + return BostonRoad(id: record.id, road: record.road ?? .local, name: record.name, points: record.rings[0]) + } + } +} diff --git a/samples/MapConductorSampleApp/Sources/pages/polyline/boston/BostonRoadsPage.swift b/samples/MapConductorSampleApp/Sources/pages/polyline/boston/BostonRoadsPage.swift new file mode 100644 index 0000000..867e29a --- /dev/null +++ b/samples/MapConductorSampleApp/Sources/pages/polyline/boston/BostonRoadsPage.swift @@ -0,0 +1,353 @@ +import MapConductorCore +import MapConductorForArcGIS +import MapConductorForGoogleMaps +import MapConductorForHERE +import MapConductorForLongdo +import MapConductorForMapKit +import MapConductorForMapLibre +import MapConductorForMapTiler +import MapConductorForMapbox +import MapConductorForMappls +import MapConductorForOpenMobileMaps +import MapConductorForTomTom +import SwiftUI + +/// Boston's roads drawn with one `Polylines` (see ``BostonRoadsViewModel``). +struct BostonRoadsPage: View { + let onToggleSidebar: () -> Void + + @State private var provider: MapProvider + @StateObject private var viewModel: BostonRoadsViewModel + @State private var probe = BostonProbe() + @State private var cycleStarted = false + + @StateObject private var googleState: GoogleMapViewState + @StateObject private var mapLibreState: MapLibreViewState + @StateObject private var mapKitState: MapKitViewState + @StateObject private var mapboxState: MapboxViewState + @StateObject private var arcGISState: ArcGISMapViewState + @StateObject private var hereState: HereMapViewState + @StateObject private var tomTomState: TomTomMapViewState + @StateObject private var mapTilerState: MapTilerViewState + @StateObject private var longdoState: LongdoViewState + @StateObject private var openMobileMapsState: OpenMobileMapsViewState + @StateObject private var mapplsState: MapplsViewState + + init(onToggleSidebar: @escaping () -> Void = {}) { + self.onToggleSidebar = onToggleSidebar + let vm = BostonRoadsViewModel() + let camera = vm.initCameraPosition + _viewModel = StateObject(wrappedValue: vm) + _provider = State(initialValue: MapProvider.initial()) + _googleState = StateObject(wrappedValue: GoogleMapViewState(cameraPosition: camera)) + _mapLibreState = StateObject(wrappedValue: MapLibreViewState(cameraPosition: camera)) + _mapKitState = StateObject(wrappedValue: MapKitViewState(mapDesignType: MapKitMapDesign.Standard, cameraPosition: camera)) + _mapboxState = StateObject(wrappedValue: MapboxViewState(cameraPosition: camera)) + _arcGISState = StateObject(wrappedValue: ArcGISMapViewState(mapDesignType: ArcGISDesign.OsmStandard, cameraPosition: camera)) + _hereState = StateObject(wrappedValue: HereMapViewState(mapDesignType: HereMapDesign.NormalDay, cameraPosition: camera)) + _tomTomState = StateObject(wrappedValue: TomTomMapViewState(mapDesignType: TomTomMapDesign.Standard, cameraPosition: camera)) + _mapTilerState = StateObject(wrappedValue: MapTilerViewState(mapDesignType: MapTilerDesign.Streets, cameraPosition: camera)) + _longdoState = StateObject(wrappedValue: LongdoViewState(mapDesignType: LongdoDesign.Normal, cameraPosition: camera)) + _openMobileMapsState = StateObject(wrappedValue: OpenMobileMapsViewState( + mapDesignType: OpenMobileMapsDesign.openStreetMap, cameraPosition: camera + )) + _mapplsState = StateObject(wrappedValue: MapplsViewState(mapDesignType: MapplsDesign.Default, cameraPosition: camera)) + } + + var body: some View { + DemoMapPageScaffold(provider: $provider, onToggleSidebar: onToggleSidebar) { + ZStack(alignment: .bottomLeading) { + BostonRoadsMapComponent( + provider: $provider, + googleState: googleState, + mapLibreState: mapLibreState, + mapKitState: mapKitState, + mapboxState: mapboxState, + arcGISState: arcGISState, + hereState: hereState, + tomTomState: tomTomState, + mapTilerState: mapTilerState, + longdoState: longdoState, + openMobileMapsState: openMobileMapsState, + mapplsState: mapplsState, + polylines: viewModel.polylineList, + tiling: viewModel.tilingOptions, + stacking: viewModel.stacking ? viewModel.stackingOverlays : nil, + tap: viewModel.tap, + onMapClick: { viewModel.onMapClick($0) } + ) + + if let phase = viewModel.phase { + BostonRoadsLoadingOverlay(phase: phase, added: viewModel.addedCount, total: viewModel.stats?.polylines) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + BostonRoadsControlPanel(viewModel: viewModel) + .padding(12) + } + } + .onAppear { + viewModel.start() + probe.start() + } + .onDisappear { probe.stop() } + .onChange(of: provider) { next in + print("ROADS provider=\(next.rawValue) footprint=\(Int(BostonRoadsViewModel.footprintMB()))MB") + } + .onChange(of: viewModel.polylines.count) { count in + guard count > 0 else { return } + probe.autopan(from: viewModel.initCameraPosition) { target, millis in + activeState?.moveCameraTo(cameraPosition: target, durationMillis: Long(millis)) + } + startCycleIfAsked() + } + } + + /// `MAPCONDUCTOR_SAMPLE_ROADS_CYCLE="maplibre,googlemaps,…[,seconds]"`: switches the + /// provider through the list once the roads are first shown, `seconds` (20 by default) + /// apart, printing the memory footprint just before each switch and at the end. + private func startCycleIfAsked() { + guard !cycleStarted, let raw = ProcessInfo.processInfo.environment["MAPCONDUCTOR_SAMPLE_ROADS_CYCLE"] else { return } + cycleStarted = true + let parts = raw.split(separator: ",").map(String.init) + let seconds = parts.last.flatMap(Double.init) ?? 20 + let providers = parts.compactMap(MapProvider.parse) + Task { @MainActor in + try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000)) + for (i, next) in providers.enumerated() { + print(String(format: "ROADS cycle i=%d from=%@ footprint=%.0fMB", i, provider.rawValue, BostonRoadsViewModel.footprintMB())) + provider = next + try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000)) + } + print(String(format: "ROADS cycle done at=%@ footprint=%.0fMB", provider.rawValue, BostonRoadsViewModel.footprintMB())) + } + } + + private var activeState: (any MapViewStateProtocol)? { + switch provider { + case .googleMaps: return googleState + case .mapLibre: return mapLibreState + case .mapKit: return mapKitState + case .mapbox: return mapboxState + case .arcGIS, .arcGIS2D: return arcGISState + case .here: return hereState + case .tomTom: return tomTomState + case .mapTiler: return mapTilerState + case .longdo: return longdoState + case .openMobileMaps: return openMobileMapsState + case .mappls: return mapplsState + } + } +} + +private struct BostonRoadsMapComponent: View { + @Binding var provider: MapProvider + @ObservedObject var googleState: GoogleMapViewState + @ObservedObject var mapLibreState: MapLibreViewState + @ObservedObject var mapKitState: MapKitViewState + @ObservedObject var mapboxState: MapboxViewState + @ObservedObject var arcGISState: ArcGISMapViewState + @ObservedObject var hereState: HereMapViewState + @ObservedObject var tomTomState: TomTomMapViewState + @ObservedObject var mapTilerState: MapTilerViewState + @ObservedObject var longdoState: LongdoViewState + @ObservedObject var openMobileMapsState: OpenMobileMapsViewState + @ObservedObject var mapplsState: MapplsViewState + + /// A reference, so SwiftUI compares it by identity rather than state by state. + let polylines: BostonPolylineList + let tiling: PolylineTilingOptions + let stacking: BostonStackingOverlays? + let tap: BostonRoadTap? + let onMapClick: (GeoPoint) -> Void + + var body: some View { + SampleMapView( + provider: $provider, + googleState: googleState, + mapLibreState: mapLibreState, + mapKitState: mapKitState, + mapboxState: mapboxState, + arcGISState: arcGISState, + hereState: hereState, + tomTomState: tomTomState, + mapTilerState: mapTilerState, + longdoState: longdoState, + openMobileMapsState: openMobileMapsState, + mapplsState: mapplsState, + onMapClick: onMapClick + ) { + { () -> MapViewContent in + var content = MapViewContent() + PolylineTiling(tiling).append(to: &content) + Polylines(polylines.states).append(to: &content) + if let stacking { + // A second `Polylines` next to the roads: the geodesic line is drawn natively, above the road tiles. + Polylines([stacking.geodesic]).append(to: &content) + Polygons(stacking.polygons).append(to: &content) + Circles([stacking.circle]).append(to: &content) + Markers(stacking.markers).append(to: &content) + } + if let tap, let road = tap.road, let point = tap.point { + content.infoBubbles = [ + InfoBubble(position: point, id: "boston-road-tap-\(tap.seq)", contentPadding: 8) { + BostonRoadInfo(road: road) + } + ] + } + return content + }() + } + } +} + +/// Covers the map while the roads load and reach it. +private struct BostonRoadsLoadingOverlay: View { + let phase: BostonLoadPhase + let added: Int + let total: Int? + + var body: some View { + ZStack { + Color.black.opacity(0.35) + VStack(spacing: 10) { + ProgressView() + Text(text).font(.subheadline) + if let fraction { + ProgressView(value: fraction).frame(width: 220) + } + } + .padding(.vertical, 16) + .padding(.horizontal, 20) + .frame(minWidth: 240) + .background(Color(UIColor.systemBackground)) + .cornerRadius(10) + .shadow(color: Color.black.opacity(0.25), radius: 12, x: 0, y: 8) + } + .ignoresSafeArea() + .accessibilityIdentifier("boston-roads-loading") + } + + private var text: String { + switch phase { + case let .read(loaded, total): + let mb = { (bytes: Int) in String(format: "%.1f", Double(bytes) / 1_048_576) } + return total > 0 ? "Loading data… \(mb(loaded)) / \(mb(total)) MB" : "Loading data… \(mb(loaded)) MB" + case .decode: return "Reading the roads…" + case .build: return "Preparing the roads…" + case .draw: + guard let total else { return "Drawing the map…" } + return "Drawing the map… \(added.formatted()) / \(total.formatted())" + } + } + + private var fraction: Double? { + switch phase { + case let .read(loaded, total) where total > 0: return Double(loaded) / Double(total) + case .draw: return total.map { $0 > 0 ? Double(added) / Double($0) : 0 } + default: return nil + } + } +} + +private struct BostonRoadsControlPanel: View { + @ObservedObject var viewModel: BostonRoadsViewModel + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Text("Boston roads").font(.headline) + Toggle("Draw as tiles", isOn: Binding(get: { viewModel.tiling }, set: { viewModel.setTiling($0) })) + .font(.subheadline) + .accessibilityIdentifier("boston-roads-tiling") + Toggle("Stacking check", isOn: Binding(get: { viewModel.stacking }, set: { viewModel.setStacking($0) })) + .font(.subheadline) + .accessibilityIdentifier("boston-roads-stacking") + BostonRoadsLegend() + if let error = viewModel.loadError { + Text(error).font(.caption).foregroundColor(.red).fixedSize(horizontal: false, vertical: true) + } + if let stats = viewModel.stats { + Text("\(stats.polylines.formatted()) polylines, \(stats.vertices.formatted()) vertices") + .font(.caption) + Text(String(format: "load %.0f ms, states %.0f ms", stats.loadMs, stats.buildMs)) + .font(.caption2).foregroundColor(.secondary) + } + Text(timingText) + .font(.caption2).foregroundColor(.secondary) + .accessibilityIdentifier("boston-roads-timing") + if let tap = viewModel.tap { + Text(tapText(tap)).font(.caption) + .accessibilityIdentifier("boston-roads-tap") + .accessibilityValue("\(tap.seq)|\(tap.road?.id ?? "")|\(tap.point?.latitude ?? .nan)|\(tap.point?.longitude ?? .nan)") + } + Text(BostonRoadsLoader.attribution).font(.system(size: 10)).foregroundColor(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .padding(12) + .frame(width: 340, alignment: .leading) + .background(Color(UIColor.systemBackground).opacity(0.95)) + .cornerRadius(12) + .shadow(color: Color.black.opacity(0.2), radius: 8, x: 0, y: 4) + } + + private var timingText: String { + let mode = viewModel.tiling ? "tiles" : "native" + guard let all = viewModel.allAddedMs else { + return "\(mode): \(viewModel.addedCount.formatted()) onAdded so far" + } + let first = viewModel.firstAddedMs.map { String(format: "first %.0f ms, ", $0) } ?? "" + return String(format: "%@: load → all onAdded %.0f ms (%@%.0f MB)", mode, all, first, viewModel.footprintMB) + } + + private func tapText(_ tap: BostonRoadTap) -> String { + guard let road = tap.road else { return "No road here" } + return "\(road.road.label) · \(road.name ?? "unnamed") · \(formatLength(road.lengthMetres))" + } +} + +private struct BostonRoadsLegend: View { + var body: some View { + LazyVGrid(columns: [GridItem(.flexible(), alignment: .leading), GridItem(.flexible(), alignment: .leading)], spacing: 2) { + ForEach(RoadClass.allCases) { road in + HStack(spacing: 6) { + RoundedRectangle(cornerRadius: 1) + .fill(Color(road.color)) + .frame(width: 18, height: max(1.5, road.width)) + Text(road.label).font(.system(size: 10)).lineLimit(1) + } + } + } + } +} + +/// What a tapped road carries, shown in an InfoBubble at the closest point on it. +private struct BostonRoadInfo: View { + let road: BostonRoad + + var body: some View { + Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 2) { + ForEach(rows, id: \.0) { row in + GridRow { + Text(row.0).fontWeight(.semibold).foregroundColor(Color(red: 0.28, green: 0.33, blue: 0.41)) + Text(row.1) + } + } + } + .font(.system(size: 12)) + .fixedSize() + .accessibilityIdentifier("boston-road-info") + } + + private var rows: [(String, String)] { + var rows: [(String, String)] = [("Class", road.road.label)] + if let name = road.name { rows.append(("Name", name)) } + rows.append(("Length", formatLength(road.lengthMetres))) + rows.append(("Vertices", "\(road.vertexCount)")) + return rows + } +} + +/// "123 m", or kilometres from 1,000 m up. +func formatLength(_ metres: Double) -> String { + metres >= 1_000 ? String(format: "%.2f km", metres / 1_000) : "\(Int(metres.rounded())) m" +} diff --git a/samples/MapConductorSampleApp/Sources/pages/polyline/boston/BostonRoadsViewModel.swift b/samples/MapConductorSampleApp/Sources/pages/polyline/boston/BostonRoadsViewModel.swift new file mode 100644 index 0000000..01ae73e --- /dev/null +++ b/samples/MapConductorSampleApp/Sources/pages/polyline/boston/BostonRoadsViewModel.swift @@ -0,0 +1,295 @@ +import Darwin +import Foundation +import MapConductorCore +import QuartzCore +import UIKit + +/// What the last tap hit: a road, or nothing (`road` nil). +struct BostonRoadTap { + let seq: Int + let road: BostonRoad? + /// Where the tap landed: the closest point on the road, or the map click's point. + let point: GeoPoint? +} + +struct BostonRoadStats { + let polylines: Int + let vertices: Int + let loadMs: Double + let buildMs: Double +} + +/// The states handed to the map, as one object (see `BostonPolygonList`). +final class BostonPolylineList { + let states: [PolylineState] + init(_ states: [PolylineState]) { self.states = states } +} + +/// The overlays the stacking check adds around Downtown Crossing: polygons enough +/// to be tiled, a circle, a natively drawn (geodesic) polyline and markers. +struct BostonStackingOverlays { + let polygons: [PolygonState] + let circle: CircleState + let geodesic: PolylineState + let markers: [MarkerState] +} + +/** + Boston's roads drawn with one `Polylines` on top of the real map. + + Every road of the city (Overture transportation segments, 54,645 polylines), + coloured, widened and stacked by class. With the default + ``PolylineTilingOptions`` they are drawn into raster tiles; the switch turns + tiling off (every road a native polyline) and loads again, so the time from + the file to the last `onAdded` can be compared. + + Tapping a road highlights it and shows its class, name and length in an + InfoBubble at the closest point on the road; tapping elsewhere closes it. + Every tap is also printed as a `BostonRoadTap` line. + + Launch environment, so a measurement opens the same view on every provider: + `MAPCONDUCTOR_SAMPLE_INIT_CAMERA` ("lat,lng,zoom"), + `MAPCONDUCTOR_SAMPLE_ROADS_TILING` (0 = off), `MAPCONDUCTOR_SAMPLE_ROADS_STACKING` (1 = on), + `MAPCONDUCTOR_SAMPLE_ROADS_CYCLE` ("maplibre,googlemaps,…[,seconds]": switch the + provider through the list, printing the memory footprint after each). + Same data and behaviour as the React and Android samples. + */ +@MainActor +final class BostonRoadsViewModel: ObservableObject { + static let tapped = UIColor(red: 37 / 255, green: 99 / 255, blue: 235 / 255, alpha: 1) + + let initCameraPosition: MapCameraPosition + + @Published private(set) var tiling: Bool + @Published private(set) var stacking: Bool + @Published private(set) var polylineList = BostonPolylineList([]) + var polylines: [PolylineState] { polylineList.states } + @Published private(set) var stats: BostonRoadStats? + @Published private(set) var phase: BostonLoadPhase? + @Published private(set) var loadError: String? + @Published private(set) var tap: BostonRoadTap? + /// From the start of loading to the last `onAdded`, and to the first. + @Published private(set) var allAddedMs: Double? + @Published private(set) var firstAddedMs: Double? + @Published private(set) var addedCount = 0 + @Published private(set) var footprintMB: Double = BostonRoadsViewModel.footprintMB() + let stackingOverlays: BostonStackingOverlays + + var tilingOptions: PolylineTilingOptions { tiling ? .Default : .Disabled } + + private var roads: [BostonRoad] = [] + private var highlighted: (state: PolylineState, color: UIColor)? + private var loadTask: Task? + private var started = 0.0 + private var loadMs = 0.0 + private var buildMs = 0.0 + // Which roads of this load have reached the map, from their `onAdded`. + private var generation = 0 + private var addedIds: Set = [] + private var expected = 0 + + init() { + let env = ProcessInfo.processInfo.environment + let parts = env["MAPCONDUCTOR_SAMPLE_INIT_CAMERA"]?.split(separator: ",").compactMap { Double($0) } ?? [] + let (lat, lng, zoom) = parts.count == 3 ? (parts[0], parts[1], parts[2]) : (42.3555, -71.0605, 15.0) + initCameraPosition = MapCameraPosition( + position: GeoPoint(latitude: lat, longitude: lng), zoom: zoom, bearing: 0, tilt: 0, paddings: nil + ) + tiling = env["MAPCONDUCTOR_SAMPLE_ROADS_TILING"] != "0" + stacking = env["MAPCONDUCTOR_SAMPLE_ROADS_STACKING"] == "1" + stackingOverlays = Self.makeStackingOverlays() + } + + func start() { + if roads.isEmpty, loadTask == nil { load() } + } + + /// Turns tiling on or off and loads the roads again, timing the load. + func setTiling(_ on: Bool) { + guard on != tiling else { return } + tiling = on + load() + } + + func setStacking(_ on: Bool) { + stacking = on + } + + func onMapClick(_ point: GeoPoint) { + onTap(state: nil, road: nil, point: point) + } + + func refreshFootprint() { + footprintMB = Self.footprintMB() + } + + private func load() { + loadTask?.cancel() + polylineList = BostonPolylineList([]) + stats = nil + loadError = nil + tap = nil + highlighted = nil + allAddedMs = nil + firstAddedMs = nil + addedCount = 0 + generation += 1 + let generation = self.generation + addedIds = [] + expected = 0 + phase = .read(loaded: 0, total: 0) + started = CACurrentMediaTime() + let tiling = self.tiling + print(String(format: "ROADS load tiling=%d t=%.3f", tiling ? 1 : 0, started)) + loadTask = Task { [weak self] in + do { + let roads = try await BostonRoadsLoader.load { [weak self] progress in + guard let self, self.generation == generation, self.phase != nil else { return } + self.phase = progress + } + guard let self, !Task.isCancelled, self.generation == generation else { return } + self.loadMs = (CACurrentMediaTime() - self.started) * 1000 + self.phase = .build + await Task.yield() + try? await Task.sleep(nanoseconds: 16_000_000) + let built = CACurrentMediaTime() + let onTap: (PolylineEvent, BostonRoad) -> Void = { [weak self] event, road in + MainActor.assumeIsolated { + self?.onTap(state: event.state, road: road, point: GeoPoint.from(position: event.clicked)) + } + } + let onAdded: OnPolylineAddedHandler = { [weak self] state in + MainActor.assumeIsolated { self?.roadAdded(state.id, generation: generation) } + } + let states = await Task.detached(priority: .userInitiated) { + roads.map { Self.makeState($0, onTap: onTap, onAdded: onAdded) } + }.value + guard !Task.isCancelled, self.generation == generation else { return } + self.buildMs = (CACurrentMediaTime() - built) * 1000 + self.roads = roads + self.expected = states.count + let vertices = roads.reduce(0) { $0 + $1.vertexCount } + self.stats = BostonRoadStats(polylines: states.count, vertices: vertices, loadMs: self.loadMs, buildMs: self.buildMs) + print(String( + format: "ROADS shown polylines=%d vertices=%d load=%.0fms build=%.0fms t=%.3f", + states.count, vertices, self.loadMs, self.buildMs, CACurrentMediaTime() + )) + self.phase = .draw + self.polylineList = BostonPolylineList(states) + self.finishDrawingIfAllAdded() + } catch { + guard let self, !Task.isCancelled else { return } + self.phase = nil + self.loadError = error.localizedDescription + } + self?.loadTask = nil + } + } + + /// `onAdded` of the road `id`: it is on the map (natively, or in the tile + /// layer the map has been given; the tile images may still be loading). + private func roadAdded(_ id: String, generation: Int) { + guard generation == self.generation, addedIds.insert(id).inserted else { return } + addedCount = addedIds.count + if addedIds.count == 1 { + firstAddedMs = (CACurrentMediaTime() - started) * 1000 + print(String(format: "ROADS firstAdded ms=%.0f t=%.3f", firstAddedMs ?? 0, CACurrentMediaTime())) + } + finishDrawingIfAllAdded() + } + + private func finishDrawingIfAllAdded() { + guard phase == .draw, expected > 0, addedIds.count >= expected else { return } + phase = nil + allAddedMs = (CACurrentMediaTime() - started) * 1000 + refreshFootprint() + print(String( + format: "ROADS added count=%d tiling=%d ms=%.0f footprint=%.0fMB t=%.3f", + addedIds.count, tiling ? 1 : 0, allAddedMs ?? 0, footprintMB, CACurrentMediaTime() + )) + } + + /// Moves the highlight to `state` (or clears it) and records the tap. + private func onTap(state: PolylineState?, road: BostonRoad?, point: GeoPoint?) { + if let previous = highlighted { previous.state.strokeColor = previous.color } + highlighted = state.map { ($0, $0.strokeColor) } + state?.strokeColor = Self.tapped + let seq = (tap?.seq ?? 0) + 1 + tap = BostonRoadTap(seq: seq, road: road, point: point) + print("BostonRoadTap seq=\(seq) id=\(road?.id ?? "") lat=\(point?.latitude ?? .nan) lng=\(point?.longitude ?? .nan)") + } + + nonisolated private static func makeState( + _ road: BostonRoad, + onTap: @escaping (PolylineEvent, BostonRoad) -> Void, + onAdded: @escaping OnPolylineAddedHandler + ) -> PolylineState { + let points = stride(from: 0, to: road.points.count, by: 2).map { + GeoPoint(latitude: road.points[$0 + 1], longitude: road.points[$0]) as GeoPointProtocol + } + return PolylineState( + points: points, + id: road.id, + strokeColor: road.road.color, + strokeWidth: road.road.width, + zIndex: road.road.zIndex, + extra: road.id, + onClick: { event in onTap(event, road) }, + onAdded: onAdded + ) + } + + /// 50 x 50 translucent squares (enough to be tiled) over Downtown Crossing, + /// a circle, a geodesic (so natively drawn) line and three markers on top. + nonisolated private static func makeStackingOverlays() -> BostonStackingOverlays { + var polygons: [PolygonState] = [] + let lat0 = 42.3500, lng0 = -71.0680, step = 0.00025, size = 0.0002 + for i in 0..<2_500 { + let lat = lat0 + Double(i / 50) * step, lng = lng0 + Double(i % 50) * step + polygons.append(PolygonState( + points: [ + GeoPoint(latitude: lat, longitude: lng), + GeoPoint(latitude: lat, longitude: lng + size), + GeoPoint(latitude: lat + size, longitude: lng + size), + GeoPoint(latitude: lat + size, longitude: lng), + ], + id: "stack-polygon-\(i)", + strokeColor: .clear, + strokeWidth: 0, + fillColor: UIColor(red: 0.2, green: 0.4, blue: 1, alpha: 0.35) + )) + } + let circle = CircleState( + center: GeoPoint(latitude: 42.3555, longitude: -71.0605), + radiusMeters: 180, + strokeColor: UIColor(red: 0.6, green: 0, blue: 0.6, alpha: 1), + strokeWidth: 2, + fillColor: UIColor(red: 0.8, green: 0.2, blue: 0.8, alpha: 0.6), + id: "stack-circle" + ) + let geodesic = PolylineState( + points: [GeoPoint(latitude: 42.3505, longitude: -71.0650), GeoPoint(latitude: 42.3605, longitude: -71.0560)], + id: "stack-geodesic", + strokeColor: UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1), + strokeWidth: 6, + geodesic: true, + zIndex: -100 + ) + let markers = [(42.3555, -71.0605), (42.3540, -71.0620), (42.3570, -71.0590)].enumerated().map { i, p in + MarkerState(position: GeoPoint(latitude: p.0, longitude: p.1), id: "stack-marker-\(i)") + } + return BostonStackingOverlays(polygons: polygons, circle: circle, geodesic: geodesic, markers: markers) + } + + /// The process's memory footprint (what iOS counts against the app), in MB. + nonisolated static func footprintMB() -> Double { + var info = task_vm_info_data_t() + var count = mach_msg_type_number_t(MemoryLayout.size / MemoryLayout.size) + let result = withUnsafeMutablePointer(to: &info) { + $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { + task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) + } + } + return result == KERN_SUCCESS ? Double(info.phys_footprint) / 1_048_576 : 0 + } +}