SPB Git

Repository Public License

PulseBeatSave.swift 14.7 KB 306 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Arcade9// File             : Games/PulseBeat/PulseBeatSave.swift10// Description      : Pulse Beat — persisted progress (bests per chart, unlocks,11//                    calibration offsets per audio route, options, lifetime12//                    totals) and the rules that apply a finished run to it and13//                    report it to the platform.14// Module           : Games15// Repository       : https://git.spboucher.ai/orix-arcade16// Created          : 2026-11-2117// Last Modified    : 2026-11-2218//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : Proprietary, all rights reserved (see license file)84// License File     : LICENSE85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation9394/// The best result on one chart. Each field keeps its own maximum, so a higher score never erases a better accuracy.95nonisolated struct PulseBest: Codable, Equatable, Sendable {96    var score = 097    /// Accuracy in tenths of a percent (0…1000).98    var accuracy = 099    var grade = 0100    var maxCombo = 0101    var fullCombo = false102    var allPerfect = false103    var plays = 0104    var cleared = false105106    init() {}107108    init(from decoder: Decoder) throws {109        let c = try decoder.container(keyedBy: CodingKeys.self)110        score = max(0, try c.decodeIfPresent(Int.self, forKey: .score) ?? 0)111        accuracy = (try c.decodeIfPresent(Int.self, forKey: .accuracy) ?? 0).clamped(0, 1000)112        grade = (try c.decodeIfPresent(Int.self, forKey: .grade) ?? 0).clamped(0, PulseGrade.s.rawValue)113        maxCombo = max(0, try c.decodeIfPresent(Int.self, forKey: .maxCombo) ?? 0)114        fullCombo = try c.decodeIfPresent(Bool.self, forKey: .fullCombo) ?? false115        allPerfect = try c.decodeIfPresent(Bool.self, forKey: .allPerfect) ?? false116        plays = max(0, try c.decodeIfPresent(Int.self, forKey: .plays) ?? 0)117        cleared = try c.decodeIfPresent(Bool.self, forKey: .cleared) ?? false118    }119120    var pulseGrade: PulseGrade { PulseGrade(rawValue: grade) ?? .d }121}122123nonisolated struct PulseBeatSave: Codable, Equatable, Sendable {124    static let speeds = [1.0, 1.25, 1.5, 2.0]125    static let offsetLimit = PulseCalibration.limitMs126    static let visualLimit = 150127    /// Distinct charts that must be cleared to open each track, in track order.128    static let trackRequirements = [0, 0, 2, 4, 7]129    /// Grade on Hard that opens a track's Expert chart.130    static let expertGrade = PulseGrade.b131132    /// Bests keyed by "<track>-<difficulty>".133    var bests: [String: PulseBest] = [:]134    /// Calibration offset in milliseconds per audio route ("wired", "bluetooth").135    var offsets: [String: Int] = [:]136    /// Routes that went through the tap-along calibration at least once.137    var calibrated: [String] = []138    var visualOffsetMs = 0139    /// Index into `speeds`.140    var speed = 1141    var hitSounds = true142    var tutorialDone = false143    var calibrationPrompted = false144    var lastTrack = PulseLibrary.tracks[0].id145    var lastDifficulty = PulseDifficulty.easy.rawValue146    var plays = 0147    var clears = 0148    var notesHit = 0149    var perfects = 0150    var bestCombo = 0151    /// Sum of the accuracies (tenths of a percent) of every finished chart: the average is `accuracySum / plays`.152    var accuracySum = 0153154    init() {}155156    init(from decoder: Decoder) throws {157        let c = try decoder.container(keyedBy: CodingKeys.self)158        bests = try c.decodeIfPresent([String: PulseBest].self, forKey: .bests) ?? [:]159        offsets = (try c.decodeIfPresent([String: Int].self, forKey: .offsets) ?? [:]).mapValues { $0.clamped(-Self.offsetLimit, Self.offsetLimit) }160        calibrated = try c.decodeIfPresent([String].self, forKey: .calibrated) ?? []161        visualOffsetMs = (try c.decodeIfPresent(Int.self, forKey: .visualOffsetMs) ?? 0).clamped(-Self.visualLimit, Self.visualLimit)162        speed = (try c.decodeIfPresent(Int.self, forKey: .speed) ?? 1).clamped(0, Self.speeds.count - 1)163        hitSounds = try c.decodeIfPresent(Bool.self, forKey: .hitSounds) ?? true164        tutorialDone = try c.decodeIfPresent(Bool.self, forKey: .tutorialDone) ?? false165        calibrationPrompted = try c.decodeIfPresent(Bool.self, forKey: .calibrationPrompted) ?? false166        lastTrack = try c.decodeIfPresent(String.self, forKey: .lastTrack) ?? PulseLibrary.tracks[0].id167        if PulseLibrary.track(lastTrack) == nil { lastTrack = PulseLibrary.tracks[0].id }168        lastDifficulty = (try c.decodeIfPresent(Int.self, forKey: .lastDifficulty) ?? 0).clamped(0, PulseDifficulty.expert.rawValue)169        plays = max(0, try c.decodeIfPresent(Int.self, forKey: .plays) ?? 0)170        clears = max(0, try c.decodeIfPresent(Int.self, forKey: .clears) ?? 0)171        notesHit = max(0, try c.decodeIfPresent(Int.self, forKey: .notesHit) ?? 0)172        perfects = max(0, try c.decodeIfPresent(Int.self, forKey: .perfects) ?? 0)173        bestCombo = max(0, try c.decodeIfPresent(Int.self, forKey: .bestCombo) ?? 0)174        accuracySum = max(0, try c.decodeIfPresent(Int.self, forKey: .accuracySum) ?? 0)175    }176177    static func key(_ track: String, _ difficulty: PulseDifficulty) -> String { "\(track)-\(difficulty.rawValue)" }178179    func best(_ track: String, _ difficulty: PulseDifficulty) -> PulseBest? { bests[Self.key(track, difficulty)] }180    func offsetMs(route: String) -> Int { offsets[route] ?? 0 }181    func isCalibrated(route: String) -> Bool { calibrated.contains(route) }182    var noteSpeed: Double { Self.speeds[speed.clamped(0, Self.speeds.count - 1)] }183    var difficulty: PulseDifficulty { PulseDifficulty(rawValue: lastDifficulty) ?? .easy }184185    /// Distinct charts cleared (grade C or better).186    var chartsCleared: Int { bests.values.filter(\.cleared).count }187    var tracksCleared: Int {188        PulseLibrary.tracks.filter { track in PulseDifficulty.allCases.contains { best(track.id, $0)?.cleared == true } }.count189    }190    var overallBestScore: Int { bests.values.map(\.score).max() ?? 0 }191    /// Average accuracy over every finished chart, 0…100.192    var averageAccuracy: Double { plays > 0 ? Double(accuracySum) / Double(plays) / 10 : 0 }193194    func isTrackUnlocked(_ index: Int) -> Bool {195        guard index >= 0, index < PulseLibrary.tracks.count else { return false }196        return chartsCleared >= Self.trackRequirements[min(index, Self.trackRequirements.count - 1)]197    }198199    func isExpertUnlocked(_ track: String) -> Bool {200        guard let hard = best(track, .hard) else { return false }201        return hard.cleared && hard.pulseGrade >= Self.expertGrade202    }203204    func isUnlocked(_ track: String, _ difficulty: PulseDifficulty) -> Bool {205        isTrackUnlocked(PulseLibrary.index(of: track)) && (difficulty != .expert || isExpertUnlocked(track))206    }207208    var unlockedTracks: Int { PulseLibrary.tracks.indices.filter(isTrackUnlocked).count }209210    /// 0…1 from real results: each track is worth its best accuracy above 60 %, weighted by the difficulty it was earned on.211    var mastery: Double {212        let total = PulseLibrary.tracks.reduce(0.0) { sum, track in213            let value = PulseDifficulty.allCases.map { difficulty -> Double in214                guard let best = best(track.id, difficulty), best.cleared else { return 0 }215                return difficulty.masteryWeight * ((Double(best.accuracy) / 1000 - 0.6) / 0.38).clamped(0, 1)216            }.max() ?? 0217            return sum + value218        }219        return (total / Double(PulseLibrary.tracks.count)).clamped(0, 1)220    }221}222223/// What a finished run changed, for the results screen and the platform report.224nonisolated struct PulseReport: Sendable, Equatable {225    var isRecord = false226    var firstClear = false227    var newTracks: [String] = []228    var expertUnlocked = false229    var previousBest = 0230}231232nonisolated enum PulseProgress {233    /// Stores a finished run in the save and returns what it changed.234    static func apply(_ result: PulseResult, to save: inout PulseBeatSave) -> PulseReport {235        var report = PulseReport()236        let key = PulseBeatSave.key(result.trackID, result.difficulty)237        let tracksBefore = PulseLibrary.tracks.indices.filter(save.isTrackUnlocked)238        let expertBefore = save.isExpertUnlocked(result.trackID)239        var best = save.bests[key] ?? PulseBest()240        report.previousBest = best.score241        report.isRecord = result.tally.score > best.score && result.tally.score > 0242        report.firstClear = result.cleared && !best.cleared243        best.score = max(best.score, result.tally.score)244        best.accuracy = max(best.accuracy, result.accuracyPermille)245        best.grade = max(best.grade, result.grade.rawValue)246        best.maxCombo = max(best.maxCombo, result.tally.maxCombo)247        best.fullCombo = best.fullCombo || result.fullCombo248        best.allPerfect = best.allPerfect || result.allPerfect249        best.cleared = best.cleared || result.cleared250        best.plays += 1251        save.bests[key] = best252        save.plays += 1253        if result.cleared { save.clears += 1 }254        save.notesHit += result.tally.hits255        save.perfects += result.tally.perfects256        save.bestCombo = max(save.bestCombo, result.tally.maxCombo)257        save.accuracySum += result.accuracyPermille258        save.lastTrack = result.trackID259        save.lastDifficulty = result.difficulty.rawValue260        report.newTracks = PulseLibrary.tracks.indices.filter { save.isTrackUnlocked($0) && !tracksBefore.contains($0) }.map { PulseLibrary.tracks[$0].id }261        report.expertUnlocked = !expertBefore && save.isExpertUnlocked(result.trackID)262        return report263    }264265    /// Reports a finished run to the platform: statistics, trophies that are not goal-driven, and one-off experience.266    @MainActor267    static func deliver(_ result: PulseResult, report: PulseReport, to services: ArcadeServices) {268        let tally = result.tally269        services.addStat("pulse.notes", Double(tally.hits))270        services.addStat("pulse.perfects", Double(tally.perfects))271        services.addStat("pulse.plays", 1)272        if result.cleared { services.addStat("pulse.cleared", 1) }273        if result.fullCombo { services.addStat("pulse.fullCombos", 1) }274        services.bestStat("pulse.bestCombo", Double(tally.maxCombo))275        services.bestStat("pulse.bestScore", Double(tally.score))276        if result.cleared { services.bestStat("pulse.bestAccuracy", (result.accuracy * 100).rounded(.down)) }277278        if result.allPerfect { services.unlock("pulse.allPerfect") }279        if result.cleared {280            if result.grade >= .s { services.unlock("pulse.sRank") }281            if result.difficulty >= .hard { services.unlock("pulse.hardClear") }282            if result.difficulty == .expert {283                services.unlock("pulse.expertClear")284                if result.grade >= .s { services.unlock("pulse.expertS") }285            }286        }287        let save = services.save.pulse288        if save.tracksCleared >= PulseLibrary.tracks.count { services.unlock("pulse.allTracks") }289        if report.firstClear {290            let title = PulseLibrary.track(result.trackID)?.title ?? result.trackID291            services.grantOnce("pulse.clear.\(result.trackID).\(result.difficulty.rawValue)", xp: 14 + result.difficulty.rawValue * 4,292                               reason: "\(title) · \(result.difficulty.title)", game: .pulseBeat)293        }294    }295296    /// Stores the outcome of the tap-along calibration for a route.297    static func setCalibration(_ offsetMs: Int, route: String, in save: inout PulseBeatSave) {298        save.offsets[route] = offsetMs.clamped(-PulseBeatSave.offsetLimit, PulseBeatSave.offsetLimit)299        if !save.calibrated.contains(route) { save.calibrated.append(route) }300    }301}302303extension PulseDifficulty: Comparable {304    nonisolated static func < (a: PulseDifficulty, b: PulseDifficulty) -> Bool { a.rawValue < b.rawValue }305}306
Files main
Menu

Theme