subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

commit 3cfd0cb10b0fe0140ff6623dc5f6ce4c6210f870
parent 7a24e6138a20e6d640c0ce16ef8b3d3e1c2b19fb
Author: Jean Schurger <jean@schurger.org>
Date:   Sun, 15 Nov 2026 22:04:21 -0500

Planner: recreational mode, earlier dives, ascent setpoint, tolerant plan decoding

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc

Diffstat:
MPackages/DiveKit/Sources/DivePlanner/Planner.swift | 128++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
MPackages/DiveKit/Tests/DivePlannerTests/DivePlannerTests.swift | 40++++++++++++++++++++++++++++++++++++++++
2 files changed, 160 insertions(+), 8 deletions(-)

diff --git a/Packages/DiveKit/Sources/DivePlanner/Planner.swift b/Packages/DiveKit/Sources/DivePlanner/Planner.swift @@ -85,6 +85,9 @@ public enum DecoModel: String, Codable, Sendable, CaseIterable { case buhlmann /// Varying permeability model with Boyle compensation. case vpmb + /// No-stop diving: the bottom time is extended to the no-stop limit (Bühlmann, with the gradient factors) or + /// to what the gas allows with its reserve, then a direct ascent. + case recreational } public enum BreathingMode: String, Codable, Sendable, CaseIterable { @@ -131,6 +134,10 @@ public struct PlanSettings: Codable, Sendable, Equatable { public var minimumGasFactor = 4.0 /// Pressure to keep in every cylinder, in bar. public var reserveBar = 40.0 + /// Stops every 10 ft instead of every 3 m. + public var stopsInFeet = false + /// Minutes shown at the surface after the dive (for the profile only). + public var surfaceSegmentMinutes = 0.0 public var environment = DiveEnvironment.sea public init() {} @@ -142,6 +149,34 @@ public struct PlanSettings: Codable, Sendable, Equatable { ascentRateStops = rate ascentRateLast6m = last6m ?? rate } + /// Tolerant decoding: a plan saved by an earlier version, without the newer settings, still opens. + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + if let value = try container.decodeIfPresent(type(of: model), forKey: .model) { model = value } + if let value = try container.decodeIfPresent(type(of: gfLow), forKey: .gfLow) { gfLow = value } + if let value = try container.decodeIfPresent(type(of: gfHigh), forKey: .gfHigh) { gfHigh = value } + if let value = try container.decodeIfPresent(type(of: vpmbConservatism), forKey: .vpmbConservatism) { vpmbConservatism = value } + if let value = try container.decodeIfPresent(type(of: descentRate), forKey: .descentRate) { descentRate = value } + if let value = try container.decodeIfPresent(type(of: ascentRate75), forKey: .ascentRate75) { ascentRate75 = value } + if let value = try container.decodeIfPresent(type(of: ascentRate50), forKey: .ascentRate50) { ascentRate50 = value } + if let value = try container.decodeIfPresent(type(of: ascentRateStops), forKey: .ascentRateStops) { ascentRateStops = value } + if let value = try container.decodeIfPresent(type(of: ascentRateLast6m), forKey: .ascentRateLast6m) { ascentRateLast6m = value } + if let value = try container.decodeIfPresent(type(of: lastStopAt6m), forKey: .lastStopAt6m) { lastStopAt6m = value } + if let value = try container.decodeIfPresent(type(of: safetyStop), forKey: .safetyStop) { safetyStop = value } + if let value = try container.decodeIfPresent(type(of: switchOnlyAtRequiredStops), forKey: .switchOnlyAtRequiredStops) { switchOnlyAtRequiredStops = value } + if let value = try container.decodeIfPresent(type(of: oxygenBreaks), forKey: .oxygenBreaks) { oxygenBreaks = value } + if let value = try container.decodeIfPresent(type(of: sacBottom), forKey: .sacBottom) { sacBottom = value } + if let value = try container.decodeIfPresent(type(of: sacDeco), forKey: .sacDeco) { sacDeco = value } + if let value = try container.decodeIfPresent(type(of: ppO2Bottom), forKey: .ppO2Bottom) { ppO2Bottom = value } + if let value = try container.decodeIfPresent(type(of: ppO2Deco), forKey: .ppO2Deco) { ppO2Deco = value } + if let value = try container.decodeIfPresent(type(of: gasSwitchSeconds), forKey: .gasSwitchSeconds) { gasSwitchSeconds = value } + if let value = try container.decodeIfPresent(type(of: problemMinutes), forKey: .problemMinutes) { problemMinutes = value } + if let value = try container.decodeIfPresent(type(of: minimumGasFactor), forKey: .minimumGasFactor) { minimumGasFactor = value } + if let value = try container.decodeIfPresent(type(of: reserveBar), forKey: .reserveBar) { reserveBar = value } + if let value = try container.decodeIfPresent(type(of: stopsInFeet), forKey: .stopsInFeet) { stopsInFeet = value } + if let value = try container.decodeIfPresent(type(of: surfaceSegmentMinutes), forKey: .surfaceSegmentMinutes) { surfaceSegmentMinutes = value } + if let value = try container.decodeIfPresent(type(of: environment), forKey: .environment) { environment = value } + } } public extension DiveEnvironment { @@ -161,12 +196,52 @@ public struct DivePlan: Codable, Sendable, Equatable { public var setpoint = 1.3 /// A rebreather dive ends on open circuit: the deco gases are the bailout gases. public var bailout = false + /// Closed circuit without bailout: a setpoint to switch to on the way up (nil: the same to the surface), and + /// the depth from which it applies, in metres. + public var ascentSetpoint: Double? + public var ascentSetpointDepth = 21.0 public init(levels: [PlanLevel], cylinders: [PlanCylinder], settings: PlanSettings = PlanSettings()) { self.levels = levels self.cylinders = cylinders self.settings = settings } + /// Tolerant decoding: a plan saved by an earlier version, without the newer settings, still opens. + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + levels = try container.decode([PlanLevel].self, forKey: .levels) + cylinders = try container.decode([PlanCylinder].self, forKey: .cylinders) + if let value = try container.decodeIfPresent(type(of: settings), forKey: .settings) { settings = value } + if let value = try container.decodeIfPresent(type(of: mode), forKey: .mode) { mode = value } + if let value = try container.decodeIfPresent(type(of: setpoint), forKey: .setpoint) { setpoint = value } + if let value = try container.decodeIfPresent(type(of: bailout), forKey: .bailout) { bailout = value } + ascentSetpoint = try container.decodeIfPresent(Double.self, forKey: .ascentSetpoint) + if let value = try container.decodeIfPresent(type(of: ascentSetpointDepth), forKey: .ascentSetpointDepth) { ascentSetpointDepth = value } + } +} + +/// A dive made before the one being planned, whose leftover gas counts. +public struct PriorDive: Sendable, Equatable { + public struct Sample: Sendable, Equatable { + /// Seconds since the start of that dive, metres, and the gas breathed from this point on. + public var time: Double + public var depth: Double + public var gas: BreathingGas + + public init(time: Double, depth: Double, gas: BreathingGas) { + self.time = time + self.depth = depth + self.gas = gas + } + } + public var samples: [Sample] + /// Seconds between the end of this dive and the start of the next one (or of the plan). + public var surfaceInterval: Double + + public init(samples: [Sample], surfaceInterval: Double) { + self.samples = samples + self.surfaceInterval = surfaceInterval + } } /// A point of the planned profile. @@ -207,6 +282,8 @@ public enum PlanWarning: Sendable, Equatable { /// What is left at the end of the bottom time is under the minimum gas. case underMinimumGas(cylinder: Int, leftBar: Double, minimumBar: Double) case cnsHigh(percent: Double) + /// Recreational mode: the dive as entered already needs decompression stops. + case exceedsNoStopLimit /// A level uses a cylinder that is not in the list. case unknownCylinder /// The decompression does not end (a gas that cannot be breathed up there, usually). @@ -233,6 +310,8 @@ public struct PlanResult: Sendable, Equatable { public var surfaceGF = 0.0 /// Ceiling when leaving the bottom, in metres. public var firstCeiling = 0.0 + /// Recreational mode: minutes added at the bottom, up to the no-stop limit or to what the gas allows. + public var bottomExtensionMinutes = 0.0 public var warnings: [PlanWarning] = [] public init() {} @@ -287,6 +366,10 @@ public enum DivePlanner { prefs.problemSolvingMinutes = Int(settings.problemMinutes.rounded()) prefs.bottomSac = settings.sacBottom * 1000 prefs.decoSac = settings.sacDeco * 1000 + prefs.imperialStops = settings.stopsInFeet + prefs.recreational = settings.model == .recreational + prefs.safetyStop = settings.safetyStop + prefs.reserveMbar = Int((settings.reserveBar * 1000).rounded()) return prefs } @@ -296,10 +379,18 @@ public enum DivePlanner { } private static func coreCylinders(_ plan: DivePlan) -> [CoreCylinder] { - plan.cylinders.map { cylinder in + var out = plan.cylinders.map { cylinder -> CoreCylinder in let change = cylinder.isDeco ? Int((switchDepth(of: cylinder, settings: plan.settings) * 1000).rounded()) : nil - return CoreCylinder(gas: coreGas(cylinder.gas), changeDepth: change.flatMap { $0 > 0 ? $0 : nil }) + return CoreCylinder(gas: coreGas(cylinder.gas), changeDepth: change.flatMap { $0 > 0 ? $0 : nil }, + sizeMl: Int(((cylinder.volumeLiters ?? 0) * 1000).rounded()), startMbar: Int(((cylinder.startBar ?? 0) * 1000).rounded())) + } + // The setpoint for the ascent is one more "cylinder" for the core: the diluent again, with a setpoint. + if plan.mode == .closedCircuit, !plan.bailout, let setpoint = plan.ascentSetpoint, let diluent = plan.levels.last?.cylinder, + plan.cylinders.indices.contains(diluent) { + out.append(CoreCylinder(gas: coreGas(plan.cylinders[diluent].gas), changeDepth: Int((plan.ascentSetpointDepth * 1000).rounded()), + setpoint: Int((setpoint * 1000).rounded()))) } + return out } /// The levels as legs: the way to each depth at the descent or ascent rate, then the rest of its time there. @@ -323,7 +414,7 @@ public enum DivePlanner { // MARK: Planning /// Plans the ascent of a dive: stops, run time, gas, oxygen exposure and what to worry about. - public static func plan(_ plan: DivePlan) -> PlanResult { + public static func plan(_ plan: DivePlan, after prior: [PriorDive] = []) -> PlanResult { var result = PlanResult() result.gasUsed = [Double](repeating: 0, count: plan.cylinders.count) let legs = waypoints(plan) @@ -332,15 +423,31 @@ public enum DivePlanner { return result } let settings = plan.settings - let output = CorePlanner.plan(waypoints: legs, cylinders: coreCylinders(plan), prefs: prefs(plan), model: model(plan)) + let earlier = prior.map { dive in + CorePriorDive(samples: dive.samples.map { + CorePriorDive.Sample(time: Int($0.time.rounded()), depth: Int(($0.depth * 1000).rounded()), gas: coreGas($0.gas)) + }, surfaceInterval: Int(dive.surfaceInterval.rounded())) + } + var output = CorePlanner.plan(waypoints: legs, cylinders: coreCylinders(plan), prefs: prefs(plan), model: model(plan), after: earlier) + // The setpoint "cylinder" is the diluent of the last level. + let diluent = plan.levels.last?.cylinder ?? 0 + func real(_ cylinder: Int) -> Int { plan.cylinders.indices.contains(cylinder) ? cylinder : diluent } + output.gasUsed = Array(output.gasUsed.prefix(plan.cylinders.count)) + output.decoGasUsed = Array(output.decoGasUsed.prefix(plan.cylinders.count)) result.points = output.track.map { - PlanPoint(time: Double($0.time), depth: Double($0.depth) / 1000, cylinder: $0.cylinder, onLoop: $0.mode != .openCircuit) + PlanPoint(time: Double($0.time), depth: Double($0.depth) / 1000, cylinder: real($0.cylinder), onLoop: $0.mode != .openCircuit) } result.stops = output.stops.map { - PlanStop(depth: Double($0.depth) / 1000, seconds: Double($0.seconds), cylinder: $0.cylinder, + PlanStop(depth: Double($0.depth) / 1000, seconds: Double($0.seconds), cylinder: real($0.cylinder), kind: $0.isGasSwitch ? .gasSwitch : .deco, endTime: Double($0.endTime)) } + result.bottomExtensionMinutes = Double(output.bottomExtension) / 60 + if output.exceedsNoStopLimit { result.warnings.append(.exceedsNoStopLimit) } + if settings.model == .recreational, output.hasSafetyStop, + let end = output.track.last(where: { $0.depth == 5000 }), let cylinder = result.points.last?.cylinder { + result.stops.append(PlanStop(depth: 5, seconds: 180, cylinder: cylinder, kind: .safety, endTime: Double(end.time))) + } result.runtime = Double(output.runtime) result.ascentTime = Double(output.runtime - output.bottomTime) result.maxDepth = plan.levels.map(\.depth).max() ?? 0 @@ -352,16 +459,19 @@ public enum DivePlanner { result.surfaceGF = surfaceGF(output.finalState) if output.timedOut { result.warnings.append(.endless) } - if !result.hasDecoStops, settings.safetyStop, result.maxDepth >= 10, !output.timedOut { + if settings.model != .recreational, !result.hasDecoStops, settings.safetyStop, result.maxDepth >= 10, !output.timedOut { insertSafetyStop(&result, plan: plan) } + if settings.surfaceSegmentMinutes > 0, let last = result.points.last { + result.points.append(PlanPoint(time: last.time + settings.surfaceSegmentMinutes * 60, depth: 0, cylinder: last.cylinder)) + } // Minimum gas (`plannernotes.cpp`): from the end of the bottom time, a problem to sort out and the ascent // to the first gas switch (or the surface), at a stressed consumption for two. let bottom = output.bottomCylinder let minimum = settings.minimumGasFactor * (settings.problemMinutes * settings.sacBottom * coreEnvironment(settings.environment).bar(output.bottomDepth) + output.decoGasUsed[bottom] / 1000) - if plan.mode == .openCircuit { result.minimumGasLiters = minimum } + if plan.mode == .openCircuit, settings.model != .recreational { result.minimumGasLiters = minimum } let usedAtBottom = (output.gasUsed[bottom] - output.decoGasUsed[bottom]) / 1000 result.warnings += warnings(for: plan, result: result, usedAtBottom: usedAtBottom, minimum: result.minimumGasLiters) return result @@ -461,6 +571,7 @@ public enum DivePlanner { /// differences, as Subsurface's "plan variations"). public static func variations(of plan: DivePlan) -> PlanVariations? { guard let last = plan.levels.indices.last, plan.levels[last].minutes > 1, plan.levels[last].depth > 1 else { return nil } + guard plan.settings.model != .recreational else { return nil } func runtime(depth: Double, minutes: Double) -> Double { var changed = plan changed.levels[last].depth += depth @@ -479,6 +590,7 @@ public enum DivePlanner { public static func noStopLimit(depth: Double, gas: BreathingGas, settings: PlanSettings = PlanSettings(), ceiling: Int = 300) -> Int? { var plan = DivePlan(levels: [], cylinders: [PlanCylinder(gas: gas)], settings: settings) plan.settings.safetyStop = false + plan.settings.model = .buhlmann // The limit is the last whole minute whose plan has no mandatory stop: found by bisection. func free(_ minutes: Int) -> Bool { plan.levels = [PlanLevel(depth: depth, minutes: Double(minutes))] diff --git a/Packages/DiveKit/Tests/DivePlannerTests/DivePlannerTests.swift b/Packages/DiveKit/Tests/DivePlannerTests/DivePlannerTests.swift @@ -139,3 +139,43 @@ final class DivePlannerTests: XCTestCase { XCTAssertLessThanOrEqual(strict.surfaceGF, 0.86) } } + +extension DivePlannerTests { + /// A plan saved by an earlier version (fewer settings) still opens, with the defaults for what it lacks. + func testOlderPlanStillDecodes() throws { + let plan = DivePlan(levels: [PlanLevel(depth: 30, minutes: 20)], cylinders: [PlanCylinder(gas: .air)]) + var object = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(plan)) as? [String: Any]) + var settings = try XCTUnwrap(object["settings"] as? [String: Any]) + for key in ["stopsInFeet", "surfaceSegmentMinutes", "reserveBar", "model", "vpmbConservatism"] { settings.removeValue(forKey: key) } + settings["gfHigh"] = 0.7 + object["settings"] = settings + for key in ["ascentSetpointDepth", "bailout", "mode", "setpoint"] { object.removeValue(forKey: key) } + let decoded = try JSONDecoder().decode(DivePlan.self, from: JSONSerialization.data(withJSONObject: object)) + XCTAssertEqual(decoded.settings.gfHigh, 0.7) + XCTAssertEqual(decoded.settings.reserveBar, 40) + XCTAssertEqual(decoded.settings.model, .buhlmann) + XCTAssertEqual(decoded.mode, .openCircuit) + XCTAssertEqual(decoded.levels, plan.levels) + XCTAssertEqual(try JSONDecoder().decode(DivePlan.self, from: JSONEncoder().encode(plan)), plan) + } + + /// The public planner in recreational mode, and after an earlier dive. + func testRecreationalAndRepetitive() { + var settings = PlanSettings() + settings.model = .recreational + let cylinders = [PlanCylinder(gas: .air, volumeLiters: 15, startBar: 200)] + let plan = DivePlan(levels: [PlanLevel(depth: 18, minutes: 20)], cylinders: cylinders, settings: settings) + let result = DivePlanner.plan(plan) + XCTAssertGreaterThan(result.bottomExtensionMinutes, 0) + XCTAssertEqual(result.stops.map(\.kind), [.safety]) + XCTAssertFalse(result.warnings.contains(.exceedsNoStopLimit)) + XCTAssertNil(result.minimumGasLiters) + // After a dive an hour before, the same dive can be extended less (or the gas still decides). + let earlier = PriorDive(samples: result.points.map { PriorDive.Sample(time: $0.time, depth: $0.depth, gas: .air) }, surfaceInterval: 3600) + let big = DivePlan(levels: plan.levels, cylinders: [PlanCylinder(gas: .air, volumeLiters: 40, startBar: 200)], settings: settings) + XCTAssertLessThan(DivePlanner.plan(big, after: [earlier]).bottomExtensionMinutes, DivePlanner.plan(big).bottomExtensionMinutes) + var deep = plan + deep.levels = [PlanLevel(depth: 40, minutes: 60)] + XCTAssertTrue(DivePlanner.plan(deep).warnings.contains(.exceedsNoStopLimit)) + } +}