SPB Git

Repository Public BSD-3-Clause

RendererTests.swift 11.4 KB 220 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Packages/ORIXMapRenderer/Tests/ORIXMapRendererTests/RendererTests.swift10// Module           : ORIXMapRendererTests11// 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 CoreGraphics89import Foundation90import ORIXGeoCore91import Testing92@testable import ORIXMapRenderer9394@MainActor private final class FakeBackend: MapBackend {95    var log: [String] = []96    func apply(camera: MapCamera, duration: TimeInterval) { log.append("camera z\(camera.zoom) d\(duration)") }97    func fit(bounds: BoundingBox, insets: MapInsets, maxZoom: Double, duration: TimeInterval) { log.append("fit \(bounds.minLat) d\(duration)") }98    func apply(styleJSON: String) { log.append("style \(styleJSON.count)") }99    func apply(overlay id: String, geoJSON: Data) { log.append("overlay \(id) \(geoJSON.count)") }100    func apply(contentInsets: MapInsets, animated: Bool) { log.append("insets \(contentInsets.bottom)") }101    func apply(frameRate: MapController.FrameRate) { log.append("fps \(frameRate)") }102    func coordinate(at point: CGPoint) -> Coordinate? { Coordinate(latitude: Double(point.y), longitude: Double(point.x)) }103    func point(for coordinate: Coordinate) -> CGPoint? { CGPoint(x: coordinate.longitude, y: coordinate.latitude) }104    var visibleBounds: BoundingBox? { BoundingBox(minLat: 0, minLon: 0, maxLat: 1, maxLon: 1) }105}106107@Suite struct MapCameraTests {108    @Test func normalization() {109        let c = MapCamera(center: Coordinate(latitude: 95, longitude: 190), zoom: 99, bearing: -90, pitch: 80).normalized110        #expect(abs(c.center.latitude - WebMercator.maxLatitude) < 1e-9 && c.center.longitude == -170 && c.zoom == 20 && c.bearing == 270 && c.pitch == 60)111        let n = MapCamera(center: Coordinate(latitude: .nan, longitude: .infinity), zoom: .nan, bearing: .infinity, pitch: -.infinity).normalized112        #expect(n.center == Coordinate(latitude: 0, longitude: 0) && n.zoom == 2 && n.bearing == 0 && n.pitch == 0)113        #expect(MapCamera(center: Coordinate(latitude: 0, longitude: 0), zoom: 3, bearing: 720).normalized.bearing == 0)114        #expect(abs(MapCamera(center: Coordinate(latitude: 0, longitude: 0), zoom: 0).metersPerPoint - 78_271.5) < 1)115    }116}117118@Suite struct FrameStatisticsTests {119    @Test func percentilesOverARollingWindow() {120        var s = FrameStatistics(capacity: 100)121        #expect(s.percentile(50) == nil && s.mean == nil)122        for i in 1...100 { s.record(milliseconds: Double(i)) }123        #expect(s.percentile(50) == 50 && s.percentile(95) == 95 && s.percentile(99) == 99 && s.percentile(100) == 100 && s.percentile(0) == 1)124        #expect(s.mean == 50.5 && s.maximum == 100)125        for _ in 0..<100 { s.record(milliseconds: 8) }126        #expect(s.percentile(99) == 8 && s.totalFrames == 200 && s.samples.count == 100)127        s.record(milliseconds: .nan); s.record(milliseconds: -1)128        #expect(s.totalFrames == 200)129        s.reset()130        #expect(s.samples.isEmpty && s.totalFrames == 0)131    }132}133134@Suite struct OverlayGeoJSONTests {135    @Test func encodesGeometriesAndDropsInvalidOnes() throws {136        let a = Coordinate(latitude: 45, longitude: -73), b = Coordinate(latitude: 46, longitude: -72), c = Coordinate(latitude: 45, longitude: -72)137        let data = OverlayFeature.geoJSON([138            OverlayFeature(.point(a), properties: ["title": "A", "n": 2, "on": true, "bad": .number(.nan)]),139            OverlayFeature(.line([a, b])),140            OverlayFeature(.polygon([[a, b, c]])),141            OverlayFeature(.point(Coordinate(latitude: 200, longitude: 0))),142            OverlayFeature(.line([a])),143            OverlayFeature(.polygon([[a, b]])),144        ])145        let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]146        let features = json["features"] as! [[String: Any]]147        #expect(features.count == 3)148        let props = features[0]["properties"] as! [String: Any]149        #expect(props["title"] as? String == "A" && props["n"] as? Double == 2 && props["on"] as? Bool == true && props["bad"] as? Double == 0)150        let ring = ((features[2]["geometry"] as! [String: Any])["coordinates"] as! [[[Double]]])[0]151        #expect(ring.count == 4 && ring.first! == ring.last! && ring[0] == [-73, 45])152        let empty = try JSONSerialization.jsonObject(with: OverlayFeature.geoJSON([])) as! [String: Any]153        #expect((empty["features"] as! [Any]).isEmpty)154    }155156    @Test func accuracyCircle() {157        let center = Coordinate(latitude: 45.5, longitude: -73.6)158        guard case .polygon(let rings) = OverlayFeature.circle(center: center, radius: 120).geometry else { Issue.record("not a polygon"); return }159        #expect(rings[0].count == 48)160        for p in rings[0] { #expect(abs(Geodesy.distance(center, p) - 120) < 0.01) }161    }162}163164@MainActor @Suite struct MapControllerTests {165    @Test func stateRequestedBeforeTheEngineExistsIsAppliedOnAttach() {166        let controller = MapController()167        controller.setStyle(Data("{\"version\":8}".utf8))168        controller.setOverlay("orix-route", features: [OverlayFeature(.line([Coordinate(latitude: 1, longitude: 1), Coordinate(latitude: 2, longitude: 2)]))])169        controller.setCamera(MapCamera(center: Coordinate(latitude: 45, longitude: -73), zoom: 12))170        controller.setContentInsets(MapInsets(bottom: 300))171        controller.fit(BoundingBox(minLat: 45, minLon: -74, maxLat: 46, maxLon: -73))172        #expect(controller.camera.zoom == 12 && !controller.isStyleLoaded)173        let backend = FakeBackend()174        controller.attach(backend)175        #expect(backend.log == ["fps standard", "insets 300.0", "camera z12.0 d0.0", "style 13"])176        var events: [MapEvent] = []177        controller.onEvent = { events.append($0) }178        controller.engineDidLoadStyle()179        // Overlays and the pending fit are applied only once the style exists.180        #expect(backend.log.count == 6 && backend.log[4].hasPrefix("overlay orix-route") && backend.log[5] == "fit 45.0 d0.0")181        #expect(controller.isStyleLoaded && events == [.styleLoaded])182    }183184    @Test func overlaysSurviveAStyleChangeAndIdenticalUpdatesAreSkipped() {185        let controller = MapController(), backend = FakeBackend()186        controller.attach(backend)187        controller.setStyle(Data("a".utf8)); controller.engineDidLoadStyle()188        let pin = [OverlayFeature(.point(Coordinate(latitude: 1, longitude: 2)))]189        controller.setOverlay("orix-pins", features: pin)190        controller.setOverlay("orix-pins", features: pin)191        controller.setStyle(Data("a".utf8))192        #expect(backend.log.filter { $0.hasPrefix("overlay") }.count == 1 && backend.log.filter { $0.hasPrefix("style") }.count == 1)193        controller.setStyle(Data("bb".utf8))194        #expect(!controller.isStyleLoaded)195        controller.setOverlay("orix-track", features: [])196        #expect(backend.log.filter { $0.hasPrefix("overlay") }.count == 1)197        controller.engineDidLoadStyle()198        #expect(backend.log.filter { $0.hasPrefix("overlay") }.count == 3)199    }200201    @Test func cameraEventsUpdateStateAndInteractionFlag() {202        let controller = MapController(), backend = FakeBackend()203        controller.attach(backend)204        var events: [MapEvent] = []205        controller.onEvent = { events.append($0) }206        let moving = MapCamera(center: Coordinate(latitude: 10, longitude: 20), zoom: 5, bearing: 400)207        controller.engineCameraDidChange(moving, reason: .gesture, finished: false)208        #expect(controller.isUserInteracting && controller.camera.bearing == 40)209        controller.engineCameraDidChange(moving, reason: .gesture, finished: true)210        #expect(!controller.isUserInteracting && events.count == 2)211        controller.engineDidTap(Coordinate(latitude: 1, longitude: 1), feature: nil)212        controller.engineDidLongPress(Coordinate(latitude: 2, longitude: 2))213        #expect(events.suffix(2) == [.tap(Coordinate(latitude: 1, longitude: 1), nil), .longPress(Coordinate(latitude: 2, longitude: 2))])214        controller.engineDidRenderFrame(milliseconds: 7)215        #expect(controller.frameStatistics.totalFrames == 1)216        controller.detach(backend)217        #expect(controller.coordinate(at: .zero) == nil && !controller.isStyleLoaded)218    }219}220
Files main
Menu

Theme