SPB Git

Repository Public License

TrafficScene.swift 27.9 KB 639 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Arcade9// File             : Games/TrafficMayhem/TrafficScene.swift10// Description      : Traffic Mayhem — SpriteKit rendering and touch input for11//                    the traffic simulation: vehicles, intent arrows, path12//                    preview, effects, sound and haptics.13// Module           : Games14// Repository       : https://git.spboucher.ai/orix-arcade15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : Proprietary, all rights reserved (see license file)83// License File     : LICENSE84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SpriteKit92import UIKit93import Observation9495nonisolated struct TrafficRunSummary: Sendable, Equatable {96    var layout: Int97    var mode: TrafficSim.Mode98    var finalScore: Int99    var survivalBonus: Int100    var cleared: Int101    var bestStreak: Int102    var closeCalls: Int103    var duration: Double104    var reason: TrafficSim.OverReason105}106107/// Values the SwiftUI HUD shows. The scene updates it only when something changes.108@Observable109final class TrafficRunModel {110    var score = 0111    var hearts = TrafficSim.startHearts112    var streak = 0113    var multiplier = 1114    var secondsLeft: Int?115    var banner: (id: Int, title: String, detail: String)?116    var coach: String?117    var flash = 0118    var summary: TrafficRunSummary?119}120121final class TrafficVehicleNode: SKNode {122    let body: SKSpriteNode123    private let ring = SKShapeNode()124    private var shownFraction = -1.0125    private var blinkers: [SKSpriteNode] = []126    let kind: VehicleKind127128    init(vehicle: TrafficVehicle, turn: TrafficTurn, steady: Bool) {129        kind = vehicle.kind130        let length = CGFloat(vehicle.kind.length), width = CGFloat(vehicle.kind.width)131        body = SKSpriteNode(texture: TrafficArt.vehicleTexture(kind: vehicle.kind, tint: vehicle.tint), size: CGSize(width: length, height: width))132        super.init()133        let shadow = SKSpriteNode(texture: TextureFactory.softDot, size: CGSize(width: length + 14, height: width + 14))134        shadow.color = .black135        shadow.colorBlendFactor = 1136        shadow.alpha = 0.6137        shadow.zPosition = -2138        addChild(shadow)139        let beam = SKSpriteNode(texture: TextureFactory.softDot, size: CGSize(width: 46, height: width + 16))140        beam.color = UIColor(hex: 0xFFF3B8)141        beam.colorBlendFactor = 1142        beam.alpha = 0.26143        beam.blendMode = .add144        beam.position = CGPoint(x: length / 2 + 15, y: 0)145        beam.zPosition = -1146        addChild(beam)147        addChild(body)148149        if turn != .straight, !vehicle.autonomous {150            let side: CGFloat = turn == .left ? 1 : -1151            for x in [length / 2 - 2.2, -length / 2 + 2.2] {152                let blinker = SKSpriteNode(texture: TrafficArt.dot, size: CGSize(width: 4.6, height: 4.6))153                blinker.color = UIColor(hex: 0xFFB020)154                blinker.colorBlendFactor = 1155                blinker.position = CGPoint(x: x, y: side * (width / 2 - 1))156                blinker.zPosition = 2157                let glow = SKSpriteNode(texture: TextureFactory.softDot, size: CGSize(width: 15, height: 15))158                glow.color = UIColor(hex: 0xFFB020)159                glow.colorBlendFactor = 1160                glow.blendMode = .add161                glow.alpha = 0.8162                blinker.addChild(glow)163                if !steady { blinker.run(.repeatForever(.sequence([.fadeAlpha(to: 0.08, duration: 0.07), .wait(forDuration: 0.26), .fadeAlpha(to: 1, duration: 0.07), .wait(forDuration: 0.3)]))) }164                addChild(blinker)165                blinkers.append(blinker)166            }167        }168        if vehicle.kind == .ambulance {169            for (index, hex) in [UInt32(0xFF3B55), 0x4DA3FF].enumerated() {170                let light = SKSpriteNode(texture: TextureFactory.softDot, size: CGSize(width: 15, height: 15))171                light.color = UIColor(hex: hex)172                light.colorBlendFactor = 1173                light.blendMode = .add174                light.position = CGPoint(x: 5, y: index == 0 ? 3.5 : -3.5)175                light.zPosition = 3176                if !steady {177                    light.alpha = index == 0 ? 1 : 0.15178                    light.run(.repeatForever(.sequence([.fadeAlpha(to: index == 0 ? 0.15 : 1, duration: 0.18), .fadeAlpha(to: index == 0 ? 1 : 0.15, duration: 0.18)])))179                }180                addChild(light)181            }182        }183        ring.lineWidth = 3184        ring.lineCap = .round185        ring.fillColor = .clear186        ring.zPosition = 4187        ring.isHidden = true188        addChild(ring)189    }190191    @available(*, unavailable)192    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not used") }193194    func removeBlinkers() {195        blinkers.forEach { $0.removeFromParent() }196        blinkers.removeAll()197    }198199    /// Patience ring around the vehicle; hidden while the driver is still relaxed.200    func setPatience(_ fraction: Double?) {201        guard let fraction, fraction < 0.8 else {202            if !ring.isHidden { ring.isHidden = true; shownFraction = -1; body.colorBlendFactor = 0 }203            return204        }205        ring.isHidden = false206        guard abs(fraction - shownFraction) > 0.012 else { return }207        shownFraction = fraction208        let radius = max(CGFloat(kind.width) / 2 + 7, 15)209        let path = UIBezierPath(arcCenter: CGPoint(x: CGFloat(kind.length) / 2 - 9, y: 0), radius: radius, startAngle: .pi / 2,210                                endAngle: .pi / 2 + .pi * 2 * CGFloat(max(fraction / 0.8, 0.02)), clockwise: true)211        ring.path = path.cgPath212        ring.strokeColor = fraction > 0.5 ? UIColor(hex: OrixColor.Hex.success) : fraction > 0.3 ? UIColor(hex: OrixColor.Hex.gold) : UIColor(hex: OrixColor.Hex.danger)213        body.color = UIColor(hex: OrixColor.Hex.danger)214        body.colorBlendFactor = fraction < 0.3 ? 0.35 : 0215    }216}217218final class TrafficScene: ArcadeScene {219    private(set) var sim: TrafficSim220    let model: TrafficRunModel221    private let layoutInfo: TrafficLayout222    private let autoplay: Bool223    private let onFinished: (TrafficRunSummary) -> Void224    private let onTutorialDone: () -> Void225226    private let city = SKSpriteNode()227    private var nodes: [Int: TrafficVehicleNode] = [:]228    private var intents: [Int: (node: SKShapeNode, leader: Int)] = [:]229    private var edgeMarkers: [Int: SKSpriteNode] = [:]230    private let preview = SKShapeNode()231    private let previewHead = SKShapeNode()232    private let conflictMarker = SKShapeNode()233    private let selectionRing = SKShapeNode(circleOfRadius: 21)234235    private var scaleK: CGFloat = 1236    private var selected: Int?237    private var touchStart = CGPoint.zero238    private var previewAge = 0.0239    private var botTimer = 0.0240    private var sirenTimer = 0.0241    private var bannerCount = 0242    private var finished = false243    private var lastSecond = -1244    private var unlockedLive: Set<String> = []245246    init(services: ArcadeServices, layout: TrafficLayout, mode: TrafficSim.Mode, seed: UInt64, tutorial: Bool, model: TrafficRunModel,247         onTutorialDone: @escaping () -> Void, onFinished: @escaping (TrafficRunSummary) -> Void) {248        sim = TrafficSim(layout: layout, mode: mode, seed: seed, tutorial: tutorial)249        layoutInfo = layout250        self.model = model251        autoplay = LaunchOptions.autoplay252        self.onFinished = onFinished253        self.onTutorialDone = onTutorialDone254        super.init(services: services, perfName: "traffic-\(layout.id)")255        backgroundColor = UIColor(hex: 0x0B1022)256        city.zPosition = -100257        world.addChild(city)258259        for node in [preview, previewHead, conflictMarker, selectionRing] {260            node.isHidden = true261            world.addChild(node)262        }263        preview.lineWidth = 6264        preview.lineCap = .round265        preview.lineJoin = .round266        preview.fillColor = .clear267        preview.zPosition = 20268        previewHead.zPosition = 21269        previewHead.lineWidth = 0270        conflictMarker.zPosition = 60271        conflictMarker.lineWidth = 3.5272        conflictMarker.lineCap = .round273        let cross = UIBezierPath(ovalIn: CGRect(x: -12, y: -12, width: 24, height: 24))274        cross.move(to: CGPoint(x: -5, y: -5)); cross.addLine(to: CGPoint(x: 5, y: 5))275        cross.move(to: CGPoint(x: -5, y: 5)); cross.addLine(to: CGPoint(x: 5, y: -5))276        conflictMarker.path = cross.cgPath277        conflictMarker.strokeColor = UIColor(hex: OrixColor.Hex.danger)278        conflictMarker.fillColor = UIColor(hex: OrixColor.Hex.danger, alpha: 0.25)279        selectionRing.lineWidth = 3280        selectionRing.fillColor = UIColor.white.withAlphaComponent(0.10)281        selectionRing.zPosition = 19282283        model.hearts = sim.hearts284        model.secondsLeft = mode == .rush ? Int(TrafficSim.rushDuration) : nil285        model.coach = Self.coachText(sim.tutorialStep)286    }287288    static func coachText(_ step: Int?) -> String? {289        switch step {290        case 0: "Tap the car to send it across the junction."291        case 1: "These two would crash. Send one, wait, then the other. Hold a car to preview its path."292        case 2: "Drivers lose patience — watch the ring. Every crash or walk-off costs a heart."293        default: nil294        }295    }296297    // MARK: Layout298299    override func layout() {300        // Fit 310 logical units across the screen, but keep at least 600 units of height visible.301        scaleK = min(size.width / 310, size.height / 600)302        world.setScale(scaleK)303        let focus = CGPoint(x: layoutInfo.focus.x, y: layoutInfo.focus.y)304        worldRestPosition = CGPoint(x: size.width / 2 - focus.x * scaleK, y: size.height / 2 - focus.y * scaleK)305        city.texture = TrafficArt.cityTexture(layout: layoutInfo, size: size, scale: scaleK)306        // World units: the baked texture covers exactly the screen once the world is scaled back up.307        city.size = CGSize(width: size.width / scaleK, height: size.height / scaleK)308        city.position = focus309    }310311    private func cg(_ v: Vec2) -> CGPoint { CGPoint(x: v.x, y: v.y) }312313    private var visibleHalfWidth: Double { Double(size.width / scaleK) / 2 }314315    // MARK: Loop316317    override func tick(dt: TimeInterval) {318        guard !finished else { return }319        if autoplay {320            botTimer -= dt321            if botTimer <= 0 {322                botTimer = 0.12323                for id in TrafficBot.choose(sim) { send(id) }324            }325        }326        let events = sim.advance(dt)327        for event in events { handle(event) }328        syncVehicles()329        syncIntents()330        syncEdgeMarkers()331        updateSelection(dt)332        updateAmbience(dt)333        if model.score != sim.score { model.score = sim.score }334        if sim.mode == .rush {335            let second = Int(sim.timeLeft.rounded(.up))336            if second != lastSecond {337                lastSecond = second338                model.secondsLeft = second339                if second <= 5, second > 0 { services.audio.play(.tick) }340            }341        }342    }343344    private func send(_ id: Int) {345        var events: [TrafficEvent] = []346        if sim.launch(id, events: &events) { events.forEach(handle) }347    }348349    // MARK: Events350351    private func handle(_ event: TrafficEvent) {352        switch event {353        case .spawned, .over: break354        case .launched(let id):355            guard let v = sim.vehicle(id) else { return }356            services.audio.play(.engine, pitch: v.kind == .sport ? 1.5 : v.kind == .truck || v.kind == .bus ? 0.75 : 1.1, volume: 0.7)357            services.haptics.play(.tap)358            nodes[id]?.setPatience(nil)359        case .cleared(let id, let points, let closeCall, let streak, let at):360            nodes[id]?.removeBlinkers()361            let before = model.multiplier362            model.streak = streak363            model.multiplier = sim.multiplier364            services.audio.play(.pass, pitch: 1 + Float(min(streak, 24)) * 0.02, volume: 0.8)365            if closeCall {366                floatText("Close call! +\(points)", at: cg(at), color: UIColor(hex: OrixColor.Hex.gold), size: 15)367                services.haptics.play(.nearMiss)368                services.audio.play(.coin)369                burst(at: cg(at), color: UIColor(hex: OrixColor.Hex.gold), count: 10, speed: 90, lifetime: 0.45, scale: 0.3, gravity: 0)370            } else {371                floatText("+\(points)", at: cg(at), color: .white, size: 13)372            }373            if sim.multiplier > before {374                services.audio.play(.combo, pitch: 0.9 + Float(sim.multiplier) * 0.1)375                services.haptics.play(.combo(sim.multiplier))376            }377            checkLiveAchievements()378        case .crashed(let a, let b, let at, let forgiven):379            for id in [a, b] { wreck(id) }380            let p = cg(at)381            burst(at: p, color: UIColor(hex: 0xFFB341), count: 26, speed: 190, lifetime: 0.55, scale: 0.4, gravity: 0)382            burst(at: p, color: .white, count: 12, speed: 260, lifetime: 0.3, scale: 0.22, gravity: 0, texture: TextureFactory.chip)383            burst(at: p, color: UIColor(hex: 0x8D95BA), count: 12, speed: 40, lifetime: 1.1, scale: 0.9, gravity: 30, additive: false)384            shake(0.9)385            services.audio.play(.crash)386            services.haptics.play(.failure)387            if forgiven { floatText("Crash! Try again", at: CGPoint(x: p.x, y: p.y + 26), color: UIColor(hex: OrixColor.Hex.gold), size: 15) }388            clearSelection()389        case .impatient(let id):390            services.audio.play(.horn, pitch: 1.05, volume: 0.6)391            nodes[id]?.body.run(.repeat(.sequence([.moveBy(x: 0, y: 1.6, duration: 0.04), .moveBy(x: 0, y: -3.2, duration: 0.08), .moveBy(x: 0, y: 1.6, duration: 0.04)]), count: 3))392        case .stormedOff(let id, let at):393            if let node = nodes.removeValue(forKey: id) {394                node.run(.sequence([.group([.fadeOut(withDuration: 0.35), .scale(to: 0.6, duration: 0.35)]), .removeFromParent()]))395            }396            burst(at: cg(at), color: UIColor(hex: 0xA9AED3), count: 14, speed: 60, lifetime: 0.7, scale: 0.7, gravity: 40, additive: false)397            floatText("Gave up!", at: CGPoint(x: at.x, y: at.y + 18), color: UIColor(hex: OrixColor.Hex.danger), size: 15)398            services.audio.play(.horn, pitch: 0.7)399            if selected == id { clearSelection() }400        case .heartLost(let remaining):401            model.hearts = remaining402            model.streak = 0403            model.multiplier = 1404            model.flash += 1405            services.haptics.play(.warning)406        case .stage(let stage):407            guard sim.mode == .endless, let text = TrafficDifficulty.announcement(layout: layoutInfo, stage: stage) else { return }408            bannerCount += 1409            model.banner = (bannerCount, text.title, text.detail)410            services.audio.play(.star, volume: 0.7)411        case .tutorial(let step):412            model.coach = Self.coachText(step)413            if step == nil { onTutorialDone() }414            else { services.audio.play(.confirm, volume: 0.6) }415        }416        if case .over(let reason) = event { finish(reason) }417    }418419    private func wreck(_ id: Int) {420        guard let node = nodes.removeValue(forKey: id) else { return }421        node.setPatience(nil)422        node.body.color = .black423        node.body.run(.colorize(withColorBlendFactor: 0.6, duration: 0.15))424        let spin = CGFloat.random(in: -1.4...1.4)425        node.run(.sequence([.group([.rotate(byAngle: reduceMotion ? 0 : spin, duration: 0.45), .sequence([.wait(forDuration: 0.5), .fadeOut(withDuration: 0.45)])]), .removeFromParent()]))426    }427428    private func checkLiveAchievements() {429        func unlock(_ id: String) {430            guard !unlockedLive.contains(id) else { return }431            unlockedLive.insert(id)432            services.unlock(id)433        }434        if sim.cleared >= 10 { unlock("traffic.first") }435        if sim.streak >= 25 { unlock("traffic.streak") }436        if sim.closeCalls >= 5 { unlock("traffic.close") }437        if sim.cleared >= 40, sim.heartsLost == 0 { unlock("traffic.flawless") }438    }439440    private func finish(_ reason: TrafficSim.OverReason) {441        guard !finished else { return }442        finished = true443        clearSelection()444        services.audio.play(reason == .timeUp ? .win : .fail)445        if reason == .timeUp { services.haptics.play(.success) }446        let summary = TrafficRunSummary(layout: layoutInfo.id, mode: sim.mode, finalScore: sim.finalScore, survivalBonus: sim.survivalBonus,447                                        cleared: sim.cleared, bestStreak: sim.bestStreak, closeCalls: sim.closeCalls, duration: sim.elapsed, reason: reason)448        writePerfReport()449        run(.sequence([.wait(forDuration: reason == .hearts ? 0.9 : 0.4), .run { [weak self] in self?.onFinished(summary) }]))450    }451452    // MARK: Node sync453454    private func syncVehicles() {455        var alive: Set<Int> = []456        for v in sim.vehicles {457            alive.insert(v.id)458            let path = layoutInfo.paths[v.path]459            let node: TrafficVehicleNode460            if let existing = nodes[v.id] {461                node = existing462            } else {463                node = TrafficVehicleNode(vehicle: v, turn: path.turn, steady: reduceMotion)464                node.zPosition = v.kind == .bus || v.kind == .truck ? 31 : 30465                world.addChild(node)466                nodes[v.id] = node467            }468            node.position = cg(path.point(at: v.s))469            node.zRotation = CGFloat(path.heading(at: v.s))470            node.setPatience(v.state == .waiting && v.patienceMax.isFinite ? v.patienceFraction : nil)471        }472        for (id, node) in nodes where !alive.contains(id) {473            node.removeFromParent()474            nodes[id] = nil475        }476    }477478    /// A short dotted arrow in front of each lane leader shows where it will go, before the player commits.479    private func syncIntents() {480        for lane in layoutInfo.controlledLanes {481            let leader = sim.leader(ofLane: lane.id)482            let path = leader.map { layoutInfo.paths[$0.path] }483            let near = leader.map { path!.stopS - ($0.s + $0.half) < 90 } ?? false484            guard let leader, let path, near else {485                intents[lane.id]?.node.isHidden = true486                continue487            }488            if let entry = intents[lane.id], entry.leader == leader.id {489                entry.node.isHidden = false490                continue491            }492            let node = intents[lane.id]?.node ?? {493                let created = SKShapeNode()494                created.lineWidth = 2.6495                created.lineCap = .round496                created.fillColor = .clear497                created.zPosition = 10498                world.addChild(created)499                return created500            }()501            let points = path.polyline(from: path.stopS + 5, to: path.stopS + 44, step: 4)502            let bezier = UIBezierPath()503            bezier.move(to: cg(points[0]))504            points.dropFirst().forEach { bezier.addLine(to: cg($0)) }505            let end = cg(points[points.count - 1])506            let heading = CGFloat(path.heading(at: path.stopS + 44))507            for side in [CGFloat(2.5), -2.5] {508                bezier.move(to: end)509                bezier.addLine(to: CGPoint(x: end.x + cos(heading + side) * 7, y: end.y + sin(heading + side) * 7))510            }511            node.path = bezier.cgPath.copy(dashingWithPhase: 0, lengths: [5, 4])512            let color: UInt32 = path.turn == .straight ? 0xFFFFFF : 0xFFB020513            node.strokeColor = UIColor(hex: color, alpha: leader.kind == .ambulance ? 0.95 : 0.6)514            node.isHidden = false515            intents[lane.id] = (node, leader.id)516        }517    }518519    /// Through traffic that is still off-screen gets a blinking chevron at the edge it will enter from.520    private func syncEdgeMarkers() {521        guard layoutInfo.throughPeriod > 0 else { return }522        let halfW = visibleHalfWidth523        var needed: Set<Int> = []524        for v in sim.vehicles where v.autonomous && v.state == .crossing {525            let p = layoutInfo.paths[v.path].point(at: v.s)526            let dx = p.x - layoutInfo.focus.x527            let heading = layoutInfo.paths[v.path].heading(at: v.s)528            let incoming = (dx < 0 && cos(heading) > 0) || (dx > 0 && cos(heading) < 0)529            guard abs(dx) > halfW + v.half, incoming else { continue }530            needed.insert(v.id)531            let marker = edgeMarkers[v.id] ?? {532                let created = SKSpriteNode(texture: TrafficArt.chevron, size: CGSize(width: 13, height: 16))533                created.color = UIColor(hex: v.kind == .sport ? OrixColor.Hex.danger : OrixColor.Hex.gold)534                created.colorBlendFactor = 1535                created.zPosition = 70536                if !reduceMotion { created.run(.repeatForever(.sequence([.fadeAlpha(to: 0.25, duration: 0.2), .fadeAlpha(to: 1, duration: 0.2)]))) }537                world.addChild(created)538                edgeMarkers[v.id] = created539                return created540            }()541            marker.position = CGPoint(x: layoutInfo.focus.x + (dx < 0 ? -(halfW - 12) : halfW - 12), y: p.y)542            marker.zRotation = dx < 0 ? 0 : .pi543        }544        for (id, marker) in edgeMarkers where !needed.contains(id) {545            marker.removeFromParent()546            edgeMarkers[id] = nil547        }548    }549550    private func updateAmbience(_ dt: TimeInterval) {551        sirenTimer -= dt552        if sirenTimer <= 0, sim.vehicles.contains(where: { $0.kind == .ambulance && $0.state != .cleared }) {553            sirenTimer = 1.5554            services.audio.play(.siren, volume: 0.5)555        }556    }557558    // MARK: Touch — tap to send, hold to preview, drag away to cancel559560    /// The launchable lane leader for the lane whose queue is nearest to `point` (logical coordinates).561    private func pick(at point: Vec2) -> Int? {562        var best: (id: Int, distance: Double)?563        for v in sim.vehicles where !v.autonomous && (v.state == .approaching || v.state == .waiting) {564            guard let leader = sim.leader(ofLane: v.lane), sim.canLaunch(leader.id) else { continue }565            let d = sim.position(of: v).distance(to: point) - v.half * 0.6566            if d < 62, d < (best?.distance ?? .infinity) { best = (leader.id, d) }567        }568        return best?.id569    }570571    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {572        guard !finished, !autoplay, let touch = touches.first else { return }573        let p = touch.location(in: world)574        touchStart = touch.location(in: self)575        guard let id = pick(at: Vec2(x: p.x, y: p.y)) else { return }576        selected = id577        previewAge = 1578        services.haptics.play(.select)579        updateSelection(0)580    }581582    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {583        guard selected != nil, let touch = touches.first else { return }584        let p = touch.location(in: self)585        if hypot(p.x - touchStart.x, p.y - touchStart.y) > 80 { clearSelection() }586    }587588    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {589        guard let id = selected else { return }590        clearSelection()591        guard !finished, !isPaused else { return }592        send(id)593    }594595    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { clearSelection() }596597    private func clearSelection() {598        selected = nil599        for node in [preview, previewHead, conflictMarker, selectionRing] { node.isHidden = true }600    }601602    private func updateSelection(_ dt: TimeInterval) {603        guard let id = selected else { return }604        guard sim.canLaunch(id), let v = sim.vehicle(id) else { clearSelection(); return }605        let path = layoutInfo.paths[v.path]606        selectionRing.position = cg(path.point(at: v.s))607        selectionRing.isHidden = false608        previewAge += dt609        guard previewAge >= 0.08 else { return }610        previewAge = 0611        let prediction = sim.predict(launching: id)612        let color = UIColor(hex: prediction.safe ? OrixColor.Hex.success : OrixColor.Hex.danger)613        selectionRing.strokeColor = color614        let end = path.exitS + 46615        let points = path.polyline(from: v.s + v.half, to: end, step: 5)616        let bezier = UIBezierPath()617        bezier.move(to: cg(points[0]))618        points.dropFirst().forEach { bezier.addLine(to: cg($0)) }619        preview.path = bezier.cgPath620        preview.strokeColor = color.withAlphaComponent(0.8)621        preview.isHidden = false622        let tip = cg(path.point(at: end + 9)), heading = CGFloat(path.heading(at: end))623        let head = UIBezierPath()624        head.move(to: tip)625        head.addLine(to: CGPoint(x: tip.x + cos(heading + 2.5) * 15, y: tip.y + sin(heading + 2.5) * 15))626        head.addLine(to: CGPoint(x: tip.x + cos(heading - 2.5) * 15, y: tip.y + sin(heading - 2.5) * 15))627        head.close()628        previewHead.path = head.cgPath629        previewHead.fillColor = color630        previewHead.isHidden = false631        if let at = prediction.collisionAt {632            conflictMarker.position = cg(at)633            conflictMarker.isHidden = false634        } else {635            conflictMarker.isHidden = true636        }637    }638}639
Files main
Menu

Theme