commit af2340e1d875d9ad4daa47d2f352dec1f13636b4
parent 572fdedac2183998bdfbd3f1f0578c09c8b1363b
Author: Jean Schurger <jean@schurger.org>
Date: Sun, 15 Nov 2026 21:54:42 -0500
Planner on the ported core: VPM-B, rebreathers, plan variations, saving a plan
- The public planner converts to the ported core: the same plans as
Subsurface, in the app's units.
- Settings: Buhlmann or VPM-B with its conservatism, ascent rates by zone,
altitude, gas switches only at required stops, breaks during oxygen stops,
reserve in each cylinder. Plan: open circuit, closed circuit at a setpoint
or semi-closed, with open-circuit bailout.
- Results: how the run time varies with depth and time, pressures with the
compressibility of the gas (gas-model.cpp), reserve warning.
- A plan can be saved as a dive of the logbook (computer 'planned dive',
profile, the plan in the notes).
- Gas tab: maximum and narcotic depth by oxygen pressure, adjustable
narcotic depth, oxygen narcotic or not.
- French strings, README, version 0.9.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc
Diffstat:
11 files changed, 1032 insertions(+), 363 deletions(-)
diff --git a/App/Localizable.xcstrings b/App/Localizable.xcstrings
@@ -41,6 +41,26 @@
}
}
},
+ "%@ for %@ min on %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%@ pendant %@ min avec %@"
+ }
+ }
+ }
+ },
+ "%@ for %lld min on %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%@ pendant %lld min avec %@"
+ }
+ }
+ }
+ },
"%@ has no dives in memory.": {
"localizations": {
"fr": {
@@ -131,6 +151,16 @@
}
}
},
+ "%@: %@ left at the end, under the reserve of %@.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%@ : %@ restants à la fin, sous la réserve de %@."
+ }
+ }
+ }
+ },
"%@: %@ left when leaving the bottom, under the minimum gas of %@.": {
"localizations": {
"fr": {
@@ -271,6 +301,16 @@
}
}
},
+ ", open-circuit bailout": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": ", secours en circuit ouvert"
+ }
+ }
+ }
+ },
"0": {
"localizations": {
"fr": {
@@ -631,6 +671,16 @@
}
}
},
+ "Altitude": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Altitude"
+ }
+ }
+ }
+ },
"Anemones, nudibranchs and crabs under the pilings.": {
"localizations": {
"fr": {
@@ -691,6 +741,46 @@
}
}
},
+ "Ascent on open-circuit bailout": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Remontée en secours circuit ouvert"
+ }
+ }
+ }
+ },
+ "Ascent, deepest quarter": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Remontée, quart le plus profond"
+ }
+ }
+ }
+ },
+ "Ascent, to half the depth": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Remontée, jusqu'à mi-profondeur"
+ }
+ }
+ }
+ },
+ "Ascent, up to %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Remontée, jusqu'à %@"
+ }
+ }
+ }
+ },
"At the bottom": {
"localizations": {
"fr": {
@@ -771,6 +861,16 @@
}
}
},
+ "Bailout, from %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Secours, à partir de %@"
+ }
+ }
+ }
+ },
"Belt, pockets…": {
"localizations": {
"fr": {
@@ -841,6 +941,16 @@
}
}
},
+ "Breaks during oxygen stops": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Pauses pendant les paliers à l'oxygène"
+ }
+ }
+ }
+ },
"Buddies": {
"localizations": {
"fr": {
@@ -861,6 +971,26 @@
}
}
},
+ "By oxygen pressure": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Selon la pression d'oxygène"
+ }
+ }
+ }
+ },
+ "Bühlmann": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Bühlmann"
+ }
+ }
+ }
+ },
"Bühlmann ZHL-16C with gradient factors, open circuit, computed the way Subsurface's planner does.": {
"localizations": {
"fr": {
@@ -881,6 +1011,16 @@
}
}
},
+ "CNS %@ %%, OTU %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "CNS %@ %%, OTU %@"
+ }
+ }
+ }
+ },
"Cancel": {
"localizations": {
"fr": {
@@ -991,6 +1131,16 @@
}
}
},
+ "Circuit": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Circuit"
+ }
+ }
+ }
+ },
"Close": {
"localizations": {
"fr": {
@@ -1001,6 +1151,26 @@
}
}
},
+ "Closed circuit (CCR)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Circuit fermé (CCR)"
+ }
+ }
+ }
+ },
+ "Closed circuit, setpoint %@ bar": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Circuit fermé, point de consigne %@ bar"
+ }
+ }
+ }
+ },
"Code received by email": {
"localizations": {
"fr": {
@@ -1031,6 +1201,16 @@
}
}
},
+ "Computed the way Subsurface's planner does (Bühlmann ZHL-16C with gradient factors, or VPM-B): its own test plans give the same run times here.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Calculé comme le fait le planificateur de Subsurface (Bühlmann ZHL-16C avec facteurs de gradient, ou VPM-B) : ses propres plans de test donnent ici les mêmes durées."
+ }
+ }
+ }
+ },
"Computer": {
"localizations": {
"fr": {
@@ -1101,6 +1281,26 @@
}
}
},
+ "Conservatism: +%@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Conservatisme : +%@"
+ }
+ }
+ }
+ },
+ "Conservatism: +%lld": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Conservatisme : +%lld"
+ }
+ }
+ }
+ },
"Consumption at %@": {
"localizations": {
"fr": {
@@ -1351,6 +1551,16 @@
}
}
},
+ "Decompression model": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Modèle de décompression"
+ }
+ }
+ }
+ },
"Decompression, from %@": {
"localizations": {
"fr": {
@@ -1451,6 +1661,16 @@
}
}
},
+ "Density: 5.2 g/L is the recommended limit, 6.2 the one not to pass.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Densité : 5,2 g/L est la limite recommandée, 6,2 celle à ne pas dépasser."
+ }
+ }
+ }
+ },
"Depth": {
"localizations": {
"fr": {
@@ -1491,6 +1711,16 @@
}
}
},
+ "Diluent": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Diluant"
+ }
+ }
+ }
+ },
"Display": {
"localizations": {
"fr": {
@@ -1611,6 +1841,16 @@
}
}
},
+ "Dive plan made with %@ %@ (%@)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plan de plongée fait avec %@ %@ (%@)"
+ }
+ }
+ }
+ },
"Dive profile": {
"localizations": {
"fr": {
@@ -2711,6 +2951,26 @@
}
}
},
+ "Narcotic depth not to pass": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Profondeur narcotique à ne pas dépasser"
+ }
+ }
+ }
+ },
+ "Narcotic depth there": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Prof. narcotique à cette profondeur"
+ }
+ }
+ }
+ },
"Nearby": {
"localizations": {
"fr": {
@@ -3181,6 +3441,16 @@
}
}
},
+ "One metre deeper: %@ of run time. One minute longer: %@ of ascent.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Un mètre plus profond : %@ de durée totale. Une minute de plus : %@ de remontée."
+ }
+ }
+ }
+ },
"Open Settings": {
"localizations": {
"fr": {
@@ -3191,6 +3461,16 @@
}
}
},
+ "Open circuit": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Circuit ouvert"
+ }
+ }
+ }
+ },
"Open in Maps": {
"localizations": {
"fr": {
@@ -3251,6 +3531,16 @@
}
}
},
+ "Oxygen counts as narcotic": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "L'oxygène compte comme narcotique"
+ }
+ }
+ }
+ },
"Oxygen limits": {
"localizations": {
"fr": {
@@ -3451,6 +3741,16 @@
}
}
},
+ "Reserve in each cylinder": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Réserve dans chaque bouteille"
+ }
+ }
+ }
+ },
"Restore the iCloud backup (%lld dives, %@)": {
"localizations": {
"fr": {
@@ -3481,6 +3781,26 @@
}
}
},
+ "Run time: %@ min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Durée totale : %@ min"
+ }
+ }
+ }
+ },
+ "Run time: %lld min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Durée totale : %lld min"
+ }
+ }
+ }
+ },
"SAC": {
"localizations": {
"fr": {
@@ -3521,6 +3841,26 @@
}
}
},
+ "Save in the logbook…": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Enregistrer dans le carnet…"
+ }
+ }
+ }
+ },
+ "Save the plan": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Vers le carnet"
+ }
+ }
+ }
+ },
"Sea": {
"localizations": {
"fr": {
@@ -3581,6 +3921,26 @@
}
}
},
+ "Semi-closed (pSCR)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Semi-fermé (pSCR)"
+ }
+ }
+ }
+ },
+ "Semi-closed circuit": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Circuit semi-fermé"
+ }
+ }
+ }
+ },
"Send this iPhone's logbook to the account": {
"localizations": {
"fr": {
@@ -3601,6 +3961,16 @@
}
}
},
+ "Setpoint": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Point de consigne"
+ }
+ }
+ }
+ },
"Settings": {
"localizations": {
"fr": {
@@ -3631,6 +4001,16 @@
}
}
},
+ "Show how the plan varies": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Montrer comment le plan varie"
+ }
+ }
+ }
+ },
"Sign in": {
"localizations": {
"fr": {
@@ -3871,6 +4251,26 @@
}
}
},
+ "Stop at %@: %@ min on %@, until %@ min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Palier à %@ : %@ min avec %@, jusqu'à %@ min"
+ }
+ }
+ }
+ },
+ "Stop at %@: %lld min on %@, until %lld min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Palier à %@ : %lld min avec %@, jusqu'à %lld min"
+ }
+ }
+ }
+ },
"Stops": {
"localizations": {
"fr": {
@@ -4011,6 +4411,16 @@
}
}
},
+ "Switch gas only at required stops": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Changer de gaz seulement aux paliers requis"
+ }
+ }
+ }
+ },
"Sync now": {
"localizations": {
"fr": {
@@ -4281,6 +4691,16 @@
}
}
},
+ "The dive is on the loop to the end of the bottom time, then on the bailout gases: mark them as decompression gases.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "La plongée se fait sur la boucle jusqu'à la fin du temps de fond, puis sur les gaz de secours : marquez-les comme gaz de décompression."
+ }
+ }
+ }
+ },
"The dive no longer exists in the logbook.": {
"localizations": {
"fr": {
@@ -4341,6 +4761,16 @@
}
}
},
+ "The logbook already has a planned dive at that time.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le carnet a déjà une plongée planifiée à cette heure."
+ }
+ }
+ }
+ },
"The logbook is removed from this iPhone. The last copy saved in iCloud Drive, if any, stays there.": {
"localizations": {
"fr": {
@@ -4381,6 +4811,26 @@
}
}
},
+ "The oxygen in the loop is lower than in the cylinder, by what the diver uses up; decompression gases are breathed through the loop as well.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "L'oxygène dans la boucle est plus bas que dans la bouteille, de ce que le plongeur consomme ; les gaz de décompression sont eux aussi respirés par la boucle."
+ }
+ }
+ }
+ },
+ "The plan becomes a dive of the logbook, marked as planned, with its profile and the plan in its notes. It is sent to the Subsurface cloud like any other dive.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le plan devient une plongée du carnet, marquée comme planifiée, avec son profil et le plan dans ses notes. Elle est envoyée au nuage Subsurface comme toute autre plongée."
+ }
+ }
+ }
+ },
"The selected dives are added to the logbook with their full profile, then uploaded to the Subsurface cloud. A dive that overlaps one already in the logbook joins it as one more dive computer; a dive the logbook already has from this computer is skipped.": {
"localizations": {
"fr": {
@@ -4391,6 +4841,16 @@
}
}
},
+ "The whole dive is on the loop, on the diluent of the last level: the other cylinders are not used.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Toute la plongée se fait sur la boucle, avec le diluant du dernier niveau : les autres bouteilles ne servent pas."
+ }
+ }
+ }
+ },
"They'll appear with your first dives.": {
"localizations": {
"fr": {
diff --git a/App/Views/PlannerView.swift b/App/Views/PlannerView.swift
@@ -281,6 +281,8 @@ struct GasToolsView: View {
@AppStorage("gasToolBestDepth") private var bestDepth = 45.0
@AppStorage("gasToolBestPO2") private var bestPO2 = 1.4
@AppStorage("gasToolLimitEND") private var limitEND = true
+ @AppStorage("gasToolMaxEND") private var maxEND = 30.0
+ @AppStorage("gasToolOxygenNarcotic") private var oxygenNarcotic = true
@AppStorage("gasToolSAC") private var sac = 18.0
@AppStorage("gasToolMinutes") private var minutes = 30.0
@AppStorage("gasToolVolume") private var volume = 11.1
@@ -290,7 +292,8 @@ struct GasToolsView: View {
let gas = BreathingGas(o2: o2 / 100, he: he / 100)
let ppO2 = gas.ppO2(atDepth: depth)
let density = gas.density(atDepth: depth)
- let best = BreathingGas.bestMix(forDepth: bestDepth, ppO2: bestPO2, maximumEND: limitEND ? 30 : nil)
+ let best = BreathingGas.bestMix(forDepth: bestDepth, ppO2: bestPO2, maximumEND: limitEND ? maxEND : nil, oxygenNarcotic: oxygenNarcotic)
+ let end = gas.equivalentNarcoticDepth(atDepth: depth, oxygenNarcotic: oxygenNarcotic)
let liters = sac * DiveEnvironment.sea.pressure(atDepth: depth) * minutes
Form {
Section {
@@ -304,8 +307,7 @@ struct GasToolsView: View {
Section("At this depth") {
row("Oxygen pressure", fixed(ppO2, 2) + " bar", alert: ppO2 > 1.6 ? .red : (ppO2 > 1.4 ? .orange : (ppO2 < 0.16 ? .red : nil)))
- row("Equivalent narcotic depth", units.depth(gas.equivalentNarcoticDepth(atDepth: depth)),
- alert: gas.equivalentNarcoticDepth(atDepth: depth) > 30.5 ? .orange : nil)
+ row("Equivalent narcotic depth", units.depth(end), alert: end > maxEND + 0.5 ? .orange : nil)
if he == 0, o2 > 21 { row("Equivalent air depth", units.depth(gas.equivalentAirDepth(atDepth: depth))) }
row("Gas density", fixed(density, 1) + " g/L", alert: density > 6.2 ? .red : (density > 5.2 ? .orange : nil))
}
@@ -316,8 +318,39 @@ struct GasToolsView: View {
if gas.minimumDepth() > 0 { row("Not breathable above", units.depth(gas.minimumDepth()), alert: .orange) }
} header: {
Text("Maximum depth")
+ }
+
+ Section {
+ Grid(alignment: .trailing, horizontalSpacing: 12, verticalSpacing: 6) {
+ GridRow {
+ Text("Oxygen").gridColumnAlignment(.leading)
+ Text("Maximum depth")
+ Text("Narcotic depth there")
+ }
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ ForEach([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6], id: \.self) { limit in
+ let mod = gas.maximumOperatingDepth(ppO2: limit)
+ GridRow {
+ Text(fixed(limit, 1) + " bar")
+ Text(units.depth(mod))
+ Text(units.depth(gas.equivalentNarcoticDepth(atDepth: mod, oxygenNarcotic: oxygenNarcotic)))
+ }
+ .monospacedDigit()
+ .fontWeight(limit == 1.4 || limit == 1.6 ? .semibold : .regular)
+ }
+ }
+ .frame(maxWidth: .infinity)
+ } header: {
+ Text("By oxygen pressure")
+ }
+
+ Section {
+ Toggle("Oxygen counts as narcotic", isOn: $oxygenNarcotic)
+ NumberRow(title: "Narcotic depth not to pass", value: units.depthBinding($maxEND), unit: units.depthUnit,
+ range: units.depthValue(10)...units.depthValue(60), step: units.depthStep)
} footer: {
- Text("The narcotic depth counts oxygen as narcotic as nitrogen. Density: 5.2 g/L is the recommended limit, 6.2 the one not to pass.")
+ Text("Density: 5.2 g/L is the recommended limit, 6.2 the one not to pass.")
}
Section {
@@ -326,7 +359,7 @@ struct GasToolsView: View {
Picker("Oxygen pressure", selection: $bestPO2) {
ForEach([1.2, 1.3, 1.4, 1.5, 1.6], id: \.self) { Text(fixed($0, 1) + " bar").tag($0) }
}
- Toggle("Keep the narcotic depth at \(units.depth(30))", isOn: $limitEND)
+ Toggle("Keep the narcotic depth at \(units.depth(maxEND))", isOn: $limitEND)
HStack {
Text("Best mix")
Spacer()
diff --git a/App/Views/TechPlanView.swift b/App/Views/TechPlanView.swift
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-2.0-only
import Charts
import DivePlanner
+import SubsurfaceLog
import SwiftUI
/// The decompression planner: levels and cylinders in, stops, gas and warnings out.
@@ -9,8 +10,11 @@ struct TechPlanView: View {
@State private var plan = TechPlanView.stored()
@State private var result = PlanResult()
@State private var confirmingReset = false
+ @State private var variations: PlanVariations?
+ @AppStorage("planShowVariations") private var showVariations = false
+ @State private var saving = LaunchOptions.flag("-savePlan")
- private static let storageKey = "divePlan"
+ private static let storageKey = "divePlan2"
/// The plan the planner starts with: one level on one cylinder, one decompression gas.
static var starter: DivePlan {
@@ -29,6 +33,28 @@ struct TechPlanView: View {
let units = model.units
Form {
Section {
+ Picker("Circuit", selection: $plan.mode) {
+ Text("Open circuit").tag(BreathingMode.openCircuit)
+ Text("Closed circuit (CCR)").tag(BreathingMode.closedCircuit)
+ Text("Semi-closed (pSCR)").tag(BreathingMode.semiClosed)
+ }
+ if plan.mode == .closedCircuit {
+ NumberRow(title: "Setpoint", value: $plan.setpoint, unit: "bar", digits: 2, range: 0.4...1.6, step: 0.1)
+ }
+ if plan.mode != .openCircuit {
+ Toggle("Ascent on open-circuit bailout", isOn: $plan.bailout)
+ }
+ } footer: {
+ if plan.mode == .closedCircuit {
+ Text(plan.bailout
+ ? "The dive is on the loop to the end of the bottom time, then on the bailout gases: mark them as decompression gases."
+ : "The whole dive is on the loop, on the diluent of the last level: the other cylinders are not used.")
+ } else if plan.mode == .semiClosed {
+ Text("The oxygen in the loop is lower than in the cylinder, by what the diver uses up; decompression gases are breathed through the loop as well.")
+ }
+ }
+
+ Section {
ForEach($plan.levels) { $level in
VStack(spacing: 8) {
NumberRow(title: "Depth", value: units.depthBinding($level.depth), unit: units.depthUnit, digits: units.imperial ? 0 : 1,
@@ -81,7 +107,9 @@ struct TechPlanView: View {
HStack {
Text("Settings")
Spacer()
- Text(verbatim: "GF \(Int((plan.settings.gfLow * 100).rounded()))/\(Int((plan.settings.gfHigh * 100).rounded()))")
+ Text(verbatim: plan.settings.model == .vpmb
+ ? "VPM-B +\(plan.settings.vpmbConservatism)"
+ : "GF \(Int((plan.settings.gfLow * 100).rounded()))/\(Int((plan.settings.gfHigh * 100).rounded()))")
.foregroundStyle(.secondary)
}
}
@@ -99,10 +127,13 @@ struct TechPlanView: View {
gasSection(units)
Section {
+ Toggle("Show how the plan varies", isOn: $showVariations)
+ Button { saving = true } label: { Label("Save in the logbook…", systemImage: "square.and.arrow.down") }
+ .disabled(result.points.count < 2 || model.isDemo)
Button("Start a new plan", role: .destructive) { confirmingReset = true }
} footer: {
VStack(alignment: .leading, spacing: 6) {
- Text("Bühlmann ZHL-16C with gradient factors, open circuit, computed the way Subsurface's planner does.")
+ Text("Computed the way Subsurface's planner does (Bühlmann ZHL-16C with gradient factors, or VPM-B): its own test plans give the same run times here.")
PlanningDisclaimer()
}
}
@@ -114,8 +145,20 @@ struct TechPlanView: View {
if let data = try? JSONEncoder().encode(plan) { UserDefaults.standard.set(data, forKey: Self.storageKey) }
let current = plan
let computed = await Task.detached(priority: .userInitiated) { DivePlanner.plan(current) }.value
- if !Task.isCancelled { result = computed }
+ guard !Task.isCancelled else { return }
+ result = computed
+ variations = nil
+ if showVariations {
+ let around = await Task.detached(priority: .utility) { DivePlanner.variations(of: current) }.value
+ if !Task.isCancelled { variations = around }
+ }
+ }
+ .task(id: showVariations) {
+ guard showVariations, variations == nil else { return }
+ let current = plan
+ variations = await Task.detached(priority: .utility) { DivePlanner.variations(of: current) }.value
}
+ .sheet(isPresented: $saving) { SavePlanView(plan: plan, result: result) }
}
// MARK: Results
@@ -133,6 +176,12 @@ struct TechPlanView: View {
}
}
.listRowInsets(EdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12))
+ if showVariations, let variations {
+ Label(String(localized: "One metre deeper: \(signed(variations.perMeter)) of run time. One minute longer: \(signed(variations.perMinute)) of ascent."),
+ systemImage: "plusminus")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ }
ForEach(Array(result.warnings.enumerated()), id: \.offset) { _, warning in
Label(describe(warning, units), systemImage: "exclamationmark.triangle.fill")
.font(.callout)
@@ -146,7 +195,7 @@ struct TechPlanView: View {
@ViewBuilder private func stops(_ units: Units) -> some View {
Section {
if result.stops.isEmpty {
- Text("No stop: a direct ascent at \(units.depth(plan.settings.ascentRate)) per minute.")
+ Text("No stop: a direct ascent at \(units.depth(plan.settings.ascentRateStops)) per minute.")
.foregroundStyle(.secondary)
}
ForEach(Array(result.stops.enumerated()), id: \.offset) { _, stop in
@@ -187,11 +236,10 @@ struct TechPlanView: View {
Text(verbatim: cylinder.gas.name).frame(width: 84, alignment: .leading)
VStack(alignment: .leading, spacing: 2) {
Text(fixed(used, 0) + " L").monospacedDigit()
- if let volume = cylinder.volumeLiters, volume > 0, let start = cylinder.startBar {
- let left = start - used / volume
- Text(String(localized: "\(units.pressure(used / volume)) used, \(units.pressure(max(0, left))) left"))
+ if let start = cylinder.startBar, let left = cylinder.pressure(afterUsing: used) {
+ Text(String(localized: "\(units.pressure(max(0, start - left))) used, \(units.pressure(max(0, left))) left"))
.font(.caption)
- .foregroundStyle(left < 0 ? Color.red : Color.secondary)
+ .foregroundStyle(left < plan.settings.reserveBar ? (left < 0 ? Color.red : Color.orange) : Color.secondary)
}
}
Spacer()
@@ -202,7 +250,7 @@ struct TechPlanView: View {
HStack {
Text("Minimum gas")
Spacer()
- Text(cylinder.volumeLiters.map { units.pressure(minimum / max($0, 0.1)) } ?? fixed(minimum, 0) + " L")
+ Text(cylinder.volumeLiters.map { units.pressure(RealGas.pressure(cylinder.gas, liters: minimum, volumeLiters: max($0, 0.1))) } ?? fixed(minimum, 0) + " L")
.monospacedDigit()
.foregroundStyle(.secondary)
}
@@ -223,8 +271,10 @@ struct TechPlanView: View {
Text(verbatim: "\(units.volume(volume)) · \(units.pressure(start))").font(.callout)
}
Text(cylinder.isDeco
- ? String(localized: "Decompression, from \(units.depth(cylinder.switchDepth ?? cylinder.gas.switchDepth(ppO2: plan.settings.ppO2Deco, in: plan.settings.environment)))")
- : String(localized: "Bottom gas"))
+ ? (plan.mode != .openCircuit && plan.bailout
+ ? String(localized: "Bailout, from \(units.depth(DivePlanner.switchDepth(of: cylinder, settings: plan.settings)))")
+ : String(localized: "Decompression, from \(units.depth(DivePlanner.switchDepth(of: cylinder, settings: plan.settings)))"))
+ : (plan.mode == .closedCircuit ? String(localized: "Diluent") : String(localized: "Bottom gas")))
.font(.caption)
.foregroundStyle(.secondary)
}
@@ -244,10 +294,19 @@ struct TechPlanView: View {
}
}
+ /// "+2 min 30 s", "−40 s".
+ private func signed(_ seconds: Double) -> String {
+ let whole = Int(seconds.rounded())
+ let sign = whole < 0 ? "−" : "+"
+ let minutes = abs(whole) / 60, rest = abs(whole) % 60
+ if minutes == 0 { return "\(sign)\(rest) s" }
+ return rest == 0 ? "\(sign)\(minutes) min" : "\(sign)\(minutes) min \(rest) s"
+ }
+
private func isSevere(_ warning: PlanWarning) -> Bool {
switch warning {
case .oxygenTooHigh, .oxygenTooLow, .notEnoughGas, .endless, .unknownCylinder: return true
- case .narcosis, .density, .underMinimumGas, .cnsHigh: return false
+ case .narcosis, .density, .underMinimumGas, .underReserve, .cnsHigh: return false
}
}
@@ -266,6 +325,8 @@ struct TechPlanView: View {
return String(localized: "Not enough \(name(cylinder)): \(fixed(needed, 0)) L needed, \(fixed(available, 0)) L in the cylinder.")
case .underMinimumGas(let cylinder, let left, let minimum):
return String(localized: "\(name(cylinder)): \(units.pressure(left)) left when leaving the bottom, under the minimum gas of \(units.pressure(minimum)).")
+ case .underReserve(let cylinder, let left, let reserve):
+ return String(localized: "\(name(cylinder)): \(units.pressure(left)) left at the end, under the reserve of \(units.pressure(reserve)).")
case .cnsHigh(let percent):
return String(localized: "Oxygen clock at \(fixed(percent, 0)) %.")
case .unknownCylinder:
@@ -402,6 +463,19 @@ private struct PlanSettingsEditor: View {
let units = model.units
Form {
Section {
+ Picker("Model", selection: $settings.model) {
+ Text("Bühlmann").tag(DecoModel.buhlmann)
+ Text(verbatim: "VPM-B").tag(DecoModel.vpmb)
+ }
+ .pickerStyle(.segmented)
+ if settings.model == .vpmb {
+ Stepper("Conservatism: +\(settings.vpmbConservatism)", value: $settings.vpmbConservatism, in: 0...4)
+ }
+ } header: {
+ Text("Decompression model")
+ }
+ if settings.model == .buhlmann {
+ Section {
Menu {
ForEach(Conservatism.allCases) { level in
Button(level.label) {
@@ -419,9 +493,12 @@ private struct PlanSettingsEditor: View {
} footer: {
Text("Lower figures are more conservative. The low factor sets how deep the first stop is, the high one how much is left on surfacing.")
}
+ }
Section("Speeds") {
NumberRow(title: "Descent", value: units.depthBinding($settings.descentRate), unit: "\(units.depthUnit)/min", range: 1...units.depthValue(40), step: units.depthStep)
- NumberRow(title: "Ascent", value: units.depthBinding($settings.ascentRate), unit: "\(units.depthUnit)/min", range: 1...units.depthValue(18), step: units.depthStep)
+ NumberRow(title: "Ascent, deepest quarter", value: units.depthBinding($settings.ascentRate75), unit: "\(units.depthUnit)/min", range: 1...units.depthValue(18), step: units.depthStep)
+ NumberRow(title: "Ascent, to half the depth", value: units.depthBinding($settings.ascentRate50), unit: "\(units.depthUnit)/min", range: 1...units.depthValue(18), step: units.depthStep)
+ NumberRow(title: "Ascent, up to \(units.depth(6))", value: units.depthBinding($settings.ascentRateStops), unit: "\(units.depthUnit)/min", range: 1...units.depthValue(18), step: units.depthStep)
NumberRow(title: "Ascent above \(units.depth(6))", value: units.depthBinding($settings.ascentRateLast6m), unit: "\(units.depthUnit)/min",
range: 1...units.depthValue(18), step: units.depthStep)
}
@@ -429,6 +506,8 @@ private struct PlanSettingsEditor: View {
Toggle("Last stop at \(units.depth(6))", isOn: $settings.lastStopAt6m)
Toggle("Safety stop when no stop is needed", isOn: $settings.safetyStop)
NumberRow(title: "Gas switch", value: $settings.gasSwitchSeconds, unit: "s", range: 0...300, step: 30)
+ Toggle("Switch gas only at required stops", isOn: $settings.switchOnlyAtRequiredStops)
+ Toggle("Breaks during oxygen stops", isOn: $settings.oxygenBreaks)
}
Section("Consumption at the surface") {
NumberRow(title: "At the bottom", value: $settings.sacBottom, unit: "L/min", digits: 1, range: 5...60, step: 1)
@@ -437,6 +516,7 @@ private struct PlanSettingsEditor: View {
Section {
NumberRow(title: "Problem at the bottom", value: $settings.problemMinutes, unit: "min", range: 0...10, step: 1)
NumberRow(title: "Consumption factor", value: $settings.minimumGasFactor, unit: "×", digits: 1, range: 1...6, step: 0.5)
+ NumberRow(title: "Reserve in each cylinder", value: units.pressureBinding($settings.reserveBar), unit: units.pressureUnit, range: 0...units.pressureValue(150))
} header: {
Text("Minimum gas")
}
@@ -451,6 +531,7 @@ private struct PlanSettingsEditor: View {
Text("Fresh").tag(true)
}
.pickerStyle(.segmented)
+ NumberRow(title: "Altitude", value: altitude(units), unit: units.depthUnit, range: 0...units.depthValue(5000), step: units.imperial ? 500 : 100)
NumberRow(title: "Pressure at the surface", value: $settings.environment.surfacePressure, unit: "bar", digits: 3, range: 0.5...1.1)
}
}
@@ -458,6 +539,14 @@ private struct PlanSettingsEditor: View {
.navigationBarTitleDisplayMode(.inline)
}
+ private func altitude(_ units: Units) -> Binding<Double> {
+ Binding {
+ units.depthValue(max(0, settings.environment.altitude)).rounded()
+ } set: {
+ settings.environment.altitude = units.metersFromDisplay($0)
+ }
+ }
+
private func fraction(_ path: WritableKeyPath<PlanSettings, Double>) -> Binding<Double> {
Binding {
(settings[keyPath: path] * 100).rounded()
@@ -466,3 +555,109 @@ private struct PlanSettingsEditor: View {
}
}
}
+
+/// Saves the plan as a dive of the logbook, the way Subsurface does: a dive whose computer is "planned dive",
+/// with the planned profile and the plan written in its notes.
+struct SavePlanView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ let plan: DivePlan
+ let result: PlanResult
+ @State private var date = Calendar.current.date(bySetting: .minute, value: 0, of: Date().addingTimeInterval(3600)) ?? Date()
+ @State private var working = false
+ @State private var error: String?
+
+ var body: some View {
+ NavigationStack {
+ Form {
+ Section {
+ DatePicker("Start", selection: $date)
+ } footer: {
+ Text("The plan becomes a dive of the logbook, marked as planned, with its profile and the plan in its notes. It is sent to the Subsurface cloud like any other dive.")
+ }
+ Section("Notes") {
+ Text(PlanText.notes(plan: plan, result: result, units: model.units))
+ .font(.footnote.monospaced())
+ }
+ if let error {
+ Section { Text(error).foregroundStyle(.red) }
+ }
+ }
+ .navigationTitle("Save the plan")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Save", action: save).disabled(working)
+ }
+ }
+ }
+ }
+
+ private func save() {
+ working = true
+ var dive = ImportedDive(when: DiveDate.naive(from: date), durationSeconds: Int(result.runtime.rounded()))
+ dive.model = "planned dive"
+ dive.sourceID = "plan-\(dive.when)"
+ dive.notes = PlanText.notes(plan: plan, result: result, units: model.units)
+ dive.surfacePressureBar = plan.settings.environment.surfacePressure
+ dive.salinity = Int((plan.settings.environment.waterDensity * 1000).rounded())
+ dive.samples = result.points.map { point in
+ var sample = ImportedDive.Sample(time: Int(point.time.rounded()), depth: (point.depth * 100).rounded() / 100)
+ if plan.cylinders.indices.contains(point.cylinder) {
+ sample.o2 = plan.cylinders[point.cylinder].gas.o2Percent
+ sample.he = plan.cylinders[point.cylinder].gas.hePercent
+ }
+ return sample
+ }
+ Task {
+ do {
+ if try await model.importDives([dive]) == 0 {
+ throw AppError.message(String(localized: "The logbook already has a planned dive at that time."))
+ }
+ dismiss()
+ } catch {
+ self.error = AppModel.describe(error)
+ working = false
+ }
+ }
+ }
+}
+
+/// The plan as text, for the notes of the saved dive.
+enum PlanText {
+ static func notes(plan: DivePlan, result: PlanResult, units: Units) -> String {
+ func name(_ index: Int) -> String { plan.cylinders.indices.contains(index) ? plan.cylinders[index].gas.name : "?" }
+ let settings = plan.settings
+ var lines = [String]()
+ let model = settings.model == .vpmb
+ ? "VPM-B +\(settings.vpmbConservatism)"
+ : "Bühlmann ZHL-16C GF \(Int((settings.gfLow * 100).rounded()))/\(Int((settings.gfHigh * 100).rounded()))"
+ lines.append(String(localized: "Dive plan made with \(Brand.name) \(Brand.shortVersion) (\(model))"))
+ switch plan.mode {
+ case .openCircuit: break
+ case .closedCircuit: lines.append(String(localized: "Closed circuit, setpoint \(fixed(plan.setpoint, 2)) bar") + (plan.bailout ? String(localized: ", open-circuit bailout") : ""))
+ case .semiClosed: lines.append(String(localized: "Semi-closed circuit") + (plan.bailout ? String(localized: ", open-circuit bailout") : ""))
+ }
+ lines.append("")
+ for level in plan.levels {
+ lines.append(String(localized: "\(units.depth(level.depth)) for \(Int(level.minutes.rounded())) min on \(name(level.cylinder))"))
+ }
+ lines.append("")
+ for stop in result.stops {
+ let minutes = Int((stop.seconds / 60).rounded()), end = Int((stop.endTime / 60).rounded())
+ lines.append(String(localized: "Stop at \(units.depth(stop.depth)): \(minutes) min on \(name(stop.cylinder)), until \(end) min"))
+ }
+ lines.append(String(localized: "Run time: \(Int((result.runtime / 60).rounded())) min"))
+ lines.append("")
+ for (index, cylinder) in plan.cylinders.enumerated() where result.gasUsed.indices.contains(index) && result.gasUsed[index] > 0 {
+ var line = "\(cylinder.gas.name): \(fixed(result.gasUsed[index], 0)) L"
+ if let start = cylinder.startBar, let left = cylinder.pressure(afterUsing: result.gasUsed[index]) {
+ line += " (\(units.pressure(start)) → \(units.pressure(max(0, left))))"
+ }
+ lines.append(line)
+ }
+ lines.append(String(localized: "CNS \(fixed(result.cns * 100, 0)) %, OTU \(fixed(result.otu, 0))"))
+ return lines.joined(separator: "\n")
+ }
+}
diff --git a/Packages/DiveKit/Sources/DivePlanner/Core.swift b/Packages/DiveKit/Sources/DivePlanner/Core.swift
@@ -39,6 +39,12 @@ struct DecoState: Sendable {
static let waterVapourSchreiner = 0.0493
static let conservatismLevels = [1.0, 1.05, 1.12, 1.22, 1.35]
+ private static func factors(_ halfLives: [Double], seconds: Double) -> [Double] {
+ halfLives.map { 1 - exp(-seconds * 1.155245301e-02 / $0) }
+ }
+ static let n2Factor1 = factors(n2HalfLife, seconds: 1), n2Factor2 = factors(n2HalfLife, seconds: 2)
+ static let heFactor1 = factors(heHalfLife, seconds: 1), heFactor2 = factors(heHalfLife, seconds: 2)
+
// VPM-B constants.
static let critRadiusN2 = 0.55, critRadiusHe = 0.45
static let critVolumeLambda = 199.58
@@ -153,10 +159,19 @@ struct DecoState: Sendable {
/// `add_segment`.
mutating func addSegment(pressure: Double, gas: CoreGas, seconds: Int, setpoint: Int, mode: CoreMode) {
let inspired = pressures(ambient: pressure - wv, gas: gas, setpoint: Double(setpoint) / 1000, mode: mode)
- let time = Double(seconds)
- for index in 0..<16 {
- n2[index] += (inspired.n2 - n2[index]) * (1 - exp(-time * 1.155245301e-02 / Self.n2HalfLife[index]))
- he[index] += (inspired.he - he[index]) * (1 - exp(-time * 1.155245301e-02 / Self.heHalfLife[index]))
+ // One and two seconds are what the planner asks for millions of times: their factors are kept ready.
+ if seconds == 1 || seconds == 2 {
+ let n2Factors = seconds == 1 ? Self.n2Factor1 : Self.n2Factor2, heFactors = seconds == 1 ? Self.heFactor1 : Self.heFactor2
+ for index in 0..<16 {
+ n2[index] += (inspired.n2 - n2[index]) * n2Factors[index]
+ he[index] += (inspired.he - he[index]) * heFactors[index]
+ }
+ } else {
+ let time = Double(seconds)
+ for index in 0..<16 {
+ n2[index] += (inspired.n2 - n2[index]) * (1 - exp(-time * 1.155245301e-02 / Self.n2HalfLife[index]))
+ he[index] += (inspired.he - he[index]) * (1 - exp(-time * 1.155245301e-02 / Self.heHalfLife[index]))
+ }
}
if vpmb { calcCrushingPressure(pressure) }
}
diff --git a/Packages/DiveKit/Sources/DivePlanner/Gas.swift b/Packages/DiveKit/Sources/DivePlanner/Gas.swift
@@ -40,7 +40,7 @@ public struct BreathingGas: Codable, Sendable, Hashable {
public static let air = BreathingGas(o2: 0.21)
public static let oxygen = BreathingGas(o2: 1)
/// Fraction of nitrogen in air, as Subsurface takes it.
- static let nitrogenInAir = 0.7902
+ static let nitrogenInAir = 0.79
public var n2: Double { max(0, 1 - o2 - he) }
public var o2Percent: Int { Int((o2 * 100).rounded()) }
diff --git a/Packages/DiveKit/Sources/DivePlanner/Planner.swift b/Packages/DiveKit/Sources/DivePlanner/Planner.swift
@@ -8,7 +8,8 @@ public struct PlanCylinder: Codable, Sendable, Equatable, Identifiable {
/// Water capacity in litres and filling pressure in bar; nil when only the gas matters.
public var volumeLiters: Double?
public var startBar: Double?
- /// A decompression gas is switched to on the way up, from `switchDepth` (nil: its depth at 1.6 bar of oxygen).
+ /// A decompression (or bailout) gas is switched to on the way up, from `switchDepth` (nil: its depth at the
+ /// decompression limit on the partial pressure of oxygen).
public var isDeco = false
public var switchDepth: Double?
@@ -20,10 +21,46 @@ public struct PlanCylinder: Codable, Sendable, Equatable, Identifiable {
self.switchDepth = switchDepth
}
- /// Litres of gas at the surface (ideal gas, which flatters fills above 200 bar by a few percent).
+ /// Litres of gas at the surface, compressibility taken into account.
public var availableLiters: Double? {
guard let volumeLiters, let startBar else { return nil }
- return volumeLiters * startBar
+ return RealGas.liters(gas, volumeLiters: volumeLiters, bar: startBar)
+ }
+
+ /// Pressure left after breathing `liters` (at the surface) from a full cylinder; negative when it does not hold that much.
+ public func pressure(afterUsing liters: Double) -> Double? {
+ guard let volumeLiters, volumeLiters > 0, let available = availableLiters else { return nil }
+ let left = available - liters
+ return left >= 0 ? RealGas.pressure(gas, liters: left, volumeLiters: volumeLiters) : left / volumeLiters
+ }
+}
+
+/// Compressibility of breathing gases (Subsurface's `core/gas-model.cpp`: cubic virial fit for O2, N2 and He at 300 K).
+public enum RealGas {
+ private static func virial(_ coefficients: [Double], _ x: Double) -> Double {
+ x * coefficients[0] + x * x * coefficients[1] + x * x * x * coefficients[2]
+ }
+
+ /// Z = pV / nRT at a pressure in bar.
+ public static func compressibility(_ gas: BreathingGas, bar: Double) -> Double {
+ let pressure = min(max(bar, 0), 500)
+ let o2 = (gas.o2 * 1000).rounded(), he = (gas.he * 1000).rounded()
+ let z = virial([-7.18092073703e-04, 2.81852572808e-06, -1.50290620492e-09], pressure) * o2
+ + virial([4.87320026468e-04, -8.83632921053e-08, 5.33304543646e-11], pressure) * he
+ + virial([-2.19260353292e-04, 2.92844845532e-06, -2.07613482075e-09], pressure) * (1000 - o2 - he)
+ return z * 0.001 + 1
+ }
+
+ /// Litres at the surface held by a cylinder at a pressure.
+ public static func liters(_ gas: BreathingGas, volumeLiters: Double, bar: Double) -> Double {
+ volumeLiters * bar / compressibility(gas, bar: bar) * compressibility(gas, bar: 1)
+ }
+
+ /// Pressure of `liters` (at the surface) put into a cylinder (`isothermal_pressure`).
+ public static func pressure(_ gas: BreathingGas, liters: Double, volumeLiters: Double) -> Double {
+ guard volumeLiters > 0 else { return 0 }
+ let ideal = liters / volumeLiters / compressibility(gas, bar: 1)
+ return ideal * compressibility(gas, bar: ideal)
}
}
@@ -33,7 +70,7 @@ public struct PlanLevel: Codable, Sendable, Equatable, Identifiable {
public var depth: Double
/// Minutes from leaving the previous depth (or the surface): the way there counts, as in dive tables.
public var minutes: Double
- /// Index of the cylinder breathed, in the plan's list.
+ /// Index of the cylinder breathed (the diluent, on a closed circuit), in the plan's list.
public var cylinder = 0
public init(depth: Double, minutes: Double, cylinder: Int = 0) {
@@ -43,19 +80,44 @@ public struct PlanLevel: Codable, Sendable, Equatable, Identifiable {
}
}
+public enum DecoModel: String, Codable, Sendable, CaseIterable {
+ /// Bühlmann ZHL-16C with gradient factors.
+ case buhlmann
+ /// Varying permeability model with Boyle compensation.
+ case vpmb
+}
+
+public enum BreathingMode: String, Codable, Sendable, CaseIterable {
+ case openCircuit
+ /// Closed circuit rebreather, at a constant partial pressure of oxygen (the setpoint).
+ case closedCircuit
+ /// Passive semi-closed rebreather.
+ case semiClosed
+}
+
public struct PlanSettings: Codable, Sendable, Equatable {
+ public var model = DecoModel.buhlmann
/// Gradient factors, as fractions (0.40 and 0.85 for "40/85").
public var gfLow = 0.40
public var gfHigh = 0.85
+ /// VPM-B conservatism, 0 (nominal) to 4.
+ public var vpmbConservatism = 2
/// Metres per minute.
public var descentRate = 18.0
- public var ascentRate = 9.0
- /// Ascent rate above 6 m.
+ /// Ascent rates by zone, as Subsurface has them: below 75 % of the average depth, from 75 % to 50 %, from
+ /// 50 % to 6 m, and above 6 m.
+ public var ascentRate75 = 9.0
+ public var ascentRate50 = 9.0
+ public var ascentRateStops = 9.0
public var ascentRateLast6m = 9.0
/// Last stop at 6 m instead of 3 m.
public var lastStopAt6m = false
/// Three minutes at 5 m on the way up of a dive without mandatory stops, deeper than 10 m.
public var safetyStop = true
+ /// A gas is only switched to where a stop is required anyway.
+ public var switchOnlyAtRequiredStops = false
+ /// Twelve minutes on oxygen, then six on a leaner gas, during long oxygen stops.
+ public var oxygenBreaks = false
/// Surface air consumption, in litres per minute: at the bottom, and during the ascent and the stops.
public var sacBottom = 20.0
public var sacDeco = 17.0
@@ -67,15 +129,38 @@ public struct PlanSettings: Codable, Sendable, Equatable {
/// Minimum gas: minutes to sort a problem out at the bottom, and factor on the consumption (two divers, stressed).
public var problemMinutes = 4.0
public var minimumGasFactor = 4.0
+ /// Pressure to keep in every cylinder, in bar.
+ public var reserveBar = 40.0
public var environment = DiveEnvironment.sea
public init() {}
+
+ /// Sets every ascent rate at once.
+ public mutating func setAscentRate(_ rate: Double, last6m: Double? = nil) {
+ ascentRate75 = rate
+ ascentRate50 = rate
+ ascentRateStops = rate
+ ascentRateLast6m = last6m ?? rate
+ }
+}
+
+public extension DiveEnvironment {
+ /// Altitude above sea level for the surface pressure, in metres (Subsurface's formula).
+ var altitude: Double {
+ get { log(1.013 / surfacePressure) * 7800 }
+ set { surfacePressure = 1.013 * exp(-newValue / 7800) }
+ }
}
public struct DivePlan: Codable, Sendable, Equatable {
public var levels: [PlanLevel]
public var cylinders: [PlanCylinder]
public var settings = PlanSettings()
+ public var mode = BreathingMode.openCircuit
+ /// Setpoint of a closed circuit, in bar.
+ public var setpoint = 1.3
+ /// A rebreather dive ends on open circuit: the deco gases are the bailout gases.
+ public var bailout = false
public init(levels: [PlanLevel], cylinders: [PlanCylinder], settings: PlanSettings = PlanSettings()) {
self.levels = levels
@@ -91,6 +176,8 @@ public struct PlanPoint: Sendable, Equatable {
public var depth: Double
/// Cylinder breathed from this point on.
public var cylinder: Int
+ /// False once the diver is off the loop of a rebreather.
+ public var onLoop = false
}
/// A stop on the way up: mandatory decompression stop, time taken by a gas switch, or safety stop.
@@ -115,6 +202,8 @@ public enum PlanWarning: Sendable, Equatable {
case density(cylinder: Int, depth: Double, gramsPerLiter: Double)
/// The plan uses more than the cylinder holds: litres needed, litres available.
case notEnoughGas(cylinder: Int, needed: Double, available: Double)
+ /// The cylinder ends under the reserve: bar left, bar to keep.
+ case underReserve(cylinder: Int, leftBar: Double, reserveBar: Double)
/// 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)
@@ -131,9 +220,10 @@ public struct PlanResult: Sendable, Equatable {
public var runtime = 0.0
public var ascentTime = 0.0
public var maxDepth = 0.0
- /// Litres of gas (at the surface) used per cylinder, same order as the plan's list.
+ /// Litres of gas (at the surface) used per cylinder, same order as the plan's list. On a closed circuit only
+ /// what is breathed off the loop is counted.
public var gasUsed: [Double] = []
- /// Minimum gas to keep in the bottom cylinder when leaving the bottom, in litres; nil without deco gas logic.
+ /// Minimum gas to keep in the bottom cylinder when leaving the bottom, in litres.
public var minimumGasLiters: Double?
public var bottomCylinder = 0
/// Share of the CNS clock (1 = 100 %) and pulmonary oxygen units.
@@ -141,259 +231,187 @@ public struct PlanResult: Sendable, Equatable {
public var otu = 0.0
/// Supersaturation on surfacing, as a share of the Bühlmann limit.
public var surfaceGF = 0.0
+ /// Ceiling when leaving the bottom, in metres.
+ public var firstCeiling = 0.0
public var warnings: [PlanWarning] = []
public init() {}
/// True when the ascent has mandatory decompression stops.
public var hasDecoStops: Bool { stops.contains { $0.kind == .deco } }
- public var decoStops: [PlanStop] { stops.filter { $0.kind != .safety } }
+}
+
+/// How the decompression changes around a plan: seconds of run time per metre deeper and per minute longer.
+public struct PlanVariations: Sendable, Equatable {
+ public var perMeter: Double
+ public var perMinute: Double
}
public enum DivePlanner {
- /// Depth step of the ascent simulation, as a duration (Subsurface's `base_timestep`).
- private static let step = 2.0
- private static let stopStep = 60.0
-
- private struct State {
- var tissues: Tissues
- var clock = 0.0
- var depth = 0.0
- var cylinder = 0
- var result = PlanResult()
+ // MARK: Conversion to the core
- mutating func mark() {
- let point = PlanPoint(time: clock, depth: depth, cylinder: cylinder)
- if let last = result.points.last, last.time == point.time, last.depth == point.depth {
- result.points[result.points.count - 1] = point
- } else {
- result.points.append(point)
- }
- }
+ private static func coreGas(_ gas: BreathingGas) -> CoreGas {
+ CoreGas(o2: Int((gas.o2 * 1000).rounded()), he: Int((gas.he * 1000).rounded()))
}
- /// Breathes the current cylinder for a while at a depth: tissues, gas used, oxygen exposure.
- private static func breathe(_ state: inout State, _ plan: DivePlan, seconds: Double, at depth: Double, sac: Double) {
- let settings = plan.settings, environment = settings.environment
- let pressure = environment.pressure(atDepth: depth)
- let gas = plan.cylinders[state.cylinder].gas
- state.tissues.load(pressure: pressure, gas: gas, seconds: seconds)
- _ = state.tissues.toleratedPressure(surfacePressure: environment.surfacePressure, gfLow: settings.gfLow, gfHigh: settings.gfHigh)
- state.result.gasUsed[state.cylinder] += sac * pressure * seconds / 60
- state.result.cns += OxygenExposure.cns(ppO2: pressure * gas.o2, seconds: seconds)
- state.result.otu += OxygenExposure.otu(ppO2: pressure * gas.o2, seconds: seconds)
+ private static func coreEnvironment(_ environment: DiveEnvironment) -> CoreEnvironment {
+ CoreEnvironment(surfaceMbar: Int((environment.surfacePressure * 1000).rounded()), salinity: Int((environment.waterDensity * 10_000).rounded()))
}
- /// Plans the ascent of a dive: stops, run time, gas, oxygen exposure and what to worry about.
- public static func plan(_ plan: DivePlan) -> PlanResult {
- let settings = plan.settings, environment = settings.environment
- var state = State(tissues: Tissues(surfacePressure: environment.surfacePressure))
- state.result.gasUsed = [Double](repeating: 0, count: plan.cylinders.count)
- guard !plan.cylinders.isEmpty, !plan.levels.isEmpty,
- plan.levels.allSatisfy({ plan.cylinders.indices.contains($0.cylinder) }) else {
- state.result.warnings = [.unknownCylinder]
- return state.result
- }
+ /// Millimetres per second, truncated the way Subsurface stores its rates.
+ private static func rate(_ metersPerMinute: Double) -> Int { max(1, Int(metersPerMinute * 1000) / 60) }
+
+ private static func model(_ plan: DivePlan) -> DecoState {
+ var model = DecoState()
+ model.vpmb = plan.settings.model == .vpmb
+ model.conservatism = plan.settings.vpmbConservatism
+ model.gfLow = plan.settings.gfLow
+ model.gfHigh = plan.settings.gfHigh
+ model.environment = coreEnvironment(plan.settings.environment)
+ model.bottomSac = plan.settings.sacBottom * 1000
+ return model
+ }
- // The part the diver decides: each level is reached at the descent or ascent rate, then held.
- state.cylinder = plan.levels[0].cylinder
- state.mark()
- for level in plan.levels {
- state.cylinder = level.cylinder
- state.mark()
- let rate = (level.depth >= state.depth ? settings.descentRate : settings.ascentRate) / 60
- var left = max(0, level.minutes * 60)
- while abs(level.depth - state.depth) > 1e-9 {
- let seconds = min(1, abs(level.depth - state.depth) / rate)
- breathe(&state, plan, seconds: seconds, at: state.depth, sac: settings.sacBottom)
- state.depth += (level.depth > state.depth ? 1 : -1) * rate * seconds
- if abs(level.depth - state.depth) < 1e-6 { state.depth = level.depth }
- state.clock += seconds
- left -= seconds
- }
- state.mark()
- while left > 0 {
- let seconds = min(60, left)
- breathe(&state, plan, seconds: seconds, at: state.depth, sac: settings.sacBottom)
- state.clock += seconds
- left -= seconds
- }
- state.mark()
- state.result.maxDepth = max(state.result.maxDepth, level.depth)
- }
- let bottomTime = state.clock
- let bottomDepth = state.depth
- let bottomCylinder = state.cylinder
- state.result.bottomCylinder = bottomCylinder
- let usedAtBottom = state.result.gasUsed[bottomCylinder]
-
- ascend(&state, plan: plan)
-
- state.result.runtime = state.clock
- state.result.ascentTime = state.clock - bottomTime
- state.result.surfaceGF = state.tissues.surfaceGradientFactor(surfacePressure: environment.surfacePressure)
-
- // Minimum gas: enough, from the end of the bottom time, to sort a problem out and bring two divers up to
- // the first gas switch (or the surface), at a stressed consumption.
- let ascentFromBottomCylinder = state.result.gasUsed[bottomCylinder] - usedAtBottom
- let minimum = settings.minimumGasFactor * (settings.problemMinutes * settings.sacBottom * environment.pressure(atDepth: bottomDepth)
- + ascentFromBottomCylinder)
- state.result.minimumGasLiters = minimum
- state.result.warnings = warnings(for: plan, result: state.result, usedAtBottom: usedAtBottom, minimum: minimum)
- return state.result
+ private static func prefs(_ plan: DivePlan) -> CorePrefs {
+ let settings = plan.settings
+ var prefs = CorePrefs()
+ prefs.ascRate75 = rate(settings.ascentRate75)
+ prefs.ascRate50 = rate(settings.ascentRate50)
+ prefs.ascRateStops = rate(settings.ascentRateStops)
+ prefs.ascRateLast6m = rate(settings.ascentRateLast6m)
+ prefs.lastStopAt6m = settings.lastStopAt6m
+ prefs.minSwitchDuration = Int(settings.gasSwitchSeconds.rounded())
+ prefs.switchAtRequiredStop = settings.switchOnlyAtRequiredStops
+ prefs.oxygenBreaks = settings.oxygenBreaks
+ prefs.bailout = plan.mode != .openCircuit && plan.bailout
+ prefs.problemSolvingMinutes = Int(settings.problemMinutes.rounded())
+ prefs.bottomSac = settings.sacBottom * 1000
+ prefs.decoSac = settings.sacDeco * 1000
+ return prefs
}
- /// The gases that can be switched to on the way up, deepest first.
- private static func gasChanges(_ plan: DivePlan) -> [(depth: Double, cylinder: Int)] {
- plan.cylinders.enumerated().compactMap { index, cylinder -> (depth: Double, cylinder: Int)? in
- guard cylinder.isDeco else { return nil }
- let depth = cylinder.switchDepth ?? cylinder.gas.switchDepth(ppO2: plan.settings.ppO2Deco, in: plan.settings.environment)
- return depth > 0 ? (depth, index) : nil
- }.sorted { $0.depth > $1.depth }
+ /// Depth from which a decompression gas is breathed, in metres.
+ public static func switchDepth(of cylinder: PlanCylinder, settings: PlanSettings) -> Double {
+ cylinder.switchDepth ?? cylinder.gas.switchDepth(ppO2: settings.ppO2Deco, in: settings.environment)
}
- private static func ascentRate(at depth: Double, _ settings: PlanSettings) -> Double {
- (depth > 6 ? settings.ascentRate : settings.ascentRateLast6m) / 60
+ private static func coreCylinders(_ plan: DivePlan) -> [CoreCylinder] {
+ plan.cylinders.map { cylinder 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 })
+ }
}
- /// Whether the diver can go from `depth` up to `target` without crossing the ceiling, after waiting `wait`
- /// seconds first. The tissues are not changed.
- private static func canAscend(_ tissues: Tissues, wait: Double, from depth: Double, to target: Double, gas: BreathingGas, settings: PlanSettings) -> Bool {
- let environment = settings.environment
- var trial = tissues
- if wait > 0 { trial.load(pressure: environment.pressure(atDepth: depth), gas: gas, seconds: wait) }
- var current = depth
- while current > target + 1e-9 {
- let rise = min(ascentRate(at: current, settings) * step, current)
- trial.load(pressure: environment.pressure(atDepth: current), gas: gas, seconds: step)
- let tolerated = trial.toleratedPressure(surfacePressure: environment.surfacePressure, gfLow: settings.gfLow, gfHigh: settings.gfHigh)
- if environment.depth(atPressure: tolerated) > current - rise + 1e-9 { return false }
- current -= rise
+ /// The levels as legs: the way to each depth at the descent or ascent rate, then the rest of its time there.
+ private static func waypoints(_ plan: DivePlan) -> [CoreWaypoint] {
+ let mode: CoreMode = plan.mode == .closedCircuit ? .closedCircuit : (plan.mode == .semiClosed ? .semiClosed : .openCircuit)
+ let setpoint = plan.mode == .closedCircuit ? Int((plan.setpoint * 1000).rounded()) : 0
+ var out = [CoreWaypoint]()
+ var depth = 0
+ for level in plan.levels {
+ let target = Int((level.depth * 1000).rounded())
+ let total = Int((level.minutes * 60).rounded())
+ let speed = target >= depth ? plan.settings.descentRate : plan.settings.ascentRate75
+ let travel = abs(target - depth) * 60 / max(1, Int(speed * 1000))
+ if travel > 0 { out.append(CoreWaypoint(seconds: travel, depth: target, cylinder: level.cylinder, setpoint: setpoint, mode: mode)) }
+ if total > travel { out.append(CoreWaypoint(seconds: total - travel, depth: target, cylinder: level.cylinder, setpoint: setpoint, mode: mode)) }
+ depth = target
}
- return true
+ return out
}
- private static func ascend(_ state: inout State, plan: DivePlan) {
+ // 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 {
+ var result = PlanResult()
+ result.gasUsed = [Double](repeating: 0, count: plan.cylinders.count)
+ let legs = waypoints(plan)
+ guard !plan.cylinders.isEmpty, !legs.isEmpty, plan.levels.allSatisfy({ plan.cylinders.indices.contains($0.cylinder) }) else {
+ result.warnings = [.unknownCylinder]
+ return result
+ }
let settings = plan.settings
- var changes = gasChanges(plan)
- // A deco gas that can already be breathed at the bottom is taken straight away (the richest such gas).
- if let usable = changes.last(where: { $0.depth >= state.depth }), usable.cylinder != state.cylinder {
- state.mark()
- state.cylinder = usable.cylinder
- state.mark()
+ let output = CorePlanner.plan(waypoints: legs, cylinders: coreCylinders(plan), prefs: prefs(plan), model: model(plan))
+
+ result.points = output.track.map {
+ PlanPoint(time: Double($0.time), depth: Double($0.depth) / 1000, cylinder: $0.cylinder, onLoop: $0.mode != .openCircuit)
}
- changes.removeAll { $0.depth >= state.depth }
-
- // Where the diver may stop: every 3 m (the 3 m stop goes when the last stop is at 6 m) and the gas switches.
- var levels = Set(stride(from: settings.lastStopAt6m ? 6.0 : 3.0, to: state.depth, by: 3.0))
- for change in changes { levels.insert(change.depth) }
- var stops = levels.filter { $0 < state.depth - 1e-9 }.sorted(by: >) + [0.0]
- var justSwitched = false
- var decoStopsFound = false
- var guardCount = 0
-
- func stay(_ state: inout State, _ seconds: Double, kind: PlanStop.Kind) {
- breathe(&state, plan, seconds: seconds, at: state.depth, sac: settings.sacDeco)
- state.clock += seconds
- if var last = state.result.stops.last, last.depth == state.depth, last.cylinder == state.cylinder, last.kind == kind {
- last.seconds += seconds
- last.endTime = state.clock
- state.result.stops[state.result.stops.count - 1] = last
- } else {
- state.result.stops.append(PlanStop(depth: state.depth, seconds: seconds, cylinder: state.cylinder, kind: kind, endTime: state.clock))
- }
+ result.stops = output.stops.map {
+ PlanStop(depth: Double($0.depth) / 1000, seconds: Double($0.seconds), cylinder: $0.cylinder,
+ kind: $0.isGasSwitch ? .gasSwitch : .deco, endTime: Double($0.endTime))
}
-
- while !stops.isEmpty {
- let target = stops.removeFirst()
- // Up to the next possible stop.
- state.mark()
- while state.depth > target + 1e-9 {
- let rise = min(ascentRate(at: state.depth, settings) * step, state.depth - target)
- breathe(&state, plan, seconds: step, at: state.depth, sac: settings.sacDeco)
- state.clock += step
- state.depth -= rise
- if state.depth - target < 1e-9 { state.depth = target }
- justSwitched = false
- }
- guard state.depth > 0 else { break }
-
- if let change = changes.first, target <= change.depth + 1e-9 {
- changes.removeFirst()
- if change.cylinder != state.cylinder {
- state.mark()
- state.cylinder = change.cylinder
- state.mark()
- if !justSwitched, plan.cylinders[change.cylinder].gas.o2Percent < 100, settings.gasSwitchSeconds > 0 {
- stay(&state, settings.gasSwitchSeconds, kind: .gasSwitch)
- justSwitched = true
- }
- }
- }
-
- let next = stops.first ?? 0
- let gas = plan.cylinders[state.cylinder].gas
- if canAscend(state.tissues, wait: 0, from: state.depth, to: next, gas: gas, settings: settings) { continue }
-
- // A stop: it ends on a whole minute of run time, as soon as the way up to the next stop is clear.
- decoStopsFound = true
- state.mark()
- var end = (state.clock / stopStep).rounded(.down) * stopStep + stopStep
- while !canAscend(state.tissues, wait: end - state.clock, from: state.depth, to: next, gas: gas, settings: settings) {
- end += stopStep
- guardCount += 1
- if guardCount > 48 * 60 {
- state.result.warnings.append(.endless)
- state.mark()
- return
- }
- }
- stay(&state, end - state.clock, kind: .deco)
- justSwitched = false
- state.mark()
+ result.runtime = Double(output.runtime)
+ result.ascentTime = Double(output.runtime - output.bottomTime)
+ result.maxDepth = plan.levels.map(\.depth).max() ?? 0
+ result.gasUsed = output.gasUsed.map { $0 / 1000 }
+ result.bottomCylinder = output.bottomCylinder
+ result.cns = output.cns
+ result.otu = output.otu
+ result.firstCeiling = Double(output.firstCeilingDepth) / 1000
+ result.surfaceGF = surfaceGF(output.finalState)
+ if output.timedOut { result.warnings.append(.endless) }
+
+ if !result.hasDecoStops, settings.safetyStop, result.maxDepth >= 10, !output.timedOut {
+ insertSafetyStop(&result, plan: plan)
}
- state.depth = 0
- state.mark()
- if !decoStopsFound, settings.safetyStop, state.result.maxDepth >= 10 {
- insertSafetyStop(&state, plan: plan)
+ // 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 }
+ let usedAtBottom = (output.gasUsed[bottom] - output.decoGasUsed[bottom]) / 1000
+ result.warnings += warnings(for: plan, result: result, usedAtBottom: usedAtBottom, minimum: result.minimumGasLiters)
+ return result
+ }
+
+ private static func surfaceGF(_ state: DecoState) -> Double {
+ let surface = state.environment.surfaceBar
+ var highest = 0.0
+ for index in 0..<16 {
+ let total = state.n2[index] + state.he[index]
+ let a = (Tissues.n2A[index] * state.n2[index] + Tissues.heA[index] * state.he[index]) / total
+ let b = (Tissues.n2B[index] * state.n2[index] + Tissues.heB[index] * state.he[index]) / total
+ highest = max(highest, (total - surface) / (a + surface / b - surface))
}
+ return highest
}
/// Adds three minutes at 5 m to an ascent that had no mandatory stop: gas and oxygen for the stop are added,
/// the profile gets the plateau. (The tissues only off-gas more: nothing else changes.)
- private static func insertSafetyStop(_ state: inout State, plan: DivePlan) {
+ private static func insertSafetyStop(_ result: inout PlanResult, plan: DivePlan) {
let settings = plan.settings, environment = settings.environment
let stopDepth = 5.0, seconds = 180.0
- guard let index = state.result.points.lastIndex(where: { $0.depth > stopDepth }), index + 1 < state.result.points.count else { return }
- let before = state.result.points[index], after = state.result.points[index + 1]
+ guard let index = result.points.lastIndex(where: { $0.depth > stopDepth }), index + 1 < result.points.count else { return }
+ let before = result.points[index], after = result.points[index + 1]
guard before.depth > after.depth else { return }
- // Time at which the ascent crosses 5 m, between the two points around it.
let crossing = before.time + (after.time - before.time) * (before.depth - stopDepth) / (before.depth - after.depth)
- let cylinder = before.cylinder
- for later in (index + 1)..<state.result.points.count { state.result.points[later].time += seconds }
- state.result.points.insert(contentsOf: [PlanPoint(time: crossing, depth: stopDepth, cylinder: cylinder),
- PlanPoint(time: crossing + seconds, depth: stopDepth, cylinder: cylinder)], at: index + 1)
+ for later in (index + 1)..<result.points.count { result.points[later].time += seconds }
+ result.points.insert(contentsOf: [PlanPoint(time: crossing, depth: stopDepth, cylinder: before.cylinder, onLoop: before.onLoop),
+ PlanPoint(time: crossing + seconds, depth: stopDepth, cylinder: before.cylinder, onLoop: before.onLoop)], at: index + 1)
let pressure = environment.pressure(atDepth: stopDepth)
- let gas = plan.cylinders[cylinder].gas
- state.tissues.load(pressure: pressure, gas: gas, seconds: seconds)
- state.result.gasUsed[cylinder] += settings.sacDeco * pressure * seconds / 60
- state.result.cns += OxygenExposure.cns(ppO2: pressure * gas.o2, seconds: seconds)
- state.result.otu += OxygenExposure.otu(ppO2: pressure * gas.o2, seconds: seconds)
- state.result.stops.append(PlanStop(depth: stopDepth, seconds: seconds, cylinder: cylinder, kind: .safety, endTime: crossing + seconds))
- state.clock += seconds
+ let gas = plan.cylinders[before.cylinder].gas
+ if !before.onLoop {
+ result.gasUsed[before.cylinder] += settings.sacDeco * pressure * seconds / 60
+ result.cns += OxygenExposure.cns(ppO2: pressure * gas.o2, seconds: seconds)
+ result.otu += OxygenExposure.otu(ppO2: pressure * gas.o2, seconds: seconds)
+ }
+ result.stops.append(PlanStop(depth: stopDepth, seconds: seconds, cylinder: before.cylinder, kind: .safety, endTime: crossing + seconds))
+ result.runtime += seconds
+ result.ascentTime += seconds
}
- private static func warnings(for plan: DivePlan, result: PlanResult, usedAtBottom: Double, minimum: Double) -> [PlanWarning] {
+ private static func warnings(for plan: DivePlan, result: PlanResult, usedAtBottom: Double, minimum: Double?) -> [PlanWarning] {
let settings = plan.settings, environment = settings.environment
- var found = result.warnings
- // Each cylinder at the deepest and at the shallowest point where it is breathed.
+ var found = [PlanWarning]()
+ // Each cylinder at the deepest and at the shallowest point where it is breathed on open circuit.
var deepest = [Int: Double](), shallowest = [Int: Double]()
- for (index, point) in result.points.enumerated() {
+ for (index, point) in result.points.enumerated() where !point.onLoop {
let until = index + 1 < result.points.count ? result.points[index + 1].depth : point.depth
for depth in [point.depth, until] {
deepest[point.cylinder] = max(deepest[point.cylinder] ?? 0, depth)
- // The first metres of the descent and the last of the ascent are left out for the hypoxia check.
if depth > 0 { shallowest[point.cylinder] = min(shallowest[point.cylinder] ?? .infinity, depth) }
}
}
@@ -407,70 +425,86 @@ public enum DivePlanner {
let density = gas.density(atDepth: depth, in: environment)
if density > 5.2 { found.append(.density(cylinder: cylinder, depth: depth, gramsPerLiter: density)) }
}
- // A hypoxic bottom gas is a problem from the surface down to the depth where it becomes breathable.
- for cylinder in Set(result.points.map(\.cylinder)).sorted() {
+ // On the loop the setpoint decides the oxygen; the diluent still has to be narcotically sane at the bottom.
+ if plan.mode == .closedCircuit {
+ if plan.setpoint > settings.ppO2Bottom + 0.005, let first = plan.levels.first {
+ found.append(.oxygenTooHigh(cylinder: first.cylinder, depth: result.maxDepth, ppO2: plan.setpoint))
+ }
+ }
+ for cylinder in Set(result.points.filter { !$0.onLoop }.map(\.cylinder)).sorted() {
let gas = plan.cylinders[cylinder].gas
- let startsAtSurface = result.points.first?.cylinder == cylinder
+ let startsAtSurface = result.points.first?.cylinder == cylinder && result.points.first?.onLoop == false
let depth = startsAtSurface ? 0 : (shallowest[cylinder] ?? 0)
let ppO2 = gas.ppO2(atDepth: depth, in: environment)
if ppO2 < 0.16 { found.append(.oxygenTooLow(cylinder: cylinder, depth: depth, ppO2: ppO2)) }
}
- for (cylinder, used) in result.gasUsed.enumerated() {
- guard let available = plan.cylinders[cylinder].availableLiters, used > 0 else { continue }
- if used > available { found.append(.notEnoughGas(cylinder: cylinder, needed: used, available: available)) }
+ for (cylinder, used) in result.gasUsed.enumerated() where used > 0 {
+ guard let available = plan.cylinders[cylinder].availableLiters else { continue }
+ if used > available {
+ found.append(.notEnoughGas(cylinder: cylinder, needed: used, available: available))
+ } else if let left = plan.cylinders[cylinder].pressure(afterUsing: used), left < settings.reserveBar {
+ found.append(.underReserve(cylinder: cylinder, leftBar: left, reserveBar: settings.reserveBar))
+ }
}
let bottom = result.bottomCylinder
- if let available = plan.cylinders[bottom].availableLiters, let volume = plan.cylinders[bottom].volumeLiters, volume > 0 {
- let left = available - usedAtBottom
- if left < minimum, usedAtBottom <= available {
- found.append(.underMinimumGas(cylinder: bottom, leftBar: left / volume, minimumBar: minimum / volume))
- }
+ if let minimum, let available = plan.cylinders[bottom].availableLiters, let volume = plan.cylinders[bottom].volumeLiters, volume > 0,
+ usedAtBottom <= available, available - usedAtBottom < minimum {
+ found.append(.underMinimumGas(cylinder: bottom,
+ leftBar: RealGas.pressure(plan.cylinders[bottom].gas, liters: available - usedAtBottom, volumeLiters: volume),
+ minimumBar: RealGas.pressure(plan.cylinders[bottom].gas, liters: minimum, volumeLiters: volume)))
}
if result.cns > 0.8 { found.append(.cnsHigh(percent: result.cns * 100)) }
return found
}
+ /// How much the run time moves for a metre deeper and for a minute longer at the last level (central
+ /// 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 }
+ func runtime(depth: Double, minutes: Double) -> Double {
+ var changed = plan
+ changed.levels[last].depth += depth
+ changed.levels[last].minutes += minutes
+ changed.settings.safetyStop = false
+ return DivePlanner.plan(changed).runtime
+ }
+ return PlanVariations(perMeter: (runtime(depth: 1, minutes: 0) - runtime(depth: -1, minutes: 0)) / 2,
+ perMinute: (runtime(depth: 0, minutes: 1) - runtime(depth: 0, minutes: -1)) / 2 - 60)
+ }
+
// MARK: Quick answers
/// How long the diver can stay at a depth and still go straight up, in minutes from leaving the surface (the
/// descent counts); nil when there is no limit within `ceiling` minutes.
public static func noStopLimit(depth: Double, gas: BreathingGas, settings: PlanSettings = PlanSettings(), ceiling: Int = 300) -> Int? {
- let environment = settings.environment
- var tissues = Tissues(surfacePressure: environment.surfacePressure)
- // Descent, second by second.
- var current = 0.0, clock = 0.0
- let rate = settings.descentRate / 60
- while current < depth - 1e-9 {
- let seconds = min(1, (depth - current) / rate)
- tissues.load(pressure: environment.pressure(atDepth: current), gas: gas, seconds: seconds)
- current += rate * seconds
- clock += seconds
+ var plan = DivePlan(levels: [], cylinders: [PlanCylinder(gas: gas)], settings: settings)
+ plan.settings.safetyStop = false
+ // 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))]
+ return !DivePlanner.plan(plan).hasDecoStops
}
- let pressure = environment.pressure(atDepth: depth)
- // To the end of the current minute, then minute by minute.
- var minutes = Int((clock / 60).rounded(.up))
- tissues.load(pressure: pressure, gas: gas, seconds: Double(minutes) * 60 - clock)
- _ = tissues.toleratedPressure(surfacePressure: environment.surfacePressure, gfLow: settings.gfLow, gfHigh: settings.gfHigh)
- guard canAscend(tissues, wait: 0, from: depth, to: 0, gas: gas, settings: settings) else { return max(0, minutes - 1) }
- while minutes < ceiling {
- tissues.load(pressure: pressure, gas: gas, seconds: 60)
- _ = tissues.toleratedPressure(surfacePressure: environment.surfacePressure, gfLow: settings.gfLow, gfHigh: settings.gfHigh)
- if !canAscend(tissues, wait: 0, from: depth, to: 0, gas: gas, settings: settings) { return minutes }
- minutes += 1
+ let descent = Int((depth / max(settings.descentRate, 1)).rounded(.up))
+ guard free(max(descent, 1)) else { return max(0, descent - 1) }
+ guard !free(ceiling) else { return nil }
+ var low = max(descent, 1), high = ceiling
+ while high - low > 1 {
+ let middle = (low + high) / 2
+ if free(middle) { low = middle } else { high = middle }
}
- return nil
+ return low
}
/// How long a cylinder lasts at a depth, in minutes from leaving the surface, keeping `reserveBar` and the gas
/// for a direct ascent with a safety stop.
- public static func gasLimit(depth: Double, volumeLiters: Double, startBar: Double, reserveBar: Double = 50,
+ public static func gasLimit(depth: Double, gas: BreathingGas = .air, volumeLiters: Double, startBar: Double, reserveBar: Double = 50,
settings: PlanSettings = PlanSettings()) -> Int {
let environment = settings.environment
- let usable = volumeLiters * max(0, startBar - reserveBar)
+ let usable = RealGas.liters(gas, volumeLiters: volumeLiters, bar: startBar) - RealGas.liters(gas, volumeLiters: volumeLiters, bar: min(reserveBar, startBar))
// Descent and ascent at the mean pressure, three minutes at 5 m.
let mean = environment.pressure(atDepth: depth / 2)
let descentMinutes = depth / settings.descentRate
- let ascentMinutes = depth / settings.ascentRate
+ let ascentMinutes = depth / settings.ascentRateStops
let travel = settings.sacBottom * mean * descentMinutes + settings.sacDeco * mean * ascentMinutes
+ (settings.safetyStop && depth >= 10 ? settings.sacDeco * environment.pressure(atDepth: 5) * 3 : 0)
let perMinute = settings.sacBottom * environment.pressure(atDepth: depth)
diff --git a/Packages/DiveKit/Sources/DivePlanner/Tissues.swift b/Packages/DiveKit/Sources/DivePlanner/Tissues.swift
@@ -1,10 +1,8 @@
// SPDX-License-Identifier: GPL-2.0-only
import Foundation
-/// Bühlmann ZHL-16C with gradient factors, nitrogen and helium. The coefficients, the water vapour pressure and
-/// the way the gradient factors are applied follow Subsurface (`core/deco.cpp`, GPL-2.0), so that a plan made here
-/// matches a plan made there.
-public struct Tissues: Sendable, Equatable {
+/// The Bühlmann ZHL-16C coefficients, for nitrogen and helium, as Subsurface has them (`core/deco.cpp`, GPL-2.0).
+enum Tissues {
static let count = 16
static let n2A: [Double] = [1.1696, 1.0, 0.8618, 0.7562, 0.62, 0.5043, 0.441, 0.4,
0.375, 0.35, 0.3295, 0.3065, 0.2835, 0.261, 0.248, 0.2327]
@@ -18,75 +16,4 @@ public struct Tissues: Sendable, Equatable {
0.8757, 0.8903, 0.8997, 0.9073, 0.9122, 0.9171, 0.9217, 0.9267]
static let heHalfLife: [Double] = [1.88, 3.02, 4.72, 6.99, 10.21, 14.48, 20.53, 29.11,
41.20, 55.19, 70.69, 90.34, 115.29, 147.42, 188.24, 240.03]
- /// Water vapour pressure in the lungs, in bar (Bühlmann's value).
- static let waterVapour = 0.0627
-
- /// Inert gas pressures in each compartment, in bar.
- public private(set) var n2: [Double]
- public private(set) var he: [Double]
- /// Deepest ceiling (as a pressure) that the low gradient factor has asked for so far in this dive: the gradient
- /// factor goes from "low" there to "high" at the surface.
- public private(set) var gfLowPressure = 0.0
-
- /// Tissues of a diver who has been at the surface, breathing air, long enough to be in equilibrium.
- public init(surfacePressure: Double) {
- n2 = [Double](repeating: (surfacePressure - Self.waterVapour) * BreathingGas.nitrogenInAir, count: Self.count)
- he = [Double](repeating: 0, count: Self.count)
- }
-
- /// Breathes a gas for a while at a constant ambient pressure.
- public mutating func load(pressure: Double, gas: BreathingGas, seconds: Double) {
- guard seconds > 0 else { return }
- let inspiredN2 = (pressure - Self.waterVapour) * gas.n2
- let inspiredHe = (pressure - Self.waterVapour) * gas.he
- for index in 0..<Self.count {
- n2[index] += (inspiredN2 - n2[index]) * (1 - pow(2, -seconds / (Self.n2HalfLife[index] * 60)))
- he[index] += (inspiredHe - he[index]) * (1 - pow(2, -seconds / (Self.heHalfLife[index] * 60)))
- }
- }
-
- /// Lowest ambient pressure the tissues tolerate now, in bar (below the surface pressure: no ceiling). Also
- /// moves the reference of the low gradient factor when the tissues ask for a deeper first stop than before.
- public mutating func toleratedPressure(surfacePressure surface: Double, gfLow: Double, gfHigh: Double) -> Double {
- var a = [Double](repeating: 0, count: Self.count), b = a, saturation = a
- var lowestCeiling = 0.0
- for index in 0..<Self.count {
- let total = n2[index] + he[index]
- saturation[index] = total
- a[index] = (Self.n2A[index] * n2[index] + Self.heA[index] * he[index]) / total
- b[index] = (Self.n2B[index] * n2[index] + Self.heB[index] * he[index]) / total
- let ceiling = (b[index] * total - gfLow * a[index] * b[index]) / ((1 - b[index]) * gfLow + b[index])
- lowestCeiling = max(lowestCeiling, ceiling)
- }
- gfLowPressure = max(gfLowPressure, lowestCeiling)
- let low = gfLowPressure
- var tolerated = 0.0
- for index in 0..<Self.count {
- let atSurface = (surface / b[index] + a[index] - surface) * gfHigh + surface
- let atFirstStop = (low / b[index] + a[index] - low) * gfLow + low
- guard atSurface < atFirstStop else { continue }
- let value = (-a[index] * b[index] * (gfHigh * low - gfLow * surface)
- - (1 - b[index]) * (gfHigh - gfLow) * low * surface
- + b[index] * (low - surface) * saturation[index])
- / (-a[index] * b[index] * (gfHigh - gfLow)
- + (1 - b[index]) * (gfLow * low - gfHigh * surface)
- + b[index] * (low - surface))
- tolerated = max(tolerated, value)
- }
- return tolerated
- }
-
- /// Highest supersaturation among the compartments if the diver were at the surface now, as a share of the
- /// Bühlmann limit (1 = on the limit): what dive computers show as "surface GF".
- public func surfaceGradientFactor(surfacePressure surface: Double) -> Double {
- var highest = 0.0
- for index in 0..<Self.count {
- let total = n2[index] + he[index]
- let a = (Self.n2A[index] * n2[index] + Self.heA[index] * he[index]) / total
- let b = (Self.n2B[index] * n2[index] + Self.heB[index] * he[index]) / total
- let limit = a + surface / b
- highest = max(highest, (total - surface) / (limit - surface))
- }
- return highest
- }
}
diff --git a/Packages/DiveKit/Tests/DivePlannerTests/DivePlannerTests.swift b/Packages/DiveKit/Tests/DivePlannerTests/DivePlannerTests.swift
@@ -11,8 +11,7 @@ final class DivePlannerTests: XCTestCase {
settings.gfLow = 1
settings.gfHigh = 1
settings.descentRate = 23
- settings.ascentRate = 9.144
- settings.ascentRateLast6m = 3.048
+ settings.setAscentRate(9.144, last6m: 3.048)
settings.lastStopAt6m = true
settings.safetyStop = false
let plan = DivePlan(levels: [PlanLevel(depth: 79, minutes: 30)],
@@ -24,8 +23,9 @@ final class DivePlannerTests: XCTestCase {
print("BENCHMARK runtime \(result.runtime / 60) min, stops:",
result.stops.map { "\(Int($0.depth)) m \(Int($0.seconds / 60))' \(plan.cylinders[$0.cylinder].gas.name)" }.joined(separator: ", "),
"min gas \((result.minimumGasLiters ?? 0) / 36) bar, gas", result.gasUsed.map { Int($0) }, "CNS \(result.cns) OTU \(result.otu)")
- XCTAssertEqual(result.runtime, 109 * 60, accuracy: 109 * 60 * 0.01 + 60)
- XCTAssertEqual((result.minimumGasLiters ?? 0) / 36, 148, accuracy: 4)
+ XCTAssertEqual(result.runtime, 109 * 60)
+ // Subsurface rounds this plan's minimum gas to 148 bar; one bar more here.
+ XCTAssertEqual(RealGas.pressure(plan.cylinders[0].gas, liters: result.minimumGasLiters ?? 0, volumeLiters: 36), 148, accuracy: 1.5)
// The switches happen where Subsurface makes them.
let switches = result.points.enumerated().compactMap { index, point -> (Double, Int)? in
index > 0 && result.points[index - 1].cylinder != point.cylinder ? (point.depth, point.cylinder) : nil
diff --git a/README.md b/README.md
@@ -55,8 +55,9 @@ The app is available in English and French.
per day for a week in `history`. The sign-in screen offers to restore it. Photos are not copied.
- Planning (its own tab), on top of the `DivePlanner` library:
- no-stop: how long at a depth on a gas with a cylinder (no-stop time, gas time, table of no-stop times);
- - decompression: levels, cylinders with nitrox, trimix and decompression gases, gradient factors, stops, run
- time, gas per cylinder, minimum gas, CNS and OTU, warnings, profile;
+ - decompression: levels, cylinders with nitrox, trimix and decompression gases, Bühlmann with gradient
+ factors or VPM-B, open circuit or rebreather (CCR, pSCR, bailout), stops, run time, gas per cylinder,
+ minimum gas, CNS and OTU, warnings, profile, plan variations, and saving the plan as a logbook dive;
- gas: maximum operating depth, equivalent narcotic and air depths, density, best mix, consumption.
- Creation of a Subsurface cloud account (email, password, code received by email).
- Demo logbook (a button on the sign-in screen, or the `-demo` launch option).
@@ -75,10 +76,14 @@ Not there yet: Subsurface XML import, dive planner.
- Importers for the Shearwater and Open Rémora formats.
- `Merge` holds the rules for dives recorded by several computers and merges them as text, so that the files
of the other computers stay byte-identical.
-- `Packages/DiveKit/Sources/DivePlanner`: gas formulas and a Bühlmann ZHL-16C planner with gradient factors
- (nitrogen and helium, open circuit, gas switches), with no dependency. The coefficients and the algorithm follow
- Subsurface's `core/deco.cpp` and `core/planner.cpp`; the tests reproduce its benchmark plan (79 m for 30 minutes
- on trimix 15/45 with EAN36 and oxygen: 109 minutes of run time).
+- `Packages/DiveKit/Sources/DivePlanner`: gas formulas and a decompression planner, with no dependency.
+ `Core.swift` is a port of Subsurface's `core/deco.cpp`, `core/planner.cpp`, `core/gas.cpp` and
+ `core/gas-model.cpp` that keeps their units and rounding (millimetres, whole seconds, millibars, two-second
+ ascent steps): Bühlmann ZHL-16C with gradient factors, VPM-B, open circuit, closed and semi-closed
+ rebreathers, bailout, oxygen breaks. `SubsurfaceVectorsTests` runs the plans of Subsurface's
+ `tests/testplan.cpp` (one Bühlmann, seven VPM-B, one closed circuit with bailout) and expects its known run
+ times to the second. Not ported: its recreational mode (the app has its own no-stop screen), setpoint
+ changes during a closed-circuit ascent, and repetitive dives.
- `Packages/DiveKit/Sources/CLibDiveComputer`: libdivecomputer, vendored unchanged (see its `README.md` for the
exact revision), built as a package target.
- `Packages/DiveKit/Sources/DiveComputerKit`: Swift on top of it. `Catalog` lists the models and matches one from
diff --git a/fastlane/Fastfile b/fastlane/Fastfile
@@ -76,9 +76,9 @@ platform :ios do
end
texts = {
"fr-CA" => ["Votre carnet de plongée sur iPhone : profils, modification hors ligne, ordinateur de plongée en Bluetooth, synchronisation facultative avec le nuage Subsurface, sauvegarde iCloud. Application indépendante de l'équipe de Subsurface.",
- "0.8 : Nouveau : onglet Planification. (1) Sans palier : pour une profondeur, un gaz et une bouteille, combien de temps on peut rester (temps sans palier, autonomie en gaz) et un tableau des temps sans palier. (2) Décompression : niveaux, bouteilles (nitrox, trimix, gaz de décompression), facteurs de gradient ; paliers, durée totale, gaz par bouteille, gaz minimum, oxygène (CNS, OTU), avertissements, profil. Calcul Bühlmann ZHL-16C comme le planificateur de Subsurface. (3) Gaz : profondeur maximale, profondeur narcotique, densité, meilleur mélange, consommation. Aide à la planification seulement : vérifier un plan avec un autre outil."],
+ "0.9 : Planification complétée d'après le planificateur de Subsurface, et validée contre ses propres plans de test (mêmes durées à la seconde). Nouveau : modèle VPM-B avec conservatisme ; recycleur fermé (point de consigne) et semi-fermé, avec remontée de secours en circuit ouvert ; vitesses de remontée par zone, altitude, changement de gaz seulement aux paliers requis, pauses pendant les paliers à l'oxygène, réserve par bouteille, variations du plan ; enregistrement du plan comme plongée du carnet ; onglet Gaz : tableau par pression d'oxygène, profondeur narcotique réglable. Aide à la planification seulement."],
"en-CA" => ["Your dive log on iPhone: profiles, offline editing, dive computer over Bluetooth, optional sync with Subsurface cloud storage, iCloud backup. Independent from the Subsurface team.",
- "0.8: New: Planning tab. (1) No-stop: for a depth, a gas and a cylinder, how long you can stay (no-stop time, gas time) and a table of no-stop times. (2) Decompression: levels, cylinders (nitrox, trimix, decompression gases), gradient factors; stops, run time, gas per cylinder, minimum gas, oxygen (CNS, OTU), warnings, profile. Buhlmann ZHL-16C computed like the Subsurface planner. (3) Gas: maximum depth, narcotic depth, density, best mix, consumption. A planning aid only: check a plan against another tool."],
+ "0.9: Planning completed after the Subsurface planner and validated against its own test plans (same run times to the second). New: VPM-B model with conservatism; closed circuit (setpoint) and semi-closed rebreathers, with open-circuit bailout; ascent rates by zone, altitude, gas switches only at required stops, breaks during oxygen stops, reserve per cylinder, plan variations; saving the plan as a dive of the logbook; Gas tab: table by oxygen pressure, adjustable narcotic depth. A planning aid only."],
}
_, locs = asc(:get, "/v1/apps/#{app.id}/betaAppLocalizations")
texts.each do |locale, (description, _)|
diff --git a/project.yml b/project.yml
@@ -13,7 +13,7 @@ settings:
base:
DEVELOPMENT_TEAM: CM5RQKJH56
CODE_SIGN_STYLE: Automatic
- MARKETING_VERSION: "0.8"
+ MARKETING_VERSION: "0.9"
CURRENT_PROJECT_VERSION: "1"
SWIFT_VERSION: "5.0"
targets: