Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : sdk/ios/Example/App/Scenarios.swift10// Module : sdk11// Repository : https://git.spboucher.ai/ka-maps-engine12// Created : 2026-12-0113// Last Modified : 2026-12-0114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import CoreLocation88import Foundation89import KAMaps90import UIKit9192struct ScenarioFailure: Error, CustomStringConvertible {93 let description: String94 init(_ d: String) { description = d }95}9697/// Scénarios scriptés, exécutés DANS l'application sur la vraie carte (vraies tuiles, vrai GPU).98/// Lancement : argument `-scenario <nom>` (ou plusieurs noms séparés par des virgules).99/// Résultats : `Documents/results/<nom>.json` ; points de capture : `Documents/checkpoint.txt`100/// (le script hôte et les essais XCUITest photographient l'écran à chaque point).101@MainActor102final class ScenarioRunner {103 let model: DemoModel104 var map: KAMapController { model.map }105 private var facts: [String: KAJSON] = [:]106 private var checkpointIndex = 0107 private let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]108109 init(model: DemoModel) { self.model = model }110111 static var requested: [String] {112 let a = ProcessInfo.processInfo.arguments113 guard let i = a.firstIndex(of: "-scenario"), i + 1 < a.count else { return [] }114 return a[i + 1].split(separator: ",").map(String.init)115 }116117 static var all: [String] { ["montreal", "quebec", "rural", "mode3d", "markers", "themes", "layers", "camera", "tools", "reveal", "idle", "memwarn", "geo", "a11y", "offline", "pack"] }118119 // MARK: Outils120121 func fact(_ k: String, _ v: KAJSON) { facts[k] = v }122123 func check(_ cond: Bool, _ what: String) throws {124 if !cond { throw ScenarioFailure(what) }125 }126127 func sleep(_ s: Double) async { try? await Task.sleep(for: .milliseconds(Int(s * 1000))) }128129 /// Attend un événement arrivé après `mark` (indice du journal).130 @discardableResult131 func wait(_ what: String, since mark: Int, timeout: Double = 25, _ pred: (KAMapEvent) -> Bool) async throws -> KAMapEvent {132 let end = Date().addingTimeInterval(timeout)133 var i = mark134 while Date() < end {135 while i < model.log.count {136 if pred(model.log[i].event) { return model.log[i].event }137 i += 1138 }139 await sleep(0.03)140 }141 let tail = model.log[min(mark, model.log.count)...].suffix(8).map(\.event.name).joined(separator: " ")142 throw ScenarioFailure("délai dépassé en attendant « \(what) » (\(timeout) s) ; événements depuis : [\(tail)] ; boucle suspendue : \(map.mapView?.isRenderLoopPaused ?? true) ; caméra \(map.camera.zoom) ; perf \((try? map.command("getPerf").encoded()) ?? "?") ; réseau \(map.networkStats)")143 }144145 var mark: Int { model.log.count }146147 func waitIdle(since m: Int, timeout: Double = 30) async throws {148 try await wait("idle", since: m, timeout: timeout) { if case .idle = $0 { return true } else { return false } }149 }150151 /// Exécute `body` puis attend le repos complet (tuiles chargées, animations finies).152 func settle(timeout: Double = 30, _ body: () throws -> Void) async throws {153 let m = mark154 try body()155 try await waitIdle(since: m, timeout: timeout)156 }157158 /// Attend que la carte soit prête (première vue chargée).159 func ready() async throws {160 let end = Date().addingTimeInterval(40)161 while Date() < end {162 if map.isReady, model.log.contains(where: { if case .load = $0.event { return true } else { return false } }) { return }163 await sleep(0.05)164 }165 throw ScenarioFailure("la carte n'a pas fini son premier chargement (40 s) — \(map.mapView?.creationError?.message ?? model.lastEventLine)")166 }167168 /// Point de capture : fige l'écran le temps que l'hôte photographie.169 func checkpoint(_ name: String) async {170 checkpointIndex += 1171 map.mapView?.renderNow()172 model.status = "SHOT \(name)"173 try? "\(checkpointIndex) \(name)".write(to: docs.appendingPathComponent("checkpoint.txt"), atomically: true, encoding: .utf8)174 await sleep(1.4)175 }176177 func noGpuErrors() throws {178 let errs = model.log.compactMap { e -> String? in if case .error(let m) = e.event { return m } else { return nil } }179 fact("engineErrors", .array((errs.prefix(3) + errs.suffix(3)).map { .string(String($0.prefix(700))) }))180 try check(map.gpuErrorCount == 0, "erreurs de validation GPU : \(map.gpuErrorCount)")181 }182183 // MARK: Boucle184185 func runAll(_ names: [String]) async {186 let dir = docs.appendingPathComponent("results", isDirectory: true)187 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)188 var failed: [String] = []189 for name in names {190 facts = [:]191 model.status = "RUN \(name)"192 let t0 = Date()193 var errorText: String?194 do {195 try await ready()196 try await run(name)197 try noGpuErrors()198 } catch {199 errorText = "\(error)"200 failed.append(name)201 }202 facts["scenario"] = .string(name)203 facts["ok"] = .bool(errorText == nil)204 facts["error"] = errorText.map(KAJSON.string) ?? .null205 facts["seconds"] = .number((Date().timeIntervalSince(t0) * 100).rounded() / 100)206 facts["frames"] = .number(Double(map.frameCount))207 facts["gpuErrors"] = .number(Double(map.gpuErrorCount))208 facts["footprintMB"] = .number((Double(physFootprint()) / 1_048_576 * 10).rounded() / 10)209 facts["engine"] = .string(KAMapController.engineVersion)210 facts["device"] = .string("\(UIDevice.current.model) \(UIDevice.current.systemName) \(UIDevice.current.systemVersion)\(ProcessInfo.processInfo.environment["SIMULATOR_DEVICE_NAME"] != nil ? " (simulateur)" : "")")211 try? KAJSON.object(facts).encoded().write(to: dir.appendingPathComponent("\(name).json"), atomically: true, encoding: .utf8)212 }213 model.status = failed.isEmpty ? "DONE ok" : "DONE FAIL \(failed.joined(separator: ","))"214 try? model.status.write(to: docs.appendingPathComponent("done.txt"), atomically: true, encoding: .utf8)215 }216217 private func run(_ name: String) async throws {218 switch name {219 case "montreal": try await place(.montreal)220 case "quebec": try await place(.quebec)221 case "rural": try await place(.rural)222 case "mode3d": try await mode3d()223 case "markers": try await markers()224 case "themes": try await themes()225 case "layers": try await layers()226 case "camera": try await camera()227 case "tools": try await tools()228 case "reveal": try await reveal()229 case "idle": try await idle()230 case "memwarn": try await memoryWarning()231 case "geo": try await geo()232 case "a11y": try await accessibility()233 case "offline": try await offline()234 case "pack": try await pack(live: false)235 case "packlive": try await pack(live: true)236 case "start3d": try await start3d()237 case "annotations": try await annotations()238 case "options": try await options()239 case "twomaps": try await twoMaps()240 case "deviceloss": try await deviceLoss()241 case "keyboard": try await keyboard()242 case "dyntype": try await dynamicType()243 case "reconnect": try await reconnect()244 case "stale": try await stale()245 case "idxkill": try await indexKill()246 case "bgstart": try await bgStart()247 case "bgfinish": try await bgFinish()248 case "engine8": try await engine8()249 case "engine12": try await engine12()250 case "staleframe": try await staleFrame()251 case "zones": try await zones()252 case "textscale": try await textScale()253 case "engine10": try await engine10()254 case "selection": try await selection()255 case "soak": try await soak()256 case "bench": try await bench()257 default: throw ScenarioFailure("scénario inconnu : \(name)")258 }259 }260261 func reset(_ p: DemoPlace = .montreal, zoom: Double? = nil, layers: Set<KALayerKind> = []) async throws {262 model.enabledLayers = layers263 model.place = p264 model.selectedLabel = nil265 model.annotationCount = 0266 if model.mode != .flat {267 try await settle { model.mode = .flat }268 }269 // SwiftUI applique le tableau de couches à sa prochaine passe : l'attendre avant de mesurer.270 let end = Date().addingTimeInterval(3)271 while Set(map.layers.map(\.kind)) != layers, Date() < end { await sleep(0.02) }272 try await settle { map.jumpTo(KACamera(center: p.coordinate, zoom: zoom ?? p.zoom)) }273 }274275 // MARK: Scénarios276277 /// Vraies tuiles d'un lieu : la vue se charge, des tuiles sont dessinées, le réseau a servi.278 private func place(_ p: DemoPlace) async throws {279 try await reset(p)280 let perf = try map.perf()281 let net = map.networkStats282 fact("tiles", .number(Double(perf.tiles)))283 fact("drawCalls", .number(Double(perf.drawCalls)))284 fact("triangles", .number(Double(perf.triangles)))285 fact("labels", .number(Double(perf.labels)))286 fact("netCompleted", .number(Double(net.completed)))287 fact("dataVersion", .string(net.dataVersion ?? ""))288 try check(perf.tiles > 0, "aucune tuile dessinée à \(p.title)")289 try check(perf.triangles > 500, "géométrie trop pauvre à \(p.title) : \(perf.triangles) triangles")290 // Le fond contient de vraies entités sous le centre de l'écran ou autour.291 let size = map.mapView?.bounds.size ?? .zero292 var hits = 0293 for (fx, fy) in [(0.5, 0.5), (0.3, 0.4), (0.7, 0.6), (0.4, 0.7), (0.6, 0.3)] {294 hits += try map.queryRendered(at: CGPoint(x: size.width * fx, y: size.height * fy)).count295 }296 fact("featuresUnderProbes", .number(Double(hits)))297 try check(hits > 0, "aucune entité sous cinq sondes à \(p.title)")298 await checkpoint("place-\(p.rawValue)")299 }300301 /// Carte créée en mode 3D alors que la caméra liée est à plat (à lancer avec `-startMode 3d`) : elle302 /// doit rester inclinée — la liaison ne la remet pas à plat à sa première passe.303 private func start3d() async throws {304 try check(ProcessInfo.processInfo.arguments.contains("-startMode"), "à lancer avec -startMode 3d")305 await sleep(1.5)306 fact("pitch", .number(map.camera.pitch))307 try check(map.camera.pitch > 40, "la carte créée en 3D est revenue à plat : inclinaison \(map.camera.pitch)")308 try check(model.mode == .volumes && map.mode == .volumes, "le mode doit rester 3D")309 // Un premier mouvement remet la liaison à jour avec la vraie caméra.310 try await settle { map.easeTo(KACameraUpdate(zoom: map.camera.zoom + 0.3), duration: 0.3) }311 await sleep(0.3)312 try check(model.camera.pitch > 40 && map.camera.pitch > 40, "après un mouvement, liaison \(model.camera.pitch)°, carte \(map.camera.pitch)°")313 await checkpoint("start-3d")314 }315316 /// Bascule 2D ↔ 3D animée.317 private func mode3d() async throws {318 try await reset(.montreal, zoom: 16.2)319 await checkpoint("mode-2d")320 try await settle { model.mode = .volumes }321 let c3 = map.camera322 fact("pitch3d", .number(c3.pitch))323 try check(c3.pitch > 40, "inclinaison 3D attendue > 40°, obtenue \(c3.pitch)")324 try check(try map.command("getMode").stringValue == "3d", "le moteur n'est pas en mode 3D")325 await checkpoint("mode-3d")326 try await settle { model.mode = .flat }327 let c2 = map.camera328 fact("pitch2d", .number(c2.pitch))329 try check(c2.pitch < 1, "inclinaison 2D attendue 0°, obtenue \(c2.pitch)")330 }331332 /// Grappes au dézoom, pastilles au zoom, toucher d'une pastille → sélection.333 private func markers() async throws {334 try await reset(.montreal, zoom: 11.5, layers: [.markers])335 let all = DemoData.layer(.markers, around: DemoPlace.montreal.coordinate, brand: model.brand).markers336 func census() throws -> (clusters: Int, singles: Int, clustered: Int) {337 var clusterIDs = Set<Int>(), singles = 0, clustered = 0338 for m in all {339 guard let p = map.project(m.coordinate), map.mapView?.bounds.contains(p) == true, let (f, _) = map.renderedMarker(layer: "markers", id: m.id) else { continue }340 if f.kind == .cluster, let id = f.clusterID {341 if clusterIDs.insert(id).inserted { clustered += f.clusterCount ?? 0 }342 } else {343 singles += 1344 }345 }346 return (clusterIDs.count, singles, clustered)347 }348 let far = try census()349 fact("z11.clusters", .number(Double(far.clusters)))350 fact("z11.singles", .number(Double(far.singles)))351 fact("z11.clusteredPoints", .number(Double(far.clustered)))352 try check(far.clusters >= 2, "grappes attendues à z11,5 : \(far.clusters)")353 try check(far.clustered > far.singles, "à z11,5 la plupart des points devraient être en grappe")354 await checkpoint("markers-clusters")355356 // Toucher d'une grappe : zoom jusqu'à l'éclatement.357 if let p = all.lazy.compactMap({ self.map.renderedMarker(layer: "markers", id: $0.id) }).first(where: { $0.feature.kind == .cluster })?.point {358 let z0 = map.camera.zoom359 let mk = mark360 map.mapView?.simulateTap(at: p)361 try await wait("cluster:click", since: mk, timeout: 5) { if case .clusterClick = $0 { return true } else { return false } }362 try await waitIdle(since: mk)363 fact("clusterTapZoomGain", .number(map.camera.zoom - z0))364 try check(map.camera.zoom > z0 + 0.5, "le toucher d'une grappe doit zoomer (z \(z0) → \(map.camera.zoom))")365 }366367 try await settle { map.jumpTo(KACamera(center: DemoPlace.montreal.coordinate, zoom: 16)) }368 let near = try census()369 fact("z16.clusters", .number(Double(near.clusters)))370 fact("z16.singles", .number(Double(near.singles)))371 try check(near.singles >= 1, "pastilles individuelles attendues à z16")372 try check(near.clusters == 0, "aucune grappe attendue à z16 (maxZoom 15) : \(near.clusters)")373374 // Toucher d'une pastille (même chemin que le reconnaisseur de toucher).375 guard let target = all.first(where: { m in376 guard let r = map.renderedMarker(layer: "markers", id: m.id), r.feature.kind == .marker else { return false }377 return map.mapView?.bounds.insetBy(dx: 30, dy: 130).contains(r.point) == true378 }), let p = map.renderedMarker(layer: "markers", id: target.id)?.point else { throw ScenarioFailure("aucune pastille touchable à z16") }379 let mk = mark380 map.mapView?.simulateTap(at: p)381 let ev = try await wait("select", since: mk, timeout: 5) { if case .select = $0 { return true } else { return false } }382 guard case .select(let f) = ev else { throw ScenarioFailure("select attendu") }383 try check(f.id == target.id, "pastille sélectionnée \(f.id ?? "?") ≠ touchée \(target.id)")384 try check(map.selection == KASelection(layer: "markers", id: target.id), "sélection du contrôleur non mise à jour")385 await sleep(0.3)386 try check(model.selection == KASelection(layer: "markers", id: target.id), "liaison SwiftUI de sélection non mise à jour")387 fact("selected", .string(target.id))388 await checkpoint("markers-selected")389 // Toucher le fond : la sélection s'efface.390 let empty = CGPoint(x: 12, y: (map.mapView?.bounds.height ?? 400) * 0.5)391 if (try map.queryRendered(at: empty, layers: ["markers"])).isEmpty {392 map.mapView?.simulateTap(at: empty)393 await sleep(0.4)394 try check(map.selection == nil, "le toucher du fond doit effacer la sélection")395 }396 }397398 /// Tous les thèmes embarqués × les quatre marques, à chaud, sans requête réseau.399 private func themes() async throws {400 try await reset(.montreal, zoom: 15.2, layers: [.markers])401 try await settle { model.mode = .volumes }402 let themes = try map.embeddedThemes()403 fact("embeddedThemes", .array(themes.map { .string($0.rawValue) }))404 try check(themes.count >= 3, "au moins trois thèmes embarqués attendus")405 let net0 = map.networkStats.requests406 var combos = 0407 for b in KABrand.allCases {408 for t in themes {409 let m = mark410 let changes = model.brand != b || model.theme != t411 model.brand = b412 model.theme = t413 if changes { try await waitIdle(since: m) }414 let got = try map.command("getTheme")415 try check(got["name"]?.stringValue == t.rawValue, "thème \(t.rawValue) non appliqué : \(got.encoded())")416 try check(got["brand"]?.stringValue == b.rawValue, "marque \(b.rawValue) non appliquée")417 combos += 1418 await checkpoint("theme-\(b.rawValue)-\(t.rawValue)")419 }420 }421 fact("combinations", .number(Double(combos)))422 fact("networkRequestsDuringSwitch", .number(Double(map.networkStats.requests - net0)))423 // Thème inconnu : erreur propre, la carte garde son thème.424 let m = mark425 map.setTheme("inexistant")426 try await wait("error", since: m, timeout: 3) { if case .error = $0 { return true } else { return false } }427 try check(map.theme == model.theme, "un thème refusé ne doit pas remplacer le thème courant")428 model.brand = .louka429 model.theme = .signature430 try await settle { model.mode = .flat }431432 // Apparence claire / sombre : le thème suit quand l'application le demande.433 guard let window = map.mapView?.window else { throw ScenarioFailure("fenêtre absente") }434 model.followsInterfaceStyle = true435 await sleep(0.3)436 var mk = mark437 window.overrideUserInterfaceStyle = .dark438 try await waitIdle(since: mk)439 try check(try map.command("getTheme")["name"]?.stringValue == "midnight", "apparence sombre : thème midnight attendu")440 await checkpoint("theme-auto-dark")441 mk = mark442 window.overrideUserInterfaceStyle = .light443 try await waitIdle(since: mk)444 try check(try map.command("getTheme")["name"]?.stringValue == "signature", "apparence claire : thème signature attendu")445 window.overrideUserInterfaceStyle = .unspecified446 model.followsInterfaceStyle = false447 await sleep(0.3)448 }449450 /// Les huit types de couches d'application.451 private func layers() async throws {452 try await reset(.montreal, zoom: 14.2)453 let m = mark454 try await settle(timeout: 40) { model.enabledLayers = Set(KALayerKind.allCases) }455 await sleep(0.2)456 let listed = try map.command("listLayers").arrayValue ?? []457 fact("layers", .array(listed))458 try check(listed.count == 8, "huit couches attendues, \(listed.count) présentes")459 // `count` ne compte pas les cellules d'une grille : la surface est vérifiée à l'image.460 for l in listed where l["type"]?.stringValue != "surface" { try check((l["count"]?.intValue ?? 0) > 0, "couche \(l["id"]?.stringValue ?? "?") vide") }461 let match = model.log[m...].compactMap { e -> KABuildingsMatch? in if case .buildingsMatch(let b) = e.event { return b } else { return nil } }.last462 if let match {463 fact("buildings.inside", .number(Double(match.inside)))464 fact("buildings.near", .number(Double(match.near)))465 fact("buildings.unmatched", .number(Double(match.unmatchedCount)))466 }467 try check(match != nil, "événement buildings:match attendu")468 try check((match?.inside ?? 0) + (match?.near ?? 0) > 0, "aucun point rattaché à une vraie empreinte")469 await checkpoint("layers-2d")470 try await settle { model.mode = .volumes }471 await checkpoint("layers-3d")472 // Bloc binaire : 20 000 points sans JSON.473 var rows: [Double] = []474 var r = SeededRandom(seed: 99)475 for _ in 0..<20_000 {476 rows += [DemoPlace.montreal.coordinate.longitude + (r.next() - 0.5) * 0.2, DemoPlace.montreal.coordinate.latitude + (r.next() - 0.5) * 0.12, r.next()]477 }478 let t0 = CACurrentMediaTime()479 let n = try map.setLayerPoints("points", rows: rows)480 fact("bulkPoints", .number(Double(n)))481 fact("bulkMs", .number(((CACurrentMediaTime() - t0) * 1000 * 10).rounded() / 10))482 try check(n == 20_000, "bloc binaire : \(n) points retenus sur 20 000")483 try await settle { map.setLayerVisible("heat", false) }484 // Retrait : la carte suit le tableau SwiftUI.485 try await settle { model.enabledLayers = [.markers] }486 await sleep(0.2)487 try check((try map.command("listLayers").arrayValue ?? []).count == 1, "les couches retirées du tableau doivent disparaître")488 try await settle { model.mode = .flat }489 }490491 /// Caméra : flyTo, fitBounds avec marges, orbite, visite, project/unproject.492 private func camera() async throws {493 try await reset(.montreal, zoom: 12)494 try await settle(timeout: 40) { map.flyTo(KACameraUpdate(center: DemoPlace.quebec.coordinate, zoom: 13), duration: 2.5) }495 let c = map.camera496 try check(abs(c.center.latitude - DemoPlace.quebec.coordinate.latitude) < 1e-4 && abs(c.zoom - 13) < 0.01, "flyTo n'a pas atteint Québec : \(c)")497 await sleep(0.3)498 try check(model.camera.isClose(to: c), "liaison SwiftUI de caméra non mise à jour")499500 // Liaison SwiftUI → carte.501 try await settle { model.camera = KACamera(center: DemoPlace.montreal.coordinate, zoom: 14) }502 try check(abs(map.camera.zoom - 14) < 0.01, "la liaison de caméra doit déplacer la carte")503504 // fitBounds : le cadre tient dans la zone utile (zones sûres + marges de contenu).505 let b = KABounds(west: -73.60, south: 45.49, east: -73.54, north: 45.52)506 try await settle { map.fitBounds(b, padding: KAEdgeInsets(all: 20)) }507 guard let view = map.mapView, let nw = map.project(CLLocationCoordinate2D(latitude: b.north, longitude: b.west)), let se = map.project(CLLocationCoordinate2D(latitude: b.south, longitude: b.east)) else { throw ScenarioFailure("projection impossible") }508 let safe = view.safeAreaInsets509 let usable = view.bounds.inset(by: UIEdgeInsets(top: safe.top + 52, left: safe.left, bottom: safe.bottom + 64, right: safe.right))510 fact("fit.nw", [.number(nw.x.rounded()), .number(nw.y.rounded())])511 fact("fit.se", [.number(se.x.rounded()), .number(se.y.rounded())])512 try check(nw.x >= usable.minX + 18 && nw.y >= usable.minY + 18 && se.x <= usable.maxX - 18 && se.y <= usable.maxY - 18, "fitBounds déborde de la zone utile : \(nw) \(se) dans \(usable)")513 try check(min(nw.x - usable.minX, usable.maxX - se.x) < 24 || min(nw.y - usable.minY, usable.maxY - se.y) < 24, "fitBounds trop lâche : \(nw) \(se) dans \(usable)")514 await checkpoint("camera-fit")515516 // Même cadrage, carte tournée et inclinée : le cadre reste dans la zone utile (marges gérées par le moteur).517 try await settle { map.jumpTo(KACameraUpdate(bearing: 35, pitch: 40)) }518 try await settle { map.fitBounds(b, padding: KAEdgeInsets(all: 20)) }519 let corners = [(b.north, b.west), (b.north, b.east), (b.south, b.west), (b.south, b.east)].compactMap { map.project(CLLocationCoordinate2D(latitude: $0.0, longitude: $0.1)) }520 try check(corners.count == 4 && corners.allSatisfy { usable.insetBy(dx: 17, dy: 17).contains($0) }, "fitBounds tourné et incliné déborde de la zone utile : \(corners) dans \(usable)")521 fact("fit.rotated", .array(corners.map { [.number($0.x.rounded()), .number($0.y.rounded())] }))522 try await settle { map.jumpTo(KACameraUpdate(bearing: 0, pitch: 0)) }523524 // Marges sur un déplacement : la cible arrive au centre de la zone utile, pas au centre de la vue.525 let target = CLLocationCoordinate2D(latitude: 45.5088, longitude: -73.5617)526 try await settle { map.easeTo(KACameraUpdate(center: target, zoom: 15), duration: 0.4, padding: .contentInsets) }527 guard let tp = map.project(target) else { throw ScenarioFailure("projection de la cible impossible") }528 fact("padding.target", [.number(tp.x.rounded()), .number(tp.y.rounded())])529 try check(hypot(tp.x - usable.midX, tp.y - usable.midY) < 2, "easeTo avec marges : cible en \(tp), centre utile \(CGPoint(x: usable.midX, y: usable.midY))")530531 // project ↔ unproject.532 let p = CGPoint(x: view.bounds.width * 0.3, y: view.bounds.height * 0.6)533 guard let ll = map.unproject(p), let back = map.project(ll) else { throw ScenarioFailure("unproject impossible") }534 try check(hypot(back.x - p.x, back.y - p.y) < 0.01, "project(unproject(p)) ≠ p")535536 // Orbite courte.537 var m = mark538 map.orbit(center: DemoPlace.montreal.coordinate, zoom: 16, pitch: 55, turns: 0.25, duration: 2.5)539 await sleep(1.2)540 await checkpoint("camera-orbit")541 try await wait("moveend", since: m, timeout: 15) { if case .moveEnd = $0 { return true } else { return false } }542 let ob = map.camera543 fact("orbit.bearing", .number(ob.bearing))544 try check(abs(abs(ob.bearing) - 90) < 2 || abs(abs(ob.bearing) - 270) < 2, "un quart de tour attendu, cap \(ob.bearing)")545546 // Visite : deux étapes annoncées.547 m = mark548 map.tour([KATourStop(camera: KACameraUpdate(center: DemoPlace.montreal.coordinate, zoom: 15, pitch: 40), hold: 0.3), KATourStop(camera: KACameraUpdate(center: CLLocationCoordinate2D(latitude: 45.51, longitude: -73.55), zoom: 15.5), hold: 0.3)], legDuration: 1.2)549 try await wait("tour:stop 1", since: m, timeout: 20) { if case .tourStop(let i) = $0 { return i == 1 } else { return false } }550 try await waitIdle(since: m, timeout: 30)551 fact("tourStops", .number(Double(model.log[m...].filter { if case .tourStop = $0.event { return true } else { return false } }.count)))552 try await settle { map.setMode(.flat) }553 }554555 /// Dessin et mesures géodésiques.556 private func tools() async throws {557 try await reset(.montreal, zoom: 15)558 let c = DemoPlace.montreal.coordinate559 let ring = [CLLocationCoordinate2D(latitude: c.latitude, longitude: c.longitude), CLLocationCoordinate2D(latitude: c.latitude, longitude: c.longitude + 0.004), CLLocationCoordinate2D(latitude: c.latitude + 0.003, longitude: c.longitude + 0.004), CLLocationCoordinate2D(latitude: c.latitude + 0.003, longitude: c.longitude)]560 var m = mark561 map.startDraw(.polygon)562 model.isDrawing = true563 // Trois sommets posés par de vrais touchers, le quatrième par l'API.564 for v in ring.prefix(3) {565 guard let p = map.project(v) else { throw ScenarioFailure("sommet hors écran") }566 map.mapView?.simulateTap(at: p)567 await sleep(0.1)568 }569 map.drawAddPoint(ring[3])570 await sleep(0.3)571 await checkpoint("tools-draw")572 map.finishDraw()573 let ev = try await wait("draw:done", since: m, timeout: 5) { if case .drawDone = $0 { return true } else { return false } }574 guard case .drawDone(let d) = ev else { throw ScenarioFailure("draw:done attendu") }575 // Rectangle d'environ 312 m × 334 m à 45,5° N.576 fact("draw.area", .number(d.area ?? 0))577 fact("draw.perimeter", .number(d.perimeter ?? 0))578 try check(d.points == 4, "quatre sommets attendus : \(d.points)")579 try check(abs((d.area ?? 0) - 104_200) < 3000, "superficie attendue ≈ 104 200 m², obtenue \(d.area ?? 0)")580 let (area, perimeter) = try map.measureArea(ring)581 try check(abs(area - (d.area ?? 0)) < 2500, "measureArea (\(area)) ≠ dessin (\(d.area ?? 0))")582 fact("measure.perimeter", .number(perimeter))583 let dist = try map.measureDistance([DemoPlace.montreal.coordinate, DemoPlace.quebec.coordinate])584 fact("measure.mtlQuebecKm", .number((dist / 10).rounded() / 100))585 try check(abs(dist - 233_600) < 2500, "Montréal–Québec attendu ≈ 233,6 km, obtenu \(dist / 1000)")586 // Ligne, puis abandon.587 m = mark588 map.startDraw(.line)589 map.drawAddPoint(ring[0])590 map.drawAddPoint(ring[1])591 map.stopDraw()592 try await wait("draw:cancel", since: m, timeout: 5) { if case .drawCancel = $0 { return true } else { return false } }593 }594595 /// Animation signature Lou-Ka et mise en évidence d'un vrai bâtiment.596 private func reveal() async throws {597 try await reset(.montreal, zoom: 14.5)598 let target = CLLocationCoordinate2D(latitude: 45.50170, longitude: -73.56730)599 let m = mark600 let started = try map.reveal(target: target, duration: 2.0)601 try check(started, "reveal ignoré (animations réduites ?)")602 try await wait("reveal:open", since: m, timeout: 20) { if case .revealOpen = $0 { return true } else { return false } }603 let c = map.camera604 fact("reveal.zoom", .number(c.zoom))605 fact("reveal.pitch", .number(c.pitch))606 try check(c.zoom > 16.5 && c.pitch > 40, "l'approche de reveal doit finir près et inclinée : \(c)")607 let sel = model.log[m...].compactMap { e -> KAFeature? in if case .select(let f) = e.event { return f } else { return nil } }.last608 fact("reveal.building", sel?.raw ?? .null)609 await checkpoint("reveal")610 try await waitIdle(since: m, timeout: 30)611 // Animations réduites : la commande rend « ignorée », l'application ouvre la fiche tout de suite.612 try map.command("setReducedMotion", ["on": true])613 try check(try map.reveal(target: target) == false, "reveal doit être ignoré quand les animations sont réduites")614 try map.command("setReducedMotion", ["on": .bool(UIAccessibility.isReduceMotionEnabled)])615 try await settle { map.clearSelection(); map.setMode(.flat) }616 }617618 /// Rendu à la demande : au repos, plus aucune image n'est dessinée.619 private func idle() async throws {620 try await reset(.montreal)621 await sleep(1.0)622 let f0 = map.frameCount623 let paused0 = map.mapView?.isRenderLoopPaused ?? false624 await sleep(3.0)625 let f1 = map.frameCount626 fact("framesDuring3sIdle", .number(Double(f1 - f0)))627 fact("renderLoopPaused", .bool(paused0))628 try check(paused0, "la boucle d'affichage devrait être suspendue au repos")629 try check(f1 == f0, "\(f1 - f0) image(s) dessinée(s) pendant 3 s de repos")630 // Un geste réveille la boucle, puis elle se rendort.631 let m = mark632 map.easeTo(KACameraUpdate(zoom: map.camera.zoom + 0.5), duration: 0.5)633 try await waitIdle(since: m)634 try check(map.frameCount > f1, "l'animation doit dessiner des images")635 await sleep(0.5)636 try check(map.mapView?.isRenderLoopPaused == true, "la boucle doit se rendormir après l'animation")637 }638639 /// Avertissement mémoire : les tuiles sont abandonnées puis reviennent du stock local, sans réseau.640 private func memoryWarning() async throws {641 try await reset(.montreal, zoom: 15)642 await sleep(0.5)643 let before = try map.perf()644 let fp0 = physFootprint()645 let net0 = map.networkStats.requests646 let m = mark647 map.mapView?.simulateMemoryWarning()648 await sleep(0.15)649 let during = try map.perf()650 try await waitIdle(since: m)651 let after = try map.perf()652 fact("gpuBefore", .number(Double(before.gpuMemory)))653 fact("gpuRightAfterWarning", .number(Double(during.gpuMemory)))654 fact("gpuAfterReload", .number(Double(after.gpuMemory)))655 fact("tilesAfter", .number(Double(after.tiles)))656 fact("footprintDeltaMB", .number(((Double(physFootprint()) - Double(fp0)) / 1_048_576 * 10).rounded() / 10))657 fact("networkRequestsForReload", .number(Double(map.networkStats.requests - net0)))658 try check(during.gpuMemory < before.gpuMemory / 2 || during.tiles < before.tiles, "l'avertissement mémoire doit libérer les tuiles (GPU \(before.gpuMemory) → \(during.gpuMemory))")659 try check(after.tiles > 0, "la vue doit se recharger après l'avertissement")660 }661662 /// Service géo réel : recherche et géocodage inverse.663 private func geo() async throws {664 let client = KAGeoClient()665 let r = try await client.search("1000 rue Sherbrooke Ouest Montréal", near: DemoPlace.montreal.coordinate, limit: 5)666 fact("search.count", .number(Double(r.count)))667 fact("search.first", .string(r.first?.label ?? ""))668 try check(!r.isEmpty, "aucun résultat de recherche")669 try check(r[0].label.contains("Sherbrooke") && abs(r[0].coordinate.latitude - 45.50) < 0.05, "premier résultat inattendu : \(r[0].label)")670 let rev = try await client.reverse(DemoPlace.montreal.coordinate)671 fact("reverse.label", .string(rev.label ?? ""))672 fact("reverse.municipality", .string(rev.municipality?.name ?? ""))673 try check(rev.municipality?.name == "Montréal" && rev.isInQuebec, "géocodage inverse inattendu : \(rev.municipality?.name ?? "nil")")674 try check(!rev.attribution.isEmpty, "attribution des données géo absente")675 do {676 _ = try await client.reverse(CLLocationCoordinate2D(latitude: 10, longitude: 10))677 throw ScenarioFailure("une position hors zone doit être refusée")678 } catch let e as KAMapError {679 fact("outOfArea.message", .string(e.message))680 try check(e.message.count > 12 && !e.message.contains("HTTP 4"), "le message d'erreur du service doit être transmis : \(e.message)")681 }682 let mtl = DemoPlace.montreal.coordinate683 let bounds = try await client.boundaries(at: mtl)684 fact("boundaries", .array(bounds.map { .string($0.id) }))685 guard let muni = bounds.first(where: { $0.level == "municipalite" }) else { throw ScenarioFailure("municipalité absente des limites : \(bounds.map(\.id))") }686 try check(muni.name == "Montréal", "municipalité inattendue : \(muni.name)")687 let places = try await client.nearby(mtl, radiusMeters: 400, limitPerKind: 2)688 fact("nearby.count", .number(Double(places.count)))689 try check(!places.isEmpty && places.allSatisfy { $0.distanceMeters <= 420 }, "lieux proches inattendus : \(places.count)")690 try check(try await client.nearbyKinds().contains { $0.kind == "metro" }, "genre « metro » attendu")691 let iso = try await client.isochrone(from: mtl, minutes: [10], profile: .walking, maxVertices: 60)692 let ring = iso.geoJSON["features"]?[0]?["geometry"]?["coordinates"]693 fact("isochrone.type", .string(iso.geoJSON["features"]?[0]?["geometry"]?["type"]?.stringValue ?? "?"))694 try check(ring != nil && !iso.notice.isEmpty, "isochrone sans géométrie ou sans réserve de méthode")695 let route = try await client.route(from: mtl, to: CLLocationCoordinate2D(latitude: 45.51, longitude: -73.58), profile: .walking)696 fact("route.meters", .number(route.distanceMeters))697 fact("route.minutes", .number((route.durationSeconds / 6).rounded() / 10))698 try check(route.path.count >= 2 && route.distanceMeters > 800 && route.distanceMeters < 3000, "trajet inattendu : \(route.distanceMeters) m, \(route.path.count) points")699 // Isochrone et trajet dessinés tels quels sur la carte.700 try await reset(.montreal, zoom: 14.2)701 try await settle {702 map.addLayer(.polygons(id: "iso", geoJSON: iso.geoJSON, fillColor: "#1f4e79", fillOpacity: 0.16, strokeColor: "#1f4e79", strokeWidth: 2, nature: .estimated))703 map.addLayer(.line(id: "trajet", path: route.path, color: "#b5452c", width: 4))704 }705 await checkpoint("geo-isochrone-route")706 map.removeLayer("iso")707 map.removeLayer("trajet")708 }709710 /// Éléments d'accessibilité : résumé de carte, pastilles visibles, attribution.711 private func accessibility() async throws {712 try await reset(.montreal, zoom: 15.5, layers: [.markers])713 guard let view = map.mapView else { throw ScenarioFailure("vue absente") }714 let els = view.accessibilityElements ?? []715 let labels = els.compactMap { ($0 as? NSObject)?.accessibilityLabel }716 fact("elements", .number(Double(els.count)))717 fact("sample", .array(labels.prefix(6).map(KAJSON.string)))718 try check(els.count >= 3, "au moins trois éléments attendus (carte, pastille, attribution) : \(els.count)")719 try check(labels.contains { $0.hasPrefix("Fictif") }, "aucune pastille exposée à VoiceOver")720 try check(labels.first == "Carte" || labels.first == "Map", "le premier élément doit être la carte")721 let attribution = els.compactMap { $0 as? UIControl }.first722 try check(attribution?.accessibilityValue?.contains("OpenStreetMap") == true, "attribution absente ou sans OpenStreetMap")723 try check(attribution.map { $0.frame.height > 8 && !$0.isHidden && view.bounds.contains($0.frame) } == true, "le bouton d'attribution doit être visible dans la vue")724 // Zoom par l'élément ajustable.725 let z0 = map.camera.zoom726 let m = mark727 (els.first as? UIAccessibilityElement)?.accessibilityIncrement()728 try await waitIdle(since: m)729 try check(map.camera.zoom > z0 + 0.9, "accessibilityIncrement doit zoomer d'un niveau")730 // Activation d'une pastille.731 let els2 = view.accessibilityElements ?? []732 if let marker = els2.compactMap({ $0 as? UIAccessibilityElement }).first(where: { $0.accessibilityLabel?.hasPrefix("Fictif") == true }) {733 let mk = mark734 _ = marker.accessibilityActivate()735 try await wait("select", since: mk, timeout: 5) { if case .select = $0 { return true } else { return false } }736 try check(map.selection != nil, "l'activation VoiceOver doit sélectionner la pastille")737 } else {738 throw ScenarioFailure("plus de pastille exposée après le zoom")739 }740 // Pastille de position fournie par l'application.741 model.userLocation = KAUserLocation(coordinate: map.camera.center, horizontalAccuracy: 40, heading: 30)742 await sleep(0.5)743 let puck = view.subviews.first { $0.accessibilityIdentifier == "KAUserLocation" }744 guard let c = map.project(map.camera.center) else { throw ScenarioFailure("projection impossible") }745 try check(puck?.isHidden == false && hypot((puck?.center.x ?? 0) - c.x, (puck?.center.y ?? 0) - c.y) < 1, "l'élément d'accessibilité de la position doit suivre la pastille")746 await checkpoint("a11y-puck")747 model.userLocation = nil748 map.clearSelection()749 }750751 /// Région hors ligne : téléchargement, puis rendu réseau coupé.752 private func offline() async throws {753 try await reset(.montreal, zoom: 12)754 for r in try map.offlineRegions() { try map.removeRegion(r.id) }755 // Hors de toute vue déjà visitée : Sherbrooke.756 let c = CLLocationCoordinate2D(latitude: 45.4042, longitude: -71.8929)757 let b = KABounds(west: c.longitude - 0.035, south: c.latitude - 0.022, east: c.longitude + 0.035, north: c.latitude + 0.022)758 let m = mark759 let t0 = Date()760 let region = try map.downloadRegion(id: "essai-sherbrooke", name: "Sherbrooke (essai)", bounds: b, minZoom: 9, maxZoom: 14)761 try check(try map.tileStoreUsage().isDownloading, "le moteur doit annoncer le téléchargement en cours")762 fact("region.tilesTotal", .number(Double(region.tilesTotal)))763 try check(region.tilesTotal >= 6, "région trop petite : \(region.tilesTotal) tuiles")764 let done = try await wait("offline:done", since: m, timeout: 120) { if case .offlineDone = $0 { return true } else { return false } }765 guard case .offlineDone(let r) = done else { throw ScenarioFailure("offline:done attendu") }766 fact("region.seconds", .number((Date().timeIntervalSince(t0) * 10).rounded() / 10))767 fact("region.bytes", .number(Double(r.bytes)))768 fact("region.errors", .number(Double(r.errors)))769 try check(r.state == .complete && r.tilesDone == r.tilesTotal, "région incomplète : \(r.tilesDone)/\(r.tilesTotal), état \(r.state.rawValue)")770 let listed = try map.offlineRegions().first { $0.id == r.id }771 try check(listed?.completedAt != nil, "date de fin de téléchargement absente")772 fact("region.dataVersion", .string(listed?.dataVersion ?? ""))773 let usage = try map.tileStoreUsage()774 try check(!usage.isDownloading, "le téléchargement devrait être terminé")775 fact("pinnedBytes", .number(Double(usage.pinnedBytes)))776 try check(usage.pinnedBytes > 0, "aucun octet épinglé après le téléchargement")777778 // Réseau coupé, mémoire vidée : la région doit se dessiner depuis le disque seul.779 model.networkEnabled = false780 await sleep(0.2)781 try check(map.mapView?.networkPolicy.isEnabled == false, "la politique réseau doit être coupée")782 map.mapView?.simulateMemoryWarning()783 let net0 = map.networkStats784 try await settle(timeout: 40) { map.jumpTo(KACamera(center: c, zoom: 13.6)) }785 let perf = try map.perf()786 let net1 = map.networkStats787 fact("offline.tiles", .number(Double(perf.tiles)))788 fact("offline.triangles", .number(Double(perf.triangles)))789 fact("offline.httpCompleted", .number(Double(net1.completed - net0.completed)))790 fact("offline.blocked", .number(Double(net1.blocked - net0.blocked)))791 try check(net1.completed == net0.completed, "aucune requête HTTP ne doit aboutir réseau coupé")792 try check(perf.tiles > 0 && perf.triangles > 500, "la région hors ligne ne se dessine pas réseau coupé (\(perf.tiles) tuiles, \(perf.triangles) triangles)")793 var hits = 0794 let size = map.mapView?.bounds.size ?? .zero795 for (fx, fy) in [(0.5, 0.5), (0.3, 0.4), (0.7, 0.6), (0.4, 0.7), (0.6, 0.3)] {796 hits += try map.queryRendered(at: CGPoint(x: size.width * fx, y: size.height * fy)).count797 }798 try check(hits > 0, "aucune entité dessinée hors ligne")799 await checkpoint("offline-region")800801 // Hors région, réseau coupé : rien ne se charge, mais rien ne casse.802 let mo = mark, fo = map.frameCount, to = Date()803 map.jumpTo(KACamera(center: CLLocationCoordinate2D(latitude: 48.4284, longitude: -71.0537), zoom: 13.5))804 // Le moteur doit renoncer (trois essais : 1 s, 3 s, 8 s) puis se mettre au repos, pas tourner à vide.805 let rested = (try? await waitIdle(since: mo, timeout: 30)) != nil806 fact("outside.idleAfterSeconds", rested ? .number((Date().timeIntervalSince(to) * 10).rounded() / 10) : .null)807 fact("outside.framesWhileWaiting", .number(Double(map.frameCount - fo)))808 fact("outside.tiles", .number(Double((try map.perf()).tiles)))809 await checkpoint("offline-outside")810811 // Suppression : plus rien d'épinglé.812 model.networkEnabled = true813 await sleep(0.2)814 try check(try map.removeRegion(r.id), "suppression de la région refusée")815 let after = try map.tileStoreUsage()816 fact("pinnedAfterRemove", .number(Double(after.pinnedBytes)))817 try check(after.pinnedBytes == 0, "des octets restent épinglés après la suppression")818 // Plafond du stock ambiant : l'éviction LRU est immédiate.819 map.setAmbientCacheCap(bytes: 2 << 20)820 await sleep(0.3)821 let capped = try map.tileStoreUsage()822 fact("ambientAfterCap2MB", .number(Double(capped.ambientBytes)))823 try check(capped.ambientBytes <= 2 << 20, "le plafond LRU n'est pas respecté : \(capped.ambientBytes)")824 map.setAmbientCacheCap(bytes: 256 << 20)825 let disk = KAOfflineManager.shared.diskUsage()826 fact("diskTileStoreBytes", .number(Double(disk.tileStoreBytes)))827 }828829 /// Archive PMTiles : téléchargée par la session d'arrière-plan, montée, puis rendue réseau coupé.830 /// `live` : première archive du catalogue du serveur (vraie archive, vraie adresse HTTPS) ; sinon831 /// l'archive d'essai servie par le Mac à l'adresse `-packURL`.832 private func pack(live: Bool) async throws {833 let index = try await KAOfflineManager.shared.fetchPackIndex()834 fact("server.dataVersion", .string(index.dataVersion))835 fact("server.packs", .number(Double(index.packs.count)))836 let mgr = KAOfflineManager.shared837 let pack: KAOfflinePack838 let c: CLLocationCoordinate2D839 if live {840 guard let first = index.packs.first(where: { $0.bytes < 120 << 20 }) else {841 fact("skipped", "aucune archive de moins de 120 Mio au catalogue du serveur")842 return843 }844 pack = first845 // Dans l'archive « montreal » mais jamais visité par les autres scénarios : Laval.846 c = first.id == "montreal" ? CLLocationCoordinate2D(latitude: 45.6066, longitude: -73.7124) : (first.bounds?.center ?? DemoPlace.montreal.coordinate)847 fact("pack.id", .string(first.id))848 fact("pack.catalogBytes", .number(Double(first.bytes)))849 } else {850 let args = ProcessInfo.processInfo.arguments851 guard let i = args.firstIndex(of: "-packURL"), i + 1 < args.count, let url = URL(string: args[i + 1]) else {852 fact("skipped", "aucune archive d'essai (-packURL absent)")853 return854 }855 // Val-d'Or : jamais visitée par les autres scénarios.856 c = CLLocationCoordinate2D(latitude: 48.0975, longitude: -77.7828)857 pack = KAOfflinePack(id: "essai", title: "Val-d'Or (essai)", url: url, bytes: 0, bounds: KABounds(west: c.longitude - 0.05, south: c.latitude - 0.03, east: c.longitude + 0.05, north: c.latitude + 0.03), minZoom: 0, maxZoom: 14, tiles: 0, dataVersion: index.dataVersion)858 }859 let id = pack.id860 mgr.allowsExpensiveNetwork = true861 mgr.removePack(id)862 try await reset(.montreal, zoom: 12)863 let t0 = Date()864 let updates = mgr.downloadUpdates865 mgr.download(pack)866 var final: KAPackDownload?867 let watcher = Task { () -> KAPackDownload? in868 for await d in updates where d.id == id {869 switch d.state {870 case .finished, .failed, .cancelled: return d871 default: continue872 }873 }874 return nil875 }876 let timeout = Task { try? await Task.sleep(for: .seconds(240)); watcher.cancel() }877 final = await watcher.value878 timeout.cancel()879 try check(final?.state == .finished, "téléchargement de l'archive : \(String(describing: final?.state))")880 fact("pack.seconds", .number((Date().timeIntervalSince(t0) * 100).rounded() / 100))881 guard let inst = mgr.installedPacks().first(where: { $0.id == id }) else { throw ScenarioFailure("archive non installée") }882 fact("pack.bytes", .number(Double(inst.bytes)))883 fact("pack.dataVersion", .string(inst.dataVersion))884 try check(inst.bytes > 10_000, "archive trop petite : \(inst.bytes) octets")885 await sleep(0.5)886 try check(try map.tileStoreUsage().archives.contains(id), "l'archive n'est pas montée dans la carte")887 if live { try check(inst.bytes == pack.bytes, "taille installée \(inst.bytes) ≠ taille annoncée \(pack.bytes)") }888889 model.networkEnabled = false890 await sleep(0.2)891 let net0 = map.networkStats892 try await settle(timeout: 40) { map.jumpTo(KACamera(center: c, zoom: 13.4)) }893 let perf = try map.perf()894 fact("pack.tiles", .number(Double(perf.tiles)))895 fact("pack.triangles", .number(Double(perf.triangles)))896 try check(map.networkStats.completed == net0.completed, "aucune requête HTTP ne doit aboutir réseau coupé")897 try check(perf.tiles > 0 && perf.triangles > 300, "l'archive ne se dessine pas réseau coupé (\(perf.tiles) tuiles, \(perf.triangles) triangles)")898 await checkpoint(live ? "offline-pack-live" : "offline-pack")899 model.networkEnabled = true900 mgr.removePack(id)901 await sleep(0.5)902 try check(!(try map.tileStoreUsage().archives.contains(id)), "l'archive supprimée doit être démontée")903 try check(!FileManager.default.fileExists(atPath: mgr.fileURL(forPack: id).path), "le fichier de l'archive doit être supprimé")904 }905906 // MARK: Mesures907908 /// Parcours de caméra scripté (aller-retour entre lieux, zooms, 3D, thèmes).909 private func drive(seconds: Double, sample: (Double) -> Void) async {910 let stops: [(CLLocationCoordinate2D, Double, Double, Double)] = [911 (DemoPlace.montreal.coordinate, 15.5, 0, 0), (CLLocationCoordinate2D(latitude: 45.515, longitude: -73.58), 16.5, 40, 55),912 (CLLocationCoordinate2D(latitude: 45.49, longitude: -73.55), 14.2, -30, 30), (CLLocationCoordinate2D(latitude: 45.53, longitude: -73.61), 13, 0, 0),913 (CLLocationCoordinate2D(latitude: 45.508, longitude: -73.554), 17, 120, 60), (DemoPlace.montreal.coordinate, 12.5, 0, 0),914 ]915 let t0 = CACurrentMediaTime()916 var i = 0917 var nextSample = 0.0918 while CACurrentMediaTime() - t0 < seconds {919 let s = stops[i % stops.count]920 i += 1921 let m = mark922 if i % 3 == 0 {923 map.flyTo(KACameraUpdate(center: s.0, zoom: s.1, bearing: s.2, pitch: s.3), duration: 2.2)924 } else {925 map.easeTo(KACameraUpdate(center: s.0, zoom: s.1, bearing: s.2, pitch: s.3), duration: 2.2, easing: .cubicInOut)926 }927 _ = try? await wait("moveend", since: m, timeout: 6) { if case .moveEnd = $0 { return true } else { return false } }928 let t = CACurrentMediaTime() - t0929 if t >= nextSample {930 sample(t)931 nextSample = t + 5932 }933 }934 }935936 /// Endurance mémoire : caméra scriptée pendant `-soakSeconds` (défaut 180), empreinte échantillonnée.937 private func soak() async throws {938 let a = ProcessInfo.processInfo.arguments939 let seconds = a.firstIndex(of: "-soakSeconds").flatMap { $0 + 1 < a.count ? Double(a[$0 + 1]) : nil } ?? 180940 try await reset(.montreal, zoom: 14, layers: [.markers, .heat])941 var samples: [(t: Double, mb: Double, gpu: Double)] = []942 var heap: [(live: Double, reserved: Double, tiles: Double, built: Double, evicted: Double)] = []943 let f0 = map.frameCount944 let t0 = CACurrentMediaTime()945 await drive(seconds: seconds) { t in946 samples.append((t, Double(physFootprint()) / 1_048_576, Double((try? self.map.perf().gpuMemory) ?? 0) / 1_048_576))947 let h = heapStats()948 let p = try? self.map.command("getPerf")949 heap.append((Double(h.inUse) / 1_048_576, Double(h.allocated) / 1_048_576, p?["tiles"]?.doubleValue ?? 0, p?["tilesBuilt"]?.doubleValue ?? 0, p?["tilesEvicted"]?.doubleValue ?? 0))950 }951 let elapsed = CACurrentMediaTime() - t0952 fact("seconds", .number(elapsed.rounded()))953 fact("avgFps", .number((Double(map.frameCount - f0) / elapsed * 10).rounded() / 10))954 fact("samples", .array(samples.map { [.number($0.t.rounded()), .number(($0.mb * 10).rounded() / 10), .number(($0.gpu * 10).rounded() / 10)] }))955 // Tas : octets vivants, octets réservés par l'allocateur, tuiles construites et évincées (cumul).956 fact("heap", .array(heap.map { [.number(($0.live * 10).rounded() / 10), .number(($0.reserved * 10).rounded() / 10), .number($0.tiles), .number($0.built), .number($0.evicted)] }))957 try check(samples.count >= 6, "trop peu d'échantillons (\(samples.count))")958 // Après la montée en charge (premier tiers), l'empreinte ne doit plus croître : médiane du959 // dernier tiers contre médiane du tiers central.960 func median(_ x: [Double]) -> Double { let s = x.sorted(); return s[s.count / 2] }961 let n = samples.count962 let mid = median(samples[(n / 3)..<(2 * n / 3)].map(\.mb)), last = median(samples[(2 * n / 3)...].map(\.mb))963 fact("footprintMidMB", .number((mid * 10).rounded() / 10))964 fact("footprintLastMB", .number((last * 10).rounded() / 10))965 fact("footprintPeakMB", .number(((samples.map(\.mb).max() ?? 0) * 10).rounded() / 10))966 fact("growthMB", .number(((last - mid) * 10).rounded() / 10))967 try check(last - mid < max(24, mid * 0.10), "l'empreinte mémoire croît : \(mid) → \(last) Mio")968 }969970 /// Mesures de trame : images par seconde et temps processeur pendant un parcours de 30 s, en 2D puis en 3D.971 private func bench() async throws {972 func measure(_ label: String, pitch: Double, zoom: Double) async throws {973 try await settle { map.jumpTo(KACamera(center: DemoPlace.montreal.coordinate, zoom: zoom, pitch: pitch)) }974 var cpu: [Double] = [], frameMs: [Double] = []975 let f0 = map.frameCount976 let t0 = CACurrentMediaTime()977 let m0 = mark978 // Rotation continue : chaque image est différente (aucune trame gratuite).979 map.orbit(center: DemoPlace.montreal.coordinate, zoom: zoom, pitch: max(pitch, 0.01), turns: 1, duration: 20)980 if pitch < 1 {981 // `orbit` passe en 3D : pour la mesure 2D, panoramique en va-et-vient.982 map.stop()983 try await settle { map.setMode(.flat) }984 }985 let tStart = CACurrentMediaTime(), fStart = map.frameCount986 var k = 0987 while CACurrentMediaTime() - tStart < 20 {988 if pitch < 1 {989 let mk = mark990 k += 1991 map.easeTo(KACameraUpdate(center: CLLocationCoordinate2D(latitude: DemoPlace.montreal.coordinate.latitude + (k % 2 == 0 ? 0.012 : -0.012), longitude: DemoPlace.montreal.coordinate.longitude + (k % 2 == 0 ? -0.02 : 0.02)), bearing: Double(k % 4) * 25), duration: 2.5, easing: .linear)992 _ = try? await wait("moveend", since: mk, timeout: 4) { if case .moveEnd = $0 { return true } else { return false } }993 } else {994 await sleep(0.5)995 }996 if let p = try? map.perf() {997 cpu.append(p.cpuMs)998 frameMs.append(p.frameMs)999 }1000 }1001 let dt = CACurrentMediaTime() - tStart1002 map.stop()1003 _ = (f0, t0, m0)1004 func med(_ x: [Double]) -> Double { let s = x.sorted(); return s.isEmpty ? 0 : s[s.count / 2] }1005 let perf = try map.perf()1006 fact("\(label).fps", .number((Double(map.frameCount - fStart) / dt * 10).rounded() / 10))1007 fact("\(label).cpuMsMedian", .number((med(cpu) * 100).rounded() / 100))1008 fact("\(label).cpuMsMax", .number(((cpu.max() ?? 0) * 100).rounded() / 100))1009 fact("\(label).frameMsMedian", .number((med(frameMs) * 100).rounded() / 100))1010 fact("\(label).drawCalls", .number(Double(perf.drawCalls)))1011 fact("\(label).triangles", .number(Double(perf.triangles)))1012 fact("\(label).tiles", .number(Double(perf.tiles)))1013 fact("\(label).gpuMB", .number((Double(perf.gpuMemory) / 1_048_576 * 10).rounded() / 10))1014 fact("\(label).quality", .number(Double(perf.quality)))1015 }1016 try await reset(.montreal, zoom: 15, layers: [.markers])1017 fact("screenMaxFps", .number(Double(map.mapView?.window?.screen.maximumFramesPerSecond ?? 0)))1018 fact("pixels", .string("\(Int((map.mapView?.bounds.width ?? 0) * (map.mapView?.contentScaleFactor ?? 0)))×\(Int((map.mapView?.bounds.height ?? 0) * (map.mapView?.contentScaleFactor ?? 0)))"))1019 try await measure("2d-z15", pitch: 0, zoom: 15)1020 try await measure("3d-z16", pitch: 58, zoom: 16.3)1021 fact("footprintEndMB", .number((Double(physFootprint()) / 1_048_576 * 10).rounded() / 10))1022 try await settle { map.setMode(.flat) }1023 }1024}1025