commit 572fdedac2183998bdfbd3f1f0578c09c8b1363b
parent f2be47b2ca6dc67b1c3de7fe8c2533d8dd525236
Author: Jean Schurger <jean@schurger.org>
Date: Sun, 15 Nov 2026 21:48:22 -0500
DivePlanner: faithful port of Subsurface's planner core, with VPM-B and rebreathers
Core.swift follows core/deco.cpp and core/planner.cpp line by line, in their
units (millimetres, whole seconds, millibars, two-second ascent steps):
Buhlmann with gradient factors, VPM-B with its conservatism levels and its
iteration on the decompression time, closed and semi-closed circuits,
open-circuit bailout, oxygen breaks, switching only at required stops, the
four ascent rate zones.
The ten plans of Subsurface's tests/testplan.cpp that do not depend on a
previous dive give its known run times to the second.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc
Diffstat:
2 files changed, 930 insertions(+), 0 deletions(-)
diff --git a/Packages/DiveKit/Sources/DivePlanner/Core.swift b/Packages/DiveKit/Sources/DivePlanner/Core.swift
@@ -0,0 +1,779 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+
+// A port of Subsurface's planner (`core/deco.cpp`, `core/planner.cpp`, `core/gas.cpp`, GPL-2.0) that keeps its
+// units and its rounding: depths in millimetres, times in whole seconds, pressures rounded to the millibar, ascent
+// by steps of two seconds. Staying that close is what lets the tests compare run times with Subsurface's own,
+// to the second. The public planner (`Planner.swift`) converts to and from these.
+
+enum CoreMode: Sendable { case openCircuit, closedCircuit, semiClosed }
+
+struct CoreEnvironment: Sendable {
+ var surfaceMbar = 1013
+ /// Grams per ten litres, as Subsurface stores it: 10300 for sea water, 10000 for fresh water.
+ var salinity = 10300
+
+ var specificWeight: Double { Double(salinity) * 0.981 / 100_000 }
+ var surfaceBar: Double { Double(surfaceMbar) / 1000 }
+ func mbar(_ depth: Int) -> Int { Int((Double(surfaceMbar) + Double(depth) * specificWeight).rounded(.toNearestOrEven)) }
+ func bar(_ depth: Int) -> Double { Double(mbar(depth)) / 1000 }
+ func atm(_ depth: Int) -> Double { Double(mbar(depth)) / 1013 }
+ /// Depth for a pressure above the surface's, in millimetres.
+ func depth(relativeMbar: Int) -> Int { Int((Double(relativeMbar) / specificWeight).rounded(.toNearestOrEven)) }
+}
+
+/// A gas in per mille, as Subsurface handles it.
+struct CoreGas: Sendable, Equatable {
+ var o2: Int
+ var he: Int
+ var n2: Int { 1000 - o2 - he }
+}
+
+struct CorePressures { var o2 = 0.0, n2 = 0.0, he = 0.0 }
+
+/// The state of the decompression model, and the model itself. A value: copying it is Subsurface's "cache".
+struct DecoState: Sendable {
+ static let n2A = Tissues.n2A, n2B = Tissues.n2B, n2HalfLife = Tissues.n2HalfLife
+ static let heA = Tissues.heA, heB = Tissues.heB, heHalfLife = Tissues.heHalfLife
+ static let waterVapour = 0.0627
+ static let waterVapourSchreiner = 0.0493
+ static let conservatismLevels = [1.0, 1.05, 1.12, 1.22, 1.35]
+
+ // VPM-B constants.
+ static let critRadiusN2 = 0.55, critRadiusHe = 0.45
+ static let critVolumeLambda = 199.58
+ static let gradientOfImperm = 8.30865
+ static let surfaceTensionGamma = 0.18137175
+ static let skinCompressionGammaC = 2.6040525
+ static let regenerationTime = 20160.0
+ static let otherGasesPressure = 0.1359888
+
+ // Configuration.
+ var vpmb = false
+ var conservatism = 0
+ var gfLow = 0.35, gfHigh = 0.75
+ var environment = CoreEnvironment()
+ /// Semi-closed rebreather: oxygen metabolised (ml/min), bottom consumption (ml/min), dump ratio (per mille).
+ var o2Consumption = 720.0, bottomSac = 20_000.0, pscrRatio = 100.0
+
+ // Tissues.
+ var n2 = [Double](repeating: 0, count: 16)
+ var he = [Double](repeating: 0, count: 16)
+ var a = [Double](repeating: 0, count: 16)
+ var b = [Double](repeating: 0, count: 16)
+ var gfLowPressure = 0.0
+ var guidingTissue = -1
+
+ // VPM-B.
+ var maxN2Crushing = [Double](repeating: 0, count: 16)
+ var maxHeCrushing = [Double](repeating: 0, count: 16)
+ var crushingOnsetTension = [Double](repeating: 0, count: 16)
+ var n2RegenRadius = [Double](repeating: 0, count: 16)
+ var heRegenRadius = [Double](repeating: 0, count: 16)
+ var initialN2Gradient = [Double](repeating: 0, count: 16)
+ var initialHeGradient = [Double](repeating: 0, count: 16)
+ var bottomN2Gradient = [Double](repeating: 0, count: 16)
+ var bottomHeGradient = [Double](repeating: 0, count: 16)
+ var maxAmbientPressure = 0.0
+ var firstCeilingMbar = 0
+ var maxBottomCeilingMbar = 0
+ var decoTime = 10_000_000
+
+ private var wv: Double { vpmb ? Self.waterVapourSchreiner : Self.waterVapour }
+ private var critN2: Double { Self.critRadiusN2 * Self.conservatismLevels[min(max(conservatism, 0), 4)] }
+ private var critHe: Double { Self.critRadiusHe * Self.conservatismLevels[min(max(conservatism, 0), 4)] }
+
+ /// `clear_deco`: a diver in equilibrium with air at the surface.
+ mutating func clear() {
+ let surface = environment.surfaceBar
+ for index in 0..<16 {
+ n2[index] = (surface - wv) * 0.781
+ he[index] = 0
+ maxN2Crushing[index] = 0
+ maxHeCrushing[index] = 0
+ n2RegenRadius[index] = critN2
+ heRegenRadius[index] = critHe
+ }
+ gfLowPressure = surface + 1.0
+ maxAmbientPressure = 0
+ firstCeilingMbar = 0
+ maxBottomCeilingMbar = 0
+ guidingTissue = -1
+ }
+
+ /// `deco_state_cache::restore(target, keep_vpmb_state = true)`: back to `cache`, keeping what the previous
+ /// pass of the VPM-B iteration worked out.
+ mutating func restore(_ cache: DecoState) {
+ var restored = cache
+ restored.bottomN2Gradient = bottomN2Gradient
+ restored.bottomHeGradient = bottomHeGradient
+ restored.initialN2Gradient = initialN2Gradient
+ restored.initialHeGradient = initialHeGradient
+ restored.firstCeilingMbar = firstCeilingMbar
+ restored.maxBottomCeilingMbar = maxBottomCeilingMbar
+ restored.decoTime = decoTime
+ self = restored
+ }
+
+ // MARK: Gas loading
+
+ /// `fill_pressures`: what the diver's lungs see, for an ambient pressure already reduced by the water vapour.
+ func pressures(ambient: Double, gas: CoreGas, setpoint: Double, mode: CoreMode) -> CorePressures {
+ var out = CorePressures()
+ if mode != .openCircuit, setpoint > 0 {
+ if setpoint >= ambient {
+ out.o2 = ambient
+ } else {
+ out.o2 = setpoint
+ if gas.o2 != 1000 {
+ out.he = (ambient - out.o2) * Double(gas.he) / Double(1000 - gas.o2)
+ out.n2 = ambient - out.o2 - out.he
+ }
+ }
+ } else if mode == .semiClosed {
+ let dropped = (1 - Double(gas.o2) / 1000) * o2Consumption / (bottomSac * pscrRatio) * 1_000_000
+ out.o2 = Double(max(0, Int(Double(gas.o2) * ambient - dropped))) / 1000
+ if gas.o2 != 1000 {
+ out.he = (ambient - out.o2) * Double(gas.he) / Double(1000 - gas.o2)
+ out.n2 = (ambient - out.o2) * Double(gas.n2) / Double(1000 - gas.o2)
+ }
+ } else {
+ out.o2 = Double(gas.o2) / 1000 * ambient
+ out.he = Double(gas.he) / 1000 * ambient
+ out.n2 = Double(gas.n2) / 1000 * ambient
+ }
+ return out
+ }
+
+ /// Partial pressure of oxygen breathed at an ambient pressure, in bar.
+ func ppO2(pressure: Double, gas: CoreGas, setpoint: Int, mode: CoreMode) -> Double {
+ pressures(ambient: pressure, gas: gas, setpoint: Double(setpoint) / 1000, mode: mode).o2
+ }
+
+ /// `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]))
+ }
+ if vpmb { calcCrushingPressure(pressure) }
+ }
+
+ // MARK: Ceiling
+
+ /// `tissue_tolerance_calc`: the lowest ambient pressure tolerated, in bar.
+ mutating func tolerance(pressure: Double) -> Double {
+ let surface = environment.surfaceBar
+ var result = 0.0
+ for index in 0..<16 {
+ let total = n2[index] + he[index]
+ 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
+ }
+ if !vpmb {
+ var lowest = 0.0
+ for index in 0..<16 {
+ let total = n2[index] + he[index]
+ let ceiling = (b[index] * total - gfLow * a[index] * b[index]) / ((1 - b[index]) * gfLow + b[index])
+ if ceiling > lowest { lowest = ceiling }
+ if lowest > gfLowPressure { gfLowPressure = lowest }
+ }
+ let low = gfLowPressure
+ for index in 0..<16 {
+ let total = n2[index] + he[index]
+ var tolerated = result
+ if (surface / b[index] + a[index] - surface) * gfHigh + surface < (low / b[index] + a[index] - low) * gfLow + low {
+ tolerated = (-a[index] * b[index] * (gfHigh * low - gfLow * surface)
+ - (1 - b[index]) * (gfHigh - gfLow) * low * surface
+ + b[index] * (low - surface) * total)
+ / (-a[index] * b[index] * (gfHigh - gfLow)
+ + (1 - b[index]) * (gfLow * low - gfHigh * surface)
+ + b[index] * (low - surface))
+ }
+ if tolerated >= result {
+ guidingTissue = index
+ result = tolerated
+ }
+ }
+ } else {
+ // The Boyle-compensated gradient depends on the ambient pressure: iterate until the ceiling is stable.
+ result = pressure
+ var reference = 0.0
+ repeat {
+ reference = result
+ result = 0
+ for index in 0..<16 {
+ let tolerated = vpmbToleratedPressure(reference: reference, index)
+ if tolerated >= result {
+ guidingTissue = index
+ result = tolerated
+ }
+ }
+ } while abs(result - reference) > 0.01
+ }
+ return result
+ }
+
+ /// `deco_allowed_depth`: the ceiling, in millimetres.
+ func allowedDepth(tolerance: Double, smooth: Bool = true) -> Int {
+ let delta = tolerance > environment.surfaceBar ? tolerance - environment.surfaceBar : 0
+ var depth = environment.depth(relativeMbar: Int((delta * 1000).rounded(.toNearestOrEven)))
+ if !smooth { depth = Int((Double(depth) / 3000).rounded(.up) * 3000) }
+ return depth
+ }
+
+ // MARK: VPM-B
+
+ private static func cube(_ x: Double) -> Double { x * x * x }
+
+ /// x³ − B x − C = 0.
+ private static func solveCubic2(_ B: Double, _ C: Double) -> Double {
+ let discriminant = 27 * C * C - 4 * cube(B)
+ if discriminant < 0 {
+ return 2 * (B / 3).squareRoot() * cos(acos(3 * C * (3 / B).squareRoot() / (2 * B)) / 3)
+ }
+ let denominator = pow(9 * C + (3 * discriminant).squareRoot(), 1.0 / 3)
+ return pow(2.0 / 3, 1.0 / 3) * B / denominator + denominator / pow(18, 1.0 / 3)
+ }
+
+ /// A r³ − B r² − C = 0.
+ private static func solveCubic(_ A: Double, _ B: Double, _ C: Double) -> Double {
+ let BA = B / A, CA = C / A
+ let discriminant = CA * (4 * cube(BA) + 27 * CA)
+ guard discriminant >= 0 else { return 0 }
+ let denominator = pow(cube(BA) + 1.5 * (9 * CA + 3.0.squareRoot() * discriminant.squareRoot()), 1.0 / 3)
+ return (BA + BA * BA / denominator + denominator) / 3
+ }
+
+ private func updateGradient(nextStopPressure: Double, firstGradient: Double) -> Double {
+ let B = Self.cube(firstGradient) / (Double(firstCeilingMbar) / 1000 + firstGradient)
+ return Self.solveCubic2(B, nextStopPressure * B)
+ }
+
+ private func vpmbToleratedPressure(reference: Double, _ index: Int) -> Double {
+ var n2Gradient = bottomN2Gradient[index], heGradient = bottomHeGradient[index]
+ if !(reference >= Double(firstCeilingMbar) / 1000 || firstCeilingMbar == 0) {
+ n2Gradient = updateGradient(nextStopPressure: reference, firstGradient: bottomN2Gradient[index])
+ heGradient = updateGradient(nextStopPressure: reference, firstGradient: bottomHeGradient[index])
+ }
+ let total = (n2Gradient * n2[index] + heGradient * he[index]) / (n2[index] + he[index])
+ return n2[index] + he[index] + Self.otherGasesPressure - total
+ }
+
+ /// `vpmb_start_gradient`.
+ mutating func vpmbStartGradient() {
+ let factor = 2 * (Self.surfaceTensionGamma / Self.skinCompressionGammaC) * (Self.skinCompressionGammaC - Self.surfaceTensionGamma)
+ for index in 0..<16 {
+ initialN2Gradient[index] = factor / n2RegenRadius[index]
+ bottomN2Gradient[index] = initialN2Gradient[index]
+ initialHeGradient[index] = factor / heRegenRadius[index]
+ bottomHeGradient[index] = initialHeGradient[index]
+ }
+ }
+
+ private func surfacePhase(he hePressure: Double, n2 n2Pressure: Double, heConstant: Double, n2Constant: Double) -> Double {
+ let inspired = (environment.surfaceBar - wv) * 0.79
+ if n2Pressure > inspired {
+ return (hePressure / heConstant + (n2Pressure - inspired) / n2Constant) / (hePressure + n2Pressure - inspired)
+ }
+ if hePressure + n2Pressure >= inspired {
+ let decay = 1 / (n2Constant - heConstant) * log((inspired - n2Pressure) / hePressure)
+ let integral = hePressure / heConstant * (1 - exp(-heConstant * decay))
+ + (n2Pressure - inspired) / n2Constant * (1 - exp(-n2Constant * decay))
+ return integral / (hePressure + n2Pressure - inspired)
+ }
+ return 0
+ }
+
+ /// `vpmb_next_gradient`: the gradients allowed once the length of the decompression is known.
+ mutating func vpmbNextGradient(decoTime seconds: Double) {
+ let decoMinutes = seconds / 60
+ let gamma = Self.surfaceTensionGamma, gammaC = Self.skinCompressionGammaC, lambda = Self.critVolumeLambda
+ for index in 0..<16 {
+ let desat = decoMinutes + surfacePhase(he: he[index], n2: n2[index],
+ heConstant: log(2.0) / Self.heHalfLife[index], n2Constant: log(2.0) / Self.n2HalfLife[index])
+ let n2B = initialN2Gradient[index] + lambda * gamma / (gammaC * desat)
+ let heB = initialHeGradient[index] + lambda * gamma / (gammaC * desat)
+ let n2C = gamma * gamma * lambda * maxN2Crushing[index] / (gammaC * gammaC * desat)
+ let heC = gamma * gamma * lambda * maxHeCrushing[index] / (gammaC * gammaC * desat)
+ bottomN2Gradient[index] = 0.5 * (n2B + (n2B * n2B - 4 * n2C).squareRoot())
+ bottomHeGradient[index] = 0.5 * (heB + (heB * heB - 4 * heC).squareRoot())
+ }
+ }
+
+ /// `nuclear_regeneration`.
+ mutating func nuclearRegeneration(seconds: Double) {
+ let minutes = seconds / 60
+ let span = 2 * (Self.skinCompressionGammaC - Self.surfaceTensionGamma)
+ for index in 0..<16 {
+ let crushedN2 = 1 / (maxN2Crushing[index] / span + 1 / critN2)
+ let crushedHe = 1 / (maxHeCrushing[index] / span + 1 / critHe)
+ n2RegenRadius[index] = crushedN2 + (critN2 - crushedN2) * (1 - exp(-minutes / Self.regenerationTime))
+ heRegenRadius[index] = crushedHe + (critHe - crushedHe) * (1 - exp(-minutes / Self.regenerationTime))
+ }
+ }
+
+ private func innerPressure(critRadius: Double, onsetTension: Double, ambient: Double) -> Double {
+ let span = 2 * (Self.skinCompressionGammaC - Self.surfaceTensionGamma)
+ let onsetRadius = 1 / (Self.gradientOfImperm / span + 1 / critRadius)
+ let A = ambient - Self.gradientOfImperm + span / onsetRadius
+ let C = onsetTension * pow(onsetRadius, 3)
+ let radius = Self.solveCubic(A, span, C)
+ return onsetTension * onsetRadius * onsetRadius * onsetRadius / (radius * radius * radius)
+ }
+
+ /// `calc_crushing_pressure`.
+ mutating func calcCrushingPressure(_ pressure: Double) {
+ for index in 0..<16 {
+ let tension = n2[index] + he[index] + Self.otherGasesPressure
+ let gradient = pressure - tension
+ var n2Crushing = gradient, heCrushing = gradient
+ if gradient <= Self.gradientOfImperm {
+ crushingOnsetTension[index] = tension
+ } else {
+ if maxAmbientPressure >= pressure { return }
+ n2Crushing = pressure - innerPressure(critRadius: critN2, onsetTension: crushingOnsetTension[index], ambient: pressure)
+ heCrushing = pressure - innerPressure(critRadius: critHe, onsetTension: crushingOnsetTension[index], ambient: pressure)
+ }
+ maxN2Crushing[index] = max(maxN2Crushing[index], n2Crushing)
+ maxHeCrushing[index] = max(maxHeCrushing[index], heCrushing)
+ }
+ maxAmbientPressure = max(pressure, maxAmbientPressure)
+ }
+}
+
+// MARK: The planner
+
+struct CoreWaypoint: Sendable {
+ /// Seconds taken to get to `depth` from the previous waypoint (or to stay there).
+ var seconds: Int
+ var depth: Int
+ var cylinder: Int
+ var setpoint = 0
+ var mode = CoreMode.openCircuit
+}
+
+struct CoreCylinder: Sendable {
+ var gas: CoreGas
+ /// Depth from which the gas is switched to on the way up; nil for a gas that is not used for the ascent.
+ var changeDepth: Int?
+}
+
+struct CorePrefs: Sendable {
+ /// Ascent rates in millimetres per second: below 75 % of the average depth, down to 50 %, up to 6 m, above.
+ var ascRate75 = 150, ascRate50 = 150, ascRateStops = 150, ascRateLast6m = 150
+ var lastStopAt6m = false
+ var minSwitchDuration = 60
+ var switchAtRequiredStop = false
+ var oxygenBreaks = false
+ var bailout = false
+ var problemSolvingMinutes = 4
+ /// Millilitres per minute.
+ var bottomSac = 20_000.0, decoSac = 17_000.0
+ var timestep = 60
+}
+
+struct CoreTrackPoint: Sendable, Equatable {
+ var time: Int
+ var depth: Int
+ var cylinder: Int
+ var mode: CoreMode
+ var setpoint: Int
+}
+
+struct CoreStop: Sendable, Equatable {
+ var depth: Int
+ var seconds: Int
+ var cylinder: Int
+ var isGasSwitch: Bool
+ var endTime: Int
+}
+
+struct CoreOutput: Sendable {
+ var track: [CoreTrackPoint] = []
+ var stops: [CoreStop] = []
+ var runtime = 0
+ var bottomTime = 0
+ var bottomDepth = 0
+ var bottomCylinder = 0
+ /// Millilitres at the surface, per cylinder; and the part breathed from each cylinder after the bottom time.
+ var gasUsed: [Double] = []
+ var decoGasUsed: [Double] = []
+ var cns = 0.0
+ var otu = 0.0
+ var firstCeilingDepth = 0
+ var timedOut = false
+ var finalState: DecoState
+}
+
+enum CorePlanner {
+ static let baseTimestep = 2
+ static let decoLevels: [Int] = Array(stride(from: 0, through: 90_000, by: 3000))
+ + [100_000, 110_000, 120_000, 130_000, 140_000, 150_000, 160_000, 170_000, 180_000, 190_000, 200_000,
+ 220_000, 240_000, 260_000, 280_000, 300_000, 320_000, 340_000, 360_000, 380_000]
+
+ static func ascentVelocity(depth: Int, average: Int, _ prefs: CorePrefs) -> Int {
+ if depth * 4 > average * 3 { return prefs.ascRate75 }
+ if depth * 2 > average { return prefs.ascRate50 }
+ return depth > 6000 ? prefs.ascRateStops : prefs.ascRateLast6m
+ }
+
+ /// `trial_ascent`.
+ private static func trialAscent(_ state: DecoState, wait: Int, from depth: Int, to stopLevel: Int, average: Int, gas: CoreGas,
+ setpoint: Int, mode: CoreMode, prefs: CorePrefs) -> Bool {
+ var trial = state
+ let environment = state.environment
+ if wait > 0 { trial.addSegment(pressure: environment.bar(depth), gas: gas, seconds: wait, setpoint: setpoint, mode: mode) }
+ if trial.vpmb {
+ let limit = trial.tolerance(pressure: environment.bar(stopLevel))
+ if trial.allowedDepth(tolerance: limit) > stopLevel { return false }
+ }
+ var current = depth
+ while current > stopLevel {
+ var rise = ascentVelocity(depth: current, average: average, prefs) * baseTimestep
+ if rise > current { rise = current }
+ trial.addSegment(pressure: environment.bar(current), gas: gas, seconds: baseTimestep, setpoint: setpoint, mode: mode)
+ let limit = trial.tolerance(pressure: environment.bar(current))
+ if trial.allowedDepth(tolerance: limit) > current - rise { return false }
+ current -= rise
+ }
+ return true
+ }
+
+ /// `wait_until`: the earliest whole step of run time at which the ascent to the next stop is clear.
+ private static func waitUntil(_ state: DecoState, clock: Int, min: Int, leap: Int, step: Int, depth: Int, target: Int, average: Int,
+ gas: CoreGas, setpoint: Int, mode: CoreMode, prefs: CorePrefs) -> Int {
+ var low = min, jump = leap
+ while true {
+ if low >= 48 * 3600 { return 50 * 3600 }
+ let upper = low + jump + step - 1 - (low + jump - 1) % step
+ if !trialAscent(state, wait: upper - clock, from: depth, to: target, average: average, gas: gas, setpoint: setpoint, mode: mode, prefs: prefs) {
+ low = upper
+ continue
+ }
+ if upper - low <= step { return upper }
+ jump /= 2
+ }
+ }
+
+ /// `sort_stops`: the deco levels and the gas switch depths in one ascending list. A switch depth that is
+ /// also a deco level appears once; the list is padded with zeros at its start.
+ private static func sortStops(levels: [Int], count: Int, changes: [(depth: Int, cylinder: Int)]) -> [Int] {
+ guard !changes.isEmpty else { return Array(levels[0..<count]) }
+ let total = count + changes.count
+ var out = [Int](repeating: 0, count: total)
+ var index = total - 1, gi = changes.count - 1, di = count - 1
+ while index >= 0 {
+ if levels[di] > changes[gi].depth {
+ out[index] = levels[di]
+ di -= 1
+ } else if levels[di] == changes[gi].depth {
+ out[index] = levels[di]
+ di -= 1
+ gi -= 1
+ } else {
+ out[index] = changes[gi].depth
+ gi -= 1
+ }
+ index -= 1
+ if di < 0 {
+ while gi >= 0 {
+ out[index] = changes[gi].depth
+ index -= 1
+ gi -= 1
+ }
+ break
+ }
+ if gi < 0 {
+ while di >= 0 {
+ out[index] = levels[di]
+ index -= 1
+ di -= 1
+ }
+ break
+ }
+ }
+ while index >= 0 {
+ out[index] = 0
+ index -= 1
+ }
+ return out
+ }
+
+ static func plan(waypoints: [CoreWaypoint], cylinders: [CoreCylinder], prefs: CorePrefs, model: DecoState) -> CoreOutput {
+ var state = model
+ state.clear()
+ let environment = state.environment
+ var output = CoreOutput(finalState: state)
+ output.gasUsed = [Double](repeating: 0, count: cylinders.count)
+ output.decoGasUsed = output.gasUsed
+ guard let last = waypoints.last, !cylinders.isEmpty else { return output }
+ let pscrFactor = state.pscrRatio / 1000
+
+ func use(_ output: inout CoreOutput, _ cylinder: Int, depth: Int, toDepth: Int, seconds: Int, sac: Double, deco: Bool, mode: CoreMode) {
+ // A closed circuit only adds the oxygen that is metabolised: its diluent use is not planned here.
+ guard mode != .closedCircuit else { return }
+ let used = environment.atm((depth + toDepth) / 2) * sac / 60 * Double(seconds) * (mode == .semiClosed ? pscrFactor : 1)
+ output.gasUsed[cylinder] += used
+ if deco { output.decoGasUsed[cylinder] += used }
+ }
+ func oxygen(_ output: inout CoreOutput, _ state: DecoState, depth: Int, cylinder: Int, seconds: Int, setpoint: Int, mode: CoreMode) {
+ let ppO2 = state.ppO2(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, setpoint: setpoint, mode: mode)
+ output.cns += OxygenExposure.cns(ppO2: ppO2, seconds: Double(seconds))
+ output.otu += OxygenExposure.otu(ppO2: ppO2, seconds: Double(seconds))
+ }
+
+ // The part the diver entered (`tissue_at_end`), second by second along each leg.
+ var clock = 0, depth = 0
+ var integral = 0.0
+ var previousSetpoint: Int?
+ output.track.append(CoreTrackPoint(time: 0, depth: 0, cylinder: waypoints[0].cylinder, mode: waypoints[0].mode, setpoint: waypoints[0].setpoint))
+ for waypoint in waypoints {
+ let setpoint = previousSetpoint ?? waypoint.setpoint
+ let gas = cylinders[waypoint.cylinder].gas
+ if state.vpmb, depth > waypoint.depth {
+ // The ceiling before an ascent within the entered part can be the deepest of the dive.
+ state.nuclearRegeneration(seconds: Double(clock))
+ state.vpmbStartGradient()
+ let ceiling = environment.mbar(state.allowedDepth(tolerance: state.tolerance(pressure: environment.bar(depth))))
+ state.maxBottomCeilingMbar = max(state.maxBottomCeilingMbar, ceiling)
+ }
+ output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: waypoint.cylinder, mode: waypoint.mode, setpoint: setpoint))
+ if waypoint.seconds > 0 {
+ for second in 0..<waypoint.seconds {
+ let exact = (Double(depth) * Double(waypoint.seconds - second) + Double(waypoint.depth) * Double(second)) / Double(waypoint.seconds)
+ let at = Int(exact.rounded(.toNearestOrEven))
+ state.addSegment(pressure: environment.bar(at), gas: gas, seconds: 1, setpoint: setpoint, mode: waypoint.mode)
+ use(&output, waypoint.cylinder, depth: at, toDepth: at, seconds: 1, sac: prefs.bottomSac, deco: false, mode: waypoint.mode)
+ oxygen(&output, state, depth: at, cylinder: waypoint.cylinder, seconds: 1, setpoint: setpoint, mode: waypoint.mode)
+ }
+ if waypoint.depth > depth { state.calcCrushingPressure(environment.bar(waypoint.depth)) }
+ integral += Double(waypoint.depth + depth) * Double(waypoint.seconds) / 2
+ clock += waypoint.seconds
+ depth = waypoint.depth
+ }
+ previousSetpoint = waypoint.setpoint
+ output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: waypoint.cylinder, mode: waypoint.mode, setpoint: waypoint.setpoint))
+ }
+ let average = clock > 0 ? Int(integral / Double(clock)) : 0
+ var bottomTime = clock
+ var cylinder = last.cylinder
+ var mode = last.mode
+ var setpoint = last.setpoint
+ output.bottomDepth = depth
+ output.bottomCylinder = cylinder
+
+ // The gases for the way up (`analyze_gaslist`): those usable from a depth above the bottom are switched
+ // to on the way; of those usable at the bottom already, the one with the shallowest limit is taken first.
+ let onLoop = mode == .closedCircuit && !prefs.bailout
+ var changes = [(depth: Int, cylinder: Int)]()
+ var firstAscentCylinder = -1
+ if !onLoop {
+ var bestDepth = Int.max
+ for (index, candidate) in cylinders.enumerated() {
+ guard let change = candidate.changeDepth else { continue }
+ if change <= depth {
+ let position = changes.firstIndex { change < $0.depth } ?? changes.count
+ changes.insert((change, index), at: position)
+ } else if change < bestDepth {
+ bestDepth = change
+ firstAscentCylinder = index
+ }
+ }
+ }
+ var breakCylinder = 0
+ if prefs.oxygenBreaks, firstAscentCylinder != -1, cylinders[firstAscentCylinder].gas.o2 <= 320 { breakCylinder = firstAscentCylinder }
+
+ var levels = decoLevels
+ if prefs.lastStopAt6m { levels[1] = 0 }
+ var stopIndex = levels.firstIndex { $0 > depth } ?? levels.count
+ if stopIndex > 0 { stopIndex -= 1 }
+ let stopLevels = sortStops(levels: levels, count: stopIndex + 1, changes: changes)
+ stopIndex += changes.count
+ let bottomStopIndex = stopIndex
+
+ state.nuclearRegeneration(seconds: Double(clock))
+ state.vpmbStartGradient()
+
+ if firstAscentCylinder != -1, firstAscentCylinder != cylinder {
+ cylinder = firstAscentCylinder
+ output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint))
+ }
+ if mode != .openCircuit, prefs.bailout {
+ // Off the loop: time to sort the problem out at the bottom, on the bailout gas.
+ mode = .openCircuit
+ setpoint = 0
+ let segment = max(prefs.minSwitchDuration, 60 * prefs.problemSolvingMinutes)
+ state.addSegment(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, seconds: segment, setpoint: setpoint, mode: mode)
+ use(&output, cylinder, depth: depth, toDepth: depth, seconds: segment, sac: prefs.bottomSac, deco: false, mode: mode)
+ oxygen(&output, state, depth: depth, cylinder: cylinder, seconds: segment, setpoint: setpoint, mode: mode)
+ output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint))
+ bottomTime += segment
+ output.track.append(CoreTrackPoint(time: bottomTime, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint))
+ }
+ output.bottomTime = bottomTime
+
+ var previousDecoTime = 100_000_000
+ state.decoTime = 10_000_000
+ let bottomCache = state
+ let bottomDepth = depth
+ let bottomCylinder = cylinder
+ let entered = output
+
+ // VPM-B iterates: the gradients allowed depend on the length of the decompression they produce.
+ while true {
+ let isFinal = !state.vpmb || previousDecoTime - state.decoTime < 10
+ if state.decoTime != 10_000_000 { state.vpmbNextGradient(decoTime: Double(state.decoTime)) }
+ previousDecoTime = state.decoTime
+ state.restore(bottomCache)
+ var pass = entered
+ depth = bottomDepth
+ cylinder = bottomCylinder
+ clock = bottomTime
+ var gi = changes.count - 1
+ stopIndex = bottomStopIndex
+ state.firstCeilingMbar = environment.mbar(state.allowedDepth(tolerance: state.tolerance(pressure: environment.bar(depth))))
+ if state.maxBottomCeilingMbar > state.firstCeilingMbar { state.firstCeilingMbar = state.maxBottomCeilingMbar }
+ pass.firstCeilingDepth = environment.depth(relativeMbar: state.firstCeilingMbar - environment.surfaceMbar)
+ var lastRate = ascentVelocity(depth: depth, average: average, prefs)
+ var pendingGasChange = false
+ var lastSegmentMinSwitch = false
+ var lastStopTime = prefs.timestep
+ var oxygenBreaking = false, oxygenBreakNext = false
+ var breakFromCylinder = 0
+ var timedOut = false
+
+ func point(_ pass: inout CoreOutput, cylinder shown: Int) {
+ let next = CoreTrackPoint(time: clock, depth: depth, cylinder: shown, mode: mode, setpoint: setpoint)
+ if pass.track.last != next { pass.track.append(next) }
+ }
+ func hold(_ pass: inout CoreOutput, _ seconds: Int, cylinder held: Int, gasSwitch: Bool) {
+ use(&pass, held, depth: depth, toDepth: depth, seconds: seconds, sac: prefs.decoSac, deco: true, mode: mode)
+ oxygen(&pass, state, depth: depth, cylinder: held, seconds: seconds, setpoint: setpoint, mode: mode)
+ if var previous = pass.stops.last, previous.depth == depth, previous.cylinder == held, previous.isGasSwitch == gasSwitch,
+ previous.endTime == clock {
+ previous.seconds += seconds
+ previous.endTime = clock + seconds
+ pass.stops[pass.stops.count - 1] = previous
+ } else {
+ pass.stops.append(CoreStop(depth: depth, seconds: seconds, cylinder: held, isGasSwitch: gasSwitch, endTime: clock + seconds))
+ }
+ }
+
+ point(&pass, cylinder: cylinder)
+ ascent: while true {
+ // Up to the next level, two seconds at a time.
+ repeat {
+ let rate = ascentVelocity(depth: depth, average: average, prefs)
+ var rise = rate * baseTimestep
+ if rate != lastRate {
+ point(&pass, cylinder: cylinder)
+ lastRate = rate
+ }
+ if depth - rise < stopLevels[stopIndex] { rise = depth - stopLevels[stopIndex] }
+ state.addSegment(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, seconds: baseTimestep, setpoint: setpoint, mode: mode)
+ use(&pass, cylinder, depth: depth, toDepth: depth - rise, seconds: baseTimestep, sac: prefs.decoSac, deco: true, mode: mode)
+ oxygen(&pass, state, depth: depth, cylinder: cylinder, seconds: baseTimestep, setpoint: setpoint, mode: mode)
+ lastSegmentMinSwitch = false
+ clock += baseTimestep
+ depth -= rise
+ } while depth > 0 && depth > stopLevels[stopIndex]
+ if depth <= 0 { break }
+ point(&pass, cylinder: cylinder)
+
+ if gi >= 0, stopLevels[stopIndex] <= changes[gi].depth {
+ if cylinder != changes[gi].cylinder {
+ let current = cylinders[cylinder].gas
+ if !prefs.switchAtRequiredStop
+ || !trialAscent(state, wait: 0, from: depth, to: stopLevels[stopIndex - 1], average: average, gas: current,
+ setpoint: setpoint, mode: mode, prefs: prefs)
+ || current.o2 < 160 {
+ cylinder = changes[gi].cylinder
+ point(&pass, cylinder: cylinder)
+ if !lastSegmentMinSwitch, cylinders[cylinder].gas.o2 != 1000 {
+ state.addSegment(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, seconds: prefs.minSwitchDuration,
+ setpoint: setpoint, mode: mode)
+ hold(&pass, prefs.minSwitchDuration, cylinder: cylinder, gasSwitch: true)
+ clock += prefs.minSwitchDuration
+ lastSegmentMinSwitch = true
+ }
+ } else {
+ pendingGasChange = true
+ }
+ }
+ gi -= 1
+ }
+ stopIndex -= 1
+
+ while true {
+ if trialAscent(state, wait: 0, from: depth, to: stopLevels[stopIndex], average: average, gas: cylinders[cylinder].gas,
+ setpoint: setpoint, mode: mode, prefs: prefs) { break }
+ point(&pass, cylinder: cylinder)
+ if pendingGasChange {
+ cylinder = changes[gi + 1].cylinder
+ point(&pass, cylinder: cylinder)
+ if !lastSegmentMinSwitch, cylinders[cylinder].gas.o2 != 1000 {
+ state.addSegment(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, seconds: prefs.minSwitchDuration,
+ setpoint: setpoint, mode: mode)
+ hold(&pass, prefs.minSwitchDuration, cylinder: cylinder, gasSwitch: true)
+ clock += prefs.minSwitchDuration
+ }
+ pendingGasChange = false
+ }
+ let newClock = waitUntil(state, clock: clock, min: clock, leap: lastStopTime * 2 + 1, step: prefs.timestep, depth: depth,
+ target: stopLevels[stopIndex], average: average, gas: cylinders[cylinder].gas,
+ setpoint: setpoint, mode: mode, prefs: prefs)
+ lastStopTime = newClock - clock
+ if lastStopTime >= 48 * 3600, depth >= 6000, !oxygenBreaking {
+ timedOut = true
+ break ascent
+ }
+ oxygenBreaking = false
+ let stopCylinder = cylinder
+ if prefs.oxygenBreaks {
+ // Twelve minutes on oxygen, then six on the break gas.
+ if cylinders[cylinder].gas.o2 == 1000 {
+ if lastStopTime >= 12 * 60 {
+ lastStopTime = 12 * 60
+ oxygenBreaking = true
+ oxygenBreakNext = true
+ breakFromCylinder = cylinder
+ cylinder = breakCylinder
+ }
+ } else if oxygenBreakNext {
+ if lastStopTime >= 6 * 60 {
+ lastStopTime = 6 * 60
+ oxygenBreaking = true
+ oxygenBreakNext = false
+ cylinder = breakFromCylinder
+ }
+ }
+ }
+ state.addSegment(pressure: environment.bar(depth), gas: cylinders[stopCylinder].gas, seconds: lastStopTime, setpoint: setpoint, mode: mode)
+ hold(&pass, lastStopTime, cylinder: stopCylinder, gasSwitch: false)
+ lastSegmentMinSwitch = false
+ clock += lastStopTime
+ if oxygenBreaking {
+ // The track shows the stop on the gas it was done on, then the gas of the next part.
+ point(&pass, cylinder: stopCylinder)
+ point(&pass, cylinder: cylinder)
+ } else {
+ break
+ }
+ }
+ point(&pass, cylinder: cylinder)
+ }
+ depth = max(depth, 0)
+ point(&pass, cylinder: cylinder)
+ pass.timedOut = timedOut
+ state.decoTime = clock - bottomTime - (3000 * (prefs.lastStopAt6m ? 2 : 1)) / max(lastRate, 1) + 20
+ output = pass
+ if isFinal || timedOut { break }
+ }
+ output.runtime = clock
+ output.finalState = state
+ return output
+ }
+}
diff --git a/Packages/DiveKit/Tests/DivePlannerTests/SubsurfaceVectorsTests.swift b/Packages/DiveKit/Tests/DivePlannerTests/SubsurfaceVectorsTests.swift
@@ -0,0 +1,151 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import XCTest
+@testable import DivePlanner
+
+/// The plans of Subsurface's own test suite (`tests/testplan.cpp`), with the run times it records as "known
+/// Subsurface runtime". The port is expected to give the same, to the second.
+final class SubsurfaceVectorsTests: XCTestCase {
+ private let air = CoreGas(o2: 210, he: 0)
+ private let ean36 = CoreGas(o2: 360, he: 0)
+ private let ean50 = CoreGas(o2: 500, he: 0)
+ private let oxygen = CoreGas(o2: 1000, he: 0)
+ private let tx18_45 = CoreGas(o2: 180, he: 450)
+
+ /// `dive::gas_mod` at 1.6 bar, rounded to 3 m.
+ private func mod(_ gas: CoreGas, _ environment: CoreEnvironment = CoreEnvironment()) -> Int {
+ let depth = Double(environment.depth(relativeMbar: 1600 * 1000 / gas.o2 - environment.surfaceMbar))
+ return Int(depth / 3000 + 0.1) * 3000
+ }
+
+ private func deco(_ gas: CoreGas) -> CoreCylinder { CoreCylinder(gas: gas, changeDepth: mod(gas)) }
+
+ /// `setupPrefsVpmb`: 10 m/min everywhere (166 mm/s once divided), last stop at 3 m, conservatism 0.
+ private var vpmbPrefs: CorePrefs {
+ var prefs = CorePrefs()
+ prefs.ascRate75 = 10000 / 60
+ prefs.ascRate50 = 10000 / 60
+ prefs.ascRateStops = 10000 / 60
+ prefs.ascRateLast6m = 10000 / 60
+ return prefs
+ }
+
+ private var vpmb: DecoState {
+ var model = DecoState()
+ model.vpmb = true
+ model.conservatism = 0
+ return model
+ }
+
+ /// `setupPrefs`: 30 ft/min, 10 ft/min above 6 m, last stop at 6 m.
+ private var imperialPrefs: CorePrefs {
+ var prefs = CorePrefs()
+ prefs.ascRate75 = 9144 / 60
+ prefs.ascRate50 = 9144 / 60
+ prefs.ascRateStops = 9144 / 60
+ prefs.ascRateLast6m = 3048 / 60
+ prefs.lastStopAt6m = true
+ return prefs
+ }
+
+ /// A square dive: straight down at `descent` mm/min, then the rest of `minutes` at the bottom.
+ private func square(_ depth: Int, minutes: Int, descent: Int) -> [CoreWaypoint] {
+ let drop = depth * 60 / descent
+ return [CoreWaypoint(seconds: drop, depth: depth, cylinder: 0), CoreWaypoint(seconds: minutes * 60 - drop, depth: depth, cylinder: 0)]
+ }
+
+ private func switches(_ output: CoreOutput) -> [(depth: Int, cylinder: Int)] {
+ var found = [(depth: Int, cylinder: Int)]()
+ for (index, point) in output.track.enumerated() where index > 0 && output.track[index - 1].cylinder != point.cylinder && point.time >= output.bottomTime {
+ found.append((point.depth, point.cylinder))
+ }
+ return found
+ }
+
+ func testBuhlmannMetric() {
+ var model = DecoState()
+ model.gfLow = 1
+ model.gfHigh = 1
+ let output = CorePlanner.plan(waypoints: square(79_000, minutes: 30, descent: 23_000),
+ cylinders: [CoreCylinder(gas: CoreGas(o2: 150, he: 450)), deco(ean36), deco(oxygen)],
+ prefs: imperialPrefs, model: model)
+ XCTAssertEqual(output.runtime, 109 * 60)
+ XCTAssertEqual(switches(output).map(\.depth), [33_000, 6000])
+ XCTAssertEqual(switches(output).map(\.cylinder), [1, 2])
+ }
+
+ func testVpmb60m30minAir() {
+ let output = CorePlanner.plan(waypoints: square(60_000, minutes: 30, descent: 99_000), cylinders: [CoreCylinder(gas: air)],
+ prefs: vpmbPrefs, model: vpmb)
+ XCTAssertEqual(output.runtime, 139 * 60 + 20)
+ }
+
+ func testVpmb60m30minEan50() {
+ let output = CorePlanner.plan(waypoints: square(60_000, minutes: 30, descent: 99_000), cylinders: [CoreCylinder(gas: air), deco(ean50)],
+ prefs: vpmbPrefs, model: vpmb)
+ XCTAssertEqual(output.runtime, 96 * 60 + 20)
+ XCTAssertEqual(switches(output).map(\.depth), [21_000])
+ }
+
+ func testVpmb60m30minTrimix() {
+ let output = CorePlanner.plan(waypoints: square(60_000, minutes: 30, descent: 99_000), cylinders: [CoreCylinder(gas: tx18_45), deco(ean50)],
+ prefs: vpmbPrefs, model: vpmb)
+ XCTAssertEqual(output.runtime, 89 * 60 + 20)
+ XCTAssertEqual(switches(output).map(\.depth), [21_000])
+ }
+
+ func testVpmb100m60min() {
+ let output = CorePlanner.plan(waypoints: square(100_000, minutes: 60, descent: 99_000),
+ cylinders: [CoreCylinder(gas: tx18_45), deco(ean50), deco(oxygen)], prefs: vpmbPrefs, model: vpmb)
+ XCTAssertEqual(output.runtime, 315 * 60 + 20)
+ XCTAssertEqual(switches(output).map(\.depth), [21_000, 6000])
+ }
+
+ func testVpmb100m10min() {
+ let output = CorePlanner.plan(waypoints: square(100_000, minutes: 10, descent: 99_000),
+ cylinders: [CoreCylinder(gas: tx18_45), deco(ean50), deco(oxygen)], prefs: vpmbPrefs, model: vpmb)
+ XCTAssertEqual(output.runtime, 57 * 60 + 20)
+ XCTAssertEqual(switches(output).map(\.depth), [21_000, 6000])
+ }
+
+ func testVpmbMultiLevelAir() {
+ let drop = 20_000 * 60 / 99_000
+ let waypoints = [CoreWaypoint(seconds: drop, depth: 20_000, cylinder: 0), CoreWaypoint(seconds: 600 - drop, depth: 20_000, cylinder: 0),
+ CoreWaypoint(seconds: 60, depth: 60_000, cylinder: 0), CoreWaypoint(seconds: 29 * 60, depth: 60_000, cylinder: 0)]
+ let output = CorePlanner.plan(waypoints: waypoints, cylinders: [CoreCylinder(gas: air)], prefs: vpmbPrefs, model: vpmb)
+ XCTAssertEqual(output.runtime, 169 * 60 + 20)
+ }
+
+ func testVpmb30m20min() {
+ let output = CorePlanner.plan(waypoints: square(30_000, minutes: 20, descent: 18_000), cylinders: [CoreCylinder(gas: air)],
+ prefs: vpmbPrefs, model: vpmb)
+ XCTAssertEqual(output.runtime, 27 * 60 + 20)
+ }
+
+ /// Several gases in the part the diver enters, one of them breathed on the way up between two levels.
+ func testVpmbSeveralGases() {
+ let waypoints = [CoreWaypoint(seconds: 120, depth: 40_000, cylinder: 0), CoreWaypoint(seconds: 18 * 60, depth: 40_000, cylinder: 0),
+ CoreWaypoint(seconds: 10 * 60, depth: 10_000, cylinder: 1), CoreWaypoint(seconds: 5 * 60, depth: 10_000, cylinder: 0)]
+ let output = CorePlanner.plan(waypoints: waypoints, cylinders: [CoreCylinder(gas: ean36), CoreCylinder(gas: CoreGas(o2: 110, he: 500))],
+ prefs: vpmbPrefs, model: vpmb)
+ XCTAssertEqual(output.runtime, 2480)
+ }
+
+ /// Closed circuit at a setpoint of 1.3 bar, then open-circuit bailout: trimix 19/33 at the bottom, EAN53 higher up.
+ func testCcrBailout() {
+ var model = DecoState()
+ model.gfLow = 0.5
+ model.gfHigh = 0.7
+ var prefs = imperialPrefs
+ prefs.bailout = true
+ let ean53 = CoreGas(o2: 530, he: 0), tx19_33 = CoreGas(o2: 190, he: 330)
+ XCTAssertEqual(mod(ean53), 18_000)
+ XCTAssertEqual(mod(tx19_33), 72_000)
+ let output = CorePlanner.plan(waypoints: [CoreWaypoint(seconds: 20 * 60, depth: 60_000, cylinder: 0, setpoint: 1300, mode: .closedCircuit)],
+ cylinders: [CoreCylinder(gas: CoreGas(o2: 200, he: 210)), deco(ean53), deco(tx19_33)], prefs: prefs, model: model)
+ XCTAssertEqual(output.runtime, 51 * 60)
+ func cylinder(at time: Int) -> Int { output.track.last { $0.time <= time }?.cylinder ?? -1 }
+ XCTAssertEqual(cylinder(at: 20 * 60 - 1), 0)
+ XCTAssertEqual(cylinder(at: 20 * 60 + 1), 2)
+ XCTAssertEqual(cylinder(at: 30 * 60), 1)
+ }
+}