Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Apps/ORIXMaps/Sources/Directions/DirectionsModel.swift10// Module : Directions11// Repository : https://git.spboucher.ai/orix-maps12// Created : 2026-11-2513// Last Modified : 2026-11-2514//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 : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import Observation90import ORIXGeoCore91import ORIXLocation92import ORIXMapRenderer93import ORIXMapStyle94import ORIXNavigation95import ORIXPrivacy96import ORIXRouting97import UIKit9899/// One end or stop of a planned route.100struct RoutePoint: Equatable, Identifiable {101 var id = UUID()102 var title: String103 /// nil = "my position", resolved when the route is computed.104 var coordinate: Coordinate?105 static var myPosition: RoutePoint { RoutePoint(title: String(localized: "My position"), coordinate: nil) }106 var isMyPosition: Bool { coordinate == nil }107}108109enum DirectionsFailure: Equatable {110 case noPosition111 case noRoutingData112 /// The points are not all inside one installed region that has routing.113 case notCovered114 case tooFarFromRoad(pointIndex: Int)115 case noConnection116 case other(String)117}118119/// Route planning and turn-by-turn guidance, computed on the device from the installed regions.120@Observable121final class DirectionsModel {122 var points: [RoutePoint] = [.myPosition]123 var mode: TravelMode = .car124 private(set) var response: RouteResponse?125 var selectedRoute = 0 { didSet { draw() } }126 private(set) var isComputing = false127 private(set) var failure: DirectionsFailure?128 /// Regions that can route, with the date of their data.129 private(set) var graphInfo: [GraphMetadata] = []130131 // Guidance132 private(set) var session: NavigationSession?133 private(set) var progress: NavigationProgress?134 private(set) var isSimulating = false135 private(set) var isRerouting = false136 private(set) var lastAnnouncement: String?137 private(set) var arrived = false138139 @ObservationIgnored private var graphs: [String: RoutingGraph] = [:]140 @ObservationIgnored private var task: Task<Void, Never>?141 @ObservationIgnored private weak var map: MapController?142 @ObservationIgnored private let location: LocationService143 @ObservationIgnored private let settings: AppSettings144 @ObservationIgnored private var consumer: UUID?145 @ObservationIgnored private var positionWaiter: UUID?146 /// Creates the device's position source, put back when a simulated drive ends.147 @ObservationIgnored private let makeDeviceProvider: () -> LocationProvider148 @ObservationIgnored let voice: VoiceGuide149 @ObservationIgnored var onArrival: (() -> Void)?150151 init(map: MapController, location: LocationService, settings: AppSettings, deviceProvider: @escaping () -> LocationProvider = { CoreLocationProvider() }) {152 self.map = map153 self.location = location154 self.settings = settings155 makeDeviceProvider = deviceProvider156 voice = SystemVoiceGuide()157 }158159 var hasRouting: Bool { !graphs.isEmpty }160 var routes: [Route] { response?.routes ?? [] }161 var route: Route? { routes.indices.contains(selectedRoute) ? routes[selectedRoute] : routes.first }162 var isNavigating: Bool { session != nil }163 var formatter: InstructionFormatter {164 InstructionFormatter(language: settings.interfaceLanguageCode == "fr" ? .french : .english, units: settings.units == .metric ? .metric : .imperial)165 }166167 func setRegions(_ regions: [MapRegion]) {168 let wanted = regions.compactMap { r in r.routingURL.map { (r.id, $0) } }169 Task {170 // Opening validates the file structure; a damaged graph is simply not offered.171 let opened = await Task.detached { () -> [String: RoutingGraph] in172 var out: [String: RoutingGraph] = [:]173 for (id, url) in wanted {174 do { out[id] = try RoutingGraph(url: url, validation: .structure) } catch { PrivacyLog(category: "routing").error("routing graph of \(id) not opened: \(String(describing: error))") }175 }176 return out177 }.value178 self.graphs = opened179 self.graphInfo = opened.values.map(\.metadata)180 }181 }182183 // MARK: Planning184185 func plan(to place: PlaceSelection) {186 points = [.myPosition, RoutePoint(title: place.title, coordinate: place.coordinate)]187 compute()188 }189190 func addStop(_ place: PlaceSelection) {191 points.insert(RoutePoint(title: place.title, coordinate: place.coordinate), at: max(1, points.count - 1))192 compute()193 }194195 func removePoint(_ id: UUID) {196 points.removeAll { $0.id == id }197 compute()198 }199200 func movePoints(from: IndexSet, to: Int) {201 points.move(fromOffsets: from, toOffset: to)202 compute()203 }204205 func reverse() {206 points.reverse()207 compute()208 }209210 func clear() {211 task?.cancel()212 stopWaitingForPosition()213 response = nil; failure = nil; isComputing = false214 points = [.myPosition]215 for id in [OverlayID.route, OverlayID.routeAlternatives, OverlayID.maneuver, OverlayID.routeTraveled] { map?.setOverlay(id, features: []) }216 }217218 private func profile() -> RoutingProfile {219 RoutingProfile.standard(for: mode).avoiding(RouteAvoidance(tolls: settings.avoidTolls, ferries: settings.avoidFerries, motorways: settings.avoidMotorways, unpaved: settings.avoidUnpaved))220 }221222 /// The smallest installed graph whose coverage contains every point.223 private func graph(covering coordinates: [Coordinate]) -> RoutingGraph? {224 graphs.values.filter { g in coordinates.allSatisfy { g.metadata.boundingBox.contains($0) } }225 .min { $0.metadata.boundingBox.latSpan * $0.metadata.boundingBox.lonSpan < $1.metadata.boundingBox.latSpan * $1.metadata.boundingBox.lonSpan }226 }227228 /// The position a route can start from. A fresh fix, or — while updates are running — the last one received: a229 /// device that does not move gets no new fix (updates are filtered by distance), so that fix is still where the230 /// device is. A fix older than ten minutes is not trusted.231 private var startFix: LocationFix? {232 guard let fix = location.lastFix else { return nil }233 if location.isFixFresh { return fix }234 let age = Date().timeIntervalSince(fix.timestamp)235 return location.usage != nil && fix.horizontalAccuracy <= 200 && age >= 0 && age < 600 ? fix : nil236 }237238 /// While the planner waits for a position, the first fix that arrives computes the route (once).239 private func waitForPosition() {240 guard positionWaiter == nil else { return }241 positionWaiter = location.addConsumer { [weak self] _ in242 guard let self else { return }243 stopWaitingForPosition()244 if failure == .noPosition { compute() }245 }246 }247248 private func stopWaitingForPosition() {249 if let positionWaiter { location.removeConsumer(positionWaiter) }250 positionWaiter = nil251 }252253 func compute() {254 task?.cancel()255 stopWaitingForPosition()256 failure = nil257 guard points.count >= 2 else { response = nil; draw(); return }258 guard hasRouting else { failure = .noRoutingData; return }259 var coordinates: [Coordinate] = []260 for p in points {261 if let c = p.coordinate { coordinates.append(c) }262 else if let fix = startFix { coordinates.append(fix.coordinate) }263 else {264 location.start(.browsing)265 failure = .noPosition266 waitForPosition()267 return268 }269 }270 guard let graph = graph(covering: coordinates) else { failure = .notCovered; response = nil; draw(); return }271 var waypoints = coordinates.map { RouteWaypoint($0) }272 // Leaving from the live position while moving: prefer a route that starts in the direction of travel.273 if points.first?.isMyPosition == true, let fix = location.lastFix, let course = fix.course, (fix.speed ?? 0) > 3 { waypoints[0].heading = course }274 let request = RouteRequest(waypoints: waypoints, profile: profile(), alternatives: points.count == 2 ? 2 : 0)275 isComputing = true276 task = Task {277 let result = await Task.detached(priority: .userInitiated) { () -> Result<RouteResponse, RoutingError> in278 do { return .success(try Router(graph: graph).compute(request)) } catch { return .failure((error as? RoutingError) ?? .invalidRequest("unexpected error")) }279 }.value280 guard !Task.isCancelled else { return }281 isComputing = false282 switch result {283 case .success(let r):284 response = r285 selectedRoute = 0286 draw()287 if let box = r.routes.first?.boundingBox { map?.fit(box, insets: MapInsets(top: 80, left: 50, bottom: 60, right: 70)) }288 case .failure(let e):289 response = nil290 draw()291 failure = Self.failure(e)292 }293 }294 }295296 private static func failure(_ e: RoutingError) -> DirectionsFailure? {297 switch e {298 case .cancelled: nil299 case .pointOutsideCoverage: .notCovered300 case .pointTooFarFromRoad(let i, _): .tooFarFromRoad(pointIndex: i)301 case .noConnection: .noConnection302 case .invalidRequest(let m): .other(m)303 }304 }305306 private func draw() {307 guard let map else { return }308 guard let route else {309 for id in [OverlayID.route, OverlayID.routeAlternatives, OverlayID.maneuver] { map.setOverlay(id, features: []) }310 return311 }312 map.setOverlay(OverlayID.route, features: [OverlayFeature(.line(route.geometry))])313 map.setOverlay(OverlayID.routeAlternatives, features: session == nil ? routes.enumerated().filter { $0.offset != selectedRoute }.map { OverlayFeature(.line($0.element.geometry)) } : [])314 map.setOverlay(OverlayID.maneuver, features: route.maneuvers.dropFirst().map { OverlayFeature(.point($0.location)) })315 }316317 // MARK: Guidance318319 /// Starts guidance on the selected route. `simulated` replays the route instead of using the device's position.320 func startNavigation(simulated: Bool) {321 guard let route, session == nil else { return }322 arrived = false323 lastAnnouncement = nil324 session = NavigationSession(route: route, options: NavigationOptions(language: formatter.language, units: formatter.units))325 voice.isEnabled = settings.voiceGuidance326 voice.volume = Float(settings.voiceVolume)327 (voice as? SystemVoiceGuide)?.voiceIdentifier = settings.voiceIdentifier328 isSimulating = simulated329 if simulated {330 let speed: Double = route.distanceMeters / max(1, route.durationSeconds)331 let provider = SimulatedLocationProvider(path: route.geometry, speed: max(1.2, speed), rate: mode == .car ? 4 : 12, interval: 0.5)332 location.setProvider(provider)333 }334 location.start(.navigation)335 consumer = location.addConsumer { [weak self] fix in self?.ingest(fix) }336 if settings.keepScreenOnDuringNavigation { UIApplication.shared.isIdleTimerDisabled = true }337 draw()338 }339340 private func ingest(_ fix: LocationFix) {341 guard var s = session else { return }342 let events = s.update(NavigationFix(coordinate: fix.coordinate, accuracy: fix.horizontalAccuracy, speed: fix.speed, course: fix.course, time: fix.timestamp))343 session = s344 for event in events {345 switch event {346 case .progress(let p):347 progress = p348 followCamera(p, fix: fix)349 if p.isOnRoute, let route {350 map?.setOverlay(OverlayID.routeTraveled, features: p.geometryIndex > 0 ? [OverlayFeature(.line(Array(route.geometry[0...p.geometryIndex]) + [p.matchedCoordinate]))] : [])351 }352 case .announce(let a):353 lastAnnouncement = a.text354 voice.speak(a.text, language: settings.interfaceLanguageCode, urgent: a.stage == .now)355 case .rerouteNeeded(let from, let course):356 reroute(from: from, course: course)357 case .waypointReached:358 break359 case .arrived:360 arrived = true361 onArrival?()362 }363 }364 }365366 private func followCamera(_ p: NavigationProgress, fix: LocationFix) {367 guard let map, !map.isUserInteracting, followsPosition else { return }368 let speed = fix.speed ?? 0369 // Closer in town, further out at speed, and closer again before a maneuver.370 var zoom = speed > 22 ? 14.6 : (speed > 11 ? 15.6 : 16.6)371 if p.distanceToNextManeuver < 250 { zoom = max(zoom, 16.4) }372 map.setCamera(MapCamera(center: p.matchedCoordinate, zoom: zoom, bearing: p.isOnRoute ? p.matchedBearing : (fix.course ?? map.camera.bearing), pitch: 50), duration: 0.9)373 }374375 /// False after the user moved the map during guidance, until "Recentre".376 var followsPosition = true377378 private func reroute(from: Coordinate, course: Double?) {379 guard let current = session?.route, let destination = current.geometry.last, let graph = graph(covering: [from, destination]) else {380 session?.rerouteFailed()381 return382 }383 isRerouting = true384 // Remaining intermediate stops are kept: only those not yet reached.385 let leg = progress?.legIndex ?? 0386 let remainingStops = current.legs.dropFirst(leg).dropLast().compactMap { current.geometry.indices.contains($0.geometryRange.upperBound) ? current.geometry[$0.geometryRange.upperBound] : nil }387 let waypoints = [RouteWaypoint(from, heading: course)] + remainingStops.map { RouteWaypoint($0) } + [RouteWaypoint(destination)]388 let request = RouteRequest(waypoints: waypoints, profile: profile())389 Task {390 let result = await Task.detached(priority: .userInitiated) { try? Router(graph: graph).compute(request) }.value391 isRerouting = false392 guard session != nil else { return }393 if let result {394 response = result395 selectedRoute = 0396 session?.setRoute(result.route)397 map?.setOverlay(OverlayID.routeTraveled, features: [])398 draw()399 let text = formatter.language == .french ? "Nouvel itinéraire." : "New route."400 voice.speak(text, language: settings.interfaceLanguageCode, urgent: true)401 } else {402 session?.rerouteFailed()403 }404 }405 }406407 func stopNavigation() {408 if let consumer { location.removeConsumer(consumer) }409 consumer = nil410 voice.stop()411 if isSimulating {412 // Back to the device's position. Updates are stopped first: swapping the source while guidance is running413 // would restart guidance on Core Location, which asks for the position permission — a preview never does.414 location.stop()415 location.setProvider(makeDeviceProvider())416 if location.authorization.isAuthorized { location.start(.browsing) }417 } else {418 location.end(.navigation)419 }420 isSimulating = false421 session = nil422 progress = nil423 followsPosition = true424 UIApplication.shared.isIdleTimerDisabled = false425 map?.setOverlay(OverlayID.routeTraveled, features: [])426 var camera = map?.camera ?? .world427 camera.pitch = 0; camera.bearing = 0428 map?.setCamera(camera, duration: 0.4)429 draw()430 }431432 func toggleVoice() {433 settings.voiceGuidance.toggle()434 voice.isEnabled = settings.voiceGuidance435 if !settings.voiceGuidance { voice.stop() }436 }437}438